Skip to content

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

release: v0.5.1 agent improvements

nash_succ4b98fc33be
diff --git a/package-lock.json b/package-lock.json
index b41d7849..2b08865e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "llm-wiki",
- "version": "0.5.0",
+ "version": "0.5.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "llm-wiki",
- "version": "0.5.0",
+ "version": "0.5.1",
"dependencies": {
"@base-ui/react": "^1.3.0",
"@fontsource-variable/geist": "^5.2.8",
diff --git a/package.json b/package.json
index 019cc3bc..a16fa681 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "llm-wiki",
"private": true,
- "version": "0.5.0",
+ "version": "0.5.1",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index b6a1f454..92d61a65 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -4461,7 +4461,7 @@ checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
[[package]]
name = "llm-wiki"
-version = "0.5.0"
+version = "0.5.1"
dependencies = [
"arrow-array",
"arrow-schema",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 17e27e9d..8b3a2f1f 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "llm-wiki"
-version = "0.5.0"
+version = "0.5.1"
description = "LLM Wiki - A personal knowledge base for LLM concepts"
authors = []
edition = "2021"
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index dfe6e31b..e084607c 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "LLM Wiki",
- "version": "0.5.0",
+ "version": "0.5.1",
"identifier": "com.llmwiki.app",
"build": {
"beforeDevCommand": "npm run dev",
diff --git a/src/App.tsx b/src/App.tsx
index 3cb841ea..e151aa6b 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -437,6 +437,7 @@ function App() {
const savedChatPreferences = await loadChatPreferences(proj.path)
useChatStore.getState().setUseWebSearch(savedChatPreferences.useWebSearch)
useChatStore.getState().setUseAnyTxtSearch(savedChatPreferences.useAnyTxtSearch)
+ useChatStore.getState().setAgentMode(savedChatPreferences.agentMode)
const savedChat = await loadChatHistory(proj.path)
if (savedChat.conversations.length > 0) {
useChatStore.getState().setConversations(savedChat.conversations)
diff --git a/src/components/chat/chat-input.tsx b/src/components/chat/chat-input.tsx
index d6de2d6f..9b2995e3 100644
--- a/src/components/chat/chat-input.tsx
+++ b/src/components/chat/chat-input.tsx
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import { isImeComposing } from "@/lib/keyboard-utils"
import type { MessageImage } from "@/stores/chat-store"
+import type { ChatAgentMode } from "@/lib/chat-agent"
import {
MAX_IMAGE_BYTES,
MAX_IMAGE_MB,
@@ -17,16 +18,21 @@ import {
export interface ChatSendOptions {
useWebSearch: boolean
useAnyTxtSearch: boolean
+ agentMode: ChatAgentMode
}
+const AGENT_MODE_OPTIONS: ChatAgentMode[] = ["fast", "standard", "deep", "local_first"]
+
interface ChatInputProps {
onSend: (text: string, images: MessageImage[], options: ChatSendOptions) => void
onStop: () => void
isStreaming: boolean
useWebSearch: boolean
useAnyTxtSearch: boolean
+ agentMode: ChatAgentMode
onUseWebSearchChange: (enabled: boolean) => void
onUseAnyTxtSearchChange: (enabled: boolean) => void
+ onAgentModeChange: (mode: ChatAgentMode) => void
anyTxtAvailable?: boolean
imageInputAvailable?: boolean
placeholder?: string
@@ -38,8 +44,10 @@ export function ChatInput({
isStreaming,
useWebSearch,
useAnyTxtSearch,
+ agentMode,
onUseWebSearchChange,
onUseAnyTxtSearchChange,
+ onAgentModeChange,
anyTxtAvailable = true,
imageInputAvailable = true,
placeholder,
@@ -151,14 +159,14 @@ export function ChatInput({
setImageError(t("chat.imageInputUnavailable"))
return
}
- onSend(trimmed, images, { useWebSearch, useAnyTxtSearch })
+ onSend(trimmed, images, { useWebSearch, useAnyTxtSearch, agentMode })
setValue("")
setImages([])
setImageError(null)
if (textareaRef.current) {
textareaRef.current.style.height = "auto"
}
- }, [imageInputAvailable, images, isStreaming, onSend, t, useAnyTxtSearch, useWebSearch, value])
+ }, [agentMode, imageInputAvailable, images, isStreaming, onSend, t, useAnyTxtSearch, useWebSearch, value])
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -182,6 +190,20 @@ export function ChatInput({
: "border-transparent bg-transparent text-muted-foreground hover:bg-accent/60 hover:text-foreground"
} disabled:pointer-events-none disabled:opacity-50`
+ const agentModeLabel = (mode: ChatAgentMode) => {
+ switch (mode) {
+ case "fast":
+ return t("chat.agentModes.fast")
+ case "deep":
+ return t("chat.agentModes.deep")
+ case "local_first":
+ return t("chat.agentModes.localFirst")
+ case "standard":
+ default:
+ return t("chat.agentModes.standard")
+ }
+ }
+
return (
<div className="border-t bg-background/95 p-3">
<div className="rounded-lg border border-border/80 bg-card/80 p-2 shadow-sm ring-1 ring-black/5 focus-within:border-ring/60 focus-within:ring-ring/20 dark:ring-white/5">
@@ -296,6 +318,33 @@ export function ChatInput({
)}
</Tooltip>
</TooltipProvider>
+ <div
+ className="inline-flex h-7 items-center rounded-md border border-border/70 bg-muted/30 p-0.5"
+ role="radiogroup"
+ aria-label={t("chat.agentMode")}
+ title={t("chat.agentMode")}
+ >
+ {AGENT_MODE_OPTIONS.map((mode) => {
+ const active = agentMode === mode
+ return (
+ <button
+ key={mode}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ disabled={isStreaming}
+ onClick={() => onAgentModeChange(mode)}
+ className={`h-6 rounded px-2 text-xs font-medium transition-colors ${
+ active
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:bg-background/60 hover:text-foreground"
+ } disabled:pointer-events-none disabled:opacity-50`}
+ >
+ {agentModeLabel(mode)}
+ </button>
+ )
+ })}
+ </div>
</div>
{isStreaming ? (
<Button
diff --git a/src/components/chat/chat-message.tsx b/src/components/chat/chat-message.tsx
index 3f211ef0..4b4cb50b 100644
--- a/src/components/chat/chat-message.tsx
+++ b/src/components/chat/chat-message.tsx
@@ -30,7 +30,7 @@ import { getHtmlLang, getTextDirection } from "@/lib/language-metadata"
import { MermaidDiagram, unwrapMermaidPre } from "@/components/mermaid-diagram"
import { inferWikiTypeFromPath } from "@/lib/wiki-page-types"
import { cleanAssistantContentForWikiSave, titleFromCleanAssistantContent } from "@/lib/chat-save-to-wiki"
-import type { ChatAgentEvent, ChatAgentEventStage } from "@/lib/chat-agent"
+import type { ChatAgentEvent, ChatAgentEventStage, ChatAgentStep } from "@/lib/chat-agent"
// Module-level cache of source file names
let cachedSourceFiles: string[] = []
@@ -118,6 +118,9 @@ function ChatMessageImpl({ message, isLastAssistant, onRegenerate, onOpenReferen
))}
</div>
)}
+ {isAssistant && (
+ <SavedAgentActivity steps={message.agentSteps ?? []} />
+ )}
{(!isUser || message.content) && (
<div
className={`rounded-lg px-3 py-2 text-sm ${
@@ -161,6 +164,31 @@ function ChatMessageImpl({ message, isLastAssistant, onRegenerate, onOpenReferen
)
}
+function SavedAgentActivity({ steps }: { steps: ChatAgentStep[] }) {
+ const events = useMemo<ChatAgentEvent[]>(() => steps
+ .filter((step) => step.type !== "final")
+ .map((step) => ({
+ stage: step.type === "understanding"
+ ? "understanding"
+ : step.type === "routing"
+ ? "routing"
+ : step.type === "tool_call"
+ ? "tool_call"
+ : "tool_result",
+ tool: step.tool,
+ query: step.query,
+ message: step.message,
+ count: step.count,
+ status: step.status,
+ })), [steps])
+ if (events.length === 0) return null
+ return (
+ <div className="rounded-md border border-border/50 bg-background/50 px-2 py-1">
+ <AgentActivity events={events} compact />
+ </div>
+ )
+}
+
export const ChatMessage = memo(ChatMessageImpl, (prev, next) =>
prev.message === next.message
&& prev.isLastAssistant === next.isLastAssistant
@@ -828,7 +856,7 @@ export function StreamingMessage({ content, agentEvents = [] }: StreamingMessage
)
}
-function AgentActivity({ events }: { events: ChatAgentEvent[] }) {
+function AgentActivity({ events, compact = false }: { events: ChatAgentEvent[]; compact?: boolean }) {
const { t } = useTranslation()
const visible = events.filter((event, index, arr) => {
const prev = arr[index - 1]
@@ -841,7 +869,7 @@ function AgentActivity({ events }: { events: ChatAgentEvent[] }) {
if (visible.length === 0) return null
return (
- <div className="mb-2 flex flex-col gap-1.5 border-b border-border/40 pb-2">
+ <div className={`${compact ? "" : "mb-2 border-b border-border/40 pb-2"} flex flex-col gap-1.5`}>
{visible.map((event, index) => {
const active = index === visible.length - 1
const Icon = agentStageIcon(event.stage)
diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsx
index 5f968378..eff0dffd 100644
--- a/src/components/chat/chat-panel.tsx
+++ b/src/components/chat/chat-panel.tsx
@@ -6,7 +6,7 @@ import { ChatMessage, StreamingMessage, useSourceFiles, type ChatReferencePrevie
import { ChatInput, type ChatSendOptions } from "./chat-input"
import { useChatStore, chatMessagesToLLM, type MessageImage, type MessageReference } from "@/stores/chat-store"
import { useWikiStore } from "@/stores/wiki-store"
-import { streamChat } from "@/lib/llm-client"
+import { isReasoningOnlyResponseError, streamChat } from "@/lib/llm-client"
import { supportsImageInput } from "@/lib/llm-providers"
import { executeIngestWrites } from "@/lib/ingest"
import { listDirectory, deleteFile } from "@/commands/fs"
@@ -139,8 +139,10 @@ export function ChatPanel() {
const maxHistoryMessages = useChatStore((s) => s.maxHistoryMessages)
const useWebSearch = useChatStore((s) => s.useWebSearch)
const useAnyTxtSearch = useChatStore((s) => s.useAnyTxtSearch)
+ const agentMode = useChatStore((s) => s.agentMode)
const setUseWebSearch = useChatStore((s) => s.setUseWebSearch)
const setUseAnyTxtSearch = useChatStore((s) => s.setUseAnyTxtSearch)
+ const setAgentMode = useChatStore((s) => s.setAgentMode)
// Derive active messages via selector to re-render on message changes
const allMessages = useChatStore((s) => s.messages)
@@ -188,6 +190,7 @@ export function ChatPanel() {
const sendOptions = options ?? {
useWebSearch: useChatStore.getState().useWebSearch,
useAnyTxtSearch: useChatStore.getState().useAnyTxtSearch,
+ agentMode: useChatStore.getState().agentMode,
}
// Auto-create a conversation if none is active
let convId = useChatStore.getState().activeConversationId
@@ -250,46 +253,55 @@ export function ChatPanel() {
appendStreamToken("</think>")
}
- await streamChat(
- llmConfig,
- agentResult.messages,
- {
- onToken: (token) => {
- if (!isCurrentRun()) return
- closeReasoning()
- accumulated += token
- appendStreamToken(token)
- },
- onReasoningToken: (token) => {
- if (!isCurrentRun()) return
- appendReasoning(token)
- },
- onDone: () => {
- if (!isCurrentRun()) return
- closeReasoning()
- finalized = true
- finalizeStream(accumulated, agentResult.references)
- setAgentEvents([])
- abortRef.current = null
- // save-worthy detection removed — user has direct "Save to Wiki" button on each message
+ const streamFinalAnswer = async (reasoningOff: boolean) => {
+ let streamError: Error | null = null
+ await streamChat(
+ llmConfig,
+ agentResult.messages,
+ {
+ onToken: (token) => {
+ if (!isCurrentRun()) return
+ closeReasoning()
+ accumulated += token
+ appendStreamToken(token)
+ },
+ onReasoningToken: (token) => {
+ if (!isCurrentRun()) return
+ if (reasoningOff) return
+ appendReasoning(token)
+ },
+ onDone: () => {},
+ onError: (err) => {
+ streamError = err
+ },
},
- onError: (err) => {
- if (!isCurrentRun()) return
- if (controller.signal.aborted || isAbortLikeError(err)) {
- finalized = true
- setStreaming(false)
- setAgentEvents([])
- abortRef.current = null
- return
- }
- finalized = true
- finalizeStream(`Error: ${err.message}`, undefined)
- setAgentEvents([])
- abortRef.current = null
- },
- },
- controller.signal,
- )
+ controller.signal,
+ reasoningOff ? { reasoning: { mode: "off" } } : undefined,
+ )
+ if (streamError) throw streamError
+ }
+
+ try {
+ await streamFinalAnswer(false)
+ } catch (err) {
+ if (!isCurrentRun()) return
+ if (isReasoningOnlyResponseError(err)) {
+ accumulated = ""
+ thinkingOpen = false
+ useChatStore.setState({ streamingContent: "" })
+ await streamFinalAnswer(true)
+ } else {
+ throw err
+ }
+ }
+
+ if (!isCurrentRun()) return
+ closeReasoning()
+ finalized = true
+ finalizeStream(accumulated, agentResult.references, agentResult.steps)
+ setAgentEvents([])
+ abortRef.current = null
+ // save-worthy detection removed — user has direct "Save to Wiki" button on each message
} catch (err) {
if (!finalized) {
if (isAbortLikeError(err) || runIdRef.current !== runId) {
@@ -423,8 +435,10 @@ export function ChatPanel() {
isStreaming={isStreaming}
useWebSearch={useWebSearch}
useAnyTxtSearch={useAnyTxtSearch}
+ agentMode={agentMode}
onUseWebSearchChange={setUseWebSearch}
onUseAnyTxtSearchChange={setUseAnyTxtSearch}
+ onAgentModeChange={setAgentMode}
anyTxtAvailable={anyTxtAvailable}
imageInputAvailable={imageInputAvailable}
placeholder={
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 65eee874..ef3945f3 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -139,6 +139,13 @@
"typeAMessage": "Type a message...",
"useWebSearch": "Web search",
"useAnyTxtSearch": "AnyTXT search",
+ "agentMode": "Agent mode",
+ "agentModes": {
+ "fast": "Fast",
+ "standard": "Standard",
+ "deep": "Deep",
+ "localFirst": "Local first"
+ },
"enableAnyTxtInSettings": "Enable AnyTXT in Settings → External Information Sources",
"sendMessage": "Send message",
"stopGeneration": "Stop generation",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index f997eace..d95a1440 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -139,6 +139,13 @@
"typeAMessage": "输入消息...",
"useWebSearch": "网页搜索",
"useAnyTxtSearch": "AnyTXT 搜索",
+ "agentMode": "Agent 模式",
+ "agentModes": {
+ "fast": "快速",
+ "standard": "标准",
+ "deep": "深度",
+ "localFirst": "本地优先"
+ },
"enableAnyTxtInSettings": "请在设置 → 外部信息源中启用 AnyTXT",
"sendMessage": "发送消息",
"stopGeneration": "停止生成",
diff --git a/src/lib/auto-save.test.ts b/src/lib/auto-save.test.ts
index 9286d220..7afba98c 100644
--- a/src/lib/auto-save.test.ts
+++ b/src/lib/auto-save.test.ts
@@ -143,19 +143,21 @@ describe("auto-save project-switch guard", () => {
expect(saveChatPreferences).toHaveBeenCalledWith("/proj/A", {
useWebSearch: false,
useAnyTxtSearch: false,
+ agentMode: "standard",
})
expect(saveReviewItems).toHaveBeenCalled()
})
it("persists chat search preferences on flush", async () => {
setProjectPath("/proj/A")
- useChatStore.setState({ useWebSearch: true, useAnyTxtSearch: true })
+ useChatStore.setState({ useWebSearch: true, useAnyTxtSearch: true, agentMode: "local_first" })
await flushAndSuspendAutoSave()
expect(saveChatPreferences).toHaveBeenCalledWith("/proj/A", {
useWebSearch: true,
useAnyTxtSearch: true,
+ agentMode: "local_first",
})
})
})
diff --git a/src/lib/auto-save.ts b/src/lib/auto-save.ts
index 846e4517..e6be0b46 100644
--- a/src/lib/auto-save.ts
+++ b/src/lib/auto-save.ts
@@ -41,6 +41,7 @@ export async function flushAndSuspendAutoSave(): Promise<void> {
saveChatPreferences(projectPath, {
useWebSearch: chat.useWebSearch,
useAnyTxtSearch: chat.useAnyTxtSearch,
+ agentMode: chat.agentMode,
}),
chat.isStreaming
? Promise.resolve()
@@ -113,6 +114,7 @@ export function setupAutoSave(): void {
saveChatPreferences(projectPath, {
useWebSearch: state.useWebSearch,
useAnyTxtSearch: state.useAnyTxtSearch,
+ agentMode: state.agentMode,
}),
saveChatHistory(projectPath, state.conversations, state.messages),
]).catch(() => {})
diff --git a/src/lib/changelog.ts b/src/lib/changelog.ts
index f29f40a4..231ae7f8 100644
--- a/src/lib/changelog.ts
+++ b/src/lib/changelog.ts
@@ -25,6 +25,20 @@ export interface ChangelogEntry {
}
export const CHANGELOG: ChangelogEntry[] = [
+ {
+ version: "0.5.1",
+ date: "2026-06-24",
+ highlights: {
+ en: [
+ "Added Chat Agent modes, persisted tool progress, and project file tools for local inspection.",
+ "Improved reasoning-model handling so chat can recover when an endpoint returns thinking text but no final answer.",
+ ],
+ zh: [
+ "新增聊天 Agent 模式、持久化工具调用进度,并加入项目文件查看工具。",
+ "改进推理模型兼容性:当端点只返回思考内容而没有最终回答时,聊天会自动兜底恢复。",
+ ],
+ },
+ },
{
version: "0.5.0",
date: "2026-06-24",
diff --git a/src/lib/chat-agent.test.ts b/src/lib/chat-agent.test.ts
index b603fca8..ed780a14 100644
--- a/src/lib/chat-agent.test.ts
+++ b/src/lib/chat-agent.test.ts
@@ -11,6 +11,23 @@ import type { LlmConfig, SearchApiConfig } from "@/stores/wiki-store"
import type { ChatMessage as LLMMessage } from "@/lib/llm-client"
vi.mock("@/commands/fs", () => ({
+ listDirectory: vi.fn(async (path: string) => {
+ if (path.endsWith("/wiki")) {
+ return [
+ { name: "concepts", path: `${path}/concepts`, is_dir: true, children: [
+ { name: "attention.md", path: `${path}/concepts/attention.md`, is_dir: false },
+ { name: "transformer.md", path: `${path}/concepts/transformer.md`, is_dir: false },
+ ] },
+ { name: "index.md", path: `${path}/index.md`, is_dir: false },
+ ]
+ }
+ if (path.endsWith("/raw/sources")) {
+ return [
+ { name: "paper.pdf", path: `${path}/paper.pdf`, is_dir: false },
+ ]
+ }
+ return []
+ }),
readFile: vi.fn(async (path: string) => {
if (path.endsWith("purpose.md")) {
return "This wiki tracks transformer research."
@@ -27,6 +44,9 @@ vi.mock("@/commands/fs", () => ({
if (path.endsWith("transformer.md")) {
return "---\ntitle: Transformer\ntype: concept\n---\n# Transformer\n\nTransformers use attention layers."
}
+ if (path.endsWith("schema.md")) {
+ return "# Schema"
+ }
return ""
}),
}))
@@ -111,12 +131,26 @@ describe("chat agent routing", () => {
hasProject: false,
webSearchEnabled: true,
anyTxtSearchEnabled: false,
+ mode: "standard",
}).map((tool) => tool.name)).toEqual(["web_search"])
expect(getChatAgentTools({
hasProject: true,
webSearchEnabled: false,
anyTxtSearchEnabled: true,
- }).map((tool) => tool.name)).toEqual(["wiki_search", "graph_search", "anytxt_search"])
+ mode: "standard",
+ }).map((tool) => tool.name)).toEqual([
+ "project_files",
+ "project_file_read",
+ "wiki_search",
+ "graph_search",
+ "anytxt_search",
+ ])
+ expect(getChatAgentTools({
+ hasProject: true,
+ webSearchEnabled: true,
+ anyTxtSearchEnabled: false,
+ mode: "local_first",
+ }).map((tool) => tool.name)).not.toContain("web_search")
})
it("does not call search tools for direct greetings", async () => {
@@ -229,6 +263,83 @@ describe("chat agent routing", () => {
]))
})
+ it("disables reasoning for internal JSON controller calls", async () => {
+ const streamChat = vi.fn(async (...args: unknown[]) => {
+ const callbacks = args[2] as { onToken: (token: string) => void; onDone: () => void }
+ callbacks.onToken('{"action":"wiki_search","queries":["attention mechanism"]}')
+ callbacks.onDone()
+ })
+ const searchWiki = vi.fn(async () => [])
+
+ await buildChatAgentMessages({
+ project: { name: "Demo", path: "/tmp/project" },
+ llmConfig: { ...llmConfig, reasoning: { mode: "high" } },
+ searchApiConfig,
+ text: "What do my notes say about attention?",
+ historyMessages: [{ role: "user", content: "What do my notes say about attention?" }],
+ dataVersion: 1,
+ options: { useWebSearch: false, useAnyTxtSearch: false },
+ deps: { streamChat, searchWiki },
+ })
+
+ expect(streamChat).toHaveBeenCalled()
+ for (const call of streamChat.mock.calls as unknown[][]) {
+ expect(call[4]).toEqual(expect.objectContaining({ reasoning: { mode: "off" } }))
+ }
+ })
+
+ it("can list project files through the project_files tool", async () => {
+ const streamChat = vi.fn(async (_cfg, _messages, callbacks) => {
+ callbacks.onToken('{"action":"project_files","queries":["what files exist"]}')
+ callbacks.onDone()
+ })
+
+ const result = await buildChatAgentMessages({
+ project: { name: "Demo", path: "/tmp/project" },
+ llmConfig,
+ searchApiConfig,
+ text: "What files are in this project?",
+ historyMessages: [{ role: "user", content: "What files are in this project?" }],
+ dataVersion: 1,
+ options: { useWebSearch: false, useAnyTxtSearch: false, mode: "standard" },
+ deps: { streamChat },
+ })
+
+ expect(result.steps).toEqual(expect.arrayContaining([
+ expect.objectContaining({ type: "tool_call", tool: "project_files" }),
+ expect.objectContaining({ type: "tool_result", tool: "project_files", count: 1 }),
+ ]))
+ expect(String(result.messages[0].content)).toContain("Project file listing")
+ expect(String(result.messages[0].content)).toContain("wiki/concepts/attention.md")
+ })
+
+ it("can read a project text file by relative path", async () => {
+ const streamChat = vi.fn(async (_cfg, _messages, callbacks) => {
+ callbacks.onToken('{"action":"project_file_read","queries":["wiki/concepts/attention.md"]}')
+ callbacks.onDone()
+ })
+
+ const result = await buildChatAgentMessages({
+ project: { name: "Demo", path: "/tmp/project" },
+ llmConfig,
+ searchApiConfig,
+ text: "Read wiki/concepts/attention.md",
+ historyMessages: [{ role: "user", content: "Read wiki/concepts/attention.md" }],
+ dataVersion: 1,
+ options: { useWebSearch: false, useAnyTxtSearch: false, mode: "standard" },
+ deps: { streamChat },
+ })
+
+ expect(result.references).toEqual([
+ {
+ title: "attention.md",
+ path: "/tmp/project/wiki/concepts/attention.md",
+ kind: "wiki",
+ },
+ ])
+ expect(String(result.messages[0].content)).toContain("Attention lets models focus")
+ })
+
it("materializes graph results without double-prefixing absolute node paths", async () => {
const searchWiki = vi.fn(async () => [
{
diff --git a/src/lib/chat-agent.ts b/src/lib/chat-agent.ts
index 07a9f387..ad951558 100644
--- a/src/lib/chat-agent.ts
+++ b/src/lib/chat-agent.ts
@@ -1,4 +1,4 @@
-import { readFile } from "@/commands/fs"
+import { listDirectory, readFile } from "@/commands/fs"
import { anyTxtSearchSmart } from "@/lib/anytxt-search"
import { computeContextBudget } from "@/lib/context-budget"
import { isGreeting } from "@/lib/greeting-detector"
@@ -10,9 +10,12 @@ import { searchWiki, type SearchResult } from "@/lib/search"
import { resolveSearchConfig, webSearch, type WebSearchResult } from "@/lib/web-search"
import type { LlmConfig, SearchApiConfig } from "@/stores/wiki-store"
import type { MessageReference } from "@/stores/chat-store"
+import type { FileNode } from "@/types/wiki"
export type ChatAgentAction =
| "answer"
+ | "project_files"
+ | "project_file_read"
| "wiki_search"
| "graph_search"
| "external_search"
@@ -56,6 +59,7 @@ export interface ChatAgentProject {
export interface ChatAgentOptions {
useWebSearch: boolean
useAnyTxtSearch: boolean
+ mode?: ChatAgentMode
}
export interface ChatAgentDeps {
@@ -109,7 +113,7 @@ export interface ChatAgentResult {
}
interface ToolObservation {
- tool: "wiki_search" | "graph_search" | "external_search"
+ tool: "project_files" | "project_file_read" | "wiki_search" | "graph_search" | "external_search"
query: string
content: string
references: MessageReference[]
@@ -118,11 +122,19 @@ interface ToolObservation {
errorCount?: number
}
-export type ChatAgentToolName = "wiki_search" | "graph_search" | "web_search" | "anytxt_search"
+export type ChatAgentMode = "fast" | "standard" | "deep" | "local_first"
+
+export type ChatAgentToolName =
+ | "project_files"
+ | "project_file_read"
+ | "wiki_search"
+ | "graph_search"
+ | "web_search"
+ | "anytxt_search"
export interface ChatAgentToolDefinition {
name: ChatAgentToolName
- action: Extract<ChatAgentAction, "wiki_search" | "graph_search" | "external_search">
+ action: Extract<ChatAgentAction, "project_files" | "project_file_read" | "wiki_search" | "graph_search" | "external_search">
stage: Extract<ChatAgentEventStage, "searching_wiki" | "searching_graph" | "searching_web" | "searching_anytxt">
label: string
description: string
@@ -166,9 +178,26 @@ interface RetrievedContext {
}
const MAX_AGENT_ROUNDS = 3
+const MAX_DEEP_AGENT_ROUNDS = 5
const MAX_TOOL_CONTEXT_CHARS = 48_000
const CHAT_AGENT_TOOL_REGISTRY: ChatAgentToolDefinition[] = [
+ {
+ name: "project_files",
+ action: "project_files",
+ stage: "searching_wiki",
+ label: "Project Files",
+ description: "List project and wiki files through the same project-bound file access used by the local API/MCP tools.",
+ requiresProject: true,
+ },
+ {
+ name: "project_file_read",
+ action: "project_file_read",
+ stage: "searching_wiki",
+ label: "Project File Read",
+ description: "Read a specific project text file by relative path when the user names a file or asks to inspect one.",
+ requiresProject: true,
+ },
{
name: "wiki_search",
action: "wiki_search",
@@ -205,11 +234,13 @@ export function getChatAgentTools(args: {
hasProject: boolean
webSearchEnabled: boolean
anyTxtSearchEnabled: boolean
+ mode?: ChatAgentMode
}): ChatAgentToolDefinition[] {
return CHAT_AGENT_TOOL_REGISTRY.filter((tool) => {
if (tool.requiresProject && !args.hasProject) return false
- if (tool.name === "web_search") return args.webSearchEnabled
+ if (tool.name === "web_search") return args.webSearchEnabled && args.mode !== "local_first"
if (tool.name === "anytxt_search") return args.anyTxtSearchEnabled
+ if (tool.name === "project_file_read") return args.mode !== "fast"
return true
})
}
@@ -261,6 +292,7 @@ export async function buildChatAgentMessages(input: ChatAgentInput): Promise<Cha
hasProject: Boolean(input.project),
webSearchEnabled: input.options.useWebSearch,
anyTxtSearchEnabled: input.options.useAnyTxtSearch,
+ mode: input.options.mode ?? "standard",
})
const projectRoutingContext = input.project
? await readProjectRoutingContext(projectPath, input.text, input.llmConfig)
@@ -285,6 +317,7 @@ export async function buildChatAgentMessages(input: ChatAgentInput): Promise<Cha
projectContext: projectRoutingContext,
webSearchEnabled: input.options.useWebSearch,
anyTxtSearchEnabled: input.options.useAnyTxtSearch,
+ mode: input.options.mode ?? "standard",
tools: enabledTools,
signal: input.signal,
streamChatImpl: deps.streamChat,
@@ -308,7 +341,8 @@ export async function buildChatAgentMessages(input: ChatAgentInput): Promise<Cha
plan.push(understandingDecision)
}
- for (let round = 0; round < MAX_AGENT_ROUNDS; round++) {
+ const maxRounds = input.options.mode === "deep" ? MAX_DEEP_AGENT_ROUNDS : MAX_AGENT_ROUNDS
+ for (let round = 0; round < maxRounds; round++) {
if (plan[plan.length - 1]?.action === "answer") break
throwIfAborted(input.signal)
const observationsBefore = observations.length
@@ -326,6 +360,7 @@ export async function buildChatAgentMessages(input: ChatAgentInput): Promise<Cha
projectContext: projectRoutingContext,
webSearchEnabled: input.options.useWebSearch,
anyTxtSearchEnabled: input.options.useAnyTxtSearch,
+ mode: input.options.mode ?? "standard",
signal: input.signal,
streamChatImpl: deps.streamChat,
})
@@ -352,63 +387,101 @@ export async function buildChatAgentMessages(input: ChatAgentInput): Promise<Cha
if (executedToolKeys.has(toolKey)) break
executedToolKeys.add(toolKey)
+ if ((decision.action === "project_files" || decision.action === "multi_search") && input.project) {
+ throwIfAborted(input.signal)
+ const tool = enabledTools.find((item) => item.name === "project_files")
+ if (tool) {
+ emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
+ const observation = await runProjectFilesTool({
+ projectPath,
+ queries,
+ llmConfig: input.llmConfig,
+ })
+ observations.push(observation)
+ emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ }
+ }
+
+ if ((decision.action === "project_file_read" || decision.action === "multi_search") && input.project) {
+ throwIfAborted(input.signal)
+ const tool = enabledTools.find((item) => item.name === "project_file_read")
+ if (tool) {
+ emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
+ const observation = await runProjectFileReadTool({
+ projectPath,
+ queries,
+ llmConfig: input.llmConfig,
+ })
+ observations.push(observation)
+ emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ }
+ }
+
if ((decision.action === "wiki_search" || decision.action === "multi_search") && input.project) {
throwIfAborted(input.signal)
const tool = enabledTools.find((item) => item.name === "wiki_search")
- if (tool) emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
- const observation = await runWikiSearchTool({
- projectPath,
- queries,
- llmConfig: input.llmConfig,
- searchWikiImpl: deps.searchWiki,
- })
- observations.push(observation)
- if (tool) emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ if (tool) {
+ emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
+ const observation = await runWikiSearchTool({
+ projectPath,
+ queries,
+ llmConfig: input.llmConfig,
+ searchWikiImpl: deps.searchWiki,
+ })
+ observations.push(observation)
+ emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ }
}
if ((decision.action === "graph_search" || decision.action === "multi_search") && input.project) {
throwIfAborted(input.signal)
const tool = enabledTools.find((item) => item.name === "graph_search")
- if (tool) emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
- const observation = await runGraphSearchTool({
- projectPath,
- dataVersion: input.dataVersion,
- queries,
- llmConfig: input.llmConfig,
- searchWikiImpl: deps.searchWiki,
- })
- observations.push(observation)
- if (tool) emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ if (tool) {
+ emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
+ const observation = await runGraphSearchTool({
+ projectPath,
+ dataVersion: input.dataVersion,
+ queries,
+ llmConfig: input.llmConfig,
+ searchWikiImpl: deps.searchWiki,
+ })
+ observations.push(observation)
+ emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ }
}
if ((decision.action === "external_search" || decision.action === "multi_search") && input.options.useWebSearch) {
throwIfAborted(input.signal)
const tool = enabledTools.find((item) => item.name === "web_search")
- if (tool) emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
- const observation = await runExternalSearchTool({
- queries,
- searchConfig,
- webSearchImpl: deps.webSearch,
- source: "web",
- })
- observations.push(observation)
- if (tool) emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ if (tool) {
+ emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
+ const observation = await runExternalSearchTool({
+ queries,
+ searchConfig,
+ webSearchImpl: deps.webSearch,
+ source: "web",
+ })
+ observations.push(observation)
+ emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ }
}
if ((decision.action === "external_search" || decision.action === "multi_search") && input.options.useAnyTxtSearch) {
throwIfAborted(input.signal)
const tool = enabledTools.find((item) => item.name === "anytxt_search")
- if (tool) emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
- const observation = await runExternalSearchTool({
- queries,
- searchConfig,
- llmConfig: input.llmConfig,
- projectPath,
- anyTxtSearchSmartImpl: deps.anyTxtSearchSmart,
- source: "anytxt",
- })
- observations.push(observation)
- if (tool) emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ if (tool) {
+ emitToolCall({ tool, queries, steps, onEvent: input.onEvent })
+ const observation = await runExternalSearchTool({
+ queries,
+ searchConfig,
+ llmConfig: input.llmConfig,
+ projectPath,
+ anyTxtSearchSmartImpl: deps.anyTxtSearchSmart,
+ source: "anytxt",
+ })
+ observations.push(observation)
+ emitToolResult({ tool, observation, steps, onEvent: input.onEvent })
+ }
}
if (observations.length === observationsBefore) break
@@ -423,7 +496,11 @@ export async function buildChatAgentMessages(input: ChatAgentInput): Promise<Cha
? historicalObservations
: []
if (observations.length > 0) input.onEvent?.({ stage: "reading_context" })
- const projectContext = input.project && observationsForAnswer.some((obs) => obs.tool === "wiki_search" || obs.tool === "graph_search")
+ const projectContext = input.project && observationsForAnswer.some((obs) =>
+ obs.tool === "project_files"
+ || obs.tool === "project_file_read"
+ || obs.tool === "wiki_search"
+ || obs.tool === "graph_search")
? await readProjectPromptContext(projectPath, input.text, input.llmConfig)
: undefined
const retrievedContext = buildRetrievedContext(observationsForAnswer, input.text, input.llmConfig)
@@ -466,6 +543,7 @@ async function decideNextAction(args: {
projectContext?: ProjectPromptContext
webSearchEnabled: boolean
anyTxtSearchEnabled: boolean
+ mode: ChatAgentMode
signal?: AbortSignal
streamChatImpl: typeof streamChat
}): Promise<ChatAgentDecision> {
@@ -479,6 +557,8 @@ async function decideNextAction(args: {
"",
"Available actions:",
"- answer: answer from conversation history or general reasoning without retrieval.",
+ "- project_files: list project/wiki files when the user asks what exists, asks for project structure, or names files/pages imprecisely.",
+ "- project_file_read: read a specific project text file when the user names a path or asks to inspect a known file.",
"- wiki_search: search the local wiki when the user asks about project/wiki/docs/knowledge.",
"- graph_search: inspect relationships between entities/concepts/pages.",
"- external_search: search enabled external information sources.",
@@ -489,18 +569,22 @@ async function decideNextAction(args: {
toolDescriptions,
"",
"Return shape:",
- "{\"action\":\"answer|wiki_search|graph_search|external_search|multi_search|finish\",\"queries\":[\"short query\"],\"answer\":\"optional direct draft\",\"reason\":\"short reason\"}",
+ "{\"action\":\"answer|project_files|project_file_read|wiki_search|graph_search|external_search|multi_search|finish\",\"queries\":[\"short query or relative file path\"],\"answer\":\"optional direct draft\",\"reason\":\"short reason\"}",
"",
"Rules:",
"- Do not retrieve for greetings, casual chat, translation/rewrite/summarize/follow-up requests about prior assistant messages.",
"- Use wiki_search for questions about the local wiki, project materials, documents, notes, or remembered knowledge.",
"- Use the project overview/purpose/index below to judge whether the local wiki is likely to contain the answer.",
"- If the project overview says the current topic is in scope, prefer wiki_search or multi_search before relying only on external_search.",
+ "- Use project_files before project_file_read when the user gives a fuzzy file/page name and you need to locate likely paths.",
"- Use graph_search for relationships, dependencies, links, entities, concepts, clusters, or graph questions.",
"- If the user enabled Web Search for this turn, treat that as a strong preference to use external_search or multi_search for current facts, web pages, public docs, product/API details, news, versions, pricing, or anything likely outside the local wiki.",
"- If the user enabled AnyTXT Search for this turn, treat that as a strong preference to use external_search or multi_search when the answer may depend on external local files outside the wiki.",
"- Do not repeat external_search for simple follow-ups, summaries, rewrites, translations, or questions that can be answered from already available observations/history, unless the user explicitly asks to search again or asks for newer information.",
"- Never choose external_search if no external source is enabled.",
+ "- In local_first mode, prefer project_files, project_file_read, wiki_search, or graph_search; use external_search only when the user explicitly asks for external information.",
+ "- In fast mode, avoid multi-step file inspection; prefer answer or a single wiki_search when retrieval is clearly needed.",
+ "- In deep mode, you may use multiple tools when the question requires broader evidence.",
"- If tool observations are already enough, choose finish.",
"- Keep queries concise and keyword-rich.",
].join("\n")
@@ -528,6 +612,7 @@ async function decideNextAction(args: {
`Project: ${args.projectName ?? "none"}`,
`Local wiki available: ${args.hasProject ? "yes" : "no"}`,
`External search enabled: ${externalEnabled ? "yes" : "no"}`,
+ `Agent mode: ${args.mode}`,
`User enabled Web Search for this turn: ${args.webSearchEnabled ? "yes" : "no"}`,
`User enabled AnyTXT Search for this turn: ${args.anyTxtSearchEnabled ? "yes" : "no"}`,
`Query understanding: ${JSON.stringify(args.understanding)}`,
@@ -565,6 +650,7 @@ async function understandUserQuery(args: {
projectContext?: ProjectPromptContext
webSearchEnabled: boolean
anyTxtSearchEnabled: boolean
+ mode: ChatAgentMode
tools: ChatAgentToolDefinition[]
signal?: AbortSignal
streamChatImpl: typeof streamChat
@@ -588,6 +674,9 @@ async function understandUserQuery(args: {
"- Use graph for relationship/entity/connection questions.",
"- Use external for current facts, public docs, web pages, product/API details, versions, pricing, or local files outside the wiki when the matching external source is enabled.",
"- Use mixed when local wiki plus external sources are both useful.",
+ "- In local_first mode, set needsWiki=true for any topic plausibly covered by the project.",
+ "- In fast mode, be conservative about extra tools.",
+ "- In deep mode, prefer mixed when both local and external evidence could help.",
"- Keep each query concise and keyword-rich.",
"",
"Enabled tools:",
@@ -605,6 +694,7 @@ async function understandUserQuery(args: {
`Local wiki available: ${args.hasProject ? "yes" : "no"}`,
`Web Search enabled: ${args.webSearchEnabled ? "yes" : "no"}`,
`AnyTXT Search enabled: ${args.anyTxtSearchEnabled ? "yes" : "no"}`,
+ `Agent mode: ${args.mode}`,
`User enabled Web Search for this turn: ${args.webSearchEnabled ? "yes" : "no"}`,
`User enabled AnyTXT Search for this turn: ${args.anyTxtSearchEnabled ? "yes" : "no"}`,
"",
@@ -670,7 +760,7 @@ function fallbackUnderstanding(
const lower = query.toLowerCase()
const needsGraph = /(关系|关联|连接|图谱|依赖|relationship|related|graph|connection|linked)/i.test(query)
const needsExternal = availability.webSearchEnabled && /(latest|current|today|news|price|version|docs|api|最新|现在|今天|新闻|价格|版本|官方文档)/i.test(lower)
- const needsWiki = availability.hasProject && !needsExternal
+ const needsWiki = availability.hasProject && (!needsExternal || availability.anyTxtSearchEnabled)
const intent: ChatAgentIntent = needsGraph
? "graph"
: needsExternal && needsWiki
@@ -782,6 +872,8 @@ export function parseDecision(raw: string, fallbackQuery: string): ChatAgentDeci
function normalizeAction(action: unknown): ChatAgentAction {
switch (action) {
case "answer":
+ case "project_files":
+ case "project_file_read":
case "wiki_search":
case "graph_search":
case "external_search":
@@ -798,6 +890,108 @@ function normalizeDecisionQueries(decision: ChatAgentDecision, fallback: string)
return (queries.length > 0 ? queries : [fallback]).slice(0, 5)
}
+async function runProjectFilesTool(args: {
+ projectPath: string
+ queries: string[]
+ llmConfig: LlmConfig
+}): Promise<ToolObservation> {
+ const maxEntries = args.llmConfig.maxContextSize > 180_000 ? 160 : 80
+ const [wikiTree, rawTree] = await Promise.all([
+ listDirectory(`${args.projectPath}/wiki`).catch(() => [] as FileNode[]),
+ listDirectory(`${args.projectPath}/raw/sources`).catch(() => [] as FileNode[]),
+ ])
+ const wikiEntries = flattenFileTree(wikiTree, "wiki").slice(0, maxEntries)
+ const rawEntries = flattenFileTree(rawTree, "raw/sources").slice(0, Math.floor(maxEntries / 2))
+ const content = [
+ "# Project file listing",
+ `Query: ${args.queries.join(" | ")}`,
+ "",
+ "## Wiki files",
+ wikiEntries.length > 0 ? wikiEntries.map((entry) => `- ${entry}`).join("\n") : "(none)",
+ wikiEntries.length >= maxEntries ? "\n[...wiki listing truncated...]" : "",
+ "",
+ "## Source files",
+ rawEntries.length > 0 ? rawEntries.map((entry) => `- ${entry}`).join("\n") : "(none)",
+ rawEntries.length >= Math.floor(maxEntries / 2) ? "\n[...source listing truncated...]" : "",
+ ].filter(Boolean).join("\n")
+ const reference: MessageReference = {
+ title: "Project file listing",
+ path: `${args.projectPath}/wiki/index.md`,
+ kind: "wiki",
+ snippet: wikiEntries.slice(0, 10).join("\n"),
+ }
+ return {
+ tool: "project_files",
+ query: args.queries.join(" | "),
+ content,
+ references: [reference],
+ pages: [],
+ items: [{
+ id: "project-files",
+ kind: "wiki",
+ source: "project_files",
+ title: "Project file listing",
+ path: `${args.projectPath}/wiki/index.md`,
+ snippet: wikiEntries.slice(0, 10).join("\n"),
+ content,
+ score: 0.8,
+ query: args.queries.join(" | "),
+ reference,
+ }],
+ errorCount: 0,
+ }
+}
+
+async function runProjectFileReadTool(args: {
+ projectPath: string
+ queries: string[]
+ llmConfig: LlmConfig
+}): Promise<ToolObservation> {
+ const { maxPageSize } = computeContextBudget(args.llmConfig.maxContextSize)
+ const pages: PageEntry[] = []
+ const errors: string[] = []
+ for (const query of args.queries.slice(0, 5)) {
+ const rel = normalizeProjectRelativePath(query)
+ if (!rel || !isReadableProjectTextPath(rel)) {
+ errors.push(`Skipped unsafe or unsupported path: ${query}`)
+ continue
+ }
+ try {
+ const raw = await readFile(`${args.projectPath}/${rel}`)
+ const content = raw.length > maxPageSize
+ ? `${raw.slice(0, maxPageSize)}\n\n[...truncated...]`
+ : raw
+ pages.push({
+ title: getFileName(rel),
+ path: rel,
+ content,
+ priority: pages.length,
+ })
+ } catch (err) {
+ errors.push(`Failed to read ${rel}: ${err instanceof Error ? err.message : String(err)}`)
+ }
+ }
+ return {
+ tool: "project_file_read",
+ query: args.queries.join(" | "),
+ content: [
+ formatWikiObservation("Project file contents", pages, []),
+ errors.length > 0 ? `Errors:\n${errors.map((err) => `- ${err}`).join("\n")}` : "",
+ ].filter(Boolean).join("\n\n"),
+ references: pages.map((page) => ({ title: page.title, path: `${args.projectPath}/${page.path}`, kind: "wiki" as const })),
+ pages: pages.map((page) => ({ title: page.title, path: `${args.projectPath}/${page.path}` })),
+ items: pages.map((page) => pageToRetrievedItem({
+ projectPath: args.projectPath,
+ page,
+ query: args.queries.join(" | "),
+ kind: "wiki",
+ source: "project_file_read",
+ score: 0.95,
+ })),
+ errorCount: errors.length,
+ }
+}
+
async function readProjectRoutingContext(
projectPath: string,
query: string,
@@ -849,6 +1043,45 @@ function trimRelevantIndex(rawIndex: string, query: string, maxChars: number): s
: rawIndex.slice(0, Math.max(0, maxChars - 40)).trimEnd() + "\n[...index truncated...]"
}
+function flattenFileTree(nodes: FileNode[], prefix: string): string[] {
+ const out: string[] = []
+ const walk = (items: FileNode[], base: string) => {
+ for (const node of items) {
+ const rel = `${base}/${node.name}`.replace(/\/+/g, "/")
+ if (node.is_dir) {
+ if (node.children) walk(node.children, rel)
+ } else {
+ out.push(rel)
+ }
+ }
+ }
+ walk(nodes, prefix)
+ return out.sort((a, b) => a.localeCompare(b))
+}
+
+function normalizeProjectRelativePath(input: string): string {
+ const stripped = input
+ .trim()
+ .replace(/^["'`]+|["'`]+$/g, "")
+ .replace(/^\.\//, "")
+ const normalized = normalizePath(stripped)
+ .replace(/^\/+/, "")
+ .replace(/^.*?\/(wiki|raw\/sources)\//, "$1/")
+ if (!normalized || normalized.includes("\0")) return ""
+ if (normalized.split("/").some((part) => part === ".." || part.startsWith("."))) return ""
+ return normalized
+}
+
+function isReadableProjectTextPath(rel: string): boolean {
+ const lower = rel.toLowerCase()
+ if (!lower.startsWith("wiki/") && !lower.startsWith("raw/sources/") && lower !== "purpose.md" && lower !== "schema.md") {
+ return false
+ }
+ return /\.(md|mdx|txt|json|yaml|yml|csv|tsv|log)$/i.test(lower)
+ || lower === "purpose.md"
+ || lower === "schema.md"
+}
+
function makeStepId(steps: ChatAgentStep[]): string {
return `step-${steps.length + 1}`
}
@@ -1535,6 +1768,10 @@ async function collectChatText(
): Promise<string> {
let out = ""
let error: Error | null = null
+ const requestOverrides: Parameters<typeof streamChat>[4] = {
+ ...overrides,
+ reasoning: overrides?.reasoning ?? { mode: "off" },
+ }
await streamChatImpl(
llmConfig,
messages,
@@ -1545,7 +1782,7 @@ async function collectChatText(
onError: (err) => { error = err },
},
signal,
- overrides,
+ requestOverrides,
)
if (error) throw error
throwIfAborted(signal)
diff --git a/src/lib/llm-client.test.ts b/src/lib/llm-client.test.ts
index 8b7e02c5..91e6d865 100644
--- a/src/lib/llm-client.test.ts
+++ b/src/lib/llm-client.test.ts
@@ -9,7 +9,7 @@ vi.mock("./tauri-fetch", async () => {
return { ...actual, getHttpFetch: () => Promise.resolve(mockHttpFetch) }
})
-import { isFetchNetworkError, streamChat } from "./llm-client"
+import { isFetchNetworkError, isReasoningOnlyResponseError, streamChat } from "./llm-client"
import type { LlmConfig } from "@/stores/wiki-store"
/**
@@ -62,6 +62,15 @@ describe("isFetchNetworkError — cross-webview fetch failures", () => {
})
})
+describe("isReasoningOnlyResponseError", () => {
+ it("recognises the reasoning-only stream diagnostic", () => {
+ expect(isReasoningOnlyResponseError(
+ new Error("Model produced 2,176 characters of reasoning / chain-of-thought, but no actual response content. Try again."),
+ )).toBe(true)
+ expect(isReasoningOnlyResponseError(new Error("plain provider error"))).toBe(false)
+ })
+})
+
/**
* The streaming-path abort handling. When the 30-min backstop fires
* mid-stream the Tauri HTTP plugin tears the body stream down with a
diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.ts
index b49fc306..d8b36177 100644
--- a/src/lib/llm-client.ts
+++ b/src/lib/llm-client.ts
@@ -52,6 +52,11 @@ function isRequestCancelledError(err: unknown): boolean {
return /^request cancel(?:l)?ed$/i.test(message.trim())
}
+export function isReasoningOnlyResponseError(err: unknown): boolean {
+ const message = err instanceof Error ? err.message : String(err)
+ return /^Model produced [\d,]+ characters of reasoning \/ chain-of-thought, but no actual response content\./.test(message)
+}
+
export async function streamChat(
config: LlmConfig,
messages: import("./llm-providers").ChatMessage[],
diff --git a/src/lib/persist.integration.test.ts b/src/lib/persist.integration.test.ts
index 4dc35e87..1f7a29ba 100644
--- a/src/lib/persist.integration.test.ts
+++ b/src/lib/persist.integration.test.ts
@@ -263,10 +263,11 @@ describe("chat persistence — round-trip (new format)", () => {
})
it("round-trips chat search preferences", async () => {
- await saveChatPreferences(tmp.path, { useWebSearch: true, useAnyTxtSearch: false })
+ await saveChatPreferences(tmp.path, { useWebSearch: true, useAnyTxtSearch: false, agentMode: "deep" })
await expect(loadChatPreferences(tmp.path)).resolves.toEqual({
useWebSearch: true,
useAnyTxtSearch: false,
+ agentMode: "deep",
})
const raw = await readFileRaw(`${tmp.path}/.llm-wiki/chat-preferences.json`)
@@ -277,6 +278,7 @@ describe("chat persistence — round-trip (new format)", () => {
await expect(loadChatPreferences(tmp.path)).resolves.toEqual({
useWebSearch: false,
useAnyTxtSearch: false,
+ agentMode: "standard",
})
})
diff --git a/src/lib/persist.ts b/src/lib/persist.ts
index a3fa0456..7e4b9891 100644
--- a/src/lib/persist.ts
+++ b/src/lib/persist.ts
@@ -2,6 +2,7 @@ import { writeFile, readFile, createDirectory } from "@/commands/fs"
import type { ReviewItem } from "@/stores/review-store"
import type { LintItem } from "@/stores/lint-store"
import type { DisplayMessage, Conversation } from "@/stores/chat-store"
+import type { ChatAgentMode } from "@/lib/chat-agent"
import { normalizePath } from "@/lib/path-utils"
async function ensureDir(projectPath: string): Promise<void> {
@@ -49,6 +50,7 @@ interface PersistedChatData {
export interface ChatPreferences {
useWebSearch: boolean
useAnyTxtSearch: boolean
+ agentMode: ChatAgentMode
}
function stripPersistedMessageImages(msg: DisplayMessage): DisplayMessage {
@@ -159,8 +161,21 @@ export async function loadChatPreferences(projectPath: string): Promise<ChatPref
return {
useWebSearch: parsed.useWebSearch === true,
useAnyTxtSearch: parsed.useAnyTxtSearch === true,
+ agentMode: normalizePersistedAgentMode(parsed.agentMode),
}
} catch {
- return { useWebSearch: false, useAnyTxtSearch: false }
+ return { useWebSearch: false, useAnyTxtSearch: false, agentMode: "standard" }
+ }
+}
+
+function normalizePersistedAgentMode(value: unknown): ChatAgentMode {
+ switch (value) {
+ case "fast":
+ case "standard":
+ case "deep":
+ case "local_first":
+ return value
+ default:
+ return "standard"
}
}
diff --git a/src/lib/reset-project-state.ts b/src/lib/reset-project-state.ts
index c47d261d..d94b2fd5 100644
--- a/src/lib/reset-project-state.ts
+++ b/src/lib/reset-project-state.ts
@@ -25,6 +25,7 @@ export async function resetProjectState(): Promise<void> {
streamingContent: "",
useWebSearch: false,
useAnyTxtSearch: false,
+ agentMode: "standard",
})
useReviewStore.setState({
diff --git a/src/stores/chat-store.ts b/src/stores/chat-store.ts
index 36177996..05e406e0 100644
--- a/src/stores/chat-store.ts
+++ b/src/stores/chat-store.ts
@@ -1,6 +1,7 @@
import { create } from "zustand"
import type { ChatMessage, ContentBlock } from "@/lib/llm-client"
import i18n from "@/i18n"
+import type { ChatAgentMode, ChatAgentStep } from "@/lib/chat-agent"
/**
* An image attached to a user message. Field names mirror the
@@ -37,6 +38,7 @@ export interface DisplayMessage {
timestamp: number
conversationId: string
references?: MessageReference[] // pages cited in this response, saved at creation time
+ agentSteps?: ChatAgentStep[] // agent tool calls and routing decisions saved with assistant replies
images?: MessageImage[] // images attached to a user message (vision input)
}
@@ -51,6 +53,7 @@ interface ChatState {
maxHistoryMessages: number
useWebSearch: boolean
useAnyTxtSearch: boolean
+ agentMode: ChatAgentMode
// Conversation management
createConversation: () => string
@@ -64,13 +67,14 @@ interface ChatState {
setConversations: (conversations: Conversation[]) => void
setStreaming: (streaming: boolean) => void
appendStreamToken: (token: string) => void
- finalizeStream: (content: string, references?: MessageReference[]) => void
+ finalizeStream: (content: string, references?: MessageReference[], agentSteps?: ChatAgentStep[]) => void
setMode: (mode: ChatState["mode"]) => void
setIngestSource: (path: string | null) => void
clearMessages: () => void
setMaxHistoryMessages: (n: number) => void
setUseWebSearch: (enabled: boolean) => void
setUseAnyTxtSearch: (enabled: boolean) => void
+ setAgentMode: (mode: ChatAgentMode) => void
removeLastAssistantMessage: () => void // for regenerate: remove last assistant reply
// Helpers
@@ -99,6 +103,7 @@ export const useChatStore = create<ChatState>((set, get) => ({
maxHistoryMessages: 10,
useWebSearch: false,
useAnyTxtSearch: false,
+ agentMode: "standard",
createConversation: () => {
const id = generateConversationId()
@@ -194,7 +199,7 @@ export const useChatStore = create<ChatState>((set, get) => ({
streamingContent: state.streamingContent + token,
})),
- finalizeStream: (content, references) =>
+ finalizeStream: (content, references, agentSteps) =>
set((state) => {
const { activeConversationId, conversations } = state
if (!activeConversationId) {
@@ -211,6 +216,7 @@ export const useChatStore = create<ChatState>((set, get) => ({
timestamp: Date.now(),
conversationId: activeConversationId,
references,
+ agentSteps,
}
return {
@@ -242,6 +248,8 @@ export const useChatStore = create<ChatState>((set, get) => ({
setUseAnyTxtSearch: (useAnyTxtSearch) => set({ useAnyTxtSearch }),
+ setAgentMode: (agentMode) => set({ agentMode }),
+
removeLastAssistantMessage: () =>
set((state) => {
const activeId = state.activeConversationId