test(personality): regression coverage for #81791
Assert config.set and /personality preserve manual agent.system_prompt, and that startup resolution prefers display.personality. Co-authored-by: kyssta-exe <kyssta-exe@users.noreply.github.com> Co-authored-by: EMT5320 <1908937833@qq.com>
This commit is contained in:
@@ -22,11 +22,41 @@ class TestCLIPersonalityNone:
|
||||
|
||||
|
||||
|
||||
def test_neutral_clears_system_prompt(self):
|
||||
def test_set_persists_display_personality_not_system_prompt(self):
|
||||
cli = self._make_cli()
|
||||
with patch("cli.save_config_value", return_value=True):
|
||||
saves = []
|
||||
|
||||
def _save(key, value):
|
||||
saves.append((key, value))
|
||||
return True
|
||||
|
||||
with patch("cli.save_config_value", side_effect=_save):
|
||||
cli._handle_personality_command("/personality helpful")
|
||||
|
||||
assert cli.system_prompt == "You are helpful."
|
||||
assert ("display.personality", "helpful") in saves
|
||||
assert not any(k == "agent.system_prompt" for k, _ in saves)
|
||||
|
||||
def test_neutral_restores_manual_system_prompt_without_wiping_config(self):
|
||||
cli = self._make_cli()
|
||||
saves = []
|
||||
|
||||
def _save(key, value):
|
||||
saves.append((key, value))
|
||||
return True
|
||||
|
||||
with (
|
||||
patch("cli.save_config_value", side_effect=_save),
|
||||
patch(
|
||||
"hermes_cli.config.read_raw_config",
|
||||
return_value={"agent": {"system_prompt": "manual forever"}},
|
||||
),
|
||||
):
|
||||
cli._handle_personality_command("/personality neutral")
|
||||
assert cli.system_prompt == ""
|
||||
|
||||
assert cli.system_prompt == "manual forever"
|
||||
assert ("display.personality", "") in saves
|
||||
assert not any(k == "agent.system_prompt" for k, _ in saves)
|
||||
|
||||
|
||||
|
||||
@@ -59,7 +89,13 @@ class TestGatewayPersonalityNone:
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_clears_ephemeral_prompt(self, tmp_path):
|
||||
runner = self._make_runner()
|
||||
config_data = {"agent": {"personalities": {"helpful": "You are helpful."}}}
|
||||
config_data = {
|
||||
"agent": {
|
||||
"system_prompt": "manual forever",
|
||||
"personalities": {"helpful": "You are helpful."},
|
||||
},
|
||||
"display": {"personality": "helpful"},
|
||||
}
|
||||
config_file = tmp_path / "config.yaml"
|
||||
config_file.write_text(yaml.dump(config_data))
|
||||
|
||||
@@ -67,7 +103,32 @@ class TestGatewayPersonalityNone:
|
||||
event = self._make_event("default")
|
||||
result = await runner._handle_personality_command(event)
|
||||
|
||||
assert runner._ephemeral_system_prompt == ""
|
||||
saved = yaml.safe_load(config_file.read_text())
|
||||
assert saved["agent"]["system_prompt"] == "manual forever"
|
||||
assert saved.get("display", {}).get("personality", None) == ""
|
||||
assert runner._ephemeral_system_prompt == "manual forever"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_set_persists_display_personality_not_system_prompt(self, tmp_path):
|
||||
runner = self._make_runner()
|
||||
config_data = {
|
||||
"agent": {
|
||||
"system_prompt": "manual forever",
|
||||
"personalities": {"helpful": "You are helpful."},
|
||||
}
|
||||
}
|
||||
config_file = tmp_path / "config.yaml"
|
||||
config_file.write_text(yaml.dump(config_data))
|
||||
|
||||
with patch("gateway.run._hermes_home", tmp_path):
|
||||
event = self._make_event("helpful")
|
||||
result = await runner._handle_personality_command(event)
|
||||
|
||||
saved = yaml.safe_load(config_file.read_text())
|
||||
assert saved["agent"]["system_prompt"] == "manual forever"
|
||||
assert saved["display"]["personality"] == "helpful"
|
||||
assert runner._ephemeral_system_prompt == "You are helpful."
|
||||
assert "helpful" in result.lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Unit tests for resolve_ephemeral_system_prompt_from_config."""
|
||||
|
||||
from hermes_cli.config import (
|
||||
render_personality_prompt,
|
||||
resolve_ephemeral_system_prompt_from_config,
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_uses_named_personality_when_set():
|
||||
cfg = {
|
||||
"display": {"personality": "helpful"},
|
||||
"agent": {
|
||||
"system_prompt": "manual forever",
|
||||
"personalities": {"helpful": "You are helpful."},
|
||||
},
|
||||
}
|
||||
assert resolve_ephemeral_system_prompt_from_config(cfg) == "You are helpful."
|
||||
|
||||
|
||||
def test_resolve_falls_back_to_manual_system_prompt():
|
||||
cfg = {
|
||||
"display": {"personality": "none"},
|
||||
"agent": {
|
||||
"system_prompt": "manual forever",
|
||||
"personalities": {"helpful": "You are helpful."},
|
||||
},
|
||||
}
|
||||
assert resolve_ephemeral_system_prompt_from_config(cfg) == "manual forever"
|
||||
|
||||
|
||||
def test_resolve_ignores_unknown_personality_name():
|
||||
cfg = {
|
||||
"display": {"personality": "missing"},
|
||||
"agent": {
|
||||
"system_prompt": "manual forever",
|
||||
"personalities": {"helpful": "You are helpful."},
|
||||
},
|
||||
}
|
||||
assert resolve_ephemeral_system_prompt_from_config(cfg) == "manual forever"
|
||||
|
||||
|
||||
def test_resolve_renders_dict_personality():
|
||||
cfg = {
|
||||
"display": {"personality": "coder"},
|
||||
"agent": {
|
||||
"system_prompt": "manual forever",
|
||||
"personalities": {
|
||||
"coder": {
|
||||
"system_prompt": "You are an expert programmer.",
|
||||
"tone": "technical",
|
||||
"style": "concise",
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
resolved = resolve_ephemeral_system_prompt_from_config(cfg)
|
||||
assert "You are an expert programmer." in resolved
|
||||
assert "Tone: technical" in resolved
|
||||
assert "Style: concise" in resolved
|
||||
|
||||
|
||||
def test_render_personality_prompt_string():
|
||||
assert render_personality_prompt(" hi ") == "hi"
|
||||
@@ -7439,6 +7439,7 @@ def test_config_set_personality_preserves_history_and_returns_info(monkeypatch):
|
||||
history_version=4,
|
||||
)
|
||||
emits = []
|
||||
writes = []
|
||||
|
||||
server._sessions["sid"] = session
|
||||
monkeypatch.setattr(
|
||||
@@ -7450,7 +7451,11 @@ def test_config_set_personality_preserves_history_and_returns_info(monkeypatch):
|
||||
server, "_session_info", lambda agent, *a: {"model": getattr(agent, "model", "?")}
|
||||
)
|
||||
monkeypatch.setattr(server, "_emit", lambda *args: emits.append(args))
|
||||
monkeypatch.setattr(server, "_write_config_key", lambda path, value: None)
|
||||
monkeypatch.setattr(
|
||||
server,
|
||||
"_write_config_key",
|
||||
lambda path, value: writes.append((path, value)),
|
||||
)
|
||||
|
||||
resp = server.handle_request(
|
||||
{
|
||||
@@ -7473,6 +7478,8 @@ def test_config_set_personality_preserves_history_and_returns_info(monkeypatch):
|
||||
assert agent.ephemeral_system_prompt == "You are helpful."
|
||||
assert agent._cached_system_prompt == "old"
|
||||
assert ("session.info", "sid", {"model": "?"}) in emits
|
||||
assert ("display.personality", "helpful") in writes
|
||||
assert not any(path == "agent.system_prompt" for path, _ in writes)
|
||||
|
||||
|
||||
def test_compress_session_history_passes_force():
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""_make_agent resolves ephemeral prompt from display.personality."""
|
||||
|
||||
from contextlib import ExitStack
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
|
||||
def _runtime():
|
||||
return {
|
||||
"provider": None,
|
||||
"base_url": None,
|
||||
"api_key": None,
|
||||
"api_mode": None,
|
||||
"command": None,
|
||||
"args": None,
|
||||
"credential_pool": None,
|
||||
}
|
||||
|
||||
|
||||
def _call_make_agent(cfg):
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("tui_gateway.server._load_cfg", return_value=cfg))
|
||||
stack.enter_context(patch("tui_gateway.server._get_db", return_value=MagicMock()))
|
||||
stack.enter_context(
|
||||
patch("tui_gateway.server._load_tool_progress_mode", return_value="compact")
|
||||
)
|
||||
stack.enter_context(
|
||||
patch("tui_gateway.server._load_reasoning_config", return_value=None)
|
||||
)
|
||||
stack.enter_context(patch("tui_gateway.server._load_service_tier", return_value=None))
|
||||
stack.enter_context(
|
||||
patch("tui_gateway.server._load_enabled_toolsets", return_value=None)
|
||||
)
|
||||
stack.enter_context(
|
||||
patch(
|
||||
"tui_gateway.server._resolve_startup_runtime",
|
||||
return_value=("test-model", None),
|
||||
)
|
||||
)
|
||||
stack.enter_context(
|
||||
patch(
|
||||
"hermes_cli.runtime_provider.resolve_runtime_provider",
|
||||
return_value=_runtime(),
|
||||
)
|
||||
)
|
||||
mock_agent = stack.enter_context(patch("run_agent.AIAgent"))
|
||||
from tui_gateway.server import _make_agent
|
||||
|
||||
_make_agent("sid-1", "key-1")
|
||||
return mock_agent.call_args.kwargs
|
||||
|
||||
|
||||
def test_make_agent_uses_display_personality_when_set():
|
||||
cfg = {
|
||||
"display": {"personality": "helpful"},
|
||||
"agent": {
|
||||
"system_prompt": "manual forever",
|
||||
"personalities": {"helpful": "You are helpful."},
|
||||
},
|
||||
}
|
||||
kwargs = _call_make_agent(cfg)
|
||||
assert kwargs["ephemeral_system_prompt"] == "You are helpful."
|
||||
|
||||
|
||||
def test_make_agent_preserves_manual_prompt_without_personality():
|
||||
cfg = {
|
||||
"display": {"personality": "none"},
|
||||
"agent": {
|
||||
"system_prompt": "manual forever",
|
||||
"personalities": {"helpful": "You are helpful."},
|
||||
},
|
||||
}
|
||||
kwargs = _call_make_agent(cfg)
|
||||
assert kwargs["ephemeral_system_prompt"] == "manual forever"
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Reproduction: /personality (desktop config.set) clobbers agent.system_prompt.
|
||||
|
||||
The desktop/TUI backend exposes a `config.set key=personality` RPC
|
||||
(tui_gateway/server.py, the `@method("config.set")` handler). When the user
|
||||
selects a personality (the desktop "assistant style" picker routes here), the
|
||||
handler does:
|
||||
|
||||
_write_config_key("display.personality", pname)
|
||||
_write_config_key("agent.system_prompt", new_prompt) # <-- clobbers manual text
|
||||
|
||||
`agent.system_prompt` is the user's GLOBAL manual system prompt (read by
|
||||
`/prompt` and the CLI's ephemeral-prompt path). Overwriting it with a
|
||||
personality's text destroys the manual prompt. The sibling in-chat slash path
|
||||
(server.py `/personality` handler) does NOT touch `agent.system_prompt` -- it
|
||||
only sets the in-session `agent.ephemeral_system_prompt` -- so the two paths
|
||||
disagree.
|
||||
|
||||
Contract tested here:
|
||||
1. A pre-existing manual `agent.system_prompt` must survive selecting a
|
||||
personality via `config.set key=personality` (the global manual prompt is
|
||||
a SEPARATE concept from the per-session personality overlay).
|
||||
2. Selecting a different personality must not leave a stale personality's
|
||||
text in `agent.system_prompt`.
|
||||
|
||||
This test drives the REAL `_write_config_key` / `_save_cfg` against a temp
|
||||
HERMES_HOME config.yaml (no mocks of the persistence layer), so the captured
|
||||
config file is genuine proof of the write.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import tui_gateway.server as server
|
||||
import yaml
|
||||
|
||||
|
||||
MANUAL_PROMPT = "manual_prompt_1"
|
||||
PERSONALITY_1 = "personality_1"
|
||||
PERSONALITY_2 = "personality_2"
|
||||
|
||||
|
||||
def _seed_config(home: str) -> None:
|
||||
cfg = {
|
||||
"agent": {
|
||||
"system_prompt": MANUAL_PROMPT,
|
||||
"personalities": {
|
||||
"personality_1": PERSONALITY_1,
|
||||
"personality_2": PERSONALITY_2,
|
||||
},
|
||||
},
|
||||
"display": {"personality": "none"},
|
||||
}
|
||||
with open(os.path.join(home, "config.yaml"), "w", encoding="utf-8") as f:
|
||||
yaml.safe_dump(cfg, f)
|
||||
|
||||
|
||||
def _read_saved_system_prompt(home: str) -> str:
|
||||
with open(os.path.join(home, "config.yaml"), encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
return (data.get("agent", {}) or {}).get("system_prompt", "")
|
||||
|
||||
|
||||
def _set(params: dict) -> dict:
|
||||
return server._methods["config.set"]("rid-1", params)
|
||||
|
||||
|
||||
def _make_session(session_id: str):
|
||||
"""Mirror a live desktop session: real agent namespace + history buffer."""
|
||||
agent = MagicMock()
|
||||
agent.ephemeral_system_prompt = None
|
||||
return {
|
||||
"session_key": session_id,
|
||||
"agent": agent,
|
||||
"history": [],
|
||||
"history_version": 0,
|
||||
"history_lock": MagicMock(__enter__=lambda self: None, __exit__=lambda self, *a: None),
|
||||
}
|
||||
|
||||
|
||||
def _run(home: str, session_id: str = ""):
|
||||
"""Select `personality_1` via the desktop personality RPC.
|
||||
|
||||
We stub the live-session pivot (_apply_personality_to_session) because the
|
||||
bug under test is the *config write* at server.py:11328-11329, not the
|
||||
in-session marker injection. Keeping it real would require a fully-built
|
||||
agent; the write happens before it regardless.
|
||||
"""
|
||||
sid = session_id or "s1"
|
||||
session = _make_session(sid)
|
||||
with (
|
||||
patch.dict(
|
||||
server._sessions, {sid: session}, clear=False
|
||||
),
|
||||
patch.object(server, "_apply_personality_to_session", return_value=(False, None)),
|
||||
# The handler calls these for the live-session pivot; not under test.
|
||||
patch.object(server, "_persist_live_session_runtime"),
|
||||
patch.object(server, "_emit"),
|
||||
):
|
||||
resp = _set({"key": "personality", "value": "personality_1", "session_id": sid})
|
||||
return resp
|
||||
|
||||
|
||||
def test_personality_selection_preserves_manual_system_prompt(tmp_path, monkeypatch):
|
||||
"""Selecting a personality must NOT overwrite the manual agent.system_prompt."""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
# Force the server module to pick up the temp home for config reads/writes.
|
||||
monkeypatch.setattr(server, "_hermes_home", Path(tmp_path))
|
||||
monkeypatch.setattr(server, "_cfg_path", None)
|
||||
monkeypatch.setattr(server, "_cfg_cache", None)
|
||||
_seed_config(str(tmp_path))
|
||||
|
||||
resp = _run(str(tmp_path))
|
||||
|
||||
assert resp["result"]["value"] == "personality_1", resp
|
||||
# THE BUG: the manual system_prompt was overwritten by the personality.
|
||||
saved = _read_saved_system_prompt(str(tmp_path))
|
||||
assert saved == MANUAL_PROMPT, (
|
||||
"agent.system_prompt was clobbered by the personality selection.\n"
|
||||
f" expected (manual): {MANUAL_PROMPT!r}\n"
|
||||
f" got (personality): {saved!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_switching_personality_leaves_no_stale_text(tmp_path, monkeypatch):
|
||||
"""After choosing `personality_2`, agent.system_prompt must retain the manual prompt.
|
||||
|
||||
The bug: selecting any personality overwrites agent.system_prompt with that
|
||||
personality's text. So after `personality_1` then `personality_2`, the field
|
||||
holds `personality_2`'s text -- still NOT the user's manual prompt. The field
|
||||
should have been left untouched (the personality overlay belongs in the
|
||||
in-session ephemeral prompt, not the durable global system prompt).
|
||||
"""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
monkeypatch.setattr(server, "_hermes_home", Path(tmp_path))
|
||||
monkeypatch.setattr(server, "_cfg_path", None)
|
||||
monkeypatch.setattr(server, "_cfg_cache", None)
|
||||
_seed_config(str(tmp_path))
|
||||
|
||||
_run(str(tmp_path), session_id="a")
|
||||
# Now switch to a different personality.
|
||||
session = _make_session("a")
|
||||
with (
|
||||
patch.dict(
|
||||
server._sessions, {"a": session}, clear=False
|
||||
),
|
||||
patch.object(server, "_apply_personality_to_session", return_value=(False, None)),
|
||||
patch.object(server, "_persist_live_session_runtime"),
|
||||
patch.object(server, "_emit"),
|
||||
):
|
||||
resp = _set({"key": "personality", "value": "personality_2", "session_id": "a"})
|
||||
|
||||
assert resp["result"]["value"] == "personality_2", resp
|
||||
saved = _read_saved_system_prompt(str(tmp_path))
|
||||
assert saved == MANUAL_PROMPT, (
|
||||
"agent.system_prompt still holds a personality's text after switching "
|
||||
f"personalities; the manual prompt was lost.\n"
|
||||
f" expected (manual): {MANUAL_PROMPT!r}\n"
|
||||
f" got: {saved!r}"
|
||||
)
|
||||
Reference in New Issue
Block a user