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
Coalesce queued harness callbacks (#636)
Call Whitedd2edaea90c8
diff --git a/core/internal_server.py b/core/internal_server.pyindex 42615810b..4578ce46d 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -38,6 +38,7 @@ from typing import Any, Optional, TYPE_CHECKINGfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import JSONResponse, StreamingResponse+from sqlalchemy.exc import IntegrityErrorfrom config import pathsfrom core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn@@ -125,6 +126,24 @@ def create_app(controller: "Controller") -> FastAPI:if not session_id:return await manager.submit(None, context, text, source=SOURCE_SCHEDULED)+ native_message_id = str(getattr(context, "message_id", None) or "").strip()+ if native_message_id:+ active = manager.in_flight.get(session_id)+ active_message_id = str(getattr(getattr(active, "context", None), "message_id", None) or "").strip()+ if active_message_id == native_message_id:+ return "duplicate"+ from storage import messages_service+ from storage.db import create_sqlite_engine++ engine = create_sqlite_engine()+ with engine.connect() as conn:+ if messages_service.native_message_exists(+ conn,+ platform="avibe",+ native_message_id=native_message_id,+ ):+ return "duplicate"+def _enqueue() -> None:from core.message_mirror import _scope_id_for_sessionfrom core.session_turns import SCHEDULED_PROVENANCE_KEY, capture_scheduled_provenance@@ -140,17 +159,21 @@ def create_app(controller: "Controller") -> FastAPI:with engine.begin() as conn:scope_id = _scope_id_for_session(conn, session_id)if scope_id is not None:- messages_service.append(- conn,- scope_id=scope_id,- session_id=session_id,- platform="avibe",- author="harness",- source="harness",- message_type=messages_service.QUEUED_TYPE,- text=text,- metadata={SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)},- )+ try:+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.QUEUED_TYPE,+ text=text,+ metadata={SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)},+ native_message_id=native_message_id or None,+ )+ except IntegrityError:+ logger.info("scheduled turn duplicate native id already queued: %s", native_message_id)return await manager.submit(session_id, context, text, source=SOURCE_SCHEDULED, enqueue=_enqueue)diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex a685c1763..1490f2fc7 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -10,7 +10,7 @@ import loggingimport asynciofrom datetime import datetime, timezonefrom pathlib import Path-from typing import Optional+from typing import Any, Optionalfrom urllib.parse import urljoinfrom config.platform_registry import get_platform_descriptor@@ -24,6 +24,21 @@ from vibe.i18n import t as i18n_tlogger = logging.getLogger(__name__)+def _coalesced_task_execution_ids(payload: dict[str, Any]) -> list[str]:+ run_ids: list[str] = []+ primary = str(payload.get("task_execution_id") or "").strip()+ if primary:+ run_ids.append(primary)+ coalesced = payload.get("coalesced_queue")+ execution_ids = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None+ if isinstance(execution_ids, list):+ for value in execution_ids:+ run_id = str(value or "").strip()+ if run_id and run_id not in run_ids:+ run_ids.append(run_id)+ return run_ids++async def _stream_chunk(controller, context, *, text: str, message_id: Optional[str], kind: str) -> None:"""Forward one durable agent message to the live streaming turn sink.@@ -216,20 +231,21 @@ class ConsolidatedMessageDispatcher:terminal_status: Optional[str] = None,) -> None:payload = context.platform_specific or {}- run_id = str(payload.get("task_execution_id") or "").strip()- if not run_id:+ run_ids = _coalesced_task_execution_ids(payload)+ if not run_ids:returnstore = Nonetry:store = SQLiteBackgroundTaskStore()- store.record_run_message(- run_id,- text=text,- message_id=message_id,- terminal_status=terminal_status,- )+ for run_id in run_ids:+ store.record_run_message(+ run_id,+ text=text,+ message_id=message_id,+ terminal_status=terminal_status,+ )except Exception as err:- logger.warning("Failed to record suppressed run output for %s: %s", run_id, err)+ logger.warning("Failed to record suppressed run output for %s: %s", ",".join(run_ids), err)finally:if store is not None:store.close()diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 6b0fb99d6..651c9dfe3 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -1653,6 +1653,8 @@ class ScheduledTaskService:state = await gate.submit_scheduled(session_id, context, message)if state == "enqueued":return AgentRunExecutionResult(error=None, complete_on_return=False, requeue_on_return=True)+ if state == "duplicate":+ return AgentRunExecutionResult(error=None, complete_on_return=True)return AgentRunExecutionResult(error=None, complete_on_return=False)async def _noop_chunk(_envelope: dict) -> None:diff --git a/core/session_turns.py b/core/session_turns.pyindex 75b14d43a..fd4e20670 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -19,10 +19,17 @@ from __future__ import annotationsimport asyncioimport loggingfrom dataclasses import dataclass+from datetime import datetime, timezonefrom typing import TYPE_CHECKING, Any, Callable, Optional+from sqlalchemy import select+from sqlalchemy.exc import IntegrityError+from core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USER_KEYS_METADATAfrom core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn+from storage import messages_service+from storage.models import messages+from vibe.i18n import t as i18n_tif TYPE_CHECKING:from modules.im import MessageContext@@ -36,6 +43,9 @@ logger = logging.getLogger(__name__)# a plain human turn (#84). Its PRESENCE also marks the row as a scheduled segment# (vs a user send) for flush_queue.SCHEDULED_PROVENANCE_KEY = "scheduled_provenance"+SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS = 60+SCHEDULED_QUEUE_BURST_HINT_THRESHOLD = 3+SCHEDULED_QUEUE_FULL_DETAIL_LIMIT = 3# The platform_specific keys the FLUSH rebuilds fresh from the session row (avibe# routing). Everything ELSE the scheduled context carries is delivery / attribution@@ -46,6 +56,7 @@ SCHEDULED_PROVENANCE_KEY = "scheduled_provenance"_FLUSH_REBUILT_KEYS = frozenset({"platform", "is_dm", "workbench_session_id", "agent_session_id", "agent_session_target", "turn_token"})+SCHEDULED_TARGET_AGENT_KEY = "scheduled_target_agent_name"def capture_scheduled_provenance(context: "MessageContext") -> dict:@@ -62,9 +73,15 @@ def capture_scheduled_provenance(context: "MessageContext") -> dict:``delivery_override`` can't be silently missed (Codex P1 #3338692433)."""spec = getattr(context, "platform_specific", None) or {}+ captured_spec = {k: v for k, v in spec.items() if k not in _FLUSH_REBUILT_KEYS}+ target = spec.get("agent_session_target")+ if isinstance(target, dict):+ target_agent = str(target.get("agent_name") or "").strip()+ if target_agent:+ captured_spec.setdefault(SCHEDULED_TARGET_AGENT_KEY, target_agent)return {"message_id": getattr(context, "message_id", None),- "platform_specific": {k: v for k, v in spec.items() if k not in _FLUSH_REBUILT_KEYS},+ "platform_specific": captured_spec,}@@ -91,6 +108,216 @@ def emit_matches_active_turn(sink: dict, context: "MessageContext") -> bool:return not (sink_token is not None and ctx_token != sink_token)+def _parse_queue_timestamp(value: Any) -> Optional[datetime]:+ if not value:+ return None+ try:+ text = str(value)+ if text.endswith("Z"):+ text = f"{text[:-1]}+00:00"+ parsed = datetime.fromisoformat(text)+ except (TypeError, ValueError):+ return None+ if parsed.tzinfo is None:+ return parsed.replace(tzinfo=timezone.utc)+ return parsed.astimezone(timezone.utc)+++def _scheduled_provenance(row: dict) -> Optional[dict]:+ metadata = row.get("metadata") or {}+ provenance = metadata.get(SCHEDULED_PROVENANCE_KEY)+ return provenance if isinstance(provenance, dict) else None+++def _scheduled_merge_key(row: dict) -> Optional[tuple[str, ...]]:+ provenance = _scheduled_provenance(row)+ if provenance is None:+ return None+ spec = provenance.get("platform_specific") or {}+ if not isinstance(spec, dict):+ return None+ trigger_kind = str(spec.get("task_trigger_kind") or "").strip()+ definition_id = str(spec.get("task_definition_id") or "").strip()+ if not trigger_kind or not definition_id:+ return None+ delivery_override = spec.get("delivery_override") if isinstance(spec.get("delivery_override"), dict) else {}+ delivery_alias = spec.get("scheduled_delivery_alias") if isinstance(spec.get("scheduled_delivery_alias"), dict) else {}+ return (+ trigger_kind,+ definition_id,+ str(spec.get("vibe_agent_name") or ""),+ str(spec.get(SCHEDULED_TARGET_AGENT_KEY) or ""),+ str(spec.get("delivery_key_external") or ""),+ str(spec.get("delivery_scope_session_key") or ""),+ str(delivery_override.get("platform") or ""),+ str(delivery_override.get("user_id") or ""),+ str(delivery_override.get("channel_id") or ""),+ str(delivery_override.get("thread_id") or ""),+ str(delivery_alias.get("mode") or ""),+ str(delivery_alias.get("clear_source") or ""),+ str(bool(spec.get("suppress_delivery"))),+ )+++def _within_scheduled_merge_window(previous: dict, current: dict) -> bool:+ prev_ts = _parse_queue_timestamp(previous.get("created_at"))+ current_ts = _parse_queue_timestamp(current.get("created_at"))+ if prev_ts is None or current_ts is None:+ return False+ delta = (current_ts - prev_ts).total_seconds()+ return 0 <= delta <= SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS+++def _collect_scheduled_segment(rows: list[dict]) -> list[dict]:+ if not rows:+ return []+ first_key = _scheduled_merge_key(rows[0])+ if first_key is None:+ return [rows[0]]+ segment = [rows[0]]+ latest = rows[0]+ for row in rows[1:]:+ if _scheduled_merge_key(row) != first_key:+ break+ if not _within_scheduled_merge_window(latest, row):+ break+ segment.append(row)+ latest = row+ return segment+++def _build_scheduled_segment_text(segment: list[dict]) -> str:+ texts = [str(row.get("text") or "") for row in segment if str(row.get("text") or "")]+ if not texts:+ return ""+ if len(texts) == 1:+ return texts[0]++ lang = _scheduled_segment_language(segment)+ parts = [+ texts[0],+ "\n\n"+ + i18n_t(+ "harness.queueCoalesced.summary",+ lang,+ count=len(texts),+ window=SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS,+ ),+ ]+ if len(texts) <= SCHEDULED_QUEUE_FULL_DETAIL_LIMIT:+ parts.append(+ "\n\n"+ + i18n_t("harness.queueCoalesced.messagesLabel", lang)+ + "\n"+ + "\n\n---\n\n".join(texts[1:])+ )+ else:+ parts.append(+ "\n\n"+ + i18n_t("harness.queueCoalesced.latestLabel", lang, additional=len(texts) - 1)+ + f"\n{texts[-1]}"+ )+ if len(texts) >= SCHEDULED_QUEUE_BURST_HINT_THRESHOLD:+ parts.append("\n\n" + i18n_t("harness.queueCoalesced.burstHint", lang))+ return "".join(parts)+++def _scheduled_segment_language(segment: list[dict]) -> str:+ for row in segment:+ spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}+ if not isinstance(spec, dict):+ continue+ lang = str(spec.get("language") or spec.get("lang") or "").strip()+ if lang:+ return lang+ return "en"+++def _scheduled_segment_native_ids(segment: list[dict]) -> list[str]:+ native_ids: list[str] = []+ for row in segment:+ native_id = str(row.get("native_message_id") or "").strip()+ if not native_id:+ native_id = str((_scheduled_provenance(row) or {}).get("message_id") or "").strip()+ if native_id and native_id not in native_ids:+ native_ids.append(native_id)+ return native_ids+++def _scheduled_segment_suppresses_delivery(segment: list[dict]) -> bool:+ for row in segment:+ spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}+ if isinstance(spec, dict) and bool(spec.get("suppress_delivery")):+ return True+ return False+++def _write_coalesced_native_id_markers(conn: Any, segment: list[dict]) -> None:+ """Keep native-id dedupe coverage for coalesced queued harness rows.++ The first native id is restored on the dispatched context and mirrored as+ the visible harness prompt. Later coalesced queued rows are deleted before+ dispatch, so write hidden rows for their native ids; otherwise a waiter retry+ for one of those callbacks would not hit ``uq_messages_platform_native``.+ """+ native_ids = _scheduled_segment_native_ids(segment)+ if not native_ids:+ return+ first = segment[0]+ suppresses_delivery = _scheduled_segment_suppresses_delivery(segment)+ marker_ids = native_ids if suppresses_delivery else native_ids[1:]+ if not marker_ids:+ return++ for native_id in marker_ids:+ try:+ messages_service.append(+ conn,+ scope_id=first["scope_id"],+ session_id=first.get("session_id"),+ platform=first.get("platform") or "avibe",+ author="harness",+ source="harness",+ message_type=messages_service.HARNESS_DEDUPE_TYPE,+ text="",+ metadata={"coalesced_from": first.get("id"), "suppressed_delivery": suppresses_delivery},+ native_message_id=native_id,+ )+ except IntegrityError:+ logger.debug("queue flush: coalesced native id marker already exists for %s", native_id, exc_info=True)+++def _scheduled_claimed_queue_row_ids(conn: Any, segment: list[dict]) -> set[str]:+ native_ids = _scheduled_segment_native_ids(segment)+ if not native_ids:+ return set()+ native_by_row_id = {+ str(row.get("id") or ""): str(row.get("native_message_id") or (_scheduled_provenance(row) or {}).get("message_id") or "").strip()+ for row in segment+ if row.get("id")+ }+ native_to_row_ids: dict[str, set[str]] = {}+ for row_id, native_id in native_by_row_id.items():+ if native_id:+ native_to_row_ids.setdefault(native_id, set()).add(row_id)+ platform = str(segment[0].get("platform") or "avibe")+ rows = (+ conn.execute(+ select(messages.c.id, messages.c.native_message_id)+ .where(messages.c.platform == platform)+ .where(messages.c.native_message_id.in_(native_ids))+ )+ .all()+ )+ claimed_row_ids: set[str] = set()+ segment_row_ids = set(native_by_row_id)+ for row_id, native_id in rows:+ if str(row_id) in segment_row_ids:+ continue+ claimed_row_ids.update(native_to_row_ids.get(str(native_id or ""), set()))+ return claimed_row_ids++@dataclassclass Turn:"""The one active turn for an avibe session — the EXECUTION half of the FSM@@ -352,6 +579,8 @@ class SessionTurnManager:scheduled_text = ""scheduled_prov: dict = {}scheduled_message_id = None+ scheduled_native_ids: list[str] = []+ dropped_duplicate_segment = Falseuser_row = Noneinbox_row = Noneattachment_specs: list = []@@ -361,23 +590,54 @@ class SessionTurnManager:rows = messages_service.list_queued(conn, session_id)if not rows:return False- if (rows[0].get("metadata") or {}).get(SCHEDULED_PROVENANCE_KEY) is not None:- # Scheduled segment: exactly this one row, run on its own.+ if _scheduled_provenance(rows[0]) is not None:+ # Scheduled segment: a leading run of same-definition harness+ # rows within the rolling merge window runs as one scheduled+ # turn. Rows remain visible individually while queued; only the+ # Agent-facing dispatch is coalesced.is_scheduled = True- segment = [rows[0]]- scheduled_text = rows[0].get("text") or ""- prov = rows[0]["metadata"][SCHEDULED_PROVENANCE_KEY] or {}- scheduled_message_id = prov.get("message_id")- scheduled_prov = prov.get("platform_specific") or {}+ initial_segment = _collect_scheduled_segment(rows)+ claimed_row_ids = _scheduled_claimed_queue_row_ids(conn, initial_segment)+ if claimed_row_ids:+ messages_service.delete_queued(conn, list(claimed_row_ids))+ bus.publish("queue.updated", {"session_id": session_id})+ segment = [r for r in initial_segment if str(r.get("id") or "") not in claimed_row_ids]+ if not segment:+ dropped_duplicate_segment = True+ else:+ segment = initial_segment+ if dropped_duplicate_segment:+ pass+ else:+ scheduled_text = _build_scheduled_segment_text(segment)+ scheduled_native_ids = _scheduled_segment_native_ids(segment)+ prov = _scheduled_provenance(segment[0]) or {}+ scheduled_message_id = scheduled_native_ids[0] if scheduled_native_ids else None+ scheduled_prov = prov.get("platform_specific") or {}+ if len(segment) > 1:+ scheduled_prov = dict(scheduled_prov)+ scheduled_prov["coalesced_queue"] = {+ "count": len(segment),+ "window_seconds": SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS,+ "message_ids": [r.get("id") for r in segment if r.get("id")],+ "native_message_ids": scheduled_native_ids,+ "execution_ids": [+ spec.get("task_execution_id")+ for r in segment+ if isinstance((spec := (_scheduled_provenance(r) or {}).get("platform_specific") or {}), dict)+ and spec.get("task_execution_id")+ ],+ }else:# User segment: the leading run of consecutive non-scheduled rows# (stop at the first scheduled row so it stays its own turn).segment = []for r in rows:- if (r.get("metadata") or {}).get(SCHEDULED_PROVENANCE_KEY) is not None:+ if _scheduled_provenance(r) is not None:breaksegment.append(r)- messages_service.delete_queued(conn, [r["id"] for r in segment])+ if segment:+ messages_service.delete_queued(conn, [r["id"] for r in segment])if not is_scheduled:texts = [r.get("text") for r in segment if (r.get("text") or "").strip()]# Carry attachments queued in this user segment so a file@@ -426,6 +686,9 @@ class SessionTurnManager:logger.exception("queue flush: failed to claim/merge for session=%s", session_id)return False+ if dropped_duplicate_segment:+ return await self.flush_queue(session_id)+# Surface the flushed (merged) user message + bump the inbox card so other# workbench views re-rank / flip 'replied' without waiting for the result# (Codex P2). A scheduled segment has NO user row — its prompt is mirrored by@@ -457,6 +720,10 @@ class SessionTurnManager:# (fresh-routing) context, then run as SOURCE_SCHEDULED — not a plain user# turn — so suppress_delivery / the delivery target / the task attribution# carry through the queue (#84).+ #+ # The coalesced native-id set is split deliberately: the first id is+ # assigned to this visible harness prompt, while later ids have already+ # been preserved as hidden dedupe marker rows during the queue claim.if context.platform_specific is None:context.platform_specific = {}context.platform_specific.update(scheduled_prov)@@ -481,6 +748,13 @@ class SessionTurnManager:logger.info("queue flush: skipped agent_run %s because it is no longer queued", run_id)return Falseawait self._run(session_id, context, scheduled_text, source=SOURCE_SCHEDULED)+ try:+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ _write_coalesced_native_id_markers(conn, segment)+ except Exception:+ logger.exception("queue flush: failed to preserve coalesced native ids for session=%s", session_id)+ return Falsereturn Truedef turn_state(self, session_id: str) -> dict:diff --git a/storage/alembic/versions/20260622_0023_harness_dedupe_inbox_indexes.py b/storage/alembic/versions/20260622_0023_harness_dedupe_inbox_indexes.pynew file mode 100644index 000000000..5e09e89e0--- /dev/null+++ b/storage/alembic/versions/20260622_0023_harness_dedupe_inbox_indexes.py@@ -0,0 +1,47 @@+"""exclude harness dedupe rows from inbox partial indexes++Revision ID: 20260622_0023+Revises: 20260610_0022+Create Date: 2026-06-22+"""++from __future__ import annotations++from alembic import op++revision = "20260622_0023"+down_revision = "20260610_0022"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ bind = op.get_bind()+ bind.exec_driver_sql("drop index if exists ix_messages_inbox_activity")+ bind.exec_driver_sql(+ "create index ix_messages_inbox_activity "+ "on messages (platform, session_id, created_at desc, id desc) "+ "where session_id is not null and type not in ('queued', 'draft', 'pending', 'harness_dedupe')"+ )+ bind.exec_driver_sql("drop index if exists ix_messages_inbox_user_send")+ bind.exec_driver_sql(+ "create index ix_messages_inbox_user_send "+ "on messages (platform, session_id, created_at desc, id desc) "+ "where session_id is not null and author = 'user' and type not in ('queued', 'draft', 'pending', 'harness_dedupe')"+ )+++def downgrade() -> None:+ bind = op.get_bind()+ bind.exec_driver_sql("drop index if exists ix_messages_inbox_user_send")+ bind.exec_driver_sql(+ "create index ix_messages_inbox_user_send "+ "on messages (platform, session_id, created_at desc, id desc) "+ "where session_id is not null and author = 'user' and type not in ('queued', 'draft', 'pending')"+ )+ bind.exec_driver_sql("drop index if exists ix_messages_inbox_activity")+ bind.exec_driver_sql(+ "create index ix_messages_inbox_activity "+ "on messages (platform, session_id, created_at desc, id desc) "+ "where session_id is not null and type not in ('queued', 'draft', 'pending')"+ )diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 8036571f3..f815ed11b 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -294,6 +294,21 @@ def append(return _row_to_payload(payload)+def native_message_exists(conn: Connection, *, platform: str, native_message_id: str) -> bool:+ """True when a platform/native message id has already been recorded."""+ platform = str(platform or "").strip()+ native_message_id = str(native_message_id or "").strip()+ if not platform or not native_message_id:+ return False+ row_id = conn.execute(+ select(messages.c.id)+ .where(messages.c.platform == platform)+ .where(messages.c.native_message_id == native_message_id)+ .limit(1)+ ).scalar_one_or_none()+ return row_id is not None++def get_quick_reply_chosen(conn: Connection, session_id: str, message_id: str) -> Optional[str]:"""The label already chosen for *message_id*'s quick-reply group, or None.@@ -553,8 +568,11 @@ DRAFT_TYPE = "draft"# This stops another tab from briefly seeing the row as a sent prompt during the# dispatch window (Codex P2).PENDING_TYPE = "pending"+# Hidden row used only to keep native-message-id dedupe coverage after multiple+# queued harness callbacks are coalesced into one dispatched turn.+HARNESS_DEDUPE_TYPE = "harness_dedupe"# Ephemeral types that must never count as inbox activity / conversation.-NON_CONVERSATION_TYPES = (QUEUED_TYPE, DRAFT_TYPE, PENDING_TYPE)+NON_CONVERSATION_TYPES = (QUEUED_TYPE, DRAFT_TYPE, PENDING_TYPE, HARNESS_DEDUPE_TYPE)# The transcript-visible types — the SINGLE source of truth shared by the# history fetch (``list_session_messages``) AND the live ``message.new`` publishdiff --git a/storage/migrations.py b/storage/migrations.pyindex 1f0beda97..8ac2de774 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -12,7 +12,7 @@ from config import pathsfrom storage.db import create_sqlite_engine, sqlite_urlINITIAL_REVISION = "20260501_0001"-LATEST_SCHEMA_REVISION = "20260610_0022"+LATEST_SCHEMA_REVISION = "20260622_0023"REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"INITIAL_TABLES = {"state_meta",@@ -508,20 +508,22 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -'create index if not exists ix_messages_mark_read ''on messages (session_id, author, read_at, created_at, id)')+ conn.execute("drop index if exists ix_messages_inbox_activity")conn.execute(- "create index if not exists ix_messages_inbox_activity "+ "create index ix_messages_inbox_activity ""on messages (platform, session_id, created_at desc, id desc) "- "where session_id is not null and type not in ('queued', 'draft', 'pending')"+ "where session_id is not null and type not in ('queued', 'draft', 'pending', 'harness_dedupe')")conn.execute("create index if not exists ix_messages_inbox_agent_reply ""on messages (platform, session_id, created_at desc, id desc) ""where session_id is not null and type in ('result', 'notify', 'error')")+ conn.execute("drop index if exists ix_messages_inbox_user_send")conn.execute(- "create index if not exists ix_messages_inbox_user_send "+ "create index ix_messages_inbox_user_send ""on messages (platform, session_id, created_at desc, id desc) "- "where session_id is not null and author = 'user' and type not in ('queued', 'draft', 'pending')"+ "where session_id is not null and author = 'user' and type not in ('queued', 'draft', 'pending', 'harness_dedupe')")diff --git a/storage/models.py b/storage/models.pyindex a1b958b55..00ee596b6 100644--- a/storage/models.py+++ b/storage/models.py@@ -362,7 +362,7 @@ messages = Table("session_id",text("created_at desc"),text("id desc"),- sqlite_where=text("session_id is not null and type not in ('queued', 'draft', 'pending')"),+ sqlite_where=text("session_id is not null and type not in ('queued', 'draft', 'pending', 'harness_dedupe')"),),Index("ix_messages_inbox_agent_reply",@@ -378,7 +378,9 @@ messages = Table("session_id",text("created_at desc"),text("id desc"),- sqlite_where=text("session_id is not null and author = 'user' and type not in ('queued', 'draft', 'pending')"),+ sqlite_where=text(+ "session_id is not null and author = 'user' and type not in ('queued', 'draft', 'pending', 'harness_dedupe')"+ ),),Index("ix_messages_scope_created", "scope_id", "created_at"),Index("ix_messages_scope_unread", "scope_id", "read_at"),diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 445789566..ff174cc89 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -503,6 +503,7 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):pre-persisted user row as queued and returns 202 {queued}, and never startsa competing agent turn. The row flushes when the running turn ends."""from core.services import sessions as sessions_service+from storage import messages_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state@@ -1127,6 +1128,85 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatchassert transcript["messages"] == []+def test_scheduled_gate_busy_duplicate_native_id_is_skipped(monkeypatch, tmp_path):+ """A retried harness callback already sitting in the queue is a duplicate,+ not a scheduler failure."""+ from core.services import sessions as sessions_service+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id="proj_sched_dup", now="2026-05-31T00:00:00Z"+ )+ _seed_project_workdir(conn, scope_id, tmp_path)+ session = sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"+ )+ session_id = session["id"]++ async def _explode_dispatch_turn(*args, **kwargs):+ raise AssertionError("a busy scheduled run must enqueue, not dispatch a turn")++ monkeypatch.setattr(session_turns, "dispatch_turn", _explode_dispatch_turn)++ controller = _build_controller_double()+ app = internal_server.create_app(controller)+ ctx = MessageContext(+ user_id="workbench",+ channel_id=session_id,+ platform="avibe",+ message_id="watch:def-watch:run-1",+ platform_specific={+ "task_execution_id": "run-1",+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ )++ async def _go():+ async def _busy():+ await asyncio.sleep(60)++ chat_task = asyncio.create_task(_busy())+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(+ task=chat_task,+ context=MessageContext(+ user_id="U",+ channel_id="C",+ platform="avibe",+ message_id="watch:def-watch:running",+ ),+ )+ try:+ first = await controller.session_turn_gate.submit_scheduled(session_id, ctx, "first")+ second = await controller.session_turn_gate.submit_scheduled(session_id, ctx, "duplicate")+ running_ctx = MessageContext(+ user_id="workbench",+ channel_id=session_id,+ platform="avibe",+ message_id="watch:def-watch:running",+ )+ running_duplicate = await controller.session_turn_gate.submit_scheduled(+ session_id,+ running_ctx,+ "running duplicate",+ )+ finally:+ chat_task.cancel()+ return first, second, running_duplicate++ assert asyncio.run(_go()) == ("enqueued", "duplicate", "duplicate")+ with engine.connect() as conn:+ queued = messages_service.list_queued(conn, session_id)+ assert [row["text"] for row in queued] == ["first"]++def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):"""Stop works for a scheduled run: because the run goes through ``_run_turn``it registers the scheduled ``context`` in ``in_flight``, so@@ -1219,6 +1299,7 @@ def _seed_avibe_session_with_queue(queued):message_type=messages_service.QUEUED_TYPE,text=text,metadata=({session_turns.SCHEDULED_PROVENANCE_KEY: prov} if prov is not None else None),+ native_message_id=(prov or {}).get("message_id") if prov is not None else None,)return session["id"]@@ -1279,6 +1360,574 @@ def test_flush_runs_scheduled_row_as_scheduled_with_provenance(tmp_path, monkeypassert messages_service.list_queued(conn, session_id) == []+def test_flush_coalesces_same_scheduled_callbacks_within_window(tmp_path, monkeypatch):+ """Harness callback rows stay visible as separate queued messages, but same+ watch/task callbacks inside the rolling window dispatch as one Agent turn."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ def prov(execution_id: str, message_id: str = "watch:def-watch") -> dict:+ return {+ "message_id": message_id,+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ }++ session_id = _seed_avibe_session_with_queue(+ [+ ("first callback", prov("run-1", "watch:def-watch:run-1")),+ ("second callback", prov("run-2", "watch:def-watch:run-2")),+ ("third callback", prov("run-3", "watch:def-watch:run-3")),+ ]+ )++ from sqlalchemy import select+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.models import messages++ with create_sqlite_engine().begin() as conn:+ assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [+ "first callback",+ "second callback",+ "third callback",+ ]++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ text, source, ctx = runs[0]+ assert source == SOURCE_SCHEDULED+ assert "first callback" in text+ assert "second callback" in text+ assert "third callback" in text+ assert "fired 3 times" in text+ assert "pause, remove, or update" in text+ assert ctx.platform_specific["task_definition_id"] == "def-watch"+ assert ctx.platform_specific["coalesced_queue"]["count"] == 3+ assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == ["run-1", "run-2", "run-3"]+ assert ctx.platform_specific["coalesced_queue"]["native_message_ids"] == [+ "watch:def-watch:run-1",+ "watch:def-watch:run-2",+ "watch:def-watch:run-3",+ ]+ with create_sqlite_engine().begin() as conn:+ assert messages_service.list_queued(conn, session_id) == []+ dedupe_rows = conn.execute(select(messages)).mappings().all()+ dedupe_native_ids = {+ row["native_message_id"]+ for row in dedupe_rows+ if row["type"] == messages_service.HARNESS_DEDUPE_TYPE+ }+ assert dedupe_native_ids == {"watch:def-watch:run-2", "watch:def-watch:run-3"}+++def test_flush_marks_suppressed_first_native_id(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"watch:def-watch:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ "suppress_delivery": True,+ },+ }++ session_id = _seed_avibe_session_with_queue(+ [+ ("first callback", prov("run-1")),+ ("second callback", prov("run-2")),+ ]+ )++ from sqlalchemy import select++ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.models import messages++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ with create_sqlite_engine().begin() as conn:+ dedupe_rows = conn.execute(select(messages)).mappings().all()+ dedupe_native_ids = {+ row["native_message_id"]+ for row in dedupe_rows+ if row["type"] == messages_service.HARNESS_DEDUPE_TYPE+ }+ assert dedupe_native_ids == {"watch:def-watch:run-1", "watch:def-watch:run-2"}+++def test_flush_does_not_coalesce_scheduled_callbacks_with_different_delivery(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ def prov(execution_id: str, channel_id: str) -> dict:+ return {+ "message_id": f"watch:def-watch:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ "delivery_override": {"platform": "slack", "channel_id": channel_id},+ },+ }++ session_id = _seed_avibe_session_with_queue(+ [+ ("first callback", prov("run-1", "C1")),+ ("different delivery", prov("run-2", "C2")),+ ]+ )++ from storage import messages_service+ from storage.db import create_sqlite_engine++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert [(text, source) for text, source, _ in runs] == [("first callback", SOURCE_SCHEDULED)]+ with create_sqlite_engine().begin() as conn:+ remaining = messages_service.list_queued(conn, session_id)+ assert [row["text"] for row in remaining] == ["different delivery"]+++def test_flush_does_not_coalesce_scheduled_callbacks_with_different_agent(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ def prov(execution_id: str, agent_name: str) -> dict:+ return {+ "message_id": f"watch:def-watch:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ "vibe_agent_name": agent_name,+ },+ }++ session_id = _seed_avibe_session_with_queue(+ [+ ("codex callback", prov("run-1", "codex")),+ ("claude callback", prov("run-2", "claude")),+ ]+ )++ from storage import messages_service+ from storage.db import create_sqlite_engine++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ text, source, ctx = runs[0]+ assert (text, source) == ("codex callback", SOURCE_SCHEDULED)+ assert ctx.platform_specific["vibe_agent_name"] == "codex"+ with create_sqlite_engine().begin() as conn:+ remaining = messages_service.list_queued(conn, session_id)+ assert [row["text"] for row in remaining] == ["claude callback"]+++def test_capture_scheduled_target_agent_splits_coalescing_key(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ def captured_prov(execution_id: str, agent_name: str) -> dict:+ ctx = MessageContext(+ user_id="U",+ channel_id="C",+ platform="avibe",+ message_id=f"watch:def-watch:{execution_id}",+ platform_specific={+ "task_execution_id": execution_id,+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ "agent_session_target": {"id": f"ses-{agent_name}", "agent_name": agent_name},+ },+ )+ return session_turns.capture_scheduled_provenance(ctx)++ session_id = _seed_avibe_session_with_queue(+ [+ ("codex target callback", captured_prov("run-1", "codex")),+ ("claude target callback", captured_prov("run-2", "claude")),+ ]+ )++ from storage import messages_service+ from storage.db import create_sqlite_engine++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ text, source, ctx = runs[0]+ assert (text, source) == ("codex target callback", SOURCE_SCHEDULED)+ assert ctx.platform_specific[session_turns.SCHEDULED_TARGET_AGENT_KEY] == "codex"+ with create_sqlite_engine().begin() as conn:+ remaining = messages_service.list_queued(conn, session_id)+ assert [row["text"] for row in remaining] == ["claude target callback"]+++def test_flush_coalesced_scheduled_copy_uses_i18n(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"watch:def-watch:{execution_id}",+ "platform_specific": {+ "language": "zh",+ "task_execution_id": execution_id,+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ }++ session_id = _seed_avibe_session_with_queue(+ [+ ("第一次 callback", prov("run-1")),+ ("第二次 callback", prov("run-2")),+ ]+ )++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ text = runs[0][0]+ assert "同一个 watch/task callback" in text+ assert "已合并的 callback 消息" in text+++def test_flush_preserves_scheduled_prompt_whitespace(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ session_id = _seed_avibe_session_with_queue(+ [+ (+ " indented: true\n",+ {+ "message_id": "watch:def-watch:run-1",+ "platform_specific": {+ "task_execution_id": "run-1",+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ },+ )+ ]+ )++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert runs[0][0] == " indented: true\n"+++def test_flush_skips_scheduled_callback_when_native_id_already_claimed(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ session_id = _seed_avibe_session_with_queue(+ [+ (+ "duplicate callback",+ {+ "message_id": "watch:def-watch:run-2",+ "platform_specific": {+ "task_execution_id": "run-2",+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ },+ )+ ]+ )++ from storage import messages_service+ from storage.db import create_sqlite_engine++ with create_sqlite_engine().begin() as conn:+ queued = messages_service.list_queued(conn, session_id)+ messages_service.delete_queued(conn, [queued[0]["id"]])+ messages_service.append(+ conn,+ scope_id=queued[0]["scope_id"],+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.HARNESS_DEDUPE_TYPE,+ text="",+ metadata={"coalesced_from": "older-row"},+ native_message_id="watch:def-watch:run-2",+ )+ messages_service.append(+ conn,+ scope_id=queued[0]["scope_id"],+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.QUEUED_TYPE,+ text="duplicate callback",+ metadata={+ session_turns.SCHEDULED_PROVENANCE_KEY: {+ "message_id": "watch:def-watch:run-2",+ "platform_specific": {+ "task_execution_id": "run-2",+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ }+ },+ native_message_id=None,+ )++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is False+ assert runs == []+ with create_sqlite_engine().begin() as conn:+ assert messages_service.list_queued(conn, session_id) == []+++def test_flush_drops_only_claimed_scheduled_callbacks(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"watch:def-watch:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ }++ session_id = _seed_avibe_session_with_queue(+ [+ ("duplicate callback", prov("run-1")),+ ("fresh callback", prov("run-2")),+ ]+ )++ from storage import messages_service+ from storage.db import create_sqlite_engine++ with create_sqlite_engine().begin() as conn:+ from sqlalchemy import update++ from storage.models import messages++ queued = messages_service.list_queued(conn, session_id)+ duplicate = queued[0]+ fresh = queued[1]+ messages_service.delete_queued(conn, [duplicate["id"]])+ messages_service.append(+ conn,+ scope_id=duplicate["scope_id"],+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.HARNESS_DEDUPE_TYPE,+ text="",+ metadata={"coalesced_from": "older-row"},+ native_message_id="watch:def-watch:run-1",+ )+ duplicate = messages_service.append(+ conn,+ scope_id=duplicate["scope_id"],+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.QUEUED_TYPE,+ text="duplicate callback",+ metadata={+ session_turns.SCHEDULED_PROVENANCE_KEY: {+ "message_id": "watch:def-watch:run-1",+ "platform_specific": {+ "task_execution_id": "run-1",+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ }+ },+ native_message_id=None,+ )+ conn.execute(+ update(messages)+ .where(messages.c.id == duplicate["id"])+ .values(created_at="2026-06-22T00:00:00Z")+ )+ conn.execute(update(messages).where(messages.c.id == fresh["id"]).values(created_at="2026-06-22T00:00:01Z"))++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ text, source, ctx = runs[0]+ assert (text, source) == ("fresh callback", SOURCE_SCHEDULED)+ assert ctx.message_id == "watch:def-watch:run-2"+ assert ctx.platform_specific["task_execution_id"] == "run-2"+ with create_sqlite_engine().begin() as conn:+ assert messages_service.list_queued(conn, session_id) == []+++def test_flush_does_not_mark_native_ids_when_context_build_fails(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ session_id = _seed_avibe_session_with_queue(+ [+ (+ "suppressed callback",+ {+ "message_id": "watch:def-watch:run-1",+ "platform_specific": {+ "task_execution_id": "run-1",+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ "suppress_delivery": True,+ },+ },+ )+ ]+ )++ from storage import messages_service+ from storage.db import create_sqlite_engine++ mgr = session_turns.SessionTurnManager(+ controller=types.SimpleNamespace(),+ build_context=lambda sid: (_ for _ in ()).throw(RuntimeError("missing session")),+ )++ assert asyncio.run(mgr.flush_queue(session_id)) is False+ with create_sqlite_engine().begin() as conn:+ from sqlalchemy import select++ from storage.models import messages++ rows = conn.execute(select(messages).where(messages.c.session_id == session_id)).mappings().all()+ assert [row for row in rows if row["type"] == messages_service.HARNESS_DEDUPE_TYPE] == []+++def test_flush_continues_after_dropping_duplicate_scheduled_segment(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ session_id = _seed_avibe_session_with_queue(+ [+ (+ "duplicate callback",+ {+ "message_id": "watch:def-watch:run-2",+ "platform_specific": {+ "task_execution_id": "run-2",+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ },+ ),+ ("queued user follow-up", None),+ ]+ )++ from storage import messages_service+ from storage.db import create_sqlite_engine++ with create_sqlite_engine().begin() as conn:+ from sqlalchemy import update++ from storage.models import messages++ queued = messages_service.list_queued(conn, session_id)+ messages_service.delete_queued(conn, [queued[0]["id"]])+ messages_service.append(+ conn,+ scope_id=queued[0]["scope_id"],+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.HARNESS_DEDUPE_TYPE,+ text="",+ metadata={"coalesced_from": "older-row"},+ native_message_id="watch:def-watch:run-2",+ )+ messages_service.append(+ conn,+ scope_id=queued[0]["scope_id"],+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.QUEUED_TYPE,+ text="duplicate callback",+ metadata={+ session_turns.SCHEDULED_PROVENANCE_KEY: {+ "message_id": "watch:def-watch:run-2",+ "platform_specific": {+ "task_execution_id": "run-2",+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ }+ },+ native_message_id=None,+ )+ queued = messages_service.list_queued(conn, session_id)+ for row in queued:+ created_at = "2026-06-22T00:00:00Z" if row["text"] == "duplicate callback" else "2026-06-22T00:01:00Z"+ conn.execute(update(messages).where(messages.c.id == row["id"]).values(created_at=created_at))++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert [(text, source) for text, source, _ in runs] == [("queued user follow-up", SOURCE_HUMAN)]+ with create_sqlite_engine().begin() as conn:+ assert messages_service.list_queued(conn, session_id) == []+++def test_flush_does_not_coalesce_scheduled_callbacks_outside_window(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"watch:def-watch:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ }++ session_id = _seed_avibe_session_with_queue(+ [+ ("first callback", prov("run-1")),+ ("late callback", prov("run-2")),+ ]+ )++ from sqlalchemy import update++ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.models import messages++ with create_sqlite_engine().begin() as conn:+ rows = messages_service.list_queued(conn, session_id)+ conn.execute(update(messages).where(messages.c.id == rows[0]["id"]).values(created_at="2026-06-22T00:00:00Z"))+ conn.execute(update(messages).where(messages.c.id == rows[1]["id"]).values(created_at="2026-06-22T00:02:01Z"))++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert [(text, source) for text, source, _ in runs] == [("first callback", SOURCE_SCHEDULED)]+ with create_sqlite_engine().begin() as conn:+ remaining = messages_service.list_queued(conn, session_id)+ assert [row["text"] for row in remaining] == ["late callback"]++def test_flush_segments_user_then_scheduled_in_order(tmp_path, monkeypatch):"""A mixed queue drains one segment per flush, in order: leading user rows mergeinto one user turn; the scheduled row then runs separately with its provenance.@@ -1374,7 +2023,7 @@ def test_capture_scheduled_provenance_keeps_delivery_drops_routing():"platform": "avibe","is_dm": False,"agent_session_id": "ses1",- "agent_session_target": {"id": "ses1"},+ "agent_session_target": {"id": "ses1", "agent_name": "worker"},"delivery_override": override,"suppress_delivery": True,"turn_source": "scheduled",@@ -1390,6 +2039,7 @@ def test_capture_scheduled_provenance_keeps_delivery_drops_routing():assert spec["suppress_delivery"] is Trueassert spec["turn_source"] == "scheduled"assert spec["task_trigger_kind"] == "task"+ assert spec[session_turns.SCHEDULED_TARGET_AGENT_KEY] == "worker"# Routing keys the flush rebuilds are NOT carried.for routing in ("platform", "is_dm", "agent_session_id", "agent_session_target"):assert routing not in specdiff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pyindex c9813a14b..f84c0c224 100644--- a/tests/test_message_dispatcher_scheduled.py+++ b/tests/test_message_dispatcher_scheduled.py@@ -209,6 +209,43 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):],)+ async def test_suppressed_coalesced_agent_run_result_marks_each_run_terminal(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "suppress_delivery": True,+ "task_trigger_kind": "agent_run",+ "task_execution_id": "run-1",+ "coalesced_queue": {"execution_ids": ["run-1", "run-2", "run-3"]},+ },+ )+ calls = []++ class _Store:+ def record_run_message(self, run_id, *, text, message_id=None, terminal_status=None):+ calls.append(("record", run_id, text, message_id, terminal_status))++ def close(self):+ calls.append(("close",))++ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):+ message_id = await dispatcher.emit_agent_message(context, "result", "private agent output")++ self.assertEqual(message_id, "suppressed:run-1")+ self.assertEqual(+ calls,+ [+ ("record", "run-1", "private agent output", "suppressed:run-1", "succeeded"),+ ("record", "run-2", "private agent output", "suppressed:run-1", "succeeded"),+ ("record", "run-3", "private agent output", "suppressed:run-1", "succeeded"),+ ("close",),+ ],+ )+async def test_suppressed_agent_run_ignores_non_result_process_messages(self):controller = _StubController()dispatcher = ConsolidatedMessageDispatcher(controller)diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex fd227cbc0..d0e65ea76 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -16,7 +16,13 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260610_0022"+HEAD_REVISION = "20260622_0023"+++def _index_sql(conn: sqlite3.Connection, name: str) -> str:+ row = conn.execute("select sql from sqlite_master where type = 'index' and name = ?", (name,)).fetchone()+ assert row is not None+ return str(row[0] or "")def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:@@ -67,6 +73,8 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:assert "ix_messages_inbox_activity" in message_indexesassert "ix_messages_inbox_agent_reply" in message_indexesassert "ix_messages_inbox_user_send" in message_indexes+ assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_activity")+ assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_user_send")agent_session_indexes = {row[1]for row in conn.execute(@@ -175,6 +183,9 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Pathassert "ix_messages_inbox_activity" in message_indexesassert "ix_messages_inbox_agent_reply" in message_indexesassert "ix_messages_inbox_user_send" in message_indexes+ with sqlite3.connect(db_path) as conn:+ assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_activity")+ assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_user_send")assert "ix_agent_sessions_scope_status_activity" in agent_session_indexes@@ -205,6 +216,23 @@ def test_run_migrations_adds_agent_events_from_previous_head(tmp_path: Path) ->assert "ix_agent_events_turn_sequence_id" in agent_event_indexes+def test_run_migrations_rebuilds_inbox_indexes_for_harness_dedupe(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"++ run_migrations(db_path, revision="20260610_0022")+ with sqlite3.connect(db_path) as conn:+ assert "harness_dedupe" not in _index_sql(conn, "ix_messages_inbox_activity")+ assert "harness_dedupe" not in _index_sql(conn, "ix_messages_inbox_user_send")++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ version = conn.execute("select version_num from alembic_version").fetchone()+ assert version == (HEAD_REVISION,)+ assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_activity")+ assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_user_send")++def test_scope_agent_backfill_migrates_explicit_agent_routes(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"run_migrations(db_path, revision="20260526_0006")diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 1b9d774d6..9ea60111b 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -3,6 +3,14 @@"title": "Fork {title}","titleUntitled": "Fork"},+ "harness": {+ "queueCoalesced": {+ "summary": "[Avibe Harness] The same watch/task callback fired {count} times within a rolling {window}-second window. The queued callbacks were coalesced into this single Agent turn.",+ "messagesLabel": "Coalesced callback messages:",+ "latestLabel": "Latest callback message after {additional} additional trigger(s):",+ "burstHint": "This callback source is firing frequently. Inspect the related watch/task and pause, remove, or update it if it is looping."+ }+ },"common": {"save": "Save","cancel": "Cancel",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 01c3fc655..324ccca27 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -3,6 +3,14 @@"title": "复刻 {title}","titleUntitled": "复刻"},+ "harness": {+ "queueCoalesced": {+ "summary": "[Avibe Harness] 同一个 watch/task callback 在滚动 {window} 秒窗口内触发了 {count} 次。已将这些排队 callback 合并为一次 Agent turn。",+ "messagesLabel": "已合并的 callback 消息:",+ "latestLabel": "后续又触发 {additional} 次后的最新 callback 消息:",+ "burstHint": "这个 callback 来源正在频繁触发。请检查相关 watch/task;如果它在循环触发,请 pause、remove 或 update。"+ }+ },"common": {"save": "保存","cancel": "取消",