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(harness): settle coalesced agent runs (#637)
Call White087e7053b5bb
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 1490f2fc7..597f3ddf8 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -39,6 +39,13 @@ def _coalesced_task_execution_ids(payload: dict[str, Any]) -> list[str]:return run_ids+def _run_is_cancelled(run: Any) -> bool:+ if not isinstance(run, dict):+ return False+ status = str(run.get("status") or "").strip().lower()+ return status in {"canceled", "cancelled"}++async def _stream_chunk(controller, context, *, text: str, message_id: Optional[str], kind: str) -> None:"""Forward one durable agent message to the live streaming turn sink.@@ -250,6 +257,26 @@ class ConsolidatedMessageDispatcher:if store is not None:store.close()+ def _record_agent_run_terminal_for_ids(+ self,+ *,+ store: Any,+ run_ids: list[str],+ text: str,+ message_id: str | None,+ terminal_status: str | None,+ ) -> None:+ for run_id in run_ids:+ get_run = getattr(store, "get_run", None)+ if callable(get_run) and _run_is_cancelled(get_run(run_id)):+ continue+ store.record_run_message(+ run_id,+ text=text,+ message_id=message_id,+ terminal_status=terminal_status,+ )+def _record_agent_run_terminal_result(self,context: MessageContext,@@ -261,20 +288,55 @@ class ConsolidatedMessageDispatcher:payload = context.platform_specific or {}if payload.get("task_trigger_kind") != "agent_run":return- run_id = str(payload.get("task_execution_id") or "").strip()- if not run_id:+ run_ids = _coalesced_task_execution_ids(payload)+ if not run_ids:returnstore = Nonetry:store = SQLiteBackgroundTaskStore()- store.record_run_message(- run_id,+ self._record_agent_run_terminal_for_ids(+ store=store,+ run_ids=run_ids,text=text,message_id=message_id,terminal_status="failed" if is_error else "succeeded",)except Exception as err:- logger.warning("Failed to record agent run terminal result for %s: %s", run_id, err)+ logger.warning("Failed to record agent run terminal result for %s: %s", ",".join(run_ids), err)+ finally:+ if store is not None:+ store.close()++ def _record_suppressed_agent_run_terminal_result(+ self,+ context: MessageContext,+ text: str,+ message_id: str | None,+ *,+ is_error: bool,+ ) -> None:+ payload = context.platform_specific or {}+ if payload.get("task_trigger_kind") != "agent_run":+ return+ run_ids = _coalesced_task_execution_ids(payload)+ if not run_ids:+ return+ store = None+ try:+ store = SQLiteBackgroundTaskStore()+ self._record_agent_run_terminal_for_ids(+ store=store,+ run_ids=run_ids,+ text=text,+ message_id=message_id,+ terminal_status="failed" if is_error else "succeeded",+ )+ except Exception as err:+ logger.warning(+ "Failed to record suppressed agent run terminal result for %s: %s",+ ",".join(run_ids),+ err,+ )finally:if store is not None:store.close()@@ -596,8 +658,13 @@ class ConsolidatedMessageDispatcher:canonical_type == "result"and (context.platform_specific or {}).get("task_trigger_kind") == "agent_run"):- terminal_status = "failed" if is_error else "succeeded"- if canonical_type == "result" or (context.platform_specific or {}).get("task_trigger_kind") != "agent_run":+ self._record_suppressed_agent_run_terminal_result(+ context,+ text,+ message_id,+ is_error=is_error,+ )+ elif canonical_type == "result" or (context.platform_specific or {}).get("task_trigger_kind") != "agent_run":self._record_suppressed_run_message(context,text,diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 651c9dfe3..f873b0713 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -183,6 +183,7 @@ class AgentRunExecutionResult:error: Optional[str]complete_on_return: boolrequeue_on_return: bool = False+ coalesced_completion_ids: tuple[str, ...] = ()def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None) -> ResolvedSessionIdTarget:@@ -408,6 +409,124 @@ class TaskExecutionRequest:)+def _agent_run_message_for_request(request: TaskExecutionRequest) -> str:+ coalesced = (request.metadata or {}).get("coalesced_queue")+ if isinstance(coalesced, dict):+ live_execution_ids = _live_coalesced_agent_run_ids(request)+ live_set = set(live_execution_ids) if live_execution_ids is not None else None+ prompt = str(coalesced.get("prompt") or "")+ if prompt and live_set is None:+ return prompt+ messages = coalesced.get("messages")+ if isinstance(messages, list):+ parts: list[str] = []+ for item in messages:+ if not isinstance(item, dict):+ continue+ execution_id = str(item.get("execution_id") or "").strip()+ if live_set is not None and execution_id not in live_set:+ continue+ message = str(item.get("message") or item.get("prompt") or "")+ if message:+ parts.append(message)+ if parts:+ return "\n\n---\n\n".join(parts)+ return str(request.message or "")+++def _live_coalesced_agent_run_ids(request: TaskExecutionRequest) -> list[str] | None:+ coalesced = (request.metadata or {}).get("coalesced_queue")+ if not isinstance(coalesced, dict):+ return None+ execution_ids = coalesced.get("execution_ids")+ if not isinstance(execution_ids, list):+ return None+ run_ids: list[str] = []+ seen: set[str] = set()+ for value in execution_ids:+ run_id = str(value or "").strip()+ if run_id and run_id not in seen:+ seen.add(run_id)+ run_ids.append(run_id)+ if not run_ids:+ return []+ store = SQLiteBackgroundTaskStore()+ try:+ queued_ids, _stale_ids = store.inspect_queued_runs_for_workbench(run_ids)+ finally:+ store.close()+ live = [request.id]+ for run_id in queued_ids:+ if run_id not in live:+ live.append(run_id)+ return live+++def _retire_stale_agent_run_queue_rows(+ *,+ session_id: Optional[str],+ execution_ids: list[str],+) -> int:+ """Retire old queued Workbench rows for recovered direct Agent Runs.++ A crash can happen after the run rows are claimed but before flush_queue+ deletes the queued harness rows. On restart the primary run is recovered and+ submitted here; leaving the old queued rows in place makes their native ids+ look like delivered duplicates even though they are only stale queue state.+ Child rows still need their native ids preserved as dedupe markers because+ only the primary prompt is re-mirrored as a visible harness row.+ """+ normalized_ids: list[str] = []+ seen: set[str] = set()+ for raw_execution_id in execution_ids:+ execution_id = str(raw_execution_id or "").strip()+ if not execution_id or execution_id in seen:+ continue+ seen.add(execution_id)+ normalized_ids.append(execution_id)+ if not session_id or not normalized_ids:+ return 0++ from storage import messages_service+ from storage.models import messages++ native_ids = [f"agent_run:{execution_id}" for execution_id in normalized_ids]+ primary_native_id = native_ids[0]+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ rows = list(+ conn.execute(+ select(messages.c.id, messages.c.native_message_id)+ .where(messages.c.session_id == session_id)+ .where(messages.c.platform == "avibe")+ .where(messages.c.type == messages_service.QUEUED_TYPE)+ .where(messages.c.native_message_id.in_(native_ids))+ )+ )+ primary_row_ids = [str(row.id) for row in rows if str(row.native_message_id or "") == primary_native_id]+ marker_row_ids = [str(row.id) for row in rows if str(row.native_message_id or "") != primary_native_id]+ if marker_row_ids:+ conn.execute(+ messages.update()+ .where(messages.c.id.in_(marker_row_ids))+ .values(+ author="harness",+ source="harness",+ type=messages_service.HARNESS_DEDUPE_TYPE,+ content_text="",+ content_json=json.dumps({"text": ""}),+ metadata_json=json.dumps({"coalesced_from": primary_native_id, "recovered_queue_row": True}),+ updated_at=_utc_now_iso(),+ )+ )+ row_ids = primary_row_ids + marker_row_ids+ if not row_ids:+ return 0+ if primary_row_ids:+ messages_service.delete_queued(conn, primary_row_ids)+ return len(row_ids)++class ScheduledTaskStore:def __init__(self, path: Optional[Path] = None):self.path = path or (paths.get_state_dir() / "scheduled_tasks.json")@@ -1124,6 +1243,27 @@ class TaskExecutionStore:tmp_path.replace(completed_path)processing_path.unlink(missing_ok=True)+ def complete_coalesced(+ self,+ request: TaskExecutionRequest,+ run_ids: list[str],+ *,+ ok: bool,+ error: Optional[str] = None,+ ) -> None:+ if self._sqlite is not None:+ from storage.background import complete_coalesced_agent_runs_for_workbench_in_connection++ with self._sqlite.engine.begin() as conn:+ complete_coalesced_agent_runs_for_workbench_in_connection(+ conn,+ run_ids,+ ok=ok,+ error=error,+ )+ return+ self.complete(request, ok=ok, error=error)+class ScheduledTaskService:"""Controller-owned runtime that executes persisted scheduled tasks."""@@ -1487,6 +1627,7 @@ class ScheduledTaskService:async def _execute_claimed_request(self, request: TaskExecutionRequest) -> None:error: Optional[str] = Noneshould_complete = True+ coalesced_completion_ids: list[str] = _live_coalesced_agent_run_ids(request) or []task_id = request.task_idsession_key = request.session_keysession_id = request.session_id@@ -1530,7 +1671,8 @@ class ScheduledTaskService:agent_name=request.agent_name,)elif request.request_type == "agent_run":- if not request.message:+ message = _agent_run_message_for_request(request)+ if not message:raise ValueError("agent run requires message")if not (request.session_id or request.session_key):raise ValueError("agent run currently requires session_id or a resolvable session target")@@ -1539,15 +1681,22 @@ class ScheduledTaskService:session_id=request.session_id,post_to=request.post_to,deliver_key=request.deliver_key,- message=request.message,+ message=message,execution_id=request.id,agent_name=request.agent_name,- metadata=request.metadata,+ metadata={+ **(request.metadata or {}),+ "source_kind": request.source_kind,+ "source_actor": request.source_actor,+ "parent_run_id": request.parent_run_id,+ "callback_session_id": request.callback_session_id,+ },)error = result.errorshould_complete = result.complete_on_returnif result.requeue_on_return:self.request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ coalesced_completion_ids = list(result.coalesced_completion_ids)else:raise ValueError(f"unknown task request type: {request.request_type}")except asyncio.CancelledError:@@ -1560,14 +1709,22 @@ class ScheduledTaskService:should_complete = Truefinally:if should_complete:- self.request_store.complete(- request,- ok=not error,- error=error,- task_id=task_id,- session_key=session_key,- session_id=session_id,- )+ if coalesced_completion_ids:+ self.request_store.complete_coalesced(+ request,+ coalesced_completion_ids,+ ok=not error,+ error=error,+ )+ else:+ self.request_store.complete(+ request,+ ok=not error,+ error=error,+ task_id=task_id,+ session_key=session_key,+ session_id=session_id,+ )await self._drain_callbacks()async def _execute_task(@@ -1650,11 +1807,40 @@ class ScheduledTaskService:gate = getattr(self.controller, "session_turn_gate", None)if target.platform == "avibe" and session_id and gate is not None:+ stale_queue_rows = _retire_stale_agent_run_queue_rows(+ session_id=session_id,+ execution_ids=_live_coalesced_agent_run_ids(+ TaskExecutionRequest(+ id=execution_id,+ request_type="agent_run",+ metadata=metadata or {},+ )+ )+ or [execution_id],+ )+ if stale_queue_rows:+ try:+ from core.inbox_events import bus++ bus.publish("queue.updated", {"session_id": session_id})+ except Exception:+ logger.debug("agent_run recovery: queue.updated publish failed", exc_info=True)state = await gate.submit_scheduled(session_id, context, message)if state == "enqueued":return AgentRunExecutionResult(error=None, complete_on_return=False, requeue_on_return=True)if state == "duplicate":- return AgentRunExecutionResult(error=None, complete_on_return=True)+ live_ids = _live_coalesced_agent_run_ids(+ TaskExecutionRequest(+ id=execution_id,+ request_type="agent_run",+ metadata=metadata or {},+ )+ )+ return AgentRunExecutionResult(+ error=None,+ complete_on_return=True,+ coalesced_completion_ids=tuple(live_ids or [execution_id]),+ )return AgentRunExecutionResult(error=None, complete_on_return=False)async def _noop_chunk(_envelope: dict) -> None:@@ -1862,6 +2048,11 @@ class ScheduledTaskService:# attribute the injected prompt to its precise definition."task_definition_id": task_id,"vibe_agent_name": agent_name,+ "source_kind": (metadata or {}).get("source_kind"),+ "source_actor": (metadata or {}).get("source_actor"),+ "parent_run_id": (metadata or {}).get("parent_run_id"),+ "callback_session_id": (metadata or {}).get("callback_session_id"),+ "coalesced_queue": (metadata or {}).get("coalesced_queue"),"suppress_delivery": bool(target_info.suppress_delivery) if target_info else False,"agent_session_target": ({diff --git a/core/session_turns.py b/core/session_turns.pyindex 92c4e27f6..eb643e36d 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -17,6 +17,7 @@ terminal-result move onto the manager in subsequent commits.from __future__ import annotationsimport asyncio+import jsonimport loggingfrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -129,6 +130,21 @@ def _scheduled_provenance(row: dict) -> Optional[dict]:return provenance if isinstance(provenance, dict) else None+def _agent_run_merge_definition_id(spec: dict) -> str:+ """Return the coalescing bucket for direct Agent Run queue rows.++ Callback-backed runs can deliver results into different caller sessions, so+ keep those rows isolated by execution id. Plain CLI/direct runs may coalesce,+ and their prompt builder always includes every queued message verbatim.+ """+ execution_id = str(spec.get("task_execution_id") or "").strip()+ if "source_kind" not in spec and "callback_session_id" not in spec:+ return f"agent_run:{execution_id}" if execution_id else ""+ if spec.get("callback_session_id") or spec.get("source_kind") == "callback":+ return f"agent_run:{execution_id}" if execution_id else ""+ return "agent_run"++def _scheduled_merge_key(row: dict) -> Optional[tuple[str, ...]]:provenance = _scheduled_provenance(row)if provenance is None:@@ -138,6 +154,8 @@ def _scheduled_merge_key(row: dict) -> Optional[tuple[str, ...]]:return Nonetrigger_kind = str(spec.get("task_trigger_kind") or "").strip()definition_id = str(spec.get("task_definition_id") or "").strip()+ if trigger_kind == "agent_run" and not definition_id:+ definition_id = _agent_run_merge_definition_id(spec)if not trigger_kind or not definition_id:return Nonedelivery_override = spec.get("delivery_override") if isinstance(spec.get("delivery_override"), dict) else {}@@ -145,8 +163,16 @@ def _scheduled_merge_key(row: dict) -> Optional[tuple[str, ...]]:return (trigger_kind,definition_id,+ str(spec.get("agent_session_id") or ""),str(spec.get("vibe_agent_name") or ""),str(spec.get(SCHEDULED_TARGET_AGENT_KEY) or ""),+ str((spec.get("agent_session_target") or {}).get("agent_name") or "")+ if isinstance(spec.get("agent_session_target"), dict)+ else "",+ str(spec.get("callback_session_id") or ""),+ str(spec.get("source_kind") or ""),+ str(spec.get("source_actor") or ""),+ str(spec.get("parent_run_id") or ""),str(spec.get("delivery_key_external") or ""),str(spec.get("delivery_scope_session_key") or ""),str(delivery_override.get("platform") or ""),@@ -193,6 +219,9 @@ def _build_scheduled_segment_text(segment: list[dict]) -> str:if len(texts) == 1:return texts[0]+ if _scheduled_segment_trigger_kind(segment) == "agent_run":+ return "\n\n---\n\n".join(texts)+lang = _scheduled_segment_language(segment)parts = [texts[0],@@ -222,6 +251,11 @@ def _build_scheduled_segment_text(segment: list[dict]) -> str:return "".join(parts)+def _scheduled_segment_trigger_kind(segment: list[dict]) -> str:+ spec = (_scheduled_provenance(segment[0]) or {}).get("platform_specific") or {} if segment else {}+ return str(spec.get("task_trigger_kind") or "").strip() if isinstance(spec, dict) else ""++def _scheduled_segment_language(segment: list[dict]) -> str:for row in segment:spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}@@ -244,6 +278,95 @@ def _scheduled_segment_native_ids(segment: list[dict]) -> list[str]:return native_ids+def _scheduled_segment_execution_id(row: dict) -> str:+ spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}+ if not isinstance(spec, dict):+ return ""+ return str(spec.get("task_execution_id") or "").strip()+++def _scheduled_row_execution_ids(row: dict) -> list[str]:+ execution_ids: list[str] = []+ execution_id = _scheduled_segment_execution_id(row)+ if execution_id:+ execution_ids.append(execution_id)+ spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}+ coalesced = spec.get("coalesced_queue") if isinstance(spec, dict) else None+ coalesced_ids = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None+ if isinstance(coalesced_ids, list):+ for value in coalesced_ids:+ coalesced_id = str(value or "").strip()+ if coalesced_id and coalesced_id not in execution_ids:+ execution_ids.append(coalesced_id)+ return execution_ids+++def _scheduled_segment_execution_ids(segment: list[dict]) -> list[str]:+ execution_ids: list[str] = []+ for row in segment:+ for execution_id in _scheduled_row_execution_ids(row):+ if execution_id not in execution_ids:+ execution_ids.append(execution_id)+ return execution_ids+++def _scheduled_segment_rows_for_execution_ids(segment: list[dict], execution_ids: set[str]) -> list[dict]:+ return [row for row in segment if set(_scheduled_row_execution_ids(row)) & execution_ids]+++def _scheduled_segment_stale_row_ids(segment: list[dict], queued_ids: set[str]) -> list[str]:+ row_ids: list[str] = []+ for row in segment:+ row_id = row.get("id")+ if not row_id:+ continue+ represented = set(_scheduled_row_execution_ids(row))+ if represented and not (represented & queued_ids):+ row_ids.append(row_id)+ return row_ids+++def _filter_coalesced_agent_run_provenance(provenance: dict, execution_ids: list[str]) -> dict:+ if not execution_ids:+ return provenance+ execution_set = set(execution_ids)+ coalesced = provenance.get("coalesced_queue")+ if not isinstance(coalesced, dict):+ return provenance+ filtered = dict(coalesced)+ raw_ids = coalesced.get("execution_ids")+ if isinstance(raw_ids, list):+ filtered["execution_ids"] = [+ str(value)+ for value in raw_ids+ if str(value or "").strip() in execution_set+ ]+ raw_messages = coalesced.get("messages")+ if isinstance(raw_messages, list):+ messages = [+ item+ for item in raw_messages+ if isinstance(item, dict)+ and str(item.get("execution_id") or "").strip() in execution_set+ ]+ filtered["messages"] = messages+ prompt_parts = [+ str(item.get("message") or item.get("prompt") or "")+ for item in messages+ if str(item.get("message") or item.get("prompt") or "")+ ]+ if prompt_parts:+ filtered["prompt"] = "\n\n---\n\n".join(prompt_parts)+ else:+ filtered.pop("prompt", None)+ result = dict(provenance)+ result["coalesced_queue"] = filtered+ current_id = str(result.get("task_execution_id") or "").strip()+ if current_id not in execution_set:+ result["task_execution_id"] = execution_ids[0]+ return result++def _scheduled_segment_suppresses_delivery(segment: list[dict]) -> bool:for row in segment:spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}@@ -287,6 +410,61 @@ def _write_coalesced_native_id_markers(conn: Any, segment: list[dict]) -> None:logger.debug("queue flush: coalesced native id marker already exists for %s", native_id, exc_info=True)+def _restore_queued_rows(conn: Any, rows: list[dict]) -> None:+ native_ids = [+ str(row.get("native_message_id") or "").strip()+ for row in rows+ if str(row.get("native_message_id") or "").strip()+ ]+ if native_ids:+ conn.execute(+ messages.delete()+ .where(messages.c.type == messages_service.HARNESS_DEDUPE_TYPE)+ .where(messages.c.native_message_id.in_(native_ids))+ )+ for row in rows:+ payload = {+ "id": row["id"],+ "scope_id": row["scope_id"],+ "session_id": row.get("session_id"),+ "platform": row.get("platform") or "avibe",+ "author": row.get("author") or "harness",+ "type": messages_service.QUEUED_TYPE,+ "author_id": row.get("author_id"),+ "author_name": row.get("author_name"),+ "source": row.get("source"),+ "native_message_id": row.get("native_message_id"),+ "parent_native_message_id": row.get("parent_native_message_id"),+ "content_text": row.get("text") or "",+ "content_json": json.dumps(row.get("content") or {"text": row.get("text") or ""}),+ "metadata_json": json.dumps(row.get("metadata") or {}),+ "created_at": row.get("created_at"),+ "updated_at": row.get("updated_at") or row.get("created_at"),+ "delivered_at": row.get("delivered_at"),+ "read_at": row.get("read_at"),+ }+ try:+ conn.execute(messages.insert().values(**payload))+ except IntegrityError:+ logger.debug("queue flush: queued row already restored or replaced for %s", row.get("id"), exc_info=True)+++def _claim_agent_run_segment_and_retire_queue(+ conn: Any,+ *,+ run_ids: list[str],+ segment: list[dict],+) -> list[str]:+ from storage.background import claim_queued_runs_for_workbench_in_connection++ claimed_run_ids = claim_queued_runs_for_workbench_in_connection(conn, run_ids)+ if set(claimed_run_ids) != set(run_ids):+ return claimed_run_ids+ messages_service.delete_queued(conn, [r["id"] for r in segment if r.get("id")])+ _write_coalesced_native_id_markers(conn, segment)+ return claimed_run_ids++def _scheduled_claimed_queue_row_ids(conn: Any, segment: list[dict]) -> set[str]:native_ids = _scheduled_segment_native_ids(segment)if not native_ids:@@ -584,6 +762,9 @@ class SessionTurnManager:user_row = Noneinbox_row = Noneattachment_specs: list = []+ pending_agent_run_ids: list[str] = []+ pending_scheduled_segment: list[dict] = []+ claimed_agent_run_ids: list[str] = []try:engine = create_sqlite_engine()with engine.begin() as conn:@@ -591,6 +772,8 @@ class SessionTurnManager:if not rows:return Falseif _scheduled_provenance(rows[0]) is not None:+ from storage.background import inspect_queued_runs_for_workbench_in_connection+# Scheduled segment: a leading run of same-definition harness# rows within the rolling merge window runs as one scheduled# turn. Rows remain visible individually while queued; only the@@ -606,6 +789,27 @@ class SessionTurnManager:dropped_duplicate_segment = Trueelse:segment = initial_segment+ if dropped_duplicate_segment:+ pass+ else:+ if _scheduled_segment_trigger_kind(segment) == "agent_run":+ run_ids = _scheduled_segment_execution_ids(segment)+ queued_run_ids, stale_run_ids = inspect_queued_runs_for_workbench_in_connection(conn, run_ids)+ if stale_run_ids:+ stale_set = set(stale_run_ids)+ queued_set = set(queued_run_ids)+ stale_row_ids = _scheduled_segment_stale_row_ids(segment, queued_set)+ if stale_row_ids:+ messages_service.delete_queued(conn, stale_row_ids)+ bus.publish("queue.updated", {"session_id": session_id})+ logger.info(+ "queue flush: removed stale coalesced agent_run rows before dispatching survivors: %s",+ ",".join(sorted(stale_set)),+ )+ segment = _scheduled_segment_rows_for_execution_ids(segment, queued_set)+ if not segment:+ dropped_duplicate_segment = True+if dropped_duplicate_segment:passelse:@@ -621,13 +825,23 @@ class SessionTurnManager:"window_seconds": SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS,"message_ids": [r.get("id") for r in segment if r.get("id")],"native_message_ids": scheduled_native_ids,- "execution_ids": [- spec.get("task_execution_id")- for r in segment- if isinstance((spec := (_scheduled_provenance(r) or {}).get("platform_specific") or {}), dict)- and spec.get("task_execution_id")- ],+ "execution_ids": queued_run_ids+ if _scheduled_segment_trigger_kind(segment) == "agent_run"+ else _scheduled_segment_execution_ids(segment),}+ if scheduled_prov.get("task_trigger_kind") == "agent_run" and queued_run_ids:+ pending_agent_run_ids = list(queued_run_ids)+ scheduled_prov = _filter_coalesced_agent_run_provenance(+ scheduled_prov,+ pending_agent_run_ids,+ )+ scheduled_message_id = f"agent_run:{pending_agent_run_ids[0]}"+ coalesced = scheduled_prov.get("coalesced_queue")+ if isinstance(coalesced, dict):+ coalesced_prompt = str(coalesced.get("prompt") or "")+ if coalesced_prompt:+ scheduled_text = coalesced_prompt+ pending_scheduled_segment = segmentelse:# User segment: the leading run of consecutive non-scheduled rows# (stop at the first scheduled row so it stays its own turn).@@ -636,7 +850,7 @@ class SessionTurnManager:if _scheduled_provenance(r) is not None:breaksegment.append(r)- if segment:+ if segment and not pending_agent_run_ids:messages_service.delete_queued(conn, [r["id"] for r in segment])if not is_scheduled:texts = [r.get("text") for r in segment if (r.get("text") or "").strip()]@@ -731,30 +945,76 @@ class SessionTurnManager:# Restore the stable scheduled:/watch:/webhook: native id so the# flushed prompt persists + dedupes under it (Codex P2), not None.context.message_id = scheduled_message_id- run_id = str(scheduled_prov.get("task_execution_id") or "").strip()- if scheduled_prov.get("task_trigger_kind") == "agent_run" and run_id:+ if pending_agent_run_ids:+ retry_agent_run_flush = Falsetry:- from storage.background import SQLiteBackgroundTaskStore-- store = SQLiteBackgroundTaskStore()- try:- claimed = store.claim_queued_run_for_workbench(run_id)- finally:- store.close()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ claimed_run_ids = _claim_agent_run_segment_and_retire_queue(+ conn,+ run_ids=pending_agent_run_ids,+ segment=pending_scheduled_segment,+ )+ if set(claimed_run_ids) != set(pending_agent_run_ids):+ queued_run_ids, stale_run_ids = inspect_queued_runs_for_workbench_in_connection(+ conn,+ pending_agent_run_ids,+ )+ stale_set = set(stale_run_ids)+ stale_row_ids = _scheduled_segment_stale_row_ids(+ pending_scheduled_segment,+ set(queued_run_ids),+ )+ if stale_row_ids:+ messages_service.delete_queued(conn, stale_row_ids)+ bus.publish("queue.updated", {"session_id": session_id})+ logger.info(+ "queue flush: skipped coalesced agent_run segment because some runs are no longer queued: %s",+ ",".join(sorted(set(pending_agent_run_ids) - set(claimed_run_ids))),+ )+ if queued_run_ids:+ retry_agent_run_flush = True+ else:+ return False+ if retry_agent_run_flush:+ return await self.flush_queue(session_id)+ claimed_agent_run_ids = claimed_run_ids+ bus.publish("queue.updated", {"session_id": session_id})except Exception:- logger.warning("queue flush: failed to mark agent_run %s running", run_id, exc_info=True)- return False- if not claimed:- logger.info("queue flush: skipped agent_run %s because it is no longer queued", run_id)+ logger.warning(+ "queue flush: failed to claim coalesced agent_run segment for session=%s",+ session_id,+ exc_info=True,+ )return False- await self._run(session_id, context, scheduled_text, source=SOURCE_SCHEDULED)try:- engine = create_sqlite_engine()- with engine.begin() as conn:- _write_coalesced_native_id_markers(conn, segment)+ await self._run(session_id, context, scheduled_text, source=SOURCE_SCHEDULED)except Exception:- logger.exception("queue flush: failed to preserve coalesced native ids for session=%s", session_id)+ if claimed_agent_run_ids:+ try:+ from storage.background import reset_workbench_claimed_runs_in_connection++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ reset_workbench_claimed_runs_in_connection(conn, claimed_agent_run_ids)+ _restore_queued_rows(conn, pending_scheduled_segment)+ except Exception:+ logger.exception("queue flush: failed to reset claimed agent runs for session=%s", session_id)+ logger.exception("queue flush: failed to start scheduled segment for session=%s", session_id)return False+ if not pending_agent_run_ids:+ if pending_scheduled_segment:+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ messages_service.delete_queued(conn, [r["id"] for r in pending_scheduled_segment])+ bus.publish("queue.updated", {"session_id": session_id})+ try:+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ _write_coalesced_native_id_markers(conn, segment)+ except Exception:+ logger.exception("queue flush: failed to preserve coalesced native ids for session=%s", session_id)+ return Falsereturn Truedef turn_state(self, session_id: str) -> dict:diff --git a/storage/background.py b/storage/background.pyindex 794cd5462..9de31a439 100644--- a/storage/background.py+++ b/storage/background.py@@ -111,6 +111,277 @@ def _like_contains_pattern(value: str) -> str:return f"%{escaped}%"+def _coalesced_agent_run_metadata(rows: dict[str, Any], run_ids: list[str]) -> dict[str, Any]:+ messages: list[dict[str, str]] = []+ prompt_parts: list[str] = []+ for run_id in run_ids:+ row = rows[run_id]+ message = str(row["message"] or row["prompt"] or "")+ messages.append({"execution_id": run_id, "message": message})+ if message:+ prompt_parts.append(message)+ metadata: dict[str, Any] = {+ "execution_ids": run_ids,+ "messages": messages,+ }+ if prompt_parts:+ metadata["prompt"] = "\n\n---\n\n".join(prompt_parts)+ return metadata+++def complete_coalesced_agent_runs_for_workbench_in_connection(+ conn: Any,+ run_ids: list[str],+ *,+ ok: bool,+ error: Optional[str] = None,+ completed_at: Optional[str] = None,+) -> list[str]:+ normalized_run_ids: list[str] = []+ seen: set[str] = set()+ for raw_run_id in run_ids:+ run_id = str(raw_run_id or "").strip()+ if not run_id or run_id in seen:+ continue+ seen.add(run_id)+ normalized_run_ids.append(run_id)+ if not normalized_run_ids:+ return []+ rows = {+ row["id"]: row+ for row in conn.execute(select(agent_runs).where(agent_runs.c.id.in_(normalized_run_ids))).mappings()+ }+ now = completed_at or _utc_now_iso()+ completed_ids: list[str] = []+ for run_id in normalized_run_ids:+ row = rows.get(run_id)+ if row is None:+ continue+ status = normalize_run_status(row["status"])+ values: dict[str, Any] = {"updated_at": now}+ if bool(row["cancel_requested"]) or status == "canceled":+ values["status"] = "canceled"+ values["completed_at"] = now+ else:+ values["status"] = "succeeded" if ok else "failed"+ values["completed_at"] = now+ if error is not None:+ values["error"] = error+ result = conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))+ if result.rowcount:+ completed_ids.append(run_id)+ return completed_ids+++def claim_queued_runs_for_workbench_in_connection(+ conn: Any,+ run_ids: list[str],+ *,+ started_at: Optional[str] = None,+) -> list[str]:+ normalized_run_ids: list[str] = []+ seen: set[str] = set()+ for raw_run_id in run_ids:+ run_id = str(raw_run_id or "").strip()+ if not run_id or run_id in seen:+ continue+ seen.add(run_id)+ normalized_run_ids.append(run_id)+ queued_run_ids, stale_run_ids = inspect_queued_runs_for_workbench_in_connection(conn, normalized_run_ids)+ if stale_run_ids or queued_run_ids != normalized_run_ids:+ return []+ primary_run_id = normalized_run_ids[0] if normalized_run_ids else ""+ if not primary_run_id:+ return []+ now = started_at or _utc_now_iso()+ rows = {+ row["id"]: row+ for row in conn.execute(select(agent_runs).where(agent_runs.c.id.in_(normalized_run_ids))).mappings()+ }+ for run_id in normalized_run_ids:+ row = rows[run_id]+ metadata = _json_loads(row["metadata_json"], {})+ if not isinstance(metadata, dict):+ metadata = {}+ metadata["workbench_queue_holds_run"] = run_id != primary_run_id+ metadata["effective_run_id"] = primary_run_id+ if run_id == primary_run_id and len(normalized_run_ids) > 1:+ metadata["coalesced_queue"] = _coalesced_agent_run_metadata(rows, normalized_run_ids)+ if run_id != primary_run_id:+ metadata["coalesced_into_run_id"] = primary_run_id+ result = conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_id)+ .where(agent_runs.c.status.in_(_status_query_values("queued")))+ .values(+ updated_at=now,+ metadata_json=_json_dumps(metadata),+ )+ )+ if not result.rowcount:+ raise RuntimeError(f"failed to claim queued agent run {run_id}")+ continue+ result = conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_id)+ .where(agent_runs.c.status.in_(_status_query_values("queued")))+ .values(+ status="running",+ started_at=now,+ updated_at=now,+ metadata_json=_json_dumps(metadata),+ )+ )+ if not result.rowcount:+ raise RuntimeError(f"failed to claim queued agent run {run_id}")+ return normalized_run_ids+++def _refresh_recovered_coalesced_workbench_runs_in_connection(conn: Any, *, now: str) -> None:+ rows = list(+ conn.execute(+ select(agent_runs)+ .where(agent_runs.c.run_type == "agent_run")+ .where(agent_runs.c.status.in_(_status_query_values("queued")))+ ).mappings()+ )+ rows_by_id = {row["id"]: row for row in rows}+ processed: set[str] = set()+ for row in rows:+ run_id = str(row["id"] or "")+ if run_id in processed:+ continue+ metadata = _json_loads(row["metadata_json"], {})+ if not isinstance(metadata, dict):+ metadata = {}+ coalesced = metadata.get("coalesced_queue") if isinstance(metadata, dict) else None+ raw_ids = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None+ if not isinstance(raw_ids, list):+ continue+ run_ids: list[str] = []+ for value in raw_ids:+ coalesced_id = str(value or "").strip()+ if coalesced_id and coalesced_id not in run_ids:+ run_ids.append(coalesced_id)+ if run_id not in run_ids:+ run_ids.insert(0, run_id)+ live_ids = [+ candidate+ for candidate in run_ids+ if candidate in rows_by_id+ and not bool(rows_by_id[candidate]["cancel_requested"])+ and normalize_run_status(rows_by_id[candidate]["status"]) == "queued"+ ]+ if not live_ids:+ processed.update(run_ids)+ continue+ primary_id = live_ids[0]+ live_rows = {candidate: rows_by_id[candidate] for candidate in live_ids}+ primary_metadata = _json_loads(rows_by_id[primary_id]["metadata_json"], {})+ if not isinstance(primary_metadata, dict):+ primary_metadata = {}+ primary_metadata["workbench_queue_holds_run"] = False+ primary_metadata["effective_run_id"] = primary_id+ primary_metadata.pop("coalesced_into_run_id", None)+ if len(live_ids) > 1:+ primary_metadata["coalesced_queue"] = _coalesced_agent_run_metadata(live_rows, live_ids)+ else:+ primary_metadata.pop("coalesced_queue", None)+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == primary_id)+ .values(metadata_json=_json_dumps(primary_metadata), updated_at=now)+ )+ for child_id in live_ids[1:]:+ child_metadata = _json_loads(rows_by_id[child_id]["metadata_json"], {})+ if not isinstance(child_metadata, dict):+ child_metadata = {}+ child_metadata["workbench_queue_holds_run"] = True+ child_metadata["effective_run_id"] = primary_id+ child_metadata["coalesced_into_run_id"] = primary_id+ child_metadata.pop("coalesced_queue", None)+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == child_id)+ .values(metadata_json=_json_dumps(child_metadata), updated_at=now)+ )+ processed.update(run_ids)+++def inspect_queued_runs_for_workbench_in_connection(conn: Any, run_ids: list[str]) -> tuple[list[str], list[str]]:+ normalized_run_ids: list[str] = []+ seen: set[str] = set()+ for raw_run_id in run_ids:+ run_id = str(raw_run_id or "").strip()+ if not run_id or run_id in seen:+ continue+ seen.add(run_id)+ normalized_run_ids.append(run_id)+ if not normalized_run_ids:+ return [], []+ rows = {+ row["id"]: row+ for row in conn.execute(select(agent_runs).where(agent_runs.c.id.in_(normalized_run_ids))).mappings()+ }+ queued_run_ids: list[str] = []+ stale_run_ids: list[str] = []+ cancel_requested_run_ids: list[str] = []+ for run_id in normalized_run_ids:+ row = rows.get(run_id)+ if row is None:+ stale_run_ids.append(run_id)+ continue+ if bool(row["cancel_requested"]):+ if normalize_run_status(row["status"]) == "queued":+ cancel_requested_run_ids.append(run_id)+ stale_run_ids.append(run_id)+ continue+ if normalize_run_status(row["status"]) != "queued":+ stale_run_ids.append(run_id)+ continue+ queued_run_ids.append(run_id)+ if cancel_requested_run_ids:+ now = _utc_now_iso()+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id.in_(cancel_requested_run_ids))+ .where(agent_runs.c.status.in_(_status_query_values("queued")))+ .values(status="canceled", completed_at=now, updated_at=now)+ )+ return queued_run_ids, stale_run_ids+++def reset_workbench_claimed_runs_in_connection(conn: Any, run_ids: list[str]) -> None:+ now = _utc_now_iso()+ seen: set[str] = set()+ for raw_run_id in run_ids:+ run_id = str(raw_run_id or "").strip()+ if not run_id or run_id in seen:+ continue+ seen.add(run_id)+ row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()+ if not row:+ continue+ metadata = _json_loads(row["metadata_json"], {})+ if not isinstance(metadata, dict):+ metadata = {}+ metadata["workbench_queue_holds_run"] = True+ metadata.pop("effective_run_id", None)+ metadata.pop("coalesced_into_run_id", None)+ values = {+ "updated_at": now,+ "metadata_json": _json_dumps(metadata),+ }+ if normalize_run_status(row["status"]) == "running":+ values["status"] = "queued"+ values["started_at"] = None+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_id)+ .values(**values)+ )++class SQLiteBackgroundTaskStore:def __init__(self, db_path: Optional[Path] = None):self.db_path = db_path or paths.get_sqlite_state_path()@@ -720,34 +991,20 @@ class SQLiteBackgroundTaskStore:*,started_at: Optional[str] = None,) -> bool:- now = started_at or _utc_now_iso()+ return self.claim_queued_runs_for_workbench([run_id], started_at=started_at) == [run_id]++ def claim_queued_runs_for_workbench(+ self,+ run_ids: list[str],+ *,+ started_at: Optional[str] = None,+ ) -> list[str]:with self.engine.begin() as conn:- row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()- if not row:- return False- if bool(row["cancel_requested"]) or normalize_run_status(row["status"]) == "canceled":- conn.execute(- update(agent_runs)- .where(agent_runs.c.id == run_id)- .values(status="canceled", completed_at=now, updated_at=now)- )- return False- metadata = _json_loads(row["metadata_json"], {})- if not isinstance(metadata, dict):- metadata = {}- metadata["workbench_queue_holds_run"] = False- result = conn.execute(- update(agent_runs)- .where(agent_runs.c.id == run_id)- .where(agent_runs.c.status.in_(_status_query_values("queued")))- .values(- status="running",- started_at=now,- updated_at=now,- metadata_json=_json_dumps(metadata),- )- )- return bool(result.rowcount)+ return claim_queued_runs_for_workbench_in_connection(conn, run_ids, started_at=started_at)++ def inspect_queued_runs_for_workbench(self, run_ids: list[str]) -> tuple[list[str], list[str]]:+ with self.engine.begin() as conn:+ return inspect_queued_runs_for_workbench_in_connection(conn, run_ids)def record_run_message(self,@@ -788,12 +1045,14 @@ class SQLiteBackgroundTaskStore:def recover_processing_runs(self) -> None:with self.engine.begin() as conn:+ now = _utc_now_iso()conn.execute(update(agent_runs).where(agent_runs.c.status.in_(_status_query_values("running"))).where(agent_runs.c.run_type != "watch_runtime")- .values(status="queued", started_at=None, pid=None)+ .values(status="queued", started_at=None, pid=None, updated_at=now))+ _refresh_recovered_coalesced_workbench_runs_in_connection(conn, now=now)def write_watch_runtime(self, payload: dict[str, Any], *, updated_at: str) -> None:watches = payload.get("watches", {}) if isinstance(payload, dict) else {}diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 7cb0b1c11..7d822d462 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -24,6 +24,7 @@ from pathlib import Pathfrom unittest.mock import AsyncMock, MagicMockimport httpx+from sqlalchemy import selectsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -1434,6 +1435,674 @@ def test_flush_coalesces_same_scheduled_callbacks_within_window(tmp_path, monkeyassert dedupe_native_ids == {"watch:def-watch:run-2", "watch:def-watch:run-3"}+def test_flush_claims_every_coalesced_agent_run(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import SQLiteBackgroundTaskStore++ request_store = TaskExecutionStore()++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ "source_kind": None,+ "callback_session_id": None,+ },+ }++ queued: list[tuple[str, dict]] = []+ for index in range(4):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"cli agent message {index + 1}",+ agent_name="codex",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ queued.append((f"cli agent message {index + 1}", prov(request.id)))++ session_id = _seed_avibe_session_with_queue(queued)++ from sqlalchemy import update+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.models import messages++ with create_sqlite_engine().begin() as conn:+ rows = messages_service.list_queued(conn, session_id)+ for index, row in enumerate(rows):+ conn.execute(+ update(messages)+ .where(messages.c.id == row["id"])+ .values(created_at=f"2026-06-22T00:00:0{index}Z")+ )++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ text, source, ctx = runs[0]+ assert source == SOURCE_SCHEDULED+ assert "cli agent message 1" in text+ assert "cli agent message 2" in text+ assert "cli agent message 3" in text+ assert "cli agent message 4" in text+ execution_ids = ctx.platform_specific["coalesced_queue"]["execution_ids"]+ assert len(execution_ids) == 4++ bg = SQLiteBackgroundTaskStore()+ try:+ stored = {run_id: bg.get_run(run_id) for run_id in execution_ids}+ finally:+ bg.close()++ assert stored[execution_ids[0]]["status"] == "running"+ assert [stored[run_id]["status"] for run_id in execution_ids[1:]] == ["queued", "queued", "queued"]+ assert [stored[run_id]["metadata"]["effective_run_id"] for run_id in execution_ids] == [+ execution_ids[0],+ execution_ids[0],+ execution_ids[0],+ execution_ids[0],+ ]+ assert stored[execution_ids[0]]["metadata"].get("coalesced_into_run_id") is None+ assert [stored[run_id]["metadata"]["coalesced_into_run_id"] for run_id in execution_ids[1:]] == [+ execution_ids[0],+ execution_ids[0],+ execution_ids[0],+ ]+ assert stored[execution_ids[0]]["metadata"]["workbench_queue_holds_run"] is False+ assert [stored[run_id]["metadata"]["workbench_queue_holds_run"] for run_id in execution_ids[1:]] == [+ True,+ True,+ True,+ ]+++def test_coalesced_agent_run_claim_is_atomic(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import SQLiteBackgroundTaskStore++ request_store = TaskExecutionStore()+ run_ids: list[str] = []+ for index in range(3):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"cli agent message {index + 1}",+ agent_name="codex",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ run_ids.append(request.id)++ bg = SQLiteBackgroundTaskStore()+ try:+ assert bg.cancel_run(run_ids[1]) is True+ assert bg.claim_queued_runs_for_workbench(run_ids) == []+ stored = {run_id: bg.get_run(run_id) for run_id in run_ids}+ finally:+ bg.close()++ assert stored[run_ids[0]]["status"] == "queued"+ assert stored[run_ids[1]]["status"] == "canceled"+ assert stored[run_ids[2]]["status"] == "queued"+ assert {row["status"] for row in stored.values()} == {"queued", "canceled"}+ assert all(row["status"] != "running" for row in stored.values())+ assert stored[run_ids[0]]["metadata"]["workbench_queue_holds_run"] is True+ assert stored[run_ids[2]]["metadata"]["workbench_queue_holds_run"] is True+ assert stored[run_ids[0]]["metadata"].get("effective_run_id") is None+ assert stored[run_ids[2]]["metadata"].get("effective_run_id") is None+++def test_flush_removes_stale_coalesced_agent_run_row_and_dispatches_survivors(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import SQLiteBackgroundTaskStore++ request_store = TaskExecutionStore()++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ "source_kind": None,+ "callback_session_id": None,+ },+ }++ queued: list[tuple[str, dict]] = []+ run_ids: list[str] = []+ for index in range(3):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"cli agent message {index + 1}",+ agent_name="codex",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ queued.append((f"cli agent message {index + 1}", prov(request.id)))+ run_ids.append(request.id)++ session_id = _seed_avibe_session_with_queue(queued)++ from storage import messages_service+ from storage.db import create_sqlite_engine++ bg = SQLiteBackgroundTaskStore()+ try:+ assert bg.cancel_run(run_ids[1]) is True+ finally:+ bg.close()++ from core.inbox_events import bus++ published: list[tuple[str, dict]] = []+ monkeypatch.setattr(bus, "publish", lambda event, payload: published.append((event, payload)))++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ text, source, ctx = runs[0]+ assert source == SOURCE_SCHEDULED+ assert "cli agent message 1" in text+ assert "cli agent message 3" in text+ assert "cli agent message 2" not in text+ assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == [run_ids[0], run_ids[2]]++ with create_sqlite_engine().begin() as conn:+ queued_rows = messages_service.list_queued(conn, session_id)+ assert queued_rows == []++ bg = SQLiteBackgroundTaskStore()+ try:+ stored = {run_id: bg.get_run(run_id) for run_id in run_ids}+ finally:+ bg.close()++ assert stored[run_ids[0]]["status"] == "running"+ assert stored[run_ids[1]]["status"] == "canceled"+ assert stored[run_ids[2]]["status"] == "queued"+ assert stored[run_ids[0]]["metadata"]["workbench_queue_holds_run"] is False+ assert stored[run_ids[2]]["metadata"]["workbench_queue_holds_run"] is True+ assert published.count(("queue.updated", {"session_id": session_id})) >= 2+++def test_flush_preserves_recovered_coalesced_agent_run_children(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore++ request_store = TaskExecutionStore()++ def prov(execution_id: str, coalesced_ids: list[str] | None = None) -> dict:+ platform_specific = {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ "source_kind": None,+ "callback_session_id": None,+ }+ if coalesced_ids:+ platform_specific["coalesced_queue"] = {"execution_ids": coalesced_ids}+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": platform_specific,+ }++ recovered_ids: list[str] = []+ for index in range(2):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"recovered message {index + 1}",+ agent_name="codex",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": index != 0})+ recovered_ids.append(request.id)+ new_request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message="new message",+ agent_name="codex",+ )+ assert request_store.claim(new_request.id) is not None+ request_store.requeue(new_request.id, metadata={"workbench_queue_holds_run": True})++ session_id = _seed_avibe_session_with_queue(+ [+ ("recovered primary", prov(recovered_ids[0], recovered_ids)),+ ("new message", prov(new_request.id)),+ ]+ )++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ _text, source, ctx = runs[0]+ assert source == SOURCE_SCHEDULED+ assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == [+ recovered_ids[0],+ recovered_ids[1],+ new_request.id,+ ]+++def test_flush_retargets_recovered_coalesced_row_when_primary_is_stale(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import SQLiteBackgroundTaskStore++ request_store = TaskExecutionStore()++ def prov(execution_id: str, coalesced_ids: list[str]) -> dict:+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ "source_kind": None,+ "callback_session_id": None,+ "coalesced_queue": {+ "execution_ids": coalesced_ids,+ "messages": [+ {"execution_id": coalesced_ids[0], "message": "stale primary prompt"},+ {"execution_id": coalesced_ids[1], "message": "surviving child prompt"},+ ],+ },+ },+ }++ run_ids: list[str] = []+ for index in range(2):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"coalesced message {index + 1}",+ agent_name="codex",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": index != 0})+ run_ids.append(request.id)++ session_id = _seed_avibe_session_with_queue(+ [("stale primary prompt", prov(run_ids[0], run_ids))]+ )++ bg = SQLiteBackgroundTaskStore()+ try:+ assert bg.cancel_run(run_ids[0]) is True+ finally:+ bg.close()++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ text, source, ctx = runs[0]+ assert source == SOURCE_SCHEDULED+ assert text == "surviving child prompt"+ assert ctx.message_id == f"agent_run:{run_ids[1]}"+ assert ctx.platform_specific["task_execution_id"] == run_ids[1]+ assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == [run_ids[1]]++ bg = SQLiteBackgroundTaskStore()+ try:+ stored = {run_id: bg.get_run(run_id) for run_id in run_ids}+ finally:+ bg.close()+ assert stored[run_ids[0]]["status"] == "canceled"+ assert stored[run_ids[1]]["status"] == "running"+++def test_flush_retries_when_agent_run_claim_finds_late_stale_row(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore+ from storage import background as background_module+ from storage.background import SQLiteBackgroundTaskStore+ from storage.models import agent_runs+ from sqlalchemy import update++ request_store = TaskExecutionStore()++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ "source_kind": None,+ "callback_session_id": None,+ },+ }++ queued: list[tuple[str, dict]] = []+ run_ids: list[str] = []+ for index in range(3):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"cli agent message {index + 1}",+ agent_name="codex",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ queued.append((f"cli agent message {index + 1}", prov(request.id)))+ run_ids.append(request.id)++ session_id = _seed_avibe_session_with_queue(queued)+ real_claim = background_module.claim_queued_runs_for_workbench_in_connection+ injected = {"done": False}++ def late_stale_claim(conn, pending_run_ids, *, started_at=None):+ if not injected["done"]:+ injected["done"] = True+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_ids[1])+ .values(status="canceled", cancel_requested=1, completed_at="2026-06-22T00:00:10Z")+ )+ return []+ return real_claim(conn, pending_run_ids, started_at=started_at)++ monkeypatch.setattr(background_module, "claim_queued_runs_for_workbench_in_connection", late_stale_claim)+ monkeypatch.setattr(session_turns, "claim_queued_runs_for_workbench_in_connection", late_stale_claim, raising=False)++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ text, source, ctx = runs[0]+ assert source == SOURCE_SCHEDULED+ assert "cli agent message 1" in text+ assert "cli agent message 3" in text+ assert "cli agent message 2" not in text+ assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == [run_ids[0], run_ids[2]]++ bg = SQLiteBackgroundTaskStore()+ try:+ stored = {run_id: bg.get_run(run_id) for run_id in run_ids}+ finally:+ bg.close()++ assert stored[run_ids[0]]["status"] == "running"+ assert stored[run_ids[1]]["status"] == "canceled"+ assert stored[run_ids[2]]["status"] == "queued"+++def test_flush_does_not_coalesce_agent_runs_with_different_callback_targets(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore++ request_store = TaskExecutionStore()++ def prov(execution_id: str, callback_session_id: str) -> dict:+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ "callback_session_id": callback_session_id,+ },+ }++ queued: list[tuple[str, dict]] = []+ for index, callback_session_id in enumerate(["caller-a", "caller-b"]):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"cli agent message {index + 1}",+ agent_name="codex",+ callback_session_id=callback_session_id,+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ queued.append((f"cli agent message {index + 1}", prov(request.id, callback_session_id)))++ session_id = _seed_avibe_session_with_queue(queued)++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ text, source, ctx = runs[0]+ assert source == SOURCE_SCHEDULED+ assert text == "cli agent message 1"+ assert "coalesced_queue" not in ctx.platform_specific+++def test_flush_does_not_coalesce_callback_backed_agent_runs(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore++ request_store = TaskExecutionStore()++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ "callback_session_id": "same-caller",+ },+ }++ queued: list[tuple[str, dict]] = []+ for index in range(2):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"callback agent message {index + 1}",+ agent_name="codex",+ callback_session_id="same-caller",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ queued.append((f"callback agent message {index + 1}", prov(request.id)))++ session_id = _seed_avibe_session_with_queue(queued)++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ text, source, ctx = runs[0]+ assert source == SOURCE_SCHEDULED+ assert text == "callback agent message 1"+ assert "coalesced_queue" not in ctx.platform_specific+++def test_flush_isolates_legacy_agent_runs_without_source_provenance(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore++ request_store = TaskExecutionStore()++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ },+ }++ queued: list[tuple[str, dict]] = []+ for index in range(2):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"legacy callback message {index + 1}",+ agent_name="codex",+ callback_session_id=f"caller-{index + 1}",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ queued.append((f"legacy callback message {index + 1}", prov(request.id)))++ session_id = _seed_avibe_session_with_queue(queued)++ mgr, runs = _manager_capturing_runs()++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ text, source, ctx = runs[0]+ assert source == SOURCE_SCHEDULED+ assert text == "legacy callback message 1"+ assert "coalesced_queue" not in ctx.platform_specific+++def test_flush_does_not_claim_agent_runs_when_context_build_fails(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import SQLiteBackgroundTaskStore++ request_store = TaskExecutionStore()++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ "source_kind": None,+ "callback_session_id": None,+ },+ }++ queued: list[tuple[str, dict]] = []+ run_ids: list[str] = []+ for index in range(2):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"cli agent message {index + 1}",+ agent_name="codex",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ queued.append((f"cli agent message {index + 1}", prov(request.id)))+ run_ids.append(request.id)++ session_id = _seed_avibe_session_with_queue(queued)++ mgr = session_turns.SessionTurnManager(+ controller=types.SimpleNamespace(),+ build_context=lambda _sid: (_ for _ in ()).throw(RuntimeError("context unavailable")),+ )++ assert asyncio.run(mgr.flush_queue(session_id)) is False++ from storage import messages_service+ from storage.db import create_sqlite_engine++ from storage.models import messages++ with create_sqlite_engine().begin() as conn:+ queued_rows = messages_service.list_queued(conn, session_id)+ dedupe_rows = conn.execute(+ select(messages)+ .where(messages.c.session_id == session_id)+ .where(messages.c.type == messages_service.HARNESS_DEDUPE_TYPE)+ ).mappings().all()+ assert [row["text"] for row in queued_rows] == ["cli agent message 1", "cli agent message 2"]+ assert dedupe_rows == []++ bg = SQLiteBackgroundTaskStore()+ try:+ stored = {run_id: bg.get_run(run_id) for run_id in run_ids}+ finally:+ bg.close()++ assert {row["status"] for row in stored.values()} == {"queued"}+ assert all(row["metadata"]["workbench_queue_holds_run"] is True for row in stored.values())+++def test_flush_resets_agent_run_claim_when_run_start_fails(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import SQLiteBackgroundTaskStore++ request_store = TaskExecutionStore()++ def prov(execution_id: str) -> dict:+ return {+ "message_id": f"agent_run:{execution_id}",+ "platform_specific": {+ "task_execution_id": execution_id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ },+ }++ queued: list[tuple[str, dict]] = []+ run_ids: list[str] = []+ for index in range(2):+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message=f"cli agent message {index + 1}",+ agent_name="codex",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ queued.append((f"cli agent message {index + 1}", prov(request.id)))+ run_ids.append(request.id)++ session_id = _seed_avibe_session_with_queue(queued)+ mgr, _runs = _manager_capturing_runs()++ async def _failing_run(*_args, **_kwargs):+ raise RuntimeError("dispatch did not start")++ mgr._run = _failing_run++ assert asyncio.run(mgr.flush_queue(session_id)) is False++ from storage import messages_service+ from storage.db import create_sqlite_engine++ with create_sqlite_engine().begin() as conn:+ queued_rows = messages_service.list_queued(conn, session_id)+ assert [row["text"] for row in queued_rows] == ["cli agent message 1", "cli agent message 2"]++ bg = SQLiteBackgroundTaskStore()+ try:+ stored = {run_id: bg.get_run(run_id) for run_id in run_ids}+ finally:+ bg.close()++ assert {row["status"] for row in stored.values()} == {"queued"}+ assert all(row["metadata"]["workbench_queue_holds_run"] is True for row in stored.values())+ assert all(row["metadata"].get("effective_run_id") is None for row in stored.values())++def test_flush_marks_suppressed_first_native_id(tmp_path, monkeypatch):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pyindex f84c0c224..c3dc96449 100644--- a/tests/test_message_dispatcher_scheduled.py+++ b/tests/test_message_dispatcher_scheduled.py@@ -246,6 +246,163 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):],)+ async def test_suppressed_coalesced_agent_run_result_preserves_cancelled_child(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "suppress_delivery": True,+ "task_trigger_kind": "agent_run",+ "task_execution_id": "run-1",+ "coalesced_queue": {"execution_ids": ["run-1", "run-2", "run-3"]},+ },+ )+ calls = []++ class _Store:+ def get_run(self, run_id):+ if run_id == "run-2":+ return {"id": run_id, "status": "canceled", "cancel_requested": True}+ return {"id": run_id, "status": "queued", "cancel_requested": False}++ def record_run_message(self, run_id, *, text, message_id=None, terminal_status=None):+ calls.append(("record", run_id, text, message_id, terminal_status))++ def close(self):+ calls.append(("close",))++ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):+ message_id = await dispatcher.emit_agent_message(context, "result", "private agent output")++ self.assertEqual(message_id, "suppressed:run-1")+ self.assertEqual(+ calls,+ [+ ("record", "run-1", "private agent output", "suppressed:run-1", "succeeded"),+ ("record", "run-3", "private agent output", "suppressed:run-1", "succeeded"),+ ("close",),+ ],+ )++ async def test_coalesced_agent_run_result_marks_each_run_terminal(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "task_trigger_kind": "agent_run",+ "task_execution_id": "run-1",+ "coalesced_queue": {"execution_ids": ["run-1", "run-2", "run-3"]},+ },+ )+ calls = []++ class _Store:+ def record_run_message(self, run_id, *, text, message_id=None, terminal_status=None):+ calls.append(("record", run_id, text, message_id, terminal_status))++ def close(self):+ calls.append(("close",))++ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):+ message_id = await dispatcher.emit_agent_message(context, "result", "shared visible result")++ self.assertEqual(message_id, "bot-msg-1")+ self.assertEqual(+ calls,+ [+ ("record", "run-1", "shared visible result", "bot-msg-1", "succeeded"),+ ("record", "run-2", "shared visible result", "bot-msg-1", "succeeded"),+ ("record", "run-3", "shared visible result", "bot-msg-1", "succeeded"),+ ("close",),+ ],+ )++ async def test_coalesced_agent_run_result_preserves_cancelled_child(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "task_trigger_kind": "agent_run",+ "task_execution_id": "run-1",+ "coalesced_queue": {"execution_ids": ["run-1", "run-2", "run-3"]},+ },+ )+ calls = []++ class _Store:+ def get_run(self, run_id):+ if run_id == "run-2":+ return {"id": run_id, "status": "canceled", "cancel_requested": True}+ return {"id": run_id, "status": "queued", "cancel_requested": False}++ def record_run_message(self, run_id, *, text, message_id=None, terminal_status=None):+ calls.append(("record", run_id, text, message_id, terminal_status))++ def close(self):+ calls.append(("close",))++ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):+ message_id = await dispatcher.emit_agent_message(context, "result", "shared visible result")++ self.assertEqual(message_id, "bot-msg-1")+ self.assertEqual(+ calls,+ [+ ("record", "run-1", "shared visible result", "bot-msg-1", "succeeded"),+ ("record", "run-3", "shared visible result", "bot-msg-1", "succeeded"),+ ("close",),+ ],+ )++ async def test_coalesced_agent_run_result_records_running_cancel_requested_run_terminal(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "task_trigger_kind": "agent_run",+ "task_execution_id": "run-1",+ "coalesced_queue": {"execution_ids": ["run-1", "run-2"]},+ },+ )+ calls = []++ class _Store:+ def get_run(self, run_id):+ if run_id == "run-1":+ return {"id": run_id, "status": "running", "cancel_requested": True}+ return {"id": run_id, "status": "queued", "cancel_requested": False}++ def record_run_message(self, run_id, *, text, message_id=None, terminal_status=None):+ calls.append(("record", run_id, text, message_id, terminal_status))++ def close(self):+ calls.append(("close",))++ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):+ message_id = await dispatcher.emit_agent_message(context, "result", "shared visible result")++ self.assertEqual(message_id, "bot-msg-1")+ self.assertEqual(+ calls,+ [+ ("record", "run-1", "shared visible result", "bot-msg-1", "succeeded"),+ ("record", "run-2", "shared visible result", "bot-msg-1", "succeeded"),+ ("close",),+ ],+ )+async def test_suppressed_agent_run_ignores_non_result_process_messages(self):controller = _StubController()dispatcher = ConsolidatedMessageDispatcher(controller)diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 7f89fafde..7fa0fe7ee 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -7,6 +7,7 @@ from pathlib import Pathfrom types import SimpleNamespaceimport pytest+from sqlalchemy import selectsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -17,6 +18,7 @@ from core.scheduled_tasks import (ScheduledTaskStore,TaskExecutionRequest,TaskExecutionStore,+ _agent_run_message_for_request,build_session_key_for_context,parse_session_key,resolve_session_id_target,@@ -1531,6 +1533,219 @@ def test_agent_run_preserves_failed_terminal_status(tmp_path: Path, monkeypatch)assert completed["result_text"] == "terminal failed"+def test_duplicate_recovered_coalesced_agent_run_settles_held_children(tmp_path: Path, monkeypatch) -> None:+ session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ run_ids: list[str] = []+ for index in range(2):+ request = request_store.enqueue_agent_run(+ session_id=session_id,+ message=f"coalesced prompt {index + 1}",+ agent_name="codex",+ metadata={"workbench_queue_holds_run": True},+ )+ run_ids.append(request.id)++ sqlite_store = request_store._sqlite+ assert sqlite_store is not None+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids+ request_store.recover_processing()++ async def _submit_scheduled(_sid, _ctx, _text):+ return "duplicate"++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ return None++ gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})+ controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)+ service = ScheduledTaskService(+ controller=controller,+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )++ asyncio.run(service._drain_requests())+ stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}++ assert stored[run_ids[0]]["status"] == "succeeded"+ assert stored[run_ids[1]]["status"] == "succeeded"+ assert stored[run_ids[0]]["completed_at"] is not None+ assert stored[run_ids[1]]["completed_at"] is not None+++def test_recover_processing_rebuilds_coalesced_metadata_without_queue_rows(+ tmp_path: Path,+ monkeypatch,+) -> None:+ session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ run_ids: list[str] = []+ for index in range(3):+ request = request_store.enqueue_agent_run(+ session_id=session_id,+ message=f"coalesced prompt {index + 1}",+ agent_name="codex",+ metadata={"workbench_queue_holds_run": True},+ )+ run_ids.append(request.id)++ sqlite_store = request_store._sqlite+ assert sqlite_store is not None+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids++ request_store.recover_processing()+ pending = request_store.list_pending()++ assert [request.id for request in pending] == [run_ids[0]]+ assert pending[0].metadata["coalesced_queue"]["execution_ids"] == run_ids+ assert _agent_run_message_for_request(pending[0]) == (+ "coalesced prompt 1\n\n---\n\ncoalesced prompt 2\n\n---\n\ncoalesced prompt 3"+ )+++def test_recovered_agent_run_retires_stale_queued_native_rows_before_gate(+ tmp_path: Path,+ monkeypatch,+) -> None:+ session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ run_ids: list[str] = []+ for index in range(2):+ request = request_store.enqueue_agent_run(+ session_id=session_id,+ message=f"coalesced prompt {index + 1}",+ agent_name="codex",+ metadata={"workbench_queue_holds_run": True},+ )+ run_ids.append(request.id)++ sqlite_store = request_store._sqlite+ assert sqlite_store is not None+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids+ request_store.recover_processing()++ from storage import messages_service+ from storage.models import agent_sessions, messages++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ session = conn.execute(+ select(agent_sessions).where(agent_sessions.c.id == session_id).limit(1)+ ).mappings().first()+ assert session is not None+ scope_id = session["scope_id"]+ for run_id in run_ids:+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.QUEUED_TYPE,+ text=f"stale queued row for {run_id}",+ native_message_id=f"agent_run:{run_id}",+ )++ submitted: list[str] = []++ async def _submit_scheduled(_sid, ctx, text):+ with engine.connect() as conn:+ if messages_service.native_message_exists(+ conn,+ platform="avibe",+ native_message_id=ctx.message_id,+ ):+ return "duplicate"+ submitted.append(text)+ return "ran"++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ return None++ gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})+ controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)+ service = ScheduledTaskService(+ controller=controller,+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )++ async def _exercise() -> None:+ await service._drain_requests()+ execution = service._inflight_executions.get(run_ids[0])+ if execution is not None:+ await execution++ asyncio.run(_exercise())++ assert len(submitted) == 1+ assert "coalesced prompt 1" in submitted[0]+ assert "coalesced prompt 2" in submitted[0]+ with engine.connect() as conn:+ assert messages_service.list_queued(conn, session_id) == []+ dedupe_rows = conn.execute(+ select(messages.c.native_message_id, messages.c.type)+ .where(messages.c.session_id == session_id)+ .where(messages.c.type == messages_service.HARNESS_DEDUPE_TYPE)+ ).all()+ assert {row.native_message_id for row in dedupe_rows} == {f"agent_run:{run_ids[1]}"}+ stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}+ assert stored[run_ids[0]]["status"] == "running"+ assert stored[run_ids[1]]["status"] == "queued"+++def test_recovered_coalesced_agent_run_early_failure_settles_children(tmp_path: Path, monkeypatch) -> None:+ session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ run_ids: list[str] = []+ for index in range(2):+ request = request_store.enqueue_agent_run(+ session_id=session_id,+ message=f"coalesced prompt {index + 1}",+ agent_name="codex",+ metadata={"workbench_queue_holds_run": True},+ )+ run_ids.append(request.id)++ sqlite_store = request_store._sqlite+ assert sqlite_store is not None+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids+ request_store.recover_processing()+ claimed = request_store.claim(run_ids[0])+ assert claimed is not None++ async def _submit_scheduled(_sid, _ctx, _text):+ raise AssertionError("the direct execution path should be patched below")++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ return None++ gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})+ controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)+ service = ScheduledTaskService(+ controller=controller,+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )++ async def _raise_early(**_kwargs):+ raise RuntimeError("target session vanished")++ service._execute_agent_run = _raise_early++ asyncio.run(service._execute_claimed_request(claimed))+ stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}++ assert stored[run_ids[0]]["status"] == "failed"+ assert stored[run_ids[1]]["status"] == "failed"+ assert stored[run_ids[0]]["completed_at"] is not None+ assert stored[run_ids[1]]["completed_at"] is not None+ assert stored[run_ids[0]]["error"] == "target session vanished"+ assert stored[run_ids[1]]["error"] == "target session vanished"++def test_agent_run_callback_enqueues_only_result_to_caller_session(tmp_path: Path, monkeypatch) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))caller_session_id = _make_avibe_session(monkeypatch, tmp_path)@@ -1849,6 +2064,108 @@ def test_workbench_queue_flush_recovery_preserves_session_fork_metadata(monkeypaassert claimed.metadata["session_fork"]["source_native_session_id"] == "thread-source"+def test_recover_processing_keeps_coalesced_agent_run_children_held(monkeypatch, tmp_path) -> None:+ session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ run_ids: list[str] = []+ for index in range(3):+ request = request_store.enqueue_agent_run(+ session_id=session_id,+ message=f"coalesced prompt {index + 1}",+ agent_name="codex",+ metadata={"workbench_queue_holds_run": True},+ )+ run_ids.append(request.id)++ sqlite_store = request_store._sqlite+ assert sqlite_store is not None+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids++ request_store.recover_processing()+ pending = request_store.list_pending()++ assert [request.id for request in pending] == [run_ids[0]]+ primary = request_store.get_run(run_ids[0])+ child = request_store.get_run(run_ids[1])+ assert primary is not None+ assert child is not None+ assert primary["status"] == "queued"+ assert child["status"] == "queued"+ assert primary["metadata"]["workbench_queue_holds_run"] is False+ assert primary["metadata"]["coalesced_queue"]["execution_ids"] == run_ids+ assert primary["metadata"]["coalesced_queue"]["messages"] == [+ {"execution_id": run_ids[0], "message": "coalesced prompt 1"},+ {"execution_id": run_ids[1], "message": "coalesced prompt 2"},+ {"execution_id": run_ids[2], "message": "coalesced prompt 3"},+ ]+ assert child["metadata"]["workbench_queue_holds_run"] is True+ assert child["metadata"]["coalesced_into_run_id"] == run_ids[0]++ claimed = request_store.claim(run_ids[0])+ assert claimed is not None+ recovered_message = _agent_run_message_for_request(claimed)+ assert "coalesced prompt 1" in recovered_message+ assert "coalesced prompt 2" in recovered_message+ assert "coalesced prompt 3" in recovered_message+++def test_recovered_coalesced_agent_run_message_filters_cancelled_child(monkeypatch, tmp_path) -> None:+ session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ run_ids: list[str] = []+ for index in range(3):+ request = request_store.enqueue_agent_run(+ session_id=session_id,+ message=f"coalesced prompt {index + 1}",+ agent_name="codex",+ metadata={"workbench_queue_holds_run": True},+ )+ run_ids.append(request.id)++ sqlite_store = request_store._sqlite+ assert sqlite_store is not None+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids+ request_store.recover_processing()+ assert sqlite_store.cancel_run(run_ids[1]) is True++ claimed = request_store.claim(run_ids[0])+ assert claimed is not None+ recovered_message = _agent_run_message_for_request(claimed)++ assert "coalesced prompt 1" in recovered_message+ assert "coalesced prompt 2" not in recovered_message+ assert "coalesced prompt 3" in recovered_message+++def test_inspect_queued_runs_finalizes_cancel_requested_queued_agent_run(monkeypatch, tmp_path) -> None:+ _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message="queued cancel request",+ agent_name="codex",+ metadata={"workbench_queue_holds_run": True},+ )+ bg = request_store._sqlite+ assert bg is not None+ bg.update_run_status(+ request.id,+ status="queued",+ updated_at="2026-06-22T00:00:00Z",+ cancel_requested=True,+ cancel_requested_at="2026-06-22T00:00:01Z",+ )++ queued_run_ids, stale_run_ids = bg.inspect_queued_runs_for_workbench([request.id])++ assert queued_run_ids == []+ assert stale_run_ids == [request.id]+ stored = bg.get_run(request.id)+ assert stored is not None+ assert stored["status"] == "canceled"+ assert stored["completed_at"] is not None++def test_drain_requests_reserves_watch_create_per_run_before_session_validation(tmp_path: Path) -> None:request_store = TaskExecutionStore(tmp_path / "task_requests")request = request_store.enqueue_definition_run(