diff --git a/CHANGELOG.md b/CHANGELOG.md index c952011d..3ea07645 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ## Unreleased +- 探索页新增「对比」:同一问题在 2–3 种检索模式下并排检索,显示耗时、召回数、SAG2 的 JEV 用量与共同命中的片段,可选 LLM 评审,并可一键按某一模式正式检索。 +- SAG2 只读引擎改在专用事件循环线程运行:大范围检索构建内存语料时不再阻塞 API 事件循环;整次超时会同步取消引擎侧工作。 - 问答页可为当前轮次选择检索模式:输入框工具栏新增与探索页一致的模式控件,默认显示将实际使用的模式及其来源(人格默认 / 信源默认 / 全局),用户选择后对后续轮次生效;付费 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。 diff --git a/README-CN.md b/README-CN.md index b5fcbc8c..94dd302f 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` 标明来源。该设置只影响检索,不改变文档入库流程。 +每个信源可在创建或编辑时设置**默认检索模式**;未设置则跟随全局默认。探索页与问答页的输入框都提供模式控件,可为当前查询或当前轮次临时切换;探索页还可开启「对比」,用同一问题并排比较 2–3 种模式的耗时、召回与用量,并一键采用其中一种。搜索与问答按“本次显式选择 → 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 30765e46..64c29321 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. 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. +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; the explore page can also run a side-by-side comparison of two or three modes for the same question (latency, hits, usage) and adopt one with a click. 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. diff --git a/apps/api/sag_api/sag/sag2_engine.py b/apps/api/sag_api/sag/sag2_engine.py index 1ccc2a6b..292e2d2e 100644 --- a/apps/api/sag_api/sag/sag2_engine.py +++ b/apps/api/sag_api/sag/sag2_engine.py @@ -9,13 +9,18 @@ 对 zleap-sag2 内部结构的依赖集中在 ``_sag_schema_present`` 与 ``_count_scope`` 两个 函数里(``engine.store.engine`` 是其关系库连接);升级 ``zleap-sag2`` 版本时需复核这两处。 + +zleap-sag2 0.1.0 在构建内存语料时会在事件循环线程上同步分词、建倒排表,范围越大阻塞越久。 +为此只读引擎及其全部协程都运行在一个专用线程的事件循环里(``_EngineLoop``), +API 事件循环只负责排队、超时与取消,不被扫描阻塞。 """ from __future__ import annotations import asyncio +import threading import time -from collections.abc import Callable +from collections.abc import Callable, Coroutine from pathlib import Path from typing import TYPE_CHECKING, Any @@ -226,9 +231,48 @@ async def drain(self) -> None: await self._condition.wait_for(lambda: self._active == 0) +class _EngineLoop: + """专用线程上的事件循环:承载只读引擎的连接、扫描与评分,不占用 API 循环。 + + ``run`` 从 API 循环提交协程并等待结果;等待方被取消(如整次超时)时同步取消 + 专用循环里的协程,避免遗留仍在扫描的工作。 + """ + + def __init__(self, name: str = "sag2-engine") -> None: + self._loop = asyncio.new_event_loop() + self._thread = threading.Thread(target=self._serve, name=name, daemon=True) + self._thread.start() + + def _serve(self) -> None: + asyncio.set_event_loop(self._loop) + try: + self._loop.run_forever() + finally: + self._loop.close() + + @property + def alive(self) -> bool: + return self._thread.is_alive() + + async def run(self, coroutine: Coroutine[Any, Any, Any]) -> Any: + future = asyncio.run_coroutine_threadsafe(coroutine, self._loop) + try: + return await asyncio.wrap_future(future) + except asyncio.CancelledError: + future.cancel() + raise + + def stop(self, timeout: float = 5.0) -> None: + if not self._thread.is_alive(): + return + self._loop.call_soon_threadsafe(self._loop.stop) + self._thread.join(timeout=timeout) + + class Sag2EngineHolder: """按配置指纹懒建、复用、重建一个只读 zleap-sag2 引擎,并限制并发检索数。 + 引擎只在专用线程的事件循环里创建和使用;``_gate`` 与整次超时留在 API 循环。 ``scorer_factory`` 仅供测试注入离线评分器;缺省由引擎按 ``JevConfig`` 创建真实客户端。 """ @@ -239,6 +283,12 @@ def __init__(self, settings: Settings, *, scorer_factory: Callable[[Any], Any] | self._fingerprint: tuple[Any, ...] | None = None self._lock = asyncio.Lock() self._gate = _AdmissionGate(settings.sag2_max_concurrent_searches) + self._loop: _EngineLoop | None = None + + def _engine_loop(self) -> _EngineLoop: + if self._loop is None or not self._loop.alive: + self._loop = _EngineLoop() + return self._loop @property def started(self) -> bool: @@ -258,8 +308,18 @@ async def refresh(self, settings: Settings) -> None: await self._gate.set_limit(settings.sag2_max_concurrent_searches) async def aclose(self) -> None: - """等待在途检索结束后关闭引擎;与 ``EngineManager._close_all_slots`` 等待空闲的语义一致。""" + """等待在途检索结束后关闭引擎并停掉专用循环;与 ``_close_all_slots`` 等待空闲的语义一致。""" await self._gate.drain() + loop, self._loop = self._loop, None + if loop is not None and loop.alive: + try: + await loop.run(self._locked_close()) + finally: + await asyncio.to_thread(loop.stop) + else: + await self._locked_close() + + async def _locked_close(self) -> None: async with self._lock: await self._close() @@ -352,43 +412,54 @@ async def _run( source_ids: tuple[str, ...] | None, top_k: int, ) -> tuple[Any, int]: + async with self._gate: + # 排队在 API 循环完成;引擎工作整体交给专用循环,扫描不阻塞其他请求。 + return await self._engine_loop().run(self._execute(query, data_source_ids, source_ids, top_k)) + + async def _execute( + self, + query: str, + data_source_ids: list[str], + source_ids: tuple[str, ...] | None, + top_k: int, + ) -> tuple[Any, int]: + """在专用循环里运行:取引擎、范围护栏、构造请求、检索与异常翻译。""" from zleap.sag2 import SearchOptions, SearchRequest, SearchScope - async with self._gate: - engine = await self.engine() - settings = self._settings - scope_chunks = await self._count_scope(engine, data_source_ids) - limit = int(settings.sag2_max_scope_chunks) - if limit and scope_chunks > limit: - raise ValidationError( - f"检索范围过大:包含 {scope_chunks:,} 个段落,超过 SAG2 证据检索上限 {limit:,},请缩小信源范围", - layer=ErrorLayer.ENGINE, - stage=ErrorStage.RETRIEVE, - ) - scope_values: dict[str, Any] = {"data_source_ids": tuple(data_source_ids)} - if source_ids is not None: - scope_values["source_ids"] = source_ids - request = SearchRequest( - query=query, - scope=SearchScope(**scope_values), - options=SearchOptions( - candidate_k=settings.sag2_candidate_k, - seed_k=settings.sag2_seed_k, - max_hops=settings.sag2_max_hops, - expansion_term_limit=settings.sag2_expansion_term_limit, - top_k=max(1, min(int(top_k), 1000)), - ), - ) - started = time.perf_counter() - try: - result = await engine.search(request) - except Exception as error: # noqa: BLE001 - translated below - raise self._translate(error) from error - log.info( - "SAG2 检索完成 sources=%d scope_chunks=%d hits=%d elapsed=%.0fms", - len(data_source_ids), scope_chunks, len(result.chunks), (time.perf_counter() - started) * 1000, + engine = await self.engine() + settings = self._settings + scope_chunks = await self._count_scope(engine, data_source_ids) + limit = int(settings.sag2_max_scope_chunks) + if limit and scope_chunks > limit: + raise ValidationError( + f"检索范围过大:包含 {scope_chunks:,} 个段落,超过 SAG2 证据检索上限 {limit:,},请缩小信源范围", + layer=ErrorLayer.ENGINE, + stage=ErrorStage.RETRIEVE, ) - return result, scope_chunks + scope_values: dict[str, Any] = {"data_source_ids": tuple(data_source_ids)} + if source_ids is not None: + scope_values["source_ids"] = source_ids + request = SearchRequest( + query=query, + scope=SearchScope(**scope_values), + options=SearchOptions( + candidate_k=settings.sag2_candidate_k, + seed_k=settings.sag2_seed_k, + max_hops=settings.sag2_max_hops, + expansion_term_limit=settings.sag2_expansion_term_limit, + top_k=max(1, min(int(top_k), 1000)), + ), + ) + started = time.perf_counter() + try: + result = await engine.search(request) + except Exception as error: # noqa: BLE001 - translated below + raise self._translate(error) from error + log.info( + "SAG2 检索完成 sources=%d scope_chunks=%d hits=%d elapsed=%.0fms", + len(data_source_ids), scope_chunks, len(result.chunks), (time.perf_counter() - started) * 1000, + ) + return result, scope_chunks @staticmethod async def _sag_schema_present(engine: Any) -> bool: diff --git a/apps/api/tests/test_sag2_retrieval.py b/apps/api/tests/test_sag2_retrieval.py index aacbc134..45c67b69 100644 --- a/apps/api/tests/test_sag2_retrieval.py +++ b/apps/api/tests/test_sag2_retrieval.py @@ -1,6 +1,8 @@ """Offline contracts for the SAG2 evidence strategy (zleap-sag2 read-only search).""" import asyncio +import threading +import time import pytest @@ -308,7 +310,8 @@ async def test_refresh_applies_new_concurrency_limit_without_dropping_inflight_s configuration = sag2_settings(sag2_max_concurrent_searches=1) holder = Sag2EngineHolder(configuration) - release, first_running = asyncio.Event(), asyncio.Event() + # The engine runs on the holder's dedicated loop thread, so signal across threads. + release, first_running = threading.Event(), threading.Event() active = peak = 0 class Engine: @@ -317,7 +320,7 @@ async def search(self, request): active += 1 peak = max(peak, active) first_running.set() - await release.wait() + await asyncio.to_thread(release.wait, 5) active -= 1 return SearchResult(query=request.query, original_query=request.query) @@ -336,15 +339,73 @@ def run(): )) first, second = run(), run() - await asyncio.wait_for(first_running.wait(), timeout=1) - await asyncio.sleep(0.01) + assert await asyncio.to_thread(first_running.wait, 1) + await asyncio.sleep(0.05) assert active == 1 # the second search queues behind the limit of 1 await holder.refresh(configuration.model_copy(update={"sag2_max_concurrent_searches": 2})) - await asyncio.sleep(0.01) + await asyncio.sleep(0.05) assert active == 2 # the raised limit admits the queued search; the first keeps running release.set() await asyncio.gather(first, second) assert peak == 2 + await holder.aclose() + + +@pytest.mark.asyncio +async def test_engine_work_runs_off_the_api_loop_and_timeouts_cancel_it(monkeypatch): + from zleap.sag2 import SearchResult + + holder = Sag2EngineHolder(sag2_settings()) + cancelled = threading.Event() + + class Engine: + async def search(self, request): + if request.query == "block": + time.sleep(0.3) # synchronous corpus build: must not stall the API loop + return SearchResult(query=request.query, original_query=request.query) + try: + await asyncio.sleep(5) + except asyncio.CancelledError: + cancelled.set() + raise + return SearchResult(query=request.query, original_query=request.query) + + async def engine(): + return Engine() + + async def count(_engine, _data_source_ids): + return 1 + + monkeypatch.setattr(holder, "engine", engine) + monkeypatch.setattr(holder, "_count_scope", count) + + def run(query): + return holder.search( + [("cfg-1", None)], query, top_k=3, requested_sources=1, source_limit_applied=False, + source_ids_by_config=None, + ) + + # While the engine blocks its own thread, the API loop keeps ticking. + ticks = 0 + + async def ticker(): + nonlocal ticks + for _ in range(10): + await asyncio.sleep(0.02) + ticks += 1 + + await asyncio.gather(run("block"), ticker()) + assert ticks == 10 + assert threading.current_thread() is threading.main_thread() + + # The whole-search timeout cancels the coroutine inside the dedicated loop. + holder._settings.sag2_search_timeout_seconds = 1.0 + with pytest.raises(ServiceUnavailableError): + await run("hang") + assert cancelled.wait(1) + assert holder._gate.active == 0 + await holder.aclose() + assert holder._loop is None @pytest.mark.parametrize(("status", "expected_type", "expected_message"), [ diff --git a/apps/web/components/features/retrieval-compare-parts.tsx b/apps/web/components/features/retrieval-compare-parts.tsx new file mode 100644 index 00000000..f93c4679 --- /dev/null +++ b/apps/web/components/features/retrieval-compare-parts.tsx @@ -0,0 +1,213 @@ +"use client"; + +import * as React from "react"; +import { Trophy } from "lucide-react"; + +import type { EvalJudge, EvalStrategyResult } from "@/lib/api"; +import type { SearchStrategy } from "@/lib/retrieval-config"; +import type { Section } from "@/lib/types"; +import { RetrievalStatus } from "@/components/features/retrieval-status"; +import { cn } from "@/lib/utils"; + +/** Small muted badge used next to a mode label (paid / default markers). */ +export const strategyBadgeClassName = + "rounded bg-muted px-1 py-0.5 text-[10px] font-normal leading-none text-muted-foreground"; + +export function pickNumber(stats: Record, key: string): number | null { + const value = stats[key]; + return typeof value === "number" && Number.isFinite(value) ? value : null; +} + +function pickTimings(stats: Record, key: string): [string, number][] { + const value = stats[key]; + if (!value || typeof value !== "object") return []; + const entries: [string, number][] = []; + for (const [k, v] of Object.entries(value as Record)) { + if (typeof v === "number" && Number.isFinite(v)) entries.push([k, v]); + } + return entries; +} + +function shortStep(key: string): string { + // "multi_es.step5_fast_expand" → "step5_fast_expand";vector.embedding → embedding + const idx = key.indexOf("."); + return idx >= 0 ? key.slice(idx + 1) : key; +} + +/** One retrieved passage: rank, heading, score bar and a two-line excerpt. */ +export function SectionRow({ + index, + section, + sectionLabel, + marker, + onClick, +}: { + index: number; + section: Section; + sectionLabel: string; + /** Optional inline marker rendered after the heading (e.g. a shared-hit tag). */ + marker?: React.ReactNode; + /** When provided the row becomes a button that opens the passage. */ + onClick?: () => void; +}) { + const body = ( + <> +
+ + {index + 1} + + + {section.heading || sectionLabel} + + {marker} + + {section.score.toFixed(4)} + +
+
+
+
+

