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(tasks): preserve request retries and fifo order

cyhc47c27731e25
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 536ff83c4..2e034591b 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -341,7 +341,7 @@ class TaskExecutionStore:
def list_pending(self) -> list[TaskExecutionRequest]:
self._ensure_dirs()
requests: list[TaskExecutionRequest] = []
- for path in sorted(self.pending_dir.glob("*.json"), key=lambda item: item.name):
+ for path in self.pending_dir.glob("*.json"):
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
@@ -350,7 +350,7 @@ class TaskExecutionStore:
if not isinstance(payload, dict):
continue
requests.append(TaskExecutionRequest.from_dict(payload))
- return requests
+ return sorted(requests, key=lambda item: (item.created_at, item.id))
def claim(self, request_id: str) -> Optional[TaskExecutionRequest]:
pending_path = self._request_path(request_id, state="pending")
@@ -361,6 +361,16 @@ class TaskExecutionStore:
payload = json.loads(processing_path.read_text(encoding="utf-8"))
return TaskExecutionRequest.from_dict(payload)
+ def requeue(self, request_id: str) -> None:
+ processing_path = self._request_path(request_id, state="processing")
+ pending_path = self._request_path(request_id, state="pending")
+ if not processing_path.exists():
+ return
+ if pending_path.exists():
+ processing_path.unlink(missing_ok=True)
+ return
+ processing_path.replace(pending_path)
+
def complete(
self,
request: TaskExecutionRequest,
@@ -520,6 +530,7 @@ class ScheduledTaskService:
if request is None:
continue
error: Optional[str] = None
+ should_complete = True
task_id = request.task_id
session_key = request.session_key
try:
@@ -542,17 +553,22 @@ class ScheduledTaskService:
)
else:
raise ValueError(f"unknown task request type: {request.request_type}")
+ except asyncio.CancelledError:
+ self.request_store.requeue(request.id)
+ should_complete = False
+ raise
except Exception as exc:
error = str(exc)
logger.error("Task execution request %s failed: %s", request.id, exc, exc_info=True)
finally:
- self.request_store.complete(
- request,
- ok=not error,
- error=error,
- task_id=task_id,
- session_key=session_key,
- )
+ if should_complete:
+ self.request_store.complete(
+ request,
+ ok=not error,
+ error=error,
+ task_id=task_id,
+ session_key=session_key,
+ )
async def _execute_task(
self,
@@ -570,14 +586,17 @@ class ScheduledTaskService:
task_id=task.id,
trigger_kind="scheduled",
)
+ except asyncio.CancelledError:
+ self.reconcile_jobs()
+ raise
except Exception as exc:
error = str(exc)
logger.error("Scheduled task %s failed: %s", task.id, exc, exc_info=True)
- finally:
- self.store.mark_task_result(task.id, error=error, disable_one_shot=disable_one_shot)
- self.reconcile_jobs()
+ self.store.mark_task_result(task.id, error=error, disable_one_shot=disable_one_shot)
+ self.reconcile_jobs()
return error
+
async def _execute_request(
self,
*,
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index c5ed6f546..3e0a39f7e 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -11,6 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.scheduled_tasks import (
ScheduledTaskService,
ScheduledTaskStore,
+ TaskExecutionRequest,
TaskExecutionStore,
build_session_key_for_context,
parse_session_key,
@@ -273,6 +274,30 @@ def test_request_store_constructor_does_not_requeue_processing_files(tmp_path: P
assert (producer_view.processing_dir / f"{request.id}.json").exists()
+def test_request_store_lists_pending_in_created_order(tmp_path: Path) -> None:
+ store = TaskExecutionStore(tmp_path / "task_requests")
+ first = TaskExecutionRequest(
+ id="zzzz",
+ request_type="hook_send",
+ created_at="2026-03-31T01:00:00+00:00",
+ session_key="slack::channel::C123",
+ prompt="first",
+ )
+ second = TaskExecutionRequest(
+ id="aaaa",
+ request_type="hook_send",
+ created_at="2026-03-31T02:00:00+00:00",
+ session_key="slack::channel::C123",
+ prompt="second",
+ )
+ store.enqueue(second)
+ store.enqueue(first)
+
+ pending = store.list_pending()
+
+ assert [item.id for item in pending] == ["zzzz", "aaaa"]
+
+
def test_recover_processing_drops_completed_requests(tmp_path: Path) -> None:
root = tmp_path / "task_requests"
store = TaskExecutionStore(root)
@@ -291,6 +316,46 @@ def test_recover_processing_drops_completed_requests(tmp_path: Path) -> None:
assert not (store.pending_dir / f"{request.id}.json").exists()
+def test_drain_requests_requeues_cancelled_task_run(tmp_path: Path) -> None:
+ path = tmp_path / "scheduled_tasks.json"
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ store = ScheduledTaskStore(path)
+ task = store.add_task(
+ session_key="slack::channel::C123",
+ prompt="send digest",
+ schedule_type="at",
+ run_at="2026-03-31T09:00:00+08:00",
+ timezone_name="Asia/Shanghai",
+ )
+ request = request_store.enqueue_task_run(task.id)
+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ raise asyncio.CancelledError()
+
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": settings_manager},
+ message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),
+ )
+ service = ScheduledTaskService(controller=controller, store=store, request_store=request_store)
+
+ try:
+ asyncio.run(service._drain_requests())
+ except asyncio.CancelledError:
+ pass
+ else:
+ raise AssertionError("expected CancelledError")
+
+ reloaded = ScheduledTaskStore(path)
+ updated = reloaded.get_task(task.id)
+ assert updated is not None
+ assert updated.last_run_at is None
+ assert updated.enabled is True
+ assert (request_store.pending_dir / f"{request.id}.json").exists()
+ assert not (request_store.processing_dir / f"{request.id}.json").exists()
+ assert not (request_store.completed_dir / f"{request.id}.json").exists()
+
+
def test_drain_requests_executes_hook_send(tmp_path: Path) -> None:
request_store = TaskExecutionStore(tmp_path / "task_requests")
request = request_store.enqueue_hook_send(session_key="slack::channel::C123", prompt="ship it")