From 1411af8be28ec84fc4c51803fcaf93b9de02a399 Mon Sep 17 00:00:00 2001 From: luoshuai990529 <58510855+luoshuai990529@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:05:29 +0800 Subject: [PATCH 1/7] =?UTF-8?q?feat(api):=20=E4=BF=A1=E6=BA=90=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E9=BB=98=E8=AE=A4=E6=A3=80=E7=B4=A2=E6=A8=A1=E5=BC=8F?= =?UTF-8?q?=E5=B9=B6=E6=8C=89=E8=8C=83=E5=9B=B4=E8=A7=A3=E6=9E=90=E6=A3=80?= =?UTF-8?q?=E7=B4=A2=E7=AD=96=E7=95=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `Source` 新增 `default_search_strategy`(可空,跟随全局),创建 / 更新接口 接受并返回该字段;取值须是当前部署可用的模式,JEV 付费模式还需已保存 API Key,拒绝时沿用能力原因码 - 新增 `resolve_search_strategy`:显式请求 → Agent 人格 → 范围内信源的共同 默认 → 全局默认;范围内信源默认不一致时不猜测,按全局处理。检索服务、 搜索接口、Agent 工具与预算统一走该解析,结果 `stats.strategy_origin` 标明来源,MCP 自动继承 - `EngineManager.require_strategy_available` 供设置、人格、信源三处共用 Co-Authored-By: Claude Fable 5.1 --- apps/api/sag_api/api/v1/search.py | 7 +- apps/api/sag_api/core/db.py | 1 + apps/api/sag_api/db/models/source.py | 3 + apps/api/sag_api/sag/engine_manager.py | 9 +- apps/api/sag_api/schemas/source.py | 7 +- apps/api/sag_api/services/agent_tooling.py | 2 +- .../api/sag_api/services/retrieval_service.py | 46 +++- apps/api/sag_api/services/source_service.py | 22 ++ apps/api/sag_api/tools/builtin.py | 9 +- .../api/tests/test_source_default_strategy.py | 213 ++++++++++++++++++ 10 files changed, 308 insertions(+), 11 deletions(-) create mode 100644 apps/api/tests/test_source_default_strategy.py 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/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_tooling.py b/apps/api/sag_api/services/agent_tooling.py index e1706ef4..0e6fdb22 100644 --- a/apps/api/sag_api/services/agent_tooling.py +++ b/apps/api/sag_api/services/agent_tooling.py @@ -348,7 +348,7 @@ 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) + strategy = knowledge_search_strategy(host_context.persona, configuration, host_context.sources) # Keep this run's mode stable while the model prepares the tool call. host_context = replace(host_context, persona={**host_context.persona, "search_strategy": strategy}) if strategy == "multi_jev": 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/builtin.py b/apps/api/sag_api/tools/builtin.py index 86bd35a3..cf10c280 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,11 @@ 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=()) -> str: + """Persona choice → shared source default → legacy default (vector unless a JEV mode is global).""" 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 ): @@ -249,7 +250,7 @@ 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) 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} 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..65be70bf --- /dev/null +++ b/apps/api/tests/test_source_default_strategy.py @@ -0,0 +1,213 @@ +"""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"] == "改名" + + for sid in (source_id, plain.json()["id"]): + await client.delete(f"/api/v1/sources/{sid}") + + +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) + await client.delete(f"/api/v1/sources/{source_id}") + + +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" From 820da14e64378dc05e7d78457b8f325b49d4268c Mon Sep 17 00:00:00 2001 From: luoshuai990529 <58510855+luoshuai990529@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:05:29 +0800 Subject: [PATCH 2/7] =?UTF-8?q?docs:=20=E8=AF=B4=E6=98=8E=E4=BF=A1?= =?UTF-8?q?=E6=BA=90=E9=BB=98=E8=AE=A4=E6=A3=80=E7=B4=A2=E6=A8=A1=E5=BC=8F?= =?UTF-8?q?=E5=8F=8A=E5=85=B6=E8=A7=A3=E6=9E=90=E9=A1=BA=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 1 + README-CN.md | 4 +++- README.md | 4 +++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ebdd59c6..a2f6b6ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ## Unreleased +- 信源可设置「默认检索模式」:创建或编辑信源时选择快速、精确、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..4ab80206 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..af9e3e9b 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. 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. From 34e8fc01a717d7674752f20af132bed30723a8cc Mon Sep 17 00:00:00 2001 From: luoshuai990529 <58510855+luoshuai990529@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:11:17 +0800 Subject: [PATCH 3/7] =?UTF-8?q?feat(web):=20=E5=88=9B=E5=BB=BA=E4=B8=8E?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E4=BF=A1=E6=BA=90=E6=97=B6=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=E6=A3=80=E7=B4=A2=E6=A8=A1=E5=BC=8F=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E5=9C=A8=E5=AF=B9=E8=AF=9D=E6=A1=86=E5=86=85=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=20JEV?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增默认检索模式选择器:首项「跟随全局默认」,各模式附通俗说明、 适用场景与付费标识;因存储能力不可用的模式灰置并给出原因 - 选择 JEV 模式但缺少服务或 Key 时,就地展开 JEV 配置(预设服务商、 Key、测试连接),保存后再创建或更新信源;提交按钮在缺 Key 时禁用并说明 - 信源卡片与详情头部显示默认模式标签;搜索页在所选范围信源默认一致且 用户未手动选择时自动采用并标注「信源默认」 - JEV 预设与校验抽到 `lib/jev-config.ts`,设置页共用;补充中英文案与 vitest 用例 Co-Authored-By: Claude Fable 5.1 --- apps/web/app/(app)/knowledge/[id]/page.tsx | 12 +- .../features/create-source-dialog.tsx | 2 +- .../features/document-deletion.test.tsx | 2 +- .../document-processing-progress.test.tsx | 2 +- .../document-restart-confirmation.test.tsx | 2 +- .../features/dsh-service-settings.test.tsx | 1 + .../features/edit-source-dialog.test.tsx | 101 ++++++ .../features/edit-source-dialog.tsx | 76 ++++- .../components/features/jev-quick-setup.tsx | 290 ++++++++++++++++++ .../features/knowledge-config-form.tsx | 18 +- .../features/knowledge-workspace.test.tsx | 1 + .../features/retrieval-mode-picker.test.tsx | 148 +++++++++ .../features/retrieval-mode-picker.tsx | 157 ++++++++++ .../features/retrieval-mode-pill.tsx | 51 +++ .../features/search-strategy-control.test.tsx | 12 +- .../features/search-strategy-control.tsx | 36 +-- .../features/search/search-panel.tsx | 6 +- .../features/search/search-provider.tsx | 52 +++- .../search/search-scope-default.test.tsx | 126 ++++++++ .../components/features/source-card.test.tsx | 43 ++- apps/web/components/features/source-card.tsx | 7 +- .../features/source-create-form.test.tsx | 156 ++++++++++ .../features/source-create-form.tsx | 78 ++++- .../features/source-deletion.test.tsx | 2 +- apps/web/lib/api.ts | 7 +- apps/web/lib/jev-config.ts | 37 +++ apps/web/lib/retrieval-config.test.ts | 35 +++ apps/web/lib/retrieval-config.ts | 49 +++ apps/web/lib/types.ts | 6 + apps/web/messages/en-US.json | 44 ++- apps/web/messages/zh-CN.json | 44 ++- 31 files changed, 1524 insertions(+), 79 deletions(-) create mode 100644 apps/web/components/features/edit-source-dialog.test.tsx create mode 100644 apps/web/components/features/jev-quick-setup.tsx create mode 100644 apps/web/components/features/retrieval-mode-picker.test.tsx create mode 100644 apps/web/components/features/retrieval-mode-picker.tsx create mode 100644 apps/web/components/features/retrieval-mode-pill.tsx create mode 100644 apps/web/components/features/search/search-scope-default.test.tsx create mode 100644 apps/web/components/features/source-create-form.test.tsx create mode 100644 apps/web/lib/jev-config.ts 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/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} +

