diff --git a/CHANGELOG.md b/CHANGELOG.md
index ebdd59c6..c952011d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@
## Unreleased
+- 问答页可为当前轮次选择检索模式:输入框工具栏新增与探索页一致的模式控件,默认显示将实际使用的模式及其来源(人格默认 / 信源默认 / 全局),用户选择后对后续轮次生效;付费 JEV 模式缺少 API Key 时在开始生成前拒绝并给出设置入口。回答的活动时间线显示本轮实际模式与来源。
+- 信源可设置「默认检索模式」:创建或编辑信源时选择快速、精确、JEV 精排或 SAG2 证据检索,并以通俗说明与付费提示帮助选择;JEV 模式缺少 API Key 时可在对话框内直接配置。搜索与问答在所选范围内信源一致时自动采用该默认(显式选择与 Agent 人格优先),结果 `stats.strategy_origin` 标明来源。不改变文档入库流程。
- 新增可选 SAG2 证据检索模式(`sag2`):接入 `zleap-sag2` 0.1.0,只读直搜 SQLite / PostgreSQL 关系库,BM25 召回后由 JEV 服务多轮评分,不依赖向量库,文档入库后即可检索;与 JEV 精排共用服务配置,失败不回退,首期不支持 MySQL / OceanBase。
- JEV 为付费服务:选择 JEV 精排或 SAG2 证据检索前必须填写 API Key;仅保存服务地址不再足以启用模式,连接测试也要求 Key。探索页灰置项直接给出原因与设置入口,SAG2 结果显示本次评分用量。
- 后端中文分词依赖由 `jieba-py` 改回 `jieba` 0.42.1,与 `zleap-sag2` 共用一份词典;分词结果不变。
diff --git a/README-CN.md b/README-CN.md
index ed5c662d..b5fcbc8c 100644
--- a/README-CN.md
+++ b/README-CN.md
@@ -570,7 +570,9 @@ config = EngineConfig.from_env()
这里列出的是应用/API 策略名称;应用将 `multi` 映射到 Python 引擎的 `full_expand`,将 `multi_es_fast` 映射到 `pruned_expand_rff`,`sag2` 由独立的 `zleap-sag2` 引擎执行。可用性取决于存储能力:`multi_es_fast` 与 `multi_jev` 需要词法检索支持,`sag2` 需要 SQLite 或 PostgreSQL 关系库。
-在“设置 → 知识库 → 检索”配置 302.AI、TypeSafe 官方或自定义 JEV 服务(默认 `jev-latest`,独立 API Key),再选择 **JEV 精排** 或 **SAG2 证据检索**。JEV 是付费服务:仅保存服务不会启用,选择任一 JEV 模式前必须填写 API Key。JEV 精排默认限时 30 秒、失败报错,可选择粗排降级。
+每个信源可在创建或编辑时设置**默认检索模式**;未设置则跟随全局默认。探索页与问答页的输入框都提供模式控件,可为当前查询或当前轮次临时切换。搜索与问答按“本次显式选择 → Agent 人格 → 范围内信源的共同默认 → 全局默认”解析模式,范围内信源默认不一致时按全局默认处理;结果 `stats.strategy_origin` 标明来源。该设置只影响检索,不改变文档入库流程。
+
+在“设置 → 知识库 → 检索”配置 302.AI、TypeSafe 官方或自定义 JEV 服务(默认 `jev-latest`,独立 API Key),再选择 **JEV 精排** 或 **SAG2 证据检索**;创建信源时选择 JEV 模式也可在对话框内直接完成该配置。JEV 是付费服务:仅保存服务不会启用,选择任一 JEV 模式前必须填写 API Key。JEV 精排默认限时 30 秒、失败报错,可选择粗排降级。
**SAG2 证据检索**与 JEV 精排共用同一服务配置,但不经向量库:它直接只读 SAG 的 SQLite / PostgreSQL 关系库(首期不支持 MySQL / OceanBase),文档分块入库后即可检索,不要求事件抽取完成,pgvector 单库部署也可使用。每次检索会扫描所选信源的全部段落并多轮调用 JEV,用量高于 JEV 精排;失败直接报错,不支持粗排降级。候选数、超时、并发与范围上限等调优参数见 `apps/api/.env.example` 的 `SAG_SAG2_*`。使用 PostgreSQL 时,连接用户需能在目标 schema 创建并读写 `sag2_state`、`sag2_search_sessions` 两张辅助表,并对 `sag2_state` 执行 `LOCK TABLE`;SAG 的业务表保持只读。
diff --git a/README.md b/README.md
index 2165776e..30765e46 100644
--- a/README.md
+++ b/README.md
@@ -568,7 +568,9 @@ Pipeline request and result types are available from `zleap.sag.pipeline`: `Pars
These are the application/API strategy names; the application maps `multi` to the Python engine's `full_expand` and `multi_es_fast` to `pruned_expand_rff`, while `sag2` runs on the separate `zleap-sag2` engine. Availability depends on storage capabilities: `multi_es_fast` and `multi_jev` require lexical search support; `sag2` requires a SQLite or PostgreSQL relational store.
-Configure 302.AI, TypeSafe, or a custom JEV service in **Settings → Knowledge → Retrieval** (default model: `jev-latest`, separate API key), then select **JEV reranking** or **SAG2 evidence retrieval**. JEV is a paid service: saving the service alone does not enable it, and an API key is required before either JEV mode can be selected. JEV reranking has a 30-second default deadline; failures return an error unless coarse fallback is enabled.
+Each source can carry a **default retrieval mode**, chosen when the source is created or edited; unset means follow the global default. Both the explore page and the chat composer offer a mode control for a one-off switch on the current query or turn. Search and chat resolve the mode as explicit request → agent persona → the shared default of every source in scope → global default, falling back to the global default when sources in scope disagree; `stats.strategy_origin` reports which one applied. The setting only affects retrieval and never changes document ingestion.
+
+Configure 302.AI, TypeSafe, or a custom JEV service in **Settings → Knowledge → Retrieval** (default model: `jev-latest`, separate API key), then select **JEV reranking** or **SAG2 evidence retrieval**; choosing a JEV mode while creating a source offers the same configuration inline. JEV is a paid service: saving the service alone does not enable it, and an API key is required before either JEV mode can be selected. JEV reranking has a 30-second default deadline; failures return an error unless coarse fallback is enabled.
**SAG2 evidence retrieval** shares the JEV service configuration but bypasses the vector store: it reads SAG's SQLite or PostgreSQL relational store directly (MySQL and OceanBase are not supported yet), documents become searchable as soon as they are chunked and stored, event extraction is not required, and pgvector single-database deployments can use it. Each search scans every passage of the selected sources and calls JEV over several rounds, so it costs more than JEV reranking; failures are reported as errors, with no coarse fallback. Tuning knobs for candidates, timeouts, concurrency and scope limits are documented as `SAG_SAG2_*` in `apps/api/.env.example`. On PostgreSQL the connecting role must be able to create and use the two auxiliary tables `sag2_state` and `sag2_search_sessions` in the target schema and to `LOCK TABLE` `sag2_state`; SAG's own tables stay read-only.
diff --git a/apps/api/sag_api/api/v1/agents.py b/apps/api/sag_api/api/v1/agents.py
index f7df15a5..4adebd8d 100644
--- a/apps/api/sag_api/api/v1/agents.py
+++ b/apps/api/sag_api/api/v1/agents.py
@@ -8,6 +8,7 @@
from sse_starlette.sse import EventSourceResponse
from sag_agent import AgentRuntime, EventType, RunHandle
+from sag_api.core.config import settings
from sag_api.core.db import SessionLocal, get_session
from sag_api.core.deps import (
get_agent_runtime,
@@ -351,6 +352,9 @@ async def ask(
thread = await svc.get_thread(session, agent.id, thread_id)
if not llm.configured:
raise ConfigurationError("尚未配置 LLM,无法生成回答")
+ if body.strategy is not None:
+ # 本轮显式选择的模式必须可用(付费 JEV 模式需已配置 Key);在流开始前就拒绝。
+ EngineManager.require_strategy_available(settings, body.strategy)
plan = await svc.prepare_ask(
session,
agent=agent,
@@ -359,6 +363,7 @@ async def ask(
attachments=body.attachments,
source_ids=body.source_ids,
llm=llm,
+ strategy=body.strategy,
)
web_enabled = body.effective_web_enabled
diff --git a/apps/api/sag_api/api/v1/search.py b/apps/api/sag_api/api/v1/search.py
index 78be5e6e..ee479421 100644
--- a/apps/api/sag_api/api/v1/search.py
+++ b/apps/api/sag_api/api/v1/search.py
@@ -44,6 +44,7 @@
event_scores_from_evidence,
published_document_inputs,
recall_event_scores,
+ resolve_search_strategy,
retrieve_relevant_sections,
stream_synthesize_search_answer,
synthesize_search_answer,
@@ -170,12 +171,14 @@ async def _retrieve_search_evidence(
body: SearchRequest | GlobalSearchRequest,
) -> tuple[SearchOutcome, EventScoreMap, bool]:
configuration = getattr(engine_manager, "_settings", settings)
- strategy = body.strategy or configuration.search_strategy
+ # Resolve once for the evidence-shape decision below; the retrieval service
+ # resolves the same inputs again and records where the mode came from.
+ strategy = resolve_search_strategy(requested=body.strategy, sources=sources, configuration=configuration).strategy
retrieval = retrieve_relevant_sections(
engine_manager,
sources,
body.query,
- strategy=strategy,
+ strategy=body.strategy,
top_k=body.top_k,
include_ranked_candidates=body.include_ranked_candidates,
)
diff --git a/apps/api/sag_api/core/db.py b/apps/api/sag_api/core/db.py
index d89c8f9c..7afedcf6 100644
--- a/apps/api/sag_api/core/db.py
+++ b/apps/api/sag_api/core/db.py
@@ -60,6 +60,7 @@ async def get_session() -> AsyncIterator[AsyncSession]:
# create_all 只建新表、不改旧表,故对演进列做幂等 ADD COLUMN。
_COLUMN_UPGRADES: dict[str, dict[str, str]] = {
"agents": {"is_default": "BOOLEAN NOT NULL DEFAULT FALSE"},
+ "sources": {"default_search_strategy": "VARCHAR(32)"},
"documents": {
"progress": "INTEGER NOT NULL DEFAULT 0",
"processing_stage": "VARCHAR(32)",
diff --git a/apps/api/sag_api/db/models/source.py b/apps/api/sag_api/db/models/source.py
index d917c91b..beecd7b2 100644
--- a/apps/api/sag_api/db/models/source.py
+++ b/apps/api/sag_api/db/models/source.py
@@ -33,6 +33,9 @@ class Source(IDMixin, TimestampMixin, Base):
document_count: Mapped[int] = mapped_column(Integer, default=0)
chunk_count: Mapped[int] = mapped_column(Integer, default=0)
event_count: Mapped[int] = mapped_column(Integer, default=0)
+ # 该信源的默认检索模式;None 表示跟随全局默认。搜索与问答在范围内信源一致时采用,
+ # 不改变文档入库流程。
+ default_search_strategy: Mapped[str | None] = mapped_column(String(32), nullable=True)
@hybrid_property
def is_deleting(self) -> bool:
diff --git a/apps/api/sag_api/sag/engine_manager.py b/apps/api/sag_api/sag/engine_manager.py
index cd40017d..8c612b21 100644
--- a/apps/api/sag_api/sag/engine_manager.py
+++ b/apps/api/sag_api/sag/engine_manager.py
@@ -425,12 +425,17 @@ def strategies_capability_report(cls, settings: Settings) -> dict[str, Any]:
return {"enabled": enabled, "disabled": disabled}
@classmethod
- def require_jev_capabilities(cls, settings: Settings, strategy: str = "multi_jev") -> None:
- """Reject explicit JEV-scored mode activation before publishing incompatible settings."""
+ def require_strategy_available(cls, settings: Settings, strategy: str) -> None:
+ """Reject selecting a mode the current deployment cannot serve, with its capability reason."""
unavailable = cls.strategies_capability_report(settings)["disabled"].get(strategy)
if unavailable is not None:
raise ConfigurationError(unavailable["message"], code=unavailable["reason"])
+ @classmethod
+ def require_jev_capabilities(cls, settings: Settings, strategy: str = "multi_jev") -> None:
+ """Reject explicit JEV-scored mode activation before publishing incompatible settings."""
+ cls.require_strategy_available(settings, strategy)
+
def _config_for(self, source: Source | None) -> Any:
overrides = None
if source is not None and source.config:
diff --git a/apps/api/sag_api/schemas/agent.py b/apps/api/sag_api/schemas/agent.py
index 6a2d186e..2da3c693 100644
--- a/apps/api/sag_api/schemas/agent.py
+++ b/apps/api/sag_api/schemas/agent.py
@@ -5,7 +5,7 @@
from pydantic import BaseModel, ConfigDict, Field, model_validator
-from sag_api.enums import BindingTargetType, MessageRole, MessageStatus
+from sag_api.enums import BindingTargetType, MessageRole, MessageStatus, SearchStrategy
class AgentCreate(BaseModel):
@@ -99,6 +99,8 @@ class MessagePageOut(BaseModel):
class AskRequest(BaseModel):
query: str = Field(default="", max_length=4000)
+ # 本轮检索模式;未传时按 Agent 人格 → 范围内信源共同默认 → 全局默认解析。
+ strategy: SearchStrategy | None = None
# 图片附件 id 列表(≤4,经 POST /attachments 上传)
attachments: list[str] = Field(default_factory=list, max_length=4)
# @知识库 范围限定:仅在这些信源内检索(空=默认全部)
diff --git a/apps/api/sag_api/schemas/source.py b/apps/api/sag_api/schemas/source.py
index 7bcc11dc..cd45d139 100644
--- a/apps/api/sag_api/schemas/source.py
+++ b/apps/api/sag_api/schemas/source.py
@@ -5,7 +5,7 @@
from pydantic import BaseModel, ConfigDict, Field
-from sag_api.enums import ConnectorKind, SourceStatus, SourceType
+from sag_api.enums import ConnectorKind, SearchStrategy, SourceStatus, SourceType
from sag_api.schemas.job import JobOut
@@ -22,12 +22,16 @@ class SourceCreate(BaseModel):
description: str = ""
connector_kind: ConnectorKind = ConnectorKind.FILE_UPLOAD
config: dict[str, Any] = Field(default_factory=dict)
+ # 默认检索模式;None 表示跟随全局默认。
+ default_search_strategy: SearchStrategy | None = None
class SourceUpdate(BaseModel):
name: str | None = Field(default=None, max_length=200)
description: str | None = None
status: SourceStatus | None = None
+ # 显式传 null 表示改回跟随全局默认;未出现则保持不变。
+ default_search_strategy: SearchStrategy | None = None
class SourceOut(BaseModel):
@@ -42,6 +46,7 @@ class SourceOut(BaseModel):
document_count: int
chunk_count: int
event_count: int
+ default_search_strategy: SearchStrategy | None = None
created_at: datetime
updated_at: datetime
deletion_job: JobOut | None = None
diff --git a/apps/api/sag_api/services/agent_domain.py b/apps/api/sag_api/services/agent_domain.py
index f209c9a8..4194bb4f 100644
--- a/apps/api/sag_api/services/agent_domain.py
+++ b/apps/api/sag_api/services/agent_domain.py
@@ -472,6 +472,7 @@ class AskPlan:
source_ids: list[str] | None = None # @范围:限定循环内检索工具可见的信源
source_scope: list[dict[str, str]] | None = None
user_message_id: str | None = None
+ strategy: str | None = None # 本轮显式选择的检索模式
def build_ask_context(
@@ -510,6 +511,7 @@ async def prepare_ask(
attachments: list[str] | None = None,
source_ids: list[str] | None = None,
llm=None,
+ strategy: str | None = None,
) -> AskPlan:
"""落库用户消息(含图片附件 meta)、解析历史(超上下文阈值时主动压缩),组装计划。"""
resolved: list[dict] = []
@@ -554,6 +556,7 @@ async def prepare_ask(
)
plan.user_message_id = user_msg.id
plan.source_scope = source_scope
+ plan.strategy = strategy
return plan
diff --git a/apps/api/sag_api/services/agent_service.py b/apps/api/sag_api/services/agent_service.py
index 66dbc305..f9517871 100644
--- a/apps/api/sag_api/services/agent_service.py
+++ b/apps/api/sag_api/services/agent_service.py
@@ -75,6 +75,7 @@ async def generate_stream(
sources=sources,
persona=agent.persona or {},
agent=agent,
+ requested_strategy=plan.strategy,
)
try:
diff --git a/apps/api/sag_api/services/agent_tooling.py b/apps/api/sag_api/services/agent_tooling.py
index e1706ef4..89bb68a5 100644
--- a/apps/api/sag_api/services/agent_tooling.py
+++ b/apps/api/sag_api/services/agent_tooling.py
@@ -348,8 +348,11 @@ def _adapt_tool(host_tool, host_context: HostToolContext, citations: list[dict])
from sag_api.tools.builtin import knowledge_search_strategy
configuration = getattr(host_context.engine_manager, "_settings", settings)
- strategy = knowledge_search_strategy(host_context.persona, configuration)
- # Keep this run's mode stable while the model prepares the tool call.
+ strategy = knowledge_search_strategy(
+ host_context.persona, configuration, host_context.sources, host_context.requested_strategy,
+ )
+ # Keep this run's mode stable while the model prepares the tool call; the
+ # explicit turn choice stays in requested_strategy so its origin is reported.
host_context = replace(host_context, persona={**host_context.persona, "search_strategy": strategy})
if strategy == "multi_jev":
source_count = min(len(host_context.sources), configuration.search_source_candidate_limit)
diff --git a/apps/api/sag_api/services/retrieval_service.py b/apps/api/sag_api/services/retrieval_service.py
index a28bb7c8..dcd2a9e5 100644
--- a/apps/api/sag_api/services/retrieval_service.py
+++ b/apps/api/sag_api/services/retrieval_service.py
@@ -30,6 +30,47 @@ class SearchSource(Protocol):
EventScoreMap = dict[tuple[str, str], float]
DocumentSourceScope = dict[str, tuple[str, ...]]
+StrategyOrigin = Literal["request", "persona", "source_default", "global"]
+
+
+@dataclass(frozen=True, slots=True)
+class ResolvedSearchStrategy:
+ """The mode a retrieval will run with and where that choice came from."""
+
+ strategy: str
+ origin: StrategyOrigin
+
+
+def common_source_default_strategy(sources) -> str | None:
+ """范围内每个信源都设置了同一默认模式时返回它;有信源未设置或不一致则返回 None。
+
+ 混合范围不猜测:一个信源的偏好不应改变其他信源的检索方式。
+ """
+ defaults: set[str] = set()
+ for source in sources:
+ value = getattr(source, "default_search_strategy", None)
+ if not value:
+ return None
+ defaults.add(normalize_search_strategy(str(value)))
+ return next(iter(defaults)) if len(defaults) == 1 else None
+
+
+def resolve_search_strategy(
+ *,
+ requested: str | None = None,
+ persona_strategy: str | None = None,
+ sources=(),
+ configuration: Any = settings,
+) -> ResolvedSearchStrategy:
+ """显式请求 → Agent 人格 → 范围内信源的共同默认 → 全局默认。"""
+ if requested:
+ return ResolvedSearchStrategy(requested, "request")
+ if persona_strategy:
+ return ResolvedSearchStrategy(persona_strategy, "persona")
+ common = common_source_default_strategy(sources)
+ if common:
+ return ResolvedSearchStrategy(common, "source_default")
+ return ResolvedSearchStrategy(configuration.search_strategy, "global")
def event_scores_from_evidence(sections: list[RetrievedSection]) -> EventScoreMap:
@@ -324,7 +365,8 @@ async def retrieve_relevant_sections(
total_start = time.perf_counter()
configuration = getattr(engine_manager, "_settings", settings)
- requested_strategy = strategy or configuration.search_strategy
+ resolved = resolve_search_strategy(requested=strategy, sources=sources, configuration=configuration)
+ requested_strategy = resolved.strategy
mode = normalize_search_strategy(requested_strategy)
if mode in JEV_SCORED_STRATEGIES:
# The JEV-scored profile owns recall and final scoring. Adding application
@@ -351,6 +393,7 @@ async def retrieve_relevant_sections(
return SearchOutcome(query=outcome.query or query, sections=visible_sections[:requested_limit], stats={
**outcome.stats,
"requested_strategy": requested_strategy,
+ "strategy_origin": resolved.origin,
"requested_top_k": requested_limit,
"candidate_top_k": requested_limit,
"candidates": len(outcome.sections),
@@ -416,6 +459,7 @@ def visible(section: RetrievedSection) -> bool:
stats = {
**outcome.stats,
"requested_strategy": requested_strategy,
+ "strategy_origin": resolved.origin,
"requested_top_k": requested_limit,
"candidate_top_k": candidate_limit,
"candidates": reranked.candidate_count,
diff --git a/apps/api/sag_api/services/source_service.py b/apps/api/sag_api/services/source_service.py
index 3cfc5828..5e642ca7 100644
--- a/apps/api/sag_api/services/source_service.py
+++ b/apps/api/sag_api/services/source_service.py
@@ -19,12 +19,14 @@
from sag_api.db.models import Document, Job, OctxInstallation, OctxTransfer, Source
from sag_api.enums import (
CONNECTOR_SOURCE_TYPE,
+ SEARCH_STRATEGIES,
DocumentStatus,
JobStatus,
JobType,
OctxTransferStatus,
SourceStatus,
SourceType,
+ normalize_search_strategy,
)
from sag_api.jobs import JobQueue
from sag_api.jobs.scheduling import DELETE_PRIORITY, set_scheduler
@@ -97,12 +99,28 @@ async def get_source(session: AsyncSession, source_id: str) -> Source:
return source
+def validated_default_search_strategy(value: str | None, configuration=settings) -> str | None:
+ """信源默认检索模式必须是当前部署可用的模式;JEV 付费模式还要求已保存 API Key。
+
+ 与设置页、Agent 人格使用同一能力报告,拒绝时带相同原因码供前端提示。
+ """
+ if value is None:
+ return None
+ strategy = normalize_search_strategy(str(value))
+ if strategy not in SEARCH_STRATEGIES:
+ raise ValidationError(f"不支持的检索模式:{value}")
+ EngineManager.require_strategy_available(configuration, strategy)
+ return strategy
+
+
async def create_source(
session: AsyncSession, data: SourceCreate, *, engine_manager: EngineManager
) -> Source:
connector = registry.get(data.connector_kind)
connector.validate_config(data.config)
source_type = CONNECTOR_SOURCE_TYPE.get(data.connector_kind, SourceType.DOCUMENT)
+ # 与设置页、Agent 人格一致,按全局配置单例判断模式可用性。
+ default_strategy = validated_default_search_strategy(data.default_search_strategy)
source = Source(
name=data.name,
@@ -111,6 +129,7 @@ async def create_source(
connector_kind=data.connector_kind,
sag_source_config_id=f"src_{new_id()[:16]}",
config=initialize_vector_identity_state(data.config or {}),
+ default_search_strategy=default_strategy,
)
session.add(source)
await session.commit()
@@ -146,6 +165,9 @@ async def update_source(
source.description = data.description
if data.status is not None:
source.status = data.status
+ if "default_search_strategy" in data.model_fields_set:
+ # 显式 null 表示改回跟随全局默认;只影响后续检索,不触发文档重处理。
+ source.default_search_strategy = validated_default_search_strategy(data.default_search_strategy)
await session.commit()
await session.refresh(source)
from sag_api.services.universe_service import schedule_universe_refresh
diff --git a/apps/api/sag_api/tools/base.py b/apps/api/sag_api/tools/base.py
index ecb0651f..b70c47ba 100644
--- a/apps/api/sag_api/tools/base.py
+++ b/apps/api/sag_api/tools/base.py
@@ -44,6 +44,8 @@ class ToolContext:
sources: list[Source] = field(default_factory=list)
persona: dict[str, Any] = field(default_factory=dict)
agent: Agent | None = None
+ # 本轮显式选择的检索模式;优先于人格与信源默认。
+ requested_strategy: str | None = None
# 全局证据编号偏移:循环在每次派发前设置,保证 [n] 跨轮递增不重号
citation_offset: int = 0
diff --git a/apps/api/sag_api/tools/builtin.py b/apps/api/sag_api/tools/builtin.py
index 86bd35a3..d9317a79 100644
--- a/apps/api/sag_api/tools/builtin.py
+++ b/apps/api/sag_api/tools/builtin.py
@@ -23,6 +23,7 @@
from sag_api.generation import build_citations
from sag_api.sag import RetrievedSection
from sag_api.services.retrieval_service import (
+ common_source_default_strategy,
event_scores_from_evidence,
published_document_inputs,
recall_event_scores,
@@ -79,11 +80,15 @@ def _events_by_section(events: list | None) -> dict[tuple[str, str], list]:
return grouped
-def knowledge_search_strategy(persona: dict[str, Any], configuration: Any = settings) -> str:
- """Keep the legacy vector default unless the user explicitly enables a JEV-scored mode."""
+def knowledge_search_strategy(
+ persona: dict[str, Any], configuration: Any = settings, sources=(), requested: str | None = None,
+) -> str:
+ """Explicit turn choice → persona → shared source default → legacy default (vector unless a JEV mode is global)."""
+ if requested:
+ return requested
configured = normalize_search_strategy(configuration.search_strategy)
default = configured if configured in JEV_SCORED_STRATEGIES else "vector"
- value = persona.get("search_strategy") or default
+ value = persona.get("search_strategy") or common_source_default_strategy(sources) or default
if default in JEV_SCORED_STRATEGIES and (
not isinstance(value, str) or normalize_search_strategy(value) not in SEARCH_STRATEGIES
):
@@ -95,6 +100,19 @@ def knowledge_search_strategy(persona: dict[str, Any], configuration: Any = sett
return value
+def knowledge_search_strategy_origin(
+ persona: dict[str, Any], sources=(), requested: str | None = None,
+) -> str:
+ """Which input decided ``knowledge_search_strategy``; reported to the UI as ``strategy_origin``."""
+ if requested:
+ return "request"
+ if persona.get("search_strategy"):
+ return "persona"
+ if common_source_default_strategy(sources):
+ return "source_default"
+ return "global"
+
+
def _format_sections(sections: list, offset: int = 0, events: list | None = None) -> str:
if not sections:
return "(无相关资料)"
@@ -249,7 +267,10 @@ async def invoke(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
if not query or not ctx.sources:
return ToolResult(content="(无相关资料)", citations=[], data={"section_count": 0})
persona = ctx.persona or {}
- strategy = knowledge_search_strategy(persona, getattr(ctx.engine_manager, "_settings", settings))
+ strategy = knowledge_search_strategy(
+ persona, getattr(ctx.engine_manager, "_settings", settings), ctx.sources, ctx.requested_strategy,
+ )
+ strategy_origin = knowledge_search_strategy_origin(persona, ctx.sources, ctx.requested_strategy)
top_k = args.get("top_k") or persona.get("top_k")
limit = max(1, min(int(top_k or 8), 50))
source_refs = {s.sag_source_config_id: {"id": s.id, "name": s.name} for s in ctx.sources}
@@ -338,7 +359,8 @@ async def invoke(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
"candidate_count": int(outcome.stats.get("candidates") or len(sections)),
"event_count": len(graph.events) if graph is not None else 0,
"event_candidates": len(event_scores),
- "retrieval_stats": outcome.stats,
+ # The tool passes an explicit strategy to retrieval, so restate where it came from.
+ "retrieval_stats": {**outcome.stats, "strategy_origin": strategy_origin},
"_graph": graph,
},
)
diff --git a/apps/api/tests/test_chat_turn_strategy.py b/apps/api/tests/test_chat_turn_strategy.py
new file mode 100644
index 00000000..c33e10cf
--- /dev/null
+++ b/apps/api/tests/test_chat_turn_strategy.py
@@ -0,0 +1,151 @@
+"""Per-turn retrieval mode in chat: explicit choice wins, is gated before streaming, and reports its origin."""
+
+from types import SimpleNamespace
+from uuid import uuid4
+
+import httpx
+import pytest
+
+from sag_api.core.config import Settings, settings
+from sag_api.sag import RetrievedSection, SearchOutcome, SourceGraphInfo
+from sag_api.sag.engine_manager import EngineManager
+from sag_api.schemas.agent import AskRequest
+from sag_api.tools.builtin import knowledge_search_strategy, knowledge_search_strategy_origin
+
+
+def configured(**changes) -> Settings:
+ return Settings(_env_file=None).model_copy(update={
+ "jev_endpoint": "https://jev.invalid/score",
+ "jev_api_key": "synthetic-jev-key",
+ "sag_vector_provider": "lancedb",
+ "search_strategy": "multi_es_fast",
+ **changes,
+ })
+
+
+def source(default: str | None, config_id: str = "cfg-1"):
+ return SimpleNamespace(
+ id=config_id, name=config_id, sag_source_config_id=config_id, default_search_strategy=default,
+ )
+
+
+def test_ask_request_accepts_optional_strategy():
+ assert AskRequest(query="q").strategy is None
+ assert AskRequest(query="q", strategy="sag2").strategy == "sag2"
+ with pytest.raises(ValueError):
+ AskRequest(query="q", strategy="nope")
+
+
+def test_turn_choice_precedes_persona_source_default_and_global():
+ configuration = configured(search_strategy="vector")
+ persona = {"search_strategy": "multi"}
+ scoped = [source("sag2")]
+ assert knowledge_search_strategy(persona, configuration, scoped, "multi_jev") == "multi_jev"
+ assert knowledge_search_strategy_origin(persona, scoped, "multi_jev") == "request"
+ assert knowledge_search_strategy(persona, configuration, scoped) == "multi"
+ assert knowledge_search_strategy_origin(persona, scoped) == "persona"
+ assert knowledge_search_strategy({}, configuration, scoped) == "sag2"
+ assert knowledge_search_strategy_origin({}, scoped) == "source_default"
+ assert knowledge_search_strategy({}, configuration, []) == "vector"
+ assert knowledge_search_strategy_origin({}, []) == "global"
+
+
+@pytest.mark.asyncio
+async def test_search_tool_uses_turn_choice_and_reports_origin(monkeypatch, publication_source):
+ from sag_api.services.agent_tooling import _adapt_tool
+ from sag_api.tools import builtin
+ from sag_api.tools.base import ToolContext
+
+ scoped = await publication_source("turn-choice", "cfg-1", "document-1")
+ scoped.default_search_strategy = "sag2"
+ engine = EngineManager(configured(search_strategy="multi_es_fast"))
+ calls = []
+
+ async def retrieve(manager, sources, query, *, strategy, top_k):
+ calls.append(strategy)
+ return SearchOutcome(query=query, sections=[RetrievedSection(
+ chunk_id="c1", heading="h", content="evidence", score=0.5, source_config_id="cfg-1",
+ source_id="document-1", metadata={"score_source": "jev"},
+ )], stats={"requested_strategy": strategy, "effective_strategy": strategy, "strategy_origin": "request"})
+
+ async def events(*_args, **_kwargs):
+ return {}
+
+ async def graph(*_args, **_kwargs):
+ return SourceGraphInfo(events=[])
+
+ engine.graph_for_sections = graph
+ monkeypatch.setattr(builtin, "retrieve_relevant_sections", retrieve)
+ monkeypatch.setattr(builtin, "recall_event_scores", events)
+ tool = builtin.SearchContextTool()
+
+ # The explicit turn choice overrides the persona and the source default.
+ result = await tool.invoke({"query": "q"}, ToolContext(
+ engine_manager=engine, sources=[scoped], persona={"search_strategy": "multi"}, requested_strategy="vector",
+ ))
+ assert calls[-1] == "vector"
+ assert result.data["retrieval_stats"]["strategy_origin"] == "request"
+
+ # Without a turn choice the persona wins, then the source default.
+ result = await tool.invoke({"query": "q"}, ToolContext(
+ engine_manager=engine, sources=[scoped], persona={"search_strategy": "multi"},
+ ))
+ assert calls[-1] == "multi" and result.data["retrieval_stats"]["strategy_origin"] == "persona"
+ result = await tool.invoke({"query": "q"}, ToolContext(engine_manager=engine, sources=[scoped], persona={}))
+ assert calls[-1] == "sag2" and result.data["retrieval_stats"]["strategy_origin"] == "source_default"
+
+ # The adapted tool's budget follows the turn choice as well.
+ adapted = _adapt_tool(tool, ToolContext(
+ engine_manager=engine, sources=[scoped], persona={}, requested_strategy="vector",
+ ), [])
+ assert adapted.spec.timeout_seconds is None
+
+
+@pytest.fixture
+async def chat_client(monkeypatch):
+ from sag_api.main import app
+
+ async def skip_unrelated_mcp(_factory, _app):
+ return None
+
+ monkeypatch.setattr("sag_api.runtime._RuntimeFactory.start_mcp", skip_unrelated_mcp)
+ snapshot = settings.model_dump()
+ try:
+ async with app.router.lifespan_context(app):
+ app.state.llm = SimpleNamespace(configured=True)
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as client:
+ registration = await client.post(
+ "/api/v1/auth/register",
+ json={"email": f"chat-mode-{uuid4().hex}@t.com", "password": "password123"},
+ )
+ assert registration.status_code == 201
+ client.headers["Authorization"] = f"Bearer {registration.json()['access_token']}"
+ yield client
+ finally:
+ for key, value in snapshot.items():
+ setattr(settings, key, value)
+
+
+async def test_ask_rejects_unavailable_turn_strategy_before_streaming(chat_client, monkeypatch):
+ client = chat_client
+ monkeypatch.setattr(settings, "sag_vector_provider", "lancedb")
+ monkeypatch.setattr(settings, "jev_endpoint", "https://jev.example/score")
+ monkeypatch.setattr(settings, "jev_api_key", None)
+ agent = (await client.post("/api/v1/agents", json={"name": "模式助手"})).json()
+ thread = (await client.post(f"/api/v1/agents/{agent['id']}/threads", json={})).json()
+ endpoint = f"/api/v1/agents/{agent['id']}/threads/{thread['id']}/ask"
+
+ rejected = await client.post(endpoint, json={"query": "问题", "strategy": "sag2"})
+ assert rejected.status_code == 400, rejected.text
+ assert rejected.json()["error"]["code"] == "jev_api_key_missing"
+ # Nothing was persisted for the rejected turn.
+ messages = await client.get(f"/api/v1/agents/{agent['id']}/threads/{thread['id']}/messages")
+ assert messages.status_code == 200 and messages.json()["items"] == []
+
+ unknown = await client.post(endpoint, json={"query": "问题", "strategy": "nope"})
+ assert unknown.status_code == 422
+
+ monkeypatch.setattr(settings, "sag_relational_provider", "mysql")
+ monkeypatch.setattr(settings, "jev_api_key", "synthetic-jev-key")
+ storage = await client.post(endpoint, json={"query": "问题", "strategy": "sag2"})
+ assert storage.status_code == 400 and storage.json()["error"]["code"] == "sag2_relational_unsupported"
diff --git a/apps/api/tests/test_source_default_strategy.py b/apps/api/tests/test_source_default_strategy.py
new file mode 100644
index 00000000..8b47544d
--- /dev/null
+++ b/apps/api/tests/test_source_default_strategy.py
@@ -0,0 +1,211 @@
+"""Per-source default retrieval mode: validation, persistence and resolution order."""
+
+from types import SimpleNamespace
+from uuid import uuid4
+
+import httpx
+import pytest
+
+from sag_api.core.config import Settings, settings
+from sag_api.sag import RetrievedSection, SearchOutcome
+from sag_api.sag.engine_manager import EngineManager
+from sag_api.services.retrieval_service import (
+ common_source_default_strategy,
+ resolve_search_strategy,
+ retrieve_relevant_sections,
+)
+from sag_api.tools.builtin import knowledge_search_strategy
+
+
+def configured(**changes) -> Settings:
+ return Settings(_env_file=None).model_copy(update={
+ "jev_endpoint": "https://jev.invalid/score",
+ "jev_api_key": "synthetic-jev-key",
+ "sag_vector_provider": "lancedb",
+ "search_strategy": "multi_es_fast",
+ **changes,
+ })
+
+
+def source(default: str | None, config_id: str = "cfg-1"):
+ return SimpleNamespace(
+ id=config_id, name=config_id, sag_source_config_id=config_id, default_search_strategy=default,
+ )
+
+
+@pytest.fixture
+async def source_client(monkeypatch):
+ from sag_api.main import app
+
+ async def skip_unrelated_mcp(_factory, _app):
+ return None
+
+ monkeypatch.setattr("sag_api.runtime._RuntimeFactory.start_mcp", skip_unrelated_mcp)
+ snapshot = settings.model_dump()
+ try:
+ async with app.router.lifespan_context(app):
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as client:
+ registration = await client.post(
+ "/api/v1/auth/register",
+ json={"email": f"source-mode-{uuid4().hex}@t.com", "password": "password123"},
+ )
+ assert registration.status_code == 201
+ client.headers["Authorization"] = f"Bearer {registration.json()['access_token']}"
+ yield client
+ finally:
+ for key, value in snapshot.items():
+ setattr(settings, key, value)
+
+
+def test_common_default_requires_every_source_to_agree():
+ assert common_source_default_strategy([]) is None
+ assert common_source_default_strategy([source("sag2"), source("sag2", "cfg-2")]) == "sag2"
+ assert common_source_default_strategy([source("sag2"), source(None, "cfg-2")]) is None
+ assert common_source_default_strategy([source("sag2"), source("vector", "cfg-2")]) is None
+ # Legacy aliases normalize before comparison.
+ assert common_source_default_strategy([source("atomic"), source("multi", "cfg-2")]) == "multi"
+
+
+def test_resolution_order_request_persona_source_global():
+ configuration = configured(search_strategy="vector")
+ scoped = [source("sag2"), source("sag2", "cfg-2")]
+
+ def resolved(**kwargs):
+ result = resolve_search_strategy(configuration=configuration, **kwargs)
+ return result.strategy, result.origin
+
+ assert resolved(requested="multi", persona_strategy="multi_jev", sources=scoped) == ("multi", "request")
+ assert resolved(persona_strategy="multi_jev", sources=scoped) == ("multi_jev", "persona")
+ assert resolved(sources=scoped) == ("sag2", "source_default")
+ assert resolved(sources=[source("sag2"), source(None, "cfg-2")]) == ("vector", "global")
+ assert resolved() == ("vector", "global")
+
+
+def test_agent_tool_follows_source_default_before_legacy_vector():
+ configuration = configured(search_strategy="multi_es_fast")
+ assert knowledge_search_strategy({}, configuration, [source("sag2")]) == "sag2"
+ assert knowledge_search_strategy({"search_strategy": "vector"}, configuration, [source("sag2")]) == "vector"
+ assert knowledge_search_strategy({}, configuration, [source("sag2"), source(None, "cfg-2")]) == "vector"
+ # A global JEV default still wins over an unknown legacy persona value, as before.
+ assert knowledge_search_strategy({"search_strategy": "retired"}, configured(search_strategy="sag2"), []) == "sag2"
+
+
+@pytest.mark.asyncio
+async def test_retrieval_reports_source_default_origin(monkeypatch):
+ from sag_api.services import retrieval_service
+
+ captured = []
+
+ class Engine:
+ _settings = configured(search_strategy="vector")
+
+ async def search_many(self, targets, query, **kwargs):
+ captured.append(kwargs["strategy"])
+ return SearchOutcome(query=query, sections=[RetrievedSection(
+ chunk_id="c1", heading="h", content="evidence", score=0.9, source_config_id="cfg-1", source_id="d1",
+ metadata={"score_source": "jev"},
+ )], stats={"effective_strategy": "sag2"})
+
+ async def published(sources, **_kwargs):
+ return {s.sag_source_config_id: ("d1",) for s in sources}
+
+ monkeypatch.setattr(retrieval_service, "published_document_inputs", published)
+ outcome = await retrieve_relevant_sections(Engine(), [source("sag2")], "q", top_k=3)
+ assert captured == ["sag2"]
+ assert outcome.stats["requested_strategy"] == "sag2"
+ assert outcome.stats["strategy_origin"] == "source_default"
+
+ outcome = await retrieve_relevant_sections(Engine(), [source("sag2")], "q", strategy="multi_jev", top_k=3)
+ assert captured[-1] == "multi_jev"
+ assert outcome.stats["strategy_origin"] == "request"
+
+
+async def test_source_default_mode_is_validated_persisted_and_clearable(source_client, monkeypatch):
+ client = source_client
+ monkeypatch.setattr(settings, "sag_vector_provider", "lancedb")
+ monkeypatch.setattr(settings, "jev_endpoint", "https://jev.example/score")
+ monkeypatch.setattr(settings, "jev_api_key", None)
+ before = {item["id"] for item in (await client.get("/api/v1/sources")).json()}
+
+ # Paid mode without a key is rejected before any row is written.
+ rejected = await client.post("/api/v1/sources", json={"name": "SAG2 库", "default_search_strategy": "sag2"})
+ assert rejected.status_code == 400, rejected.text
+ assert rejected.json()["error"]["code"] == "jev_api_key_missing"
+ assert {item["id"] for item in (await client.get("/api/v1/sources")).json()} == before
+
+ unknown = await client.post("/api/v1/sources", json={"name": "x", "default_search_strategy": "nope"})
+ assert unknown.status_code == 422
+
+ monkeypatch.setattr(settings, "jev_api_key", "synthetic-jev-key")
+ created = await client.post("/api/v1/sources", json={"name": "SAG2 库", "default_search_strategy": "sag2"})
+ assert created.status_code == 201, created.text
+ body = created.json()
+ assert body["default_search_strategy"] == "sag2"
+ source_id = body["id"]
+ assert (await client.get(f"/api/v1/sources/{source_id}")).json()["default_search_strategy"] == "sag2"
+
+ # Follow-global is the default when the field is omitted.
+ plain = await client.post("/api/v1/sources", json={"name": "普通库"})
+ assert plain.status_code == 201 and plain.json()["default_search_strategy"] is None
+
+ # Updates: a mode the storage cannot serve is rejected; null clears back to global.
+ monkeypatch.setattr(settings, "sag_vector_provider", "pgvector")
+ blocked = await client.patch(f"/api/v1/sources/{source_id}", json={"default_search_strategy": "multi_jev"})
+ assert blocked.status_code == 400 and blocked.json()["error"]["code"] == "vector_provider_lacks_lexical"
+ assert (await client.get(f"/api/v1/sources/{source_id}")).json()["default_search_strategy"] == "sag2"
+ renamed = await client.patch(f"/api/v1/sources/{source_id}", json={"name": "改名"})
+ assert renamed.status_code == 200 and renamed.json()["default_search_strategy"] == "sag2"
+ cleared = await client.patch(f"/api/v1/sources/{source_id}", json={"default_search_strategy": None})
+ assert cleared.status_code == 200, cleared.text
+ assert cleared.json()["default_search_strategy"] is None
+ assert cleared.json()["name"] == "改名"
+ # Sources are left in place: a background delete job would still be writing
+ # while the app shuts down and contend for the SQLite lock at teardown.
+
+
+async def test_global_search_uses_shared_source_default(source_client, monkeypatch):
+ from sag_api.core.deps import get_engine_manager
+ from sag_api.main import app
+
+ client = source_client
+ monkeypatch.setattr(settings, "sag_vector_provider", "lancedb")
+ monkeypatch.setattr(settings, "search_strategy", "vector")
+ monkeypatch.setattr(settings, "jev_endpoint", "https://jev.example/score")
+ monkeypatch.setattr(settings, "jev_api_key", "synthetic-jev-key")
+ created = await client.post("/api/v1/sources", json={"name": "SAG2 库", "default_search_strategy": "sag2"})
+ assert created.status_code == 201, created.text
+ source_id = created.json()["id"]
+ seen = []
+
+ class StubEngine:
+ _settings = settings
+
+ async def search_many(self, targets, query, **kwargs):
+ seen.append(kwargs.get("strategy"))
+ return SearchOutcome(query=query, sections=[], stats={"effective_strategy": kwargs.get("strategy")})
+
+ async def grep_chunks(self, *args, **kwargs):
+ return []
+
+ app.dependency_overrides[get_engine_manager] = lambda: StubEngine()
+ try:
+ scoped = await client.post("/api/v1/search", json={"query": "q", "source_ids": [source_id]})
+ assert scoped.status_code == 200, scoped.text
+ assert seen[-1] == "sag2"
+ assert scoped.json()["stats"]["strategy_origin"] == "source_default"
+
+ explicit = await client.post(
+ "/api/v1/search", json={"query": "q", "source_ids": [source_id], "strategy": "vector"},
+ )
+ assert explicit.status_code == 200, explicit.text
+ assert seen[-1] == "vector"
+ assert explicit.json()["stats"]["strategy_origin"] == "request"
+ finally:
+ app.dependency_overrides.pop(get_engine_manager, None)
+
+
+def test_require_strategy_available_matches_capability_report():
+ assert EngineManager.require_strategy_available(configured(), "sag2") is None
+ with pytest.raises(Exception) as error:
+ EngineManager.require_strategy_available(configured(sag_relational_provider="mysql"), "sag2")
+ assert getattr(error.value, "code", None) == "sag2_relational_unsupported"
diff --git a/apps/web/app/(app)/knowledge/[id]/page.tsx b/apps/web/app/(app)/knowledge/[id]/page.tsx
index 0f8aba83..c52962bd 100644
--- a/apps/web/app/(app)/knowledge/[id]/page.tsx
+++ b/apps/web/app/(app)/knowledge/[id]/page.tsx
@@ -26,6 +26,7 @@ import {
FolderImportDialog,
type FolderImportDialogHandle,
} from "@/components/features/folder-import-dialog";
+import { RetrievalModePill } from "@/components/features/retrieval-mode-pill";
import { RetrievalTestDialog } from "@/components/features/retrieval-test-dialog";
import { SourceIdCopy } from "@/components/features/source-id-copy";
import { SourceGraph } from "@/components/features/source-graph";
@@ -123,9 +124,14 @@ export default function SourceDetailPage() {
{source ? (
<>
-
- {source.name}
-
+
+
+ {source.name}
+
+ {source.default_search_strategy && (
+
+ )}
+
{t("sourceStats", {
documents: source.document_count,
diff --git a/apps/web/components/features/app-shell.tsx b/apps/web/components/features/app-shell.tsx
index e3722547..da9d9f24 100644
--- a/apps/web/components/features/app-shell.tsx
+++ b/apps/web/components/features/app-shell.tsx
@@ -133,6 +133,7 @@ const CONVERSATION_TRANSPORT: ConversationTransport = {
sourceIds,
knowledgeOnly,
webEnabled,
+ strategy,
onEvent,
signal,
}) => {
@@ -145,6 +146,7 @@ const CONVERSATION_TRANSPORT: ConversationTransport = {
attachment_count: attachmentIds?.length ?? 0,
source_ids: sourceIds,
web_enabled: webEnabled,
+ strategy,
});
const promise = streamAgentAsk(
agentId,
@@ -155,6 +157,8 @@ const CONVERSATION_TRANSPORT: ConversationTransport = {
source_ids: sourceIds,
knowledge_only: knowledgeOnly === true || !webEnabled,
web_enabled: webEnabled,
+ // Only an explicit per-turn pick travels; otherwise the backend resolves the mode.
+ ...(strategy ? { strategy } : {}),
},
(event) => {
// 只记录关键事件,跳过高频 message.delta
diff --git a/apps/web/components/features/chat/conversation-panel.test.tsx b/apps/web/components/features/chat/conversation-panel.test.tsx
index 2be334eb..4c256fdb 100644
--- a/apps/web/components/features/chat/conversation-panel.test.tsx
+++ b/apps/web/components/features/chat/conversation-panel.test.tsx
@@ -6,20 +6,33 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import english from "@/messages/en-US.json";
import type { ConversationMessage, ConversationSessionSnapshot } from "@/lib/conversation-runtime";
-import type { MessageSourceScope, Source } from "@/lib/types";
+import { AgentHttpError } from "@/lib/sse";
+import type { Agent, Capabilities, MessageSourceScope, Source } from "@/lib/types";
import { ConversationPanel } from "./conversation-panel";
const state = vi.hoisted(() => ({
snapshot: null as ConversationSessionSnapshot | null,
send: vi.fn(), activate: vi.fn(), ensureHistory: vi.fn(), setInput: vi.fn(),
+ toastError: vi.fn(),
sources: [] as Source[],
+ scoped: [{ id: "composer-source", name: "Composer selection" }],
+ capabilities: { llm_configured: true } as Partial,
+ agent: null as Agent | null,
}));
+const catalog = english as unknown as Record>;
vi.mock("next-intl", () => ({
useLocale: () => "en-US",
- useTranslations: () => (key: keyof typeof english.Conversation) => english.Conversation[key] ?? key,
+ useTranslations: (namespace: string) => (key: string, values?: Record) =>
+ (catalog[namespace]?.[key] ?? key).replace(/\{(\w+)\}/g, (_, name: string) => String(values?.[name] ?? "")),
}));
+vi.mock("next/link", () => ({
+ default: React.forwardRef>(
+ function Link({ children, href, ...props }, ref) { return {children}; },
+ ),
+}));
+vi.mock("sonner", () => ({ toast: { error: state.toastError, success: vi.fn() } }));
vi.mock("@/components/features/app-shell", () => ({
- useApp: () => ({ capabilities: { llm_configured: true }, timezone: "UTC" }),
+ useApp: () => ({ capabilities: state.capabilities, agent: state.agent, timezone: "UTC" }),
}));
vi.mock("./conversation-provider", () => ({
useConversationSession: () => state.snapshot,
@@ -29,7 +42,7 @@ vi.mock("./conversation-provider", () => ({
getSessionSnapshot: () => ({ run: {} }),
}),
useConversationComposer: () => ({
- input: "Unsent draft", scoped: [{ id: "composer-source", name: "Composer selection" }],
+ input: "Unsent draft", scoped: state.scoped,
images: [], webEnabled: false, setInput: state.setInput,
setImages: vi.fn(), setScoped: vi.fn(), setWebEnabled: vi.fn(),
}),
@@ -42,16 +55,49 @@ vi.mock("@/components/features/markdown-content", () => ({
vi.mock("./prompt-preview", () => ({ PromptPreview: () => null }));
vi.mock("./agent-activity-timeline", () => ({ AgentActivityTimeline: () => null }));
+const ALL_STRATEGIES = ["vector", "multi_es_fast", "multi", "multi_jev", "sag2"] as const;
+const emptySession: ConversationSessionSnapshot = {
+ sessionId: "session-1", agentId: "agent-1", threadId: "thread-1", error: null, run: null,
+ history: { status: "ready", requestId: 0, hasMore: false, nextCursor: null, error: null }, messages: [],
+};
+function source(id: string, defaultStrategy: Source["default_search_strategy"] = null, status = "active"): Source {
+ return {
+ id, name: id, description: "", source_type: "document", connector_kind: "file_upload",
+ status, default_search_strategy: defaultStrategy, document_count: 0, chunk_count: 0, event_count: 0,
+ created_at: "2026-10-09T00:00:00Z", updated_at: "2026-10-09T00:00:00Z",
+ } as Source;
+}
+function agent(searchStrategy?: string): Agent {
+ return {
+ id: "agent-1", name: "Agent", avatar: "", created_at: "2026-10-09T00:00:00Z", updated_at: "2026-10-09T00:00:00Z",
+ persona: { greeting: "Hi", ...(searchStrategy ? { search_strategy: searchStrategy as Agent["persona"]["search_strategy"] } : {}) },
+ };
+}
+function pointerEvent(type: string) {
+ const event = new MouseEvent(type, { bubbles: true, button: 0 });
+ Object.defineProperties(event, { pointerId: { value: 1 }, pointerType: { value: "mouse" } });
+ return event;
+}
+
let container: HTMLDivElement;
let root: Root;
const originalScrollIntoView = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollIntoView");
beforeEach(() => {
vi.clearAllMocks();
state.sources = [];
+ state.scoped = [{ id: "composer-source", name: "Composer selection" }];
+ state.capabilities = { llm_configured: true };
+ state.agent = null;
+ state.snapshot = emptySession;
state.send.mockResolvedValue({});
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
- Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { configurable: true, value: vi.fn() });
+ Object.defineProperties(HTMLElement.prototype, {
+ scrollIntoView: { configurable: true, value: vi.fn() },
+ hasPointerCapture: { configurable: true, value: () => false },
+ releasePointerCapture: { configurable: true, value: () => undefined },
+ setPointerCapture: { configurable: true, value: () => undefined },
+ });
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
@@ -65,20 +111,25 @@ afterEach(async () => {
else delete (HTMLElement.prototype as Partial).scrollIntoView;
});
+async function renderPanel() {
+ await act(async () => root.render());
+}
+const trigger = () => container.querySelector('[data-testid="search-strategy"]')!;
+const hint = () => container.querySelector('[data-testid="search-strategy-hint"]')?.textContent ?? null;
+const sendButton = () => container.querySelector(`button[title="${english.Conversation.send}"]`)!;
+async function pick(label: string) {
+ await act(async () => trigger().dispatchEvent(pointerEvent("pointerdown")));
+ const item = [...document.body.querySelectorAll('[role="menuitem"]')]
+ .find((candidate) => candidate.textContent?.includes(label))!;
+ await act(async () => { item.dispatchEvent(pointerEvent("pointermove")); item.dispatchEvent(pointerEvent("pointerup")); item.click(); });
+}
+
describe("retry source scope", () => {
it("excludes deleting sources from mentions while keeping the composer selection", async () => {
- state.sources = ["active", "paused", "error", "deleting", "delete_failed"].map((status) => ({
- id: status, name: status, description: "", source_type: "document", connector_kind: "file_upload",
- status, document_count: 0, chunk_count: 0, event_count: 0,
- created_at: "2026-10-09T00:00:00Z", updated_at: "2026-10-09T00:00:00Z",
- } as Source));
- state.snapshot = {
- sessionId: "session-1", agentId: "agent-1", threadId: "thread-1", error: null, run: null,
- history: { status: "ready", requestId: 0, hasMore: false, nextCursor: null, error: null }, messages: [],
- };
- await act(async () => root.render());
+ state.sources = ["active", "paused", "error", "deleting", "delete_failed"].map((status) => source(status, null, status));
+ await renderPanel();
const textarea = container.querySelector("textarea")!;
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(textarea, "@");
@@ -100,13 +151,10 @@ describe("retry source scope", () => {
sourceScope: saved as MessageSourceScope[] | null,
};
state.snapshot = {
- sessionId: "session-1", agentId: "agent-1", threadId: "thread-1", error: null, run: null,
- history: { status: "ready", requestId: 0, hasMore: false, nextCursor: null, error: null },
+ ...emptySession,
messages: [base, { ...base, id: "answer", role: "assistant", content: "Original answer", sourceScope: null }],
};
- await act(async () => root.render());
+ await renderPanel();
const retry = container.querySelector('button[aria-label="Generate answer again"]')!;
expect(retry).toBeTruthy();
await act(async () => retry.click());
@@ -115,3 +163,90 @@ describe("retry source scope", () => {
}));
});
});
+
+describe("composer retrieval mode", () => {
+ it("shows the global default without a hint when nothing else applies", async () => {
+ state.capabilities = { llm_configured: true, search_strategy: "multi_es_fast" };
+ await renderPanel();
+ expect(trigger().textContent).toContain("Fast (multi_es-fast)");
+ expect(hint()).toBeNull();
+ expect(trigger().disabled).toBe(false);
+ });
+
+ it("prefers the agent persona mode and says so", async () => {
+ state.capabilities = { llm_configured: true, search_strategy: "vector", search_strategies: [...ALL_STRATEGIES] };
+ state.agent = agent("sag2");
+ state.sources = [source("composer-source", "multi")];
+ await renderPanel();
+ expect(trigger().textContent).toContain("SAG2 evidence retrieval");
+ expect(hint()).toContain("Persona default");
+ });
+
+ it("falls back to the shared source default when the persona mode cannot be served", async () => {
+ // Without an advertised search_strategies list the JEV modes are unsupported.
+ state.capabilities = { llm_configured: true, search_strategy: "vector" };
+ state.agent = agent("sag2");
+ state.sources = [source("composer-source", "multi")];
+ await renderPanel();
+ expect(trigger().textContent).toContain("Precise");
+ expect(hint()).toContain("Source default");
+ });
+
+ it("ignores source defaults that the scoped sources do not share", async () => {
+ state.scoped = [{ id: "a", name: "a" }, { id: "b", name: "b" }];
+ state.sources = [source("a", "multi"), source("b", "multi_es_fast")];
+ await renderPanel();
+ expect(trigger().textContent).toContain("Fast (vector)");
+ expect(hint()).toBeNull();
+ });
+
+ it("omits the mode from the request when nothing is pinned", async () => {
+ state.agent = agent("multi");
+ await renderPanel();
+ await act(async () => sendButton().click());
+ expect(state.send).toHaveBeenCalledTimes(1);
+ expect(state.send.mock.calls[0][1]).not.toHaveProperty("strategy");
+ });
+
+ it("sends the pinned mode and drops the origin hint", async () => {
+ state.agent = agent("multi");
+ await renderPanel();
+ expect(hint()).toContain("Persona default");
+ await pick("Fast (multi_es-fast)");
+ expect(trigger().textContent).toContain("Fast (multi_es-fast)");
+ expect(hint()).toBeNull();
+ await act(async () => sendButton().click());
+ expect(state.send).toHaveBeenCalledWith("session-1", expect.objectContaining({ strategy: "multi_es_fast" }));
+ });
+
+ it("locks the control while a run is in flight", async () => {
+ state.snapshot = {
+ ...emptySession,
+ run: { requestId: "r", runId: "run-1", lifecycle: "running", startedAt: 0, assistantMessageId: "a", steps: [], pendingApproval: null },
+ };
+ await renderPanel();
+ expect(trigger().disabled).toBe(true);
+ });
+
+ it("keeps a pre-stream mode rejection above the composer with a settings link", async () => {
+ state.send.mockRejectedValue(new AgentHttpError("Add a JEV API key first", "jev_api_key_missing", 400));
+ await renderPanel();
+ await act(async () => sendButton().click());
+ const notice = container.querySelector('[data-testid="strategy-notice"]')!;
+ expect(notice.textContent).toContain("Add a JEV API key first");
+ expect(notice.getAttribute("data-code")).toBe("jev_api_key_missing");
+ expect(container.querySelector('[data-testid="strategy-notice-settings"]')?.getAttribute("href"))
+ .toBe("/settings?tab=knowledge§ion=jev");
+ expect(state.toastError).not.toHaveBeenCalled();
+ await pick("Precise");
+ expect(container.querySelector('[data-testid="strategy-notice"]')).toBeNull();
+ });
+
+ it("still toasts errors that are not about the retrieval mode", async () => {
+ state.send.mockRejectedValue(new AgentHttpError("Server exploded", "internal_error", 500));
+ await renderPanel();
+ await act(async () => sendButton().click());
+ expect(container.querySelector('[data-testid="strategy-notice"]')).toBeNull();
+ expect(state.toastError).toHaveBeenCalledWith("Server exploded");
+ });
+});
diff --git a/apps/web/components/features/chat/conversation-panel.tsx b/apps/web/components/features/chat/conversation-panel.tsx
index ea24092c..9947c1b0 100644
--- a/apps/web/components/features/chat/conversation-panel.tsx
+++ b/apps/web/components/features/chat/conversation-panel.tsx
@@ -3,6 +3,7 @@
import * as React from "react";
import { ArrowUp, Check, Copy, FileUp, Globe2, ImagePlus, Library, Plus, RotateCcw, Square, Trash2, X } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
+import Link from "next/link";
import { toast } from "sonner";
import { toolArgumentsPreview } from "@/lib/agent-run-activity";
@@ -15,6 +16,16 @@ import {
isComposerCompositionKeyEvent,
shouldSubmitAfterEnter,
} from "@/lib/composer-keyboard";
+import {
+ DEFAULT_SEARCH_STRATEGY,
+ getScopeDefaultStrategy,
+ getSearchStrategiesDisabled,
+ isSearchStrategy,
+ isSearchStrategyRejectionCode,
+ type SearchStrategy,
+} from "@/lib/retrieval-config";
+import { settingsTabHref } from "@/lib/settings-config";
+import { AgentHttpError } from "@/lib/sse";
import type { Citation, MessageSourceScope, Source } from "@/lib/types";
import { cn } from "@/lib/utils";
import { copyText } from "@/lib/clipboard";
@@ -35,6 +46,7 @@ import {
type ConversationMessageRenderContext,
} from "@/components/features/chat/conversation-transcript";
import { PromptPreview } from "@/components/features/chat/prompt-preview";
+import { SearchStrategyControl } from "@/components/features/search-strategy-control";
import { AuthImage } from "@/components/features/auth-image";
import { Button } from "@/components/ui/button";
import {
@@ -60,6 +72,18 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+/** Where a rejected JEV mode gets fixed; the same section the mode menu links to. */
+const JEV_SETTINGS_HREF = settingsTabHref("knowledge", "jev");
+
+/** Who decided the mode shown in the composer when nothing is pinned. */
+type ChatStrategyOrigin = "pinned" | "persona" | "source_default" | "global";
+
+/** A pre-stream rejection of the chosen retrieval mode, shown above the composer. */
+interface StrategyNotice {
+ code: string;
+ message: string;
+}
+
function MessageActions({
content,
citations,
@@ -186,9 +210,11 @@ export function ConversationPanel({
onToolMatchClick,
}: ConversationPanelProps) {
const t = useTranslations("Conversation");
+ const searchStrategies = useTranslations("SearchStrategies");
+ const retrievalModes = useTranslations("RetrievalModes");
const locale = useLocale();
const resolvedPlaceholder = placeholder ?? t("defaultPlaceholder");
- const { capabilities } = useApp();
+ const { capabilities, agent } = useApp();
const runtime = useConversationRuntime();
const session = useConversationSession(sessionId);
const detailPanel = useDetailPanel();
@@ -205,6 +231,9 @@ export function ConversationPanel({
useConversationComposer(sessionId);
const imagesRef = React.useRef(images);
const [sources, setSources] = React.useState([]);
+ // An explicit pick lives with this panel only; it is sent as `strategy` until the panel unmounts.
+ const [pinnedStrategy, setPinnedStrategy] = React.useState(null);
+ const [strategyNotice, setStrategyNotice] = React.useState(null);
const [mentionOpen, setMentionOpen] = React.useState(false);
const [mentionIdx, setMentionIdx] = React.useState(0);
const [uploading, setUploading] = React.useState(false);
@@ -267,6 +296,46 @@ export function ConversationPanel({
return q ? sources.filter((s) => s.name.toLowerCase().includes(q)) : sources;
}, [sources, mentionQuery]);
React.useEffect(() => setMentionIdx(0), [mentionQuery]);
+
+ // Mirror the backend's resolution order so the composer shows the mode a turn will actually use:
+ // pinned pick → agent persona → shared default of the scoped sources → global default.
+ const unsupportedStrategyMessage = searchStrategies("unsupportedBackend");
+ const strategyDisabledMap = React.useMemo(
+ () => getSearchStrategiesDisabled(capabilities, unsupportedStrategyMessage),
+ [capabilities, unsupportedStrategyMessage],
+ );
+ const personaStrategy = React.useMemo(() => {
+ const value = agent?.persona?.search_strategy;
+ return isSearchStrategy(value) && !strategyDisabledMap[value] ? value : null;
+ }, [agent?.persona?.search_strategy, strategyDisabledMap]);
+ // Scopes only carry id + name; the loaded source list supplies each one's default.
+ // A scope whose source is not loaded yet counts as "no default", like the backend treats null.
+ const scopeDefaultStrategy = React.useMemo(() => getScopeDefaultStrategy(
+ scoped.map((scope) => ({
+ default_search_strategy: sources.find((source) => source.id === scope.id)?.default_search_strategy ?? null,
+ })),
+ strategyDisabledMap,
+ ), [scoped, sources, strategyDisabledMap]);
+ const globalStrategy = isSearchStrategy(capabilities?.search_strategy)
+ ? capabilities.search_strategy
+ : DEFAULT_SEARCH_STRATEGY;
+ const resolvedStrategy = personaStrategy ?? scopeDefaultStrategy ?? globalStrategy;
+ const strategyOrigin: ChatStrategyOrigin = pinnedStrategy
+ ? "pinned"
+ : personaStrategy
+ ? "persona"
+ : scopeDefaultStrategy
+ ? "source_default"
+ : "global";
+ const strategyHint = strategyOrigin === "persona"
+ ? retrievalModes("personaDefaultHint")
+ : strategyOrigin === "source_default"
+ ? retrievalModes("scopeDefaultHint")
+ : undefined;
+ const pinStrategy = React.useCallback((value: SearchStrategy) => {
+ setPinnedStrategy(value);
+ setStrategyNotice(null);
+ }, []);
React.useEffect(() => {
mentionListRef.current
?.querySelector(`[data-idx="${mentionIdx}"]`)
@@ -537,6 +606,7 @@ export function ConversationPanel({
uploadingRef.current = true;
setUploading(true);
+ setStrategyNotice(null);
try {
const uploaded = pendingImages.length
? await Promise.all(pendingImages.map((item) => api.uploadAttachment(item.file)))
@@ -547,6 +617,8 @@ export function ConversationPanel({
attachmentIds: uploaded.map((item) => item.id),
sourceScope: selectedScope,
webEnabled,
+ // Omitted unless pinned so the backend applies persona / source / global defaults itself.
+ ...(pinnedStrategy ? { strategy: pinnedStrategy } : {}),
});
// send 在首次 await 前就登记 run;未登记表示被全局并发边界拒绝,保留草稿。
@@ -563,7 +635,13 @@ export function ConversationPanel({
followOutputRef.current = true;
void request.catch((error) => {
- toast.error(error instanceof Error ? error.message : t("connectionInterrupted"));
+ // A mode this deployment cannot serve is rejected before streaming; keep that
+ // explanation next to the mode control instead of letting it vanish with a toast.
+ if (error instanceof AgentHttpError && isSearchStrategyRejectionCode(error.code)) {
+ setStrategyNotice({ code: error.code, message: error.message });
+ } else {
+ toast.error(error instanceof Error ? error.message : t("connectionInterrupted"));
+ }
getDiagnosticsStore().record("qa.error", {
context: "conversation.send",
error_message: error instanceof Error ? error.message.slice(0, 500) : String(error).slice(0, 500),
@@ -737,6 +815,31 @@ export function ConversationPanel({
+ {strategyNotice && (
+
+ {strategyNotice.message}
+
+ {searchStrategies("openSettings")}
+
+
+
+ )}
{images.length > 0 && (
@@ -945,6 +1048,14 @@ export function ConversationPanel({
: t("webDisabledDescription")}
+
diff --git a/apps/web/components/features/create-source-dialog.tsx b/apps/web/components/features/create-source-dialog.tsx
index 4efb3162..9c866b5d 100644
--- a/apps/web/components/features/create-source-dialog.tsx
+++ b/apps/web/components/features/create-source-dialog.tsx
@@ -36,7 +36,7 @@ export function CreateSourceDialog({
)}
-
+
{t("new")}
{t("dialogDescription")}
diff --git a/apps/web/components/features/document-deletion.test.tsx b/apps/web/components/features/document-deletion.test.tsx
index e2bc21fb..1f83be79 100644
--- a/apps/web/components/features/document-deletion.test.tsx
+++ b/apps/web/components/features/document-deletion.test.tsx
@@ -12,7 +12,7 @@ import { OctxExportProvider } from "./octx-export-provider";
const source: Source = {
id: "source-1", name: "Reports", description: "", source_type: "document", connector_kind: "file_upload",
- status: "active", document_count: 0, chunk_count: 0, event_count: 0,
+ status: "active", default_search_strategy: null, document_count: 0, chunk_count: 0, event_count: 0,
created_at: "2026-10-09T00:00:00Z", updated_at: "2026-10-09T00:00:00Z",
};
const cleanup: BackgroundJob = {
diff --git a/apps/web/components/features/document-processing-progress.test.tsx b/apps/web/components/features/document-processing-progress.test.tsx
index a2864b33..f8ca74c6 100644
--- a/apps/web/components/features/document-processing-progress.test.tsx
+++ b/apps/web/components/features/document-processing-progress.test.tsx
@@ -238,7 +238,7 @@ describe("live document details", () => {
let current: Doc = { ...base, status: "paused" };
const source: Source = {
id: "source-1", name: "Reports", description: "", source_type: "document",
- connector_kind: "file_upload", status: "active", document_count: 1,
+ connector_kind: "file_upload", status: "active", default_search_strategy: null, document_count: 1,
chunk_count: 20, event_count: 0, created_at: base.created_at, updated_at: base.updated_at,
};
vi.spyOn(api, "getSource").mockResolvedValue(source);
diff --git a/apps/web/components/features/document-restart-confirmation.test.tsx b/apps/web/components/features/document-restart-confirmation.test.tsx
index 6ddcb718..223ccfa9 100644
--- a/apps/web/components/features/document-restart-confirmation.test.tsx
+++ b/apps/web/components/features/document-restart-confirmation.test.tsx
@@ -21,7 +21,7 @@ const paused: Doc = {
};
const source: Source = {
id: "source-1", name: "Reports", description: "", source_type: "document", connector_kind: "file_upload",
- status: "active", document_count: 1, chunk_count: 20, event_count: 4,
+ status: "active", default_search_strategy: null, document_count: 1, chunk_count: 20, event_count: 4,
created_at: paused.created_at, updated_at: paused.updated_at,
};
diff --git a/apps/web/components/features/dsh-service-settings.test.tsx b/apps/web/components/features/dsh-service-settings.test.tsx
index eefc203b..0aa53ddd 100644
--- a/apps/web/components/features/dsh-service-settings.test.tsx
+++ b/apps/web/components/features/dsh-service-settings.test.tsx
@@ -42,6 +42,7 @@ const sources: Source[] = [
source_type: "document",
connector_kind: "local",
status: "active",
+ default_search_strategy: null,
document_count: 0,
chunk_count: 0,
event_count: 0,
diff --git a/apps/web/components/features/edit-source-dialog.test.tsx b/apps/web/components/features/edit-source-dialog.test.tsx
new file mode 100644
index 00000000..2a03c187
--- /dev/null
+++ b/apps/web/components/features/edit-source-dialog.test.tsx
@@ -0,0 +1,101 @@
+/** @vitest-environment jsdom */
+import * as React from "react";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { NextIntlClientProvider } from "next-intl";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import messages from "@/messages/en-US.json";
+import { api } from "@/lib/api";
+import type { Capabilities, Source } from "@/lib/types";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { EditSourceDialog } from "./edit-source-dialog";
+
+const state = vi.hoisted(() => ({
+ capabilities: {} as Partial,
+ refreshCapabilities: vi.fn(async () => {}),
+}));
+vi.mock("@/components/features/app-shell", () => ({ useApp: () => state }));
+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+vi.mock("next/link", () => ({
+ default: React.forwardRef>(
+ function Link({ children, href, ...props }, ref) { return {children}; },
+ ),
+}));
+
+const source: Source = {
+ id: "source-1", name: "Manuals", description: "Specs", source_type: "document", connector_kind: "file_upload",
+ status: "active", default_search_strategy: "multi", document_count: 0, chunk_count: 0, event_count: 0,
+ created_at: "2026-10-24T00:00:00Z", updated_at: "2026-10-24T00:00:00Z",
+};
+
+let root: Root;
+let container: HTMLDivElement;
+let onUpdated: ReturnType void>>;
+
+beforeEach(() => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ state.capabilities = { search_strategy: "vector", search_strategies: ["vector", "multi_es_fast", "multi", "multi_jev", "sag2"] };
+ onUpdated = vi.fn();
+ vi.spyOn(api, "updateSource").mockImplementation(async (_id, body) => ({ ...source, ...body }) as Source);
+ vi.spyOn(api, "getModelConfig").mockResolvedValue({ jev_endpoint: null, jev_model: "jev-latest" } as never);
+ Object.defineProperties(HTMLElement.prototype, {
+ hasPointerCapture: { configurable: true, value: () => false }, releasePointerCapture: { configurable: true, value: () => undefined },
+ setPointerCapture: { configurable: true, value: () => undefined }, scrollIntoView: { configurable: true, value: () => undefined },
+ });
+ vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);
+});
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+function pointerEvent(type: string) {
+ const event = new MouseEvent(type, { bubbles: true, button: 0 });
+ Object.defineProperties(event, { pointerId: { value: 1 }, pointerType: { value: "mouse" } });
+ return event;
+}
+async function openDialog() {
+ await act(async () => root.render(
+
+
+ ,
+ ));
+ await act(async () => container.querySelector("button")!.click());
+ const dialog = document.body.querySelector('[role="dialog"]')!;
+ expect(dialog).not.toBeNull();
+ return dialog;
+}
+async function pickMode(testId: string) {
+ const trigger = document.body.querySelector('[data-testid="retrieval-mode-picker"]')!;
+ await act(async () => trigger.dispatchEvent(pointerEvent("pointerdown")));
+ const option = document.body.querySelector(`[data-testid="${testId}"]`)!;
+ expect(option, `option ${testId}`).not.toBeNull();
+ await act(async () => { option.dispatchEvent(pointerEvent("pointerdown")); option.dispatchEvent(pointerEvent("pointerup")); });
+}
+
+describe("edit source dialog", () => {
+ it("preselects the saved default mode and sends it unchanged", async () => {
+ const dialog = await openDialog();
+ expect(dialog.textContent).toContain("name, description and default retrieval mode");
+ expect(dialog.querySelector('[data-testid="retrieval-mode-picker"]')?.textContent).toContain("Precise");
+ await act(async () => dialog.querySelector("form")!.requestSubmit());
+ expect(api.updateSource).toHaveBeenCalledWith("source-1", { name: "Manuals", description: "Specs", default_search_strategy: "multi" });
+ expect(onUpdated).toHaveBeenCalledWith(expect.objectContaining({ default_search_strategy: "multi" }));
+ });
+ it("sends null when switching back to the global default", async () => {
+ const dialog = await openDialog();
+ await pickMode("retrieval-mode-global");
+ await act(async () => dialog.querySelector("form")!.requestSubmit());
+ expect(api.updateSource).toHaveBeenCalledWith("source-1", { name: "Manuals", description: "Specs", default_search_strategy: null });
+ });
+ it("blocks saving a JEV mode until the key is entered", async () => {
+ state.capabilities = {
+ ...state.capabilities,
+ search_strategies_disabled: { sag2: { reason: "jev_not_configured", message: "Configure JEV" } },
+ };
+ const dialog = await openDialog();
+ await pickMode("retrieval-mode-sag2");
+ expect(dialog.querySelector('[data-testid="jev-quick-setup"]')).not.toBeNull();
+ expect(dialog.querySelector('button[type="submit"]')!.disabled).toBe(true);
+ expect(dialog.querySelector('[data-testid="source-form-blocked"]')).not.toBeNull();
+ });
+});
diff --git a/apps/web/components/features/edit-source-dialog.tsx b/apps/web/components/features/edit-source-dialog.tsx
index 5c8ba6ca..5c2baf80 100644
--- a/apps/web/components/features/edit-source-dialog.tsx
+++ b/apps/web/components/features/edit-source-dialog.tsx
@@ -5,7 +5,17 @@ import { Pencil } from "lucide-react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
+import { useApp } from "@/components/features/app-shell";
+import { useJevQuickSetup } from "@/components/features/jev-quick-setup";
+import { RetrievalModePicker } from "@/components/features/retrieval-mode-picker";
import { api, ApiError } from "@/lib/api";
+import {
+ DEFAULT_SEARCH_STRATEGY,
+ getSearchStrategiesDisabled,
+ isSearchStrategy,
+ needsJevQuickSetup,
+ type SearchStrategy,
+} from "@/lib/retrieval-config";
import type { Source } from "@/lib/types";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
@@ -35,32 +45,65 @@ export function EditSourceDialog({
tooltipSide?: React.ComponentProps["side"];
}) {
const t = useTranslations("SourceForm");
+ const strategies = useTranslations("SearchStrategies");
+ const modes = useTranslations("RetrievalModes");
+ const { capabilities } = useApp();
const [open, setOpen] = React.useState(false);
const [name, setName] = React.useState(source.name);
const [description, setDescription] = React.useState(source.description ?? "");
+ const [mode, setMode] = React.useState(
+ source.default_search_strategy ?? null,
+ );
const [loading, setLoading] = React.useState(false);
+ const [error, setError] = React.useState(null);
+
+ const globalStrategy = isSearchStrategy(capabilities?.search_strategy)
+ ? capabilities.search_strategy
+ : DEFAULT_SEARCH_STRATEGY;
+ const unsupportedMessage = strategies("unsupportedBackend");
+ const disabledMap = React.useMemo(
+ () => getSearchStrategiesDisabled(capabilities, unsupportedMessage),
+ [capabilities, unsupportedMessage],
+ );
+ const jevSetupNeeded = open && needsJevQuickSetup(mode, disabledMap);
+ const jevSetup = useJevQuickSetup({ enabled: jevSetupNeeded });
+ const jevKeyMissing = jevSetupNeeded && !jevSetup.ready;
React.useEffect(() => {
if (!open) return;
setName(source.name);
setDescription(source.description ?? "");
+ setMode(source.default_search_strategy ?? null);
+ setError(null);
}, [open, source]);
async function submit(e: React.FormEvent) {
e.preventDefault();
const cleanName = name.trim();
- if (!cleanName) return;
+ if (!cleanName || jevKeyMissing) return;
setLoading(true);
+ setError(null);
try {
+ if (jevSetupNeeded) {
+ try {
+ await jevSetup.save();
+ } catch {
+ // The quick setup shows the failure next to its fields.
+ return;
+ }
+ }
const updated = await api.updateSource(source.id, {
name: cleanName,
description: description.trim(),
+ default_search_strategy: mode,
});
toast.success(t("updated"));
onUpdated?.(updated);
setOpen(false);
} catch (err) {
- toast.error(err instanceof ApiError ? err.message : t("updateFailed"));
+ const message = err instanceof ApiError ? err.message : t("updateFailed");
+ setError(message);
+ toast.error(message);
} finally {
setLoading(false);
}
@@ -85,7 +128,7 @@ export function EditSourceDialog({
{t("edit")}
-
+
{t("edit")}
{t("editDescription")}
@@ -114,9 +157,32 @@ export function EditSourceDialog({
rows={2}
/>
+ {
+ setMode(next);
+ setError(null);
+ }}
+ globalStrategy={globalStrategy}
+ disabledMap={disabledMap}
+ disabled={loading}
+ jevSetup={jevSetup}
+ />
+
+ {error && (
+
+ {error}
+
+ )}
-
-