Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Added feature to update queue positions on telegram when messages are dequeued and added new tests

Alishahryar16d8f13d84e42
diff --git a/api/app.py b/api/app.py
index fe9809dd..24133601 100644
--- a/api/app.py
+++ b/api/app.py
@@ -107,7 +107,8 @@ async def lifespan(app: FastAPI):
{
"trees": saved_trees,
"node_to_tree": session_store.get_node_mapping(),
- }
+ },
+ queue_update_callback=message_handler._update_queue_positions,
)
# Reconcile restored state - anything PENDING/IN_PROGRESS is lost across restart
if message_handler.tree_queue.cleanup_stale_nodes() > 0:
diff --git a/messaging/handler.py b/messaging/handler.py
index 6035b153..5960b709 100644
--- a/messaging/handler.py
+++ b/messaging/handler.py
@@ -16,7 +16,7 @@ from markdown_it import MarkdownIt
from .base import MessagingPlatform, SessionManagerInterface
from .models import IncomingMessage
from .session import SessionStore
-from .tree_queue import TreeQueueManager, MessageNode, MessageState
+from .tree_queue import TreeQueueManager, MessageNode, MessageState, MessageTree
from .event_parser import parse_cli_event
logger = logging.getLogger(__name__)
@@ -245,7 +245,9 @@ class ClaudeMessageHandler:
self.platform = platform
self.cli_manager = cli_manager
self.session_store = session_store
- self.tree_queue = TreeQueueManager()
+ self.tree_queue = TreeQueueManager(
+ queue_update_callback=self._update_queue_positions
+ )
async def handle_message(self, incoming: IncomingMessage) -> None:
"""
@@ -346,6 +348,34 @@ class ClaudeMessageHandler:
parse_mode="MarkdownV2",
)
+ async def _update_queue_positions(self, tree: MessageTree) -> None:
+ """Refresh queued status messages after a dequeue."""
+ try:
+ queued_ids = await tree.get_queue_snapshot()
+ except Exception as e:
+ logger.warning(f"Failed to read queue snapshot: {e}")
+ return
+
+ if not queued_ids:
+ return
+
+ position = 0
+ for node_id in queued_ids:
+ node = tree.get_node(node_id)
+ if not node or node.state != MessageState.PENDING:
+ continue
+ position += 1
+ self.platform.fire_and_forget(
+ self.platform.queue_edit_message(
+ node.incoming.chat_id,
+ node.status_message_id,
+ format_status(
+ "📋", "Queued", f"(position {position}) - waiting..."
+ ),
+ parse_mode="MarkdownV2",
+ )
+ )
+
async def _process_node(
self,
node_id: str,
diff --git a/messaging/tree_data.py b/messaging/tree_data.py
index e51dc9e3..50f437e6 100644
--- a/messaging/tree_data.py
+++ b/messaging/tree_data.py
@@ -249,6 +249,18 @@ class MessageTree:
except asyncio.QueueEmpty:
return None
+ async def get_queue_snapshot(self) -> List[str]:
+ """
+ Get a snapshot of the current queue order.
+
+ Returns:
+ List of node IDs in FIFO order.
+ """
+ async with self._lock:
+ # asyncio.Queue stores its items in a deque at _queue.
+ # We copy it here for safe, consistent reads.
+ return list(self._queue._queue)
+
def get_queue_size(self) -> int:
"""Get number of messages waiting in queue."""
return self._queue.qsize()
diff --git a/messaging/tree_processor.py b/messaging/tree_processor.py
index 30cf74d7..753e4d4c 100644
--- a/messaging/tree_processor.py
+++ b/messaging/tree_processor.py
@@ -5,7 +5,7 @@ Handles the async processing lifecycle of tree nodes.
import asyncio
import logging
-from typing import Callable, Awaitable
+from typing import Callable, Awaitable, Optional
from .tree_data import MessageTree, MessageNode, MessageState
@@ -19,6 +19,32 @@ class TreeQueueProcessor:
Separates the async processing logic from the data management.
"""
+ def __init__(
+ self,
+ queue_update_callback: Optional[
+ Callable[[MessageTree], Awaitable[None]]
+ ] = None,
+ ):
+ self._queue_update_callback = queue_update_callback
+
+ def set_queue_update_callback(
+ self,
+ queue_update_callback: Optional[
+ Callable[[MessageTree], Awaitable[None]]
+ ],
+ ) -> None:
+ """Update the callback used to refresh queue positions."""
+ self._queue_update_callback = queue_update_callback
+
+ async def _notify_queue_updated(self, tree: MessageTree) -> None:
+ """Invoke queue update callback if set."""
+ if not self._queue_update_callback:
+ return
+ try:
+ await self._queue_update_callback(tree)
+ except Exception as e:
+ logger.warning(f"Queue update callback failed: {e}")
+
async def process_node(
self,
tree: MessageTree,
@@ -56,6 +82,8 @@ class TreeQueueProcessor:
processor: Callable[[str, MessageNode], Awaitable[None]],
) -> None:
"""Process the next message in queue, if any."""
+ next_node_id = None
+ node = None
async with tree._lock:
next_node_id = await tree.dequeue()
@@ -75,6 +103,10 @@ class TreeQueueProcessor:
self.process_node(tree, node, processor)
)
+ # Queue positions changed after dequeue; refresh queued status messages.
+ if next_node_id:
+ await self._notify_queue_updated(tree)
+
async def enqueue_and_start(
self,
tree: MessageTree,
diff --git a/messaging/tree_queue.py b/messaging/tree_queue.py
index 8c91c81e..c151addc 100644
--- a/messaging/tree_queue.py
+++ b/messaging/tree_queue.py
@@ -36,9 +36,14 @@ class TreeQueueManager:
- TreeQueueProcessor: Async queue processing
"""
- def __init__(self):
+ def __init__(
+ self,
+ queue_update_callback: Optional[
+ Callable[[MessageTree], Awaitable[None]]
+ ] = None,
+ ):
self._repository = TreeRepository()
- self._processor = TreeQueueProcessor()
+ self._processor = TreeQueueProcessor(queue_update_callback)
self._lock = asyncio.Lock()
logger.info("TreeQueueManager initialized")
@@ -319,6 +324,15 @@ class TreeQueueManager:
"""Get the number of active message trees."""
return len(self._repository._trees)
+ def set_queue_update_callback(
+ self,
+ queue_update_callback: Optional[
+ Callable[[MessageTree], Awaitable[None]]
+ ],
+ ) -> None:
+ """Set callback for queue position updates."""
+ self._processor.set_queue_update_callback(queue_update_callback)
+
def register_node(self, node_id: str, root_id: str) -> None:
"""Register a node ID to a tree (for external mapping)."""
self._repository.register_node(node_id, root_id)
@@ -328,8 +342,14 @@ class TreeQueueManager:
return self._repository.to_dict()
@classmethod
- def from_dict(cls, data: dict) -> "TreeQueueManager":
+ def from_dict(
+ cls,
+ data: dict,
+ queue_update_callback: Optional[
+ Callable[[MessageTree], Awaitable[None]]
+ ] = None,
+ ) -> "TreeQueueManager":
"""Deserialize from dictionary."""
- manager = cls()
+ manager = cls(queue_update_callback=queue_update_callback)
manager._repository = TreeRepository.from_dict(data)
return manager
diff --git a/tests/test_handler.py b/tests/test_handler.py
index eb6fa265..31fafb64 100644
--- a/tests/test_handler.py
+++ b/tests/test_handler.py
@@ -1,5 +1,7 @@
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+from messaging.tree_data import MessageTree, MessageNode
+from messaging.models import IncomingMessage
from messaging.handler import ClaudeMessageHandler
from messaging.tree_queue import MessageState
@@ -106,6 +108,67 @@ async def test_handle_message_queued(handler, mock_platform, incoming_message_fa
)
+async def test_update_queue_positions(handler, mock_platform):
+ root_incoming = IncomingMessage(
+ text="Root",
+ chat_id="chat_1",
+ user_id="user_1",
+ message_id="root",
+ platform="telegram",
+ )
+ root = MessageNode(
+ node_id="root",
+ incoming=root_incoming,
+ status_message_id="status_root",
+ )
+ tree = MessageTree(root)
+
+ child_incoming_1 = IncomingMessage(
+ text="Child 1",
+ chat_id="chat_1",
+ user_id="user_1",
+ message_id="child_1",
+ platform="telegram",
+ reply_to_message_id="root",
+ )
+ child_incoming_2 = IncomingMessage(
+ text="Child 2",
+ chat_id="chat_1",
+ user_id="user_1",
+ message_id="child_2",
+ platform="telegram",
+ reply_to_message_id="root",
+ )
+
+ await tree.add_node(
+ node_id="child_1",
+ incoming=child_incoming_1,
+ status_message_id="status_1",
+ parent_id="root",
+ )
+ await tree.add_node(
+ node_id="child_2",
+ incoming=child_incoming_2,
+ status_message_id="status_2",
+ parent_id="root",
+ )
+
+ await tree.enqueue("child_1")
+ await tree.enqueue("child_2")
+
+ await handler._update_queue_positions(tree)
+
+ calls = mock_platform.queue_edit_message.call_args_list
+ assert len(calls) == 2
+ assert calls[0][0][0] == "chat_1"
+ assert calls[0][0][1] == "status_1"
+ assert "position 1" in calls[0][0][2]
+ assert calls[1][0][0] == "chat_1"
+ assert calls[1][0][1] == "status_2"
+ assert "position 2" in calls[1][0][2]
+
+
@pytest.mark.asyncio
async def test_stop_all_tasks(handler, mock_cli_manager, mock_platform):
mock_node = MagicMock()
diff --git a/tests/test_tree_processor.py b/tests/test_tree_processor.py
index b2218879..6b7560dd 100644
--- a/tests/test_tree_processor.py
+++ b/tests/test_tree_processor.py
@@ -157,3 +157,16 @@ async def test_process_next_with_item(tree_processor, sample_tree):
await sample_tree._current_task
except asyncio.CancelledError:
pass
+
+
+async def test_process_next_triggers_queue_update(sample_tree):
+ callback = AsyncMock()
+ processor = TreeQueueProcessor(queue_update_callback=callback)
+
+ await sample_tree._queue.put("next_node")
+ sample_tree.get_node = MagicMock(return_value=None)
+
+ await processor._process_next(sample_tree, AsyncMock())
+
+ callback.assert_awaited_once_with(sample_tree)
diff --git a/tests/test_tree_queue.py b/tests/test_tree_queue.py
index 2d6194b9..1aaebd42 100644
--- a/tests/test_tree_queue.py
+++ b/tests/test_tree_queue.py
@@ -207,6 +207,55 @@ class TestMessageTree:
assert node_id == "m1"
assert tree.get_queue_size() == 0
+ @pytest.mark.asyncio
+ async def test_queue_snapshot(self):
+ """Test queue snapshot order."""
+ incoming = IncomingMessage(
+ text="Root",
+ chat_id="1",
+ user_id="1",
+ message_id="root",
+ platform="test",
+ )
+ root = MessageNode(node_id="root", incoming=incoming, status_message_id="s1")
+ tree = MessageTree(root)
+
+ child_incoming_1 = IncomingMessage(
+ text="Child 1",
+ chat_id="1",
+ user_id="1",
+ message_id="child_1",
+ platform="test",
+ reply_to_message_id="root",
+ )
+ child_incoming_2 = IncomingMessage(
+ text="Child 2",
+ chat_id="1",
+ user_id="1",
+ message_id="child_2",
+ platform="test",
+ reply_to_message_id="root",
+ )
+
+ await tree.add_node(
+ node_id="child_1",
+ incoming=child_incoming_1,
+ status_message_id="s2",
+ parent_id="root",
+ )
+ await tree.add_node(
+ node_id="child_2",
+ incoming=child_incoming_2,
+ status_message_id="s3",
+ parent_id="root",
+ )
+
+ await tree.enqueue("child_1")
+ await tree.enqueue("child_2")
+
+ snapshot = await tree.get_queue_snapshot()
+ assert snapshot == ["child_1", "child_2"]
+
def test_tree_serialization(self):
"""Test tree to_dict and from_dict."""
incoming = IncomingMessage(