+ )} - - diff --git a/apps/web/components/features/jev-quick-setup.tsx b/apps/web/components/features/jev-quick-setup.tsx new file mode 100644 index 00000000..9b17cd0a --- /dev/null +++ b/apps/web/components/features/jev-quick-setup.tsx @@ -0,0 +1,290 @@ +"use client"; + +import * as React from "react"; +import { FlaskConical, Settings2 } from "lucide-react"; +import Link from "next/link"; +import { useTranslations } from "next-intl"; + +import { useApp } from "@/components/features/app-shell"; +import { Button } from "@/components/ui/button"; +import { Field, FieldLabel } from "@/components/ui/field"; +import { Input } from "@/components/ui/input"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Spinner } from "@/components/ui/spinner"; +import { api, ApiError } from "@/lib/api"; +import { + isValidJevEndpoint, + JEV_DEFAULT_MODEL, + JEV_ENDPOINTS, + JEV_PROVIDER_NAMES, + providerForEndpoint, + type JevProvider, +} from "@/lib/jev-config"; +import { settingsTabHref } from "@/lib/settings-config"; +import type { ModelConfigPatch } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +/** The shared JEV service section inside the knowledge settings tab. */ +export const JEV_SETTINGS_HREF = settingsTabHref("knowledge", "jev"); + +export interface JevQuickSetupState { + provider: JevProvider; + endpoint: string; + apiKey: string; + endpointValid: boolean; + /** Endpoint and key are both usable, so `save()` may run. */ + ready: boolean; + testing: boolean; + saving: boolean; + testResult: { ok: boolean; message: string } | null; + /** Last save failure, shown inline next to the fields. */ + error: string | null; + setProvider: (provider: JevProvider) => void; + setEndpoint: (endpoint: string) => void; + setApiKey: (apiKey: string) => void; + test: () => Promise; + /** + * Persists the shared JEV service (endpoint, model, key) and refreshes + * capabilities so JEV modes stop being reported as disabled. Records the + * failure in `error` and rethrows so the caller can stop its own submit. + */ + save: () => Promise; +} + +/** + * Draft state for configuring the paid JEV service without leaving a source + * dialog. `enabled` is true while a JEV mode is selected but blocked only by a + * missing configuration; the first time that happens a saved endpoint and + * model are read back so a custom deployment is not silently replaced by the + * 302.AI preset. + */ +export function useJevQuickSetup({ enabled }: { enabled: boolean }): JevQuickSetupState { + const t = useTranslations("RetrievalModes"); + const { refreshCapabilities } = useApp(); + const [provider, setProviderState] = React.useState("302"); + const [endpoint, setEndpointState] = React.useState(JEV_ENDPOINTS["302"]); + const [model, setModel] = React.useState(JEV_DEFAULT_MODEL); + const [apiKey, setApiKeyState] = React.useState(""); + const [testing, setTesting] = React.useState(false); + const [saving, setSaving] = React.useState(false); + const [testResult, setTestResult] = React.useState(null); + const [error, setError] = React.useState(null); + const prefilledRef = React.useRef(false); + const dirtyRef = React.useRef(false); + + React.useEffect(() => { + if (!enabled || prefilledRef.current) return; + prefilledRef.current = true; + api.getModelConfig().then((config) => { + if (dirtyRef.current) return; + const savedEndpoint = config.jev_endpoint?.trim(); + if (savedEndpoint) { + setEndpointState(savedEndpoint); + setProviderState(providerForEndpoint(savedEndpoint)); + } + const savedModel = config.jev_model?.trim(); + if (savedModel) setModel(savedModel); + }).catch(() => { + /* The 302.AI preset stays in place when the saved config cannot be read. */ + }); + }, [enabled]); + + const endpointValid = isValidJevEndpoint(endpoint); + const ready = endpointValid && Boolean(apiKey.trim()); + + const patch = React.useCallback((): ModelConfigPatch => ({ + jev_endpoint: endpoint.trim(), + jev_model: model.trim() || JEV_DEFAULT_MODEL, + jev_api_key: apiKey.trim(), + }), [apiKey, endpoint, model]); + + const setProvider = React.useCallback((next: JevProvider) => { + dirtyRef.current = true; + setTestResult(null); + setError(null); + setProviderState(next); + if (next === "custom") return; + setEndpointState(JEV_ENDPOINTS[next]); + setModel(JEV_DEFAULT_MODEL); + }, []); + + const setEndpoint = React.useCallback((next: string) => { + dirtyRef.current = true; + setTestResult(null); + setError(null); + setEndpointState(next); + }, []); + + const setApiKey = React.useCallback((next: string) => { + dirtyRef.current = true; + setTestResult(null); + setError(null); + setApiKeyState(next); + }, []); + + const test = React.useCallback(async () => { + setTesting(true); + setTestResult(null); + try { + setTestResult(await api.testJevModelConfig(patch())); + } catch (cause) { + setTestResult({ + ok: false, + message: cause instanceof ApiError ? cause.message : t("jevTestFailed"), + }); + } finally { + setTesting(false); + } + }, [patch, t]); + + const save = React.useCallback(async () => { + setSaving(true); + setError(null); + try { + await api.saveModelConfig(patch()); + await refreshCapabilities(); + } catch (cause) { + setError(cause instanceof ApiError ? cause.message : t("jevSaveFailed")); + throw cause; + } finally { + setSaving(false); + } + }, [patch, refreshCapabilities, t]); + + return { + provider, + endpoint, + apiKey, + endpointValid, + ready, + testing, + saving, + testResult, + error, + setProvider, + setEndpoint, + setApiKey, + test, + save, + }; +} + +export function JevQuickSetup({ + setup, + idPrefix, + disabled = false, + className, +}: { + setup: JevQuickSetupState; + idPrefix: string; + disabled?: boolean; + className?: string; +}) { + const t = useTranslations("RetrievalModes"); + const providerName = setup.provider === "custom" ? null : JEV_PROVIDER_NAMES[setup.provider]; + const endpointInvalid = !setup.endpointValid; + + return ( +
+
+

{t("jevSetupTitle")}

+

{t("jevSetupDescription")}

+
+
+ + {t("jevProvider")} + + + + {t("jevEndpoint")} + setup.setEndpoint(event.target.value)} + /> + {endpointInvalid && ( +

{t("jevEndpointInvalid")}

+ )} +
+ + {t("jevApiKey")} +
+ setup.setApiKey(event.target.value)} + /> + +
+
+
+ {setup.testResult && ( +

+ {setup.testResult.message} +

+ )} + {setup.error && ( +

+ {setup.error} +

+ )} +

+ {t("jevSharedNote")}{" "} + + + {t("jevOpenSettings")} + +

