Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(chat): move result metrics beside timestamp (#1128)

Call White78576932e6ea
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 94fccc492..4832dd15e 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -1630,15 +1630,12 @@ class ConsolidatedMessageDispatcher:
include_quick_replies=quick_replies_on,
keep_file_links=True,
)
- recorded_text = self._fold_footer(
- background_enhanced.text or persist_text,
- result_footer,
- )
persisted_output = persist_agent_message(
target_context,
result_type,
- recorded_text,
+ background_enhanced.text or persist_text,
quick_replies=[b.text for b in background_enhanced.buttons] or None,
+ result_footer=result_footer,
metadata=output_metadata,
native_message_id=native_output_id,
)
@@ -1647,6 +1644,7 @@ class ConsolidatedMessageDispatcher:
target_context,
result_type,
recorded_text,
+ result_footer=result_footer,
metadata=output_metadata,
native_message_id=native_output_id,
)
@@ -1789,14 +1787,15 @@ class ConsolidatedMessageDispatcher:
# 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)
+ # * IM platforms WITHOUT subtext rendering (Telegram/WeChat)
# 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.
+ # * Avibe carries it as structured message content; the Web
+ # transcript renders it beside the timestamp.
+ # ``folded_footer`` is the canonical footnote carried to IM
+ # delivery, agent-run records, and structured Web message content.
+ # It is set for every platform; only the presentation differs.
folded_footer: Optional[str] = result_footer if mutates_turn_lifecycle else None
if folded_footer:
# Gate on the DELIVERY TARGET's capabilities, not the source
@@ -1807,7 +1806,7 @@ class ConsolidatedMessageDispatcher:
# Subtext-capable: deliver as the grey subtext footer (body
# stays clean); persistence still folds it in below.
done_footer = folded_footer
- else:
+ elif target_context.platform != "avibe":
# No subtext rendering: fold onto the delivered body too.
display_text = self._fold_footer(display_text, folded_footer)
# Pass subtext to RAW send_message calls only when set, so an adapter
@@ -1975,12 +1974,9 @@ 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.
+ # Agent-run records keep the complete body+footer text for every
+ # platform. The Web message row separately persists a clean body
+ # plus structured footer below.
persisted_result_text = self._fold_footer(persist_text, folded_footer)
run_provenance = output_semantics.provenance(context)
workbench_run_waits_for_persistence = (
@@ -2023,12 +2019,12 @@ class ConsolidatedMessageDispatcher:
avibe_enhanced = process_reply(
raw_text, include_quick_replies=quick_replies_on, keep_file_links=True
)
- avibe_text = self._fold_footer(avibe_enhanced.text or persist_text, folded_footer)
persisted_output = persist_agent_message(
target_context,
result_type,
- avibe_text,
+ avibe_enhanced.text or persist_text,
quick_replies=[b.text for b in avibe_enhanced.buttons] or None,
+ result_footer=folded_footer,
metadata=output_metadata,
native_message_id=native_output_id,
)
@@ -2037,6 +2033,7 @@ class ConsolidatedMessageDispatcher:
target_context,
result_type,
persisted_result_text,
+ result_footer=folded_footer,
metadata=output_metadata,
native_message_id=native_output_id,
)
diff --git a/core/message_mirror.py b/core/message_mirror.py
index d88be5fff..4dafcffd8 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -321,6 +321,7 @@ def persist_agent_message(
text: str,
*,
quick_replies: Optional[list[str]] = None,
+ result_footer: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
native_message_id: Optional[str] = None,
error_sink: Optional[list] = None,
@@ -432,6 +433,11 @@ def persist_agent_message(
# render their own native buttons from the same parse).
if quick_replies:
content = {**(content or {}), "quick_replies": list(quick_replies)}
+ # Keep the generated duration/token summary as structured content.
+ # IM delivery may still fold it into ``text``, while the Web
+ # transcript can render it beside the timestamp without guessing.
+ if result_footer:
+ content = {**(content or {}), "result_footer": result_footer}
appended_row = _append_quietly(
conn,
scope_id=scope_id,
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index d6cf83c9c..6308a7111 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -549,6 +549,7 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
persist.assert_called_once()
_, _ptype, ptext = persist.call_args.args
self.assertEqual(ptext, "Answer body\n\n✅ ⏱️ 5s · 🪙 1.2k tok")
+ self.assertEqual(persist.call_args.kwargs["result_footer"], "✅ ⏱️ 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 /
@@ -567,6 +568,22 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
_, 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")
+ self.assertEqual(persist.call_args.kwargs["result_footer"], "✅ ⏱️ 5s · 🪙 1.2k tok")
+
+ async def test_avibe_persists_clean_body_with_structured_result_footer(self):
+ controller = _StubController(platform="avibe")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="U1", channel_id="C1", platform="avibe")
+
+ 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"
+ )
+
+ _, persisted_type, persisted_text = persist.call_args.args
+ self.assertEqual(persisted_type, "result")
+ self.assertEqual(persisted_text, "Answer body")
+ self.assertEqual(persist.call_args.kwargs["result_footer"], "✅ ⏱️ 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 raw
@@ -732,9 +749,9 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(controller.im_client.sent_messages, [])
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")
+ """A suppressed Web result keeps structured UI metrics while its run
+ record retains the complete folded text."""
+ controller = _StubController(platform="avibe")
dispatcher = ConsolidatedMessageDispatcher(controller)
captured = {}
@@ -743,15 +760,18 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
dispatcher._record_suppressed_run_message = _capture
context = MessageContext(
- user_id="U1", channel_id="C1", platform="slack",
+ user_id="U1", channel_id="C1", platform="avibe",
platform_specific={"suppress_delivery": True},
)
- await dispatcher.emit_agent_message(
- context, "result", "private output", result_footer="✅ ⏱️ 5s · 🪙 1.2k tok"
- )
+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:
+ 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")
+ self.assertEqual(persist.call_args.args[2], "private output")
+ self.assertEqual(persist.call_args.kwargs["result_footer"], "✅ ⏱️ 5s · 🪙 1.2k tok")
async def test_notify_persisted_only_on_successful_send(self):
controller = _StubController(platform="slack")
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index 4aee2b632..524a226cf 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -123,6 +123,27 @@ def test_persist_agent_writes_typed_agent_row_on_same_scope(isolated_state):
assert agent_row["scope_id"] == user_row["scope_id"]
+def test_persist_agent_keeps_result_footer_as_structured_content(isolated_state):
+ ctx = _slack_ctx()
+ mirror_inbound(ctx, "ping")
+ persist_agent_message(
+ ctx,
+ "result",
+ "pong\n\n✅ ⏱️ 5s · 🪙 1.2k tok",
+ result_footer="✅ ⏱️ 5s · 🪙 1.2k tok",
+ )
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(messages).where(messages.c.author == "agent")
+ ).mappings().one()
+
+ content = json.loads(row["content_json"])
+ assert content["kind"] == "result"
+ assert content["result_footer"] == "✅ ⏱️ 5s · 🪙 1.2k tok"
+
+
def test_agent_output_provenance_is_hidden_metadata_and_deduplicated(isolated_state):
ctx = _slack_ctx()
mirror_inbound(ctx, "ping")
diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
index 2becc017c..3554eed47 100644
--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
@@ -707,6 +707,71 @@ describe('read-only transcript locks the secret-request cards', () => {
});
});
+describe('Agent result metrics tail', () => {
+ const footer = '✅ ⏱️ 5s · 🪙 1.2k tok';
+
+ it('renders structured duration and token usage once, after the timestamp', () => {
+ const markup = render(
+ <MessageRow
+ message={agentWithQuickReplies({ result_footer: footer })}
+ session={session()}
+ messageFontSize={13}
+ />,
+ );
+
+ expect(markup.split(footer)).toHaveLength(2);
+ expect(markup.indexOf('2026-07-27')).toBeLessThan(markup.indexOf(footer));
+ expect(markup).toContain('opacity-100');
+ expect(markup).toContain('flex-wrap');
+ });
+
+ it('moves a legacy folded footer out of the Markdown body', () => {
+ const legacy = {
+ ...agentWithQuickReplies(),
+ text: `Answer body\n\n${footer}`,
+ content: {},
+ } as WorkbenchMessage;
+ const markup = render(
+ <MessageRow message={legacy} session={session()} messageFontSize={13} />,
+ );
+
+ expect(markup).toContain('Answer body');
+ expect(markup.split(footer)).toHaveLength(2);
+ expect(markup.indexOf('2026-07-27')).toBeLessThan(markup.indexOf(footer));
+ });
+
+ it('renders a footer-only completion in metadata without an empty bubble', () => {
+ const footerOnly = {
+ ...agentWithQuickReplies(),
+ text: footer,
+ content: {},
+ } as WorkbenchMessage;
+ const markup = render(
+ <MessageRow message={footerOnly} session={session()} messageFontSize={13} />,
+ );
+
+ expect(markup.split(footer)).toHaveLength(2);
+ expect(markup.indexOf('2026-07-27')).toBeLessThan(markup.indexOf(footer));
+ expect(markup).not.toContain('vr-markdown--inherit-size');
+ });
+
+ it('removes a legacy folded footer from an error status pill', () => {
+ const legacyError = {
+ ...agentWithQuickReplies(),
+ type: 'error',
+ text: `Failed to finish\n\n${footer}`,
+ content: {},
+ } as WorkbenchMessage;
+ const markup = render(
+ <MessageRow message={legacyError} session={session()} messageFontSize={13} />,
+ );
+
+ expect(markup).toContain('Failed to finish');
+ expect(markup.split(footer)).toHaveLength(2);
+ expect(markup.indexOf('2026-07-27')).toBeLessThan(markup.indexOf(footer));
+ });
+});
+
describe('agent-authored local file links', () => {
const linkedMessage = (author: 'agent' | 'user'): WorkbenchMessage => ({
...agentWithQuickReplies(),
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 729e6cf41..db59a122d 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -27,6 +27,7 @@ import { isEditableFile, isEditableMeta, previewOverlayKind } from '../../lib/fi
import { recentPathLabel } from '../../lib/editorRecents';
import type { LocalFileLinkTarget } from '../../lib/localFileLinks';
import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';
+import { resultFooterParts } from '../../lib/resultFooter';
import {
activityItemKind,
activityKindI18nKey,
@@ -3485,6 +3486,7 @@ export const MessageRow = memo(function MessageRow({
// rows link to the source session's chat; task/watch rows to the Harness view.
const triggerLink = isHarness ? chatTriggerLink(message, t('chat.source.agentFallback')) : null;
const messageFontStyle = { fontSize: `${normalizeChatMessageFontSize(messageFontSize)}px` };
+ const resultPresentation = resultFooterParts(message);
// User-uploaded attachments ride in ``content.attachments`` (agent-reply media
// is rewritten inline into the text instead, handled by the Markdown renderer).
@@ -3556,9 +3558,9 @@ export const MessageRow = memo(function MessageRow({
// original line breaks stay visible (a harness prompt often mixes authored
// Markdown with line-oriented waiter output); agent/system replies are
// authored Markdown and must not get stray hard breaks.
- const bodyNode = message.text ? (
+ const bodyNode = resultPresentation.body ? (
<Markdown
- content={message.text}
+ content={resultPresentation.body}
// An annotation the user typed is the user's own words (rule 05), so it
// keeps their line breaks exactly as the ordinary user bubble does.
softBreaks={isUser || isHarness || (row.kind === 'annotation' && row.annotation.direction === 'user')}
@@ -3576,7 +3578,7 @@ export const MessageRow = memo(function MessageRow({
readOnly={readOnly}
className="vr-markdown--inherit-size"
/>
- ) : drawsEmptyBodyPlaceholder(row, messageAttachments.length > 0) ? (
+ ) : !resultPresentation.footer && drawsEmptyBodyPlaceholder(row, messageAttachments.length > 0) ? (
<div className="text-[13px] text-muted">—</div>
) : null;
@@ -3587,8 +3589,16 @@ export const MessageRow = memo(function MessageRow({
// the unnamed ``group-hover`` ChatImage uses for its own overlay button.
// Coarse pointers (touch) have no hover, so keep it always visible there.
const time = (
- <span className="px-1 font-mono text-[10px] text-muted opacity-0 transition-opacity duration-150 group-hover/message:opacity-100 group-focus-within/message:opacity-100 pointer-coarse:opacity-100">
- {formatLocalDateTime(message.created_at)}
+ <span
+ className={clsx(
+ 'inline-flex max-w-full flex-wrap items-center gap-x-1.5 gap-y-0.5 px-1 font-mono text-[10px] text-muted transition-opacity duration-150',
+ resultPresentation.footer
+ ? 'opacity-100'
+ : 'opacity-0 group-hover/message:opacity-100 group-focus-within/message:opacity-100 pointer-coarse:opacity-100',
+ )}
+ >
+ <span className="whitespace-nowrap">{formatLocalDateTime(message.created_at)}</span>
+ {resultPresentation.footer ? <span className="min-w-0 break-words">{resultPresentation.footer}</span> : null}
</span>
);
@@ -3616,7 +3626,9 @@ export const MessageRow = memo(function MessageRow({
<Bell className="mt-px size-3 shrink-0" />
<span className="min-w-0 break-words">
<span className="font-semibold">{t('chat.notifyLabel')}</span>
- {message.text && <span className="font-normal text-gold/80"> · {message.text}</span>}
+ {resultPresentation.body && (
+ <span className="font-normal text-gold/80"> · {resultPresentation.body}</span>
+ )}
</span>
</div>
{time}
@@ -3715,10 +3727,12 @@ export const MessageRow = memo(function MessageRow({
<RoleAvatar tone={isAgent ? 'mint' : 'muted'}>{isAgent ? <Bot /> : <Info />}</RoleAvatar>
{name && <span className="text-[11px] font-medium text-muted">{name}</span>}
</div>
- <div className={isAgent ? AGENT_BUBBLE : SYSTEM_BUBBLE} style={messageFontStyle}>
- {bodyNode}
- {attachmentsNode}
- </div>
+ {bodyNode || attachmentsNode ? (
+ <div className={isAgent ? AGENT_BUBBLE : SYSTEM_BUBBLE} style={messageFontStyle}>
+ {bodyNode}
+ {attachmentsNode}
+ </div>
+ ) : null}
{quickRepliesNode}
{vaultRequestsNode}
{time}
diff --git a/ui/src/lib/resultFooter.test.ts b/ui/src/lib/resultFooter.test.ts
new file mode 100644
index 000000000..d90bf5a4c
--- /dev/null
+++ b/ui/src/lib/resultFooter.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+
+import type { WorkbenchMessage } from '@/context/ApiContext';
+import { resultFooterParts } from './resultFooter';
+
+const message = (
+ text: string,
+ content: Record<string, unknown> = {},
+ over: Partial<WorkbenchMessage> = {},
+) => ({
+ author: 'agent',
+ type: 'result',
+ text,
+ content,
+ ...over,
+}) as WorkbenchMessage;
+
+describe('resultFooterParts', () => {
+ it('uses structured content and removes an older folded copy', () => {
+ const footer = '✅ ⏱️ 5s · 🪙 1.2k tok';
+ expect(resultFooterParts(message(`Answer\n\n${footer}`, { result_footer: footer }))).toEqual({
+ body: 'Answer',
+ footer,
+ });
+ });
+
+ it('keeps a clean new message body beside its structured footer', () => {
+ const footer = '✅ ⏱️ 2m 24s';
+ expect(resultFooterParts(message('Answer', { result_footer: footer }))).toEqual({
+ body: 'Answer',
+ footer,
+ });
+ });
+
+ it('recognizes legacy duration and token footer shapes', () => {
+ for (const footer of [
+ '✅ ⏱️ 0s',
+ '⚠️ ⏱️ 2m 4s · 🪙 240k tok',
+ '❌ 🪙 12.3k tok',
+ '✅ 🪙 1.4M tok',
+ ]) {
+ expect(resultFooterParts(message(`Answer\n\n${footer}`))).toEqual({ body: 'Answer', footer });
+ }
+ });
+
+ it('moves a standalone generated footer out of a footer-only completion body', () => {
+ const footer = '✅ ⏱️ 5s · 🪙 1.2k tok';
+ expect(resultFooterParts(message(footer))).toEqual({ body: '', footer });
+ });
+
+ it('does not move authored text or non-Agent result content', () => {
+ const text = 'Answer\n\n✅ Looks good';
+ expect(resultFooterParts(message(text))).toEqual({ body: text, footer: null });
+ const coinText = 'Answer\n\n✅ 🪙 deployment complete';
+ expect(resultFooterParts(message(coinText))).toEqual({ body: coinText, footer: null });
+ expect(resultFooterParts(message('✅ 🪙 deployment complete'))).toEqual({
+ body: '✅ 🪙 deployment complete',
+ footer: null,
+ });
+ expect(resultFooterParts(message(text, {}, { author: 'user', type: 'user' }))).toEqual({
+ body: text,
+ footer: null,
+ });
+ });
+});
diff --git a/ui/src/lib/resultFooter.ts b/ui/src/lib/resultFooter.ts
new file mode 100644
index 000000000..e3e69c9b0
--- /dev/null
+++ b/ui/src/lib/resultFooter.ts
@@ -0,0 +1,41 @@
+import type { WorkbenchMessage } from '@/context/ApiContext';
+
+const LEGACY_RESULT_FOOTER_RE =
+ /^(?:✅|⚠️|❌) (?:⏱️ (?:\d+m )?\d+s(?: · 🪙 \d+(?:\.\d+)?[kM]? tok)?|🪙 \d+(?:\.\d+)?[kM]? tok)$/u;
+
+export type ResultFooterParts = {
+ body: string;
+ footer: string | null;
+};
+
+/** Separate Avibe's generated duration/token summary from an Agent reply body. */
+export function resultFooterParts(
+ message: Pick<WorkbenchMessage, 'author' | 'type' | 'text' | 'content'>,
+): ResultFooterParts {
+ if (message.author !== 'agent' || (message.type !== 'result' && message.type !== 'error')) {
+ return { body: message.text, footer: null };
+ }
+
+ const structured = (message.content as { result_footer?: unknown } | null)?.result_footer;
+ if (typeof structured === 'string' && structured.trim()) {
+ const footer = structured.trim();
+ const suffix = `\n\n${footer}`;
+ return {
+ body: message.text.endsWith(suffix) ? message.text.slice(0, -suffix.length) : message.text,
+ footer,
+ };
+ }
+
+ if (LEGACY_RESULT_FOOTER_RE.test(message.text)) {
+ return { body: '', footer: message.text };
+ }
+
+ // Rows created before result_footer became structured still contain the exact
+ // generated footer as their final paragraph. Match only that closed format so
+ // authored prose ending in ordinary emoji/text is never moved.
+ const splitAt = message.text.lastIndexOf('\n\n');
+ if (splitAt < 0) return { body: message.text, footer: null };
+ const candidate = message.text.slice(splitAt + 2);
+ if (!LEGACY_RESULT_FOOTER_RE.test(candidate)) return { body: message.text, footer: null };
+ return { body: message.text.slice(0, splitAt), footer: candidate };
+}