The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(local-runtime): prefill progress in chat; endpoint ownership guard for profile collisions
emozilla2087aa77fe39
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 0aafb364ab1..84909835592 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -1052,15 +1052,18 @@ _DIRECT_API_ACTIVITY_HEARTBEAT_SECONDS = 15.0def _managed_local_load_notice(agent, api_kwargs: dict) -> "Optional[str]":- """'⏳ loading <model> into memory — N%' when the managed local server is- loading this request's model right now; None otherwise.+ """A live phase notice while the managed local server works before the+ first token, or None when neither phase (nor the managed server) applies:- A cold local model spends ~tens of seconds streaming weights off disk- before the first token can exist. Without this, that window renders as+ - "⏳ loading <model> into memory — N%" (weights streaming off disk;+ real per-tensor percent from the router's SSE stream)+ - "⚙ processing prompt — N of ~M tokens (P%)" (prefill; live counter+ from /slots, denominator estimated from the request body)++ A cold local model spends ~tens of seconds loading and a long-context+ turn spends tens more in prefill; without this, both windows render asthe generic "no output yet (provider may be slow or overloaded)" stall- warning — alarming copy for a healthy, expected phase. The progress- snapshot is fed by the router's SSE stream (per-tensor load callback),- so the percent is real, not inferred.+ warning — alarming copy for healthy, expected phases."""try:base = str(getattr(agent, "base_url", "") or "")@@ -1069,7 +1072,10 @@ def _managed_local_load_notice(agent, api_kwargs: dict) -> "Optional[str]":import json as _jsonfrom urllib.parse import urlparse- from hermes_cli.local_runtime.load_progress import get_loading_progress+ from hermes_cli.local_runtime.load_progress import (+ get_loading_progress,+ get_prefill_progress,+ )from hermes_cli.local_runtime.supervisor import state_pathstate = _json.loads(state_path().read_text(encoding="utf-8"))@@ -1078,12 +1084,23 @@ def _managed_local_load_notice(agent, api_kwargs: dict) -> "Optional[str]":return Nonemodel = str(api_kwargs.get("model", ""))progress = get_loading_progress().get(model)- if progress is None:- return None- return (- f"⏳ loading {model} into memory — {progress['percent']}% "- "(responses start once the model is loaded)"- )+ if progress is not None:+ return (+ f"⏳ loading {model} into memory — {progress['percent']}% "+ "(responses start once the model is loaded)"+ )+ prefill = get_prefill_progress(model)+ if prefill is not None:+ processed = int(prefill["processed"])+ total = estimate_request_context_tokens(api_kwargs)+ if total and total >= processed:+ pct = max(0, min(100, round(processed / total * 100)))+ return (+ f"⚙ processing prompt — {processed:,} of ~{total:,} "+ f"tokens ({pct}%)"+ )+ return f"⚙ processing prompt — {processed:,} tokens"+ return Noneexcept Exception: # noqa: BLE001 — a status nicety must never break a callreturn Nonediff --git a/apps/desktop/src/components/assistant-ui/thread/status.tsx b/apps/desktop/src/components/assistant-ui/thread/status.tsxindex 835fff41007..f3650946d0d 100644--- a/apps/desktop/src/components/assistant-ui/thread/status.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/status.tsx@@ -51,10 +51,11 @@ const HintText: FC<{ children: ReactNode }> = ({ children }) => (<span className={cn(SCAFFOLD_LABEL_CLASS, 'shimmer min-w-0 flex-1 truncate')}>{children}</span>)-/** Wait hint with a real progress bar for managed-local model loads. The- * percent comes from llama-server's per-tensor load callback (via the- * gateway's wait frames), so a determinate bar is honest — and a 40s cold- * load reads as visible progress instead of an alarming stall. */+/** Wait hint with a real progress bar for managed-local model loads and+ * prompt processing. The percents come from llama-server itself (per-tensor+ * load callback / live prefill counter, via the gateway's wait frames), so a+ * determinate bar is honest — a 40s cold load or a long prefill reads as+ * visible progress instead of an alarming stall. */const WaitHint: FC<{ hint: string }> = ({ hint }) => {const { t } = useI18n()const load = parseModelLoadWait(hint)@@ -63,18 +64,25 @@ const WaitHint: FC<{ hint: string }> = ({ hint }) => {return <HintText>{hint}</HintText>}+ const label =+ load.kind === 'load'+ ? t.assistant.thread.loadingLocalModel(load.model)+ : t.assistant.thread.processingPrompt(load.detail)+return (<span className="flex min-w-0 flex-1 items-center gap-2">- <span className={cn(SCAFFOLD_LABEL_CLASS, 'shimmer min-w-0 shrink truncate')}>- {t.assistant.thread.loadingLocalModel(load.model)}- </span>- <span className="h-1 w-24 shrink-0 overflow-hidden rounded-full bg-(--ui-bg-tertiary)">- <span- className="block h-full rounded-full bg-primary transition-[width] duration-500"- style={{ width: `${Math.max(2, load.percent)}%` }}- />- </span>- <span className={cn(SCAFFOLD_LABEL_CLASS, 'shrink-0 tabular-nums')}>{load.percent}%</span>+ <span className={cn(SCAFFOLD_LABEL_CLASS, 'shimmer min-w-0 shrink truncate')}>{label}</span>+ {load.percent !== null && (+ <>+ <span className="h-1 w-24 shrink-0 overflow-hidden rounded-full bg-(--ui-bg-tertiary)">+ <span+ className="block h-full rounded-full bg-primary transition-[width] duration-500"+ style={{ width: `${Math.max(2, load.percent)}%` }}+ />+ </span>+ <span className={cn(SCAFFOLD_LABEL_CLASS, 'shrink-0 tabular-nums')}>{load.percent}%</span>+ </>+ )}</span>)}diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 01e92a905df..85f060ea91d 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3266,6 +3266,7 @@ export const en: Translations = {showEarlier: 'Show earlier messages',loadingResponse: 'Hermes is loading a response',loadingLocalModel: model => `Loading ${model} into memory`,+ processingPrompt: detail => (detail ? `Processing prompt (${detail} tokens)` : 'Processing prompt'),resumeWhenBackgroundDone: count =>count === 1? 'Will resume when the background task finishes'diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 8e0e295f3f7..1ac2305daa3 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2822,6 +2822,7 @@ export interface Translations {showEarlier: stringloadingResponse: stringloadingLocalModel: (model: string) => string+ processingPrompt: (detail: string) => stringresumeWhenBackgroundDone: (count: number) => stringthinking: stringthought: stringdiff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 700f8db4b6d..7ab9213a5ac 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3424,6 +3424,7 @@ export const zh: Translations = {showEarlier: '显示更早的消息',loadingResponse: 'Hermes 正在加载回复',loadingLocalModel: model => `正在将 ${model} 载入内存`,+ processingPrompt: detail => (detail ? `正在处理提示词(${detail} 个 token)` : '正在处理提示词'),resumeWhenBackgroundDone: count =>count === 1 ? '后台任务完成后将自动继续' : `${count} 个后台任务完成后将自动继续`,thinking: '思考中',diff --git a/apps/desktop/src/store/provider-wait.test.ts b/apps/desktop/src/store/provider-wait.test.tsindex c4d3da3f79c..130655d9df4 100644--- a/apps/desktop/src/store/provider-wait.test.ts+++ b/apps/desktop/src/store/provider-wait.test.ts@@ -23,7 +23,25 @@ describe('parseModelLoadWait', () => {it('extracts model and percent from a load frame', () => {expect(parseModelLoadWait('⏳ loading Qwen3.6-35B-A3B-UD-Q4_K_M into memory — 42% (responses start once the model is loaded)')- ).toEqual({ model: 'Qwen3.6-35B-A3B-UD-Q4_K_M', percent: 42 })+ ).toEqual({ detail: '', kind: 'load', model: 'Qwen3.6-35B-A3B-UD-Q4_K_M', percent: 42 })+ })++ it('extracts counts and percent from a prefill frame', () => {+ expect(parseModelLoadWait('⚙ processing prompt — 12,288 of ~39,551 tokens (31%)')).toEqual({+ detail: '12,288 / ~39,551',+ kind: 'prefill',+ model: '',+ percent: 31+ })+ })++ it('parses a totalless prefill frame with a null percent (no fake bar)', () => {+ expect(parseModelLoadWait('⚙ processing prompt — 12,288 tokens')).toEqual({+ detail: '12,288',+ kind: 'prefill',+ model: '',+ percent: null+ })})it('returns null for every other wait frame', () => {@@ -36,3 +54,11 @@ describe('parseModelLoadWait', () => {expect(parseModelLoadWait('⏳ loading m into memory — 999%')?.percent).toBe(100)})})++describe('providerWaitText accepts prefill frames', () => {+ it('passes the ⚙ processing-prompt frame through', () => {+ const frame = '⚙ processing prompt — 12,288 of ~39,551 tokens (31%)'++ expect(providerWaitText(frame)).toBe(frame)+ })+})diff --git a/apps/desktop/src/store/provider-wait.ts b/apps/desktop/src/store/provider-wait.tsindex 95737ebf0a7..0d72a2d6bf2 100644--- a/apps/desktop/src/store/provider-wait.ts+++ b/apps/desktop/src/store/provider-wait.ts@@ -45,19 +45,44 @@ export function clearAllProviderWaits(): void {export function providerWaitText(text: string): string {const value = text.trim()- return /^(?:⏳|⚠|↻)\s*(?:waiting on|loading|no (?:output|response)|model returned)/i.test(value) ? value : ''+ return /^(?:⏳|⚠|↻|⚙)\s*(?:waiting on|loading|processing prompt|no (?:output|response)|model returned)/i.test(value)+ ? value+ : ''}-/** Parse a managed-local model-load frame ("⏳ loading <model> into memory —- * 43% …") into its parts, or null for every other wait frame. The percent is- * real (per-tensor load callback relayed by the server), so surfaces can- * render an honest determinate bar instead of prose. */-export function parseModelLoadWait(text: string): null | { model: string; percent: number } {- const m = /^⏳\s*loading\s+(.+?)\s+into memory\s+—\s+(\d{1,3})%/i.exec(text.trim())+/** Parse a managed-local progress frame into bar-renderable parts, or null+ * for every other wait frame. Two shapes, both minted by the backend's+ * _managed_local_load_notice (the percents are real — per-tensor load+ * callback / live prefill counter — so a determinate bar is honest):+ * "⏳ loading <model> into memory — 43% …" -> kind: 'load'+ * "⚙ processing prompt — 12,288 of ~39,551 tokens (31%)" -> kind: 'prefill'+ * A totalless prefill frame ("⚙ processing prompt — 12,288 tokens") parses+ * with percent: null and renders as text, not a bar. */+export function parseModelLoadWait(+ text: string+): null | { detail: string; kind: 'load' | 'prefill'; model: string; percent: null | number } {+ const value = text.trim()+ const load = /^⏳\s*loading\s+(.+?)\s+into memory\s+—\s+(\d{1,3})%/i.exec(value)++ if (load) {+ return {+ detail: '',+ kind: 'load',+ model: load[1],+ percent: Math.max(0, Math.min(100, Number(load[2])))+ }+ }- if (!m) {- return null+ const prefill = /^⚙\s*processing prompt\s+—\s+([\d,]+)(?:\s+of\s+~([\d,]+))?\s+tokens(?:\s+\((\d{1,3})%\))?/i.exec(value)++ if (prefill) {+ return {+ detail: prefill[2] ? `${prefill[1]} / ~${prefill[2]}` : prefill[1],+ kind: 'prefill',+ model: '',+ percent: prefill[3] === undefined ? null : Math.max(0, Math.min(100, Number(prefill[3])))+ }}- return { model: m[1], percent: Math.max(0, Math.min(100, Number(m[2]))) }+ return null}diff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.pyindex c4f581bce9c..dc266f52613 100644--- a/hermes_cli/local_runtime/endpoint.py+++ b/hermes_cli/local_runtime/endpoint.py@@ -52,12 +52,21 @@ def _state_endpoint() -> dict | None:if not base_url:return Noneendpoint = {"base_url": base_url, "api_key": state.get("api_key", "")}- # Healthy server: done.+ # Ownership proof: the stable port means a SECOND install (different+ # HERMES_HOME — a scratch profile, say) can own 127.0.0.1:18434 with a+ # different api key while this install's state file still points there.+ # /health is a public route, so it answers 200 for ANYONE's server —+ # trusting it alone sent every chat request and the load-progress+ # watcher at a server that 401s our key, silently. The recorded+ # supervisor pid is the tiebreaker: health-200 from a server whose+ # recorded child is DEAD is someone else's server, never a starting one.+ pid_ok = _pid_alive(int(state.get("pid") or 0))+ # Healthy server: done (when it's ours).try:health = base_url.rsplit("/v1", 1)[0] + "/health"with urllib.request.urlopen(health, timeout=3) as r:if r.status == 200:- return endpoint+ return endpoint if pid_ok else Noneexcept (urllib.error.URLError, OSError, TimeoutError):pass# Not healthy YET: a live supervisor child is a STARTING server (state@@ -65,7 +74,7 @@ def _state_endpoint() -> dict | None:# optimistically so readiness probes racing the boot see a configured# provider, not missing credentials. A dead pid is a crashed-without-# cleanup leftover — ignore it so requests don't blackhole.- if _pid_alive(int(state.get("pid") or 0)):+ if pid_ok:return endpointreturn Nonediff --git a/hermes_cli/local_runtime/load_progress.py b/hermes_cli/local_runtime/load_progress.pyindex fb0597000f3..db85854822e 100644--- a/hermes_cli/local_runtime/load_progress.py+++ b/hermes_cli/local_runtime/load_progress.py@@ -149,3 +149,42 @@ def get_loading_progress() -> dict[str, dict]:"percent": e["percent"]}for m, e in _snapshot.items()if now - e["ts"] < _STALE_ENTRY_TTL_S}+++def get_prefill_progress(model: str) -> "dict | None":+ """{"processed": tokens} while the managed server is prompt-processing+ for ``model``, or None (idle, decoding, unreachable, or foreign server).++ llama-server's /slots reports ``n_prompt_tokens_processed`` climbing in+ real time during prefill, but exposes no total — callers supply their+ own denominator (the request's estimated token count). Busiest+ processing slot wins when several are active: a parallel small request+ (title generation) freezes its counter during decode while a live+ prefill keeps climbing past it. One authenticated HTTP call per poll;+ every failure reads as "no prefill" — this is garnish, never load-+ bearing.+ """+ ep = _endpoint()+ if ep is None:+ return None+ base, key = ep+ try:+ from urllib.parse import quote++ req = urllib.request.Request(+ f"{base}/slots?model={quote(model)}",+ headers={"Authorization": f"Bearer {key}"})+ with urllib.request.urlopen(req, timeout=2) as r:+ slots = json.loads(r.read())+ except Exception: # noqa: BLE001+ return None+ best = 0+ for slot in slots if isinstance(slots, list) else []:+ if not slot.get("is_processing"):+ continue+ try:+ processed = int(slot.get("n_prompt_tokens_processed") or 0)+ except (TypeError, ValueError):+ continue+ best = max(best, processed)+ return {"processed": best} if best > 0 else Nonediff --git a/tests/hermes_cli/test_load_progress.py b/tests/hermes_cli/test_load_progress.pyindex d65540cdc49..69dd97f7e10 100644--- a/tests/hermes_cli/test_load_progress.py+++ b/tests/hermes_cli/test_load_progress.py@@ -124,14 +124,119 @@ def test_load_notice_for_managed_model(tmp_path, monkeypatch):def test_load_notice_matches_desktop_wait_filter():- """The notice must pass the desktop's providerWaitText regex (anchored- '⏳ loading') and parse under parseModelLoadWait's shape — pinned here- as a plain string contract so the two sides can't drift silently."""+ """The notices must pass the desktop's providerWaitText regex and parse+ under parseModelLoadWait's shapes — pinned here as plain string+ contracts so the two sides can't drift silently."""import re- sample = "⏳ loading Qwen3.6-35B-A3B-UD-Q4_K_M into memory — 43% (responses start once the model is loaded)"- # providerWaitText's accept set (mirrored from provider-wait.ts):- assert re.match(r"^(?:⏳|⚠|↻)\s*(?:waiting on|loading|no (?:output|response)|model returned)", sample)- # parseModelLoadWait's shape (mirrored):- m = re.match(r"^⏳\s*loading\s+(.+?)\s+into memory\s+—\s+(\d{1,3})%", sample)+ accept = r"^(?:⏳|⚠|↻|⚙)\s*(?:waiting on|loading|processing prompt|no (?:output|response)|model returned)"++ load = "⏳ loading Qwen3.6-35B-A3B-UD-Q4_K_M into memory — 43% (responses start once the model is loaded)"+ assert re.match(accept, load)+ m = re.match(r"^⏳\s*loading\s+(.+?)\s+into memory\s+—\s+(\d{1,3})%", load)assert m and m.group(1) == "Qwen3.6-35B-A3B-UD-Q4_K_M" and m.group(2) == "43"++ prefill = "⚙ processing prompt — 12,288 of ~39,551 tokens (31%)"+ assert re.match(accept, prefill)+ p = re.match(r"^⚙\s*processing prompt\s+—\s+([\d,]+)(?:\s+of\s+~([\d,]+))?\s+tokens(?:\s+\((\d{1,3})%\))?", prefill)+ assert p and p.group(1) == "12,288" and p.group(2) == "39,551" and p.group(3) == "31"++ bare = "⚙ processing prompt — 12,288 tokens"+ assert re.match(accept, bare)+ b = re.match(r"^⚙\s*processing prompt\s+—\s+([\d,]+)(?:\s+of\s+~([\d,]+))?\s+tokens(?:\s+\((\d{1,3})%\))?", bare)+ assert b and b.group(1) == "12,288" and b.group(2) is None and b.group(3) is None+++# ── prefill progress ─────────────────────────────────────────+++def test_prefill_notice_for_managed_model(tmp_path, monkeypatch):+ from agent.chat_completion_helpers import _managed_local_load_notice++ state = tmp_path / "server.json"+ state.write_text(json.dumps({"base_url": "http://127.0.0.1:18434/v1",+ "api_key": "k"}), encoding="utf-8")+ monkeypatch.setattr("hermes_cli.local_runtime.supervisor.state_path",+ lambda: state)+ monkeypatch.setattr(lp, "_ensure_watcher", lambda: None)+ # No load in flight; a prefill counter is live.+ monkeypatch.setattr(lp, "get_prefill_progress",+ lambda model: {"processed": 12288})+ import agent.chat_completion_helpers as cch++ monkeypatch.setattr(cch, "estimate_request_context_tokens",+ lambda kw: 39551)++ class _Agent:+ base_url = "http://127.0.0.1:18434/v1"++ notice = _managed_local_load_notice(_Agent(), {"model": "Qwen-Test"})+ assert notice == "⚙ processing prompt — 12,288 of ~39,551 tokens (31%)"++ # Counter past the estimate (estimator undercounted): drop the bogus+ # denominator rather than showing >100%.+ monkeypatch.setattr(cch, "estimate_request_context_tokens", lambda kw: 100)+ notice = _managed_local_load_notice(_Agent(), {"model": "Qwen-Test"})+ assert notice == "⚙ processing prompt — 12,288 tokens"+++def test_load_notice_outranks_prefill(tmp_path, monkeypatch):+ """While a load entry exists the load notice wins — prefill can't start+ before the model is resident, so a simultaneous claim means the load+ snapshot is authoritative."""+ from agent.chat_completion_helpers import _managed_local_load_notice++ state = tmp_path / "server.json"+ state.write_text(json.dumps({"base_url": "http://127.0.0.1:18434/v1",+ "api_key": "k"}), encoding="utf-8")+ monkeypatch.setattr("hermes_cli.local_runtime.supervisor.state_path",+ lambda: state)+ monkeypatch.setattr(lp, "_ensure_watcher", lambda: None)+ lp._apply_event("Qwen-Test", "status_change", _loading_event(0.5))+ monkeypatch.setattr(lp, "get_prefill_progress",+ lambda model: {"processed": 999})++ class _Agent:+ base_url = "http://127.0.0.1:18434/v1"++ notice = _managed_local_load_notice(_Agent(), {"model": "Qwen-Test"})+ assert notice is not None and notice.startswith("⏳ loading")+++def test_prefill_progress_reads_busiest_processing_slot(monkeypatch):+ monkeypatch.setattr(lp, "_endpoint", lambda: ("http://127.0.0.1:1", "k"))++ class _Resp:+ def __init__(self, payload):+ self._payload = payload++ def read(self):+ return json.dumps(self._payload).encode()++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ slots = [+ {"id": 0, "is_processing": False, "n_prompt_tokens_processed": 500},+ {"id": 1, "is_processing": True, "n_prompt_tokens_processed": 42},+ {"id": 2, "is_processing": True, "n_prompt_tokens_processed": 32768},+ ]+ monkeypatch.setattr(lp.urllib.request, "urlopen",+ lambda req, timeout=0: _Resp(slots))+ assert lp.get_prefill_progress("m") == {"processed": 32768}++ # Nothing processing -> None (idle slots' counters are leftovers).+ idle = [{"id": 0, "is_processing": False, "n_prompt_tokens_processed": 500}]+ monkeypatch.setattr(lp.urllib.request, "urlopen",+ lambda req, timeout=0: _Resp(idle))+ assert lp.get_prefill_progress("m") is None++ # Unreachable server -> None, never an exception.+ def _boom(req, timeout=0):+ raise OSError("refused")++ monkeypatch.setattr(lp.urllib.request, "urlopen", _boom)+ assert lp.get_prefill_progress("m") is Nonediff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.pyindex d8cc03f9de2..316ca9f4507 100644--- a/tests/hermes_cli/test_local_runtime.py+++ b/tests/hermes_cli/test_local_runtime.py@@ -10,6 +10,7 @@ exercise detection fingerprinting and supervisor logic without a GPU.from __future__ import annotationsimport json+import osimport threadingfrom http.server import BaseHTTPRequestHandler, HTTPServerfrom pathlib import Path@@ -359,7 +360,10 @@ def test_llamacpp_endpoint_resolution_prefers_managed(tmp_path, monkeypatch, stustate_path().parent.mkdir(parents=True, exist_ok=True)state_path().write_text(json.dumps({- "base_url": f"http://127.0.0.1:{port}/v1", "api_key": "sk-managed", "pid": 1,+ # A LIVE pid: the ownership guard treats health-200 + dead recorded+ # pid as a foreign server on our stable port (scratch-profile+ # collision), so claiming this test process models "our server".+ "base_url": f"http://127.0.0.1:{port}/v1", "api_key": "sk-managed", "pid": os.getpid(),}), encoding="utf-8")resolved = ep.resolve_llamacpp_endpoint()assert resolved == {"base_url": f"http://127.0.0.1:{port}/v1", "api_key": "sk-managed"}@@ -599,7 +603,9 @@ def test_switch_model_explicit_llamacpp_provider(tmp_path, monkeypatch, stub_serstate_path().parent.mkdir(parents=True, exist_ok=True)state_path().write_text(json.dumps({"base_url": f"http://127.0.0.1:{port}/v1",- "api_key": "sk-managed", "pid": 4242,+ # Live pid: ownership guard rejects health-200 + dead recorded pid+ # (foreign server on our stable port).+ "api_key": "sk-managed", "pid": os.getpid(),}), encoding="utf-8")from hermes_cli.model_switch import switch_model@@ -625,7 +631,10 @@ def test_runtime_provider_seam_llamacpp_alias(tmp_path, monkeypatch, stub_serverstate_path().parent.mkdir(parents=True, exist_ok=True)state_path().write_text(json.dumps({- "base_url": f"http://127.0.0.1:{port}/v1", "api_key": "sk-managed", "pid": 1,+ # A LIVE pid: the ownership guard treats health-200 + dead recorded+ # pid as a foreign server on our stable port (scratch-profile+ # collision), so claiming this test process models "our server".+ "base_url": f"http://127.0.0.1:{port}/v1", "api_key": "sk-managed", "pid": os.getpid(),}), encoding="utf-8")from hermes_cli.runtime_provider import _resolve_named_custom_runtime@@ -695,7 +704,7 @@ def test_bootstrap_reuses_running_server(tmp_path, monkeypatch, stub_server):monkeypatch.setattr(bootstrap, "_SUPERVISOR", None)state_path().parent.mkdir(parents=True, exist_ok=True)state_path().write_text(json.dumps({- "base_url": f"http://127.0.0.1:{port}/v1", "api_key": "k", "pid": 1,+ "base_url": f"http://127.0.0.1:{port}/v1", "api_key": "k", "pid": os.getpid(),}), encoding="utf-8")called = []