From c2932b63a6b7b867e072d89c09e78e43476477ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=81=E5=9C=A8=E5=90=B5=E7=9D=80=E5=90=83=E7=B3=96?= Date: Tue, 11 Aug 2026 17:32:56 +0800 Subject: [PATCH 1/6] fix: honor Hermes home on Windows --- apps/memos-local-plugin/install.ps1 | 47 +++++++++++++++++-- .../server/routes/import-export.ts | 34 +++++++++++--- .../unit/install/hermes-provider-link.test.ts | 30 +++++++++++- .../tests/unit/server/http.test.ts | 12 ++++- .../unit/server/import-export-path.test.ts | 46 ++++++++++++++++++ .../viewer/src/stores/i18n.ts | 4 +- .../viewer/src/views/ImportView.tsx | 2 +- 7 files changed, 158 insertions(+), 17 deletions(-) create mode 100644 apps/memos-local-plugin/tests/unit/server/import-export-path.test.ts diff --git a/apps/memos-local-plugin/install.ps1 b/apps/memos-local-plugin/install.ps1 index 4604e0b47..3391c3b05 100644 --- a/apps/memos-local-plugin/install.ps1 +++ b/apps/memos-local-plugin/install.ps1 @@ -60,6 +60,37 @@ function Test-BetterSqlite3 { } } +function Resolve-HermesHostHome { + $ConfiguredHome = $env:HERMES_HOME + if ($ConfiguredHome -and $ConfiguredHome.Trim()) { + $Candidate = [Environment]::ExpandEnvironmentVariables($ConfiguredHome.Trim()) + if ($Candidate -eq "~") { + if (-not $env:USERPROFILE -or -not $env:USERPROFILE.Trim()) { + Stop-Die "HERMES_HOME uses '~', but USERPROFILE is not set." + } + $UserProfile = $env:USERPROFILE.Trim() + $Candidate = $UserProfile + } elseif ($Candidate.StartsWith("~\") -or $Candidate.StartsWith("~/")) { + if (-not $env:USERPROFILE -or -not $env:USERPROFILE.Trim()) { + Stop-Die "HERMES_HOME uses '~', but USERPROFILE is not set." + } + $UserProfile = $env:USERPROFILE.Trim() + $RelativeHome = $Candidate.Substring(2) + $Candidate = Join-Path $UserProfile $RelativeHome + } + if (-not [IO.Path]::IsPathRooted($Candidate)) { + Stop-Die "HERMES_HOME must be an absolute path: $ConfiguredHome" + } + return [IO.Path]::GetFullPath($Candidate) + } + + if (-not $env:LOCALAPPDATA -or -not $env:LOCALAPPDATA.Trim()) { + Stop-Die "LOCALAPPDATA is not set; set HERMES_HOME to the Hermes data directory." + } + $LocalAppData = $env:LOCALAPPDATA.Trim() + return [IO.Path]::GetFullPath((Join-Path $LocalAppData "hermes")) +} + $PluginId = "memos-local-plugin" $NpmPackage = "@memtensor/memos-local-plugin" $OpenClawPort = 18799 @@ -82,14 +113,18 @@ try { } # Agent detection +$HermesHome = Resolve-HermesHostHome +# Keep every child process on the same normalized host-data directory. This is +# process-scoped and does not overwrite the user's persisted environment. +$env:HERMES_HOME = $HermesHome $HasOpenClaw = Test-Path "$env:USERPROFILE\.openclaw" -$HasHermes = Test-Path "$env:LOCALAPPDATA\hermes" +$HasHermes = Test-Path $HermesHome Write-Host "`n Detected agents:" -ForegroundColor White if ($HasOpenClaw) { Write-Host " - OpenClaw (~/.openclaw)" -ForegroundColor Green } else { Write-Host " - OpenClaw (not installed)" -ForegroundColor DarkGray } -if ($HasHermes) { Write-Host " - Hermes (~/AppData/Local/hermes)" -ForegroundColor Green } +if ($HasHermes) { Write-Host " - Hermes ($HermesHome)" -ForegroundColor Green } else { Write-Host " - Hermes (not installed)" -ForegroundColor DarkGray } Write-Host "`n Install into which agent?" @@ -113,7 +148,7 @@ switch ($Choice) { } if ($AgentSelection -eq "auto") { - if (-not $HasOpenClaw -and -not $HasHermes) { Stop-Die "Neither ~/.openclaw nor ~/AppData/Local/hermes exists. Install one first." } + if (-not $HasOpenClaw -and -not $HasHermes) { Stop-Die "Neither ~/.openclaw nor Hermes home ($HermesHome) exists. Install one first." } if ($HasOpenClaw -and $HasHermes) { $AgentSelection = "all" } elseif ($HasOpenClaw) { $AgentSelection = "openclaw" } else { $AgentSelection = "hermes" } @@ -609,10 +644,12 @@ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n', 'utf8'); function Install-Hermes { Write-Host "`n=== Hermes Install ===" -ForegroundColor Cyan + # MemOS package/runtime files remain in the canonical LocalAppData install + # root. Hermes host data below follows HERMES_HOME and may live elsewhere. $Prefix = Join-Path $env:LOCALAPPDATA "hermes\memos-plugin" $RuntimeSelection = Resolve-HermesRuntimeHome -InstallRoot $Prefix $HomeDir = $RuntimeSelection.Path - $ConfigFile = Join-Path $env:LOCALAPPDATA "hermes\config.yaml" + $ConfigFile = Join-Path $HermesHome "config.yaml" $AdapterDir = Join-Path $Prefix "adapters\hermes" Deploy-Tarball -Prefix $Prefix -BeforeSwap { @@ -664,7 +701,7 @@ function Install-Hermes { Write-Warning "plugin.yaml copy may have failed; verify $AdapterDir\memos_provider\plugin.yaml exists." } - $UserPluginDir = Join-Path $env:LOCALAPPDATA "hermes\plugins\memory" + $UserPluginDir = Join-Path $HermesHome "plugins\memory" New-Item -ItemType Directory -Path $UserPluginDir -Force | Out-Null Write-Host "Ensuring user plugin dir: $UserPluginDir" $ProviderTargets = @( diff --git a/apps/memos-local-plugin/server/routes/import-export.ts b/apps/memos-local-plugin/server/routes/import-export.ts index efdf16595..082aabe23 100644 --- a/apps/memos-local-plugin/server/routes/import-export.ts +++ b/apps/memos-local-plugin/server/routes/import-export.ts @@ -7,8 +7,10 @@ * POST /api/v1/import → accept a JSON bundle and insert * non-colliding rows. * GET /api/v1/import/hermes-native/scan - * → count ~/.hermes/memories/MEMORY.md - * entries when running as Hermes. + * → count $HERMES_HOME/memories/MEMORY.md + * entries when running as Hermes (on + * Windows the default home is under + * %LOCALAPPDATA%\hermes). * POST /api/v1/import/hermes-native/run * → import a batch from that file. * GET /api/v1/import/openclaw-native/scan @@ -129,7 +131,7 @@ export function registerImportExportRoutes( }); routes.set("GET /api/v1/import/hermes-native/scan", async () => { - const path = hermesNativeMemoryPath(); + const path = resolveHermesNativeMemoryPath(); if (!isHermes) { return { found: false, @@ -143,7 +145,7 @@ export function registerImportExportRoutes( }); routes.set("POST /api/v1/import/hermes-native/run", async (ctx) => { - const path = hermesNativeMemoryPath(); + const path = resolveHermesNativeMemoryPath(); if (!isHermes) { writeError( ctx, @@ -333,8 +335,28 @@ function parseMultipartBundle(contentType: string, body: Buffer): string | null return null; } -function hermesNativeMemoryPath(): string { - return join(homedir(), ".hermes", "memories", "MEMORY.md"); +interface HermesNativeMemoryPathOptions { + env?: NodeJS.ProcessEnv; + platform?: NodeJS.Platform; + userHome?: string; +} + +/** Resolve the host Hermes memory file, not the separate MemOS runtime home. */ +export function resolveHermesNativeMemoryPath( + options: HermesNativeMemoryPathOptions = {}, +): string { + const env = options.env ?? process.env; + const configuredHome = env.HERMES_HOME?.trim(); + const platform = options.platform ?? process.platform; + const userHome = options.userHome ?? homedir(); + + const hermesHome = configuredHome + ? configuredHome + : platform === "win32" && env.LOCALAPPDATA?.trim() + ? join(env.LOCALAPPDATA.trim(), "hermes") + : join(userHome, ".hermes"); + + return join(hermesHome, "memories", "MEMORY.md"); } function openClawHome(): string { diff --git a/apps/memos-local-plugin/tests/unit/install/hermes-provider-link.test.ts b/apps/memos-local-plugin/tests/unit/install/hermes-provider-link.test.ts index 81ab18a1b..d0de2f5bc 100644 --- a/apps/memos-local-plugin/tests/unit/install/hermes-provider-link.test.ts +++ b/apps/memos-local-plugin/tests/unit/install/hermes-provider-link.test.ts @@ -26,11 +26,39 @@ describe("Hermes provider install links", () => { it("PowerShell installer links both checkout-local and user-level provider paths", () => { const source = readFileSync(path.join(repoRoot, "install.ps1"), "utf8"); - expect(source).toContain('hermes\\plugins\\memory'); + expect(source).toContain('$UserPluginDir = Join-Path $HermesHome "plugins\\memory"'); expect(source).toContain('(Join-Path $PluginDir "memtensor")'); expect(source).toContain('(Join-Path $UserPluginDir "memtensor")'); }); + it("PowerShell installer resolves Hermes host data from HERMES_HOME", () => { + const source = readFileSync(path.join(repoRoot, "install.ps1"), "utf8"); + + expect(source).toContain("function Resolve-HermesHostHome"); + expect(source).toContain('$ConfiguredHome = $env:HERMES_HOME'); + expect(source).toContain("[Environment]::ExpandEnvironmentVariables"); + expect(source).toContain("[IO.Path]::IsPathRooted"); + expect(source).toContain('$HermesHome = Resolve-HermesHostHome'); + expect(source).toContain('$env:HERMES_HOME = $HermesHome'); + expect(source).toContain('$HasHermes = Test-Path $HermesHome'); + expect(source).toContain('$ConfigFile = Join-Path $HermesHome "config.yaml"'); + expect(source).toContain('$UserPluginDir = Join-Path $HermesHome "plugins\\memory"'); + expect(source).not.toContain('$ConfigFile = Join-Path $env:LOCALAPPDATA "hermes\\config.yaml"'); + expect(source).not.toContain('$UserPluginDir = Join-Path $env:LOCALAPPDATA "hermes\\plugins\\memory"'); + }); + + it("PowerShell installer keeps code and MemOS package paths under LocalAppData", () => { + const source = readFileSync(path.join(repoRoot, "install.ps1"), "utf8"); + + expect(source).toContain('$Prefix = Join-Path $env:LOCALAPPDATA "hermes\\memos-plugin"'); + expect(source).toContain( + '$VenvPy = Join-Path $env:LOCALAPPDATA "hermes\\hermes-agent\\venv\\Scripts\\python.exe"', + ); + expect(source).toContain( + '$DefaultPluginDir = Join-Path $env:LOCALAPPDATA "hermes\\hermes-agent\\plugins\\memory"', + ); + }); + it("PowerShell installer surfaces junction failures instead of swallowing them", () => { const source = readFileSync(path.join(repoRoot, "install.ps1"), "utf8"); diff --git a/apps/memos-local-plugin/tests/unit/server/http.test.ts b/apps/memos-local-plugin/tests/unit/server/http.test.ts index 613fcb30e..485ca8fa7 100644 --- a/apps/memos-local-plugin/tests/unit/server/http.test.ts +++ b/apps/memos-local-plugin/tests/unit/server/http.test.ts @@ -664,8 +664,10 @@ describe("HTTP server — REST routes", () => { it("imports Hermes native MEMORY.md in batches", async () => { const oldHome = process.env.HOME; + const oldHermesHome = process.env.HERMES_HOME; const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "memos-hermes-native-")); - const nativeDir = path.join(tmpHome, ".hermes", "memories"); + const hermesHome = path.join(tmpHome, "configured-hermes-home"); + const nativeDir = path.join(hermesHome, "memories"); fs.mkdirSync(nativeDir, { recursive: true }); fs.writeFileSync( path.join(nativeDir, "MEMORY.md"), @@ -673,6 +675,7 @@ describe("HTTP server — REST routes", () => { "utf8", ); process.env.HOME = tmpHome; + process.env.HERMES_HOME = hermesHome; const importBundle = core.importBundle as unknown as ReturnType; importBundle.mockImplementation(async (bundle: { traces?: unknown[] }) => ({ @@ -687,7 +690,7 @@ describe("HTTP server — REST routes", () => { const scanBody = (await scan.json()) as { found: boolean; total: number; path: string }; expect(scanBody.found).toBe(true); expect(scanBody.total).toBe(2); - expect(scanBody.path).toMatch(/\.hermes\/memories\/MEMORY\.md$/); + expect(scanBody.path).toBe(path.join(hermesHome, "memories", "MEMORY.md")); const run = await fetch(`${local.url}/api/v1/import/hermes-native/run`, { method: "POST", @@ -726,6 +729,11 @@ describe("HTTP server — REST routes", () => { } else { process.env.HOME = oldHome; } + if (oldHermesHome === undefined) { + delete process.env.HERMES_HOME; + } else { + process.env.HERMES_HOME = oldHermesHome; + } fs.rmSync(tmpHome, { recursive: true, force: true }); } }); diff --git a/apps/memos-local-plugin/tests/unit/server/import-export-path.test.ts b/apps/memos-local-plugin/tests/unit/server/import-export-path.test.ts new file mode 100644 index 000000000..dea09ea03 --- /dev/null +++ b/apps/memos-local-plugin/tests/unit/server/import-export-path.test.ts @@ -0,0 +1,46 @@ +import * as path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { resolveHermesNativeMemoryPath } from "../../../server/routes/import-export.js"; + +describe("Hermes native memory path", () => { + it("uses HERMES_HOME before platform defaults", () => { + const hermesHome = path.join(path.sep, "custom", "hermes-profile"); + + expect( + resolveHermesNativeMemoryPath({ + env: { + HERMES_HOME: hermesHome, + LOCALAPPDATA: path.join(path.sep, "local-app-data"), + }, + platform: "win32", + userHome: path.join(path.sep, "users", "alice"), + }), + ).toBe(path.join(hermesHome, "memories", "MEMORY.md")); + }); + + it("uses the Windows Hermes LocalAppData home by default", () => { + const localAppData = path.join(path.sep, "users", "alice", "AppData", "Local"); + + expect( + resolveHermesNativeMemoryPath({ + env: { LOCALAPPDATA: localAppData }, + platform: "win32", + userHome: path.join(path.sep, "users", "alice"), + }), + ).toBe(path.join(localAppData, "hermes", "memories", "MEMORY.md")); + }); + + it("keeps the Unix Hermes home fallback", () => { + const userHome = path.join(path.sep, "home", "alice"); + + expect( + resolveHermesNativeMemoryPath({ + env: {}, + platform: "linux", + userHome, + }), + ).toBe(path.join(userHome, ".hermes", "memories", "MEMORY.md")); + }); +}); diff --git a/apps/memos-local-plugin/viewer/src/stores/i18n.ts b/apps/memos-local-plugin/viewer/src/stores/i18n.ts index 8ce733f27..b0f683d79 100644 --- a/apps/memos-local-plugin/viewer/src/stores/i18n.ts +++ b/apps/memos-local-plugin/viewer/src/stores/i18n.ts @@ -779,7 +779,7 @@ const en = { "import.migrate.notFound": "No legacy database found.", "import.hermes.title": "Import Hermes native memories", "import.hermes.desc": - "Read ~/.hermes/memories/MEMORY.md and import each entry separated by a single § line into this memory plugin.", + "Read memories/MEMORY.md from the current Hermes home and import each entry separated by a single § line into this memory plugin.", "import.hermes.scan": "Scan native memory file", "import.hermes.run": "Import native memories", "import.hermes.stop": "Stop import", @@ -1645,7 +1645,7 @@ const zh: Record = { "import.migrate.notFound": "没有找到旧数据库。", "import.hermes.title": "导入 Hermes 原生记忆", "import.hermes.desc": - "读取 ~/.hermes/memories/MEMORY.md,并把用单独一行 § 分隔的每条记忆导入当前记忆插件。", + "读取当前 Hermes 主目录下的 memories/MEMORY.md,并把用单独一行 § 分隔的每条记忆导入当前记忆插件。", "import.hermes.scan": "扫描原生记忆文件", "import.hermes.run": "导入原生记忆", "import.hermes.stop": "停止导入", diff --git a/apps/memos-local-plugin/viewer/src/views/ImportView.tsx b/apps/memos-local-plugin/viewer/src/views/ImportView.tsx index b2d52858e..6719620f7 100644 --- a/apps/memos-local-plugin/viewer/src/views/ImportView.tsx +++ b/apps/memos-local-plugin/viewer/src/views/ImportView.tsx @@ -10,7 +10,7 @@ * hermes — the server picks the right path based on its own * `options.agent`) and copies rows into the V7 store. * - Hermes native import: when this viewer is attached to Hermes, - * batch-imports `~/.hermes/memories/MEMORY.md` entries separated + * batch-imports `$HERMES_HOME/memories/MEMORY.md` entries separated * by a single `§` line. * - OpenClaw native import: when attached to OpenClaw, batch-imports * OpenClaw agent session JSONL user/assistant messages. From 9656bfc4ec236156f66dbf389a354d32aa322266 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=81=E5=9C=A8=E5=90=B5=E7=9D=80=E5=90=83=E7=B3=96?= Date: Tue, 11 Aug 2026 18:05:53 +0800 Subject: [PATCH 2/6] fix: verify local embedding model downloads --- apps/memos-local-plugin/install.ps1 | 2 + apps/memos-local-plugin/install.sh | 2 + .../server/routes/models.ts | 42 +++++++++++++++++-- .../unit/install/local-model-notice.test.ts | 25 +++++++++++ .../tests/unit/server/models.test.ts | 26 ++++++++++++ .../viewer/src/stores/i18n.ts | 8 ++-- 6 files changed, 97 insertions(+), 8 deletions(-) create mode 100644 apps/memos-local-plugin/tests/unit/install/local-model-notice.test.ts create mode 100644 apps/memos-local-plugin/tests/unit/server/models.test.ts diff --git a/apps/memos-local-plugin/install.ps1 b/apps/memos-local-plugin/install.ps1 index 3391c3b05..0aa2ec950 100644 --- a/apps/memos-local-plugin/install.ps1 +++ b/apps/memos-local-plugin/install.ps1 @@ -237,6 +237,8 @@ function Deploy-Tarball { } Write-Success "Package extracted" Write-Success "Dependencies ready" + Write-Warn "Local MiniLM model weights are not bundled." + Write-Host " If embedding.provider is local, the first Viewer test or use downloads about 23 MB from Hugging Face." $DeploySucceeded = $true } catch { $DeployError = $_ diff --git a/apps/memos-local-plugin/install.sh b/apps/memos-local-plugin/install.sh index 9c208e15c..aba324a18 100755 --- a/apps/memos-local-plugin/install.sh +++ b/apps/memos-local-plugin/install.sh @@ -360,6 +360,8 @@ deploy_tarball_to_prefix() { fi fi success "Dependencies ready" + warn "Local MiniLM model weights are not bundled." + printf " ${DIM}If embedding.provider is local, the first Viewer test or use downloads about 23 MB from Hugging Face.${NC}\n" } # ─── Generate runtime config.yaml ───────────────────────────────────────── diff --git a/apps/memos-local-plugin/server/routes/models.ts b/apps/memos-local-plugin/server/routes/models.ts index 757aaed1d..fb186bf1a 100644 --- a/apps/memos-local-plugin/server/routes/models.ts +++ b/apps/memos-local-plugin/server/routes/models.ts @@ -19,6 +19,7 @@ * unsaved, and we don't want to accidentally persist a bad API key. * The test runs with values from the request body only. */ +import { createEmbedder, type Embedder } from "../../core/embedding/index.js"; import type { ServerDeps } from "../types.js"; import { parseJson, writeError, type Routes } from "./registry.js"; @@ -153,6 +154,42 @@ async function resolveSecrets( // ─── Embedding probe ───────────────────────────────────────────────────── +const DEFAULT_LOCAL_EMBEDDING_MODEL = "Xenova/all-MiniLM-L6-v2"; + +type LocalProbeEmbedder = Pick; +type LocalProbeEmbedderFactory = (model: string) => LocalProbeEmbedder; + +function createLocalProbeEmbedder(model: string): LocalProbeEmbedder { + return createEmbedder({ + provider: "local", + model, + dimensions: 384, + openRouter: false, + cache: { enabled: false, maxItems: 0 }, + }); +} + +/** + * Load the local model and execute a real embedding. The transformer pipeline + * is process-global, so intentionally keep it warm after a successful probe. + */ +export async function probeLocalEmbedding( + model: string, + create: LocalProbeEmbedderFactory = createLocalProbeEmbedder, +): Promise { + const resolvedModel = model.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL; + try { + const vector = await create(resolvedModel).embedOne("ping"); + if (vector.length === 0) throw new Error("no embedding vector returned"); + return vector.length; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new Error( + `Local embedding model download/load failed; check access to Hugging Face: ${message}`, + ); + } +} + async function probeEmbedding(req: TestRequest): Promise { const provider = req.provider ?? ""; const endpoint = normUrl(req.endpoint ?? ""); @@ -244,10 +281,7 @@ async function probeEmbedding(req: TestRequest): Promise { return first.length; } case "local": - // Local embedder requires the model file in-process; skip the - // HTTP probe and just acknowledge — the lifecycle check at - // `core.init` already validated the local provider. - return 0; + return probeLocalEmbedding(model); default: throw new Error(`unsupported embedding provider: ${provider}`); } diff --git a/apps/memos-local-plugin/tests/unit/install/local-model-notice.test.ts b/apps/memos-local-plugin/tests/unit/install/local-model-notice.test.ts new file mode 100644 index 000000000..cd96b9a50 --- /dev/null +++ b/apps/memos-local-plugin/tests/unit/install/local-model-notice.test.ts @@ -0,0 +1,25 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +const repoRoot = path.resolve(__dirname, "../../.."); + +describe("local embedding model download notice", () => { + it.each(["install.sh", "install.ps1"])("warns during %s installation", (file) => { + const source = readFileSync(path.join(repoRoot, file), "utf8"); + + expect(source).toContain("Local MiniLM model weights are not bundled"); + expect(source).toContain("Hugging Face"); + expect(source).toContain("23 MB"); + }); + + it("explains the first-use download in the Viewer", () => { + const source = readFileSync(path.join(repoRoot, "viewer/src/stores/i18n.ts"), "utf8"); + + expect(source).toContain("first test or use downloads about 23 MB from Hugging Face"); + expect(source).toContain("首次测试或使用时需从 Hugging Face 下载约 23 MB"); + expect(source).not.toContain("The bundled embedder"); + expect(source).not.toContain("插件内置嵌入模型"); + }); +}); diff --git a/apps/memos-local-plugin/tests/unit/server/models.test.ts b/apps/memos-local-plugin/tests/unit/server/models.test.ts new file mode 100644 index 000000000..43e292050 --- /dev/null +++ b/apps/memos-local-plugin/tests/unit/server/models.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it, vi } from "vitest"; + +import { probeLocalEmbedding } from "../../../server/routes/models.js"; + +describe("local embedding model probe", () => { + it("loads the default MiniLM model and verifies a real vector", async () => { + const embedOne = vi.fn(async () => Float32Array.from([0.1, 0.2, 0.3])); + const create = vi.fn(() => ({ embedOne })); + + await expect(probeLocalEmbedding("", create)).resolves.toBe(3); + expect(create).toHaveBeenCalledWith("Xenova/all-MiniLM-L6-v2"); + expect(embedOne).toHaveBeenCalledWith("ping"); + }); + + it("surfaces download/load guidance on failure", async () => { + const embedOne = vi.fn(async () => { + throw new Error("fetch failed"); + }); + + await expect( + probeLocalEmbedding("custom/minilm", () => ({ embedOne })), + ).rejects.toThrow( + "Local embedding model download/load failed; check access to Hugging Face: fetch failed", + ); + }); +}); diff --git a/apps/memos-local-plugin/viewer/src/stores/i18n.ts b/apps/memos-local-plugin/viewer/src/stores/i18n.ts index b0f683d79..94b038c98 100644 --- a/apps/memos-local-plugin/viewer/src/stores/i18n.ts +++ b/apps/memos-local-plugin/viewer/src/stores/i18n.ts @@ -856,7 +856,7 @@ const en = { "settings.tab.general": "General", "settings.warn.title": "Model configuration", "settings.warn.emb": - "The bundled embedder is small. For better recall we recommend a dedicated model (e.g. bge-m3).", + "The default local embedder is small and downloads on first use. For better recall we recommend a dedicated model (e.g. bge-m3).", "settings.warn.sum": "Summarizer is required — without it, task summaries and scoring fall back to crude heuristics.", "settings.warn.skill": @@ -869,7 +869,7 @@ const en = { "settings.embedding.title": "Embedding", "settings.embedding.desc": "Vector embedding model used by retrieval and deduplication.", "settings.embedding.localHint": - "Currently using built-in MiniLM-L6-v2 (384-dim, ~23 MB). Select another provider for better retrieval accuracy.", + "The local MiniLM-L6-v2 model runs on-device (384-dim); the first test or use downloads about 23 MB from Hugging Face. The Test button downloads and verifies it. Select another provider for better retrieval accuracy.", "settings.embedding.maintenance.title": "Embedding maintenance", "settings.embedding.maintenance.stats": "Ready {ready}/{total}; missing {missing}; dimension mismatch {mismatch}; current dim {dim}.", @@ -1715,7 +1715,7 @@ const zh: Record = { "settings.tab.hub": "团队分享", "settings.tab.general": "通用", "settings.warn.title": "模型配置提醒", - "settings.warn.emb": "插件内置嵌入模型较小。为获得更精准的记忆检索,建议配置 bge-m3 等专业嵌入模型。", + "settings.warn.emb": "默认本地嵌入模型较小,权重需在首次使用时下载。为获得更精准的记忆检索,建议配置 bge-m3 等专业嵌入模型。", "settings.warn.sum": "摘要模型为必填。若不配置,反思与奖励信号只能走粗糙启发式。", "settings.warn.skill": "技能诱导建议配置更强的推理模型以提升稳定性。", "settings.provider": "提供商", @@ -1726,7 +1726,7 @@ const zh: Record = { "settings.embedding.title": "嵌入模型", "settings.embedding.desc": "用于记忆检索与去重的向量嵌入模型。", "settings.embedding.localHint": - "当前使用内置 MiniLM-L6-v2(384 维,约 23 MB)。选择其他 Provider 可获得更精准的检索效果。", + "本地 MiniLM-L6-v2 在设备上运行(384 维);首次测试或使用时需从 Hugging Face 下载约 23 MB。“测试”按钮会下载并验证模型。选择其他 Provider 可获得更精准的检索效果。", "settings.embedding.maintenance.title": "向量维护", "settings.embedding.maintenance.stats": "可用 {ready}/{total};缺失 {missing};维度不匹配 {mismatch};当前维度 {dim}。", From 2113f61c0c975f0105434a11ab56a64b312b74d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=81=E5=9C=A8=E5=90=B5=E7=9D=80=E5=90=83=E7=B3=96?= Date: Tue, 11 Aug 2026 19:55:17 +0800 Subject: [PATCH 3/6] fix: refresh Windows viewer after config save --- apps/memos-local-plugin/server/http.ts | 15 ++++--- .../memos-local-plugin/server/routes/admin.ts | 20 +++++++-- .../server/routes/health.ts | 9 +++- .../server/routes/registry.ts | 2 +- apps/memos-local-plugin/server/types.ts | 2 + .../tests/unit/server/admin.test.ts | 21 +++++++-- .../tests/unit/server/http.test.ts | 6 ++- .../tests/unit/viewer/restart.test.ts | 44 ++++++++++++------- .../tests/unit/viewer/settings-save.test.ts | 31 +++++++++++++ .../viewer/src/components/RestartOverlay.tsx | 9 +++- .../viewer/src/settings-save.ts | 12 +++++ .../viewer/src/stores/health.ts | 2 + .../viewer/src/stores/i18n.ts | 6 ++- .../viewer/src/stores/restart.ts | 38 +++++++++++++++- .../viewer/src/views/SettingsView.tsx | 16 +++++-- 15 files changed, 194 insertions(+), 39 deletions(-) create mode 100644 apps/memos-local-plugin/tests/unit/viewer/settings-save.test.ts create mode 100644 apps/memos-local-plugin/viewer/src/settings-save.ts diff --git a/apps/memos-local-plugin/server/http.ts b/apps/memos-local-plugin/server/http.ts index 82a2b201d..b8e486d40 100644 --- a/apps/memos-local-plugin/server/http.ts +++ b/apps/memos-local-plugin/server/http.ts @@ -22,6 +22,7 @@ * no reverse proxy, no peer cores). */ +import { randomUUID } from "node:crypto"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import { rootLogger } from "../core/logger/index.js"; @@ -54,19 +55,23 @@ export async function startHttpServer( deps: ServerDeps, options: ServerOptions = {}, ): Promise { + const runtimeOptions: ServerOptions = { + ...options, + instanceId: options.instanceId?.trim() || randomUUID(), + }; const log = rootLogger.child({ channel: "server.http" }); - const host = options.host ?? "127.0.0.1"; - const port = options.port ?? 0; - const extraHeaders = options.extraHeaders ?? {}; + const host = runtimeOptions.host ?? "127.0.0.1"; + const port = runtimeOptions.port ?? 0; + const extraHeaders = runtimeOptions.extraHeaders ?? {}; - const routes = buildRoutes(deps, options); + const routes = buildRoutes(deps, runtimeOptions); const server = createServer(async (req, res) => { for (const [k, v] of Object.entries(extraHeaders)) { res.setHeader(k, v); } try { - await dispatch(req, res, routes, deps, options, log); + await dispatch(req, res, routes, deps, runtimeOptions, log); } catch (err) { const msg = err instanceof Error ? err.message : String(err); log.error("request.unhandled", { path: req.url, err: msg }); diff --git a/apps/memos-local-plugin/server/routes/admin.ts b/apps/memos-local-plugin/server/routes/admin.ts index 3089d937e..4daa693a6 100644 --- a/apps/memos-local-plugin/server/routes/admin.ts +++ b/apps/memos-local-plugin/server/routes/admin.ts @@ -115,7 +115,7 @@ export function registerAdminRoutes(routes: Routes, deps: ServerDeps, options: S return { ok: true, restarting: true, killedHermes }; }); - routes.set("POST /api/v1/admin/restart", async (_ctx) => { + routes.set("POST /api/v1/admin/restart", async (ctx) => { const agent = options.agent ?? "unknown"; if (agent === "openclaw") { const platform = options.lifecycle?.platform ?? process.platform; @@ -137,14 +137,28 @@ export function registerAdminRoutes(routes: Routes, deps: ServerDeps, options: S if (agent === "hermes") { const platform = options.lifecycle?.platform ?? process.platform; if (platform === "win32") { + // Drain SQLite/background work before the process exits. Windows does + // not deliver POSIX SIGTERM semantics reliably, so do not depend on a + // signal handler for graceful core shutdown here. + try { + await deps.core.shutdown(); + } catch { + // The process still needs to exit so the next Hermes launch can + // replace it with a config-fresh Viewer. + } + // The browser already has the manual handoff instructions by the time + // this response flushes. Stop the old Viewer afterwards so starting + // Hermes creates a genuinely fresh daemon with the saved config. + scheduleWindowsShutdownAfterResponse(ctx.res, options); return { ok: true, restarting: false, manualRestartRequired: true, platform, + instanceId: options.instanceId, message: - `Configuration saved. Close Hermes, run Stop-Process -Id ${process.pid} ` + - "in PowerShell to stop Memory Viewer, then start Hermes again.", + "Configuration saved. Close Hermes completely, then start Hermes again. " + + "Memory Viewer will reconnect automatically.", }; } const killed = await terminateHermesChat(); diff --git a/apps/memos-local-plugin/server/routes/health.ts b/apps/memos-local-plugin/server/routes/health.ts index 9dee2774c..c8a3dec54 100644 --- a/apps/memos-local-plugin/server/routes/health.ts +++ b/apps/memos-local-plugin/server/routes/health.ts @@ -6,12 +6,17 @@ * expected to be O(1) (cached). */ -import type { ServerDeps } from "../types.js"; +import type { ServerDeps, ServerOptions } from "../types.js"; import type { RouteContext, Routes } from "./registry.js"; -export function registerHealthRoutes(routes: Routes, deps: ServerDeps): void { +export function registerHealthRoutes( + routes: Routes, + deps: ServerDeps, + options: ServerOptions = {}, +): void { const serviceIdentity = { service: "memos-local-plugin", + instanceId: options.instanceId, }; routes.set("GET /api/v1/health", async () => { const health = await deps.core.health(); diff --git a/apps/memos-local-plugin/server/routes/registry.ts b/apps/memos-local-plugin/server/routes/registry.ts index 7adaf8c53..1c75dddc1 100644 --- a/apps/memos-local-plugin/server/routes/registry.ts +++ b/apps/memos-local-plugin/server/routes/registry.ts @@ -161,7 +161,7 @@ export function buildRoutes( options: ServerOptions, ): Routes { const routes = new Routes(); - registerHealthRoutes(routes, deps); + registerHealthRoutes(routes, deps, options); registerOverviewRoutes(routes, deps); registerSessionRoutes(routes, deps); registerMemoryRoutes(routes, deps, options); diff --git a/apps/memos-local-plugin/server/types.ts b/apps/memos-local-plugin/server/types.ts index ee5d6753d..720603a1b 100644 --- a/apps/memos-local-plugin/server/types.ts +++ b/apps/memos-local-plugin/server/types.ts @@ -17,6 +17,8 @@ import type { BridgeHealth, MemoryCore } from "../agent-contract/memory-core.js" import type { LogRecord } from "../agent-contract/log-record.js"; export interface ServerOptions { + /** Unique ID for this HTTP-server lifetime; generated by startHttpServer. */ + instanceId?: string; /** Network port to listen on. Defaults to 0 (random free port). */ port?: number; /** Hostname/interface to bind. Defaults to 127.0.0.1 (loopback only). */ diff --git a/apps/memos-local-plugin/tests/unit/server/admin.test.ts b/apps/memos-local-plugin/tests/unit/server/admin.test.ts index 014f3ac14..e8ba703b5 100644 --- a/apps/memos-local-plugin/tests/unit/server/admin.test.ts +++ b/apps/memos-local-plugin/tests/unit/server/admin.test.ts @@ -122,30 +122,43 @@ describe("admin lifecycle routes", () => { expect(requestShutdown).toHaveBeenCalledOnce(); }); - it("keeps an unsupervised Windows Hermes viewer alive for manual restart", async () => { + it("shuts down a Windows Hermes viewer after returning restart instructions", async () => { const requestShutdown = vi.fn(); + const shutdown = vi.fn().mockResolvedValue(undefined); const routes = new Routes(); + const res = makeResponse(); registerAdminRoutes( routes, - { core: {} as MemoryCore }, + { core: { shutdown } as unknown as MemoryCore }, { agent: "hermes", + instanceId: "viewer-old", lifecycle: { supervised: false, platform: "win32", requestShutdown }, }, ); const restart = routes.getExact("POST /api/v1/admin/restart"); - const result = await restart!({} as never); + const result = await restart!({ res } as never); expect(result).toMatchObject({ ok: true, restarting: false, manualRestartRequired: true, platform: "win32", + instanceId: "viewer-old", + message: expect.not.stringContaining("Stop-Process"), }); expect(spawnMock).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(500); + expect(shutdown).toHaveBeenCalledOnce(); + await vi.advanceTimersByTimeAsync(2_000); expect(requestShutdown).not.toHaveBeenCalled(); + + res.writableFinished = true; + res.emit("finish"); + await vi.advanceTimersByTimeAsync(299); + expect(requestShutdown).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(requestShutdown).toHaveBeenCalledOnce(); }); it("keeps Windows OpenClaw alive and returns manual gateway restart instructions", async () => { diff --git a/apps/memos-local-plugin/tests/unit/server/http.test.ts b/apps/memos-local-plugin/tests/unit/server/http.test.ts index 485ca8fa7..2ce77e9a5 100644 --- a/apps/memos-local-plugin/tests/unit/server/http.test.ts +++ b/apps/memos-local-plugin/tests/unit/server/http.test.ts @@ -235,7 +235,11 @@ describe("HTTP server — REST routes", () => { const r = await fetch(`${handle.url}/api/v1/health`); expect(r.status).toBe(200); const body = await r.json(); - expect(body).toMatchObject({ ok: true, version: "test" }); + expect(body).toMatchObject({ + ok: true, + version: "test", + instanceId: expect.any(String), + }); expect(core.health).toHaveBeenCalled(); }); diff --git a/apps/memos-local-plugin/tests/unit/viewer/restart.test.ts b/apps/memos-local-plugin/tests/unit/viewer/restart.test.ts index 574d3ee3e..7860a8a96 100644 --- a/apps/memos-local-plugin/tests/unit/viewer/restart.test.ts +++ b/apps/memos-local-plugin/tests/unit/viewer/restart.test.ts @@ -59,23 +59,37 @@ describe("viewer restart flow", () => { expect(fakeWindow.location.href).toMatch(/^\/\?_t=\d+$/); }); - it("stops polling when Windows requires a manual restart", async () => { - globalThis.fetch = vi.fn(async () => new Response(JSON.stringify({ - ok: true, - restarting: false, - manualRestartRequired: true, - platform: "win32", - message: "Close Hermes and start it again.", - }), { status: 200 })) as typeof fetch; + it("waits for a replacement instance after Windows requests a manual restart", async () => { + let healthChecks = 0; + globalThis.fetch = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => { + if (init?.method === "POST") { + return new Response(JSON.stringify({ + ok: true, + restarting: false, + manualRestartRequired: true, + platform: "win32", + instanceId: "viewer-old", + message: "Close Hermes and start it again.", + }), { status: 200 }); + } + healthChecks += 1; + if (healthChecks === 1) { + return new Response(JSON.stringify({ ok: true, instanceId: "viewer-old" }), { + status: 200, + }); + } + if (healthChecks === 2) throw new TypeError("viewer is down"); + return new Response(JSON.stringify({ ok: true, instanceId: "viewer-new" }), { + status: 200, + }); + }) as typeof fetch; - await triggerRestart(); + const restarting = triggerRestart(); + await vi.runAllTimersAsync(); + await restarting; - expect(globalThis.fetch).toHaveBeenCalledOnce(); - expect(restartState.value).toEqual({ - phase: "manualRestartRequired", - message: "Close Hermes and start it again.", - }); - expect(fakeWindow.location.href).toBe(""); + expect(healthChecks).toBe(3); + expect(fakeWindow.location.href).toMatch(/^\/?\?_t=\d+$/); }); it("shows manual restart instructions returned by Windows OpenClaw", async () => { diff --git a/apps/memos-local-plugin/tests/unit/viewer/settings-save.test.ts b/apps/memos-local-plugin/tests/unit/viewer/settings-save.test.ts new file mode 100644 index 000000000..00a5c30fb --- /dev/null +++ b/apps/memos-local-plugin/tests/unit/viewer/settings-save.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it, vi } from "vitest"; + +import { saveSettingsAndRestart } from "../../../viewer/src/settings-save"; + +describe("settings save flow", () => { + it("applies the saved server config before starting the restart", async () => { + const events: string[] = []; + const saved = { + embedding: { + provider: "local", + model: "Xenova/all-MiniLM-L6-v2", + }, + }; + const persist = vi.fn(async () => { + events.push("persist"); + return saved; + }); + const applySaved = vi.fn((value: typeof saved) => { + events.push("apply"); + expect(value).toBe(saved); + }); + const restart = vi.fn(async () => { + events.push("restart"); + }); + + await saveSettingsAndRestart(saved, persist, applySaved, restart); + + expect(events).toEqual(["persist", "apply", "restart"]); + expect(applySaved).toHaveBeenCalledWith(saved); + }); +}); diff --git a/apps/memos-local-plugin/viewer/src/components/RestartOverlay.tsx b/apps/memos-local-plugin/viewer/src/components/RestartOverlay.tsx index 9869c5beb..43b901f79 100644 --- a/apps/memos-local-plugin/viewer/src/components/RestartOverlay.tsx +++ b/apps/memos-local-plugin/viewer/src/components/RestartOverlay.tsx @@ -22,6 +22,9 @@ function FullScreenSpinner() { const message = overlayMessage(s.phase, agentType, s.message); const hint = overlayHint(s.phase, agentType); const terminal = isTerminalPhase(s.phase); + const dismissible = terminal && !( + s.phase === "manualRestartRequired" && agentType === "hermes" + ); return (
{message}
{hint}
- {terminal && ( + {dismissible && (