Skip to content

Commit

Permalink
fix: refresh should not create new thread
Browse files Browse the repository at this point in the history
  • Loading branch information
namchuai committed Aug 8, 2024
1 parent b43242b commit c766f0f
Show file tree
Hide file tree
Showing 16 changed files with 240 additions and 119 deletions.
3 changes: 1 addition & 2 deletions joi/src/core/TextArea/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import React, { ReactNode, forwardRef } from 'react'
import React, { forwardRef } from 'react'
import { twMerge } from 'tailwind-merge'

import './styles.scss'
import { ScrollArea } from '../ScrollArea'

export interface TextAreaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
Expand Down
49 changes: 39 additions & 10 deletions web/containers/Providers/DataLoader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,27 @@

import { useEffect } from 'react'

import { useAtomValue } from 'jotai'

import useAssistantCreate, { janAssistant } from '@/hooks/useAssistantCreate'
import useAssistantQuery from '@/hooks/useAssistantQuery'
import useEngineQuery from '@/hooks/useEngineQuery'
import { useLoadTheme } from '@/hooks/useLoadTheme'
import useModelHub from '@/hooks/useModelHub'
import useModels from '@/hooks/useModels'
import useThreads from '@/hooks/useThreads'
import useModelQuery from '@/hooks/useModelQuery'
import useThreadCreateMutation from '@/hooks/useThreadCreateMutation'
import useThreadQuery from '@/hooks/useThreadQuery'

import { getSelectedModelAtom } from '@/helpers/atoms/Model.atom'
import { threadsAtom } from '@/helpers/atoms/Thread.atom'

const DataLoader: React.FC = () => {
const { getThreadList } = useThreads()
const { getModels } = useModels()
const selectedModel = useAtomValue(getSelectedModelAtom)
const allThreads = useAtomValue(threadsAtom)
const { data: assistants } = useAssistantQuery()
const { data: models } = useModelQuery()
const { data: threads, isLoading: isFetchingThread } = useThreadQuery()
const createThreadMutation = useThreadCreateMutation()
const assistantCreateMutation = useAssistantCreate()

useEffect(() => {
Expand All @@ -25,16 +34,36 @@ const DataLoader: React.FC = () => {
}
}, [assistants, assistantCreateMutation])

// automatically create new thread if thread list is empty
useEffect(() => {
if (isFetchingThread) return
if (allThreads.length > 0) return
if (!assistants || assistants.length === 0) return
if (!models || models.length === 0) return
if (allThreads.length === 0 && !createThreadMutation.isPending) {
const model = selectedModel ?? models[0]
const assistant = assistants[0]

console.log('Create new thread because user have no thread')
createThreadMutation.mutate({
modelId: model.id,
assistant: assistant,
})
}
}, [
assistants,
models,
isFetchingThread,
threads,
createThreadMutation,
allThreads,
selectedModel,
])

useModelHub()
useLoadTheme()
useEngineQuery()

useEffect(() => {
getThreadList()
getModels()
}, [getThreadList, getModels])

console.debug('Load Data...')
return null
}

Expand Down
2 changes: 1 addition & 1 deletion web/containers/Providers/KeyListener.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { useAtomValue, useSetAtom } from 'jotai'
import useAssistantQuery from '@/hooks/useAssistantQuery'
import useThreads from '@/hooks/useThreads'

import { copyOverInstructionEnabledAtom } from '@/screens/Settings/Advanced/components/CopyOverInstruction'
import { copyOverInstructionEnabledAtom } from '@/screens/Thread/ThreadRightPanel/AssistantSettingContainer/components/CopyOverInstruction'

import { toaster } from '../Toast'

Expand Down
19 changes: 8 additions & 11 deletions web/helpers/atoms/Thread.atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,14 @@ export const isGeneratingResponseAtom = atom<boolean>(false)
*/
export const threadsAtom = atom<Thread[]>([])

