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
fix(workbench): a promoted silent-final result stays mid-Turn in Activity and the pet (#2815)
Call White3c660c77f971
diff --git a/core/message_mirror.py b/core/message_mirror.pyindex db91d033d..019529ecf 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -37,7 +37,7 @@ from core.services import sessions as workbench_sessions_servicefrom modules.im.base import MessageContextfrom storage import agent_events_service, messages_service, settings_servicefrom storage.db import get_cached_sqlite_engine-from vibe.message_types import activity_role_for, spec_for+from vibe.message_types import PROMOTED_FROM_KEY, PROMOTED_FROM_TYPES, activity_role_for, spec_forlogger = logging.getLogger(__name__)@@ -757,9 +757,6 @@ def _write_committed_row(return messages_service.get_message(conn, row_id, include_local_error_detail=True)-# Transcript-visible agent text that does not end its Turn: an ``output`` phase-# boundary and an ``interim`` narration bubble.-_TURN_TEXT_TYPES = ("output", "interim")def promote_turn_text_to_result(row_id: str, *, suppress_delivery: bool = False) -> Optional[dict]:@@ -793,25 +790,34 @@ def promote_turn_text_to_result(row_id: str, *, suppress_delivery: bool = False)turn_text = (messages.c.id == row_id,messages.c.author == "agent",- messages.c.type.in_(_TURN_TEXT_TYPES),+ messages.c.type.in_(PROMOTED_FROM_TYPES),)- stored = conn.execute(select(messages.c.content_json).where(*turn_text)).first()+ stored = conn.execute(+ select(messages.c.type, messages.c.content_json, messages.c.metadata_json).where(*turn_text)+ ).first()if stored is None:return None++ def stored_object(raw: Optional[str]) -> dict:+ try:+ value = json.loads(raw or "{}")+ except (TypeError, ValueError):+ return {}+ return value if isinstance(value, dict) else {}+# ``content.kind`` names the type the row was persisted as; it moves- # with the type, as every persist path keeps the two together.- try:- content = json.loads(stored[0] or "{}")- except (TypeError, ValueError):- content = {}- if not isinstance(content, dict):- content = {}+ # with the type, as every persist path keeps the two together. The+ # metadata keeps the type it had, so the Activity timeline still sees+ # the row mid-Turn (``PROMOTED_FROM_KEY``).promoted = conn.execute(update(messages).where(*turn_text).values(type="result",- content_json=json.dumps({**content, "kind": "result"}),+ content_json=json.dumps({**stored_object(stored.content_json), "kind": "result"}),+ metadata_json=json.dumps(+ {**stored_object(stored.metadata_json), PROMOTED_FROM_KEY: stored.type}+ ),updated_at=messages_service.canonical_message_timestamp(_now()),)).rowcountdiff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.pyindex 48531f3d3..7658e5e9d 100644--- a/storage/agent_activity_service.py+++ b/storage/agent_activity_service.py@@ -43,6 +43,8 @@ from core.backend_failure import is_backend_failure_notificationfrom storage import agent_events_service, messages_servicefrom storage.models import message_deliveries, session_turnsfrom vibe.message_types import (+ PROMOTED_FROM_KEY,+ PROMOTED_FROM_TYPES,activity_role_for,is_detached_completion,spec_for,@@ -123,6 +125,23 @@ def _duration_ms(started_iso: Optional[str], ended_iso: Optional[str]) -> Optionreturn int(delta)+def _activity_role(msg_type: Any, metadata: Optional[dict]) -> str:+ """A row's Activity role, where a promoted silent-final result keeps its text's role.++ Only Activity grouping reads the promotion marker: the row stays where its text+ was mid-Turn, so the Turn's groups are the ones that text had. Every other+ reader, fork recovery among them, sees the Turn's terminal output it now is.+ The marker counts only on a ``result`` and only with a type promotion writes,+ because a client may put any metadata on its own message.+ """+ message_type = msg_type if isinstance(msg_type, str) else ""+ values = metadata or {}+ promoted_from = values.get(PROMOTED_FROM_KEY)+ if message_type == "result" and promoted_from in PROMOTED_FROM_TYPES:+ message_type = promoted_from+ return activity_role_for(message_type, values)++def _is_terminal(msg_type: Any, author: Any, metadata: Optional[dict]) -> bool:"""Whether an agent message legally CLOSES a turn.@@ -140,10 +159,7 @@ def _is_terminal(msg_type: Any, author: Any, metadata: Optional[dict]) -> bool:"""if author != "agent":return False- return activity_role_for(- msg_type if isinstance(msg_type, str) else "",- metadata,- ) == "terminal"+ return _activity_role(msg_type, metadata) == "terminal"def _outcome_status(terminal_outcome: Any) -> str:@@ -286,10 +302,7 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, Anmtype = msg.get("type")author = msg.get("author")metadata = msg.get("metadata") or {}- activity_role = activity_role_for(- mtype if isinstance(mtype, str) else "",- metadata,- )+ activity_role = _activity_role(mtype, metadata)accepted_role = accepted_roles.get(str(msg.get("id") or ""))if _is_terminal(mtype, author, metadata):kind = "terminal"diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex 2794f9360..8ba7e9c98 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -406,6 +406,11 @@ scenarios:- tests/test_message_dispatcher_silent_final.py::SilentFinalTurnResultTests::test_a_replayed_output_is_recorded_without_displacing_newer_text- tests/test_message_dispatcher_silent_final.py::SilentFinalTurnResultTests::test_nothing_else_promotes_earlier_text- tests/test_vibey_agent.py::test_a_silent_final_leaves_the_visible_reply_before_it_as_the_result+ - tests/test_agent_activity_service.py::test_a_promoted_silent_final_result_keeps_the_turns_activity+ - tests/test_agent_activity_service.py::test_a_promotion_marker_counts_only_on_a_promoted_result+ supporting_tests:+ - ui/src/pet/petState.test.ts+ - ui/src/pet/PetPage.test.tsx- id: MESSAGE-DELIVERY-326name: A Vibey reply a steer superseded stays a visible reply whatever its length, and a silent final makes it the Turn's resultstatus: covereddiff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.pyindex b045ad533..df6b36543 100644--- a/tests/test_agent_activity_service.py+++ b/tests/test_agent_activity_service.py@@ -2004,3 +2004,117 @@ def test_stop_without_terminal_stays_interrupted(isolated_state):assert [g["status"] for g in groups] == ["interrupted"]assert groups[0]["anchor_message_id"] == "m_u1" # anchored to its own triggerassert groups[0]["anchor_position"] == "after"++[email protected]("shown_type", ["interim", "output"])+def test_a_promoted_silent_final_result_keeps_the_turns_activity(isolated_state, monkeypatch, shown_type):+ """Scenario: MESSAGE-DELIVERY-325.++ A Turn's text promoted to its result when the Turn ended on a silent reply+ renders as the result, but stays where it was mid-Turn: the Activity groups+ around it are exactly the ones its text had before promotion.+ """+ from types import SimpleNamespace++ from core import web_push_notifications+ from core.message_mirror import promote_turn_text_to_result+ from vibe.message_types import activity_role_for++ monkeypatch.setattr(+ web_push_notifications,+ "threading",+ SimpleNamespace(Thread=lambda **_kwargs: SimpleNamespace(start=lambda: None)),+ )+ engine = create_sqlite_engine()+ sid, turn_id = "ses_promoted", "trn_promoted"+ with engine.begin() as conn:+ scope = _seed_session(conn, session_id=sid)+ delivery = message_deliveries.insert_delivery(+ conn,+ delivery_id="m_p1",+ session_id=sid,+ priority="p3",+ state="reserved",+ snapshot=message_deliveries.message_snapshot(+ scope_id=scope,+ session_id=sid,+ platform="avibe",+ author="harness",+ source="harness",+ message_type="harness",+ text="watch fired",+ ),+ dispatch_text="watch fired",+ now="2026-06-01T10:00:00.000000+00:00",+ )+ message_deliveries.insert_turn(+ conn,+ turn_id=turn_id,+ session_id=sid,+ initial_delivery_id=delivery["id"],+ state="starting",+ backend="claude",+ start_attempt_id="atm_promoted",+ dispatch_text="watch fired",+ now="2026-06-01T10:00:00.000000+00:00",+ )+ assert message_deliveries.open_start_attempt(+ conn,+ delivery["id"],+ expected_version=int(delivery["version"]),+ turn_id=turn_id,+ attempt_id="atm_promoted",+ ) is not None+ assert _accept_start(conn, turn_id)+ _evt(conn, scope, sid, eid="e_p1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash` `{\"command\":\"a\"}`")+ _msg(+ conn, scope, sid, mid="m_text", mtype=shown_type, author="agent",+ created_at="2026-06-01T10:00:02Z", text="The report.", metadata={"turn_id": turn_id},+ )+ _evt(conn, scope, sid, eid="e_p2", created_at="2026-06-01T10:00:03Z", text="🔧 `Read` `{\"file_path\":\"b\"}`")+ message_deliveries.terminalize_turn(+ conn,+ turn_id,+ outcome="completed",+ settled_by="terminal_result",+ evidence_kind="test_silent_final",+ )++ with engine.connect() as conn:+ before = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]++ promoted = promote_turn_text_to_result("m_text")++ assert promoted is not None and promoted["type"] == "result"+ with engine.connect() as conn:+ after = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]+ assert after == before+ # Everywhere else, fork recovery among them, the row is the Turn's terminal output.+ assert activity_role_for(promoted["type"], promoted["metadata"]) == "terminal"+++def test_a_promotion_marker_counts_only_on_a_promoted_result(isolated_state):+ """Scenario: MESSAGE-DELIVERY-325.++ A client can put any metadata on its own message: a forged marker on a user row+ neither hides that Turn's start nor merges the previous Turn's activity into it.+ """+ engine = create_sqlite_engine()+ sid = "ses_forged"+ with engine.begin() as conn:+ scope = _seed_session(conn, session_id=sid)+ _msg(conn, scope, sid, mid="m_q1", mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q1", source="user")+ _evt(conn, scope, sid, eid="e_f1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash` `{\"command\":\"a\"}`")+ _msg(+ conn, scope, sid, mid="m_q2", mtype="user", author="user", created_at="2026-06-01T10:01:00Z",+ text="q2", source="user", metadata={"promoted_from": "result"},+ )+ _evt(conn, scope, sid, eid="e_f2", created_at="2026-06-01T10:01:01Z", text="🔧 `Read` `{\"file_path\":\"b\"}`")+ _msg(conn, scope, sid, mid="m_r2", mtype="result", author="agent", created_at="2026-06-01T10:01:02Z", text="answer")++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]+ assert [(g["status"], g["anchor_message_id"], g["steps"]) for g in groups] == [+ ("interrupted", "m_q1", 1),+ ("done", "m_r2", 1),+ ]diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsxindex 923c9f769..1105da2e1 100644--- a/ui/src/pet/PetPage.test.tsx+++ b/ui/src/pet/PetPage.test.tsx@@ -2131,6 +2131,20 @@ describe('Personal Agent review: history and lifecycle', () => {} finally { vi.useRealTimers(); }});+ it('draws a promoted result after the input it answered and before a later input answered by silence', async () => {+ // Scenario: MESSAGE-DELIVERY-325.+ tails.S = [+ message('ask', 'S', { author: 'user', type: 'user', text: 'Check CI' }),+ message('report', 'S', { text: 'CI is green', read_at: null, metadata: { promoted_from: 'output' } }),+ message('steer', 'S', { author: 'user', type: 'user', text: 'Also the docs' }),+ ];+ render(<PetPage />); await showDetail();+ const text = document.querySelector('.pet-mini-detail')?.textContent ?? '';+ expect(text.indexOf('Check CI')).toBeGreaterThanOrEqual(0);+ expect(text.indexOf('Check CI')).toBeLessThan(text.indexOf('CI is green'));+ expect(text.indexOf('CI is green')).toBeLessThan(text.indexOf('Also the docs'));+ });+it('renders reference sidecars in current and historical Markdown', async () => {const reference = (id: string, title: string) => ({ references: [{ kind: 'session', session_id: id, title }] });tails.S = [diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsxindex 5eafa57c5..e98c47c95 100644--- a/ui/src/pet/PetPage.tsx+++ b/ui/src/pet/PetPage.tsx@@ -1143,9 +1143,10 @@ const MainDetail: React.FC<MainDetailProps> = (props) => {// Open at the end, where the newest result sits right above its actions and// the toggle row. If the result and its actions do not fit, start at the// result instead, just past the top edge fade, so it is read from its first- // line rather than from under the fade.+ // line rather than from under the fade. A later input drawn after a promoted+ // result (`answersEarlierInput`) moves the end, so a new input re-scrolls.if (result && history) history.scrollTop = Math.max(0, Math.min(history.scrollHeight - history.clientHeight, result.offsetTop - FADE_PX));- }, [props.visible, resultKey]);+ }, [props.visible, resultKey, props.exchange.user?.id]);useEffect(() => {const node = lastResultRef.current;if (!props.visible || !node) return;@@ -1162,11 +1163,13 @@ const MainDetail: React.FC<MainDetailProps> = (props) => {const firstCurrent = props.messages.findIndex((message) => message.id === props.exchange.user?.id || props.exchange.results.some((result) => result.id === message.id));const history = props.messages.slice(0, Math.max(0, firstCurrent)).filter((message) => message.type === 'user' || message.type === 'result').slice(-6);+ const currentUser = props.exchange.user && <div className="pet-mini-detail-user"><Markdown content={props.exchange.user.text} references={(props.exchange.user.content as { references?: MentionReference[] })?.references} softBreaks /></div>;return (<div className="pet-mini-detail-inner">{history.map((message) => <div key={message.id} className={message.author === 'user' ? 'pet-mini-detail-user' : 'pet-mini-detail-result'}><Markdown content={message.text} references={(message.content as { references?: MentionReference[] })?.references} softBreaks /></div>)}- {props.exchange.user && <div className="pet-mini-detail-user"><Markdown content={props.exchange.user.text} references={(props.exchange.user.content as { references?: MentionReference[] })?.references} softBreaks /></div>}+ {!props.exchange.answersEarlierInput && currentUser}{props.exchange.results.map((message, index) => <div ref={index === props.exchange.results.length - 1 ? lastResultRef : undefined} key={message.id} className="pet-mini-detail-result"><Markdown content={message.text} references={(message.content as { references?: MentionReference[] })?.references} softBreaks /></div>)}+ {props.exchange.answersEarlierInput && currentUser}{props.failure && (<div className="pet-mini-detail-notice" role="status"><p>{props.failure.text}</p>diff --git a/ui/src/pet/petState.test.ts b/ui/src/pet/petState.test.tsindex fb86902cc..b5b437c82 100644--- a/ui/src/pet/petState.test.ts+++ b/ui/src/pet/petState.test.ts@@ -138,6 +138,24 @@ describe('latestExchange', () => {const exchange = latestExchange([user(), row({ type: 'tool_call' }), result({ text: 'done' })], false);expect(exchange.results.map((message) => message.text)).toEqual(['done']);});++ it('pairs a promoted result with the input before it, not a later input answered by silence', () => {+ // Scenario: MESSAGE-DELIVERY-325. The earlier text was promoted where it stood.+ const report = result({ read_at: null, text: 'report', metadata: { promoted_from: 'output' } });+ const exchange = latestExchange([user('check CI'), report, user('also the docs')], false);+ expect(exchange.user?.text).toBe('also the docs');+ expect(exchange.results).toEqual([report]);+ expect(exchange.answersEarlierInput).toBe(true);+ });++ it.each([+ ['a promoted result after the latest input answers that input', { promoted_from: 'interim' }, 'after'],+ ['an unpromoted result before the latest input keeps today\'s order', {}, 'before'],+ ] as const)('%s', (_name, metadata, position) => {+ const reply = result({ read_at: null, text: 'reply', metadata });+ const rows = position === 'after' ? [user('old'), user('ask'), reply] : [user('old'), reply, user('ask')];+ expect(latestExchange(rows, false).answersEarlierInput).toBe(false);+ });});const agent = (overrides: Partial<RunningAgent>): RunningAgent => ({diff --git a/ui/src/pet/petState.ts b/ui/src/pet/petState.tsindex e7586754c..bcf01a39a 100644--- a/ui/src/pet/petState.ts+++ b/ui/src/pet/petState.ts@@ -150,6 +150,11 @@ export const latestExchange = (/** False when unread results may reach past the loaded tail, so the pet* must not mark read and sends the user to the Workbench instead. */unreadComplete: boolean;+ /** True when the results answer an input before `user`: the latest input was+ * answered by silence, so its Turn's earlier text became the result where it+ * stood (`metadata.promoted_from`). The panel draws them before `user`,+ * right after the input they answer. */+ answersEarlierInput: boolean;} => {const transcript = messages.filter((message) => isTranscriptMessage(message));let user: WorkbenchMessage | null = null;@@ -161,15 +166,29 @@ export const latestExchange = (}const results = transcript.filter(isAgentResult);const unread = results.filter((message) => message.read_at === null);+ // Only a promoted result: any other result before the latest input keeps+ // being shown after it, as before.+ const answersEarlierInput = (shown: WorkbenchMessage[]) => {+ const last = shown[shown.length - 1];+ return Boolean(+ user && last && last.metadata?.promoted_from && transcript.indexOf(last) < transcript.indexOf(user),+ );+ };if (unread.length === 0) {const last = results[results.length - 1];+ const shown = last ? [last] : [];// Inbox says something is unread, but the tail has no unread result: those// replies sit past the loaded window. A fully-loaded session treats a// leftover count as stale.- return { user, results: last ? [last] : [], unreadComplete: unreadCount <= 0 || !hasOlder };+ return {+ user,+ results: shown,+ unreadComplete: unreadCount <= 0 || !hasOlder,+ answersEarlierInput: answersEarlierInput(shown),+ };}// Unread rows reach past the tail when the oldest loaded result is itself// unread, or when the inbox count is ahead of the unread results we have.const unreadComplete = !hasOlder || (results[0].read_at !== null && unread.length >= unreadCount);- return { user, results: unread, unreadComplete };+ return { user, results: unread, unreadComplete, answersEarlierInput: answersEarlierInput(unread) };};diff --git a/vibe/message_types.py b/vibe/message_types.pyindex ea3dfed85..90de78aa3 100644--- a/vibe/message_types.py+++ b/vibe/message_types.py@@ -150,6 +150,15 @@ def is_detached_completion(message_type: str, metadata: Any = None) -> bool:TRANSCRIPT_COPY_KEY = "transcript_copy"+# Metadata on a ``result`` promoted from Turn text when its Turn ended on a silent+# reply (``core.message_mirror.promote_turn_text_to_result``): the type it was+# persisted as, one of ``PROMOTED_FROM_TYPES``. The row is that Turn's terminal+# output everywhere; only Activity grouping keeps it where its text was mid-Turn.+PROMOTED_FROM_KEY = "promoted_from"+# Transcript-visible agent text that does not end its Turn, and so can be promoted.+PROMOTED_FROM_TYPES = ("output", "interim")++def activity_role_for(message_type: str, metadata: Any = None) -> str:"""Resolve one row's role in the current Turn's Activity timeline."""