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
Phase 5: Encapsulation - Repository and MessageTree API
Cursor Agent959d1bdf5bae
diff --git a/messaging/tree_data.py b/messaging/tree_data.pyindex 7ab1d6ec..210bd6eb 100644--- a/messaging/tree_data.py+++ b/messaging/tree_data.py@@ -269,6 +269,43 @@ class MessageTree:"""Get number of messages waiting in queue."""return self._queue.qsize()+ def cancel_current_task(self) -> bool:+ """Cancel the currently running task. Returns True if a task was cancelled."""+ if self._current_task and not self._current_task.done():+ self._current_task.cancel()+ return True+ return False++ def drain_queue_and_mark_cancelled(+ self, error_message: str = "Cancelled by user"+ ) -> List["MessageNode"]:+ """+ Drain the queue, mark each node as ERROR, and return affected nodes.+ Does not acquire lock; caller must ensure no concurrent queue access.+ """+ nodes: List[MessageNode] = []+ while True:+ try:+ node_id = self._queue.get_nowait()+ except asyncio.QueueEmpty:+ break+ node = self._nodes.get(node_id)+ if node:+ node.state = MessageState.ERROR+ node.error_message = error_message+ nodes.append(node)+ return nodes++ def reset_processing_state(self) -> None:+ """Reset processing flags after cancel/cleanup."""+ self._is_processing = False+ self._current_node_id = None++ @property+ def current_node_id(self) -> Optional[str]:+ """Get the ID of the node currently being processed."""+ return self._current_node_id+def to_dict(self) -> dict:"""Serialize tree to dictionary."""return {diff --git a/messaging/tree_processor.py b/messaging/tree_processor.pyindex 189958af..71ee9398 100644--- a/messaging/tree_processor.py+++ b/messaging/tree_processor.py@@ -165,7 +165,4 @@ class TreeQueueProcessor:def cancel_current(self, tree: MessageTree) -> bool:"""Cancel the currently running task in a tree."""- if tree._current_task and not tree._current_task.done():- tree._current_task.cancel()- return True- return False+ return tree.cancel_current_task()diff --git a/messaging/tree_queue.py b/messaging/tree_queue.pyindex be0c91d3..eb59931d 100644--- a/messaging/tree_queue.py+++ b/messaging/tree_queue.py@@ -56,16 +56,6 @@ class TreeQueueManager:logger.info("TreeQueueManager initialized")- @property- def _trees(self):- """Access internal tree dict for backward compatibility."""- return self._repository._trees-- @property- def _node_to_tree(self):- """Access internal node mapping for backward compatibility."""- return self._repository._node_to_tree-async def create_tree(self,node_id: str,@@ -117,11 +107,12 @@ class TreeQueueManager:Tuple of (tree, new_node)"""async with self._lock:- if parent_node_id not in self._repository._node_to_tree:+ if not self._repository.has_node(parent_node_id):raise ValueError(f"Parent node {parent_node_id} not found in any tree")- root_id = self._repository._node_to_tree[parent_node_id]- tree = self._repository._trees[root_id]+ tree = self._repository.get_tree_for_node(parent_node_id)+ if not tree:+ raise ValueError(f"Parent node {parent_node_id} not found in any tree")# Add node (tree has its own lock) - outside manager lock to avoid deadlocknode = await tree.add_node(@@ -132,9 +123,9 @@ class TreeQueueManager:)async with self._lock:- self._repository.register_node(node_id, root_id)+ self._repository.register_node(node_id, tree.root_id)- logger.info(f"Added node {node_id} to tree {root_id}")+ logger.info(f"Added node {node_id} to tree {tree.root_id}")return tree, nodedef get_tree(self, root_id: str) -> Optional[MessageTree]:@@ -248,10 +239,11 @@ class TreeQueueManager:cancelled_nodes = []- # 1. Cancel running task via processor- if self._processor.cancel_current(tree):- if tree._current_node_id:- node = tree.get_node(tree._current_node_id)+ # 1. Cancel running task+ if tree.cancel_current_task():+ current_id = tree.current_node_id+ if current_id:+ node = tree.get_node(current_id)if node and node.state not in (MessageState.COMPLETED,MessageState.ERROR,@@ -260,21 +252,11 @@ class TreeQueueManager:node.error_message = "Cancelled by user"cancelled_nodes.append(node)- # 2. Clear queue and update states- while not tree._queue.empty():- try:- node_id = tree._queue.get_nowait()- node = tree.get_node(node_id)- if node:- node.state = MessageState.ERROR- node.error_message = "Cancelled by user"- cancelled_nodes.append(node)- except asyncio.QueueEmpty:- break+ # 2. Drain queue and mark nodes as cancelled+ queue_nodes = tree.drain_queue_and_mark_cancelled()+ cancelled_nodes.extend(queue_nodes)# 3. Cleanup: Mark ANY other PENDING or IN_PROGRESS nodes as ERROR- # This handles stale nodes from previous sessions without counting them as "cancelled now"- # unless they were in the active queue above.cleanup_count = 0for node in tree.all_nodes():if (@@ -285,8 +267,7 @@ class TreeQueueManager:node.error_message = "Stale task cleaned up"cleanup_count += 1- tree._is_processing = False- tree._current_node_id = None+ tree.reset_processing_state()if cancelled_nodes:logger.info(@@ -375,7 +356,7 @@ class TreeQueueManager:def get_tree_count(self) -> int:"""Get the number of active message trees."""- return len(self._repository._trees)+ return self._repository.tree_count()def set_queue_update_callback(self,diff --git a/messaging/tree_repository.py b/messaging/tree_repository.pyindex 1333f9f1..f966c6f0 100644--- a/messaging/tree_repository.py+++ b/messaging/tree_repository.py@@ -47,6 +47,14 @@ class TreeRepository:"""Register a node ID to a tree."""self._node_to_tree[node_id] = root_id+ def has_node(self, node_id: str) -> bool:+ """Check if a node is registered in any tree."""+ return node_id in self._node_to_tree++ def tree_count(self) -> int:+ """Get the number of trees in the repository."""+ return len(self._trees)+def is_tree_busy(self, root_id: str) -> bool:"""Check if a tree is currently processing."""tree = self._trees.get(root_id)diff --git a/tests/test_messaging.py b/tests/test_messaging.pyindex 5b7ad845..98beeebd 100644--- a/tests/test_messaging.py+++ b/tests/test_messaging.py@@ -359,7 +359,7 @@ class TestTreeQueueManager:from messaging.tree_queue import TreeQueueManagermgr = TreeQueueManager()- assert mgr._trees == {}+ assert mgr.get_tree_count() == 0def test_tree_not_busy_initially(self):"""Test tree is not busy when no messages."""diff --git a/tests/test_tree_repository.py b/tests/test_tree_repository.pyindex 3fc0b8b6..df41fba7 100644--- a/tests/test_tree_repository.py+++ b/tests/test_tree_repository.py@@ -28,7 +28,7 @@ def test_add_and_get_tree(repository, sample_tree):assert repository.get_tree("root_id") == sample_treeassert repository.get_tree_for_node("root_id") == sample_tree- assert repository._node_to_tree["root_id"] == "root_id"+ assert repository.has_node("root_id")def test_get_tree_nonexistent(repository):@@ -41,7 +41,7 @@ def test_register_node(repository, sample_tree):repository.register_node("child_id", "root_id")assert repository.get_tree_for_node("child_id") == sample_tree- assert repository._node_to_tree["child_id"] == "root_id"+ assert repository.has_node("child_id")def test_get_node(repository, sample_tree):@@ -132,7 +132,7 @@ def test_to_from_dict(repository, sample_tree):tree = new_repo.get_tree("root_id")assert tree is not Noneassert tree.root_id == "root_id"- assert new_repo._node_to_tree["root_id"] == "root_id"+ assert new_repo.get_tree_for_node("root_id") == treedef test_all_trees(repository, sample_tree):