Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(scheduled-research): push a finished briefing on the terminal event

Haozhe Wu9b1f49867afd
diff --git a/agent/src/api/state.py b/agent/src/api/state.py
index 469e14cbb..614901a37 100644
--- a/agent/src/api/state.py
+++ b/agent/src/api/state.py
@@ -67,9 +67,37 @@ def _get_session_service():
runs_dir=runs_dir,
)
_set_host_attr("_session_service", _session_service)
+ _attach_delivery_listener(event_bus)
return _session_service
+#: Terminal attempt events a finished scheduled briefing can follow.
+_DELIVERY_TRIGGER_EVENTS = frozenset(
+ {"attempt.completed", "attempt.failed", "attempt.cancelled"}
+)
+
+
+def _attach_delivery_listener(event_bus) -> None:
+ """Let a finished run push its briefing without waiting for the next tick.
+
+ The listener only *asks* for a sweep. Delivery correctness lives in the
+ periodic sweep and the persisted outbox row; this is latency, and it is
+ written so that failing to fire costs nothing but the wait.
+
+ Args:
+ event_bus: The session event bus to listen on.
+ """
+
+ def _on_event(event) -> None:
+ if event.event_type not in _DELIVERY_TRIGGER_EVENTS:
+ return
+ from src.api.scheduled_routes import _get_scheduled_research_executor
+
+ _get_scheduled_research_executor().request_sweep()
+
+ event_bus.add_listener(_on_event)
+
+
def _get_channel_runtime():
"""Lazy-init IM channel runtime without starting platform adapters."""
global _channel_runtime, _channel_bus, _channel_manager
diff --git a/agent/src/scheduled_research/executor.py b/agent/src/scheduled_research/executor.py
index d084be06e..67603015f 100644
--- a/agent/src/scheduled_research/executor.py
+++ b/agent/src/scheduled_research/executor.py
@@ -219,6 +219,8 @@ class ScheduledResearchExecutor:
self._briefing_reader = briefing_reader
self._channel_sender = channel_sender
self._delivery_lease_ms = delivery_lease_ms
+ self._loop: asyncio.AbstractEventLoop | None = None
+ self._sweep_task: asyncio.Task | None = None
self._tick_interval_ms = tick_interval_ms
self._now_fn = now_fn
self._enabled = enabled
@@ -342,6 +344,10 @@ class ScheduledResearchExecutor:
return recovered
async def _run(self) -> None:
+ # Captured here rather than at construction: the executor is built
+ # before the server's loop exists, and request_sweep needs a loop that
+ # is actually running to schedule onto.
+ self._loop = asyncio.get_running_loop()
while not self._stopping:
try:
await self.tick(self._now_fn())
@@ -481,6 +487,43 @@ class ScheduledResearchExecutor:
claimed_at = job.delivery.updated_at
return claimed_at is None or now_ms - claimed_at >= self._delivery_lease_ms
+ def request_sweep(self) -> None:
+ """Ask for a delivery sweep as soon as the loop is free.
+
+ Called from the session event listener, so it runs on whichever thread
+ published the event and must not block. Sweeps coalesce: one already in
+ flight covers anything that arrived while it was running, and the claim
+ makes an overlap harmless in any case. Without a running loop this is a
+ no-op — the periodic tick is what makes delivery correct, and this only
+ makes it prompt.
+ """
+ loop = self._loop
+ if loop is None or not loop.is_running():
+ return
+ if self._sweep_task is not None and not self._sweep_task.done():
+ return
+
+ def _schedule() -> None:
+ if self._sweep_task is not None and not self._sweep_task.done():
+ return
+ self._sweep_task = loop.create_task(self._sweep_quietly())
+
+ try:
+ loop.call_soon_threadsafe(_schedule)
+ except RuntimeError:
+ # The loop closed between the check and the call; the next tick
+ # picks the row up.
+ pass
+
+ async def _sweep_quietly(self) -> None:
+ """Run a sweep whose failure must not escape into the event path."""
+ try:
+ await self.sweep_deliveries()
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.error("requested delivery sweep failed", exc_info=True)
+
async def sweep_deliveries(self) -> int:
"""Deliver every briefing whose run has reached a terminal state.
diff --git a/agent/src/session/events.py b/agent/src/session/events.py
index c3fcda420..ab126c53d 100644
--- a/agent/src/session/events.py
+++ b/agent/src/session/events.py
@@ -14,7 +14,7 @@ import uuid
logger = logging.getLogger(__name__)
from dataclasses import dataclass, field
-from typing import Any, AsyncIterator, Dict, List, Optional
+from typing import Any, AsyncIterator, Callable, Dict, List, Optional
@dataclass
@@ -73,6 +73,7 @@ class EventBus:
self.max_buffer_size = max_buffer_size
self._buffers: Dict[str, List[SSEEvent]] = {}
self._subscribers: Dict[str, List[asyncio.Queue]] = {}
+ self._listeners: List[Callable[[SSEEvent], None]] = []
self._lock = threading.Lock()
self._loop: Optional[asyncio.AbstractEventLoop] = None
@@ -100,6 +101,17 @@ class EventBus:
self._buffers[session_id] = buffer[-self.max_buffer_size:]
queues = list(self._subscribers.get(session_id, []))
+ listeners = list(self._listeners)
+
+ # Listeners run before the queues so a slow subscriber cannot delay
+ # them, and each is isolated: this is the SSE hot path, and a listener
+ # that raises must not cost the UI its event stream. A listener is
+ # expected to record or schedule, never to do I/O inline.
+ for listener in listeners:
+ try:
+ listener(event)
+ except Exception:
+ logger.exception("EventBus listener failed for %s", event.event_type)
# Safely enqueue onto the queue from inside the asyncio loop.
for queue in queues:
@@ -111,6 +123,33 @@ class EventBus:
except asyncio.QueueFull:
pass
+ def add_listener(self, listener: Callable[[SSEEvent], None]) -> None:
+ """Register a callback invoked for every published event.
+
+ Unlike :meth:`subscribe`, which is per session and per SSE connection,
+ a listener sees every session — which is what a component that reacts
+ to runs it did not open needs.
+
+ Args:
+ listener: Synchronous callback. It runs on the publishing thread,
+ so it must be cheap and must not raise; schedule any real work
+ elsewhere.
+ """
+ with self._lock:
+ if listener not in self._listeners:
+ self._listeners.append(listener)
+
+ def remove_listener(self, listener: Callable[[SSEEvent], None]) -> None:
+ """Unregister a callback added by :meth:`add_listener`.
+
+ Args:
+ listener: The previously registered callback. Unknown callbacks
+ are ignored so teardown never has to check first.
+ """
+ with self._lock:
+ if listener in self._listeners:
+ self._listeners.remove(listener)
+
@staticmethod
def _safe_put(queue: asyncio.Queue, event: SSEEvent) -> None:
"""Safely put an event onto a queue.
diff --git a/agent/tests/test_scheduled_delivery_hook.py b/agent/tests/test_scheduled_delivery_hook.py
new file mode 100644
index 000000000..71c4ad271
--- /dev/null
+++ b/agent/tests/test_scheduled_delivery_hook.py
@@ -0,0 +1,100 @@
+"""The event hook makes delivery prompt; the sweep is what makes it correct.
+
+A briefing that waits for the next poll is still delivered, just late. The
+hook exists to remove that wait — and must never be able to cost anything
+else, so it runs off the SSE publish path and coalesces.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from src.scheduled_research.executor import ScheduledResearchExecutor
+from src.scheduled_research.models import DeliveryStatus, ScheduledResearchJob
+from src.scheduled_research.store import ScheduledResearchJobStore
+from src.session.events import EventBus, SSEEvent
+
+
+def _job(**overrides) -> ScheduledResearchJob:
+ base = dict(id="j1", prompt="p", schedule="60000", next_run_at=0)
+ base.update(overrides)
+ return ScheduledResearchJob(**base)
+
+
+def test_a_listener_that_raises_cannot_break_the_event_stream() -> None:
+ """This is the SSE hot path; a bad listener must cost nothing."""
+ bus = EventBus()
+ seen: list[str] = []
+
+ def _explodes(_event: SSEEvent) -> None:
+ raise RuntimeError("listener is broken")
+
+ bus.add_listener(_explodes)
+ bus.add_listener(lambda event: seen.append(event.event_type))
+
+ bus.emit("s1", "attempt.completed", {})
+
+ assert seen == ["attempt.completed"]
+ # And the event still reached the buffer every reconnecting client reads.
+ assert len(bus.replay("s1", replay_all=True)) == 1
+
+
+def test_a_removed_listener_stops_hearing_events() -> None:
+ bus = EventBus()
+ seen: list[str] = []
+ listener = lambda event: seen.append(event.event_type) # noqa: E731
+
+ bus.add_listener(listener)
+ bus.emit("s1", "attempt.completed", {})
+ bus.remove_listener(listener)
+ bus.emit("s1", "attempt.failed", {})
+
+ assert seen == ["attempt.completed"]
+
+
+def test_a_requested_sweep_delivers_without_waiting_for_a_tick(tmp_path: Path) -> None:
+ """The whole point: the briefing goes out when the run ends, not later."""
+ store = ScheduledResearchJobStore(tmp_path / "jobs.json")
+ job = _job(delivery_channel="telegram", delivery_target="chat-1")
+ job.delivery.status = DeliveryStatus.PENDING
+ job.delivery.session_id = "s1"
+ job.delivery.key = "j1:s1:telegram"
+ store.upsert(job)
+ sent: list[str] = []
+
+ async def _sender(_channel, _target, text):
+ sent.append(text)
+
+ async def _scenario() -> None:
+ executor = ScheduledResearchExecutor(
+ store,
+ lambda _j: None,
+ enabled=False,
+ briefing_reader=lambda _s: ("completed", "prompt briefing"),
+ channel_sender=_sender,
+ )
+ executor._loop = asyncio.get_running_loop()
+ executor.request_sweep()
+ # Yield until the coalesced task has run.
+ for _ in range(10):
+ await asyncio.sleep(0)
+ if sent:
+ break
+
+ asyncio.run(_scenario())
+
+ assert sent == ["prompt briefing"]
+ assert store.get("j1").delivery.status is DeliveryStatus.SENT
+
+
+def test_requesting_a_sweep_without_a_running_loop_is_a_no_op(tmp_path: Path) -> None:
+ """Construction happens before the server loop exists."""
+ store = ScheduledResearchJobStore(tmp_path / "jobs.json")
+ executor = ScheduledResearchExecutor(store, lambda _j: None, enabled=False)
+
+ executor.request_sweep() # must not raise
+
+ assert executor._sweep_task is None