LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
feat: multi-conversation chat with conversation list and history limit setting
nash_su0c81b21ec968
diff --git a/src/App.tsx b/src/App.tsxindex de50eb40..3b0eaee4 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -102,8 +102,14 @@ function App() {// Load persisted chat historytry {const savedChat = await loadChatHistory(proj.path)- if (savedChat.length > 0) {- useChatStore.getState().setMessages(savedChat)+ if (savedChat.conversations.length > 0) {+ useChatStore.getState().setConversations(savedChat.conversations)+ useChatStore.getState().setMessages(savedChat.messages)+ // Set most recent conversation as active+ const sorted = [...savedChat.conversations].sort((a, b) => b.updatedAt - a.updatedAt)+ if (sorted[0]) {+ useChatStore.getState().setActiveConversation(sorted[0].id)+ }}} catch {// ignore, start freshdiff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsxindex 33d550b7..59b61125 100644--- a/src/components/chat/chat-panel.tsx+++ b/src/components/chat/chat-panel.tsx@@ -1,5 +1,5 @@-import { useRef, useEffect, useCallback } from "react"-import { BookOpen } from "lucide-react"+import { useRef, useEffect, useCallback, useState } from "react"+import { BookOpen, Plus, Trash2, MessageSquare } from "lucide-react"import { Button } from "@/components/ui/button"import { ChatMessage, StreamingMessage, useSourceFiles } from "./chat-message"import { ChatInput } from "./chat-input"@@ -16,9 +16,104 @@ import type { FileNode } from "@/types/wiki"// Store the page mapping from the last query so SourceFilesBar can show which pages were citedexport let lastQueryPages: { title: string; path: string }[] = []+function formatDate(timestamp: number): string {+ const d = new Date(timestamp)+ const now = new Date()+ const isToday = d.toDateString() === now.toDateString()+ if (isToday) {+ return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })+ }+ return d.toLocaleDateString([], { month: "short", day: "numeric" })+}++function ConversationSidebar() {+ const conversations = useChatStore((s) => s.conversations)+ const activeConversationId = useChatStore((s) => s.activeConversationId)+ const messages = useChatStore((s) => s.messages)+ const createConversation = useChatStore((s) => s.createConversation)+ const deleteConversation = useChatStore((s) => s.deleteConversation)+ const setActiveConversation = useChatStore((s) => s.setActiveConversation)++ const [hoveredId, setHoveredId] = useState<string | null>(null)++ const sorted = [...conversations].sort((a, b) => b.updatedAt - a.updatedAt)++ function getMessageCount(convId: string): number {+ return messages.filter((m) => m.conversationId === convId).length+ }++ return (+ <div className="flex h-full w-[200px] flex-shrink-0 flex-col border-r bg-muted/30">+ <div className="border-b p-2">+ <Button+ variant="outline"+ size="sm"+ className="w-full gap-2"+ onClick={() => createConversation()}+ >+ <Plus className="h-3.5 w-3.5" />+ New Chat+ </Button>+ </div>++ <div className="flex-1 overflow-y-auto py-1">+ {sorted.length === 0 ? (+ <p className="px-3 py-4 text-xs text-muted-foreground text-center">+ No conversations yet+ </p>+ ) : (+ sorted.map((conv) => {+ const isActive = conv.id === activeConversationId+ const msgCount = getMessageCount(conv.id)+ return (+ <div+ key={conv.id}+ className={`group relative mx-1 my-0.5 flex cursor-pointer flex-col rounded-md px-2 py-1.5 text-sm transition-colors ${+ isActive+ ? "bg-primary/10 text-primary"+ : "hover:bg-accent text-foreground"+ }`}+ onClick={() => setActiveConversation(conv.id)}+ onMouseEnter={() => setHoveredId(conv.id)}+ onMouseLeave={() => setHoveredId(null)}+ >+ <div className="flex items-start justify-between gap-1">+ <span className="line-clamp-2 flex-1 text-xs font-medium leading-snug">+ {conv.title}+ </span>+ {hoveredId === conv.id && (+ <button+ className="flex-shrink-0 rounded p-0.5 text-muted-foreground hover:text-destructive"+ onClick={(e) => {+ e.stopPropagation()+ deleteConversation(conv.id)+ }}+ >+ <Trash2 className="h-3 w-3" />+ </button>+ )}+ </div>+ <div className="mt-0.5 flex items-center gap-1.5 text-[10px] text-muted-foreground">+ <span>{formatDate(conv.updatedAt)}</span>+ {msgCount > 0 && (+ <>+ <span>·</span>+ <span>{msgCount} msgs</span>+ </>+ )}+ </div>+ </div>+ )+ })+ )}+ </div>+ </div>+ )+}+export function ChatPanel() {useSourceFiles() // Keep source file cache warm- const messages = useChatStore((s) => s.messages)+ const activeConversationId = useChatStore((s) => s.activeConversationId)const isStreaming = useChatStore((s) => s.isStreaming)const streamingContent = useChatStore((s) => s.streamingContent)const mode = useChatStore((s) => s.mode)@@ -26,6 +121,14 @@ export function ChatPanel() {const setStreaming = useChatStore((s) => s.setStreaming)const appendStreamToken = useChatStore((s) => s.appendStreamToken)const finalizeStream = useChatStore((s) => s.finalizeStream)+ const createConversation = useChatStore((s) => s.createConversation)+ const maxHistoryMessages = useChatStore((s) => s.maxHistoryMessages)++ // Derive active messages via selector to re-render on message changes+ const allMessages = useChatStore((s) => s.messages)+ const activeMessages = activeConversationId+ ? allMessages.filter((m) => m.conversationId === activeConversationId)+ : []const project = useWikiStore((s) => s.project)const llmConfig = useWikiStore((s) => s.llmConfig)@@ -41,10 +144,16 @@ export function ChatPanel() {if (container) {container.scrollTop = container.scrollHeight}- }, [messages, streamingContent])+ }, [activeMessages, streamingContent])const handleSend = useCallback(async (text: string) => {+ // Auto-create a conversation if none is active+ let convId = useChatStore.getState().activeConversationId+ if (!convId) {+ convId = createConversation()+ }+addMessage("user", text)setStreaming(true)@@ -55,17 +164,9 @@ export function ChatPanel() {const maxCtx = llmConfig.maxContextSize || 204800// ── Budget allocation ──────────────────────────────────- // Total context split into parts:- // System prompt fixed: ~0.5%- // purpose.md: ~0.2%- // wiki/index.md: 5% (max)- // Wiki page content: 60%- // Conversation history: 20%- // Reserved for LLM: ~15%const INDEX_BUDGET = Math.floor(maxCtx * 0.05)const PAGE_BUDGET = Math.floor(maxCtx * 0.6)const MAX_PAGE_SIZE = Math.min(Math.floor(PAGE_BUDGET * 0.3), 30_000)- const HISTORY_BUDGET = Math.floor(maxCtx * 0.2)const [rawIndex, purpose] = await Promise.all([readFile(`${project.path}/wiki/index.md`).catch(() => ""),@@ -79,7 +180,6 @@ export function ChatPanel() {// ── Trim index by relevance if over budget ─────────────let index = rawIndexif (rawIndex.length > INDEX_BUDGET) {- // Keep lines that match any search token, plus section headersconst { tokenizeQuery } = await import("@/lib/search")const tokens = tokenizeQuery(text)const lines = rawIndex.split("\n")@@ -204,24 +304,13 @@ export function ChatPanel() {lastQueryPages = relevantPages.map((p) => ({ title: p.title, path: p.path }))}- // ── Conversation history with budget control ─────────────- // Keep newest messages first, drop oldest if over budget- const HISTORY_BUDGET_CHARS = llmConfig.maxContextSize- ? Math.floor(llmConfig.maxContextSize * 0.2)- : 40960- const rawMessages = useChatStore.getState().messages+ // ── Conversation history with count limit ────────────────+ // Only include messages from the active conversation, last N messages+ const activeConvMessages = useChatStore.getState().getActiveMessages().filter((m) => m.role === "user" || m.role === "assistant")- const trimmedMessages: typeof rawMessages = []- let historyChars = 0- // Iterate from newest to oldest- for (let i = rawMessages.length - 1; i >= 0; i--) {- const msg = rawMessages[i]- const msgSize = msg.content.length- if (historyChars + msgSize > HISTORY_BUDGET_CHARS) break- trimmedMessages.unshift(msg)- historyChars += msgSize- }- const llmMessages = [...systemMessages, ...chatMessagesToLLM(trimmedMessages)]+ .slice(-maxHistoryMessages)++ const llmMessages = [...systemMessages, ...chatMessagesToLLM(activeConvMessages)]const controller = new AbortController()abortRef.current = controller@@ -239,7 +328,6 @@ export function ChatPanel() {onDone: () => {finalizeStream(accumulated)abortRef.current = null- // Check if LLM marked this answer as save-worthycheckSaveWorthy(accumulated, text)},onError: (err) => {@@ -250,7 +338,7 @@ export function ChatPanel() {controller.signal,)},- [llmConfig, addMessage, setStreaming, appendStreamToken, finalizeStream],+ [llmConfig, addMessage, setStreaming, appendStreamToken, finalizeStream, createConversation, maxHistoryMessages],)const handleStop = useCallback(() => {@@ -273,48 +361,64 @@ export function ChatPanel() {}}, [project, llmConfig, setFileTree])- const hasAssistantMessages = messages.some((m) => m.role === "assistant")+ const hasAssistantMessages = activeMessages.some((m) => m.role === "assistant")const showWriteButton = mode === "ingest" && !isStreaming && hasAssistantMessagesreturn (- <div className="flex h-full flex-col">- <div- ref={scrollContainerRef}- className="flex-1 overflow-y-auto px-3 py-2"- >- <div className="flex flex-col gap-3">- {messages.map((msg) => (- <ChatMessage key={msg.id} message={msg} />- ))}- {isStreaming && <StreamingMessage content={streamingContent} />}- <div ref={bottomRef} />- </div>+ <div className="flex h-full flex-row overflow-hidden">+ <ConversationSidebar />++ <div className="flex flex-1 flex-col overflow-hidden">+ {!activeConversationId ? (+ <div className="flex flex-1 items-center justify-center text-muted-foreground">+ <div className="text-center">+ <MessageSquare className="mx-auto mb-3 h-8 w-8 opacity-30" />+ <p className="text-sm">Start a new conversation</p>+ <p className="mt-1 text-xs opacity-60">Click "New Chat" to begin</p>+ </div>+ </div>+ ) : (+ <>+ <div+ ref={scrollContainerRef}+ className="flex-1 overflow-y-auto px-3 py-2"+ >+ <div className="flex flex-col gap-3">+ {activeMessages.map((msg) => (+ <ChatMessage key={msg.id} message={msg} />+ ))}+ {isStreaming && <StreamingMessage content={streamingContent} />}+ <div ref={bottomRef} />+ </div>+ </div>++ {showWriteButton && (+ <div className="border-t px-3 py-2">+ <Button+ variant="outline"+ size="sm"+ onClick={handleWriteToWiki}+ className="w-full gap-2"+ >+ <BookOpen className="h-4 w-4" />+ Write to Wiki+ </Button>+ </div>+ )}+ </>+ )}++ <ChatInput+ onSend={handleSend}+ onStop={handleStop}+ isStreaming={isStreaming}+ placeholder={+ mode === "ingest"+ ? "Discuss the source or ask follow-up questions..."+ : "Type a message..."+ }+ /></div>-- {showWriteButton && (- <div className="border-t px-3 py-2">- <Button- variant="outline"- size="sm"- onClick={handleWriteToWiki}- className="w-full gap-2"- >- <BookOpen className="h-4 w-4" />- Write to Wiki- </Button>- </div>- )}-- <ChatInput- onSend={handleSend}- onStop={handleStop}- isStreaming={isStreaming}- placeholder={- mode === "ingest"- ? "Discuss the source or ask follow-up questions..."- : "Type a message..."- }- /></div>)}@@ -331,7 +435,6 @@ function checkSaveWorthy(response: string, question: string) {const firstLine = response.split("\n").find((l) => l.trim() && !l.startsWith("<!--"))?.replace(/^#+\s*/, "").trim() ?? "Chat answer"const title = firstLine.slice(0, 60)- // Store the content reference so the review action can save itconst contentToSave = responseconst questionText = question@@ -347,7 +450,6 @@ function checkSaveWorthy(response: string, question: string) {}function encodeContent(text: string): string {- // Use base64-like encoding to safely store content in action stringreturn btoa(encodeURIComponent(text))}diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsxindex 87ab1c36..c40063cc 100644--- a/src/components/settings/settings-view.tsx+++ b/src/components/settings/settings-view.tsx@@ -1,4 +1,5 @@import { useWikiStore } from "@/stores/wiki-store"+import { useChatStore } from "@/stores/chat-store"import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"import { Label } from "@/components/ui/label"@@ -20,12 +21,16 @@ const LANGUAGES = [{ value: "zh", label: "中文" },]+const HISTORY_OPTIONS = [2, 4, 6, 8, 10, 20]+export function SettingsView() {const { t } = useTranslation()const llmConfig = useWikiStore((s) => s.llmConfig)const setLlmConfig = useWikiStore((s) => s.setLlmConfig)const searchApiConfig = useWikiStore((s) => s.searchApiConfig)const setSearchApiConfig = useWikiStore((s) => s.setSearchApiConfig)+ const maxHistoryMessages = useChatStore((s) => s.maxHistoryMessages)+ const setMaxHistoryMessages = useChatStore((s) => s.setMaxHistoryMessages)const [provider, setProvider] = useState(llmConfig.provider)const [apiKey, setApiKey] = useState(llmConfig.apiKey)@@ -259,6 +264,35 @@ export function SettingsView() {)}</div>+ {/* Chat History section */}+ <div className="space-y-4 rounded-lg border p-4">+ <h3 className="font-semibold">Chat History</h3>+ <p className="text-xs text-muted-foreground">+ Number of previous messages included when talking to AI. More = better context but uses more tokens.+ </p>+ <div className="space-y-2">+ <Label>Max conversation messages sent to AI</Label>+ <div className="flex flex-wrap gap-2">+ {HISTORY_OPTIONS.map((n) => (+ <button+ key={n}+ onClick={() => setMaxHistoryMessages(n)}+ className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${+ maxHistoryMessages === n+ ? "border-primary bg-primary text-primary-foreground"+ : "border-border hover:bg-accent"+ }`}+ >+ {n}+ </button>+ ))}+ </div>+ <p className="text-xs text-muted-foreground">+ Currently: {maxHistoryMessages} messages ({maxHistoryMessages / 2} rounds of conversation)+ </p>+ </div>+ </div>+<Button onClick={handleSave} className="w-full">{saved ? t("settings.saved") : t("settings.save")}</Button>diff --git a/src/lib/auto-save.ts b/src/lib/auto-save.tsindex ff18841a..6281cf52 100644--- a/src/lib/auto-save.ts+++ b/src/lib/auto-save.ts@@ -18,14 +18,14 @@ export function setupAutoSave(): void {}, 1000)})- // Auto-save chat messages (debounced 2s, skip during streaming)+ // Auto-save chat conversations and messages (debounced 2s, skip during streaming)useChatStore.subscribe((state) => {if (state.isStreaming) returnif (chatTimer) clearTimeout(chatTimer)chatTimer = setTimeout(() => {const project = useWikiStore.getState().projectif (project) {- saveChatHistory(project.path, state.messages).catch(() => {})+ saveChatHistory(project.path, state.conversations, state.messages).catch(() => {})}}, 2000)})diff --git a/src/lib/persist.ts b/src/lib/persist.tsindex 06f7bf47..9bd6d698 100644--- a/src/lib/persist.ts+++ b/src/lib/persist.ts@@ -1,6 +1,6 @@import { writeFile, readFile, createDirectory } from "@/commands/fs"import type { ReviewItem } from "@/stores/review-store"-import type { DisplayMessage } from "@/stores/chat-store"+import type { DisplayMessage, Conversation } from "@/stores/chat-store"async function ensureDir(projectPath: string): Promise<void> {await createDirectory(`${projectPath}/.llm-wiki`).catch(() => {})@@ -20,18 +20,50 @@ export async function loadReviewItems(projectPath: string): Promise<ReviewItem[]}}-export async function saveChatHistory(projectPath: string, messages: DisplayMessage[]): Promise<void> {+interface PersistedChatData {+ conversations: Conversation[]+ messages: DisplayMessage[]+}++export async function saveChatHistory(+ projectPath: string,+ conversations: Conversation[],+ messages: DisplayMessage[]+): Promise<void> {await ensureDir(projectPath)- // Only save last 100 messages to keep file manageable- const toSave = messages.slice(-100)+ // Only save last 200 messages to keep file manageable+ const toSave: PersistedChatData = {+ conversations,+ messages: messages.slice(-200),+ }await writeFile(`${projectPath}/.llm-wiki/chat-history.json`, JSON.stringify(toSave, null, 2))}-export async function loadChatHistory(projectPath: string): Promise<DisplayMessage[]> {+export async function loadChatHistory(projectPath: string): Promise<PersistedChatData> {try {const content = await readFile(`${projectPath}/.llm-wiki/chat-history.json`)- return JSON.parse(content) as DisplayMessage[]+ const parsed = JSON.parse(content)++ // Backward compatibility: old format was just an array of messages+ if (Array.isArray(parsed)) {+ const legacyMessages = parsed as DisplayMessage[]+ // Migrate legacy messages into a default conversation+ const defaultConv: Conversation = {+ id: "default",+ title: "Previous Conversations",+ createdAt: legacyMessages[0]?.timestamp ?? Date.now(),+ updatedAt: legacyMessages[legacyMessages.length - 1]?.timestamp ?? Date.now(),+ }+ const migratedMessages = legacyMessages.map((m) => ({+ ...m,+ conversationId: "default",+ }))+ return { conversations: [defaultConv], messages: migratedMessages }+ }++ // New format+ return parsed as PersistedChatData} catch {- return []+ return { conversations: [], messages: [] }}}diff --git a/src/stores/chat-store.ts b/src/stores/chat-store.tsindex a6b0043f..47f988dd 100644--- a/src/stores/chat-store.ts+++ b/src/stores/chat-store.ts@@ -1,28 +1,51 @@import { create } from "zustand"import type { ChatMessage } from "@/lib/llm-client"+export interface Conversation {+ id: string+ title: string+ createdAt: number+ updatedAt: number+}+export interface DisplayMessage {id: stringrole: "user" | "assistant" | "system"content: stringtimestamp: number+ conversationId: string}interface ChatState {+ conversations: Conversation[]+ activeConversationId: string | nullmessages: DisplayMessage[]isStreaming: booleanstreamingContent: stringmode: "chat" | "ingest"ingestSource: string | null+ maxHistoryMessages: number++ // Conversation management+ createConversation: () => string+ deleteConversation: (id: string) => void+ setActiveConversation: (id: string | null) => void+ renameConversation: (id: string, title: string) => void+ // Message managementaddMessage: (role: DisplayMessage["role"], content: string) => voidsetMessages: (messages: DisplayMessage[]) => void+ setConversations: (conversations: Conversation[]) => voidsetStreaming: (streaming: boolean) => voidappendStreamToken: (token: string) => voidfinalizeStream: (content: string) => voidsetMode: (mode: ChatState["mode"]) => voidsetIngestSource: (path: string | null) => voidclearMessages: () => void+ setMaxHistoryMessages: (n: number) => void++ // Helpers+ getActiveMessages: () => DisplayMessage[]}let messageCounter = 0@@ -32,28 +55,99 @@ function nextId(): string {return String(messageCounter)}-export const useChatStore = create<ChatState>((set) => ({+function generateConversationId(): string {+ return `conv_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`+}++export const useChatStore = create<ChatState>((set, get) => ({+ conversations: [],+ activeConversationId: null,messages: [],isStreaming: false,streamingContent: "",mode: "chat",ingestSource: null,+ maxHistoryMessages: 10,- addMessage: (role, content) =>+ createConversation: () => {+ const id = generateConversationId()+ const now = Date.now()+ const newConversation: Conversation = {+ id,+ title: "New Conversation",+ createdAt: now,+ updatedAt: now,+ }+ set((state) => ({+ conversations: [newConversation, ...state.conversations],+ activeConversationId: id,+ }))+ return id+ },++ deleteConversation: (id) =>+ set((state) => {+ const remaining = state.conversations.filter((c) => c.id !== id)+ const newActiveId =+ state.activeConversationId === id+ ? (remaining[0]?.id ?? null)+ : state.activeConversationId+ return {+ conversations: remaining,+ messages: state.messages.filter((m) => m.conversationId !== id),+ activeConversationId: newActiveId,+ }+ }),++ setActiveConversation: (id) => set({ activeConversationId: id }),++ renameConversation: (id, title) =>set((state) => ({- messages: [- ...state.messages,- {- id: nextId(),- role,- content,- timestamp: Date.now(),- },- ],+ conversations: state.conversations.map((c) =>+ c.id === id ? { ...c, title, updatedAt: Date.now() } : c+ ),})),+ addMessage: (role, content) =>+ set((state) => {+ const { activeConversationId, conversations } = state+ if (!activeConversationId) return state++ const newMessage: DisplayMessage = {+ id: nextId(),+ role,+ content,+ timestamp: Date.now(),+ conversationId: activeConversationId,+ }++ // Auto-set title from first user message (first 50 chars)+ const convMessages = state.messages.filter(+ (m) => m.conversationId === activeConversationId && m.role === "user"+ )+ const updatedConversations =+ role === "user" && convMessages.length === 0+ ? conversations.map((c) =>+ c.id === activeConversationId+ ? { ...c, title: content.slice(0, 50), updatedAt: Date.now() }+ : c+ )+ : conversations.map((c) =>+ c.id === activeConversationId+ ? { ...c, updatedAt: Date.now() }+ : c+ )++ return {+ messages: [...state.messages, newMessage],+ conversations: updatedConversations,+ }+ }),+setMessages: (messages) => set({ messages }),+ setConversations: (conversations) => set({ conversations }),+setStreaming: (isStreaming) => set({ isStreaming }),appendStreamToken: (token) =>@@ -62,25 +156,53 @@ export const useChatStore = create<ChatState>((set) => ({})),finalizeStream: (content) =>- set((state) => ({- isStreaming: false,- streamingContent: "",- messages: [- ...state.messages,- {- id: nextId(),- role: "assistant" as const,- content,- timestamp: Date.now(),- },- ],- })),+ set((state) => {+ const { activeConversationId, conversations } = state+ if (!activeConversationId) {+ return {+ isStreaming: false,+ streamingContent: "",+ }+ }++ const newMessage: DisplayMessage = {+ id: nextId(),+ role: "assistant" as const,+ content,+ timestamp: Date.now(),+ conversationId: activeConversationId,+ }++ return {+ isStreaming: false,+ streamingContent: "",+ messages: [...state.messages, newMessage],+ conversations: conversations.map((c) =>+ c.id === activeConversationId+ ? { ...c, updatedAt: Date.now() }+ : c+ ),+ }+ }),setMode: (mode) => set({ mode }),setIngestSource: (ingestSource) => set({ ingestSource }),- clearMessages: () => set({ messages: [] }),+ clearMessages: () =>+ set((state) => ({+ messages: state.messages.filter(+ (m) => m.conversationId !== state.activeConversationId+ ),+ })),++ setMaxHistoryMessages: (maxHistoryMessages) => set({ maxHistoryMessages }),++ getActiveMessages: () => {+ const { messages, activeConversationId } = get()+ if (!activeConversationId) return []+ return messages.filter((m) => m.conversationId === activeConversationId)+ },}))export function chatMessagesToLLM(messages: DisplayMessage[]): ChatMessage[] {