Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(im): render concise status bubble regardless of show_message_types (#750)

Qi Qi8ab61efce02c
diff --git a/core/controller.py b/core/controller.py
index 36b6608ad..e36967ff2 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -157,6 +157,23 @@ def _target_agent_variant(value: Any, backend: Any = None, agent_name: Any = Non
return None if variant in sentinel_values else variant
+def _refresh_status_bubble_config(controller: Any) -> None:
+ """Best-effort, mtime-guarded reload so Web UI changes to the status-bubble
+ settings (progress style + heartbeat/no-output thresholds) take effect for
+ turns that never pass through an IM inbound handler first (e.g. scheduled /
+ background agent runs), where nothing else calls ``_refresh_config_from_disk``
+ before the getters read ``controller.config``.
+
+ Implemented as a module-level helper taking the controller explicitly and
+ resolving the reload via ``getattr`` so lightweight test stubs that invoke the
+ getters unbound (a bare ``SimpleNamespace`` self) simply skip the refresh
+ instead of raising ``AttributeError``.
+ """
+ refresh = getattr(controller, "_refresh_config_from_disk", None)
+ if callable(refresh):
+ refresh()
+
+
class Controller:
"""Main controller that coordinates all bot operations"""
@@ -499,7 +516,8 @@ class Controller:
Called on every ``_t()`` invocation (guarded by mtime check).
Refreshes: language, show_duration, ack_mode, include_time_info, include_user_info,
- reply_enhancements, and mutable platform message filters.
+ reply_enhancements, agent_progress_style, agent_status_heartbeat_ms,
+ agent_status_no_output_ms, and mutable platform message filters.
"""
try:
config_path = paths.get_config_path()
@@ -516,6 +534,9 @@ class Controller:
self.config.include_time_info = v2_config.include_time_info
self.config.include_user_info = v2_config.include_user_info
self.config.reply_enhancements = v2_config.reply_enhancements
+ self.config.agent_progress_style = v2_config.agent_progress_style
+ self.config.agent_status_heartbeat_ms = v2_config.agent_status_heartbeat_ms
+ self.config.agent_status_no_output_ms = v2_config.agent_status_no_output_ms
self.config.resource_governance = v2_config.runtime.resource_governance
governor = getattr(self, "_agent_resource_governor", None)
if governor is not None:
@@ -903,6 +924,7 @@ class Controller:
Currently a global config setting; per-channel overrides can layer on top
here later without touching the dispatcher.
"""
+ _refresh_status_bubble_config(self)
value = getattr(self.config, "agent_progress_style", DEFAULT_AGENT_PROGRESS_STYLE)
return value if value in ("concise", "verbose", "off") else DEFAULT_AGENT_PROGRESS_STYLE
@@ -926,10 +948,12 @@ class Controller:
return self.get_progress_style_for_context(context) == "concise"
def get_heartbeat_interval_ms_for_context(self, context: MessageContext) -> int:
+ _refresh_status_bubble_config(self)
value = getattr(self.config, "agent_status_heartbeat_ms", 15000)
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 15000
def get_no_output_hint_after_ms_for_context(self, context: MessageContext) -> int:
+ _refresh_status_bubble_config(self)
value = getattr(self.config, "agent_status_no_output_ms", 180000)
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 180000
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index e239189c9..63b499f17 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -157,6 +157,19 @@ class ConsolidatedMessageDispatcher:
# per-key consolidated lock so finalize and a concurrent process render
# can't interleave (C1).
self._status_finalized: set[str] = set()
+ # Turn-keys whose tracked ``_consolidated_message_ids`` entry is a CONCISE
+ # status bubble (as opposed to a verbose consolidated process-log message,
+ # which shares the same dict). Cleanup keys on this — not the current
+ # progress style — so a mid-turn concise->off/verbose flip still retires
+ # the bubble, while a genuine verbose log is never mistaken for a bubble
+ # and deleted. Dropped per turn in ``_drop_status_keys``.
+ self._concise_bubble_keys: set[str] = set()
+ # Per-turn (consolidated_key) snapshot of the effective progress style, so
+ # a single turn cannot flip concise<->verbose<->off mid-way even if the Web
+ # UI setting changes while the backend is still emitting. Resolved lazily on
+ # first use per turn (see ``_concise_progress_style``), dropped in
+ # ``_drop_status_keys``.
+ self._turn_progress_style: dict[str, str] = {}
# Injectable monotonic-ish clock (wall time) so tests get deterministic
# elapsed/stale values without sleeping.
self._now = time.time
@@ -286,6 +299,8 @@ class ConsolidatedMessageDispatcher:
self._status_last_activity_at.pop(key, None)
self._status_render_tick.pop(key, None)
self._status_step_count.pop(key, None)
+ self._concise_bubble_keys.discard(key)
+ self._turn_progress_style.pop(key, None)
# NOTE: the finalized marker is intentionally NOT discarded here. The
# runtime gate is released only AFTER this teardown (in the agent
# service's finally), so a late same-token process emit during that
@@ -323,15 +338,36 @@ class ConsolidatedMessageDispatcher:
return DEFAULT_AGENT_PROGRESS_STYLE
def _concise_progress_style(self, context: MessageContext) -> str:
- """Effective progress style for the process-message path.
+ """Effective progress style for the process-message path, SNAPSHOTTED per
+ turn.
Only platforms with the ``supports_status_bubble`` capability (Slack/
Discord today) opt into concise/off; every other platform keeps the
existing ``verbose`` append path, so their output stays byte-identical.
- """
+
+ The effective style is resolved ONCE per turn (keyed by the turn's
+ consolidated key) and cached for the rest of that turn. ``self.config`` may
+ still be hot-reloaded mid-turn (via ``_t()`` or the controller getters) so
+ the NEXT turn starts fresh — that satisfies the "scheduled/background turns
+ pick up Web UI changes at their START" requirement — but a single turn can
+ never flip style halfway. That intra-turn stability is what keeps the
+ concise-bubble vs verbose-log lifecycle self-consistent (a mid-turn flip
+ would otherwise strand a bubble, delete a verbose log, or leave a heartbeat
+ stamping a log)."""
if not self._capabilities(context).supports_status_bubble:
return "verbose"
- return self._progress_style(context)
+ key = self._get_consolidated_message_key(context)
+ cached = self._turn_progress_style.get(key)
+ if cached is not None:
+ return cached
+ style = self._progress_style(context)
+ # Bound the cache: entries are dropped per turn in ``_drop_status_keys``,
+ # but clear proactively if it ever grows large so a missed teardown can't
+ # leak unboundedly (mirrors the ``_status_finalized`` guard).
+ if len(self._turn_progress_style) > 512:
+ self._turn_progress_style.clear()
+ self._turn_progress_style[key] = style
+ return style
async def _render_concise_status(
self,
@@ -375,7 +411,17 @@ class ConsolidatedMessageDispatcher:
# process emit was in flight. Bailing here keeps the terminal
# bubble from being resurrected back to a "working" line (C1).
return None
- existing_id = self._consolidated_message_ids.get(consolidated_key)
+ # Only reuse the tracked id when it was itself created as a concise
+ # bubble. If the turn started in ``verbose`` and the Web UI flipped to
+ # ``concise`` mid-turn, the tracked id is the verbose consolidated
+ # process-log message; reusing (and later retiring) it would delete the
+ # user's log. Treat that as "no bubble yet" and post a FRESH concise
+ # bubble, leaving the verbose log untracked and intact.
+ existing_id = (
+ self._consolidated_message_ids.get(consolidated_key)
+ if consolidated_key in self._concise_bubble_keys
+ else None
+ )
# Buffer holds the latest rendered label so the heartbeat can
# re-render it with an elapsed-time footer without a new event.
self._consolidated_message_buffers[consolidated_key] = label
@@ -415,6 +461,12 @@ class ConsolidatedMessageDispatcher:
logger.error(f"Failed to send status bubble: {err}", exc_info=True)
return None
+ # Mark this turn-key as a concise bubble so terminal cleanup retires it
+ # by identity even after a mid-turn style flip, without mistaking a
+ # verbose process-log id (same dict) for a bubble.
+ if message_id:
+ self._concise_bubble_keys.add(consolidated_key)
+
# Keep the elapsed timer alive even when the agent goes quiet (long tool).
if message_id:
self._start_status_heartbeat(context, im_client, consolidated_key)
@@ -700,6 +752,11 @@ class ConsolidatedMessageDispatcher:
# Stop if the turn was superseded or the bubble is gone.
if not self._is_current_runtime_turn(context):
return
+ # Stop if the key is no longer a concise bubble — e.g. a mid-turn
+ # concise->verbose flip reused this message as the verbose log; the
+ # heartbeat must not keep stamping a status footer onto a log.
+ if consolidated_key not in self._concise_bubble_keys:
+ return
message_id = self._consolidated_message_ids.get(consolidated_key)
if not message_id:
return
@@ -722,6 +779,10 @@ class ConsolidatedMessageDispatcher:
# in _render_concise_status).
if consolidated_key in self._status_finalized:
return
+ # Also bail if the key stopped being a concise bubble since this tick
+ # was scheduled (mid-turn concise->verbose flip reused the message).
+ if consolidated_key not in self._concise_bubble_keys:
+ return
if self._consolidated_message_ids.get(consolidated_key) != message_id:
return
body, footer = self._compose_status_message(context, consolidated_key)
@@ -748,10 +809,19 @@ class ConsolidatedMessageDispatcher:
pass
def _concise_status_bubble_id(self, context: MessageContext) -> Optional[str]:
- """The live concise status-bubble id for this turn, if any (else None)."""
- if self._concise_progress_style(context) != "concise":
+ """The live concise status-bubble id for this turn, if any (else None).
+
+ Keyed on whether a CONCISE bubble was actually posted for this turn, not
+ the current progress style: a Web UI ``concise`` -> ``off``/``verbose``
+ change mid-turn (now visible immediately via the getter self-refresh) must
+ still let the result path retire an already-posted bubble. Gating on the
+ concise-bubble key set (rather than plain ``_consolidated_message_ids``
+ membership) avoids mistaking a verbose consolidated process-log id — which
+ lives in the same dict — for a status bubble and deleting it."""
+ key = self._get_consolidated_message_key(context)
+ if key not in self._concise_bubble_keys:
return None
- return self._consolidated_message_ids.get(self._get_consolidated_message_key(context))
+ return self._consolidated_message_ids.get(key)
async def _finalize_status_key(self, consolidated_key: str) -> Optional[str]:
"""Atomically mark a turn-key finalized and capture its current bubble id.
@@ -792,9 +862,14 @@ class ConsolidatedMessageDispatcher:
if a bubble exists — edits it to the terminal footer. The footer marker
(✅ for ``done`` else ⏹, time only when ``show_duration``) is owned by
``_status_footer_text``. ``reason`` ∈ {"done","stopped","failed"}."""
- if self._concise_progress_style(context) != "concise":
- return
key = self._get_consolidated_message_key(context)
+ # Gate on whether a CONCISE bubble was posted for this turn, not the current
+ # style: a Web UI concise -> off/verbose change mid-turn must still collapse
+ # an already-posted bubble. Keying on the concise-bubble set (not plain
+ # _consolidated_message_ids membership) avoids collapsing a verbose
+ # consolidated process-log message, which shares that dict.
+ if key not in self._concise_bubble_keys:
+ return
# Heartbeat first: the render also takes the per-key lock, so stopping it
# before _finalize_status_key avoids contending with a live tick.
await self._stop_status_heartbeat(key)
@@ -1549,6 +1624,10 @@ class ConsolidatedMessageDispatcher:
# requirement: the process log is complete even when a channel hides it).
persist_agent_message(target_context, canonical_type, persist_text)
+ # Target platform toolcall-delivery gate stays in FRONT of the concise
+ # shortcut: when a turn is routed via ``delivery_override`` to a target
+ # that cannot deliver toolcalls (e.g. the WeChat override flow), the
+ # toolcall stays persisted-only and must NOT attempt a status bubble.
if canonical_type == "toolcall" and not self._supports_toolcall_delivery(target_context):
logger.info(
"Skipping toolcall delivery for platform %s; persisted local process log only.",
@@ -1556,6 +1635,24 @@ class ConsolidatedMessageDispatcher:
)
return None
+ # The concise status bubble is a single ephemeral status line, NOT the
+ # verbose per-message log that ``show_message_types`` governs. When a
+ # status-bubble platform (Slack/Discord) is in ``concise`` style, render
+ # tool-step / muttering emits into the bubble regardless of the
+ # ``is_message_type_hidden`` visibility toggle below: persistence already
+ # happened above so nothing is lost, and users who want zero process
+ # output use ``off``. This bypasses ONLY the visibility toggle — the
+ # target toolcall-delivery gate above still applies. ``system`` emits
+ # carry no status label and stay on the gated path.
+ if canonical_type in {"assistant", "toolcall"} and self._concise_progress_style(context) == "concise":
+ # ``_render_concise_status`` renders a footer-only bubble when the
+ # stripped body is empty but ``status_label`` is present, so do not
+ # drop empty-body toolcall emits here.
+ concise_chunk = strip_file_links(text).strip()
+ return await self._render_concise_status(
+ im_client, context, concise_chunk, status_label=status_label
+ )
+
if settings_manager.is_message_type_hidden(settings_key, canonical_type):
preview = text if len(text) <= 500 else f"{text[:500]}…"
logger.info(
@@ -1588,6 +1685,11 @@ class ConsolidatedMessageDispatcher:
lock = self._get_consolidated_message_lock(consolidated_key)
async with lock:
+ # Verbose consolidation path. Because the progress style is snapshotted
+ # per turn (see ``_concise_progress_style``), a turn that reaches here is
+ # verbose for its whole lifetime — it never posted a concise bubble — so
+ # ``_consolidated_message_ids[key]`` here is only ever a verbose log id,
+ # never a status bubble to reconcile.
max_bytes = self._get_consolidated_max_bytes(context)
split_threshold = self._get_consolidated_split_threshold(context)
existing = self._consolidated_message_buffers.get(consolidated_key, "")
diff --git a/tests/test_controller_config_reload.py b/tests/test_controller_config_reload.py
index 246b8e456..5c7cb3538 100644
--- a/tests/test_controller_config_reload.py
+++ b/tests/test_controller_config_reload.py
@@ -112,3 +112,55 @@ def test_refresh_config_updates_remote_access_for_audio_asr(tmp_path, monkeypatc
assert controller.config.remote_access.vibe_cloud.instance_secret == "secret"
assert controller.audio_asr_service.config is controller.config
+
+
+def test_refresh_config_updates_agent_progress_style(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ controller = Controller.__new__(Controller)
+ controller.config = V2Config.from_payload(
+ {**_config_payload({"bot_token": "discord-token"}), "agent_progress_style": "off"}
+ )
+ controller.im_clients = {}
+ controller._config_mtime = None
+ assert controller.config.agent_progress_style == "off"
+
+ latest_config = V2Config.from_payload(
+ {
+ **_config_payload({"bot_token": "discord-token"}),
+ "agent_progress_style": "concise",
+ "agent_status_heartbeat_ms": 9000,
+ "agent_status_no_output_ms": 45000,
+ }
+ )
+ latest_config.save()
+
+ controller._refresh_config_from_disk()
+
+ assert controller.config.agent_progress_style == "concise"
+ assert controller.config.agent_status_heartbeat_ms == 9000
+ assert controller.config.agent_status_no_output_ms == 45000
+
+
+def test_progress_style_getter_self_refreshes_from_disk(tmp_path, monkeypatch) -> None:
+ # Background / scheduled runs never pass through an IM inbound handler, so
+ # nothing calls _refresh_config_from_disk before the style gate. The getter
+ # must reload on its own so a Web UI off->concise change takes effect without
+ # an unrelated refresh or restart.
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ controller = Controller.__new__(Controller)
+ controller.config = V2Config.from_payload(
+ {**_config_payload({"bot_token": "discord-token"}), "agent_progress_style": "off"}
+ )
+ controller.im_clients = {}
+ controller._config_mtime = None
+
+ latest_config = V2Config.from_payload(
+ {**_config_payload({"bot_token": "discord-token"}), "agent_progress_style": "concise"}
+ )
+ latest_config.save()
+
+ # No prior _refresh_config_from_disk call; the getter itself must pick it up.
+ assert controller.get_progress_style_for_context(None) == "concise"
+ assert controller.get_heartbeat_interval_ms_for_context(None) == 15000
diff --git a/tests/test_message_dispatcher_status_bubble.py b/tests/test_message_dispatcher_status_bubble.py
index ce0da6fbf..5f43d7b05 100644
--- a/tests/test_message_dispatcher_status_bubble.py
+++ b/tests/test_message_dispatcher_status_bubble.py
@@ -29,11 +29,14 @@ from modules.im.formatters.slack_formatter import SlackFormatter
class _StubSettingsManager:
+ def __init__(self, hidden_types=None):
+ self._hidden_types = set(hidden_types or ())
+
def _canonicalize_message_type(self, message_type):
return message_type
def is_message_type_hidden(self, settings_key, canonical_type):
- return False
+ return canonical_type in self._hidden_types
class _StubSessionHandler:
@@ -71,7 +74,15 @@ class _EditClient:
class _StubController:
- def __init__(self, *, platform="slack", im_client=None, progress_style="concise", backend_alive=None):
+ def __init__(
+ self,
+ *,
+ platform="slack",
+ im_client=None,
+ progress_style="concise",
+ backend_alive=None,
+ hidden_types=None,
+ ):
self.config = type(
"Config", (), {"platform": platform, "language": "en", "reply_enhancements": False}
)()
@@ -80,6 +91,7 @@ class _StubController:
self.agent_service = None
self._progress_style_value = progress_style
self._backend_alive_value = backend_alive
+ self._hidden_types = hidden_types
def _get_settings_key(self, context):
return context.channel_id
@@ -88,7 +100,7 @@ class _StubController:
return f"{context.platform}::{context.channel_id}"
def get_settings_manager_for_context(self, context):
- return _StubSettingsManager()
+ return _StubSettingsManager(self._hidden_types)
def get_im_client_for_context(self, context):
return self.im_client
@@ -178,6 +190,86 @@ class StatusBubbleProcessTests(unittest.IsolatedAsyncioTestCase):
d = _dispatcher(controller)
self.assertEqual(d._concise_progress_style(_ctx("lark")), "verbose")
+ async def test_concise_toolcall_renders_despite_hidden_toolcall(self):
+ # Regression: the concise status bubble is an ephemeral status line, not
+ # the verbose per-message log that ``show_message_types`` governs. A
+ # toolcall emit must render into the bubble even when the channel hides
+ # the toolcall message type (the default show_message_types=['assistant']).
+ controller = _StubController(platform="slack", hidden_types={"toolcall"})
+ d = _dispatcher(controller)
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ mid = await d.emit_agent_message(
+ _ctx(), "toolcall", "🔧 `Read` `{}`", status_label="🔧 Read: a.py"
+ )
+ self.assertEqual(mid, "msg-1")
+ self.assertEqual(controller.im_client.sent[0][1], "🔧 Read: a.py")
+
+ async def test_concise_renders_empty_chunk_with_status_label(self):
+ # File-link-only body strips to empty, but a non-empty status_label still
+ # renders the bubble (footer/label), so tool steps are never dropped.
+ controller = _StubController(platform="slack", hidden_types={"toolcall"})
+ d = _dispatcher(controller)
+ with mock.patch("core.message_dispatcher.strip_file_links", return_value=""):
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ mid = await d.emit_agent_message(
+ _ctx(), "toolcall", "[f](file:///tmp/x)", status_label="🔧 Read: x"
+ )
+ self.assertEqual(mid, "msg-1")
+ self.assertEqual(controller.im_client.sent[0][1], "🔧 Read: x")
+
+ async def test_concise_empty_chunk_and_no_label_does_not_render(self):
+ # Empty body AND no status_label → nothing to show; no bubble is posted.
+ controller = _StubController(platform="slack", hidden_types={"toolcall"})
+ d = _dispatcher(controller)
+ with mock.patch("core.message_dispatcher.strip_file_links", return_value=""):
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ mid = await d.emit_agent_message(_ctx(), "toolcall", "[f](file:///tmp/x)")
+ self.assertIsNone(mid)
+ self.assertEqual(controller.im_client.sent, [])
+
+ async def test_concise_assistant_renders_despite_hidden_assistant(self):
+ # Concise mode bypasses the visibility toggle for assistant mutterings too;
+ # users who want zero process output use progress_style=off.
+ controller = _StubController(platform="slack", hidden_types={"assistant", "toolcall"})
+ d = _dispatcher(controller)
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ mid = await d.emit_agent_message(_ctx(), "assistant", "thinking about it")
+ self.assertEqual(mid, "msg-1")
+ self.assertEqual(controller.im_client.sent[0][1], "thinking about it")
+
+ async def test_concise_toolcall_persisted_only_when_target_blocks_toolcall_delivery(self):
+ # A Slack concise turn routed via delivery_override to a target that
+ # cannot deliver toolcalls (WeChat) must stay persisted-only: the target
+ # toolcall-delivery gate runs BEFORE the concise shortcut, so no status
+ # bubble send is attempted to a platform that can't deliver toolcalls.
+ controller = _StubController(platform="slack", hidden_types={"toolcall"})
+ d = _dispatcher(controller)
+ ctx = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={
+ "delivery_override": {"platform": "wechat", "channel_id": "wx1", "user_id": "wxu"}
+ },
+ )
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ mid = await d.emit_agent_message(
+ ctx, "toolcall", "🔧 `Read` `{}`", status_label="🔧 Read: a.py"
+ )
+ self.assertIsNone(mid)
+ self.assertEqual(controller.im_client.sent, [])
+
+ async def test_off_still_respects_no_bubble_when_toolcall_hidden(self):
+ # off must remain fully silent regardless of the visibility toggle.
+ controller = _StubController(
+ platform="slack", progress_style="off", hidden_types={"toolcall"}
+ )
+ d = _dispatcher(controller)
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ mid = await d.emit_agent_message(_ctx(), "toolcall", "🔧 `Read` `{}`")
+ self.assertIsNone(mid)
+ self.assertEqual(controller.im_client.sent, [])
+
class StatusBubbleResultTests(unittest.IsolatedAsyncioTestCase):
async def test_result_posts_fresh_message_and_deletes_bubble(self):
@@ -199,6 +291,85 @@ class StatusBubbleResultTests(unittest.IsolatedAsyncioTestCase):
result_persists = [c for c in persist.call_args_list if c.args[1] == "result"]
self.assertEqual(result_persists[-1].args[2], "Final answer")
+ async def test_style_snapshot_keeps_concise_when_config_flips_to_off(self):
+ # The effective progress style is snapshotted per turn: a Web UI flip to
+ # off mid-turn does NOT take effect until the next turn, so the concise
+ # bubble is rendered and retired normally (no stranded bubble).
+ controller = _StubController(platform="slack")
+ d = _dispatcher(controller)
+ ctx = _ctx()
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`") # bubble msg-1
+ controller._progress_style_value = "off" # Web UI change mid-turn (deferred)
+ self.assertEqual(d._concise_progress_style(ctx), "concise") # snapshot unchanged
+ result_id = await d.emit_agent_message(ctx, "result", "Final answer")
+ self.assertEqual(result_id, "msg-2") # fresh result message
+ self.assertEqual(controller.im_client.deletes, ["msg-1"]) # bubble retired, not stuck
+
+ async def test_verbose_result_does_not_delete_process_log(self):
+ # Verbose mode stores its consolidated process-log id in the SAME dict as
+ # concise bubbles. The result path must NOT mistake that log for a status
+ # bubble and delete/collapse it — verbose users keep their process log.
+ controller = _StubController(platform="slack", progress_style="verbose")
+ d = _dispatcher(controller)
+ ctx = _ctx()
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`") # verbose log msg-1
+ await d.emit_agent_message(ctx, "result", "Final answer")
+ self.assertEqual(controller.im_client.deletes, []) # process log NOT deleted
+ self.assertIn("msg-1", [m for m, _, _ in controller.im_client.sent]) # log still present
+
+ async def test_style_snapshot_keeps_verbose_when_config_flips_to_concise(self):
+ # Turn starts verbose (log posted). A Web UI flip to concise mid-turn is
+ # deferred to the next turn by the per-turn snapshot, so the next emit keeps
+ # appending to the SAME verbose log (no fresh concise bubble) and the result
+ # never retires it.
+ controller = _StubController(platform="slack", progress_style="verbose")
+ d = _dispatcher(controller)
+ ctx = _ctx()
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`") # verbose log msg-1
+ controller._progress_style_value = "concise" # Web UI flip mid-turn (deferred)
+ self.assertEqual(d._concise_progress_style(ctx), "verbose") # snapshot unchanged
+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Read` `{}`") # appended to msg-1, no new bubble
+ result_id = await d.emit_agent_message(ctx, "result", "Final answer")
+ self.assertEqual(result_id, "msg-2") # only the log (msg-1) + result (msg-2) were sent
+ self.assertEqual([m for m, _, _ in controller.im_client.sent], ["msg-1", "msg-2"])
+ self.assertEqual(controller.im_client.deletes, []) # verbose log NOT retired
+
+ async def test_style_snapshot_keeps_concise_when_config_flips_to_verbose(self):
+ # Turn starts concise (bubble posted). A Web UI flip to verbose mid-turn is
+ # deferred by the snapshot, so the next emit keeps editing the SAME concise
+ # bubble and the result retires it normally.
+ controller = _StubController(platform="slack", progress_style="concise")
+ d = _dispatcher(controller)
+ ctx = _ctx()
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ await d.emit_agent_message(
+ ctx, "toolcall", "🔧 `Bash` `{}`", status_label="🔧 Bash"
+ ) # concise bubble msg-1
+ controller._progress_style_value = "verbose" # Web UI flip mid-turn (deferred)
+ self.assertEqual(d._concise_progress_style(ctx), "concise") # snapshot unchanged
+ await d.emit_agent_message(
+ ctx, "toolcall", "🔧 `Read` `{}`", status_label="🔧 Read"
+ ) # edits the same bubble msg-1, no new message
+ result_id = await d.emit_agent_message(ctx, "result", "Final answer")
+ self.assertEqual(result_id, "msg-2") # result is its own new message
+ self.assertEqual(controller.im_client.deletes, ["msg-1"]) # concise bubble retired normally
+
+ async def test_style_snapshot_cleared_after_turn(self):
+ # The per-turn snapshot is dropped in teardown so the NEXT turn re-reads
+ # config — i.e. a Web UI change still takes effect, just at turn boundaries.
+ controller = _StubController(platform="slack", progress_style="concise")
+ d = _dispatcher(controller)
+ ctx = _ctx()
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`")
+ key = d._get_consolidated_message_key(ctx)
+ self.assertEqual(d._turn_progress_style.get(key), "concise") # snapshot taken
+ await d.emit_agent_message(ctx, "result", "Done")
+ self.assertNotIn(key, d._turn_progress_style) # cleared at turn end
+
async def test_result_done_footer_keeps_session_tokens(self):
# A backend that reports session tokens before the result → the fresh
# result message's done footer carries "✅ done · {n} tok".
@@ -423,6 +594,21 @@ class StatusBubbleResultTests(unittest.IsolatedAsyncioTestCase):
await d.emit_agent_message(ctx, "result", "Done")
self.assertNotIn(key, d._status_heartbeat_tasks) # cancelled + cleared
+ async def test_heartbeat_render_bails_when_key_no_longer_concise(self):
+ # After a concise->verbose mid-turn flip the message is reused as a verbose
+ # log and the concise marker is dropped; a still-scheduled heartbeat tick
+ # must not stamp a status footer onto that log.
+ controller = _StubController(platform="slack")
+ d = _dispatcher(controller)
+ ctx = _ctx()
+ with mock.patch("core.message_dispatcher.persist_agent_message"):
+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`") # bubble msg-1
+ key = d._get_consolidated_message_key(ctx)
+ d._concise_bubble_keys.discard(key) # simulate the verbose-path marker drop
+ controller.im_client.edits.clear()
+ await d._status_heartbeat_render_once(ctx, controller.im_client, key, "msg-1")
+ self.assertEqual(controller.im_client.edits, []) # no footer stamped on the log
+
class BeginStatusBubbleTests(unittest.IsolatedAsyncioTestCase):
async def test_begin_creates_bubble_then_first_emit_edits_same_id(self):