Feat: web temporary chat (#6650)
* temporray chat stage1 * temporary page in root * temporary chat * handle redirection properly ` * temporary chat header * Update extensions-web/src/conversational-web/extension.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * update routetree * better error handling * fix strecthed assitant on desktop * update yarn link to workspace for better link consistency --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
parent
ccf378f2c6
commit
2101242530
@ -11,6 +11,9 @@ import {
|
||||
} from '@janhq/core'
|
||||
import { RemoteApi } from './api'
|
||||
import { getDefaultAssistant, ObjectParser, combineConversationItemsToMessages } from './utils'
|
||||
import { ApiError } from '../shared/types/errors'
|
||||
|
||||
const CONVERSATION_NOT_FOUND_EVENT = 'conversation-not-found'
|
||||
|
||||
export default class ConversationalExtensionWeb extends ConversationalExtension {
|
||||
private remoteApi: RemoteApi | undefined
|
||||
@ -111,6 +114,15 @@ export default class ConversationalExtensionWeb extends ConversationalExtension
|
||||
return messages
|
||||
} catch (error) {
|
||||
console.error('Failed to list messages:', error)
|
||||
// Check if it's a 404 error (conversation not found)
|
||||
if (error instanceof ApiError && error.isNotFound()) {
|
||||
// Trigger a navigation event to redirect to home
|
||||
// We'll use a custom event that the web app can listen to
|
||||
window.dispatchEvent(new CustomEvent(CONVERSATION_NOT_FOUND_EVENT, {
|
||||
detail: { threadId, error: error.message }
|
||||
}))
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,9 +5,45 @@
|
||||
|
||||
import { getSharedAuthService, JanAuthService } from '../shared'
|
||||
import { JanModel, janProviderStore } from './store'
|
||||
import { ApiError } from '../shared/types/errors'
|
||||
|
||||
// JAN_API_BASE is defined in vite.config.ts
|
||||
|
||||
// Constants
|
||||
const TEMPORARY_CHAT_ID = 'temporary-chat'
|
||||
|
||||
/**
|
||||
* Determines the appropriate API endpoint and request payload based on chat type
|
||||
* @param request - The chat completion request
|
||||
* @returns Object containing endpoint URL and processed request payload
|
||||
*/
|
||||
function getChatCompletionConfig(request: JanChatCompletionRequest, stream: boolean = false) {
|
||||
const isTemporaryChat = request.conversation_id === TEMPORARY_CHAT_ID
|
||||
|
||||
// For temporary chats, use the stateless /chat/completions endpoint
|
||||
// For regular conversations, use the stateful /conv/chat/completions endpoint
|
||||
const endpoint = isTemporaryChat
|
||||
? `${JAN_API_BASE}/chat/completions`
|
||||
: `${JAN_API_BASE}/conv/chat/completions`
|
||||
|
||||
const payload = {
|
||||
...request,
|
||||
stream,
|
||||
...(isTemporaryChat ? {
|
||||
// For temporary chat: don't store anything, remove conversation metadata
|
||||
conversation_id: undefined,
|
||||
} : {
|
||||
// For regular chat: store everything, use conversation metadata
|
||||
store: true,
|
||||
store_reasoning: true,
|
||||
conversation: request.conversation_id,
|
||||
conversation_id: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
return { endpoint, payload, isTemporaryChat }
|
||||
}
|
||||
|
||||
export interface JanModelsResponse {
|
||||
object: string
|
||||
data: JanModel[]
|
||||
@ -102,7 +138,8 @@ export class JanApiClient {
|
||||
|
||||
return models
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to fetch models'
|
||||
const errorMessage = error instanceof ApiError ? error.message :
|
||||
error instanceof Error ? error.message : 'Failed to fetch models'
|
||||
janProviderStore.setError(errorMessage)
|
||||
janProviderStore.setLoadingModels(false)
|
||||
throw error
|
||||
@ -115,22 +152,18 @@ export class JanApiClient {
|
||||
try {
|
||||
janProviderStore.clearError()
|
||||
|
||||
const { endpoint, payload } = getChatCompletionConfig(request, false)
|
||||
|
||||
return await this.authService.makeAuthenticatedRequest<JanChatCompletionResponse>(
|
||||
`${JAN_API_BASE}/conv/chat/completions`,
|
||||
endpoint,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
...request,
|
||||
stream: false,
|
||||
store: true,
|
||||
store_reasoning: true,
|
||||
conversation: request.conversation_id,
|
||||
conversation_id: undefined,
|
||||
}),
|
||||
body: JSON.stringify(payload),
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to create chat completion'
|
||||
const errorMessage = error instanceof ApiError ? error.message :
|
||||
error instanceof Error ? error.message : 'Failed to create chat completion'
|
||||
janProviderStore.setError(errorMessage)
|
||||
throw error
|
||||
}
|
||||
@ -144,23 +177,17 @@ export class JanApiClient {
|
||||
): Promise<void> {
|
||||
try {
|
||||
janProviderStore.clearError()
|
||||
|
||||
|
||||
const authHeader = await this.authService.getAuthHeader()
|
||||
|
||||
const response = await fetch(`${JAN_API_BASE}/conv/chat/completions`, {
|
||||
const { endpoint, payload } = getChatCompletionConfig(request, true)
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...authHeader,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...request,
|
||||
stream: true,
|
||||
store: true,
|
||||
store_reasoning: true,
|
||||
conversation: request.conversation_id,
|
||||
conversation_id: undefined,
|
||||
}),
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
@ -216,7 +243,8 @@ export class JanApiClient {
|
||||
reader.releaseLock()
|
||||
}
|
||||
} catch (error) {
|
||||
const err = error instanceof Error ? error : new Error('Unknown error occurred')
|
||||
const err = error instanceof ApiError ? error :
|
||||
error instanceof Error ? error : new Error('Unknown error occurred')
|
||||
janProviderStore.setError(err.message)
|
||||
onError?.(err)
|
||||
throw err
|
||||
@ -230,7 +258,8 @@ export class JanApiClient {
|
||||
await this.getModels()
|
||||
console.log('Jan API client initialized successfully')
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to initialize API client'
|
||||
const errorMessage = error instanceof ApiError ? error.message :
|
||||
error instanceof Error ? error.message : 'Failed to initialize API client'
|
||||
janProviderStore.setError(errorMessage)
|
||||
throw error
|
||||
} finally {
|
||||
|
||||
@ -15,6 +15,7 @@ import {
|
||||
} from '@janhq/core' // cspell: disable-line
|
||||
import { janApiClient, JanChatMessage } from './api'
|
||||
import { janProviderStore } from './store'
|
||||
import { ApiError } from '../shared/types/errors'
|
||||
|
||||
// Jan models support tools via MCP
|
||||
const JAN_MODEL_CAPABILITIES = ['tools'] as const
|
||||
@ -192,7 +193,8 @@ export default class JanProviderWeb extends AIEngine {
|
||||
console.error(`Failed to unload Jan session ${sessionId}:`, error)
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
error: error instanceof ApiError ? error.message :
|
||||
error instanceof Error ? error.message : 'Unknown error',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -16,6 +16,7 @@ import { logoutUser, refreshToken, guestLogin } from './api'
|
||||
import { AuthProviderRegistry } from './registry'
|
||||
import { AuthBroadcast } from './broadcast'
|
||||
import type { ProviderType } from './providers'
|
||||
import { ApiError } from '../types/errors'
|
||||
|
||||
const authProviderRegistry = new AuthProviderRegistry()
|
||||
|
||||
@ -160,7 +161,7 @@ export class JanAuthService {
|
||||
this.tokenExpiryTime = Date.now() + tokens.expires_in * 1000
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh access token:', error)
|
||||
if (error instanceof Error && error.message.includes('401')) {
|
||||
if (error instanceof ApiError && error.isStatus(401)) {
|
||||
await this.handleSessionExpired()
|
||||
}
|
||||
throw error
|
||||
@ -305,9 +306,7 @@ export class JanAuthService {
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(
|
||||
`API request failed: ${response.status} ${response.statusText} - ${errorText}`
|
||||
)
|
||||
throw new ApiError(response.status, response.statusText, errorText)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
@ -418,7 +417,7 @@ export class JanAuthService {
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch user profile:', error)
|
||||
if (error instanceof Error && error.message.includes('401')) {
|
||||
if (error instanceof ApiError && error.isStatus(401)) {
|
||||
// Authentication failed - handle session expiry
|
||||
await this.handleSessionExpired()
|
||||
return null
|
||||
|
||||
50
extensions-web/src/shared/types/errors.ts
Normal file
50
extensions-web/src/shared/types/errors.ts
Normal file
@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Shared error types for API responses
|
||||
*/
|
||||
|
||||
export class ApiError extends Error {
|
||||
public readonly status: number
|
||||
public readonly statusText: string
|
||||
public readonly responseText: string
|
||||
|
||||
constructor(status: number, statusText: string, responseText: string, message?: string) {
|
||||
super(message || `API request failed: ${status} ${statusText} - ${responseText}`)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
this.statusText = statusText
|
||||
this.responseText = responseText
|
||||
|
||||
// Maintains proper stack trace for where our error was thrown (only available on V8)
|
||||
if ((Error as any).captureStackTrace) {
|
||||
(Error as any).captureStackTrace(this, ApiError)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is a specific HTTP status code
|
||||
*/
|
||||
isStatus(code: number): boolean {
|
||||
return this.status === code
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is a 404 Not Found error
|
||||
*/
|
||||
isNotFound(): boolean {
|
||||
return this.status === 404
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is a client error (4xx)
|
||||
*/
|
||||
isClientError(): boolean {
|
||||
return this.status >= 400 && this.status < 500
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is a server error (5xx)
|
||||
*/
|
||||
isServerError(): boolean {
|
||||
return this.status >= 500 && this.status < 600
|
||||
}
|
||||
}
|
||||
@ -21,8 +21,8 @@
|
||||
"@dnd-kit/core": "6.3.1",
|
||||
"@dnd-kit/modifiers": "9.0.0",
|
||||
"@dnd-kit/sortable": "10.0.0",
|
||||
"@jan/extensions-web": "link:../extensions-web",
|
||||
"@janhq/core": "link:../core",
|
||||
"@jan/extensions-web": "workspace:*",
|
||||
"@janhq/core": "workspace:*",
|
||||
"@radix-ui/react-accordion": "1.2.11",
|
||||
"@radix-ui/react-avatar": "1.1.10",
|
||||
"@radix-ui/react-dialog": "1.1.15",
|
||||
|
||||
6
web-app/src/constants/chat.ts
Normal file
6
web-app/src/constants/chat.ts
Normal file
@ -0,0 +1,6 @@
|
||||
/**
|
||||
* Chat-related constants
|
||||
*/
|
||||
|
||||
export const TEMPORARY_CHAT_ID = 'temporary-chat'
|
||||
export const TEMPORARY_CHAT_QUERY_ID = 'temporary-chat'
|
||||
@ -1,13 +1,40 @@
|
||||
import { useLeftPanel } from '@/hooks/useLeftPanel'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { IconLayoutSidebar } from '@tabler/icons-react'
|
||||
import { IconLayoutSidebar, IconMessage, IconMessageFilled } from '@tabler/icons-react'
|
||||
import { ReactNode } from '@tanstack/react-router'
|
||||
import { useRouter } from '@tanstack/react-router'
|
||||
import { route } from '@/constants/routes'
|
||||
import { PlatformFeatures } from '@/lib/platform/const'
|
||||
import { PlatformFeature } from '@/lib/platform/types'
|
||||
import { TEMPORARY_CHAT_QUERY_ID } from '@/constants/chat'
|
||||
|
||||
type HeaderPageProps = {
|
||||
children?: ReactNode
|
||||
}
|
||||
const HeaderPage = ({ children }: HeaderPageProps) => {
|
||||
const { open, setLeftPanel } = useLeftPanel()
|
||||
const router = useRouter()
|
||||
const currentPath = router.state.location.pathname
|
||||
|
||||
const isHomePage = currentPath === route.home
|
||||
|
||||
// Parse temporary chat flag from URL search params directly to avoid invariant errors
|
||||
const searchString = window.location.search
|
||||
const urlSearchParams = new URLSearchParams(searchString)
|
||||
const isTemporaryChat = isHomePage && urlSearchParams.get(TEMPORARY_CHAT_QUERY_ID) === 'true'
|
||||
|
||||
const handleChatToggle = () => {
|
||||
console.log('Chat toggle clicked!', { isTemporaryChat, isHomePage, currentPath })
|
||||
if (isHomePage) {
|
||||
if (isTemporaryChat) {
|
||||
console.log('Switching to regular chat')
|
||||
router.navigate({ to: route.home, search: {} })
|
||||
} else {
|
||||
console.log('Switching to temporary chat')
|
||||
router.navigate({ to: route.home, search: { [TEMPORARY_CHAT_QUERY_ID]: true } })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
@ -30,6 +57,29 @@ const HeaderPage = ({ children }: HeaderPageProps) => {
|
||||
</button>
|
||||
)}
|
||||
{children}
|
||||
|
||||
{/* Temporary Chat Toggle - Only show on home page if feature is enabled */}
|
||||
{PlatformFeatures[PlatformFeature.TEMPORARY_CHAT] && isHomePage && (
|
||||
<div className="ml-auto">
|
||||
<button
|
||||
className="size-8 cursor-pointer flex items-center justify-center rounded hover:bg-main-view-fg/10 transition-all duration-200 ease-in-out relative z-20"
|
||||
onClick={handleChatToggle}
|
||||
title={isTemporaryChat ? 'Switch to Regular Chat' : 'Start Temporary Chat'}
|
||||
>
|
||||
{isTemporaryChat ? (
|
||||
<IconMessageFilled
|
||||
size={18}
|
||||
className="text-main-view-fg"
|
||||
/>
|
||||
) : (
|
||||
<IconMessage
|
||||
size={18}
|
||||
className="text-main-view-fg"
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@ -33,6 +33,7 @@ import {
|
||||
} from '@/utils/reasoning'
|
||||
import { useAssistant } from './useAssistant'
|
||||
import { useShallow } from 'zustand/shallow'
|
||||
import { TEMPORARY_CHAT_QUERY_ID, TEMPORARY_CHAT_ID } from '@/constants/chat'
|
||||
|
||||
export const useChat = () => {
|
||||
const [
|
||||
@ -80,12 +81,21 @@ export const useChat = () => {
|
||||
|
||||
const getMessages = useMessages((state) => state.getMessages)
|
||||
const addMessage = useMessages((state) => state.addMessage)
|
||||
const setMessages = useMessages((state) => state.setMessages)
|
||||
const setModelLoadError = useModelLoad((state) => state.setModelLoadError)
|
||||
const router = useRouter()
|
||||
|
||||
const getCurrentThread = useCallback(async () => {
|
||||
let currentThread = retrieveThread()
|
||||
|
||||
// Check if we're in temporary chat mode
|
||||
const isTemporaryMode = window.location.search.includes(`${TEMPORARY_CHAT_QUERY_ID}=true`)
|
||||
|
||||
// Clear messages for existing temporary thread on reload to ensure fresh start
|
||||
if (isTemporaryMode && currentThread?.id === TEMPORARY_CHAT_ID) {
|
||||
setMessages(TEMPORARY_CHAT_ID, [])
|
||||
}
|
||||
|
||||
if (!currentThread) {
|
||||
// Get prompt directly from store when needed
|
||||
const currentPrompt = usePrompt.getState().prompt
|
||||
@ -93,14 +103,28 @@ export const useChat = () => {
|
||||
const assistants = useAssistant.getState().assistants
|
||||
const selectedModel = useModelProvider.getState().selectedModel
|
||||
const selectedProvider = useModelProvider.getState().selectedProvider
|
||||
|
||||
currentThread = await createThread(
|
||||
{
|
||||
id: selectedModel?.id ?? defaultModel(selectedProvider),
|
||||
provider: selectedProvider,
|
||||
},
|
||||
currentPrompt,
|
||||
assistants.find((a) => a.id === currentAssistant?.id) || assistants[0]
|
||||
isTemporaryMode ? 'Temporary Chat' : currentPrompt,
|
||||
assistants.find((a) => a.id === currentAssistant?.id) || assistants[0],
|
||||
undefined, // no project metadata
|
||||
isTemporaryMode // pass temporary flag
|
||||
)
|
||||
|
||||
// Clear messages for temporary chat to ensure fresh start on reload
|
||||
if (isTemporaryMode && currentThread?.id === TEMPORARY_CHAT_ID) {
|
||||
setMessages(TEMPORARY_CHAT_ID, [])
|
||||
}
|
||||
|
||||
// Set flag for temporary chat navigation
|
||||
if (currentThread.id === TEMPORARY_CHAT_ID) {
|
||||
sessionStorage.setItem('temp-chat-nav', 'true')
|
||||
}
|
||||
|
||||
router.navigate({
|
||||
to: route.threadsDetail,
|
||||
params: { threadId: currentThread.id },
|
||||
|
||||
@ -2,6 +2,7 @@ import { create } from 'zustand'
|
||||
import { ulid } from 'ulidx'
|
||||
import { getServiceHub } from '@/hooks/useServiceHub'
|
||||
import { Fzf } from 'fzf'
|
||||
import { TEMPORARY_CHAT_ID } from '@/constants/chat'
|
||||
|
||||
type ThreadState = {
|
||||
threads: Record<string, Thread>
|
||||
@ -21,7 +22,8 @@ type ThreadState = {
|
||||
model: ThreadModel,
|
||||
title?: string,
|
||||
assistant?: Assistant,
|
||||
projectMetadata?: { id: string; name: string; updated_at: number }
|
||||
projectMetadata?: { id: string; name: string; updated_at: number },
|
||||
isTemporary?: boolean
|
||||
) => Promise<Thread>
|
||||
updateCurrentThreadModel: (model: ThreadModel) => void
|
||||
getFilteredThreads: (searchTerm: string) => Thread[]
|
||||
@ -61,9 +63,12 @@ export const useThreads = create<ThreadState>()((set, get) => ({
|
||||
},
|
||||
{} as Record<string, Thread>
|
||||
)
|
||||
// Filter out temporary chat for search index
|
||||
const filteredForSearch = Object.values(threadMap).filter(t => t.id !== TEMPORARY_CHAT_ID)
|
||||
|
||||
set({
|
||||
threads: threadMap,
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(threadMap), {
|
||||
searchIndex: new Fzf<Thread[]>(filteredForSearch, {
|
||||
selector: (item: Thread) => item.title,
|
||||
}),
|
||||
})
|
||||
@ -71,15 +76,18 @@ export const useThreads = create<ThreadState>()((set, get) => ({
|
||||
getFilteredThreads: (searchTerm: string) => {
|
||||
const { threads, searchIndex } = get()
|
||||
|
||||
// Filter out temporary chat from all operations
|
||||
const filteredThreadsValues = Object.values(threads).filter(t => t.id !== TEMPORARY_CHAT_ID)
|
||||
|
||||
// If no search term, return all threads
|
||||
if (!searchTerm) {
|
||||
// return all threads
|
||||
return Object.values(threads)
|
||||
return filteredThreadsValues
|
||||
}
|
||||
|
||||
let currentIndex = searchIndex
|
||||
if (!currentIndex?.find) {
|
||||
currentIndex = new Fzf<Thread[]>(Object.values(threads), {
|
||||
currentIndex = new Fzf<Thread[]>(filteredThreadsValues, {
|
||||
selector: (item: Thread) => item.title,
|
||||
})
|
||||
set({ searchIndex: currentIndex })
|
||||
@ -125,7 +133,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({
|
||||
getServiceHub().threads().deleteThread(threadId)
|
||||
return {
|
||||
threads: remainingThreads,
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(remainingThreads), {
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(remainingThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
|
||||
selector: (item: Thread) => item.title,
|
||||
}),
|
||||
}
|
||||
@ -165,7 +173,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({
|
||||
|
||||
return {
|
||||
threads: remainingThreads,
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(remainingThreads), {
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(remainingThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
|
||||
selector: (item: Thread) => item.title,
|
||||
}),
|
||||
}
|
||||
@ -218,18 +226,24 @@ export const useThreads = create<ThreadState>()((set, get) => ({
|
||||
setCurrentThreadId: (threadId) => {
|
||||
if (threadId !== get().currentThreadId) set({ currentThreadId: threadId })
|
||||
},
|
||||
createThread: async (model, title, assistant, projectMetadata) => {
|
||||
createThread: async (model, title, assistant, projectMetadata, isTemporary) => {
|
||||
const newThread: Thread = {
|
||||
id: ulid(),
|
||||
title: title ?? 'New Thread',
|
||||
id: isTemporary ? TEMPORARY_CHAT_ID : ulid(),
|
||||
title: title ?? (isTemporary ? 'Temporary Chat' : 'New Thread'),
|
||||
model,
|
||||
updated: Date.now() / 1000,
|
||||
assistants: assistant ? [assistant] : [],
|
||||
...(projectMetadata && {
|
||||
...(projectMetadata && !isTemporary && {
|
||||
metadata: {
|
||||
project: projectMetadata,
|
||||
},
|
||||
}),
|
||||
...(isTemporary && {
|
||||
metadata: {
|
||||
isTemporary: true,
|
||||
...(projectMetadata && { project: projectMetadata }),
|
||||
},
|
||||
}),
|
||||
}
|
||||
return await getServiceHub()
|
||||
.threads()
|
||||
@ -307,7 +321,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({
|
||||
const newThreads = { ...state.threads, [threadId]: updatedThread }
|
||||
return {
|
||||
threads: newThreads,
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(newThreads), {
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(newThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
|
||||
selector: (item: Thread) => item.title,
|
||||
}),
|
||||
}
|
||||
@ -337,7 +351,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({
|
||||
|
||||
return {
|
||||
threads: updatedThreads,
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(updatedThreads), {
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(updatedThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
|
||||
selector: (item: Thread) => item.title,
|
||||
}),
|
||||
}
|
||||
@ -359,7 +373,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({
|
||||
const newThreads = { ...state.threads, [threadId]: updatedThread }
|
||||
return {
|
||||
threads: newThreads,
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(newThreads), {
|
||||
searchIndex: new Fzf<Thread[]>(Object.values(newThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
|
||||
selector: (item: Thread) => item.title,
|
||||
}),
|
||||
}
|
||||
|
||||
@ -64,4 +64,7 @@ export const PlatformFeatures: Record<PlatformFeature, boolean> = {
|
||||
|
||||
// First message persisted thread - enabled for web only
|
||||
[PlatformFeature.FIRST_MESSAGE_PERSISTED_THREAD]: !isPlatformTauri(),
|
||||
|
||||
// Temporary chat mode - enabled for web only
|
||||
[PlatformFeature.TEMPORARY_CHAT]: !isPlatformTauri(),
|
||||
}
|
||||
@ -66,4 +66,7 @@ export enum PlatformFeature {
|
||||
|
||||
// First message persisted thread - web-only feature for storing first user message locally during thread creation
|
||||
FIRST_MESSAGE_PERSISTED_THREAD = 'firstMessagePersistedThread',
|
||||
|
||||
// Temporary chat mode - web-only feature for ephemeral conversations like ChatGPT
|
||||
TEMPORARY_CHAT = 'temporaryChat',
|
||||
}
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
{
|
||||
"welcome": "Hi, how are you?",
|
||||
"description": "How can I help you today?",
|
||||
"temporaryChat": "Temporary Chat",
|
||||
"temporaryChatDescription": "Start a temporary conversation that won't be saved to your chat history.",
|
||||
"status": {
|
||||
"empty": "No Chats Found"
|
||||
},
|
||||
|
||||
@ -124,6 +124,10 @@
|
||||
"error": "Error",
|
||||
"success": "Success",
|
||||
"warning": "Warning",
|
||||
"conversationNotAvailable": "Conversation not available",
|
||||
"conversationNotAvailableDescription": "The conversation you are trying to access is not available or has been deleted.",
|
||||
"temporaryChat": "Temporary Chat",
|
||||
"temporaryChatTooltip": "Temporary chat won't appear in your history",
|
||||
"noResultsFoundDesc": "We couldn't find any chats matching your search. Try a different keyword.",
|
||||
"searchModels": "Search models...",
|
||||
"searchStyles": "Search styles...",
|
||||
|
||||
@ -13,18 +13,29 @@ type SearchParams = {
|
||||
id: string
|
||||
provider: string
|
||||
}
|
||||
'temporary-chat'?: boolean
|
||||
}
|
||||
import DropdownAssistant from '@/containers/DropdownAssistant'
|
||||
import { useEffect } from 'react'
|
||||
import { useThreads } from '@/hooks/useThreads'
|
||||
import { PlatformFeatures } from '@/lib/platform/const'
|
||||
import { PlatformFeature } from '@/lib/platform/types'
|
||||
import { TEMPORARY_CHAT_QUERY_ID } from '@/constants/chat'
|
||||
|
||||
export const Route = createFileRoute(route.home as any)({
|
||||
component: Index,
|
||||
validateSearch: (search: Record<string, unknown>): SearchParams => ({
|
||||
model: search.model as SearchParams['model'],
|
||||
}),
|
||||
validateSearch: (search: Record<string, unknown>): SearchParams => {
|
||||
const result: SearchParams = {
|
||||
model: search.model as SearchParams['model'],
|
||||
}
|
||||
|
||||
// Only include temporary-chat if it's explicitly true
|
||||
if (search[TEMPORARY_CHAT_QUERY_ID] === 'true' || search[TEMPORARY_CHAT_QUERY_ID] === true) {
|
||||
result['temporary-chat'] = true
|
||||
}
|
||||
|
||||
return result
|
||||
},
|
||||
})
|
||||
|
||||
function Index() {
|
||||
@ -32,6 +43,7 @@ function Index() {
|
||||
const { providers } = useModelProvider()
|
||||
const search = useSearch({ from: route.home as any })
|
||||
const selectedModel = search.model
|
||||
const isTemporaryChat = search['temporary-chat']
|
||||
const { setCurrentThreadId } = useThreads()
|
||||
|
||||
// Conditional to check if there are any valid providers
|
||||
@ -60,10 +72,10 @@ function Index() {
|
||||
<div className="w-full md:w-4/6 mx-auto">
|
||||
<div className="mb-8 text-center">
|
||||
<h1 className="font-editorialnew text-main-view-fg text-4xl">
|
||||
{t('chat:welcome')}
|
||||
{isTemporaryChat ? t('chat:temporaryChat') : t('chat:welcome')}
|
||||
</h1>
|
||||
<p className="text-main-view-fg/70 text-lg mt-2">
|
||||
{t('chat:description')}
|
||||
{isTemporaryChat ? t('chat:temporaryChatDescription') : t('chat:description')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex-1 shrink-0">
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import { createFileRoute, useParams } from '@tanstack/react-router'
|
||||
import { createFileRoute, useParams, redirect, useNavigate } from '@tanstack/react-router'
|
||||
import cloneDeep from 'lodash.clonedeep'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from '@/i18n/react-i18next-compat'
|
||||
|
||||
import HeaderPage from '@/containers/HeaderPage'
|
||||
import { useThreads } from '@/hooks/useThreads'
|
||||
@ -21,16 +23,63 @@ import { PlatformFeatures } from '@/lib/platform/const'
|
||||
import { PlatformFeature } from '@/lib/platform/types'
|
||||
import ScrollToBottom from '@/containers/ScrollToBottom'
|
||||
import { PromptProgress } from '@/components/PromptProgress'
|
||||
import { TEMPORARY_CHAT_ID, TEMPORARY_CHAT_QUERY_ID } from '@/constants/chat'
|
||||
import { useThreadScrolling } from '@/hooks/useThreadScrolling'
|
||||
import { IconInfoCircle } from '@tabler/icons-react'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
|
||||
const CONVERSATION_NOT_FOUND_EVENT = 'conversation-not-found'
|
||||
|
||||
const TemporaryChatIndicator = ({ t }: { t: (key: string) => string }) => {
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 px-3 py-1 rounded-md bg-main-view-fg/5 text-main-view-fg/70 text-sm">
|
||||
<span>{t('common:temporaryChat')}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="relative z-20">
|
||||
<IconInfoCircle
|
||||
size={14}
|
||||
className="text-main-view-fg/50 hover:text-main-view-fg/70 transition-colors cursor-pointer"
|
||||
/>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="z-[9999]">
|
||||
<p>{t('common:temporaryChatTooltip')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// as route.threadsDetail
|
||||
export const Route = createFileRoute('/threads/$threadId')({
|
||||
beforeLoad: ({ params }) => {
|
||||
// Check if this is the temporary chat being accessed directly
|
||||
if (params.threadId === TEMPORARY_CHAT_ID) {
|
||||
// Check if we have the navigation flag in sessionStorage
|
||||
const hasNavigationFlag = sessionStorage.getItem('temp-chat-nav')
|
||||
|
||||
if (!hasNavigationFlag) {
|
||||
// Direct access - redirect to home with query parameter
|
||||
throw redirect({
|
||||
to: '/',
|
||||
search: { [TEMPORARY_CHAT_QUERY_ID]: true },
|
||||
replace: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Clear the flag immediately after checking
|
||||
sessionStorage.removeItem('temp-chat-nav')
|
||||
}
|
||||
},
|
||||
component: ThreadDetail,
|
||||
})
|
||||
|
||||
function ThreadDetail() {
|
||||
const serviceHub = useServiceHub()
|
||||
const { threadId } = useParams({ from: Route.id })
|
||||
const navigate = useNavigate()
|
||||
const { t } = useTranslation()
|
||||
const setCurrentThreadId = useThreads((state) => state.setCurrentThreadId)
|
||||
const setCurrentAssistant = useAssistant((state) => state.setCurrentAssistant)
|
||||
const assistants = useAssistant((state) => state.assistants)
|
||||
@ -49,9 +98,33 @@ function ThreadDetail() {
|
||||
const thread = useThreads(useShallow((state) => state.threads[threadId]))
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
|
||||
// Get padding height for ChatGPT-style message positioning
|
||||
const { paddingHeight } = useThreadScrolling(threadId, scrollContainerRef)
|
||||
|
||||
// Listen for conversation not found events
|
||||
useEffect(() => {
|
||||
const handleConversationNotFound = (event: CustomEvent) => {
|
||||
const { threadId: notFoundThreadId } = event.detail
|
||||
if (notFoundThreadId === threadId) {
|
||||
// Skip error handling for temporary chat - it's expected to not exist on server
|
||||
if (threadId === TEMPORARY_CHAT_ID) {
|
||||
return
|
||||
}
|
||||
|
||||
toast.error(t('common:conversationNotAvailable'), {
|
||||
description: t('common:conversationNotAvailableDescription')
|
||||
})
|
||||
navigate({ to: '/', replace: true })
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener(CONVERSATION_NOT_FOUND_EVENT, handleConversationNotFound as EventListener)
|
||||
return () => {
|
||||
window.removeEventListener(CONVERSATION_NOT_FOUND_EVENT, handleConversationNotFound as EventListener)
|
||||
}
|
||||
}, [threadId, navigate])
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentThreadId(threadId)
|
||||
const assistant = assistants.find(
|
||||
@ -137,9 +210,15 @@ function ThreadDetail() {
|
||||
<div className="flex flex-col h-full">
|
||||
<HeaderPage>
|
||||
<div className="flex items-center justify-between w-full pr-2">
|
||||
{PlatformFeatures[PlatformFeature.ASSISTANTS] && (
|
||||
<DropdownAssistant />
|
||||
)}
|
||||
<div>
|
||||
{PlatformFeatures[PlatformFeature.ASSISTANTS] && (
|
||||
<DropdownAssistant />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 flex justify-center">
|
||||
{threadId === TEMPORARY_CHAT_ID && <TemporaryChatIndicator t={t} />}
|
||||
</div>
|
||||
<div></div>
|
||||
</div>
|
||||
</HeaderPage>
|
||||
<div className="flex flex-col h-[calc(100%-40px)]">
|
||||
|
||||
@ -8,10 +8,16 @@ import {
|
||||
ExtensionTypeEnum,
|
||||
ThreadMessage,
|
||||
} from '@janhq/core'
|
||||
import { TEMPORARY_CHAT_ID } from '@/constants/chat'
|
||||
import type { MessagesService } from './types'
|
||||
|
||||
export class DefaultMessagesService implements MessagesService {
|
||||
async fetchMessages(threadId: string): Promise<ThreadMessage[]> {
|
||||
// Don't fetch messages from server for temporary chat - it's local only
|
||||
if (threadId === TEMPORARY_CHAT_ID) {
|
||||
return []
|
||||
}
|
||||
|
||||
return (
|
||||
ExtensionManager.getInstance()
|
||||
.get<ConversationalExtension>(ExtensionTypeEnum.Conversational)
|
||||
@ -21,6 +27,11 @@ export class DefaultMessagesService implements MessagesService {
|
||||
}
|
||||
|
||||
async createMessage(message: ThreadMessage): Promise<ThreadMessage> {
|
||||
// Don't create messages on server for temporary chat - it's local only
|
||||
if (message.thread_id === TEMPORARY_CHAT_ID) {
|
||||
return message
|
||||
}
|
||||
|
||||
return (
|
||||
ExtensionManager.getInstance()
|
||||
.get<ConversationalExtension>(ExtensionTypeEnum.Conversational)
|
||||
@ -30,6 +41,11 @@ export class DefaultMessagesService implements MessagesService {
|
||||
}
|
||||
|
||||
async deleteMessage(threadId: string, messageId: string): Promise<void> {
|
||||
// Don't delete messages on server for temporary chat - it's local only
|
||||
if (threadId === TEMPORARY_CHAT_ID) {
|
||||
return
|
||||
}
|
||||
|
||||
await ExtensionManager.getInstance()
|
||||
.get<ConversationalExtension>(ExtensionTypeEnum.Conversational)
|
||||
?.deleteMessage(threadId, messageId)
|
||||
|
||||
@ -6,6 +6,7 @@ import { defaultAssistant } from '@/hooks/useAssistant'
|
||||
import { ExtensionManager } from '@/lib/extension'
|
||||
import { ConversationalExtension, ExtensionTypeEnum } from '@janhq/core'
|
||||
import type { ThreadsService } from './types'
|
||||
import { TEMPORARY_CHAT_ID } from '@/constants/chat'
|
||||
|
||||
export class DefaultThreadsService implements ThreadsService {
|
||||
async fetchThreads(): Promise<Thread[]> {
|
||||
@ -16,7 +17,10 @@ export class DefaultThreadsService implements ThreadsService {
|
||||
.then((threads) => {
|
||||
if (!Array.isArray(threads)) return []
|
||||
|
||||
return threads.map((e) => {
|
||||
// Filter out temporary threads from the list
|
||||
const filteredThreads = threads.filter((e) => e.id !== TEMPORARY_CHAT_ID)
|
||||
|
||||
return filteredThreads.map((e) => {
|
||||
return {
|
||||
...e,
|
||||
updated:
|
||||
@ -47,6 +51,11 @@ export class DefaultThreadsService implements ThreadsService {
|
||||
}
|
||||
|
||||
async createThread(thread: Thread): Promise<Thread> {
|
||||
// For temporary threads, bypass the conversational extension (in-memory only)
|
||||
if (thread.id === TEMPORARY_CHAT_ID) {
|
||||
return thread
|
||||
}
|
||||
|
||||
return (
|
||||
ExtensionManager.getInstance()
|
||||
.get<ConversationalExtension>(ExtensionTypeEnum.Conversational)
|
||||
@ -82,6 +91,11 @@ export class DefaultThreadsService implements ThreadsService {
|
||||
}
|
||||
|
||||
async updateThread(thread: Thread): Promise<void> {
|
||||
// For temporary threads, skip updating via conversational extension
|
||||
if (thread.id === TEMPORARY_CHAT_ID) {
|
||||
return
|
||||
}
|
||||
|
||||
await ExtensionManager.getInstance()
|
||||
.get<ConversationalExtension>(ExtensionTypeEnum.Conversational)
|
||||
?.modifyThread({
|
||||
@ -118,6 +132,11 @@ export class DefaultThreadsService implements ThreadsService {
|
||||
}
|
||||
|
||||
async deleteThread(threadId: string): Promise<void> {
|
||||
// For temporary threads, skip deleting via conversational extension
|
||||
if (threadId === TEMPORARY_CHAT_ID) {
|
||||
return
|
||||
}
|
||||
|
||||
await ExtensionManager.getInstance()
|
||||
.get<ConversationalExtension>(ExtensionTypeEnum.Conversational)
|
||||
?.deleteThread(threadId)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user