Skip to content

The agent that grows with you

fix(sessions): the low-disk prompt states what pruning will really do

Tekniumd5a62eda480b
diff --git a/apps/desktop/src/store/agent-notices.ts b/apps/desktop/src/store/agent-notices.ts
index 683855428ee..cae13347009 100644
--- a/apps/desktop/src/store/agent-notices.ts
+++ b/apps/desktop/src/store/agent-notices.ts
@@ -24,6 +24,8 @@ export interface AgentNoticePayload {
ttl_ms?: null | number
key?: string
id?: string
+ /** Full text behind a short `text` (the low-disk auto-prune question): the toast's expandable body. */
+ detail?: string
}
const LEVEL_TO_TOAST_KIND: Record<string, NotificationKind> = {
@@ -135,7 +137,8 @@ export function noticeToToast(payload: AgentNoticePayload | undefined): Notifica
id: payload?.key || payload?.id,
kind: LEVEL_TO_TOAST_KIND[payload?.level ?? 'info'] ?? 'info',
message: primary,
- meta
+ meta,
+ ...(payload?.detail?.trim() ? { detail: payload.detail.trim() } : {})
}
}
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 6cf4a26fa5f..628eda75322 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -5657,7 +5657,7 @@ export interface TodoUpdatedPayload {
todos: unknown[]
revision: number
}
-/** ``agent/credits_tracker.py::AgentNotice`` via notice_callback, and ``server._await_agent_ready``'s slow-build notice. ``level``: info | warn | error | success; ``kind``: sticky | ttl | agent. */
+/** ``agent/credits_tracker.py::AgentNotice`` via notice_callback, and ``server._await_agent_ready``'s slow-build notice. ``level``: info | warn | error | success; ``kind``: sticky | ttl | agent. ``detail``: the full text behind a short ``text`` (the low-disk auto-prune question): Desktop shows it in the toast's expandable body, the Ink TUI prints it into the transcript. */
export interface NotificationShowPayload {
text: string
level: string
@@ -5665,6 +5665,7 @@ export interface NotificationShowPayload {
ttl_ms?: number | null
key?: string | null
id?: string | null
+ detail?: string | null
}
export interface NotificationClearPayload {
key: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 55ea261ddd0..9c9d9c1b0ce 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -24190,7 +24190,7 @@
},
"NotificationShowPayload": {
"additionalProperties": false,
- "description": "``agent/credits_tracker.py::AgentNotice`` via notice_callback, and ``server._await_agent_ready``'s\nslow-build notice. ``level``: info | warn | error | success; ``kind``: sticky | ttl | agent.",
+ "description": "``agent/credits_tracker.py::AgentNotice`` via notice_callback, and ``server._await_agent_ready``'s\nslow-build notice. ``level``: info | warn | error | success; ``kind``: sticky | ttl | agent.\n``detail``: the full text behind a short ``text`` (the low-disk auto-prune question): Desktop shows\nit in the toast's expandable body, the Ink TUI prints it into the transcript.",
"properties": {
"text": {
"title": "Text",
@@ -24239,6 +24239,18 @@
],
"default": null,
"title": "Id"
+ },
+ "detail": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Detail"
}
},
"required": [
diff --git a/gateway/run_housekeeping_disk.py b/gateway/run_housekeeping_disk.py
index ffcc064a772..736d171b810 100644
--- a/gateway/run_housekeeping_disk.py
+++ b/gateway/run_housekeeping_disk.py
@@ -68,14 +68,15 @@ def maybe_post_auto_prune_prompt(runner, loop) -> None:
prune_advisor.snooze(Path(home))
-_LOCAL_NOTIFIED: set[str] = set()
+_LOCAL_NOTIFIED: dict[str, float] = {}
async def publish_local_auto_prune_notice(authority, ref) -> None:
"""Desktop / Ink TUI sessions (``AuthorityConnection.resume``): one sticky ``notification.show``
- per profile per gateway process while the disk is low and auto-prune is undecided. The classic
+ per profile per snooze window while the disk is low and auto-prune is undecided. The classic
CLI asks at its own startup, so its sessions are skipped here."""
import asyncio
+ import time
from gateway.config import Platform
from gateway.session_policy import policy_for_source
from hermes_cli import prune_advisor
@@ -92,16 +93,26 @@ async def publish_local_auto_prune_notice(authority, ref) -> None:
if policy is None or policy.source not in {"tui", "gui"}:
return
home = Path(authority.db.db_path).parent
- if str(home) in _LOCAL_NOTIFIED or prune_advisor.should_ask(home) is None:
+ if not prune_advisor.notice_due(home, _LOCAL_NOTIFIED):
return
- _LOCAL_NOTIFIED.add(str(home))
+ _LOCAL_NOTIFIED[str(home)] = time.time()
advice = await asyncio.to_thread(prune_advisor.advise, home)
if advice is None:
return
- live.event_stream.publish(ref.session_id, {
- "text": "⚠ " + " ".join(prune_advisor.advice_lines(advice)), "level": "warn", "kind": "sticky",
- "ttl_ms": None, "key": "sessions.auto_prune", "id": "sessions.auto_prune"},
- event_type="notification.show")
+ live.event_stream.publish(ref.session_id, prune_advisor.notice_payload(advice), event_type="notification.show")
+
+
+def clear_local_auto_prune_notice(runner, source) -> None:
+ """After /autoprune is answered on a local session, drop its sticky notice for that viewer."""
+ from gateway.config import Platform
+ from gateway.session_authorities import active_authority
+ from hermes_cli.prune_advisor import NOTICE_KEY
+ if getattr(source, "platform", None) != Platform.LOCAL:
+ return
+ authority = active_authority(runner)
+ live = authority.sessions.get(source.chat_id) if authority is not None else None
+ if live is not None:
+ live.event_stream.publish(source.chat_id, {"key": NOTICE_KEY}, event_type="notification.clear")
async def _post(runner, profile, home, advice) -> bool:
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.py
index 0327ccdc448..379a68cac8d 100644
--- a/gateway/slash_commands.py
+++ b/gateway/slash_commands.py
@@ -597,7 +597,11 @@ class GatewaySlashCommandsMixin(
async def _handle_autoprune_command(self, event: MessageEvent) -> str:
"""Handle /autoprune — the low-disk auto-prune decision (same text as the CLI)."""
- return _execute("autoprune", args=event.get_command_args()).text
+ reply = _execute("autoprune", args=event.get_command_args()).text
+ if event.get_command_args().strip().lower() in {"on", "off", "enable", "disable", "yes", "no", "later", "snooze"}:
+ from gateway.run_housekeeping_disk import clear_local_auto_prune_notice
+ clear_local_auto_prune_notice(self, event.source)
+ return reply
async def _handle_version_command(self, event: MessageEvent) -> str:
"""Handle /version — show the running Hermes Agent version."""
diff --git a/hermes_cli/prune_advisor.py b/hermes_cli/prune_advisor.py
index 50ade9fcd7e..299fed2e668 100644
--- a/hermes_cli/prune_advisor.py
+++ b/hermes_cli/prune_advisor.py
@@ -88,21 +88,34 @@ def disk_snapshot(home: Optional[Path] = None) -> Optional[DiskSnapshot]:
return DiskSnapshot(size, usage.free, usage.total)
-def _user_sessions_config(home: Optional[Path]) -> Optional[dict]:
- """The ``sessions:`` block of *home*'s own config.yaml ({} when absent); None when unreadable."""
- import hermes_yaml as yaml
- from hermes_cli.config import read_user_config_raw
+def _effective_sessions(home: Optional[Path]) -> Optional[dict]:
+ """*home*'s ``sessions:`` block as maintenance sees it (user file, ``${VAR}`` expansion, managed
+ overlay; no defaults merged) or None when the file cannot be read. Read through *home*'s own
+ config path, so gateway housekeeping gets each served profile's values, not the caller's."""
+ from hermes_cli.config_effective import load_user_config_effective
try:
- sessions = read_user_config_raw(_home(home) / "config.yaml").get("sessions")
- except (OSError, ValueError, yaml.YAMLError):
+ sessions = load_user_config_effective(_home(home) / "config.yaml", fail_closed=True).get("sessions")
+ except Exception as exc: # health: allow BLE001 -- any parse/read failure means "unreadable": never ask on it
+ logger.debug("auto-prune advice: config unreadable: %s", exc, exc_info=True)
return None
return sessions if isinstance(sessions, dict) else {}
+def _retention_days(sessions: dict) -> int:
+ """Same coercion maintenance applies (``int(...)``); an unusable value reads as the default."""
+ try:
+ days = int(sessions.get("retention_days", 90))
+ except (TypeError, ValueError):
+ return 90
+ return days if days >= 0 else 90
+
+
def undecided(home: Optional[Path] = None) -> bool:
- """True while the user's own config.yaml has no ``sessions.auto_prune`` (default not chosen)."""
- sessions = _user_sessions_config(home)
- return sessions is not None and "auto_prune" not in sessions # unreadable config: never nag on it
+ """True while neither the user's config nor an administrator's managed layer sets
+ ``sessions.auto_prune``. A managed value is already decided: asking would promise a choice the
+ user cannot make."""
+ sessions = _effective_sessions(home)
+ return sessions is not None and "auto_prune" not in sessions
def _snooze_path(home: Optional[Path]) -> Path:
@@ -141,9 +154,8 @@ def advise(home: Optional[Path] = None) -> Optional[Advice]:
return None
# Read the settings from THIS home's config: gateway housekeeping calls this for every served
# profile without entering its scope. Only an explicit key differs from the defaults here.
- sessions = _user_sessions_config(home) or {}
- retention = sessions.get("retention_days", 90)
- retention = retention if isinstance(retention, int) and retention >= 0 else 90
+ sessions = _effective_sessions(home) or {}
+ retention = _retention_days(sessions)
prunable = total = prunable_msgs = total_msgs = 0
estimate_ok = True
try:
@@ -205,11 +217,41 @@ def advice_lines(advice: Advice, *, command_prefix: str = "/") -> list[str]:
return lines
+NOTICE_KEY = "sessions.auto_prune"
+
+
+def notice_payload(advice: Advice) -> dict:
+ """``notification.show`` payload for TUI/Desktop: a short status-line ``text`` plus the full
+ question in ``detail`` (Desktop's expandable toast body; Ink prints it into the transcript)."""
+ d = advice.disk
+ return {"text": f"⚠ Low disk ({_gb(d.free_bytes)} free) · /autoprune on|off|later",
+ "detail": "\n".join(advice_lines(advice)), "level": "warn", "kind": "sticky", "ttl_ms": None,
+ "key": NOTICE_KEY, "id": NOTICE_KEY}
+
+
+def notice_due(home: Optional[Path], shown: dict) -> bool:
+ """Per-process dedup that re-arms: a home already noticed is due again once the gate passes
+ and a full snooze window has gone by since (so ``later`` really asks again in a week)."""
+ if should_ask(home) is None:
+ return False
+ last = shown.get(str(_home(home)))
+ return last is None or time.time() - last >= SNOOZE_SECONDS
+
+
+def managed() -> bool:
+ """True when an administrator pins ``sessions.auto_prune`` (the user cannot change it)."""
+ from hermes_cli import managed_scope
+ return managed_scope.is_key_managed("sessions.auto_prune")
+
+
def decide(enable: bool, home: Optional[Path] = None) -> bool:
- """Persist the user's answer as an explicit ``sessions.auto_prune``; ends the prompt for good."""
+ """Persist the user's answer as an explicit ``sessions.auto_prune``; ends the prompt for good.
+ False when the save failed or did not take effect (an administrator-managed value wins)."""
import hermes_yaml as yaml
from hermes_constants import mkdir_under_hermes_home
from utils import atomic_roundtrip_yaml_update
+ if managed():
+ return False
path = _home(home) / "config.yaml"
try:
mkdir_under_hermes_home(path.parent)
@@ -221,30 +263,35 @@ def decide(enable: bool, home: Optional[Path] = None) -> bool:
_snooze_path(home).unlink(missing_ok=True)
except OSError:
pass
- return True
+ return bool((_effective_sessions(home) or {}).get("auto_prune")) == bool(enable)
+
+
+_SAVE_FAILED = "Could not save sessions.auto_prune; check disk space and config.yaml permissions."
def run_command(args: str, home: Optional[Path] = None) -> str:
"""``/autoprune [on|off|later|status]`` — the one handler behind the CLI, TUI, Desktop and
messaging surfaces."""
- from hermes_cli.config import load_config_readonly
arg = (args or "").strip().lower()
+ sessions = _effective_sessions(home) or {}
+ state = "on" if sessions.get("auto_prune") else "off"
+ if arg in {"on", "off", "enable", "disable", "yes", "no", "later", "snooze"} and managed():
+ return f"Auto-prune is {state}, set by your administrator; it cannot be changed here."
if arg in {"on", "enable", "yes"}:
return ("Auto-prune is on: ended sessions inactive past retention_days are deleted once a day."
- if decide(True, home) else "Could not save sessions.auto_prune; check config.yaml permissions.")
+ if decide(True, home) else _SAVE_FAILED)
if arg in {"off", "disable", "no"}:
return ("Auto-prune is off and you will not be asked again. `hermes sessions prune` still works any time."
- if decide(False, home) else "Could not save sessions.auto_prune; check config.yaml permissions.")
+ if decide(False, home) else _SAVE_FAILED)
if arg in {"later", "snooze"}:
snooze(home)
return "OK, I'll ask again in a week if the disk is still low."
- sessions = (load_config_readonly() or {}).get("sessions") or {}
- state = "on" if sessions.get("auto_prune") else "off"
- chosen = "default" if undecided(home) else "your setting"
+ chosen = ("set by your administrator" if managed() else
+ "default" if "auto_prune" not in sessions else "your setting")
snap = disk_snapshot(home)
disk = (f" state.db {_gb(snap.db_bytes)}; {_gb(snap.free_bytes)} free of {_gb(snap.total_bytes)}"
f"{' (low)' if snap.low else ''}.") if snap else ""
- return (f"Auto-prune is {state} ({chosen}), retention {sessions.get('retention_days', 90)} days.{disk} "
+ return (f"Auto-prune is {state} ({chosen}), retention {_retention_days(sessions)} days.{disk} "
"Usage: /autoprune on | off | later")
@@ -267,7 +314,7 @@ def offer_interactive(*, cprint, ask=input) -> Optional[bool]:
if answer in {"y", "yes", "n", "no"}:
enable = answer.startswith("y")
if not decide(enable):
- cprint(" Could not save sessions.auto_prune; check disk space and config.yaml permissions.")
+ cprint(f" {_SAVE_FAILED}")
return None
cprint(" ✓ sessions.auto_prune: true" if enable else
" ✓ sessions.auto_prune: false. You won't be asked again.")
diff --git a/tests/hermes_cli/test_prune_advisor.py b/tests/hermes_cli/test_prune_advisor.py
index 69b488f3c1d..04b72d608d9 100644
--- a/tests/hermes_cli/test_prune_advisor.py
+++ b/tests/hermes_cli/test_prune_advisor.py
@@ -60,6 +60,39 @@ def test_prompt_says_pruning_will_not_help_when_nothing_is_old_enough(home, monk
advice = prune_advisor.advise(home)
assert advice.prunable_sessions == 1
assert "will not help" not in "\n".join(prune_advisor.advice_lines(advice))
- # The estimate reads THIS home's settings; an explicit 0-day retention is kept, not defaulted.
- (home / "config.yaml").write_text("sessions:\n retention_days: 0\n", encoding="utf-8")
- assert prune_advisor.advise(home).retention_days == 0
+ # Retention is read the way maintenance reads it (effective config, int()): a quoted or
+ # env-referenced 0 must not be described as the 90-day default.
+ monkeypatch.setenv("KEEP_DAYS", "0")
+ for value in ("0", '"0"', "${KEEP_DAYS}"):
+ (home / "config.yaml").write_text(f"sessions:\n retention_days: {value}\n", encoding="utf-8")
+ assert prune_advisor.advise(home).retention_days == 0, value
+
+
+def test_admin_managed_setting_is_never_asked_nor_overwritten(home, monkeypatch, tmp_path):
+ """An administrator-pinned auto_prune is already decided: no prompt, and /autoprune off must
+ not claim to have turned pruning off while the managed true still applies."""
+ from hermes_cli import managed_scope
+ managed = tmp_path / "managed"
+ managed.mkdir()
+ (managed / "config.yaml").write_text("sessions:\n auto_prune: true\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))
+ managed_scope.invalidate_managed_cache()
+ _disk(monkeypatch, free_gb=1)
+ try:
+ assert prune_advisor.should_ask(home) is None
+ reply = prune_advisor.run_command("off", home)
+ assert "administrator" in reply
+ cfg = home / "config.yaml"
+ assert not cfg.exists() or "auto_prune" not in cfg.read_text(encoding="utf-8-sig")
+ finally:
+ managed_scope.invalidate_managed_cache()
+
+
+def test_later_re_arms_the_local_notice_after_the_snooze_window(home, monkeypatch):
+ _disk(monkeypatch, free_gb=1)
+ shown: dict = {}
+ assert prune_advisor.notice_due(home, shown)
+ shown[str(home)] = time.time()
+ assert not prune_advisor.notice_due(home, shown) # same process, same window: once
+ shown[str(home)] = time.time() - prune_advisor.SNOOZE_SECONDS - 1
+ assert prune_advisor.notice_due(home, shown) # a week later it asks again
diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.py
index 813d21762c7..563bb13679b 100644
--- a/tui_gateway/contracts/events.py
+++ b/tui_gateway/contracts/events.py
@@ -420,7 +420,9 @@ event("todo.updated", TodoUpdatedPayload, doc="Full todo snapshot after a todo t
class NotificationShowPayload(Payload):
"""``agent/credits_tracker.py::AgentNotice`` via notice_callback, and ``server._await_agent_ready``'s
- slow-build notice. ``level``: info | warn | error | success; ``kind``: sticky | ttl | agent."""
+ slow-build notice. ``level``: info | warn | error | success; ``kind``: sticky | ttl | agent.
+ ``detail``: the full text behind a short ``text`` (the low-disk auto-prune question): Desktop shows
+ it in the toast's expandable body, the Ink TUI prints it into the transcript."""
text: str
level: str
@@ -428,6 +430,7 @@ class NotificationShowPayload(Payload):
ttl_ms: int | None = None
key: str | None = None
id: str | None = None
+ detail: str | None = None
class NotificationClearPayload(Payload):
diff --git a/tui_gateway/methods_slash.py b/tui_gateway/methods_slash.py
index e02a0c7260d..1836e8464e4 100644
--- a/tui_gateway/methods_slash.py
+++ b/tui_gateway/methods_slash.py
@@ -438,6 +438,13 @@ def _mirror_stop(sid, session, agent, arg) -> None:
# name → mirror(sid, session, agent, arg); a falsy return means "no warning".
+def _mirror_autoprune(sid, session, agent, arg) -> str:
+ """An answered low-disk question drops its sticky notice (``later`` too: it re-arms in a week)."""
+ if arg:
+ _emit("notification.clear", sid, {"key": "sessions.auto_prune"})
+ return ""
+
+
_SLASH_MIRRORS = {
"model": lambda sid, session, agent, arg: (
_apply_model_switch(sid, session, arg).get("warning", "") if arg and agent else ""),
@@ -445,7 +452,8 @@ _SLASH_MIRRORS = {
"compress": lambda sid, session, agent, arg: (
_compress_live_with_feedback(sid, session, agent, arg, snapshot_kwargs=False) if agent else ""),
"fast": _mirror_fast,
- "reload-mcp": _mirror_reload_mcp, "stop": _mirror_stop}
+ "reload-mcp": _mirror_reload_mcp, "stop": _mirror_stop,
+ "autoprune": _mirror_autoprune}
def _compute_host_slash(sid: str, session: dict, name: str, command: str) -> tuple[str, str]:
diff --git a/tui_gateway/session_registry.py b/tui_gateway/session_registry.py
index 50c69cf062f..17af1b94a3e 100644
--- a/tui_gateway/session_registry.py
+++ b/tui_gateway/session_registry.py
@@ -364,26 +364,24 @@ def _init_session(
_schedule_mcp_late_refresh(sid, agent)
-_AUTO_PRUNE_NOTIFIED: set[str] = set()
+_AUTO_PRUNE_NOTIFIED: dict[str, float] = {}
def _maybe_notify_auto_prune(sid: str, profile_home: str | None) -> None:
- """Low disk + auto-prune never decided: one sticky notice (TUI status line / Desktop toast)
- per profile per process, on session create and cold resume. The cheap gate runs inline;
+ """Low disk + auto-prune never decided: a sticky notice (TUI status line / Desktop toast) per
+ profile per snooze window, on session create and cold resume. The cheap gate runs inline;
the DB estimate runs off-thread."""
from hermes_cli import prune_advisor
from hermes_constants import get_hermes_home
home = Path(profile_home) if profile_home else get_hermes_home()
- if str(home) in _AUTO_PRUNE_NOTIFIED or prune_advisor.should_ask(home) is None:
+ if not prune_advisor.notice_due(home, _AUTO_PRUNE_NOTIFIED):
return
- _AUTO_PRUNE_NOTIFIED.add(str(home))
+ _AUTO_PRUNE_NOTIFIED[str(home)] = time.time()
def _work() -> None:
advice = prune_advisor.advise(home)
if advice is not None:
- _emit("notification.show", sid, {
- "text": "⚠ " + " ".join(prune_advisor.advice_lines(advice)), "level": "warn",
- "kind": "sticky", "ttl_ms": None, "key": "sessions.auto_prune", "id": "sessions.auto_prune"})
+ _emit("notification.show", sid, prune_advisor.notice_payload(advice))
from agent.memory_provider import spawn_context_thread
spawn_context_thread(_work, name="auto-prune-advice").start()
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index 2aa379a61ee..fe019aea870 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -1041,6 +1041,29 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
})
}
+ type NoticeEventPayload = Extract<AnyGatewayEvent, { type: 'notification.show' }>['payload']
+
+ const showGatewayNotice = (p: NoticeEventPayload) => {
+ if (!p?.text) {
+ return
+ }
+
+ // A notice with a full question (the low-disk auto-prune prompt) prints it into the
+ // transcript once: the status slot is one truncated line and would drop the commands.
+ if (typeof p.detail === 'string' && p.detail.trim()) {
+ sys(p.detail)
+ }
+
+ turnController.showNotice({
+ id: p.id ?? undefined,
+ key: p.key ?? undefined,
+ kind: p.kind === 'ttl' ? 'ttl' : 'sticky',
+ level: isNoticeLevel(p.level) ? p.level : 'info',
+ text: p.text,
+ ttl_ms: p.ttl_ms ?? null
+ })
+ }
+
return (ev: AnyGatewayEvent) => {
const sid = getUiState().sid
@@ -1216,20 +1239,7 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
// wire and stays snake_case in UiState.notice (no mapping layer). The
// text already carries its own glyph; turnController decides whether to
// show now or hold until turn end (FaceTicker wins while busy).
- const p = ev.payload
-
- if (!p?.text) {
- return
- }
-
- turnController.showNotice({
- id: p.id ?? undefined,
- key: p.key ?? undefined,
- kind: p.kind === 'ttl' ? 'ttl' : 'sticky',
- level: isNoticeLevel(p.level) ? p.level : 'info',
- text: p.text,
- ttl_ms: p.ttl_ms ?? null
- })
+ showGatewayNotice(ev.payload)
return
}