feat: add React frontend with chat and note browsing
This commit is contained in:
@@ -1 +1,4 @@
|
||||
ref_docs/
|
||||
web/node_modules/
|
||||
web/dist/
|
||||
.env
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Knowledge Assistant</title>
|
||||
</head>
|
||||
<body class="bg-gray-50">
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "knowledge-assistant-web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-markdown": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.1.7",
|
||||
"@types/react": "^19.1.4",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"@vitejs/plugin-react": "^4.5.2",
|
||||
"tailwindcss": "^4.1.7",
|
||||
"typescript": "~5.8.3",
|
||||
"vite": "^6.3.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import Layout from './components/Layout'
|
||||
|
||||
export default function App() {
|
||||
return <Layout />
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { Note, Message } from '../types'
|
||||
|
||||
const BASE = '/api'
|
||||
|
||||
export async function fetchNotes(): Promise<Note[]> {
|
||||
const res = await fetch(`${BASE}/notes`)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchNote(id: string): Promise<Note> {
|
||||
const res = await fetch(`${BASE}/notes/${encodeURIComponent(id)}`)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function createNote(note: { title: string; content: string; tags?: string[] }): Promise<Note> {
|
||||
const res = await fetch(`${BASE}/notes`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(note),
|
||||
})
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function deleteNote(id: string): Promise<void> {
|
||||
await fetch(`${BASE}/notes/${encodeURIComponent(id)}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function rebuildIndex(): Promise<void> {
|
||||
await fetch(`${BASE}/index`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export function streamChat(
|
||||
message: string,
|
||||
onEvent: (event: { type: string; agent: string; content: string; role: string }) => void,
|
||||
onDone: () => void,
|
||||
onError: (err: string) => void,
|
||||
): AbortController {
|
||||
const controller = new AbortController()
|
||||
|
||||
fetch(`${BASE}/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message }),
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) {
|
||||
onError(`HTTP ${res.status}`)
|
||||
return
|
||||
}
|
||||
const reader = res.body?.getReader()
|
||||
if (!reader) {
|
||||
onError('No response body')
|
||||
return
|
||||
}
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() || ''
|
||||
|
||||
let currentEvent = ''
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event: ')) {
|
||||
currentEvent = line.slice(7)
|
||||
} else if (line.startsWith('data: ')) {
|
||||
try {
|
||||
const data = JSON.parse(line.slice(6))
|
||||
onEvent({ type: currentEvent, ...data })
|
||||
} catch {
|
||||
// skip malformed JSON
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
onDone()
|
||||
})
|
||||
.catch((err) => {
|
||||
if (err.name !== 'AbortError') {
|
||||
onError(err.message)
|
||||
}
|
||||
})
|
||||
|
||||
return controller
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { useChat } from '../hooks/useChat'
|
||||
import MessageBubble from './MessageBubble'
|
||||
|
||||
export default function ChatPanel() {
|
||||
const { messages, loading, sendMessage, clearMessages } = useChat()
|
||||
const [input, setInput] = useState('')
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||
}, [messages])
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!input.trim()) return
|
||||
sendMessage(input)
|
||||
setInput('')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex items-center justify-between px-6 py-3 border-b border-gray-200 bg-white">
|
||||
<h1 className="text-lg font-semibold text-gray-800">Knowledge Assistant</h1>
|
||||
{messages.length > 0 && (
|
||||
<button
|
||||
onClick={clearMessages}
|
||||
className="text-xs text-gray-500 hover:text-gray-700 px-3 py-1 rounded-md hover:bg-gray-100"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4">
|
||||
{messages.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-full text-gray-400 text-sm">
|
||||
Ask me anything about your notes...
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{messages.map((msg) => (
|
||||
<MessageBubble key={msg.id} message={msg} />
|
||||
))}
|
||||
{loading && messages[messages.length - 1]?.role === 'assistant' && (
|
||||
<div className="flex items-center gap-1 text-gray-400 text-xs ml-2 mb-3">
|
||||
<span className="animate-pulse">thinking...</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="px-6 py-4 border-t border-gray-200 bg-white">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
placeholder="Type your message..."
|
||||
className="flex-1 px-4 py-2.5 text-sm border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
disabled={loading}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !input.trim()}
|
||||
className="px-5 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-xl hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useState } from 'react'
|
||||
import ChatPanel from './ChatPanel'
|
||||
import NoteList from './NoteList'
|
||||
import NoteDetail from './NoteDetail'
|
||||
import { useNotes } from '../hooks/useNotes'
|
||||
|
||||
export default function Layout() {
|
||||
const { notes, selectedNote, loadNote, removeNote, setSelectedNote } = useNotes()
|
||||
const [sidebarTab, setSidebarTab] = useState<'chat' | 'notes'>('chat')
|
||||
|
||||
return (
|
||||
<div className="flex h-screen bg-gray-50">
|
||||
<div className="w-72 border-r border-gray-200 bg-white flex flex-col shrink-0">
|
||||
<div className="flex border-b border-gray-200">
|
||||
<button
|
||||
onClick={() => setSidebarTab('chat')}
|
||||
className={`flex-1 py-3 text-sm font-medium ${
|
||||
sidebarTab === 'chat'
|
||||
? 'text-blue-600 border-b-2 border-blue-600'
|
||||
: 'text-gray-500 hover:text-gray-700'
|
||||
}`}
|
||||
>
|
||||
Chat
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setSidebarTab('notes')}
|
||||
className={`flex-1 py-3 text-sm font-medium ${
|
||||
sidebarTab === 'notes'
|
||||
? 'text-blue-600 border-b-2 border-blue-600'
|
||||
: 'text-gray-500 hover:text-gray-700'
|
||||
}`}
|
||||
>
|
||||
Notes
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{sidebarTab === 'notes' && (
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<NoteList
|
||||
notes={notes}
|
||||
selectedId={selectedNote?.id}
|
||||
onSelect={loadNote}
|
||||
onDelete={removeNote}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sidebarTab === 'chat' && (
|
||||
<div className="flex-1 flex items-center justify-center text-sm text-gray-400 p-4 text-center">
|
||||
Use the chat panel to interact with your knowledge assistant
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 flex">
|
||||
{selectedNote ? (
|
||||
<div className="flex-1">
|
||||
<NoteDetail note={selectedNote} onClose={() => setSelectedNote(null)} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1">
|
||||
<ChatPanel />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Message } from '../types'
|
||||
|
||||
interface Props {
|
||||
message: Message
|
||||
}
|
||||
|
||||
export default function MessageBubble({ message }: Props) {
|
||||
const isUser = message.role === 'user'
|
||||
|
||||
return (
|
||||
<div className={`flex ${isUser ? 'justify-end' : 'justify-start'} mb-3`}>
|
||||
<div
|
||||
className={`max-w-[75%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${
|
||||
isUser
|
||||
? 'bg-blue-600 text-white rounded-br-md'
|
||||
: 'bg-white text-gray-800 shadow-sm border border-gray-200 rounded-bl-md'
|
||||
}`}
|
||||
>
|
||||
{!isUser && message.agent && (
|
||||
<div className="text-[10px] font-medium text-blue-500 mb-1 uppercase tracking-wide">
|
||||
{message.agent}
|
||||
</div>
|
||||
)}
|
||||
<div className="whitespace-pre-wrap">{message.content}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { Note } from '../types'
|
||||
|
||||
interface Props {
|
||||
note: Note
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function NoteDetail({ note, onClose }: Props) {
|
||||
return (
|
||||
<div className="h-full flex flex-col bg-white">
|
||||
<div className="flex items-center justify-between px-6 py-3 border-b border-gray-200">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-800">{note.title}</h2>
|
||||
{note.tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mt-1">
|
||||
{note.tags.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="text-xs px-2 py-0.5 bg-blue-50 text-blue-600 rounded-full"
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 text-lg"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4">
|
||||
<pre className="text-sm text-gray-700 whitespace-pre-wrap font-sans leading-relaxed">
|
||||
{note.content}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { Note } from '../types'
|
||||
|
||||
interface Props {
|
||||
notes: Note[]
|
||||
selectedId?: string
|
||||
onSelect: (id: string) => void
|
||||
onDelete: (id: string) => void
|
||||
}
|
||||
|
||||
export default function NoteList({ notes, selectedId, onSelect, onDelete }: Props) {
|
||||
if (notes.length === 0) {
|
||||
return (
|
||||
<div className="p-4 text-sm text-gray-400 text-center">
|
||||
No notes yet
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{notes.map((note) => (
|
||||
<div
|
||||
key={note.id}
|
||||
onClick={() => onSelect(note.id)}
|
||||
className={`px-4 py-3 cursor-pointer hover:bg-gray-50 transition-colors ${
|
||||
selectedId === note.id ? 'bg-blue-50 border-l-2 border-blue-500' : ''
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<h3 className="text-sm font-medium text-gray-800 truncate">{note.title}</h3>
|
||||
{note.tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mt-1">
|
||||
{note.tags.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="text-[10px] px-1.5 py-0.5 bg-gray-100 text-gray-500 rounded"
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDelete(note.id)
|
||||
}}
|
||||
className="text-gray-400 hover:text-red-500 text-xs shrink-0"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useState, useCallback, useRef } from 'react'
|
||||
import { streamChat } from '../api/client'
|
||||
import type { Message } from '../types'
|
||||
|
||||
export function useChat() {
|
||||
const [messages, setMessages] = useState<Message[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const controllerRef = useRef<AbortController | null>(null)
|
||||
|
||||
const sendMessage = useCallback((content: string) => {
|
||||
if (!content.trim() || loading) return
|
||||
|
||||
const userMsg: Message = {
|
||||
id: Date.now().toString(),
|
||||
role: 'user',
|
||||
content,
|
||||
}
|
||||
setMessages((prev) => [...prev, userMsg])
|
||||
setLoading(true)
|
||||
|
||||
const assistantMsg: Message = {
|
||||
id: (Date.now() + 1).toString(),
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
}
|
||||
setMessages((prev) => [...prev, assistantMsg])
|
||||
|
||||
controllerRef.current = streamChat(
|
||||
content,
|
||||
(event) => {
|
||||
if (event.type === 'message' && event.content) {
|
||||
setMessages((prev) => {
|
||||
const last = prev[prev.length - 1]
|
||||
if (last.role === 'assistant') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...last,
|
||||
content: last.content + event.content,
|
||||
agent: event.agent || last.agent,
|
||||
},
|
||||
]
|
||||
}
|
||||
return prev
|
||||
})
|
||||
}
|
||||
},
|
||||
() => setLoading(false),
|
||||
(err) => {
|
||||
setMessages((prev) => {
|
||||
const last = prev[prev.length - 1]
|
||||
if (last.role === 'assistant') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{ ...last, content: last.content || `Error: ${err}` },
|
||||
]
|
||||
}
|
||||
return prev
|
||||
})
|
||||
setLoading(false)
|
||||
},
|
||||
)
|
||||
}, [loading])
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
controllerRef.current?.abort()
|
||||
setMessages([])
|
||||
setLoading(false)
|
||||
}, [])
|
||||
|
||||
return { messages, loading, sendMessage, clearMessages }
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useState, useCallback, useEffect } from 'react'
|
||||
import { fetchNotes, fetchNote, deleteNote } from '../api/client'
|
||||
import type { Note } from '../types'
|
||||
|
||||
export function useNotes() {
|
||||
const [notes, setNotes] = useState<Note[]>([])
|
||||
const [selectedNote, setSelectedNote] = useState<Note | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const loadNotes = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await fetchNotes()
|
||||
setNotes(data || [])
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
setLoading(false)
|
||||
}, [])
|
||||
|
||||
const loadNote = useCallback(async (id: string) => {
|
||||
try {
|
||||
const note = await fetchNote(id)
|
||||
setSelectedNote(note)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, [])
|
||||
|
||||
const removeNote = useCallback(async (id: string) => {
|
||||
try {
|
||||
await deleteNote(id)
|
||||
setNotes((prev) => prev.filter((n) => n.id !== id))
|
||||
if (selectedNote?.id === id) {
|
||||
setSelectedNote(null)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, [selectedNote])
|
||||
|
||||
useEffect(() => {
|
||||
loadNotes()
|
||||
}, [loadNotes])
|
||||
|
||||
return { notes, selectedNote, loading, loadNotes, loadNote, removeNote, setSelectedNote }
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
@import "tailwindcss";
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
export interface Note {
|
||||
id: string
|
||||
title: string
|
||||
content?: string
|
||||
tags: string[]
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: string
|
||||
role: 'user' | 'assistant'
|
||||
content: string
|
||||
agent?: string
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user