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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(im): concise status bubble for Slack/Discord
Qi Qic75be0ea042d
diff --git a/config/platform_registry.py b/config/platform_registry.pyindex 48f29938e..dec7257bc 100644--- a/config/platform_registry.py+++ b/config/platform_registry.py@@ -14,6 +14,10 @@ class PlatformCapabilities:supports_buttons: boolsupports_quick_replies: boolsupports_message_editing: bool+ # Platform can delete a previously-sent message. Used so the status bubble can+ # be removed (rather than edited-in-place) when the final result is posted as a+ # NEW message, which is what makes IM fire a push notification for the result.+ supports_message_deletion: bool = Falsemarkdown_upload_returns_message_id: bool = Falsequick_reply_single_column: bool = Falsesupports_typing_indicator: bool = False@@ -24,6 +28,10 @@ class PlatformCapabilities:supports_message_indicator_delete: bool = Falsepreferred_processing_indicator: str = "typing"force_preferred_processing_indicator: bool = False+ # Platform can host the concise single status bubble (edit-in-place + subtext+ # footer) that becomes the result. One capability shared by the dispatcher and+ # the processing indicator instead of a hardcoded {"slack","discord"} literal.+ supports_status_bubble: bool = False@dataclass(frozen=True)@@ -138,9 +146,11 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {supports_buttons=True,supports_quick_replies=True,supports_message_editing=True,+ supports_message_deletion=True,supports_typing_indicator=True,typing_indicator_best_effort=True,supports_reaction_indicator=True,+ supports_status_bubble=True,),),"discord": PlatformDescriptor(@@ -160,9 +170,11 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {supports_buttons=True,supports_quick_replies=True,supports_message_editing=True,+ supports_message_deletion=True,markdown_upload_returns_message_id=True,supports_typing_indicator=True,supports_reaction_indicator=True,+ supports_status_bubble=True,),),"telegram": PlatformDescriptor(@@ -182,6 +194,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {supports_buttons=True,supports_quick_replies=True,supports_message_editing=True,+ supports_message_deletion=True,markdown_upload_returns_message_id=True,quick_reply_single_column=True,supports_typing_indicator=True,diff --git a/config/v2_config.py b/config/v2_config.pyindex b180b9809..985838f20 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -412,6 +412,12 @@ class V2Config:reply_enhancements: bool = True # Enable quick-reply buttonsshow_pages_prompt: bool = True # Inject Show Pages capability guidance into agent promptslanguage: str = "en" # Global language setting (see vibe/i18n)+ # Concise status-bubble UX for editing platforms (Slack/Discord):+ # "concise" (default) one self-updating bubble that becomes the result,+ # "verbose" legacy append/split process log, "off" no process bubble.+ agent_progress_style: str = "concise"+ agent_status_heartbeat_ms: int = 15000 # status-bubble elapsed-timer heartbeat+ agent_status_no_output_ms: int = 180000 # "no output for N min" hint threshold# True once the user has finished the setup wizard. This is the explicit# gate for ``setup_state().needs_setup`` — it replaces the old heuristic# that inferred "setup done" from having a mode plus configured platform@@ -618,6 +624,20 @@ class V2Config:language = normalize_language(payload.get("language"), default="en")+ agent_progress_style = payload.get("agent_progress_style", "concise")+ if agent_progress_style not in ("concise", "verbose", "off"):+ agent_progress_style = "concise"++ def _positive_int(value, default, maximum):+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0 or value > maximum:+ return default+ return value++ # Cap to sane upper bounds so a fat-fingered value can't silence the+ # heartbeat (heartbeat ≤ 1h, no-output hint ≤ 24h); out-of-range → default.+ agent_status_heartbeat_ms = _positive_int(payload.get("agent_status_heartbeat_ms"), 15000, 3_600_000)+ agent_status_no_output_ms = _positive_int(payload.get("agent_status_no_output_ms"), 180000, 86_400_000)+# ``setup_completed`` is the explicit setup gate. Read the stored value# when present; otherwise leave it ``None`` here and derive it below# from the legacy "setup done" heuristic so installs configured before@@ -653,6 +673,9 @@ class V2Config:reply_enhancements=reply_enhancements,show_pages_prompt=show_pages_prompt,language=language,+ agent_progress_style=agent_progress_style,+ agent_status_heartbeat_ms=agent_status_heartbeat_ms,+ agent_status_no_output_ms=agent_status_no_output_ms,)# Migration: when the payload predates ``setup_completed``, derive it@@ -713,6 +736,9 @@ class V2Config:"reply_enhancements": self.reply_enhancements,"show_pages_prompt": self.show_pages_prompt,"language": self.language,+ "agent_progress_style": self.agent_progress_style,+ "agent_status_heartbeat_ms": self.agent_status_heartbeat_ms,+ "agent_status_no_output_ms": self.agent_status_no_output_ms,"setup_completed": self.setup_completed,}content = json.dumps(payload, indent=2)diff --git a/core/controller.py b/core/controller.pyindex 86406f79a..5ae97dd10 100644--- a/core/controller.py+++ b/core/controller.py@@ -865,6 +865,61 @@ class Controller:settings_key = self._get_settings_key(context)return build_context_session_key(context, platform=platform, settings_key=settings_key)+ def backend_alive(self, context: MessageContext) -> Optional[bool]:+ """Best-effort backend liveness for the concise status bubble's footer.++ Delegates to ``AgentService.backend_alive`` (which dispatches to the+ per-backend probe). Returns ``None`` when unknown — the dispatcher+ treats ``None``/missing as alive so it never false-alarms ⚠️.+ """+ service = getattr(self, "agent_service", None)+ probe = getattr(service, "backend_alive", None)+ if not callable(probe):+ return None+ try:+ return probe(context)+ except Exception:+ logger.debug("backend_alive delegation failed", exc_info=True)+ return None++ # ---- concise status-bubble settings (read by the message dispatcher) ----++ def get_progress_style_for_context(self, context: MessageContext) -> str:+ """Resolve the process-message UX style for this context: concise|verbose|off.++ Currently a global config setting; per-channel overrides can layer on top+ here later without touching the dispatcher.+ """+ value = getattr(self.config, "agent_progress_style", "concise")+ return value if value in ("concise", "verbose", "off") else "concise"++ def uses_concise_status_bubble(self, context: MessageContext) -> bool:+ """True when this turn renders a concise status bubble (Slack/Discord ++ progress_style=concise). The single source of truth shared by the message+ dispatcher (which creates the bubble) and the processing indicator (which+ suppresses its ack-message/reaction so there is no duplicate signal)."""+ # Resolve platform with the SAME fallback the dispatcher's _get_platform+ # uses (config.platform) so the bubble-creation gate and this suppression+ # gate never disagree on an edge config; both then read the SAME+ # ``supports_status_bubble`` capability rather than a hardcoded platform set.+ platform = (+ context.platform+ or (context.platform_specific or {}).get("platform")+ or getattr(self.config, "platform", None)+ or self.primary_platform+ )+ if not get_platform_descriptor(platform).capabilities.supports_status_bubble:+ return False+ return self.get_progress_style_for_context(context) == "concise"++ def get_heartbeat_interval_ms_for_context(self, context: MessageContext) -> int:+ 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:+ 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+def get_im_client_for_context(self, context: Optional[MessageContext] = None) -> BaseIMClient:if context is None:return self.im_clients[self.primary_platform]@@ -1149,6 +1204,7 @@ class Controller:*,is_error: bool = False,level: str = "normal",+ status_label: Optional[str] = None,):"""Backward-compatible entrypoint; delegated to message dispatcher."""return await self.message_dispatcher.emit_agent_message(@@ -1158,8 +1214,19 @@ class Controller:parse_mode=parse_mode,is_error=is_error,level=level,+ status_label=status_label,)+ def note_session_tokens(self, context: MessageContext, *, total: int) -> None:+ """Report the session's current context-window occupancy for the status+ footer (backend-agnostic). SETs an absolute snapshot; the next footer render+ shows it. No-op if the dispatcher is unavailable (partially-wired test+ controllers)."""+ dispatcher = getattr(self, "message_dispatcher", None)+ if dispatcher is None:+ return+ dispatcher.note_session_tokens(context, total=total)+# Main run methoddef run(self):"""Run the controller"""diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 06c140b97..37b46d260 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -184,10 +184,13 @@ class MessageHandler(BaseHandler):settings_key = self._get_settings_key(context)session_key = self._get_session_key(context)- # Update thread's current message_id so log messages follow this user message- # This is critical for proper log message grouping when agent receivers- # hold references to older contexts- self.controller.update_thread_message_id(context)+ # NOTE: claiming the thread's current message_id (the dispatcher's+ # per-turn bubble trigger) and posting the "starting" status bubble+ # now happen in AgentService.handle_message, AFTER the runtime gate+ # is acquired — i.e. when this turn actually STARTS rather than while+ # it is queued behind an in-flight turn. This keeps a queued turn+ # from hijacking the running turn's bubble key or posting a premature+ # bubble.platform_payload = context.platform_specific or {}resolved_target = platform_payload.get("agent_run_target")@@ -380,6 +383,10 @@ class MessageHandler(BaseHandler):context.platform_specific = specif is_human:+ # The concise status bubble (footer-only at turn start) is now+ # posted by AgentService.handle_message after the runtime gate is acquired,+ # so it only appears once this turn truly starts (not while it is+ # queued). See _begin_turn_status there.processing_indicator = await self.controller.processing_indicator.start(context, agent_name)if is_human and subagent_name and context.message_id:diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 597f3ddf8..e9c52e16b 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport loggingimport asyncio+import timefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Optional@@ -15,6 +16,7 @@ from urllib.parse import urljoinfrom config.platform_registry import get_platform_descriptorfrom modules.im import MessageContext+from modules.im.formatters.base_formatter import to_status_labelfrom core.message_mirror import persist_agent_messagefrom core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocksfrom core.session_turns import emit_matches_active_turn@@ -104,6 +106,11 @@ async def _stream_chunk(controller, context, *, text: str, message_id: Optional[_WECHAT_TEXT_LIMIT = 1900_WECHAT_CONSOLIDATED_SPLIT_THRESHOLD = 1700+# Append the current action's own elapsed time to the status-bubble BODY only+# once it has been running this long (e.g. ``🔧 Bash · 2:30``). Below this a+# normal fast step stays a clean label. This is the always-moving "still running"+# signal that the heartbeat keeps ticking even when no new emit arrives.+_ACTION_TIME_HINT_S = 10.0class ConsolidatedMessageDispatcher:@@ -115,6 +122,43 @@ class ConsolidatedMessageDispatcher:self._consolidated_message_buffers: dict[str, str] = {}self._consolidated_message_locks: dict[str, asyncio.Lock] = {}self._thread_current_message_id: dict[str, str] = {}+ # NB: the concise status bubble is a single short replace-not-append line+ # (to_status_label caps at ~60 chars, well under any platform limit), so it+ # never splits into multiple messages — the "overflow" (case 3) the design+ # doc lists is unreachable by construction and needs no tidy state.+ # P1 liveness: per-turn (consolidated_key) start + last-activity timestamps+ # drive the footer (turn elapsed) and the body's current-action runtime+ # (now − last activity); one heartbeat task per turn; cancelled before the+ # final edit-into-result so a stale tick can't stomp the result.+ self._status_started_at: dict[str, float] = {}+ self._status_last_activity_at: dict[str, float] = {}+ # Per-turn render counter so the running footer's hourglass glyph cycles+ # (⏳ ⌛ ⏳ ⌛) across heartbeats/emits without any external event — a+ # zero-width "still alive" motion that replaces the old "working…" dots.+ self._status_render_tick: dict[str, int] = {}+ # Per-turn (consolidated_key) count of real action emits (toolcall ++ # assistant) so the footer can show a monotonically-growing "{n} st"+ # progress signal. Heartbeat re-renders do NOT go through the emit path,+ # so they never inflate it. Dropped per turn in ``_drop_status_keys``.+ self._status_step_count: dict[str, int] = {}+ # Current context-window occupancy (keyed by SESSION key, not turn-key) so+ # the footer can show "{n} tok" of context the session is using. Backends+ # report the latest snapshot via ``note_session_tokens(total=…)`` (Claude:+ # last assistant message usage; Codex: thread/tokenUsage/updated last). It+ # tracks the live context size — growing with the conversation and dropping+ # after a /compact — so it persists across turns, NOT turn-scoped state.+ self._session_token_total: dict[str, int] = {}+ self._status_heartbeat_tasks: dict[str, asyncio.Task] = {}+ # Turn-keys whose bubble has already been finalized (edited into the+ # result or collapsed to a terminal marker). A late in-flight process+ # emit for one of these keys must NOT resurrect/overwrite the terminal+ # bubble — see ``_render_concise_status``. Mark + read happens under the+ # per-key consolidated lock so finalize and a concurrent process render+ # can't interleave (C1).+ self._status_finalized: set[str] = set()+ # Injectable monotonic-ish clock (wall time) so tests get deterministic+ # elapsed/stale values without sleeping.+ self._now = time.timedef _get_platform(self, context: MessageContext) -> str:return context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform@@ -222,12 +266,571 @@ class ConsolidatedMessageDispatcher:self._consolidated_message_locks[key] = asyncio.Lock()return self._consolidated_message_locks[key]+ async def _drop_status_keys(self, key: str) -> None:+ """Stop the turn's heartbeat and drop ALL per-turn status state for ``key``.++ Single owner of the teardown sequence so the message id, buffer, and the+ two timestamp dicts can never drift between the two clear call sites.+ Heartbeat is cancelled BEFORE the lock — the heartbeat render also takes+ this lock, so awaiting it while holding the lock would deadlock.+ """+ await self._stop_status_heartbeat(key)+ async with self._get_consolidated_message_lock(key):+ self._consolidated_message_ids.pop(key, None)+ self._consolidated_message_buffers.pop(key, None)+ self._status_started_at.pop(key, None)+ self._status_last_activity_at.pop(key, None)+ self._status_render_tick.pop(key, None)+ self._status_step_count.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+ # window still passes _is_current_runtime_turn; keeping the key+ # finalized makes _render_concise_status bail instead of re-opening a+ # bubble after the answer was posted (P2). The set is bounded in+ # _finalize_status_key.+ # Drop the lock itself LAST — only after the ``async with`` block above+ # has released it — so the per-key lock dict can't grow unbounded across+ # many turns (C6). Popping a still-held lock would orphan the held lock.+ self._consolidated_message_locks.pop(key, None)+async def _clear_consolidated_state(self, context: MessageContext) -> None:+ await self._drop_status_keys(self._get_consolidated_message_key(context))++ # ------------------------------------------------------------------+ # Concise status bubble (Slack / Discord)+ # ------------------------------------------------------------------++ def _progress_style(self, context: MessageContext) -> str:+ """Resolve the per-channel progress style: ``concise`` | ``verbose`` | ``off``.++ Defaults to ``concise`` (the locked default for editing platforms). A+ controller may expose ``get_progress_style_for_context`` once the+ settings/UI plumbing lands; until then this returns the default and the+ feature degrades to existing behavior only via ``_concise_progress_style``.+ """+ getter = getattr(self.controller, "get_progress_style_for_context", None)+ if callable(getter):+ try:+ value = getter(context)+ if value in {"concise", "verbose", "off"}:+ return value+ except Exception:+ logger.debug("get_progress_style_for_context failed; defaulting concise", exc_info=True)+ return "concise"++ def _concise_progress_style(self, context: MessageContext) -> str:+ """Effective progress style for the process-message path.++ 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.+ """+ if not self._capabilities(context).supports_status_bubble:+ return "verbose"+ return self._progress_style(context)++ async def _render_concise_status(+ self,+ im_client,+ context: MessageContext,+ chunk: str,+ status_label: Optional[str] = None,+ *,+ allow_empty_body: bool = False,+ ) -> Optional[str]:+ """Render ONE status bubble that REPLACES (not appends) the latest action.++ The process bubble stays a single short line (`🔧 <action>`) plus a+ liveness footer; it never splits and never leaves ``continued below``+ fragments. The same bubble is later edited into the final result (see the+ ``result`` branch). Persistence already happened upstream — this only+ shapes the IM view.++ ``status_label`` (when non-empty) is a backend-computed clean tool-call+ label (claude-pipe style: ``🔧 Read: message_dispatcher.py``) used for the+ bubble body in place of the raw ``to_status_label(chunk)`` fallback. It+ never touches the persisted/verbose text — only the concise bubble view.++ ``allow_empty_body`` posts a footer-only bubble (no action label yet, e.g.+ turn start / pure thinking); the adapters render an empty body as the+ footer alone.+ """+ label = status_label or to_status_label(chunk)+ if not label and not allow_empty_body:+ return None+consolidated_key = self._get_consolidated_message_key(context)lock = self._get_consolidated_message_lock(consolidated_key)+ target_context = self._get_target_context(context)+ now = self._now()+async with lock:- self._consolidated_message_ids.pop(consolidated_key, None)- self._consolidated_message_buffers.pop(consolidated_key, None)+ if consolidated_key in self._status_finalized:+ # The turn already finalized (result edited the bubble into the+ # answer, or it was collapsed to a terminal marker) while this+ # 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)+ # 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+ self._status_started_at.setdefault(consolidated_key, now)+ self._status_last_activity_at[consolidated_key] = now+ # Count this as a step only for a real action emit (a non-empty label);+ # the footer-only turn-start bubble (empty label) is not a step.+ if label:+ self._status_step_count[consolidated_key] = self._status_step_count.get(consolidated_key, 0) + 1+ body, footer = self._compose_status_message(context, consolidated_key)++ message_id = existing_id+ if existing_id:+ try:+ ok = await im_client.edit_message(+ target_context,+ existing_id,+ text=body,+ parse_mode="markdown",+ subtext=footer,+ )+ except Exception as err:+ logger.warning(f"Failed to edit status bubble: {err}")+ ok = False+ if not ok:+ # Edit failed (message gone / perms): drop the id and re-send.+ self._consolidated_message_ids.pop(consolidated_key, None)+ message_id = None++ if message_id is None:+ try:+ message_id = await im_client.send_message(+ target_context, body, parse_mode="markdown", subtext=footer+ )+ self._consolidated_message_ids[consolidated_key] = message_id+ except Exception as err:+ logger.error(f"Failed to send status bubble: {err}", exc_info=True)+ return None++ # 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)+ return message_id++ async def begin_status_bubble(self, context: MessageContext) -> None:+ """Post the status bubble IMMEDIATELY at turn start (footer-only).++ Without this the bubble only appears on the first process emit, leaving+ an early gap while the backend spins up. This posts an initial bubble so+ the user sees activity at once; the first real process emit then finds+ the existing id and EDITS it in place (no duplicate bubble).++ The body is EMPTY — the running footer ("⏳ 0s") already conveys that the+ agent started, so a redundant "starting agent" body line is dropped. The+ first real process emit fills the body in.++ No-op unless the channel is in ``concise`` style (so only Slack/Discord+ concise; ``off``/``verbose`` and non-status-bubble platforms are skipped),+ and idempotent: if a bubble already exists for this turn it does nothing.+ Wrapped so a bubble failure never blocks the turn.++ C2: this is awaited from ``AgentService._begin_turn_status`` WHILE the+ runtime gate lock is held, so a slow IM post (e.g. a Slack rate-limit)+ would freeze every queued turn behind it. Bound the post at 5s — if it+ doesn't land in time we log and return; the first real process emit then+ creates the bubble via the idempotent guard, so nothing is lost.+ """+ try:+ # No-delivery runs (scheduled / watch / agent-run targeting a Slack or+ # Discord no-delivery session) suppress every emitted message at the+ # chokepoint; this turn-start post runs BEFORE that branch, so guard it+ # here too or a private run would leak a visible ⏳ bubble to the channel.+ if (context.platform_specific or {}).get("suppress_delivery"):+ return+ if self._concise_progress_style(context) != "concise":+ return+ consolidated_key = self._get_consolidated_message_key(context)+ if self._consolidated_message_ids.get(consolidated_key):+ return+ im_client = self._get_im_client(context)+ # Reuse the exact process-emit render path so the starting bubble is+ # created, stored, and heartbeated identically to a real emit, but with+ # an empty body (footer only). The first real emit later EDITS this id.+ try:+ await asyncio.wait_for(+ self._render_concise_status(im_client, context, "", allow_empty_body=True),+ timeout=5,+ )+ except asyncio.TimeoutError:+ # Don't hold the gate on a slow post; the idempotent first-emit+ # path will create the bubble once the backend starts emitting.+ logger.debug("begin_status_bubble timed out; first emit will create the bubble")+ except Exception:+ logger.debug("begin_status_bubble failed; turn continues", exc_info=True)++ # ---- liveness footer + heartbeat ----++ def _heartbeat_interval_s(self, context: MessageContext) -> float:+ getter = getattr(self.controller, "get_heartbeat_interval_ms_for_context", None)+ if callable(getter):+ try:+ value = getter(context)+ if value and value > 0:+ return float(value) / 1000.0+ except Exception:+ logger.debug("get_heartbeat_interval_ms_for_context failed; default 15s", exc_info=True)+ return 15.0++ def _no_output_hint_after_s(self, context: MessageContext) -> float:+ getter = getattr(self.controller, "get_no_output_hint_after_ms_for_context", None)+ if callable(getter):+ try:+ value = getter(context)+ if value and value > 0:+ return float(value) / 1000.0+ except Exception:+ logger.debug("get_no_output_hint_after_ms_for_context failed; default 180s", exc_info=True)+ return 180.0++ @staticmethod+ def _format_elapsed(seconds: float) -> str:+ total = max(0, int(seconds))+ if total < 60:+ return f"{total}s"+ return f"{total // 60}:{total % 60:02d}"++ @staticmethod+ def _format_token_count(tokens: int) -> str:+ """Compact token count: ``999`` / ``12.3k`` / ``248k`` / ``1.4M``.++ One decimal below 100k and below 10M; whole units above (the number is+ already large enough that a decimal adds noise, not precision)."""+ n = max(0, int(tokens))+ if n < 1000:+ return str(n)+ if n < 100_000:+ return f"{n / 1000:.1f}k"+ if n < 1_000_000:+ return f"{round(n / 1000)}k"+ if n < 10_000_000:+ return f"{n / 1_000_000:.1f}M"+ return f"{round(n / 1_000_000)}M"++ def _token_session_key(self, context: MessageContext) -> str:+ """Key for context-window occupancy: scoped per CONVERSATION (thread / DM),+ not per channel. The channel-level ``_get_session_key`` alone would let one+ thread's token update overwrite every other thread's footer in the same+ channel, since distinct agent sessions are derived from the thread anchor (P2)."""+ return f"{self._get_session_key(context)}:{context.thread_id or context.channel_id}"++ def note_session_tokens(self, context: MessageContext, *, total: int) -> None:+ """SET the session's current context-window occupancy shown in the footer.++ Both backends report ``total`` as a live snapshot (Claude: latest assistant+ usage; Codex: ``thread/tokenUsage/updated`` last). A pure SET — never an+ accumulation — so the figure tracks the live context size and drops after a+ /compact. Invalid/negative values are ignored. The next footer render (emit+ or heartbeat) picks it up.+ """+ try:+ value = int(total)+ except (TypeError, ValueError):+ return+ if value >= 0:+ self._session_token_total[self._token_session_key(context)] = value++ def _backend_dead(self, context: MessageContext) -> bool:+ """Best-effort backend-liveness probe (B1). Returns True ONLY when the+ controller can definitively say the backend is gone; unknown → False so+ we never false-alarm. Controller dispatches by backend (Claude receiver+ task / Codex transport)."""+ probe = getattr(self.controller, "backend_alive", None)+ if not callable(probe):+ return False+ try:+ alive = probe(context)+ except Exception:+ logger.debug("backend_alive probe failed; treating as alive", exc_info=True)+ return False+ return alive is False++ def _show_duration(self) -> bool:+ """Whether the terminal/done footer should show the elapsed TIME.++ Mirrors the existing ``config.show_duration`` (default False) that gates+ duration in result messages, so the completion footer no longer double-+ surfaces the duration. The RUNNING footer is unaffected (its elapsed time+ is live liveness, not a final duration summary)."""+ return bool(getattr(getattr(self.controller, "config", None), "show_duration", False))++ def _token_field(self, context: MessageContext) -> str:+ """The ``{n} tok`` footer field for the session's current context-window+ occupancy, or "" when unknown/zero (a backend that does not report usage+ shows nothing)."""+ tokens = self._session_token_total.get(self._token_session_key(context), 0)+ if tokens <= 0:+ return ""+ return self._t("status.tokens", count=self._format_token_count(tokens))++ def _status_footer_text(+ self,+ context: MessageContext,+ *,+ elapsed_s: float,+ done: bool = False,+ reason: str = "done",+ backend_dead: bool = False,+ hourglass: str = "⏳",+ steps: int = 0,+ ) -> str:+ elapsed = self._format_elapsed(elapsed_s)+ token_field = self._token_field(context)+ if done:+ # Terminal footer: a reason word with a marker (✅ clean "done", ⏹+ # "stopped"/"failed"). Elapsed time is appended only when show_duration+ # is on (matches result-message duration gating); the session token+ # total is kept so the final bubble still reports usage.+ marker = "✅" if reason == "done" else "⏹"+ footer = f"{marker} {self._t('status.' + reason)}"+ if self._show_duration():+ footer += f" · {elapsed}"+ if token_field:+ footer += f" · {token_field}"+ return footer+ if backend_dead:+ return f"⚠️ {self._t('status.backendUnresponsive')} · {elapsed}"+ # Running footer (compact, one mobile line): ``{hourglass} {elapsed}[ ·+ # {n} st][ · {tokens}]``. The hourglass glyph cycles ⏳/⌛ across renders+ # for a zero-width "alive" motion; 0-value fields are omitted so turn+ # start is just ``⏳ 0s``. The "time since last activity" lives in the+ # BODY (attached to the current action) instead of a standalone field.+ footer = f"{hourglass} {elapsed}"+ if steps > 0:+ footer += f" · {self._t('status.steps', count=steps)}"+ if token_field:+ footer += f" · {token_field}"+ return footer++ def _decorate_body_with_action_time(+ self, context: MessageContext, body: str, action_elapsed_s: float, *, backend_dead: bool+ ) -> str:+ """Append the current action's own runtime to the body once it crosses+ ``_ACTION_TIME_HINT_S`` (e.g. ``🔧 Bash · 2:30``). This value is driven by+ the heartbeat clock, so it keeps climbing during a single long operation+ and reads as "actively running" rather than "stuck". A ⚠️ is added once it+ exceeds the no-output threshold while the backend is still alive."""+ if not body or action_elapsed_s < _ACTION_TIME_HINT_S:+ return body+ emphasis = "⚠️ " if (not backend_dead and action_elapsed_s >= self._no_output_hint_after_s(context)) else ""+ return f"{body} · {emphasis}{self._format_elapsed(action_elapsed_s)}"++ def _compose_status_message(+ self,+ context: MessageContext,+ consolidated_key: str,+ *,+ done: bool = False,+ reason: str = "done",+ result_body: Optional[str] = None,+ ) -> tuple[str, str]:+ """Return ``(body, footer)`` for the status bubble.++ The IM adapters own footer styling (Slack native context block, Discord+ ``-#`` subtext), so core hands them the two pieces separately via the+ ``subtext`` parameter rather than merging them into one string. The body+ may be empty (no action label yet) — adapters then render footer-only.+ """+ body = result_body if result_body is not None else self._consolidated_message_buffers.get(consolidated_key, "")+ now = self._now()+ started = self._status_started_at.get(consolidated_key, now)+ elapsed_s = now - started+ if done:+ footer = self._status_footer_text(context, elapsed_s=elapsed_s, done=True, reason=reason)+ else:+ last = self._status_last_activity_at.get(consolidated_key, started)+ tick = self._status_render_tick.get(consolidated_key, 0)+ self._status_render_tick[consolidated_key] = tick + 1+ hourglass = "⏳" if tick % 2 == 0 else "⌛"+ backend_dead = self._backend_dead(context)+ body = self._decorate_body_with_action_time(+ context, body, now - last, backend_dead=backend_dead+ )+ footer = self._status_footer_text(+ context,+ elapsed_s=elapsed_s,+ backend_dead=backend_dead,+ hourglass=hourglass,+ steps=self._status_step_count.get(consolidated_key, 0),+ )+ return body, footer++ def _start_status_heartbeat(+ self,+ context: MessageContext,+ im_client,+ consolidated_key: str,+ ) -> None:+ # One heartbeat per turn-key. The loop re-reads the CURRENT bubble id each+ # tick, so a re-sent bubble (after an edit failure) keeps its timer without+ # churning tasks (Nit N1).+ existing = self._status_heartbeat_tasks.get(consolidated_key)+ if existing and not existing.done():+ return+ try:+ task = asyncio.create_task(+ self._status_heartbeat_loop(context, im_client, consolidated_key)+ )+ except RuntimeError:+ # No running loop (sync test context) — heartbeat is optional liveness.+ return+ self._status_heartbeat_tasks[consolidated_key] = task++ async def _status_heartbeat_loop(+ self,+ context: MessageContext,+ im_client,+ consolidated_key: str,+ ) -> None:+ try:+ while True:+ await asyncio.sleep(self._heartbeat_interval_s(context))+ # Stop if the turn was superseded or the bubble is gone.+ if not self._is_current_runtime_turn(context):+ return+ message_id = self._consolidated_message_ids.get(consolidated_key)+ if not message_id:+ return+ await self._status_heartbeat_render_once(context, im_client, consolidated_key, message_id)+ except asyncio.CancelledError:+ return++ async def _status_heartbeat_render_once(+ self,+ context: MessageContext,+ im_client,+ consolidated_key: str,+ message_id: str,+ ) -> None:+ lock = self._get_consolidated_message_lock(consolidated_key)+ async with lock:+ # Bail if the turn finalized (result delivered → bubble about to be+ # deleted/collapsed) since this tick was scheduled, so a stray tick+ # can't re-render a bubble that's being retired (mirrors the C1 guard+ # in _render_concise_status).+ if consolidated_key in self._status_finalized:+ return+ if self._consolidated_message_ids.get(consolidated_key) != message_id:+ return+ body, footer = self._compose_status_message(context, consolidated_key)+ target_context = self._get_target_context(context)+ try:+ await im_client.edit_message(+ target_context, message_id, text=body, parse_mode="markdown", subtext=footer+ )+ except asyncio.CancelledError:+ # Blocker: must propagate so task.cancel() actually terminates the+ # loop; swallowing it makes _stop_status_heartbeat's await hang.+ raise+ except Exception as err:+ logger.debug("heartbeat edit failed for %s: %s", message_id, err)++ async def _stop_status_heartbeat(self, consolidated_key: str) -> None:+ task = self._status_heartbeat_tasks.pop(consolidated_key, None)+ if task is None:+ return+ task.cancel()+ try:+ await task+ except (asyncio.CancelledError, Exception):+ 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":+ return None+ return self._consolidated_message_ids.get(self._get_consolidated_message_key(context))++ async def _finalize_status_key(self, consolidated_key: str) -> Optional[str]:+ """Atomically mark a turn-key finalized and capture its current bubble id.++ Acquiring the per-key consolidated lock makes "add to ``_status_finalized``+ + read the bubble id" indivisible against a concurrent+ ``_render_concise_status`` (which takes the same lock and bails when the+ key is already finalized). So a late in-flight process emit either runs+ BEFORE this finalize (its bubble id is then the one we collapse/edit) or+ sees the key finalized and bails — it can never land after the terminal+ edit and stomp the bubble back to "working" (C1)."""+ async with self._get_consolidated_message_lock(consolidated_key):+ # Finalized markers persist past _drop_status_keys (see note there) so+ # they must be bounded. A marker only needs to outlive its own turn's+ # teardown→gate-release window (sub-second), so when the set grows large+ # every entry in it is from a turn finished long ago and safe to drop;+ # clear before re-adding THIS turn's key so the live one always remains.+ if len(self._status_finalized) > 512:+ self._status_finalized.clear()+ self._status_finalized.add(consolidated_key)+ return self._consolidated_message_ids.get(consolidated_key)++ async def _collapse_status_bubble(+ self, context: MessageContext, im_client, *, reason: str = "done"+ ) -> None:+ """Collapse a still-open concise status bubble to its terminal marker.++ Single helper for every terminal path that DOESN'T edit the bubble into a+ visible answer: a terminal result that delivered nothing visible (empty /+ silent / suppressed), and the non-inline orphan path (B3) where the result+ was delivered as a separate message. Without it, an eagerly-posted+ footer-only ``begin_status_bubble`` (or a still-running process bubble)+ stays stuck on its last state when the turn ends (missing agent,+ exception, user stop, attachment-only delivery).++ It stops the heartbeat first (so no late tick stomps the marker), then+ marks the key finalized + captures the bubble id atomically (C1), then —+ 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)+ # 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)+ bubble_id = await self._finalize_status_key(key)+ if not bubble_id:+ return+ elapsed_s = self._now() - self._status_started_at.get(key, self._now())+ marker = self._status_footer_text(context, elapsed_s=elapsed_s, done=True, reason=reason)+ target_context = self._get_target_context(context)+ try:+ # Render the marker as the footer (empty body → footer-only bubble) so+ # the edit goes through the status-block path and REPLACES the bubble's+ # blocks. A plain text-only chat.update would leave the old "running"+ # Slack blocks visible, hiding the terminal marker (P2).+ await im_client.edit_message(target_context, bubble_id, text="", subtext=marker, parse_mode="markdown")+ except Exception as err:+ logger.debug("Failed to collapse status bubble %s: %s", bubble_id, err)++ async def _retire_status_bubble(+ self,+ context: MessageContext,+ im_client,+ bubble_id: str,+ *,+ delivered: bool,+ reason: str = "done",+ ) -> None:+ """Retire the transient status bubble once the result is delivered as its+ own message. DELETE it (so the turn ends as just the fresh, notifying+ result) when the platform supports deletion and the result was delivered;+ otherwise collapse it to a terminal marker (the prior behavior) so it never+ lingers as "running"."""+ if delivered and self._capabilities(context).supports_message_deletion:+ try:+ if await im_client.delete_message(self._get_target_context(context), bubble_id):+ return+ except Exception as err:+ logger.debug("Failed to delete status bubble %s; collapsing instead: %s", bubble_id, err)+ await self._collapse_status_bubble(context, im_client, reason=reason)def _record_suppressed_run_message(self,@@ -284,6 +887,7 @@ class ConsolidatedMessageDispatcher:message_id: str | None,*,is_error: bool,+ log_label: str = "agent run terminal result",) -> None:payload = context.platform_specific or {}if payload.get("task_trigger_kind") != "agent_run":@@ -302,7 +906,7 @@ class ConsolidatedMessageDispatcher:terminal_status="failed" if is_error else "succeeded",)except Exception as err:- logger.warning("Failed to record agent run terminal result for %s: %s", ",".join(run_ids), err)+ logger.warning("Failed to record %s for %s: %s", log_label, ",".join(run_ids), err)finally:if store is not None:store.close()@@ -315,31 +919,13 @@ class ConsolidatedMessageDispatcher:*,is_error: bool,) -> None:- payload = context.platform_specific or {}- if payload.get("task_trigger_kind") != "agent_run":- return- run_ids = _coalesced_task_execution_ids(payload)- if not run_ids:- return- store = None- try:- store = SQLiteBackgroundTaskStore()- self._record_agent_run_terminal_for_ids(- store=store,- run_ids=run_ids,- text=text,- message_id=message_id,- terminal_status="failed" if is_error else "succeeded",- )- except Exception as err:- logger.warning(- "Failed to record suppressed agent run terminal result for %s: %s",- ",".join(run_ids),- err,- )- finally:- if store is not None:- store.close()+ self._record_agent_run_terminal_result(+ context,+ text,+ message_id,+ is_error=is_error,+ log_label="suppressed agent run terminal result",+ )async def clear_consolidated_message_id(self,@@ -350,16 +936,10 @@ class ConsolidatedMessageDispatcher:thread_key = context.thread_id or context.channel_idmsg_id = trigger_message_id if trigger_message_id else (context.message_id or "")key = f"{session_key}:{thread_key}:{msg_id}"-- lock = self._get_consolidated_message_lock(key)- async with lock:- self._consolidated_message_ids.pop(key, None)- self._consolidated_message_buffers.pop(key, None)+ await self._drop_status_keys(key)def _get_consolidated_max_bytes(self, context: MessageContext) -> int:- platform = (- context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform- )+ platform = self._get_platform(context)if platform == "discord":return 2000if platform == "wechat":@@ -367,9 +947,7 @@ class ConsolidatedMessageDispatcher:return 4000def _get_consolidated_split_threshold(self, context: MessageContext) -> int:- platform = (- context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform- )+ platform = self._get_platform(context)if platform == "discord":return 1800if platform == "wechat":@@ -381,25 +959,17 @@ class ConsolidatedMessageDispatcher:return len(text.encode("utf-8"))def _get_result_max_chars(self, context: MessageContext) -> int:- platform = (- context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform- )- if platform == "discord":+ if self._get_platform(context) == "discord":return 1900return 30000def _get_result_max_bytes(self, context: MessageContext) -> Optional[int]:- platform = (- context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform- )- if platform == "wechat":+ if self._get_platform(context) == "wechat":return _WECHAT_TEXT_LIMITreturn Nonedef _should_split_long_result(self, context: MessageContext) -> bool:- return (- context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform- ) in {"discord", "wechat"}+ return self._get_platform(context) in {"discord", "wechat"}def _result_within_limit(self, context: MessageContext, text: str) -> bool:max_bytes = self._get_result_max_bytes(context)@@ -411,11 +981,7 @@ class ConsolidatedMessageDispatcher:return self._capabilities(context).supports_quick_repliesdef _is_wechat_context(self, context: MessageContext) -> bool:- return (- context.platform- or (context.platform_specific or {}).get("platform")- or self.controller.config.platform- ) == "wechat"+ return self._get_platform(context) == "wechat"def _supports_message_editing(self, im_client, context: MessageContext) -> bool:supports_editing = getattr(im_client, "supports_message_editing", None)@@ -545,6 +1111,7 @@ class ConsolidatedMessageDispatcher:*,is_error: bool = False,level: str = "normal",+ status_label: Optional[str] = None,) -> Optional[str]:"""Centralized dispatch for agent messages.@@ -570,6 +1137,12 @@ class ConsolidatedMessageDispatcher:Used for intentional, non-noteworthy lifecycle events (e.g. a user-initiated stop) so the turn ends cleanly with no user-facing bubble —replacing the old "fake it with empty text" trick with an explicit flag.++ ``status_label`` is an optional backend-computed clean tool-call label+ (claude-pipe style) used ONLY as the concise status-bubble body for the+ process path (assistant/toolcall). The persisted row and the verbose+ append path keep using the original ``text`` unchanged; when it is empty+ the bubble falls back to ``to_status_label(text)`` as before."""settings_manager = self.controller.get_settings_manager_for_context(context)im_client = self._get_im_client(context)@@ -577,6 +1150,13 @@ class ConsolidatedMessageDispatcher:canonical_type = settings_manager._canonicalize_message_type(message_type or "")settings_key = self._get_settings_key(context)+ # Terminal status-bubble reason word for the done/orphan footer:+ # a clean turn is "done" (✅); a failure is "stopped" (⏹) when it was an+ # intentional silent stop (e.g. user stop), else "failed" (⏹). Computed+ # here where both is_error + level are known, then threaded into the+ # compose/tidy helpers so the footer marker stays consistent.+ terminal_reason = "done" if not is_error else ("stopped" if level == "silent" else "failed")+# OUTBOUND status chokepoint (one of exactly two — the other is the# inbound AgentService.handle_message). A terminal ``result`` ends the# turn, so settle the avibe sidebar dot here regardless of delivery@@ -606,6 +1186,9 @@ class ConsolidatedMessageDispatcher:# A terminal result — even silent/empty — still means the turn# finished: release the streaming SSE waiter so it closes now# instead of hanging until the safety timeout, with no visible chunk.+ # Collapse any eagerly-posted footer-only bubble first so it+ # doesn't stay stuck (missing agent / exception / user stop).+ await self._collapse_status_bubble(context, im_client, reason=terminal_reason)await self._clear_consolidated_state(context)self._record_agent_run_terminal_result(context,@@ -672,6 +1255,9 @@ class ConsolidatedMessageDispatcher:terminal_status=terminal_status,)if canonical_type == "result":+ # A suppressed result still ends the turn; collapse any concise+ # status bubble posted to a real channel so it doesn't stay stuck.+ await self._collapse_status_bubble(context, im_client, reason=terminal_reason)await self._clear_consolidated_state(context)self._signal_turn_complete(context)return message_id@@ -700,10 +1286,38 @@ class ConsolidatedMessageDispatcher:scheduled_anchor_message_id: Optional[str] = Nonedelivered_as_attachment = False+ # Concise status bubble (Slack/Discord): the live process bubble for+ # this turn. The result is ALWAYS delivered as a NEW message (never+ # an edit of the bubble) so the IM fires a push notification; the+ # transient bubble is then deleted (or collapsed to a marker when the+ # platform can't delete) by ``_retire_status_bubble`` below.+ status_bubble_id = self._concise_status_bubble_id(context)+ status_consolidated_key = self._get_consolidated_message_key(context) if status_bubble_id else None+ # S3: stop the heartbeat + finalize the key BEFORE delivery so a late+ # heartbeat tick / in-flight process emit can't resurrect the bubble+ # while we retire it (C1).+ if status_consolidated_key:+ await self._stop_status_heartbeat(status_consolidated_key)+ await self._finalize_status_key(status_consolidated_key)+# ``enhanced`` (extracted file links + quick-reply buttons) was# computed above for persistence; reuse it for delivery.display_text = enhanced.text if enhanced.text.strip() else text+ # The concise done-footer (``✅ done · 248k tok``) is attached to the+ # fresh result message as platform subtext so the turn's final+ # outcome + context-window usage survives the bubble's deletion.+ done_footer: Optional[str] = None+ if status_consolidated_key:+ _, done_footer = self._compose_status_message(+ context, status_consolidated_key, done=True, reason=terminal_reason, result_body=display_text+ )+ # Pass subtext to RAW send_message calls only when set, so an adapter+ # whose send_message predates the subtext kwarg is never handed it+ # (the helper paths apply the same guard internally).+ footer_kwargs = {"subtext": done_footer} if done_footer else {}++ # Deliver the result as a NEW message: inline / split / summarized.if self._result_within_limit(context, display_text):try:primary_message_id = await self._send_result_inline(@@ -712,6 +1326,7 @@ class ConsolidatedMessageDispatcher:display_text,enhanced.buttons if enhanced else [],parse_mode,+ subtext=done_footer,)scheduled_anchor_message_id = primary_message_idexcept Exception as err:@@ -719,7 +1334,7 @@ class ConsolidatedMessageDispatcher:logger.warning("Failed to send result with quick replies, falling back: %s", err)try:primary_message_id = await im_client.send_message(- target_context, display_text, parse_mode=parse_mode+ target_context, display_text, parse_mode=parse_mode, **footer_kwargs)scheduled_anchor_message_id = primary_message_idexcept Exception as fallback_err:@@ -734,23 +1349,28 @@ class ConsolidatedMessageDispatcher:display_text,enhanced.buttons if enhanced else [],parse_mode,+ subtext=done_footer,)scheduled_anchor_message_id = primary_message_idexcept Exception as err:logger.error("Failed to send split result messages: %s", err)else:+ # Summary path (too big to send inline, not splittable): post a+ # short summary AND attach the full content as a .md file. The+ # attachment supplements ONLY this path — inline/split already+ # deliver the full result, so they don't upload.summary = self._build_result_summary(display_text, self._get_result_max_chars(context))try:- primary_message_id = await im_client.send_message(target_context, summary, parse_mode=parse_mode)+ primary_message_id = await im_client.send_message(+ target_context, summary, parse_mode=parse_mode, **footer_kwargs+ )scheduled_anchor_message_id = primary_message_idexcept Exception as err:logger.error("Failed to send result summary: %s", err)- if (- context.platform- or (context.platform_specific or {}).get("platform")- or self.controller.config.platform- ) in {"slack", "discord", "telegram", "lark"} and hasattr(im_client, "upload_markdown"):+ if self._get_platform(context) in {"slack", "discord", "telegram", "lark"} and hasattr(+ im_client, "upload_markdown"+ ):try:attachment_message_id = await im_client.upload_markdown(target_context,@@ -802,6 +1422,7 @@ class ConsolidatedMessageDispatcher:display_text,enhanced.buttons if enhanced else [],parse_mode,+ subtext=done_footer,)scheduled_anchor_message_id = primary_message_idlogger.info("Result delivered via split messages (fallback)")@@ -831,10 +1452,29 @@ class ConsolidatedMessageDispatcher:except Exception as err:logger.warning("Failed to finalize scheduled delivery anchor: %s", err)+ # Retire the transient status bubble now the result is delivered as+ # its own (notifying) message: DELETE it so the turn ends as just the+ # fresh result. When the platform can't delete (or the delete fails,+ # or nothing was delivered) fall back to collapsing it to a terminal+ # marker (✅ done / ⏹ stopped|failed) so it never reads as running.+ if status_bubble_id:+ await self._retire_status_bubble(+ context,+ im_client,+ status_bubble_id,+ delivered=primary_message_id is not None,+ reason=terminal_reason,+ )+# Final result closes the current turn: clear consolidated# assistant/tool/system message state so the next user turn starts# a fresh log message instead of appending to the previous one.- await self._clear_consolidated_state(context)+ # Use the key captured at the top of this branch when present so+ # teardown can't drift onto a recomputed key (C5).+ if status_consolidated_key:+ await self._drop_status_keys(status_consolidated_key)+ else:+ await self._clear_consolidated_state(context)self._record_agent_run_terminal_result(context,@@ -924,6 +1564,16 @@ class ConsolidatedMessageDispatcher:if not self._supports_message_editing(im_client, context):return await self._send_unconsolidated_log_message(im_client, context, chunk)+ # Concise status bubble (Slack/Discord): one replace-not-append line that+ # is later edited into the result. ``off`` shows no process bubble at all+ # (typing + final result only). ``verbose`` falls through to the legacy+ # append/split consolidation below (and is the path for all other platforms).+ progress_style = self._concise_progress_style(context)+ if progress_style == "off":+ return None+ if progress_style == "concise":+ return await self._render_concise_status(im_client, context, chunk, status_label=status_label)+consolidated_key = self._get_consolidated_message_key(context)lock = self._get_consolidated_message_lock(consolidated_key)@@ -1065,14 +1715,20 @@ class ConsolidatedMessageDispatcher:text: str,buttons,parse_mode,+ subtext: Optional[str] = None,) -> str:keyboard = Noneif buttons and self._supports_quick_replies(context):keyboard = self._build_quick_reply_keyboard(context, buttons)+ # ``subtext`` (the concise done-footer) is only set for status-bubble+ # platforms; pass it as a kwarg ONLY when present so non-bubble adapters+ # whose senders don't accept ``subtext`` are never handed it.+ footer = {"subtext": subtext} if subtext else {}+native_markdown_sender = getattr(im_client, "send_markdown_message", None)if parse_mode == "markdown" and callable(native_markdown_sender):- return await native_markdown_sender(context, text, keyboard=keyboard)+ return await native_markdown_sender(context, text, keyboard=keyboard, **footer)if keyboard is not None:return await im_client.send_message_with_buttons(@@ -1080,9 +1736,10 @@ class ConsolidatedMessageDispatcher:text,keyboard,parse_mode=parse_mode,+ **footer,)- return await im_client.send_message(context, text, parse_mode=parse_mode)+ return await im_client.send_message(context, text, parse_mode=parse_mode, **footer)async def _send_split_result_messages(self,@@ -1091,30 +1748,51 @@ class ConsolidatedMessageDispatcher:text: str,buttons,parse_mode,+ subtext: Optional[str] = None,) -> Optional[str]:+ """Deliver a long result as multiple fresh messages.++ Quick-reply buttons and the ``subtext`` done-footer both ride on the LAST+ chunk (a mid-stream footer would read wrong); every chunk is a new send so+ the result notifies. Returns the first chunk's id (the delivery anchor).+ """chunks = self._split_result_text_for_context(context, text)first_message_id: Optional[str] = Nonefor index, chunk in enumerate(chunks):is_last_chunk = index == len(chunks) - 1+ want_buttons = is_last_chunk and buttons and self._supports_quick_replies(context)+ chunk_subtext = subtext if is_last_chunk else Nonemessage_id: Optional[str] = None- if is_last_chunk and buttons and self._supports_quick_replies(context):+ if want_buttons:try:message_id = await self._send_result_inline(- im_client,- context,- chunk,- buttons,- parse_mode,+ im_client, context, chunk, buttons, parse_mode, subtext=chunk_subtext)except Exception as err:logger.warning("Failed to send split result chunk with quick replies, falling back: %s", err)if message_id is None:- message_id = await self._send_result_inline(im_client, context, chunk, [], parse_mode)+ # A later-chunk failure must NOT propagate so an earlier delivered+ # chunk isn't lost — best-effort, log, continue.+ try:+ message_id = await self._send_result_inline(+ im_client, context, chunk, [], parse_mode, subtext=chunk_subtext+ )+ except Exception as err:+ logger.warning("Failed to send split result chunk %d: %s", index, err)+ message_id = None++ if index == 0 and message_id is None:+ # The HEAD chunk failed: abandon the split and return None so the+ # caller's fallback delivers the COMPLETE content (e.g. as a .md+ # upload). Returning a later chunk's id here would mark a head-less+ # partial — the user seeing only the tail — as a successful delivery.+ logger.warning("Split result head chunk failed to send; abandoning partial split")+ return None- if first_message_id is None:+ if first_message_id is None and message_id is not None:first_message_id = message_idreturn first_message_iddiff --git a/core/processing_indicator.py b/core/processing_indicator.pyindex ca4074ef0..ade9d959b 100644--- a/core/processing_indicator.py+++ b/core/processing_indicator.py@@ -140,6 +140,16 @@ class ProcessingIndicatorService:if mode in _PROCESSING_INDICATOR_MODES and mode not in candidates[:index]]+ def _concise_status_bubble_active(self, context: MessageContext) -> bool:+ check = getattr(self.controller, "uses_concise_status_bubble", None)+ if not callable(check):+ return False+ try:+ return bool(check(context))+ except Exception:+ logger.debug("uses_concise_status_bubble check failed; not suppressing", exc_info=True)+ return False+def _processing_modes(self, context: MessageContext) -> list[str]:capabilities = self._capabilities(context)return [@@ -186,6 +196,19 @@ class ProcessingIndicatorService:if not enabled:return handle+ if self._concise_status_bubble_active(context):+ # The concise status bubble is the primary progress indicator, but we+ # still want the lightweight 👀 received-ack reaction AND typing+ # keepalive (both best-effort, both cleaned up on finish). We only drop+ # the ack MESSAGE mode — a separate text bubble would duplicate the+ # status bubble and can't be deleted on Slack. (B2)+ capabilities = self._capabilities(context)+ if self._mode_supported(capabilities, "reaction", context):+ await self._start_reaction_indicator(handle)+ if self._mode_supported(capabilities, "typing", context):+ await self._start_typing_indicator(handle)+ return handle+for mode in self._processing_modes(context):if mode == "message" and await self._start_message_indicator(handle, agent_name):return handlediff --git a/docs/plans/HANDOFF-status-bubble.md b/docs/plans/HANDOFF-status-bubble.mdnew file mode 100644index 000000000..57d2808b1--- /dev/null+++ b/docs/plans/HANDOFF-status-bubble.md@@ -0,0 +1,124 @@+# HANDOFF — 状态条 P0 实现(断点续传用)++> 给"被清空上下文后的我 / 接力者"看。读完这份 + `agent-progress-status-bubble.md`(完整 spec) 就能无损继续。+> **恢复方法**:先 `git -C <worktree> diff` 看已改动,再看下方"进度"与"任务清单(TaskList)",从第一个未完成任务继续。++## 环境+- Worktree:`/essd/qiqi/code/dev/avibe/.agents/worktrees/agent-progress-status-bubble`+- 分支:`feat/agent-progress-status-bubble`,基于 `alex/master`(remote `alex` = github.com/avibe-bot/avibe)。+- 完整设计:`docs/plans/agent-progress-status-bubble.md`(已定稿,含 §1-§12 + 评审折回)。+- 工作目录命令一律用绝对路径或 `git -C`,避免 cd 权限弹窗。++## 目标(两诉求)+1. 不污染消息列表:一轮跑完只剩一条结果,无过程残渣。+2. 推理状态可感知:长时间无新内容也能看出没挂。+仅 **Slack / Discord**(支持编辑)。其余平台回退现状、行为 byte-identical。++## 锁定决策(不要再推翻)+- concise = Slack/Discord **首版直接默认**。+- **Edit 优先**:状态条 edit 成 Result;Delete 仅"过程溢出成2+条"时删多余的。+- 过程状态条 = **单行替换**(不 append/不 split/不 continued-below);正文 = 当前动作标签。+- 持久化不变:store 仍存完整 process 行 + result 行;可视清理 ≠ 删数据。+- 计时是 **P1** 心跳驱动;**P0 不带计时**(静态 `⏳ 思考中` / `🔧 <动作>`)。+- 可感知=分层:进程心跳(已运行计时) + 后端存活探针 + 无输出提示 + ⏳ 保留(P1)。++## 评审必守(codex 两轮)+- **B1** 后端探针按后端分流:Claude `controller.receiver_tasks[key].done()`;Codex `CodexTransport.is_alive`(transport.py:157-164)。心跳落 agent 内、对外暴露 `backend_alive(context)->bool`。(P1)+- **B2** concise 下抑制 processing_indicator 的 ack 消息/reaction,仅留 typing;注意 Slack `supports_message_indicator_delete=False`,ack_mode=message 时不抑制会永久残留。+- **B3** result 6 路径只有 inline 与 edit 干净;其余(split/summary+.md/fallback/失败通知)在另发后必须清理孤儿状态条。+- **S1** ✅已做:`base_formatter.to_status_label()` 安全清洗(去反引号/首行/截断)。+- **S2** 新增 `_consolidated_overflow_ids: dict[str,list[str]]`,并在 `_clear_consolidated_state` 清。+- **S3** 取消心跳(await)→再 edit result,**不能塞 finally**;stop/error 路径也取消。(P1)+- **S4** Slack `edit_message` 返回 **bool**!edit 成功后 `primary_message_id = 已知气泡 id`,不可取返回值。+- **S5** dispatcher 侧 per-message `asyncio.Lock` 字典,把 cancel-heartbeat→edit-result 整段原子化。+- N1 last_activity 按 turn-key 存;N3 P0 无计时;N4 心跳 edit 包 `try/except CancelledError`。++## 关键落点(worktree 实测行号)+- `core/message_dispatcher.py`+ - `ConsolidatedMessageDispatcher.__init__` 状态字典 @114-117+ - `emit_agent_message` @539;result 分支 @697-891;process 块(assistant/toolcall/system) @893-1027+ - `_clear_consolidated_state` @225-230;`_get_consolidated_message_key` 附近+ - `_supports_message_editing` @420;`_send_unconsolidated_log_message` @517+ - split/threshold helpers @359-377+- `modules/im/formatters/base_formatter.py`:`to_status_label`(已加,顶部)、`format_toolcall`@374+- `modules/im/slack.py` / `modules/im/discord.py`:`edit_message`(Slack 返回 bool)、带按钮 edit、typing+- `core/processing_indicator.py`:`start()` / `_candidate_modes()`(B2 抑制点)+- `modules/agents/claude_agent.py`:`handle_message`@79、`receiver_tasks` 填充@123-126、toolcall emit@~611++## 实现切片(= TaskList)+- [x] T1 落点核对+- [x] T2 `to_status_label` helper + 实测+- [ ] T3 过程路径→单状态条一行替换(concise,Slack/Discord)+- [ ] T4 edit_message 带按钮 + dispatcher per-message 锁(S4/S5)+- [ ] T5 result 情况1 edit-into-result + 孤儿清理(B3) + indicator 抑制(B2)+- [ ] T6 单测 + ruff+- 后续 P1:心跳/计时/后端探针/无输出提示;P1 长结果切分首段 edit;P2 溢出删多余条。++## 如何判断 concise 生效(实现内部用)+平台是否 slack/discord + `_supports_message_editing` 为真 + progress_style!=off。建议加一个 `_use_concise_status(context)` 私有判定,集中口径。++## 测试 & lint+- 单测:`python3 -m pytest tests/<file> -q`(worktree 内)。新测放 `tests/`。+- lint:`ruff check <changed.py>`(push 前必跑)。+- 不重启本地 vibe;跨平台人工验证用 Incus(用户触发"回归测试"时)。++## 提交规范+- commit:`type(scope): summary`。先不 push,除非用户要求。已在 feature 分支。++## 进度日志(每步追加)+- 2026-06-24: 建 worktree(alex/master) + 带入 spec + 落点核对 + `to_status_label` 落地实测通过。下一步 T3。+- 2026-06-24: **P0 核心完成**(未提交,feature 分支工作区)。+ - `base_formatter.to_status_label()`:安全单行标签(去反引号/首行/截断,保留下划线)。+ - `message_dispatcher`:新增 `_progress_style`/`_concise_progress_style`/`_render_concise_status`/`_concise_status_bubble_id`/`_edit_bubble_into_result`/`_tidy_orphan_status_bubble`;`__init__` 加 `_consolidated_overflow_ids`;`_clear_consolidated_state` 清 overflow。+ - process 块:Slack/Discord 走单状态条**一行替换**(concise 默认;off=无气泡;verbose/其他平台=旧路径不变)。+ - result 分支:**case1 edit-into-result**(S4 用已知气泡 id),非 inline/edit 失败时**孤儿气泡收成 ✅**(B3)。**踩坑修复**:曾把原 `if/elif/else` 投递链拆成两个 `if` 导致 consumed=True 时落到 summary 误发第二条——已改成 `if status_bubble_consumed: pass / elif ...` 重新接好链。+ - 测试:`tests/test_message_dispatcher_status_bubble.py` 10 passed;既有 dispatcher 套件 61 passed(无回归);ruff 全过。+ - 验证用 python:`/essd/qiqi/code/dev/avibe/.venv/bin/python -m pytest <file> -q`(worktree 内 `uv run` 会因缺 ui/dist 构建失败,别用)。+- 2026-06-24: **P0 已 commit** `e72cb385`。+- 2026-06-24: **P1 完成**(未提交→见下条)。+ - `message_dispatcher`:注入时钟 `self._now`(可测);per-turn `_status_started_at`/`_status_last_activity_at`/`_status_heartbeat_tasks`。+ - footer:`_format_elapsed`/`_status_footer_text`(运行 `⏳ m:ss`、完成 `✅`、后端死 `⚠️`、久无输出提示)/`_compose_with_footer`(Discord `-#`、Slack 斜体小字)/`_compose_status_message`。+ - 心跳:`_start_status_heartbeat`/`_status_heartbeat_loop`(~30s, turn-token+bubble 守卫, `CancelledError` 安全)/`_status_heartbeat_render_once`(走 consolidated lock 串行 render↔heartbeat = S5 等效)/`_stop_status_heartbeat`。+ - **S3**:result 分支在任何 edit 前 `await _stop_status_heartbeat(key)`;`_clear_consolidated_state` 也先停心跳(在取锁前,避免与 heartbeat render 抢同一 lock 死锁)再清 timing。+ - **完成 footer**:edit-into-result 用 `_compose_status_message(done=True, result_body=display_text)` → `答案\n\n_✅ m:ss_`;孤儿 tidy → `✅ m:ss`。持久化/SSE 仍用干净 display_text(footer 仅在 IM edit)。+ - **B1 探针 hook**:`_backend_dead`→`controller.backend_alive(context)`(None/缺失=不判死,安全)。**注意:controller.backend_alive 尚未实现** → ⚠️ 暂不会真正触发;需后续在 controller 落地按后端分流(Claude `receiver_tasks[key].done()` / Codex `transport.is_alive`)。+ - i18n:`status.backendUnresponsive`/`status.noOutputFor` 加到 en.json/zh.json。+ - 测试:status_bubble 套件 17 passed(含 footer/心跳 render/S3 停心跳);既有 dispatcher 61 passed;ruff 全过。+- 2026-06-24: **Loop 续作(commit 链)**:+ - `f8cdd29d` Step A — backend_alive 真正生效(base/claude/service/controller 分层探针;Codex 暂 None)。+8 tests。+ - `2954e6fb` Step C — 长结果(Discord)首段 edit 进气泡(case2);`_send_split_result_messages` 加 `edit_first_message_id`。+ - `71165875` **评审修复**(codex 全量 diff 评审 issues-found → 已修):+ - **Blocker**:heartbeat render 吞了 `CancelledError` → `_stop` 永久 hang → 改为 `raise`;心跳循环改为每 tick 读当前 bubble id(一 turn 一 task,re-send 不丢计时)。+ - split 后续 chunk 失败不再外抛(否则首段已发却被判未消费→孤儿 ✅ 覆盖已发内容)。+ - `suppress_delivery` 结果路径补孤儿气泡 tidy。+ - `clear_consolidated_message_id` 补停心跳+清 timing。+ - +2 回归测试(cancel-mid-edit 能终止;split 后续失败保留首段)。+ - 全量:status_bubble 套件 + backend_alive + result_fallback/platform_limits/scheduled = **74 passed**;ruff 全过。+- **目标达成(P0/P1)**:两诉求(不污染列表 + 状态可感知)在 Slack/Discord 已端到端实现、评审、修复、测试。++- 2026-06-24: **全设计目标 loop(每步过 opus+codex 双验收)**:+ - `a8c3bb5a` Step B — progress_style + 心跳/无输出阈值接 V2 config + controller getters + config_to_payload(防 partial-save 丢失) + 上下界 cap。+ - `0c6b6dbe` Step E — concise 下 indicator 行为:**保留 👀 received-ack reaction + typing keepalive**,仅抑制 ack **消息**(它会重复状态条且 Slack 删不掉);`Controller.uses_concise_status_bubble` 单一真源。逻辑在 `start()` 的 concise 分支(reaction+typing best-effort),非 first-wins。+ - `ad0af1c0` Step D — Codex backend_alive(transport.is_alive);删不可达 overflow 脚手架。+ - `d82aa567` Step F — footer 下沉适配器:Slack context block / Discord `-#`;core 改传 (body, footer);base 抽象加 `subtext`,Multi 仅 set 时转发(不破坏其它适配器)。+ - 每步 opus(general-purpose)+codex-expert 双评审,blocker/should-fix 当轮修复并加回归测试。+- `b030d757` **Web UI 开关** — Messaging 设置页 CompactSelect(精简/详细/关闭) for `agent_progress_style`,i18n en/zh,`npm run build` 通过。opus+codex ACCEPT(修复了编辑碰撞误删的 `appShell.moreSettings`)。+- **设计目标状态:spec 全部目标(后端 + 前端)已完成并逐轮 opus+codex 验收,共 12 commits。**+ - 注意:Web UI 子代理误改了**主 checkout**(master 工作区);已把 3 个 UI 文件搬回 worktree 并 `git checkout` 还原 master,worktree ui 用软链 node_modules 重新 build 验证。+- **运行测试**:worktree 内 `/essd/qiqi/code/dev/avibe/.venv/bin/python -m pytest ... -p no:cacheprovider`;UI build `cd ui && npm run build`(node_modules 为指向主 checkout 的软链,gitignore)。+- **未推送/未发 PR**(按用户明确约束,等其指示)。++- **历史/已被取代的"剩余"清单(多已完成,仅留档)**:+ - **B 设置 plumbing**:`progress_style`(concise/off/verbose)+心跳/无输出阈值 接 V2 config + Web UI(现 dispatcher 已用安全默认 concise;getter 缺失即降级)。需动 config schema + React UI = 独立 PR 量级。+ - **E B2 indicator 抑制**:仅 `ack_mode=message`(非默认)才双信号;依赖 B 的 progress_style 解析。+ - **D case3 溢出删多余条**:状态条天生单行短、几乎不溢出 → 极低价值;`_consolidated_overflow_ids` 已预埋。+ - **F Slack context-block footer**:现用斜体小字近似,可升级为 `[section,context]`。+ - **Codex backend_alive**:transport 解析后接 `is_alive`(现 None 安全)。+ - **(原始遗留)** controller.backend_alive —— 已在 Step A 实现。+ - **Slack context block footer**:当前用斜体小字近似;可升级为 `[section, context]`(评审 B5)。+ - **Discord footer 字节预算**:edit-into-result 给 display_text 追加 footer ~15B,理论上 +footer 可能逼近 2000;当前 within_limit 用 1900 字符判定,余量足够,但严格起见可在判定时预留 footer 字节。+ - **B2 indicator 抑制**:concise 下抑制 ack 消息/reaction。默认 Slack ack=typing 无双信号,故 P0 不阻塞;待 `progress_style` 设置 plumbing 落地后随 P1 一起做(注意 Slack `supports_message_indicator_delete=False` 的 ack 残留)。+ - **P1**:心跳(已运行计时)+后端分流探针(B1)+typing 保活+"无输出"提示+取消心跳→edit 顺序(S3)+per-message 锁(S5,心跳并发才需要)+计时 footer(Discord `-#`/Slack context block)。+ - **P1**:result 情况2(长结果切分首段 edit)。**P2**:情况3(溢出删第2+条,用 `_consolidated_overflow_ids`)。+ - **设置 plumbing**:`get_progress_style_for_context` 目前 controller 未实现 → `_progress_style` 默认 concise;待接 V2 config/Web UI(concise/verbose/off + heartbeat/no_output 阈值)。+ - 未 commit(按规范等用户指示)。建议 commit msg:`feat(im): concise status bubble for slack/discord (P0)`。diff --git a/docs/plans/agent-progress-status-bubble.md b/docs/plans/agent-progress-status-bubble.mdnew file mode 100644index 000000000..b3d546e59--- /dev/null+++ b/docs/plans/agent-progress-status-bubble.md@@ -0,0 +1,155 @@+# 过程消息精简方案 —— 「会变成结果的状态条」(Slack / Discord)++> 状态:**已定稿(精简版)**。取代此前两份较重的方案(已删)。经 codex-expert 两轮评审(sound-with-changes),3 Blocker / 5 Should-fix / 5 Nit 已折回。+> 范围:Slack / Discord(支持原地编辑 + typing)。其余平台回退现状、不受影响。+> 只为解决两个核心诉求:+> 1. **不污染消息列表**:一轮跑完只留一条结果,不留过程残渣。+> 2. **推理状态可感知**:长时间没新内容也能看出"还活着、没挂"。++## 1. 一句话方案++整轮只维护**一条状态条**(复用现有合并气泡的 message_id),过程中显示一行极简状态 + 走动的计时;**结束时把这条状态条原地 `edit` 成最终结果**。常态下既不删消息、也不新发——一轮只剩一条结果。++## 2. 设计原则(按用户拍板)++- **优先 Edit,不用 Delete**:反正终态必须有一条 Result,就让状态条 edit 成 Result。+- **Delete 仅用于收尾清理**:唯一场景是"过程中一条装不下、发了 2 条"——这时删掉第 2 条、把第 1 条 edit 成 Result。属边缘兜底。+- **状态条一行替换、不累加**:永远短 → 几乎不会触发上面的多条/删除场景。+- **过程不丢**:完整过程照常持久化到 store;我们只精简 **IM 呈现**,Web/transcript 不变。++## 3. 状态条生命周期++单条消息,原地编辑:++| 阶段 | 正文(极简,单行替换) | 计时(P1 才有,见下) |+|---|---|---|+| 开始 | `⏳ 思考中` | `0:01` |+| 进行 | `🔧 <最新动作>` | `0:08` |+| 完成 | `<最终结果>` | footer `✅ 18s` |+| 停止/失败 | `⚠️ 已停止` / `❌ <一句话>` | `0:31` |++- 正文只显示"最新一个动作",**不拼接历史**(复用已 emit 的过程文本取最新一条,**无需新增结构化事件通道**)。+- **计时是 P1 心跳驱动的**(§5);P0 先不带计时,状态条是静态的 `⏳ 思考中` / `🔧 <动作>`(Nit N3,避免 P0 验收时问"计时呢")。+- **"当前动作"标签的提取(Should-fix S1)**:不能对 `format_toolcall` 输出**裸截 50 字**——它形如 `🔧 \`execute_command\` \`{"command":"pytest…"}\``,裸截会切坏反引号/JSON。需新增 `format_toolcall_status_label()`:只取工具名 + 单独截参数 + 去反引号。assistant 文本是多行(`\n\n` join),取**首行截断**;真有思考文本时显示首行,**不要硬显示"思考中"**——仅在确无文本时才回落 `⏳ 思考中`。+- Discord 计时用 `-#` 小字;Slack 用 context block 小字。++## 4. 结果落地(三种情况)++> **评审 B3 提醒**:result 分支现有 6 条投递路径,只有 inline 与 edit 干净组合;其余需逐条处理(见下表与 §8 孤儿清理)。++| 路径 | edit-into-bubble 处理 |+|---|---|+| inline (`_send_result_inline`) | 拦截 `send_message`→`edit_message(bubble_id, …, keyboard=)`;干净 ✅ |+| split (`_send_split_result_messages`) | 首段改 edit、其余发新消息——需加 `first_message_id_to_edit` 参数 fork 现循环 |+| summary + `.md` upload | 摘要 edit 进气泡、附件另发;**注意 S4**(见下) |+| fallback upload / 失败通知 / 附件通知 | edit 失败时**状态条会变孤儿**,必须清理(§8) |++三种情况:+1. **常态(状态条 1 条 + 结果能放下)**:状态条 `edit` 成结果(带 quick-reply 按钮走 edit-with-buttons 通道)。**不删、不新发。**+2. **结果很长,一条装不下**:状态条 edit 成结果**第 1 段**,其余段作为新消息追加,按钮挂最后一段。沿用 `_split_result_text_by_bytes`,仅首段由 edit 现有气泡产出(split 函数加参数)。+3. **过程曾溢出成 2+ 条**(边缘):**删掉第 2..N 条**,把第 1 条按 1/2 规则 edit 成结果。++> **Should-fix S4(关键 bug 点)**:Slack `edit_message` **返回 `bool` 不是 message_id**(`slack.py:1469-1497`)。edit 成功后必须 `primary_message_id = <已知气泡 id>`,**不可** `= await edit_message(...)`(那会得到 `True`),否则 `finalize_scheduled_delivery`(`:830`) 与 `_stream_chunk` 全断。+> 结果走 `.md` 附件等兜底:逻辑不变,只把"首条结果消息"改为 edit 气泡产出,并按 S4 显式设 id。++## 5. 状态可感知(防"假死")—— 分层判断++"卡死"分三种,单一信号不够,分层侦测:++| 情况 | 侦测手段 |+|---|---|+| ① avibe 进程崩了/被杀 | **进程心跳**停 → footer 的"已运行"计时不再增长 |+| ② 后端(claude/codex)挂了/无响应 | **后端存活探针**(按后端分流,见下)→ 翻 `⚠️ 后端无响应` |+| ③ 长任务跑得久但正常 | 当前动作标签 + "已运行"在涨 = 正常 |++**后端存活探针必须按后端分流(Blocker B1)**:`controller.receiver_tasks`(`controller.py:177`)**只有 Claude 会填**(`claude_agent.py:123-126`);Codex 用 per-dir `CodexTransport`、不在其中 → 裸查会 `KeyError`,或 Claude 切 Codex 后残留 truthy 误判。故:+- Claude:`receiver_tasks[runtime_session_key].done()`;+- Codex:查该 session 活跃 transport 的 `CodexTransport.is_alive`(`transport.py:157-164`)。++→ 因此**心跳应落在各 agent 内部**(Claude agent 能拿 `receiver_tasks`,Codex agent 能拿自己的 transport),而非 dispatcher(拿不到 agent 句柄)。心跳通过 agent 暴露的统一接口(如 `backend_alive(context)->bool`)回报存活,dispatcher/渲染层只消费布尔值。++**进程心跳(必要,且非装饰)**:一个挂在 turn 上的心跳任务,每 ~30s 做两件实事:+1. 刷新 footer 的 **"已运行"计时**(mm:ss,由心跳驱动 → 长任务期间也在涨 = avibe 活着);+2. **按后端分流探存活**,没了就把 footer 翻成 `⚠️ 后端无响应`。+心跳 turn 结束即停、受 turn-token 守卫,stale turn 不刷;真实事件到来时即时重渲染(重置动作标签与"无输出"计时器)。`last_activity_at` 须**按 turn-key 存**(`dict[consolidated_key,float]`),避免跨 session 串扰(Nit N1)。心跳循环对自身 `edit` 调用要 `try/except CancelledError: return`,防取消时留半截状态(Nit N4)。++**残留盲区兜底**:后端活着但某工具内部死循环永不返回 —— 事件层无法与"超长正常任务"区分(avibe 故意不设 turn 超时,正经任务可能跑数小时)。用**温和提示**而非死亡判决:>N 分钟(默认 3min)无任何新活动时,footer 追加 `· 已 N 分钟无输出` 作为线索。++**typing 指示**:全程保活(Slack RTM / Discord `sendTyping`),与心跳双保险。++### footer 样式(保留沙漏 ⏳,辨识度)+```+运行中 -# ⏳ 运行 pytest · 4:30+久无输出 -# ⏳ 运行 pytest · 6:00 · 已 3 分钟无输出+后端无响应 -# ⚠️ 后端无响应 · 4:30+完成 -# ✅ 18s+```+- "已运行计时" = turn 开始至今,心跳驱动增长。+- Discord 用 `-#` 小字;Slack 用 context block 小字。++## 6. 相比"大方案"砍掉了什么++- ❌ 结构化进度事件旁路(`AgentProgressEvent`)——复用已 emit 的文本取最新一行即可。+- ❌ 平台中立渲染器抽象层——只做两平台,直接在适配器里拼 footer。+- ❌ `tidy_overflow` 能力位、批量删除。+- ❌ verbose/concise 双 pipeline 大改——过程路径从"累加+切分+continued below"改为"一行替换",多半是**净减代码**。++## 7. 实现落点 / 新增++- `core/message_dispatcher.py`+ - 过程合并块(~893-1027):Slack/Discord 走"单状态条、一行替换",去掉 append/split/`continued below`。+ - result 分支(~697-891):首条结果消息改为 **edit 现有状态条**(无气泡则回退现发送逻辑);按 §4 表逐路径处理;**edit 成功后按 S4 显式设 `primary_message_id`**;持久化(process 行 + result 行)不变。+ - 复用 `_consolidated_message_ids` 记状态条 id;**显式新增 `_consolidated_overflow_ids: dict[str,list[str]]`**(仅情况 3 用),并在 `_clear_consolidated_state`(`:225-230`) 一并清(Should-fix S2)。+ - **新增 per-message 编辑锁字典** `dict[message_id, asyncio.Lock]`,把"**取消心跳 → edit 结果**"整段**原子化**在锁内(Should-fix S5;光靠 Discord `_run_on_client_loop` 不够,会被心跳 edit 抢后写)。+ - `last_activity_at` 按 turn-key 存(N1)。+- 心跳:**落在各 agent 内部**(Claude/Codex 各自能拿存活句柄,B1),per-turn asyncio task,挂 turn 生命周期、受 turn-token 守卫;agent 暴露统一 `backend_alive(context)->bool` 给渲染层。+- `modules/im/slack.py` / `discord.py`+ - `edit_message` 支持带按钮(edit-into-result 用,避免 quick-reply 丢失)。**注意 Slack `edit_message` 返回 bool(S4)**。+ - footer 渲染:Discord `-#`、Slack context block。+ - 情况 3 需要 `delete_message`(删自己发的消息;两平台 API 简单,仅此一处用到)。+- `core/processing_indicator.py`(Blocker B2):concise 下**抑制 ack 消息/reaction、仅留 typing**。需落地一个抑制 hook——`start(..., suppress_message=True)` 或服务内读 `progress_style`。**额外**:Slack `supports_message_indicator_delete=False`,若部署配了 `ack_mode=message` 又不抑制,`finish()` 删不掉 ACK → **永久残留**;抑制 hook 必须覆盖这条路径。+- `modules/im/formatters/base_formatter.py`:新增 `format_toolcall_status_label()`(S1,干净提取工具名/截参数/去反引号)。+- `vibe/i18n/`:`status.thinking/working/done/stopped/stillRunning/backendUnresponsive` 等。++## 8. 边界处理++- **edit 失败 + 孤儿气泡清理(Blocker B3)**:edit 失败/走附件兜底/失败通知等路径会让状态条变孤儿(永远卡 `⏳`)。每条非 inline 路径在另发结果后,**必须把孤儿状态条 edit 成"✅/见上"或删除**,不可放任。回退新发本身不阻塞。+- **过程被频道隐藏**:没有状态条 → 只有 typing + 结果,更干净(结果走正常发送)。+- **Discord 长度**:状态条与"结果能否放下"判断要**预留 footer 字节**,否则撞 2000 上限。+- **顺序(防旧状态盖结果,Should-fix S3)**:**取消心跳(await 其结束) → 再 edit 成结果**,且这步**不能塞 `finally`**(`finally` 在 :889-891 与 indicator 清理并列,会与 edit 并发)。**stop / `is_error` / 异常**终态路径同样要取消心跳(不只正常 result);与 `release_runtime_turn` / `finish_terminal_turn` 钩子串起来。+- **持久化不退化**:edit/删除均不改 store 中 process/result 行(失败结果仍按 `error` 入库)。++## 9. 设置++频道级 `progress_style`:`concise`(**Slack/Discord 首版直接默认**,见 §11 分叉2)/ `off`(仅 typing + 结果)。+可调:`heartbeat_interval_ms`(默认 30000)、`no_output_hint_after_ms`(默认 180000,即 3min 触发"已 N 分钟无输出"提示)、`show_step_count`(默认关,先不显示步数保持最简)。状态条正文固定显示"当前动作"(已拍,见 §11);footer 保留 ⏳ 沙漏。++## 10. 实现顺序(最小切片)++> P0 **先不带计时**(计时随 P1 心跳落地)——状态条 P0 阶段是静态动作标签(Nit N3)。++1. **P0**|Slack/Discord 过程改"单状态条一行替换"(去 append/split)+ `format_toolcall_status_label()`(S1)+ `edit_message` 带按钮 + dispatcher 侧 per-message 编辑锁(S5)。+2. **P0**|result 情况 1:edit 状态条成结果(按 S4 设 id;含回退新发 + 孤儿清理 B3)+ indicator 抑制 hook(B2)。+3. **P1**|心跳计时 + 后端分流存活探针(B1)+ typing 保活 + 取消心跳→edit 顺序(S3)。+4. **P1**|result 情况 2(长结果切分,首段 edit)+ 无输出提示。+5. **P2**|result 情况 3(溢出删第 2+ 条,需 `_consolidated_overflow_ids` S2)—— 实际极少触发。++## 11. 决策++**已拍(分叉1)**:状态条正文**显示当前动作**`🔧 <最新动作>`(截断 ~50 字、剥 workspace 前缀;无工具回合显示 `⏳ 思考中`)。来源是**复用已 emit 的过程文本取最新一条**,仍**不引入结构化事件通道**——只是把现在"累加"改成"取最新一行替换"。属 P0 范围。++**已拍(分叉2)**:concise **首版直接设为 Slack / Discord 默认**(不灰度)。其余平台仍回退现状。++**已拍(分叉3)**:状态可感知采用**「进程心跳 + 后端探针 + 已运行计时 + 无输出提示」分层方案**(见 §5),而非单纯计时器或单纯时间戳。+- 心跳 ~30s(`heartbeat_interval_ms` 默认 30000,可调),驱动"已运行"计时增长 + 探后端存活;真实事件到来时即时重渲染并重置"无输出"计时器。+- 选"已运行计时(心跳驱动)"而非"事件驱动绝对时间戳"的原因:绝对时间戳在**长任务**中途无子事件时会冻结、误报卡死;心跳驱动的已运行计时在长任务期间仍增长,配合后端探针与"无输出"提示,能区分①avibe 死 ②后端死 ③长任务正常。+- 保留 ⏳ 沙漏图标(辨识度)。++## 12. 测试++- 单测:状态条一行替换不切分;result 情况 1/2/3;心跳刷新计时;取消心跳→edit 顺序无"旧状态盖结果"(含 stop/error 路径,S3);edit-into-result 不丢按钮;**edit 成功后 id 是气泡 id 不是 True(S4)**;Discord footer 字节预算不撞上限;**edit 失败/附件兜底后无孤儿状态条(B3)**;`_consolidated_overflow_ids` 在情况 3 后被清(S2)。+- **后端探针(B1)**:Claude 用 `receiver_tasks`、Codex 用 transport.is_alive;Claude→Codex 同 session 切换不误判;缺 key 不 `KeyError`。+- **标签提取(S1)**:`format_toolcall_status_label()` 不产生坏 markdown;assistant 多行取首行截断。+- **indicator(B2)**:concise 下 `ack_mode=typing` 与 `ack_mode=message` 均无残留 ACK,仅 typing。+- 持久化回归:concise 下 store 仍有完整 process + result 行。+- 人工:Incus 跑 Slack + Discord,确认①一轮一条结果②计时走动③无过程残渣④后端杀掉时翻 `⚠️ 后端无响应`。diff --git a/docs/plans/status-bubble-liveness-signals.md b/docs/plans/status-bubble-liveness-signals.mdnew file mode 100644index 000000000..c96106663--- /dev/null+++ b/docs/plans/status-bubble-liveness-signals.md@@ -0,0 +1,113 @@+# Status Bubble — Liveness Signals (A + B + C)++Addendum to `agent-progress-status-bubble.md`. Approved by the user via a+phone-width Show Page mockup (2026-06-25).++## Problem++The running footer's `Xs ago` (time since last activity) keeps growing during a+long single operation, so a healthy turn *looks* stuck. We need positive,+monotonically-increasing signals that prove work is still happening.++## Final design++Replace the `working…` word and the standalone `Xs ago` field. The running+footer becomes compact (≈28 chars, one mobile line):++```+start ⏳ 0s+normal ⌛ 18s · 6 st · 12.3k tok body: 🔧 Read: dispatcher.py+long op ⏳ 2:45 · 6 st · 12.3k tok body: 🔧 Bash · 2:30 (body ticks)+dead ⚠️ backend not responding · 2:45+done ✅ done · 248k tok (· 1:24 · when show_duration)+```++### A — Current context-window occupancy (footer)+Revised after the user clarified the figure should express **how much of the+current session's context window is in use** (so they can gauge remaining+headroom), NOT cumulative billing. It is a live SNAPSHOT — grows with the+conversation and DROPS after a /compact. Keyed by `session_key`, persists across+turns, kept on the terminal/done footer. Reported via `note_session_tokens(context,+*, total=…)` (SET, not accumulate).++Verified token sources (against installed `claude_agent_sdk 0.2.93` source ++`codex 0.141.0` / openai/codex protocol):+- **Claude** — the **latest** `AssistantMessage.usage` (the raw per-request+ Anthropic usage block) `= input_tokens + cache_read_input_tokens ++ cache_creation_input_tokens + output_tokens` = the full prompt for that request+ (= context) plus the response that joins it. SET on each assistant message →+ tracks live and the last one wins. (`ResultMessage.usage` is the CLI's+ CUMULATIVE turn usage — overstates occupancy — and is NOT used.)+- **Codex** — the `thread/tokenUsage/updated` notification's+ `tokenUsage.last.totalTokens` (the "latest active context size" the Codex CLI's+ own context bar uses); v1 fallback `info.last_token_usage.total_tokens`. NOT+ `tokenUsage.total` (cumulative). The previously-read `turn.usage` does NOT exist+ in the v2 app-server `Turn` object, so that path is removed.+- Display `{n} tok` with `12.3k / 248k / 1.4M` formatting; **omit when 0/unknown**.++### B — Current-action elapsed (body) — the anti-"stuck" signal+- `action_elapsed = now - last_activity_at` (resets on each real emit; heartbeat+ does NOT reset it). Appended to the body action label only when+ `action_elapsed >= 10s` (fixed `_ACTION_TIME_HINT_S`). Re-rendered by the+ heartbeat every ~15s → it keeps climbing during a single long op.+- When `action_elapsed >= no_output_hint_after_s` AND backend not dead, prefix+ the body time with `⚠️ ` ("unusually long"). This **repurposes the existing+ `agent_status_no_output_ms` config** (its old consumer, the footer `ago`+ emphasis, is removed) — no config churn.++### C — Step count (footer)+- `_status_step_count[turn_key]` increments once per real action emit+ (`_render_concise_status`; heartbeat re-renders are excluded). Display `{n} st`,+ omit when 0.++### Footer assembly+- Hourglass cycles `⏳`/`⌛` per render tick (replaces the `working…` dots) — zero+ width, keeps the "alive" motion.+- Running: `{hour} {turn_elapsed}[ · {n} st][ · {tokens}]`.+- Backend dead: unchanged.+- Terminal: `{marker} {reason}[ · {duration} when show_duration][ · {tokens}]`.++## i18n (vibe/i18n)+- Remove `status.working`, `status.ago` (no longer used).+- Add `status.steps` = `{count} st` / `{count} st`, `status.tokens` = `{count} tok` / `{count} tok`.+- Keep `done/stopped/failed/backendUnresponsive`.++## State (dispatcher)+- New: `_status_step_count: dict[str,int]` (turn-key, dropped in `_drop_status_keys`).+- New: `_session_token_total: dict[str,int]` (session-key, persists across turns).++## Out of scope / not done+- No new Web UI setting (no new knob).+- Codex live within-turn token growth (only per-turn at `turn/completed`); the+ body action-time covers liveness during a long Codex op.++## Slices+1. Dispatcher render + state + i18n + `note_session_tokens` + step counting + tests.+2. Claude token plumbing + test.+3. Codex token plumbing + test.+4. opus + codex acceptance; ruff; amend into the single commit.++## Result delivery: delete bubble + fresh result (notifications)++Editing the bubble into the final result means IM platforms fire NO push+notification for the result (edits don't notify). So the result is now ALWAYS+delivered as a NEW message and the transient bubble is retired:++- In-progress: post the bubble, edit it in place during the turn (unchanged).+- Result: send the answer as a fresh message (inline / split / summary) so the IM+ notifies. The fresh result carries the `✅ done · {tokens}` footer as platform+ subtext (Slack context block, Discord `-#`), so the outcome + context occupancy+ survive the bubble's deletion. `subtext` is now a first-class optional on+ `send_message_with_buttons` (Slack/Discord) and Slack `send_markdown_message`,+ passed only when set so non-bubble adapters are unaffected.+- Retire the bubble via `_retire_status_bubble`: DELETE it when the platform+ supports deletion (`PlatformCapabilities.supports_message_deletion`, new) and+ the result was delivered; otherwise fall back to collapsing it to a terminal+ marker (the prior behavior) so it never lingers as "running". Send-then-delete+ ordering: a failed send keeps the bubble (collapsed), never an empty void.+- New `delete_message(context, message_id) -> bool`: base default no-op (False),+ Slack `chat.delete`, Discord fetch+delete; Telegram already had it.+- Removed: `_edit_bubble_into_result` and the split-path bubble reuse+ (`edit_first_message_id`) — both obsolete under delete+resend. Also fixed a+ latent drift where the summary-path `.md` attachment ran for all result paths;+ it is back inside the summary `else` branch only.diff --git a/modules/agents/base.py b/modules/agents/base.pyindex 716d12d16..b614a31d3 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -113,6 +113,16 @@ class BaseAgent(ABC):"""Return runtime identities scoped to a persisted Avibe settings key."""return set()+ def backend_alive(self, context: Any) -> Optional[bool]:+ """Best-effort liveness of this backend for the given turn context.++ Returns ``True`` (alive), ``False`` (definitively gone), or ``None``+ (unknown — the default). Callers MUST treat ``None`` as alive so an+ unknown state never triggers a false "backend not responding" warning.+ The concise status bubble uses this to flip its footer to ⚠️.+ """+ return None+def mark_runtime_turn_started(self, context: Any) -> None:"""Mark the current gated turn as accepted by the backend runtime.diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 91a986e66..29f93aff1 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -189,6 +189,22 @@ class ClaudeAgent(BaseAgent):if callable(release):release(context)+ def backend_alive(self, context) -> Optional[bool]:+ """Liveness via the receiver task for this turn's runtime session.++ ``receiver_tasks`` is keyed by the Claude runtime session key. When that+ key matches the turn's ``AGENT_RUNTIME_TURN_KEY`` we know the answer; if+ it doesn't (e.g. a client-overridden runtime key) we return ``None`` so+ the caller never false-alarms."""+ payload = getattr(context, "platform_specific", None) or {}+ key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip()+ if not key:+ return None+ task = self.receiver_tasks.get(key)+ if task is None:+ return None+ return not task.done()+async def _handle_question_callback(self, request: AgentRequest) -> None:"""Handle question-related callbacks (button clicks, modal submissions).@@ -558,10 +574,17 @@ class ClaudeAgent(BaseAgent):# continuetoolcalls.append(- formatter.format_toolcall(- block.name,- block.input,- get_relative_path=lambda path: self.get_relative_path(path, context),+ (+ formatter.format_toolcall(+ block.name,+ block.input,+ get_relative_path=lambda path: self.get_relative_path(path, context),+ ),+ formatter.format_toolcall_label(+ block.name,+ block.input,+ get_relative_path=lambda path: self.get_relative_path(path, context),+ ),))elif isinstance(block, TextBlock):@@ -569,6 +592,14 @@ class ClaudeAgent(BaseAgent):if text:text_parts.append(text)+ # Update the status footer's session token figure to this+ # request's context-window occupancy. SET (not add): the+ # latest assistant message reflects current context size,+ # so the figure tracks it live and drops after a /compact.+ context_tokens = self._extract_context_tokens(message)+ if context_tokens:+ self.controller.note_session_tokens(context, total=context_tokens)+auth_failure_assistant = self._is_auth_failure_assistant_message(message)assistant_text = self._extract_text_blocks(message, context)auth_failure_text = assistant_text or "OAuth authentication failed."@@ -608,12 +639,16 @@ class ClaudeAgent(BaseAgent):parse_mode="markdown",)- for toolcall in toolcalls:+ for toolcall_text, toolcall_label in toolcalls:+ # Persisted/verbose text stays the original+ # ``format_toolcall`` output; ``status_label`` carries+ # the clean claude-pipe label for the concise bubble only.await self.controller.emit_agent_message(context,"toolcall",- toolcall,+ toolcall_text,parse_mode="markdown",+ status_label=toolcall_label,)if text_parts:@@ -1261,6 +1296,42 @@ class ClaudeAgent(BaseAgent):has_retry = "retry" in normalized or "retried" in normalizedreturn has_tool and has_parse and has_retry+ @staticmethod+ def _extract_context_tokens(message) -> int:+ """Current context-window occupancy from an AssistantMessage's ``usage``.++ Each AssistantMessage carries the RAW per-request Anthropic usage block+ (``data["message"]["usage"]``), so its ``input_tokens ++ cache_read_input_tokens + cache_creation_input_tokens`` is the full prompt+ sent for that request — i.e. the whole context at that moment — and+ ``output_tokens`` is the response that joins the context for the next+ request. The LATEST assistant message therefore reflects the current+ occupancy, which the dispatcher SETs (not accumulates) so the figure+ tracks the live context size and drops after a /compact.++ NB: ``ResultMessage.usage`` is the CLI's CUMULATIVE turn usage (summed+ across requests), so it overstates occupancy and must NOT be used here.++ Defensive: ``usage`` may be a dict or object, or absent — returns 0 rather+ than raising so a missing field never breaks the turn."""+ usage = getattr(message, "usage", None)+ if usage is None:+ return 0++ def _field(name: str) -> int:+ value = usage.get(name) if isinstance(usage, dict) else getattr(usage, name, None)+ try:+ return int(value) if value and int(value) > 0 else 0+ except (TypeError, ValueError):+ return 0++ return (+ _field("input_tokens")+ + _field("cache_read_input_tokens")+ + _field("cache_creation_input_tokens")+ + _field("output_tokens")+ )+def _detect_message_type(self, message) -> Optional[str]:"""Infer message type name from Claude SDK class."""if not hasattr(message, "__class__"):diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex be7f8a083..eb68598fb 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -89,6 +89,27 @@ class CodexAgent(BaseAgent):# BaseAgent interface# ------------------------------------------------------------------+ def backend_alive(self, context) -> Optional[bool]:+ """Liveness via the CodexTransport for this turn's working directory.++ Resolves base_session_id → cwd → transport and returns transport.is_alive.+ Returns None (unknown) when anything can't be resolved, so the status+ bubble never false-alarms ⚠️."""+ payload = getattr(context, "platform_specific", None) or {}+ base_session_id = str(payload.get("turn_base_session_id") or "").strip()+ if not base_session_id:+ return None+ cwd = self._session_mgr.get_cwd(base_session_id)+ if not cwd:+ return None+ transport = self._transports.get(cwd)+ if transport is None:+ return None+ try:+ return bool(transport.is_alive)+ except Exception:+ return None+async def handle_message(self, request: AgentRequest) -> None:"""Process a user message by routing it through app-server.diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.pyindex 6ced98f7a..4c762a275 100644--- a/modules/agents/codex/event_handler.py+++ b/modules/agents/codex/event_handler.py@@ -492,6 +492,53 @@ class CodexEventHandler:async def _on_context_compacted(self, params: dict[str, Any], request: AgentRequest) -> None:return+ @staticmethod+ def _extract_context_tokens(params: dict[str, Any]) -> int:+ """Current context-window occupancy from a ``thread/tokenUsage/updated``+ notification.++ The app-server v2 payload nests it as ``tokenUsage.last.totalTokens`` —+ the "latest active context size" the Codex CLI's own context bar uses (it+ grows with the conversation and DROPS after a /compact). This is the SNAPSHOT+ ``last`` breakdown, NOT ``total`` (which is the monotonic cumulative billing+ figure). The legacy v1 event stream nests the same value as+ ``info.last_token_usage.total_tokens`` (snake_case); both are tried.++ Defensive: missing/malformed → 0 so a protocol change never breaks the turn."""+ if not isinstance(params, dict):+ return 0+ # v2 app-server (camelCase) → v1 event stream (snake_case under "info").+ last = None+ usage = params.get("tokenUsage")+ if isinstance(usage, dict) and isinstance(usage.get("last"), dict):+ last = usage["last"]+ else:+ info = params.get("info")+ if isinstance(info, dict) and isinstance(info.get("last_token_usage"), dict):+ last = info["last_token_usage"]+ if not isinstance(last, dict):+ return 0+ for name in ("totalTokens", "total_tokens"):+ value = last.get(name)+ try:+ if value and int(value) > 0:+ return int(value)+ except (TypeError, ValueError):+ continue+ return 0++ async def _on_token_usage_updated(self, params: dict[str, Any], request: AgentRequest) -> None:+ """``thread/tokenUsage/updated`` → set the status footer's session token+ figure to the current context-window occupancy. SET (not add): the value is+ a live snapshot of context size, not a cumulative total."""+ tokens = self._extract_context_tokens(params)+ if not tokens:+ return+ turn_id = params.get("turnId") or params.get("turn_id") or ""+ turn_state = self._agent._turn_registry.get_turn(turn_id) if turn_id else None+ ctx = (turn_state.request if turn_state else request).context+ self._agent.controller.note_session_tokens(ctx, total=tokens)+# ------------------------------------------------------------------# Cleanup# ------------------------------------------------------------------@@ -509,6 +556,7 @@ class CodexEventHandler:"thread/started": _on_thread_started,"turn/started": _on_turn_started,"turn/completed": _on_turn_completed,+ "thread/tokenUsage/updated": _on_token_usage_updated,"item/completed": _on_item_completed,"error": _on_error,"item/agentMessage/delta": _on_agent_message_delta,diff --git a/modules/agents/service.py b/modules/agents/service.pyindex 11ff097f7..c44c71d80 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -25,6 +25,9 @@ class AgentService:self.agents: Dict[str, BaseAgent] = {}self.default_agent = "claude"self._turn_gates: dict[str, _RuntimeTurnGate] = {}+ # Strong refs to fire-and-forget tasks (e.g. the cancellation tidy) so the+ # event loop doesn't GC them before they run (asyncio only weak-refs tasks).+ self._background_tasks: set[asyncio.Task] = set()def register(self, agent: BaseAgent):self.agents[agent.name] = agent@@ -55,10 +58,50 @@ class AgentService:manager = getattr(self.controller, "session_turns", None)if manager is not None:manager.on_running(request.context)+ # Turn-start work runs HERE — after the gate/on_running confirm the+ # turn is actually running — not while it was queued behind another+ # turn. Claiming the shared per-turn trigger id and posting the+ # "starting" status bubble now means a queued turn never hijacks the+ # running turn's bubble key or posts a premature bubble. Both hooks+ # are optional and guarded so a missing hook or a bubble failure can+ # never break the turn.+ await self._begin_turn_status(request.context)self._track_processing_indicator_turn(request)await agent.handle_message(request)except asyncio.CancelledError:- self.release_runtime_turn(request.context)+ # Shutdown / SIGTERM / supersede cancels the turn mid-flight. Without a+ # terminal emit the concise status bubble stays stuck on its last+ # action. Best effort: SCHEDULE (don't await) a silent terminal result+ # so the outbound chokepoint collapses the bubble + settles the dot;+ # awaiting here would swallow the cancellation. (C3)+ #+ # The runtime turn must be released AFTER that emit runs, NOT before:+ # releasing clears the turn token, and the result branch drops any+ # emit whose turn is no longer current — so an early release would+ # make the scheduled tidy a no-op and leave the bubble stuck. Release+ # inside the scheduled task's finally; fall back to a synchronous+ # release if the emit can't be scheduled so the gate never leaks.+ emit = getattr(self.controller, "emit_agent_message", None)+ scheduled = False+ if callable(emit):+ try:++ async def _tidy_on_cancel() -> None:+ try:+ await emit(request.context, "result", "", is_error=True, level="silent")+ except Exception:+ logger.debug("Failed to emit terminal tidy on cancellation", exc_info=True)+ finally:+ self.release_runtime_turn(request.context)++ tidy_task = asyncio.create_task(_tidy_on_cancel())+ self._background_tasks.add(tidy_task)+ tidy_task.add_done_callback(self._background_tasks.discard)+ scheduled = True+ except Exception:+ logger.debug("Failed to schedule terminal tidy on cancellation", exc_info=True)+ if not scheduled:+ self.release_runtime_turn(request.context)raiseexcept Exception:# The message handler converts backend exceptions into a terminal@@ -183,6 +226,26 @@ class AgentService:gate = self._turn_gates.get(runtime_key)return gate is not None and gate.token == runtime_token+ def backend_alive(self, context: Any) -> Optional[bool]:+ """Resolve the backend for this turn (via its runtime gate) and ask it+ whether it is still alive. Returns ``None`` when the backend is unknown+ or has no probe — callers treat ``None`` as alive (no false alarm)."""+ payload = getattr(context, "platform_specific", None) or {}+ runtime_key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip()+ gate = self._turn_gates.get(runtime_key) if runtime_key else None+ backend = gate.backend if gate else None+ agent = self.agents.get(backend) if backend else None+ if agent is None:+ return None+ probe = getattr(agent, "backend_alive", None)+ if not callable(probe):+ return None+ try:+ return probe(context)+ except Exception:+ logger.debug("backend_alive probe raised for %s", backend, exc_info=True)+ return None+def _get_turn_gate(self, runtime_key: str) -> "_RuntimeTurnGate":if runtime_key not in self._turn_gates:self._turn_gates[runtime_key] = _RuntimeTurnGate()@@ -220,6 +283,29 @@ class AgentService:returnrequest.context.platform_specific[AGENT_TURN_TOKEN] = runtime_token+ async def _begin_turn_status(self, context: Any) -> None:+ """Run turn-start status work at the real start of the turn.++ Claims the shared per-turn trigger id (so the dispatcher's consolidated+ bubble key points at THIS turn) and posts the initial "starting" status+ bubble. Both are best-effort: a controller without these hooks, or a+ bubble failure, must not break the turn. The bubble is awaited inline so+ it exists before the backend's first process emit can edit it.+ """+ update_thread_message_id = getattr(self.controller, "update_thread_message_id", None)+ if callable(update_thread_message_id):+ try:+ update_thread_message_id(context)+ except Exception:+ logger.debug("update_thread_message_id failed at turn start", exc_info=True)+ dispatcher = getattr(self.controller, "message_dispatcher", None)+ begin_status_bubble = getattr(dispatcher, "begin_status_bubble", None) if dispatcher else None+ if callable(begin_status_bubble):+ try:+ await begin_status_bubble(context)+ except Exception:+ logger.debug("begin_status_bubble failed at turn start", exc_info=True)+def _track_processing_indicator_turn(self, request: AgentRequest) -> None:handle = getattr(request, "processing_indicator", None)if handle is None:diff --git a/modules/im/base.py b/modules/im/base.pyindex 7dba6c88e..ed1fd0e45 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -323,10 +323,20 @@ class BaseIMClient(ABC):@abstractmethodasync def send_message(- self, context: MessageContext, text: str, parse_mode: Optional[str] = None, reply_to: Optional[str] = None+ self,+ context: MessageContext,+ text: str,+ parse_mode: Optional[str] = None,+ reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> Optional[str]:"""Send a text message+ ``subtext`` is an optional de-emphasized footer (concise status bubble):+ platforms that support it (Slack context block, Discord ``-#``) render it+ as small secondary text; others may ignore it. Only ever passed on the+ Slack/Discord concise status path.+Args:context: Message context (channel, thread, etc)text: Message text@@ -340,7 +350,12 @@ class BaseIMClient(ABC):@abstractmethodasync def send_message_with_buttons(- self, context: MessageContext, text: str, keyboard: InlineKeyboard, parse_mode: Optional[str] = None+ self,+ context: MessageContext,+ text: str,+ keyboard: InlineKeyboard,+ parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> Optional[str]:"""Send a message with inline buttons@@ -349,6 +364,8 @@ class BaseIMClient(ABC):text: Message textkeyboard: Inline keyboard configurationparse_mode: Optional formatting mode+ subtext: Optional de-emphasized footer (see send_message); only passed+ by status-bubble platforms, so non-bubble adapters need not accept it.Returns:Message ID of sent message, or None when not delivered@@ -453,6 +470,7 @@ class BaseIMClient(ABC):text: Optional[str] = None,keyboard: Optional[InlineKeyboard] = None,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> bool:"""Edit an existing message@@ -462,12 +480,24 @@ class BaseIMClient(ABC):text: New text (if provided)keyboard: New keyboard (if provided)parse_mode: Optional formatting mode (markdown, html, etc)+ subtext: Optional de-emphasized footer (see send_message); platforms+ that don't support it may ignore it.Returns:Success status"""pass+ async def delete_message(self, context: MessageContext, message_id: str) -> bool:+ """Delete a previously-sent message.++ Default is a no-op returning ``False`` for platforms that cannot delete+ (callers must treat ``False`` as "not deleted" and fall back). Platforms+ that support deletion override this; ``PlatformCapabilities.+ supports_message_deletion`` advertises support without a probe call.+ """+ return False+async def remove_inline_keyboard(self,context: MessageContext,diff --git a/modules/im/discord.py b/modules/im/discord.pyindex e6a7c0d3d..7334f8f15 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -471,20 +471,48 @@ class DiscordBot(BaseIMClient):return await self._run_on_client_loop(_impl())+ @staticmethod+ def _compose_status_content(text: Optional[str], subtext: Optional[str]) -> Optional[str]:+ """Append a concise status footer as Discord ``-#`` subtext.++ ``subtext`` is only passed by the status-bubble dispatcher; when it is+ falsy the content is the body unchanged (byte-identical to today). The+ footer is short and prioritized over the body if the 2000-char limit is+ hit (the status body is ~60 chars, so this is not normally reached).++ When the body is empty (footer-only bubble at turn start / pure thinking),+ the content is just ``-# {subtext}`` with NO leading newlines.+ """+ if not subtext:+ return text+ footer = f"-# {subtext}"+ body = text or ""+ if not body.strip():+ return footer+ suffix = f"\n\n{footer}"+ limit = 2000+ if len(body) + len(suffix) > limit:+ keep = max(0, limit - len(suffix))+ body = body[:keep]+ return f"{body}{suffix}"+async def send_message(self,context: MessageContext,text: str,parse_mode: Optional[str] = None,reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:+ content = self._compose_status_content(text, subtext)+async def _impl() -> str:- if not text:+ if not content:raise ValueError("Discord send_message requires non-empty text")target = await self._resolve_target(context)if target is None:raise RuntimeError("Discord channel not found")- message = await target.send(content=text)+ message = await target.send(content=content)if self.settings_manager and context.thread_id:try:if self.sessions:@@ -501,7 +529,10 @@ class DiscordBot(BaseIMClient):text: str,keyboard: InlineKeyboard,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:+ content = self._compose_status_content(text, subtext) if subtext else text+async def _impl() -> str:target = await self._resolve_target(context)if target is None:@@ -512,7 +543,7 @@ class DiscordBot(BaseIMClient):if _PersistentStartView.is_all_static(keyboard)else _DiscordButtonView(self, context, keyboard))- message = await target.send(content=text, view=view)+ message = await target.send(content=content, view=view)if self.settings_manager and context.thread_id:try:if self.sessions:@@ -530,7 +561,10 @@ class DiscordBot(BaseIMClient):text: Optional[str] = None,keyboard: Optional[InlineKeyboard] = None,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> bool:+ content = self._compose_status_content(text, subtext) if text is not None else text+async def _impl() -> bool:target = await self._resolve_target(context)if target is None:@@ -544,7 +578,7 @@ class DiscordBot(BaseIMClient):if _PersistentStartView.is_all_static(keyboard)else _DiscordButtonView(self, context, keyboard))- await msg.edit(content=text, view=view)+ await msg.edit(content=content, view=view)return Trueexcept Exception as err:logger.debug("Failed to edit Discord message: %s", err)@@ -552,6 +586,25 @@ class DiscordBot(BaseIMClient):return await self._run_on_client_loop(_impl())+ async def delete_message(self, context: MessageContext, message_id: str) -> bool:+ """Delete a Discord message."""+ if not message_id:+ return False++ async def _impl() -> bool:+ target = await self._resolve_target(context)+ if target is None:+ return False+ try:+ msg = await target.fetch_message(int(message_id))+ await msg.delete()+ return True+ except Exception as err:+ logger.debug("Failed to delete Discord message: %s", err)+ return False++ return await self._run_on_client_loop(_impl())+async def remove_inline_keyboard(self,context: MessageContext,diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex ef3171d07..edf69c4bf 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -368,8 +368,13 @@ class FeishuBot(BaseIMClient):text: str,parse_mode: Optional[str] = None,reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:- """Send a text message to Feishu."""+ """Send a text message to Feishu.++ ``subtext`` (concise status-bubble footer) is part of the BaseIMClient+ contract; Feishu has no native footer styling, so it is accepted and+ ignored (no behavior change)."""self._ensure_client()if not text:raise ValueError("Feishu send_message requires non-empty text")@@ -631,8 +636,12 @@ class FeishuBot(BaseIMClient):text: Optional[str] = None,keyboard: Optional[InlineKeyboard] = None,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> bool:- """Edit an existing Feishu message."""+ """Edit an existing Feishu message.++ ``subtext`` is accepted for the BaseIMClient contract and ignored:+ Feishu has no native de-emphasized footer styling (no behavior change)."""self._ensure_client()try:from lark_oapi.api.im.v1 import (diff --git a/modules/im/formatters/base_formatter.py b/modules/im/formatters/base_formatter.pyindex 40e435b43..1f37a5e85 100644--- a/modules/im/formatters/base_formatter.py+++ b/modules/im/formatters/base_formatter.py@@ -2,10 +2,45 @@ from abc import ABC, abstractmethodfrom typing import Optional, List, Tuple, Any, Dictimport jsonimport logging+import relogger = logging.getLogger(__name__)+def _truncate_status(text: str, max_len: int) -> str:+ """Truncate ``text`` to ``max_len`` chars with a trailing ellipsis.++ The single safe-truncation primitive shared by ``to_status_label`` and+ ``format_toolcall_label`` so the two never drift on how they shorten a+ status line. Trims trailing whitespace before appending ``…``.+ """+ if len(text) > max_len:+ return text[:max_len].rstrip() + "…"+ return text+++def to_status_label(text: str, max_len: int = 60) -> str:+ """Reduce an already-formatted process message to a single clean status line.++ Used by the concise status-bubble flow (Slack/Discord): the agent backends+ emit toolcall/assistant text that may be multi-line and wrapped in inline+ code (e.g. ``🔧 `Bash` `{"command":"pytest tests/"}` ``). Naively truncating+ that at N chars can cut inside a backtick block and leave dangling markup+ that the renderer mangles. This takes the FIRST line, strips inline-code+ backticks (the main truncation hazard), collapses whitespace, and truncates+ with an ellipsis — so the label is always safe to drop into a message.++ Underscores / asterisks are intentionally preserved so file names like+ ``message_dispatcher.py`` survive intact.+ """+ if not text:+ return ""+ stripped = text.strip()+ first_line = stripped.split("\n", 1)[0] if stripped else ""+ cleaned = re.sub(r"\s+", " ", first_line.replace("`", "")).strip()+ return _truncate_status(cleaned, max_len)++class BaseMarkdownFormatter(ABC):"""Abstract base class for platform-specific markdown formatters"""@@ -412,6 +447,92 @@ class BaseMarkdownFormatter(ABC):return f"🔧 {self.format_code_inline(tool_name)}"return f"🔧 {self.format_code_inline(tool_name)} {self.format_code_inline(params)}"+ # Salient-arg priority: the first key present wins as the label's detail.+ _TOOLCALL_LABEL_ARG_PRIORITY = (+ "command",+ "cmd",+ "file_path",+ "filePath",+ "path",+ "pattern",+ "query",+ "url",+ "directory",+ "notebook_path",+ "prompt",+ )+ # Path-like keys get ``get_relative_path`` applied so the workspace prefix+ # is stripped (e.g. ``…/repo/message_dispatcher.py`` → ``message_dispatcher.py``).+ _TOOLCALL_LABEL_PATH_KEYS = frozenset(+ {"file_path", "filePath", "path", "directory", "notebook_path", "cwd", "workdir"}+ )++ def format_toolcall_label(+ self,+ tool_name: str,+ tool_input: Optional[Dict[str, Any]] = None,+ get_relative_path: Optional[callable] = None,+ max_len: int = 60,+ ) -> str:+ """Build a clean claude-pipe-style status label for a tool call.++ Produces ``🔧 <ToolName>: <primary-arg>`` (or ``🔧 <ToolName>`` when no+ usable arg is found), e.g. ``🔧 Bash: pytest tests/test_x.py`` or+ ``🔧 Read: message_dispatcher.py``. The most salient argument is picked+ from ``tool_input`` in a fixed priority order; path-like keys are run+ through ``get_relative_path`` (when provided) so the workspace prefix is+ dropped. The chosen value is reduced to a single clean line (first line,+ collapsed whitespace, surrounding quotes/backticks stripped) and the+ whole label is truncated with the SAME safe primitive as+ ``to_status_label``. Underscores are preserved so file names survive.++ Pure/standalone — carries no platform state, so any formatter can use it.+ """+ # Defensive: a backend could hand a non-dict input; never raise from the+ # live status-label path (just render the bare tool name).+ if not isinstance(tool_input, dict):+ tool_input = {}++ chosen_key: Optional[str] = None+ chosen_value: Any = None+ for key in self._TOOLCALL_LABEL_ARG_PRIORITY:+ value = tool_input.get(key)+ if isinstance(value, str) and value.strip():+ chosen_key = key+ chosen_value = value+ break+ if chosen_key is None:+ # Fall back to the first non-empty string value in insertion order.+ for key, value in tool_input.items():+ if isinstance(value, str) and value.strip():+ chosen_key = key+ chosen_value = value+ break++ detail = ""+ if chosen_key is not None:+ raw = chosen_value+ if chosen_key in self._TOOLCALL_LABEL_PATH_KEYS and get_relative_path:+ try:+ raw = get_relative_path(raw)+ except Exception:+ raw = chosen_value+ detail = self._clean_label_value(str(raw))++ if detail:+ label = f"🔧 {tool_name}: {detail}"+ else:+ label = f"🔧 {tool_name}"+ return _truncate_status(label, max_len)++ @staticmethod+ def _clean_label_value(value: str) -> str:+ """Reduce a raw arg value to one clean line: first line only, collapsed+ whitespace, surrounding quotes/backticks stripped."""+ first_line = value.split("\n", 1)[0]+ cleaned = re.sub(r"\s+", " ", first_line).strip()+ return cleaned.strip("\"'`")+def format_todo_item(self, status: str, priority: str, content: str, completed: bool = False) -> str:"""Format a todo item with status and priority"""status_emoji = {"pending": "⏳", "in_progress": "🔄", "completed": "✅"}.get(status, "⏳")diff --git a/modules/im/multi.py b/modules/im/multi.pyindex fe2e42a40..455fbc510 100644--- a/modules/im/multi.py+++ b/modules/im/multi.py@@ -311,10 +311,15 @@ class MultiIMClient(BaseIMClient):text: str,parse_mode: Optional[str] = None,reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:- return await self.get_client_for_context(context).send_message(- context, text, parse_mode=parse_mode, reply_to=reply_to- )+ # Forward ``subtext`` only when set: it is a concise-status-bubble extra+ # that only Slack/Discord implement; passing it (even as None) to adapters+ # that don't declare the kwarg would raise TypeError.+ kwargs = {"parse_mode": parse_mode, "reply_to": reply_to}+ if subtext is not None:+ kwargs["subtext"] = subtext+ return await self.get_client_for_context(context).send_message(context, text, **kwargs)async def send_message_with_buttons(self,@@ -322,9 +327,15 @@ class MultiIMClient(BaseIMClient):text: str,keyboard: InlineKeyboard,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:+ # Forward subtext only when set, so adapters that don't declare the kwarg+ # aren't handed it (mirrors send_message / edit_message forwarding).+ kwargs = {"parse_mode": parse_mode}+ if subtext is not None:+ kwargs["subtext"] = subtextreturn await self.get_client_for_context(context).send_message_with_buttons(- context, text, keyboard, parse_mode=parse_mode+ context, text, keyboard, **kwargs)def supports_message_editing(self, context: Optional[MessageContext] = None) -> bool:@@ -375,14 +386,12 @@ class MultiIMClient(BaseIMClient):text: Optional[str] = None,keyboard: Optional[InlineKeyboard] = None,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> bool:- return await self.get_client_for_context(context).edit_message(- context,- message_id,- text=text,- keyboard=keyboard,- parse_mode=parse_mode,- )+ kwargs = {"text": text, "keyboard": keyboard, "parse_mode": parse_mode}+ if subtext is not None:+ kwargs["subtext"] = subtext+ return await self.get_client_for_context(context).edit_message(context, message_id, **kwargs)async def remove_inline_keyboard(self,diff --git a/modules/im/slack.py b/modules/im/slack.pyindex c1370777e..1657d8ec4 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -5,7 +5,7 @@ import loggingimport reimport timeimport aiohttp-from typing import Dict, Any, Optional, Callable, List+from typing import Dict, Any, Optional, Callable, List, Tuplefrom slack_sdk.web.async_client import AsyncWebClientfrom slack_sdk.socket_mode.aiohttp import SocketModeClientfrom slack_sdk.socket_mode.request import SocketModeRequest@@ -536,6 +536,12 @@ class SlackBot(BaseIMClient):"text": text,}+ def _build_context_footer_block(self, subtext: str, parse_mode: Optional[str] = None) -> Dict[str, Any]:+ """A native ``context`` block rendering ``subtext`` as small gray footer+ text (the concise status footer / result done-footer)."""+ footer_text = self._convert_markdown_to_slack_mrkdwn(subtext) if parse_mode == "markdown" else subtext+ return {"type": "context", "elements": [{"type": "mrkdwn", "text": footer_text}]}+@staticmethoddef _build_actions_blocks(keyboard: InlineKeyboard) -> List[Dict[str, Any]]:blocks: List[Dict[str, Any]] = []@@ -574,6 +580,45 @@ class SlackBot(BaseIMClient):blocks.extend(self._build_actions_blocks(keyboard))return blocks+ def _build_status_blocks(+ self,+ body: str,+ subtext: str,+ keyboard: Optional[InlineKeyboard] = None,+ parse_mode: Optional[str] = None,+ ) -> Tuple[List[Dict[str, Any]], str]:+ """Render a status bubble as ``[markdown(body), context(subtext)]`` blocks.++ The BODY uses a native Slack ``markdown`` block so it renders standard+ markdown fully (no ``Show more`` auto-collapse, unlike a ``section``+ mrkdwn block). The footer (``subtext``) stays a native ``context`` block+ so it shows as small gray text under the body. Returns ``(blocks,+ fallback_text)`` where the fallback mirrors ``send_markdown_message`` and+ is the visible body text shown in notifications / no-block clients.++ When ``body`` is empty/whitespace (no action label yet — turn start /+ pure thinking), the markdown block is dropped so the bubble renders as the+ footer ``context`` block alone, and the fallback text falls back to the+ stripped footer so notifications still carry something visible.++ Callers MUST length-guard the body against ``_SLACK_MARKDOWN_TEXT_LIMIT``+ before calling this (the ``markdown`` block has that cap); when the body+ is too long they should signal fallback so the dispatcher uses its normal+ result delivery (split/upload) instead of cramming it here.+ """+ # The body is standard markdown — markdown blocks take it as-is, so we+ # do NOT run _convert_markdown_to_slack_mrkdwn on it. The footer is short+ # control text rendered in a context element, so converting it for+ # parse_mode="markdown" keeps the prior behavior.+ blocks: List[Dict[str, Any]] = []+ if body and body.strip():+ blocks.append(self._build_markdown_block(body))+ blocks.append(self._build_context_footer_block(subtext, parse_mode=parse_mode))+ if keyboard:+ blocks.extend(self._build_actions_blocks(keyboard))+ fallback_text = self._get_visible_text(body) if (body and body.strip()) else (subtext or "").strip()+ return blocks, fallback_text+@staticmethoddef _is_markdown_block_rejection(error: SlackApiError) -> bool:response = getattr(error, "response", None)@@ -710,9 +755,15 @@ class SlackBot(BaseIMClient):text: str,parse_mode: Optional[str] = None,reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:"""Send a message to Slack"""self._ensure_clients()+ # Concise status bubble: render the footer as a native context block+ # (small gray text) instead of an inline italic line. Only the status+ # dispatcher passes ``subtext``; every other caller keeps the legacy path.+ if subtext:+ return await self._send_status_message(context, text, subtext, parse_mode=parse_mode, reply_to=reply_to)try:if not text:raise ValueError("Slack send_message requires non-empty text")@@ -740,12 +791,60 @@ class SlackBot(BaseIMClient):logger.error(f"Error sending Slack message: {e}")raise+ async def _send_status_message(+ self,+ context: MessageContext,+ body: str,+ subtext: str,+ parse_mode: Optional[str] = None,+ reply_to: Optional[str] = None,+ ) -> str:+ """Post a status bubble (body + native context-block footer).++ The body MAY be empty (footer-only bubble at turn start / pure thinking);+ the footer (``subtext``) carries the liveness line, so the bubble renders+ as the ``context`` block alone. An empty body therefore must NOT raise.+ """+ if not body and not (subtext and subtext.strip()):+ raise ValueError("Slack status bubble requires a body or footer")+ # The status bubble renders the body as a native markdown block, which is+ # capped at _SLACK_MARKDOWN_TEXT_LIMIT. A body over the cap must NOT be+ # crammed here; raise so the dispatcher falls back to its normal result+ # delivery (split / upload) instead of rendering a broken bubble.+ if len(body) > _SLACK_MARKDOWN_TEXT_LIMIT:+ raise ValueError("Slack status bubble body exceeds markdown block limit")+ blocks, fallback_text = self._build_status_blocks(body, subtext, keyboard=None, parse_mode=parse_mode)+ kwargs: Dict[str, Any] = {+ "channel": context.channel_id,+ "blocks": blocks,+ "text": fallback_text,+ }+ if context.thread_id:+ kwargs["thread_ts"] = context.thread_id+ elif reply_to:+ kwargs["thread_ts"] = reply_to+ try:+ response = await self._post_message_with_dm_recovery(+ context,+ kwargs,+ log_label="status-bubble send",+ )+ except SlackApiError as e:+ logger.error(f"Error sending Slack status bubble: {e}")+ raise+ if self.settings_manager and (context.thread_id or reply_to):+ thread_ts = context.thread_id or reply_to+ if self.sessions:+ self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)+ return response["ts"]+async def send_markdown_message(self,context: MessageContext,text: str,keyboard: Optional[InlineKeyboard] = None,reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:"""Send standard Markdown using Slack's native markdown block.@@ -758,6 +857,11 @@ class SlackBot(BaseIMClient):raise ValueError("Slack send_markdown_message requires non-empty text")if len(text) > _SLACK_MARKDOWN_TEXT_LIMIT:+ # Over the markdown-block cap: keep the LEGACY mrkdwn/section path and+ # do NOT attach the done-footer subtext. Passing subtext routes the+ # send through the status-bubble path, which rejects bodies > the cap+ # (so a 12k–30k inline result would otherwise fail to post). The footer+ # is a non-essential trailer; reliable delivery of the body wins.if keyboard:return await self.send_message_with_buttons(context,@@ -771,6 +875,8 @@ class SlackBot(BaseIMClient):blocks = [self._build_markdown_block(text)]if keyboard:blocks.extend(self._build_actions_blocks(keyboard))+ if subtext:+ blocks.append(self._build_context_footer_block(subtext, parse_mode="markdown"))kwargs = {"channel": context.channel_id,@@ -796,6 +902,11 @@ class SlackBot(BaseIMClient):logger.error(f"Error sending Slack native markdown message: {e}")raiselogger.warning("Slack rejected native markdown block; falling back to legacy mrkdwn rendering")+ # Do NOT forward subtext here: it re-routes through _send_status_message,+ # which rebuilds the SAME native markdown block Slack just rejected, so+ # the fallback would hit the identical invalid_blocks error and degrade+ # to attachment/failure. Use the legacy mrkdwn/section path; the done+ # footer is dropped on this rare recovery path so the body still posts.if keyboard:return await self.send_message_with_buttons(context,@@ -1407,6 +1518,7 @@ class SlackBot(BaseIMClient):keyboard: InlineKeyboard,parse_mode: Optional[str] = None,reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:"""Send a message with interactive buttons"""self._ensure_clients()@@ -1433,6 +1545,8 @@ class SlackBot(BaseIMClient):blocks = self._build_button_blocks(visible_text, keyboard, parse_mode=parse_mode)if blocks and blocks[0].get("type") == "section":blocks[0]["text"]["verbatim"] = True+ if subtext:+ blocks.append(self._build_context_footer_block(subtext, parse_mode=parse_mode))# Prepare message kwargskwargs = {@@ -1473,9 +1587,32 @@ class SlackBot(BaseIMClient):text: Optional[str] = None,keyboard: Optional[InlineKeyboard] = None,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> bool:"""Edit an existing Slack message"""self._ensure_clients()+ # Concise status bubble: re-render body + native context-block footer.+ if subtext:+ # The body renders as a native markdown block (capped at+ # _SLACK_MARKDOWN_TEXT_LIMIT). A body over the cap must NOT be crammed+ # here; return False so the dispatcher treats it as a failed edit and+ # falls back to its normal result delivery (split / upload).+ if len(text or "") > _SLACK_MARKDOWN_TEXT_LIMIT:+ return False+ try:+ blocks, fallback_text = self._build_status_blocks(+ text or "", subtext, keyboard=keyboard, parse_mode=parse_mode+ )+ await self.web_client.chat_update(+ channel=context.channel_id,+ ts=message_id,+ text=fallback_text,+ blocks=blocks,+ )+ return True+ except SlackApiError as e:+ logger.error(f"Error editing Slack status bubble: {e}")+ return Falsetry:if text and parse_mode == "markdown":text = self._convert_markdown_to_slack_mrkdwn(text)@@ -1496,6 +1633,18 @@ class SlackBot(BaseIMClient):logger.error(f"Error editing Slack message: {e}")return False+ async def delete_message(self, context: MessageContext, message_id: str) -> bool:+ """Delete a Slack message via ``chat.delete``."""+ if not message_id:+ return False+ self._ensure_clients()+ try:+ await self.web_client.chat_delete(channel=context.channel_id, ts=message_id)+ return True+ except SlackApiError as e:+ logger.error(f"Error deleting Slack message: {e}")+ return False+async def remove_inline_keyboard(self,context: MessageContext,diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex a6e0b4222..353edb18b 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -1130,8 +1130,16 @@ class TelegramBot(BaseIMClient):return message_idasync def send_message(- self, context: MessageContext, text: str, parse_mode: Optional[str] = None, reply_to: Optional[str] = None+ self,+ context: MessageContext,+ text: str,+ parse_mode: Optional[str] = None,+ reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:+ # ``subtext`` (concise status-bubble footer) is part of the BaseIMClient+ # contract; Telegram has no native footer styling, so it is accepted and+ # ignored (no behavior change).payload = self._build_payload(context,self.format_markdown(text),@@ -1179,7 +1187,10 @@ class TelegramBot(BaseIMClient):text: Optional[str] = None,keyboard: Optional[InlineKeyboard] = None,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> bool:+ # ``subtext`` is accepted for the BaseIMClient contract and ignored:+ # Telegram has no native de-emphasized footer styling (no behavior change).payload = {"chat_id": context.channel_id,"message_id": int(message_id),diff --git a/modules/im/wechat.py b/modules/im/wechat.pyindex 05e61af3f..fa2c4a1ae 100644--- a/modules/im/wechat.py+++ b/modules/im/wechat.py@@ -525,8 +525,13 @@ class WeChatBot(BaseIMClient):text: str,parse_mode: Optional[str] = None,reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:- """Send a plain text message to a WeChat user."""+ """Send a plain text message to a WeChat user.++ ``subtext`` (concise status-bubble footer) is part of the BaseIMClient+ contract; WeChat has no native footer styling, so it is accepted and+ ignored (no behavior change)."""if not text:raise ValueError("WeChat send_message requires non-empty text")@@ -590,8 +595,11 @@ class WeChatBot(BaseIMClient):text: Optional[str] = None,keyboard: Optional[InlineKeyboard] = None,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> bool:- """WeChat does not support editing sent messages."""+ """WeChat does not support editing sent messages.++ ``subtext`` is accepted for the BaseIMClient contract and ignored."""return Falseasync def answer_callback(diff --git a/tests/test_agent_backend_alive.py b/tests/test_agent_backend_alive.pynew file mode 100644index 000000000..33e78f19b--- /dev/null+++ b/tests/test_agent_backend_alive.py@@ -0,0 +1,126 @@+"""Backend liveness probe (B1) for the concise status bubble.++AgentService.backend_alive resolves the backend via the turn gate and delegates+to the per-backend probe; ClaudeAgent.backend_alive reads receiver_tasks.+Unknown states return None so the caller never false-alarms.+"""++from __future__ import annotations++import sys+import types+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from modules.agents.base import AGENT_RUNTIME_TURN_KEY+from modules.agents.service import AgentService+from modules.agents.claude_agent import ClaudeAgent+from modules.agents.codex.agent import CodexAgent+from modules.im import MessageContext+++class _Task:+ def __init__(self, done: bool):+ self._done = done++ def done(self) -> bool:+ return self._done+++def _ctx(runtime_key: str | None):+ ps = {AGENT_RUNTIME_TURN_KEY: runtime_key} if runtime_key is not None else {}+ return MessageContext(user_id="U1", channel_id="C1", platform="slack", platform_specific=ps)+++class ClaudeBackendAliveTests(unittest.TestCase):+ def _agent(self, receiver_tasks):+ agent = ClaudeAgent.__new__(ClaudeAgent) # bypass heavy __init__+ agent.receiver_tasks = receiver_tasks+ return agent++ def test_running_task_is_alive(self):+ agent = self._agent({"k1": _Task(done=False)})+ self.assertIs(agent.backend_alive(_ctx("k1")), True)++ def test_done_task_is_dead(self):+ agent = self._agent({"k1": _Task(done=True)})+ self.assertIs(agent.backend_alive(_ctx("k1")), False)++ def test_missing_key_is_unknown(self):+ agent = self._agent({"k1": _Task(done=False)})+ self.assertIsNone(agent.backend_alive(_ctx("other")))++ def test_no_runtime_key_is_unknown(self):+ agent = self._agent({"k1": _Task(done=False)})+ self.assertIsNone(agent.backend_alive(_ctx(None)))+++class CodexBackendAliveTests(unittest.TestCase):+ def _agent(self, *, cwd_for_session, transports):+ agent = CodexAgent.__new__(CodexAgent) # bypass heavy __init__+ agent._session_mgr = types.SimpleNamespace(get_cwd=lambda bid: cwd_for_session.get(bid))+ agent._transports = transports+ return agent++ def _ctx_base(self, base_session_id):+ return MessageContext(+ user_id="U1", channel_id="C1", platform="slack",+ platform_specific={"turn_base_session_id": base_session_id} if base_session_id else {},+ )++ def test_alive_transport(self):+ agent = self._agent(+ cwd_for_session={"b1": "/repo"},+ transports={"/repo": types.SimpleNamespace(is_alive=True)},+ )+ self.assertIs(agent.backend_alive(self._ctx_base("b1")), True)++ def test_dead_transport(self):+ agent = self._agent(+ cwd_for_session={"b1": "/repo"},+ transports={"/repo": types.SimpleNamespace(is_alive=False)},+ )+ self.assertIs(agent.backend_alive(self._ctx_base("b1")), False)++ def test_no_transport_is_unknown(self):+ agent = self._agent(cwd_for_session={"b1": "/repo"}, transports={})+ self.assertIsNone(agent.backend_alive(self._ctx_base("b1")))++ def test_no_cwd_is_unknown(self):+ agent = self._agent(cwd_for_session={}, transports={})+ self.assertIsNone(agent.backend_alive(self._ctx_base("b1")))++ def test_no_base_session_is_unknown(self):+ agent = self._agent(cwd_for_session={"b1": "/repo"}, transports={})+ self.assertIsNone(agent.backend_alive(self._ctx_base(None)))+++class AgentServiceBackendAliveTests(unittest.TestCase):+ def _service(self, *, backend_name, gate_backend, probe_return):+ svc = AgentService.__new__(AgentService) # bypass __init__+ fake_agent = types.SimpleNamespace(backend_alive=lambda context: probe_return)+ svc.agents = {backend_name: fake_agent}+ svc._turn_gates = {"rk": types.SimpleNamespace(backend=gate_backend, token="t")}+ return svc++ def test_resolves_backend_via_gate_and_delegates(self):+ svc = self._service(backend_name="claude", gate_backend="claude", probe_return=True)+ self.assertIs(svc.backend_alive(_ctx("rk")), True)++ def test_dead_propagates(self):+ svc = self._service(backend_name="claude", gate_backend="claude", probe_return=False)+ self.assertIs(svc.backend_alive(_ctx("rk")), False)++ def test_unknown_backend_returns_none(self):+ svc = self._service(backend_name="claude", gate_backend="codex", probe_return=True)+ self.assertIsNone(svc.backend_alive(_ctx("rk")))++ def test_no_gate_returns_none(self):+ svc = self._service(backend_name="claude", gate_backend="claude", probe_return=True)+ self.assertIsNone(svc.backend_alive(_ctx("missing")))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_agent_service.py b/tests/test_agent_service.pyindex 674d57278..39546d7d4 100644--- a/tests/test_agent_service.py+++ b/tests/test_agent_service.py@@ -79,6 +79,89 @@ class _Controller:self.session_turns = None+class _OrderRecordingTurnManager:+ def __init__(self, log: list[str]):+ self._log = log++ def on_running(self, _context):+ self._log.append("on_running")+++class _OrderRecordingDispatcher:+ def __init__(self, log: list[str]):+ self._log = log++ async def begin_status_bubble(self, _context):+ self._log.append("begin_status_bubble")+++class _TurnStartController:+ """Records the relative order of the turn-start hooks vs the agent run."""++ def __init__(self, log: list[str]):+ self.session_turns = _OrderRecordingTurnManager(log)+ self.message_dispatcher = _OrderRecordingDispatcher(log)+ self._log = log++ def update_thread_message_id(self, _context):+ self._log.append("update_thread_message_id")+++class _OrderRecordingAgent(_RuntimeAgent):+ def __init__(self, log: list[str]):+ super().__init__()+ self._log = log++ async def handle_message(self, request):+ self._log.append("handle_message")+ await super().handle_message(request)+++def test_agent_service_runs_turn_start_hooks_after_gate_before_agent() -> None:+ async def _run():+ log: list[str] = []+ controller = _TurnStartController(log)+ service = AgentService(controller=controller)+ controller.agent_service = service+ agent = _OrderRecordingAgent(log)+ service.register(agent)++ await service.handle_message("claude", _request("hi"))++ # on_running (gate confirmed) must precede the bubble hooks, which in turn+ # precede the agent run. This is what keeps a queued turn from claiming+ # the trigger id / posting a premature bubble before it actually starts.+ assert log == [+ "on_running",+ "update_thread_message_id",+ "begin_status_bubble",+ "handle_message",+ ]++ asyncio.run(_run())+++def test_agent_service_turn_start_hooks_optional_and_guarded() -> None:+ async def _run():+ # A controller WITHOUT the turn-start hooks (and a dispatcher whose+ # bubble raises) must not break the turn.+ class _NoHookController:+ session_turns = None+ message_dispatcher = SimpleNamespace(+ begin_status_bubble=AsyncMock(side_effect=RuntimeError("bubble boom"))+ )++ service = AgentService(controller=_NoHookController())+ agent = _RuntimeAgent()+ service.register(agent)++ await service.handle_message("claude", _request("hi"))++ assert agent.started == ["hi"]++ asyncio.run(_run())++class _FailingTurnManager:def on_running(self, _context):raise RuntimeError("status failed")@@ -414,6 +497,69 @@ def test_agent_service_releases_gate_when_on_running_fails() -> None:asyncio.run(_run())+def test_agent_service_schedules_terminal_tidy_on_cancellation() -> None:+ # C3: a turn cancelled mid-flight (shutdown / SIGTERM) must SCHEDULE a silent+ # terminal result so the outbound chokepoint collapses the stuck status bubble+ # + settles the dot, then re-raise CancelledError.+ async def _run():+ controller = _Controller()+ emit_calls: list[tuple[tuple, dict]] = []+ token_at_emit: list[str] = []+ emitted = asyncio.Event()++ async def _emit(*args, **kwargs):+ # Capture the runtime-turn token AT EMIT TIME. The fix requires the+ # tidy emit to run while the turn is STILL current (token not yet+ # cleared) — otherwise the real result branch drops it as stale and+ # the bubble never collapses. An early release would make this "".+ gate = service._turn_gates.get("session:/repo")+ token_at_emit.append(gate.token if gate else "")+ emit_calls.append((args, kwargs))+ emitted.set()++ controller.emit_agent_message = _emit+ service = AgentService(controller=controller)+ controller.agent_service = service++ hanging = asyncio.Event()++ class _HangingAgent(_RuntimeAgent):+ async def handle_message(self, _request):+ await hanging.wait() # block until cancelled++ agent = _HangingAgent()+ service.register(agent)+ request = _request("cancel-me")++ task = asyncio.create_task(service.handle_message("claude", request))+ await asyncio.sleep(0.05) # let it reach the hanging agent+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ else:+ raise AssertionError("CancelledError should propagate")++ # The terminal tidy emit was scheduled (create_task) → let it run.+ await asyncio.wait_for(emitted.wait(), timeout=2.0)+ assert len(emit_calls) == 1+ args, kwargs = emit_calls[0]+ # emit(context, "result", "", is_error=True, level="silent")+ assert args[0] is request.context+ assert args[1] == "result"+ assert kwargs.get("is_error") is True+ assert kwargs.get("level") == "silent"+ # The turn was STILL current at emit time (token not cleared first) so the+ # tidy isn't dropped as stale — this is the ordering the C3 fix guarantees.+ assert token_at_emit and token_at_emit[0]+ # Gate released AFTER the tidy emit so a later prompt can't hang behind the+ # cancelled turn.+ assert not service._turn_gates["session:/repo"].token++ asyncio.run(_run())++def test_agent_service_releases_gate_when_exception_terminal_emit_fails() -> None:async def _run():controller = _Controller()diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex 9f18ee2d2..a7e560128 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -219,6 +219,30 @@ def test_save_config_preserves_show_pages_prompt_toggle(monkeypatch, tmp_path):assert payload["show_pages_prompt"] is False+def test_save_config_preserves_status_bubble_settings_on_partial_save(monkeypatch, tmp_path):+ """An unrelated partial save must NOT reset agent_progress_style / intervals.++ Regression for the config_to_payload omission that wiped these on any UI save.+ """+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ full = _full_config_payload()+ full["agent_progress_style"] = "verbose"+ full["agent_status_heartbeat_ms"] = 12000+ created = api.save_config(full)+ assert created.agent_progress_style == "verbose"+ assert created.agent_status_heartbeat_ms == 12000++ # Toggle an unrelated field — the status-bubble settings must survive.+ updated = api.save_config({"show_duration": False})+ payload = api.config_to_payload(updated)++ assert updated.agent_progress_style == "verbose"+ assert updated.agent_status_heartbeat_ms == 12000+ assert payload["agent_progress_style"] == "verbose"+ assert payload["agent_status_heartbeat_ms"] == 12000++def test_config_load_defaults_missing_show_pages_prompt_to_enabled():payload = _full_config_payload()payload.pop("show_pages_prompt")diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex 973a69777..3be1e2dba 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -688,6 +688,10 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):def format_toolcall(*_args, **_kwargs):return "Bash(pwd)"+ @staticmethod+ def format_toolcall_label(*_args, **_kwargs):+ return "🔧 Bash: pwd"+@staticmethoddef format_assistant_message(parts):return "\n\n".join(parts)@@ -705,7 +709,10 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):first_emit = controller.emit_agent_message.await_args_list[0]self.assertEqual(first_emit.args, (context, "toolcall", "Bash(pwd)"))- self.assertEqual(first_emit.kwargs, {"parse_mode": "markdown"})+ self.assertEqual(+ first_emit.kwargs,+ {"parse_mode": "markdown", "status_label": "🔧 Bash: pwd"},+ )self.assertEqual(context.platform_specific["turn_token"], "T2")self.assertEqual(context.platform_specific["agent_runtime_turn_key"], composite_key)self.assertEqual(context.platform_specific["agent_runtime_turn_token"], "R2")diff --git a/tests/test_claude_token_usage.py b/tests/test_claude_token_usage.pynew file mode 100644index 000000000..4c58e5b28--- /dev/null+++ b/tests/test_claude_token_usage.py@@ -0,0 +1,56 @@+"""Claude backend → current context-window occupancy for the status-bubble footer.++Covers ``ClaudeAgent._extract_context_tokens``: it reads the RAW per-request usage+from an AssistantMessage (the latest one reflects current context size) and sums+input + cache_read + cache_creation + output. It must degrade to 0 when ``usage``+is missing/malformed so a missing field never breaks the turn.+"""++import unittest++from modules.agents.claude_agent import ClaudeAgent+++class _Msg:+ def __init__(self, usage):+ self.usage = usage+++class _UsageObj:+ def __init__(self, **kw):+ for k, v in kw.items():+ setattr(self, k, v)+++class ExtractContextTokensTests(unittest.TestCase):+ def test_sums_prompt_and_output_including_cache(self):+ # Full prompt sent = input + cache_read + cache_creation; + output joins+ # the context for the next request → all four count toward occupancy.+ msg = _Msg(+ {+ "input_tokens": 1200,+ "cache_read_input_tokens": 30000,+ "cache_creation_input_tokens": 800,+ "output_tokens": 345,+ }+ )+ self.assertEqual(ClaudeAgent._extract_context_tokens(msg), 1200 + 30000 + 800 + 345)++ def test_object_usage_is_supported(self):+ msg = _Msg(_UsageObj(input_tokens=100, output_tokens=50))+ # cache fields absent → counted as 0.+ self.assertEqual(ClaudeAgent._extract_context_tokens(msg), 150)++ def test_missing_usage_is_zero(self):+ self.assertEqual(ClaudeAgent._extract_context_tokens(_Msg(None)), 0)+ self.assertEqual(ClaudeAgent._extract_context_tokens(object()), 0)++ def test_malformed_fields_are_ignored(self):+ msg = _Msg({"input_tokens": "nope", "output_tokens": None, "cache_read_input_tokens": -5})+ self.assertEqual(ClaudeAgent._extract_context_tokens(msg), 0)+ msg2 = _Msg({"input_tokens": 20, "output_tokens": "x"})+ self.assertEqual(ClaudeAgent._extract_context_tokens(msg2), 20)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_codex_token_usage.py b/tests/test_codex_token_usage.pynew file mode 100644index 000000000..df2f37e15--- /dev/null+++ b/tests/test_codex_token_usage.py@@ -0,0 +1,47 @@+"""Codex backend → current context-window occupancy for the status-bubble footer.++Covers ``CodexEventHandler._extract_context_tokens``: it reads the SNAPSHOT+``tokenUsage.last.totalTokens`` from a ``thread/tokenUsage/updated`` notification+(the "latest active context size" the Codex CLI's own context bar uses), NOT the+cumulative ``total``. It must support the legacy v1 snake_case shape and degrade+to 0 when the field is missing/malformed.+"""++import unittest++from modules.agents.codex.event_handler import CodexEventHandler+++class ExtractContextTokensTests(unittest.TestCase):+ def test_v2_camelcase_reads_last_total(self):+ params = {+ "threadId": "t1",+ "turnId": "u1",+ "tokenUsage": {+ "last": {"totalTokens": 38000, "inputTokens": 37000, "outputTokens": 1000},+ "total": {"totalTokens": 250000}, # cumulative — must NOT be used+ "modelContextWindow": 200000,+ },+ }+ self.assertEqual(CodexEventHandler._extract_context_tokens(params), 38000)++ def test_v1_snakecase_info_shape(self):+ params = {"info": {"last_token_usage": {"total_tokens": 12345}}}+ self.assertEqual(CodexEventHandler._extract_context_tokens(params), 12345)++ def test_missing_or_malformed_is_zero(self):+ self.assertEqual(CodexEventHandler._extract_context_tokens({}), 0)+ self.assertEqual(CodexEventHandler._extract_context_tokens({"tokenUsage": {"last": None}}), 0)+ self.assertEqual(CodexEventHandler._extract_context_tokens("nope"), 0)+ self.assertEqual(+ CodexEventHandler._extract_context_tokens({"tokenUsage": {"last": {"totalTokens": "x"}}}), 0+ )++ def test_total_field_is_ignored_when_last_absent(self):+ # Only `last` is occupancy; a payload with just `total` yields 0.+ params = {"tokenUsage": {"total": {"totalTokens": 999999}}}+ self.assertEqual(CodexEventHandler._extract_context_tokens(params), 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_message_dispatcher_status_bubble.py b/tests/test_message_dispatcher_status_bubble.pynew file mode 100644index 000000000..d7dee8d95--- /dev/null+++ b/tests/test_message_dispatcher_status_bubble.py@@ -0,0 +1,795 @@+"""Concise status-bubble flow (Slack/Discord).++Covers docs/plans/agent-progress-status-bubble.md P0 + P1:+- process messages render as ONE status bubble that REPLACES (not appends);+- the result EDITS that same bubble into the final answer (case 1, S4 id) with a+ ``✅ <elapsed>`` completion footer;+- a non-inline / failed-edit result tidies the orphan bubble (B3);+- ``progress_style=off`` shows no process bubble;+- non-editing platforms keep the legacy verbose append path (no regression);+- liveness footer rendering (elapsed / no-output hint / backend-dead) + heartbeat+ render + S3 cancel-before-edit ordering;+- to_status_label produces clean single-line labels (S1).+"""++from __future__ import annotations++import asyncio+import sys+import unittest+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.message_dispatcher import ConsolidatedMessageDispatcher+from modules.im import MessageContext+from modules.im.formatters.base_formatter import to_status_label+from modules.im.formatters.slack_formatter import SlackFormatter+++class _StubSettingsManager:+ def _canonicalize_message_type(self, message_type):+ return message_type++ def is_message_type_hidden(self, settings_key, canonical_type):+ return False+++class _StubSessionHandler:+ def finalize_scheduled_delivery(self, context, sent_message_id):+ pass+++class _EditClient:+ """IM stub that records sends and edits; edit return value is configurable."""++ def __init__(self, edit_result: bool = True, delete_result: bool = True):+ self.sent = [] # (message_id, text, subtext)+ self.edits = [] # (message_id, text, subtext)+ self.deletes = [] # message_id+ self._n = 0+ self._edit_result = edit_result+ self._delete_result = delete_result++ def should_use_thread_for_reply(self):+ return False++ async def send_message(self, context, text, parse_mode=None, reply_to=None, subtext=None):+ self._n += 1+ mid = f"msg-{self._n}"+ self.sent.append((mid, text, subtext))+ return mid++ async def edit_message(self, context, message_id, text=None, keyboard=None, parse_mode=None, subtext=None):+ self.edits.append((message_id, text, subtext))+ return self._edit_result++ async def delete_message(self, context, message_id):+ self.deletes.append(message_id)+ return self._delete_result+++class _StubController:+ def __init__(self, *, platform="slack", im_client=None, progress_style=None, backend_alive=None):+ self.config = type(+ "Config", (), {"platform": platform, "language": "en", "reply_enhancements": False}+ )()+ self.session_handler = _StubSessionHandler()+ self.im_client = im_client or _EditClient()+ self.agent_service = None+ self._progress_style_value = progress_style+ self._backend_alive_value = backend_alive++ def _get_settings_key(self, context):+ return context.channel_id++ def _get_session_key(self, context):+ return f"{context.platform}::{context.channel_id}"++ def get_settings_manager_for_context(self, context):+ return _StubSettingsManager()++ def get_im_client_for_context(self, context):+ return self.im_client++ def get_progress_style_for_context(self, context):+ return self._progress_style_value++ def backend_alive(self, context):+ return self._backend_alive_value+++def _ctx(platform="slack"):+ return MessageContext(user_id="U1", channel_id="C1", platform=platform)+++def _dispatcher(controller, *, now=1000.0, disable_heartbeat=True):+ d = ConsolidatedMessageDispatcher(controller)+ d._now = lambda: now+ if disable_heartbeat:+ d._start_status_heartbeat = lambda *a, **k: None+ return d+++class StatusBubbleProcessTests(unittest.IsolatedAsyncioTestCase):+ async def test_process_messages_replace_in_one_bubble(self):+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ ctx = _ctx()+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ id1 = await d.emit_agent_message(ctx, "toolcall", "🔧 `Read` `{\"file_path\":\"a.py\"}`")+ id2 = await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{\"command\":\"pytest\"}`")+ self.assertEqual(id1, "msg-1")+ self.assertEqual(id2, "msg-1") # same bubble+ self.assertEqual([m for m, _, _ in controller.im_client.sent], ["msg-1"]) # one send+ # Second emit EDITED (replace, not append): body + footer kept separate.+ # Two emits → 2 steps; hourglass on the 2nd render is ⌛ (cycles ⏳/⌛).+ self.assertEqual(+ controller.im_client.edits,+ [("msg-1", "🔧 Bash {\"command\":\"pytest\"}", "⌛ 0s · 2 st")],+ )+ self.assertNotIn("`", controller.im_client.edits[0][1])++ async def test_status_label_renders_clean_label_not_raw_json(self):+ # A backend-computed clean label (claude-pipe style) is used for the+ # bubble body in place of the raw format_toolcall JSON text.+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ ctx = _ctx()+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ mid = await d.emit_agent_message(+ ctx,+ "toolcall",+ "🔧 `Bash` `{\"command\":\"pytest tests/test_x.py\"}`",+ status_label="🔧 Bash: pytest tests/test_x.py",+ )+ self.assertEqual(mid, "msg-1")+ body, _subtext = controller.im_client.sent[0][1], controller.im_client.sent[0][2]+ self.assertEqual(body, "🔧 Bash: pytest tests/test_x.py")+ self.assertNotIn("{", body) # raw JSON not used as the bubble body++ async def test_empty_status_label_falls_back_to_to_status_label(self):+ 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` `{\"command\":\"pytest\"}`", status_label=""+ )+ self.assertEqual(controller.im_client.sent[0][1], "🔧 Bash {\"command\":\"pytest\"}")++ async def test_progress_style_off_shows_no_bubble(self):+ controller = _StubController(platform="slack", progress_style="off")+ d = _dispatcher(controller)+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ result = await d.emit_agent_message(_ctx(), "toolcall", "🔧 `Read` `{}`")+ self.assertIsNone(result)+ self.assertEqual(controller.im_client.sent, [])+ self.assertEqual(controller.im_client.edits, [])++ async def test_non_editing_platform_uses_verbose_append(self):+ controller = _StubController(platform="lark")+ d = _dispatcher(controller)+ self.assertEqual(d._concise_progress_style(_ctx("lark")), "verbose")+++class StatusBubbleResultTests(unittest.IsolatedAsyncioTestCase):+ async def test_result_posts_fresh_message_and_deletes_bubble(self):+ # The result is delivered as a NEW message (so the IM fires a push+ # notification), carrying the ✅ done footer; the transient status bubble is+ # then DELETED so the turn ends as just the fresh result.+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ ctx = _ctx()+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`") # bubble msg-1+ result_id = await d.emit_agent_message(ctx, "result", "Final answer")+ self.assertEqual(result_id, "msg-2") # a brand-new message, NOT the bubble+ # Fresh result send carries the done footer (show_duration off → no time).+ self.assertIn(("msg-2", "Final answer", "✅ done"), controller.im_client.sent)+ # The status bubble was deleted, not edited into the answer.+ self.assertEqual(controller.im_client.deletes, ["msg-1"])+ # Persisted text is the clean answer (no footer).+ 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_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".+ 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+ d.note_session_tokens(ctx, total=248000) # backend reports occupancy+ await d.emit_agent_message(ctx, "result", "Final answer")+ self.assertIn(("msg-2", "Final answer", "✅ done · 248k tok"), controller.im_client.sent)+ self.assertEqual(controller.im_client.deletes, ["msg-1"])++ async def test_bubble_collapsed_when_delete_unsupported_or_fails(self):+ # Fallback: when the bubble delete fails (or the platform can't delete) the+ # bubble is collapsed to a terminal marker instead, so it never lingers as+ # "running". The result is still delivered as a fresh message.+ controller = _StubController(platform="slack", im_client=_EditClient(delete_result=False))+ 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+ result_id = await d.emit_agent_message(ctx, "result", "Final answer")+ self.assertEqual(result_id, "msg-2") # fresh result message+ self.assertIn(("msg-2", "Final answer", "✅ done"), controller.im_client.sent)+ self.assertEqual(controller.im_client.deletes, ["msg-1"]) # delete attempted+ # Delete returned False → fall back to collapsing the bubble to a marker.+ self.assertIn(("msg-1", "", "✅ done"), controller.im_client.edits)++ async def test_result_without_prior_bubble_sends_normally(self):+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ result_id = await d.emit_agent_message(_ctx(), "result", "Just an answer")+ self.assertEqual(result_id, "msg-1")+ self.assertEqual([t for _, t, _ in controller.im_client.sent], ["Just an answer"])+ self.assertEqual(controller.im_client.edits, [])++ async def test_long_discord_result_splits_fresh_and_deletes_bubble(self):+ # Discord long result → split path: every chunk is a NEW send (no bubble+ # reuse), and the transient bubble is deleted afterwards.+ controller = _StubController(platform="discord")+ d = _dispatcher(controller)+ ctx = _ctx("discord")+ long_text = "x" * 2500 # exceeds discord 1900-char inline limit → splits+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`") # bubble msg-1+ result_id = await d.emit_agent_message(ctx, "result", long_text)+ self.assertEqual(result_id, "msg-2") # first fresh chunk (delivery anchor)+ # At least two fresh chunk sends, all starting with the long body.+ chunk_sends = [(t, st) for m, t, st in controller.im_client.sent if t.startswith("x")]+ self.assertGreaterEqual(len(chunk_sends), 2)+ # The done footer rides ONLY the last chunk (mid-stream footer reads wrong).+ self.assertIsNone(chunk_sends[0][1])+ self.assertEqual(chunk_sends[-1][1], "✅ done")+ # The bubble was deleted (never reused as a chunk).+ self.assertEqual(controller.im_client.deletes, ["msg-1"])++ async def test_split_later_chunk_failure_keeps_first_chunk(self):+ # Discord long result: chunk 0 sends fine, a later chunk send fails. The+ # failure must NOT propagate; the first chunk stays delivered and the+ # bubble is still retired (deleted).+ class _FailLaterChunk(_EditClient):+ def __init__(self):+ super().__init__()+ self._x_sends = 0++ async def send_message(self, context, text, parse_mode=None, reply_to=None, subtext=None):+ if text.startswith("x"):+ self._x_sends += 1+ if self._x_sends >= 2: # fail the 2nd+ chunk+ raise RuntimeError("later chunk send failed")+ return await super().send_message(context, text, parse_mode, reply_to, subtext)++ controller = _StubController(platform="discord", im_client=_FailLaterChunk())+ d = _dispatcher(controller)+ ctx = _ctx("discord")+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`") # bubble msg-1+ result_id = await d.emit_agent_message(ctx, "result", "x" * 2500)+ self.assertEqual(result_id, "msg-2") # first chunk delivered+ self.assertEqual(controller.im_client.deletes, ["msg-1"]) # bubble still retired++ async def test_split_head_chunk_failure_returns_none(self):+ # If the HEAD chunk fails to send, the split is abandoned (returns None) so+ # the caller's fallback delivers the COMPLETE content — never a head-less+ # partial marked as delivered just because a later chunk happened to send.+ class _FailFirstChunk(_EditClient):+ def __init__(self):+ super().__init__()+ self._x_sends = 0++ async def send_message(self, context, text, parse_mode=None, reply_to=None, subtext=None):+ if text.startswith("x"):+ self._x_sends += 1+ if self._x_sends == 1: # fail ONLY the head chunk+ raise RuntimeError("head chunk send failed")+ return await super().send_message(context, text, parse_mode, reply_to, subtext)++ controller = _StubController(platform="discord", im_client=_FailFirstChunk())+ d = _dispatcher(controller)+ ctx = _ctx("discord")+ result = await d._send_split_result_messages(+ controller.im_client, ctx, "x" * 2500, [], "markdown"+ )+ self.assertIsNone(result) # abandoned → caller falls back to full delivery+ # No chunk was kept as the anchor (head missing).+ self.assertEqual([t for _, t, _ in controller.im_client.sent if t.startswith("x")][:1], [])++ async def test_slack_result_delivered_via_native_markdown_then_bubble_deleted(self):+ # A Slack result is delivered inline via the native markdown sender as a+ # FRESH message (carrying the done footer as subtext); the bubble is then+ # deleted. The native sender accepts ``subtext`` like the real adapter.+ class _MarkdownClient(_EditClient):+ def __init__(self):+ super().__init__()+ self.markdown_sends = []++ async def send_markdown_message(self, context, text, keyboard=None, reply_to=None, subtext=None):+ self._n += 1+ mid = f"native-{self._n}"+ self.markdown_sends.append((mid, text, subtext))+ return mid++ controller = _StubController(platform="slack", im_client=_MarkdownClient())+ d = _dispatcher(controller)+ ctx = _ctx()+ long_text = "x" * 20000 # within Slack's 30000-char result limit → inline+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`") # bubble msg-1 (send_message)+ result_id = await d.emit_agent_message(ctx, "result", long_text)+ self.assertEqual(result_id, "native-2") # fresh native-markdown send+ self.assertEqual(controller.im_client.markdown_sends, [("native-2", long_text, "✅ done")])+ self.assertEqual(controller.im_client.deletes, ["msg-1"]) # bubble deleted++ async def test_late_process_emit_does_not_resurrect_finalized_bubble(self):+ # C1: once the turn finalized (result edited the bubble to ✅ done), a late+ # in-flight process emit for the SAME key must bail instead of overwriting+ # the terminal bubble back to a "working" line.+ 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+ await d.emit_agent_message(ctx, "result", "Final answer") # finalize → ✅ done+ edits_after_finalize = len(controller.im_client.edits)+ # A late process emit for the same turn key (e.g. a straggler before+ # teardown) must NOT edit/resurrect the now-finalized bubble.+ # NB: _clear_consolidated_state ran in the result path, but the key is in+ # _status_finalized for the duration; re-seed it to simulate the race+ # window where finalize landed but the late emit shares the key.+ key = d._get_consolidated_message_key(ctx)+ d._status_finalized.add(key)+ d._consolidated_message_ids[key] = "msg-1"+ late = await d._render_concise_status(controller.im_client, ctx, "🔧 `Read` `{}`")+ self.assertIsNone(late) # bailed+ self.assertEqual(len(controller.im_client.edits), edits_after_finalize) # no new edit++ async def test_late_emit_after_result_does_not_reopen_bubble(self):+ # P2: the runtime gate is released only AFTER the result path's teardown,+ # so a late same-turn process emit in that window still passes the+ # runtime-turn guard. The finalized marker must SURVIVE _drop_status_keys+ # (not re-seeded here) so the late emit bails instead of opening a new+ # running bubble after the answer was posted.+ 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+ await d.emit_agent_message(ctx, "result", "Final answer") # delete bubble + fresh result+ sends_before = len(controller.im_client.sent)+ edits_before = len(controller.im_client.edits)+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ late = await d.emit_agent_message(ctx, "toolcall", "🔧 `Read` `{}`")+ self.assertIsNone(late) # bailed on the surviving finalized marker+ self.assertEqual(len(controller.im_client.sent), sends_before) # no new bubble posted+ self.assertEqual(len(controller.im_client.edits), edits_before)++ async def test_error_result_collapse_fallback_uses_failed_marker(self):+ # C4: on an is_error turn where the bubble delete fails, the collapse+ # fallback reflects the failure outcome (⏹ failed), NOT a hardcoded ✅ done.+ controller = _StubController(platform="slack", im_client=_EditClient(delete_result=False))+ 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+ result_id = await d.emit_agent_message(ctx, "result", "Failed answer", is_error=True)+ self.assertEqual(result_id, "msg-2") # fresh result message+ self.assertEqual(controller.im_client.deletes, ["msg-1"]) # delete attempted (failed)+ self.assertIn(("msg-1", "", "⏹ failed"), controller.im_client.edits) # collapse fallback+ self.assertNotIn(("msg-1", "", "✅ done"), controller.im_client.edits)++ async def test_result_teardown_drops_lock_dict_entry(self):+ # C6: after a turn ends, the per-key consolidated lock must be dropped from+ # _consolidated_message_locks so it can't grow unbounded across turns.+ 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)+ self.assertIn(key, d._consolidated_message_locks) # lock created+ await d.emit_agent_message(ctx, "result", "Final answer")+ # Per-turn state (lock + message id) is dropped so they can't grow+ # unbounded. The finalized marker intentionally SURVIVES teardown — it must+ # outlive the turn's gate-release window so a late same-turn emit can't+ # re-open the bubble (P2); it is bounded separately in _finalize_status_key.+ self.assertNotIn(key, d._consolidated_message_locks)+ self.assertNotIn(key, d._consolidated_message_ids)+ self.assertIn(key, d._status_finalized)++ async def test_result_stops_heartbeat_before_edit(self):+ # Heartbeat ENABLED here: emit a process message to start it, then the+ # result must cancel it (S3) so no stale tick stomps the answer.+ controller = _StubController(platform="slack")+ d = _dispatcher(controller, disable_heartbeat=False)+ 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.assertIn(key, d._status_heartbeat_tasks) # heartbeat running+ await d.emit_agent_message(ctx, "result", "Done")+ self.assertNotIn(key, d._status_heartbeat_tasks) # cancelled + cleared+++class BeginStatusBubbleTests(unittest.IsolatedAsyncioTestCase):+ async def test_begin_creates_bubble_then_first_emit_edits_same_id(self):+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ ctx = _ctx()+ await d.begin_status_bubble(ctx)+ # One immediate send with an EMPTY body (footer-only): the running footer+ # alone conveys the agent started; no redundant "starting agent" line.+ self.assertEqual([m for m, _, _ in controller.im_client.sent], ["msg-1"])+ self.assertEqual(controller.im_client.sent[0][1], "")+ # Footer-only turn-start bubble: just the hourglass + elapsed, no step+ # (empty label is not a step) and no token field (none reported yet).+ self.assertEqual(controller.im_client.sent[0][2], "⏳ 0s")+ self.assertEqual(controller.im_client.edits, [])+ # First real process emit finds the existing id and EDITS it (no 2nd send),+ # filling in the action-label body. That emit is the 1st step; the glyph+ # cycles to ⌛ on this second render.+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ emit_id = await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`")+ self.assertEqual(emit_id, "msg-1")+ self.assertEqual([m for m, _, _ in controller.im_client.sent], ["msg-1"]) # still one send+ self.assertEqual(controller.im_client.edits, [("msg-1", "🔧 Bash {}", "⌛ 0s · 1 st")])++ async def test_begin_is_idempotent(self):+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ ctx = _ctx()+ await d.begin_status_bubble(ctx)+ await d.begin_status_bubble(ctx) # second call: bubble already exists → no-op+ self.assertEqual([m for m, _, _ in controller.im_client.sent], ["msg-1"])+ self.assertEqual(controller.im_client.edits, [])++ async def test_begin_noop_when_suppress_delivery(self):+ # No-delivery runs (scheduled / watch targeting a Slack/Discord no-delivery+ # session) must NOT leak a visible turn-start bubble — the turn-start post+ # runs before the chokepoint's suppress-delivery branch, so it is guarded here.+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ ctx = _ctx()+ ctx.platform_specific = {"suppress_delivery": True}+ await d.begin_status_bubble(ctx)+ self.assertEqual(controller.im_client.sent, [])+ self.assertEqual(controller.im_client.edits, [])++ async def test_begin_noop_when_style_off(self):+ controller = _StubController(platform="slack", progress_style="off")+ d = _dispatcher(controller)+ await d.begin_status_bubble(_ctx())+ self.assertEqual(controller.im_client.sent, [])+ self.assertEqual(controller.im_client.edits, [])++ async def test_begin_noop_on_non_status_bubble_platform(self):+ controller = _StubController(platform="lark")+ d = _dispatcher(controller)+ await d.begin_status_bubble(_ctx("lark"))+ self.assertEqual(controller.im_client.sent, [])+ self.assertEqual(controller.im_client.edits, [])++ async def test_empty_error_result_tidies_starting_bubble(self):+ # Regression: a turn that posts the footer-only bubble then ends via the+ # empty terminal result (missing agent / exception) must collapse the+ # bubble to a terminal marker instead of leaving it stuck "working".+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ ctx = _ctx()+ await d.begin_status_bubble(ctx) # posts footer-only msg-1+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ result_id = await d.emit_agent_message(ctx, "result", "", is_error=True)+ self.assertIsNone(result_id) # empty result delivers nothing+ # is_error + non-silent → "failed": ⏹ failed marker, not ✅.+ self.assertIn(("msg-1", "", "⏹ failed"), controller.im_client.edits)++ async def test_silent_result_tidies_starting_bubble(self):+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ ctx = _ctx()+ await d.begin_status_bubble(ctx)+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await d.emit_agent_message(ctx, "result", "🛑 stopped", level="silent")+ # Silent but NOT is_error → clean ✅ done marker.+ self.assertIn(("msg-1", "", "✅ done"), controller.im_client.edits)++ async def test_error_silent_result_tidies_starting_bubble_with_stop_marker(self):+ # A manually-stopped (silent + is_error) terminal collapses to ⏹ stopped.+ controller = _StubController(platform="slack")+ d = _dispatcher(controller)+ ctx = _ctx()+ await d.begin_status_bubble(ctx)+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await d.emit_agent_message(ctx, "result", "", level="silent", is_error=True)+ self.assertIn(("msg-1", "", "⏹ stopped"), controller.im_client.edits)++ async def test_error_result_posts_fresh_message_with_failed_footer(self):+ # A non-empty errored (non-silent) result is delivered as a fresh message+ # whose done footer carries the "failed" reason (show_duration off → no+ # time); the bubble is then deleted.+ 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+ await d.emit_agent_message(ctx, "result", "Interrupted", is_error=True)+ self.assertIn(("msg-2", "Interrupted", "⏹ failed"), controller.im_client.sent)+ self.assertEqual(controller.im_client.deletes, ["msg-1"])+++class HeartbeatCancellationTests(unittest.IsolatedAsyncioTestCase):+ async def test_stop_heartbeat_terminates_even_mid_edit(self):+ # Blocker regression: CancelledError in the heartbeat edit must propagate+ # so task.cancel() terminates the loop; otherwise _stop_status_heartbeat+ # would hang and block result delivery.+ started = asyncio.Event()++ class _BlockingClient(_EditClient):+ async def edit_message(self, context, message_id, text=None, keyboard=None, parse_mode=None, subtext=None):+ started.set()+ await asyncio.sleep(3600) # block until cancelled++ controller = _StubController(platform="slack", im_client=_BlockingClient())+ d = ConsolidatedMessageDispatcher(controller)+ d._now = lambda: 1000.0+ d._heartbeat_interval_s = lambda ctx: 0.0 # fire immediately+ 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)+ await asyncio.wait_for(started.wait(), timeout=2.0) # heartbeat entered the edit+ await asyncio.wait_for(d._stop_status_heartbeat(key), timeout=2.0) # must NOT hang+ self.assertNotIn(key, d._status_heartbeat_tasks)+++class LivenessFooterTests(unittest.IsolatedAsyncioTestCase):+ def test_format_elapsed(self):+ d = _dispatcher(_StubController())+ self.assertEqual(d._format_elapsed(0), "0s")+ self.assertEqual(d._format_elapsed(59), "59s")+ self.assertEqual(d._format_elapsed(60), "1:00")+ self.assertEqual(d._format_elapsed(125), "2:05")++ def test_footer_running_and_done(self):+ d = _dispatcher(_StubController())+ ctx = _ctx()+ # Running footer (compact): {hourglass} {elapsed}; 0-value fields omitted.+ self.assertEqual(d._status_footer_text(ctx, elapsed_s=5), "⏳ 5s")+ # The hourglass glyph is whatever the caller passes (cycled by compose).+ self.assertEqual(d._status_footer_text(ctx, elapsed_s=5, hourglass="⌛"), "⌛ 5s")+ # show_duration off (default stub config) → done footer is the reason word.+ self.assertEqual(d._status_footer_text(ctx, elapsed_s=18, done=True), "✅ done")+ # A stopped terminal turn shows ⏹ stopped; a failed turn shows ⏹ failed.+ self.assertEqual(+ d._status_footer_text(ctx, elapsed_s=18, done=True, reason="stopped"), "⏹ stopped"+ )+ self.assertEqual(+ d._status_footer_text(ctx, elapsed_s=18, done=True, reason="failed"), "⏹ failed"+ )++ def test_footer_running_with_steps_and_tokens(self):+ d = _dispatcher(_StubController())+ ctx = _ctx()+ # steps appended only when > 0; tokens read from the session total.+ self.assertEqual(d._status_footer_text(ctx, elapsed_s=18, steps=6), "⏳ 18s · 6 st")+ d.note_session_tokens(ctx, total=12345)+ self.assertEqual(+ d._status_footer_text(ctx, elapsed_s=18, steps=6, hourglass="⌛"),+ "⌛ 18s · 6 st · 12.3k tok",+ )++ def test_footer_done_with_show_duration_appends_time(self):+ controller = _StubController()+ controller.config.show_duration = True+ d = _dispatcher(controller)+ ctx = _ctx()+ self.assertEqual(d._status_footer_text(ctx, elapsed_s=18, done=True), "✅ done · 18s")+ self.assertEqual(+ d._status_footer_text(ctx, elapsed_s=84, done=True, reason="stopped"), "⏹ stopped · 1:24"+ )+ self.assertEqual(+ d._status_footer_text(ctx, elapsed_s=84, done=True, reason="failed"), "⏹ failed · 1:24"+ )++ def test_footer_done_keeps_session_tokens(self):+ d = _dispatcher(_StubController())+ ctx = _ctx()+ d.note_session_tokens(ctx, total=248000)+ # Terminal footer keeps the session token total (show_duration off here).+ self.assertEqual(d._status_footer_text(ctx, elapsed_s=84, done=True), "✅ done · 248k tok")++ def test_token_count_formatting(self):+ d = _dispatcher(_StubController())+ self.assertEqual(d._format_token_count(0), "0")+ self.assertEqual(d._format_token_count(999), "999")+ self.assertEqual(d._format_token_count(12345), "12.3k")+ self.assertEqual(d._format_token_count(248000), "248k")+ self.assertEqual(d._format_token_count(1_400_000), "1.4M")++ def test_note_session_tokens_sets_absolute_snapshot(self):+ d = _dispatcher(_StubController())+ ctx = _ctx()+ key = d._token_session_key(ctx)+ d.note_session_tokens(ctx, total=38000)+ self.assertEqual(d._session_token_total[key], 38000)+ # Pure SET (not accumulate): a later snapshot replaces, and can DROP+ # (e.g. after a /compact) — never adds.+ d.note_session_tokens(ctx, total=12000)+ self.assertEqual(d._session_token_total[key], 12000)+ # Invalid values are ignored (keep the last good snapshot).+ d.note_session_tokens(ctx, total="nope")+ d.note_session_tokens(ctx, total=-5)+ self.assertEqual(d._session_token_total[key], 12000)++ def test_token_totals_isolated_per_thread(self):+ # Two threads in the SAME channel must not share the occupancy figure — a+ # token update in one thread must not change the other thread's footer (P2).+ d = _dispatcher(_StubController())+ a = MessageContext(user_id="U1", channel_id="C1", platform="slack", thread_id="T-a")+ b = MessageContext(user_id="U1", channel_id="C1", platform="slack", thread_id="T-b")+ d.note_session_tokens(a, total=38000)+ d.note_session_tokens(b, total=120000)+ self.assertEqual(d._token_field(a), "38.0k tok")+ self.assertEqual(d._token_field(b), "120k tok")+ self.assertNotEqual(d._token_session_key(a), d._token_session_key(b))++ def test_body_action_time_decoration(self):+ d = _dispatcher(_StubController())+ ctx = _ctx()+ # Below the hint threshold → body unchanged.+ self.assertEqual(+ d._decorate_body_with_action_time(ctx, "🔧 Bash", 5, backend_dead=False), "🔧 Bash"+ )+ # Past the threshold → append the action's own runtime.+ self.assertEqual(+ d._decorate_body_with_action_time(ctx, "🔧 Bash", 150, backend_dead=False),+ "🔧 Bash · 2:30",+ )+ # Past the no-output threshold (180s default), alive → ⚠️ emphasis.+ self.assertEqual(+ d._decorate_body_with_action_time(ctx, "🔧 Bash", 200, backend_dead=False),+ "🔧 Bash · ⚠️ 3:20",+ )+ # Empty body is never decorated.+ self.assertEqual(d._decorate_body_with_action_time(ctx, "", 300, backend_dead=False), "")++ def test_footer_backend_dead(self):+ d = _dispatcher(_StubController())+ ctx = _ctx()+ footer = d._status_footer_text(ctx, elapsed_s=12, backend_dead=True)+ self.assertEqual(footer, "⚠️ backend not responding · 12s")++ def test_backend_dead_probe(self):+ # Unknown (no probe / None) → not dead; explicit False → dead.+ self.assertFalse(_dispatcher(_StubController(backend_alive=None))._backend_dead(_ctx()))+ self.assertTrue(_dispatcher(_StubController(backend_alive=False))._backend_dead(_ctx()))+ self.assertFalse(_dispatcher(_StubController(backend_alive=True))._backend_dead(_ctx()))++ async def test_heartbeat_render_updates_elapsed(self):+ controller = _StubController(platform="discord")+ clock = {"t": 1000.0}+ d = ConsolidatedMessageDispatcher(controller)+ d._now = lambda: clock["t"]+ d._start_status_heartbeat = lambda *a, **k: None # control manually+ ctx = _ctx("discord")+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`")+ key = d._get_consolidated_message_key(ctx)+ last_activity_before = d._status_last_activity_at[key]+ clock["t"] = 1075.0 # +75s elapsed+ await d._status_heartbeat_render_once(ctx, controller.im_client, key, "msg-1")+ # Body + footer are passed separately; the adapter owns -# styling now.+ # 75s since the only emit → the body gains the action's own runtime+ # ("🔧 Bash {} · 1:15"); footer is the compact running form (1 step).+ # emit composed once (⏳), heartbeat composes again → glyph cycles to ⌛.+ self.assertEqual(+ controller.im_client.edits[-1], ("msg-1", "🔧 Bash {} · 1:15", "⌛ 1:15 · 1 st")+ )+ # Invariant: a heartbeat re-render must NOT reset last-activity — that is+ # what lets the action runtime keep growing during a quiet stretch.+ self.assertEqual(d._status_last_activity_at[key], last_activity_before)++ def test_hourglass_cycles_across_renders(self):+ # The hourglass glyph alternates ⏳ ⌛ ⏳ ⌛ on each running render so the+ # bubble animates across heartbeats/emits without any new event.+ d = _dispatcher(_StubController())+ ctx = _ctx()+ key = d._get_consolidated_message_key(ctx)+ d._consolidated_message_buffers[key] = "🔧 Bash {}"+ glyphs = []+ for _ in range(4):+ _, footer = d._compose_status_message(ctx, key)+ glyphs.append(footer.split(" ", 1)[0]) # leading hourglass glyph+ self.assertEqual(glyphs, ["⏳", "⌛", "⏳", "⌛"])+++class StatusLabelTests(unittest.TestCase):+ def test_strips_backticks_and_takes_first_line(self):+ self.assertEqual(+ to_status_label("🔧 `Bash` `{\"command\":\"pytest\"}`"),+ "🔧 Bash {\"command\":\"pytest\"}",+ )++ def test_multiline_assistant_uses_first_line(self):+ self.assertEqual(to_status_label("Reading the file.\n\nThen editing."), "Reading the file.")++ def test_truncates_with_ellipsis_and_keeps_underscores(self):+ out = to_status_label("🔧 Read message_dispatcher_really_long_name.py extra tail here", max_len=20)+ self.assertTrue(out.endswith("…"))+ self.assertLessEqual(len(out), 21)+ self.assertIn("_", out)++ def test_empty(self):+ self.assertEqual(to_status_label(""), "")+++class FormatToolcallLabelTests(unittest.TestCase):+ """Clean claude-pipe-style tool-call labels: ``🔧 <Tool>: <primary-arg>``."""++ def setUp(self):+ self.fmt = SlackFormatter()++ def test_bash_uses_command(self):+ self.assertEqual(+ self.fmt.format_toolcall_label("Bash", {"command": "pytest tests/test_x.py"}),+ "🔧 Bash: pytest tests/test_x.py",+ )++ def test_read_file_path_strips_workspace_prefix(self):+ out = self.fmt.format_toolcall_label(+ "Read",+ {"file_path": "/workspace/repo/core/message_dispatcher.py"},+ get_relative_path=lambda p: p.replace("/workspace/repo/", ""),+ )+ self.assertEqual(out, "🔧 Read: core/message_dispatcher.py")++ def test_grep_pattern_strips_surrounding_quotes(self):+ self.assertEqual(+ self.fmt.format_toolcall_label("Grep", {"pattern": '"consolidated"'}),+ "🔧 Grep: consolidated",+ )++ def test_empty_input_yields_bare_tool(self):+ self.assertEqual(self.fmt.format_toolcall_label("TodoWrite", {}), "🔧 TodoWrite")+ self.assertEqual(self.fmt.format_toolcall_label("TodoWrite", None), "🔧 TodoWrite")++ def test_no_usable_string_arg_yields_bare_tool(self):+ # Non-string values don't count as a salient arg.+ self.assertEqual(self.fmt.format_toolcall_label("Foo", {"limit": 5}), "🔧 Foo")++ def test_long_arg_truncates_with_ellipsis(self):+ out = self.fmt.format_toolcall_label(+ "Bash", {"command": "echo " + "x" * 200}, max_len=30+ )+ self.assertTrue(out.endswith("…"))+ self.assertLessEqual(len(out), 31)++ def test_first_line_and_collapsed_whitespace(self):+ out = self.fmt.format_toolcall_label("Bash", {"command": "make build\nmake test"})+ self.assertEqual(out, "🔧 Bash: make build")++ def test_command_priority_over_file_path(self):+ out = self.fmt.format_toolcall_label(+ "Tool", {"file_path": "a.py", "command": "ls"}+ )+ self.assertEqual(out, "🔧 Tool: ls")++ def test_fallback_to_first_string_value(self):+ out = self.fmt.format_toolcall_label("Custom", {"foo": "bar"})+ self.assertEqual(out, "🔧 Custom: bar")++ def test_preserves_underscores_in_file_name(self):+ out = self.fmt.format_toolcall_label("Read", {"file_path": "message_dispatcher.py"})+ self.assertEqual(out, "🔧 Read: message_dispatcher.py")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_status_bubble_footer_render.py b/tests/test_status_bubble_footer_render.pynew file mode 100644index 000000000..0d2cb7d6d--- /dev/null+++ b/tests/test_status_bubble_footer_render.py@@ -0,0 +1,148 @@+"""Adapter-level rendering of the concise status-bubble footer (Step F).++The dispatcher now hands the IM adapters ``(body, footer)`` separately via the+optional ``subtext`` parameter; each adapter owns the footer styling:+- Slack renders the body as a native ``markdown`` block and the footer as a+ native ``context`` block (small gray text);+- Discord renders it as ``-#`` subtext.++These are pure structural unit tests that do not touch a live client.+"""++from __future__ import annotations++import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from modules.im import MessageContext+from modules.im.discord import DiscordBot+from modules.im.slack import SlackBot+++class SlackStatusBlocksTests(unittest.TestCase):+ def test_build_status_blocks_markdown_body_plus_context(self):+ # Construct without running the heavy __init__; only the pure block+ # builder is exercised. parse_mode="plain" avoids the markdown converter.+ bot = SlackBot.__new__(SlackBot)+ blocks, fallback_text = bot._build_status_blocks(+ body="🔧 x", subtext="⏳ 5s", keyboard=None, parse_mode="plain"+ )+ # Body renders as a native markdown block (standard markdown, no+ # Show more/less auto-collapse) carrying the RAW body.+ self.assertEqual(blocks[0]["type"], "markdown")+ self.assertEqual(blocks[0]["text"], "🔧 x")+ # Footer stays a native context block (small gray text).+ self.assertEqual(blocks[1]["type"], "context")+ self.assertEqual(blocks[1]["elements"][0]["type"], "mrkdwn")+ self.assertEqual(blocks[1]["elements"][0]["text"], "⏳ 5s")+ # Fallback text (notifications / no-block clients) mirrors+ # send_markdown_message's visible-text fallback.+ self.assertEqual(fallback_text, "🔧 x")+ # No keyboard → exactly two blocks (no actions block).+ self.assertEqual(len(blocks), 2)++ def test_build_status_blocks_empty_body_is_context_only(self):+ # A footer-only bubble (no action label yet) drops the markdown block and+ # renders the footer context block alone; fallback text = stripped footer.+ bot = SlackBot.__new__(SlackBot)+ blocks, fallback_text = bot._build_status_blocks(+ body="", subtext="⏳ working. · 0s · 0s ago", keyboard=None, parse_mode="plain"+ )+ self.assertEqual(len(blocks), 1)+ self.assertEqual(blocks[0]["type"], "context")+ self.assertEqual(blocks[0]["elements"][0]["text"], "⏳ working. · 0s · 0s ago")+ self.assertEqual(fallback_text, "⏳ working. · 0s · 0s ago")++ def test_build_status_blocks_whitespace_body_is_context_only(self):+ bot = SlackBot.__new__(SlackBot)+ blocks, _ = bot._build_status_blocks(+ body=" ", subtext="⏳ working · 1s", keyboard=None, parse_mode="plain"+ )+ self.assertEqual(len(blocks), 1)+ self.assertEqual(blocks[0]["type"], "context")+++class DiscordStatusContentTests(unittest.TestCase):+ def test_compose_status_content_uses_subtext_marker(self):+ content = DiscordBot._compose_status_content("🔧 x", "⏳ 5s")+ self.assertIn("-# ⏳ 5s", content)+ self.assertTrue(content.startswith("🔧 x"))++ def test_compose_status_content_empty_body_is_footer_only(self):+ # Footer-only bubble: just "-# {subtext}" with NO leading newlines.+ self.assertEqual(+ DiscordBot._compose_status_content("", "⏳ working. · 0s · 0s ago"),+ "-# ⏳ working. · 0s · 0s ago",+ )+ self.assertEqual(+ DiscordBot._compose_status_content(None, "⏳ working · 1s"),+ "-# ⏳ working · 1s",+ )++ def test_compose_status_content_without_subtext_is_unchanged(self):+ # No subtext → byte-identical body (every non-status caller).+ self.assertEqual(DiscordBot._compose_status_content("plain body", None), "plain body")++ def test_buttons_subtext_composes_footer_into_content(self):+ # send_message_with_buttons reuses _compose_status_content for the done+ # footer, so a result-with-buttons carries the ✅ done footer too.+ content = DiscordBot._compose_status_content("Final answer", "✅ done · 248k tok")+ self.assertTrue(content.startswith("Final answer"))+ self.assertTrue(content.endswith("-# ✅ done · 248k tok"))+++class SlackContextFooterTests(unittest.TestCase):+ def test_build_context_footer_block_is_mrkdwn_context(self):+ bot = SlackBot.__new__(SlackBot)+ block = bot._build_context_footer_block("✅ done · 248k tok", parse_mode="plain")+ self.assertEqual(block["type"], "context")+ self.assertEqual(block["elements"][0]["text"], "✅ done · 248k tok")+++class DeletionCapabilityTests(unittest.TestCase):+ def test_status_bubble_platforms_advertise_deletion(self):+ from config.platform_registry import get_platform_descriptor++ for platform in ("slack", "discord"):+ caps = get_platform_descriptor(platform).capabilities+ self.assertTrue(caps.supports_message_deletion, platform)+ # A non-deletion platform stays False (drives the collapse fallback).+ self.assertFalse(get_platform_descriptor("lark").capabilities.supports_message_deletion)++ def test_compose_status_content_truncates_body_to_fit_2000_limit(self):+ # Over-limit body is truncated so the footer survives within Discord's+ # 2000-char content cap, and the footer marker is preserved verbatim.+ subtext = "⏳ working"+ content = DiscordBot._compose_status_content("x" * 3000, subtext)+ self.assertIsNotNone(content)+ self.assertLessEqual(len(content), 2000)+ self.assertTrue(content.endswith(f"-# {subtext}"))+++class SlackMarkdownOverLimitTests(unittest.IsolatedAsyncioTestCase):+ async def test_over_limit_markdown_keeps_legacy_path_without_subtext(self):+ # A result over the markdown-block cap (12k) but under the dispatcher's+ # inline limit must stay on the LEGACY mrkdwn path: passing subtext would+ # route it through the status-bubble send, which rejects bodies > the cap,+ # so the result would fail to post inline. The done-footer is dropped here.+ bot = SlackBot.__new__(SlackBot)+ bot._ensure_clients = lambda: None # type: ignore[method-assign]+ calls: list[dict] = []++ async def _send_message(context, text, parse_mode=None, reply_to=None, subtext=None):+ calls.append({"len": len(text), "subtext": subtext})+ return "msg-legacy"++ bot.send_message = _send_message # type: ignore[method-assign]+ ctx = MessageContext(user_id="U1", channel_id="C1", platform="slack")+ mid = await bot.send_markdown_message(ctx, "x" * 13000, subtext="✅ done · 248k tok")+ self.assertEqual(mid, "msg-legacy")+ self.assertEqual(len(calls), 1)+ self.assertIsNone(calls[0]["subtext"]) # legacy path: no subtext attached+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_status_bubble_indicator.py b/tests/test_status_bubble_indicator.pynew file mode 100644index 000000000..566f39d18--- /dev/null+++ b/tests/test_status_bubble_indicator.py@@ -0,0 +1,121 @@+"""Step E: in concise mode the processing indicator keeps ONLY typing.++The concise status bubble is the visual indicator, so an ack message / reaction+would be a duplicate signal (and a Slack ack message can't be deleted). B2.+"""++from __future__ import annotations++import sys+import types+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.controller import Controller+from core.processing_indicator import ProcessingIndicatorService+from config.v2_config import V2Config+from modules.im import MessageContext+from tests.test_api_save_config_merge import _full_config_payload+++def _cfg(style):+ payload = _full_config_payload()+ payload["agent_progress_style"] = style+ return V2Config.from_payload(payload)+++def _ctx(platform="slack"):+ return MessageContext(user_id="U1", channel_id="C1", platform=platform)+++class UsesConciseStatusBubbleTests(unittest.TestCase):+ def _fake(self, platform, style):+ cfg = _cfg(style)+ fake = types.SimpleNamespace(primary_platform=platform, config=cfg)+ fake.get_progress_style_for_context = lambda ctx: Controller.get_progress_style_for_context(fake, ctx)+ return fake++ def test_slack_concise_true(self):+ fake = self._fake("slack", "concise")+ self.assertTrue(Controller.uses_concise_status_bubble(fake, _ctx("slack")))++ def test_discord_concise_true(self):+ fake = self._fake("discord", "concise")+ self.assertTrue(Controller.uses_concise_status_bubble(fake, _ctx("discord")))++ def test_slack_off_false(self):+ fake = self._fake("slack", "off")+ self.assertFalse(Controller.uses_concise_status_bubble(fake, _ctx("slack")))++ def test_non_editing_platform_false(self):+ fake = self._fake("lark", "concise")+ self.assertFalse(Controller.uses_concise_status_bubble(fake, _ctx("lark")))+++class ProcessingModeSuppressionTests(unittest.TestCase):+ def test_non_concise_keeps_all_modes(self):+ svc = ProcessingIndicatorService.__new__(ProcessingIndicatorService)+ svc._capabilities = lambda ctx: object()+ svc._candidate_modes = lambda caps: ["message", "typing", "reaction"]+ svc._mode_supported = lambda caps, mode, ctx: True+ self.assertEqual(svc._processing_modes(_ctx()), ["message", "typing", "reaction"])++ def test_active_check_defensive_when_controller_lacks_method(self):+ svc = ProcessingIndicatorService.__new__(ProcessingIndicatorService)+ svc.controller = types.SimpleNamespace() # no uses_concise_status_bubble+ self.assertFalse(svc._concise_status_bubble_active(_ctx()))+++class StartConciseTests(unittest.IsolatedAsyncioTestCase):+ """In concise mode start() keeps the 👀 received-ack reaction AND typing+ keepalive (both best-effort), but never the ack message."""++ def _svc(self, *, concise, reaction_supported=True, typing_supported=True):+ svc = ProcessingIndicatorService.__new__(ProcessingIndicatorService)+ svc.controller = types.SimpleNamespace(uses_concise_status_bubble=lambda ctx: concise)+ svc._capabilities = lambda ctx: object()++ def mode_supported(caps, mode, ctx):+ return {"reaction": reaction_supported, "typing": typing_supported}.get(mode, True)++ svc._mode_supported = mode_supported+ svc._processing_modes = lambda ctx: ["message", "typing", "reaction"]+ svc.calls = []++ async def _reaction(handle):+ svc.calls.append("reaction")+ return True++ async def _typing(handle):+ svc.calls.append("typing")+ return True++ async def _message(handle, agent_name):+ svc.calls.append("message")+ return True++ svc._start_reaction_indicator = _reaction+ svc._start_typing_indicator = _typing+ svc._start_message_indicator = _message+ return svc++ async def test_concise_adds_reaction_and_typing_no_message(self):+ svc = self._svc(concise=True)+ await svc.start(_ctx(), "claude")+ self.assertEqual(svc.calls, ["reaction", "typing"]) # 👀 kept + typing; no ack message++ async def test_concise_skips_reaction_when_unsupported(self):+ svc = self._svc(concise=True, reaction_supported=False)+ await svc.start(_ctx(), "claude")+ self.assertEqual(svc.calls, ["typing"])++ async def test_non_concise_uses_first_wins(self):+ svc = self._svc(concise=False)+ await svc.start(_ctx(), "claude")+ self.assertEqual(svc.calls, ["message"]) # first candidate wins, unchanged+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_status_bubble_settings.py b/tests/test_status_bubble_settings.pynew file mode 100644index 000000000..811b41979--- /dev/null+++ b/tests/test_status_bubble_settings.py@@ -0,0 +1,118 @@+"""Step B: concise status-bubble settings plumbing.++V2Config carries agent_progress_style + heartbeat/no-output thresholds (parsed,+validated, round-tripped); Controller getters expose them to the dispatcher.+"""++from __future__ import annotations++import sys+import tempfile+import types+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from config.v2_config import V2Config+from core.controller import Controller+from tests.test_api_save_config_merge import _full_config_payload+++def _payload(**extra):+ base = _full_config_payload()+ base.update(extra)+ return base+++class ConfigParsingTests(unittest.TestCase):+ def test_defaults(self):+ cfg = V2Config.from_payload(_payload())+ self.assertEqual(cfg.agent_progress_style, "concise")+ self.assertEqual(cfg.agent_status_heartbeat_ms, 15000)+ self.assertEqual(cfg.agent_status_no_output_ms, 180000)++ def test_valid_overrides(self):+ cfg = V2Config.from_payload(+ _payload(+ agent_progress_style="off",+ agent_status_heartbeat_ms=12000,+ agent_status_no_output_ms=60000,+ )+ )+ self.assertEqual(cfg.agent_progress_style, "off")+ self.assertEqual(cfg.agent_status_heartbeat_ms, 12000)+ self.assertEqual(cfg.agent_status_no_output_ms, 60000)++ def test_invalid_values_fall_back_to_defaults(self):+ cfg = V2Config.from_payload(+ _payload(+ agent_progress_style="bogus",+ agent_status_heartbeat_ms=-5,+ agent_status_no_output_ms="nope",+ )+ )+ self.assertEqual(cfg.agent_progress_style, "concise")+ self.assertEqual(cfg.agent_status_heartbeat_ms, 15000)+ self.assertEqual(cfg.agent_status_no_output_ms, 180000)++ def test_bool_is_not_accepted_as_int(self):+ cfg = V2Config.from_payload(_payload(agent_status_heartbeat_ms=True))+ self.assertEqual(cfg.agent_status_heartbeat_ms, 15000)++ def test_out_of_range_int_falls_back_to_default(self):+ # Above the sane cap (heartbeat 1h / no-output 24h) → default, so a+ # fat-fingered value can't silence the heartbeat.+ cfg = V2Config.from_payload(+ _payload(agent_status_heartbeat_ms=10_000_000, agent_status_no_output_ms=10**12)+ )+ self.assertEqual(cfg.agent_status_heartbeat_ms, 15000)+ self.assertEqual(cfg.agent_status_no_output_ms, 180000)++ def test_save_load_round_trip(self):+ with tempfile.TemporaryDirectory() as d:+ path = Path(d) / "config.json"+ cfg = V2Config.from_payload(+ _payload(agent_progress_style="verbose", agent_status_heartbeat_ms=15000)+ )+ cfg.save(config_path=path)+ loaded = V2Config.load(config_path=path)+ self.assertEqual(loaded.agent_progress_style, "verbose")+ self.assertEqual(loaded.agent_status_heartbeat_ms, 15000)+ self.assertEqual(loaded.agent_status_no_output_ms, 180000)+++class ControllerGetterTests(unittest.TestCase):+ def _fake(self, **overrides):+ cfg = V2Config.from_payload(_payload())+ for k, v in overrides.items():+ setattr(cfg, k, v)+ return types.SimpleNamespace(config=cfg)++ def test_progress_style_getter(self):+ fake = self._fake(agent_progress_style="off")+ self.assertEqual(Controller.get_progress_style_for_context(fake, None), "off")++ def test_progress_style_getter_guards_bad_value(self):+ fake = self._fake(agent_progress_style="bogus")+ self.assertEqual(Controller.get_progress_style_for_context(fake, None), "concise")++ def test_interval_getters(self):+ fake = self._fake(agent_status_heartbeat_ms=9000, agent_status_no_output_ms=45000)+ self.assertEqual(Controller.get_heartbeat_interval_ms_for_context(fake, None), 9000)+ self.assertEqual(Controller.get_no_output_hint_after_ms_for_context(fake, None), 45000)++ def test_interval_getters_guard_bad_value(self):+ fake = self._fake(agent_status_heartbeat_ms=0, agent_status_no_output_ms=-1)+ self.assertEqual(Controller.get_heartbeat_interval_ms_for_context(fake, None), 15000)+ self.assertEqual(Controller.get_no_output_hint_after_ms_for_context(fake, None), 180000)++ def test_interval_getters_reject_bool(self):+ # bool is an int subclass; the getter must not treat True as 1ms.+ fake = self._fake(agent_status_heartbeat_ms=True, agent_status_no_output_ms=False)+ self.assertEqual(Controller.get_heartbeat_interval_ms_for_context(fake, None), 15000)+ self.assertEqual(Controller.get_no_output_hint_after_ms_for_context(fake, None), 180000)+++if __name__ == "__main__":+ unittest.main()diff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsxindex 5b45cce49..322f5f5a8 100644--- a/ui/src/components/settings/SettingsMessagingPage.tsx+++ b/ui/src/components/settings/SettingsMessagingPage.tsx@@ -32,6 +32,7 @@ const SAVE_KEYS = ['include_user_info','reply_enhancements','show_pages_prompt',+ 'agent_progress_style','audio_asr','slack','discord',@@ -119,6 +120,11 @@ export const SettingsMessagingPage: React.FC = () => {{ value: 'reaction', label: t('dashboard.ackReaction'), disabled: !reactionSupported },{ value: 'message', label: t('dashboard.ackMessage'), disabled: false },];+ const progressStyleOptions = [+ { value: 'concise', label: t('dashboard.agentProgressStyleConcise') },+ { value: 'verbose', label: t('dashboard.agentProgressStyleVerbose') },+ { value: 'off', label: t('dashboard.agentProgressStyleOff') },+ ];const includeTimeInfoEnabled = config.include_time_info !== false;const audioAsr = config.audio_asr || {};const audioEchoEnabled = audioAsr.echo_transcript !== false;@@ -326,6 +332,29 @@ export const SettingsMessagingPage: React.FC = () => {}/>+ <SettingsRow+ title={t('dashboard.agentProgressStyle')}+ description={t('dashboard.agentProgressStyleHint')}+ control={+ <CompactSelect+ value={config.agent_progress_style || 'concise'}+ onChange={(event) =>+ void persist({+ ...config,+ agent_progress_style: event.target.value || 'concise',+ })+ }+ className="w-40"+ >+ {progressStyleOptions.map((option) => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </CompactSelect>+ }+ />+<SettingsRowtitle={t('dashboard.errorRetryLimit')}description={t('dashboard.errorRetryLimitHint')}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 09d99b0a9..949256a3c 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1365,6 +1365,11 @@"replyEnhancementsHint": "Allow agents to add clickable quick-reply buttons at the end of result messages","showPagesPrompt": "Show Page Guidance","showPagesPromptHint": "Tell agents when and how to use visual Show Pages. The vibe show CLI remains available when this is off.",+ "agentProgressStyle": "Progress display (Slack/Discord)",+ "agentProgressStyleHint": "How agent progress is shown: a single concise status bubble that becomes the result, the verbose process log, or off.",+ "agentProgressStyleConcise": "Concise",+ "agentProgressStyleVerbose": "Verbose",+ "agentProgressStyleOff": "Off","chatMessageFontSize": "Chat Message Font Size","chatMessageFontSizeHint": "Font size for user and agent message bubbles in the Web UI chat","slackLinkPreviews": "Suppress Slack Link Previews",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 83fd0dca8..4b5263b40 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1365,6 +1365,11 @@"replyEnhancementsHint": "允许 Agent 在结果消息末尾添加可点击的快捷回复按钮","showPagesPrompt": "Show Page 引导","showPagesPromptHint": "提示 Agent 何时以及如何使用可视化 Show Page。关闭后 vibe show CLI 仍然可用。",+ "agentProgressStyle": "进度显示(Slack/Discord)",+ "agentProgressStyleHint": "Agent 进度的呈现方式:精简状态条(最终变成结果) / 详细过程日志 / 关闭。",+ "agentProgressStyleConcise": "精简",+ "agentProgressStyleVerbose": "详细",+ "agentProgressStyleOff": "关闭","chatMessageFontSize": "聊天消息字号","chatMessageFontSizeHint": "Web UI 聊天页里用户和 Agent 消息气泡的文字大小","slackLinkPreviews": "关闭 Slack 链接预览",diff --git a/vibe/api.py b/vibe/api.pyindex 5a2773898..c6390c049 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -955,6 +955,9 @@ def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dic"include_user_info": config.include_user_info,"reply_enhancements": config.reply_enhancements,"show_pages_prompt": config.show_pages_prompt,+ "agent_progress_style": config.agent_progress_style,+ "agent_status_heartbeat_ms": config.agent_status_heartbeat_ms,+ "agent_status_no_output_ms": config.agent_status_no_output_ms,"setup_completed": config.setup_completed,}return payloaddiff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 65587a643..16cbdb1f3 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1,4 +1,12 @@{+ "status": {+ "backendUnresponsive": "backend not responding",+ "done": "done",+ "stopped": "stopped",+ "failed": "failed",+ "steps": "{count} st",+ "tokens": "{count} tok"+ },"fork": {"title": "Fork {title}","titleUntitled": "Fork"diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex acb25119c..6f55a19d4 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1,4 +1,12 @@{+ "status": {+ "backendUnresponsive": "后端无响应",+ "done": "完成",+ "stopped": "已终止",+ "failed": "失败",+ "steps": "{count} 步",+ "tokens": "{count} tok"+ },"fork": {"title": "复刻 {title}","titleUntitled": "复刻"