(0)
diff --git a/web/app/_helpers/withAnalytics.tsx b/web/app/_helpers/withAnalytics.tsx
index 72ddbb3af..2271c3464 100644
--- a/web/app/_helpers/withAnalytics.tsx
+++ b/web/app/_helpers/withAnalytics.tsx
@@ -1,16 +1,15 @@
-"use client";
-import React, { useEffect } from "react";
+'use client'
+import React, { useEffect } from 'react'
export function withAnalytics>(
Component: React.ComponentType
): React.FC
{
const WrappedComponent: React.FC
= (props) => {
-
useEffect(() => {
// Initialize analytics
- }, []);
+ }, [])
- return ;
- };
- return WrappedComponent;
+ return
+ }
+ return WrappedComponent
}
diff --git a/web/app/_hooks/useChatMessages.ts b/web/app/_hooks/useChatMessages.ts
index cba1074ab..7c7f22d80 100644
--- a/web/app/_hooks/useChatMessages.ts
+++ b/web/app/_hooks/useChatMessages.ts
@@ -1,14 +1,14 @@
-import { ChatMessage, RawMessage, toChatMessage } from "@/_models/ChatMessage";
-import { executeSerial } from "@/_services/pluginService";
-import { useAtomValue, useSetAtom } from "jotai";
-import { useEffect, useState } from "react";
-import { DataService } from "@janhq/core";
-import { addOldMessagesAtom } from "@/_helpers/atoms/ChatMessage.atom";
+import { ChatMessage, RawMessage, toChatMessage } from '@/_models/ChatMessage'
+import { executeSerial } from '@/_services/pluginService'
+import { useAtomValue, useSetAtom } from 'jotai'
+import { useEffect, useState } from 'react'
+import { DataService } from '@janhq/core'
+import { addOldMessagesAtom } from '@/_helpers/atoms/ChatMessage.atom'
import {
currentConversationAtom,
conversationStatesAtom,
updateConversationHasMoreAtom,
-} from "@/_helpers/atoms/Conversation.atom";
+} from '@/_helpers/atoms/Conversation.atom'
/**
* Custom hooks to get chat messages for current(active) conversation
@@ -17,47 +17,55 @@ import {
* @returns
*/
const useChatMessages = (offset = 0) => {
- const [loading, setLoading] = useState(true);
- const addOldChatMessages = useSetAtom(addOldMessagesAtom);
- const currentConvo = useAtomValue(currentConversationAtom);
- const convoStates = useAtomValue(conversationStatesAtom);
- const updateConvoHasMore = useSetAtom(updateConversationHasMoreAtom);
+ const [loading, setLoading] = useState(true)
+ const addOldChatMessages = useSetAtom(addOldMessagesAtom)
+ const currentConvo = useAtomValue(currentConversationAtom)
+ const convoStates = useAtomValue(conversationStatesAtom)
+ const updateConvoHasMore = useSetAtom(updateConversationHasMoreAtom)
useEffect(() => {
if (!currentConvo) {
- return;
+ return
}
- const hasMore = convoStates[currentConvo._id ?? ""]?.hasMore ?? true;
- if (!hasMore) return;
+ const hasMore = convoStates[currentConvo._id ?? '']?.hasMore ?? true
+ if (!hasMore) return
const getMessages = async () => {
- executeSerial(DataService.GetConversationMessages, currentConvo._id).then((data: any) => {
- if (!data) {
- return;
+ executeSerial(DataService.GetConversationMessages, currentConvo._id).then(
+ (data: any) => {
+ if (!data) {
+ return
+ }
+ const newMessages = parseMessages(data ?? [])
+ addOldChatMessages(newMessages)
+ updateConvoHasMore(currentConvo._id ?? '', false)
+ setLoading(false)
}
- const newMessages = parseMessages(data ?? []);
- addOldChatMessages(newMessages);
- updateConvoHasMore(currentConvo._id ?? "", false);
- setLoading(false);
- });
- };
- getMessages();
- }, [offset, currentConvo?._id, convoStates, addOldChatMessages, updateConvoHasMore]);
+ )
+ }
+ getMessages()
+ }, [
+ offset,
+ currentConvo?._id,
+ convoStates,
+ addOldChatMessages,
+ updateConvoHasMore,
+ ])
return {
loading: loading,
error: undefined,
- hasMore: convoStates[currentConvo?._id ?? ""]?.hasMore ?? true,
- };
-};
-
-function parseMessages(messages: RawMessage[]): ChatMessage[] {
- const newMessages: ChatMessage[] = [];
- for (const m of messages) {
- const chatMessage = toChatMessage(m);
- newMessages.push(chatMessage);
+ hasMore: convoStates[currentConvo?._id ?? '']?.hasMore ?? true,
}
- return newMessages;
}
-export default useChatMessages;
+function parseMessages(messages: RawMessage[]): ChatMessage[] {
+ const newMessages: ChatMessage[] = []
+ for (const m of messages) {
+ const chatMessage = toChatMessage(m)
+ newMessages.push(chatMessage)
+ }
+ return newMessages
+}
+
+export default useChatMessages
diff --git a/web/app/_hooks/useCreateConversation.ts b/web/app/_hooks/useCreateConversation.ts
index 8b492abf2..665e32e03 100644
--- a/web/app/_hooks/useCreateConversation.ts
+++ b/web/app/_hooks/useCreateConversation.ts
@@ -1,46 +1,44 @@
-import { useAtom, useSetAtom } from "jotai";
-import { Conversation } from "@/_models/Conversation";
-import { executeSerial } from "@/_services/pluginService";
-import { DataService } from "@janhq/core";
+import { useAtom, useSetAtom } from 'jotai'
+import { Conversation } from '@/_models/Conversation'
+import { executeSerial } from '@/_services/pluginService'
+import { DataService } from '@janhq/core'
import {
userConversationsAtom,
setActiveConvoIdAtom,
addNewConversationStateAtom,
updateConversationWaitingForResponseAtom,
updateConversationErrorAtom,
-} from "@/_helpers/atoms/Conversation.atom";
-import useInitModel from "./useInitModel";
-import { AssistantModel } from "@/_models/AssistantModel";
+} from '@/_helpers/atoms/Conversation.atom'
+import useInitModel from './useInitModel'
+import { AssistantModel } from '@/_models/AssistantModel'
const useCreateConversation = () => {
- const { initModel } = useInitModel();
+ const { initModel } = useInitModel()
const [userConversations, setUserConversations] = useAtom(
userConversationsAtom
- );
- const setActiveConvoId = useSetAtom(setActiveConvoIdAtom);
- const addNewConvoState = useSetAtom(addNewConversationStateAtom);
- const updateConvWaiting = useSetAtom(
- updateConversationWaitingForResponseAtom
- );
- const updateConvError = useSetAtom(updateConversationErrorAtom);
+ )
+ const setActiveConvoId = useSetAtom(setActiveConvoIdAtom)
+ const addNewConvoState = useSetAtom(addNewConversationStateAtom)
+ const updateConvWaiting = useSetAtom(updateConversationWaitingForResponseAtom)
+ const updateConvError = useSetAtom(updateConversationErrorAtom)
const requestCreateConvo = async (model: AssistantModel) => {
- const conversationName = model.name;
+ const conversationName = model.name
const conv: Conversation = {
modelId: model._id,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
name: conversationName,
- };
- const id = await executeSerial(DataService.CreateConversation, conv);
+ }
+ const id = await executeSerial(DataService.CreateConversation, conv)
- if (id) updateConvWaiting(id, true);
+ if (id) updateConvWaiting(id, true)
initModel(model).then((res: any) => {
- if (id) updateConvWaiting(id, false);
+ if (id) updateConvWaiting(id, false)
if (res?.error) {
- updateConvError(id, res.error);
+ updateConvError(id, res.error)
}
- });
+ })
const mappedConvo: Conversation = {
_id: id,
@@ -48,19 +46,19 @@ const useCreateConversation = () => {
name: conversationName,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
- };
+ }
- addNewConvoState(id ?? "", {
+ addNewConvoState(id ?? '', {
hasMore: true,
waitingForResponse: false,
- });
- setUserConversations([mappedConvo, ...userConversations]);
- setActiveConvoId(id);
- };
+ })
+ setUserConversations([mappedConvo, ...userConversations])
+ setActiveConvoId(id)
+ }
return {
requestCreateConvo,
- };
-};
+ }
+}
-export default useCreateConversation;
+export default useCreateConversation
diff --git a/web/app/_hooks/useDeleteConversation.ts b/web/app/_hooks/useDeleteConversation.ts
index 703a54011..cd2dde4d8 100644
--- a/web/app/_hooks/useDeleteConversation.ts
+++ b/web/app/_hooks/useDeleteConversation.ts
@@ -1,61 +1,61 @@
-import { currentPromptAtom } from "@/_helpers/JotaiWrapper";
-import { execute } from "@/_services/pluginService";
-import { useAtom, useAtomValue, useSetAtom } from "jotai";
-import { DataService } from "@janhq/core";
-import { deleteConversationMessage } from "@/_helpers/atoms/ChatMessage.atom";
+import { currentPromptAtom } from '@/_helpers/JotaiWrapper'
+import { execute } from '@/_services/pluginService'
+import { useAtom, useAtomValue, useSetAtom } from 'jotai'
+import { DataService } from '@janhq/core'
+import { deleteConversationMessage } from '@/_helpers/atoms/ChatMessage.atom'
import {
userConversationsAtom,
getActiveConvoIdAtom,
setActiveConvoIdAtom,
-} from "@/_helpers/atoms/Conversation.atom";
+} from '@/_helpers/atoms/Conversation.atom'
import {
showingProductDetailAtom,
showingAdvancedPromptAtom,
-} from "@/_helpers/atoms/Modal.atom";
+} from '@/_helpers/atoms/Modal.atom'
import {
MainViewState,
setMainViewStateAtom,
-} from "@/_helpers/atoms/MainView.atom";
+} from '@/_helpers/atoms/MainView.atom'
export default function useDeleteConversation() {
const [userConversations, setUserConversations] = useAtom(
- userConversationsAtom,
- );
- const setCurrentPrompt = useSetAtom(currentPromptAtom);
- const setShowingProductDetail = useSetAtom(showingProductDetailAtom);
- const setShowingAdvancedPrompt = useSetAtom(showingAdvancedPromptAtom);
- const activeConvoId = useAtomValue(getActiveConvoIdAtom);
+ userConversationsAtom
+ )
+ const setCurrentPrompt = useSetAtom(currentPromptAtom)
+ const setShowingProductDetail = useSetAtom(showingProductDetailAtom)
+ const setShowingAdvancedPrompt = useSetAtom(showingAdvancedPromptAtom)
+ const activeConvoId = useAtomValue(getActiveConvoIdAtom)
- const setActiveConvoId = useSetAtom(setActiveConvoIdAtom);
- const deleteMessages = useSetAtom(deleteConversationMessage);
- const setMainViewState = useSetAtom(setMainViewStateAtom);
+ const setActiveConvoId = useSetAtom(setActiveConvoIdAtom)
+ const deleteMessages = useSetAtom(deleteConversationMessage)
+ const setMainViewState = useSetAtom(setMainViewStateAtom)
const deleteConvo = async () => {
if (activeConvoId) {
try {
- await execute(DataService.DeleteConversation, activeConvoId);
+ await execute(DataService.DeleteConversation, activeConvoId)
const currentConversations = userConversations.filter(
- (c) => c._id !== activeConvoId,
- );
- setUserConversations(currentConversations);
- deleteMessages(activeConvoId);
+ (c) => c._id !== activeConvoId
+ )
+ setUserConversations(currentConversations)
+ deleteMessages(activeConvoId)
if (currentConversations.length > 0) {
- setActiveConvoId(currentConversations[0]._id);
+ setActiveConvoId(currentConversations[0]._id)
} else {
- setMainViewState(MainViewState.Welcome);
- setActiveConvoId(undefined);
+ setMainViewState(MainViewState.Welcome)
+ setActiveConvoId(undefined)
}
- setCurrentPrompt("");
- setShowingProductDetail(false);
- setShowingAdvancedPrompt(false);
+ setCurrentPrompt('')
+ setShowingProductDetail(false)
+ setShowingAdvancedPrompt(false)
} catch (err) {
- console.error(err);
+ console.error(err)
}
}
- };
+ }
return {
deleteConvo,
- };
+ }
}
diff --git a/web/app/_hooks/useDeleteModel.ts b/web/app/_hooks/useDeleteModel.ts
index a8015d660..b561a3779 100644
--- a/web/app/_hooks/useDeleteModel.ts
+++ b/web/app/_hooks/useDeleteModel.ts
@@ -1,21 +1,21 @@
-import { execute, executeSerial } from "@/_services/pluginService";
-import { ModelManagementService } from "@janhq/core";
-import { useSetAtom } from "jotai";
-import { downloadedModelAtom } from "@/_helpers/atoms/DownloadedModel.atom";
-import { getDownloadedModels } from "./useGetDownloadedModels";
-import { AssistantModel } from "@/_models/AssistantModel";
+import { execute, executeSerial } from '@/_services/pluginService'
+import { ModelManagementService } from '@janhq/core'
+import { useSetAtom } from 'jotai'
+import { downloadedModelAtom } from '@/_helpers/atoms/DownloadedModel.atom'
+import { getDownloadedModels } from './useGetDownloadedModels'
+import { AssistantModel } from '@/_models/AssistantModel'
export default function useDeleteModel() {
- const setDownloadedModels = useSetAtom(downloadedModelAtom);
+ const setDownloadedModels = useSetAtom(downloadedModelAtom)
const deleteModel = async (model: AssistantModel) => {
- execute(ModelManagementService.DeleteDownloadModel, model._id);
- await executeSerial(ModelManagementService.DeleteModel, model._id);
+ execute(ModelManagementService.DeleteDownloadModel, model._id)
+ await executeSerial(ModelManagementService.DeleteModel, model._id)
// reload models
- const downloadedModels = await getDownloadedModels();
- setDownloadedModels(downloadedModels);
- };
+ const downloadedModels = await getDownloadedModels()
+ setDownloadedModels(downloadedModels)
+ }
- return { deleteModel };
+ return { deleteModel }
}
diff --git a/web/app/_hooks/useDownloadModel.ts b/web/app/_hooks/useDownloadModel.ts
index 137e876c8..e25fc2e52 100644
--- a/web/app/_hooks/useDownloadModel.ts
+++ b/web/app/_hooks/useDownloadModel.ts
@@ -1,8 +1,8 @@
-import { executeSerial } from "@/_services/pluginService";
-import { DataService, ModelManagementService } from "@janhq/core";
-import { ModelVersion } from "@/_models/ModelVersion";
-import { Product } from "@/_models/Product";
-import { AssistantModel } from "@/_models/AssistantModel";
+import { executeSerial } from '@/_services/pluginService'
+import { DataService, ModelManagementService } from '@janhq/core'
+import { ModelVersion } from '@/_models/ModelVersion'
+import { Product } from '@/_models/Product'
+import { AssistantModel } from '@/_models/AssistantModel'
export default function useDownloadModel() {
const assistanModel = (
@@ -32,24 +32,24 @@ export default function useDownloadModel() {
greeting: model.greeting,
type: model.type,
createdAt: new Date(model.createdAt).getTime(),
- updatedAt: new Date(model.updatedAt ?? "").getTime(),
- status: "",
+ updatedAt: new Date(model.updatedAt ?? '').getTime(),
+ status: '',
releaseDate: -1,
tags: model.tags,
- };
- };
+ }
+ }
const downloadModel = async (model: Product, modelVersion: ModelVersion) => {
- modelVersion.startDownloadAt = Date.now();
- const assistantModel = assistanModel(model, modelVersion);
- await executeSerial(ModelManagementService.StoreModel, assistantModel);
+ modelVersion.startDownloadAt = Date.now()
+ const assistantModel = assistanModel(model, modelVersion)
+ await executeSerial(ModelManagementService.StoreModel, assistantModel)
await executeSerial(ModelManagementService.DownloadModel, {
downloadUrl: modelVersion.downloadLink,
fileName: modelVersion._id,
- });
- };
+ })
+ }
return {
downloadModel,
- };
+ }
}
diff --git a/web/app/_hooks/useGetAppVersion.ts b/web/app/_hooks/useGetAppVersion.ts
index c17ec208b..e89de231f 100644
--- a/web/app/_hooks/useGetAppVersion.ts
+++ b/web/app/_hooks/useGetAppVersion.ts
@@ -1,17 +1,17 @@
-import { useEffect, useState } from "react";
+import { useEffect, useState } from 'react'
export default function useGetAppVersion() {
- const [version, setVersion] = useState("");
+ const [version, setVersion] = useState('')
useEffect(() => {
- getAppVersion();
- }, []);
+ getAppVersion()
+ }, [])
const getAppVersion = () => {
window.electronAPI.appVersion().then((version: string | undefined) => {
- setVersion(version ?? "");
- });
- };
+ setVersion(version ?? '')
+ })
+ }
- return { version };
+ return { version }
}
diff --git a/web/app/_hooks/useGetConfiguredModels.ts b/web/app/_hooks/useGetConfiguredModels.ts
index f34f3052c..c866a6201 100644
--- a/web/app/_hooks/useGetConfiguredModels.ts
+++ b/web/app/_hooks/useGetConfiguredModels.ts
@@ -1,22 +1,22 @@
-import { Product } from "@/_models/Product";
-import { useEffect, useState } from "react";
-import { getConfiguredModels } from "./useGetDownloadedModels";
+import { Product } from '@/_models/Product'
+import { useEffect, useState } from 'react'
+import { getConfiguredModels } from './useGetDownloadedModels'
export default function useGetConfiguredModels() {
- const [loading, setLoading] = useState(false);
- const [models, setModels] = useState([]);
+ const [loading, setLoading] = useState(false)
+ const [models, setModels] = useState([])
const fetchModels = async () => {
- setLoading(true);
- const models = await getConfiguredModels();
- setLoading(false);
- setModels(models);
- };
+ setLoading(true)
+ const models = await getConfiguredModels()
+ setLoading(false)
+ setModels(models)
+ }
// TODO allow user for filter
useEffect(() => {
- fetchModels();
- }, []);
+ fetchModels()
+ }, [])
- return { loading, models };
+ return { loading, models }
}
diff --git a/web/app/_hooks/useGetCurrentUser.ts b/web/app/_hooks/useGetCurrentUser.ts
index ad06e3afd..c31e581c9 100644
--- a/web/app/_hooks/useGetCurrentUser.ts
+++ b/web/app/_hooks/useGetCurrentUser.ts
@@ -1,35 +1,35 @@
// @ts-nocheck
-import { useSession } from "next-auth/react";
-import { useEffect, useState } from "react";
-import useSignOut from "./useSignOut";
-import { DefaultUser, User } from "@/_models/User";
+import { useSession } from 'next-auth/react'
+import { useEffect, useState } from 'react'
+import useSignOut from './useSignOut'
+import { DefaultUser, User } from '@/_models/User'
export default function useGetCurrentUser() {
- const { data: session, status } = useSession();
- const { signOut } = useSignOut();
- const [loading, setLoading] = useState(status === "loading");
- const [user, setUser] = useState();
+ const { data: session, status } = useSession()
+ const { signOut } = useSignOut()
+ const [loading, setLoading] = useState(status === 'loading')
+ const [user, setUser] = useState()
useEffect(() => {
if (
- status !== "loading" &&
+ status !== 'loading' &&
session &&
- session?.error === "RefreshAccessTokenError"
+ session?.error === 'RefreshAccessTokenError'
) {
- signOut();
+ signOut()
}
- }, [session, status]);
+ }, [session, status])
useEffect(() => {
- if (status === "loading") {
- setUser(undefined);
- setLoading(true);
- return;
+ if (status === 'loading') {
+ setUser(undefined)
+ setLoading(true)
+ return
}
- if (status === "unauthenticated") {
- setUser(undefined);
- setLoading(false);
- return;
+ if (status === 'unauthenticated') {
+ setUser(undefined)
+ setLoading(false)
+ return
}
const tmp = {
@@ -37,11 +37,11 @@ export default function useGetCurrentUser() {
displayName: session?.user?.name ?? DefaultUser.displayName,
avatarUrl: session?.user?.image ?? DefaultUser.avatarUrl,
email: session?.user?.email ?? DefaultUser.email,
- };
+ }
- setUser(tmp);
- setLoading(false);
- }, [status]);
+ setUser(tmp)
+ setLoading(false)
+ }, [status])
- return { user, loading };
+ return { user, loading }
}
diff --git a/web/app/_hooks/useGetDownloadedModels.ts b/web/app/_hooks/useGetDownloadedModels.ts
index 9d3f11f34..251027d57 100644
--- a/web/app/_hooks/useGetDownloadedModels.ts
+++ b/web/app/_hooks/useGetDownloadedModels.ts
@@ -1,30 +1,30 @@
-import { Product } from "@/_models/Product";
-import { useEffect } from "react";
-import { executeSerial } from "../../../electron/core/plugin-manager/execution/extension-manager";
-import { ModelManagementService } from "@janhq/core";
-import { useAtom } from "jotai";
-import { downloadedModelAtom } from "@/_helpers/atoms/DownloadedModel.atom";
-import { AssistantModel } from "@/_models/AssistantModel";
+import { Product } from '@/_models/Product'
+import { useEffect } from 'react'
+import { executeSerial } from '../../../electron/core/plugin-manager/execution/extension-manager'
+import { ModelManagementService } from '@janhq/core'
+import { useAtom } from 'jotai'
+import { downloadedModelAtom } from '@/_helpers/atoms/DownloadedModel.atom'
+import { AssistantModel } from '@/_models/AssistantModel'
export function useGetDownloadedModels() {
- const [downloadedModels, setDownloadedModels] = useAtom(downloadedModelAtom);
+ const [downloadedModels, setDownloadedModels] = useAtom(downloadedModelAtom)
useEffect(() => {
getDownloadedModels().then((downloadedModels) => {
- setDownloadedModels(downloadedModels);
- });
- }, []);
+ setDownloadedModels(downloadedModels)
+ })
+ }, [])
- return { downloadedModels };
+ return { downloadedModels }
}
export async function getDownloadedModels(): Promise {
const downloadedModels: AssistantModel[] = await executeSerial(
ModelManagementService.GetFinishedDownloadModels
- );
- return downloadedModels ?? [];
+ )
+ return downloadedModels ?? []
}
export async function getConfiguredModels(): Promise {
- return executeSerial(ModelManagementService.GetConfiguredModels);
+ return executeSerial(ModelManagementService.GetConfiguredModels)
}
diff --git a/web/app/_hooks/useGetHuggingFaceModel.ts b/web/app/_hooks/useGetHuggingFaceModel.ts
index 613dcd337..85a3636f8 100644
--- a/web/app/_hooks/useGetHuggingFaceModel.ts
+++ b/web/app/_hooks/useGetHuggingFaceModel.ts
@@ -1,26 +1,26 @@
-import { useState } from "react";
-import { SearchModelParamHf } from "@/_models/hf/SearchModelParam.hf";
-import { Product } from "@/_models/Product";
-import { useSetAtom } from "jotai";
-import { modelLoadMoreAtom } from "@/_helpers/atoms/ExploreModelLoading.atom";
+import { useState } from 'react'
+import { SearchModelParamHf } from '@/_models/hf/SearchModelParam.hf'
+import { Product } from '@/_models/Product'
+import { useSetAtom } from 'jotai'
+import { modelLoadMoreAtom } from '@/_helpers/atoms/ExploreModelLoading.atom'
export default function useGetHuggingFaceModel() {
- const setLoadMoreInProgress = useSetAtom(modelLoadMoreAtom);
- const [modelList, setModelList] = useState([]);
+ const setLoadMoreInProgress = useSetAtom(modelLoadMoreAtom)
+ const [modelList, setModelList] = useState([])
const [currentOwner, setCurrentOwner] = useState(
undefined
- );
+ )
const getHuggingFaceModel = async (owner?: string) => {
if (!owner) {
- setModelList([]);
- return;
+ setModelList([])
+ return
}
const searchParams: SearchModelParamHf = {
search: { owner },
limit: 5,
- };
+ }
// const result = await searchModels(searchParams);
// console.debug("result", JSON.stringify(result));
// if (owner !== currentOwner) {
@@ -29,8 +29,8 @@ export default function useGetHuggingFaceModel() {
// } else {
// setModelList([...modelList, ...result.data]);
// }
- setLoadMoreInProgress(false);
- };
+ setLoadMoreInProgress(false)
+ }
- return { modelList, getHuggingFaceModel };
+ return { modelList, getHuggingFaceModel }
}
diff --git a/web/app/_hooks/useGetMostSuitableModelVersion.ts b/web/app/_hooks/useGetMostSuitableModelVersion.ts
index 8f8fc40e8..1ea0f66d1 100644
--- a/web/app/_hooks/useGetMostSuitableModelVersion.ts
+++ b/web/app/_hooks/useGetMostSuitableModelVersion.ts
@@ -1,25 +1,25 @@
-import { ModelVersion } from "@/_models/ModelVersion";
-import { useState } from "react";
-import { useAtomValue } from "jotai";
-import { totalRamAtom } from "@/_helpers/atoms/SystemBar.atom";
+import { ModelVersion } from '@/_models/ModelVersion'
+import { useState } from 'react'
+import { useAtomValue } from 'jotai'
+import { totalRamAtom } from '@/_helpers/atoms/SystemBar.atom'
export default function useGetMostSuitableModelVersion() {
- const [suitableModel, setSuitableModel] = useState();
- const totalRam = useAtomValue(totalRamAtom);
+ const [suitableModel, setSuitableModel] = useState()
+ const totalRam = useAtomValue(totalRamAtom)
const getMostSuitableModelVersion = async (modelVersions: ModelVersion[]) => {
// find the model version with the highest required RAM that is still below the user's RAM by 80%
const modelVersion = modelVersions.reduce((prev, current) => {
if (current.maxRamRequired > prev.maxRamRequired) {
if (current.maxRamRequired < totalRam * 0.8) {
- return current;
+ return current
}
}
- return prev;
- });
+ return prev
+ })
- setSuitableModel(modelVersion);
- };
+ setSuitableModel(modelVersion)
+ }
- return { suitableModel, getMostSuitableModelVersion };
+ return { suitableModel, getMostSuitableModelVersion }
}
diff --git a/web/app/_hooks/useGetPerformanceTag.ts b/web/app/_hooks/useGetPerformanceTag.ts
index 822841263..81380dc66 100644
--- a/web/app/_hooks/useGetPerformanceTag.ts
+++ b/web/app/_hooks/useGetPerformanceTag.ts
@@ -1,8 +1,8 @@
-import { useState } from "react";
-import { ModelVersion } from "@/_models/ModelVersion";
-import { ModelPerformance, TagType } from "@/_components/SimpleTag/TagType";
-import { useAtomValue } from "jotai";
-import { totalRamAtom } from "@/_helpers/atoms/SystemBar.atom";
+import { useState } from 'react'
+import { ModelVersion } from '@/_models/ModelVersion'
+import { ModelPerformance, TagType } from '@/_components/SimpleTag/TagType'
+import { useAtomValue } from 'jotai'
+import { totalRamAtom } from '@/_helpers/atoms/SystemBar.atom'
// Recommendation:
// `Recommended (green)`: "Max RAM required" is 80% of users max RAM.
@@ -10,38 +10,41 @@ import { totalRamAtom } from "@/_helpers/atoms/SystemBar.atom";
// `Not enough RAM (red)`: User RAM is below "Max RAM required"
export default function useGetPerformanceTag() {
- const [performanceTag, setPerformanceTag] = useState();
- const totalRam = useAtomValue(totalRamAtom);
+ const [performanceTag, setPerformanceTag] = useState()
+ const totalRam = useAtomValue(totalRamAtom)
const getPerformanceForModel = async (modelVersion: ModelVersion) => {
- const requiredRam = modelVersion.maxRamRequired;
- setPerformanceTag(calculateRamPerformance(requiredRam, totalRam));
- };
+ const requiredRam = modelVersion.maxRamRequired
+ setPerformanceTag(calculateRamPerformance(requiredRam, totalRam))
+ }
- let title = "";
+ let title = ''
switch (performanceTag) {
case ModelPerformance.PerformancePositive:
- title = "Recommended";
- break;
+ title = 'Recommended'
+ break
case ModelPerformance.PerformanceNeutral:
- title = "Slow on your device";
- break;
+ title = 'Slow on your device'
+ break
case ModelPerformance.PerformanceNegative:
- title = "Not enough RAM";
- break;
+ title = 'Not enough RAM'
+ break
}
- return { performanceTag, title, getPerformanceForModel };
+ return { performanceTag, title, getPerformanceForModel }
}
-const calculateRamPerformance = (requiredRamAmt: number, totalRamAmt: number) => {
- const percentage = requiredRamAmt / totalRamAmt;
+const calculateRamPerformance = (
+ requiredRamAmt: number,
+ totalRamAmt: number
+) => {
+ const percentage = requiredRamAmt / totalRamAmt
if (percentage < 0.8) {
- return ModelPerformance.PerformancePositive;
+ return ModelPerformance.PerformancePositive
} else if (percentage >= 0.8 && percentage < 1) {
- return ModelPerformance.PerformanceNeutral;
+ return ModelPerformance.PerformanceNeutral
} else {
- return ModelPerformance.PerformanceNegative;
+ return ModelPerformance.PerformanceNegative
}
-};
+}
diff --git a/web/app/_hooks/useGetSystemResources.ts b/web/app/_hooks/useGetSystemResources.ts
index 47733e14e..6453b3950 100644
--- a/web/app/_hooks/useGetSystemResources.ts
+++ b/web/app/_hooks/useGetSystemResources.ts
@@ -1,37 +1,42 @@
-import { useEffect, useState } from "react";
-import { executeSerial } from "../../../electron/core/plugin-manager/execution/extension-manager";
-import { SystemMonitoringService } from "@janhq/core";
-import { useSetAtom } from "jotai";
-import { totalRamAtom } from "@/_helpers/atoms/SystemBar.atom";
+import { useEffect, useState } from 'react'
+import { executeSerial } from '../../../electron/core/plugin-manager/execution/extension-manager'
+import { SystemMonitoringService } from '@janhq/core'
+import { useSetAtom } from 'jotai'
+import { totalRamAtom } from '@/_helpers/atoms/SystemBar.atom'
export default function useGetSystemResources() {
- const [ram, setRam] = useState(0);
- const [cpu, setCPU] = useState(0);
- const setTotalRam = useSetAtom(totalRamAtom);
+ const [ram, setRam] = useState(0)
+ const [cpu, setCPU] = useState(0)
+ const setTotalRam = useSetAtom(totalRamAtom)
const getSystemResources = async () => {
- const resourceInfor = await executeSerial(SystemMonitoringService.GetResourcesInfo);
- const currentLoadInfor = await executeSerial(SystemMonitoringService.GetCurrentLoad);
- const ram = (resourceInfor?.mem?.active ?? 0) / (resourceInfor?.mem?.total ?? 1);
- if (resourceInfor?.mem?.total) setTotalRam(resourceInfor.mem.total);
+ const resourceInfor = await executeSerial(
+ SystemMonitoringService.GetResourcesInfo
+ )
+ const currentLoadInfor = await executeSerial(
+ SystemMonitoringService.GetCurrentLoad
+ )
+ const ram =
+ (resourceInfor?.mem?.active ?? 0) / (resourceInfor?.mem?.total ?? 1)
+ if (resourceInfor?.mem?.total) setTotalRam(resourceInfor.mem.total)
- setRam(Math.round(ram * 100));
- setCPU(Math.round(currentLoadInfor?.currentLoad ?? 0));
- };
+ setRam(Math.round(ram * 100))
+ setCPU(Math.round(currentLoadInfor?.currentLoad ?? 0))
+ }
useEffect(() => {
- getSystemResources();
+ getSystemResources()
// Fetch interval - every 3s
const intervalId = setInterval(() => {
- getSystemResources();
- }, 5000);
+ getSystemResources()
+ }, 5000)
// clean up
- return () => clearInterval(intervalId);
- }, []);
+ return () => clearInterval(intervalId)
+ }, [])
return {
ram,
cpu,
- };
+ }
}
diff --git a/web/app/_hooks/useGetUserConversations.ts b/web/app/_hooks/useGetUserConversations.ts
index c3380425a..c749f9f7f 100644
--- a/web/app/_hooks/useGetUserConversations.ts
+++ b/web/app/_hooks/useGetUserConversations.ts
@@ -1,38 +1,38 @@
-import { Conversation, ConversationState } from "@/_models/Conversation";
-import { useSetAtom } from "jotai";
-import { executeSerial } from "@/_services/pluginService";
-import { DataService } from "@janhq/core";
+import { Conversation, ConversationState } from '@/_models/Conversation'
+import { useSetAtom } from 'jotai'
+import { executeSerial } from '@/_services/pluginService'
+import { DataService } from '@janhq/core'
import {
conversationStatesAtom,
userConversationsAtom,
-} from "@/_helpers/atoms/Conversation.atom";
+} from '@/_helpers/atoms/Conversation.atom'
const useGetUserConversations = () => {
- const setConversationStates = useSetAtom(conversationStatesAtom);
- const setConversations = useSetAtom(userConversationsAtom);
+ const setConversationStates = useSetAtom(conversationStatesAtom)
+ const setConversations = useSetAtom(userConversationsAtom)
const getUserConversations = async () => {
try {
const convos: Conversation[] | undefined = await executeSerial(
DataService.GetConversations
- );
- const convoStates: Record = {};
+ )
+ const convoStates: Record = {}
convos?.forEach((convo) => {
- convoStates[convo._id ?? ""] = {
+ convoStates[convo._id ?? ''] = {
hasMore: true,
waitingForResponse: false,
- };
- });
- setConversationStates(convoStates);
- setConversations(convos ?? []);
+ }
+ })
+ setConversationStates(convoStates)
+ setConversations(convos ?? [])
} catch (ex) {
- console.log(ex);
+ console.log(ex)
}
- };
+ }
return {
getUserConversations,
- };
-};
+ }
+}
-export default useGetUserConversations;
+export default useGetUserConversations
diff --git a/web/app/_hooks/useInitModel.ts b/web/app/_hooks/useInitModel.ts
index 0a0c04280..0c1532f19 100644
--- a/web/app/_hooks/useInitModel.ts
+++ b/web/app/_hooks/useInitModel.ts
@@ -1,33 +1,33 @@
-import { executeSerial } from "@/_services/pluginService";
-import { InferenceService } from "@janhq/core";
-import { useAtom } from "jotai";
-import { activeAssistantModelAtom } from "@/_helpers/atoms/Model.atom";
-import { AssistantModel } from "@/_models/AssistantModel";
+import { executeSerial } from '@/_services/pluginService'
+import { InferenceService } from '@janhq/core'
+import { useAtom } from 'jotai'
+import { activeAssistantModelAtom } from '@/_helpers/atoms/Model.atom'
+import { AssistantModel } from '@/_models/AssistantModel'
export default function useInitModel() {
- const [activeModel, setActiveModel] = useAtom(activeAssistantModelAtom);
+ const [activeModel, setActiveModel] = useAtom(activeAssistantModelAtom)
const initModel = async (model: AssistantModel) => {
if (activeModel && activeModel._id === model._id) {
- console.debug(`Model ${model._id} is already init. Ignore..`);
- return;
+ console.debug(`Model ${model._id} is already init. Ignore..`)
+ return
}
- const currentTime = Date.now();
- console.debug("Init model: ", model._id);
+ const currentTime = Date.now()
+ console.debug('Init model: ', model._id)
- const res = await executeSerial(InferenceService.InitModel, model._id);
+ const res = await executeSerial(InferenceService.InitModel, model._id)
if (res?.error) {
- console.log("error occured: ", res);
- return res;
+ console.log('error occured: ', res)
+ return res
} else {
console.debug(
`Init model successfully!, take ${Date.now() - currentTime}ms`
- );
- setActiveModel(model);
- return {};
+ )
+ setActiveModel(model)
+ return {}
}
- };
+ }
- return { initModel };
+ return { initModel }
}
diff --git a/web/app/_hooks/useSendChatMessage.ts b/web/app/_hooks/useSendChatMessage.ts
index 769b1158e..09355ed1e 100644
--- a/web/app/_hooks/useSendChatMessage.ts
+++ b/web/app/_hooks/useSendChatMessage.ts
@@ -1,74 +1,94 @@
-import { currentPromptAtom } from "@/_helpers/JotaiWrapper";
-import { useAtom, useAtomValue, useSetAtom } from "jotai";
-import { DataService, EventName, InferenceService, events, store } from "@janhq/core";
-import { RawMessage, toChatMessage } from "@/_models/ChatMessage";
-import { executeSerial } from "@/_services/pluginService";
-import { addNewMessageAtom } from "@/_helpers/atoms/ChatMessage.atom";
-import { currentConversationAtom, updateConversationAtom } from "@/_helpers/atoms/Conversation.atom";
+import { currentPromptAtom } from '@/_helpers/JotaiWrapper'
+import { useAtom, useAtomValue, useSetAtom } from 'jotai'
+import {
+ DataService,
+ EventName,
+ InferenceService,
+ events,
+ store,
+} from '@janhq/core'
+import { RawMessage, toChatMessage } from '@/_models/ChatMessage'
+import { executeSerial } from '@/_services/pluginService'
+import { addNewMessageAtom } from '@/_helpers/atoms/ChatMessage.atom'
+import {
+ currentConversationAtom,
+ updateConversationAtom,
+} from '@/_helpers/atoms/Conversation.atom'
export default function useSendChatMessage() {
- const currentConvo = useAtomValue(currentConversationAtom);
- const addNewMessage = useSetAtom(addNewMessageAtom);
- const updateConversation = useSetAtom(updateConversationAtom);
+ const currentConvo = useAtomValue(currentConversationAtom)
+ const addNewMessage = useSetAtom(addNewMessageAtom)
+ const updateConversation = useSetAtom(updateConversationAtom)
- const [currentPrompt, setCurrentPrompt] = useAtom(currentPromptAtom);
+ const [currentPrompt, setCurrentPrompt] = useAtom(currentPromptAtom)
- let timeout: any | undefined = undefined;
+ let timeout: any | undefined = undefined
function updateConvSummary(newMessage: any) {
if (timeout) {
- clearTimeout(timeout);
+ clearTimeout(timeout)
}
timeout = setTimeout(() => {
- const conv = currentConvo;
- if (!currentConvo?.summary || currentConvo.summary === "" || currentConvo.summary.startsWith("User request:")) {
+ const conv = currentConvo
+ if (
+ !currentConvo?.summary ||
+ currentConvo.summary === '' ||
+ currentConvo.summary.startsWith('User request:')
+ ) {
// Request convo summary
setTimeout(async () => {
- newMessage.message = "summary this conversation in 5 words";
- const result = await executeSerial(InferenceService.InferenceRequest, newMessage);
- if (result?.message && result.message.split(" ").length <= 7 && conv?._id) {
+ newMessage.message = 'summary this conversation in 5 words'
+ const result = await executeSerial(
+ InferenceService.InferenceRequest,
+ newMessage
+ )
+ if (
+ result?.message &&
+ result.message.split(' ').length <= 7 &&
+ conv?._id
+ ) {
const updatedConv = {
...conv,
summary: result.message,
- };
- updateConversation(updatedConv);
- await executeSerial(DataService.UpdateConversation, updatedConv);
+ }
+ updateConversation(updatedConv)
+ await executeSerial(DataService.UpdateConversation, updatedConv)
}
- }, 1000);
+ }, 1000)
}
- }, 100);
+ }, 100)
}
const sendChatMessage = async () => {
- setCurrentPrompt("");
- const prompt = currentPrompt.trim();
+ setCurrentPrompt('')
+ const prompt = currentPrompt.trim()
const newMessage: RawMessage = {
conversationId: currentConvo?._id,
message: prompt,
- user: "user",
+ user: 'user',
createdAt: new Date().toISOString(),
- };
- const id = await executeSerial(DataService.CreateMessage, newMessage);
- newMessage._id = id;
+ }
+ const id = await executeSerial(DataService.CreateMessage, newMessage)
+ newMessage._id = id
- const newChatMessage = toChatMessage(newMessage);
- addNewMessage(newChatMessage);
+ const newChatMessage = toChatMessage(newMessage)
+ addNewMessage(newChatMessage)
- events.emit(EventName.OnNewMessageRequest, newMessage);
+ events.emit(EventName.OnNewMessageRequest, newMessage)
if (!currentConvo?.summary && currentConvo) {
const updatedConv = {
...currentConvo,
summary: `Prompt: ${prompt}`,
- };
- updateConversation(updatedConv);
- await executeSerial(DataService.UpdateConversation, updatedConv);
+ }
+ updateConversation(updatedConv)
+ await executeSerial(DataService.UpdateConversation, updatedConv)
}
- updateConvSummary(newMessage);
- };
+ updateConvSummary(newMessage)
+ }
return {
sendChatMessage,
- };
+ }
}
diff --git a/web/app/_hooks/useSignIn.ts b/web/app/_hooks/useSignIn.ts
index 445979028..7fa47ceec 100644
--- a/web/app/_hooks/useSignIn.ts
+++ b/web/app/_hooks/useSignIn.ts
@@ -1,9 +1,9 @@
-import { signIn } from "next-auth/react";
+import { signIn } from 'next-auth/react'
export default function useSignIn() {
const signInWithKeyCloak = () => {
- return signIn("keycloak");
- };
+ return signIn('keycloak')
+ }
- return { signInWithKeyCloak };
+ return { signInWithKeyCloak }
}
diff --git a/web/app/_hooks/useSignOut.ts b/web/app/_hooks/useSignOut.ts
index de6440d49..86f8fa92a 100644
--- a/web/app/_hooks/useSignOut.ts
+++ b/web/app/_hooks/useSignOut.ts
@@ -1,14 +1,14 @@
-import { signOut as signOutNextAuth } from "next-auth/react";
+import { signOut as signOutNextAuth } from 'next-auth/react'
export default function useSignOut() {
const signOut = async () => {
try {
- await fetch(`api/auth/logout`, { method: "GET" });
- await signOutNextAuth({ callbackUrl: "/" });
+ await fetch(`api/auth/logout`, { method: 'GET' })
+ await signOutNextAuth({ callbackUrl: '/' })
} catch (e) {
- console.error(e);
+ console.error(e)
}
- };
+ }
- return { signOut };
+ return { signOut }
}
diff --git a/web/app/_hooks/useStartStopModel.ts b/web/app/_hooks/useStartStopModel.ts
index 1c97d59f8..a2deed011 100644
--- a/web/app/_hooks/useStartStopModel.ts
+++ b/web/app/_hooks/useStartStopModel.ts
@@ -1,26 +1,29 @@
-import { executeSerial } from "@/_services/pluginService";
-import { ModelManagementService, InferenceService } from "@janhq/core";
-import useInitModel from "./useInitModel";
-import { useSetAtom } from "jotai";
-import { activeAssistantModelAtom } from "@/_helpers/atoms/Model.atom";
+import { executeSerial } from '@/_services/pluginService'
+import { ModelManagementService, InferenceService } from '@janhq/core'
+import useInitModel from './useInitModel'
+import { useSetAtom } from 'jotai'
+import { activeAssistantModelAtom } from '@/_helpers/atoms/Model.atom'
export default function useStartStopModel() {
- const { initModel } = useInitModel();
- const setActiveModel = useSetAtom(activeAssistantModelAtom);
+ const { initModel } = useInitModel()
+ const setActiveModel = useSetAtom(activeAssistantModelAtom)
const startModel = async (modelId: string) => {
- const model = await executeSerial(ModelManagementService.GetModelById, modelId);
+ const model = await executeSerial(
+ ModelManagementService.GetModelById,
+ modelId
+ )
if (!model) {
- alert(`Model ${modelId} not found! Please re-download the model first.`);
+ alert(`Model ${modelId} not found! Please re-download the model first.`)
} else {
- await initModel(model);
+ await initModel(model)
}
- };
+ }
const stopModel = async (modelId: string) => {
- await executeSerial(InferenceService.StopModel, modelId);
- setActiveModel(undefined);
- };
+ await executeSerial(InferenceService.StopModel, modelId)
+ setActiveModel(undefined)
+ }
- return { startModel, stopModel };
+ return { startModel, stopModel }
}
diff --git a/web/app/_models/AssistantModel.ts b/web/app/_models/AssistantModel.ts
index 9b6c5060a..5263c81df 100644
--- a/web/app/_models/AssistantModel.ts
+++ b/web/app/_models/AssistantModel.ts
@@ -1,4 +1,4 @@
-import { ProductType } from "./Product";
+import { ProductType } from './Product'
/**
* Represent a model
@@ -8,58 +8,58 @@ export type AssistantModel = {
* Combination of owner and model name.
* Being used as file name. MUST be unique.
*/
- _id: string;
+ _id: string
- name: string;
+ name: string
- quantMethod: string;
+ quantMethod: string
- bits: number;
+ bits: number
- size: number;
+ size: number
- maxRamRequired: number;
+ maxRamRequired: number
- usecase: string;
+ usecase: string
- downloadLink: string;
+ downloadLink: string
/**
* For tracking download info
*/
- startDownloadAt?: number;
+ startDownloadAt?: number
- finishDownloadAt?: number;
+ finishDownloadAt?: number
- productId: string;
+ productId: string
- productName: string;
+ productName: string
- shortDescription: string;
+ shortDescription: string
- longDescription: string;
+ longDescription: string
- avatarUrl: string;
+ avatarUrl: string
- author: string;
+ author: string
- version: string;
+ version: string
- modelUrl: string;
+ modelUrl: string
- nsfw: boolean;
+ nsfw: boolean
- greeting: string;
+ greeting: string
- type: ProductType;
+ type: ProductType
- createdAt: number;
+ createdAt: number
- updatedAt?: number;
+ updatedAt?: number
- status: string;
+ status: string
- releaseDate: number;
+ releaseDate: number
- tags: string[];
-};
+ tags: string[]
+}
diff --git a/web/app/_models/ChatMessage.ts b/web/app/_models/ChatMessage.ts
index 296c63b44..e074a011c 100644
--- a/web/app/_models/ChatMessage.ts
+++ b/web/app/_models/ChatMessage.ts
@@ -1,69 +1,81 @@
-import { NewMessageResponse } from "@janhq/core";
+import { NewMessageResponse } from '@janhq/core'
export enum MessageType {
- Text = "Text",
- Image = "Image",
- ImageWithText = "ImageWithText",
- Error = "Error",
+ Text = 'Text',
+ Image = 'Image',
+ ImageWithText = 'ImageWithText',
+ Error = 'Error',
}
export enum MessageSenderType {
- Ai = "assistant",
- User = "user",
+ Ai = 'assistant',
+ User = 'user',
}
export enum MessageStatus {
- Ready = "ready",
- Pending = "pending",
+ Ready = 'ready',
+ Pending = 'pending',
}
export interface ChatMessage {
- id: string;
- conversationId: string;
- messageType: MessageType;
- messageSenderType: MessageSenderType;
- senderUid: string;
- senderName: string;
- senderAvatarUrl: string;
- text: string | undefined;
- imageUrls?: string[] | undefined;
- createdAt: number;
- status: MessageStatus;
+ id: string
+ conversationId: string
+ messageType: MessageType
+ messageSenderType: MessageSenderType
+ senderUid: string
+ senderName: string
+ senderAvatarUrl: string
+ text: string | undefined
+ imageUrls?: string[] | undefined
+ createdAt: number
+ status: MessageStatus
}
export interface RawMessage {
- _id?: string;
- conversationId?: string;
- user?: string;
- avatar?: string;
- message?: string;
- createdAt?: string;
- updatedAt?: string;
+ _id?: string
+ conversationId?: string
+ user?: string
+ avatar?: string
+ message?: string
+ createdAt?: string
+ updatedAt?: string
}
-export const toChatMessage = (m: RawMessage | NewMessageResponse): ChatMessage => {
- const createdAt = new Date(m.createdAt ?? "").getTime();
- const imageUrls: string[] = [];
- const imageUrl = undefined;
+export const toChatMessage = (
+ m: RawMessage | NewMessageResponse
+): ChatMessage => {
+ const createdAt = new Date(m.createdAt ?? '').getTime()
+ const imageUrls: string[] = []
+ const imageUrl = undefined
if (imageUrl) {
- imageUrls.push(imageUrl);
+ imageUrls.push(imageUrl)
}
- const messageType = MessageType.Text;
- const messageSenderType = m.user === "user" ? MessageSenderType.User : MessageSenderType.Ai;
+ const messageType = MessageType.Text
+ const messageSenderType =
+ m.user === 'user' ? MessageSenderType.User : MessageSenderType.Ai
- const content = m.message ?? "";
+ const content = m.message ?? ''
return {
id: (m._id ?? 0).toString(),
conversationId: (m.conversationId ?? 0).toString(),
messageType: messageType,
messageSenderType: messageSenderType,
- senderUid: m.user?.toString() || "0",
- senderName: m.user === "user" ? "You" : m.user && m.user !== "ai" && m.user !== "assistant" ? m.user : "Assistant",
- senderAvatarUrl: m.avatar ? m.avatar : m.user === "user" ? "icons/avatar.svg" : "icons/app_icon.svg",
+ senderUid: m.user?.toString() || '0',
+ senderName:
+ m.user === 'user'
+ ? 'You'
+ : m.user && m.user !== 'ai' && m.user !== 'assistant'
+ ? m.user
+ : 'Assistant',
+ senderAvatarUrl: m.avatar
+ ? m.avatar
+ : m.user === 'user'
+ ? 'icons/avatar.svg'
+ : 'icons/app_icon.svg',
text: content,
imageUrls: imageUrls,
createdAt: createdAt,
status: MessageStatus.Ready,
- };
-};
+ }
+}
diff --git a/web/app/_models/Conversation.ts b/web/app/_models/Conversation.ts
index bb972d4f4..58f02b406 100644
--- a/web/app/_models/Conversation.ts
+++ b/web/app/_models/Conversation.ts
@@ -1,20 +1,20 @@
export interface Conversation {
- _id?: string;
- modelId?: string;
- name?: string;
- image?: string;
- message?: string;
- lastMessage?: string;
- summary?: string;
- createdAt?: string;
- updatedAt?: string;
+ _id?: string
+ modelId?: string
+ name?: string
+ image?: string
+ message?: string
+ lastMessage?: string
+ summary?: string
+ createdAt?: string
+ updatedAt?: string
}
/**
* Store the state of conversation like fetching, waiting for response, etc.
*/
export type ConversationState = {
- hasMore: boolean;
- waitingForResponse: boolean;
- error?: Error;
-};
+ hasMore: boolean
+ waitingForResponse: boolean
+ error?: Error
+}
diff --git a/web/app/_models/DownloadState.ts b/web/app/_models/DownloadState.ts
index 64d7fb5c2..70a4fbd6d 100644
--- a/web/app/_models/DownloadState.ts
+++ b/web/app/_models/DownloadState.ts
@@ -2,21 +2,21 @@
* Represent the state of a download
*/
export type DownloadState = {
- modelId: string;
- time: DownloadTime;
- speed: number;
- percent: number;
- size: DownloadSize;
- fileName: string;
- error?: string;
-};
+ modelId: string
+ time: DownloadTime
+ speed: number
+ percent: number
+ size: DownloadSize
+ fileName: string
+ error?: string
+}
export type DownloadTime = {
- elapsed: number;
- remaining: number;
-};
+ elapsed: number
+ remaining: number
+}
export type DownloadSize = {
- total: number;
- transferred: number;
-};
+ total: number
+ transferred: number
+}
diff --git a/web/app/_models/ModelVersion.ts b/web/app/_models/ModelVersion.ts
index dc94887c6..e23b9ce2f 100644
--- a/web/app/_models/ModelVersion.ts
+++ b/web/app/_models/ModelVersion.ts
@@ -6,18 +6,18 @@ export type ModelVersion = {
* Combination of owner and model name.
* Being used as file name. Should be unique.
*/
- _id: string;
- name: string;
- quantMethod: string;
- bits: number;
- size: number;
- maxRamRequired: number;
- usecase: string;
- downloadLink: string;
- productId: string;
+ _id: string
+ name: string
+ quantMethod: string
+ bits: number
+ size: number
+ maxRamRequired: number
+ usecase: string
+ downloadLink: string
+ productId: string
/**
* For tracking download state
*/
- startDownloadAt?: number;
- finishDownloadAt?: number;
-};
+ startDownloadAt?: number
+ finishDownloadAt?: number
+}
diff --git a/web/app/_models/Product.ts b/web/app/_models/Product.ts
index c6601fe6e..c2bd6384a 100644
--- a/web/app/_models/Product.ts
+++ b/web/app/_models/Product.ts
@@ -1,31 +1,31 @@
-import { ModelVersion } from "./ModelVersion";
-import { ProductInput } from "./ProductInput";
-import { ProductOutput } from "./ProductOutput";
+import { ModelVersion } from './ModelVersion'
+import { ProductInput } from './ProductInput'
+import { ProductOutput } from './ProductOutput'
export enum ProductType {
- LLM = "LLM",
- GenerativeArt = "GenerativeArt",
- ControlNet = "ControlNet",
+ LLM = 'LLM',
+ GenerativeArt = 'GenerativeArt',
+ ControlNet = 'ControlNet',
}
export interface Product {
- _id: string;
- name: string;
- shortDescription: string;
- avatarUrl: string;
- longDescription: string;
- author: string;
- version: string;
- modelUrl: string;
- nsfw: boolean;
- greeting: string;
- type: ProductType;
- inputs?: ProductInput;
- outputs?: ProductOutput;
- createdAt: number;
- updatedAt?: number;
- status: string;
- releaseDate: number;
- tags: string[];
- availableVersions: ModelVersion[];
+ _id: string
+ name: string
+ shortDescription: string
+ avatarUrl: string
+ longDescription: string
+ author: string
+ version: string
+ modelUrl: string
+ nsfw: boolean
+ greeting: string
+ type: ProductType
+ inputs?: ProductInput
+ outputs?: ProductOutput
+ createdAt: number
+ updatedAt?: number
+ status: string
+ releaseDate: number
+ tags: string[]
+ availableVersions: ModelVersion[]
}
diff --git a/web/app/_models/ProductInput.ts b/web/app/_models/ProductInput.ts
index 343429b23..9873e88c2 100644
--- a/web/app/_models/ProductInput.ts
+++ b/web/app/_models/ProductInput.ts
@@ -1,23 +1,23 @@
export interface ProductInput {
- body: ItemProperties[];
- slug: string;
- headers: ProductHeader;
+ body: ItemProperties[]
+ slug: string
+ headers: ProductHeader
}
export type ProductHeader = {
- accept: string;
- contentType: string;
-};
+ accept: string
+ contentType: string
+}
export type ItemProperties = {
- name: string;
- type: string;
- items?: ProductBodyItem[];
- example?: unknown;
- description?: string;
-};
+ name: string
+ type: string
+ items?: ProductBodyItem[]
+ example?: unknown
+ description?: string
+}
export type ProductBodyItem = {
- type: string;
- properties: ItemProperties[];
-};
+ type: string
+ properties: ItemProperties[]
+}
diff --git a/web/app/_models/ProductOutput.ts b/web/app/_models/ProductOutput.ts
index 6042dcac6..b89b9722a 100644
--- a/web/app/_models/ProductOutput.ts
+++ b/web/app/_models/ProductOutput.ts
@@ -1,8 +1,8 @@
-import { ItemProperties } from "./ProductInput";
+import { ItemProperties } from './ProductInput'
export interface ProductOutput {
- slug: string;
- type: string;
- properties: ItemProperties[];
- description: string;
+ slug: string
+ type: string
+ properties: ItemProperties[]
+ description: string
}
diff --git a/web/app/_models/User.ts b/web/app/_models/User.ts
index b3d9583d5..81de924eb 100644
--- a/web/app/_models/User.ts
+++ b/web/app/_models/User.ts
@@ -1,18 +1,18 @@
export interface User {
- id: string;
- displayName: string;
- avatarUrl: string;
- email?: string;
+ id: string
+ displayName: string
+ avatarUrl: string
+ email?: string
}
export const DefaultUser = {
- id: "0",
- displayName: "Anonymous",
- avatarUrl: "icons/app_icon.svg",
- email: "",
-};
+ id: '0',
+ displayName: 'Anonymous',
+ avatarUrl: 'icons/app_icon.svg',
+ email: '',
+}
export enum Role {
- User = "user",
- Assistant = "assistant",
-}
\ No newline at end of file
+ User = 'user',
+ Assistant = 'assistant',
+}
diff --git a/web/app/_models/hf/SearchModelParam.hf.ts b/web/app/_models/hf/SearchModelParam.hf.ts
index 1ba9811f4..6944d31ab 100644
--- a/web/app/_models/hf/SearchModelParam.hf.ts
+++ b/web/app/_models/hf/SearchModelParam.hf.ts
@@ -1,53 +1,53 @@
export type SearchModelParamHf = {
search?: {
- owner?: string;
- task?: Task;
- };
+ owner?: string
+ task?: Task
+ }
credentials?: {
- accessToken: string;
- };
- limit: number;
-};
+ accessToken: string
+ }
+ limit: number
+}
export type Task =
- | "text-classification"
- | "token-classification"
- | "table-question-answering"
- | "question-answering"
- | "zero-shot-classification"
- | "translation"
- | "summarization"
- | "conversational"
- | "feature-extraction"
- | "text-generation"
- | "text2text-generation"
- | "fill-mask"
- | "sentence-similarity"
- | "text-to-speech"
- | "automatic-speech-recognition"
- | "audio-to-audio"
- | "audio-classification"
- | "voice-activity-detection"
- | "depth-estimation"
- | "image-classification"
- | "object-detection"
- | "image-segmentation"
- | "text-to-image"
- | "image-to-text"
- | "image-to-image"
- | "unconditional-image-generation"
- | "video-classification"
- | "reinforcement-learning"
- | "robotics"
- | "tabular-classification"
- | "tabular-regression"
- | "tabular-to-text"
- | "table-to-text"
- | "multiple-choice"
- | "text-retrieval"
- | "time-series-forecasting"
- | "visual-question-answering"
- | "document-question-answering"
- | "zero-shot-image-classification"
- | "graph-ml"
- | "other";
+ | 'text-classification'
+ | 'token-classification'
+ | 'table-question-answering'
+ | 'question-answering'
+ | 'zero-shot-classification'
+ | 'translation'
+ | 'summarization'
+ | 'conversational'
+ | 'feature-extraction'
+ | 'text-generation'
+ | 'text2text-generation'
+ | 'fill-mask'
+ | 'sentence-similarity'
+ | 'text-to-speech'
+ | 'automatic-speech-recognition'
+ | 'audio-to-audio'
+ | 'audio-classification'
+ | 'voice-activity-detection'
+ | 'depth-estimation'
+ | 'image-classification'
+ | 'object-detection'
+ | 'image-segmentation'
+ | 'text-to-image'
+ | 'image-to-text'
+ | 'image-to-image'
+ | 'unconditional-image-generation'
+ | 'video-classification'
+ | 'reinforcement-learning'
+ | 'robotics'
+ | 'tabular-classification'
+ | 'tabular-regression'
+ | 'tabular-to-text'
+ | 'table-to-text'
+ | 'multiple-choice'
+ | 'text-retrieval'
+ | 'time-series-forecasting'
+ | 'visual-question-answering'
+ | 'document-question-answering'
+ | 'zero-shot-image-classification'
+ | 'graph-ml'
+ | 'other'
diff --git a/web/app/_services/coreService.ts b/web/app/_services/coreService.ts
index c8bd328c4..8c0c5374f 100644
--- a/web/app/_services/coreService.ts
+++ b/web/app/_services/coreService.ts
@@ -1,21 +1,21 @@
-import { store } from "./storeService";
-import { EventEmitter } from "./eventsService";
+import { store } from './storeService'
+import { EventEmitter } from './eventsService'
export const setupCoreServices = () => {
- if (typeof window === "undefined") {
- console.log("undefine", window);
- return;
+ if (typeof window === 'undefined') {
+ console.log('undefine', window)
+ return
} else {
- console.log("Setting up core services");
+ console.log('Setting up core services')
}
if (!window.corePlugin) {
window.corePlugin = {
store,
events: new EventEmitter(),
- };
+ }
}
if (!window.coreAPI) {
// fallback electron API
- window.coreAPI = window.electronAPI;
+ window.coreAPI = window.electronAPI
}
-};
+}
diff --git a/web/app/_services/eventsService.ts b/web/app/_services/eventsService.ts
index cbdce426b..cea4966bd 100644
--- a/web/app/_services/eventsService.ts
+++ b/web/app/_services/eventsService.ts
@@ -1,40 +1,40 @@
export class EventEmitter {
- private handlers: Map;
+ private handlers: Map
constructor() {
- this.handlers = new Map();
+ this.handlers = new Map()
}
public on(eventName: string, handler: Function): void {
if (!this.handlers.has(eventName)) {
- this.handlers.set(eventName, []);
+ this.handlers.set(eventName, [])
}
- this.handlers.get(eventName)?.push(handler);
+ this.handlers.get(eventName)?.push(handler)
}
public off(eventName: string, handler: Function): void {
if (!this.handlers.has(eventName)) {
- return;
+ return
}
- const handlers = this.handlers.get(eventName);
- const index = handlers?.indexOf(handler);
+ const handlers = this.handlers.get(eventName)
+ const index = handlers?.indexOf(handler)
if (index !== undefined && index !== -1) {
- handlers?.splice(index, 1);
+ handlers?.splice(index, 1)
}
}
public emit(eventName: string, args: any): void {
if (!this.handlers.has(eventName)) {
- return;
+ return
}
- const handlers = this.handlers.get(eventName);
+ const handlers = this.handlers.get(eventName)
handlers?.forEach((handler) => {
- handler(args);
- });
+ handler(args)
+ })
}
}
diff --git a/web/app/_services/pluginService.ts b/web/app/_services/pluginService.ts
index cd45d0d30..31d325145 100644
--- a/web/app/_services/pluginService.ts
+++ b/web/app/_services/pluginService.ts
@@ -1,49 +1,60 @@
-"use client";
-import { extensionPoints, plugins } from "../../../electron/core/plugin-manager/execution/index";
-import { CoreService, DataService, InferenceService, ModelManagementService } from "@janhq/core";
+'use client'
+import {
+ extensionPoints,
+ plugins,
+} from '../../../electron/core/plugin-manager/execution/index'
+import {
+ CoreService,
+ DataService,
+ InferenceService,
+ ModelManagementService,
+} from '@janhq/core'
export const isCorePluginInstalled = () => {
if (!extensionPoints.get(DataService.GetConversations)) {
- return false;
+ return false
}
if (!extensionPoints.get(InferenceService.InitModel)) {
- return false;
+ return false
}
if (!extensionPoints.get(ModelManagementService.DownloadModel)) {
- return false;
+ return false
}
- return true;
-};
+ return true
+}
export const setupBasePlugins = async () => {
- if (typeof window === "undefined" || typeof window.electronAPI === "undefined") {
- return;
+ if (
+ typeof window === 'undefined' ||
+ typeof window.electronAPI === 'undefined'
+ ) {
+ return
}
- const basePlugins = await window.electronAPI.basePlugins();
+ const basePlugins = await window.electronAPI.basePlugins()
if (
!extensionPoints.get(DataService.GetConversations) ||
!extensionPoints.get(InferenceService.InitModel) ||
!extensionPoints.get(ModelManagementService.DownloadModel)
) {
- const installed = await plugins.install(basePlugins);
+ const installed = await plugins.install(basePlugins)
if (installed) {
- window.location.reload();
+ window.location.reload()
}
}
-};
+}
export const execute = (name: CoreService, args?: any) => {
if (!extensionPoints.get(name)) {
- alert("Missing extension for function: " + name);
- return undefined;
+ alert('Missing extension for function: ' + name)
+ return undefined
}
- return extensionPoints.execute(name, args);
-};
+ return extensionPoints.execute(name, args)
+}
export const executeSerial = (name: CoreService, args?: any) => {
if (!extensionPoints.get(name)) {
- alert("Missing extension for function: " + name);
- return Promise.resolve(undefined);
+ alert('Missing extension for function: ' + name)
+ return Promise.resolve(undefined)
}
- return extensionPoints.executeSerial(name, args);
-};
+ return extensionPoints.executeSerial(name, args)
+}
diff --git a/web/app/_services/storeService.ts b/web/app/_services/storeService.ts
index fb5a233e4..c70c3177f 100644
--- a/web/app/_services/storeService.ts
+++ b/web/app/_services/storeService.ts
@@ -1,5 +1,5 @@
-import { StoreService } from "@janhq/core";
-import { executeSerial } from "./pluginService";
+import { StoreService } from '@janhq/core'
+import { executeSerial } from './pluginService'
/**
* Create a collection on data store
@@ -9,8 +9,11 @@ import { executeSerial } from "./pluginService";
* @returns {Promise}
*
*/
-function createCollection(name: string, schema?: { [key: string]: any }): Promise {
- return executeSerial(StoreService.CreateCollection, { name, schema });
+function createCollection(
+ name: string,
+ schema?: { [key: string]: any }
+): Promise {
+ return executeSerial(StoreService.CreateCollection, { name, schema })
}
/**
@@ -21,7 +24,7 @@ function createCollection(name: string, schema?: { [key: string]: any }): Promis
*
*/
function deleteCollection(name: string): Promise {
- return executeSerial(StoreService.DeleteCollection, name);
+ return executeSerial(StoreService.DeleteCollection, name)
}
/**
@@ -36,7 +39,7 @@ function insertOne(collectionName: string, value: any): Promise {
return executeSerial(StoreService.InsertOne, {
collectionName,
value,
- });
+ })
}
/**
@@ -46,7 +49,7 @@ function insertOne(collectionName: string, value: any): Promise {
* @returns {Promise} A promise that resolves when the record is retrieved.
*/
function findOne(collectionName: string, key: string): Promise {
- return executeSerial(StoreService.FindOne, { collectionName, key });
+ return executeSerial(StoreService.FindOne, { collectionName, key })
}
/**
@@ -65,7 +68,7 @@ function findMany(
collectionName,
selector,
sort,
- });
+ })
}
/**
@@ -77,12 +80,16 @@ function findMany(
* @returns Promise