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(chat): preserve transcript order and trigger source (#1161)
Call Whitef94a9bbd7901
diff --git a/core/internal_server.py b/core/internal_server.pyindex a713fa52b..81177959f 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -162,6 +162,9 @@ def create_app(controller: "Controller") -> FastAPI:submission_platform = str(getattr(context, "platform", None) or "avibe").strip()native_message_id = str(getattr(context, "message_id", None) or "").strip()+ submission_spec = dict(getattr(context, "platform_specific", None) or {})+ author_id = str(submission_spec.get("task_definition_id") or "").strip() or None+ author_name = str(submission_spec.get("task_trigger_kind") or "").strip() or Nonededupe_key: str | None = Nonedelivery_id: str | None = Nonedelivery_request: DeliveryRequest | None = None@@ -299,6 +302,8 @@ def create_app(controller: "Controller") -> FastAPI:session_id=session_id,platform=submission_platform,author="harness",+ author_id=author_id,+ author_name=author_name,source="harness",message_type="harness",text=text,@@ -356,6 +361,8 @@ def create_app(controller: "Controller") -> FastAPI:platform=submission_platform,source="harness",author="harness",+ author_id=author_id,+ author_name=author_name,message_type="harness",display_text=text,metadata={@@ -373,6 +380,8 @@ def create_app(controller: "Controller") -> FastAPI:"scope_id": scope_id,"display_text": delivery_request.display_text,"message_metadata": dict(delivery_request.metadata or {}),+ "author_id": delivery_request.author_id,+ "author_name": delivery_request.author_name,})try:diff --git a/core/services/session_fork.py b/core/services/session_fork.pyindex f2f86c147..328b8ea4e 100644--- a/core/services/session_fork.py+++ b/core/services/session_fork.py@@ -501,6 +501,7 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:from storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config+ from storage.messages_service import transcript_order_valuefrom storage.models import messagesensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))@@ -509,7 +510,7 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:with engine.connect() as conn:anchor = conn.execute(select(- messages.c.created_at,+ transcript_order_value().label("transcript_order_at"),messages.c.id,messages.c.author,messages.c.type,@@ -520,11 +521,11 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:).mappings().first()if anchor is None:return ForkSourceState()- anchor_created_at = anchor["created_at"]+ anchor_order_at = anchor["transcript_order_at"]anchor_id = anchor["id"]after_anchor = (- (messages.c.created_at > anchor_created_at)- | ((messages.c.created_at == anchor_created_at) & (messages.c.id > anchor_id))+ (transcript_order_value() > anchor_order_at)+ | ((transcript_order_value() == anchor_order_at) & (messages.c.id > anchor_id)))latest_after_anchor = conn.execute(select(messages.c.author, messages.c.type, messages.c.metadata_json)@@ -546,7 +547,7 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:),after_anchor,)- .order_by(messages.c.created_at.desc(), messages.c.id.desc())+ .order_by(transcript_order_value().desc(), messages.c.id.desc()).limit(1)).mappings().first()latest_after_anchor_author = (@@ -666,6 +667,7 @@ def _forked_session_title(source_title: str, lang: str = "en") -> str:def _latest_source_message_anchor(conn: Any, source_session_id: str) -> SourceMessageAnchor:from sqlalchemy import select+ from storage.messages_service import transcript_order_valuefrom storage.models import agent_events, message_deliveries, messages, session_turnsactive_initial = conn.execute(@@ -708,7 +710,7 @@ def _latest_source_message_anchor(conn: Any, source_session_id: str) -> SourceMemessages.c.session_id == source_session_id,messages.c.type.in_(_FORK_ANCHOR_TYPES),)- .order_by(messages.c.created_at.desc(), messages.c.id.desc())+ .order_by(transcript_order_value().desc(), messages.c.id.desc()).limit(1)).mappings().first()if row is None:diff --git a/core/session_turns.py b/core/session_turns.pyindex 15c94fe4b..dc89748f7 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -4246,8 +4246,16 @@ class SessionTurnManager:display_text=str(spec.get("display_text") or text),content_json=spec.get("message_content") if isinstance(spec.get("message_content"), dict) else None,metadata=spec.get("message_metadata") if isinstance(spec.get("message_metadata"), dict) else {},- author_id=str(spec.get("author_id") or "").strip() or None,- author_name=str(spec.get("author_name") or "").strip() or None,+ author_id=str(+ spec.get("author_id")+ or (spec.get("task_definition_id") if source == SOURCE_SCHEDULED else "")+ or ""+ ).strip() or None,+ author_name=str(+ spec.get("author_name")+ or (spec.get("task_trigger_kind") if source == SOURCE_SCHEDULED else "")+ or ""+ ).strip() or None,native_message_id=native_message_id,)result = await self.deliver(request, context=context)diff --git a/core/show_git.py b/core/show_git.pyindex 56ef5b6e4..1b07eebdc 100644--- a/core/show_git.py+++ b/core/show_git.py@@ -285,6 +285,7 @@ def load_turn_checkpoint_context(from sqlalchemy import func, select, tuple_from storage.db import get_cached_sqlite_engine+ from storage.messages_service import transcript_order_valuefrom storage.models import (agent_runs,message_deliveries,@@ -409,9 +410,10 @@ def load_turn_checkpoint_context(messages.c.content_json,messages.c.native_message_id,).where(messages.c.session_id == session_id)+ message_order = transcript_order_value(messages)if after is None:message_query = message_query.order_by(- messages.c.created_at.desc(), messages.c.id.desc()+ message_order.desc(), messages.c.id.desc()).limit(1)else:message_query = (@@ -420,8 +422,8 @@ def load_turn_checkpoint_context(TURN_CHECKPOINT_INPUT_AUTHOR_TYPES))- .where(messages.c.created_at >= after)- .order_by(messages.c.created_at.asc(), messages.c.id.asc())+ .where(message_order >= after)+ .order_by(message_order.asc(), messages.c.id.asc()).limit(1))message_row = conn.execute(message_query).first()diff --git a/core/web_push_notifications.py b/core/web_push_notifications.pyindex 737208b64..c955879a8 100644--- a/core/web_push_notifications.py+++ b/core/web_push_notifications.py@@ -8,7 +8,7 @@ import threadingimport timefrom typing import Any-from sqlalchemy import or_, select+from sqlalchemy import and_, or_, selectfrom storage import messages_service, web_push_servicefrom storage.models import agent_sessions, messages@@ -141,7 +141,7 @@ def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[sagent_row = conn.execute(select(messages.c.session_id,- messages.c.created_at,+ messages_service.transcript_order_value(messages).label("transcript_at"),messages.c.id,messages.c.type,messages.c.metadata_json,@@ -156,7 +156,9 @@ def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[s_parse_metadata(agent_row[4]),):return []- session_id, created_at, row_id = agent_row[0], agent_row[1], agent_row[2]+ session_id, transcript_at, row_id = agent_row[0], agent_row[1], agent_row[2]++ user_order = messages_service.transcript_order_value(messages)user_rows = conn.execute(select(messages.c.metadata_json)@@ -172,10 +174,12 @@ def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[s)).where(- (messages.c.created_at < created_at)- | ((messages.c.created_at == created_at) & (messages.c.id < row_id))+ or_(+ user_order < transcript_at,+ and_(user_order == transcript_at, messages.c.id < row_id),+ ))- .order_by(messages.c.created_at.desc(), messages.c.id.desc())+ .order_by(user_order.desc(), messages.c.id.desc())).all()for user_row in user_rows:try:diff --git a/storage/alembic/versions/20260804_0046_message_transcript_order.py b/storage/alembic/versions/20260804_0046_message_transcript_order.pynew file mode 100644index 000000000..4ed9d9bc6--- /dev/null+++ b/storage/alembic/versions/20260804_0046_message_transcript_order.py@@ -0,0 +1,120 @@+"""index the exact Message transcript-entry order++Queued input enters the visible transcript when its Delivery is accepted, while+directly accepted communication enters at creation. Both timestamps are+canonicalized to fixed-width UTC microseconds, making+``coalesce(delivered_at, created_at)`` an exact, lexically sortable key. The+matching expression index lets transcript cursor reads stop at their page limit.++Revision ID: 20260804_0046+Revises: 20260802_0045+Create Date: 2026-08-04+"""++from __future__ import annotations++from datetime import datetime, timezone+from typing import Any++import sqlalchemy as sa+from alembic import op++revision = "20260804_0046"+down_revision = "20260802_0045"+branch_labels = None+depends_on = None++_ORDER_EXPR = "coalesce(delivered_at, created_at)"+_INDEX = "ix_messages_session_transcript_id"+DROP_INDEX_SQL = f"drop index if exists {_INDEX}"+CREATE_INDEX_SQL = (+ f"create index {_INDEX} on messages (session_id, {_ORDER_EXPR}, id)"+)+_INDEX_SQL = {+ _INDEX: CREATE_INDEX_SQL,+ "ix_messages_mark_read": (+ f"create index ix_messages_mark_read "+ f"on messages (session_id, author, read_at, {_ORDER_EXPR}, id)"+ ),+ "ix_messages_inbox_activity": (+ f"create index ix_messages_inbox_activity "+ f"on messages (platform, session_id, {_ORDER_EXPR} desc, id desc) "+ "where session_id is not null and type in "+ "('user', 'harness', 'annotation', 'result', 'notify', 'error', 'assistant')"+ ),+ "ix_messages_inbox_agent_reply": (+ f"create index ix_messages_inbox_agent_reply "+ f"on messages (platform, session_id, {_ORDER_EXPR} desc, id desc) "+ "where session_id is not null and type in ('result', 'notify', 'error')"+ ),+ "ix_messages_inbox_user_send": (+ f"create index ix_messages_inbox_user_send "+ f"on messages (platform, session_id, {_ORDER_EXPR} desc, id desc) "+ "where session_id is not null and ((author = 'user' and type = 'user') "+ "or (author = 'harness' and type = 'harness') "+ "or (author = 'harness' and type = 'annotation'))"+ ),+}+_LEGACY_INDEX_SQL = {+ name: sql.replace(_ORDER_EXPR, "created_at")+ for name, sql in _INDEX_SQL.items()+ if name != "ix_messages_session_transcript_id"+}+++def _drop_indexes(bind: Any) -> None:+ for name in _INDEX_SQL:+ bind.exec_driver_sql(f"drop index if exists {name}")+++def _canonical_timestamp(value: Any) -> str | None:+ text = str(value or "").strip()+ if not text:+ return None+ parseable = text[:-1] + "+00:00" if text.endswith("Z") else text+ try:+ instant = datetime.fromisoformat(parseable)+ except ValueError:+ return text+ if instant.tzinfo is None:+ instant = instant.replace(tzinfo=timezone.utc)+ return instant.astimezone(timezone.utc).isoformat(timespec="microseconds").replace(+ "+00:00", "Z"+ )+++def upgrade() -> None:+ bind = op.get_bind()+ rows = bind.execute(+ sa.text("select id, created_at, delivered_at from messages")+ ).mappings()+ updates: list[dict[str, str | None]] = []+ for row in rows:+ created_at = _canonical_timestamp(row["created_at"])+ delivered_at = _canonical_timestamp(row["delivered_at"])+ if created_at != row["created_at"] or delivered_at != row["delivered_at"]:+ updates.append(+ {+ "id": str(row["id"]),+ "created_at": created_at,+ "delivered_at": delivered_at,+ }+ )+ if updates:+ bind.execute(+ sa.text(+ "update messages set created_at=:created_at, "+ "delivered_at=:delivered_at where id=:id"+ ),+ updates,+ )+ _drop_indexes(bind)+ for sql in _INDEX_SQL.values():+ bind.exec_driver_sql(sql)+++def downgrade() -> None:+ bind = op.get_bind()+ _drop_indexes(bind)+ for sql in _LEGACY_INDEX_SQL.values():+ bind.exec_driver_sql(sql)diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex c47722e79..df229f5c5 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -1036,7 +1036,15 @@ def _insert_message(snapshot: dict[str, Any],accepted_at: str,) -> None:+ from storage.messages_service import canonical_message_timestamp+existing = conn.execute(select(messages).where(messages.c.id == message_id)).mappings().first()+ normalized_accepted_at = canonical_message_timestamp(accepted_at)+ normalized_created_at = canonical_message_timestamp(+ snapshot.get("created_at") or accepted_at+ )+ assert normalized_accepted_at is not None+ assert normalized_created_at is not Nonevalues = {"id": message_id,"scope_id": snapshot.get("scope_id"),@@ -1052,9 +1060,9 @@ def _insert_message("content_text": snapshot.get("content_text"),"content_json": snapshot["content_json"],"metadata_json": snapshot["metadata_json"],- "created_at": snapshot.get("created_at") or accepted_at,- "updated_at": accepted_at,- "delivered_at": accepted_at,+ "created_at": normalized_created_at,+ "updated_at": normalized_accepted_at,+ "delivered_at": normalized_accepted_at,"read_at": snapshot.get("read_at"),}if existing is None:diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 198eb9b9a..3f82d83d1 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -38,7 +38,27 @@ from vibe.message_types import types_withdef _utc_now_iso() -> str:- return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+ return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace(+ "+00:00", "Z"+ )+++def canonical_message_timestamp(value: Any) -> str | None:+ """Return one lexically sortable UTC representation for Message timestamps."""++ text = str(value or "").strip()+ if not text:+ return None+ parseable = text[:-1] + "+00:00" if text.endswith("Z") else text+ try:+ instant = datetime.fromisoformat(parseable)+ except ValueError:+ return text+ if instant.tzinfo is None:+ instant = instant.replace(tzinfo=timezone.utc)+ return instant.astimezone(timezone.utc).isoformat(timespec="microseconds").replace(+ "+00:00", "Z"+ )def _timestamp_key(value: Any, row_id: Any) -> tuple[datetime, str]:@@ -57,14 +77,10 @@ def _timestamp_key(value: Any, row_id: Any) -> tuple[datetime, str]:def _new_message_id() -> str:"""Time-sortable message id.- The transcript and inbox order rows by ``(created_at, id)`` and- ``created_at`` is second-resolution, so two rows written in the same second- — e.g. a fast avibe turn where the user prompt and the agent result land- together — tie on ``created_at``. A microsecond-clock prefix makes the id- monotonic so that tie-break preserves insertion order; otherwise a random- uuid could render the result before the prompt, or make the inbox pick the- wrong "last" row for its activity / replied state. The random suffix keeps- ids unique within the same microsecond.+ The durable transcript key uses Message acceptance-or-creation time plus id.+ Legacy and imported rows may still have second-resolution timestamps, so a+ microsecond-clock prefix makes the id tie-break preserve insertion order.+ The random suffix keeps ids unique within the same microsecond."""return f"msg_{int(time.time() * 1_000_000):015x}{uuid.uuid4().hex[:8]}"@@ -103,11 +119,30 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:_AGENT_RUN_NATIVE_PREFIX = "agent_run:"-def _attach_agent_run_provenance(+def _native_harness_provenance(native_message_id: Any) -> tuple[str | None, str | None]:+ """Recover trigger kind/definition from the stable native Message identity.++ Delivery snapshots written before provenance was carried through the durable+ queue can have null ``author_name``/``author_id`` even though the native id+ still records the exact trigger. This is read compatibility for those rows;+ current writers persist the same values directly.+ """++ parts = str(native_message_id or "").split(":")+ kind = parts[0] if parts else ""+ if kind in {"watch", "webhook", "scheduled"}:+ return kind, parts[1] if len(parts) >= 3 and parts[1] else None+ if kind in {"hook", "agent_run"}:+ return kind, None+ return None, None+++def _attach_harness_provenance(conn: Connection, payloads: list[dict[str, Any]]) -> list[dict[str, Any]]:- """Read-side provenance for agent-callback ("自动触发") chat messages (A9a).+ """Read-side provenance for every durable Harness chat message.+ Stable native ids repair legacy queued rows whose trigger fields were lost.A harness ``agent_run`` prompt is stored as ``native_message_id ="agent_run:<execution_id>"`` with no source-session pointer (the write pathrecords none). Resolve it read-side: message → its ``agent_runs`` row@@ -120,6 +155,12 @@ def _attach_agent_run_provenance(exec_by_msg: dict[str, str] = {}for payload in payloads:native_id = payload.get("native_message_id")+ if payload.get("source") == "harness":+ kind, definition_id = _native_harness_provenance(native_id)+ if not payload.get("author_name") and kind:+ payload["author_name"] = kind+ if not payload.get("author_id") and definition_id:+ payload["author_id"] = definition_idif (payload.get("source") == "harness"and isinstance(native_id, str)@@ -216,6 +257,18 @@ def _attach_agent_run_provenance(return payloads+def transcript_order_value(table: Any = messages) -> Any:+ """SQLite ordering key for when a Message entered the transcript.++ A queued Delivery may be submitted while another Turn is active. Its Message+ is authored then but enters the transcript only when native start accepts it,+ recorded in ``delivered_at``. Directly accepted rows have no ``delivered_at``+ and keep their microsecond ``created_at`` plus id tie-break.+ """++ return func.coalesce(table.c.delivered_at, table.c.created_at)++_WS_RE = re.compile(r"\s+")# Snippet window radii (chars) either side of the matched term. Tuned for a@@ -358,7 +411,7 @@ def search_messages(# sessions stay active), so exclude a disabled scope's messages too. A# missing scope_settings row (legacy / folder-less project) is enabled..where(or_(scope_settings.c.enabled.is_(None), scope_settings.c.enabled != 0))- .order_by(messages.c.created_at.desc(), messages.c.id.desc())+ .order_by(transcript_order_value().desc(), messages.c.id.desc()).limit(effective_limit))@@ -440,7 +493,8 @@ def append(author = HARNESS_TYPEresolved_type = HARNESS_TYPE- now = _utc_now_iso()+ now = canonical_message_timestamp(_utc_now_iso())+ assert now is not Nonepayload = {"id": _new_message_id(),"scope_id": scope_id,@@ -458,7 +512,7 @@ def append("metadata_json": json.dumps(metadata or {}),"created_at": now,"updated_at": now,- "delivered_at": delivered_at,+ "delivered_at": canonical_message_timestamp(delivered_at),"read_at": read_at,}conn.execute(messages.insert().values(**payload))@@ -629,8 +683,9 @@ def list_session_messages(# yields an empty window. ``query`` already carries the type/metadata# filter, so the older/anchor/newer sub-queries inherit it — the anchor# only appears if it is itself transcript-visible.+ order_value = transcript_order_value()anchor = conn.execute(- select(messages.c.created_at).where(+ select(order_value).where(messages.c.id == around_id, messages.c.session_id == session_id)).scalar_one_or_none()@@ -640,11 +695,11 @@ def list_session_messages(older_q = (query.where(or_(- messages.c.created_at < anchor,- and_(messages.c.created_at == anchor, messages.c.id < around_id),+ order_value < anchor,+ and_(order_value == anchor, messages.c.id < around_id),))- .order_by(messages.c.created_at.desc(), messages.c.id.desc())+ .order_by(order_value.desc(), messages.c.id.desc()).limit(effective_limit + 1))older = [_row_to_payload(dict(row)) for row in conn.execute(older_q).mappings().all()]@@ -660,18 +715,18 @@ def list_session_messages(newer_q = (query.where(or_(- messages.c.created_at > anchor,- and_(messages.c.created_at == anchor, messages.c.id > around_id),+ order_value > anchor,+ and_(order_value == anchor, messages.c.id > around_id),))- .order_by(messages.c.created_at.asc(), messages.c.id.asc())+ .order_by(order_value.asc(), messages.c.id.asc()).limit(effective_limit + 1))newer = [_row_to_payload(dict(row)) for row in conn.execute(newer_q).mappings().all()]has_newer = len(newer) > effective_limitnewer = newer[:effective_limit]- merged = _attach_agent_run_provenance(conn, older + anchor_rows + newer)+ merged = _attach_harness_provenance(conn, older + anchor_rows + newer)return {"messages": merged,"next_after_id": newer[-1]["id"] if has_newer and newer else None,@@ -679,8 +734,9 @@ def list_session_messages(}if tail:# Newest ``limit`` rows, then flip back to chronological for the caller.- query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit + 1)- rows = _attach_agent_run_provenance(+ order_value = transcript_order_value()+ query = query.order_by(order_value.desc(), messages.c.id.desc()).limit(effective_limit + 1)+ rows = _attach_harness_provenance(conn, [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()])has_older = len(rows) > effective_limit@@ -692,18 +748,19 @@ def list_session_messages("next_before_id": rows[0]["id"] if has_older and rows else None,}if before_id:+ order_value = transcript_order_value()anchor = conn.execute(- select(messages.c.created_at).where(messages.c.id == before_id)+ select(order_value).where(messages.c.id == before_id)).scalar_one_or_none()if anchor is not None:query = query.where(or_(- messages.c.created_at < anchor,- and_(messages.c.created_at == anchor, messages.c.id < before_id),+ order_value < anchor,+ and_(order_value == anchor, messages.c.id < before_id),))- query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit + 1)- rows = _attach_agent_run_provenance(+ query = query.order_by(order_value.desc(), messages.c.id.desc()).limit(effective_limit + 1)+ rows = _attach_harness_provenance(conn, [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()])has_older = len(rows) > effective_limit@@ -715,18 +772,20 @@ def list_session_messages("next_before_id": rows[0]["id"] if has_older and rows else None,}if after_id:+ order_value = transcript_order_value()anchor = conn.execute(- select(messages.c.created_at).where(messages.c.id == after_id)+ select(order_value).where(messages.c.id == after_id)).scalar_one_or_none()if anchor is not None:query = query.where(or_(- messages.c.created_at > anchor,- and_(messages.c.created_at == anchor, messages.c.id > after_id),+ order_value > anchor,+ and_(order_value == anchor, messages.c.id > after_id),))- query = query.order_by(messages.c.created_at.asc(), messages.c.id.asc()).limit(effective_limit + 1)- rows = _attach_agent_run_provenance(+ order_value = transcript_order_value()+ query = query.order_by(order_value.asc(), messages.c.id.asc()).limit(effective_limit + 1)+ rows = _attach_harness_provenance(conn, [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()])# Probe one extra row against the clamped page size: a full page alone does@@ -906,7 +965,7 @@ def list_inbox_sessions("""def _latest_message_value(- column_name: str,+ column_name: Optional[str],*,author: Optional[str] = None,types: Optional[tuple[str, ...]] = None,@@ -914,11 +973,13 @@ def list_inbox_sessions(input_turn_only: bool = False,) -> Any:msg = messages.alias()+ order_value = transcript_order_value(msg)+ selected_value = order_value if column_name is None else getattr(msg.c, column_name)query = (- select(getattr(msg.c, column_name))+ select(selected_value).where(msg.c.session_id == agent_sessions.c.id).where(msg.c.session_id.is_not(None))- .order_by(msg.c.created_at.desc(), msg.c.id.desc())+ .order_by(order_value.desc(), msg.c.id.desc()).limit(1))if platform is not None:@@ -943,12 +1004,12 @@ def list_inbox_sessions(# Drive from the small session set and do top-1 index probes per session.# This preserves the inbox contract while avoiding full message-window# materialization as history grows.- last_activity_at = _latest_message_value("created_at", conversation_only=True)+ last_activity_at = _latest_message_value(None, conversation_only=True)last_author = _latest_message_value("author", conversation_only=True)preview_id = _latest_message_value("id", types=_INBOX_PREVIEW_TYPES)- preview_at = _latest_message_value("created_at", types=_INBOX_PREVIEW_TYPES)+ preview_at = _latest_message_value(None, types=_INBOX_PREVIEW_TYPES)last_terminal_id = _latest_message_value("id", types=_INBOX_SETTLES_REPLY_TYPES)- last_terminal_at = _latest_message_value("created_at", types=_INBOX_SETTLES_REPLY_TYPES)+ last_terminal_at = _latest_message_value(None, types=_INBOX_SETTLES_REPLY_TYPES)last_turn_terminal_id = (select(session_turns.c.id).where(@@ -978,7 +1039,7 @@ def list_inbox_sessions(.scalar_subquery())last_input_at = _latest_message_value(- "created_at", conversation_only=True, input_turn_only=True+ None, conversation_only=True, input_turn_only=True)last_input_id = _latest_message_value("id", conversation_only=True, input_turn_only=True)last_input_turn_state = (@@ -1094,11 +1155,9 @@ def list_inbox_sessions(unread = int(row["unread_count"] or 0)# Awaiting the agent: the latest human or harness input is newer than the# agent's latest reply. Persistent across a reload and stays set for the whole- # agent turn, unlike a literal "last author" check. ``created_at`` is- # second-resolution, so compare ``(created_at, id)`` tuples — the message- # id carries a microsecond-clock prefix (see ``_new_message_id``), giving- # the right order for a follow-up sent in the same second as the prior- # reply.+ # agent turn, unlike a literal "last author" check. The timestamp values+ # here are the same acceptance-or-creation positions used by the transcript;+ # id remains the stable tie-break for legacy second-resolution rows.last_input_at = row["last_input_at"]last_input_id = row["last_input_id"]# Execution settlement belongs to SessionTurn. A visible result Message@@ -1181,18 +1240,15 @@ def mark_session_read()if until_message_id:anchor = conn.execute(- select(messages.c.created_at).where(messages.c.id == until_message_id)+ select(transcript_order_value()).where(messages.c.id == until_message_id)).scalar_one_or_none()if anchor is not None:- # ``created_at`` is stored at second precision, so a bare- # ``<= anchor`` would also mark newer messages created in the- # same second as read. Tie-break on ``id`` so only rows at-or-- # before the anchor message itself are affected.+ order_value = transcript_order_value()base = base.where(or_(- messages.c.created_at < anchor,+ order_value < anchor,and_(- messages.c.created_at == anchor,+ order_value == anchor,messages.c.id <= until_message_id,),)@@ -1212,7 +1268,7 @@ def list_messages_for_inbox_scope(query = (select(messages).where(messages.c.scope_id == scope_id)- .order_by(messages.c.created_at.desc(), messages.c.id.desc())+ .order_by(transcript_order_value().desc(), messages.c.id.desc()).limit(min(max(int(limit), 1), 50)))return [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]diff --git a/storage/migrations.py b/storage/migrations.pyindex aacc72694..073f9d547 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -764,8 +764,6 @@ def _ensure_agent_runs_expression_indexes(conn: sqlite3.Connection) -> None:def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:- from vibe.message_types import build_partial_index_predicate-if "agent_sessions" in tables:conn.execute("create index if not exists ix_agent_sessions_visibility "@@ -781,6 +779,20 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -)if "messages" not in tables:return+ transcript_index = import_module(+ "storage.alembic.versions.20260804_0046_message_transcript_order"+ )+ transcript_row = conn.execute(+ "select sql from sqlite_master where type = 'index' and name = ?",+ (transcript_index._INDEX,),+ ).fetchone()+ if (+ transcript_row is None+ or _normalized_index_sql(transcript_row[0])+ != _normalized_index_sql(transcript_index.CREATE_INDEX_SQL)+ ):+ conn.execute(transcript_index.DROP_INDEX_SQL)+ conn.execute(transcript_index.CREATE_INDEX_SQL)conn.execute('create index if not exists ix_messages_session_created_id on messages (session_id, created_at, id)')conn.execute('create index if not exists ix_messages_session_type_created_id on messages (session_id, type, created_at, id)')conn.execute('create index if not exists ix_messages_platform_session_created_id on messages (platform, session_id, created_at, id)')@@ -788,21 +800,19 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -'create index if not exists ix_messages_unread_session ''on messages (platform, type, author, read_at, session_id)')- conn.execute(- 'create index if not exists ix_messages_mark_read '- 'on messages (session_id, author, read_at, created_at, id)'- )- for index_name in (- "ix_messages_inbox_activity",- "ix_messages_inbox_agent_reply",- "ix_messages_inbox_user_send",- ):+ for index_name, index_sql in transcript_index._INDEX_SQL.items():+ if index_name == transcript_index._INDEX:+ continue+ row = conn.execute(+ "select sql from sqlite_master where type = 'index' and name = ?",+ (index_name,),+ ).fetchone()+ if row is not None and _normalized_index_sql(row[0]) == _normalized_index_sql(+ index_sql+ ):+ continueconn.execute(f"drop index if exists {index_name}")- conn.execute(- f"create index {index_name} "- "on messages (platform, session_id, created_at desc, id desc) "- f"where {build_partial_index_predicate(index_name)}"- )+ conn.execute(index_sql)def _ensure_agent_events_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:diff --git a/storage/models.py b/storage/models.pyindex d111c3858..9ba6368b4 100644--- a/storage/models.py+++ b/storage/models.py@@ -436,12 +436,19 @@ messages = Table(Index("ix_messages_session_type_created_id", "session_id", "type", "created_at", "id"),Index("ix_messages_platform_session_created_id", "platform", "session_id", "created_at", "id"),Index("ix_messages_unread_session", "platform", "type", "author", "read_at", "session_id"),- Index("ix_messages_mark_read", "session_id", "author", "read_at", "created_at", "id"),+ Index(+ "ix_messages_mark_read",+ "session_id",+ "author",+ "read_at",+ text("coalesce(delivered_at, created_at)"),+ "id",+ ),Index("ix_messages_inbox_activity","platform","session_id",- text("created_at desc"),+ text("coalesce(delivered_at, created_at) desc"),text("id desc"),sqlite_where=text(build_partial_index_predicate("ix_messages_inbox_activity")),),@@ -449,7 +456,7 @@ messages = Table("ix_messages_inbox_agent_reply","platform","session_id",- text("created_at desc"),+ text("coalesce(delivered_at, created_at) desc"),text("id desc"),sqlite_where=text(build_partial_index_predicate("ix_messages_inbox_agent_reply")),),@@ -457,7 +464,7 @@ messages = Table("ix_messages_inbox_user_send","platform","session_id",- text("created_at desc"),+ text("coalesce(delivered_at, created_at) desc"),text("id desc"),sqlite_where=text(build_partial_index_predicate("ix_messages_inbox_user_send")),),diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.pyindex 314bcc27d..552edfe80 100644--- a/tests/test_agent_activity_service.py+++ b/tests/test_agent_activity_service.py@@ -853,8 +853,7 @@ def test_queued_initial_message_opens_at_its_accepted_turn(isolated_state,monkeypatch,):- """Submission order stays in the transcript, but execution grouping starts when- the queued Delivery becomes the initial owner of its accepted Turn."""+ """Transcript entry and execution grouping both start at Delivery acceptance."""engine = create_sqlite_engine()sid = "ses_queued_boundary"@@ -975,8 +974,8 @@ def test_queued_initial_message_opens_at_its_accepted_turn(assert [row["id"] for row in transcript] == ["msg_first_input",- "msg_queued_input","msg_first_result",+ "msg_queued_input","msg_second_result",]assert [group["status"] for group in groups] == ["done", "done"]diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex df5ea87bb..fd57c585b 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -1843,7 +1843,7 @@ def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(conn.execute(update(delivery_rows).where(delivery_rows.c.id == queued["id"])- .values(submitted_at="2026-06-22T00:00:37Z")+ .values(submitted_at="2026-06-22T00:00:37.000000Z"))generated_ids = iter((@@ -1853,6 +1853,11 @@ def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order()monkeypatch.setattr(messages_service, "_new_message_id", lambda: next(generated_ids))monkeypatch.setattr(messages_service, "_utc_now_iso", lambda: "2026-06-22T00:00:37Z")+ monkeypatch.setattr(+ message_deliveries,+ "turn_now_iso",+ lambda: "2026-06-22T00:00:37.000000Z",+ )result = messages_service.append(conn,scope_id=queued["scope_id"],@@ -1866,8 +1871,8 @@ def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(update(messages).where(messages.c.id == result["id"]).values(- created_at="2026-06-22T00:00:37Z",- updated_at="2026-06-22T00:00:37Z",+ created_at="2026-06-22T00:00:37.000000Z",+ updated_at="2026-06-22T00:00:37.000000Z",))@@ -1929,9 +1934,9 @@ def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(("result", "fast queued result"),]assert [row["created_at"] for row in transcript["messages"]] == [- "2026-06-22T00:00:37Z",- "2026-06-22T00:00:37Z",- "2026-06-22T00:00:37Z",+ "2026-06-22T00:00:37.000000Z",+ "2026-06-22T00:00:37.000000Z",+ "2026-06-22T00:00:37.000000Z",]assert [row["id"] for row in transcript["messages"]] == ["msg_000000000000100aaaaaaaa",@@ -2947,7 +2952,16 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatchcontroller = _build_controller_double()app = internal_server.create_app(controller)- ctx = MessageContext(user_id="workbench", channel_id=session_id, platform="avibe")+ ctx = MessageContext(+ user_id="workbench",+ channel_id=session_id,+ platform="avibe",+ message_id="watch:def-watch:scheduled-busy",+ platform_specific={+ "task_trigger_kind": "watch",+ "task_definition_id": "def-watch",+ },+ )async def _go():async def _busy():@@ -2979,6 +2993,8 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatchassert [q["text"] for q in queued] == ["scheduled while busy"]assert queued[0]["scope_id"] == scope_idassert queued[0]["author"] == "harness"+ assert queued[0]["author_name"] == "watch"+ assert queued[0]["author_id"] == "def-watch"assert [row["text"] for row in transcript["messages"]] == ["active owner"]assert ("queue.updated", {"session_id": session_id}) in publisheddiff --git a/tests/test_message_search.py b/tests/test_message_search.pyindex 815031ff8..d28f1e810 100644--- a/tests/test_message_search.py+++ b/tests/test_message_search.py@@ -70,6 +70,7 @@ def _insert_msg(msg_type=None,source=None,msg_id=None,+ delivered_at=None,):"""Direct insert so a test controls created_at / type / platform / text.@@ -91,6 +92,7 @@ def _insert_msg(metadata_json="{}",created_at=created_at,updated_at=created_at,+ delivered_at=delivered_at,read_at=None,))@@ -493,6 +495,40 @@ def test_search_limit_clamped_and_caps_matches(isolated_state):assert floored["total"] == 1+def test_search_recency_uses_transcript_acceptance_order(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_search_order", "Search order")+ _insert_msg(+ conn,+ scope_id,+ "ses_search_order",+ "user",+ "deploy queued",+ "2026-08-04T00:00:01.000000Z",+ msg_id="msg_001",+ delivered_at="2026-08-04T00:00:04.000000Z",+ )+ _insert_msg(+ conn,+ scope_id,+ "ses_search_order",+ "agent",+ "deploy reply",+ "2026-08-04T00:00:03.000000Z",+ msg_id="msg_003",+ )++ with engine.connect() as conn:+ result = messages_service.search_messages(conn, query="deploy")++ assert [match["id"] for match in result["sessions"][0]["matches"]] == [+ "msg_001",+ "msg_003",+ ]++# --- list_session_messages around_id window ---------------------------------diff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex cbf0f9dc0..1accfeb6f 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -330,6 +330,230 @@ def test_agent_run_provenance_skips_missing_source_session(isolated_state):assert "source_session_id" not in by_id["msg_ghost"]+ ("native_message_id", "expected_kind", "expected_definition_id"),+ [+ ("watch:def_watch:run_1", "watch", "def_watch"),+ ("watch:run_legacy", "watch", None),+ ("scheduled:def_task:run_2", "scheduled", "def_task"),+ ("scheduled:run_legacy", "scheduled", None),+ ("webhook:def_hook:run_3", "webhook", "def_hook"),+ ("webhook:run_legacy", "webhook", None),+ ("hook:run_4", "hook", None),+ ("agent_run:run_5", "agent_run", None),+ ],+)+def test_legacy_queued_harness_message_recovers_native_provenance(+ isolated_state,+ native_message_id,+ expected_kind,+ expected_definition_id,+):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_target")+ _insert_harness_msg(+ conn,+ scope_id,+ "ses_target",+ author_name=None,+ native_message_id=native_message_id,+ msg_id="msg_trigger",+ created_at="2026-08-04T00:00:00Z",+ )++ with engine.connect() as conn:+ [message] = messages_service.list_session_messages(+ conn,+ session_id="ses_target",+ )["messages"]++ assert message["author_name"] == expected_kind+ assert message.get("author_id") == expected_definition_id+++def test_transcript_orders_queued_input_at_acceptance_across_all_cursors(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_order")+ _insert_msg(+ conn,+ scope_id,+ "ses_order",+ "user",+ "first prompt",+ "2026-08-04T00:00:00Z",+ msg_id="msg_001",+ )+ _insert_msg(+ conn,+ scope_id,+ "ses_order",+ "agent",+ "reply before queued input starts",+ "2026-08-04T00:00:02Z",+ msg_id="msg_003",+ )+ _insert_msg(+ conn,+ scope_id,+ "ses_order",+ "user",+ "submitted while busy",+ "2026-08-04T00:00:01Z",+ msg_id="msg_002",+ )+ conn.execute(+ messages.update()+ .where(messages.c.id == "msg_002")+ .values(delivered_at="2026-08-04T00:00:03.500000+00:00")+ )++ with engine.connect() as conn:+ all_rows = messages_service.list_session_messages(+ conn,+ session_id="ses_order",+ )["messages"]+ tail = messages_service.list_session_messages(+ conn,+ session_id="ses_order",+ tail=True,+ limit=2,+ )["messages"]+ before = messages_service.list_session_messages(+ conn,+ session_id="ses_order",+ before_id="msg_002",+ limit=2,+ )["messages"]+ around = messages_service.list_session_messages(+ conn,+ session_id="ses_order",+ around_id="msg_003",+ limit=1,+ )["messages"]++ assert [row["id"] for row in all_rows] == ["msg_001", "msg_003", "msg_002"]+ assert [row["id"] for row in tail] == ["msg_003", "msg_002"]+ assert [row["id"] for row in before] == ["msg_001", "msg_003"]+ assert [row["id"] for row in around] == ["msg_001", "msg_003", "msg_002"]+++def test_append_keeps_subsecond_transcript_order_for_direct_reply(+ isolated_state,+ monkeypatch,+):+ monkeypatch.setattr(+ messages_service,+ "_utc_now_iso",+ lambda: "2026-08-04T00:00:00.750000Z",+ )+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_subsecond")+ prompt = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_subsecond",+ platform="avibe",+ author="user",+ text="prompt",+ delivered_at="2026-08-04T08:00:00.500000+08:00",+ )+ reply = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_subsecond",+ platform="avibe",+ author="agent",+ text="reply",+ )++ with engine.connect() as conn:+ transcript = messages_service.list_session_messages(+ conn,+ session_id="ses_subsecond",+ )["messages"]++ assert reply["created_at"] == "2026-08-04T00:00:00.750000Z"+ assert prompt["delivered_at"] == "2026-08-04T00:00:00.500000Z"+ assert [row["text"] for row in transcript] == ["prompt", "reply"]+++def test_transcript_preserves_submillisecond_acceptance_order(+ isolated_state,+ monkeypatch,+):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_microsecond")+ timestamps = iter(+ (+ "2026-08-04T00:00:00.000000Z",+ "2026-08-04T00:00:00.000100Z",+ )+ )+ monkeypatch.setattr(+ messages_service, "_utc_now_iso", lambda: next(timestamps)+ )+ queued = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_microsecond",+ platform="avibe",+ author="user",+ text="queued",+ delivered_at="2026-08-04T00:00:00.000900Z",+ )+ reply = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_microsecond",+ platform="avibe",+ author="agent",+ text="reply",+ )++ with engine.connect() as conn:+ transcript = messages_service.list_session_messages(+ conn,+ session_id="ses_microsecond",+ )["messages"]++ assert queued["id"] < reply["id"]+ assert [row["text"] for row in transcript] == ["reply", "queued"]+++def test_transcript_tail_uses_the_exact_order_expression_index(isolated_state):+ engine = create_sqlite_engine()+ order_value = messages_service.transcript_order_value()+ statement = (+ select(messages.c.id)+ .where(+ messages.c.session_id == "ses_plan",+ messages.c.type.in_(messages_service.TRANSCRIPT_TYPES),+ )+ .order_by(order_value.desc(), messages.c.id.desc())+ .limit(51)+ )+ compiled = statement.compile(engine, compile_kwargs={"literal_binds": True})++ with engine.connect() as conn:+ plan = "\n".join(+ str(row[-1])+ for row in conn.exec_driver_sql(+ "EXPLAIN QUERY PLAN " + str(compiled)+ ).all()+ )++ assert "USING INDEX ix_messages_session_transcript_id (session_id=?)" in plan+ assert "TEMP B-TREE" not in plan++def test_mark_session_read_ties_break_on_id(isolated_state):"""When ``until_message_id`` points at a message whose ``created_at``is shared by newer messages (second precision), only rows at-or-before@@ -903,7 +1127,19 @@ def _seed_titled_session(conn, scope_id: str, session_id: str, title: str) -> No)-def _insert_msg(conn, scope_id, session_id, author, text, created_at, *, read=True, msg_type=None, msg_id=None):+def _insert_msg(+ conn,+ scope_id,+ session_id,+ author,+ text,+ created_at,+ *,+ read=True,+ msg_type=None,+ msg_id=None,+ delivered_at=None,+):"""Direct insert so the test controls created_at (second-resolution) + read_at.Agent rows default to type='result' (the user-facing reply the inbox@@ -925,6 +1161,7 @@ def _insert_msg(conn, scope_id, session_id, author, text, created_at, *, read=Trmetadata_json="{}",created_at=created_at,updated_at=created_at,+ delivered_at=delivered_at,read_at=created_at if (read and author == "agent") else None,))@@ -1278,6 +1515,81 @@ def test_list_inbox_sessions_same_second_followup_uses_id_tiebreaker(isolated_stassert rows["ses_done_tie"]["replied"] is False+def test_list_inbox_sessions_uses_transcript_acceptance_order(isolated_state):+ """Inbox activity and awaiting state follow the visible transcript order.++ A queued input can be authored before a reply but accepted after it. Its+ acceptance is then the newest visible activity and the Session is awaiting+ another reply even though ``created_at`` alone says the opposite.+ """+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_titled_session(conn, scope_id, "ses_acceptance", "Acceptance")+ _insert_msg(+ conn,+ scope_id,+ "ses_acceptance",+ "user",+ "queued follow-up",+ "2026-08-04T00:00:01.000000Z",+ msg_id="msg_001",+ delivered_at="2026-08-04T00:00:04.000000Z",+ )+ _insert_msg(+ conn,+ scope_id,+ "ses_acceptance",+ "agent",+ "reply before acceptance",+ "2026-08-04T00:00:03.000000Z",+ msg_id="msg_003",+ )++ with engine.connect() as conn:+ row = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"][0]++ assert row["last_activity_at"] == "2026-08-04T00:00:04.000000Z"+ assert row["last_message_author"] == "user"+ assert row["replied"] is True+++def test_mark_session_read_uses_transcript_acceptance_boundary(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_acceptance_read")+ _insert_msg(+ conn,+ scope_id,+ "ses_acceptance_read",+ "user",+ "queued follow-up",+ "2026-08-04T00:00:01.000000Z",+ msg_id="msg_001",+ delivered_at="2026-08-04T00:00:04.000000Z",+ )+ _insert_msg(+ conn,+ scope_id,+ "ses_acceptance_read",+ "agent",+ "reply before acceptance",+ "2026-08-04T00:00:03.000000Z",+ read=False,+ msg_id="msg_003",+ )++ with engine.begin() as conn:+ updated = messages_service.mark_session_read(+ conn,+ "ses_acceptance_read",+ until_message_id="msg_001",+ )++ assert updated == 1++def test_list_inbox_sessions_pagination(isolated_state):"""Keyset 'load more' walks sessions in last-activity order."""engine = create_sqlite_engine()diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 37c51acd4..e56982f13 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -260,7 +260,9 @@ def test_fifo_segment_starts_one_turn_and_materializes_one_merged_message(manage"remote:user-a","remote:user-b",]- assert stored["created_at"] == accepted[0]["submitted_at"]+ assert stored["created_at"] == messages_service.canonical_message_timestamp(+ accepted[0]["submitted_at"]+ )assert stored["delivered_at"] == accepted[0]["materialized_at"]@@ -2353,9 +2355,22 @@ def test_pre_dispatch_hydration_failure_is_definitively_recoverable(managers) ->assert _row(engine, str(admitted.delivery_id))["state"] == "claimed"-def test_submit_reports_the_requeued_state_after_prewrite_failure(+ ("trigger_kind", "definition_id"),+ [+ ("scheduled", "task_123"),+ ("watch", "watch_123"),+ ("webhook", "webhook_123"),+ ("hook", None),+ ("agent_run", None),+ ("activity_recovery", None),+ ],+)+def test_scheduled_submit_preserves_trigger_provenance_after_prewrite_failure(managers,monkeypatch,+ trigger_kind,+ definition_id,) -> None:manager, _other, engine, _engine_b, starts = managerspublished: list[tuple[str, dict]] = []@@ -2369,10 +2384,17 @@ def test_submit_reports_the_requeued_state_after_prewrite_failure(lambda event, payload: published.append((event, payload)),)+ context = _context()+ context.platform_specific.update(+ {+ "task_trigger_kind": trigger_kind,+ "task_definition_id": definition_id,+ }+ )result = asyncio.run(manager.submit("ses_fsm",- _context(),+ context,"retry exact scheduled work",source=SOURCE_SCHEDULED,)@@ -2384,6 +2406,9 @@ def test_submit_reports_the_requeued_state_after_prewrite_failure(rows = _rows(engine)assert len(rows) == 1assert rows[0]["state"] == "queued"+ payload = delivery_store.delivery_payload(rows[0])+ assert payload["author_name"] == trigger_kind+ assert payload["author_id"] == definition_idassert ("queue.updated", {"session_id": "ses_fsm"}) in published@@ -2878,7 +2903,9 @@ def test_materialized_message_preserves_submission_and_acceptance_times(managersmessage = conn.execute(select(messages).where(messages.c.id == delivery["id"])).mappings().one()- assert message["created_at"] == delivery["submitted_at"]+ assert message["created_at"] == messages_service.canonical_message_timestamp(+ delivery["submitted_at"]+ )assert message["delivered_at"] == delivery["materialized_at"]diff --git a/tests/test_session_fork.py b/tests/test_session_fork.pyindex a1492ca72..a020ae27b 100644--- a/tests/test_session_fork.py+++ b/tests/test_session_fork.py@@ -1237,6 +1237,72 @@ def test_fork_source_state_tracks_nonterminal_messages_after_anchor(engine.dispose()+def test_fork_source_state_uses_delivery_acceptance_for_anchor_order(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from config import paths+ from storage.importer import ensure_sqlite_state++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ db_path = paths.get_sqlite_state_path()+ source_id = _seed_source_session(db_path, tmp_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ row = conn.execute(+ select(agent_sessions).where(agent_sessions.c.id == source_id)+ ).mappings().one()+ conn.execute(+ messages.insert(),+ [+ {+ "id": "msg_prior_result",+ "scope_id": row["scope_id"],+ "session_id": source_id,+ "platform": "avibe",+ "author": "agent",+ "type": "result",+ "source": None,+ "content_text": "prior result",+ "content_json": "{}",+ "metadata_json": "{}",+ "created_at": "2026-08-04T00:00:02.000000Z",+ "updated_at": "2026-08-04T00:00:02.000000Z",+ "delivered_at": None,+ },+ {+ "id": "msg_queued_anchor",+ "scope_id": row["scope_id"],+ "session_id": source_id,+ "platform": "avibe",+ "author": "user",+ "type": "user",+ "source": "user",+ "content_text": "queued prompt",+ "content_json": "{}",+ "metadata_json": "{}",+ "created_at": "2026-08-04T00:00:01.000000Z",+ "updated_at": "2026-08-04T00:00:03.000000Z",+ "delivered_at": "2026-08-04T00:00:03.000000Z",+ },+ ],+ )++ state = fork_source_state(+ {+ "source_session_id": source_id,+ "source_message_id": "msg_queued_anchor",+ }+ )++ assert state.has_messages_after_anchor is False+ assert state.latest_after_anchor_author is None+ assert state.has_terminal_agent_output_after_anchor is False+ finally:+ engine.dispose()++def test_fork_source_state_ignores_notify_as_terminal_output(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/test_show_git.py b/tests/test_show_git.pyindex 31210d5e4..d4403c76d 100644--- a/tests/test_show_git.py+++ b/tests/test_show_git.py@@ -965,6 +965,83 @@ def test_storage_lookup_includes_harness_driving_message():) == TurnCheckpointContext()+def test_storage_lookup_uses_transcript_acceptance_order():+ from storage import messages_service+ from storage.db import get_cached_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.models import agent_sessions, messages+ from storage.settings_service import upsert_scope++ ensure_sqlite_state(primary_platform="avibe")+ session_id = "ses_acceptance_checkpoint"+ with get_cached_sqlite_engine().begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_acceptance_checkpoint",+ now="2026-08-04T00:00:00.000000+00:00",+ )+ conn.execute(+ agent_sessions.insert().values(+ id=session_id,+ scope_id=scope_id,+ agent_backend="codex",+ agent_variant="default",+ session_anchor=session_id,+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at="2026-08-04T00:00:00.000000+00:00",+ updated_at="2026-08-04T00:00:00.000000+00:00",+ last_active_at="2026-08-04T00:00:00.000000+00:00",+ )+ )+ queued = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="user",+ message_type="user",+ source="user",+ text="queued input accepted last",+ )+ direct = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="user",+ message_type="user",+ source="user",+ text="direct input accepted first",+ )+ conn.execute(+ messages.update()+ .where(messages.c.id == queued["id"])+ .values(+ created_at="2026-08-04T00:00:01.000000+00:00",+ delivered_at="2026-08-04T00:00:04.000000+00:00",+ )+ )+ conn.execute(+ messages.update()+ .where(messages.c.id == direct["id"])+ .values(created_at="2026-08-04T00:00:02.000000+00:00")+ )++ expected = TurnCheckpointContext(+ message="queued input accepted last",+ message_id=queued["id"],+ )+ assert show_git.load_turn_checkpoint_context(session_id) == expected+ assert show_git.load_turn_checkpoint_context(+ session_id,+ after="2026-08-04T00:00:03.000000+00:00",+ ) == expected++def test_storage_lookup_includes_annotation_driving_message():from storage import messages_servicefrom storage.db import get_cached_sqlite_enginediff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 6d0d3a25c..ed19a939b 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -28,7 +28,7 @@ from storage.settings_service import SQLiteSettingsService, upsert_scopefrom vibe.message_types import build_partial_index_predicate-HEAD_REVISION = "20260802_0045"+HEAD_REVISION = "20260804_0046"MESSAGE_PARTIAL_INDEX_PREDICATES = {"ix_messages_inbox_activity": ("session_id is not null and type in "@@ -67,7 +67,8 @@ def test_message_partial_index_ddl_matches_catalog_contract(assert catalog_predicate == expected_predicateassert ddl == (f"CREATE INDEX {index_name} ON messages "- f"(platform, session_id, created_at desc, id desc) WHERE {expected_predicate}"+ "(platform, session_id, coalesce(delivered_at, created_at) desc, id desc) "+ f"WHERE {expected_predicate}")@@ -101,6 +102,62 @@ def test_alembic_script_directory_has_exactly_one_head() -> None:assert heads[0] == HEAD_REVISION+def test_message_transcript_order_upgrade_normalizes_and_indexes_exact_time(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260802_0045")+ with sqlite3.connect(db_path) as conn:+ conn.execute(+ """+ insert into messages (+ id, platform, author, type, content_json, metadata_json,+ created_at, updated_at, delivered_at+ ) values (?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "msg_legacy_order",+ "avibe",+ "user",+ "user",+ "{}",+ "{}",+ "2026-08-04T08:00:00+08:00",+ "2026-08-04T08:00:00+08:00",+ "2026-08-04T08:00:00.000999+08:00",+ ),+ )+ conn.commit()++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ row = conn.execute(+ "select created_at, delivered_at from messages where id = ?",+ ("msg_legacy_order",),+ ).fetchone()+ index_sql = _index_sql(conn, "ix_messages_session_transcript_id")+ dependent_index_sql = {+ name: _index_sql(conn, name)+ for name in (+ "ix_messages_mark_read",+ "ix_messages_inbox_activity",+ "ix_messages_inbox_agent_reply",+ "ix_messages_inbox_user_send",+ )+ }++ assert row == (+ "2026-08-04T00:00:00.000000Z",+ "2026-08-04T00:00:00.000999Z",+ )+ assert "coalesce(delivered_at, created_at)" in index_sql.lower()+ assert all(+ "coalesce(delivered_at, created_at)" in sql.lower()+ for sql in dependent_index_sql.values()+ )++def test_scoped_native_message_identity_upgrade_and_safe_downgrade(tmp_path: Path,) -> None:@@ -1243,6 +1300,7 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:)}assert "ix_messages_session_created_id" in message_indexes+ assert "ix_messages_session_transcript_id" in message_indexesassert "ix_messages_session_type_created_id" in message_indexesassert "ix_messages_platform_session_created_id" in message_indexesassert "ix_messages_unread_session" in message_indexes@@ -1582,7 +1640,7 @@ def test_show_annotation_migration_changes_only_the_user_send_index() -> None:db_path = tmp_path / "vibe.sqlite"run_migrations(db_path, revision="20260726_0037")- now = "2026-07-27T00:00:00Z"+ now = "2026-07-27T00:00:00.000000Z"legacy_payloads = [("agent", "assistant", "assistant.mark.created")for _ in range(5)@@ -1655,7 +1713,10 @@ def test_show_annotation_migration_changes_only_the_user_send_index(assert user_send_index.endswith(MESSAGE_PARTIAL_INDEX_PREDICATES["ix_messages_inbox_user_send"])- assert "(platform, session_id, created_at desc, id desc)" in user_send_index+ assert (+ "(platform, session_id, coalesce(delivered_at, created_at) desc, id desc)"+ in user_send_index+ )assert version == (HEAD_REVISION,)command.downgrade(migrations.alembic_config(db_path), "20260726_0037")diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.pyindex 0c7bf86bb..6986b18fd 100644--- a/tests/test_web_push_notifications.py+++ b/tests/test_web_push_notifications.py@@ -4,7 +4,7 @@ from core import web_push_notificationsfrom storage import message_deliveries, messages_service, web_push_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state-from storage.models import agent_sessions+from storage.models import agent_sessions, messagesfrom storage.settings_service import upsert_scope@@ -184,6 +184,96 @@ def test_backend_failure_notify_passes_durable_web_push_gates(monkeypatch, tmp_pengine.dispose()+def test_web_push_owner_uses_transcript_acceptance_order(monkeypatch, tmp_path):+ 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_acceptance_owner",+ now="2026-08-04T00:00:00.000000Z",+ )+ conn.execute(+ agent_sessions.insert().values(+ id="ses_acceptance_owner",+ scope_id=scope_id,+ agent_backend="codex",+ agent_variant="default",+ session_anchor="ses_acceptance_owner",+ native_session_id="",+ title="Acceptance owner",+ status="active",+ metadata_json="{}",+ created_at="2026-08-04T00:00:00.000000Z",+ updated_at="2026-08-04T00:00:00.000000Z",+ last_active_at="2026-08-04T00:00:00.000000Z",+ )+ )+ before = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_acceptance_owner",+ platform="avibe",+ author="user",+ source="user",+ metadata={"_web_push_user_key": "remote:before"},+ message_type="user",+ text="accepted before result",+ )+ after = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_acceptance_owner",+ platform="avibe",+ author="user",+ source="user",+ metadata={"_web_push_user_key": "remote:after"},+ message_type="user",+ text="accepted after result",+ )+ result = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_acceptance_owner",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="done",+ )+ conn.execute(+ messages.update()+ .where(messages.c.id == before["id"])+ .values(+ created_at="2026-08-04T00:00:01.000000Z",+ delivered_at="2026-08-04T00:00:02.000000Z",+ )+ )+ conn.execute(+ messages.update()+ .where(messages.c.id == after["id"])+ .values(+ created_at="2026-08-04T00:00:02.000000Z",+ delivered_at="2026-08-04T00:00:04.000000Z",+ )+ )+ conn.execute(+ messages.update()+ .where(messages.c.id == result["id"])+ .values(created_at="2026-08-04T00:00:03.000000Z")+ )++ with engine.connect() as conn:+ assert web_push_notifications._web_push_user_keys_for_message(+ conn,+ result["id"],+ ) == ["remote:before"]+ engine.dispose()++def test_send_to_enabled_subscriptions_waits_then_sends_to_owner_devices(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))ensure_sqlite_state()diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex fc6c2ede3..57db760b0 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -37,13 +37,21 @@ import {resolveActivityLabel,sortBackgroundActivities,} from '../../lib/backgroundActivity';-import { chatTriggerLink, harnessChipLabelKey, isUnresolvedAgentCallback } from '../../lib/chatTrigger';+import {+ chatTriggerLink,+ harnessChipLabelKey,+ needsHarnessProvenanceReconcile,+} from '../../lib/chatTrigger';import { AnnotationMessage } from './AnnotationMessage';import { AGENT_BUBBLE, SYSTEM_BUBBLE, USER_BUBBLE } from './chatBubble';import { RoleAvatar } from './RoleAvatar';import { useFileDrop } from '../../lib/useFileDrop';import { quoteText } from '../../lib/quoteText';-import { mergeById, insertMessageOrdered } from '../../lib/transcriptOrder';+import {+ isTranscriptWindowDisjoint,+ mergeById,+ insertMessageOrdered,+} from '../../lib/transcriptOrder';import { AgentRoutePicker } from './AgentRoutePicker';import { ShowPageShareControl } from './ShowPageShareControl';import { ShowPageAnnotateControl } from './ShowPageAnnotateControl';@@ -775,9 +783,9 @@ export const ChatPage: React.FC = () => {if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetchconst fresh = res.messages.filter(isTranscriptMessage);if (fresh.length) {- const tailOldestId = fresh[0].id;+ const tailOldest = fresh[0];const previousOldestId = oldestLoadedIdRef.current;- const previousNewestId = newestLoadedIdRef.current;+ const previousNewest = messagesRef.current[messagesRef.current.length - 1];setMessages((prev) => {const merged = mergeById(prev, fresh);// Following the tail: keep the window capped. A gap larger than the tail@@ -791,7 +799,11 @@ export const ChatPage: React.FC = () => {}return merged;});- if (!previousOldestId || !previousNewestId || tailOldestId > previousNewestId) {+ if (+ !previousOldestId ||+ !previousNewest ||+ isTranscriptWindowDisjoint(previousNewest, tailOldest)+ ) {setOlderCursor(res.next_before_id ?? null);}}@@ -1126,10 +1138,9 @@ export const ChatPage: React.FC = () => {return;}appendMessage(msg);- // A9a: a live agent-callback prompt is published before its source- // session is resolved, so pull the enriched REST row (mergeById fills- // source_session_* in place) — the chip appears without a reload/refocus.- if (isUnresolvedAgentCallback(msg)) void reconcile();+ // Harness live rows can precede read-side provenance enrichment. Pull+ // the enriched REST row so trigger/source chips update without reload.+ if (needsHarnessProvenanceReconcile(msg)) void reconcile();// Agent Activity: a terminal reply settles the turn → mark the generation// settled and rebuild groups from storage (chip, rows, status, duration all// come from the endpoint, never the lossy live buffer).diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 541f58f0d..817ead38d 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -3058,6 +3058,8 @@"scheduled": "Scheduled task","watch": "Watch","webhook": "Webhook",+ "hook": "Hook",+ "activityRecovery": "Recovered activity","showIntent": "Page action","harness": "From agent","from": "From",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 00c7e0ecd..62395d9b6 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -3058,6 +3058,8 @@"scheduled": "定时任务","watch": "Watch 监听","webhook": "Webhook",+ "hook": "Hook",+ "activityRecovery": "活动恢复","showIntent": "页面操作","harness": "来自 Agent","from": "来自",diff --git a/ui/src/lib/chatTrigger.test.ts b/ui/src/lib/chatTrigger.test.tsindex 86e7896c0..93e782d3c 100644--- a/ui/src/lib/chatTrigger.test.ts+++ b/ui/src/lib/chatTrigger.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { chatTriggerLink, harnessChipLabelKey, isUnresolvedAgentCallback } from './chatTrigger';+import { chatTriggerLink, harnessChipLabelKey, needsHarnessProvenanceReconcile } from './chatTrigger';type Msg = Parameters<typeof chatTriggerLink>[0];const msg = (over: Partial<Msg>): Msg => ({@@ -70,14 +70,20 @@ describe('chatTriggerLink', () => {expect(link({ author_name: 'agent_run', source_session_id: null })).toBeNull();});- it('prefers the source link over the kind link when both could apply', () => {+ it('keeps an explicitly sourced watch on its exact source link', () => {expect(link({ author_name: 'watch', source_session_id: 'ses_src' })?.kind).toBe('source');});});-describe('isUnresolvedAgentCallback', () => {- const m = (over: Partial<Parameters<typeof isUnresolvedAgentCallback>[0]>) =>- isUnresolvedAgentCallback({ source: 'harness', native_message_id: 'agent_run:exec1', source_session_id: null, ...over });+describe('needsHarnessProvenanceReconcile', () => {+ const m = (over: Partial<Parameters<typeof needsHarnessProvenanceReconcile>[0]>) =>+ needsHarnessProvenanceReconcile({+ source: 'harness',+ native_message_id: 'agent_run:exec1',+ source_session_id: null,+ author_name: 'agent_run',+ ...over,+ });it('is true for a live agent_run harness message without a resolved source', () => {expect(m({})).toBe(true);@@ -87,8 +93,19 @@ describe('isUnresolvedAgentCallback', () => {expect(m({ source_session_id: 'ses_src' })).toBe(false);});- it('is false for non-agent_run harness messages and non-harness messages', () => {- expect(m({ native_message_id: 'scheduled:def:exec' })).toBe(false);+ it('also reconciles legacy trigger rows whose native identity outlived provenance', () => {+ for (const native_message_id of [+ 'scheduled:def:exec',+ 'watch:def:exec',+ 'webhook:def:exec',+ 'hook:exec',+ ]) {+ expect(m({ native_message_id, author_name: null })).toBe(true);+ }+ });++ it('is false for complete non-agent trigger rows and non-harness messages', () => {+ expect(m({ native_message_id: 'scheduled:def:exec', author_name: 'scheduled' })).toBe(false);expect(m({ native_message_id: null })).toBe(false);expect(m({ source: 'agent' })).toBe(false);});@@ -109,9 +126,11 @@ describe('harnessChipLabelKey (leading-label key by source presence)', () => {expect(key({ author_name: null, source_session_id: null })).toBe('chat.source.harness');});- it('task / watch / webhook keep their own self-contained labels (unchanged)', () => {+ it('every non-agent Harness trigger keeps its own self-contained label', () => {expect(key({ author_name: 'watch' })).toBe('chat.source.watch');expect(key({ author_name: 'webhook' })).toBe('chat.source.webhook');+ expect(key({ author_name: 'hook' })).toBe('chat.source.hook');+ expect(key({ author_name: 'activity_recovery' })).toBe('chat.source.activityRecovery');for (const author_name of ['scheduled', 'task_run', 'task']) {expect(key({ author_name })).toBe('chat.source.scheduled');}diff --git a/ui/src/lib/chatTrigger.ts b/ui/src/lib/chatTrigger.tsindex af8df6176..55649c5a2 100644--- a/ui/src/lib/chatTrigger.ts+++ b/ui/src/lib/chatTrigger.ts@@ -15,19 +15,22 @@ export type ChatTriggerLink =| { kind: 'harness'; to: string };const AGENT_RUN_NATIVE_PREFIX = 'agent_run:';+const HARNESS_NATIVE_PREFIXES = ['agent_run:', 'scheduled:', 'watch:', 'webhook:', 'hook:'];-// True for a live agent-callback ("自动触发") harness message that has NOT yet-// been enriched with its source session (A9a). The live ``message.new`` payload-// is published raw (before ``list_session_messages`` resolves the source), so-// ChatPage triggers a targeted reconcile on these to pull the enriched REST row-// (``mergeById`` then fills ``source_session_*`` in place) — otherwise the source-// chip would only appear after a manual reload/refocus.-export function isUnresolvedAgentCallback(- message: Pick<WorkbenchMessage, 'source' | 'native_message_id' | 'source_session_id'>,+// Live Harness rows can arrive before read-side enrichment. Agent callbacks need+// source-session resolution; legacy queued triggers may need kind/definition+// recovery from their stable native id. A targeted reconcile fills either set.+export function needsHarnessProvenanceReconcile(+ message: Pick<+ WorkbenchMessage,+ 'source' | 'native_message_id' | 'source_session_id' | 'author_name'+ >,): boolean {+ if (message.source !== 'harness' || typeof message.native_message_id !== 'string') return false;+ if (message.author_name == null) {+ return HARNESS_NATIVE_PREFIXES.some((prefix) => message.native_message_id?.startsWith(prefix));+ }return (- message.source === 'harness' &&- typeof message.native_message_id === 'string' &&message.native_message_id.startsWith(AGENT_RUN_NATIVE_PREFIX) &&message.source_session_id == null);@@ -97,6 +100,8 @@ export function harnessChipLabelKey(message: TriggerFields): string {if (kind === 'show_intent') return 'chat.source.showIntent';if (kind === 'watch') return 'chat.source.watch';if (kind === 'webhook') return 'chat.source.webhook';+ if (kind === 'hook') return 'chat.source.hook';+ if (kind === 'activity_recovery') return 'chat.source.activityRecovery';if (TASK_KINDS.has(kind ?? '')) return 'chat.source.scheduled';return 'chat.source.harness';}diff --git a/ui/src/lib/transcriptOrder.test.ts b/ui/src/lib/transcriptOrder.test.tsindex 5cd5c6e46..0e7bc1d4b 100644--- a/ui/src/lib/transcriptOrder.test.ts+++ b/ui/src/lib/transcriptOrder.test.ts@@ -3,22 +3,21 @@ import { describe, expect, it } from 'vitest';import type { WorkbenchMessage } from '../context/ApiContext';import {byCreatedThenId,+ isTranscriptWindowDisjoint,mergeById,insertMessageOrdered,messageOrderTimeMs,timestampOrderTimeMs,+ transcriptOrderTimeMs,} from './transcriptOrder';-// The transcript keeps its rows in durable (created_at, id) order at all times.-// Only id + created_at drive ordering, so fixtures fill just those; the rest is-// cast away. ``created_at`` is second-resolution server-side, so same-second rows-// with different ids exercise the id tie-break (the case that would otherwise let-// a fast agent result render ahead of its prompt). Timestamps stay whole-second to-// match the real format — mixing fractional seconds would only test a string--// compare artifact the server never produces.+// The transcript keeps rows in durable transcript-entry order. Direct Messages+// use created_at plus their time-sortable id; accepted Delivery Messages use+// delivered_at so time spent waiting in the queue cannot move them above the+// reply that completed first.const t = (s: number) => `2024-01-01T00:00:${String(s).padStart(2, '0')}Z`;-const mk = (id: string, created_at: string): WorkbenchMessage =>- ({ id, created_at }) as unknown as WorkbenchMessage;+const mk = (id: string, created_at: string, delivered_at: string | null = null): WorkbenchMessage =>+ ({ id, created_at, delivered_at }) as unknown as WorkbenchMessage;const ids = (list: WorkbenchMessage[]): string[] => list.map((m) => m.id);describe('messageOrderTimeMs', () => {@@ -32,6 +31,16 @@ describe('messageOrderTimeMs', () => {});});+describe('transcriptOrderTimeMs', () => {+ it('uses native acceptance for a message submitted while another turn was active', () => {+ expect(+ transcriptOrderTimeMs(+ mk('msg_000000000000001deadbeef', '2026-08-04T00:00:01Z', '2026-08-04T00:00:03.500000Z'),+ ),+ ).toBeCloseTo(Date.parse('2026-08-04T00:00:03.500Z'), 6);+ });+});+describe('timestampOrderTimeMs', () => {it('retains microseconds from UTC and offset ISO timestamps', () => {const base = Date.parse('2026-07-30T10:00:00.500Z');@@ -59,6 +68,25 @@ describe('byCreatedThenId', () => {it('returns 0 only for the same id at the same time', () => {expect(byCreatedThenId(mk('a', t(1)), mk('a', t(1)))).toBe(0);});++ it('places a queued input after the reply that completed before its acceptance', () => {+ const reply = mk('msg_003', '2026-08-04T00:00:02Z');+ const queued = mk('msg_002', '2026-08-04T00:00:01Z', '2026-08-04T00:00:03.500000Z');+ expect(byCreatedThenId(reply, queued)).toBe(-1);+ });+});++describe('isTranscriptWindowDisjoint', () => {+ it('uses acceptance order rather than sortable ids at the reconciliation boundary', () => {+ const previousNewest = mk('msg_003', '2026-08-04T00:00:02Z');+ const tailOldest = mk(+ 'msg_002',+ '2026-08-04T00:00:01Z',+ '2026-08-04T00:00:03.500000Z',+ );++ expect(isTranscriptWindowDisjoint(previousNewest, tailOldest)).toBe(true);+ });});describe('mergeById', () => {@@ -83,8 +111,11 @@ describe('mergeById', () => {it('fills late-arriving source-session provenance onto an existing live row (A9a)', () => {const live = { id: 'm1', created_at: t(1), source_session_id: null } as unknown as WorkbenchMessage;const enriched = {- id: 'm1', created_at: t(1),- source_session_id: 'ses_src', source_session_title: 'Src', source_session_agent_name: 'pm',+ id: 'm1',+ created_at: t(1),+ source_session_id: 'ses_src',+ source_session_title: 'Src',+ source_session_agent_name: 'pm',} as unknown as WorkbenchMessage;const [row] = mergeById([live], [enriched]);expect(row.source_session_id).toBe('ses_src');@@ -92,6 +123,26 @@ describe('mergeById', () => {expect(row.source_session_agent_name).toBe('pm');});+ it('fills trigger provenance recovered from a legacy native id', () => {+ const live = {+ id: 'm1',+ created_at: t(1),+ delivered_at: null,+ author_name: null,+ author_id: null,+ } as unknown as WorkbenchMessage;+ const enriched = {+ id: 'm1',+ created_at: t(1),+ delivered_at: null,+ author_name: 'watch',+ author_id: 'def_watch',+ } as unknown as WorkbenchMessage;+ const [row] = mergeById([live], [enriched]);+ expect(row.author_name).toBe('watch');+ expect(row.author_id).toBe('def_watch');+ });+it('does not overwrite an already-resolved source-session id with a null reconcile', () => {const existing = { id: 'm1', created_at: t(1), source_session_id: 'ses_src' } as unknown as WorkbenchMessage;const incoming = { id: 'm1', created_at: t(1), source_session_id: null } as unknown as WorkbenchMessage;diff --git a/ui/src/lib/transcriptOrder.ts b/ui/src/lib/transcriptOrder.tsindex c736fc6b2..6426c1119 100644--- a/ui/src/lib/transcriptOrder.ts+++ b/ui/src/lib/transcriptOrder.ts@@ -17,14 +17,15 @@ export const timestampOrderTimeMs = (timestamp: string): number => {return milliseconds + (microseconds % 1_000) / 1_000;};-/** Best available wall-clock position for a durable transcript row.+/** Best available wall-clock position for a durable message row.*- * Persisted message timestamps are second-resolution. Canonical `msg_` ids add- * a microsecond clock prefix specifically to preserve ordering inside that- * second, so prefer it whenever present and retain `created_at` for imported or- * historical ids.+ * Canonical `msg_` ids recover a microsecond clock for legacy second-resolution+ * rows; imported ids fall back to created_at. Placement helpers outside the+ * transcript use this authored-time position.*/-export const messageOrderTimeMs = (message: Pick<WorkbenchMessage, 'id' | 'created_at'>): number => {+export const messageOrderTimeMs = (+ message: Pick<WorkbenchMessage, 'id' | 'created_at'>,+): number => {const idTime = TIME_SORTABLE_MESSAGE_ID_RE.exec(message.id)?.[1];if (idTime) {const microseconds = Number.parseInt(idTime, 16);@@ -33,21 +34,32 @@ export const messageOrderTimeMs = (message: Pick<WorkbenchMessage, 'id' | 'creatreturn timestampOrderTimeMs(message.created_at);};+/** When the row became part of the visible transcript. */+export const transcriptOrderTimeMs = (+ message: Pick<WorkbenchMessage, 'created_at' | 'delivered_at'>,+): number => timestampOrderTimeMs(message.delivered_at || message.created_at);+// Pure ordering/merge helpers for the chat transcript, kept transport-agnostic-// (they only read ``created_at`` / ``id``) so the ordering contract can be unit-// tested independently of the ChatPage component. The chat keeps its ``messages``-// array sorted in durable (created_at, id) order at all times; these helpers are-// the only things that decide where a row lands.+// so the ordering contract can be unit tested independently of ChatPage. The+// chat keeps its rows sorted by transcript-entry time plus id at all times.-// Durable transcript order: ``created_at`` is second-resolution, so the message-// id (a microsecond-clock prefix, see messages_service._new_message_id) is the-// tie-break — matching the server's ``(created_at, id)`` ordering.+// Durable transcript order matches storage.messages_service: acceptance time+// for queued Deliveries, otherwise microsecond creation time, then id as the+// stable tie-break.export const byCreatedThenId = (a: WorkbenchMessage, b: WorkbenchMessage): number => {- if (a.created_at !== b.created_at) return a.created_at < b.created_at ? -1 : 1;+ const aTime = transcriptOrderTimeMs(a);+ const bTime = transcriptOrderTimeMs(b);+ if (aTime !== bTime) return aTime < bTime ? -1 : 1;if (a.id === b.id) return 0;return a.id < b.id ? -1 : 1;};+/** Whether a newly fetched tail begins strictly after the loaded window. */+export const isTranscriptWindowDisjoint = (+ previousNewest: WorkbenchMessage,+ tailOldest: WorkbenchMessage,+): boolean => byCreatedThenId(tailOldest, previousNewest) > 0;+// Union two row sets, deduped by id and re-sorted into durable order. Used by the// BATCH paths (initial snapshot, reconcile, older-page load), so a fast agent// result that arrives over /api/events *before* its prompt row still lands in the@@ -69,12 +81,23 @@ export const mergeById = (// untouched, and unseen incoming ids are appended as before.const patched = existing.map((m) => {const inc = incomingById.get(m.id);- if (inc && m.source_session_id == null && inc.source_session_id != null) {+ if (+ inc &&+ ((m.source_session_id == null && inc.source_session_id != null) ||+ (m.author_name == null && inc.author_name != null) ||+ (m.author_id == null && inc.author_id != null))+ ) {return {...m,- source_session_id: inc.source_session_id,- source_session_title: inc.source_session_title,- source_session_agent_name: inc.source_session_agent_name,+ ...(m.source_session_id == null && inc.source_session_id != null+ ? {+ source_session_id: inc.source_session_id,+ source_session_title: inc.source_session_title,+ source_session_agent_name: inc.source_session_agent_name,+ }+ : {}),+ ...(m.author_name == null && inc.author_name != null ? { author_name: inc.author_name } : {}),+ ...(m.author_id == null && inc.author_id != null ? { author_id: inc.author_id } : {}),};}return m;