Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(harness): deliver lane callbacks once (#919)

Call White2a8367a80179
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index ea8847dc3..b5461d59a 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -150,8 +150,8 @@ class MessageHandler(BaseHandler):
# Mirror the originating prompt into the workbench messages table
# before we kick off the agent, so the transcript shows the turn
# that produced the reply. Human turns are source='user'; harness
- # turns (scheduled task / watch / webhook) are author='user' but
- # source='harness' so the UI can mark who triggered them. Wrapped in
+ # turns (scheduled task / watch / webhook) use a first-class harness
+ # author/type so they cannot be mistaken for human input. Wrapped in
# try/except inside the helper so a mirror failure can't break the turn.
if source == self.TURN_SOURCE_HUMAN:
from core.message_mirror import mirror_inbound
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 5fd68d83f..79ef771a8 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -995,7 +995,10 @@ class ConsolidatedMessageDispatcher:
if run_terminal_status and self._run_has_blocking_activity(run_id):
defer_terminal = getattr(store, "defer_run_terminal", None)
if callable(defer_terminal):
- defer_kwargs = {"terminal_status": run_terminal_status}
+ defer_kwargs = {
+ "terminal_status": run_terminal_status,
+ "result_text": text,
+ }
if terminal_error is not None:
defer_kwargs["error"] = terminal_error
defer_terminal(run_id, **defer_kwargs)
@@ -1051,23 +1054,6 @@ class ConsolidatedMessageDispatcher:
logger.warning("Failed to inspect owned Activities for Run %s", run_id, exc_info=True)
return True
- def _forward_agent_run_outputs(
- self,
- run_ids: list[str],
- *,
- raise_on_error: bool = False,
- ) -> None:
- service = getattr(self.controller, "scheduled_task_service", None)
- forward = getattr(service, "forward_run_outputs", None)
- if not callable(forward):
- return
- try:
- forward(run_ids)
- except Exception:
- logger.warning("Failed to forward Agent Run outputs for %s", ",".join(run_ids), exc_info=True)
- if raise_on_error:
- raise
-
def _record_agent_run_terminal_result(
self,
context: MessageContext,
@@ -1119,11 +1105,6 @@ class ConsolidatedMessageDispatcher:
finally:
if store is not None:
store.close()
- self._forward_agent_run_outputs(
- run_ids,
- raise_on_error=require_confirmation,
- )
-
def _record_suppressed_agent_run_terminal_result(
self,
context: MessageContext,
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 2d075256f..38484719b 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -349,12 +349,11 @@ def agent_message_exists(context: MessageContext, native_message_id: str | None)
def mirror_harness_inbound(context: MessageContext, text: str) -> None:
"""Record a harness-originated prompt (scheduled task / watch / webhook).
- Harness turns inject a *user-role* prompt into a session that the human
- never typed, so the row is ``author='user'`` (the agent reads it as user
- input) but ``source='harness'`` — the transcript can then mark it as
- triggered by a scheduled task / watch instead of the user. ``author_name``
- carries the trigger kind (scheduled / watch / webhook / ...) and
- ``author_id`` the run-definition id, per the provenance spec.
+ The backend consumes the prompt as turn input, but the persisted row must
+ not claim the human authored it. ``author`` and ``type`` therefore use the
+ first-class harness role while ``source='harness'`` preserves provenance.
+ ``author_name`` carries the trigger kind (scheduled / watch / webhook / ...)
+ and ``author_id`` the run-definition id, per the provenance spec.
Unlike :func:`mirror_inbound` this *does* cover avibe: no REST endpoint
writes the harness prompt, so without this the workbench transcript would
@@ -406,11 +405,11 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:
scope_id=scope_id,
session_id=row_session_id,
platform=context.platform,
- author="user",
+ author="harness",
source="harness",
author_name=trigger_kind,
author_id=definition_id,
- message_type="user",
+ message_type=messages_service.HARNESS_TYPE,
text=text,
native_message_id=context.message_id,
parent_native_message_id=context.thread_id,
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index e00f990e8..83e99244b 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -302,7 +302,6 @@ def enqueue_session_callback(
message: str,
source_actor: str,
parent_run_id: Optional[str] = None,
- output_id: Optional[str] = None,
) -> Optional["TaskExecutionRequest"]:
"""Enqueue a callback turn into an existing agent session — the shared entry used by Agent
Run / watch / scheduled-task callbacks and vault-request auto-resume. Resolves the session's
@@ -334,14 +333,7 @@ def enqueue_session_callback(
source_kind="callback",
source_actor=source_actor,
parent_run_id=parent_run_id,
- metadata={
- key: value
- for key, value in {
- "callback_parent_run_id": parent_run_id,
- "callback_output_id": output_id,
- }.items()
- if value is not None
- },
+ metadata={"callback_parent_run_id": parent_run_id} if parent_run_id else {},
)
@@ -1107,6 +1099,28 @@ class TaskExecutionStore:
return run
return None
+ def find_explicit_session_delivery(
+ self,
+ *,
+ parent_run_id: str,
+ session_id: str,
+ ) -> Optional[dict[str, Any]]:
+ if self._sqlite is not None:
+ return self._sqlite.find_explicit_session_delivery(
+ parent_run_id=parent_run_id,
+ session_id=session_id,
+ )
+ for run in self._list_file_runs():
+ if (
+ run.get("request_type") == "agent_run"
+ and run.get("source_kind") == "agent"
+ and run.get("parent_run_id") == parent_run_id
+ and run.get("session_id") == session_id
+ and str(run.get("message") or "").strip()
+ ):
+ return run
+ return None
+
def settle_deferred_run(
self,
run_id: str,
@@ -1128,6 +1142,7 @@ class TaskExecutionStore:
*,
terminal_status: str,
error: Optional[str] = None,
+ result_text: Optional[str] = None,
) -> bool:
if self._sqlite is None:
return False
@@ -1135,6 +1150,7 @@ class TaskExecutionStore:
run_id,
terminal_status=terminal_status,
error=error,
+ result_text=result_text,
)
def update_callback_status(
@@ -2032,43 +2048,6 @@ class ScheduledTaskService:
self.request_store.update_callback_status(run_id, status="sent", callback_run_id=callback_run.id)
self._drain_dirty = True
- @staticmethod
- def _structured_run_outputs(run: dict[str, Any]) -> list[dict[str, Any]]:
- payload = run.get("result_payload")
- outputs = payload.get("outputs") if isinstance(payload, dict) else None
- if not isinstance(outputs, list):
- return []
- return [dict(item) for item in outputs if isinstance(item, dict)]
-
- def forward_run_outputs(self, run_ids: list[str]) -> list[TaskExecutionRequest]:
- """Forward every newly recorded output under the parent Run's callback policy."""
-
- callbacks: list[TaskExecutionRequest] = []
- for run_id in dict.fromkeys(str(value or "").strip() for value in run_ids):
- if not run_id:
- continue
- run = self.request_store.get_run(run_id)
- if not run or not str(run.get("callback_session_id") or "").strip():
- continue
- for output in self._structured_run_outputs(run):
- output_id = str(output.get("id") or "").strip()
- message = str(output.get("text") or "").strip()
- if not output_id or not message:
- continue
- source_actor = f"{run_id}:output:{output_id}"
- callback = enqueue_session_callback(
- self.request_store,
- session_id=str(run["callback_session_id"]),
- message=message,
- source_actor=source_actor,
- parent_run_id=run_id,
- output_id=output_id,
- )
- if callback is not None:
- callbacks.append(callback)
- self._drain_dirty = True
- return callbacks
-
def settle_activity_runs(self, activity: Any) -> list[str]:
"""Settle deferred Runs when a failed/stopped owned Activity is last."""
@@ -2184,7 +2163,15 @@ class ScheduledTaskService:
if not callback_session_id:
return None
run_id = str(run.get("id") or "")
- output_callbacks = self.forward_run_outputs([run_id])
+ explicit_delivery = self.request_store.find_explicit_session_delivery(
+ parent_run_id=run_id,
+ session_id=callback_session_id,
+ )
+ if explicit_delivery is not None:
+ # A lane may explicitly report to its callback Session before its
+ # terminal result. That accepted child Run is the callback delivery;
+ # do not echo the same final through the automatic fallback too.
+ return TaskExecutionRequest.from_dict(explicit_delivery)
status = _normalize_requested_run_status(run.get("status")) or str(
run.get("status") or ""
)
@@ -2199,8 +2186,6 @@ class ScheduledTaskService:
)
if terminal_callback is not None:
return terminal_callback
- if output_callbacks:
- return output_callbacks[-1]
return enqueue_session_callback(
self.request_store,
session_id=callback_session_id,
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index 56e436d1c..7ae3a69e4 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -16,11 +16,13 @@ from typing import Any, Optional
from config import paths
from core.backend_failure import BACKEND_FAILURE_EVENT, is_backend_failure_notification
from vibe.i18n import t
+from vibe.message_identity import INPUT_TURN_AUTHOR_TYPES, is_input_turn
TRIM_LATEST_RUNNING_TURN_BACKENDS = {"codex", "opencode"}
TERMINAL_AGENT_OUTPUT_TYPES = {"result", "error"}
SOURCE_PROGRESS_AGENT_OUTPUT_TYPES = {"assistant", *TERMINAL_AGENT_OUTPUT_TYPES}
ACTIVE_SOURCE_RUN_STATUSES = ("pending", "queued", "processing", "running")
+INPUT_TURN_MESSAGE_TYPES = tuple(message_type for _, message_type in INPUT_TURN_AUTHOR_TYPES)
class SessionForkError(ValueError):
@@ -79,7 +81,7 @@ class ForkSourceState:
latest_after_anchor_type: Optional[str] = None
has_messages_after_anchor: bool = False
has_terminal_agent_output_after_anchor: bool = False
- has_user_turn_after_anchor: bool = False
+ has_input_turn_after_anchor: bool = False
anchor_is_backend_failure: bool = False
@property
@@ -96,8 +98,8 @@ class SourceMessageAnchor:
message_type: Optional[str] = None
@property
- def is_running_user_turn(self) -> bool:
- return self.author == "user" and self.message_type == "user"
+ def is_running_input_turn(self) -> bool:
+ return is_input_turn(self.author, self.message_type)
def reserve_forked_session(
@@ -154,7 +156,7 @@ def reserve_forked_session(
)
source_anchor = _latest_source_message_anchor(conn, str(row["id"]))
source_has_active_run = _source_has_active_agent_run(conn, str(row["id"]))
- inferred_running_turn = source_anchor.is_running_user_turn or (
+ inferred_running_turn = source_anchor.is_running_input_turn or (
source_backend == "opencode"
and source_has_active_run
)
@@ -173,7 +175,7 @@ def reserve_forked_session(
if fork_point is not None:
opencode_fork_message_id, opencode_fork_empty_history = fork_point
opencode_boundary_from_active_run = bool(
- source_has_active_run and not source_anchor.is_running_user_turn
+ source_has_active_run and not source_anchor.is_running_input_turn
)
effective_native_turn_started = True
source_message_id = source_anchor.message_id
@@ -426,7 +428,9 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
.where(
messages.c.session_id == source_session_id,
or_(
- messages.c.type.in_(["user", *list(SOURCE_PROGRESS_AGENT_OUTPUT_TYPES)]),
+ messages.c.type.in_(
+ [*INPUT_TURN_MESSAGE_TYPES, *list(SOURCE_PROGRESS_AGENT_OUTPUT_TYPES)]
+ ),
and_(
messages.c.type == "notify",
func.json_extract(messages.c.metadata_json, "$.event")
@@ -457,13 +461,17 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
)
)
)
- has_user_turn_after_anchor = (
+ has_input_turn_after_anchor = (
conn.execute(
select(messages.c.id)
.where(
messages.c.session_id == source_session_id,
- messages.c.author == "user",
- messages.c.type == "user",
+ or_(
+ *(
+ and_(messages.c.author == author, messages.c.type == message_type)
+ for author, message_type in INPUT_TURN_AUTHOR_TYPES
+ )
+ ),
after_anchor,
)
.limit(1)
@@ -477,7 +485,7 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
latest_after_anchor_type=latest_after_anchor_type or None,
has_messages_after_anchor=latest_after_anchor is not None,
has_terminal_agent_output_after_anchor=has_terminal_agent_output_after_anchor,
- has_user_turn_after_anchor=has_user_turn_after_anchor,
+ has_input_turn_after_anchor=has_input_turn_after_anchor,
anchor_is_backend_failure=is_backend_failure_notification(
anchor["type"],
_load_metadata(anchor["metadata_json"]),
diff --git a/core/show_git.py b/core/show_git.py
index f733b318d..83d5dc533 100644
--- a/core/show_git.py
+++ b/core/show_git.py
@@ -16,6 +16,7 @@ from typing import Any
from config import paths
from core.git_binary import ResolvedGit, resolve_git
+from vibe.message_identity import HARNESS_TYPE
logger = logging.getLogger(__name__)
@@ -278,13 +279,13 @@ def load_turn_checkpoint_context(session_id: str, *, after: str | None = None) -
)
else:
message_query = (
- message_query.where(messages.c.type.in_(("user", "pending")))
+ message_query.where(messages.c.type.in_(("user", "pending", HARNESS_TYPE)))
.where(messages.c.created_at >= after)
.order_by(messages.c.created_at.asc(), messages.c.id.asc())
.limit(1)
)
message_row = conn.execute(message_query).first()
- if message_row is None or message_row.type not in {"user", "pending"}:
+ if message_row is None or message_row.type not in {"user", "pending", HARNESS_TYPE}:
return TurnCheckpointContext()
return TurnCheckpointContext(
message=_read_message_text(message_row.content_text, message_row.content_json),
diff --git a/docs/plans/full-duplex-sessions.md b/docs/plans/full-duplex-sessions.md
index 2bd443770..7e9bc9dc1 100644
--- a/docs/plans/full-duplex-sessions.md
+++ b/docs/plans/full-duplex-sessions.md
@@ -81,7 +81,8 @@ read-only compatibility alias for older clients, not the Session state model.
### Run outputs and callbacks
-The existing `agent_runs.result_payload_json` stores an idempotent output ledger:
+The existing `agent_runs.result_payload_json` stores an idempotent output ledger,
+while `agent_runs.result_text` stores only the terminal result:
```json
{
@@ -97,15 +98,19 @@ The existing `agent_runs.result_payload_json` stores an idempotent output ledger
}
```
-No visible wrapper text is added. Each new output can enqueue one callback turn
-immediately. Callback turns are deduplicated by structured Run lineage. Parent
-`callback_status` stays pending while the parent Run is active and settles once
-after the parent reaches its one idempotent terminal transition.
+No visible wrapper text is added. Intermediate output remains in the ledger and
+the originating Session; it does not enqueue callback work. After the parent Run
+reaches its one idempotent terminal transition, callback policy enqueues exactly
+one turn containing the terminal `result_text`. Callback turns are deduplicated
+by Run lineage. An explicit child Agent Run delivered to the callback Session
+satisfies that policy, so the automatic fallback does not echo the same report.
+Parent `callback_status` stays pending while the parent Run is active and settles
+once against that single delivery.
-If a Run fails or is canceled after forwarding partial outputs, its callback
-Session receives one additional terminal failure/cancellation Message. A
-successful Run with streamed outputs does not repeat them in a synthetic final
-summary.
+If a Run fails or is canceled after recording partial outputs, its callback
+Session receives one terminal failure/cancellation Message. A successful Run
+receives one terminal result Message; prior Activity or progress output is not
+copied into the callback Session.
A terminal Run intent is retained in `result_payload_json` while a non-detached
owned Activity remains active. A later Activity output can complete that Run
@@ -162,8 +167,8 @@ only that Turn, while the retry retains Run-completion authority. Recovered
terminal Activities wait behind any output still owed by the same Run. Output
containing only `<silent>` directives uses the same silent Run-settlement path
as an empty summary. Activity output follows a durable handoff order: persist the
-Outbox snapshot, deliver and persist the Message, settle the Run and its callback
-outputs, then delete the snapshot. A failed snapshot write, Run write, or delete
+Outbox snapshot, deliver and persist the Message, settle the Run and its callback,
+then delete the snapshot. A failed snapshot write, Run write, or delete
keeps the Activity active, queued, or claimed for an idempotent retry.
## Other backend protocol disposition
@@ -203,8 +208,8 @@ lifecycle.
newer Turn remains active.
- `MESSAGE-DELIVERY-004`: one Turn emits multiple output Messages and completes
once.
-- `MESSAGE-DELIVERY-005`: one Run forwards multiple callback outputs and reaches
- one idempotent terminal transition.
+- `MESSAGE-DELIVERY-005`: one Run retains multiple structured outputs, reaches
+ one idempotent terminal transition, and sends one terminal callback.
Focused unit/contract tests cover Activity transitions, restart recovery,
summary and no-summary policies, state-axis projection, structured provenance,
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 8c1587805..d4caf4f2a 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -33,6 +33,7 @@ from modules.agents.codex.session import CodexSessionManager
from modules.agents.codex.transport import CodexTransport
from modules.agents.codex.turn_state import CodexTurnRegistry
from vibe.codex_config import LEGACY_MANAGED_PROVIDER_IDS, MANAGED_PROVIDER_ID
+from vibe.message_identity import is_input_turn
logger = logging.getLogger(__name__)
@@ -927,13 +928,13 @@ class CodexAgent(BaseAgent):
source_state = fork_source_state(fork)
if source_state.anchor_is_terminal_agent_output:
return False
- anchor_is_running_user = (
- getattr(source_state, "anchor_author", None) == "user"
- and getattr(source_state, "anchor_type", None) == "user"
+ anchor_is_running_input = is_input_turn(
+ getattr(source_state, "anchor_author", None),
+ getattr(source_state, "anchor_type", None),
)
- if getattr(source_state, "has_user_turn_after_anchor", False):
+ if getattr(source_state, "has_input_turn_after_anchor", False):
return False
- if anchor_is_running_user:
+ if anchor_is_running_input:
if source_state.has_messages_after_anchor:
return True
if bool(fork.get("native_turn_started")):
diff --git a/modules/agents/opencode/session.py b/modules/agents/opencode/session.py
index 5df89c199..cbfc4282d 100644
--- a/modules/agents/opencode/session.py
+++ b/modules/agents/opencode/session.py
@@ -15,6 +15,7 @@ from typing import Dict, Optional, Tuple
from core.services.session_fork import fork_source_state, pending_native_fork
from modules.agents.native_sessions.opencode import OpenCodeNativeSessionProvider
from modules.agents.base import AgentRequest, BaseAgent
+from vibe.message_identity import is_input_turn
from .server import OpenCodeServerManager
@@ -117,9 +118,9 @@ class OpenCodeSessionManager:
if bool(fork.get("opencode_boundary_from_active_run")):
return True, message_id
source_state = fork_source_state(fork)
- anchor_is_running_user = (
- getattr(source_state, "anchor_author", None) == "user"
- and getattr(source_state, "anchor_type", None) == "user"
+ anchor_is_running_input = is_input_turn(
+ getattr(source_state, "anchor_author", None),
+ getattr(source_state, "anchor_type", None),
)
if source_state.anchor_is_terminal_agent_output:
logger.info(
@@ -127,13 +128,13 @@ class OpenCodeSessionManager:
source_session_id,
)
return True, None
- if source_state.has_terminal_agent_output_after_anchor and not anchor_is_running_user:
+ if source_state.has_terminal_agent_output_after_anchor and not anchor_is_running_input:
logger.info(
"OpenCode running fork for %s kept full history because the source completed before first use",
source_session_id,
)
return True, None
- if getattr(source_state, "has_messages_after_anchor", False) and not anchor_is_running_user:
+ if getattr(source_state, "has_messages_after_anchor", False) and not anchor_is_running_input:
point = self._current_running_fork_point(source_session_id)
if point.available:
return True, point.message_id
diff --git a/storage/alembic/versions/20260716_0030_harness_input_index.py b/storage/alembic/versions/20260716_0030_harness_input_index.py
new file mode 100644
index 000000000..66d8544f1
--- /dev/null
+++ b/storage/alembic/versions/20260716_0030_harness_input_index.py
@@ -0,0 +1,42 @@
+"""index human and harness inbox inputs
+
+Revision ID: 20260716_0030
+Revises: 20260707_0029
+Create Date: 2026-07-16
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20260716_0030"
+down_revision = "20260707_0029"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ bind.exec_driver_sql(
+ "update messages set author = 'harness', type = 'harness' "
+ "where source = 'harness' and author = 'user' and type = 'user'"
+ )
+ 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 = 'user') or "
+ "(author = 'harness' and type = 'harness'))"
+ )
+
+
+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', 'harness_dedupe')"
+ )
diff --git a/storage/background.py b/storage/background.py
index 5d1484b56..d1c1786f5 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -1278,12 +1278,14 @@ class SQLiteBackgroundTaskStore:
payload_changed = False
effective_terminal_status = terminal_status
effective_terminal_error = error
+ deferred_result_text = None
if terminal_status and "deferred_terminal_status" in result_payload:
effective_terminal_status = _stronger_terminal_status(
result_payload.pop("deferred_terminal_status", None),
terminal_status,
)
deferred_error = result_payload.pop("deferred_terminal_error", None)
+ deferred_result_text = result_payload.pop("deferred_terminal_result_text", None)
if deferred_error is not None:
effective_terminal_error = str(deferred_error)
payload_changed = True
@@ -1306,11 +1308,6 @@ class SQLiteBackgroundTaskStore:
recorded = True
payload_changed = True
- existing_text = str(row["result_text"] or "")
- if recorded:
- result_text = f"{existing_text}\n\n{visible_text}" if existing_text else visible_text
- else:
- result_text = existing_text
message_ids = _json_loads(row["message_ids_json"], [])
if not isinstance(message_ids, list):
message_ids = []
@@ -1323,18 +1320,23 @@ class SQLiteBackgroundTaskStore:
"updated_at": now,
}
if recorded:
- values.update(
- result_text=result_text,
- message_ids_json=_json_dumps(message_ids),
- )
+ values["message_ids_json"] = _json_dumps(message_ids)
conn.execute(
update(agent_runs)
.where(agent_runs.c.id == run_id)
.values(**values)
)
if effective_terminal_status:
+ terminal_result_text = (
+ str(deferred_result_text)
+ if deferred_result_text is not None
+ else visible_text
+ )
terminal_values: dict[str, Any] = {
"status": normalize_run_status(effective_terminal_status),
+ # Structured outputs remain available in result_payload, but
+ # result_text is the one terminal result used by callbacks.
+ "result_text": terminal_result_text,
"completed_at": now,
"updated_at": now,
}
@@ -1375,9 +1377,10 @@ class SQLiteBackgroundTaskStore:
*,
terminal_status: str,
error: Optional[str] = None,
+ result_text: Optional[str] = None,
updated_at: Optional[str] = None,
) -> bool:
- """Remember a terminal intent and diagnostic while an Activity blocks it."""
+ """Remember a terminal intent and result while an Activity blocks it."""
now = updated_at or _utc_now_iso()
row_to_publish = None
@@ -1404,11 +1407,18 @@ class SQLiteBackgroundTaskStore:
error_text is not None
and not result_payload.get("deferred_terminal_error")
)
- if not status_changed and not error_changed:
+ deferred_result_text = str(result_text) if result_text is not None else None
+ result_text_changed = bool(
+ deferred_result_text is not None
+ and result_payload.get("deferred_terminal_result_text") != deferred_result_text
+ )
+ if not status_changed and not error_changed and not result_text_changed:
return False
result_payload["deferred_terminal_status"] = normalized
if error_changed:
result_payload["deferred_terminal_error"] = error_text
+ if result_text_changed:
+ result_payload["deferred_terminal_result_text"] = deferred_result_text
conn.execute(
update(agent_runs)
.where(agent_runs.c.id == run_id)
@@ -1452,6 +1462,7 @@ class SQLiteBackgroundTaskStore:
return False
result_payload.pop("deferred_terminal_status", None)
deferred_error = result_payload.pop("deferred_terminal_error", None)
+ deferred_result_text = result_payload.pop("deferred_terminal_result_text", None)
status = (
_stronger_terminal_status(deferred_status, terminal_status)
if terminal_status
@@ -1466,6 +1477,8 @@ class SQLiteBackgroundTaskStore:
effective_error = deferred_error if deferred_error is not None else error
if effective_error is not None:
values["error"] = str(effective_error)
+ if deferred_result_text is not None:
+ values["result_text"] = str(deferred_result_text)
transition = conn.execute(
update(agent_runs)
.where(agent_runs.c.id == run_id)
@@ -1493,7 +1506,7 @@ class SQLiteBackgroundTaskStore:
parent_run_id: str,
source_actor: str,
) -> Optional[dict[str, Any]]:
- """Return the callback Run for one structured parent-output identity."""
+ """Return the callback Run for one parent callback identity."""
with self.engine.connect() as conn:
row = conn.execute(
@@ -1507,6 +1520,28 @@ class SQLiteBackgroundTaskStore:
).mappings().first()
return self._run_from_row(row) if row else None
+ def find_explicit_session_delivery(
+ self,
+ *,
+ parent_run_id: str,
+ session_id: str,
+ ) -> Optional[dict[str, Any]]:
+ """Return a child Agent Run explicitly delivered to the callback Session."""
+
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.run_type == "agent_run")
+ .where(agent_runs.c.source_kind == "agent")
+ .where(agent_runs.c.parent_run_id == parent_run_id)
+ .where(agent_runs.c.session_id == session_id)
+ .where(agent_runs.c.message.is_not(None))
+ .where(func.length(func.trim(agent_runs.c.message)) > 0)
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ .limit(1)
+ ).mappings().first()
+ return self._run_from_row(row) if row else None
+
def recover_processing_runs(self) -> None:
with run_update_event_transaction(self.engine) as conn:
now = _utc_now_iso()
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 3ecc43911..8d3e9e487 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -22,6 +22,7 @@ from sqlalchemy.engine import Connection
from storage.db import escape_sql_like
from storage.models import agent_sessions, messages, scope_settings, scopes
+from vibe.message_identity import HARNESS_TYPE, INPUT_TURN_AUTHOR_TYPES
def _utc_now_iso() -> str:
@@ -129,17 +130,17 @@ def search_messages(
*,
query: str,
platform: str = "avibe",
- types: Iterable[str] = ("user", "result"),
+ types: Optional[Iterable[str]] = None,
limit: int = 50,
) -> dict[str, Any]:
"""Global message-content search, grouped by session.
Substring (case-insensitive) ``LIKE`` over ``messages.content_text``, scoped
to one ``platform`` (Workbench = ``avibe``) and a set of transcript-visible
- ``types`` (the user's prompts + the agent's rendered ``result`` replies — both
- land on a message the chat actually renders, so a clicked result is always
- jumpable). Archived sessions are excluded, as are messages under an archived
- PROJECT — ``projects_service.archive_project`` disables a project by setting
+ ``types`` (human prompts + harness prompts + the agent's rendered ``result``
+ replies — all land on a message the chat actually renders, so a clicked result
+ is always jumpable). Archived sessions are excluded, as are messages under an
+ archived PROJECT — ``projects_service.archive_project`` disables a project by setting
``scope_settings.enabled = 0`` (its sessions stay ``active``), so the scope's
disabled state is the authoritative "archived project" signal here. A scope
with no ``scope_settings`` row is treated as enabled (legacy / folder-less
@@ -160,7 +161,7 @@ def search_messages(
return {"sessions": [], "total": 0, "session_count": 0}
like = escape_sql_like(cleaned)
- type_list = list(types)
+ type_list = list(types if types is not None else ("user", HARNESS_TYPE, "result"))
effective_limit = min(max(int(limit), 1), 200)
stmt = (
@@ -268,6 +269,9 @@ def append(
# must be ``user`` (not ``assistant``), or the user+result transcript filter
# would drop it. Typed callers (inbox/IM mirror) pass message_type explicitly.
resolved_type = message_type or ("user" if author == "user" else "assistant")
+ if source == HARNESS_TYPE and author == "user" and resolved_type == "user":
+ author = HARNESS_TYPE
+ resolved_type = HARNESS_TYPE
now = _utc_now_iso()
payload = {
@@ -578,13 +582,14 @@ NON_CONVERSATION_TYPES = (QUEUED_TYPE, DRAFT_TYPE, PENDING_TYPE, HARNESS_DEDUPE_
# history fetch (``list_session_messages``) AND the live ``message.new`` publish
# gate, so what a page loads and what it receives over the stream are identical.
# Excludes the agent's process log (``assistant`` / ``tool_call``) and ``system``
-# (which isn't persisted at all). Harness-triggered prompts are ``user``, so they
-# are included. ``show_page`` transcript marks are kept via a metadata-source
+# (which isn't persisted at all). Harness-triggered prompts have their own type
+# so they cannot be mistaken for human input. ``show_page`` transcript marks are
+# kept via a metadata-source
# override in the fetch even though their row type is ``assistant``. ``error`` is a
# terminal FAILED result (turned the dot red): shown in the conversation like any
# terminal message, but the unread queries below stay ``result``-only so a failure
# is not counted as an unread agent reply.
-TRANSCRIPT_TYPES = ("user", "result", "notify", "error")
+TRANSCRIPT_TYPES = ("user", HARNESS_TYPE, "result", "notify", "error")
def enqueue_queued(
@@ -857,9 +862,9 @@ def list_inbox_sessions(
session's most recent message of *any* author (the activity clock),
descending. The preview text is the session's latest *agent* reply
(distinct from the sort key). ``replied`` is True when the session is
- *awaiting the agent* — the user's latest message is newer than the agent's
- latest reply — so it stays set for the whole time the agent is working and
- survives a reload, clearing only once the agent replies.
+ *awaiting the agent* — the latest human or harness input is newer than the
+ agent's latest reply — so it stays set for the whole time the agent is
+ working and survives a reload, clearing only once the agent replies.
Keyset pagination via ``before`` (an opaque ``"<last_activity_at>|<session_id>"``
cursor returned as ``next_cursor``).
@@ -871,6 +876,7 @@ def list_inbox_sessions(
author: Optional[str] = None,
types: Optional[tuple[str, ...]] = None,
conversation_only: bool = False,
+ input_turn_only: bool = False,
) -> Any:
msg = messages.alias()
query = (
@@ -886,6 +892,15 @@ def list_inbox_sessions(
query = query.where(msg.c.author == author)
if types is not None:
query = query.where(msg.c.type.in_(types))
+ if input_turn_only:
+ query = query.where(
+ or_(
+ *(
+ and_(msg.c.author == input_author, msg.c.type == input_type)
+ for input_author, input_type in INPUT_TURN_AUTHOR_TYPES
+ )
+ )
+ )
if conversation_only:
query = query.where(msg.c.type.notin_(NON_CONVERSATION_TYPES))
return query.scalar_subquery()
@@ -897,8 +912,10 @@ def list_inbox_sessions(
last_author = _latest_message_value("author", conversation_only=True)
preview_id = _latest_message_value("id", types=("result", "notify", "error"))
preview_at = _latest_message_value("created_at", types=("result", "notify", "error"))
- last_user_at = _latest_message_value("created_at", author="user", conversation_only=True)
- last_user_id = _latest_message_value("id", author="user", conversation_only=True)
+ last_input_at = _latest_message_value(
+ "created_at", conversation_only=True, input_turn_only=True
+ )
+ last_input_id = _latest_message_value("id", conversation_only=True, input_turn_only=True)
# Unread agent messages per session.
m = messages
@@ -927,8 +944,8 @@ def list_inbox_sessions(
unread_count_col,
preview_id.label("preview_id"),
preview_at.label("preview_at"),
- last_user_at.label("last_user_at"),
- last_user_id.label("last_user_id"),
+ last_input_at.label("last_input_at"),
+ last_input_id.label("last_input_id"),
)
.select_from(
agent_sessions.join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True).join(
@@ -984,23 +1001,23 @@ def list_inbox_sessions(
except json.JSONDecodeError:
preview = ""
unread = int(row["unread_count"] or 0)
- # Awaiting the agent: the user's latest message is newer than the agent's
- # latest reply. Persistent across a reload and stays set for the whole
- # agent turn, unlike a "last author == user" check. ``created_at`` is
+ # 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.
- last_user_at = row["last_user_at"]
- last_user_id = row["last_user_id"]
+ last_input_at = row["last_input_at"]
+ last_input_id = row["last_input_id"]
preview_at = row["preview_at"]
preview_id = row["preview_id"]
awaiting_reply = bool(
- last_user_at is not None
+ last_input_at is not None
and preview_at is not None
and (
- last_user_at > preview_at
- or (last_user_at == preview_at and (last_user_id or "") > (preview_id or ""))
+ last_input_at > preview_at
+ or (last_input_at == preview_at and (last_input_id or "") > (preview_id or ""))
)
)
sessions.append(
diff --git a/storage/migrations.py b/storage/migrations.py
index 77795c956..269d462d6 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -629,7 +629,9 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -
conn.execute(
"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')"
+ "where session_id is not null and "
+ "((author = 'user' and type = 'user') or "
+ "(author = 'harness' and type = 'harness'))"
)
diff --git a/storage/models.py b/storage/models.py
index c0435f6b4..ec11af715 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -338,10 +338,11 @@ messages = Table(
Column("type", String, nullable=False, server_default="assistant"),
Column("author_id", String, nullable=True),
Column("author_name", Text, nullable=True),
- # Origin of the message (user / agent / harness), distinct from the coarse
- # ``author`` role — a Harness-triggered prompt is author='user' but
- # source='harness'. ``author_name`` holds the display name (username /
- # agent_name / task|watch), ``author_id`` the precise id.
+ # Origin of the message (user / agent / harness), distinct from authorship.
+ # Harness-triggered prompts use author/type/source='harness' so no automated
+ # input can be represented as human-authored. ``author_name`` holds the
+ # display name (username / agent_name / task|watch), ``author_id`` the precise
+ # id.
Column("source", String, nullable=True),
Column("native_message_id", String, nullable=True),
Column("parent_native_message_id", String, nullable=True),
@@ -382,7 +383,8 @@ messages = Table(
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', 'harness_dedupe')"
+ "session_id is not null and ((author = 'user' and type = 'user') "
+ "or (author = 'harness' and type = 'harness'))"
),
),
Index("ix_messages_scope_created", "scope_id", "created_at"),
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index df0e1e957..bacacfdc0 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -38,11 +38,11 @@ scenarios:
layer: scenario
test: tests/scenarios/message_delivery/test_message_delivery_scenarios.py::MessageDeliveryScenarioTests::test_one_turn_multiple_outputs_scenario_completes_once
- id: MESSAGE-DELIVERY-005
- name: One Run forwards multiple callback outputs and completes once
+ name: One Run retains multiple outputs but callbacks only its terminal result once
status: covered
kind: lifecycle
layer: contract
- test: tests/test_scheduled_tasks.py::test_agent_run_forwards_multiple_outputs_and_completes_once
+ test: tests/test_scheduled_tasks.py::test_agent_run_keeps_output_ledger_but_callbacks_only_terminal_result
- id: MESSAGE-DELIVERY-006
name: Every turn entry point reaches Show checkpoint lifecycle
status: covered
diff --git a/tests/scenarios/message_delivery/observations.yaml b/tests/scenarios/message_delivery/observations.yaml
index f43e64262..4dd5e7716 100644
--- a/tests/scenarios/message_delivery/observations.yaml
+++ b/tests/scenarios/message_delivery/observations.yaml
@@ -1,3 +1,15 @@
version: 1
capability: message_delivery
-observations: []
+observations:
+ - id: OBS-MESSAGE-DELIVERY-001
+ source: live_local_diagnosis
+ related_scenarios:
+ - MESSAGE-DELIVERY-005
+ summary: Structured Run output fan-out injected Activity summaries and duplicate finals into the callback Session.
+ previous_assumption: Every user-visible full-duplex Run output should become its own callback turn.
+ observed_behavior: Callback Sessions received Claude Activity labels, command fragments, and both explicit and automatic copies of the final report.
+ required_updates:
+ - retain intermediate outputs only in the Run output ledger and originating Session
+ - keep result_text terminal-only and enqueue one terminal callback
+ - treat an explicit child delivery to the callback Session as satisfying the automatic callback
+ - persist harness-originated prompts with a non-user author and message type
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 85aa2f768..3ddf2e48b 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -2153,7 +2153,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
latest_after_anchor_type="result",
has_messages_after_anchor=True,
has_terminal_agent_output_after_anchor=True,
- has_user_turn_after_anchor=False,
+ has_input_turn_after_anchor=False,
),
):
thread_id = await agent._start_or_resume_thread(transport, request)
@@ -2220,7 +2220,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
latest_after_anchor_type="user",
has_messages_after_anchor=True,
has_terminal_agent_output_after_anchor=False,
- has_user_turn_after_anchor=True,
+ has_input_turn_after_anchor=True,
),
):
thread_id = await agent._start_or_resume_thread(transport, request)
@@ -2231,6 +2231,31 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
"thread/inject_items",
])
+ async def test_should_roll_back_forked_running_harness_turn(self):
+ agent = object.__new__(CodexAgent)
+ fork = {
+ "source_session_id": "ses-source",
+ "source_message_id": "msg-harness",
+ "trim_latest_running_turn": True,
+ "native_turn_started": True,
+ }
+
+ with patch.object(
+ _MODULE,
+ "fork_source_state",
+ return_value=SimpleNamespace(
+ anchor_author="harness",
+ anchor_type="harness",
+ anchor_is_terminal_agent_output=False,
+ has_messages_after_anchor=True,
+ has_terminal_agent_output_after_anchor=False,
+ has_input_turn_after_anchor=False,
+ ),
+ ):
+ should_rollback = await agent._should_rollback_forked_running_turn(fork)
+
+ self.assertTrue(should_rollback)
+
async def test_start_or_resume_thread_does_not_roll_back_user_anchor_before_native_start(self):
agent = object.__new__(CodexAgent)
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index 21ec87624..1d47d4c49 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -293,7 +293,11 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
(
"defer",
"run-failed",
- {"terminal_status": "failed", "error": "provider unavailable"},
+ {
+ "terminal_status": "failed",
+ "result_text": "",
+ "error": "provider unavailable",
+ },
),
)
self.assertEqual(calls[1][0:2], ("output", "run-failed"))
@@ -530,8 +534,8 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
def get_run(self, run_id):
return {"status": "running"}
- def defer_run_terminal(self, run_id, *, terminal_status):
- calls.append(("defer", run_id, terminal_status))
+ def defer_run_terminal(self, run_id, *, terminal_status, result_text):
+ calls.append(("defer", run_id, terminal_status, result_text))
def record_run_output(self, run_id, **kwargs):
calls.append(("output", run_id, kwargs["output_id"], kwargs["terminal_status"]))
@@ -571,7 +575,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(
calls,
[
- ("defer", "run-owned", "succeeded"),
+ ("defer", "run-owned", "succeeded", "started background work"),
("output", "run-owned", "output-1", None),
("output", "run-owned", "output-2", "succeeded"),
],
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index 3e9983d59..8bc62a9fb 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -597,9 +597,9 @@ def test_persist_agent_sets_source_and_agent_name(isolated_state):
def test_harness_inbound_avibe_session_scoped(isolated_state):
- """A scheduled/watch turn on an avibe session lands an author='user',
- source='harness' row attributed to the session — with author_name = the
- trigger kind and author_id = the run-definition id (the provenance spec).
+ """A scheduled/watch turn on an avibe session lands an author/type='harness'
+ row attributed to the session — with author_name = the trigger kind and
+ author_id = the run-definition id (the provenance spec).
No REST endpoint writes this, so the mirror must cover avibe here."""
engine = create_sqlite_engine()
now = "2026-05-30T12:00:00Z"
@@ -640,11 +640,11 @@ def test_harness_inbound_avibe_session_scoped(isolated_state):
select(messages).where(messages.c.session_id == "ses_harness")
).mappings().first()
assert row is not None
- assert row["author"] == "user" # agent reads it as user input
- assert row["source"] == "harness" # but origin is the harness
+ assert row["author"] == "harness"
+ assert row["source"] == "harness"
assert row["author_name"] == "watch"
assert row["author_id"] == "def_42"
- assert row["type"] == "user"
+ assert row["type"] == "harness"
assert row["content_text"] == "the watched condition fired"
@@ -669,7 +669,8 @@ def test_harness_inbound_im_scope_keyed(isolated_state):
with engine.connect() as conn:
row = conn.execute(select(messages).where(messages.c.platform == "slack")).mappings().first()
assert row["source"] == "harness"
- assert row["author"] == "user"
+ assert row["author"] == "harness"
+ assert row["type"] == "harness"
assert row["author_name"] == "scheduled"
assert row["author_id"] == "def_7"
assert row["session_id"] is None
@@ -725,6 +726,8 @@ def test_harness_inbound_avibe_publishes_message_new(isolated_state):
assert event_type == "message.new"
assert data["session_id"] == "ses_hp"
assert data["source"] == "harness"
+ assert data["author"] == "harness"
+ assert data["type"] == "harness"
assert data["author_name"] == "scheduled"
assert data["text"] == "nightly digest"
diff --git a/tests/test_message_search.py b/tests/test_message_search.py
index 2f00fa664..10dcbba2e 100644
--- a/tests/test_message_search.py
+++ b/tests/test_message_search.py
@@ -151,6 +151,33 @@ def test_search_finds_cjk_term(isolated_state):
assert match["snippet"]["match"] == "部署"
+def test_search_finds_harness_prompt_by_default(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_harness", "Automated")
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_harness",
+ "harness",
+ "inspect callback delivery",
+ "2026-06-01T10:00:00Z",
+ msg_type=messages_service.HARNESS_TYPE,
+ source="harness",
+ )
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="callback")
+
+ match = result["sessions"][0]["matches"][0]
+ assert (match["author"], match["source"], match["type"]) == (
+ "harness",
+ "harness",
+ messages_service.HARNESS_TYPE,
+ )
+
+
def test_search_excludes_im_platform_rows(isolated_state):
"""A ``result`` row on a non-avibe (IM) platform is excluded for the default
platform='avibe' search — search is Workbench-scoped."""
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index 83a49acdd..757e89085 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -254,6 +254,63 @@ def test_error_terminal_in_transcript_but_not_unread(isolated_state):
assert unread.get(scope_id, 0) == 0
+def test_harness_prompt_is_visible_but_not_treated_as_user_text(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_harness")
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_harness",
+ "harness",
+ "scheduled input",
+ "2026-05-30T10:00:00Z",
+ msg_type=messages_service.HARNESS_TYPE,
+ )
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_harness",
+ "user",
+ "human input",
+ "2026-05-30T10:00:01Z",
+ msg_type="user",
+ )
+
+ with engine.connect() as conn:
+ transcript = messages_service.list_session_messages(
+ conn,
+ session_id="ses_harness",
+ types=messages_service.TRANSCRIPT_TYPES,
+ )
+ first_user = messages_service.first_user_text(conn, "ses_harness")
+
+ assert [message["type"] for message in transcript["messages"]] == ["harness", "user"]
+ assert first_user == "human input"
+
+
+def test_append_normalizes_legacy_harness_identity(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_harness_append")
+ row = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_harness_append",
+ platform="avibe",
+ author="user",
+ message_type="user",
+ source="harness",
+ text="scheduled input",
+ )
+
+ assert row["author"] == messages_service.HARNESS_TYPE
+ assert row["type"] == messages_service.HARNESS_TYPE
+ assert row["source"] == messages_service.HARNESS_TYPE
+
+
def test_same_second_messages_order_by_insertion(isolated_state):
"""Rows sharing a (second-resolution) created_at still order by insertion in
the transcript: the monotonic message id breaks the ``(created_at, id)`` tie,
@@ -633,6 +690,38 @@ def test_list_inbox_sessions_awaiting_reply_persists_through_agent_stream(isolat
assert row2["preview_text"] == "R2"
+def test_list_inbox_sessions_counts_harness_prompt_as_pending_input(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_titled_session(conn, scope_id, "ses_harness", "Automated")
+ _insert_msg(conn, scope_id, "ses_harness", "agent", "R1", "2026-05-30T10:00:00Z")
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_harness",
+ "harness",
+ "scheduled follow-up",
+ "2026-05-30T10:01:00Z",
+ msg_type=messages_service.HARNESS_TYPE,
+ )
+
+ with engine.connect() as conn:
+ pending = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"][0]
+
+ assert pending["replied"] is True
+ assert pending["last_message_author"] == "harness"
+ assert pending["preview_text"] == "R1"
+
+ with engine.begin() as conn:
+ _insert_msg(conn, scope_id, "ses_harness", "agent", "R2", "2026-05-30T10:02:00Z")
+ with engine.connect() as conn:
+ completed = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"][0]
+
+ assert completed["replied"] is False
+ assert completed["preview_text"] == "R2"
+
+
def test_list_inbox_sessions_same_second_followup_uses_id_tiebreaker(isolated_state):
"""``created_at`` is second-resolution, so a follow-up sent in the SAME second
as the prior agent reply ties on time; the time-sortable message id breaks the
diff --git a/tests/test_opencode_session_manager.py b/tests/test_opencode_session_manager.py
index c9bc1bb10..104438824 100644
--- a/tests/test_opencode_session_manager.py
+++ b/tests/test_opencode_session_manager.py
@@ -619,7 +619,14 @@ def test_opencode_saved_boundary_is_ignored_when_source_completed_after_anchor()
server.create_session.assert_not_awaited()
-def test_opencode_saved_user_boundary_survives_source_completion_before_fork_starts() -> None:
+ ("anchor_author", "anchor_type"),
+ [("user", "user"), ("harness", "harness")],
+)
+def test_opencode_saved_input_boundary_survives_source_completion_before_fork_starts(
+ anchor_author: str,
+ anchor_type: str,
+) -> None:
sessions = SimpleNamespace(
get_agent_session_id=Mock(return_value=None),
ensure_agent_session_id=Mock(return_value="ses-fork"),
@@ -655,8 +662,8 @@ def test_opencode_saved_user_boundary_survives_source_completion_before_fork_sta
"modules.agents.opencode.session.fork_source_state",
return_value=SimpleNamespace(
anchor_is_terminal_agent_output=False,
- anchor_author="user",
- anchor_type="user",
+ anchor_author=anchor_author,
+ anchor_type=anchor_type,
has_messages_after_anchor=True,
has_terminal_agent_output_after_anchor=True,
),
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index ebf14fa17..2bb21c966 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -2021,7 +2021,63 @@ def test_agent_run_callback_enqueues_only_result_to_caller_session(tmp_path: Pat
assert callback_run["message"] == "complete delegated result"
-def test_agent_run_forwards_multiple_outputs_and_completes_once(tmp_path: Path, monkeypatch) -> None:
+def test_agent_run_explicit_delivery_suppresses_automatic_callback(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ caller_session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id="target-session",
+ message="delegated work",
+ agent_name="codex",
+ callback_session_id=caller_session_id,
+ )
+ explicit = request_store.enqueue_agent_run(
+ session_id=caller_session_id,
+ message="explicit final report",
+ agent_name="codex",
+ source_kind="agent",
+ source_actor="target-session",
+ parent_run_id=request.id,
+ )
+ store = SQLiteBackgroundTaskStore()
+ try:
+ store.record_run_message(
+ request.id,
+ text="automatic terminal result",
+ terminal_status="succeeded",
+ )
+ finally:
+ store.close()
+ service = ScheduledTaskService(
+ controller=_avibe_controller_double(
+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ ),
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_callbacks())
+
+ original = request_store.get_run(request.id)
+ assert original is not None
+ assert original["callback_status"] == "sent"
+ assert original["callback_run_id"] == explicit.id
+ callback_runs = [
+ run
+ for run in request_store.list_runs()
+ if run.get("source_kind") == "callback" and run.get("parent_run_id") == request.id
+ ]
+ assert callback_runs == []
+
+
+def test_agent_run_keeps_output_ledger_but_callbacks_only_terminal_result(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
caller_session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
@@ -2045,47 +2101,46 @@ def test_agent_run_forwards_multiple_outputs_and_completes_once(tmp_path: Path,
assert sqlite_store.defer_run_terminal(
request.id,
terminal_status="succeeded",
+ result_text="terminal delegated result",
) is True
first = sqlite_store.record_run_output(
request.id,
- output_id="output-1",
- text="first callback output",
+ output_id="terminal-output",
+ text="terminal delegated result",
sequence=1,
provenance={"run_id": request.id},
)
- service.forward_run_outputs([request.id])
running = request_store.get_run(request.id)
assert first["recorded"] is True
assert first["terminal_transition"] is False
assert running is not None
assert running["status"] == "running"
+ assert not running["result_text"]
assert running["callback_status"] == "pending"
assert running["result_payload"]["deferred_terminal_status"] == "succeeded"
second = sqlite_store.record_run_output(
request.id,
- output_id="output-2",
- text="second callback output",
+ output_id="activity-output",
+ text="background activity completion",
sequence=2,
provenance={"run_id": request.id},
terminal_status="succeeded",
)
- service.forward_run_outputs([request.id])
terminal = request_store.get_run(request.id)
assert terminal is not None
completed_at = terminal["completed_at"]
duplicate = sqlite_store.record_run_output(
request.id,
- output_id="output-2",
- text="second callback output",
+ output_id="activity-output",
+ text="background activity completion",
sequence=2,
provenance={"run_id": request.id},
terminal_status="succeeded",
)
- service.forward_run_outputs([request.id])
asyncio.run(service._drain_callbacks())
original = request_store.get_run(request.id)
@@ -2098,10 +2153,11 @@ def test_agent_run_forwards_multiple_outputs_and_completes_once(tmp_path: Path,
assert original["completed_at"] == completed_at
assert original["callback_status"] == "sent"
assert "deferred_terminal_status" not in original["result_payload"]
- assert original["result_text"] == "first callback output\n\nsecond callback output"
+ assert "deferred_terminal_result_text" not in original["result_payload"]
+ assert original["result_text"] == "terminal delegated result"
assert [item["id"] for item in original["result_payload"]["outputs"]] == [
- "output-1",
- "output-2",
+ "terminal-output",
+ "activity-output",
]
callback_runs = [
@@ -2109,14 +2165,58 @@ def test_agent_run_forwards_multiple_outputs_and_completes_once(tmp_path: Path,
for run in request_store.list_runs()
if run.get("source_kind") == "callback" and run.get("parent_run_id") == request.id
]
- assert [run["message"] for run in callback_runs] == [
- "first callback output",
- "second callback output",
+ assert [run["message"] for run in callback_runs] == ["terminal delegated result"]
+ assert callback_runs[0]["source_actor"] == request.id
+
+
+def test_settled_deferred_run_delivers_saved_terminal_result(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ caller_session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id="target-session",
+ message="delegated work",
+ agent_name="codex",
+ callback_session_id=caller_session_id,
+ )
+ service = ScheduledTaskService(
+ controller=_avibe_controller_double(
+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ ),
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+ assert request_store.claim(request.id) is not None
+ assert request_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ result_text="terminal delegated result",
+ ) is True
+
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ sqlite_store.record_run_output(
+ request.id,
+ output_id="activity-output",
+ text="intermediate activity output",
+ )
+ assert request_store.settle_deferred_run(request.id) is True
+ asyncio.run(service._drain_callbacks())
+
+ original = request_store.get_run(request.id)
+ assert original is not None
+ assert original["result_text"] == "terminal delegated result"
+ assert "deferred_terminal_result_text" not in original["result_payload"]
+ callback_runs = [
+ run
+ for run in request_store.list_runs()
+ if run.get("source_kind") == "callback" and run.get("parent_run_id") == request.id
]
- assert {run["metadata"]["callback_output_id"] for run in callback_runs} == {
- "output-1",
- "output-2",
- }
+ assert [run["message"] for run in callback_runs] == ["terminal delegated result"]
@pytest.mark.parametrize(
@@ -2126,7 +2226,7 @@ def test_agent_run_forwards_multiple_outputs_and_completes_once(tmp_path: Path,
("canceled", "The run was canceled before producing a result."),
],
)
-def test_agent_run_forwards_terminal_status_after_partial_output(
+def test_agent_run_callbacks_only_terminal_status_after_partial_output(
tmp_path: Path,
monkeypatch,
terminal_status: str,
@@ -2155,12 +2255,12 @@ def test_agent_run_forwards_terminal_status_after_partial_output(
recorded = sqlite_store.record_run_output(
request.id,
output_id="output-1",
- text="partial callback output",
+ text="intermediate activity output",
sequence=1,
provenance={"run_id": request.id},
)
assert recorded["recorded"] is True
- service.forward_run_outputs([request.id])
+ assert not request_store.get_run(request.id)["result_text"]
if terminal_status == "failed":
request_store.complete(request, ok=False, error="backend disconnected")
else:
@@ -2178,12 +2278,9 @@ def test_agent_run_forwards_terminal_status_after_partial_output(
for run in request_store.list_runs()
if run.get("source_kind") == "callback" and run.get("parent_run_id") == request.id
]
- assert [run["message"] for run in callback_runs] == [
- "partial callback output",
- expected_message,
- ]
- assert callback_runs[1]["source_actor"] == f"{request.id}:terminal:{terminal_status}"
- assert original["callback_run_id"] == callback_runs[1]["id"]
+ assert [run["message"] for run in callback_runs] == [expected_message]
+ assert callback_runs[0]["source_actor"] == f"{request.id}:terminal:{terminal_status}"
+ assert original["callback_run_id"] == callback_runs[0]["id"]
def test_duplicate_terminal_output_does_not_append_result_text_again(
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index 0b802b280..0c7ac3797 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -9,6 +9,7 @@ from sqlalchemy import select
from core.services.session_fork import (
SessionForkError,
+ SourceMessageAnchor,
fork_anchor_is_terminal_agent_output,
fork_metadata_from_session_metadata,
fork_source_has_agent_output_after_anchor,
@@ -175,7 +176,15 @@ def test_reserve_forked_codex_running_fork_marks_trim(tmp_path: Path) -> None:
assert metadata["fork_native_turn_started"] is True
-def test_reserve_forked_session_infers_running_user_anchor_without_live_hint(tmp_path: Path) -> None:
+ ("author", "message_type"),
+ [("user", "user"), ("harness", messages_service.HARNESS_TYPE)],
+)
+def test_reserve_forked_session_infers_running_input_anchor_without_live_hint(
+ tmp_path: Path,
+ author: str,
+ message_type: str,
+) -> None:
db_path = tmp_path / "vibe.sqlite"
source_id = _seed_source_session(db_path, tmp_path)
engine = create_sqlite_engine(db_path)
@@ -184,21 +193,22 @@ def test_reserve_forked_session_infers_running_user_anchor_without_live_hint(tmp
row = conn.execute(
select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)
).mappings().one()
- running_user = messages_service.append(
+ running_input = messages_service.append(
conn,
scope_id=row["scope_id"],
session_id=source_id,
platform="avibe",
- author="user",
- message_type="user",
+ author=author,
+ message_type=message_type,
text="long running request",
+ source="harness" if author == "harness" else None,
)
finally:
engine.dispose()
result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
- assert result.fork.source_message_id == running_user["id"]
+ assert result.fork.source_message_id == running_input["id"]
assert result.fork.trim_latest_running_turn is True
assert result.fork.native_turn_started is False
engine = create_sqlite_engine(db_path)
@@ -211,7 +221,7 @@ def test_reserve_forked_session_infers_running_user_anchor_without_live_hint(tmp
engine.dispose()
metadata = json.loads(forked["metadata_json"])
- assert metadata["fork_source_message_id"] == running_user["id"]
+ assert metadata["fork_source_message_id"] == running_input["id"]
assert metadata["fork_trim_latest_running_turn"] is True
assert metadata["fork_native_turn_started"] is False
@@ -1300,7 +1310,63 @@ def test_fork_source_state_uses_latest_progress_after_anchor(
assert state.latest_after_anchor_type == "user"
assert state.has_messages_after_anchor is True
assert state.has_terminal_agent_output_after_anchor is False
- assert state.has_user_turn_after_anchor is True
+ assert state.has_input_turn_after_anchor is True
+ finally:
+ engine.dispose()
+
+
+def test_harness_message_is_an_input_turn() -> None:
+ assert SourceMessageAnchor(
+ author="harness",
+ message_type="harness",
+ ).is_running_input_turn is True
+
+
+def test_fork_source_state_tracks_harness_turn_after_anchor(
+ 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()
+ anchor = messages_service.append(
+ conn,
+ scope_id=row["scope_id"],
+ session_id=source_id,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="previous result",
+ )
+ messages_service.append(
+ conn,
+ scope_id=row["scope_id"],
+ session_id=source_id,
+ platform="avibe",
+ author="harness",
+ message_type=messages_service.HARNESS_TYPE,
+ text="automated follow-up",
+ source="harness",
+ )
+
+ state = fork_source_state(
+ {"source_session_id": source_id, "source_message_id": anchor["id"]}
+ )
+
+ assert state.latest_after_anchor_author == "harness"
+ assert state.latest_after_anchor_type == messages_service.HARNESS_TYPE
+ assert state.has_messages_after_anchor is True
+ assert state.has_terminal_agent_output_after_anchor is False
+ assert state.has_input_turn_after_anchor is True
finally:
engine.dispose()
diff --git a/tests/test_show_git.py b/tests/test_show_git.py
index 6fb556c0a..33290dc3f 100644
--- a/tests/test_show_git.py
+++ b/tests/test_show_git.py
@@ -836,3 +836,63 @@ def test_storage_lookup_uses_turn_boundary_instead_of_later_pending_message():
context = show_git.load_turn_checkpoint_context(session_id, after="2099-01-01T00:00:00+00:00")
assert context.message == "current driving message"
assert context.message_id == current["id"]
+
+
+def test_storage_lookup_includes_harness_driving_message():
+ 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_harness_checkpoint"
+ with get_cached_sqlite_engine().begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_harness_checkpoint",
+ now="2026-07-15T00:00:00+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-07-15T00:00:00+00:00",
+ updated_at="2026-07-15T00:00:00+00:00",
+ last_active_at="2026-07-15T00:00:00+00:00",
+ )
+ )
+ prompt = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ message_type=messages_service.HARNESS_TYPE,
+ source="harness",
+ text="refresh the dashboard",
+ native_message_id="agent_run:run-harness",
+ )
+ conn.execute(
+ messages.update()
+ .where(messages.c.id == prompt["id"])
+ .values(created_at="2099-01-01T00:00:01+00:00")
+ )
+
+ expected = TurnCheckpointContext(
+ message="refresh the dashboard",
+ run_id="run-harness",
+ message_id=prompt["id"],
+ )
+ assert show_git.load_turn_checkpoint_context(session_id) == expected
+ assert show_git.load_turn_checkpoint_context(
+ session_id, after="2099-01-01T00:00:00+00:00"
+ ) == expected
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 0b6d7c6fb..f913c30bc 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -17,7 +17,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260707_0029"
+HEAD_REVISION = "20260716_0030"
def _index_sql(conn: sqlite3.Connection, name: str) -> str:
@@ -101,7 +101,7 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "ix_messages_inbox_agent_reply" in message_indexes
assert "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")
+ assert "author = 'harness'" in _index_sql(conn, "ix_messages_inbox_user_send")
assert "uq_vault_secrets_name_folded" in vault_secret_indexes
assert "lower(name)" in _index_sql(conn, "uq_vault_secrets_name_folded").lower()
assert "ix_vault_auth_factors_kind_rp" in vault_auth_factor_indexes
@@ -307,7 +307,7 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Path
assert "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 "author = 'harness'" in _index_sql(conn, "ix_messages_inbox_user_send")
assert "ix_agent_sessions_scope_status_activity" in agent_session_indexes
@@ -338,7 +338,7 @@ 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:
+def test_run_migrations_rebuilds_inbox_indexes_for_harness_inputs(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path, revision="20260610_0022")
@@ -352,7 +352,46 @@ def test_run_migrations_rebuilds_inbox_indexes_for_harness_dedupe(tmp_path: Path
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")
+ assert "author = 'harness'" in _index_sql(conn, "ix_messages_inbox_user_send")
+
+
+def test_run_migrations_backfills_legacy_harness_prompt_identity(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+
+ run_migrations(db_path, revision="20260707_0029")
+ with sqlite3.connect(db_path) as conn:
+ _insert_scope(conn, "scope_harness")
+ _insert_agent_session(
+ conn,
+ row_id="ses_harness",
+ scope_id="scope_harness",
+ anchor="ses_harness",
+ workdir=None,
+ backend="codex",
+ native="",
+ last_active="2026-07-15T00:00:00Z",
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, source,
+ content_text, content_json, metadata_json, created_at, updated_at
+ ) values (
+ 'msg_harness', 'scope_harness', 'ses_harness', 'avibe',
+ 'user', 'user', 'harness', 'scheduled input', '{}', '{}',
+ '2026-07-15T00:00:00Z', '2026-07-15T00:00:00Z'
+ )
+ """
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ row = conn.execute(
+ "select author, type, source from messages where id = 'msg_harness'"
+ ).fetchone()
+ assert row == ("harness", "harness", "harness")
def test_run_migrations_strips_vault_secret_preview_metadata(tmp_path: Path) -> None:
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index a15819aa1..f2ddf6e0b 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -70,6 +70,7 @@ const emptyRuntimeState = (): SessionRuntimeState => ({
// the same rows the initial load shows (assistant / tool_call are process log).
const isTranscriptMessage = (msg: WorkbenchMessage): boolean =>
msg.type === 'user' ||
+ msg.type === 'harness' ||
msg.type === 'result' ||
msg.type === 'error' ||
msg.type === 'notify' ||
@@ -2471,8 +2472,8 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
const isNotify = isNotifyMessageType(message.type);
const isAgent = !isNotify && message.author === 'agent';
const isSystem = !isNotify && message.author === 'system';
- // A harness-origin row is a user-role prompt the human didn't type (scheduled
- // task / watch / webhook); collapsed by default so it doesn't dominate.
+ // A harness-origin row is turn input the human didn't type (scheduled task /
+ // watch / webhook); collapsed by default so it doesn't dominate.
const isHarness = !isNotify && !isAgent && !isSystem && message.source === 'harness';
const isUser = !isNotify && !isAgent && !isSystem && !isHarness;
const messageFontStyle = { fontSize: `${normalizeChatMessageFontSize(messageFontSize)}px` };
diff --git a/ui/src/components/workbench/search/SearchResultRow.test.ts b/ui/src/components/workbench/search/SearchResultRow.test.ts
new file mode 100644
index 000000000..cced029a1
--- /dev/null
+++ b/ui/src/components/workbench/search/SearchResultRow.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest';
+
+import { messageSearchRole } from './messageSearchRole';
+
+describe('messageSearchRole', () => {
+ it('keeps harness-originated matches distinct from human and agent messages', () => {
+ expect(messageSearchRole({ author: 'harness', source: 'harness', type: 'harness' })).toBe(
+ 'automated',
+ );
+ expect(messageSearchRole({ author: 'user', source: 'harness', type: 'user' })).toBe(
+ 'automated',
+ );
+ expect(messageSearchRole({ author: 'user', source: 'user', type: 'user' })).toBe('you');
+ expect(messageSearchRole({ author: 'agent', source: 'agent', type: 'result' })).toBe('agent');
+ });
+});
diff --git a/ui/src/components/workbench/search/SearchResultRow.tsx b/ui/src/components/workbench/search/SearchResultRow.tsx
index 6c2ff3533..de93e67e7 100644
--- a/ui/src/components/workbench/search/SearchResultRow.tsx
+++ b/ui/src/components/workbench/search/SearchResultRow.tsx
@@ -4,6 +4,7 @@ import clsx from 'clsx';
import type { MessageSearchMatch } from '../../../context/ApiContext';
import { formatRelativeTime } from '../../../lib/relativeTime';
import { Button } from '../../ui/button';
+import { messageSearchRole } from './messageSearchRole';
import { Snippet } from './Snippet';
type SearchResultRowProps = {
@@ -14,7 +15,7 @@ type SearchResultRowProps = {
onSelect?: () => void;
};
-// One matching message: a role chip (YOU / AGENT), the highlighted snippet, and
+// One matching message: a role chip, the highlighted snippet, and
// a muted relative timestamp. Presentational + reusable by both the desktop
// palette and the mobile page — navigation is wired by the consumer via
// ``onSelect``.
@@ -27,7 +28,17 @@ type SearchResultRowProps = {
// palette relies on that attribute to scroll the active row into view.
export const SearchResultRow: React.FC<SearchResultRowProps> = ({ match, selected, onSelect }) => {
const { t } = useTranslation();
- const isUser = match.author === 'user';
+ const role = messageSearchRole(match);
+ const roleLabel = {
+ you: t('workbench.search.roleYou'),
+ automated: t('workbench.search.roleAutomated'),
+ agent: t('workbench.search.roleAgent'),
+ }[role];
+ const roleClass = {
+ you: 'bg-cyan-soft text-cyan',
+ automated: 'bg-violet-soft text-violet',
+ agent: 'bg-mint-soft text-mint',
+ }[role];
return (
<Button
@@ -45,12 +56,10 @@ export const SearchResultRow: React.FC<SearchResultRowProps> = ({ match, selecte
<span
className={clsx(
'shrink-0 rounded-md px-2 py-0.5 font-mono text-[9px] font-bold uppercase tracking-wider',
- isUser
- ? 'bg-cyan-soft text-cyan'
- : 'bg-mint-soft text-mint',
+ roleClass,
)}
>
- {isUser ? t('workbench.search.roleYou') : t('workbench.search.roleAgent')}
+ {roleLabel}
</span>
<span className="min-w-0 flex-1">
<Snippet snippet={match.snippet} />
diff --git a/ui/src/components/workbench/search/messageSearchRole.ts b/ui/src/components/workbench/search/messageSearchRole.ts
new file mode 100644
index 000000000..41b145e59
--- /dev/null
+++ b/ui/src/components/workbench/search/messageSearchRole.ts
@@ -0,0 +1,12 @@
+import type { MessageSearchMatch } from '../../../context/ApiContext';
+
+export type MessageSearchRole = 'you' | 'automated' | 'agent';
+
+export const messageSearchRole = (
+ match: Pick<MessageSearchMatch, 'author' | 'source' | 'type'>,
+): MessageSearchRole => {
+ if (match.author === 'harness' || match.source === 'harness' || match.type === 'harness') {
+ return 'automated';
+ }
+ return match.author === 'user' ? 'you' : 'agent';
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 5aec25c9d..3e6386827 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -953,13 +953,13 @@ export type WorkbenchMessage = {
session_id: string | null;
platform: string;
author: 'user' | 'agent' | 'system' | string;
- // First-class message type: 'user' | 'assistant' | 'tool_call' | 'notify' |
- // 'result'. Distinct from the coarse author — the chat renders 'notify' as a
- // terminal status marker, and the inbox previews 'result' only.
- type: 'user' | 'assistant' | 'tool_call' | 'notify' | 'result' | string;
+ // First-class message type: 'user' | 'harness' | 'assistant' | 'tool_call' |
+ // 'notify' | 'result'. Distinct from the coarse author — the chat renders
+ // 'notify' as a terminal status marker, and the inbox previews 'result' only.
+ type: 'user' | 'harness' | 'assistant' | 'tool_call' | 'notify' | 'result' | string;
// Origin of the message, distinct from the coarse ``author`` role: a
- // harness-triggered prompt is author='user' but source='harness'. Drives the
- // transcript's "Scheduled task" / "Watch" provenance tag.
+ // harness-triggered prompt uses author/type='harness'. Drives the transcript's
+ // "Scheduled task" / "Watch" provenance tag.
source: 'user' | 'agent' | 'harness' | string | null;
author_id: string | null;
author_name: string | null;
@@ -984,14 +984,14 @@ export type MessageSnippet = {
suffix: string;
};
-// A single matching message within a session group. ``type`` is the coarse
-// chat role the row chip renders ('user' → YOU, otherwise AGENT); ``source``
-// carries provenance (harness/user/agent) like WorkbenchMessage.
+// A single matching message within a session group. The row chip derives its
+// role from author/type/source so harness prompts remain distinct from both
+// human input and agent output.
export type MessageSearchMatch = {
id: string;
author: string;
source: string | null;
- type: 'user' | 'result' | string;
+ type: 'user' | 'harness' | 'result' | string;
created_at: string;
snippet: MessageSnippet;
};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 66f957bc2..fa11363e3 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1043,6 +1043,7 @@
},
"search": {
"roleYou": "You",
+ "roleAutomated": "Automated",
"roleAgent": "Agent",
"title": "Search",
"entry": "Search",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 76e85bc0b..0849d2d59 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1043,6 +1043,7 @@
},
"search": {
"roleYou": "你",
+ "roleAutomated": "自动触发",
"roleAgent": "助手",
"title": "搜索",
"entry": "搜索",
diff --git a/vibe/message_identity.py b/vibe/message_identity.py
new file mode 100644
index 000000000..97b1143e5
--- /dev/null
+++ b/vibe/message_identity.py
@@ -0,0 +1,14 @@
+"""Lightweight message authorship and input-turn semantics."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+HARNESS_TYPE = "harness"
+INPUT_TURN_AUTHOR_TYPES = (("user", "user"), ("harness", HARNESS_TYPE))
+
+
+def is_input_turn(author: Optional[str], message_type: Optional[str]) -> bool:
+ """Return whether a transcript row starts human or harness agent work."""
+
+ return (author, message_type) in INPUT_TURN_AUTHOR_TYPES