+ {section.content} +

+ + ); + if (!onClick) { + return
{body}
; + } + return ( + + ); +} + +/** Compact latency / candidate summary for one strategy run. */ +export function StatsPill({ stats }: { stats: Record }) { + const latency = pickNumber(stats, "latency_total_ms"); + const engineLatency = pickNumber(stats, "latency_engine_ms"); + const candidates = pickNumber(stats, "candidates"); + const relevant = pickNumber(stats, "relevant"); + const parts: string[] = []; + if (latency != null) parts.push(`${latency.toFixed(0)}ms`); + else if (engineLatency != null) parts.push(`${engineLatency.toFixed(0)}ms`); + if (candidates != null) parts.push(`cand=${candidates}`); + if (relevant != null) parts.push(`rel=${relevant}`); + const engineTimings = pickTimings(stats, "engine_timings"); + const topSteps = engineTimings + .filter(([key]) => !/\.total$/.test(key)) // total 已经在 pill 里 + .sort((a, b) => b[1] - a[1]) + .slice(0, 3); + if (parts.length === 0 && topSteps.length === 0) return null; + return ( +
+ {parts.length > 0 && {parts.join(" · ")}} + {topSteps.length > 0 && ( + `${k}=${v.toFixed(0)}ms`).join("\n")}> + {topSteps.map(([k, v]) => `${shortStep(k)}=${v.toFixed(0)}ms`).join(" · ")} + + )} +
+ ); +} + +/** One strategy's column as shown in the per-source retrieval test dialog. */ +export function ColumnResult({ + result, + label, + sectionLabel, + emptyLabel, +}: { + result: EvalStrategyResult | undefined; + label: string; + sectionLabel: string; + emptyLabel: string; +}) { + if (!result) return null; + return ( +
+ +
+ {label} + +
+
+ {result.error ? ( +

+ {result.error} +

+ ) : result.sections.length === 0 ? ( +

+ {emptyLabel} +

+ ) : ( + result.sections.map((section, i) => ( + + )) + )} +
+
+ ); +} + +/** Pairwise LLM verdicts, or the reason none were produced. */ +export function JudgeVerdicts({ + judges, + judgeReason, + missingLabel, + tieLabel = "tie", + strategyLabelFor, + className, +}: { + judges: EvalJudge[]; + judgeReason: string | null; + missingLabel: string; + tieLabel?: string; + strategyLabelFor: (value: SearchStrategy) => string; + className?: string; +}) { + return ( +
+ {judges.length === 0 ? ( +

{judgeReason || missingLabel}

+ ) : ( +
    + {judges.map((verdict, i) => { + const winner = + verdict.winner === "A" + ? strategyLabelFor(verdict.a_strategy) + : verdict.winner === "B" + ? strategyLabelFor(verdict.b_strategy) + : tieLabel; + return ( +
  • + + + {winner} + + + {verdict.reason} + +
  • + ); + })} +
+ )} +
+ ); +} diff --git a/apps/web/components/features/retrieval-test-dialog.test.tsx b/apps/web/components/features/retrieval-test-dialog.test.tsx new file mode 100644 index 00000000..900ab6f4 --- /dev/null +++ b/apps/web/components/features/retrieval-test-dialog.test.tsx @@ -0,0 +1,89 @@ +/** @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, type EvalCompareResponse } from "@/lib/api"; +import type { Capabilities, Section } from "@/lib/types"; +import { RetrievalTestDialog } from "./retrieval-test-dialog"; + +const state = vi.hoisted(() => ({ capabilities: {} as Partial })); +vi.mock("@/components/features/app-shell", () => ({ useApp: () => state })); +vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +function section(chunk: string, score: number): Section { + return { chunk_id: chunk, heading: `Heading ${chunk}`, content: `Body ${chunk}`, score, rank: 1, source_id: "s1", source_name: "Manuals" }; +} +const compareResponse: EvalCompareResponse = { + query: "question", + results: [ + { strategy: "vector", sections: [section("c1", 0.8)], stats: { latency_total_ms: 300, candidates: 20, relevant: 5 }, error: null }, + { strategy: "multi_es_fast", sections: [], stats: {}, error: "lexical search unavailable" }, + ], + judges: [{ a_strategy: "vector", b_strategy: "multi_es_fast", winner: "A", reason: "Only A retrieved anything" }], + judge_enabled: true, + judge_reason: null, +}; + +let root: Root; +let container: HTMLDivElement; + +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"] }; + 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 openDialog() { + await act(async () => root.render( + + {}} /> + , + )); + const dialog = document.body.querySelector('[role="dialog"]')!; + expect(dialog).not.toBeNull(); + return dialog; +} +async function typeQuery(dialog: HTMLElement, value: string) { + const input = dialog.querySelector("#rt-q")!; + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!; + await act(async () => { + setter.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} + +describe("retrieval test dialog", () => { + it("still renders the single-mode form", async () => { + const dialog = await openDialog(); + expect(dialog.textContent).toContain("Test retrieval · Manuals"); + expect(dialog.querySelector("#rt-q")).not.toBeNull(); + expect(dialog.querySelector("#rt-a-select")).toBeNull(); + }); + it("compares two strategies with the shared columns and verdict list", async () => { + const evalCompare = vi.spyOn(api, "evalCompare").mockResolvedValue(compareResponse); + const dialog = await openDialog(); + await act(async () => dialog.querySelector("#rt-compare")!.click()); + expect(dialog.querySelector("#rt-a-select")).not.toBeNull(); + expect(dialog.querySelector("#rt-b-select")).not.toBeNull(); + await typeQuery(dialog, "question"); + await act(async () => dialog.querySelector("form")!.requestSubmit()); + expect(evalCompare).toHaveBeenCalledWith({ + query: "question", source_ids: ["s1"], top_k: 8, strategies: ["vector", "multi_es_fast"], judge: true, + }); + expect(dialog.textContent).toContain("Fast (vector)"); + expect(dialog.textContent).toContain("Heading c1"); + expect(dialog.textContent).toContain("300ms · cand=20 · rel=5"); + expect(dialog.textContent).toContain("lexical search unavailable"); + expect(dialog.querySelector('[data-testid="compare-judges"]')?.textContent).toContain("Only A retrieved anything"); + }); +}); diff --git a/apps/web/components/features/retrieval-test-dialog.tsx b/apps/web/components/features/retrieval-test-dialog.tsx index d8782321..cdac7506 100644 --- a/apps/web/components/features/retrieval-test-dialog.tsx +++ b/apps/web/components/features/retrieval-test-dialog.tsx @@ -6,12 +6,7 @@ import { useTranslations } from "next-intl"; import { toast } from "sonner"; import { useApp } from "@/components/features/app-shell"; -import { - api, - ApiError, - type EvalCompareResponse, - type EvalStrategyResult, -} from "@/lib/api"; +import { api, ApiError, type EvalCompareResponse } from "@/lib/api"; import { DEFAULT_SEARCH_STRATEGY, getSearchStrategiesDisabled, @@ -19,6 +14,11 @@ import { type SearchStrategy, } from "@/lib/retrieval-config"; import type { Section } from "@/lib/types"; +import { + ColumnResult, + JudgeVerdicts, + SectionRow, +} from "@/components/features/retrieval-compare-parts"; import { RetrievalStatus } from "@/components/features/retrieval-status"; import { Button } from "@/components/ui/button"; import { Spinner } from "@/components/ui/spinner"; @@ -379,164 +379,12 @@ function CompareColumns({ />
-
- {data.judges.length === 0 ? ( -

- {data.judge_reason || judgeMissingLabel} -

- ) : ( -
    - {data.judges.map((verdict, i) => { - const winner = - verdict.winner === "A" - ? strategyLabelFor(verdict.a_strategy) - : verdict.winner === "B" - ? strategyLabelFor(verdict.b_strategy) - : "tie"; - return ( -
  • - - - {winner} - - - {verdict.reason} - -
  • - ); - })} -
- )} -
- - ); -} - -function ColumnResult({ - result, - label, - sectionLabel, - emptyLabel, -}: { - result: EvalStrategyResult | undefined; - label: string; - sectionLabel: string; - emptyLabel: string; -}) { - if (!result) return null; - return ( -
- -
- {label} - -
-
- {result.error ? ( -

- {result.error} -

- ) : result.sections.length === 0 ? ( -

- {emptyLabel} -

- ) : ( - result.sections.map((section, i) => ( - - )) - )} -
-
- ); -} - -function StatsPill({ stats }: { stats: Record }) { - const latency = pickNumber(stats, "latency_total_ms"); - const engineLatency = pickNumber(stats, "latency_engine_ms"); - const candidates = pickNumber(stats, "candidates"); - const relevant = pickNumber(stats, "relevant"); - const parts: string[] = []; - if (latency != null) parts.push(`${latency.toFixed(0)}ms`); - else if (engineLatency != null) parts.push(`${engineLatency.toFixed(0)}ms`); - if (candidates != null) parts.push(`cand=${candidates}`); - if (relevant != null) parts.push(`rel=${relevant}`); - const engineTimings = pickTimings(stats, "engine_timings"); - const topSteps = engineTimings - .filter(([key]) => !/\.total$/.test(key)) // total 已经在 pill 里 - .sort((a, b) => b[1] - a[1]) - .slice(0, 3); - if (parts.length === 0 && topSteps.length === 0) return null; - return ( -
- {parts.length > 0 && {parts.join(" · ")}} - {topSteps.length > 0 && ( - `${k}=${v.toFixed(0)}ms`).join("\n")}> - {topSteps.map(([k, v]) => `${shortStep(k)}=${v.toFixed(0)}ms`).join(" · ")} - - )} -
- ); -} - -function pickNumber(stats: Record, key: string): number | null { - const value = stats[key]; - return typeof value === "number" && Number.isFinite(value) ? value : null; -} - -function pickTimings(stats: Record, key: string): [string, number][] { - const value = stats[key]; - if (!value || typeof value !== "object") return []; - const entries: [string, number][] = []; - for (const [k, v] of Object.entries(value as Record)) { - if (typeof v === "number" && Number.isFinite(v)) entries.push([k, v]); - } - return entries; -} - -function shortStep(key: string): string { - // "multi_es.step5_fast_expand" → "step5_fast_expand";vector.embedding → embedding - const idx = key.indexOf("."); - return idx >= 0 ? key.slice(idx + 1) : key; -} - -function SectionRow({ - index, - section, - sectionLabel, -}: { - index: number; - section: Section; - sectionLabel: string; -}) { - return ( -
-
- - {index + 1} - - - {section.heading || sectionLabel} - - - {section.score.toFixed(4)} - -
-
-
-
-

- {section.content} -

+
); } diff --git a/apps/web/components/features/search/search-compare-results.test.tsx b/apps/web/components/features/search/search-compare-results.test.tsx new file mode 100644 index 00000000..3164e568 --- /dev/null +++ b/apps/web/components/features/search/search-compare-results.test.tsx @@ -0,0 +1,142 @@ +/** @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 type { EvalCompareResponse, EvalStrategyResult } from "@/lib/api"; +import type { Section } from "@/lib/types"; +import { + countChunkColumns, + SearchCompareResults, + type SearchCompareResultsProps, +} from "./search-compare-results"; + +function section(chunk: string, score: number): Section { + return { + chunk_id: chunk, heading: `Heading ${chunk}`, content: `Body ${chunk}`, score, rank: 1, + source_id: "src", source_name: "Manuals", + }; +} + +const vector: EvalStrategyResult = { + strategy: "vector", + sections: [section("c1", 0.9), section("c2", 0.8)], + stats: { latency_total_ms: 1234, requested_strategy: "vector", effective_strategy: "vector" }, + error: null, +}; +const sag2: EvalStrategyResult = { + strategy: "sag2", + sections: [section("c1", 0.95), section("c3", 0.7)], + stats: { + latency_total_ms: 2500, requested_strategy: "sag2", effective_strategy: "sag2", + jev_usage: { requests: 3, judgments: 12, input_tokens: 4096, output_tokens: null }, + sag2: { jev_ms: 1800, local_ms: 700, scope_chunks: 40, hops: 2 }, + }, + error: null, +}; +const failed: EvalStrategyResult = { strategy: "multi", sections: [], stats: {}, error: "boom" }; + +const data: EvalCompareResponse = { + query: "question", + results: [vector, sag2, failed], + judges: [{ a_strategy: "vector", b_strategy: "sag2", winner: "B", reason: "More complete" }], + judge_enabled: true, + judge_reason: null, +}; + +let root: Root; +let container: HTMLDivElement; +const onAdopt = vi.fn(); +const onOpenSection = vi.fn(); +const onRetry = vi.fn(); + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + onAdopt.mockClear(); onOpenSection.mockClear(); onRetry.mockClear(); + container = document.createElement("div"); document.body.append(container); root = createRoot(container); +}); +afterEach(async () => { await act(async () => root.unmount()); container.remove(); }); + +async function render(props: Partial = {}) { + await act(async () => root.render( + + + , + )); + return container; +} +const column = (strategy: string) => container.querySelector(`[data-testid="compare-column-${strategy}"]`)!; +const metrics = (strategy: string) => column(strategy).querySelector('[data-testid="compare-metrics"]')?.textContent ?? ""; + +describe("search compare results", () => { + it("renders one column per mode with a readable metrics strip", async () => { + await render(); + expect(metrics("vector")).toBe("1.2 s·2 hits"); + expect(metrics("sag2")).toBe("2.5 s·2 hits·JEV 3 requests · 12 judgments · 4,096 input tokens"); + expect(column("sag2").textContent).toContain("SAG2 evidence retrieval"); + expect(column("sag2").textContent).toContain("Paid"); + expect(column("vector").textContent).not.toContain("Paid"); + }); + it("shows a failed mode as a muted alert and does not offer to adopt it", async () => { + await render(); + expect(column("multi").querySelector('[role="alert"]')?.textContent).toBe("boom"); + expect(column("multi").querySelector('[data-testid="compare-adopt-multi"]')?.disabled).toBe(true); + expect(metrics("multi")).toBe("0 hits"); + }); + it("marks passages that two or more modes retrieved", async () => { + await render(); + const markers = [...container.querySelectorAll('[data-testid="compare-common-hit"]')]; + expect(markers).toHaveLength(2); + expect(column("vector").querySelectorAll('[data-testid="compare-common-hit"]')).toHaveLength(1); + expect(column("sag2").querySelectorAll('[data-testid="compare-common-hit"]')).toHaveLength(1); + expect(countChunkColumns(data.results).get("c1")).toBe(2); + expect(countChunkColumns(data.results).get("c2")).toBe(1); + }); + it("adopts a mode and opens a passage through the callbacks", async () => { + await render(); + await act(async () => column("vector").querySelector('[data-testid="compare-adopt-vector"]')!.click()); + expect(onAdopt).toHaveBeenCalledWith("vector"); + const rows = column("sag2").querySelectorAll("button"); + const passage = [...rows].find((button) => button.textContent?.includes("Heading c3"))!; + await act(async () => passage.click()); + expect(onOpenSection).toHaveBeenCalledWith(sag2.sections[1], 1, sag2); + }); + it("lists the pairwise verdicts, or the reason the judge did not run", async () => { + await render(); + const judges = container.querySelector('[data-testid="compare-judges"]')!; + expect(judges.textContent).toContain("SAG2 evidence retrieval"); + expect(judges.textContent).toContain("More complete"); + await render({ data: { ...data, judges: [], judge_enabled: false, judge_reason: "LLM not configured" } }); + expect(container.querySelector('[data-testid="compare-judges"]')?.textContent).toBe("LLM not configured"); + await render({ data: { ...data, judges: [], judge_reason: null } }); + expect(container.querySelector('[data-testid="compare-judges"]')?.textContent).toBe("No judge verdict was produced"); + }); + it("explains a changed execution under the column header", async () => { + const fallback: EvalStrategyResult = { + ...sag2, + stats: { ...sag2.stats, effective_strategy: "vector", fallback_used: true }, + }; + await render({ data: { ...data, results: [vector, fallback] } }); + expect(column("sag2").textContent).toContain("Requested: SAG2 evidence retrieval"); + expect(column("sag2").textContent).toContain("Actual: Coarse ranking"); + expect(column("vector").querySelector('[role="status"]')).toBeNull(); + }); + it("draws a busy column per pending mode and a retry when the whole request failed", async () => { + await render({ data: null, busy: true, pendingStrategies: ["vector", "sag2"] }); + expect(container.querySelectorAll('[aria-busy="true"]')).toHaveLength(2); + expect(column("sag2").textContent).toContain("SAG2 evidence retrieval"); + await render({ data: null, error: "service down" }); + expect(container.textContent).toContain("Comparison failed"); + expect(container.textContent).toContain("service down"); + const retry = [...container.querySelectorAll("button")].find((button) => button.textContent === "Retry")!; + await act(async () => retry.click()); + expect(onRetry).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/web/components/features/search/search-compare-results.tsx b/apps/web/components/features/search/search-compare-results.tsx new file mode 100644 index 00000000..69732dec --- /dev/null +++ b/apps/web/components/features/search/search-compare-results.tsx @@ -0,0 +1,299 @@ +"use client"; + +import * as React from "react"; +import { useLocale, useTranslations } from "next-intl"; +import { Search as SearchIcon, Trophy } from "lucide-react"; + +import type { EvalCompareResponse, EvalStrategyResult } from "@/lib/api"; +import { + getSearchStrategy, + isJevScoredStrategy, + SEARCH_STRATEGY_ICONS, + type SearchStrategy, +} from "@/lib/retrieval-config"; +import type { Section } from "@/lib/types"; +import { cn } from "@/lib/utils"; +import { EmptyState } from "@/components/features/empty-state"; +import { + JudgeVerdicts, + pickNumber, + SectionRow, + strategyBadgeClassName, +} from "@/components/features/retrieval-compare-parts"; +import { RetrievalStatus } from "@/components/features/retrieval-status"; +import { Button } from "@/components/ui/button"; +import { Skeleton } from "@/components/ui/skeleton"; + +function record(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? value as Record + : {}; +} + +/** True when the server ran something other than the requested mode. */ +function executionChanged(result: EvalStrategyResult): boolean { + const { stats } = result; + if (stats.fallback_used === true || Boolean(record(stats.ranking).fallback_reason)) return true; + const requested = typeof stats.requested_strategy === "string" ? stats.requested_strategy : result.strategy; + const effective = typeof stats.effective_strategy === "string" ? stats.effective_strategy : requested; + return requested !== effective; +} + +/** Count how many columns retrieved each chunk so shared hits can be marked. */ +export function countChunkColumns(results: ReadonlyArray): Map { + const counts = new Map(); + for (const column of results) { + const seen = new Set(); + for (const section of column.sections) { + if (section.chunk_id) seen.add(section.chunk_id); + } + for (const chunkId of seen) counts.set(chunkId, (counts.get(chunkId) ?? 0) + 1); + } + return counts; +} + +function gridClassName(count: number, compact: boolean): string { + if (compact || count <= 1) return "grid-cols-1"; + return count >= 3 ? "grid-cols-1 md:grid-cols-3" : "grid-cols-1 md:grid-cols-2"; +} + +function ColumnHeading({ strategy }: { strategy: SearchStrategy }) { + const strategies = useTranslations("SearchStrategies"); + const entry = getSearchStrategy(strategy); + const Icon = SEARCH_STRATEGY_ICONS[entry.value]; + return ( + + + {strategies(entry.labelKey)} + {isJevScoredStrategy(entry.value) && ( + {strategies("paid")} + )} + + ); +} + +function MetricsStrip({ result }: { result: EvalStrategyResult }) { + const t = useTranslations("Search"); + const locale = useLocale(); + const format = (value: number) => value.toLocaleString(locale); + const latency = pickNumber(result.stats, "latency_total_ms") ?? pickNumber(result.stats, "latency_engine_ms"); + const usage = record(result.stats.jev_usage); + const requests = pickNumber(usage, "requests"); + const judgments = pickNumber(usage, "judgments"); + const inputTokens = pickNumber(usage, "input_tokens"); + const parts: string[] = []; + if (latency !== null) parts.push(t("compareLatency", { seconds: (latency / 1000).toFixed(1) })); + parts.push(t("compareHits", { count: result.sections.length })); + if (requests !== null && judgments !== null) { + parts.push(t("compareUsage", { + requests: format(requests), + judgments: format(judgments), + tokens: inputTokens === null ? "" : t("compareUsageTokens", { tokens: format(inputTokens) }), + })); + } + return ( +

+ {parts.map((part, index) => ( + + {index > 0 && } + {part} + + ))} +

+ ); +} + +function CompareColumn({ + result, + chunkColumns, + onAdopt, + onOpenSection, +}: { + result: EvalStrategyResult; + chunkColumns: Map; + onAdopt: (strategy: SearchStrategy) => void; + onOpenSection: (section: Section, index: number, column: EvalStrategyResult) => void; +}) { + const t = useTranslations("Search"); + // The strip already reports JEV usage; keep the status box for execution changes only. + const statusStats = React.useMemo(() => { + const { jev_usage: _usage, ...rest } = result.stats; + void _usage; + return rest; + }, [result.stats]); + return ( +
+
+
+ + +
+ +
+ {!result.error && executionChanged(result) && ( + + )} + {result.error ? ( +

+ {result.error} +

+ ) : result.sections.length === 0 ? ( +

{t("compareEmpty")}

+ ) : ( +
+ {result.sections.map((section, index) => ( + = 2 ? ( + + {t("commonHit")} + + ) : undefined} + onClick={() => onOpenSection(section, index, result)} + /> + ))} +
+ )} +
+ ); +} + +function BusyColumn({ strategy }: { strategy: SearchStrategy }) { + return ( +
+ + + {Array.from({ length: 4 }).map((_, index) => ( + + ))} +
+ ); +} + +export interface SearchCompareResultsProps { + data: EvalCompareResponse | null; + busy: boolean; + /** Modes in flight, used for the skeleton columns while busy. */ + pendingStrategies: ReadonlyArray; + /** Whole-request failure (as opposed to one mode's `error`). */ + error: string | null; + compact: boolean; + onAdopt: (strategy: SearchStrategy) => void; + onOpenSection: (section: Section, index: number, column: EvalStrategyResult) => void; + onRetry: () => void; +} + +/** Side-by-side columns for 2–3 retrieval modes plus the pairwise LLM verdicts. */ +export function SearchCompareResults({ + data, + busy, + pendingStrategies, + error, + compact, + onAdopt, + onOpenSection, + onRetry, +}: SearchCompareResultsProps) { + const t = useTranslations("Search"); + const strategies = useTranslations("SearchStrategies"); + const strategyLabelFor = React.useCallback( + (value: SearchStrategy) => strategies(getSearchStrategy(value).labelKey), + [strategies], + ); + const chunkColumns = React.useMemo( + () => countChunkColumns(data?.results ?? []), + [data], + ); + + if (busy) { + return ( +
+ {pendingStrategies.map((strategy) => ( + + ))} +
+ ); + } + + if (error) { + return ( + + {t("retry")} + + )} + /> + ); + } + + if (!data) return null; + + return ( +
+
+ {data.results.map((result) => ( + + ))} +
+
+

+ + {t("judgeToggle")} +

+ +
+
+ ); +} diff --git a/apps/web/components/features/search/search-panel-compare.test.tsx b/apps/web/components/features/search/search-panel-compare.test.tsx new file mode 100644 index 00000000..16fca9d4 --- /dev/null +++ b/apps/web/components/features/search/search-panel-compare.test.tsx @@ -0,0 +1,219 @@ +/** @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 type { EvalCompareResponse } from "@/lib/api"; +import type { Capabilities, Section } from "@/lib/types"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { SearchPanel } from "./search-panel"; +import { SearchProvider, useSearchWorkspace } from "./search-provider"; + +const state = vi.hoisted(() => ({ capabilities: {} as Partial })); +const detail = vi.hoisted(() => ({ open: vi.fn() })); +vi.mock("@/components/features/app-shell", () => ({ useApp: () => state })); +vi.mock("@/components/features/detail-panel", () => ({ useDetailPanel: () => detail })); +vi.mock("next/dynamic", () => ({ default: () => () => null })); +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}; }, + ), +})); + +function section(chunk: string, score: number): Section { + return { chunk_id: chunk, heading: `Heading ${chunk}`, content: `Body ${chunk}`, score, rank: 1, source_id: "src", source_name: "Manuals" }; +} +const compareResponse: EvalCompareResponse = { + query: "question", + results: [ + { strategy: "multi", sections: [section("c1", 0.8)], stats: { latency_total_ms: 900 }, error: null }, + { strategy: "sag2", sections: [section("c1", 0.9), section("c2", 0.7)], stats: { latency_total_ms: 2100 }, error: null }, + ], + judges: [], + judge_enabled: true, + judge_reason: null, +}; + +let root: Root; +let container: HTMLDivElement; +let compareRequests: Array>; +let searchRequests: Array>; +let workspace: ReturnType; + +function Capture() { + workspace = useSearchWorkspace(); + return null; +} + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + state.capabilities = { + llm_configured: true, search_strategy: "vector", + search_strategies: ["vector", "multi_es_fast", "multi", "multi_jev", "sag2"], + }; + detail.open.mockClear(); + compareRequests = []; searchRequests = []; + vi.stubGlobal("fetch", async (url: RequestInfo | URL, options?: RequestInit) => { + const target = String(url); + if (target.includes("/sources")) return Response.json([]); + if (target.includes("/activity")) return Response.json([]); + if (target.includes("/search/eval-compare")) { + compareRequests.push(JSON.parse(String(options?.body))); + return Response.json(compareResponse); + } + if (target.includes("/search")) { + searchRequests.push(JSON.parse(String(options?.body))); + return Response.json({ error: { code: "boom", message: "stopped" } }, { status: 500 }); + } + return Response.json({}); + }); + 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.unstubAllGlobals(); }); + +async function render() { + await act(async () => root.render( + + + + + + + + , + )); +} +const byTestId = (id: string) => container.querySelector(`[data-testid="${id}"]`); +const chip = (strategy: string) => byTestId(`search-compare-chip-${strategy}`) as HTMLButtonElement | null; +const chipState = (strategy: string) => chip(strategy)?.getAttribute("data-state"); +async function click(element: HTMLElement | null) { + expect(element).not.toBeNull(); + await act(async () => element!.click()); +} +async function typeQuery(value: string) { + const input = container.querySelector('input[type="text"]')!; + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!; + await act(async () => { + setter.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} +async function submit() { + await act(async () => container.querySelector("form")!.requestSubmit()); +} + +describe("search compare mode", () => { + it("replaces the mode control with 2–3 chips seeded from the current mode", async () => { + await render(); + expect(byTestId("search-strategy")).not.toBeNull(); + expect(byTestId("search-compare-config")).toBeNull(); + await click(byTestId("search-compare-toggle")); + expect(byTestId("search-strategy")).toBeNull(); + expect(container.querySelectorAll('[data-testid^="search-compare-chip-"]')).toHaveLength(5); + expect(chipState("vector")).toBe("on"); + expect(chipState("sag2")).toBe("on"); + expect(chipState("multi")).toBe("off"); + expect(chip("sag2")?.textContent).toContain("Paid"); + expect(chip("vector")?.textContent).not.toContain("Paid"); + expect(byTestId("search-compare-hint")?.textContent).toBe("Pick 2–3 modes to compare side by side with the same question"); + + await click(chip("multi")); + expect(chipState("multi")).toBe("on"); + expect(chip("multi_jev")?.disabled).toBe(true); + expect(chip("multi_es_fast")?.disabled).toBe(true); + await click(chip("vector")); + expect(chipState("vector")).toBe("off"); + expect(chip("multi_jev")?.disabled).toBe(false); + // Two is the floor: deselecting one of the remaining pair is ignored. + await click(chip("sag2")); + expect(chipState("sag2")).toBe("on"); + expect(chipState("multi")).toBe("on"); + }); + + it("omits modes the deployment cannot serve", async () => { + state.capabilities = { + ...state.capabilities, + search_strategies_disabled: { sag2: { reason: "jev_api_key_missing", message: "Add a key" } }, + }; + await render(); + await click(byTestId("search-compare-toggle")); + expect(chip("sag2")).toBeNull(); + expect(chipState("vector")).toBe("on"); + expect(chipState("multi_jev")).toBe("on"); + }); + + it("runs eval-compare with the query, chips, scope and judge, then adopts a mode", async () => { + await render(); + await act(async () => workspace.setScope([{ id: "a", name: "Alpha" }])); + await click(byTestId("search-compare-toggle")); + await click(chip("multi")); + await click(chip("vector")); + // The scope chips move under the mode chips while comparing. + expect(byTestId("search-compare-config")?.textContent).toContain("Alpha"); + expect(byTestId("search-compare-judge")?.getAttribute("data-state")).toBe("checked"); + await typeQuery("question"); + await submit(); + expect(compareRequests).toEqual([ + { query: "question", strategies: ["multi", "sag2"], source_ids: ["a"], top_k: 12, judge: true }, + ]); + expect(searchRequests).toEqual([]); + const results = byTestId("search-compare-results")!; + expect(results.querySelector('[data-testid="compare-column-multi"]')).not.toBeNull(); + expect(results.querySelector('[data-testid="compare-column-sag2"]')).not.toBeNull(); + expect(results.querySelectorAll('[data-testid="compare-common-hit"]')).toHaveLength(2); + + await click(byTestId("compare-adopt-sag2")); + expect(byTestId("search-compare-config")).toBeNull(); + expect(workspace.strategy).toBe("sag2"); + expect(workspace.strategyOrigin).toBe("pinned"); + expect(searchRequests).toEqual([ + expect.objectContaining({ query: "question", strategy: "sag2", source_ids: ["a"] }), + ]); + expect(byTestId("search-strategy")?.textContent).toContain("SAG2 evidence retrieval"); + }); + + it("hides the judge switch without an LLM and sends judge=false", async () => { + state.capabilities = { ...state.capabilities, llm_configured: false }; + await render(); + await click(byTestId("search-compare-toggle")); + expect(byTestId("search-compare-judge")).toBeNull(); + expect(byTestId("search-compare-config")?.textContent).toContain("Scope: all knowledge"); + await typeQuery("question"); + await submit(); + expect(compareRequests).toEqual([ + { query: "question", strategies: ["vector", "sag2"], top_k: 12, judge: false }, + ]); + }); + + it("keeps the last normal result while compare is on and restores it when off", async () => { + await render(); + await typeQuery("question"); + await submit(); + expect(searchRequests).toHaveLength(1); + expect(container.textContent).toContain("Search did not complete"); + await click(byTestId("search-compare-toggle")); + expect(container.textContent).not.toContain("Search did not complete"); + expect(container.textContent).toContain("Enter a question and press Enter to compare"); + await click(byTestId("search-compare-toggle")); + expect(container.textContent).toContain("Search did not complete"); + expect(searchRequests).toHaveLength(1); + }); + + it("opens a compared passage through the detail panel", async () => { + await render(); + await click(byTestId("search-compare-toggle")); + await typeQuery("question"); + await submit(); + const passage = [...container.querySelectorAll('[data-testid="compare-column-sag2"] button')] + .find((button) => button.textContent?.includes("Heading c2"))!; + await click(passage); + expect(detail.open).toHaveBeenCalledWith({ + kind: "chunk", sourceId: "src", chunkId: "c2", heading: "Heading c2", sourceName: "Manuals", + }); + }); +}); diff --git a/apps/web/components/features/search/search-panel.tsx b/apps/web/components/features/search/search-panel.tsx index decd1834..1a8db4d1 100644 --- a/apps/web/components/features/search/search-panel.tsx +++ b/apps/web/components/features/search/search-panel.tsx @@ -5,19 +5,25 @@ import dynamic from "next/dynamic"; import { useTranslations } from "next-intl"; import { Clock, + Columns2, History, Library, List, Search as SearchIcon, Sparkles, + Trophy, Waypoints, X, } from "lucide-react"; import { toast } from "sonner"; +import type { EvalStrategyResult } from "@/lib/api"; import { getSearchStrategy, getSearchStrategiesDisabled, + isJevScoredStrategy, + SEARCH_STRATEGIES, + SEARCH_STRATEGY_ICONS, type SearchStrategy, } from "@/lib/retrieval-config"; import type { SearchResultSort } from "@/lib/search-result-sort"; @@ -28,6 +34,7 @@ import type { Citation, SearchEvent, SearchResponse, + Section, Source, } from "@/lib/types"; import { useApp } from "@/components/features/app-shell"; @@ -45,9 +52,17 @@ import { SearchSummaryCard, sectionCitation, } from "@/components/features/search/search-panel-sections"; +import { SearchCompareResults } from "@/components/features/search/search-compare-results"; +import { + COMPARE_MAX_STRATEGIES, + COMPARE_MIN_STRATEGIES, + useSearchCompare, +} from "@/components/features/search/use-search-compare"; import { SearchStrategyControl } from "@/components/features/search-strategy-control"; +import { strategyBadgeClassName } from "@/components/features/retrieval-compare-parts"; import { EmptyState } from "@/components/features/empty-state"; import { Skeleton } from "@/components/ui/skeleton"; +import { Switch } from "@/components/ui/switch"; import { Toggle } from "@/components/ui/toggle"; import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"; import { @@ -135,6 +150,18 @@ export function SearchPanel({ const hydrationKeyRef = React.useRef(""); const contentView = search.contentView; const changeContentView = search.setContentView; + const disabledMap = React.useMemo( + () => getSearchStrategiesDisabled(capabilities, searchStrategies("unsupportedBackend")), + [capabilities, searchStrategies], + ); + const enabledStrategies = React.useMemo( + () => SEARCH_STRATEGIES.map((item) => item.value).filter((value) => !disabledMap[value]), + [disabledMap], + ); + const compare = useSearchCompare({ + enabledStrategies, + judgeAvailable: Boolean(capabilities?.llm_configured), + }); const executeSearch = React.useCallback( async (options: { @@ -167,6 +194,62 @@ export function SearchPanel({ [changeContentView, onSearchComplete, onSearchError, onSearchStart, search, t], ); + const compareRun = compare.run; + const runCompare = React.useCallback(async (query?: string) => { + const text = (query ?? search.query).trim(); + if (!text) return null; + setMentionOpen(false); + changeContentView("results"); + // Same scope resolution as the normal search: no scope means every source. + return compareRun({ + query: text, + sourceIds: search.scoped.length ? search.scoped.map((source) => source.id) : undefined, + topK: search.topK, + }); + }, [changeContentView, compareRun, search.query, search.scoped, search.topK]); + + function toggleCompare(on: boolean) { + if (on) compare.enable(search.strategy); + else compare.disable(); + } + + /** Pin the compared mode and land in the regular results with the same question. */ + function adoptStrategy(strategy: SearchStrategy) { + const query = (compare.result?.query || compare.lastQuery || search.query).trim(); + search.setStrategy(strategy); + compare.disable(); + if (!query) return; + search.setQuery(query); + void executeSearch({ query, strategy, saveExploration: false }); + } + + /** A compared passage opens through the same detail flow as the normal list. */ + function openCompareSection(section: Section, index: number, column: EvalStrategyResult) { + const citation = sectionCitation(section, index); + if (onCitationClick) { + onCitationClick(citation, { + query: compare.result?.query ?? compare.lastQuery, + sections: column.sections, + events: [], + entities: [], + relations: [], + source_hits: [], + summary: "", + exploration_id: null, + stats: column.stats, + }); + return; + } + if (!section.chunk_id || !section.source_id) return; + open({ + kind: "chunk", + sourceId: section.source_id, + chunkId: section.chunk_id, + heading: section.heading, + sourceName: section.source_name ?? undefined, + }); + } + const activitySourceIds = React.useMemo( () => search.scoped.map((source) => source.id).sort(), [search.scoped], @@ -286,6 +369,10 @@ export function SearchPanel({ async function run(e?: React.FormEvent) { e?.preventDefault(); + if (compare.enabled) { + await runCompare(); + return; + } await executeSearch({ saveExploration: false, }); @@ -301,7 +388,7 @@ export function SearchPanel({ } const activeView = showGraphView ? view : "list"; - const graphViewActive = activeView === "graph" && Boolean(search.result?.events.length); + const graphViewActive = !compare.enabled && activeView === "graph" && Boolean(search.result?.events.length); const citations = React.useMemo( () => search.result?.sections.map(sectionCitation) ?? [], [search.result], @@ -328,6 +415,24 @@ export function SearchPanel({ current: currentViewLabel, next: nextViewLabel, }); + // In compare mode the scope chips move under the mode chips so the input keeps its room. + const scopeChips = search.scoped.map((sc) => ( + + + {sc.name} + + + )); return (
- {search.scoped.map((sc) => ( - - - {sc.name} - - - ))} + {!compare.enabled && scopeChips} { const cancelledSearch = search.busy; search.clear(); + compare.reset(); if (cancelledSearch) onSearchCancel?.(); setMentionOpen(false); inputRef.current?.focus(); @@ -438,13 +529,26 @@ export function SearchPanel({ )} - + + + {t("compare")} + + {!compare.enabled && ( + + )}
{mentionOpen && (
@@ -490,6 +594,7 @@ export function SearchPanel({ type="button" onClick={() => { search.cancel(); + compare.cancel(); onSearchCancel?.(); onCancel?.(); }} @@ -499,6 +604,63 @@ export function SearchPanel({ )}
+ {compare.enabled && ( +
+
+ + {enabledStrategies.map((value) => { + const Icon = SEARCH_STRATEGY_ICONS[value]; + const on = compare.strategies.includes(value); + return ( + = COMPARE_MAX_STRATEGIES} + data-testid={`search-compare-chip-${value}`} + className="h-7 min-w-0 gap-1.5 rounded-full border border-border bg-transparent px-2.5 text-xs font-normal text-muted-foreground hover:text-foreground data-[state=on]:border-primary/40 data-[state=on]:bg-primary/10 data-[state=on]:text-primary [&_svg]:size-3.5" + > + + {searchStrategies(getSearchStrategy(value).labelKey)} + {isJevScoredStrategy(value) && ( + {searchStrategies("paid")} + )} + + ); + })} + + + {compare.strategies.length < COMPARE_MIN_STRATEGIES ? t("compareMin") : t("compareHint")} + +
+
+ {compare.judgeAvailable && ( + + )} +
+ {search.scoped.length ? scopeChips : {t("compareScopeAll")}} +
+
+
+ )} {showRecentActivity && showContentSwitcher && ( @@ -516,7 +678,7 @@ export function SearchPanel({ {t("history")} @@ -524,7 +686,7 @@ export function SearchPanel({ {t("recentActivity")} @@ -533,7 +695,44 @@ export function SearchPanel({
)} - {contentView === "results" && search.busy && search.result === null ? ( + {compare.enabled && contentView === "results" ? ( +
+ {compare.busy || compare.result || compare.error ? ( + <> +
+

+ {t("results")} + + + {t("compare")} + +

+ {!compact && compare.lastQuery && ( + {compare.lastQuery} + )} +
+ void runCompare(compare.lastQuery)} + /> + + ) : ( +
+
+ +

{t("compareStartTitle")}

+

{t("compareHint")}

+
+
+ )} +
+ ) : contentView === "results" && search.busy && search.result === null ? (
diff --git a/apps/web/components/features/search/use-search-compare.test.ts b/apps/web/components/features/search/use-search-compare.test.ts new file mode 100644 index 00000000..c72f4227 --- /dev/null +++ b/apps/web/components/features/search/use-search-compare.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from "vitest"; + +import type { SearchStrategy } from "@/lib/retrieval-config"; +import { + COMPARE_MAX_STRATEGIES, + COMPARE_MIN_STRATEGIES, + defaultCompareStrategies, + selectCompareStrategies, + sortCompareStrategies, +} from "./use-search-compare"; + +const all: SearchStrategy[] = ["vector", "multi_es_fast", "multi", "multi_jev", "sag2"]; + +describe("default compare selection", () => { + it("pairs the current mode with sag2 when it is enabled", () => { + expect(defaultCompareStrategies("vector", all)).toEqual(["vector", "sag2"]); + expect(defaultCompareStrategies("multi", all)).toEqual(["multi", "sag2"]); + }); + it("falls back to multi_jev, then multi, when sag2 is unavailable", () => { + expect(defaultCompareStrategies("vector", ["vector", "multi", "multi_jev"])).toEqual(["vector", "multi_jev"]); + expect(defaultCompareStrategies("vector", ["vector", "multi_es_fast", "multi"])).toEqual(["vector", "multi"]); + }); + it("never pairs a mode with itself", () => { + expect(defaultCompareStrategies("sag2", all)).toEqual(["multi_jev", "sag2"]); + expect(defaultCompareStrategies("multi", ["vector", "multi"])).toEqual(["vector", "multi"]); + }); + it("uses any other enabled mode when no preferred alternative exists", () => { + expect(defaultCompareStrategies("vector", ["vector", "multi_es_fast"])).toEqual(["vector", "multi_es_fast"]); + }); + it("leaves a single pick when nothing else can be served", () => { + expect(defaultCompareStrategies("vector", ["vector"])).toEqual(["vector"]); + expect(defaultCompareStrategies("sag2", ["vector"])).toEqual(["vector"]); + }); +}); + +describe("compare selection bounds", () => { + it("accepts two or three enabled modes in catalog order", () => { + expect(selectCompareStrategies(["vector", "sag2"], ["sag2", "multi", "vector"], all)).toEqual(["vector", "multi", "sag2"]); + expect(selectCompareStrategies(["vector", "multi", "sag2"], ["multi", "sag2"], all)).toEqual(["multi", "sag2"]); + }); + it("keeps the previous picks when the change would leave fewer than two", () => { + expect(selectCompareStrategies(["vector", "sag2"], ["sag2"], all)).toEqual(["vector", "sag2"]); + expect(selectCompareStrategies(["vector", "sag2"], [], all)).toEqual(["vector", "sag2"]); + }); + it("keeps the previous picks when the change would exceed three", () => { + expect(selectCompareStrategies(["vector", "multi", "sag2"], ["vector", "multi", "multi_jev", "sag2"], all)) + .toEqual(["vector", "multi", "sag2"]); + }); + it("drops unknown and disabled values before applying the bounds", () => { + expect(selectCompareStrategies(["vector", "multi"], ["vector", "multi", "bogus", "sag2"], ["vector", "multi"])) + .toEqual(["vector", "multi"]); + }); + it("exposes the 2–3 bounds used by the chips", () => { + expect(COMPARE_MIN_STRATEGIES).toBe(2); + expect(COMPARE_MAX_STRATEGIES).toBe(3); + expect(sortCompareStrategies(["sag2", "vector"])).toEqual(["vector", "sag2"]); + }); +}); diff --git a/apps/web/components/features/search/use-search-compare.ts b/apps/web/components/features/search/use-search-compare.ts new file mode 100644 index 00000000..94bde25e --- /dev/null +++ b/apps/web/components/features/search/use-search-compare.ts @@ -0,0 +1,212 @@ +"use client"; + +import * as React from "react"; +import { useTranslations } from "next-intl"; + +import { api, ApiError, type EvalCompareResponse } from "@/lib/api"; +import { + isSearchStrategy, + SEARCH_STRATEGIES, + type SearchStrategy, +} from "@/lib/retrieval-config"; + +export const COMPARE_MIN_STRATEGIES = 2; +export const COMPARE_MAX_STRATEGIES = 3; + +/** The alternative that differs most from a typical pick, in order of preference. */ +const PREFERRED_ALTERNATIVES: readonly SearchStrategy[] = ["sag2", "multi_jev", "multi"]; + +/** Keep chips and columns in catalog order regardless of click order. */ +export function sortCompareStrategies( + values: ReadonlyArray, +): SearchStrategy[] { + const picked = new Set(values); + return SEARCH_STRATEGIES.map((item) => item.value).filter((value) => picked.has(value)); +} + +/** + * Seed the compare selection: the mode the user already has, plus the enabled + * mode that behaves most differently from it (sag2 → multi_jev → multi). + */ +export function defaultCompareStrategies( + current: SearchStrategy, + enabled: ReadonlyArray, +): SearchStrategy[] { + const picks: SearchStrategy[] = enabled.includes(current) ? [current] : []; + const alternative = PREFERRED_ALTERNATIVES.find( + (value) => value !== current && enabled.includes(value), + ) ?? enabled.find((value) => value !== current); + if (alternative) picks.push(alternative); + return sortCompareStrategies(picks); +} + +/** + * Apply a toggle-group change while enforcing 2–3 picks: a change that would + * leave the group outside that range is ignored and the previous picks stay. + */ +export function selectCompareStrategies( + current: ReadonlyArray, + next: ReadonlyArray, + enabled: ReadonlyArray, +): SearchStrategy[] { + const valid = sortCompareStrategies( + next.filter((value): value is SearchStrategy => isSearchStrategy(value) && enabled.includes(value)), + ); + if (valid.length < COMPARE_MIN_STRATEGIES || valid.length > COMPARE_MAX_STRATEGIES) { + return sortCompareStrategies(current); + } + return valid; +} + +export interface SearchCompareRunOptions { + query: string; + sourceIds?: string[]; + topK?: number; +} + +export interface SearchCompareState { + /** Compare mode is on: the search box runs eval-compare instead of a normal search. */ + enabled: boolean; + /** Selected modes, filtered to what the deployment can serve. */ + strategies: SearchStrategy[]; + /** Whether an LLM judge can run at all on this deployment. */ + judgeAvailable: boolean; + /** Effective judge flag sent with the request. */ + judge: boolean; + busy: boolean; + /** Modes of the request in flight, so busy columns can be drawn. */ + pendingStrategies: SearchStrategy[]; + result: EvalCompareResponse | null; + error: string | null; + lastQuery: string; + canRun: boolean; + enable: (current: SearchStrategy) => void; + disable: () => void; + selectStrategies: (values: ReadonlyArray) => void; + setJudge: (judge: boolean) => void; + run: (options: SearchCompareRunOptions) => Promise; + cancel: () => void; + reset: () => void; +} + +/** + * Local state for the side-by-side compare on the search page. It never + * touches the normal search lifecycle in SearchProvider, so toggling compare + * off brings the previous normal result straight back. + */ +export function useSearchCompare({ + enabledStrategies, + judgeAvailable, +}: { + enabledStrategies: ReadonlyArray; + judgeAvailable: boolean; +}): SearchCompareState { + const t = useTranslations("Search"); + const [enabled, setEnabled] = React.useState(false); + const [selected, setSelected] = React.useState([]); + const [judgeChoice, setJudgeChoice] = React.useState(true); + const [busy, setBusy] = React.useState(false); + const [pendingStrategies, setPendingStrategies] = React.useState([]); + const [result, setResult] = React.useState(null); + const [error, setError] = React.useState(null); + const [lastQuery, setLastQuery] = React.useState(""); + const abortRef = React.useRef(null); + + const enabledKey = enabledStrategies.join("\u0000"); + const strategies = React.useMemo( + () => selected.filter((value) => enabledStrategies.includes(value)), + // eslint-disable-next-line react-hooks/exhaustive-deps + [selected, enabledKey], + ); + const judge = judgeAvailable && judgeChoice; + + const cancel = React.useCallback(() => { + abortRef.current?.abort(); + abortRef.current = null; + setBusy(false); + }, []); + + React.useEffect(() => () => { + abortRef.current?.abort(); + }, []); + + const enable = React.useCallback((current: SearchStrategy) => { + setSelected(defaultCompareStrategies(current, enabledStrategies)); + setEnabled(true); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [enabledKey]); + + const disable = React.useCallback(() => { + cancel(); + setEnabled(false); + }, [cancel]); + + const selectStrategies = React.useCallback((values: ReadonlyArray) => { + setSelected((current) => selectCompareStrategies(current, values, enabledStrategies)); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [enabledKey]); + + const reset = React.useCallback(() => { + cancel(); + setResult(null); + setError(null); + setLastQuery(""); + setPendingStrategies([]); + }, [cancel]); + + const run = React.useCallback(async ({ query, sourceIds, topK }: SearchCompareRunOptions) => { + const text = query.trim(); + if (!text || strategies.length < COMPARE_MIN_STRATEGIES) return null; + abortRef.current?.abort(); + const controller = new AbortController(); + abortRef.current = controller; + setBusy(true); + setError(null); + setResult(null); + setLastQuery(text); + setPendingStrategies(strategies); + try { + const response = await api.evalCompare({ + query: text, + strategies, + source_ids: sourceIds, + top_k: topK, + judge, + }, controller.signal); + if (abortRef.current !== controller) return null; + setResult(response); + return response; + } catch (caught) { + if (abortRef.current !== controller) return null; + if (!(caught instanceof ApiError && caught.code === "aborted")) { + setError(caught instanceof ApiError ? caught.message : t("compareFailed")); + } + return null; + } finally { + if (abortRef.current === controller) { + abortRef.current = null; + setBusy(false); + } + } + }, [judge, strategies, t]); + + return { + enabled, + strategies, + judgeAvailable, + judge, + busy, + pendingStrategies, + result, + error, + lastQuery, + canRun: !busy && strategies.length >= COMPARE_MIN_STRATEGIES, + enable, + disable, + selectStrategies, + setJudge: setJudgeChoice, + run, + cancel, + reset, + }; +} diff --git a/apps/web/messages/en-US.json b/apps/web/messages/en-US.json index 694ff202..38266835 100644 --- a/apps/web/messages/en-US.json +++ b/apps/web/messages/en-US.json @@ -1303,7 +1303,26 @@ "startTitle": "Enter a question to start searching", "startDescription": "Answers use only relevance-ranked evidence and preserve clickable references.", "emptyGraph": "No event–entity relationships to display", - "emptyGraphDescription": "The matching events are not linked to entities yet. Switch to the list to view event summaries." + "emptyGraphDescription": "The matching events are not linked to entities yet. Switch to the list to view event summaries.", + "compare": "Compare", + "compareAria": "Compare retrieval modes side by side", + "compareModesAria": "Modes to compare", + "compareHint": "Pick 2–3 modes to compare side by side with the same question", + "compareMin": "Pick at least 2 modes to compare", + "compareScopeAll": "Scope: all knowledge", + "compareStartTitle": "Enter a question and press Enter to compare", + "compareRunning": "Running the modes side by side…", + "compareEmpty": "Nothing was retrieved", + "compareFailed": "Comparison failed", + "compareLatency": "{seconds} s", + "compareHits": "{count, plural, one {# hit} other {# hits}}", + "compareUsage": "JEV {requests} requests · {judgments} judgments{tokens}", + "compareUsageTokens": " · {tokens} input tokens", + "judgeToggle": "LLM judge", + "judgeMissing": "No judge verdict was produced", + "judgeTie": "Tie", + "adoptMode": "Search with this mode", + "commonHit": "Shared hit" }, "Graph": { "layout": "Graph layout", diff --git a/apps/web/messages/zh-CN.json b/apps/web/messages/zh-CN.json index 82ea6899..1f241476 100644 --- a/apps/web/messages/zh-CN.json +++ b/apps/web/messages/zh-CN.json @@ -1303,7 +1303,26 @@ "startTitle": "输入问题开始搜索", "startDescription": "回答只会使用经过相关性重排的证据,并保留可点击引用。", "emptyGraph": "没有可展示的事件—实体关系", - "emptyGraphDescription": "当前命中的事件尚未关联实体,可切回列表查看事件摘要。" + "emptyGraphDescription": "当前命中的事件尚未关联实体,可切回列表查看事件摘要。", + "compare": "对比", + "compareAria": "并排对比多种检索模式", + "compareModesAria": "参与对比的检索模式", + "compareHint": "选择 2–3 种模式,用同一问题并排对比", + "compareMin": "至少选择 2 种模式才能对比", + "compareScopeAll": "范围:全部知识库", + "compareStartTitle": "输入问题,回车开始对比", + "compareRunning": "正在并排检索…", + "compareEmpty": "没有召回任何内容", + "compareFailed": "对比检索失败", + "compareLatency": "耗时 {seconds} s", + "compareHits": "召回 {count, number} 条", + "compareUsage": "JEV {requests} 次请求 · {judgments} 次判定{tokens}", + "compareUsageTokens": " · {tokens} token", + "judgeToggle": "LLM 评审", + "judgeMissing": "本次未生成评审结果", + "judgeTie": "平局", + "adoptMode": "按此模式检索", + "commonHit": "共同命中" }, "Graph": { "layout": "图谱布局",