Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71b8f9be24 | ||
|
|
d257188d09 | ||
|
|
bde0220373 | ||
|
|
a88d227cc0 | ||
|
|
0d0cefb25e | ||
|
|
be8cf028ff | ||
|
|
d0a4fd60f2 | ||
|
|
aae877b880 | ||
|
|
ef5ff06590 | ||
|
|
7eb38aa6ad | ||
|
|
2624228f6f |
No files matched your search
@@ -4,6 +4,39 @@ Hy Memory and MemHub are versioned and released independently.
|
||||
|
||||
## Unreleased
|
||||
|
||||
- MemHub's DeepSeek Harness app page can grant recall again (#230). The
|
||||
"一键插入应用" switch used to be greyed out with `unsupported_host`, and a
|
||||
profile installed from the CLI stayed `install-only` with no way to approve
|
||||
it. The one switch now covers every detected profile
|
||||
(`deepseek-harness:<profile>`): on installs each profile's MCP patch and
|
||||
grants recall, off removes the patch and revokes the grant. The page lists
|
||||
each profile with its state, and names any profile that failed while
|
||||
keeping the others. While the switch is on, a profile created later is
|
||||
installed and granted automatically, without restarting MemHub; the Runtime
|
||||
also no longer fails every host read when it meets a profile created after
|
||||
it started. The harness docs no longer describe an unmounted sources page.
|
||||
|
||||
- MemHub's `deepseek-harness` source imports session files whose names carry the
|
||||
format generation: `session.v3.jsonl.zstd` and `session.v4.jsonl.zstd` are now
|
||||
discovered alongside the original `session.jsonl[.zstd]`. Discovery accepts
|
||||
any `session[.vN].jsonl[.zstd]` name and the header's `version` decides
|
||||
whether the session is parsed (v0/v3/v4) or refused as `unsupported_schema`.
|
||||
A refused file is reported and keeps no cursor, so the release that learns
|
||||
its format reads it from the top.
|
||||
v4 tool results, which are written as plain `text` blocks rather than
|
||||
`tool-result` blocks, are read through the same clipping and credential
|
||||
scrubbing path. Previously every versioned session was invisible: the import
|
||||
job completed with `discovered 0` while the files sat on disk.
|
||||
|
||||
- SDK: Intention dedup is now configurable per client
|
||||
(`MemoryConfig.recall.intention_dedup_enabled`, default `true`;
|
||||
`recall.intention_dedup_threshold`, default `MEMORY_DEDUP_THRESHOLD` or
|
||||
`0.95`). Env defaults: `MEMORY_INTENTION_DEDUP_ENABLED`,
|
||||
`MEMORY_INTENTION_DEDUP_THRESHOLD`. When on, behaviour is unchanged
|
||||
(duplicates found at read time are still deleted); when off, no intention
|
||||
dedup runs, at read time or within a write batch, and nothing is hidden,
|
||||
dropped or deleted. The threshold applies to read-time dedup only. Refs #241.
|
||||
|
||||
## MemHub 1.0.6 — 2026-11-02
|
||||
|
||||
Build 37, on `hy-memory==2.0.11`. Linux x64/arm64 Runtime and macOS arm64
|
||||
|
||||
@@ -182,9 +182,29 @@ SDK 不设置 Rerank Search 并发上限。开启后模型在 `HyMemoryClient`
|
||||
| `MEMORY_RECALL_STRENGTH_TAU` | `180` | 衰减时间常数,天 |
|
||||
| `MEMORY_RECALL_ACCESS_TRACKING` | `true` | Strength 开启时是否回写访问信息 |
|
||||
| `MEMORY_ENTITY_STORE_ENABLED` | `false` | 是否维护独立 entity collection;当前 Reader 不直接读取 |
|
||||
| `MEMORY_INTENTION_DEDUP_ENABLED` | `true` | 是否对 L7 Intention 判重(读侧和写入侧批内);见下文 |
|
||||
| `MEMORY_INTENTION_DEDUP_THRESHOLD` | `MEMORY_DEDUP_THRESHOLD`,再缺省为 `0.95` | Intention 读侧判重的 cosine 阈值 |
|
||||
|
||||
旧数据可调用当前公开方法 `client.build_entity_store(user_id)` 补建 Entity Store。
|
||||
|
||||
Intention 判重:开启时(默认,与以往行为一致),Search 召回的 L7 Intention 中,
|
||||
同 `user_id` + 同 `agent_id` + `memory_at` 同一天 + `valid_until` 相同、且 cosine ≥ 阈值的
|
||||
条目视为复本,只返回最早写入的一条,其余在后台从向量库**删除**。判重不区分内容中的项目、
|
||||
对象等语义差异,内容高度相似但对象不同的意图可能被误删;写入时同一批抽取结果也会做一次
|
||||
批内判重。关闭后这两处都不判重,不隐藏、不丢弃、也不删除意图。两项对应
|
||||
`MemoryConfig.recall.intention_dedup_enabled` /
|
||||
`recall.intention_dedup_threshold`,按 client 生效,环境变量只提供默认值:
|
||||
|
||||
```python
|
||||
client = HyMemoryClient.from_config({
|
||||
"recall": {"intention_dedup_enabled": False},
|
||||
})
|
||||
```
|
||||
|
||||
`MEMORY_DEDUP_THRESHOLD` 同时被写入侧批内意图判重和 dedup 内核使用;
|
||||
`MEMORY_INTENTION_DEDUP_THRESHOLD` 只影响读侧 Intention 判重,写入侧批内判重的阈值
|
||||
仍取 `MEMORY_DEDUP_THRESHOLD`。
|
||||
|
||||
## 日志、Trace 与历史
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|
||||
@@ -432,6 +432,14 @@ class RecallConfig:
|
||||
retrieval_clauses_require_keyword: bool = None # env: MEMORY_RETRIEVAL_CLAUSES_REQUIRE_KEYWORD
|
||||
retrieval_clauses_min_keyword_score: float = None # normalized BM25 floor
|
||||
supplemental_propositions_enabled: bool = None # env: MEMORY_SUPPLEMENTAL_PROPOSITIONS_ENABLED
|
||||
# ── Intention(L7)判重 ──
|
||||
# 开启(默认):召回时同 user+agent+同天 memory_at+同 valid_until 且
|
||||
# cosine≥阈值 的意图视为复本,只返回最早一条,其余异步从 VDB 删除(历史行为)。
|
||||
# 关闭:读侧与写入侧批内都不判重——不隐藏、不丢弃、不删除任何意图。
|
||||
intention_dedup_enabled: bool = None # env: MEMORY_INTENTION_DEDUP_ENABLED
|
||||
# 读侧意图判重 cosine 阈值。env: MEMORY_INTENTION_DEDUP_THRESHOLD,
|
||||
# 未设置时回退到共享的 MEMORY_DEDUP_THRESHOLD(兼容旧部署),默认 0.95。
|
||||
intention_dedup_threshold: float = None
|
||||
|
||||
# 最小分数阈值
|
||||
min_score_threshold: float = 0.0
|
||||
@@ -750,6 +758,15 @@ class RecallConfig:
|
||||
self.supplemental_propositions_enabled = _get_env_bool(
|
||||
"MEMORY_SUPPLEMENTAL_PROPOSITIONS_ENABLED", False
|
||||
)
|
||||
if self.intention_dedup_enabled is None:
|
||||
self.intention_dedup_enabled = _get_env_bool(
|
||||
"MEMORY_INTENTION_DEDUP_ENABLED", True
|
||||
)
|
||||
if self.intention_dedup_threshold is None:
|
||||
self.intention_dedup_threshold = _get_env_float(
|
||||
"MEMORY_INTENTION_DEDUP_THRESHOLD",
|
||||
_get_env_float("MEMORY_DEDUP_THRESHOLD", 0.95),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -1384,6 +1401,8 @@ class MemoryConfig:
|
||||
"supplemental_propositions_enabled": (
|
||||
self.recall.supplemental_propositions_enabled
|
||||
),
|
||||
"intention_dedup_enabled": self.recall.intention_dedup_enabled,
|
||||
"intention_dedup_threshold": self.recall.intention_dedup_threshold,
|
||||
},
|
||||
"pipeline": {
|
||||
"default_version": self.pipeline.default_version,
|
||||
|
||||
@@ -15,6 +15,9 @@ HY Memory - Intention (L7) 召回 + 惰性过期转换 + 复本判定
|
||||
→ 视为同一个意图的复本(extractor 复读机 / 多 session 重复表达)。
|
||||
保留组里 `gmt_created` 最早的(老的先来先得,稳定 id);
|
||||
- **异步删库**:其余复本 fire-and-forget 从 VDB 删除,不影响本次调用 RT。
|
||||
- **开关**:判重受 `MemoryConfig.recall.intention_dedup_enabled`(默认开)与
|
||||
`recall.intention_dedup_threshold` 控制,由 reader 按 client 配置传入。
|
||||
关闭时完全跳过判重:不隐藏、不删除任何意图(写入侧批内判重同样跳过)。
|
||||
|
||||
Q: 为什么要看 memory_at 和 valid_until?
|
||||
A: 意图是 point-in-time 信号。同一句"我周五要开会",如果一条 memory_at 在
|
||||
@@ -38,8 +41,14 @@ from ...models.memory import MemoryLayer, MemoryStatus
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _get_dedup_threshold() -> float:
|
||||
"""去重 cosine 阈值:沿用 dedup 内核的 MEMORY_DEDUP_THRESHOLD,默认 0.95。"""
|
||||
def _get_dedup_threshold(configured: Optional[float] = None) -> float:
|
||||
"""去重 cosine 阈值:优先用 client 配置;否则(或配置非法)沿用 dedup 内核的
|
||||
MEMORY_DEDUP_THRESHOLD,默认 0.95。"""
|
||||
try:
|
||||
if configured is not None:
|
||||
return float(configured)
|
||||
except (TypeError, ValueError):
|
||||
logger.warning(f"[intention] invalid dedup threshold: {configured!r}")
|
||||
try:
|
||||
return float(os.environ.get("MEMORY_DEDUP_THRESHOLD", 0.95))
|
||||
except (TypeError, ValueError):
|
||||
@@ -244,6 +253,8 @@ async def recall_intentions(
|
||||
stats_out: Optional[Dict[str, Any]] = None,
|
||||
include_sources: Optional[List[str]] = None,
|
||||
exclude_sources: Optional[List[str]] = None,
|
||||
dedup_enabled: bool = True,
|
||||
dedup_threshold: Optional[float] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
召回未过期的 L7_INTENTION 节点(VDB),惰性过期转 L2_FACT,判重并异步删复本。
|
||||
@@ -260,6 +271,11 @@ async def recall_intentions(
|
||||
now: 当前时间(默认 datetime.now(),测试可注入)
|
||||
stats_out: 可选 dict,本函数把分段耗时与数量**原地回填**进去,供调用方落
|
||||
READ_INTENTION pipeline log。传 None 则完全不统计(零开销)。
|
||||
dedup_enabled: 是否执行读侧判重(及复本异步删库)。False 时跳过判重,
|
||||
所有未过期意图原样返回,不删除任何节点。默认 True(历史行为)。
|
||||
dedup_threshold: 判重 cosine 阈值。None 时回退到 env
|
||||
MEMORY_DEDUP_THRESHOLD(默认 0.95),兼容直接调用本函数的旧代码;
|
||||
reader 总是传入 `recall.intention_dedup_threshold`。
|
||||
|
||||
Returns:
|
||||
[{"node_id", "score", "node", "layer": "l7_intention", "source": "vdb_intention"}, ...]
|
||||
@@ -272,7 +288,7 @@ async def recall_intentions(
|
||||
埋点字段(回填进 stats_out):
|
||||
耗时(ms): vdb_search_ms / expire_ms / backfill_embed_ms / dedup_ms / total_ms
|
||||
数量: fetched / expired / survivors / dedup_dropped / returned
|
||||
配置: fetch_limit / out_limit / dedup_threshold
|
||||
配置: fetch_limit / out_limit / dedup_enabled / dedup_threshold
|
||||
说明: expire_ms、backfill_embed_ms 只有真的发生了对应操作才非 0,
|
||||
借此可判断慢在 VDB 检索、逐条过期转换、补拉向量还是判重计算。
|
||||
"""
|
||||
@@ -358,7 +374,7 @@ async def recall_intentions(
|
||||
_t = time.perf_counter()
|
||||
_backfilled = 0
|
||||
_missing_cnt = 0
|
||||
if survivors:
|
||||
if survivors and dedup_enabled: # 补拉只为判重;关闭时无需这次 VDB 读
|
||||
missing_ids = [
|
||||
h.get("node_id") for h in survivors
|
||||
if h.get("node_id") and not getattr(h.get("node"), "embedding", None)
|
||||
@@ -391,18 +407,23 @@ async def recall_intentions(
|
||||
)
|
||||
|
||||
# 2. 判重:同 user + 同天 memory_at + valid_until 同日 + cosine≥threshold
|
||||
# dedup_enabled=False → 完全跳过:不隐藏、不删除。
|
||||
_t = time.perf_counter()
|
||||
threshold = _get_dedup_threshold()
|
||||
try:
|
||||
kept, delete_ids = _partition_duplicates(survivors, threshold)
|
||||
except Exception as e:
|
||||
# 任何 dedup 异常 → 降级为不去重(返回全部 survivors 截断 limit)
|
||||
logger.warning(f"[intention] dedup partition failed, degrade to raw: {e}")
|
||||
threshold = _get_dedup_threshold(dedup_threshold)
|
||||
if dedup_enabled:
|
||||
try:
|
||||
kept, delete_ids = _partition_duplicates(survivors, threshold)
|
||||
except Exception as e:
|
||||
# 任何 dedup 异常 → 降级为不去重(返回全部 survivors 截断 limit)
|
||||
logger.warning(f"[intention] dedup partition failed, degrade to raw: {e}")
|
||||
kept, delete_ids = survivors, []
|
||||
else:
|
||||
kept, delete_ids = survivors, []
|
||||
# 纯 CPU(cosine 两两比较);survivors 多时可能显著
|
||||
_stat(
|
||||
dedup_ms=round((time.perf_counter() - _t) * 1000, 2),
|
||||
dedup_dropped=len(delete_ids),
|
||||
dedup_enabled=bool(dedup_enabled),
|
||||
dedup_threshold=threshold,
|
||||
)
|
||||
|
||||
|
||||
@@ -1856,6 +1856,12 @@ class BaseReadPipeline(ReadPipeline):
|
||||
stats_out=_intent_stats,
|
||||
include_sources=request.include_sources,
|
||||
exclude_sources=request.exclude_sources,
|
||||
dedup_enabled=bool(getattr(
|
||||
self.config.recall, "intention_dedup_enabled", True
|
||||
)),
|
||||
dedup_threshold=getattr(
|
||||
self.config.recall, "intention_dedup_threshold", None
|
||||
),
|
||||
)
|
||||
await trace_log.log_intention(
|
||||
stats=_intent_stats,
|
||||
|
||||
@@ -635,6 +635,7 @@ class MemoryWriter(WritePipeline):
|
||||
不查 VDB、不做"新写入 vs 库里已有"的对比,避免给 VDB 增加读压力。
|
||||
库内存量污染由 recall 侧异步删除逐步清理。best-effort:任何异常都
|
||||
回退到"不判重、全写入",绝不影响 upsert 主流程。
|
||||
`recall.intention_dedup_enabled=False` 时跳过批内判重,全部写入。
|
||||
"""
|
||||
if not intentions:
|
||||
return []
|
||||
@@ -660,7 +661,11 @@ class MemoryWriter(WritePipeline):
|
||||
# ============ 批内 dedup(不查 VDB,只对本批 intentions 互斥判重) ============
|
||||
keep_mask: List[bool] = [True] * len(intentions)
|
||||
try:
|
||||
dropped = self._intention_batch_dedup(intentions, embeddings)
|
||||
dropped = (
|
||||
self._intention_batch_dedup(intentions, embeddings)
|
||||
if getattr(self.config.recall, "intention_dedup_enabled", True)
|
||||
else []
|
||||
)
|
||||
for i in dropped:
|
||||
if 0 <= i < len(keep_mask):
|
||||
keep_mask[i] = False
|
||||
|
||||
@@ -30,8 +30,7 @@ vi.mock("@one-memory/runtime-control", async (importOriginal) => ({
|
||||
}));
|
||||
|
||||
function languageState(uiLanguage: string | null, extra = {}) {
|
||||
const sdk =
|
||||
uiLanguage === null || uiLanguage === "zh-Hans" ? "auto" : uiLanguage;
|
||||
const sdk = uiLanguage === null ? "auto" : uiLanguage;
|
||||
return {
|
||||
ui_language: uiLanguage,
|
||||
sdk_language: sdk,
|
||||
@@ -95,7 +94,7 @@ describe("memhub settings language", () => {
|
||||
});
|
||||
expect(transport.put).not.toHaveBeenCalled();
|
||||
const text = (await capturedRun(["settings", "language"])).stdout;
|
||||
expect(text).toContain("界面语言:跟随系统(未选择)");
|
||||
expect(text).toContain("界面语言:未设置(SDK 自动识别)");
|
||||
expect(text).toContain("SDK 提示语言:auto");
|
||||
});
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
* `memhub settings language [<code>|system]`.
|
||||
*
|
||||
* The display language the App reports to the Runtime (`ui_language`), and
|
||||
* the SDK prompt language it implies. zh-Hans and "system" (no explicit
|
||||
* choice) pass no language, so the SDK keeps detecting Chinese or English as
|
||||
* before; every other code, en included, makes extraction and the other SDK
|
||||
* prompts use that language. A change applies at once: a write in flight
|
||||
* the SDK prompt language it implies. Every code, zh-Hans and en included,
|
||||
* makes extraction and the other SDK prompts use that language; "system"
|
||||
* (no language set) passes none, so the SDK keeps detecting Chinese or
|
||||
* English as before. The App sends the language it shows, so it is only
|
||||
* unset on an install without the App. A change applies at once: a write in flight
|
||||
* finishes in the old language, the next ones use the new one. The App sends
|
||||
* its own choice again whenever it changes there.
|
||||
*/
|
||||
@@ -162,14 +163,14 @@ export function renderLanguageText(document: LanguageDocument): string {
|
||||
const lines = [
|
||||
`界面语言:${
|
||||
state.ui_language === null
|
||||
? "跟随系统(未选择)"
|
||||
? "未设置(SDK 自动识别)"
|
||||
: `${state.ui_language}(${NAMES[state.ui_language]})`
|
||||
}`,
|
||||
`SDK 提示语言:${sdkText(state.sdk_language)}`,
|
||||
];
|
||||
if (document.state === "ok") {
|
||||
lines.push(
|
||||
`可选:${UI_LANGUAGES.join("、")}、system。简体中文和 system 不指定语言,其余语言(包括 en)会让 SDK 使用该语言。`,
|
||||
`可选:${UI_LANGUAGES.join("、")}、system。任一语言(包括 zh-Hans、en)都会让 SDK 使用该语言;system 不指定语言,SDK 自动识别中文或英文。`,
|
||||
);
|
||||
}
|
||||
if (document.state === "unchanged") lines.push("没有需要改动的设置。");
|
||||
|
||||
@@ -766,7 +766,7 @@ class PipelineStatus(BaseModel):
|
||||
#: default; empty while every feature is at its default.
|
||||
features: dict[MemoryFeatureName, bool] = Field(default_factory=dict)
|
||||
#: The display language the App last reported (`ui_language`); null =
|
||||
#: never chosen or "follow the system".
|
||||
#: none set (the App sends the language it shows, even following the system).
|
||||
ui_language: UiLanguage | None = None
|
||||
#: The SDK prompt language: `auto` (the SDK detects zh/en) or a code.
|
||||
sdk_language: str = SDK_LANGUAGE_AUTO
|
||||
@@ -777,9 +777,9 @@ class UiLanguageState(BaseModel):
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
#: What the App reported; null = never chosen or "follow the system".
|
||||
#: What the App reported; null = none set (CLI/API-only, or `system`).
|
||||
ui_language: UiLanguage | None
|
||||
#: What SDK clients are built with: `auto` (zh-Hans or no choice: the SDK
|
||||
#: What SDK clients are built with: `auto` (no language set: the SDK
|
||||
#: detects zh/en, as before) or the code passed as `MemoryConfig.language`.
|
||||
sdk_language: str
|
||||
languages: tuple[UiLanguage, ...] = UI_LANGUAGES
|
||||
@@ -4616,9 +4616,9 @@ def create_app(
|
||||
async def put_ui_language(request: UiLanguageUpdate) -> UiLanguageChange:
|
||||
"""Record the App's display language; one global setting, not per user.
|
||||
|
||||
zh-Hans and null pass no language to the SDK, which keeps detecting
|
||||
zh/en as before; every other code (en included) is passed as
|
||||
`MemoryConfig.language`. A change of that SDK language rebuilds the
|
||||
Every code (zh-Hans and en included) is passed as
|
||||
`MemoryConfig.language`; only null passes no language, so the SDK
|
||||
keeps detecting zh/en as before. A change of that SDK language rebuilds the
|
||||
SDK clients like a feature change: a write in flight finishes in the
|
||||
old language. Nothing stored is migrated and no collection is renamed.
|
||||
"""
|
||||
|
||||
@@ -367,8 +367,8 @@ def language_kwargs(language: str | None) -> LanguageKwargs:
|
||||
def apply_sdk_language(config: MemoryConfig, language: str | None) -> MemoryConfig:
|
||||
"""Set the SDK prompt language (`MemoryConfig.language`), when there is one.
|
||||
|
||||
None (zh-Hans, or no choice) sets nothing: the SDK detects zh/en as it
|
||||
always did. Like a feature, the language never touches `vector_store`, so
|
||||
None (no language set) sets nothing: the SDK detects zh/en as it always
|
||||
did. Every display language, zh-Hans included, is set explicitly. Like a feature, the language never touches `vector_store`, so
|
||||
the collection identity never depends on it.
|
||||
"""
|
||||
if language is not None:
|
||||
|
||||
@@ -209,6 +209,7 @@ class JsonlSourceAdapter:
|
||||
file_predicate: Callable[[AuthorizedSourceFile], bool] | None = None,
|
||||
suffixes: frozenset[str] = frozenset({".jsonl"}),
|
||||
header_selector: Callable[[dict[str, JsonValue]], bool] | None = None,
|
||||
header_gate: Callable[[dict[str, JsonValue] | None], bool] | None = None,
|
||||
) -> None:
|
||||
if descriptor.source_id != grant.source_id:
|
||||
raise ValueError("Descriptor and authorized root source IDs must match")
|
||||
@@ -219,6 +220,10 @@ class JsonlSourceAdapter:
|
||||
self.file_predicate = file_predicate or (lambda _: True)
|
||||
self.suffixes = suffixes
|
||||
self.header_selector = header_selector
|
||||
# False refuses the whole file before any record is read. It reports
|
||||
# and leaves no cursor, so a release that learns the format reads the
|
||||
# file from the top instead of finding it already behind a checkpoint.
|
||||
self.header_gate = header_gate
|
||||
self._header_cache: dict[str, tuple[str, dict[str, JsonValue] | None]] = {}
|
||||
self._history_listing_cache: SourceListing | None = None
|
||||
|
||||
@@ -371,6 +376,9 @@ class JsonlSourceAdapter:
|
||||
source_file, checkpoint, header = await asyncio.to_thread(
|
||||
self._prepare, listed, options
|
||||
)
|
||||
if self.header_gate is not None and not self.header_gate(header):
|
||||
yield ScanFailure(reason_code=ScanIssueCode.UNSUPPORTED_SCHEMA)
|
||||
continue
|
||||
_log.debug(
|
||||
"import_file_read source=%s file=%d/%d file_bytes=%d planned_bytes=%d",
|
||||
self.descriptor.source_id,
|
||||
@@ -574,6 +582,9 @@ class JsonlSourceAdapter:
|
||||
# resumed scan starts past the header, and the records after it need
|
||||
# it just as much as the first batch did.
|
||||
header = await _read_header(reader, source_file, self.header_selector)
|
||||
if self.header_gate is not None and not self.header_gate(header):
|
||||
yield ScanFailure(reason_code=ScanIssueCode.UNSUPPORTED_SCHEMA)
|
||||
continue
|
||||
last: SourceCursor = _start_cursor(source_file, options, checkpoint)
|
||||
async for raw in iterate_in_worker(
|
||||
partial(reader, source_file, checkpoint=checkpoint),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import re
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
from pydantic import JsonValue
|
||||
@@ -37,6 +38,19 @@ DEEPSEEK_HARNESS_DESCRIPTOR = SourceDescriptor(
|
||||
),
|
||||
)
|
||||
|
||||
#: One session is one file, and the name carries the format generation it was
|
||||
#: written in: `session.jsonl[.zstd]` for the first format, then
|
||||
#: `session.v3.jsonl.zstd` and `session.v4.jsonl.zstd`. The version segment is
|
||||
#: part of the published on-disk contract, so discovery must accept it — the
|
||||
#: earlier exact-name match imported none of the versioned files.
|
||||
SESSION_FILE = re.compile(r"^session(?:\.v[0-9]+)?\.jsonl(?:\.zstd)?$")
|
||||
|
||||
#: Session generations this parser has been verified against: the first format
|
||||
#: (header `version: 0`), v3 and v4. Discovery is intentionally wider than
|
||||
#: parsing: a future generation is found by pattern and then skipped from its
|
||||
#: header, so it is reported as unsupported instead of silently vanishing.
|
||||
SUPPORTED_SESSION_VERSIONS = frozenset({0, 3, 4})
|
||||
|
||||
|
||||
def create_deepseek_harness_adapter(
|
||||
grant: AuthorizedSourceRoot,
|
||||
@@ -49,25 +63,43 @@ def create_deepseek_harness_adapter(
|
||||
grant=grant,
|
||||
parser=parse_deepseek_harness_record,
|
||||
source_version=source_version,
|
||||
file_predicate=lambda source_file: (
|
||||
source_file.relative_path.name in {"session.jsonl", "session.jsonl.zstd"}
|
||||
),
|
||||
file_predicate=lambda source_file: bool(SESSION_FILE.match(source_file.relative_path.name)),
|
||||
suffixes=frozenset({".jsonl", ".zstd"}),
|
||||
header_selector=_is_session_header,
|
||||
header_gate=_supported_session,
|
||||
)
|
||||
|
||||
|
||||
def _is_session_header(record: dict[str, JsonValue]) -> bool:
|
||||
"""Harness writes the session's `cwd` once, in the first line only.
|
||||
|
||||
Verified against a session this machine produced: the header is
|
||||
`{"type":"session","version":0,"id":...,"cwd":"/private/tmp/dsh-verify"}`
|
||||
and no later record repeats it. Read per-record, `cwd` is therefore always
|
||||
absent and every turn imports with no workspace.
|
||||
Verified against sessions this machine produced: the header is
|
||||
`{"type":"session","version":0|4,"id":...,"cwd":...}` and no later record
|
||||
repeats it. Read per-record, `cwd` is therefore always absent and every turn
|
||||
imports with no workspace.
|
||||
"""
|
||||
return record.get("type") == "session"
|
||||
|
||||
|
||||
def _supported_session(header: dict[str, JsonValue] | None) -> bool:
|
||||
"""Whether the session's declared format generation is one we can read.
|
||||
|
||||
A missing header, or a header without `version`, is the first format — the
|
||||
earliest files this adapter already read. Any declared version outside
|
||||
`SUPPORTED_SESSION_VERSIONS` is refused rather than interpreted with today's
|
||||
field rules: a future format may change field semantics, and importing it
|
||||
wrongly is harder to undo than not importing it yet.
|
||||
"""
|
||||
if header is None:
|
||||
return True
|
||||
version = header.get("version")
|
||||
if version is None:
|
||||
return True
|
||||
if not isinstance(version, int) or isinstance(version, bool):
|
||||
return False
|
||||
return version in SUPPORTED_SESSION_VERSIONS
|
||||
|
||||
|
||||
def parse_deepseek_harness_record(
|
||||
record: dict[str, JsonValue],
|
||||
context: SourceRecordContext,
|
||||
@@ -80,6 +112,11 @@ def parse_deepseek_harness_record(
|
||||
)
|
||||
event_type = record.get("type")
|
||||
data = as_record(record.get("data"))
|
||||
if not _supported_session(context.header):
|
||||
return ParsedSkip(
|
||||
reason_code=ScanIssueCode.UNSUPPORTED_SCHEMA,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
if event_type == "session":
|
||||
return ParsedSkip(reason_code=ScanIssueCode.UNKNOWN_RECORD)
|
||||
if data is None:
|
||||
@@ -148,11 +185,18 @@ def _tool_message(
|
||||
"""`tool/call` carries name and arguments; `tool/result` a user-role message.
|
||||
|
||||
The same call also appears as a `tool-call` block in `assistant/message`;
|
||||
only the event is read, so it is stored once.
|
||||
only the event is read, so it is stored once. The first format and v3 wrap
|
||||
the result in `tool-result` blocks; v4 writes plain `text` blocks, so both
|
||||
shapes are read through the same clipping and credential-scrubbing path.
|
||||
"""
|
||||
message = as_record(data.get("message"))
|
||||
if record.get("type") == "tool/result" and message is not None:
|
||||
text = tool_blocks_evidence(message.get("content"), block_types=frozenset({"tool-result"}))
|
||||
if text is None:
|
||||
text = tool_blocks_evidence(
|
||||
[{"type": "tool-result", "content": message.get("content")}],
|
||||
block_types=frozenset({"tool-result"}),
|
||||
)
|
||||
message_id = first_string(message.get("id"), data.get("callId"))
|
||||
else:
|
||||
text = tool_evidence_text(data)
|
||||
|
||||
@@ -74,9 +74,9 @@ class ConfigDocument(BaseModel):
|
||||
#: SDK retrieval and extraction features a person set; an unset one keeps
|
||||
#: the SDK default. See `one_memory.memory_features`.
|
||||
memory_features: MemoryFeatures = Field(default_factory=MemoryFeatures)
|
||||
#: The display language a person chose in the App; None = never chosen or
|
||||
#: "follow the system". See `one_memory.ui_language` for what it does to
|
||||
#: the SDK.
|
||||
#: The display language the App shows (its choice, or the system language
|
||||
#: it follows); None = none set. See `one_memory.ui_language` for what it
|
||||
#: does to the SDK.
|
||||
ui_language: UiLanguage | None = None
|
||||
|
||||
@field_validator("sources")
|
||||
|
||||
@@ -3,14 +3,19 @@
|
||||
The App owns the choice (its language selector) and tells Core whenever it
|
||||
changes, so Core can build every SDK client with it. It is one global value in
|
||||
`config.json` (`ui_language`), beside `memory_mode` and `memory_features`;
|
||||
absent (never chosen, or "follow the system") means no explicit choice.
|
||||
absent means no language was set (a CLI/API-only install, or
|
||||
`settings language system`). An App that follows the system sends the
|
||||
language it resolved and shows, not null.
|
||||
|
||||
The owner's rule for the SDK:
|
||||
|
||||
- zh-Hans, or no explicit choice: pass no language. The SDK keeps detecting
|
||||
Chinese or English from the text, exactly as before this setting existed.
|
||||
- Any other code, including en: pass it as `MemoryConfig.language`, so
|
||||
extraction and the other prompts use that language.
|
||||
- Any supported code, zh-Hans and en included: pass it as
|
||||
`MemoryConfig.language`, so extraction and the other prompts use that
|
||||
language. Every display language is passed explicitly (#243).
|
||||
- No language at all (never set, as on a CLI/API-only install): pass no
|
||||
language. The SDK keeps detecting Chinese or English from the text, exactly
|
||||
as before this setting existed. The App does not leave it unset: it sends
|
||||
the language it shows, including when it follows the system.
|
||||
|
||||
The language never names a collection; a change rebuilds the SDK handles the
|
||||
way a mode or feature change does (#218 use count).
|
||||
@@ -51,8 +56,6 @@ UI_LANGUAGES: tuple[UiLanguage, ...] = (
|
||||
)
|
||||
#: Codes earlier App builds stored, and the code each one is now.
|
||||
LEGACY_UI_LANGUAGES: dict[str, UiLanguage] = {"zh-CN": "zh-Hans"}
|
||||
#: Display languages that leave the SDK's own zh/en detection in charge.
|
||||
AUTO_DETECTED: frozenset[str] = frozenset({"zh-Hans"})
|
||||
#: What status shows when no language is passed to the SDK.
|
||||
SDK_LANGUAGE_AUTO = "auto"
|
||||
|
||||
@@ -66,8 +69,9 @@ def normalize_ui_language(value: object) -> UiLanguage | None:
|
||||
|
||||
|
||||
def sdk_language(ui_language: str | None) -> str | None:
|
||||
"""The `MemoryConfig.language` for a display language; None = SDK auto-detect."""
|
||||
language = normalize_ui_language(ui_language)
|
||||
if language is None or language in AUTO_DETECTED:
|
||||
return None
|
||||
return language
|
||||
"""The `MemoryConfig.language` for a display language; None = SDK auto-detect.
|
||||
|
||||
Every supported code is passed as is; only an unset (or unknown) value
|
||||
leaves the SDK to detect zh/en.
|
||||
"""
|
||||
return normalize_ui_language(ui_language)
|
||||
@@ -25,6 +25,7 @@
|
||||
| `test_c1_cross_source_session_isolation.py` | `contract` | Same session name in two sources must stay two conversations. |
|
||||
| `test_c1_damage_per_source.py` | `contract` | Damage and unknown schema, per source: a bad record must not sink the import. |
|
||||
| `test_c1_deepseek_profiles.py` | `contract` | DeepSeek Harness has two profiles; only the headless session form is importable. |
|
||||
| `test_c1_deepseek_versioned_sessions.py` | `contract` | DeepSeek Harness versions its session file names; every generation must import. |
|
||||
| `test_c1_import_event_matrix.py` | `contract` | C1 owned matrix: existing history, new file, append, truncate/replace, restart, revoke. |
|
||||
| `test_c1_import_failure_injection.py` | `contract` | C1 failure injection: atomic receipt, disk-full, read-only source, rotation. |
|
||||
| `test_c1_import_instrumentation.py` | `contract` | Instrumented import accounting: bytes read, opens, hashes, jobs, duplicates. |
|
||||
@@ -318,4 +319,4 @@
|
||||
| `test_workspace_recall.py` | `contract` | Workspace memories were unreachable from every host; these pin the way in. |
|
||||
| `test_write_queue_lease_renewal.py` | `contract` | Rule 8: a lease must outlive the work it covers, and be renewed while it runs. |
|
||||
|
||||
共 313 个测试文件。
|
||||
共 314 个测试文件。
|
||||
@@ -14,8 +14,8 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
PRIMARY_MARKERS = ("unit", "contract", "integration", "performance", "live")
|
||||
EXPECTED_TEST_FILE_COUNT = 313
|
||||
EXPECTED_TEST_FILES_SHA256 = "dcada5d5421767196a79e415dd47c2b6c6d67681972dbe81481b31867d318928"
|
||||
EXPECTED_TEST_FILE_COUNT = 314
|
||||
EXPECTED_TEST_FILES_SHA256 = "d745df3dfb964a8d2197c1ca3768728249d84ac4729305155ae1ef48428a19e4"
|
||||
|
||||
# Pure transformations, validation models, parity checks and state machines.
|
||||
# This list is intentionally small: uncertain files default to contract.
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
"""DeepSeek Harness versions its session file names; every generation must import.
|
||||
|
||||
The first format writes `<session>/session.jsonl[.zstd]`; v3 and v4 write
|
||||
`session.v3.jsonl.zstd` / `session.v4.jsonl.zstd`. Discovery used to match only
|
||||
the two unversioned names, so every v3/v4 session was invisible to the import
|
||||
job — `discovered 0` while the files sat on disk. These tests pin the file-name
|
||||
contract, the header gate that keeps an unknown future version out of the
|
||||
database, and the upgrade path where a library imported before the fix picks up
|
||||
the versioned files on its next scan.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import zstandard
|
||||
|
||||
from one_memory.imports.adapters import ScanFailure, ScanIssueCode
|
||||
from one_memory.imports.sources import deepseek_harness
|
||||
from one_memory.imports.sources.deepseek_harness import (
|
||||
DEEPSEEK_HARNESS_DESCRIPTOR,
|
||||
create_deepseek_harness_adapter,
|
||||
)
|
||||
from tests.test_secondary_source_adapters import (
|
||||
_cursors,
|
||||
_evidence,
|
||||
_evidence_text,
|
||||
_grant,
|
||||
_scan,
|
||||
_skip_codes,
|
||||
)
|
||||
|
||||
|
||||
def _write_session(directory: Path, name: str, records: list[dict[str, object]]) -> None:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
payload = "".join(f"{json.dumps(record)}\n" for record in records).encode()
|
||||
(directory / name).write_bytes(zstandard.ZstdCompressor().compress(payload))
|
||||
|
||||
|
||||
def _conversation(version: int | None, *, directory: str = "run-a") -> list[dict[str, object]]:
|
||||
header: dict[str, object] = {
|
||||
"type": "session",
|
||||
"version": version,
|
||||
"id": directory,
|
||||
"cwd": "/private/versioned-project",
|
||||
}
|
||||
return [
|
||||
header,
|
||||
{
|
||||
"type": "user/message",
|
||||
"seq": 1,
|
||||
"data": {
|
||||
"id": "human",
|
||||
"role": "user",
|
||||
"source": {"kind": "user"},
|
||||
"content": [{"type": "text", "text": "visible human"}],
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "assistant/message",
|
||||
"seq": 2,
|
||||
"data": {
|
||||
"message": {
|
||||
"id": "assistant",
|
||||
"role": "assistant",
|
||||
"content": [{"type": "text", "text": "visible assistant"}],
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _session_adapter(tmp_path: Path):
|
||||
root = tmp_path / "dsh"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root, create_deepseek_harness_adapter(
|
||||
_grant(DEEPSEEK_HARNESS_DESCRIPTOR.source_id, root, tmp_path)
|
||||
)
|
||||
|
||||
|
||||
def test_versioned_v4_session_file_is_discovered_and_imported(tmp_path: Path) -> None:
|
||||
root, adapter = _session_adapter(tmp_path)
|
||||
session = root / "run-v4"
|
||||
records = _conversation(4, directory="run-v4")
|
||||
records.append(
|
||||
{
|
||||
"type": "tool/result",
|
||||
"seq": 3,
|
||||
"time": 1793341068763,
|
||||
"data": {
|
||||
"callId": "call-1",
|
||||
"message": {"role": "tool", "content": [{"type": "text", "text": "tool output"}]},
|
||||
},
|
||||
}
|
||||
)
|
||||
_write_session(session, "session.v4.jsonl.zstd", records)
|
||||
# A rotated backup next to the live file must not be imported as a second copy.
|
||||
(session / "session.v4.jsonl.zstd.orig-20261027").write_bytes(
|
||||
zstandard.ZstdCompressor().compress(b'{"type":"session","version":4}\n')
|
||||
)
|
||||
|
||||
events = _scan(adapter)
|
||||
|
||||
assert _evidence_text(events) == ["visible human", "visible assistant", "tool output"]
|
||||
evidence = _evidence(events)
|
||||
assert {event.evidence.project for event in evidence} == {"versioned-project"}
|
||||
assert {event.evidence.conversation_id for event in evidence} == {"run-v4"}
|
||||
|
||||
|
||||
def test_versioned_v3_session_file_is_discovered_and_imported(tmp_path: Path) -> None:
|
||||
root, adapter = _session_adapter(tmp_path)
|
||||
_write_session(root / "run-v3", "session.v3.jsonl.zstd", _conversation(3))
|
||||
|
||||
events = _scan(adapter)
|
||||
|
||||
assert _evidence_text(events) == ["visible human", "visible assistant"]
|
||||
|
||||
|
||||
def _tool_result(content: list[dict[str, object]]) -> dict[str, object]:
|
||||
return {
|
||||
"type": "tool/result",
|
||||
"seq": 3,
|
||||
"data": {"callId": "call-1", "message": {"role": "tool", "content": content}},
|
||||
}
|
||||
|
||||
|
||||
def test_tool_output_imports_in_either_block_shape(tmp_path: Path) -> None:
|
||||
"""`tool/result` output written as `text` blocks used to be dropped.
|
||||
|
||||
Only `tool-result` blocks were read, so a session that writes plain `text`
|
||||
blocks lost every tool output. Both shapes must arrive, in any generation.
|
||||
"""
|
||||
root, adapter = _session_adapter(tmp_path)
|
||||
v3 = _conversation(3, directory="run-v3-text")
|
||||
v3.append(_tool_result([{"type": "text", "text": "v3 text output"}]))
|
||||
_write_session(root / "run-v3-text", "session.v3.jsonl.zstd", v3)
|
||||
v0 = _conversation(0, directory="run-v0-block")
|
||||
v0.append(_tool_result([{"type": "tool-result", "content": "v0 block output"}]))
|
||||
_write_session(root / "run-v0-block", "session.jsonl.zstd", v0)
|
||||
|
||||
texts = _evidence_text(_scan(adapter))
|
||||
|
||||
assert "v3 text output" in texts
|
||||
assert "v0 block output" in texts
|
||||
|
||||
|
||||
def test_text_tool_output_is_scrubbed_like_block_output(tmp_path: Path) -> None:
|
||||
root, adapter = _session_adapter(tmp_path)
|
||||
secret = "sk-" + "a" * 40
|
||||
records = _conversation(4, directory="run-secret")
|
||||
records.append(_tool_result([{"type": "text", "text": f"token {secret} " + "x" * 5000}]))
|
||||
_write_session(root / "run-secret", "session.v4.jsonl.zstd", records)
|
||||
|
||||
tool = _evidence_text(_scan(adapter))[-1]
|
||||
|
||||
assert secret not in tool
|
||||
assert len(tool) < 2000
|
||||
|
||||
|
||||
def test_session_file_names_outside_the_contract_are_not_imported(tmp_path: Path) -> None:
|
||||
root, adapter = _session_adapter(tmp_path)
|
||||
for name in (
|
||||
"session.v4.jsonl.zstd.orig-20261027",
|
||||
"session.vx.jsonl.zstd",
|
||||
"other.v4.jsonl.zstd",
|
||||
"session.v4.json",
|
||||
):
|
||||
_write_session(root / name.replace(".", "-"), name, _conversation(4))
|
||||
|
||||
assert _evidence(_scan(adapter)) == []
|
||||
|
||||
|
||||
def test_unknown_future_session_version_imports_nothing(tmp_path: Path) -> None:
|
||||
root, adapter = _session_adapter(tmp_path)
|
||||
records = _conversation(5)
|
||||
records.append(
|
||||
{
|
||||
"type": "user/message",
|
||||
"seq": 9,
|
||||
"data": {
|
||||
"id": "future",
|
||||
"role": "user",
|
||||
"source": {"kind": "user"},
|
||||
"content": [{"type": "text", "text": "future generation payload"}],
|
||||
},
|
||||
}
|
||||
)
|
||||
_write_session(root / "run-v5", "session.v5.jsonl.zstd", records)
|
||||
|
||||
events = _scan(adapter)
|
||||
|
||||
assert _evidence(events) == []
|
||||
assert ScanIssueCode.UNSUPPORTED_SCHEMA in _skip_codes(events)
|
||||
|
||||
|
||||
def test_unknown_session_version_is_reported_and_read_once_supported(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Not importing a future format yet must stay "yet".
|
||||
|
||||
A cursor left behind by the refused scan would put the whole session behind
|
||||
the checkpoint, so the release that learns the format would read nothing.
|
||||
"""
|
||||
root, adapter = _session_adapter(tmp_path)
|
||||
_write_session(root / "run-v5", "session.v5.jsonl.zstd", _conversation(5))
|
||||
|
||||
refused = _scan(adapter)
|
||||
|
||||
assert _cursors(refused) == {}
|
||||
assert [event.reason_code for event in refused if isinstance(event, ScanFailure)] == [
|
||||
ScanIssueCode.UNSUPPORTED_SCHEMA
|
||||
]
|
||||
|
||||
monkeypatch.setattr(deepseek_harness, "SUPPORTED_SESSION_VERSIONS", frozenset({0, 3, 4, 5}))
|
||||
_, upgraded = _session_adapter(tmp_path)
|
||||
|
||||
assert _evidence_text(_scan(upgraded, cursors=_cursors(refused))) == [
|
||||
"visible human",
|
||||
"visible assistant",
|
||||
]
|
||||
|
||||
|
||||
def test_upgrade_scan_rediscovers_versioned_files_already_on_disk(tmp_path: Path) -> None:
|
||||
"""A library imported before this fix must pick up the files on its next scan.
|
||||
|
||||
The first scan sees only the unversioned session that the old predicate
|
||||
matched; after the upgrade, the versioned file next to it is discovered by
|
||||
the next scan while the already imported session stays deduplicated by the
|
||||
cursor it left behind.
|
||||
"""
|
||||
root, adapter = _session_adapter(tmp_path)
|
||||
old = root / "run-old"
|
||||
_write_session(old, "session.jsonl.zstd", _conversation(0, directory="run-old"))
|
||||
first_scan = _scan(adapter)
|
||||
assert _evidence_text(first_scan) == ["visible human", "visible assistant"]
|
||||
assert _evidence(first_scan)[0].evidence.conversation_id == "run-old"
|
||||
|
||||
versioned = root / "run-v4"
|
||||
_write_session(versioned, "session.v4.jsonl.zstd", _conversation(4, directory="run-v4"))
|
||||
cursors = _cursors(first_scan)
|
||||
assert cursors # the old session left a cursor behind
|
||||
|
||||
upgrade_scan = _scan(adapter, cursors=cursors)
|
||||
|
||||
assert _evidence_text(upgrade_scan) == ["visible human", "visible assistant"]
|
||||
assert {event.evidence.conversation_id for event in _evidence(upgrade_scan)} == {"run-v4"}
|
||||
@@ -193,7 +193,7 @@ def _qwenwork() -> Harness:
|
||||
|
||||
def _deepseek() -> Harness:
|
||||
def write(path: Path, turns: list[Turn]) -> None:
|
||||
# deepseek only accepts a file literally named session.jsonl, and nests
|
||||
# deepseek only accepts files named session[.vN].jsonl[.zstd], and nests
|
||||
# the turn under "data".
|
||||
lines: list[dict] = [{"type": "session", "version": 0, "id": "s1", "cwd": "/w"}]
|
||||
for index, (role, text, _session) in enumerate(turns):
|
||||
@@ -225,7 +225,7 @@ def _deepseek() -> Harness:
|
||||
|
||||
from one_memory.imports.sources.deepseek_harness import create_deepseek_harness_adapter
|
||||
|
||||
# deepseek accepts only a file literally named session.jsonl.
|
||||
# deepseek accepts only session[.vN].jsonl[.zstd]; the first format is used here.
|
||||
return Harness(
|
||||
"deepseek-harness",
|
||||
write,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""The App's display language, and the SDK prompt language it implies.
|
||||
|
||||
The owner's rule: zh-Hans, or no explicit choice, passes no language, so the
|
||||
SDK keeps detecting zh/en exactly as before; every other code (en included)
|
||||
is passed as `MemoryConfig.language` (hy-memory 2.0.11). A change rebuilds the
|
||||
The owner's rule (#243): every display language, zh-Hans and en included, is
|
||||
passed as `MemoryConfig.language` (hy-memory 2.0.11); only an unset language
|
||||
passes none, so the SDK keeps detecting zh/en exactly as before. A change rebuilds the
|
||||
handles the way a mode or feature change does, and the language never touches
|
||||
the vector collection identity.
|
||||
"""
|
||||
@@ -28,8 +28,8 @@ from one_memory.secrets import InMemorySecretStore
|
||||
from one_memory.ui_language import UI_LANGUAGES, normalize_ui_language, sdk_language
|
||||
|
||||
TOKEN = "ui-language-test"
|
||||
#: Every code except zh-Hans is passed to the SDK.
|
||||
PASSED = ("en", "zh-Hant", "ja", "es", "de", "pt", "fr", "ko", "ru", "id")
|
||||
#: Every code is passed to the SDK, zh-Hans included.
|
||||
PASSED = ("en", "zh-Hans", "zh-Hant", "ja", "es", "de", "pt", "fr", "ko", "ru", "id")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -51,7 +51,7 @@ def _config(tmp_path: Path, language: str | None):
|
||||
|
||||
|
||||
def test_eleven_codes_and_the_legacy_chinese_code() -> None:
|
||||
assert ("en", "zh-Hans", *PASSED[1:]) == UI_LANGUAGES
|
||||
assert PASSED == UI_LANGUAGES
|
||||
assert len(UI_LANGUAGES) == 11
|
||||
# Earlier App builds stored zh-CN; it is zh-Hans now.
|
||||
assert normalize_ui_language("zh-CN") == "zh-Hans"
|
||||
@@ -60,19 +60,20 @@ def test_eleven_codes_and_the_legacy_chinese_code() -> None:
|
||||
assert normalize_ui_language(None) is None
|
||||
|
||||
|
||||
def test_only_zh_hans_and_no_choice_leave_the_sdk_to_detect() -> None:
|
||||
def test_only_an_unset_language_leaves_the_sdk_to_detect() -> None:
|
||||
assert sdk_language(None) is None
|
||||
assert sdk_language("zh-Hans") is None
|
||||
assert sdk_language("zh-CN") is None
|
||||
assert sdk_language("system") is None
|
||||
assert sdk_language("xx") is None
|
||||
# zh-Hans is passed like every other code; the legacy zh-CN maps to it.
|
||||
assert sdk_language("zh-Hans") == "zh-Hans"
|
||||
assert sdk_language("zh-CN") == "zh-Hans"
|
||||
for code in PASSED:
|
||||
assert sdk_language(code) == code
|
||||
|
||||
|
||||
def test_zh_hans_and_no_choice_build_the_config_of_before(tmp_path) -> None:
|
||||
before = repr(dataclasses.asdict(_config(tmp_path, None)))
|
||||
def test_no_language_builds_the_config_of_before(tmp_path) -> None:
|
||||
assert _config(tmp_path, None).language is None
|
||||
assert repr(dataclasses.asdict(_config(tmp_path, sdk_language("zh-Hans")))) == before
|
||||
assert _config(tmp_path, sdk_language("zh-Hans")).language == "zh-Hans"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", PASSED)
|
||||
@@ -282,17 +283,31 @@ def test_ui_language_api_get_put_and_status(tmp_path, monkeypatch) -> None:
|
||||
assert current["languages"] == list(UI_LANGUAGES)
|
||||
assert reads.current_language() is None and writes.sdk_language() is None
|
||||
|
||||
# zh-Hans: recorded, but the SDK still detects zh/en; nothing rebuilt.
|
||||
# zh-Hans is passed explicitly: Chinese prompts, handles rebuilt (#243).
|
||||
body = (
|
||||
await client.put("/api/v1/settings/ui-language", json={"ui_language": "zh-Hans"})
|
||||
).json()
|
||||
assert body == {**current, "ui_language": "zh-Hans", "rebuilt": False}
|
||||
assert retired == [] and reads.current_language() is None
|
||||
assert body == {
|
||||
**current,
|
||||
"ui_language": "zh-Hans",
|
||||
"sdk_language": "zh-Hans",
|
||||
"rebuilt": True,
|
||||
}
|
||||
assert reads.current_language() == "zh-Hans" and writes.sdk_language() == "zh-Hans"
|
||||
assert retired == ["zh-Hans"]
|
||||
processing = (await client.get("/api/v1/memory-processing")).json()
|
||||
assert processing["pipeline"]["sdk_language"] == "zh-Hans"
|
||||
|
||||
# The same value again changes nothing.
|
||||
body = (
|
||||
await client.put("/api/v1/settings/ui-language", json={"ui_language": "zh-Hans"})
|
||||
).json()
|
||||
assert body["rebuilt"] is False and retired == ["zh-Hans"]
|
||||
|
||||
body = (await client.put("/api/v1/settings/ui-language", json={"ui_language": "ja"})).json()
|
||||
assert body["sdk_language"] == "ja" and body["rebuilt"] is True
|
||||
assert reads.current_language() == "ja" and writes.sdk_language() == "ja"
|
||||
assert retired == ["ja"]
|
||||
assert retired == ["zh-Hans", "ja"]
|
||||
|
||||
# An explicit English choice forces English prompts.
|
||||
body = (await client.put("/api/v1/settings/ui-language", json={"ui_language": "en"})).json()
|
||||
@@ -302,7 +317,7 @@ def test_ui_language_api_get_put_and_status(tmp_path, monkeypatch) -> None:
|
||||
assert processing["pipeline"]["ui_language"] == "en"
|
||||
assert processing["pipeline"]["sdk_language"] == "en"
|
||||
|
||||
# Back to "follow the system": auto again.
|
||||
# Unset (CLI `settings language system`): auto again.
|
||||
body = (await client.put("/api/v1/settings/ui-language", json={"ui_language": None})).json()
|
||||
assert body["sdk_language"] == "auto" and body["rebuilt"] is True
|
||||
assert reads.current_language() is None
|
||||
|
||||
@@ -15,9 +15,13 @@ it("bakes fallback release identity when the packaging pipeline omits it", async
|
||||
expect(config).toMatch(
|
||||
/__ONE_MEMORY_BUILD_NUMBER__: JSON\.stringify\(\s*String\(releaseBuildNumber\)/,
|
||||
);
|
||||
expect(config).toMatch(
|
||||
/process\.env\.ONE_MEMORY_COMMIT\?\.trim\(\) \|\| readSourceCommit\(\)/,
|
||||
expect(config).toContain(
|
||||
"const releaseCommit = resolveReleaseCommit(process.env.ONE_MEMORY_COMMIT)",
|
||||
);
|
||||
expect(config).toMatch(/if \(!trimmed\) return readSourceCommit\(\);/);
|
||||
// A supplied commit must be the full 40-character form the runtime accepts.
|
||||
expect(config).toContain("/^[0-9a-f]{40}$/i.test(trimmed)");
|
||||
expect(config).toContain("return trimmed.toLowerCase();");
|
||||
expect(config).toMatch(
|
||||
/execFileSync\("git", \["rev-parse", "HEAD"\],[\s\S]*?encoding: "utf8"/,
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LanguageSnapshot } from "@one-memory/i18n";
|
||||
import type { GuiLocale, LanguageSnapshot } from "@one-memory/i18n";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { coreUiLanguage, installCoreLanguageSync } from "./core-language-sync";
|
||||
|
||||
@@ -21,11 +21,16 @@ function source(initial: LanguageSnapshot) {
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
describe("Core language sync", () => {
|
||||
it("tells Core null for system and the code for an explicit choice", () => {
|
||||
expect(coreUiLanguage("system")).toBeNull();
|
||||
expect(coreUiLanguage("zh-Hans")).toBe("zh-Hans");
|
||||
expect(coreUiLanguage("en")).toBe("en");
|
||||
expect(coreUiLanguage("ja")).toBe("ja");
|
||||
it("tells Core the language the GUI shows, system included", () => {
|
||||
const shown = (
|
||||
preference: LanguageSnapshot["preference"],
|
||||
locale: GuiLocale,
|
||||
) => coreUiLanguage({ preference, locale, revision: 0 });
|
||||
expect(shown("system", "zh-Hans")).toBe("zh-Hans");
|
||||
expect(shown("system", "en")).toBe("en");
|
||||
expect(shown("zh-Hans", "zh-Hans")).toBe("zh-Hans");
|
||||
expect(shown("en", "en")).toBe("en");
|
||||
expect(shown("ja", "ja")).toBe("ja");
|
||||
});
|
||||
|
||||
it("sends the stored choice once at launch, then every change", async () => {
|
||||
@@ -38,29 +43,33 @@ describe("Core language sync", () => {
|
||||
await settle();
|
||||
language.change({ preference: "system", locale: "en", revision: 2 });
|
||||
await settle();
|
||||
expect(send.mock.calls).toEqual([["es"], ["ja"], [null]]);
|
||||
expect(send.mock.calls).toEqual([["es"], ["ja"], ["en"]]);
|
||||
dispose();
|
||||
language.change({ preference: "de", locale: "de", revision: 3 });
|
||||
await settle();
|
||||
expect(send).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("an untouched install sends null, which leaves the SDK on auto", async () => {
|
||||
it("an untouched install sends the system language the GUI shows", async () => {
|
||||
const language = source({
|
||||
preference: "system",
|
||||
locale: "ja",
|
||||
locale: "zh-Hans",
|
||||
revision: 0,
|
||||
});
|
||||
const send = vi.fn(async () => {});
|
||||
installCoreLanguageSync({ language, send });
|
||||
await settle();
|
||||
expect(send.mock.calls).toEqual([[null]]);
|
||||
expect(send.mock.calls).toEqual([["zh-Hans"]]);
|
||||
// Choosing the language already shown changes nothing Core sees.
|
||||
language.change({ preference: "zh-Hans", locale: "zh-Hans", revision: 1 });
|
||||
await settle();
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reports a failed send and retries it with the next change", async () => {
|
||||
const language = source({ preference: "fr", locale: "fr", revision: 0 });
|
||||
const send = vi
|
||||
.fn<(value: string | null) => Promise<void>>()
|
||||
.fn<(value: string) => Promise<void>>()
|
||||
.mockRejectedValueOnce(new Error("core_unavailable"))
|
||||
.mockResolvedValue(undefined);
|
||||
const reportError = vi.fn();
|
||||
|
||||
@@ -1,35 +1,37 @@
|
||||
import type { GuiLocale, LanguagePreference } from "@one-memory/i18n";
|
||||
import type { GuiLocale, LanguageSnapshot } from "@one-memory/i18n";
|
||||
import type { NativeLanguageSource } from "./native-language";
|
||||
|
||||
/** What Core is told: a code, or null for "follow the system". */
|
||||
export function coreUiLanguage(
|
||||
preference: LanguagePreference,
|
||||
): GuiLocale | null {
|
||||
return preference === "system" ? null : preference;
|
||||
/**
|
||||
* What Core is told: the language the GUI shows. "Follow the system" sends
|
||||
* the language it resolved to, so the memories match the interface a person
|
||||
* sees; the App never leaves the SDK to detect zh/en (#243).
|
||||
*/
|
||||
export function coreUiLanguage(snapshot: LanguageSnapshot): GuiLocale {
|
||||
return snapshot.locale;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep Core's `ui_language` setting on the display language a person chose.
|
||||
* Keep Core's `ui_language` setting on the display language the GUI shows.
|
||||
*
|
||||
* Core builds every SDK client with it: zh-Hans and "follow the system" pass
|
||||
* no language (the SDK keeps detecting zh/en), any other choice sets the SDK
|
||||
* prompt language. Sent once when installed, so a choice made before this
|
||||
* existed reaches Core, then on every committed change; a value Core already
|
||||
* has is not sent again. Best effort: a failed send is reported and retried
|
||||
* with the next change or launch, and never blocks the GUI.
|
||||
* Core builds every SDK client with it and passes it, zh-Hans included, as
|
||||
* the SDK prompt language. Sent once when installed, so a choice made before
|
||||
* this existed, or the system language followed at this launch, reaches
|
||||
* Core; then on every committed change. A value Core already has is not sent
|
||||
* again. Best effort: a failed send is reported and retried with the next
|
||||
* change or launch, and never blocks the GUI.
|
||||
*/
|
||||
export function installCoreLanguageSync(options: {
|
||||
language: NativeLanguageSource;
|
||||
send(uiLanguage: GuiLocale | null): Promise<void>;
|
||||
send(uiLanguage: GuiLocale): Promise<void>;
|
||||
reportError?(error: unknown): void;
|
||||
}): () => void {
|
||||
let closed = false;
|
||||
let sent: GuiLocale | null | undefined;
|
||||
let sent: GuiLocale | undefined;
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
const push = () => {
|
||||
queue = queue.then(async () => {
|
||||
if (closed) return;
|
||||
const value = coreUiLanguage(options.language.read().preference);
|
||||
const value = coreUiLanguage(options.language.read());
|
||||
if (value === sent) return;
|
||||
try {
|
||||
await options.send(value);
|
||||
|
||||
@@ -526,7 +526,22 @@ describe("hourly isolated desktop launch", () => {
|
||||
expect(resolvePackagedBuildNumber("-1")).toBeUndefined();
|
||||
expect(resolvePackagedBuildNumber(undefined, "3907")).toBe(3907);
|
||||
expect(resolvePackagedBuildNumber("3908", "3907")).toBe(3908);
|
||||
expect(resolvePackagedCommit(undefined, "388fd0e9")).toBe("388fd0e9");
|
||||
expect(resolvePackagedCommit("not-a-sha", "388fd0e9")).toBe("388fd0e9");
|
||||
});
|
||||
|
||||
it("resolves only a full 40-character commit and lowercases it", () => {
|
||||
// Every downstream check (packaged-runtime install, local install, release
|
||||
// download, release scripts) requires 40 lowercase hex characters.
|
||||
const embedded = "388fd0e9b3c41a2d5e6f7a8b9c0d1e2f3a4b5c6d";
|
||||
expect(resolvePackagedCommit(undefined, embedded)).toBe(embedded);
|
||||
expect(resolvePackagedCommit(embedded.toUpperCase())).toBe(embedded);
|
||||
expect(
|
||||
resolvePackagedCommit(` ${embedded.toUpperCase()} `, undefined),
|
||||
).toBe(embedded);
|
||||
expect(resolvePackagedCommit("388fd0e9", embedded)).toBe(embedded);
|
||||
expect(resolvePackagedCommit("388fd0e9")).toBeUndefined();
|
||||
expect(resolvePackagedCommit("not-a-sha", embedded)).toBe(embedded);
|
||||
expect(resolvePackagedCommit(`${embedded}0`, embedded)).toBe(embedded);
|
||||
expect(resolvePackagedCommit("g".repeat(40), embedded)).toBe(embedded);
|
||||
expect(resolvePackagedCommit(undefined, "unknown")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -143,6 +143,12 @@ export function resolvePackagedBuildNumber(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The packaged-runtime install, local install, release download and release
|
||||
* scripts all require a full 40-character lowercase commit. Normalise here so
|
||||
* that one format crosses this boundary: an uppercase full SHA is lowercased,
|
||||
* and a short or malformed value is skipped so it cannot shadow the next source.
|
||||
*/
|
||||
export function resolvePackagedCommit(
|
||||
environmentValue: unknown,
|
||||
embeddedValue?: unknown,
|
||||
@@ -150,7 +156,7 @@ export function resolvePackagedCommit(
|
||||
for (const value of [environmentValue, embeddedValue]) {
|
||||
if (typeof value !== "string") continue;
|
||||
const trimmed = value.trim();
|
||||
if (/^[0-9a-f]{7,40}$/i.test(trimmed)) return trimmed;
|
||||
if (/^[0-9a-f]{40}$/i.test(trimmed)) return trimmed.toLowerCase();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -594,9 +594,11 @@ async function initialize(isQuitting: () => boolean): Promise<void> {
|
||||
throw new Error("host_permission_store_unavailable");
|
||||
}
|
||||
if (isQuitting()) return;
|
||||
const hosts = (await recallHosts(app.getPath("home"))).filter(
|
||||
(host) => host.hostId !== "openclaw",
|
||||
);
|
||||
const scanHosts = async () =>
|
||||
(await recallHosts(app.getPath("home"))).filter(
|
||||
(host) => host.hostId !== "openclaw",
|
||||
);
|
||||
const hosts = await scanHosts();
|
||||
readDiagnosticSummary = async () => {
|
||||
const core = coreSupervisor;
|
||||
if (!core) return {};
|
||||
@@ -876,10 +878,14 @@ async function initialize(isQuitting: () => boolean): Promise<void> {
|
||||
});
|
||||
ipcMain.handle("one-memory:recall-hosts", async (event) => {
|
||||
assertAllowedRenderer(event.senderFrame?.url);
|
||||
// A Harness profile can appear at any time, and which ones exist is only
|
||||
// knowable from the disk. In place, so `requireHost` sees it too. One
|
||||
// directory read per list, next to an IPC round trip per host below.
|
||||
hosts.splice(0, hosts.length, ...(await scanHosts()));
|
||||
if (connectionClient?.host) {
|
||||
const inspector = createConnectionClient({ dataDir });
|
||||
const rows: unknown[] = [];
|
||||
for (const host of hosts) {
|
||||
for (const host of [...hosts]) {
|
||||
const inspected = await inspector.host?.({
|
||||
hostId: host.hostId,
|
||||
operation: "inspect",
|
||||
|
||||
@@ -11,8 +11,20 @@ const { resolveBuildNumber, resolveBuildVersion } =
|
||||
};
|
||||
const releaseVersion = resolveBuildVersion(process.env);
|
||||
const releaseBuildNumber = resolveBuildNumber(process.env);
|
||||
const releaseCommit =
|
||||
process.env.ONE_MEMORY_COMMIT?.trim() || readSourceCommit();
|
||||
const releaseCommit = resolveReleaseCommit(process.env.ONE_MEMORY_COMMIT);
|
||||
|
||||
// The runtime accepts only a full 40-character commit, so an explicitly
|
||||
// supplied malformed value fails the build instead of being baked and skipped.
|
||||
function resolveReleaseCommit(explicit: string | undefined): string {
|
||||
const trimmed = explicit?.trim();
|
||||
if (!trimmed) return readSourceCommit();
|
||||
if (!/^[0-9a-f]{40}$/i.test(trimmed)) {
|
||||
throw new Error(
|
||||
`ONE_MEMORY_COMMIT must be a full 40-character hex commit, got ${JSON.stringify(trimmed)}`,
|
||||
);
|
||||
}
|
||||
return trimmed.toLowerCase();
|
||||
}
|
||||
|
||||
function readSourceCommit(): string {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
/**
|
||||
* #230: DeepSeek Harness has no single host, so the app page used to grey the
|
||||
* switch out with `unsupported_host` and offered no other way to grant recall.
|
||||
* The one switch now covers every detected profile.
|
||||
*/
|
||||
|
||||
import type { SourceResponse } from "@one-memory/contracts";
|
||||
import {
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from "@testing-library/react";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { ApplicationDetail } from "./ApplicationDetail";
|
||||
import { readConnectionPreferences } from "./connection-preferences";
|
||||
import { resetConnectionReconcile } from "./connection-reconcile";
|
||||
import { harnessBridge } from "./harness-profiles.test-fixture";
|
||||
|
||||
const source = {
|
||||
source_id: "deepseek-harness",
|
||||
display_name: "DeepSeek Harness",
|
||||
authorized: true,
|
||||
sync_enabled: true,
|
||||
capabilities: {
|
||||
historical_import: "implemented",
|
||||
incremental_import: "implemented",
|
||||
live_sync: "implemented",
|
||||
recall: "implemented",
|
||||
installer: "implemented",
|
||||
verification: "real_replayed",
|
||||
},
|
||||
} as SourceResponse;
|
||||
|
||||
function renderDetail() {
|
||||
return render(
|
||||
<ApplicationDetail
|
||||
source={source}
|
||||
sources={[source]}
|
||||
stale={false}
|
||||
setSync={vi.fn()}
|
||||
refresh={vi.fn().mockResolvedValue({ sources: [source] })}
|
||||
onBack={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
function profileItems() {
|
||||
return within(
|
||||
screen.getByRole("list", { name: "DeepSeek Harness 的 Profile" }),
|
||||
)
|
||||
.getAllByRole("listitem")
|
||||
.map((item) => item.textContent);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
resetConnectionReconcile();
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
window.oneMemory = undefined;
|
||||
window.localStorage.clear();
|
||||
resetConnectionReconcile();
|
||||
});
|
||||
|
||||
it("lists every detected profile with its own state", async () => {
|
||||
harnessBridge({ desktop: "approved", web: "not-installed" });
|
||||
renderDetail();
|
||||
await waitFor(() =>
|
||||
expect(profileItems()).toEqual(["desktop:已接入", "web:未接入"]),
|
||||
);
|
||||
const insertion = screen.getByRole("switch", { name: "一键插入应用" });
|
||||
expect(insertion.hasAttribute("disabled")).toBe(false);
|
||||
expect(screen.queryByText(/当前安装不支持一键插入/)).toBeNull();
|
||||
});
|
||||
|
||||
it("turns every profile on with the one switch and remembers the choice", async () => {
|
||||
const { api, state } = harnessBridge({
|
||||
desktop: "not-installed",
|
||||
web: "not-installed",
|
||||
});
|
||||
renderDetail();
|
||||
const insertion = await screen.findByRole("switch", { name: "一键插入应用" });
|
||||
await waitFor(() => expect(profileItems()).toHaveLength(2));
|
||||
expect(insertion.getAttribute("aria-checked")).toBe("false");
|
||||
fireEvent.click(insertion);
|
||||
await waitFor(() =>
|
||||
expect(profileItems()).toEqual(["desktop:已接入", "web:已接入"]),
|
||||
);
|
||||
expect(api.installRecall.mock.calls.map(([hostId]) => hostId)).toEqual([
|
||||
"deepseek-harness:desktop",
|
||||
"deepseek-harness:web",
|
||||
]);
|
||||
expect([...state.values()]).toEqual(["approved", "approved"]);
|
||||
expect(insertion.getAttribute("aria-checked")).toBe("true");
|
||||
// Not "未接通": the self-checks the grants recorded were read back.
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole("button", { name: /已接通|未接通|检测中/ }).textContent,
|
||||
).toBe("已接通"),
|
||||
);
|
||||
// Remembered, so a profile found on a later launch is connected too.
|
||||
expect(readConnectionPreferences().hostSourceIds).toEqual([
|
||||
"deepseek-harness",
|
||||
]);
|
||||
});
|
||||
|
||||
it("names the profile that failed and keeps the others on", async () => {
|
||||
const { state } = harnessBridge(
|
||||
{ desktop: "not-installed", web: "not-installed" },
|
||||
{ failInstall: ["web"] },
|
||||
);
|
||||
renderDetail();
|
||||
const insertion = await screen.findByRole("switch", { name: "一键插入应用" });
|
||||
await waitFor(() => expect(profileItems()).toHaveLength(2));
|
||||
fireEvent.click(insertion);
|
||||
const alert = await screen.findByRole("alert");
|
||||
expect(alert.textContent).toContain("以下 Profile 未能接入:web");
|
||||
expect(alert.textContent).toContain("应用控制通道暂不可用");
|
||||
await waitFor(() =>
|
||||
expect(profileItems()).toEqual(["desktop:已接入", "web:未接入"]),
|
||||
);
|
||||
expect(state.get("deepseek-harness:desktop")).toBe("approved");
|
||||
expect(insertion.getAttribute("aria-checked")).toBe("true");
|
||||
});
|
||||
|
||||
it("turns every linked profile off with the one switch", async () => {
|
||||
const { api, state } = harnessBridge({
|
||||
desktop: "approved",
|
||||
web: "approved",
|
||||
});
|
||||
renderDetail();
|
||||
const insertion = await screen.findByRole("switch", { name: "一键插入应用" });
|
||||
await waitFor(() =>
|
||||
expect(insertion.getAttribute("aria-checked")).toBe("true"),
|
||||
);
|
||||
fireEvent.click(insertion);
|
||||
await waitFor(() =>
|
||||
expect(profileItems()).toEqual(["desktop:未接入", "web:未接入"]),
|
||||
);
|
||||
expect(api.uninstallRecall).toHaveBeenCalledTimes(2);
|
||||
expect([...state.values()]).toEqual(["not-installed", "not-installed"]);
|
||||
expect(insertion.getAttribute("aria-checked")).toBe("false");
|
||||
expect(readConnectionPreferences().hostSourceIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("names the profile whose connection could not be removed", async () => {
|
||||
harnessBridge(
|
||||
{ desktop: "approved", web: "approved" },
|
||||
{
|
||||
failUninstall: ["desktop"],
|
||||
},
|
||||
);
|
||||
renderDetail();
|
||||
const insertion = await screen.findByRole("switch", { name: "一键插入应用" });
|
||||
await waitFor(() =>
|
||||
expect(insertion.getAttribute("aria-checked")).toBe("true"),
|
||||
);
|
||||
fireEvent.click(insertion);
|
||||
// Removal failed but revocation went through: the grant is gone, the file
|
||||
// is left for the person to check.
|
||||
expect((await screen.findByRole("alert")).textContent).toContain(
|
||||
"已撤销以下 Profile 的记忆权限,但连接文件没有全部移除,请核对:desktop",
|
||||
);
|
||||
});
|
||||
|
||||
it("says how to get a profile when none is detected", async () => {
|
||||
harnessBridge({});
|
||||
renderDetail();
|
||||
expect(
|
||||
await screen.findByText(
|
||||
"还没有检测到 DeepSeek Harness 的 Profile。创建 Profile 后再回到此页。",
|
||||
),
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
screen
|
||||
.getByRole("switch", { name: "一键插入应用" })
|
||||
.hasAttribute("disabled"),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -2,15 +2,21 @@ import type { SourceResponse } from "@one-memory/contracts";
|
||||
import type { MessageKey } from "@one-memory/i18n";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { AppMark } from "./app-mark";
|
||||
import { connectionHostId, preferenceHasSource } from "./connection-hosts";
|
||||
import {
|
||||
connectionHostId,
|
||||
isProfileSource,
|
||||
preferenceHasSource,
|
||||
profileName,
|
||||
} from "./connection-hosts";
|
||||
import {
|
||||
readConnectionPreferences,
|
||||
writeConnectionPreference,
|
||||
} from "./connection-preferences";
|
||||
import { noteUserHostChoice } from "./connection-reconcile";
|
||||
import type { RecallLinkCheck } from "./global";
|
||||
import type { RecallHostStatus, RecallLinkCheck } from "./global";
|
||||
import {
|
||||
disconnectHost,
|
||||
disconnectProfiles,
|
||||
enableHostConnection,
|
||||
hostCapabilities,
|
||||
hostConnectionApproved,
|
||||
@@ -19,8 +25,11 @@ import {
|
||||
hostWriteReason,
|
||||
matchHost,
|
||||
probeHost,
|
||||
profileHosts,
|
||||
profileWriteFailures,
|
||||
refreshRecallHosts,
|
||||
setHostMemoryPermission,
|
||||
sourceConnectionApproved,
|
||||
UNSUPPORTED_NOTE,
|
||||
useRecallHosts,
|
||||
} from "./host-state";
|
||||
@@ -63,6 +72,24 @@ function connectionLabel(input: {
|
||||
return "未开启关联";
|
||||
}
|
||||
|
||||
/** The recorded self-check across the profiles that may use memory: wired
|
||||
* only when every one of them is, otherwise the first one that is not. */
|
||||
function profilesProbeState(profiles: RecallHostStatus[]) {
|
||||
const linked = profiles.filter(hostConnectionApproved);
|
||||
if (!linked.length) return null;
|
||||
for (const host of linked) {
|
||||
const state = host.selfCheck?.state ?? null;
|
||||
if (state !== "wired") return state;
|
||||
}
|
||||
return "wired";
|
||||
}
|
||||
|
||||
function profileList(hosts: readonly ProfileHost[]) {
|
||||
return hosts.map((host) => profileName(host.hostId)).join(", ");
|
||||
}
|
||||
|
||||
type ProfileHost = Pick<RecallHostStatus, "hostId">;
|
||||
|
||||
function SourceIcon({ source }: { source: SourceResponse }) {
|
||||
return (
|
||||
<AppMark
|
||||
@@ -215,7 +242,10 @@ export function ApplicationDetail({
|
||||
if (!mounted.current || version !== epoch.current) return;
|
||||
setRead({ sourceId: id, state: "ready" });
|
||||
setCheckedAt(new Date().toISOString());
|
||||
if (matched?.installed) void probeLink(matched.hostId);
|
||||
// A per-profile source has no single host to probe; its status comes
|
||||
// from each profile's recorded self-check instead.
|
||||
if (matched?.installed && !isProfileSource(id))
|
||||
void probeLink(matched.hostId);
|
||||
else setLink(null);
|
||||
} catch {
|
||||
if (mounted.current && version === epoch.current)
|
||||
@@ -292,10 +322,14 @@ export function ApplicationDetail({
|
||||
}
|
||||
const current = read.sourceId === source.source_id ? read : null;
|
||||
const host = matchHost(hosts, source.source_id);
|
||||
const profileSource = isProfileSource(source.source_id);
|
||||
const profiles = profileHosts(hosts, source.source_id);
|
||||
const loading = !current || current.state === "loading";
|
||||
const readFailed = current?.state === "error";
|
||||
const approved = hostConnectionApproved(host);
|
||||
const unsupported = hostConnectionUnsupported(host);
|
||||
const approved = profileSource
|
||||
? sourceConnectionApproved(hosts, source.source_id)
|
||||
: hostConnectionApproved(host);
|
||||
const unsupported = !profileSource && hostConnectionUnsupported(host);
|
||||
const insertionChecked = insertionIntent ?? approved;
|
||||
const memoryChecked = memoryIntent ?? host?.permission?.state === "approved";
|
||||
const probing =
|
||||
@@ -305,9 +339,10 @@ export function ApplicationDetail({
|
||||
loading ||
|
||||
readFailed ||
|
||||
(stale && current?.state !== "ready");
|
||||
const probeState =
|
||||
link?.probe.state ??
|
||||
(linkPending || linkFailed ? null : (host?.selfCheck?.state ?? null));
|
||||
const probeState = profileSource
|
||||
? profilesProbeState(profiles)
|
||||
: (link?.probe.state ??
|
||||
(linkPending || linkFailed ? null : (host?.selfCheck?.state ?? null)));
|
||||
const stateText = connectionLabel({
|
||||
approved,
|
||||
insertionOn: insertionChecked,
|
||||
@@ -326,10 +361,43 @@ export function ApplicationDetail({
|
||||
? { reason: failureNote(installError.failure) }
|
||||
: {}),
|
||||
});
|
||||
async function applyProfiles(enabled: boolean) {
|
||||
if (enabled) {
|
||||
try {
|
||||
await enableHostConnection(source.source_id);
|
||||
} finally {
|
||||
// Each grant records its self-check on the desktop, and the status row
|
||||
// reads those; nothing else re-reads them while this page is open.
|
||||
await refreshRecallHosts().catch(() => {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const results = await disconnectProfiles(source.source_id);
|
||||
const failed = results.filter((item) => item.outcome.state === "failed");
|
||||
const retained = results.filter(
|
||||
(item) =>
|
||||
item.outcome.state === "revoked" || item.outcome.state === "review",
|
||||
);
|
||||
if (retained.length)
|
||||
setInstallError({
|
||||
key: "appProfilesRevokedRetained",
|
||||
params: { profiles: profileList(retained) },
|
||||
});
|
||||
const first = failed[0]?.outcome;
|
||||
if (first?.state === "failed")
|
||||
throw Object.assign(Error("disconnect_failed"), {
|
||||
profiles: failed.map((item) => profileName(item.hostId)),
|
||||
failure: {
|
||||
reason: first.reason,
|
||||
rereadFailed: first.rereadFailed,
|
||||
} satisfies HostFailure,
|
||||
});
|
||||
}
|
||||
async function applyInsertion(enabled: boolean) {
|
||||
const bridge = window.oneMemory;
|
||||
if (!bridge) return;
|
||||
setInstallError("");
|
||||
if (profileSource) return applyProfiles(enabled);
|
||||
if (enabled) {
|
||||
await enableHostConnection(source.source_id);
|
||||
void probeLink(hostId);
|
||||
@@ -385,6 +453,30 @@ export function ApplicationDetail({
|
||||
}
|
||||
// A failed turn-on keeps the stored choice on; a failed turn-off
|
||||
// shows the grant that is really still there after the re-read.
|
||||
// Per-profile sources name the profiles that failed; the others
|
||||
// keep what they got.
|
||||
const failedProfiles =
|
||||
profileWriteFailures(error) ??
|
||||
(error as { profiles?: string[] }).profiles ??
|
||||
null;
|
||||
if (failedProfiles) {
|
||||
setInstallError({
|
||||
key: wanted
|
||||
? "appProfilesConnectFailed"
|
||||
: "appProfilesDisconnectFailed",
|
||||
params: { profiles: failedProfiles.join(", ") },
|
||||
failure: wanted
|
||||
? {
|
||||
reason: hostWriteReason(error),
|
||||
rereadFailed: hostRereadFailed(error),
|
||||
}
|
||||
: ((error as { failure?: HostFailure }).failure ?? {
|
||||
reason: null,
|
||||
rereadFailed: false,
|
||||
}),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
setInstallError(
|
||||
wanted
|
||||
? {
|
||||
@@ -561,6 +653,31 @@ export function ApplicationDetail({
|
||||
<div>
|
||||
<h2>{text("一键插入应用")}</h2>
|
||||
<p>{text("安装记忆连接,并默认允许此应用使用已授权记忆。")}</p>
|
||||
{profileSource &&
|
||||
(profiles.length ? (
|
||||
<>
|
||||
<ul
|
||||
className="r6-app-profiles"
|
||||
aria-label={t("appProfilesLabel", {
|
||||
name: source.display_name,
|
||||
})}
|
||||
>
|
||||
{profiles.map((profile) => (
|
||||
<li key={profile.hostId}>
|
||||
{t(
|
||||
hostConnectionApproved(profile)
|
||||
? "appProfileOn"
|
||||
: "appProfileOff",
|
||||
{ profile: profileName(profile.hostId) },
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>{t("appProfilesHint")}</p>
|
||||
</>
|
||||
) : (
|
||||
<p>{t("appProfilesNone", { name: source.display_name })}</p>
|
||||
))}
|
||||
{unsupported && (
|
||||
<p>{`${source.display_name} ${text(UNSUPPORTED_NOTE)}`}</p>
|
||||
)}
|
||||
@@ -578,6 +695,7 @@ export function ApplicationDetail({
|
||||
stale ||
|
||||
appLocationNote !== null ||
|
||||
unsupported ||
|
||||
(profileSource && !profiles.length) ||
|
||||
source.capabilities?.installer !== "implemented" ||
|
||||
source.capabilities?.recall !== "implemented" ||
|
||||
!hostCapabilities().install
|
||||
|
||||
@@ -31,6 +31,8 @@ import {
|
||||
hostBridgeAvailable,
|
||||
hostConnectionApproved,
|
||||
hostConnectionUnknown,
|
||||
sourceConnectionApproved,
|
||||
sourceConnectionIncomplete,
|
||||
useRecallHosts,
|
||||
} from "./host-state";
|
||||
import { subscribePoll } from "./poll-scheduler";
|
||||
@@ -737,12 +739,7 @@ export function ApplicationsHome({
|
||||
failure.kind === "host"
|
||||
? preferences.hostSourceIds.some((id) =>
|
||||
sameConnectionHost(id, failure.sourceId),
|
||||
) &&
|
||||
!hosts.some(
|
||||
(host) =>
|
||||
hostConnectionApproved(host) &&
|
||||
hostMatchesSource(failure.sourceId, host.hostId),
|
||||
)
|
||||
) && sourceConnectionIncomplete(hosts, failure.sourceId)
|
||||
: preferences.syncSourceIds.includes(failure.sourceId) &&
|
||||
!imports.sources.some(
|
||||
(source) =>
|
||||
@@ -754,14 +751,22 @@ export function ApplicationsHome({
|
||||
const autoFailureText = autoFailures
|
||||
.map((failure) =>
|
||||
failure.kind === "host"
|
||||
? t("apps.autoHostFailed", {
|
||||
name: nameOf(failure.sourceId),
|
||||
reason: failure.reason
|
||||
? t("apps.failureReason", {
|
||||
reason: localizeFailureReason(failure.reason),
|
||||
})
|
||||
: "",
|
||||
})
|
||||
? t(
|
||||
failure.profiles
|
||||
? "apps.autoHostProfilesFailed"
|
||||
: "apps.autoHostFailed",
|
||||
{
|
||||
name: nameOf(failure.sourceId),
|
||||
...(failure.profiles
|
||||
? { profiles: failure.profiles.join(", ") }
|
||||
: {}),
|
||||
reason: failure.reason
|
||||
? t("apps.failureReason", {
|
||||
reason: localizeFailureReason(failure.reason),
|
||||
})
|
||||
: "",
|
||||
},
|
||||
)
|
||||
: t("apps.autoSyncFailed", {
|
||||
name: nameOf(failure.sourceId),
|
||||
reason: localizeFailureReason(failure.reason),
|
||||
@@ -1181,8 +1186,9 @@ export function ApplicationsHome({
|
||||
t,
|
||||
callState === "unavailable",
|
||||
) || sourceSyncActivity(source.source_id, syncHealth, locale, t);
|
||||
const host = hosts.find((item) =>
|
||||
sourceMatchesHost(source.source_id, item.hostId),
|
||||
const recallAllowed = sourceConnectionApproved(
|
||||
hosts,
|
||||
source.source_id,
|
||||
);
|
||||
return (
|
||||
<div className="r6-home-app-row" key={source.source_id}>
|
||||
@@ -1193,8 +1199,7 @@ export function ApplicationsHome({
|
||||
<p>
|
||||
{source.sync_enabled
|
||||
? t("apps.syncEnabled")
|
||||
: host?.installed &&
|
||||
host.permission?.state === "approved"
|
||||
: recallAllowed
|
||||
? t("apps.recallAllowed")
|
||||
: source.authorized
|
||||
? t("apps.historyAllowed")
|
||||
|
||||
@@ -118,6 +118,14 @@
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.r6-app-profiles {
|
||||
font-size: 13px;
|
||||
color: #637786;
|
||||
line-height: 1.8;
|
||||
margin: 4px 0;
|
||||
padding-left: 18px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.r6-app-detail-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/** Mirrors desktop `SOURCE_HOST`. OpenClaw and DeepSeek Harness profiles
|
||||
* are not accepted by one-click insertion. */
|
||||
/** Mirrors desktop `SOURCE_HOST`. OpenClaw is not accepted by one-click
|
||||
* insertion; DeepSeek Harness has no single host and goes through
|
||||
* `PROFILE_SOURCES` instead. */
|
||||
export const SOURCE_HOST: Readonly<Record<string, string>> = {
|
||||
cursor: "cursor",
|
||||
"claude-code": "claude-code",
|
||||
@@ -14,6 +15,23 @@ export const SOURCE_HOST: Readonly<Record<string, string>> = {
|
||||
|
||||
export const ONE_CLICK_SOURCES = new Set(Object.keys(SOURCE_HOST));
|
||||
|
||||
/** Sources configured per profile. Each profile is its own host
|
||||
* (`deepseek-harness:<profile>`, with its own patch, credential and grant), so
|
||||
* the app's one switch covers every profile the desktop detected. */
|
||||
export const PROFILE_SOURCES: ReadonlySet<string> = new Set([
|
||||
"deepseek-harness",
|
||||
]);
|
||||
|
||||
export function isProfileSource(sourceId: string) {
|
||||
return PROFILE_SOURCES.has(sourceId);
|
||||
}
|
||||
|
||||
/** `deepseek-harness:web` -> `web`. */
|
||||
export function profileName(hostId: string) {
|
||||
const colon = hostId.indexOf(":");
|
||||
return colon < 0 ? hostId : hostId.slice(colon + 1);
|
||||
}
|
||||
|
||||
export function connectionHostId(sourceId: string): string | null {
|
||||
return SOURCE_HOST[sourceId] ?? null;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { SourceResponse } from "@one-memory/contracts";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { connectionHostId, sameConnectionHost } from "./connection-hosts";
|
||||
import {
|
||||
connectionHostId,
|
||||
isProfileSource,
|
||||
sameConnectionHost,
|
||||
} from "./connection-hosts";
|
||||
import {
|
||||
readConnectionPreferences,
|
||||
writeConnectionPreference,
|
||||
@@ -8,11 +12,13 @@ import {
|
||||
import {
|
||||
cachedRecallHosts,
|
||||
enableHostConnection,
|
||||
hostConnectionApproved,
|
||||
hostConnectionUnsupported,
|
||||
hostWriteInFlight,
|
||||
hostWriteReason,
|
||||
matchHost,
|
||||
profileHosts,
|
||||
profileWriteFailures,
|
||||
sourceConnectionIncomplete,
|
||||
} from "./host-state";
|
||||
import { onClientReset, queryClient } from "./query-client";
|
||||
import { latestSource, sourceWriteInFlight } from "./source-state";
|
||||
@@ -37,6 +43,8 @@ export type AutoConnectFailure = {
|
||||
kind: "sync" | "host";
|
||||
sourceId: string;
|
||||
reason: string | null;
|
||||
/** Which profiles of a per-profile source it was; the others are kept. */
|
||||
profiles?: string[];
|
||||
};
|
||||
export type AutoConnectState = {
|
||||
running: string[];
|
||||
@@ -53,8 +61,10 @@ queryClient.setQueryDefaults(AUTO_KEY, {
|
||||
});
|
||||
|
||||
let flight: Promise<AutoConnectFailure[]> | null = null;
|
||||
const seenProfiles = new Map<string, Set<string>>();
|
||||
onClientReset(() => {
|
||||
flight = null;
|
||||
seenProfiles.clear();
|
||||
});
|
||||
|
||||
function autoState() {
|
||||
@@ -148,8 +158,26 @@ export async function reconcileConnectionPreferences(
|
||||
function hostNeedsApply(sourceId: string) {
|
||||
const hosts = cachedRecallHosts();
|
||||
if (hosts === undefined) return false;
|
||||
const host = matchHost(hosts, sourceId);
|
||||
return !hostConnectionApproved(host) && !hostConnectionUnsupported(host);
|
||||
return sourceConnectionIncomplete(hosts, sourceId);
|
||||
}
|
||||
|
||||
/** `attempted` holds one apply per source, which is right until a per-profile
|
||||
* source grows a profile: that one was never tried, so the remembered switch
|
||||
* gets one more apply. A profile that fails is not retried on every poll. */
|
||||
function rearmNewProfiles(sourceIds: string[]) {
|
||||
const hosts = cachedRecallHosts();
|
||||
if (hosts === undefined) return;
|
||||
for (const sourceId of sourceIds) {
|
||||
if (!isProfileSource(sourceId)) continue;
|
||||
const current = profileHosts(hosts, sourceId).map((host) => host.hostId);
|
||||
const seen = seenProfiles.get(sourceId);
|
||||
seenProfiles.set(sourceId, new Set([...(seen ?? []), ...current]));
|
||||
if (!seen || current.every((hostId) => seen.has(hostId))) continue;
|
||||
updateAuto((state) => ({
|
||||
...state,
|
||||
attempted: state.attempted.filter((key) => key !== hostKey(sourceId)),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a remembered host is still waiting for (or in) its one apply. */
|
||||
@@ -191,6 +219,7 @@ export function autoReconcile(
|
||||
if (hostConnectionUnsupported(matchHost(hosts, id)))
|
||||
writeConnectionPreference("host", id, false);
|
||||
const preferences = readConnectionPreferences();
|
||||
rearmNewProfiles(preferences.hostSourceIds);
|
||||
const { attempted } = autoState();
|
||||
const only = options.only;
|
||||
const wantedHosts = only
|
||||
@@ -256,6 +285,7 @@ export function retryAutoReconcile(options: ReconcileOptions) {
|
||||
|
||||
export function resetConnectionReconcile() {
|
||||
flight = null;
|
||||
seenProfiles.clear();
|
||||
queryClient.removeQueries({ queryKey: AUTO_KEY });
|
||||
}
|
||||
|
||||
@@ -301,12 +331,15 @@ async function runReconcile(
|
||||
// Per-app: other hosts keep going. Unsupported never succeeds on retry.
|
||||
if (error instanceof Error && error.message === "host_unsupported")
|
||||
writeConnectionPreference("host", sourceId, false);
|
||||
else
|
||||
else {
|
||||
const profiles = profileWriteFailures(error);
|
||||
failures.push({
|
||||
kind: "host",
|
||||
sourceId,
|
||||
reason: hostWriteReason(error),
|
||||
...(profiles ? { profiles } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/** A fake desktop bridge holding DeepSeek Harness profile hosts, for tests. */
|
||||
|
||||
import { vi } from "vitest";
|
||||
import type { RecallHostStatus, RecallPermissionStatus } from "./global";
|
||||
|
||||
type Bridge = NonNullable<typeof window.oneMemory>;
|
||||
type Grant =
|
||||
| "not-installed"
|
||||
| "install-only"
|
||||
| "approved"
|
||||
| "revoked"
|
||||
| "unsupported";
|
||||
|
||||
function permission(hostId: string, state: Grant): RecallPermissionStatus {
|
||||
return {
|
||||
hostId,
|
||||
state,
|
||||
reason: null,
|
||||
receipt:
|
||||
state === "not-installed" || state === "unsupported"
|
||||
? null
|
||||
: {
|
||||
hostId,
|
||||
installationId: `install-${hostId}`,
|
||||
revision: 1,
|
||||
status: state,
|
||||
allowedTools: state === "approved" ? ["om_recall"] : [],
|
||||
allowedScopes: state === "approved" ? ["all-apps"] : [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A desktop that knows a set of Harness profiles and keeps their state. */
|
||||
export function harnessBridge(
|
||||
initial: Record<string, Grant>,
|
||||
options: { failInstall?: string[]; failUninstall?: string[] } = {},
|
||||
) {
|
||||
const state = new Map(
|
||||
Object.entries(initial).map(([profile, grant]) => [
|
||||
`deepseek-harness:${profile}`,
|
||||
grant,
|
||||
]),
|
||||
);
|
||||
const hosts = (): RecallHostStatus[] =>
|
||||
[...state].map(([hostId, grant]) => ({
|
||||
hostId,
|
||||
label: `DeepSeek Harness · ${hostId.split(":")[1]}`,
|
||||
present: true,
|
||||
installed: grant === "install-only" || grant === "approved",
|
||||
permission: permission(hostId, grant),
|
||||
// Recorded by the desktop when the grant lands, as on a real install.
|
||||
selfCheck:
|
||||
grant === "approved"
|
||||
? { state: "wired", detail: "", probed_at: "2026-11-02" }
|
||||
: null,
|
||||
skillDrift: null,
|
||||
}));
|
||||
const failing = (hostId: string, list: string[] = []) =>
|
||||
list.some((profile) => hostId === `deepseek-harness:${profile}`);
|
||||
const api = {
|
||||
getRecallHosts: vi.fn(async () => hosts()),
|
||||
getRecallPermission: vi.fn(async (hostId: string) =>
|
||||
permission(hostId, state.get(hostId) ?? "not-installed"),
|
||||
),
|
||||
previewRecallInstall: vi.fn(async (hostId: string) => ({
|
||||
hostId,
|
||||
hostLabel: hostId,
|
||||
files: [],
|
||||
fingerprint: `fp-${hostId}`,
|
||||
})),
|
||||
installRecall: vi.fn(async (hostId: string, _approved?: string) => {
|
||||
if (failing(hostId, options.failInstall))
|
||||
throw Error(
|
||||
"Error invoking remote method 'one-memory:install-recall': Error: host_control_unavailable",
|
||||
);
|
||||
state.set(hostId, "install-only");
|
||||
return {
|
||||
hostId,
|
||||
installed: true,
|
||||
permission: permission(hostId, "install-only"),
|
||||
};
|
||||
}),
|
||||
setRecallPermission: vi.fn(async (hostId: string, _input: unknown) => {
|
||||
state.set(hostId, "approved");
|
||||
return permission(hostId, "approved");
|
||||
}),
|
||||
revokeRecallPermission: vi.fn(async (hostId: string, _input: unknown) => {
|
||||
state.set(hostId, "revoked");
|
||||
return permission(hostId, "revoked");
|
||||
}),
|
||||
previewRecallUninstall: vi.fn(async (hostId: string) => ({
|
||||
hostId,
|
||||
hostLabel: hostId,
|
||||
files: [],
|
||||
review: [],
|
||||
fingerprint: `fp-${hostId}`,
|
||||
})),
|
||||
uninstallRecall: vi.fn(async (hostId: string, _approved?: string) => {
|
||||
if (failing(hostId, options.failUninstall))
|
||||
throw Error(
|
||||
"Error invoking remote method 'one-memory:uninstall-recall': Error: host_control_unavailable",
|
||||
);
|
||||
state.set(hostId, "not-installed");
|
||||
return {
|
||||
hostId,
|
||||
installed: false,
|
||||
permission: permission(hostId, "not-installed"),
|
||||
};
|
||||
}),
|
||||
repairRecallCommands: vi.fn(async () => []),
|
||||
};
|
||||
window.oneMemory = api as unknown as Bridge;
|
||||
return {
|
||||
api,
|
||||
state,
|
||||
addProfile(profile: string) {
|
||||
state.set(`deepseek-harness:${profile}`, "not-installed");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
/**
|
||||
* DeepSeek Harness is configured per profile: every `deepseek-harness:<profile>`
|
||||
* is its own host with its own patch, credential and grant. The app page has
|
||||
* one switch for all of them (#230). These pin what that switch does: on
|
||||
* installs and grants every detected profile, off removes and revokes every
|
||||
* linked one, a failing profile is named without undoing the others, and a
|
||||
* profile that appears later is picked up by the remembered switch.
|
||||
*/
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { saveConnectionPreferences } from "./connection-preferences";
|
||||
import {
|
||||
autoReconcile,
|
||||
resetConnectionReconcile,
|
||||
} from "./connection-reconcile";
|
||||
import { harnessBridge } from "./harness-profiles.test-fixture";
|
||||
import {
|
||||
disconnectProfiles,
|
||||
enableHostConnection,
|
||||
hostWriteReason,
|
||||
ProfileWriteError,
|
||||
profileHosts,
|
||||
refreshRecallHosts,
|
||||
sourceConnectionApproved,
|
||||
sourceConnectionIncomplete,
|
||||
} from "./host-state";
|
||||
|
||||
afterEach(() => {
|
||||
window.oneMemory = undefined;
|
||||
window.localStorage.clear();
|
||||
resetConnectionReconcile();
|
||||
});
|
||||
|
||||
describe("DeepSeek Harness profile hosts", () => {
|
||||
it("lists only the profiles of the per-profile source", async () => {
|
||||
harnessBridge({ desktop: "not-installed", web: "approved" });
|
||||
const hosts = await refreshRecallHosts();
|
||||
expect(
|
||||
profileHosts(hosts, "deepseek-harness").map((host) => host.hostId),
|
||||
).toEqual(["deepseek-harness:desktop", "deepseek-harness:web"]);
|
||||
expect(profileHosts(hosts, "cursor")).toEqual([]);
|
||||
// One approved profile reads as on; the other is still to do.
|
||||
expect(sourceConnectionApproved(hosts, "deepseek-harness")).toBe(true);
|
||||
expect(sourceConnectionIncomplete(hosts, "deepseek-harness")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("turning the DeepSeek Harness switch on", () => {
|
||||
it("installs and grants every profile that is not approved yet", async () => {
|
||||
const { api, state } = harnessBridge({
|
||||
desktop: "not-installed",
|
||||
headless: "revoked",
|
||||
web: "approved",
|
||||
});
|
||||
await refreshRecallHosts();
|
||||
await enableHostConnection("deepseek-harness");
|
||||
expect(api.installRecall.mock.calls.map(([hostId]) => hostId)).toEqual([
|
||||
"deepseek-harness:desktop",
|
||||
"deepseek-harness:headless",
|
||||
]);
|
||||
expect(api.setRecallPermission).toHaveBeenCalledWith(
|
||||
"deepseek-harness:desktop",
|
||||
expect.objectContaining({
|
||||
allowedTools: ["om_recall", "om_conversations", "om_diagnostic_trace"],
|
||||
allowedScopes: ["all-apps", "source:deepseek-harness"],
|
||||
userConfirmed: true,
|
||||
}),
|
||||
);
|
||||
expect([...state.values()]).toEqual(["approved", "approved", "approved"]);
|
||||
});
|
||||
|
||||
it("keeps the profiles that worked and names the one that failed", async () => {
|
||||
const { api, state } = harnessBridge(
|
||||
{ desktop: "not-installed", web: "not-installed" },
|
||||
{ failInstall: ["web"] },
|
||||
);
|
||||
await refreshRecallHosts();
|
||||
const error = await enableHostConnection("deepseek-harness").catch(
|
||||
(reason: unknown) => reason,
|
||||
);
|
||||
expect(error).toBeInstanceOf(ProfileWriteError);
|
||||
expect((error as ProfileWriteError).profiles).toEqual(["web"]);
|
||||
expect((error as Error).message).toContain("host_control_unavailable");
|
||||
expect(state.get("deepseek-harness:desktop")).toBe("approved");
|
||||
expect(state.get("deepseek-harness:web")).toBe("not-installed");
|
||||
expect(api.setRecallPermission).toHaveBeenCalledTimes(1);
|
||||
// The failure re-read lands the real state of every profile.
|
||||
const hosts = await refreshRecallHosts();
|
||||
expect(sourceConnectionApproved(hosts, "deepseek-harness")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("turning the DeepSeek Harness switch off", () => {
|
||||
it("removes and revokes every linked profile and leaves unlinked ones alone", async () => {
|
||||
const { api, state } = harnessBridge({
|
||||
desktop: "approved",
|
||||
headless: "not-installed",
|
||||
web: "approved",
|
||||
});
|
||||
await refreshRecallHosts();
|
||||
const results = await disconnectProfiles("deepseek-harness");
|
||||
expect(results.map((item) => [item.hostId, item.outcome.state])).toEqual([
|
||||
["deepseek-harness:desktop", "removed"],
|
||||
["deepseek-harness:web", "removed"],
|
||||
]);
|
||||
expect(api.uninstallRecall).toHaveBeenCalledTimes(2);
|
||||
expect(state.get("deepseek-harness:desktop")).toBe("not-installed");
|
||||
expect(state.get("deepseek-harness:web")).toBe("not-installed");
|
||||
});
|
||||
|
||||
it("revokes a profile whose files cannot be removed and still reaches the rest", async () => {
|
||||
const { api, state } = harnessBridge(
|
||||
{ desktop: "approved", web: "approved" },
|
||||
{ failUninstall: ["desktop"] },
|
||||
);
|
||||
await refreshRecallHosts();
|
||||
const results = await disconnectProfiles("deepseek-harness");
|
||||
expect(results.map((item) => item.outcome.state)).toEqual([
|
||||
"revoked",
|
||||
"removed",
|
||||
]);
|
||||
expect(api.revokeRecallPermission).toHaveBeenCalledWith(
|
||||
"deepseek-harness:desktop",
|
||||
expect.objectContaining({ userConfirmed: true }),
|
||||
);
|
||||
expect(state.get("deepseek-harness:desktop")).toBe("revoked");
|
||||
expect(state.get("deepseek-harness:web")).toBe("not-installed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("a profile created after the switch was turned on", () => {
|
||||
it("is installed and granted by the remembered switch while the app is running", async () => {
|
||||
saveConnectionPreferences({
|
||||
syncSourceIds: [],
|
||||
hostSourceIds: ["deepseek-harness"],
|
||||
});
|
||||
const harness = harnessBridge({ desktop: "not-installed" });
|
||||
await refreshRecallHosts();
|
||||
expect(await autoReconcile({ sources: [] })).toEqual([]);
|
||||
expect(harness.api.installRecall).toHaveBeenCalledTimes(1);
|
||||
|
||||
// One attempt was already spent on this source; the new profile gets its own.
|
||||
harness.addProfile("web");
|
||||
await refreshRecallHosts();
|
||||
expect(await autoReconcile({ sources: [] })).toEqual([]);
|
||||
expect(harness.api.installRecall.mock.calls.at(-1)).toEqual([
|
||||
"deepseek-harness:web",
|
||||
"fp-deepseek-harness:web",
|
||||
]);
|
||||
expect(harness.state.get("deepseek-harness:web")).toBe("approved");
|
||||
});
|
||||
|
||||
it("does not retry a failing profile on every poll", async () => {
|
||||
saveConnectionPreferences({
|
||||
syncSourceIds: [],
|
||||
hostSourceIds: ["deepseek-harness"],
|
||||
});
|
||||
const harness = harnessBridge(
|
||||
{ desktop: "approved", web: "not-installed" },
|
||||
{ failInstall: ["web"] },
|
||||
);
|
||||
await refreshRecallHosts();
|
||||
expect(await autoReconcile({ sources: [] })).toEqual([
|
||||
{
|
||||
kind: "host",
|
||||
sourceId: "deepseek-harness",
|
||||
reason: "应用控制通道暂不可用",
|
||||
profiles: ["web"],
|
||||
},
|
||||
]);
|
||||
await refreshRecallHosts();
|
||||
expect(await autoReconcile({ sources: [] })).toBeNull();
|
||||
expect(harness.api.installRecall).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stays out while the switch is off", async () => {
|
||||
const harness = harnessBridge({ desktop: "not-installed" });
|
||||
await refreshRecallHosts();
|
||||
expect(await autoReconcile({ sources: [] })).toBeNull();
|
||||
harness.addProfile("web");
|
||||
await refreshRecallHosts();
|
||||
expect(await autoReconcile({ sources: [] })).toBeNull();
|
||||
expect(harness.api.installRecall).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("a profile whose name MemHub cannot grant", () => {
|
||||
it("is named with the real reason and does not hold up the others", async () => {
|
||||
const { state } = harnessBridge({
|
||||
My_Profile: "unsupported",
|
||||
web: "not-installed",
|
||||
});
|
||||
await refreshRecallHosts();
|
||||
const error = await enableHostConnection("deepseek-harness").catch(
|
||||
(reason: unknown) => reason,
|
||||
);
|
||||
expect((error as ProfileWriteError).profiles).toEqual(["My_Profile"]);
|
||||
expect(hostWriteReason(error)).toBe("appProfileNameUnsupported");
|
||||
expect(state.get("deepseek-harness:web")).toBe("approved");
|
||||
// Nothing is left for the remembered switch to keep trying.
|
||||
expect(
|
||||
sourceConnectionIncomplete(
|
||||
await refreshRecallHosts(),
|
||||
"deepseek-harness",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,10 @@
|
||||
import { MutationObserver, useQuery } from "@tanstack/react-query";
|
||||
import { connectionHostId, hostMatchesSource } from "./connection-hosts";
|
||||
import {
|
||||
connectionHostId,
|
||||
hostMatchesSource,
|
||||
isProfileSource,
|
||||
profileName,
|
||||
} from "./connection-hosts";
|
||||
import type {
|
||||
RecallHostStatus,
|
||||
RecallPermissionStatus,
|
||||
@@ -226,6 +231,7 @@ export function matchHost(
|
||||
|
||||
const REASONS: Record<string, string> = {
|
||||
host_unsupported: "它没有 MCP 通道,无法发放可撤销的记忆凭证",
|
||||
profile_name_unsupported: "appProfileNameUnsupported",
|
||||
unsupported_host: "当前安装不支持一键插入",
|
||||
connection_client_unavailable: "桌面端的连接组件不可用",
|
||||
noncanonical_data_dir_host_integration_disabled: "测试实例不接入应用",
|
||||
@@ -350,18 +356,77 @@ export function hostWriteInFlight() {
|
||||
return queryClient.isMutating({ mutationKey: HOST_WRITE }) > 0;
|
||||
}
|
||||
|
||||
/** A per-profile source writes to every profile, so it waits on each of them. */
|
||||
function sourceHost(sourceId: string) {
|
||||
if (isProfileSource(sourceId))
|
||||
return [
|
||||
sourceId,
|
||||
...profileHosts(cachedRecallHosts(), sourceId).map((host) => host.hostId),
|
||||
];
|
||||
return [connectionHostId(sourceId) ?? sourceId];
|
||||
}
|
||||
|
||||
/** Every detected profile host of a per-profile source, e.g. DeepSeek Harness. */
|
||||
export function profileHosts(
|
||||
hosts: readonly RecallHostStatus[] | undefined,
|
||||
sourceId: string,
|
||||
) {
|
||||
if (!isProfileSource(sourceId)) return [];
|
||||
return (hosts ?? []).filter((host) => host.hostId.startsWith(`${sourceId}:`));
|
||||
}
|
||||
|
||||
/** The app switch reads as on: its host, or for a per-profile source any
|
||||
* profile, may use memory. A failed profile is reported, not hidden. */
|
||||
export function sourceConnectionApproved(
|
||||
hosts: readonly RecallHostStatus[] | undefined,
|
||||
sourceId: string,
|
||||
) {
|
||||
if (isProfileSource(sourceId))
|
||||
return profileHosts(hosts, sourceId).some(hostConnectionApproved);
|
||||
return hostConnectionApproved(matchHost(hosts, sourceId));
|
||||
}
|
||||
|
||||
/** Something the switch would still do: a host, or any profile, that is
|
||||
* neither approved nor unsupported. */
|
||||
export function sourceConnectionIncomplete(
|
||||
hosts: readonly RecallHostStatus[] | undefined,
|
||||
sourceId: string,
|
||||
) {
|
||||
const pending = (host: RecallHostStatus | null) =>
|
||||
!hostConnectionApproved(host) && !hostConnectionUnsupported(host);
|
||||
if (isProfileSource(sourceId))
|
||||
return profileHosts(hosts, sourceId).some(pending);
|
||||
return pending(matchHost(hosts, sourceId));
|
||||
}
|
||||
|
||||
/** Some profiles of a per-profile source could not be written; the others
|
||||
* were kept. The message keeps the first cause so `hostWriteReason` names it. */
|
||||
export class ProfileWriteError extends Error {
|
||||
readonly profiles: string[];
|
||||
constructor(profiles: string[], cause: unknown) {
|
||||
super(
|
||||
`profile_write_failed ${cause instanceof Error ? cause.message : ""}`.trim(),
|
||||
);
|
||||
this.profiles = profiles;
|
||||
}
|
||||
}
|
||||
|
||||
/** The profile names a failed write left behind, if it was a profile write. */
|
||||
export function profileWriteFailures(error: unknown): string[] | null {
|
||||
return error instanceof ProfileWriteError ? error.profiles : null;
|
||||
}
|
||||
|
||||
type Connected = {
|
||||
hostId: string;
|
||||
installed: boolean;
|
||||
permission?: RecallPermissionStatus;
|
||||
};
|
||||
|
||||
async function connect(sourceId: string): Promise<Connected | null> {
|
||||
const hostId = connectionHostId(sourceId);
|
||||
type Bridge = NonNullable<ReturnType<typeof bridge>>;
|
||||
|
||||
async function connect(sourceId: string): Promise<Connected[]> {
|
||||
const profiles = isProfileSource(sourceId);
|
||||
const hostId = profiles ? sourceId : connectionHostId(sourceId);
|
||||
const api = bridge();
|
||||
if (
|
||||
!hostId ||
|
||||
@@ -371,12 +436,65 @@ async function connect(sourceId: string): Promise<Connected | null> {
|
||||
!api.setRecallPermission
|
||||
)
|
||||
throw Error("unsupported_host");
|
||||
const existing = matchHost(await refreshRecallHosts(), sourceId);
|
||||
if (hostConnectionUnsupported(existing)) throw Error("host_unsupported");
|
||||
if (hostConnectionApproved(existing)) {
|
||||
await api.repairRecallCommands?.();
|
||||
return null;
|
||||
const hosts = await refreshRecallHosts();
|
||||
if (profiles) return connectProfiles(api, sourceId, hosts);
|
||||
const result = await grantHost(
|
||||
api,
|
||||
hostId,
|
||||
sourceId,
|
||||
matchHost(hosts, sourceId),
|
||||
);
|
||||
await api.repairRecallCommands?.();
|
||||
return result ? [result] : [];
|
||||
}
|
||||
|
||||
/** One switch, every detected profile. A profile that fails does not undo
|
||||
* the ones that worked; the error names it. Profiles already approved are
|
||||
* left alone, so turning the switch on again only reaches what is missing. */
|
||||
async function connectProfiles(
|
||||
api: Bridge,
|
||||
sourceId: string,
|
||||
hosts: RecallHostStatus[],
|
||||
): Promise<Connected[]> {
|
||||
const profiles = profileHosts(hosts, sourceId);
|
||||
if (!profiles.length) throw Error("profiles_not_found");
|
||||
const connected: Connected[] = [];
|
||||
const failed: string[] = [];
|
||||
let cause: unknown;
|
||||
for (const host of profiles) {
|
||||
try {
|
||||
const result = await grantHost(api, host.hostId, sourceId, host);
|
||||
if (result) connected.push(result);
|
||||
} catch (error) {
|
||||
failed.push(profileName(host.hostId));
|
||||
// Harness speaks MCP, so "unsupported" can only mean the id grammar
|
||||
// refused this name; "no MCP channel" would send the person astray.
|
||||
cause ??= hostConnectionUnsupported(host)
|
||||
? Error("profile_name_unsupported")
|
||||
: error;
|
||||
}
|
||||
}
|
||||
if (failed.length < profiles.length) await api.repairRecallCommands?.();
|
||||
if (failed.length) throw new ProfileWriteError(failed, cause);
|
||||
return connected;
|
||||
}
|
||||
|
||||
/** Installs and grants one host; null when it was already approved. */
|
||||
async function grantHost(
|
||||
api: Bridge,
|
||||
hostId: string,
|
||||
sourceId: string,
|
||||
existing: RecallHostStatus | null,
|
||||
): Promise<Connected | null> {
|
||||
if (
|
||||
!api.previewRecallInstall ||
|
||||
!api.installRecall ||
|
||||
!api.getRecallPermission ||
|
||||
!api.setRecallPermission
|
||||
)
|
||||
throw Error("unsupported_host");
|
||||
if (hostConnectionUnsupported(existing)) throw Error("host_unsupported");
|
||||
if (hostConnectionApproved(existing)) return null;
|
||||
const preview = await api.previewRecallInstall(hostId);
|
||||
const installed = await api.installRecall(hostId, preview.fingerprint);
|
||||
let permission =
|
||||
@@ -394,19 +512,19 @@ async function connect(sourceId: string): Promise<Connected | null> {
|
||||
}
|
||||
if (permission.receipt?.status !== "approved")
|
||||
throw Error("permission_not_approved");
|
||||
await api.repairRecallCommands?.();
|
||||
return { hostId, installed: true, permission };
|
||||
}
|
||||
|
||||
function landConnected(result: Connected | null) {
|
||||
if (result)
|
||||
function landConnected(results: Connected[]) {
|
||||
for (const result of results)
|
||||
landHost(result.hostId, {
|
||||
installed: result.installed,
|
||||
permission: result.permission,
|
||||
});
|
||||
}
|
||||
|
||||
/** Installs and grants one host; resolves only once the grant is approved. */
|
||||
/** Installs and grants one host (or every profile of a per-profile source);
|
||||
* resolves only once the grants are approved. */
|
||||
export const enableHostConnection = hostWrite(
|
||||
sourceHost,
|
||||
connect,
|
||||
@@ -479,6 +597,22 @@ async function disconnect(hostId: string): Promise<Disconnected> {
|
||||
}
|
||||
}
|
||||
|
||||
function landDisconnected({
|
||||
hostId,
|
||||
outcome,
|
||||
}: {
|
||||
hostId: string;
|
||||
outcome: DisconnectOutcome;
|
||||
}) {
|
||||
if (outcome.state === "removed")
|
||||
landHost(hostId, {
|
||||
installed: false,
|
||||
...(outcome.permission ? { permission: outcome.permission } : {}),
|
||||
});
|
||||
else if (outcome.state !== "failed" && outcome.permission)
|
||||
landHost(hostId, { permission: outcome.permission });
|
||||
}
|
||||
|
||||
export const disconnectHost = hostWrite(
|
||||
(hostId: string) => [hostId],
|
||||
async (
|
||||
@@ -489,14 +623,48 @@ export const disconnectHost = hostWrite(
|
||||
const rereadFailed = !(await rereadOnce());
|
||||
return { hostId, outcome: { ...result, rereadFailed } };
|
||||
},
|
||||
({ hostId, outcome }) => {
|
||||
if (outcome.state === "removed")
|
||||
landHost(hostId, {
|
||||
installed: false,
|
||||
...(outcome.permission ? { permission: outcome.permission } : {}),
|
||||
landDisconnected,
|
||||
);
|
||||
|
||||
export type ProfileDisconnect = { hostId: string; outcome: DisconnectOutcome };
|
||||
|
||||
/** Linked to MemHub at all: installed, or holding a receipt that is not yet
|
||||
* revoked. A profile that never was has nothing to remove. */
|
||||
function profileLinked(host: RecallHostStatus) {
|
||||
const status = host.permission?.receipt?.status;
|
||||
return host.installed || (status !== undefined && status !== "revoked");
|
||||
}
|
||||
|
||||
/** Turn a per-profile source off: each linked profile is removed and its grant
|
||||
* revoked, exactly as one host would be. One failure does not stop the rest;
|
||||
* every outcome is returned so the page can name the profile it concerns. */
|
||||
export const disconnectProfiles = hostWrite(
|
||||
sourceHost,
|
||||
async (sourceId: string): Promise<ProfileDisconnect[]> => {
|
||||
const profiles = profileHosts(await refreshRecallHosts(), sourceId).filter(
|
||||
profileLinked,
|
||||
);
|
||||
const results: ProfileDisconnect[] = [];
|
||||
let anyFailed = false;
|
||||
for (const host of profiles) {
|
||||
const outcome = await disconnect(host.hostId);
|
||||
anyFailed ||= outcome.state === "failed";
|
||||
results.push({
|
||||
hostId: host.hostId,
|
||||
outcome:
|
||||
outcome.state === "failed"
|
||||
? { ...outcome, rereadFailed: false }
|
||||
: outcome,
|
||||
});
|
||||
else if (outcome.state !== "failed" && outcome.permission)
|
||||
landHost(hostId, { permission: outcome.permission });
|
||||
}
|
||||
if (anyFailed && !(await rereadOnce()))
|
||||
for (const result of results)
|
||||
if (result.outcome.state === "failed")
|
||||
result.outcome = { ...result.outcome, rereadFailed: true };
|
||||
return results;
|
||||
},
|
||||
(results) => {
|
||||
for (const result of results) landDisconnected(result);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -91,7 +91,14 @@ describe("single state layer", () => {
|
||||
});
|
||||
|
||||
it("reads and writes host connections only through host-state", () => {
|
||||
expect(offenders(hostUses, ["host-state.ts", "global.d.ts"])).toEqual([]);
|
||||
expect(
|
||||
offenders(hostUses, [
|
||||
"host-state.ts",
|
||||
"global.d.ts",
|
||||
// Test support: it is the fake bridge, and only tests import it.
|
||||
"harness-profiles.test-fixture.ts",
|
||||
]),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("reads and writes sources only through source-state", () => {
|
||||
|
||||
@@ -189,14 +189,14 @@ node apps/cli/dist/one-memory.cjs settings features reset
|
||||
```bash
|
||||
node apps/cli/dist/one-memory.cjs settings language # 界面语言和 SDK 提示语言
|
||||
node apps/cli/dist/one-memory.cjs settings language ja # 设为日语,立即生效
|
||||
node apps/cli/dist/one-memory.cjs settings language system # 跟随系统(不指定 SDK 语言)
|
||||
node apps/cli/dist/one-memory.cjs settings language system # 清除设置(不指定 SDK 语言)
|
||||
```
|
||||
|
||||
- 可选 11 种:`en`、`zh-Hans`、`zh-Hant`、`ja`、`es`、`de`、`pt`、`fr`、`ko`、`ru`、`id`,以及 `system`;旧代码 `zh-CN` 按 `zh-Hans` 处理。
|
||||
- App 切换语言时会自动设置(Desktop 启动时也会同步一次已保存的选择)。全局设置,存于 `config.json` 的 `ui_language`;从未选择时不写入。
|
||||
- `zh-Hans` 和 `system` 不向 SDK 传语言,SDK 照旧自动识别中文或英文;其余语言(包括 `en`)作为 `MemoryConfig.language` 传给 SDK,提取等提示使用该语言。
|
||||
- App 切换语言时会自动设置;Desktop 每次启动也会同步一次界面实际显示的语言(App 选“跟随系统”时,发送它按系统语言解析出的语言,例如 `zh-Hans`)。全局设置,存于 `config.json` 的 `ui_language`;从未设置时不写入。
|
||||
- 所有语言(包括 `zh-Hans` 和 `en`)都作为 `MemoryConfig.language` 传给 SDK,提取等提示使用该语言;只有未设置(`system`,或只用 CLI/API、从未打开 App 的安装)时不向 SDK 传语言,SDK 照旧自动识别中文或英文。
|
||||
- 修改会像功能开关一样重建 SDK 客户端;不迁移数据,不改集合名(需要 hy-memory 2.0.11 的 `MemoryConfig.language`)。
|
||||
- `status --json` 的 `pipeline.ui_language` / `pipeline.sdk_language`(`auto` 或语言代码)。API:`GET`/`PUT /api/v1/settings/ui-language`。
|
||||
- `status --json` 的 `pipeline.ui_language` / `pipeline.sdk_language`(`auto` 或语言代码;`zh-Hans` 用户显示 `zh-Hans`)。API:`GET`/`PUT /api/v1/settings/ui-language`。
|
||||
|
||||
## 8. 召回(recall)
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ Preview 不会弹出给用户;开关点击本身被视为确认。关闭时通
|
||||
| [Qwen Code](qwen-code.md) | 开放 | MCP + Skill | 无自动 Hook | `$QWEN_HOME/projects` 扫描 |
|
||||
| [Pi](pi.md) | 开放 | CLI Skill,不使用 MCP | JS Capture Extension | Pi session 扫描 + Extension 实时入口 |
|
||||
| [OpenClaw](openclaw.md) | 正式产品冻结 | 当前没有;仅有未开放的底层 MCP 写入器 | 没有 Hook、Plugin 或 Prefetch | Adapter 也被冻结,开关不可用 |
|
||||
| [DeepSeek Harness](deepseek-harness.md) | 详情页排除,来源管理页按 Profile 接入 | Profile 级 MCP Patch | 无自动 Hook | `$DSH_HOME/sessions` 扫描 |
|
||||
| [DeepSeek Harness](deepseek-harness.md) | 开放;一个开关覆盖全部已检测 Profile | Profile 级 MCP Patch | 无自动 Hook | `$DSH_HOME/sessions` 扫描 |
|
||||
|
||||
## 同步开关的统一精确语义
|
||||
|
||||
|
||||
@@ -1,28 +1,45 @@
|
||||
# DeepSeek Harness 一键插入支持
|
||||
|
||||
更新日期:2026-10-18
|
||||
更新日期:2026-11-02
|
||||
|
||||
## 结论
|
||||
|
||||
DeepSeek Harness 的 Profile 级 MCP 安装器已经实现,Profile Scoped Host ID(`deepseek-harness:<profile>`)在权限层按不透明标签处理,可正常走完 Preview 与安装。
|
||||
DeepSeek Harness 按 Profile 配置 MCP:每个 Profile 是一个独立 Host(`deepseek-harness:<profile>`),有自己的 `cordis.patch.yml`、Credential 与 Grant。应用详情页只有一个“一键插入应用”开关,它一次覆盖桌面检测到的全部 Profile:打开时逐个安装并授权,关闭时逐个移除并撤销。
|
||||
|
||||
## 接入方式和产品状态
|
||||
|
||||
| 项目 | DeepSeek Harness 当前实现 |
|
||||
|---|---|
|
||||
| 应用详情页一键插入 | 有意排除,因为无法选择 Profile |
|
||||
| 来源管理页 Profile 安装 | 可用;每个 Profile 独立 Patch、Credential 与 Grant |
|
||||
| 应用详情页一键插入 | 可用;一个开关覆盖全部已检测 Profile,并列出每个 Profile 的状态 |
|
||||
| 首次导入批量连接 | 排除;在应用详情页打开开关 |
|
||||
| Harness 查询 MemHub | 通过 Profile 级 Cordis MCP Client |
|
||||
| Skill | 没有 |
|
||||
| Prompt 前自动 Prefetch | 没有 |
|
||||
| Capture Hook/Plugin | 没有 |
|
||||
| Harness 新会话进入 MemHub | Core 扫描 `$DSH_HOME/sessions` |
|
||||
| Harness 新会话进入 MemHub | Core 扫描 `$DSH_HOME/sessions`,按 `session[.vN].jsonl[.zstd]` 识别会话文件 |
|
||||
|
||||
会话文件按写入时的格式版本命名:首版为 `session.jsonl` / `session.jsonl.zstd`,v3/v4 起为 `session.v3.jsonl.zstd` / `session.v4.jsonl.zstd`。来源扫描接受带版本号的名称;解析前再读文件头 `version` 字段,只导入已验证的 v0/v3/v4,未来未知版本不会被解析:整个文件以 `unsupported_schema` 报告,且不留下读取进度,将来支持该版本的发布会从头读取(错误导入比暂时漏导更难回滚)。`tool/result` 的输出无论写成 `tool-result` 块还是纯 `text` 块,都按同一条裁剪与凭据清洗路径导入。
|
||||
|
||||
## 两个开关分别做什么
|
||||
|
||||
### “一键插入应用”
|
||||
### 打开“一键插入应用”
|
||||
|
||||
应用详情页不可用。来源管理页对每个 Profile 写 `cordis.patch.yml`、创建独立 Credential 并授权;Host ID 形如 `deepseek-harness:<profile>`,冒号只作为标签存在,权限层的安装目录按 Host ID 摘要生成,不参与路径拼接。
|
||||
应用详情页对每个已检测、尚未获批的 Profile:
|
||||
|
||||
1. 预览并写入该 Profile 的 `cordis.patch.yml` 受管块,创建独立 Credential;
|
||||
2. 授予 `om_recall`、`om_conversations`、`om_diagnostic_trace`,范围为 `all-apps` 与 `source:deepseek-harness`(与其他应用的一键插入相同)。
|
||||
|
||||
已获批的 Profile 不会重装。某个 Profile 失败时,其他 Profile 的结果保留,页面提示失败的 Profile 名称;开关只要有一个 Profile 获批就显示为开。Host ID 里的冒号只作为标签存在,权限层的安装目录按 Host ID 摘要生成,不参与路径拼接。
|
||||
|
||||
### 关闭“一键插入应用”
|
||||
|
||||
对每个已接入的 Profile 先撤销 Credential,再删除受管块(与其他应用的关闭语义相同)。受管块被改过、无法删除时仍会撤销授权,页面列出需要核对的 Profile;撤销也失败的 Profile 会单独列出,它仍可使用记忆。从未接入的 Profile 不受影响。
|
||||
|
||||
### 之后新建的 Profile
|
||||
|
||||
桌面每次刷新应用接入状态时都会重新枚举 Profile(`$DSH_HOME/profiles/<profile>/cordis.yml`),应用首页打开时每 3 秒刷新一次;常驻的 Runtime 收到未知的 Profile Host ID 时也会重新读盘。开关的选择会被记住:开关为开时,新出现的 Profile 由应用首页自动安装并授权,不需要重启 MemHub。
|
||||
|
||||
每个新 Profile 触发一次自动尝试;失败时应用首页会指明 Profile,不会每次轮询都重试,下次启动或点击重试时再试一次。开关为关时不会自动接入任何 Profile。
|
||||
|
||||
### 打开“同步开关”
|
||||
|
||||
@@ -32,12 +49,10 @@ DeepSeek Harness 的 Profile 级 MCP 安装器已经实现,Profile Scoped Host
|
||||
|
||||
Core 停止扫描和 pending Job claim,running Job可结束,已有 Memory 保留。它不会修改任何 Profile 的 `cordis.patch.yml` 或 Credential。
|
||||
|
||||
### 修复一键安装后的组合语义
|
||||
### 组合语义
|
||||
|
||||
未来修复 Profile Host ID 后:
|
||||
|
||||
- 某个 Profile 的一键插入只决定该 Profile 是否能查询 MemHub;
|
||||
- 全局同步开关决定 MemHub 是否继续读取整个 DeepSeek Harness 的 Session;
|
||||
- 一键插入决定已检测 Profile 是否能查询 MemHub;
|
||||
- 同步开关决定 MemHub 是否继续读取整个 DeepSeek Harness 的 Session;
|
||||
- 没有自动 Prefetch,也没有 Capture Hook。
|
||||
|
||||
## Profile 粒度
|
||||
@@ -58,7 +73,7 @@ deepseek-harness:headless
|
||||
...
|
||||
```
|
||||
|
||||
理论上每个 Profile 拥有独立 Patch、Journal、Credential 和 Grant;Core 会话同步仍按统一的 `deepseek-harness` 来源扫描 `$DSH_HOME/sessions`。
|
||||
每个 Profile 拥有独立 Patch、Journal、Credential 和 Grant;Core 会话同步仍按统一的 `deepseek-harness` 来源扫描 `$DSH_HOME/sessions`。
|
||||
|
||||
## MCP Patch
|
||||
|
||||
@@ -85,13 +100,15 @@ DeepSeek Harness 不安装 Skill,也不安装 Capture Hook;新会话进入 M
|
||||
|
||||
## UI 状态
|
||||
|
||||
- 应用详情页排除 DeepSeek Harness,因为单一来源页无法选择 Profile。
|
||||
- 首次导入批量连接也排除它。
|
||||
- 来源管理页会列出每个 Profile,并显示独立安装按钮。
|
||||
- 应用详情页的“一键插入应用”下方列出每个已检测 Profile 及其“已接入 / 未接入”状态;没有检测到 Profile 时开关不可用,并提示创建 Profile 后回到此页。
|
||||
- Host ID 只接受小写字母、数字和连字符(最长 32 个字符)。名称不符合的 Profile 仍会列出,但无法授权,页面会指明它和原因,不影响其他 Profile。
|
||||
- 连接状态取各已接入 Profile 记录的自检结果:全部接通才显示“已接通”。
|
||||
- 首次导入批量连接排除 DeepSeek Harness。
|
||||
- CLI 的 `memhub host install deepseek-harness:<profile>` 只安装,不授权(状态停在 `install-only`);授权入口只有应用详情页的开关,CLI 没有授权命令。
|
||||
|
||||
## 已修复:Profile Host ID 校验
|
||||
|
||||
此前来源管理页安装会在写入 `cordis.patch.yml` 和创建 Credential 之前失败,原因是:
|
||||
此前 Profile 安装会在写入 `cordis.patch.yml` 和创建 Credential 之前失败,原因是:
|
||||
|
||||
```text
|
||||
系统生成 hostId = deepseek-harness:<profile>
|
||||
@@ -101,18 +118,12 @@ HostGrantStore 也不接受冒号
|
||||
|
||||
Host ID 是不可解释的标签:安装目录对它取摘要,不会把它拼进路径。现在权限层与 Grant 存储都接受一个可选的 `:<profile>` 段,因此 Profile 安装可以正常走完。这不是 DeepSeek Harness 不支持 MCP 的问题,而是 Profile Host ID 格式与权限校验不一致,现已对齐。
|
||||
|
||||
## 修复后的权限语义风险
|
||||
## 已修复:应用详情页返回 `unsupported_host`
|
||||
|
||||
来源管理页当前默认授权选择可能包含:
|
||||
|
||||
- `om_recall`、`om_conversations`、`om_diagnostic_trace`(`om_ask` 已随 `MemHub_ask` 移除,旧授权仍可读取但不再授权任何工具);
|
||||
- `all-apps`;
|
||||
- 所有已授权 Source 和 Workspace。
|
||||
|
||||
这比应用详情页通用授权更宽。Host ID 修复后仍应确认是否希望每个 Profile 默认获得如此宽的权限。
|
||||
此前应用详情页按“一个来源对应一个 Host”接入,而 DeepSeek Harness 没有不带 Profile 的 Host,开关因此置灰并返回 `unsupported_host`,安装后的 Profile 也只能停在 `install-only`(#230)。现在开关直接作用于全部 `deepseek-harness:<profile>` Host,复用与其他应用相同的安装、授权、撤销与卸载接口。
|
||||
|
||||
## 重复安装与卸载
|
||||
|
||||
底层 Patch 安装是幂等的:已有受管块时替换,不追加第二份。相同 Row ID 出现在 MemHub 哨兵块外时默认拒绝接管。
|
||||
|
||||
正常卸载设计是先撤销该 Profile Credential,再删除受管块并保留其他 Patch;如果删完没有其他 Row,恢复 `[]`。用户修改过受管块时不强删。
|
||||
卸载先撤销该 Profile Credential,再删除受管块并保留其他 Patch;如果删完没有其他 Row,恢复 `[]`。用户修改过受管块时不强删。
|
||||
@@ -926,6 +926,23 @@ const baseEnglishMessages = {
|
||||
"Memory access was revoked, so {name} can no longer look up memories. Full removal could not be confirmed; review these paths manually: {paths}.",
|
||||
appRemovalReview:
|
||||
"Full connection removal could not be confirmed. Review these paths manually: {paths}.",
|
||||
appProfilesLabel: "{name} profiles",
|
||||
appProfileOn: "{profile}: connected",
|
||||
appProfileOff: "{profile}: not connected",
|
||||
appProfilesHint:
|
||||
"The switch installs the memory connection and grants access for every detected profile, and revokes them all when turned off. While it is on, new profiles are connected automatically.",
|
||||
appProfilesNone:
|
||||
"No {name} profile was detected. Create a profile, then come back to this page.",
|
||||
appProfilesConnectFailed:
|
||||
"These profiles could not be connected: {profiles}. The other profiles were kept. {reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"These profiles could not be disconnected and can still use memories: {profiles}. Please retry. {reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"Memory access was revoked for these profiles, but not all of their connection files were removed; review them: {profiles}.",
|
||||
appProfileNameUnsupported:
|
||||
"profile names may only use lowercase letters, digits and hyphens, up to 32 characters",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"{name} could not connect these profiles automatically ({profiles}){reason}.",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"Cursor's connection credential changed. Fully quit and reopen Cursor before starting a new conversation.",
|
||||
连接其他工具: "Connect other tools",
|
||||
|
||||
@@ -298,6 +298,23 @@ export const settingsSpanishMessages = {
|
||||
"Se revocó el permiso; {name} ya no puede consultar memorias. No se pudo confirmar la eliminación completa de la conexión. Comprueba manualmente: {paths}.",
|
||||
appRemovalReview:
|
||||
"No se pudo confirmar la eliminación completa de la conexión. Comprueba manualmente: {paths}.",
|
||||
appProfilesLabel: "Perfiles de {name}",
|
||||
appProfileOn: "{profile}: conectado",
|
||||
appProfileOff: "{profile}: sin conectar",
|
||||
appProfilesHint:
|
||||
"El interruptor instala la conexión de memorias y concede acceso a cada perfil detectado, y los revoca todos al apagarlo. Mientras esté activado, los perfiles nuevos se conectan automáticamente.",
|
||||
appProfilesNone:
|
||||
"No se detectó ningún perfil de {name}. Crea un perfil y vuelve a esta página.",
|
||||
appProfilesConnectFailed:
|
||||
"No se pudieron conectar estos perfiles: {profiles}. Los demás perfiles se mantienen.{reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"No se pudieron desconectar estos perfiles y aún pueden usar memorias: {profiles}. Reintenta.{reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"Se revocó el acceso a memorias de estos perfiles, pero no se eliminaron todos sus archivos de conexión; revísalos: {profiles}.",
|
||||
appProfileNameUnsupported:
|
||||
"los nombres de perfil solo admiten minúsculas, dígitos y guiones, hasta 32 caracteres",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"No se pudieron conectar automáticamente estos perfiles de {name} ({profiles}){reason}. ",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"Las credenciales de conexión de Cursor se actualizaron. Cierra completamente Cursor y vuelve a abrirlo; después, inicia una conversación nueva.",
|
||||
连接其他工具: "Conectar otras herramientas",
|
||||
@@ -350,6 +367,23 @@ const chineseOverrides: Partial<
|
||||
appRevokedReview:
|
||||
"已撤销记忆权限,{name} 已查不到记忆。但无法确认连接已全部移除,需要你手动核对:{paths}。",
|
||||
appRemovalReview: "无法确认连接已全部移除,需要你手动核对:{paths}。",
|
||||
appProfilesLabel: "{name} 的 Profile",
|
||||
appProfileOn: "{profile}:已接入",
|
||||
appProfileOff: "{profile}:未接入",
|
||||
appProfilesHint:
|
||||
"开关会为每个已检测到的 Profile 安装记忆连接并授权,关闭时全部撤销。开关开启期间,新建的 Profile 会自动接入。",
|
||||
appProfilesNone:
|
||||
"还没有检测到 {name} 的 Profile。创建 Profile 后再回到此页。",
|
||||
appProfilesConnectFailed:
|
||||
"以下 Profile 未能接入:{profiles}。其他 Profile 已保留。{reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"以下 Profile 的连接未能移除,记忆权限也未能撤销,仍可使用记忆:{profiles}。请重试。{reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"已撤销以下 Profile 的记忆权限,但连接文件没有全部移除,请核对:{profiles}。",
|
||||
appProfileNameUnsupported:
|
||||
"Profile 名称只能包含小写字母、数字和连字符,最长 32 个字符",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"{name} 的以下 Profile 未能自动接入({profiles}){reason}。",
|
||||
};
|
||||
export const settingsChineseMessages = Object.fromEntries(
|
||||
Object.keys(settingsSpanishMessages).map((key) => [
|
||||
|
||||
@@ -1103,6 +1103,23 @@ export const germanMessages: Record<MessageKey, string> = {
|
||||
"Der Erinnerungszugriff wurde widerrufen; {name} kann keine Erinnerungen mehr abfragen. Die vollständige Entfernung konnte nicht bestätigt werden; prüfen Sie diese Pfade manuell: {paths}.",
|
||||
appRemovalReview:
|
||||
"Vollständige Entfernung der Verbindung konnte nicht bestätigt werden. Prüfen Sie diese Pfade manuell: {paths}.",
|
||||
appProfilesLabel: "Profile von {name}",
|
||||
appProfileOn: "{profile}: verbunden",
|
||||
appProfileOff: "{profile}: nicht verbunden",
|
||||
appProfilesHint:
|
||||
"Der Schalter installiert für jedes erkannte Profil die Erinnerungsverbindung und erteilt den Zugriff; beim Ausschalten wird er für alle widerrufen. Solange er eingeschaltet ist, werden neue Profile automatisch verbunden.",
|
||||
appProfilesNone:
|
||||
"Es wurde kein Profil von {name} erkannt. Legen Sie ein Profil an und kehren Sie dann zu dieser Seite zurück.",
|
||||
appProfilesConnectFailed:
|
||||
"Diese Profile konnten nicht verbunden werden: {profiles}. Die übrigen Profile bleiben erhalten. {reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"Diese Profile konnten nicht getrennt werden und können weiterhin Erinnerungen nutzen: {profiles}. Bitte versuchen Sie es erneut. {reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"Der Erinnerungszugriff dieser Profile wurde widerrufen, aber nicht alle Verbindungsdateien wurden entfernt; prüfen Sie sie: {profiles}.",
|
||||
appProfileNameUnsupported:
|
||||
"Profilnamen dürfen nur Kleinbuchstaben, Ziffern und Bindestriche enthalten, höchstens 32 Zeichen",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"Diese Profile von {name} konnten nicht automatisch verbunden werden ({profiles}){reason}.",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"Die Verbindungs-Anmeldedaten von Cursor haben sich geändert. Beenden Sie Cursor vollständig und öffnen Sie es erneut, bevor Sie eine neue Unterhaltung beginnen.",
|
||||
连接其他工具: "Andere Tools verbinden",
|
||||
|
||||
@@ -1116,6 +1116,23 @@ export const frenchMessages: Record<MessageKey, string> = {
|
||||
"L’accès aux mémoires a été révoqué : {name} ne peut plus rechercher de mémoires. La suppression complète n’a pas pu être confirmée ; vérifiez manuellement ces chemins : {paths}.",
|
||||
appRemovalReview:
|
||||
"La suppression complète de la connexion n’a pas pu être confirmée. Vérifiez manuellement ces chemins : {paths}.",
|
||||
appProfilesLabel: "Profils de {name}",
|
||||
appProfileOn: "{profile} : connecté",
|
||||
appProfileOff: "{profile} : non connecté",
|
||||
appProfilesHint:
|
||||
"L’interrupteur installe la connexion aux mémoires et accorde l’accès à chaque profil détecté, puis les révoque tous lorsqu’il est désactivé. Tant qu’il est activé, les nouveaux profils sont connectés automatiquement.",
|
||||
appProfilesNone:
|
||||
"Aucun profil de {name} n’a été détecté. Créez un profil, puis revenez sur cette page.",
|
||||
appProfilesConnectFailed:
|
||||
"Ces profils n’ont pas pu être connectés : {profiles}. Les autres profils sont conservés. {reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"Ces profils n’ont pas pu être déconnectés et peuvent encore utiliser les mémoires : {profiles}. Réessayez. {reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"L’accès aux mémoires de ces profils a été révoqué, mais tous leurs fichiers de connexion n’ont pas été supprimés ; vérifiez-les : {profiles}.",
|
||||
appProfileNameUnsupported:
|
||||
"les noms de profil ne peuvent contenir que des minuscules, des chiffres et des tirets, 32 caractères au maximum",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"Ces profils de {name} n’ont pas pu être connectés automatiquement ({profiles}){reason}.",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"L’identifiant de connexion de Cursor a changé. Quittez complètement Cursor et rouvrez-le avant de démarrer une nouvelle conversation.",
|
||||
连接其他工具: "Connecter d’autres outils",
|
||||
|
||||
@@ -1086,6 +1086,23 @@ export const indonesianMessages: Record<MessageKey, string> = {
|
||||
"Akses memori telah dicabut, sehingga {name} tidak dapat lagi mencari memori. Penghapusan penuh belum dapat dikonfirmasi; tinjau jalur berikut secara manual: {paths}.",
|
||||
appRemovalReview:
|
||||
"Penghapusan koneksi penuh belum dapat dikonfirmasi. Tinjau jalur berikut secara manual: {paths}.",
|
||||
appProfilesLabel: "Profil {name}",
|
||||
appProfileOn: "{profile}: terhubung",
|
||||
appProfileOff: "{profile}: belum terhubung",
|
||||
appProfilesHint:
|
||||
"Sakelar ini memasang koneksi memori dan memberi akses untuk setiap profil yang terdeteksi, lalu mencabut semuanya saat dimatikan. Selama sakelar menyala, profil baru akan terhubung otomatis.",
|
||||
appProfilesNone:
|
||||
"Tidak ada profil {name} yang terdeteksi. Buat profil, lalu kembali ke halaman ini.",
|
||||
appProfilesConnectFailed:
|
||||
"Profil berikut tidak dapat dihubungkan: {profiles}. Profil lainnya tetap dipertahankan. {reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"Profil berikut tidak dapat diputuskan dan masih dapat memakai memori: {profiles}. Coba lagi. {reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"Akses memori untuk profil berikut telah dicabut, tetapi tidak semua file koneksinya dihapus; tinjau: {profiles}.",
|
||||
appProfileNameUnsupported:
|
||||
"nama profil hanya boleh berisi huruf kecil, angka, dan tanda hubung, maksimal 32 karakter",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"Profil {name} berikut tidak dapat terhubung otomatis ({profiles}){reason}.",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"Kredensial koneksi Cursor telah berubah. Keluar sepenuhnya lalu buka kembali Cursor sebelum memulai percakapan baru.",
|
||||
连接其他工具: "Hubungkan alat lain",
|
||||
|
||||
@@ -1083,6 +1083,23 @@ export const japaneseMessages: Record<MessageKey, string> = {
|
||||
"記憶へのアクセスを取り消したため、{name} は記憶を照会できなくなりました。接続が完全に削除されたか確認できませんでした。次のパスを手動で確認してください:{paths}。",
|
||||
appRemovalReview:
|
||||
"接続が完全に削除されたか確認できませんでした。次のパスを手動で確認してください:{paths}。",
|
||||
appProfilesLabel: "{name} のプロファイル",
|
||||
appProfileOn: "{profile}:接続済み",
|
||||
appProfileOff: "{profile}:未接続",
|
||||
appProfilesHint:
|
||||
"このスイッチは検出されたすべてのプロファイルに記憶の接続をインストールしてアクセスを許可し、オフにするとすべて取り消します。オンの間は、新しいプロファイルも自動的に接続されます。",
|
||||
appProfilesNone:
|
||||
"{name} のプロファイルが検出されませんでした。プロファイルを作成してから、このページに戻ってください。",
|
||||
appProfilesConnectFailed:
|
||||
"次のプロファイルを接続できませんでした:{profiles}。ほかのプロファイルはそのまま維持されます。{reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"次のプロファイルの接続を解除できず、引き続き記憶を使用できます:{profiles}。もう一度お試しください。{reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"次のプロファイルの記憶へのアクセスを取り消しましたが、接続ファイルの一部は削除されていません。確認してください:{profiles}。",
|
||||
appProfileNameUnsupported:
|
||||
"プロファイル名に使えるのは小文字、数字、ハイフンのみで、32 文字までです",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"{name} の次のプロファイルを自動的に接続できませんでした({profiles}){reason}。",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"Cursor の接続の認証情報が更新されました。Cursor を完全に終了して開き直してから、新しい会話を始めてください。",
|
||||
连接其他工具: "ほかのツールを接続",
|
||||
|
||||
@@ -1060,6 +1060,23 @@ export const koreanMessages: Record<MessageKey, string> = {
|
||||
"기억 접근 권한이 취소되어 {name}은(는) 더 이상 기억을 조회할 수 없습니다. 완전히 제거되었는지 확인할 수 없으니 다음 경로를 직접 확인하세요: {paths}.",
|
||||
appRemovalReview:
|
||||
"연결이 완전히 제거되었는지 확인할 수 없습니다. 다음 경로를 직접 확인하세요: {paths}.",
|
||||
appProfilesLabel: "{name} 프로필",
|
||||
appProfileOn: "{profile}: 연결됨",
|
||||
appProfileOff: "{profile}: 연결 안 됨",
|
||||
appProfilesHint:
|
||||
"이 스위치는 감지된 모든 프로필에 기억 연결을 설치하고 접근을 허용하며, 끄면 모두 취소합니다. 켜져 있는 동안 새 프로필은 자동으로 연결됩니다.",
|
||||
appProfilesNone:
|
||||
"{name} 프로필이 감지되지 않았습니다. 프로필을 만든 뒤 이 페이지로 돌아오세요.",
|
||||
appProfilesConnectFailed:
|
||||
"다음 프로필을 연결하지 못했습니다: {profiles}. 다른 프로필은 유지됩니다. {reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"다음 프로필의 연결을 해제하지 못해 여전히 기억을 사용할 수 있습니다: {profiles}. 다시 시도하세요. {reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"다음 프로필의 기억 접근 권한을 취소했지만 연결 파일이 모두 제거되지는 않았습니다. 확인하세요: {profiles}.",
|
||||
appProfileNameUnsupported:
|
||||
"프로필 이름에는 소문자, 숫자, 하이픈만 사용할 수 있으며 최대 32자입니다",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"{name}의 다음 프로필을 자동으로 연결하지 못했습니다({profiles}){reason}.",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"Cursor의 연결 자격 증명이 변경되었습니다. 새 대화를 시작하기 전에 Cursor를 완전히 종료했다가 다시 여세요.",
|
||||
连接其他工具: "다른 도구 연결",
|
||||
|
||||
@@ -1107,6 +1107,23 @@ export const portugueseMessages: Record<MessageKey, string> = {
|
||||
"O acesso às memórias foi revogado, então {name} não pode mais consultar memórias. Não foi possível confirmar a remoção completa; revise estes caminhos manualmente: {paths}.",
|
||||
appRemovalReview:
|
||||
"Não foi possível confirmar a remoção completa da conexão. Revise estes caminhos manualmente: {paths}.",
|
||||
appProfilesLabel: "Perfis de {name}",
|
||||
appProfileOn: "{profile}: conectado",
|
||||
appProfileOff: "{profile}: não conectado",
|
||||
appProfilesHint:
|
||||
"O interruptor instala a conexão de memórias e concede acesso a cada perfil detectado, e revoga todos ao ser desligado. Enquanto estiver ligado, novos perfis são conectados automaticamente.",
|
||||
appProfilesNone:
|
||||
"Nenhum perfil de {name} foi detectado. Crie um perfil e volte a esta página.",
|
||||
appProfilesConnectFailed:
|
||||
"Não foi possível conectar estes perfis: {profiles}. Os outros perfis foram mantidos. {reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"Não foi possível desconectar estes perfis, que ainda podem usar memórias: {profiles}. Tente novamente. {reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"O acesso às memórias foi revogado para estes perfis, mas nem todos os arquivos de conexão foram removidos; revise-os: {profiles}.",
|
||||
appProfileNameUnsupported:
|
||||
"nomes de perfil só podem usar letras minúsculas, dígitos e hifens, até 32 caracteres",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"Não foi possível conectar automaticamente estes perfis de {name} ({profiles}){reason}.",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"A credencial de conexão do Cursor mudou. Feche o Cursor por completo e abra novamente antes de iniciar uma nova conversa.",
|
||||
连接其他工具: "Conectar outras ferramentas",
|
||||
|
||||
@@ -1092,6 +1092,23 @@ export const russianMessages: Record<MessageKey, string> = {
|
||||
"Доступ к памяти отозван: {name} больше не может искать записи памяти. Полное удаление не подтверждено; проверьте эти пути вручную: {paths}.",
|
||||
appRemovalReview:
|
||||
"Полное удаление подключения не подтверждено. Проверьте эти пути вручную: {paths}.",
|
||||
appProfilesLabel: "Профили {name}",
|
||||
appProfileOn: "{profile}: подключён",
|
||||
appProfileOff: "{profile}: не подключён",
|
||||
appProfilesHint:
|
||||
"Переключатель устанавливает подключение к памяти и выдаёт доступ каждому найденному профилю, а при выключении отзывает доступ у всех. Пока он включён, новые профили подключаются автоматически.",
|
||||
appProfilesNone:
|
||||
"Профили {name} не найдены. Создайте профиль и вернитесь на эту страницу.",
|
||||
appProfilesConnectFailed:
|
||||
"Не удалось подключить профили: {profiles}. Остальные профили сохранены. {reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"Не удалось отключить профили, они всё ещё могут использовать память: {profiles}. Повторите попытку. {reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"Доступ к памяти для этих профилей отозван, но не все файлы подключения удалены; проверьте их: {profiles}.",
|
||||
appProfileNameUnsupported:
|
||||
"имя профиля может содержать только строчные буквы, цифры и дефисы, не более 32 символов",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"Не удалось автоматически подключить эти профили {name} ({profiles}){reason}.",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"Учётные данные подключения Cursor изменились. Полностью закройте и снова откройте Cursor, прежде чем начинать новый диалог.",
|
||||
连接其他工具: "Подключить другие инструменты",
|
||||
|
||||
@@ -990,6 +990,22 @@ export const traditionalChineseMessages: Record<MessageKey, string> = {
|
||||
appRevokedReview:
|
||||
"已撤銷記憶權限,{name} 已無法查詢記憶。但無法確認連線已全部移除,請手動核對以下路徑:{paths}。",
|
||||
appRemovalReview: "無法確認連線已全部移除,請手動核對以下路徑:{paths}。",
|
||||
appProfilesLabel: "{name} 的 Profile",
|
||||
appProfileOn: "{profile}:已串接",
|
||||
appProfileOff: "{profile}:未串接",
|
||||
appProfilesHint:
|
||||
"開關會為每個已偵測到的 Profile 安裝記憶連線並授權,關閉時全部撤銷。開關開啟期間,新建立的 Profile 會自動串接。",
|
||||
appProfilesNone: "尚未偵測到 {name} 的 Profile。建立 Profile 後請回到此頁。",
|
||||
appProfilesConnectFailed:
|
||||
"以下 Profile 未能串接:{profiles}。其他 Profile 已保留。{reason}",
|
||||
appProfilesDisconnectFailed:
|
||||
"以下 Profile 的連線未能移除,記憶權限也未能撤銷,仍可使用記憶:{profiles}。請重試。{reason}",
|
||||
appProfilesRevokedRetained:
|
||||
"已撤銷以下 Profile 的記憶權限,但連線檔案沒有全部移除,請核對:{profiles}。",
|
||||
appProfileNameUnsupported:
|
||||
"Profile 名稱只能包含小寫字母、數字和連字號,最長 32 個字元",
|
||||
"apps.autoHostProfilesFailed":
|
||||
"{name} 的以下 Profile 未能自動串接({profiles}){reason}。",
|
||||
"Cursor 的连接凭证已更新。请完全退出并重新打开 Cursor,再开始新对话。":
|
||||
"Cursor 的連線憑證已更新。請完全結束並重新開啟 Cursor,再開始新對話。",
|
||||
连接其他工具: "連線其他工具",
|
||||
|
||||
@@ -21,6 +21,7 @@ interface Options {
|
||||
permissions: HostPermissions;
|
||||
layouts: ReadonlyMap<string, RecallHostLayout>;
|
||||
hosts?: readonly RecallHostDescriptor[];
|
||||
discoverHosts?: () => Promise<readonly RecallHostDescriptor[]>;
|
||||
}
|
||||
|
||||
/** Constructed inside the Runtime with its existing permission owner. */
|
||||
@@ -28,6 +29,7 @@ export function createConnectionControlService(options: Options) {
|
||||
const hostControl = createHostControlService({
|
||||
permissions: options.permissions,
|
||||
hosts: options.hosts ?? [],
|
||||
...(options.discoverHosts ? { discover: options.discoverHosts } : {}),
|
||||
});
|
||||
let controller: Promise<ConnectionController | null> | null = null;
|
||||
let pinned: string | null = null;
|
||||
|
||||
@@ -194,6 +194,39 @@ it.each([
|
||||
expect(f.effects).toEqual([]);
|
||||
},
|
||||
);
|
||||
it("finds a Harness profile created after the Runtime started, and only a profile", async () => {
|
||||
const f = await fixture();
|
||||
const hostId = "deepseek-harness:later";
|
||||
const later = {
|
||||
hostId,
|
||||
label: "DeepSeek Harness · later",
|
||||
layout: { ...f.layout, hostId, hostLabel: "DeepSeek Harness · later" },
|
||||
presencePath: f.root,
|
||||
};
|
||||
const discover = vi.fn(async () => [...f.hosts, later]);
|
||||
const service = createHostControlService({
|
||||
permissions: f.permissions as unknown as HostPermissions,
|
||||
hosts: f.hosts,
|
||||
discover,
|
||||
});
|
||||
await service.handle({ hostId, operation: "getPermission", args: [] });
|
||||
expect(f.methods.getPermission).toHaveBeenCalledWith(later.layout);
|
||||
// Remembered: the disk is read once per new profile, not once per call.
|
||||
await service.handle({ hostId, operation: "getPermission", args: [] });
|
||||
expect(discover).toHaveBeenCalledTimes(1);
|
||||
await expect(
|
||||
service.handle({
|
||||
hostId: "deepseek-harness:absent",
|
||||
operation: "getPermission",
|
||||
args: [],
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
expect(discover).toHaveBeenCalledTimes(2);
|
||||
await expect(
|
||||
service.handle({ hostId: "unknown", operation: "getPermission", args: [] }),
|
||||
).rejects.toThrow();
|
||||
expect(discover).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("clones nested arguments and trusted layout before an asynchronous owner observes them", async () => {
|
||||
const f = await fixture();
|
||||
let release!: () => void;
|
||||
|
||||
@@ -149,6 +149,8 @@ function validateArgs(operation: HostControlOperation, args: unknown[]): void {
|
||||
export function createHostControlService(options: {
|
||||
permissions: HostPermissions;
|
||||
hosts: readonly RecallHostDescriptor[];
|
||||
/** Re-reads the disk for a profile host created since this service started. */
|
||||
discover?: () => Promise<readonly RecallHostDescriptor[]>;
|
||||
}) {
|
||||
const permissions = options.permissions;
|
||||
const hosts = new Map<string, RecallHostDescriptor>();
|
||||
@@ -158,6 +160,17 @@ export function createHostControlService(options: {
|
||||
fail();
|
||||
hosts.set(source.hostId, structuredClone(source));
|
||||
}
|
||||
/** Only a profile id can appear after start; every other host is a fixed
|
||||
* path, so an unknown one is refused without touching the disk. */
|
||||
async function discovered(hostId: string) {
|
||||
if (!options.discover || !hostId.includes(":")) return undefined;
|
||||
const found = (await options.discover()).find(
|
||||
(source) =>
|
||||
source.hostId === hostId && source.layout.hostId === source.hostId,
|
||||
);
|
||||
if (found) hosts.set(hostId, structuredClone(found));
|
||||
return found;
|
||||
}
|
||||
return {
|
||||
async handle(input: unknown): Promise<unknown> {
|
||||
const request = exact(input, ["hostId", "operation", "args"]);
|
||||
@@ -169,7 +182,10 @@ export function createHostControlService(options: {
|
||||
!Array.isArray(request.args)
|
||||
)
|
||||
fail();
|
||||
const host = hosts.get(request.hostId);
|
||||
// A known host must not yield here: its arguments are cloned below,
|
||||
// before the caller's next tick can change them.
|
||||
const host =
|
||||
hosts.get(request.hostId) ?? (await discovered(request.hostId));
|
||||
if (!host) fail();
|
||||
const operation = request.operation as HostControlOperation;
|
||||
if (
|
||||
|
||||
@@ -732,12 +732,14 @@ export async function createRuntimeService(
|
||||
verifyHostRuntime,
|
||||
config.hostRuntime?.manifestSha256 ?? "daily",
|
||||
);
|
||||
const hosts = (
|
||||
await recallHosts(config.hostHome ?? os.homedir(), {
|
||||
...process.env,
|
||||
ONE_MEMORY_HOST_HOME: config.hostHome,
|
||||
})
|
||||
).filter((host) => host.hostId !== "openclaw");
|
||||
const scanHosts = async () =>
|
||||
(
|
||||
await recallHosts(config.hostHome ?? os.homedir(), {
|
||||
...process.env,
|
||||
ONE_MEMORY_HOST_HOME: config.hostHome,
|
||||
})
|
||||
).filter((host) => host.hostId !== "openclaw");
|
||||
const hosts = await scanHosts();
|
||||
await verifyHostRuntime().then(
|
||||
async () => {
|
||||
// Every Runtime start after an upgrade, the App's or `memhub
|
||||
@@ -767,6 +769,9 @@ export async function createRuntimeService(
|
||||
connection,
|
||||
permissions,
|
||||
hosts,
|
||||
// The Runtime outlives the App: a Harness profile created after it
|
||||
// started must not make every later host read fail.
|
||||
discoverHosts: scanHosts,
|
||||
layouts: new Map(
|
||||
hosts.flatMap((host) =>
|
||||
host.hostId === "claude-code"
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Intention(L7)读侧判重开关(issue #241)。
|
||||
|
||||
覆盖:
|
||||
1. 默认开启:行为不变,复本只返回最早一条,其余异步删库;
|
||||
2. 关闭:不隐藏、不删除,两条意图都返回;
|
||||
3. 阈值生效:cosine 低于阈值不判重,高于阈值判重;
|
||||
4. reader 按 client 的 MemoryConfig.recall 读取开关/阈值,而非调用时的 env;
|
||||
5. MemoryConfig 默认值与 env 回退;
|
||||
6. 写入侧批内判重同样受开关控制;阈值不影响写入侧;
|
||||
7. 关闭时不为判重补拉 embedding;配置阈值非法时不影响召回。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from hy_memory.config import MemoryConfig
|
||||
from hy_memory.pipelines.base import ReadRequest
|
||||
from hy_memory.pipelines._retrieval.intention import recall_intentions
|
||||
|
||||
from tests.test_intention_dedup import (
|
||||
_FakeVectorStore,
|
||||
_make_intention_node,
|
||||
_run,
|
||||
)
|
||||
|
||||
|
||||
_MA = datetime(2025, 8, 6)
|
||||
_VU = datetime(2025, 8, 31, 23, 59)
|
||||
_NOW = datetime(2025, 8, 6, 12, 0)
|
||||
|
||||
|
||||
def _unit(vec):
|
||||
n = sum(x * x for x in vec) ** 0.5 or 1.0
|
||||
return [x / n for x in vec]
|
||||
|
||||
|
||||
def _seed_project_pair(vs, *, emb_a, emb_b):
|
||||
"""A / B 两个项目的近似意图:同 user/agent/同天/同截止日。A 更早写入。"""
|
||||
a = _make_intention_node(
|
||||
"A 项目每周一触发发布前校验流程", memory_at=_MA, valid_until=_VU,
|
||||
gmt_created=datetime(2025, 8, 1), embedding=emb_a,
|
||||
)
|
||||
b = _make_intention_node(
|
||||
"B 项目每周一触发发布前校验流程", memory_at=_MA, valid_until=_VU,
|
||||
gmt_created=datetime(2025, 8, 2), embedding=emb_b,
|
||||
)
|
||||
_run(vs.upsert(a))
|
||||
_run(vs.upsert(b))
|
||||
return a, b
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# recall_intentions 参数
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_default_on_keeps_earliest_and_deletes_duplicate():
|
||||
vs = _FakeVectorStore()
|
||||
emb = _unit([1.0, 0.0])
|
||||
a, b = _seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
|
||||
stats = {}
|
||||
result = _run(recall_intentions(
|
||||
vs, emb, user_ids=["u1"], limit=10, now=_NOW, stats_out=stats,
|
||||
))
|
||||
assert [h["node_id"] for h in result] == [a.node_id]
|
||||
assert vs.delete_calls == [b.node_id]
|
||||
assert stats["dedup_enabled"] is True
|
||||
assert stats["dedup_dropped"] == 1
|
||||
|
||||
|
||||
def test_off_returns_both_and_deletes_nothing():
|
||||
vs = _FakeVectorStore()
|
||||
emb = _unit([1.0, 0.0])
|
||||
a, b = _seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
|
||||
stats = {}
|
||||
result = _run(recall_intentions(
|
||||
vs, emb, user_ids=["u1"], limit=10, now=_NOW, stats_out=stats,
|
||||
dedup_enabled=False,
|
||||
))
|
||||
assert {h["node_id"] for h in result} == {a.node_id, b.node_id}
|
||||
assert vs.delete_calls == []
|
||||
assert stats["dedup_enabled"] is False
|
||||
assert stats["dedup_dropped"] == 0
|
||||
|
||||
|
||||
def test_threshold_respected():
|
||||
# cosine(a, b) = 0.9
|
||||
emb_a = _unit([1.0, 0.0])
|
||||
emb_b = _unit([0.9, (1 - 0.81) ** 0.5])
|
||||
|
||||
# 默认 0.95 → 0.9 不算复本
|
||||
vs = _FakeVectorStore()
|
||||
_seed_project_pair(vs, emb_a=emb_a, emb_b=emb_b)
|
||||
result = _run(recall_intentions(
|
||||
vs, emb_a, user_ids=["u1"], limit=10, now=_NOW, dedup_threshold=0.95,
|
||||
))
|
||||
assert len(result) == 2
|
||||
assert vs.delete_calls == []
|
||||
|
||||
# 调低到 0.85 → 判重,删较晚的 B
|
||||
vs = _FakeVectorStore()
|
||||
a, b = _seed_project_pair(vs, emb_a=emb_a, emb_b=emb_b)
|
||||
stats = {}
|
||||
result = _run(recall_intentions(
|
||||
vs, emb_a, user_ids=["u1"], limit=10, now=_NOW,
|
||||
dedup_threshold=0.85, stats_out=stats,
|
||||
))
|
||||
assert [h["node_id"] for h in result] == [a.node_id]
|
||||
assert vs.delete_calls == [b.node_id]
|
||||
assert stats["dedup_threshold"] == 0.85
|
||||
|
||||
|
||||
def test_explicit_threshold_wins_over_env(monkeypatch):
|
||||
monkeypatch.setenv("MEMORY_DEDUP_THRESHOLD", "0.5")
|
||||
emb_a = _unit([1.0, 0.0])
|
||||
emb_b = _unit([0.9, (1 - 0.81) ** 0.5])
|
||||
vs = _FakeVectorStore()
|
||||
_seed_project_pair(vs, emb_a=emb_a, emb_b=emb_b)
|
||||
result = _run(recall_intentions(
|
||||
vs, emb_a, user_ids=["u1"], limit=10, now=_NOW, dedup_threshold=0.95,
|
||||
))
|
||||
assert len(result) == 2
|
||||
assert vs.delete_calls == []
|
||||
|
||||
|
||||
def test_off_skips_embedding_backfill():
|
||||
vs = _FakeVectorStore()
|
||||
emb = _unit([1.0, 0.0])
|
||||
_seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
|
||||
|
||||
backfill_calls = []
|
||||
|
||||
async def _get_embeddings(ids):
|
||||
backfill_calls.append(ids)
|
||||
return {}
|
||||
|
||||
vs.get_embeddings = _get_embeddings
|
||||
for n in vs._nodes.values():
|
||||
n.embedding = None
|
||||
result = _run(recall_intentions(
|
||||
vs, emb, user_ids=["u1"], limit=10, now=_NOW, dedup_enabled=False,
|
||||
))
|
||||
assert len(result) == 2
|
||||
assert backfill_calls == []
|
||||
|
||||
|
||||
def test_invalid_threshold_degrades_to_env_default(monkeypatch):
|
||||
monkeypatch.delenv("MEMORY_DEDUP_THRESHOLD", raising=False)
|
||||
vs = _FakeVectorStore()
|
||||
emb = _unit([1.0, 0.0])
|
||||
a, b = _seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
|
||||
stats = {}
|
||||
result = _run(recall_intentions(
|
||||
vs, emb, user_ids=["u1"], limit=10, now=_NOW, stats_out=stats,
|
||||
dedup_threshold="not-a-number",
|
||||
))
|
||||
assert [h["node_id"] for h in result] == [a.node_id]
|
||||
assert stats["dedup_threshold"] == 0.95
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# 写入侧批内判重
|
||||
# ============================================================================
|
||||
|
||||
|
||||
class _SameVectorEmbed:
|
||||
"""所有文本同一向量:cosine=1,开启判重时必判为复本。"""
|
||||
|
||||
async def embed_batch(self, texts):
|
||||
return [_unit([1.0, 0.0]) for _ in texts]
|
||||
|
||||
async def embed_queued(self, text):
|
||||
return _unit([1.0, 0.0])
|
||||
|
||||
|
||||
def _store_batch(config_recall):
|
||||
from hy_memory.pipelines.base import WriteRequest
|
||||
from hy_memory.pipelines.writer import MemoryWriter
|
||||
|
||||
cfg = MemoryConfig.from_dict({"recall": config_recall})
|
||||
vs = _FakeVectorStore()
|
||||
writer = MemoryWriter(cfg, embed_service=_SameVectorEmbed(), vector_store=vs)
|
||||
req = WriteRequest(
|
||||
content="", messages=[], user_id="u1", agent_id="a1",
|
||||
session_id="s1", request_id=uuid.uuid4().hex,
|
||||
)
|
||||
intentions = [
|
||||
{"content": "A 项目每周一触发发布前校验流程", "tags": [], "valid_until": None},
|
||||
{"content": "B 项目每周一触发发布前校验流程", "tags": [], "valid_until": None},
|
||||
]
|
||||
return _run(writer._store_intentions(intentions, req, vs, req.request_id)), vs
|
||||
|
||||
|
||||
def test_write_batch_dedup_default_on_unchanged():
|
||||
ids, vs = _store_batch({})
|
||||
assert len(ids) == 1
|
||||
assert [n.content for n in vs._nodes.values()] == [
|
||||
"A 项目每周一触发发布前校验流程",
|
||||
]
|
||||
|
||||
|
||||
def test_write_batch_dedup_off_stores_both():
|
||||
ids, vs = _store_batch({"intention_dedup_enabled": False})
|
||||
assert len(ids) == 2
|
||||
assert len(vs._nodes) == 2
|
||||
|
||||
|
||||
def test_read_threshold_does_not_change_write_batch_dedup(monkeypatch):
|
||||
"""intention_dedup_threshold 只管读侧;写入侧仍取 MEMORY_DEDUP_THRESHOLD。"""
|
||||
monkeypatch.delenv("MEMORY_DEDUP_THRESHOLD", raising=False)
|
||||
ids, _ = _store_batch({"intention_dedup_threshold": 1.5})
|
||||
assert len(ids) == 1
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# MemoryConfig
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_config_defaults(monkeypatch):
|
||||
for k in (
|
||||
"MEMORY_INTENTION_DEDUP_ENABLED",
|
||||
"MEMORY_INTENTION_DEDUP_THRESHOLD",
|
||||
"MEMORY_DEDUP_THRESHOLD",
|
||||
):
|
||||
monkeypatch.delenv(k, raising=False)
|
||||
cfg = MemoryConfig()
|
||||
assert cfg.recall.intention_dedup_enabled is True
|
||||
assert cfg.recall.intention_dedup_threshold == 0.95
|
||||
|
||||
|
||||
def test_config_env_fallbacks(monkeypatch):
|
||||
monkeypatch.setenv("MEMORY_INTENTION_DEDUP_ENABLED", "false")
|
||||
monkeypatch.setenv("MEMORY_DEDUP_THRESHOLD", "0.9")
|
||||
monkeypatch.delenv("MEMORY_INTENTION_DEDUP_THRESHOLD", raising=False)
|
||||
cfg = MemoryConfig()
|
||||
assert cfg.recall.intention_dedup_enabled is False
|
||||
# 未设专用阈值 → 回退共享 MEMORY_DEDUP_THRESHOLD(兼容旧部署)
|
||||
assert cfg.recall.intention_dedup_threshold == 0.9
|
||||
|
||||
monkeypatch.setenv("MEMORY_INTENTION_DEDUP_THRESHOLD", "0.8")
|
||||
assert MemoryConfig().recall.intention_dedup_threshold == 0.8
|
||||
|
||||
|
||||
def test_config_from_dict_overrides_env(monkeypatch):
|
||||
monkeypatch.setenv("MEMORY_INTENTION_DEDUP_ENABLED", "true")
|
||||
cfg = MemoryConfig.from_dict({"recall": {
|
||||
"intention_dedup_enabled": False,
|
||||
"intention_dedup_threshold": 0.99,
|
||||
}})
|
||||
assert cfg.recall.intention_dedup_enabled is False
|
||||
assert cfg.recall.intention_dedup_threshold == 0.99
|
||||
assert cfg.to_dict()["recall"]["intention_dedup_enabled"] is False
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# reader:按 client 配置,而不是调用时的 env
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def _reader_for(enabled: bool, vs):
|
||||
from hy_memory.pipelines.reader_hybrid import HybridReadPipeline
|
||||
|
||||
cfg = MemoryConfig.from_dict({
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"collection_name": f"t_intent_sw_{uuid.uuid4().hex[:8]}",
|
||||
"embedding_dims": 2,
|
||||
},
|
||||
"recall": {"intention_dedup_enabled": enabled},
|
||||
})
|
||||
reader = HybridReadPipeline(cfg, vector_store=vs)
|
||||
reader._vector_store = vs
|
||||
reader._vector_store_initialized = True
|
||||
return reader
|
||||
|
||||
|
||||
async def _no_keyword_hits(**kw):
|
||||
return []
|
||||
|
||||
|
||||
def _read_project_pair(enabled: bool):
|
||||
"""经 reader 完整读路径召回 A/B 两条近似意图;返回 (返回的意图 id, 删库调用, a, b)。"""
|
||||
vs = _FakeVectorStore()
|
||||
vs.keyword_search = _no_keyword_hits
|
||||
emb = _unit([1.0, 0.0])
|
||||
a, b = _seed_project_pair(vs, emb_a=emb, emb_b=list(emb))
|
||||
# 读路径用真实 now:让两条都未过期且同一天
|
||||
today = datetime.now()
|
||||
for n in (a, b):
|
||||
n.memory_at = today
|
||||
n.valid_until = None
|
||||
reader = _reader_for(enabled, vs)
|
||||
_run(reader.initialize())
|
||||
resp = _run(reader.read(ReadRequest(
|
||||
query="发布前校验", query_embedding=emb,
|
||||
user_ids=["u1"], agent_ids=["a1"], limit=10, intention_limit=5,
|
||||
)))
|
||||
ids = {
|
||||
m["memory_id"] for m in resp.memories
|
||||
if m.get("layer") == "l7_intention"
|
||||
}
|
||||
return ids, list(vs.delete_calls), a, b
|
||||
|
||||
|
||||
@pytest.mark.parametrize("env_value", ["true", "false"])
|
||||
def test_reader_uses_per_client_config_not_env(monkeypatch, env_value):
|
||||
"""调用时的 env 与 client 配置无关:两个 client 一开一关,各自生效。"""
|
||||
monkeypatch.setenv("MEMORY_INTENTION_DEDUP_ENABLED", env_value)
|
||||
monkeypatch.setenv("MEMORY_DEDUP_THRESHOLD", "0.0")
|
||||
|
||||
ids_on, deleted_on, a, b = _read_project_pair(True)
|
||||
assert ids_on == {a.node_id}
|
||||
assert deleted_on == [b.node_id]
|
||||
|
||||
ids_off, deleted_off, a, b = _read_project_pair(False)
|
||||
assert ids_off == {a.node_id, b.node_id}
|
||||
assert deleted_off == []
|
||||
|
||||
|
||||
def test_reader_passes_client_threshold(monkeypatch):
|
||||
monkeypatch.setenv("MEMORY_DEDUP_THRESHOLD", "0.1")
|
||||
seen = []
|
||||
|
||||
async def _spy(*args, **kwargs):
|
||||
seen.append(kwargs)
|
||||
return []
|
||||
|
||||
monkeypatch.setattr("hy_memory.pipelines.reader_base.recall_intentions", _spy)
|
||||
vs = _FakeVectorStore()
|
||||
vs.keyword_search = _no_keyword_hits
|
||||
reader = _reader_for(True, vs)
|
||||
reader.config.recall.intention_dedup_threshold = 0.97
|
||||
_run(reader.initialize())
|
||||
_run(reader.read(ReadRequest(
|
||||
query="发布前校验", query_embedding=_unit([1.0, 0.0]),
|
||||
user_ids=["u1"], agent_ids=["a1"], limit=10, intention_limit=5,
|
||||
)))
|
||||
assert seen and seen[0]["dedup_enabled"] is True
|
||||
assert seen[0]["dedup_threshold"] == 0.97
|
||||
Reference in new issue
Block a user