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

feat: add smart retrieval mode

nash_su3f3cfa0bbe25
diff --git a/src-tauri/src/agent/runtime.rs b/src-tauri/src/agent/runtime.rs
index 4d784e7a..37fe13b7 100644
--- a/src-tauri/src/agent/runtime.rs
+++ b/src-tauri/src/agent/runtime.rs
@@ -22,8 +22,9 @@ use super::router::route_query;
use super::skills::{load_project_skills, AgentSkill};
use super::tools::{self, AnyTxtConfig, ToolRegistry, WebSearchConfig};
use super::types::{
- AgentChatRequest, AgentChatResponse, AgentMode, AgentReference, AgentSkillMode, AgentToolEvent,
- AgentUsage, AgentUserInputField, AgentUserInputOption, AgentUserInputRequest,
+ AgentChatRequest, AgentChatResponse, AgentMode, AgentReference, AgentRetrievalMode,
+ AgentSkillMode, AgentToolEvent, AgentUsage, AgentUserInputField, AgentUserInputOption,
+ AgentUserInputRequest,
};
use super::workspace::{agent_workspace_display, AGENT_WORKSPACE_DIR};
@@ -1341,12 +1342,14 @@ impl AgentRuntime {
let mut observations = Vec::<AgentObservation>::new();
let mut executed_retrievals = BTreeSet::<String>::new();
let mut retrieval_steps = 0usize;
+ let mut consecutive_no_gain_retrievals = 0usize;
let mut force_final_next = false;
let mut last_prompt_chars = 0usize;
let has_explicit_skills =
request.skill_mode == AgentSkillMode::Explicit && !skills.is_empty();
let max_iterations = agent_loop_iteration_budget(request.mode, has_explicit_skills);
- let retrieval_budget = agent_loop_retrieval_budget(request.mode, has_explicit_skills);
+ let retrieval_budget =
+ agent_loop_retrieval_budget(request.mode, request.retrieval_mode, has_explicit_skills);
if let Some(command) = request
.shell_command
@@ -1412,7 +1415,7 @@ impl AgentRuntime {
)
} else {
(
- build_agent_loop_system(&built_context.system),
+ build_agent_loop_system(&built_context.system, request.retrieval_mode),
build_agent_loop_user(
&built_context.user,
request,
@@ -1682,10 +1685,12 @@ impl AgentRuntime {
});
}
- if action.tool.as_deref().is_some_and(is_agent_retrieval_tool) {
+ let retrieval_tool = action.tool.as_deref().is_some_and(is_agent_retrieval_tool);
+ let evidence_count_before = smart_evidence_count(&references);
+ if retrieval_tool {
let tool = action.tool.as_deref().unwrap_or_default();
if let Ok(input) = self.agent_loop_tool_input(request, tool, &action) {
- let signature = format!("{tool}:{}", canonical_json(&input));
+ let signature = retrieval_signature(tool, &input, request.retrieval_mode);
if !executed_retrievals.insert(signature) {
observations.push(record_loop_tool_rejection(
tool,
@@ -1755,6 +1760,23 @@ impl AgentRuntime {
});
}
observations.push(observation);
+ if retrieval_tool && request.retrieval_mode == AgentRetrievalMode::Smart {
+ let evidence_count_after = smart_evidence_count(&references);
+ let latest = observations.last().expect("observation was just appended");
+ if retrieval_added_evidence(
+ &latest.tool,
+ &latest.summary,
+ evidence_count_before,
+ evidence_count_after,
+ ) {
+ consecutive_no_gain_retrievals = 0;
+ } else {
+ consecutive_no_gain_retrievals += 1;
+ if consecutive_no_gain_retrievals >= 2 {
+ force_final_next = true;
+ }
+ }
+ }
}
let answer = agent_iteration_limit_answer(max_iterations, observations.len(), &references);
@@ -2737,7 +2759,18 @@ fn agent_loop_iteration_budget(mode: AgentMode, has_skills: bool) -> usize {
}
}
-fn agent_loop_retrieval_budget(mode: AgentMode, has_explicit_skills: bool) -> usize {
+fn agent_loop_retrieval_budget(
+ mode: AgentMode,
+ retrieval_mode: AgentRetrievalMode,
+ has_explicit_skills: bool,
+) -> usize {
+ if retrieval_mode == AgentRetrievalMode::Smart {
+ return match mode {
+ AgentMode::Fast => 3,
+ AgentMode::Standard | AgentMode::LocalFirst => 4,
+ AgentMode::Deep => 6,
+ };
+ }
let base = match mode {
AgentMode::Fast => 2,
AgentMode::Standard | AgentMode::LocalFirst => 4,
@@ -2766,6 +2799,52 @@ fn canonical_json(value: &Value) -> String {
serde_json::to_string(value).unwrap_or_else(|_| value.to_string())
}
+fn retrieval_signature(tool: &str, input: &Value, mode: AgentRetrievalMode) -> String {
+ if mode != AgentRetrievalMode::Smart {
+ return format!("{tool}:{}", canonical_json(input));
+ }
+ let mut normalized = input.clone();
+ if let Some(query) = normalized.get_mut("query") {
+ if let Some(value) = query.as_str() {
+ let compact = value
+ .to_lowercase()
+ .split(|character: char| {
+ character.is_whitespace() || character.is_ascii_punctuation()
+ })
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join(" ");
+ *query = Value::String(compact);
+ }
+ }
+ format!("{tool}:{}", canonical_json(&normalized))
+}
+
+fn smart_evidence_count(references: &[AgentReference]) -> usize {
+ references
+ .iter()
+ .map(|reference| format!("{}:{}", reference.kind, reference.path))
+ .collect::<BTreeSet<_>>()
+ .len()
+}
+
+fn retrieval_added_evidence(
+ tool: &str,
+ summary: &str,
+ reference_count_before: usize,
+ reference_count_after: usize,
+) -> bool {
+ if reference_count_after > reference_count_before {
+ return true;
+ }
+ if tool == "wiki.read_page" {
+ return summary
+ .split_once('\n')
+ .is_some_and(|(_, content)| !content.trim().is_empty());
+ }
+ false
+}
+
fn should_fallback_wiki_search(
planner_unavailable_or_failed: bool,
tools: &super::types::AgentToolOptions,
@@ -2774,7 +2853,12 @@ fn should_fallback_wiki_search(
planner_unavailable_or_failed && tools.wiki && skills_empty
}
-fn build_agent_loop_system(base_system: &str) -> String {
+fn build_agent_loop_system(base_system: &str, retrieval_mode: AgentRetrievalMode) -> String {
+ let smart_retrieval = if retrieval_mode == AgentRetrievalMode::Smart {
+ "\nSmart retrieval is enabled. Treat retrieval as a bounded evidence loop: after every observation, identify only the unresolved evidence gap, then either issue one concise revised retrieval action or answer. Prefer reading/following already discovered pages before broadening the query. Do not repeat equivalent queries. Stop as soon as the available evidence supports a cited answer; optional background is not a reason to continue."
+ } else {
+ ""
+ };
format!(
"{base_system}\n\nAgent loop protocol:\n\
Return only compact JSON. Do not wrap it in markdown.\n\
@@ -2793,7 +2877,7 @@ Use tools when they are useful, then wait for the observation in the next turn b
Do not claim that a generated file exists until a workspace.write_file or shell.exec observation confirms it. In the final answer, mention only observed generated file paths.\n\
Converge quickly. Do not keep reading optional references, running optional validation, or polishing after the requested deliverable has been written. Prefer final as soon as the core user request is satisfied.\n\
Only use shell.exec when active skill instructions or the user's explicit request require command-line work after files have been written with workspace.write_file. Generated files must be written under the Agent workspace described above. Commands whose explicit file paths stay inside the Agent workspace can run without an approval prompt; commands that mention external paths, home directories, downloads, temp folders, or network URLs require approval.\n\
-Use wiki.write_page only when the user explicitly asks to create or update a wiki page. Existing pages are create-only unless allowOverwrite is explicitly justified by the user's request."
+Use wiki.write_page only when the user explicitly asks to create or update a wiki page. Existing pages are create-only unless allowOverwrite is explicitly justified by the user's request.{smart_retrieval}"
)
}
@@ -4460,12 +4544,91 @@ mod tests {
#[test]
fn retrieval_budget_expands_only_for_explicit_skill_turns() {
- assert_eq!(agent_loop_retrieval_budget(AgentMode::Fast, false), 2);
- assert_eq!(agent_loop_retrieval_budget(AgentMode::Standard, false), 4);
- assert_eq!(agent_loop_retrieval_budget(AgentMode::LocalFirst, false), 4);
- assert_eq!(agent_loop_retrieval_budget(AgentMode::Deep, false), 8);
- assert_eq!(agent_loop_retrieval_budget(AgentMode::Standard, true), 8);
- assert_eq!(agent_loop_retrieval_budget(AgentMode::Deep, true), 12);
+ assert_eq!(
+ agent_loop_retrieval_budget(AgentMode::Fast, AgentRetrievalMode::Standard, false),
+ 2
+ );
+ assert_eq!(
+ agent_loop_retrieval_budget(AgentMode::Standard, AgentRetrievalMode::Standard, false),
+ 4
+ );
+ assert_eq!(
+ agent_loop_retrieval_budget(AgentMode::LocalFirst, AgentRetrievalMode::Standard, false),
+ 4
+ );
+ assert_eq!(
+ agent_loop_retrieval_budget(AgentMode::Deep, AgentRetrievalMode::Standard, false),
+ 8
+ );
+ assert_eq!(
+ agent_loop_retrieval_budget(AgentMode::Standard, AgentRetrievalMode::Standard, true),
+ 8
+ );
+ assert_eq!(
+ agent_loop_retrieval_budget(AgentMode::Deep, AgentRetrievalMode::Standard, true),
+ 12
+ );
+ assert_eq!(
+ agent_loop_retrieval_budget(AgentMode::Standard, AgentRetrievalMode::Smart, false),
+ 4
+ );
+ assert_eq!(
+ agent_loop_retrieval_budget(AgentMode::Deep, AgentRetrievalMode::Smart, true),
+ 6
+ );
+ }
+
+ #[test]
+ fn smart_retrieval_normalizes_equivalent_query_signatures() {
+ let left = serde_json::json!({"query": "Agent, Runtime!", "topK": 5});
+ let right = serde_json::json!({"query": "agent runtime", "topK": 5});
+ assert_eq!(
+ retrieval_signature("wiki.search", &left, AgentRetrievalMode::Smart),
+ retrieval_signature("wiki.search", &right, AgentRetrievalMode::Smart),
+ );
+ assert_ne!(
+ retrieval_signature("wiki.search", &left, AgentRetrievalMode::Standard),
+ retrieval_signature("wiki.search", &right, AgentRetrievalMode::Standard),
+ );
+ }
+
+ #[test]
+ fn smart_retrieval_prompt_explains_bounded_evidence_loop() {
+ let prompt = build_agent_loop_system("base", AgentRetrievalMode::Smart);
+ assert!(prompt.contains("bounded evidence loop"));
+ assert!(prompt.contains("Do not repeat equivalent queries"));
+ assert!(
+ !build_agent_loop_system("base", AgentRetrievalMode::Standard)
+ .contains("bounded evidence loop")
+ );
+ }
+
+ #[test]
+ fn smart_retrieval_counts_page_reads_but_not_repeated_searches_as_new_evidence() {
+ assert!(retrieval_added_evidence(
+ "wiki.search",
+ "1 result(s), 1 new",
+ 0,
+ 1
+ ));
+ assert!(!retrieval_added_evidence(
+ "wiki.search",
+ "1 result(s), 0 new",
+ 1,
+ 1
+ ));
+ assert!(retrieval_added_evidence(
+ "wiki.read_page",
+ "read wiki/a.md\npage content",
+ 1,
+ 1
+ ));
+ assert!(!retrieval_added_evidence(
+ "wiki.read_page",
+ "read wiki/a.md\n",
+ 1,
+ 1
+ ));
}
#[test]
diff --git a/src-tauri/src/agent/types.rs b/src-tauri/src/agent/types.rs
index 75bb64f4..6311c85e 100644
--- a/src-tauri/src/agent/types.rs
+++ b/src-tauri/src/agent/types.rs
@@ -15,6 +15,22 @@ impl Default for AgentMode {
}
}
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum AgentRetrievalMode {
+ // Preserve the established single-pass/planner-driven retrieval behavior.
+ Standard,
+ // Let the Agent iteratively close evidence gaps under a strict retrieval
+ // budget and no-progress guard.
+ Smart,
+}
+
+impl Default for AgentRetrievalMode {
+ fn default() -> Self {
+ Self::Standard
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentToolOptions {
@@ -77,6 +93,8 @@ pub struct AgentChatRequest {
#[serde(default)]
pub mode: AgentMode,
#[serde(default)]
+ pub retrieval_mode: AgentRetrievalMode,
+ #[serde(default)]
pub tools: AgentToolOptions,
#[serde(default)]
pub top_k: Option<usize>,
@@ -125,6 +143,7 @@ impl Default for AgentChatRequest {
session_id: None,
run_id: None,
mode: AgentMode::default(),
+ retrieval_mode: AgentRetrievalMode::default(),
tools: AgentToolOptions::default(),
top_k: None,
include_content: None,
@@ -280,6 +299,7 @@ mod tests {
assert_eq!(req.session_id.as_deref(), Some("s1"));
assert!(req.run_id.is_none());
assert_eq!(req.mode, AgentMode::Standard);
+ assert_eq!(req.retrieval_mode, AgentRetrievalMode::Standard);
assert_eq!(req.top_k, Some(7));
assert_eq!(req.context_files, vec!["wiki/page.md".to_string()]);
assert_eq!(req.skill_mode, AgentSkillMode::Explicit);
@@ -294,6 +314,7 @@ mod tests {
let req: AgentChatRequest = serde_json::from_value(serde_json::json!({
"message": "hello",
"mode": "local_first",
+ "retrievalMode": "smart",
"tools": {
"wiki": false,
"web": true,
@@ -303,6 +324,7 @@ mod tests {
.unwrap();
assert_eq!(req.mode, AgentMode::LocalFirst);
+ assert_eq!(req.retrieval_mode, AgentRetrievalMode::Smart);
assert!(!req.tools.wiki);
assert!(req.tools.web);
assert!(req.tools.anytxt);
diff --git a/src/App.tsx b/src/App.tsx
index 3d5b522a..6be4e1bc 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -479,6 +479,7 @@ function App() {
useChatStore.getState().setUseWebSearch(savedChatPreferences.useWebSearch)
useChatStore.getState().setUseAnyTxtSearch(savedChatPreferences.useAnyTxtSearch)
useChatStore.getState().setAgentMode(savedChatPreferences.agentMode)
+ useChatStore.getState().setRetrievalMode(savedChatPreferences.retrievalMode)
useChatStore.getState().setDisabledSkills(savedChatPreferences.disabledSkills)
} catch {
// ignore, start fresh
diff --git a/src/components/chat/chat-input.tsx b/src/components/chat/chat-input.tsx
index 61c68396..4bce08c5 100644
--- a/src/components/chat/chat-input.tsx
+++ b/src/components/chat/chat-input.tsx
@@ -1,11 +1,11 @@
import { useEffect, useMemo, useRef, useState, useCallback } from "react"
-import { FileSearch, FileText, Globe2, ImagePlus, Send, Sparkles, Square, X } from "lucide-react"
+import { BrainCircuit, FileSearch, FileText, Globe2, ImagePlus, Send, Sparkles, Square, X } from "lucide-react"
import { useTranslation } from "react-i18next"
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-types"
+import type { ChatAgentMode, ChatRetrievalMode } from "@/lib/chat-agent-types"
import {
MAX_IMAGE_BYTES,
MAX_IMAGE_MB,
@@ -19,6 +19,7 @@ export interface ChatSendOptions {
useWebSearch: boolean
useAnyTxtSearch: boolean
agentMode: ChatAgentMode
+ retrievalMode: ChatRetrievalMode
skills: string[]
contextFiles: string[]
skillMode?: "auto" | "explicit"
@@ -27,6 +28,7 @@ export interface ChatSendOptions {
}
const AGENT_MODE_OPTIONS: ChatAgentMode[] = ["fast", "standard", "deep", "local_first"]
+const RETRIEVAL_MODE_OPTIONS: ChatRetrievalMode[] = ["standard", "smart"]
export interface ChatSkillOption {
id: string
@@ -134,6 +136,7 @@ interface ChatInputProps {
useWebSearch: boolean
useAnyTxtSearch: boolean
agentMode: ChatAgentMode
+ retrievalMode: ChatRetrievalMode
availableSkills: ChatSkillOption[]
selectedSkills: string[]
availableContextFiles: string[]
@@ -141,6 +144,7 @@ interface ChatInputProps {
onUseWebSearchChange: (enabled: boolean) => void
onUseAnyTxtSearchChange: (enabled: boolean) => void
onAgentModeChange: (mode: ChatAgentMode) => void
+ onRetrievalModeChange: (mode: ChatRetrievalMode) => void
onSelectedSkillsChange: (skills: string[]) => void
onSelectedContextFilesChange: (paths: string[]) => void
anyTxtAvailable?: boolean
@@ -155,6 +159,7 @@ export function ChatInput({
useWebSearch,
useAnyTxtSearch,
agentMode,
+ retrievalMode,
availableSkills,
selectedSkills,
availableContextFiles,
@@ -162,6 +167,7 @@ export function ChatInput({
onUseWebSearchChange,
onUseAnyTxtSearchChange,
onAgentModeChange,
+ onRetrievalModeChange,
onSelectedSkillsChange,
onSelectedContextFilesChange,
anyTxtAvailable = true,
@@ -369,6 +375,7 @@ export function ChatInput({
useWebSearch,
useAnyTxtSearch,
agentMode,
+ retrievalMode,
skills: selectedSkills,
contextFiles: selectedContextFiles,
skillMode: selectedSkills.length > 0 ? "explicit" : "auto",
@@ -380,7 +387,7 @@ export function ChatInput({
if (textareaRef.current) {
textareaRef.current.style.height = "auto"
}
- }, [agentMode, imageInputAvailable, images, isStreaming, onSend, selectedContextFiles, selectedSkills, t, useAnyTxtSearch, useWebSearch, value])
+ }, [agentMode, imageInputAvailable, images, isStreaming, onSend, retrievalMode, selectedContextFiles, selectedSkills, t, useAnyTxtSearch, useWebSearch, value])
const applySlashSkill = useCallback(
(skill: ChatSkillOption) => {
@@ -804,6 +811,36 @@ export function ChatInput({
</div>
)}
</div>
+ <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.retrievalMode")}
+ title={t("chat.retrievalModeHint")}
+ >
+ <BrainCircuit className="mx-1 h-3.5 w-3.5 text-muted-foreground" />
+ {RETRIEVAL_MODE_OPTIONS.map((retrieval) => {
+ const active = retrievalMode === retrieval
+ return (
+ <button
+ key={retrieval}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ disabled={isStreaming}
+ onClick={() => onRetrievalModeChange(retrieval)}
+ 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`}
+ >
+ {retrieval === "smart"
+ ? t("chat.retrievalModes.smart")
+ : t("chat.retrievalModes.standard")}
+ </button>
+ )
+ })}
+ </div>
<div
className="inline-flex h-7 items-center rounded-md border border-border/70 bg-muted/30 p-0.5"
role="radiogroup"
diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsx
index c5ca0c02..d57e8c38 100644
--- a/src/components/chat/chat-panel.tsx
+++ b/src/components/chat/chat-panel.tsx
@@ -443,12 +443,14 @@ export function ChatPanel() {
const useWebSearch = useChatStore((s) => s.useWebSearch)
const useAnyTxtSearch = useChatStore((s) => s.useAnyTxtSearch)
const agentMode = useChatStore((s) => s.agentMode)
+ const retrievalMode = useChatStore((s) => s.retrievalMode)
const selectedSkills = useChatStore((s) => s.selectedSkills)
const selectedContextFiles = useChatStore((s) => s.selectedContextFiles)
const disabledSkills = useChatStore((s) => s.disabledSkills)
const setUseWebSearch = useChatStore((s) => s.setUseWebSearch)
const setUseAnyTxtSearch = useChatStore((s) => s.setUseAnyTxtSearch)
const setAgentMode = useChatStore((s) => s.setAgentMode)
+ const setRetrievalMode = useChatStore((s) => s.setRetrievalMode)
const setSelectedSkills = useChatStore((s) => s.setSelectedSkills)
const setSelectedContextFiles = useChatStore((s) => s.setSelectedContextFiles)
@@ -687,6 +689,7 @@ export function ChatPanel() {
useWebSearch: useChatStore.getState().useWebSearch,
useAnyTxtSearch: useChatStore.getState().useAnyTxtSearch,
agentMode: useChatStore.getState().agentMode,
+ retrievalMode: useChatStore.getState().retrievalMode,
skills: useChatStore.getState().selectedSkills,
contextFiles: useChatStore.getState().selectedContextFiles,
skillMode: useChatStore.getState().selectedSkills.length > 0 ? "explicit" : "auto",
@@ -950,6 +953,7 @@ export function ChatPanel() {
sessionId: convId,
runId: backendRunId,
mode: sendOptions.agentMode,
+ retrievalMode: sendOptions.retrievalMode,
stream: true,
tools: {
wiki: true,
@@ -1027,6 +1031,7 @@ export function ChatPanel() {
runId: backendRunId,
persistSession: false,
mode: sendOptions.agentMode,
+ retrievalMode: sendOptions.retrievalMode,
tools: {
wiki: true,
web: sendOptions.useWebSearch,
@@ -1309,6 +1314,7 @@ export function ChatPanel() {
useWebSearch: useChatStore.getState().useWebSearch,
useAnyTxtSearch: useChatStore.getState().useAnyTxtSearch,
agentMode: useChatStore.getState().agentMode,
+ retrievalMode: useChatStore.getState().retrievalMode,
skills: useChatStore.getState().selectedSkills,
contextFiles: useChatStore.getState().selectedContextFiles,
skillMode: useChatStore.getState().selectedSkills.length > 0 ? "explicit" : "auto",
@@ -1340,6 +1346,7 @@ export function ChatPanel() {
useWebSearch: useChatStore.getState().useWebSearch,
useAnyTxtSearch: useChatStore.getState().useAnyTxtSearch,
agentMode: useChatStore.getState().agentMode,
+ retrievalMode: useChatStore.getState().retrievalMode,
skills: useChatStore.getState().selectedSkills,
contextFiles: useChatStore.getState().selectedContextFiles,
skillMode: useChatStore.getState().selectedSkills.length > 0 ? "explicit" : "auto",
@@ -1432,6 +1439,7 @@ export function ChatPanel() {
useWebSearch={useWebSearch}
useAnyTxtSearch={useAnyTxtSearch}
agentMode={agentMode}
+ retrievalMode={retrievalMode}
availableSkills={availableSkills}
selectedSkills={selectedSkills}
availableContextFiles={availableContextFiles}
@@ -1439,6 +1447,7 @@ export function ChatPanel() {
onUseWebSearchChange={setUseWebSearch}
onUseAnyTxtSearchChange={setUseAnyTxtSearch}
onAgentModeChange={setAgentMode}
+ onRetrievalModeChange={setRetrievalMode}
onSelectedSkillsChange={setSelectedSkills}
onSelectedContextFilesChange={setSelectedContextFiles}
anyTxtAvailable={anyTxtAvailable}
diff --git a/src/components/settings/sections/skills-section.tsx b/src/components/settings/sections/skills-section.tsx
index 894dd5cc..42553fb1 100644
--- a/src/components/settings/sections/skills-section.tsx
+++ b/src/components/settings/sections/skills-section.tsx
@@ -24,6 +24,7 @@ export function SkillsSection() {
const useWebSearch = useChatStore((s) => s.useWebSearch)
const useAnyTxtSearch = useChatStore((s) => s.useAnyTxtSearch)
const agentMode = useChatStore((s) => s.agentMode)
+ const retrievalMode = useChatStore((s) => s.retrievalMode)
const selectedSkills = useChatStore((s) => s.selectedSkills)
const disabledSkills = useChatStore((s) => s.disabledSkills)
const setSelectedSkills = useChatStore((s) => s.setSelectedSkills)
@@ -57,10 +58,11 @@ export function SkillsSection() {
useWebSearch,
useAnyTxtSearch,
agentMode,
+ retrievalMode,
selectedSkills: nextSelected,
disabledSkills: nextDisabled,
})
- }, [agentMode, project?.path, useAnyTxtSearch, useWebSearch])
+ }, [agentMode, project?.path, retrievalMode, useAnyTxtSearch, useWebSearch])
const scan = useCallback(async () => {
if (!project?.path) {
diff --git a/src/i18n/en.json b/src/i18n/en.json
index e71f03c0..fc15b40b 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -222,6 +222,12 @@
"agents": "Agents"
},
"agentMode": "Agent mode",
+ "retrievalMode": "Retrieval mode",
+ "retrievalModeHint": "Standard keeps the existing retrieval behavior. Smart iteratively closes evidence gaps under a strict budget.",
+ "retrievalModes": {
+ "standard": "Standard retrieval",
+ "smart": "Smart retrieval"
+ },
"agentModes": {
"fast": "Fast",
"standard": "Standard",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index a2c3251d..2f33f08b 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -222,6 +222,12 @@
"agents": "Agents"
},
"agentMode": "Agent 模式",
+ "retrievalMode": "检索模式",
+ "retrievalModeHint": "传统检索保持现有行为;智能检索会在严格预算内根据证据缺口迭代检索。",
+ "retrievalModes": {
+ "standard": "传统检索",
+ "smart": "智能检索"
+ },
"agentModes": {
"fast": "快速",
"standard": "标准",
diff --git a/src/lib/auto-save.test.ts b/src/lib/auto-save.test.ts
index 9c2d9882..77293367 100644
--- a/src/lib/auto-save.test.ts
+++ b/src/lib/auto-save.test.ts
@@ -144,6 +144,7 @@ describe("auto-save project-switch guard", () => {
useWebSearch: false,
useAnyTxtSearch: false,
agentMode: "standard",
+ retrievalMode: "standard",
selectedSkills: [],
disabledSkills: [],
})
@@ -156,6 +157,7 @@ describe("auto-save project-switch guard", () => {
useWebSearch: true,
useAnyTxtSearch: true,
agentMode: "local_first",
+ retrievalMode: "smart",
selectedSkills: ["reviewer"],
disabledSkills: [],
})
@@ -166,6 +168,7 @@ describe("auto-save project-switch guard", () => {
useWebSearch: true,
useAnyTxtSearch: true,
agentMode: "local_first",
+ retrievalMode: "smart",
selectedSkills: ["reviewer"],
disabledSkills: [],
})
diff --git a/src/lib/auto-save.ts b/src/lib/auto-save.ts
index b2ad154f..15782a74 100644
--- a/src/lib/auto-save.ts
+++ b/src/lib/auto-save.ts
@@ -42,6 +42,7 @@ export async function flushAndSuspendAutoSave(): Promise<void> {
useWebSearch: chat.useWebSearch,
useAnyTxtSearch: chat.useAnyTxtSearch,
agentMode: chat.agentMode,
+ retrievalMode: chat.retrievalMode,
selectedSkills: chat.selectedSkills,
disabledSkills: chat.disabledSkills,
}),
@@ -117,6 +118,7 @@ export function setupAutoSave(): void {
useWebSearch: state.useWebSearch,
useAnyTxtSearch: state.useAnyTxtSearch,
agentMode: state.agentMode,
+ retrievalMode: state.retrievalMode,
selectedSkills: state.selectedSkills,
disabledSkills: state.disabledSkills,
}),
diff --git a/src/lib/chat-agent-types.ts b/src/lib/chat-agent-types.ts
index e747d1fe..4b4ee426 100644
--- a/src/lib/chat-agent-types.ts
+++ b/src/lib/chat-agent-types.ts
@@ -31,6 +31,7 @@ export interface ChatAgentEvent {
}
export type ChatAgentMode = "fast" | "standard" | "deep" | "local_first"
+export type ChatRetrievalMode = "standard" | "smart"
export type ChatAgentToolName =
| "project_files"
diff --git a/src/lib/persist.integration.test.ts b/src/lib/persist.integration.test.ts
index 70fa6af0..bdfa45bb 100644
--- a/src/lib/persist.integration.test.ts
+++ b/src/lib/persist.integration.test.ts
@@ -330,6 +330,7 @@ describe("chat persistence — round-trip (new format)", () => {
useWebSearch: true,
useAnyTxtSearch: false,
agentMode: "deep",
+ retrievalMode: "smart",
selectedSkills: ["reviewer", "illustrator"],
disabledSkills: ["legacy"],
})
@@ -337,12 +338,14 @@ describe("chat persistence — round-trip (new format)", () => {
useWebSearch: true,
useAnyTxtSearch: false,
agentMode: "deep",
+ retrievalMode: "smart",
selectedSkills: ["reviewer", "illustrator"],
disabledSkills: ["legacy"],
})
const raw = await readFileRaw(`${tmp.path}/.llm-wiki/chat-preferences.json`)
expect(raw).toContain('"useWebSearch": true')
+ expect(raw).toContain('"retrievalMode": "smart"')
})
it("defaults chat search preferences to off when no file exists", async () => {
@@ -350,6 +353,7 @@ describe("chat persistence — round-trip (new format)", () => {
useWebSearch: false,
useAnyTxtSearch: false,
agentMode: "standard",
+ retrievalMode: "standard",
selectedSkills: [],
disabledSkills: [],
})
diff --git a/src/lib/persist.ts b/src/lib/persist.ts
index a9e809a3..03ea88bf 100644
--- a/src/lib/persist.ts
+++ b/src/lib/persist.ts
@@ -2,7 +2,7 @@ import { writeFile, readFile, createDirectory, listDirectory } from "@/commands/
import { normalizeReviewItems, 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-types"
+import type { ChatAgentMode, ChatRetrievalMode } from "@/lib/chat-agent-types"
import { normalizePath } from "@/lib/path-utils"
import type { FileNode } from "@/types/wiki"
@@ -52,6 +52,7 @@ export interface ChatPreferences {
useWebSearch: boolean
useAnyTxtSearch: boolean
agentMode: ChatAgentMode
+ retrievalMode: ChatRetrievalMode
selectedSkills: string[]
disabledSkills: string[]
}
@@ -258,6 +259,7 @@ export async function loadChatPreferences(projectPath: string): Promise<ChatPref
useWebSearch: parsed.useWebSearch === true,
useAnyTxtSearch: parsed.useAnyTxtSearch === true,
agentMode: normalizePersistedAgentMode(parsed.agentMode),
+ retrievalMode: normalizePersistedRetrievalMode(parsed.retrievalMode),
selectedSkills: normalizePersistedSkillList(parsed.selectedSkills),
disabledSkills: normalizePersistedSkillList(parsed.disabledSkills),
}
@@ -266,6 +268,7 @@ export async function loadChatPreferences(projectPath: string): Promise<ChatPref
useWebSearch: false,
useAnyTxtSearch: false,
agentMode: "standard",
+ retrievalMode: "standard",
selectedSkills: [],
disabledSkills: [],
}
@@ -295,3 +298,7 @@ function normalizePersistedAgentMode(value: unknown): ChatAgentMode {
return "standard"
}
}
+
+function normalizePersistedRetrievalMode(value: unknown): ChatRetrievalMode {
+ return value === "smart" ? "smart" : "standard"
+}
diff --git a/src/lib/reset-project-state.ts b/src/lib/reset-project-state.ts
index 5b310376..c5caa3fa 100644
--- a/src/lib/reset-project-state.ts
+++ b/src/lib/reset-project-state.ts
@@ -27,6 +27,7 @@ export async function resetProjectState(): Promise<void> {
useWebSearch: false,
useAnyTxtSearch: false,
agentMode: "standard",
+ retrievalMode: "standard",
selectedSkills: [],
disabledSkills: [],
})
diff --git a/src/stores/chat-store.test.ts b/src/stores/chat-store.test.ts
index bdb262bd..5b9305fa 100644
--- a/src/stores/chat-store.test.ts
+++ b/src/stores/chat-store.test.ts
@@ -14,12 +14,19 @@ describe("chat-store conversation isolation", () => {
useWebSearch: false,
useAnyTxtSearch: false,
agentMode: "standard",
+ retrievalMode: "standard",
selectedSkills: [],
selectedContextFiles: [],
disabledSkills: [],
})
})
+ it("defaults to standard retrieval and allows smart retrieval opt-in", () => {
+ expect(useChatStore.getState().retrievalMode).toBe("standard")
+ useChatStore.getState().setRetrievalMode("smart")
+ expect(useChatStore.getState().retrievalMode).toBe("smart")
+ })
+
it("writes async assistant results back to the original conversation", () => {
const store = useChatStore.getState()
const first = store.createConversation()
diff --git a/src/stores/chat-store.ts b/src/stores/chat-store.ts
index 63a8f671..881f25b9 100644
--- a/src/stores/chat-store.ts
+++ b/src/stores/chat-store.ts
@@ -1,7 +1,7 @@
import { create } from "zustand"
import type { ChatMessage, ContentBlock } from "@/lib/llm-client"
import i18n from "@/i18n"
-import type { ChatAgentFileChange, ChatAgentMode, ChatAgentStep, ChatUserInputRequest } from "@/lib/chat-agent-types"
+import type { ChatAgentFileChange, ChatAgentMode, ChatAgentStep, ChatRetrievalMode, ChatUserInputRequest } from "@/lib/chat-agent-types"
/**
* An image attached to a user message. Field names mirror the
@@ -60,6 +60,7 @@ interface ChatState {
useWebSearch: boolean
useAnyTxtSearch: boolean
agentMode: ChatAgentMode
+ retrievalMode: ChatRetrievalMode
selectedSkills: string[]
selectedContextFiles: string[]
disabledSkills: string[]
@@ -86,6 +87,7 @@ interface ChatState {
setUseWebSearch: (enabled: boolean) => void
setUseAnyTxtSearch: (enabled: boolean) => void
setAgentMode: (mode: ChatAgentMode) => void
+ setRetrievalMode: (mode: ChatRetrievalMode) => void
setSelectedSkills: (skills: string[]) => void
setSelectedContextFiles: (paths: string[]) => void
setDisabledSkills: (skills: string[]) => void
@@ -118,6 +120,7 @@ export const useChatStore = create<ChatState>((set, get) => ({
useWebSearch: false,
useAnyTxtSearch: false,
agentMode: "standard",
+ retrievalMode: "standard",
selectedSkills: [],
selectedContextFiles: [],
disabledSkills: [],
@@ -320,6 +323,8 @@ export const useChatStore = create<ChatState>((set, get) => ({
setAgentMode: (agentMode) => set({ agentMode }),
+ setRetrievalMode: (retrievalMode) => set({ retrievalMode }),
+
setSelectedSkills: (selectedSkills) =>
set((state) => ({
selectedSkills,