+
+ ); +} diff --git a/apps/web/components/features/knowledge-config-form.tsx b/apps/web/components/features/knowledge-config-form.tsx index 6d06adc9..809d4fa3 100644 --- a/apps/web/components/features/knowledge-config-form.tsx +++ b/apps/web/components/features/knowledge-config-form.tsx @@ -30,6 +30,12 @@ import { SEARCH_STRATEGIES, type JevScoredStrategy, } from "@/lib/retrieval-config"; +import { + JEV_DEFAULT_MODEL, + JEV_ENDPOINTS, + providerForEndpoint, + type JevProvider, +} from "@/lib/jev-config"; import type { ModelConfig, ModelConfigPatch } from "@/lib/types"; import { Tooltip, @@ -38,12 +44,6 @@ import { TooltipTrigger, } from "@/components/ui/tooltip"; -const JEV_DEFAULT_MODEL = "jev-latest"; -const JEV_ENDPOINTS = { - "302": "https://api.302.ai/typesafeai/v1/systemone", - official: "https://api.typesafe.ai/v1/systemone", -} as const; -type JevProvider = keyof typeof JEV_ENDPOINTS | "custom"; type SavedJevDraft = { endpoint: string; model: string; @@ -52,12 +52,6 @@ type SavedJevDraft = { strategy: ModelConfig["search_strategy"]; }; -function providerForEndpoint(endpoint: string): JevProvider { - if (!endpoint.trim() || endpoint.trim() === JEV_ENDPOINTS["302"]) return "302"; - if (endpoint.trim() === JEV_ENDPOINTS.official) return "official"; - return "custom"; -} - export function KnowledgeConfigForm() { const t = useTranslations("KnowledgeConfig"); const strategies = useTranslations("SearchStrategies"); diff --git a/apps/web/components/features/knowledge-workspace.test.tsx b/apps/web/components/features/knowledge-workspace.test.tsx index 04ec1a16..e47b003a 100644 --- a/apps/web/components/features/knowledge-workspace.test.tsx +++ b/apps/web/components/features/knowledge-workspace.test.tsx @@ -14,6 +14,7 @@ const source: Source = { source_type: "document", connector_kind: "file_upload", status: "active", + default_search_strategy: null, document_count: 2, chunk_count: 2, event_count: 4, diff --git a/apps/web/components/features/retrieval-mode-picker.test.tsx b/apps/web/components/features/retrieval-mode-picker.test.tsx new file mode 100644 index 00000000..e39eddf0 --- /dev/null +++ b/apps/web/components/features/retrieval-mode-picker.test.tsx @@ -0,0 +1,148 @@ +/** @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 { needsJevQuickSetup, type SearchStrategy, type SearchStrategyDisabledMap } from "@/lib/retrieval-config"; +import { useJevQuickSetup } from "./jev-quick-setup"; +import { RetrievalModePicker } from "./retrieval-mode-picker"; + +vi.mock("next/link", () => ({ + default: React.forwardRef>( + function Link({ children, href, ...props }, ref) { return {children}; }, + ), +})); +vi.mock("@/components/features/app-shell", () => ({ useApp: () => ({ refreshCapabilities: vi.fn() }) })); + +let root: Root; +let container: HTMLDivElement; +const onValueChange = vi.fn<(value: SearchStrategy | null) => void>(); + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + onValueChange.mockClear(); + 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; +} + +function Harness({ value, disabledMap, withJevSetup = false }: { + value: SearchStrategy | null; disabledMap?: SearchStrategyDisabledMap; withJevSetup?: boolean; +}) { + const jevSetup = useJevQuickSetup({ enabled: needsJevQuickSetup(value, disabledMap) }); + return ( + + ); +} + +async function mount(props: React.ComponentProps) { + await act(async () => root.render( + , + )); +} +async function openOptions() { + const trigger = container.querySelector('[data-testid="retrieval-mode-picker"]')!; + await act(async () => trigger.dispatchEvent(pointerEvent("pointerdown"))); + return [...document.body.querySelectorAll('[role="option"]')]; +} +const description = () => container.querySelector('[data-testid="retrieval-mode-description"]')!.textContent ?? ""; + +describe("retrieval mode picker", () => { + it("lists follow-global first with the current default, then every mode with paid badges", async () => { + await mount({ value: null }); + expect(container.querySelector('[data-testid="retrieval-mode-picker"]')?.textContent).toContain("Follow the global default (currently: Fast (vector))"); + const options = await openOptions(); + expect(options.map(option => option.getAttribute("data-testid"))).toEqual([ + "retrieval-mode-global", "retrieval-mode-vector", "retrieval-mode-multi_es_fast", + "retrieval-mode-multi", "retrieval-mode-multi_jev", "retrieval-mode-sag2", + ]); + expect(document.body.querySelector('[data-testid="retrieval-mode-sag2-paid"]')?.textContent).toBe("Paid"); + expect(document.body.querySelector('[data-testid="retrieval-mode-multi_jev-paid"]')?.textContent).toBe("Paid"); + expect(document.body.querySelector('[data-testid="retrieval-mode-vector-paid"]')).toBeNull(); + const sag2 = options.find(option => option.getAttribute("data-testid") === "retrieval-mode-sag2")!; + await act(async () => { sag2.dispatchEvent(pointerEvent("pointerdown")); sag2.dispatchEvent(pointerEvent("pointerup")); }); + expect(onValueChange).toHaveBeenCalledWith("sag2"); + }); + it("reports follow-global as null and describes the global mode", async () => { + await mount({ value: "multi" }); + const global = (await openOptions()).find(option => option.getAttribute("data-testid") === "retrieval-mode-global")!; + await act(async () => { global.dispatchEvent(pointerEvent("pointerdown")); global.dispatchEvent(pointerEvent("pointerup")); }); + expect(onValueChange).toHaveBeenCalledWith(null); + await mount({ value: null }); + expect(description()).toContain("uses whatever default is chosen in Settings"); + expect(description()).toContain("Current global default: Fast (vector)"); + expect(description()).toContain("Finds the passages closest in meaning"); + }); + it("shows a plain-language summary, when to use it and the paid note for the selected mode", async () => { + await mount({ value: "sag2" }); + expect(description()).toContain("searches the original text over several rounds"); + expect(description()).toContain("Higher usage per search, billed by volume"); + expect(container.querySelector('[data-testid="retrieval-mode-paid-note"]')?.textContent).toBe("Paid service · needs a JEV API key"); + await mount({ value: "vector" }); + expect(description()).toContain("Fastest and cheapest"); + expect(container.querySelector('[data-testid="retrieval-mode-paid-note"]')).toBeNull(); + }); + it("disables modes the deployment cannot serve and shows the reason, but keeps key-only blockers selectable", async () => { + await mount({ + value: null, + disabledMap: { + multi_jev: { reason: "vector_provider_lacks_lexical", message: "Needs lexical search" }, + sag2: { reason: "jev_api_key_missing", message: "Add a JEV API key" }, + }, + }); + const options = await openOptions(); + const multiJev = options.find(option => option.getAttribute("data-testid") === "retrieval-mode-multi_jev")!; + const sag2 = options.find(option => option.getAttribute("data-testid") === "retrieval-mode-sag2")!; + expect(multiJev.getAttribute("aria-disabled")).toBe("true"); + expect(multiJev.textContent).toContain("Unavailable"); + expect(multiJev.textContent).toContain("Needs lexical search"); + expect(sag2.getAttribute("aria-disabled")).not.toBe("true"); + expect(sag2.textContent).toContain("Key needed"); + expect(sag2.textContent).not.toContain("Add a JEV API key"); + }); + it.each(["jev_not_configured", "jev_api_key_missing"])("renders the inline JEV setup for %s", async reason => { + await mount({ value: "sag2", withJevSetup: true, disabledMap: { sag2: { reason, message: "Add a JEV API key" } } }); + const setup = container.querySelector('[data-testid="jev-quick-setup"]')!; + expect(setup).not.toBeNull(); + expect(setup.textContent).toContain("Set up the JEV service first"); + expect(setup.textContent).toContain("Settings → Knowledge → JEV reranking service"); + expect(container.querySelector("#mode-jev-endpoint")!.value).toBe("https://api.302.ai/typesafeai/v1/systemone"); + expect(container.querySelector("#mode-jev-endpoint")!.readOnly).toBe(true); + expect(container.querySelector("#mode-jev-api-key")!.type).toBe("password"); + expect(container.querySelector('[data-testid="jev-quick-setup-settings"]')!.getAttribute("href")).toBe("/settings?tab=knowledge§ion=jev"); + expect(container.querySelector('[data-testid="jev-quick-setup-test"]')!.disabled).toBe(true); + }); + it.each([ + ["sag2" as const, "sag2_relational_unsupported"], + ["multi_jev" as const, "vector_provider_lacks_lexical"], + ["sag2" as const, "unsupported_backend"], + ])("hides the inline setup for %s blocked by %s", async (value, reason) => { + await mount({ value, withJevSetup: true, disabledMap: { [value]: { reason, message: "Not here" } } }); + expect(container.querySelector('[data-testid="jev-quick-setup"]')).toBeNull(); + expect(description()).toContain("Not here"); + }); + it("hides the inline setup for non-JEV modes and when the service is already configured", async () => { + await mount({ value: "multi", withJevSetup: true, disabledMap: { sag2: { reason: "jev_api_key_missing", message: "Add a key" } } }); + expect(container.querySelector('[data-testid="jev-quick-setup"]')).toBeNull(); + await mount({ value: "sag2", withJevSetup: true }); + expect(container.querySelector('[data-testid="jev-quick-setup"]')).toBeNull(); + }); +}); diff --git a/apps/web/components/features/retrieval-mode-picker.tsx b/apps/web/components/features/retrieval-mode-picker.tsx new file mode 100644 index 00000000..277cb678 --- /dev/null +++ b/apps/web/components/features/retrieval-mode-picker.tsx @@ -0,0 +1,157 @@ +"use client"; + +import * as React from "react"; +import { useTranslations } from "next-intl"; + +import { JevQuickSetup, type JevQuickSetupState } from "@/components/features/jev-quick-setup"; +import { Field, FieldLabel } from "@/components/ui/field"; +import { + Select, + SelectContent, + SelectItem, + SelectSeparator, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { + getSearchStrategy, + isJevConfigDisabledReason, + isJevScoredStrategy, + needsJevQuickSetup, + SEARCH_STRATEGIES, + SEARCH_STRATEGY_ICONS, + type SearchStrategy, + type SearchStrategyDisabledMap, +} from "@/lib/retrieval-config"; +import { cn } from "@/lib/utils"; + +/** Select value standing in for "no source default; follow the global setting". */ +export const FOLLOW_GLOBAL_VALUE = "__global__"; + +const MODE_COPY = { + vector: { summary: "vectorSummary", whenToUse: "vectorWhenToUse" }, + multi_es_fast: { summary: "multiEsFastSummary", whenToUse: "multiEsFastWhenToUse" }, + multi: { summary: "multiSummary", whenToUse: "multiWhenToUse" }, + multi_jev: { summary: "multiJevSummary", whenToUse: "multiJevWhenToUse" }, + sag2: { summary: "sag2Summary", whenToUse: "sag2WhenToUse" }, +} as const satisfies Record; + +const badgeClassName = + "rounded bg-muted px-1 py-0.5 text-[10px] font-normal leading-none text-muted-foreground"; + +export function RetrievalModePicker({ + id, + value, + onValueChange, + globalStrategy, + disabledMap, + disabled = false, + jevSetup, +}: { + id: string; + /** `null` follows the global default. */ + value: SearchStrategy | null; + onValueChange: (value: SearchStrategy | null) => void; + globalStrategy: SearchStrategy; + /** `capabilities.search_strategies_disabled`, normalised by `getSearchStrategiesDisabled`. */ + disabledMap?: SearchStrategyDisabledMap; + disabled?: boolean; + /** + * Inline JEV service setup. Rendered under the description only while the + * selected mode is JEV-scored and blocked solely by a missing configuration. + */ + jevSetup?: JevQuickSetupState; +}) { + const t = useTranslations("RetrievalModes"); + const strategies = useTranslations("SearchStrategies"); + const globalMode = getSearchStrategy(globalStrategy); + const globalLabel = strategies(globalMode.labelKey); + const selected = value ? getSearchStrategy(value) : null; + const selectedInfo = selected ? disabledMap?.[selected.value] : undefined; + const selectedUnavailable = Boolean(selectedInfo) && !isJevConfigDisabledReason(selectedInfo?.reason); + const showJevSetup = jevSetup !== undefined && needsJevQuickSetup(value, disabledMap); + const describedMode = selected ?? globalMode; + + return ( + + {t("label")} + + +
+ {!selected && ( + <> +

{t("followGlobalDescription")}

+

{t("globalModeLead", { label: globalLabel })}

+ + )} +

{t(MODE_COPY[describedMode.value].summary)}

+

{t(MODE_COPY[describedMode.value].whenToUse)}

+ {isJevScoredStrategy(describedMode.value) && ( +

+ {t("paidNeedsKey")} +

+ )} + {selectedUnavailable && selectedInfo && ( +

{selectedInfo.message}

+ )} +
+ + {showJevSetup && jevSetup && ( + + )} +
+ ); +} diff --git a/apps/web/components/features/retrieval-mode-pill.tsx b/apps/web/components/features/retrieval-mode-pill.tsx new file mode 100644 index 00000000..994156d8 --- /dev/null +++ b/apps/web/components/features/retrieval-mode-pill.tsx @@ -0,0 +1,51 @@ +"use client"; + +import { useTranslations } from "next-intl"; + +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { + getSearchStrategy, + SEARCH_STRATEGY_ICONS, + type SearchStrategy, +} from "@/lib/retrieval-config"; +import { cn } from "@/lib/utils"; + +/** Compact "default retrieval mode" marker shown next to a source's name. */ +export function RetrievalModePill({ + strategy, + className, + tooltipSide = "bottom", +}: { + strategy: SearchStrategy; + className?: string; + tooltipSide?: React.ComponentProps["side"]; +}) { + const t = useTranslations("RetrievalModes"); + const strategies = useTranslations("SearchStrategies"); + const mode = getSearchStrategy(strategy); + const Icon = SEARCH_STRATEGY_ICONS[mode.value]; + const label = strategies(mode.labelKey); + const tooltip = t("pillTooltip", { label }); + + return ( + + + + + {label} + + + + {tooltip} + + + ); +} diff --git a/apps/web/components/features/search-strategy-control.test.tsx b/apps/web/components/features/search-strategy-control.test.tsx index 0f903311..960ddd12 100644 --- a/apps/web/components/features/search-strategy-control.test.tsx +++ b/apps/web/components/features/search-strategy-control.test.tsx @@ -35,10 +35,10 @@ function pointerEvent(type: string) { Object.defineProperties(event, { pointerId: { value: 1 }, pointerType: { value: "mouse" } }); return event; } -async function open(disabledMap?: SearchStrategyDisabledMap, value: SearchStrategy = "vector") { +async function open(disabledMap?: SearchStrategyDisabledMap, value: SearchStrategy = "vector", hint?: string) { await act(async () => root.render( - + , )); const trigger = container.querySelector('[data-testid="search-strategy"]')!; @@ -60,6 +60,14 @@ describe("search strategy dropdown", () => { expect(item(items, "SAG2 evidence retrieval").textContent).toContain("BM25 recall scored over several JEV rounds"); expect(document.body.querySelector('[data-testid$="-settings"]')).toBeNull(); }); + it("shows where the current mode came from when a hint is given", async () => { + await open(undefined, "sag2", "Source default"); + const hint = container.querySelector('[data-testid="search-strategy-hint"]'); + expect(hint?.textContent).toContain("Source default"); + expect(document.body.querySelector('[role="menu"]')?.textContent).toContain("Source default"); + await open(undefined, "sag2"); + expect(container.querySelector('[data-testid="search-strategy-hint"]')).toBeNull(); + }); it("selects SAG2 when it is enabled", async () => { const items = await open(); const sag2 = item(items, "SAG2 evidence retrieval"); diff --git a/apps/web/components/features/search-strategy-control.tsx b/apps/web/components/features/search-strategy-control.tsx index 60b4a445..6d08a0d6 100644 --- a/apps/web/components/features/search-strategy-control.tsx +++ b/apps/web/components/features/search-strategy-control.tsx @@ -1,17 +1,9 @@ "use client"; -import { - Check, - ChevronDown, - ScanSearch, - Settings2, - ShieldQuestion, - Sparkles, - Zap, -} from "lucide-react"; +import { Check, ChevronDown, Settings2 } from "lucide-react"; import { useTranslations } from "next-intl"; import Link from "next/link"; -import { Fragment, type ComponentType } from "react"; +import { Fragment } from "react"; import { DropdownMenu, @@ -32,19 +24,12 @@ import { isJevConfigDisabledReason, isJevScoredStrategy, SEARCH_STRATEGIES, + SEARCH_STRATEGY_ICONS, type SearchStrategy, type SearchStrategyDisabledMap, } from "@/lib/retrieval-config"; import { settingsTabHref } from "@/lib/settings-config"; -const STRATEGY_ICONS: Record> = { - vector: Zap, - multi_es_fast: ShieldQuestion, - multi: Sparkles, - multi_jev: Sparkles, - sag2: ScanSearch, -}; - /** The shared JEV service section inside the knowledge settings tab. */ const JEV_SETTINGS_HREF = settingsTabHref("knowledge", "jev"); @@ -56,6 +41,7 @@ export function SearchStrategyControl({ defaultValue, onValueChange, disabledMap, + hint, }: { value: SearchStrategy; defaultValue: SearchStrategy; @@ -65,10 +51,12 @@ export function SearchStrategyControl({ * key 缺失即启用,存在即灰置 + Tooltip 展示 message。 */ disabledMap?: SearchStrategyDisabledMap; + /** Short muted note on where the current value came from (e.g. the scoped source's default). */ + hint?: string; }) { const t = useTranslations("SearchStrategies"); const currentStrategy = getSearchStrategy(value); - const CurrentIcon = STRATEGY_ICONS[currentStrategy.value]; + const CurrentIcon = SEARCH_STRATEGY_ICONS[currentStrategy.value]; return ( @@ -82,15 +70,21 @@ export function SearchStrategyControl({ > {t(currentStrategy.labelKey)} + {hint && ( + + · {hint} + + )} - + {t("mode")} + {hint && {hint}} {SEARCH_STRATEGIES.map((strategy) => { - const Icon = STRATEGY_ICONS[strategy.value]; + const Icon = SEARCH_STRATEGY_ICONS[strategy.value]; const selected = strategy.value === value; const isDefault = strategy.value === defaultValue; const paid = isJevScoredStrategy(strategy.value); diff --git a/apps/web/components/features/search/search-panel.tsx b/apps/web/components/features/search/search-panel.tsx index 4983783d..decd1834 100644 --- a/apps/web/components/features/search/search-panel.tsx +++ b/apps/web/components/features/search/search-panel.tsx @@ -120,6 +120,7 @@ export function SearchPanel({ }: SearchPanelProps) { const t = useTranslations("Search"); const searchStrategies = useTranslations("SearchStrategies"); + const retrievalModes = useTranslations("RetrievalModes"); const search = useSearchWorkspace(); const { capabilities } = useApp(); const ensureSources = search.ensureSources; @@ -269,8 +270,10 @@ export function SearchPanel({ }, [search]); function changeStrategy(value: SearchStrategy) { - if (value === search.strategy) return; + const changed = value !== search.strategy; + // Pin even an unchanged pick so a later scope change no longer overrides it. search.setStrategy(value); + if (!changed) return; const activeQuery = search.query.trim() || search.lastQuery; if ((search.result !== null || search.busy) && activeQuery) { void executeSearch({ @@ -440,6 +443,7 @@ export function SearchPanel({ defaultValue={search.defaultStrategy} onValueChange={changeStrategy} disabledMap={getSearchStrategiesDisabled(capabilities, searchStrategies("unsupportedBackend"))} + hint={search.strategyOrigin === "scope" ? retrievalModes("scopeDefaultHint") : undefined} /> {mentionOpen && ( diff --git a/apps/web/components/features/search/search-provider.tsx b/apps/web/components/features/search/search-provider.tsx index 365ab2ec..eac7f28f 100644 --- a/apps/web/components/features/search/search-provider.tsx +++ b/apps/web/components/features/search/search-provider.tsx @@ -5,7 +5,7 @@ import { useTranslations } from "next-intl"; import { api, ApiError } from "@/lib/api"; import { isSourceDeleting } from "@/lib/source-activity"; -import type { SearchStrategy } from "@/lib/retrieval-config"; +import { getScopeDefaultStrategy, type SearchStrategy } from "@/lib/retrieval-config"; import type { ActivityItem, SearchResponse, Source } from "@/lib/types"; import { activationFromSearch, @@ -31,8 +31,13 @@ export type { SearchPhase, SearchRunIntent } from "@/components/features/search/ export interface SearchScope { id: string; name: string; + /** Carried over from the full source when known, so the scope default resolves before the source list loads. */ + default_search_strategy?: SearchStrategy | null; } +/** Where the strategy shown in the search control came from. */ +export type SearchStrategyOrigin = "pinned" | "scope" | "global"; + export interface SearchRunOptions { query?: string; topK?: number; @@ -49,7 +54,10 @@ interface SearchWorkspaceState extends SearchLifecycleState { query: string; scoped: SearchScope[]; sources: Source[]; + /** The user's explicit pick while `strategyPinned`; otherwise mirrors the global default. */ strategy: SearchStrategy; + /** True once the user picked a strategy in this session; scope defaults no longer override it. */ + strategyPinned: boolean; activity: ActivityItem[] | null; history: string[]; contentView: SearchContentView; @@ -58,6 +66,9 @@ interface SearchWorkspaceState extends SearchLifecycleState { interface SearchWorkspaceContextValue extends SearchWorkspaceState { defaultStrategy: SearchStrategy; + /** Common non-null default of every scoped source, or null when they disagree or nothing is scoped. */ + scopeDefaultStrategy: SearchStrategy | null; + strategyOrigin: SearchStrategyOrigin; canLoadMore: boolean; setQuery: (query: string) => void; setStrategy: (strategy: SearchStrategy) => void; @@ -186,6 +197,7 @@ export function SearchProvider({ committedSearchKey: "", lastQuery: "", strategy: defaultStrategy, + strategyPinned: false, lastStrategy: defaultStrategy, topK: DEFAULT_SEARCH_TOP_K, hasMore: false, @@ -232,11 +244,29 @@ export function SearchProvider({ setState((current) => ({ ...current, strategy: defaultStrategy, + strategyPinned: false, lastStrategy: defaultStrategy, })); } }, [defaultStrategy]); + // Sources scoped through the picker carry their own default; scopes restored + // from a URL only have an id, so fall back to the loaded source list. + const scopeDefaultStrategy = React.useMemo(() => getScopeDefaultStrategy( + state.scoped.map((scope) => state.sources.find((source) => source.id === scope.id) ?? scope), + disabledMap, + ), [disabledMap, state.scoped, state.sources]); + const effectiveStrategy = state.strategyPinned + ? state.strategy + : (scopeDefaultStrategy ?? defaultStrategy); + const strategyOrigin: SearchStrategyOrigin = state.strategyPinned + ? "pinned" + : scopeDefaultStrategy + ? "scope" + : "global"; + const effectiveStrategyRef = React.useRef(effectiveStrategy); + effectiveStrategyRef.current = effectiveStrategy; + const cancel = React.useCallback(() => { const activeRequest = activeRequestRef.current; requestIdRef.current += 1; @@ -346,7 +376,7 @@ export function SearchProvider({ return null; } - const strategy = options.strategy ?? snapshot.strategy; + const strategy = options.strategy ?? effectiveStrategyRef.current; const sourceIds = options.sourceIds ?? (snapshot.scoped.length ? snapshot.scoped.map((source) => source.id) : undefined); const requestedKey = createSearchKey({ query, strategy, sourceIds }); @@ -495,7 +525,7 @@ export function SearchProvider({ }, [clear, t]); const setStrategy = React.useCallback((strategy: SearchStrategy) => { - setState((current) => ({ ...current, strategy })); + setState((current) => ({ ...current, strategy, strategyPinned: true })); }, []); // capabilities 变化后,如果当前选中的策略已被后端标记为不可用, @@ -505,7 +535,7 @@ export function SearchProvider({ setState((current) => { if (!disabledMap[current.strategy]) return current; if (current.strategy === defaultStrategy) return current; - return { ...current, strategy: defaultStrategy }; + return { ...current, strategy: defaultStrategy, strategyPinned: false }; }); }, [disabledMap, defaultStrategy]); @@ -518,7 +548,11 @@ export function SearchProvider({ ...current, scoped: current.scoped.some((item) => item.id === source.id) ? current.scoped.filter((item) => item.id !== source.id) - : [...current.scoped, { id: source.id, name: source.name }], + : [...current.scoped, { + id: source.id, + name: source.name, + default_search_strategy: source.default_search_strategy ?? null, + }], })); }, []); @@ -562,7 +596,7 @@ export function SearchProvider({ const draftSearchKey = createSearchKey({ query: state.query, - strategy: state.strategy, + strategy: effectiveStrategy, sourceIds: state.scoped.map((source) => source.id), }); const canLoadMore = canLoadMoreSearch({ @@ -577,7 +611,10 @@ export function SearchProvider({ const value = React.useMemo( () => ({ ...state, + strategy: effectiveStrategy, defaultStrategy, + scopeDefaultStrategy, + strategyOrigin, canLoadMore, setQuery, setStrategy, @@ -599,6 +636,9 @@ export function SearchProvider({ canLoadMore, clear, defaultStrategy, + effectiveStrategy, + scopeDefaultStrategy, + strategyOrigin, ensureActivity, ensureSources, clearHistory, diff --git a/apps/web/components/features/search/search-scope-default.test.tsx b/apps/web/components/features/search/search-scope-default.test.tsx new file mode 100644 index 00000000..fa1ba28a --- /dev/null +++ b/apps/web/components/features/search/search-scope-default.test.tsx @@ -0,0 +1,126 @@ +/** @vitest-environment jsdom */ +import * as React from "react"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { NextIntlClientProvider } from "next-intl"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import messages from "@/messages/zh-CN.json"; +import type { SearchStrategy, SearchStrategyDisabledMap } from "@/lib/retrieval-config"; +import type { Source } from "@/lib/types"; +import { SearchProvider, useSearchWorkspace, type SearchScope } from "./search-provider"; + +afterEach(() => { vi.unstubAllGlobals(); }); + +function source(id: string, defaultStrategy: SearchStrategy | null): Source { + return { + id, name: id, description: "", source_type: "document", connector_kind: "file_upload", status: "active", + default_search_strategy: defaultStrategy, document_count: 0, chunk_count: 0, event_count: 0, + created_at: "2026-10-24T00:00:00Z", updated_at: "2026-10-24T00:00:00Z", + }; +} +const sources = [source("a", "sag2"), source("b", "sag2"), source("c", "multi"), source("d", null)]; +const scope = (...ids: string[]): SearchScope[] => ids.map((id) => ({ id, name: id })); + +function Controls({ onReady }: { onReady: (workspace: ReturnType) => void }) { + const workspace = useSearchWorkspace(); + onReady(workspace); + return <> +
{workspace.strategy}
+
{workspace.strategyOrigin}
+
{workspace.scopeDefaultStrategy ?? "none"}
+ ; +} + +async function harness(disabledMap?: SearchStrategyDisabledMap) { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const requests: Array> = []; + vi.stubGlobal("fetch", async (url: RequestInfo | URL, options?: RequestInit) => { + if (String(url).endsWith("/sources")) return Response.json(sources); + requests.push(JSON.parse(String(options?.body))); + return Response.json({ error: { code: "boom", message: "stopped" } }, { status: 500 }); + }); + let workspace!: ReturnType; + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + await act(async () => root.render( + + { workspace = value; }} /> + + )); + const read = (id: string) => container.querySelector(`#${id}`)?.textContent; + return { + requests, + read, + get workspace() { return workspace; }, + act: (callback: () => unknown) => act(async () => { await callback(); }), + cleanup: async () => { await act(async () => root.unmount()); container.remove(); }, + }; +} + +describe("search scope default strategy", () => { + it("follows the shared default of the scoped sources once they are loaded", async () => { + const h = await harness(); + try { + expect(h.read("strategy")).toBe("vector"); + expect(h.read("origin")).toBe("global"); + await h.act(() => h.workspace.setScope(scope("a", "b"))); + // Scopes restored by id alone resolve only after the source list arrives. + expect(h.read("origin")).toBe("global"); + await h.act(() => h.workspace.ensureSources()); + expect(h.read("strategy")).toBe("sag2"); + expect(h.read("origin")).toBe("scope"); + expect(h.read("scope-default")).toBe("sag2"); + await h.act(() => h.workspace.setScope(scope("a", "c"))); + expect(h.read("strategy")).toBe("vector"); + expect(h.read("origin")).toBe("global"); + await h.act(() => h.workspace.setScope(scope("a", "d"))); + expect(h.read("origin")).toBe("global"); + await h.act(() => h.workspace.setScope([])); + expect(h.read("origin")).toBe("global"); + } finally { await h.cleanup(); } + }); + it("uses the default carried by a toggled source before the list loads", async () => { + const h = await harness(); + try { + await h.act(() => h.workspace.toggleSource(sources[2])); + expect(h.read("strategy")).toBe("multi"); + expect(h.read("origin")).toBe("scope"); + } finally { await h.cleanup(); } + }); + it("ignores a scope default the deployment can no longer serve", async () => { + const h = await harness({ sag2: { reason: "jev_api_key_missing", message: "Add a key" } }); + try { + await h.act(() => h.workspace.toggleSource(sources[0])); + expect(h.read("strategy")).toBe("vector"); + expect(h.read("origin")).toBe("global"); + } finally { await h.cleanup(); } + }); + it("keeps an explicit pick across scope changes and sends it with the request", async () => { + const h = await harness(); + try { + await h.act(() => h.workspace.ensureSources()); + await h.act(() => h.workspace.setScope(scope("a", "b"))); + expect(h.read("strategy")).toBe("sag2"); + await h.act(() => h.workspace.setStrategy("multi_es_fast")); + expect(h.read("strategy")).toBe("multi_es_fast"); + expect(h.read("origin")).toBe("pinned"); + await h.act(() => h.workspace.setScope(scope("a"))); + expect(h.read("strategy")).toBe("multi_es_fast"); + expect(h.read("origin")).toBe("pinned"); + await h.act(() => h.workspace.run({ query: "question" }).catch(() => {})); + expect(h.requests).toEqual([expect.objectContaining({ strategy: "multi_es_fast", source_ids: ["a"] })]); + } finally { await h.cleanup(); } + }); + it("runs with the scope default when nothing is pinned", async () => { + const h = await harness(); + try { + await h.act(() => h.workspace.ensureSources()); + await h.act(() => h.workspace.setScope(scope("b"))); + await h.act(() => h.workspace.run({ query: "question" }).catch(() => {})); + expect(h.requests).toEqual([expect.objectContaining({ strategy: "sag2", source_ids: ["b"] })]); + expect(h.read("origin")).toBe("scope"); + } finally { await h.cleanup(); } + }); +}); diff --git a/apps/web/components/features/source-card.test.tsx b/apps/web/components/features/source-card.test.tsx index 4c5e423c..cab5328b 100644 --- a/apps/web/components/features/source-card.test.tsx +++ b/apps/web/components/features/source-card.test.tsx @@ -16,6 +16,7 @@ const source: Source = { source_type: "document", connector_kind: "file_upload", status: "active", + default_search_strategy: null, document_count: 2, chunk_count: 2, event_count: 4, @@ -23,21 +24,25 @@ const source: Source = { updated_at: "2026-07-27T12:00:00Z", }; +function render(value: Source) { + return renderToStaticMarkup( + + + + + + + , + ); +} + describe("source card", () => { it("exposes an always-visible source id control outside its navigation link", () => { - const html = renderToStaticMarkup( - - - - - - - , - ); + const html = render(source); const navigationEnd = html.indexOf(""); const copyButton = html.indexOf('aria-label="复制信源 ID"'); @@ -49,4 +54,16 @@ describe("source card", () => { expect(navigationEnd).toBeGreaterThanOrEqual(0); expect(copyButton).toBeGreaterThan(navigationEnd); }); + + it("shows a default retrieval mode pill only when the source sets one", () => { + expect(render(source)).not.toContain('data-testid="source-default-mode"'); + expect(render({ ...source, default_search_strategy: undefined } as unknown as Source)) + .not.toContain('data-testid="source-default-mode"'); + + const html = render({ ...source, default_search_strategy: "sag2" }); + expect(html).toContain('data-testid="source-default-mode"'); + expect(html).toContain('data-strategy="sag2"'); + expect(html).toContain("SAG2 证据检索"); + expect(html).toContain('aria-label="默认检索模式:SAG2 证据检索;搜索和问答时仍可临时切换"'); + }); }); diff --git a/apps/web/components/features/source-card.tsx b/apps/web/components/features/source-card.tsx index 5f5b1a7c..3767e84a 100644 --- a/apps/web/components/features/source-card.tsx +++ b/apps/web/components/features/source-card.tsx @@ -11,6 +11,7 @@ import { relativeTime } from "@/lib/format"; import { Button } from "@/components/ui/button"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { EditSourceDialog } from "@/components/features/edit-source-dialog"; +import { RetrievalModePill } from "@/components/features/retrieval-mode-pill"; import { useOctxExports } from "@/components/features/octx-export-provider"; import { useApp } from "@/components/features/app-shell"; import { SourceIdCopy } from "@/components/features/source-id-copy"; @@ -27,6 +28,7 @@ export function SourceCard({ source, onChanged }: { source: Source; onChanged?: const { startExport, isSourceExporting } = useOctxExports(); const exportRunning = isSourceExporting(source.id); + const defaultMode = source.default_search_strategy ?? null; const handleExport = React.useCallback( (event: React.MouseEvent) => { @@ -50,10 +52,13 @@ export function SourceCard({ source, onChanged }: { source: Source; onChanged?: }
-
+

{source.name}

+ {defaultMode && ( + + )}

{source.description || t("noDescription")} diff --git a/apps/web/components/features/source-create-form.test.tsx b/apps/web/components/features/source-create-form.test.tsx new file mode 100644 index 00000000..895e85d1 --- /dev/null +++ b/apps/web/components/features/source-create-form.test.tsx @@ -0,0 +1,156 @@ +/** @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, ApiError } from "@/lib/api"; +import type { Capabilities, Source } from "@/lib/types"; +import { SourceCreateForm } from "./source-create-form"; + +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 created: Source = { + id: "source-1", name: "Manuals", description: "", source_type: "document", connector_kind: "file_upload", + status: "active", default_search_strategy: null, document_count: 0, chunk_count: 0, event_count: 0, + created_at: "2026-10-24T00:00:00Z", updated_at: "2026-10-24T00:00:00Z", +}; +const keyMissing = { reason: "jev_api_key_missing", message: "Add a JEV API key" }; + +let root: Root; +let container: HTMLDivElement; +let onCreated: 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"], + search_strategies_disabled: { multi_jev: keyMissing, sag2: keyMissing }, + }; + state.refreshCapabilities.mockClear(); + onCreated = vi.fn(); + vi.spyOn(api, "createSource").mockImplementation(async body => ({ ...created, ...body }) as Source); + vi.spyOn(api, "saveModelConfig").mockResolvedValue({} as never); + 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(); }); + +async function mount() { + await act(async () => root.render( + , + )); +} +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 type(input: HTMLInputElement | HTMLTextAreaElement, value: string) { + await act(async () => { + Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), "value")!.set!.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} +async function pickMode(testId: string) { + const trigger = container.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")); }); +} +const nameInput = () => container.querySelector('input[maxlength="200"]')!; +const submitButton = () => container.querySelector('button[type="submit"]')!; +async function submit() { + await act(async () => container.querySelector("form")!.requestSubmit()); +} + +describe("source create form", () => { + it("creates a source that follows the global default without sending a strategy", async () => { + await mount(); + await type(nameInput(), "Manuals"); + expect(container.querySelector('[data-testid="jev-quick-setup"]')).toBeNull(); + await submit(); + expect(api.createSource).toHaveBeenCalledWith({ name: "Manuals", description: "" }); + expect(api.saveModelConfig).not.toHaveBeenCalled(); + expect(onCreated).toHaveBeenCalledWith(expect.objectContaining({ id: "source-1" })); + }); + it("sends the chosen default retrieval mode", async () => { + await mount(); + await type(nameInput(), "Manuals"); + await pickMode("retrieval-mode-multi"); + await submit(); + expect(api.createSource).toHaveBeenCalledWith({ name: "Manuals", description: "", default_search_strategy: "multi" }); + expect(api.saveModelConfig).not.toHaveBeenCalled(); + }); + it("blocks creation until a JEV key is entered, then saves the service before creating", async () => { + await mount(); + await type(nameInput(), "Manuals"); + await pickMode("retrieval-mode-sag2"); + expect(container.querySelector('[data-testid="jev-quick-setup"]')).not.toBeNull(); + expect(submitButton().disabled).toBe(true); + expect(container.querySelector('[data-testid="source-form-blocked"]')?.textContent).toBe("Enter a JEV API key to save this default mode."); + + await type(container.querySelector('input[type="password"]')!, "jev-secret"); + expect(submitButton().disabled).toBe(false); + expect(container.querySelector('[data-testid="source-form-blocked"]')).toBeNull(); + + await submit(); + expect(api.saveModelConfig).toHaveBeenCalledWith({ + jev_endpoint: "https://api.302.ai/typesafeai/v1/systemone", jev_model: "jev-latest", jev_api_key: "jev-secret", + }); + expect(state.refreshCapabilities).toHaveBeenCalledTimes(1); + expect(api.createSource).toHaveBeenCalledWith({ name: "Manuals", description: "", default_search_strategy: "sag2" }); + expect(vi.mocked(api.saveModelConfig).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(api.createSource).mock.invocationCallOrder[0]); + }); + it("keeps a saved custom endpoint instead of replacing it with the preset", async () => { + vi.mocked(api.getModelConfig).mockResolvedValue({ jev_endpoint: "https://jev.internal/score", jev_model: "jev-pinned" } as never); + await mount(); + await type(nameInput(), "Manuals"); + await pickMode("retrieval-mode-multi_jev"); + const endpoint = container.querySelector('input[type="url"]')!; + expect(endpoint.value).toBe("https://jev.internal/score"); + expect(endpoint.readOnly).toBe(false); + await type(container.querySelector('input[type="password"]')!, "k"); + await submit(); + expect(api.saveModelConfig).toHaveBeenCalledWith({ jev_endpoint: "https://jev.internal/score", jev_model: "jev-pinned", jev_api_key: "k" }); + }); + it("shows a JEV save failure inline and does not create the source", async () => { + vi.mocked(api.saveModelConfig).mockRejectedValue(new ApiError(400, "jev_invalid", "JEV rejected the key")); + await mount(); + await type(nameInput(), "Manuals"); + await pickMode("retrieval-mode-sag2"); + await type(container.querySelector('input[type="password"]')!, "bad"); + await submit(); + expect(container.querySelector('[data-testid="jev-quick-setup-error"]')?.textContent).toBe("JEV rejected the key"); + expect(api.createSource).not.toHaveBeenCalled(); + expect(onCreated).not.toHaveBeenCalled(); + expect(submitButton().disabled).toBe(false); + }); + it("shows a backend rejection of the default mode inline", async () => { + vi.mocked(api.createSource).mockRejectedValue(new ApiError(400, "vector_provider_lacks_lexical", "Lexical search is required")); + await mount(); + await type(nameInput(), "Manuals"); + await pickMode("retrieval-mode-multi"); + await submit(); + expect(container.querySelector('[data-testid="source-form-error"]')?.textContent).toBe("Lexical search is required"); + expect(onCreated).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/components/features/source-create-form.tsx b/apps/web/components/features/source-create-form.tsx index 4c4123dc..41b73f23 100644 --- a/apps/web/components/features/source-create-form.tsx +++ b/apps/web/components/features/source-create-form.tsx @@ -4,7 +4,17 @@ import * as React from "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"; @@ -22,23 +32,58 @@ export function SourceCreateForm({ compact?: boolean; }) { const t = useTranslations("SourceForm"); + const strategies = useTranslations("SearchStrategies"); + const modes = useTranslations("RetrievalModes"); + const { capabilities } = useApp(); const [name, setName] = React.useState(""); const [description, setDescription] = React.useState(""); + const [mode, setMode] = React.useState(null); const [loading, setLoading] = React.useState(false); + const [error, setError] = React.useState(null); const nameId = React.useId(); const descriptionId = React.useId(); + const modeId = React.useId(); + + 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 = needsJevQuickSetup(mode, disabledMap); + const jevSetup = useJevQuickSetup({ enabled: jevSetupNeeded }); + const jevKeyMissing = jevSetupNeeded && !jevSetup.ready; async function submit(event: React.FormEvent) { event.preventDefault(); + if (jevKeyMissing) return; setLoading(true); + setError(null); try { - const source = await api.createSource({ name: name.trim(), description: description.trim() }); + if (jevSetupNeeded) { + try { + await jevSetup.save(); + } catch { + // The quick setup shows the failure next to its fields. + return; + } + } + const source = await api.createSource({ + name: name.trim(), + description: description.trim(), + ...(mode ? { default_search_strategy: mode } : {}), + }); toast.success(t("created")); onCreated(source); setName(""); setDescription(""); - } catch (error) { - toast.error(error instanceof ApiError ? error.message : t("createFailed")); + setMode(null); + } catch (cause) { + const message = cause instanceof ApiError ? cause.message : t("createFailed"); + setError(message); + toast.error(message); } finally { setLoading(false); } @@ -71,14 +116,37 @@ export function SourceCreateForm({ rows={compact ? 3 : 2} /> + { + setMode(next); + setError(null); + }} + globalStrategy={globalStrategy} + disabledMap={disabledMap} + disabled={loading} + jevSetup={jevSetup} + /> -

+ {error && ( +

+ {error} +

+ )} + +
+ {jevKeyMissing && ( + + {modes("keyRequiredToSubmit")} + + )} {onCancel && ( )} -
diff --git a/apps/web/components/features/source-deletion.test.tsx b/apps/web/components/features/source-deletion.test.tsx index 31c15da4..541194bf 100644 --- a/apps/web/components/features/source-deletion.test.tsx +++ b/apps/web/components/features/source-deletion.test.tsx @@ -18,7 +18,7 @@ import { KnowledgeWorkspace, SourceRow } from "./knowledge-workspace"; const source: Source = { id: "source-1", name: "Reports", description: "", source_type: "document", connector_kind: "file_upload", - status: "active", document_count: 2, chunk_count: 4, event_count: 5, + status: "active", default_search_strategy: null, document_count: 2, chunk_count: 4, event_count: 5, created_at: "2026-10-09T00:00:00Z", updated_at: "2026-10-09T00:00:00Z", }; const deletion: BackgroundJob = { diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts index e556093d..0fafb70a 100644 --- a/apps/web/lib/api.ts +++ b/apps/web/lib/api.ts @@ -786,7 +786,12 @@ export const api = { // 信源 listSources: () => request("/api/v1/sources"), getSource: (id: string) => request(`/api/v1/sources/${id}`), - createSource: (b: { name: string; description?: string }) => + createSource: (b: { + name: string; + description?: string; + /** Omit (or send null) to follow the global default retrieval mode. */ + default_search_strategy?: SearchStrategy | null; + }) => request("/api/v1/sources", { method: "POST", body: JSON.stringify(b), diff --git a/apps/web/lib/jev-config.ts b/apps/web/lib/jev-config.ts new file mode 100644 index 00000000..5145fb38 --- /dev/null +++ b/apps/web/lib/jev-config.ts @@ -0,0 +1,37 @@ +/** + * Shared JEV scoring-service presets. The knowledge settings page and the + * inline quick setup inside the source dialogs write the same three fields + * (`jev_endpoint`, `jev_model`, `jev_api_key`), so they must agree on these. + */ +export const JEV_DEFAULT_MODEL = "jev-latest"; + +export const JEV_ENDPOINTS = { + "302": "https://api.302.ai/typesafeai/v1/systemone", + official: "https://api.typesafe.ai/v1/systemone", +} as const; + +export type JevPresetProvider = keyof typeof JEV_ENDPOINTS; +export type JevProvider = JevPresetProvider | "custom"; + +/** Human-readable provider names shown next to the API key field. */ +export const JEV_PROVIDER_NAMES: Record = { + "302": "302.AI", + official: "TypeSafe", +}; + +export function providerForEndpoint(endpoint: string): JevProvider { + const trimmed = endpoint.trim(); + if (!trimmed || trimmed === JEV_ENDPOINTS["302"]) return "302"; + if (trimmed === JEV_ENDPOINTS.official) return "official"; + return "custom"; +} + +/** A complete HTTP(S) URL without embedded credentials, matching the settings form. */ +export function isValidJevEndpoint(endpoint: string): boolean { + try { + const url = new URL(endpoint.trim()); + return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password; + } catch { + return false; + } +} diff --git a/apps/web/lib/retrieval-config.test.ts b/apps/web/lib/retrieval-config.test.ts index a2839801..5a5bcccc 100644 --- a/apps/web/lib/retrieval-config.test.ts +++ b/apps/web/lib/retrieval-config.test.ts @@ -1,11 +1,14 @@ import { describe, expect, it } from "vitest"; import { + getScopeDefaultStrategy, getSearchStrategiesDisabled, isJevConfigDisabledReason, isJevScoredStrategy, isSearchStrategy, JEV_SCORED_STRATEGIES, + needsJevQuickSetup, SEARCH_STRATEGIES, + SEARCH_STRATEGY_ICONS, SEARCH_STRATEGY_REQUIREMENTS, } from "./retrieval-config"; @@ -68,3 +71,35 @@ describe("SAG2 strategy availability", () => { expect(isJevConfigDisabledReason("jev_not_configured")).toBe(true); }); }); + +describe("source default strategy", () => { + it("resolves a scope default only when every scoped source shares the same non-null value", () => { + expect(getScopeDefaultStrategy([])).toBeNull(); + expect(getScopeDefaultStrategy([{ default_search_strategy: "sag2" }])).toBe("sag2"); + expect(getScopeDefaultStrategy([{ default_search_strategy: "sag2" }, { default_search_strategy: "sag2" }])).toBe("sag2"); + expect(getScopeDefaultStrategy([{ default_search_strategy: "sag2" }, { default_search_strategy: "multi" }])).toBeNull(); + expect(getScopeDefaultStrategy([{ default_search_strategy: "sag2" }, { default_search_strategy: null }])).toBeNull(); + expect(getScopeDefaultStrategy([{ default_search_strategy: "multi" }, {}])).toBeNull(); + expect(getScopeDefaultStrategy([{ default_search_strategy: null }, {}])).toBeNull(); + }); + it("ignores a scope default the deployment currently cannot serve", () => { + const blocked = { sag2: { reason: "jev_api_key_missing", message: "Add a key" } }; + expect(getScopeDefaultStrategy([{ default_search_strategy: "sag2" }], blocked)).toBeNull(); + expect(getScopeDefaultStrategy([{ default_search_strategy: "multi" }], blocked)).toBe("multi"); + }); + it("offers the inline JEV setup only for JEV modes blocked by a missing configuration", () => { + const disabled = { + multi_jev: { reason: "vector_provider_lacks_lexical", message: "Lexical" }, + sag2: { reason: "jev_api_key_missing", message: "Key" }, + }; + expect(needsJevQuickSetup("sag2", disabled)).toBe(true); + expect(needsJevQuickSetup("sag2", { sag2: { reason: "jev_not_configured", message: "Configure" } })).toBe(true); + expect(needsJevQuickSetup("multi_jev", disabled)).toBe(false); + expect(needsJevQuickSetup("multi", { multi: { reason: "jev_api_key_missing", message: "Key" } })).toBe(false); + expect(needsJevQuickSetup("sag2", {})).toBe(false); + expect(needsJevQuickSetup(null, disabled)).toBe(false); + }); + it("has an icon for every mode", () => { + for (const strategy of SEARCH_STRATEGIES) expect(SEARCH_STRATEGY_ICONS[strategy.value]).toBeTypeOf("object"); + }); +}); diff --git a/apps/web/lib/retrieval-config.ts b/apps/web/lib/retrieval-config.ts index 09429ca0..e545cafb 100644 --- a/apps/web/lib/retrieval-config.ts +++ b/apps/web/lib/retrieval-config.ts @@ -1,3 +1,11 @@ +import { + ScanSearch, + ShieldQuestion, + Sparkles, + Zap, + type LucideIcon, +} from "lucide-react"; + export const SEARCH_STRATEGIES = [ { value: "vector", @@ -30,6 +38,15 @@ export type SearchStrategy = (typeof SEARCH_STRATEGIES)[number]["value"]; export const DEFAULT_SEARCH_STRATEGY: SearchStrategy = "vector"; +/** One icon per mode, shared by the search control, the source pill and the picker. */ +export const SEARCH_STRATEGY_ICONS: Record = { + vector: Zap, + multi_es_fast: ShieldQuestion, + multi: Sparkles, + multi_jev: Sparkles, + sag2: ScanSearch, +}; + /** * Capability keys a strategy needs from the current vector provider. * 后端 apps/api/sag_api/enums.py::SEARCH_STRATEGY_REQUIREMENTS 是权威来源; @@ -110,3 +127,35 @@ export function getSearchStrategiesDisabled( } return disabled; } + +/** + * True when a JEV-scored mode is only blocked by an incomplete JEV service + * configuration, i.e. the user can unblock it by entering an API key. + */ +export function needsJevQuickSetup( + strategy: SearchStrategy | null | undefined, + disabledMap: SearchStrategyDisabledMap | null | undefined, +): boolean { + return isJevScoredStrategy(strategy) + && isJevConfigDisabledReason(disabledMap?.[strategy]?.reason); +} + +/** + * The default mode shared by every source in a search scope. The backend only + * honours a source default when all scoped sources agree on the same non-null + * value, so the client mirrors that rule. A scope default the deployment can + * no longer serve (present in `disabledMap`) is ignored as well. + */ +export function getScopeDefaultStrategy( + sources: ReadonlyArray<{ default_search_strategy?: SearchStrategy | null }>, + disabledMap?: SearchStrategyDisabledMap | null, +): SearchStrategy | null { + if (sources.length === 0) return null; + const first = sources[0].default_search_strategy ?? null; + if (!first) return null; + for (const source of sources) { + if ((source.default_search_strategy ?? null) !== first) return null; + } + if (disabledMap?.[first]) return null; + return first; +} diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts index 801d4d0a..c1c3946e 100644 --- a/apps/web/lib/types.ts +++ b/apps/web/lib/types.ts @@ -71,6 +71,12 @@ export interface Source { connector_kind: string; status: SourceStatus; deletion_job?: BackgroundJob | null; + /** + * Default retrieval mode for search and chat scoped to this source. + * `null` follows the global default; older backends omit the field, which + * callers must treat the same way (`source.default_search_strategy ?? null`). + */ + default_search_strategy: SearchStrategy | null; document_count: number; chunk_count: number; event_count: number; diff --git a/apps/web/messages/en-US.json b/apps/web/messages/en-US.json index 11b51e39..7aa1e6d4 100644 --- a/apps/web/messages/en-US.json +++ b/apps/web/messages/en-US.json @@ -285,11 +285,11 @@ "creating": "Creating…", "create": "Create source", "new": "New source", - "dialogDescription": "Sources hold content. After creation, upload documents and SAG will parse, chunk, and extract events automatically.", + "dialogDescription": "Sources hold content. Name it, pick a default retrieval mode, then upload documents to search and chat.", "updated": "Source updated", "updateFailed": "Failed to update source", "edit": "Edit source", - "editDescription": "Change this source’s name and description.", + "editDescription": "Change this source’s name, description and default retrieval mode.", "saving": "Saving…", "saveChanges": "Save changes" }, @@ -619,6 +619,46 @@ "openSettings": "Open settings", "unsupportedBackend": "This server does not advertise support for this JEV-scored mode. Upgrade the server to use it." }, + "RetrievalModes": { + "label": "Default retrieval mode", + "followGlobal": "Follow the global default (currently: {label})", + "followGlobalDescription": "No separate setting: this source uses whatever default is chosen in Settings and changes along with it.", + "globalModeLead": "Current global default: {label}", + "vectorSummary": "Finds the passages closest in meaning to your question.", + "vectorWhenToUse": "Fastest and cheapest; good for clear material and direct questions.", + "multiEsFastSummary": "Keyword and entity recall plus event hops, with no LLM reranking.", + "multiEsFastWhenToUse": "Balanced speed and quality; good for material full of specific terms, model numbers or names.", + "multiSummary": "Combines entity relationships with LLM reranking.", + "multiWhenToUse": "Most complete results, but slower and uses your generation model; good for complex questions and survey-style material.", + "multiJevSummary": "After recall and graph expansion, the JEV service scores each piece of evidence.", + "multiJevWhenToUse": "Fast and accurate, billed per call; needs a JEV API key and a vector store with lexical search.", + "sag2Summary": "The SAG2 algorithm searches the original text over several rounds, scored by the JEV service; no vector store needed and strong on multi-hop follow-ups.", + "sag2WhenToUse": "Higher usage per search, billed by volume; needs a JEV API key. Document ingestion is unchanged.", + "paid": "Paid", + "paidNeedsKey": "Paid service · needs a JEV API key", + "needsKeyBadge": "Key needed", + "unavailable": "Unavailable", + "switchHint": "You can still switch modes per search or chat.", + "pillTooltip": "Default retrieval mode: {label}. You can still switch modes per search or chat.", + "scopeDefaultHint": "Source default", + "keyRequiredToSubmit": "Enter a JEV API key to save this default mode.", + "jevSetupTitle": "Set up the JEV service first", + "jevSetupDescription": "This mode sends your question and candidate evidence to the JEV service for scoring, which needs an API key.", + "jevProvider": "Provider", + "jevProviderOfficial": "TypeSafe official", + "jevProviderCustom": "Custom", + "jevEndpoint": "Service URL", + "jevEndpointInvalid": "Enter a complete HTTP(S) URL.", + "jevApiKey": "API key", + "jevApiKeyPlaceholder": "Enter your {provider} API key", + "jevApiKeyCustomPlaceholder": "Enter the API key for your JEV service", + "jevTest": "Test connection", + "jevTesting": "Testing…", + "jevTestFailed": "Connection test failed", + "jevSaveFailed": "Failed to save the JEV service", + "jevSharedNote": "Saved once for every JEV mode; change it later under Settings → Knowledge → JEV reranking service.", + "jevOpenSettings": "Open settings" + }, "RetrievalTest": { "failed": "Retrieval failed", "title": "Test retrieval · {source}", diff --git a/apps/web/messages/zh-CN.json b/apps/web/messages/zh-CN.json index 8be0c7fc..e4fbd1b9 100644 --- a/apps/web/messages/zh-CN.json +++ b/apps/web/messages/zh-CN.json @@ -285,11 +285,11 @@ "creating": "创建中…", "create": "创建信源", "new": "新建信源", - "dialogDescription": "信源用来装内容。创建后上传文档,SAG 会自动解析、分块并抽取事件。", + "dialogDescription": "信源用来装内容。起个名字、选好默认检索模式,创建后上传文档即可搜索和问答。", "updated": "信源已更新", "updateFailed": "更新失败", "edit": "修改信源", - "editDescription": "调整这个信息源的名称和描述。", + "editDescription": "调整这个信源的名称、描述和默认检索模式。", "saving": "保存中…", "saveChanges": "保存修改" }, @@ -619,6 +619,46 @@ "openSettings": "去设置", "unsupportedBackend": "当前服务端未声明支持此 JEV 评分模式,请升级服务端后使用。" }, + "RetrievalModes": { + "label": "默认检索模式", + "followGlobal": "跟随全局默认(当前:{label})", + "followGlobalDescription": "不单独设置,和系统设置里的默认模式保持一致;全局默认变化时,这个信源会跟着变。", + "globalModeLead": "当前全局默认:{label}", + "vectorSummary": "按语义相似度直接找最接近的段落。", + "vectorWhenToUse": "响应最快、成本最低;适合资料清晰、问题直接的知识库。", + "multiEsFastSummary": "关键词与实体召回加事件多跳,不调用大模型精排。", + "multiEsFastWhenToUse": "速度与效果均衡;适合有明确名词、型号、人名的资料。", + "multiSummary": "结合实体关系并由大模型精排。", + "multiWhenToUse": "结果最完整但更慢、消耗生成模型;适合复杂问题与综述型资料。", + "multiJevSummary": "召回与图扩展后,由 JEV 服务给每条证据打相关性分。", + "multiJevWhenToUse": "速度快、准确率高,按次计费;需要 JEV API Key 且向量库支持词法检索。", + "sag2Summary": "由 SAG2 算法在原文上多轮检索并由 JEV 服务评分,不依赖向量库,擅长多跳追问。", + "sag2WhenToUse": "每次检索用量较高、按量计费;需要 JEV API Key。文档入库流程不变。", + "paid": "付费", + "paidNeedsKey": "付费服务 · 需要 JEV API Key", + "needsKeyBadge": "待填 Key", + "unavailable": "不可用", + "switchHint": "搜索和问答时仍可临时切换。", + "pillTooltip": "默认检索模式:{label};搜索和问答时仍可临时切换", + "scopeDefaultHint": "信源默认", + "keyRequiredToSubmit": "填写 JEV API Key 后才能保存这个默认模式。", + "jevSetupTitle": "先配置 JEV 服务", + "jevSetupDescription": "这个模式会把问题和候选证据发给 JEV 服务打分,需要一个 API Key。", + "jevProvider": "服务商", + "jevProviderOfficial": "TypeSafe 官方", + "jevProviderCustom": "自定义", + "jevEndpoint": "服务地址", + "jevEndpointInvalid": "请填写完整的 HTTP(S) 地址。", + "jevApiKey": "API Key", + "jevApiKeyPlaceholder": "填写 {provider} API Key", + "jevApiKeyCustomPlaceholder": "填写 JEV 服务的 API Key", + "jevTest": "测试连接", + "jevTesting": "测试中…", + "jevTestFailed": "连接测试失败", + "jevSaveFailed": "JEV 服务保存失败", + "jevSharedNote": "保存后用于全部 JEV 模式,可在 设置 → 知识库 → JEV 精排服务 中修改。", + "jevOpenSettings": "打开设置" + }, "RetrievalTest": { "failed": "检索失败", "title": "检索测试 · {source}", From 94b7a94c97e1e6e97db5bdd3d7586979b810ad35 Mon Sep 17 00:00:00 2001 From: luoshuai990529 <58510855+luoshuai990529@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:46:34 +0800 Subject: [PATCH 4/7] =?UTF-8?q?test(api):=20=E4=BF=A1=E6=BA=90=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E6=A8=A1=E5=BC=8F=E7=94=A8=E4=BE=8B=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E5=9C=A8=E6=94=B6=E5=B0=BE=E6=97=B6=E5=88=A0=E9=99=A4=E4=BF=A1?= =?UTF-8?q?=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 删除会排入后台任务并持续写库,与应用关闭时的清理争抢 SQLite 锁, 导致全量运行偶发 `database is locked`;与其他接口测试一致,保留信源 Co-Authored-By: Claude Fable 5.1 --- apps/api/tests/test_source_default_strategy.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/apps/api/tests/test_source_default_strategy.py b/apps/api/tests/test_source_default_strategy.py index 65be70bf..8b47544d 100644 --- a/apps/api/tests/test_source_default_strategy.py +++ b/apps/api/tests/test_source_default_strategy.py @@ -159,9 +159,8 @@ async def test_source_default_mode_is_validated_persisted_and_clearable(source_c assert cleared.status_code == 200, cleared.text assert cleared.json()["default_search_strategy"] is None assert cleared.json()["name"] == "改名" - - for sid in (source_id, plain.json()["id"]): - await client.delete(f"/api/v1/sources/{sid}") + # 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): @@ -203,7 +202,6 @@ async def grep_chunks(self, *args, **kwargs): assert explicit.json()["stats"]["strategy_origin"] == "request" finally: app.dependency_overrides.pop(get_engine_manager, None) - await client.delete(f"/api/v1/sources/{source_id}") def test_require_strategy_available_matches_capability_report(): From b7bcb0e31f2b17e758263560af4895c155ada968 Mon Sep 17 00:00:00 2001 From: luoshuai990529 <58510855+luoshuai990529@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:17:12 +0800 Subject: [PATCH 5/7] =?UTF-8?q?feat(api):=20=E9=97=AE=E7=AD=94=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=8C=89=E8=BD=AE=E9=80=89=E6=8B=A9=E6=A3=80=E7=B4=A2?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `AskRequest` 新增可选 `strategy`,经 `AskPlan` 与工具上下文的 `requested_strategy` 传入 `search_context`,优先于 Agent 人格与信源默认 - `/ask` 在开始流式生成前校验该模式在当前部署可用,付费 JEV 模式缺 Key 时直接返回 400,不落库用户消息 - 工具结果的 `retrieval_stats.strategy_origin` 标明本轮模式来源 (request / persona / source_default / global),供活动时间线展示 Co-Authored-By: Claude Fable 5.1 --- apps/api/sag_api/api/v1/agents.py | 5 + apps/api/sag_api/schemas/agent.py | 4 +- apps/api/sag_api/services/agent_domain.py | 3 + apps/api/sag_api/services/agent_service.py | 1 + apps/api/sag_api/services/agent_tooling.py | 7 +- apps/api/sag_api/tools/base.py | 2 + apps/api/sag_api/tools/builtin.py | 29 +++- apps/api/tests/test_chat_turn_strategy.py | 151 +++++++++++++++++++++ 8 files changed, 195 insertions(+), 7 deletions(-) create mode 100644 apps/api/tests/test_chat_turn_strategy.py 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/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/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 0e6fdb22..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, host_context.sources) - # 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/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 cf10c280..d9317a79 100644 --- a/apps/api/sag_api/tools/builtin.py +++ b/apps/api/sag_api/tools/builtin.py @@ -80,8 +80,12 @@ 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, sources=()) -> str: - """Persona choice → shared source default → legacy default (vector unless a JEV mode is global).""" +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 common_source_default_strategy(sources) or default @@ -96,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 "(无相关资料)" @@ -250,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), ctx.sources) + 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} @@ -339,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" From 7e283427608c05de14b5e4745d7b4bf473150abe Mon Sep 17 00:00:00 2001 From: luoshuai990529 <58510855+luoshuai990529@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:17:12 +0800 Subject: [PATCH 6/7] =?UTF-8?q?docs:=20=E8=AF=B4=E6=98=8E=E9=97=AE?= =?UTF-8?q?=E7=AD=94=E9=A1=B5=E6=8C=89=E8=BD=AE=E9=80=89=E6=8B=A9=E6=A3=80?= =?UTF-8?q?=E7=B4=A2=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 1 + README-CN.md | 2 +- README.md | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a2f6b6ba..c952011d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ## 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 结果显示本次评分用量。 diff --git a/README-CN.md b/README-CN.md index 4ab80206..b5fcbc8c 100644 --- a/README-CN.md +++ b/README-CN.md @@ -570,7 +570,7 @@ 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 关系库。 -每个信源可在创建或编辑时设置**默认检索模式**;未设置则跟随全局默认。搜索与问答按“本次显式选择 → Agent 人格 → 范围内信源的共同默认 → 全局默认”解析模式,范围内信源默认不一致时按全局默认处理;结果 `stats.strategy_origin` 标明来源。该设置只影响检索,不改变文档入库流程。 +每个信源可在创建或编辑时设置**默认检索模式**;未设置则跟随全局默认。探索页与问答页的输入框都提供模式控件,可为当前查询或当前轮次临时切换。搜索与问答按“本次显式选择 → Agent 人格 → 范围内信源的共同默认 → 全局默认”解析模式,范围内信源默认不一致时按全局默认处理;结果 `stats.strategy_origin` 标明来源。该设置只影响检索,不改变文档入库流程。 在“设置 → 知识库 → 检索”配置 302.AI、TypeSafe 官方或自定义 JEV 服务(默认 `jev-latest`,独立 API Key),再选择 **JEV 精排** 或 **SAG2 证据检索**;创建信源时选择 JEV 模式也可在对话框内直接完成该配置。JEV 是付费服务:仅保存服务不会启用,选择任一 JEV 模式前必须填写 API Key。JEV 精排默认限时 30 秒、失败报错,可选择粗排降级。 diff --git a/README.md b/README.md index af9e3e9b..30765e46 100644 --- a/README.md +++ b/README.md @@ -568,7 +568,7 @@ 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. -Each source can carry a **default retrieval mode**, chosen when the source is created or edited; unset means follow the global default. 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. +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. From 17ae9f49824ccbe9be595af01159e9cf362c47da Mon Sep 17 00:00:00 2001 From: luoshuai990529 <58510855+luoshuai990529@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:31:55 +0800 Subject: [PATCH 7/7] =?UTF-8?q?feat(web):=20=E9=97=AE=E7=AD=94=E8=BE=93?= =?UTF-8?q?=E5=85=A5=E6=A1=86=E6=8C=89=E8=BD=AE=E9=80=89=E6=8B=A9=E6=A3=80?= =?UTF-8?q?=E7=B4=A2=E6=A8=A1=E5=BC=8F=E5=B9=B6=E6=98=BE=E7=A4=BA=E6=9D=A5?= =?UTF-8?q?=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 输入框工具栏在「联网」旁加入与探索页一致的模式控件,默认显示将实际 使用的模式并标注来源(人格默认 / 信源默认),生成中禁用 - 用户选择后仅对本面板后续轮次生效,请求体携带 `strategy`;未选择时不传, 由后端按人格 → 信源默认 → 全局解析 - 模式在当前部署不可用被拒绝时,在输入框上方内联提示并提供设置入口 - 回答活动时间线显示本轮模式来源;补充中英文案与 vitest 用例 Co-Authored-By: Claude Fable 5.1 --- apps/web/components/features/app-shell.tsx | 4 + .../features/chat/conversation-panel.test.tsx | 179 +++++++++++++++--- .../features/chat/conversation-panel.tsx | 115 ++++++++++- .../features/retrieval-status.test.tsx | 19 ++ .../components/features/retrieval-status.tsx | 22 ++- .../features/search-strategy-control.tsx | 8 +- apps/web/lib/conversation-runtime.test.ts | 19 +- apps/web/lib/conversation-runtime.ts | 6 + apps/web/lib/retrieval-config.test.ts | 8 + apps/web/lib/retrieval-config.ts | 15 ++ apps/web/lib/sse.test.ts | 13 ++ apps/web/lib/sse.ts | 3 + apps/web/lib/types.ts | 2 + apps/web/messages/en-US.json | 9 +- apps/web/messages/zh-CN.json | 9 +- 15 files changed, 399 insertions(+), 32 deletions(-) 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/retrieval-status.test.tsx b/apps/web/components/features/retrieval-status.test.tsx index 1b4a1231..fa96ac0f 100644 --- a/apps/web/components/features/retrieval-status.test.tsx +++ b/apps/web/components/features/retrieval-status.test.tsx @@ -39,6 +39,25 @@ describe("retrieval execution status", () => { }); }); +describe("retrieval mode origin", () => { + const ran = { requested_strategy: "sag2", effective_strategy: "sag2", ranking: { method: "jev", fallback_reason: null } }; + it("says the mode came from the agent persona", async () => { + expect(await render({ ...ran, strategy_origin: "persona" }, "sag2")).toBe("Using SAG2 evidence retrieval (persona default)"); + }); + it("says the mode came from the scoped sources", async () => { + expect(await render({ ...ran, strategy_origin: "source_default" }, "sag2")).toBe("Using SAG2 evidence retrieval (source default)"); + }); + it.each(["request", "global", "unexpected"])("stays silent for a %s origin when the execution is unchanged", async (origin) => { + expect(await render({ ...ran, strategy_origin: origin }, "sag2")).toBe(""); + }); + it("keeps the origin next to a changed execution", async () => { + const text = await render({ requested_strategy: "sag2", effective_strategy: "vector", strategy_origin: "source_default" }, "sag2"); + expect(text).toContain("Using SAG2 evidence retrieval (source default)"); + expect(text).toContain("Requested: SAG2 evidence retrieval"); + expect(text).toContain("Actual: Fast (vector)"); + }); +}); + describe("SAG2 execution status", () => { const success = { requested_strategy: "sag2", effective_strategy: "sag2", fallback_used: false, diff --git a/apps/web/components/features/retrieval-status.tsx b/apps/web/components/features/retrieval-status.tsx index 12585ca2..4d4b8bbb 100644 --- a/apps/web/components/features/retrieval-status.tsx +++ b/apps/web/components/features/retrieval-status.tsx @@ -21,6 +21,22 @@ function finiteNumber(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; } +/** + * Origins worth a line of their own: the user did not pick the mode and it is + * not simply the global default, so say where it came from. "request" and + * "global" stay silent unless the execution changed. + */ +const EXPLAINED_ORIGINS = { + persona: "originPersona", + source_default: "originSourceDefault", +} as const; + +function explainedOrigin(value: unknown): keyof typeof EXPLAINED_ORIGINS | null { + return typeof value === "string" && Object.hasOwn(EXPLAINED_ORIGINS, value) + ? value as keyof typeof EXPLAINED_ORIGINS + : null; +} + /** Explain execution changes without treating same-profile coarse ranking as JEV success. */ export function RetrievalStatus({ stats, requestedStrategy }: { stats: Record; @@ -50,11 +66,15 @@ export function RetrievalStatus({ stats, requestedStrategy }: { }) : null; const executionChanged = jevFallback || partial || changed; - if (!executionChanged && usageText === null) return null; + const origin = explainedOrigin(stats.strategy_origin); + // The origin describes the resolved (requested) mode; a changed execution is reported separately. + const originMode = requested ?? effective; + if (!executionChanged && usageText === null && !(origin && originMode)) return null; function label(mode: string) { return isSearchStrategy(mode) ? strategies(getSearchStrategy(mode).labelKey) : mode; } return
+ {origin && originMode &&

{t("origin", { mode: label(originMode), origin: t(EXPLAINED_ORIGINS[origin]) })}

} {executionChanged && requested &&

{t("requested", { mode: label(requested) })}{" · "}{t("actual", { mode: jevFallback ? t("coarse") : label(effective ?? requested) })}

} {jevFallback &&

{t("jevFallback")}

} {partial &&

{t("partial")}

} diff --git a/apps/web/components/features/search-strategy-control.tsx b/apps/web/components/features/search-strategy-control.tsx index 6d08a0d6..ca5453e3 100644 --- a/apps/web/components/features/search-strategy-control.tsx +++ b/apps/web/components/features/search-strategy-control.tsx @@ -42,6 +42,7 @@ export function SearchStrategyControl({ onValueChange, disabledMap, hint, + disabled, }: { value: SearchStrategy; defaultValue: SearchStrategy; @@ -53,6 +54,8 @@ export function SearchStrategyControl({ disabledMap?: SearchStrategyDisabledMap; /** Short muted note on where the current value came from (e.g. the scoped source's default). */ hint?: string; + /** Lock the control while a request is in flight, like the toolbar toggles around it. */ + disabled?: boolean; }) { const t = useTranslations("SearchStrategies"); const currentStrategy = getSearchStrategy(value); @@ -61,12 +64,13 @@ export function SearchStrategyControl({ return ( - +