Merge branch 'main' into fix508

This commit is contained in:
0xSage 2023-11-28 15:04:05 +08:00 committed by GitHub
commit 64daa31aa6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 149 additions and 136 deletions

View File

@ -1 +1 @@
0.1.11 0.1.17

View File

@ -25,6 +25,7 @@ let currentModelFile = null;
*/ */
interface InitModelResponse { interface InitModelResponse {
error?: any; error?: any;
modelFile?: string;
} }
/** /**
@ -51,7 +52,7 @@ function initModel(modelFile: string): Promise<InitModelResponse> {
.then(validateModelStatus) .then(validateModelStatus)
.catch((err) => { .catch((err) => {
log.error("error: " + JSON.stringify(err)); log.error("error: " + JSON.stringify(err));
return { error: err }; return { error: err, modelFile };
}) })
); );
} }

View File

@ -20,15 +20,12 @@ import { twMerge } from 'tailwind-merge'
import LogoMark from '@/containers/Brand/Logo/Mark' import LogoMark from '@/containers/Brand/Logo/Mark'
import { FeatureToggleContext } from '@/context/FeatureToggle'
import { MainViewState } from '@/constants/screens' import { MainViewState } from '@/constants/screens'
import { useMainViewState } from '@/hooks/useMainViewState' import { useMainViewState } from '@/hooks/useMainViewState'
export default function RibbonNav() { export default function RibbonNav() {
const { mainViewState, setMainViewState } = useMainViewState() const { mainViewState, setMainViewState } = useMainViewState()
const { experimentalFeatureEnabed } = useContext(FeatureToggleContext)
const onMenuClick = (state: MainViewState) => { const onMenuClick = (state: MainViewState) => {
if (mainViewState === state) return if (mainViewState === state) return
@ -49,8 +46,6 @@ export default function RibbonNav() {
] ]
const secondaryMenus = [ const secondaryMenus = [
// Add menu if experimental feature
...(experimentalFeatureEnabed ? [] : []),
{ {
name: 'Explore Models', name: 'Explore Models',
icon: <CpuIcon size={20} className="flex-shrink-0" />, icon: <CpuIcon size={20} className="flex-shrink-0" />,

View File

@ -28,7 +28,6 @@ import { MainViewState } from '@/constants/screens'
import { useMainViewState } from '@/hooks/useMainViewState' import { useMainViewState } from '@/hooks/useMainViewState'
export default function CommandSearch() { export default function CommandSearch() {
const { experimentalFeatureEnabed } = useContext(FeatureToggleContext)
const { setMainViewState } = useMainViewState() const { setMainViewState } = useMainViewState()
const menus = [ const menus = [
@ -44,8 +43,6 @@ export default function CommandSearch() {
), ),
state: MainViewState.Chat, state: MainViewState.Chat,
}, },
// Added experimental feature here
...(experimentalFeatureEnabed ? [] : []),
{ {
name: 'Explore Models', name: 'Explore Models',
icon: <CpuIcon size={16} className="mr-3 text-muted-foreground" />, icon: <CpuIcon size={16} className="mr-3 text-muted-foreground" />,

View File

@ -31,6 +31,8 @@ export function useActiveModel() {
return return
} }
setActiveModel(undefined)
setStateModel({ state: 'start', loading: true, model: modelId }) setStateModel({ state: 'start', loading: true, model: modelId })
const model = downloadedModels.find((e) => e.id === modelId) const model = downloadedModels.find((e) => e.id === modelId)
@ -52,7 +54,7 @@ export function useActiveModel() {
console.debug('Init model: ', modelId) console.debug('Init model: ', modelId)
const path = join('models', model.name, modelId) const path = join('models', model.name, modelId)
const res = await initModel(path) const res = await initModel(path)
if (res?.error && (!activeModel?.id || modelId === activeModel?.id)) { if (res && res.error && res.modelFile === stateModel.model) {
const errorMessage = `${res.error}` const errorMessage = `${res.error}`
alert(errorMessage) alert(errorMessage)
setStateModel(() => ({ setStateModel(() => ({
@ -60,7 +62,6 @@ export function useActiveModel() {
loading: false, loading: false,
model: modelId, model: modelId,
})) }))
setActiveModel(undefined)
} else { } else {
console.debug( console.debug(
`Init model ${modelId} successfully!, take ${ `Init model ${modelId} successfully!, take ${

View File

@ -59,6 +59,7 @@ export default function useSendChatMessage() {
...newMessage, ...newMessage,
messages: newMessage.messages?.slice(0, -1).concat([summaryMsg]), messages: newMessage.messages?.slice(0, -1).concat([summaryMsg]),
}) })
.catch(console.error)
if ( if (
currentConvo && currentConvo &&
currentConvo.id === newMessage.threadId && currentConvo.id === newMessage.threadId &&

View File

@ -1,9 +1,5 @@
import { useContext } from 'react'
import { useAtomValue } from 'jotai' import { useAtomValue } from 'jotai'
import { FeatureToggleContext } from '@/context/FeatureToggle'
import ChatInstruction from '../ChatInstruction' import ChatInstruction from '../ChatInstruction'
import ChatItem from '../ChatItem' import ChatItem from '../ChatItem'
@ -11,15 +7,12 @@ import { getCurrentChatMessagesAtom } from '@/helpers/atoms/ChatMessage.atom'
const ChatBody: React.FC = () => { const ChatBody: React.FC = () => {
const messages = useAtomValue(getCurrentChatMessagesAtom) const messages = useAtomValue(getCurrentChatMessagesAtom)
const { experimentalFeatureEnabed } = useContext(FeatureToggleContext)
return ( return (
<div className="flex h-full w-full flex-col-reverse overflow-y-auto"> <div className="flex h-full w-full flex-col-reverse overflow-y-auto">
{messages.map((message) => ( {messages.map((message) => (
<ChatItem {...message} key={message.id} /> <ChatItem {...message} key={message.id} />
))} ))}
{experimentalFeatureEnabed && messages.length === 0 && ( {messages.length === 0 && <ChatInstruction />}
<ChatInstruction />
)}
</div> </div>
) )
} }

View File

@ -35,7 +35,8 @@ const ChatInstruction = () => {
What does this Assistant do? How does it behave? What should it avoid What does this Assistant do? How does it behave? What should it avoid
doing? doing?
</p> </p>
{!isSettingInstruction && ( {!isSettingInstruction && activeConvoId && (
<>
<Button <Button
themes={'outline'} themes={'outline'}
className="w-32" className="w-32"
@ -43,6 +44,7 @@ const ChatInstruction = () => {
> >
Give Instruction Give Instruction
</Button> </Button>
</>
)} )}
{isSettingInstruction && ( {isSettingInstruction && (
<div className="space-y-4"> <div className="space-y-4">

View File

@ -7,7 +7,10 @@ import SimpleTextMessage from '../SimpleTextMessage'
type Ref = HTMLDivElement type Ref = HTMLDivElement
const ChatItem = forwardRef<Ref, ThreadMessage>((message, ref) => ( const ChatItem = forwardRef<Ref, ThreadMessage>((message, ref) => (
<div ref={ref} className="py-4 even:bg-secondary dark:even:bg-secondary/20"> <div
ref={ref}
className="relative py-4 first:pb-14 even:bg-secondary dark:even:bg-secondary/20"
>
<SimpleTextMessage {...message} /> <SimpleTextMessage {...message} />
</div> </div>
)) ))

View File

@ -11,7 +11,6 @@ import { twMerge } from 'tailwind-merge'
import { useActiveModel } from '@/hooks/useActiveModel' import { useActiveModel } from '@/hooks/useActiveModel'
import { useCreateConversation } from '@/hooks/useCreateConversation' import { useCreateConversation } from '@/hooks/useCreateConversation'
import { useGetDownloadedModels } from '@/hooks/useGetDownloadedModels'
import useGetUserConversations from '@/hooks/useGetUserConversations' import useGetUserConversations from '@/hooks/useGetUserConversations'
import { displayDate } from '@/utils/datetime' import { displayDate } from '@/utils/datetime'
@ -27,11 +26,10 @@ export default function HistoryList() {
const conversations = useAtomValue(userConversationsAtom) const conversations = useAtomValue(userConversationsAtom)
const threadStates = useAtomValue(conversationStatesAtom) const threadStates = useAtomValue(conversationStatesAtom)
const { getUserConversations } = useGetUserConversations() const { getUserConversations } = useGetUserConversations()
const { activeModel, startModel } = useActiveModel() const { activeModel } = useActiveModel()
const { requestCreateConvo } = useCreateConversation() const { requestCreateConvo } = useCreateConversation()
const activeConvoId = useAtomValue(getActiveConvoIdAtom) const activeConvoId = useAtomValue(getActiveConvoIdAtom)
const setActiveConvoId = useSetAtom(setActiveConvoIdAtom) const setActiveConvoId = useSetAtom(setActiveConvoIdAtom)
const { downloadedModels } = useGetDownloadedModels()
useEffect(() => { useEffect(() => {
getUserConversations() getUserConversations()
@ -48,14 +46,6 @@ export default function HistoryList() {
console.debug('modelId is undefined') console.debug('modelId is undefined')
return return
} }
const model = downloadedModels.find((e) => e.id === convo.modelId)
if (convo == null) {
console.debug('modelId is undefined')
return
}
if (model != null) {
startModel(model.id)
}
if (activeConvoId !== convo.id) { if (activeConvoId !== convo.id) {
setActiveConvoId(convo.id) setActiveConvoId(convo.id)
} }

View File

@ -35,18 +35,19 @@ const MessageToolbar = ({ message }: { message: ThreadMessage }) => {
} }
return ( return (
<div className="flex flex-row items-center"> <div className="flex flex-row items-center">
<div className="flex overflow-hidden rounded-md border border-border bg-background/20">
{message.status === MessageStatus.Pending && ( {message.status === MessageStatus.Pending && (
<StopCircle <div
className="mx-1 cursor-pointer rounded-sm bg-gray-800 px-[3px]" className="cursor-pointer border-r border-border px-2 py-2 hover:bg-background/80"
size={20}
onClick={() => stopInference()} onClick={() => stopInference()}
/> >
<StopCircle size={14} />
</div>
)} )}
{message.status !== MessageStatus.Pending && {message.status !== MessageStatus.Pending &&
message.id === messages[0]?.id && ( message.id === messages[0]?.id && (
<RefreshCcw <div
className="mx-1 cursor-pointer rounded-sm bg-gray-800 px-[3px]" className="cursor-pointer border-r border-border px-2 py-2 hover:bg-background/80"
size={20}
onClick={() => { onClick={() => {
const messageRequest: MessageRequest = { const messageRequest: MessageRequest = {
id: message.id ?? '', id: message.id ?? '',
@ -66,21 +67,23 @@ const MessageToolbar = ({ message }: { message: ThreadMessage }) => {
} }
events.emit(EventName.OnNewMessageRequest, messageRequest) events.emit(EventName.OnNewMessageRequest, messageRequest)
}} }}
/> >
<RefreshCcw size={14} />
</div>
)} )}
<ClipboardCopy <div
className="mx-1 cursor-pointer rounded-sm bg-gray-800 px-[3px]" className="cursor-pointer border-r border-border px-2 py-2 hover:bg-background/80"
size={20}
onClick={() => { onClick={() => {
navigator.clipboard.writeText(message.content ?? '') navigator.clipboard.writeText(message.content ?? '')
toaster({ toaster({
title: 'Copied to clipboard', title: 'Copied to clipboard',
}) })
}} }}
/> >
<Trash2Icon <ClipboardCopy size={14} />
className="mx-1 cursor-pointer rounded-sm bg-gray-800 px-[3px]" </div>
size={20} <div
className="cursor-pointer px-2 py-2 hover:bg-background/80"
onClick={async () => { onClick={async () => {
deleteAMessage(message.id ?? '') deleteAMessage(message.id ?? '')
if (thread) if (thread)
@ -91,7 +94,10 @@ const MessageToolbar = ({ message }: { message: ThreadMessage }) => {
messages: messages.filter((e) => e.id !== message.id), messages: messages.filter((e) => e.id !== message.id),
}) })
}} }}
/> >
<Trash2Icon size={14} />
</div>
</div>
</div> </div>
) )
} }

View File

@ -5,6 +5,7 @@ import { ChatCompletionRole, MessageStatus, ThreadMessage } from '@janhq/core'
import hljs from 'highlight.js' import hljs from 'highlight.js'
import { useAtomValue } from 'jotai'
import { Marked } from 'marked' import { Marked } from 'marked'
import { markedHighlight } from 'marked-highlight' import { markedHighlight } from 'marked-highlight'
@ -21,6 +22,8 @@ import { displayDate } from '@/utils/datetime'
import MessageToolbar from '../MessageToolbar' import MessageToolbar from '../MessageToolbar'
import { getCurrentChatMessagesAtom } from '@/helpers/atoms/ChatMessage.atom'
const marked = new Marked( const marked = new Marked(
markedHighlight({ markedHighlight({
langPrefix: 'hljs', langPrefix: 'hljs',
@ -47,7 +50,6 @@ const marked = new Marked(
) )
const SimpleTextMessage: React.FC<ThreadMessage> = (props) => { const SimpleTextMessage: React.FC<ThreadMessage> = (props) => {
const { experimentalFeatureEnabed } = useContext(FeatureToggleContext)
const parsedText = marked.parse(props.content ?? '') const parsedText = marked.parse(props.content ?? '')
const isUser = props.role === ChatCompletionRole.User const isUser = props.role === ChatCompletionRole.User
const isSystem = props.role === ChatCompletionRole.System const isSystem = props.role === ChatCompletionRole.System
@ -55,9 +57,10 @@ const SimpleTextMessage: React.FC<ThreadMessage> = (props) => {
const [lastTimestamp, setLastTimestamp] = useState<number | undefined>() const [lastTimestamp, setLastTimestamp] = useState<number | undefined>()
const [tokenSpeed, setTokenSpeed] = useState(0) const [tokenSpeed, setTokenSpeed] = useState(0)
const messages = useAtomValue(getCurrentChatMessagesAtom)
useEffect(() => { useEffect(() => {
if (props.status === MessageStatus.Ready || !experimentalFeatureEnabed) { if (props.status === MessageStatus.Ready) {
return return
} }
const currentTimestamp = new Date().getTime() // Get current time in milliseconds const currentTimestamp = new Date().getTime() // Get current time in milliseconds
@ -73,25 +76,30 @@ const SimpleTextMessage: React.FC<ThreadMessage> = (props) => {
setTokenSpeed(averageTokenSpeed) setTokenSpeed(averageTokenSpeed)
setTokenCount(totalTokenCount) setTokenCount(totalTokenCount)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.content]) }, [props.content])
return ( return (
<div className="group mx-auto rounded-xl px-4 lg:w-3/4"> <div className="group relative mx-auto rounded-xl px-4 lg:w-3/4">
<div <div
className={twMerge( className={twMerge(
'mb-1 flex items-center justify-start gap-2', 'mb-2 flex items-center justify-start gap-x-2',
!isUser && 'mt-2' !isUser && 'mt-2'
)} )}
> >
{!isUser && !isSystem && <LogoMark width={20} />} {!isUser && !isSystem && <LogoMark width={20} />}
<div className="text-sm font-extrabold capitalize">{props.role}</div> <div className="text-sm font-extrabold capitalize">{props.role}</div>
<p className="text-xs font-medium">{displayDate(props.createdAt)}</p> <p className="text-xs font-medium">{displayDate(props.createdAt)}</p>
<div
{experimentalFeatureEnabed && ( className={twMerge(
<div className="hidden cursor-pointer group-hover:flex"> 'absolute right-0 cursor-pointer transition-all',
messages[0].id === props.id
? 'absolute -bottom-10 left-4'
: 'hidden group-hover:flex'
)}
>
<MessageToolbar message={props} /> <MessageToolbar message={props} />
</div> </div>
)}
</div> </div>
<div className={twMerge('w-full')}> <div className={twMerge('w-full')}>
@ -111,9 +119,8 @@ const SimpleTextMessage: React.FC<ThreadMessage> = (props) => {
</> </>
)} )}
</div> </div>
{experimentalFeatureEnabed && {(props.status === MessageStatus.Pending || tokenSpeed > 0) && (
(props.status === MessageStatus.Pending || tokenSpeed > 0) && ( <p className="mt-2 text-xs font-medium text-foreground">
<p className="mt-1 text-xs font-medium text-white">
Token Speed: {Number(tokenSpeed).toFixed(2)}/s Token Speed: {Number(tokenSpeed).toFixed(2)}/s
</p> </p>
)} )}

View File

@ -10,9 +10,12 @@ import { twMerge } from 'tailwind-merge'
import { currentPromptAtom } from '@/containers/Providers/Jotai' import { currentPromptAtom } from '@/containers/Providers/Jotai'
import { FeatureToggleContext } from '@/context/FeatureToggle'
import ShortCut from '@/containers/Shortcut' import ShortCut from '@/containers/Shortcut'
import { toaster } from '@/containers/Toast'
import { FeatureToggleContext } from '@/context/FeatureToggle'
import { MainViewState } from '@/constants/screens' import { MainViewState } from '@/constants/screens'
import { useActiveModel } from '@/hooks/useActiveModel' import { useActiveModel } from '@/hooks/useActiveModel'
@ -61,9 +64,13 @@ const ChatScreen = () => {
const [isModelAvailable, setIsModelAvailable] = useState( const [isModelAvailable, setIsModelAvailable] = useState(
downloadedModels.some((x) => x.id === currentConvo?.modelId) downloadedModels.some((x) => x.id === currentConvo?.modelId)
) )
const { experimentalFeatureEnabed } = useContext(FeatureToggleContext)
const textareaRef = useRef<HTMLTextAreaElement>(null) const textareaRef = useRef<HTMLTextAreaElement>(null)
const { startModel } = useActiveModel()
const modelRef = useRef(activeModel)
useEffect(() => {
modelRef.current = activeModel
}, [activeModel])
useEffect(() => { useEffect(() => {
getUserConversations() getUserConversations()
@ -81,6 +88,24 @@ const ChatScreen = () => {
}, [currentConvo, downloadedModels]) }, [currentConvo, downloadedModels])
const handleSendMessage = async () => { const handleSendMessage = async () => {
if (!activeModel || activeModel.id !== currentConvo?.modelId) {
const model = downloadedModels.find((e) => e.id === currentConvo?.modelId)
// Model is available to start
if (model != null) {
toaster({
title: 'Message queued.',
description: 'It will be sent once the model is done loading.',
})
startModel(model.id).then(() => {
setTimeout(() => {
if (modelRef?.current?.id === currentConvo?.modelId)
sendChatMessage()
}, 300)
})
}
return
}
if (activeConversationId) { if (activeConversationId) {
sendChatMessage() sendChatMessage()
} else { } else {
@ -149,20 +174,16 @@ const ChatScreen = () => {
Download Model Download Model
</Button> </Button>
)} )}
{experimentalFeatureEnabed && (
<Paintbrush <Paintbrush
size={16} size={16}
className="cursor-pointer text-muted-foreground" className="cursor-pointer text-muted-foreground"
onClick={() => cleanConvo()} onClick={() => cleanConvo()}
/> />
)}
{
<Trash2Icon <Trash2Icon
size={16} size={16}
className="cursor-pointer text-muted-foreground" className="cursor-pointer text-muted-foreground"
onClick={() => deleteConvo()} onClick={() => deleteConvo()}
/> />
}
</div> </div>
</div> </div>
</div> </div>
@ -206,11 +227,7 @@ const ChatScreen = () => {
ref={textareaRef} ref={textareaRef}
onKeyDown={(e) => handleKeyDown(e)} onKeyDown={(e) => handleKeyDown(e)}
placeholder="Type your message ..." placeholder="Type your message ..."
disabled={ disabled={stateModel.loading || !currentConvo}
!activeModel ||
stateModel.loading ||
activeModel.id !== currentConvo?.modelId
}
value={currentPrompt} value={currentPrompt}
onChange={(e) => { onChange={(e) => {
handleMessageChange(e) handleMessageChange(e)
@ -218,8 +235,8 @@ const ChatScreen = () => {
/> />
<Button <Button
size="lg" size="lg"
disabled={!activeModel || disabled || stateModel.loading} disabled={disabled || stateModel.loading || !currentConvo}
themes={!activeModel ? 'secondary' : 'primary'} themes={'primary'}
onClick={handleSendMessage} onClick={handleSendMessage}
> >
Send Send