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(result): show_duration duration + token usage as grey footer (#829)
Qi Qie3282021abb6
diff --git a/core/controller.py b/core/controller.pyindex bf3929d49..f39c1b146 100644--- a/core/controller.py+++ b/core/controller.py@@ -1262,6 +1262,7 @@ class Controller:is_error: bool = False,level: str = "normal",status_label: Optional[str] = None,+ result_footer: Optional[str] = None,):"""Backward-compatible entrypoint; delegated to message dispatcher."""return await self.message_dispatcher.emit_agent_message(@@ -1272,6 +1273,7 @@ class Controller:is_error=is_error,level=level,status_label=status_label,+ result_footer=result_footer,)def note_session_tokens(self, context: MessageContext, *, total: int) -> None:@@ -1284,6 +1286,15 @@ class Controller:returndispatcher.note_session_tokens(context, total=total)+ def session_token_field(self, context: MessageContext) -> str:+ """The compact ``{n} tok`` footer field for the session's current+ context-window occupancy, or "" when unknown/zero or the dispatcher is+ unavailable (partially-wired test controllers)."""+ dispatcher = getattr(self, "message_dispatcher", None)+ if dispatcher is None:+ return ""+ return dispatcher.session_token_field(context)+# Main run methoddef run(self):"""Run the controller"""diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 85a561335..8394229a7 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -571,6 +571,16 @@ class ConsolidatedMessageDispatcher:return f"{n / 1_000_000:.1f}M"return f"{round(n / 1_000_000)}M"+ @staticmethod+ def _fold_footer(text: str, footer: Optional[str]) -> str:+ """Append a de-emphasized footnote onto a body for platforms that cannot+ render a native subtext footer, with the same ``\\n\\n`` separator used for+ delivery. Returns ``text`` unchanged when there is no footer, and the+ footer alone when the body is empty."""+ if not footer:+ return text+ return f"{text}\n\n{footer}" if (text or "").strip() else footer+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@@ -627,6 +637,13 @@ class ConsolidatedMessageDispatcher:return ""return self._t("status.tokens", count=self._format_token_count(tokens))+ def session_token_field(self, context: MessageContext) -> str:+ """Public accessor for the compact ``{n} tok`` field of the session's+ current context-window occupancy (``""`` when unknown/zero). Lets the+ ``show_duration`` result footer reuse the same figure and styling as the+ concise status bubble."""+ return self._token_field(context)+def _status_footer_text(self,context: MessageContext,@@ -1197,6 +1214,7 @@ class ConsolidatedMessageDispatcher:is_error: bool = False,level: str = "normal",status_label: Optional[str] = None,+ result_footer: Optional[str] = None,) -> Optional[str]:"""Centralized dispatch for agent messages.@@ -1228,6 +1246,11 @@ class ConsolidatedMessageDispatcher:process path (assistant/toolcall). The persisted row and the verboseappend path keep using the original ``text`` unchanged; when it is emptythe bubble falls back to ``to_status_label(text)`` as before.++ ``result_footer`` is an optional de-emphasized one-line footnote for a+ terminal ``result`` (the show_duration duration + token usage). It rides+ as the platform subtext footer and, in concise mode, supersedes the status+ bubble's own terminal footer so the outcome line stays consistent."""settings_manager = self.controller.get_settings_manager_for_context(context)im_client = self._get_im_client(context)@@ -1322,20 +1345,25 @@ class ConsolidatedMessageDispatcher:try:message_id = f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"terminal_status = None+ # Delivery is suppressed (private scheduled/agent_run), so the footer+ # can't ride subtext — fold the show_duration footnote into the+ # RECORDED text so the stored result keeps the duration/token info+ # that used to live in the body. No-op when there is no footer.+ recorded_text = self._fold_footer(text, result_footer)if (canonical_type == "result"and (context.platform_specific or {}).get("task_trigger_kind") == "agent_run"):self._record_suppressed_agent_run_terminal_result(context,- text,+ recorded_text,message_id,is_error=is_error,)elif canonical_type == "result" or (context.platform_specific or {}).get("task_trigger_kind") != "agent_run":self._record_suppressed_run_message(context,- text,+ recorded_text,message_id,terminal_status=terminal_status,)@@ -1397,6 +1425,34 @@ class ConsolidatedMessageDispatcher:_, done_footer = self._compose_status_message(context, status_consolidated_key, done=True, reason=terminal_reason, result_body=display_text)+ # A caller-supplied ``result_footer`` (the show_duration duration ++ # token footnote) is delivered per platform capability:+ # * platforms that render the de-emphasized subtext footer+ # (``supports_status_bubble``: Slack/Discord/Lark) get it as+ # grey subtext — and in concise mode it supersedes the bubble's+ # own ``✅ done · …`` line so the terminal footer stays+ # consistent (grey, one line, no head text);+ # * platforms WITHOUT subtext rendering (Telegram/WeChat/Avibe)+ # fold it onto the body as a trailing line, so the footnote+ # stays visible AND their senders (which don't accept the+ # ``subtext`` kwarg) are never handed it.+ # ``folded_footer`` is the footnote to APPEND to the stored text so+ # a reloaded transcript / inbox / agent-run record keeps the+ # duration/token info (it used to live in the result body). It is+ # set for BOTH platform kinds; only the DELIVERY form differs.+ folded_footer: Optional[str] = result_footer or None+ if result_footer:+ # Gate on the DELIVERY TARGET's capabilities, not the source+ # context: a delivery_override can redirect a Slack/Discord/Lark+ # turn to a non-subtext target (or vice versa), and the footer+ # must follow where it is actually delivered/persisted.+ if self._capabilities(target_context).supports_status_bubble:+ # Subtext-capable: deliver as the grey subtext footer (body+ # stays clean); persistence still folds it in below.+ done_footer = result_footer+ else:+ # No subtext rendering: fold onto the delivered body too.+ display_text = self._fold_footer(display_text, result_footer)# 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).@@ -1561,9 +1617,17 @@ class ConsolidatedMessageDispatcher:else:await self._clear_consolidated_state(context)+ # The stored text keeps the footnote for BOTH platform kinds:+ # ``display_text`` already carries it on non-subtext platforms (folded+ # above), while subtext platforms delivered it out-of-band — folding+ # ``folded_footer`` onto the clean ``persist_text`` reconstructs the+ # same body+footer without double-appending (persist_text is never+ # mutated) and is a no-op when there is no footer.+ persisted_result_text = self._fold_footer(persist_text, folded_footer)+self._record_agent_run_terminal_result(context,- display_text,+ persisted_result_text,primary_message_id,is_error=is_error,)@@ -1588,7 +1652,7 @@ class ConsolidatedMessageDispatcher:avibe_enhanced = process_reply(text, include_quick_replies=quick_replies_on, keep_file_links=True)- avibe_text = avibe_enhanced.text or persist_text+ avibe_text = self._fold_footer(avibe_enhanced.text or persist_text, folded_footer)persist_agent_message(target_context,result_type,@@ -1596,7 +1660,9 @@ class ConsolidatedMessageDispatcher:quick_replies=[b.text for b in avibe_enhanced.buttons] or None,)else:- persist_agent_message(target_context, result_type, persist_text)+ persist_agent_message(+ target_context, result_type, persisted_result_text+ )if primary_message_id and display_text:# Stream the delivered result to live consumers (avibe SSE).diff --git a/modules/agents/base.py b/modules/agents/base.pyindex b614a31d3..726b94546 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -504,15 +504,44 @@ class BaseAgent(ABC):# dot stays green and the stream hangs until the 600s timeout (Codex P2).await self.controller.emit_agent_message(context, "result", "", parse_mode=parse_mode, is_error=is_error)else:- formatted = self._get_formatter(context).format_result_message(- subtype or "",- duration_ms,- visible_result,- show_duration=True,- )+ token_field = ""+ get_token_field = getattr(self.controller, "session_token_field", None)+ if callable(get_token_field):+ try:+ token_field = get_token_field(context) or ""+ except Exception:+ token_field = ""+ # Duration + token usage ride as a de-emphasized grey subtext footer+ # (the same channel as the concise status footer), NOT a prominent head+ # line. The body carries only the actual answer + suffix.+ result_footer = None+ if duration_ms > 0 or token_field:+ result_footer = self._get_formatter(context).format_result_footer(+ subtype or "",+ duration_ms,+ token_field=token_field,+ )+ parts = []+ if visible_result and visible_result.strip():+ parts.append(visible_result)if visible_suffix:- formatted = f"{formatted}\n{visible_suffix}"- await self.controller.emit_agent_message(context, "result", formatted, parse_mode=parse_mode, is_error=is_error)+ parts.append(visible_suffix)+ body = "\n".join(parts)+ # Footer-only completion (show_duration on, no visible result/suffix):+ # promote the footnote to the visible body so a duration/token-only turn+ # is still delivered/persisted/streamed. An empty body would otherwise be+ # treated as a silent terminal result and the footnote would be lost.+ if not body.strip() and result_footer:+ body = result_footer+ result_footer = None+ await self.controller.emit_agent_message(+ context,+ "result",+ body,+ parse_mode=parse_mode,+ is_error=is_error,+ result_footer=result_footer,+ )# Remove ack reaction after result is sentif request:diff --git a/modules/im/avibe.py b/modules/im/avibe.pyindex b6be944f9..5f2d83c09 100644--- a/modules/im/avibe.py+++ b/modules/im/avibe.py@@ -109,7 +109,11 @@ class AvibeBot(BaseIMClient):text: str,parse_mode: Optional[str] = None,reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:+ # ``subtext`` is accepted for the BaseIMClient contract and ignored: the+ # Web Chat surface has no native de-emphasized footer, so the dispatcher+ # folds any footnote into ``text`` for this platform instead.message_id = _new_message_id()logger.debug("AvibeBot.send_message: scope=%s message_id=%s len=%s reply_to=%s",@@ -135,7 +139,10 @@ class AvibeBot(BaseIMClient):text: str,keyboard: InlineKeyboard,parse_mode: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:+ # ``subtext`` accepted for the BaseIMClient contract and ignored (see+ # send_message); the dispatcher folds footnotes into ``text`` here.message_id = _new_message_id()button_count = len(getattr(keyboard, "buttons", []) or [])logger.debug(diff --git a/modules/im/formatters/base_formatter.py b/modules/im/formatters/base_formatter.pyindex 520dae072..d8c2654b6 100644--- a/modules/im/formatters/base_formatter.py+++ b/modules/im/formatters/base_formatter.py@@ -392,38 +392,78 @@ class BaseMarkdownFormatter(ABC):parts = [header] + escaped_partsreturn "\n\n".join(parts)- def format_result_message(+ def format_result_footer(self,subtype: str,duration_ms: int,- result: Optional[str] = None,+ token_field: str = "",show_duration: bool = True,) -> str:- """Format result message.-- Format: ⏱️ Success: 2m 24s (when show_duration=True)- ⏱️ Success (when show_duration=False)+ """Build the compact one-line result footnote (no answer body).++ The outcome word (``Success``/``Done``/…) is a compact status emoji, and+ the duration/token fields keep their own glyphs (⏱️ time, 🪙 tokens) so it+ reads like the concise status footer. Meant to ride as a de-emphasized+ grey subtext footer, not as a prominent head line.++ Format: ✅ ⏱️ 2m 24s · 🪙 240k tok (success, duration + tokens known)+ ✅ ⏱️ 2m 24s (success, no tokens)+ ✅ 🪙 240k tok (no duration, tokens known)+ ✅ (nothing else to show)+ ⚠️ ⏱️ 2m 24s (warning subtype)+ ❌ ⏱️ 2m 24s (error subtype)++ ``token_field`` is the already-formatted compact usage string (e.g.+ ``240k tok``); duration and tokens share the same ``·`` separator as the+ concise footer, and each field is omitted when empty."""- subtype_display = subtype.capitalize() if subtype else "Done"+ subtype_lower = (subtype or "").lower()+ if subtype_lower.startswith("error"):+ marker = "❌"+ elif subtype_lower == "warning":+ marker = "⚠️"+ else:+ marker = "✅"+ segments: list[str] = []if show_duration and duration_ms > 0:total_seconds = duration_ms / 1000minutes = int(total_seconds // 60)seconds = int(total_seconds % 60)if minutes > 0:- duration_str = f"{minutes}m {seconds}s"+ segments.append(f"⏱️ {minutes}m {seconds}s")else:- duration_str = f"{seconds}s"+ segments.append(f"⏱️ {seconds}s")- result_text = f"⏱️ {subtype_display}: {duration_str}"- else:- result_text = f"⏱️ {subtype_display}"+ if token_field:+ segments.append(f"🪙 {token_field}")- if result:- result_text += f"\n\n{result}"+ footer = marker+ if segments:+ footer += " " + " · ".join(segments)+ return footer- return result_text+ def format_result_message(+ self,+ subtype: str,+ duration_ms: int,+ result: Optional[str] = None,+ show_duration: bool = True,+ token_field: str = "",+ ) -> str:+ """Result footnote plus (optionally) the answer body below it.++ Retained for the legacy Claude SDK formatting path; the primary result+ flow now delivers the footnote via :meth:`format_result_footer` as a+ de-emphasized subtext footer instead of a head line.+ """+ footer = self.format_result_footer(+ subtype, duration_ms, token_field=token_field, show_duration=show_duration+ )+ if result:+ return f"{footer}\n\n{result}"+ return footerdef format_tool_result(self, is_error: bool, content: Optional[str] = None) -> str:"""Format tool result block"""diff --git a/modules/im/slack.py b/modules/im/slack.pyindex 19b6788c2..4b538ab54 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -857,20 +857,21 @@ 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.+ # Over the markdown-block cap: keep the LEGACY mrkdwn/section path, which+ # cannot carry a separate context-footer block (routing through the+ # status-bubble path would reject bodies > the cap). Fold ``subtext``+ # onto the body instead so the show_duration/token footnote is retained+ # rather than silently dropped for 12k–30k inline results.+ body = f"{text}\n\n{subtext}" if subtext else textif keyboard:return await self.send_message_with_buttons(context,- text,+ body,keyboard,parse_mode="markdown",reply_to=reply_to,)- return await self.send_message(context, text, parse_mode="markdown", reply_to=reply_to)+ return await self.send_message(context, body, parse_mode="markdown", reply_to=reply_to)blocks = [self._build_markdown_block(text)]if keyboard:@@ -902,20 +903,22 @@ 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.+ # Do NOT forward subtext as a separate footer block here: that 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. Instead FOLD+ # the footer onto the body (plain mrkdwn) so the show_duration/token+ # footnote is retained rather than dropped on this recovery path.+ body = f"{text}\n\n{subtext}" if subtext else textif keyboard:return await self.send_message_with_buttons(context,- text,+ body,keyboard,parse_mode="markdown",reply_to=reply_to,)- return await self.send_message(context, text, parse_mode="markdown", reply_to=reply_to)+ return await self.send_message(context, body, parse_mode="markdown", reply_to=reply_to)if self.settings_manager and (context.thread_id or reply_to):thread_ts = context.thread_id or reply_todiff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex 353edb18b..97d7ea4c6 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -1078,12 +1078,17 @@ class TelegramBot(BaseIMClient):text: str,keyboard: Optional[InlineKeyboard] = None,reply_to: Optional[str] = None,+ subtext: Optional[str] = None,) -> str:"""Send LLM-authored Markdown through Telegram Rich Messages when useful.Bot API 10.1 rich messages understand GFM-like block structure. Plainshort markdown still uses the legacy HTML conversion path because it isolder, broadly deployed, and sufficient for simple emphasis/links/code.++ ``subtext`` is accepted for the BaseIMClient contract and ignored:+ Telegram has no native de-emphasized footer, so the dispatcher folds any+ footnote into ``text`` for this platform instead."""if not self._should_send_rich_markdown(text):if keyboard is not None:diff --git a/tests/test_agent_silent_result.py b/tests/test_agent_silent_result.pyindex 9e989bfbf..ab10ce376 100644--- a/tests/test_agent_silent_result.py+++ b/tests/test_agent_silent_result.py@@ -9,17 +9,26 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from modules.agents.base import AgentRequest, BaseAgentfrom modules.im import MessageContext+from modules.im.formatters.slack_formatter import SlackFormatterclass _StubController:- def __init__(self):+ def __init__(self, token_field: str = ""):self.config = SimpleNamespace(show_duration=True)- self.im_client = SimpleNamespace(formatter=None)+ self.im_client = SimpleNamespace(formatter=SlackFormatter())self.settings_manager = SimpleNamespace(sessions=None)self.messages = []+ self.result_footers = []+ self._token_field = token_field- async def emit_agent_message(self, context, message_type, text, parse_mode="markdown", *, is_error=False, level="normal"):+ def session_token_field(self, context):+ return self._token_field++ async def emit_agent_message(+ self, context, message_type, text, parse_mode="markdown", *, is_error=False, level="normal", result_footer=None+ ):self.messages.append((message_type, text, parse_mode))+ self.result_footers.append(result_footer)class _StubAgent(BaseAgent):@@ -60,6 +69,21 @@ class AgentSilentResultTests(unittest.IsolatedAsyncioTestCase):# result path settles the dot + releases the stream.self.assertEqual(controller.messages, [("result", "", "markdown")])+ async def test_footer_only_result_is_promoted_to_visible_body(self):+ # show_duration on + no visible result/suffix: the duration/token footnote+ # is promoted to the visible body (and NOT sent as a separate footer), so a+ # timing-only completion is still delivered/persisted instead of going+ # silent (Codex P2).+ controller = _StubController(token_field="1.2k tok")+ agent = _StubAgent(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")++ await agent.emit_result_message(context, "", subtype="success", duration_ms=5000)++ self.assertEqual(controller.messages, [("result", "✅ ⏱️ 5s · 🪙 1.2k tok", "markdown")])+ # Promoted to body, so no separate subtext footer is passed.+ self.assertEqual(controller.result_footers, [None])+class AgentSessionIdContextTests(unittest.TestCase):def test_bind_agent_session_id_attaches_returned_public_session_id(self):diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex 002172a95..543fff801 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -79,6 +79,21 @@ class _NativeMarkdownIMClient(_StubIMClient):return message_id+class _SubtextNativeMarkdownIMClient(_StubIMClient):+ """Native-markdown client that accepts (and records) the ``subtext`` footer,+ modelling a ``supports_status_bubble`` platform (Slack/Discord/Lark)."""++ def __init__(self):+ super().__init__()+ self.native_markdown_messages = []++ async def send_markdown_message(self, context, text, keyboard=None, reply_to=None, subtext=None):+ self.native_markdown_messages.append((context.channel_id, text, keyboard, reply_to, subtext))+ message_id = f"native-{self._next_id}"+ self._next_id += 1+ return message_id++class _StubController:def __init__(self,@@ -146,6 +161,104 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):self.assertIsNone(reply_to)self.assertEqual([button.text for button in keyboard.buttons[0]], ["Continue", "Stop"])+ async def test_result_footer_rides_subtext_on_status_bubble_platform(self):+ """On a ``supports_status_bubble`` platform (Slack) the show_duration+ footnote is delivered as the de-emphasized ``subtext`` footer and the body+ stays clean."""+ im_client = _SubtextNativeMarkdownIMClient()+ controller = _StubController(platform="slack", im_client=im_client)+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")++ message_id = await dispatcher.emit_agent_message(+ context, "result", "Answer body", result_footer="✅ ⏱️ 5s · 🪙 1.2k tok"+ )++ self.assertEqual(message_id, "native-1")+ channel_id, text, _keyboard, _reply_to, subtext = im_client.native_markdown_messages[0]+ self.assertEqual(text, "Answer body")+ self.assertEqual(subtext, "✅ ⏱️ 5s · 🪙 1.2k tok")++ async def test_result_footer_folds_into_body_without_subtext_platform(self):+ """On a platform WITHOUT subtext rendering (Telegram) the footnote folds+ onto the body and no ``subtext`` kwarg is passed — a send_message that+ lacks the kwarg would otherwise raise (the Codex P2 regression)."""+ im_client = _StubIMClient() # send_message has no ``subtext`` parameter+ controller = _StubController(platform="telegram", im_client=im_client)+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="telegram")++ message_id = await dispatcher.emit_agent_message(+ context, "result", "Answer body", result_footer="✅ ⏱️ 5s · 🪙 1.2k tok"+ )++ self.assertEqual(message_id, "msg-1")+ channel_id, text, _parse_mode = im_client.sent_messages[0]+ self.assertEqual(text, "Answer body\n\n✅ ⏱️ 5s · 🪙 1.2k tok")++ async def test_result_footer_uses_delivery_target_capability_not_source(self):+ """A Slack (subtext) turn redirected via ``delivery_override`` to a+ non-subtext target (Telegram) must FOLD the footnote, not hand ``subtext``+ to the target adapter that ignores it (Codex P2)."""+ im_client = _StubIMClient() # no ``subtext`` kwarg on send_message+ controller = _StubController(platform="slack", im_client=im_client)+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="slack",+ platform_specific={"delivery_override": {"platform": "telegram", "channel_id": "T1"}},+ )++ message_id = await dispatcher.emit_agent_message(+ context, "result", "Answer body", result_footer="✅ ⏱️ 5s · 🪙 1.2k tok"+ )++ self.assertEqual(message_id, "msg-1")+ _channel, text, _parse_mode = im_client.sent_messages[0]+ self.assertEqual(text, "Answer body\n\n✅ ⏱️ 5s · 🪙 1.2k tok")++ async def test_result_footer_persisted_on_subtext_platform(self):+ """On a subtext platform (Slack) the footer is delivered out-of-band as+ subtext, but the stored text must still keep it so a reloaded transcript /+ inbox / agent-run record retains the duration/token info (Codex P2)."""+ im_client = _SubtextNativeMarkdownIMClient()+ controller = _StubController(platform="slack", im_client=im_client)+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")++ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ await dispatcher.emit_agent_message(+ context, "result", "Answer body", result_footer="✅ ⏱️ 5s · 🪙 1.2k tok"+ )++ # Delivered: body clean, footer rides subtext.+ _c, text, _k, _r, subtext = im_client.native_markdown_messages[0]+ self.assertEqual(text, "Answer body")+ self.assertEqual(subtext, "✅ ⏱️ 5s · 🪙 1.2k tok")+ # Persisted: footer folded into the stored text.+ persist.assert_called_once()+ _, _ptype, ptext = persist.call_args.args+ self.assertEqual(ptext, "Answer body\n\n✅ ⏱️ 5s · 🪙 1.2k tok")++ async def test_folded_result_footer_is_persisted_for_non_subtext_platform(self):+ """The folded footnote must be persisted too, so a reloaded transcript /+ inbox entry matches the delivered message (result-path invariant)."""+ im_client = _StubIMClient()+ controller = _StubController(platform="telegram", im_client=im_client)+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="telegram")++ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ await dispatcher.emit_agent_message(+ context, "result", "Answer body", result_footer="✅ ⏱️ 5s · 🪙 1.2k tok"+ )++ persist.assert_called_once()+ _, persisted_type, persisted_text = persist.call_args.args+ self.assertEqual(persisted_type, "result")+ self.assertEqual(persisted_text, "Answer body\n\n✅ ⏱️ 5s · 🪙 1.2k tok")+async def test_result_persists_cleaned_display_text_not_raw(self):"""The persisted result must match what the user was shown, not the rawtext with reply-enhancer artifacts. The inbox preview + chat transcript@@ -203,6 +316,28 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):persist.assert_not_called()self.assertTrue(message_id.startswith("suppressed:"))+ async def test_suppressed_result_records_folded_footer(self):+ """A suppressed (private) result can't ride subtext, so the footnote must+ be folded into the recorded text to keep the duration/token info (Codex P2)."""+ controller = _StubController(platform="slack")+ dispatcher = ConsolidatedMessageDispatcher(controller)+ captured = {}++ def _capture(context, text, message_id, terminal_status=None):+ captured["text"] = text++ dispatcher._record_suppressed_run_message = _capture+ context = MessageContext(+ user_id="U1", channel_id="C1", platform="slack",+ platform_specific={"suppress_delivery": True},+ )++ await dispatcher.emit_agent_message(+ context, "result", "private output", result_footer="✅ ⏱️ 5s · 🪙 1.2k tok"+ )++ self.assertEqual(captured["text"], "private output\n\n✅ ⏱️ 5s · 🪙 1.2k tok")+async def test_notify_persisted_only_on_successful_send(self):controller = _StubController(platform="slack")dispatcher = ConsolidatedMessageDispatcher(controller)diff --git a/tests/test_result_message_token_field.py b/tests/test_result_message_token_field.pynew file mode 100644index 000000000..99175876d--- /dev/null+++ b/tests/test_result_message_token_field.py@@ -0,0 +1,70 @@+from __future__ import annotations++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from modules.im.formatters.slack_formatter import SlackFormatter+++def test_result_footer_uses_status_emoji_time_and_token_glyphs() -> None:+ formatter = SlackFormatter()++ footer = formatter.format_result_footer(+ "success",+ duration_ms=144_000,+ token_field="240k tok",+ )++ assert footer == "✅ ⏱️ 2m 24s · 🪙 240k tok"+++def test_result_footer_omits_token_field_when_empty() -> None:+ formatter = SlackFormatter()++ footer = formatter.format_result_footer("success", duration_ms=5_000, token_field="")++ assert footer == "✅ ⏱️ 5s"+++def test_result_footer_shows_token_without_duration() -> None:+ formatter = SlackFormatter()++ footer = formatter.format_result_footer("success", duration_ms=0, token_field="12.3k tok")++ assert footer == "✅ 🪙 12.3k tok"+++def test_result_footer_bare_marker_when_nothing_else() -> None:+ formatter = SlackFormatter()++ footer = formatter.format_result_footer(+ "success", duration_ms=0, token_field="", show_duration=False+ )++ assert footer == "✅"+++def test_result_footer_error_and_warning_markers() -> None:+ formatter = SlackFormatter()++ error = formatter.format_result_footer("error_max_turns", duration_ms=5_000)+ warning = formatter.format_result_footer("warning", duration_ms=5_000)++ assert error == "❌ ⏱️ 5s"+ assert warning == "⚠️ ⏱️ 5s"+++def test_result_message_keeps_footer_above_body_for_legacy_path() -> None:+ formatter = SlackFormatter()++ rendered = formatter.format_result_message(+ "success",+ duration_ms=144_000,+ result="all done",+ show_duration=True,+ token_field="240k tok",+ )++ assert rendered == "✅ ⏱️ 2m 24s · 🪙 240k tok\n\nall done"diff --git a/tests/test_slack_markdown_footer.py b/tests/test_slack_markdown_footer.pynew file mode 100644index 000000000..f51783ac9--- /dev/null+++ b/tests/test_slack_markdown_footer.py@@ -0,0 +1,81 @@+from __future__ import annotations++import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from config.v2_config import SlackConfig+from modules.im.base import MessageContext+from modules.im.slack import SlackApiError, SlackBot, _SLACK_MARKDOWN_TEXT_LIMIT+++class SlackMarkdownFooterTests(unittest.IsolatedAsyncioTestCase):+ async def test_long_result_folds_subtext_into_body(self):+ """A 12k-30k inline Slack result falls back to the legacy mrkdwn path,+ which can't carry a context-footer block; the show_duration footnote must+ be folded onto the body instead of silently dropped (Codex P2)."""+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ slack._ensure_clients = lambda: None+ captured = {}++ async def fake_send(context, text, parse_mode=None, reply_to=None):+ captured["text"] = text+ return "ts-1"++ slack.send_message = fake_send+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")+ big = "x" * (_SLACK_MARKDOWN_TEXT_LIMIT + 1)++ message_id = await slack.send_markdown_message(context, big, subtext="✅ ⏱️ 5s · 🪙 1.2k tok")++ self.assertEqual(message_id, "ts-1")+ self.assertEqual(captured["text"], f"{big}\n\n✅ ⏱️ 5s · 🪙 1.2k tok")++ async def test_long_result_without_subtext_unchanged(self):+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ slack._ensure_clients = lambda: None+ captured = {}++ async def fake_send(context, text, parse_mode=None, reply_to=None):+ captured["text"] = text+ return "ts-2"++ slack.send_message = fake_send+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")+ big = "y" * (_SLACK_MARKDOWN_TEXT_LIMIT + 1)++ await slack.send_markdown_message(context, big)++ self.assertEqual(captured["text"], big)+++ async def test_block_rejection_fallback_folds_subtext(self):+ """When Slack rejects the native markdown block (invalid_blocks etc.), the+ legacy-mrkdwn recovery must fold the footnote onto the body so the+ show_duration/token footer survives (Codex P2)."""+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ slack._ensure_clients = lambda: None+ slack._is_markdown_block_rejection = lambda err: True+ captured = {}++ async def raise_rejection(context, kwargs, log_label=None):+ raise SlackApiError("invalid_blocks", {"ok": False, "error": "invalid_blocks"})++ async def fake_send(context, text, parse_mode=None, reply_to=None):+ captured["text"] = text+ return "ts-3"++ slack._post_message_with_dm_recovery = raise_rejection+ slack.send_message = fake_send+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")++ message_id = await slack.send_markdown_message(context, "Answer body", subtext="✅ ⏱️ 5s · 🪙 1.2k tok")++ self.assertEqual(message_id, "ts-3")+ self.assertEqual(captured["text"], "Answer body\n\n✅ ⏱️ 5s · 🪙 1.2k tok")+++if __name__ == "__main__":+ unittest.main()