export const deleteThreadAtom = atom(null, (_get, set, threadId: string) => {
set(threadsAtom, (threads) => {
// set active thread to the latest
const allThreads = threads.filter((c) => c.id !== threadId)
if (allThreads.length > 0) {
const latestThread = allThreads[0]
set(activeThreadIdAtom, latestThread.id)
}

return allThreads
})
export const deleteThreadAtom = atom(null, (get, set, threadId: string) => {
const allThreads = get(threadsAtom)
const filteredThreads = allThreads.filter((t) => t.id !== threadId)
if (filteredThreads.length > 0) {
const latestThread = allThreads[0]
set(activeThreadIdAtom, latestThread.id)
}
set(threadsAtom, filteredThreads)
})

export const activeThreadAtom = atom<Thread | undefined>((get) =>
Expand Down
26 changes: 26 additions & 0 deletions web/hooks/useModelQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useQuery } from '@tanstack/react-query'

import { useSetAtom } from 'jotai'

import useCortex from './useCortex'

import { downloadedModelsAtom } from '@/helpers/atoms/Model.atom'

export const modelQueryKey = ['getModels']

const useModelQuery = () => {
const { fetchModels } = useCortex()
const setDownloadedModels = useSetAtom(downloadedModelsAtom)

return useQuery({
queryKey: modelQueryKey,
queryFn: async () => {
const models = await fetchModels()
setDownloadedModels(models)
return models
},
staleTime: 30 * 1000,
})
}

export default useModelQuery
58 changes: 58 additions & 0 deletions web/hooks/useThreadCreateMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { Assistant } from '@janhq/core'
import { useMutation } from '@tanstack/react-query'

import { useSetAtom } from 'jotai'

import { toaster } from '@/containers/Toast'

import useCortex from './useCortex'

import { setThreadMessagesAtom } from '@/helpers/atoms/ChatMessage.atom'
import { setActiveThreadIdAtom, threadsAtom } from '@/helpers/atoms/Thread.atom'

export type ThreadCreateMutationVariables = {
modelId: string
assistant: Assistant
instructions?: string
}

const useThreadCreateMutation = () => {
const { createThread } = useCortex()
const setThreads = useSetAtom(threadsAtom)
const setActiveThreadId = useSetAtom(setActiveThreadIdAtom)
const setThreadMessage = useSetAtom(setThreadMessagesAtom)

return useMutation({
mutationFn: async (variables: ThreadCreateMutationVariables) => {
const { assistant, modelId, instructions } = variables
if (instructions) {
assistant.instructions = instructions
}

return createThread({
...assistant,
model: modelId,
})
},

onSuccess: (thread, variables, context) => {
console.log('New thread created', thread, variables, context)
setThreads((threads) => [thread, ...threads])
setActiveThreadId(thread.id)
setThreadMessage(thread.id, [])
},

onError: (error, variables) => {
console.error(
`Failed to create new thread: ${JSON.stringify(variables)}, error: ${error}`
)
toaster({
title: 'Failed to create thread',
description: `Unexpected error while creating thread. Please try again!`,
type: 'error',
})
},
})
}

export default useThreadCreateMutation
26 changes: 26 additions & 0 deletions web/hooks/useThreadQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useQuery } from '@tanstack/react-query'

import { useSetAtom } from 'jotai'

import useCortex from './useCortex'

import { threadsAtom } from '@/helpers/atoms/Thread.atom'

export const threadQueryKey = ['getThreads']

const useThreadQuery = () => {
const { fetchThreads } = useCortex()
const setThreads = useSetAtom(threadsAtom)

return useQuery({
queryKey: threadQueryKey,
queryFn: async () => {
const threads = await fetchThreads()
setThreads(threads)
return threads
},
staleTime: 30 * 1000,
})
}

export default useThreadQuery
7 changes: 0 additions & 7 deletions web/hooks/useThreads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,12 @@ const useThreads = () => {
const deleteThreadState = useSetAtom(deleteThreadAtom)
const cleanMessages = useSetAtom(cleanChatMessageAtom)
const {
fetchThreads,
createThread,
fetchMessages,
deleteThread: deleteCortexThread,
cleanThread: cleanCortexThread,
} = useCortex()

const getThreadList = useCallback(async () => {
const threads = await fetchThreads()
setThreads(threads)
}, [setThreads, fetchThreads])

const setActiveThread = useCallback(
async (threadId: string) => {
const messages = await fetchMessages(threadId)
Expand Down Expand Up @@ -85,7 +79,6 @@ const useThreads = () => {
)

return {
getThreadList,
createThread: createNewThread,
setActiveThread,
deleteThread,
Expand Down
16 changes: 10 additions & 6 deletions web/screens/HubScreen2/components/SliderItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import useAssistantQuery from '@/hooks/useAssistantQuery'
import { downloadStateListAtom } from '@/hooks/useDownloadState'
import useModelDownloadMutation from '@/hooks/useModelDownloadMutation'
import { QuickStartModel } from '@/hooks/useModelHub'
import useThreads from '@/hooks/useThreads'

import useThreadCreateMutation from '@/hooks/useThreadCreateMutation'

import { formatDownloadPercentage, toGibibytes } from '@/utils/converter'
import { downloadProgress } from '@/utils/download'
Expand Down Expand Up @@ -75,8 +76,8 @@ const DownloadContainer: React.FC<DownloadContainerProps> = ({
fileName,
}) => {
const downloadModelMutation = useModelDownloadMutation()
const createThreadMutation = useThreadCreateMutation()
const setMainViewState = useSetAtom(mainViewStateAtom)
const { createThread } = useThreads()
const { data: assistants } = useAssistantQuery()

const { abortDownload } = useAbortDownload()
Expand Down Expand Up @@ -116,16 +117,19 @@ const DownloadContainer: React.FC<DownloadContainerProps> = ({
return
}

await createThread(persistModelId, {
...assistants[0],
model: persistModelId,
await createThreadMutation.mutateAsync({
modelId: persistModelId,
assistant: {
...assistants[0],
model: persistModelId,
},
})
setDownloadLocalModelModalStage('NONE', undefined)
setMainViewState(MainViewState.Thread)
}, [
setDownloadLocalModelModalStage,
setMainViewState,
createThread,
createThreadMutation,
persistModelId,
assistants,
])
Expand Down
41 changes: 0 additions & 41 deletions web/screens/Settings/Advanced/components/CopyOverInstruction.tsx

This file was deleted.

2 changes: 0 additions & 2 deletions web/screens/Settings/Advanced/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import useModelStop from '@/hooks/useModelStop'
import { useSettings } from '@/hooks/useSettings'

import DataFolder from './DataFolder'
import CopyOverInstructionItem from './components/CopyOverInstruction'

import DataMigration from './components/DataMigration'

Expand Down Expand Up @@ -459,7 +458,6 @@ const Advanced = () => {

{/* Factory Reset */}
{/* <FactoryReset /> */}
{experimentalEnabled && <CopyOverInstructionItem />}
{experimentalEnabled && <DataMigration />}
</div>
</ScrollArea>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ const ChatTextInput: React.FC<Props> = ({

const isGeneratingResponse = useAtomValue(isGeneratingResponseAtom)

const disabled = useMemo(() => {
return !activeThreadId
}, [activeThreadId])
const disabled = useMemo(() => !activeThreadId, [activeThreadId])

const onChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
Expand All @@ -44,10 +42,8 @@ const ChatTextInput: React.FC<Props> = ({
)

useEffect(() => {
if (textareaRef.current) {
textareaRef.current.focus()
}
}, [activeThreadId])
textareaRef.current?.focus()
})

useEffect(() => {
if (textareaRef.current?.clientHeight) {
Expand Down
Loading

0 comments on commit c766f0f

Please sign in to comment.