jan/web-app/src/lib/extension.ts
Faisal Amir 852ea84cd8
epic: Jan with new UI/UX (#4964)
* chore: initial new FE setup

* chore: update namespace text-left-panel foreground variable

* chore: enable dynamic mainview color

* chore: remove greetings new chat

* chore: fix chat input style

* chore: simplify hook useAppearance

* chore: enable internationalization

* chore: prepare vn locale

* chore: keyboardshortcut layout

* chore: update keyboard shortcut exclude pathname

* chore: update state active setting route

* chore: fix update theme by system

* chore: handle dynamic primary color

* chore: fix left panel navigation active state and styled item privacy analytic

* chore: reorder general setting being a first

* chore: add function reset appearance

* chore: update scrollbar

* chore: update delete thread with dialog confirmation

* chore: update state dialog inside dropdown menu

* chore: wip thread detail or chat page

* chore: wip model dropdown

* chore: prepare model dropdown select

* chore: update model providers setting

* chore: show provider on model dropdown based isActive toogle

* chore: update layout model provider

* chore: update state active on storage

* chore: update gap of item dropdown model

* chore: update select model base on id

* chore: update edit model capabilities

* chore: add dialog to add model

* chore: update sheet for model setting

* chore: add sheet setting each model

* chore: make dynamic syntax highlight

* chore: fix menu setting appearance theme

* chore: markdown render support emoji

* chore: markdown support latex

* chore: change codeblock default theme

* chore: update ui codeblock

* chore: custom render link taget new window

* chore: fix copy button codeblock

* chore: update accent and desctructive color

* chore: setup user chat message

* chore: prepare some page settings

* chore: simple list extension and prepare mcp, local api, and hardware

* chore: mcp-serve

* chore: MCP server UI

* chore: update local api server config

* chore: adjust chat input

* chore: update local api server log

* chore: prepare hub page

* chore: remove help page

* chore: update mock

* chore: prepare http proxy setting UI

* chore: adjust local api server and title every action

* fix: chore FE package (#4962)

* fix: update command which referred to non-existent web app

* fix: added commented out macos platform for now

* fix: remove the platform name as macos

* fix: remove unnecessary line for platform name in HeaderPage component

* fix: update dev script to specify port 3000 for Vite

* feat: model providers and chat completion

* enhancement: threads performance

* fix: thread content update

* chore: clean up threads

* fix: performance issue with streaming and state loop

* fix: streaming

* fix: react markdow

* feat: extension manager

* chore: add nodePolyfills include path

* chore: improve performance avoid unhandle rejection

* chore: update pre margin bottom

* chore: swith thread should be deafult scroll to bottom

* chore: wip scroll to bottom

* chore: add model loader

* chore: add platform utils

* feat: threads functionality

* chore: setup toaster

* chore: persist threads deletion

* fix: create thread with new message

* chore: create new thread should change route path

* chore: navigate after delet dialog thread

* chore: thread favorites and orders

* chore: dismiss deleting modal on delete

* chore: remove undefined properties

* chore: remove deprecated run step

* chore: fix delete thread

* chore: create empty thread content on started streaming

* chore: correct messages store key

* chore: stuck at generating state

* chore: preapre chat toolbar

* chore: introduce in-memory app state

* chore: update extensions migration logic

* chore: remove redundant extensions migration gate

* chore: message toolbar user and assistant

* chore: add logo gemini

* feat: remote providers with model capabilities

* chore: maintain provider settings

* chore: move speed token into chat input

* chore: temp harcoded model loader

* chore: make chat text selectable and truncate model list

* chore: update shortcut UI

* Feat/implement threads (#4977)

* chore: add fuse.js library for enhanced search functionality

* feat: implement thread filtering with Fuse.js for improved search capabilities

* fix: update the fuseOptions

* feat: add search functionality to LeftPanel and refactor thread retrieval logic

* refactor: optimize thread filtering and improve search functionality in LeftPanel

* fix: more edits

* refactor: remove duplicate import of useAppState in StreamingContent component

* chore: update navigate after delete all thread

* chore: pass prop speedToken from new chat input

* chore: persist provider general settings

* chore: styling search left panel

* chore: cleanup margin

* chore: update size icon

* chore: improve chat input

* chore: imprve list markdown

* chore: animate border

* feat: local model provider work

* chore: persist manually added model

* chore: prepare download management ui and show version on general setting

* chore: improve pre tag

* chore: remove buton install extension and improve light theme download

* chore: add missing hardware information handler

* chore: cleanup small ui

* chore: update default provider settings

* fix: missing fs commands

* chore: correct provider models

* chore: prepare delete model

* chore: handle thinking block

* chore: fix conditional message toolbar

* chore: pophover download select none

* enhancement: add prune mode

* chore: model settings

* chore: bump engine version tauri

* chore: update style thinking

* chore: add indicator and toogle mcp server

* chore: wip hub

* chore: update model settings

* chore: mvp hub

* chore: add function rename title

* chore: update function delete message

* chore: update rename title

* chore: update model settings

* chore: persist MCP configs

* refactor: clean up utils

* chore: add tools to completion request

* chore: clean up

* chore: ignore assets

---------

Co-authored-by: Ivan Leo <ivanleomk@gmail.com>
Co-authored-by: Louis <louis@jan.ai>
2025-05-15 19:38:59 +07:00

247 lines
6.4 KiB
TypeScript

import { AIEngine, BaseExtension, ExtensionTypeEnum } from '@janhq/core'
import { convertFileSrc, invoke } from '@tauri-apps/api/core'
/**
* 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
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
}
}
export type ExtensionManifest = {
url: string
name: string
productName?: string
active?: boolean
description?: string
version?: string
}
/**
* 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>()
/**
* 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
)
}
}
/**
* 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.
*/
load() {
this.listExtensions().forEach((ext) => {
ext.onLoad()
})
}
/**
* 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 res = await invoke('get_active_extensions')
if (!res || !Array.isArray(res)) return []
const extensions: Extension[] = res.map((ext: ExtensionManifest) => {
return new Extension(
ext.url,
ext.name,
ext.productName,
ext.active,
ext.description,
ext.version
)
})
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) {
// Import class
const extensionUrl = extension.url
await import(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 invoke('install_extension', {
extensions,
})) as ExtensionManifest[]
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.
*/
uninstall(extensions: string[], reload = true) {
if (typeof window === 'undefined') {
return
}
return invoke('uninstall_extension', { extensions, reload })
}
/**
* Shared instance of ExtensionManager.
*/
static getInstance() {
if (!window.core.extensionManager)
window.core.extensionManager = new ExtensionManager()
return window.core.extensionManager as ExtensionManager
}
}