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

Initiate multiple conversation on telegram and reply to continue them

Alishahryar1488ecbd4a160
diff --git a/providers/claude_cli.py b/providers/claude_cli.py
index c1ebbf09..6d4da48e 100644
--- a/providers/claude_cli.py
+++ b/providers/claude_cli.py
@@ -114,8 +114,29 @@ class CLISession:
self.api_url = api_url
self.allowed_dirs = [os.path.normpath(d) for d in (allowed_dirs or [])]
self.process: Optional[asyncio.subprocess.Process] = None
+ self.current_session_id: Optional[str] = None
+ self._is_busy = False
- async def start_task(self, prompt: str) -> AsyncGenerator[dict, None]:
+ @property
+ def is_busy(self) -> bool:
+ """Check if a task is currently running."""
+ return self._is_busy
+
+ async def start_task(
+ self, prompt: str, session_id: Optional[str] = None
+ ) -> AsyncGenerator[dict, None]:
+ """
+ Start a new task or continue an existing session.
+
+ Args:
+ prompt: The user's message/prompt
+ session_id: Optional session ID to resume. If provided, uses --resume flag.
+
+ Yields:
+ Event dictionaries from the CLI, including a special 'session_info' event
+ with the session ID when available.
+ """
+ self._is_busy = True
env = os.environ.copy()
# Ensure we have a dummy key if none exists, as CLI often requires it
@@ -132,15 +153,28 @@ class CLISession:
env["TERM"] = "dumb"
env["PYTHONIOENCODING"] = "utf-8"
- cmd = [
- "claude",
- "-p",
- prompt,
- "--output-format",
- "stream-json",
- "--dangerously-skip-permissions",
- "--verbose",
- ]
+ # Build command based on whether resuming or starting new
+ if session_id:
+ # Resume existing session
+ cmd = [
+ "claude",
+ "--resume", session_id,
+ "-p", prompt,
+ "--output-format", "stream-json",
+ "--dangerously-skip-permissions",
+ "--verbose",
+ ]
+ logger.info(f"Resuming Claude session {session_id} with prompt: {prompt[:50]}...")
+ else:
+ # Start new session
+ cmd = [
+ "claude",
+ "-p", prompt,
+ "--output-format", "stream-json",
+ "--dangerously-skip-permissions",
+ "--verbose",
+ ]
+ logger.info(f"Starting new Claude session with prompt: {prompt[:50]}...")
if self.allowed_dirs:
for d in self.allowed_dirs:
@@ -148,44 +182,95 @@ class CLISession:
logger.info(f"Launching Claude CLI in {self.workspace}")
- self.process = await asyncio.create_subprocess_exec(
- *cmd,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- cwd=self.workspace,
- env=env,
- )
+ try:
+ self.process = await asyncio.create_subprocess_exec(
+ *cmd,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ cwd=self.workspace,
+ env=env,
+ )
- if not self.process or not self.process.stdout:
- logger.error("Claude CLI process failed to start or stdout not captured.")
- yield {"type": "exit", "code": 1}
- return
+ if not self.process or not self.process.stdout:
+ logger.error("Claude CLI process failed to start or stdout not captured.")
+ yield {"type": "exit", "code": 1}
+ return
- while True:
- line = await self.process.stdout.readline()
- if not line:
- break
+ session_id_extracted = False
- line_str = line.decode("utf-8", errors="replace").strip()
- if not line_str:
- continue
+ while True:
+ line = await self.process.stdout.readline()
+ if not line:
+ break
- try:
- event = json.loads(line_str)
- yield event
- except json.JSONDecodeError:
- logger.debug(f"Non-JSON output: {line_str}")
- yield {"type": "raw", "content": line_str}
-
- if self.process.stderr:
- stderr_output = await self.process.stderr.read()
- if stderr_output:
- logger.error(
- f"Claude CLI Stderr: {stderr_output.decode('utf-8', errors='replace')}"
- )
-
- return_code = await self.process.wait()
- yield {"type": "exit", "code": return_code}
+ line_str = line.decode("utf-8", errors="replace").strip()
+ if not line_str:
+ continue
+
+ try:
+ event = json.loads(line_str)
+
+ # Extract session ID from various event types
+ if not session_id_extracted:
+ extracted_id = self._extract_session_id(event)
+ if extracted_id:
+ self.current_session_id = extracted_id
+ session_id_extracted = True
+ logger.info(f"Extracted session ID: {extracted_id}")
+ # Emit a special event with the session ID
+ yield {"type": "session_info", "session_id": extracted_id}
+
+ yield event
+ except json.JSONDecodeError:
+ logger.debug(f"Non-JSON output: {line_str}")
+ yield {"type": "raw", "content": line_str}
+
+ if self.process.stderr:
+ stderr_output = await self.process.stderr.read()
+ if stderr_output:
+ logger.error(
+ f"Claude CLI Stderr: {stderr_output.decode('utf-8', errors='replace')}"
+ )
+
+ return_code = await self.process.wait()
+ yield {"type": "exit", "code": return_code}
+ finally:
+ self._is_busy = False
+
+ def _extract_session_id(self, event: Dict) -> Optional[str]:
+ """
+ Extract session ID from CLI event.
+
+ The session ID appears in different places depending on event type:
+ - In 'init' or 'system' events as 'session_id' or 'sessionId'
+ - In 'result' events under result.session_id
+ - Sometimes in message metadata
+ """
+ if not isinstance(event, dict):
+ return None
+
+ # Direct session_id field
+ if "session_id" in event:
+ return event["session_id"]
+ if "sessionId" in event:
+ return event["sessionId"]
+
+ # Check in nested structures
+ for key in ["init", "system", "result", "metadata"]:
+ if key in event and isinstance(event[key], dict):
+ nested = event[key]
+ if "session_id" in nested:
+ return nested["session_id"]
+ if "sessionId" in nested:
+ return nested["sessionId"]
+
+ # Check in conversation info
+ if "conversation" in event and isinstance(event["conversation"], dict):
+ conv = event["conversation"]
+ if "id" in conv:
+ return conv["id"]
+
+ return None
async def stop(self):
if self.process and self.process.returncode is None:
diff --git a/providers/message_queue.py b/providers/message_queue.py
new file mode 100644
index 00000000..f35419c2
--- /dev/null
+++ b/providers/message_queue.py
@@ -0,0 +1,169 @@
+"""
+Message Queue Manager for Claude CLI Telegram Bot
+
+Handles queuing of messages when Claude is busy processing a request.
+Messages are processed one-by-one in order per session.
+"""
+
+import asyncio
+import logging
+from typing import Callable, Awaitable, Dict, Optional, NamedTuple
+from dataclasses import dataclass
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class QueuedMessage:
+ """A message waiting to be processed."""
+ prompt: str
+ chat_id: int
+ msg_id: int
+ reply_msg_id: int # The status message to update
+ event: any # Original Telegram event for context
+
+
+class SessionQueue:
+ """Queue for a single session."""
+
+ def __init__(self, session_id: str):
+ self.session_id = session_id
+ self.queue: asyncio.Queue[QueuedMessage] = asyncio.Queue()
+ self.is_processing = False
+ self.current_task: Optional[asyncio.Task] = None
+
+
+class MessageQueueManager:
+ """
+ Manages per-session message queues.
+
+ When a session is busy, new messages are queued and processed
+ one-by-one after the current request completes.
+ """
+
+ def __init__(self):
+ self._queues: Dict[str, SessionQueue] = {}
+ self._lock = asyncio.Lock()
+
+ def _get_or_create_queue(self, session_id: str) -> SessionQueue:
+ """Get existing queue or create new one for session."""
+ if session_id not in self._queues:
+ self._queues[session_id] = SessionQueue(session_id)
+ return self._queues[session_id]
+
+ def is_session_busy(self, session_id: str) -> bool:
+ """Check if a session is currently processing a request."""
+ if session_id not in self._queues:
+ return False
+ return self._queues[session_id].is_processing
+
+ async def enqueue(
+ self,
+ session_id: str,
+ message: QueuedMessage,
+ processor: Callable[[str, QueuedMessage], Awaitable[None]],
+ ) -> bool:
+ """
+ Add a message to the session's queue.
+
+ If the session is not busy, processing starts immediately.
+ If busy, the message is queued for later processing.
+
+ Args:
+ session_id: Claude session ID
+ message: The queued message data
+ processor: Async function to process the message
+
+ Returns:
+ True if message was queued (session busy), False if processed immediately
+ """
+ async with self._lock:
+ sq = self._get_or_create_queue(session_id)
+
+ if sq.is_processing:
+ # Session is busy, queue the message
+ await sq.queue.put(message)
+ queue_size = sq.queue.qsize()
+ logger.info(f"Queued message for session {session_id}, queue size: {queue_size}")
+ return True
+ else:
+ # Session is free, start processing
+ sq.is_processing = True
+
+ # Process outside the lock
+ await self._process_message(session_id, message, processor)
+ return False
+
+ async def _process_message(
+ self,
+ session_id: str,
+ message: QueuedMessage,
+ processor: Callable[[str, QueuedMessage], Awaitable[None]],
+ ) -> None:
+ """Process a single message and then check the queue."""
+ try:
+ await processor(session_id, message)
+ except Exception as e:
+ logger.error(f"Error processing message for session {session_id}: {e}")
+ finally:
+ # Check if there are more messages in the queue
+ await self._process_next(session_id, processor)
+
+ async def _process_next(
+ self,
+ session_id: str,
+ processor: Callable[[str, QueuedMessage], Awaitable[None]],
+ ) -> None:
+ """Process the next message in queue, if any."""
+ async with self._lock:
+ if session_id not in self._queues:
+ return
+
+ sq = self._queues[session_id]
+
+ if sq.queue.empty():
+ # No more messages, mark session as free
+ sq.is_processing = False
+ logger.debug(f"Session {session_id} queue empty, marking as free")
+ return
+
+ # Get next message
+ try:
+ next_msg = sq.queue.get_nowait()
+ logger.info(f"Processing next queued message for session {session_id}")
+ except asyncio.QueueEmpty:
+ sq.is_processing = False
+ return
+
+ # Process next message (outside lock)
+ await self._process_message(session_id, next_msg, processor)
+
+ def get_queue_size(self, session_id: str) -> int:
+ """Get the number of messages waiting in a session's queue."""
+ if session_id not in self._queues:
+ return 0
+ return self._queues[session_id].queue.qsize()
+
+ def cancel_session(self, session_id: str) -> int:
+ """
+ Cancel all queued messages for a session.
+
+ Returns:
+ Number of messages that were cancelled
+ """
+ if session_id not in self._queues:
+ return 0
+
+ sq = self._queues[session_id]
+ cancelled = 0
+
+ while not sq.queue.empty():
+ try:
+ sq.queue.get_nowait()
+ cancelled += 1
+ except asyncio.QueueEmpty:
+ break
+
+ sq.is_processing = False
+ logger.info(f"Cancelled {cancelled} queued messages for session {session_id}")
+ return cancelled
diff --git a/providers/session_store.py b/providers/session_store.py
new file mode 100644
index 00000000..b89c8208
--- /dev/null
+++ b/providers/session_store.py
@@ -0,0 +1,190 @@
+"""
+Session Store for Claude CLI Telegram Bot
+
+Provides persistent storage for mapping Telegram messages to Claude CLI session IDs.
+This enables conversation continuation when replying to old messages.
+"""
+
+import json
+import os
+import logging
+from datetime import datetime
+from typing import Optional, Dict, Any
+from dataclasses import dataclass, asdict
+import threading
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class SessionRecord:
+ """A single session record."""
+ session_id: str
+ chat_id: int
+ initial_msg_id: int # The first message that started this session
+ last_msg_id: int # Most recent message in this session
+ created_at: str
+ updated_at: str
+
+
+class SessionStore:
+ """
+ Persistent storage for Telegram message ↔ Claude session mappings.
+
+ Uses a JSON file for storage with thread-safe operations.
+ """
+
+ def __init__(self, storage_path: str = "sessions.json"):
+ self.storage_path = storage_path
+ self._lock = threading.Lock()
+ self._sessions: Dict[str, SessionRecord] = {} # session_id -> record
+ self._msg_to_session: Dict[str, str] = {} # "chat_id:msg_id" -> session_id
+ self._load()
+
+ def _make_key(self, chat_id: int, msg_id: int) -> str:
+ """Create a unique key from chat_id and msg_id."""
+ return f"{chat_id}:{msg_id}"
+
+ def _load(self) -> None:
+ """Load sessions from disk."""
+ if not os.path.exists(self.storage_path):
+ return
+
+ try:
+ with open(self.storage_path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+
+ for sid, record_data in data.get("sessions", {}).items():
+ record = SessionRecord(**record_data)
+ self._sessions[sid] = record
+ # Index by initial and last message
+ self._msg_to_session[self._make_key(record.chat_id, record.initial_msg_id)] = sid
+ self._msg_to_session[self._make_key(record.chat_id, record.last_msg_id)] = sid
+
+ logger.info(f"Loaded {len(self._sessions)} sessions from {self.storage_path}")
+ except Exception as e:
+ logger.error(f"Failed to load sessions: {e}")
+
+ def _save(self) -> None:
+ """Persist sessions to disk."""
+ try:
+ data = {
+ "sessions": {sid: asdict(record) for sid, record in self._sessions.items()}
+ }
+ with open(self.storage_path, 'w', encoding='utf-8') as f:
+ json.dump(data, f, indent=2)
+ except Exception as e:
+ logger.error(f"Failed to save sessions: {e}")
+
+ def save_session(
+ self,
+ session_id: str,
+ chat_id: int,
+ initial_msg_id: int,
+ ) -> None:
+ """
+ Save a new session mapping.
+
+ Args:
+ session_id: Claude CLI session ID
+ chat_id: Telegram chat ID
+ initial_msg_id: The message ID that started this session
+ """
+ with self._lock:
+ now = datetime.utcnow().isoformat()
+ record = SessionRecord(
+ session_id=session_id,
+ chat_id=chat_id,
+ initial_msg_id=initial_msg_id,
+ last_msg_id=initial_msg_id,
+ created_at=now,
+ updated_at=now,
+ )
+ self._sessions[session_id] = record
+ self._msg_to_session[self._make_key(chat_id, initial_msg_id)] = session_id
+ self._save()
+ logger.info(f"Saved session {session_id} for chat {chat_id}, msg {initial_msg_id}")
+
+ def get_session_by_msg(self, chat_id: int, msg_id: int) -> Optional[str]:
+ """
+ Look up a session ID by a message that's part of that session.
+
+ Args:
+ chat_id: Telegram chat ID
+ msg_id: Message ID to look up
+
+ Returns:
+ Session ID if found, None otherwise
+ """
+ with self._lock:
+ key = self._make_key(chat_id, msg_id)
+ return self._msg_to_session.get(key)
+
+ def update_last_message(self, session_id: str, msg_id: int) -> None:
+ """
+ Update the last message ID for a session.
+
+ This is called when we send a new response in an existing session,
+ so replies to that response will also continue the session.
+
+ Args:
+ session_id: Claude session ID
+ msg_id: New last message ID
+ """
+ with self._lock:
+ if session_id not in self._sessions:
+ logger.warning(f"Session {session_id} not found for update")
+ return
+
+ record = self._sessions[session_id]
+ old_key = self._make_key(record.chat_id, record.last_msg_id)
+
+ # Update record
+ record.last_msg_id = msg_id
+ record.updated_at = datetime.utcnow().isoformat()
+
+ # Update index - add new key, keep old one for chain lookups
+ new_key = self._make_key(record.chat_id, msg_id)
+ self._msg_to_session[new_key] = session_id
+
+ self._save()
+ logger.debug(f"Updated session {session_id} last_msg to {msg_id}")
+
+ def get_session_record(self, session_id: str) -> Optional[SessionRecord]:
+ """Get full session record."""
+ with self._lock:
+ return self._sessions.get(session_id)
+
+ def cleanup_old_sessions(self, max_age_days: int = 30) -> int:
+ """
+ Remove sessions older than max_age_days.
+
+ Returns:
+ Number of sessions removed
+ """
+ with self._lock:
+ cutoff = datetime.utcnow()
+ removed = 0
+
+ to_remove = []
+ for sid, record in self._sessions.items():
+ try:
+ created = datetime.fromisoformat(record.created_at)
+ age_days = (cutoff - created).days
+ if age_days > max_age_days:
+ to_remove.append(sid)
+ except Exception:
+ pass
+
+ for sid in to_remove:
+ record = self._sessions.pop(sid)
+ # Remove index entries
+ self._msg_to_session.pop(self._make_key(record.chat_id, record.initial_msg_id), None)
+ self._msg_to_session.pop(self._make_key(record.chat_id, record.last_msg_id), None)
+ removed += 1
+
+ if removed:
+ self._save()
+ logger.info(f"Cleaned up {removed} old sessions")
+
+ return removed
diff --git a/server.py b/server.py
index db48c095..db9afa9e 100644
--- a/server.py
+++ b/server.py
@@ -308,40 +308,42 @@ INTERNAL_API_URL = "http://localhost:8082/v1"
# Initialize Global Instances
cli_session = CLISession(WORKSPACE_PATH, INTERNAL_API_URL, ALLOWED_DIRS)
+# Session storage and message queue (imported from providers)
+from providers.session_store import SessionStore
+from providers.message_queue import MessageQueueManager, QueuedMessage
+
+session_store = SessionStore(os.path.join(WORKSPACE_PATH, "sessions.json"))
+message_queue = MessageQueueManager()
+
def register_bot_handlers(client: "TelegramClient"):
ALLOWED_USER_ID = os.getenv("ALLOWED_TELEGRAM_USER_ID")
logger.info(f"DEBUG: Registering bot handlers. Allowed user ID: {ALLOWED_USER_ID}")
- @client.on(events.NewMessage())
- async def handle_telegram_message(event):
- sender_id = str(event.sender_id)
- logger.info(f"BOT_EVENT: From {sender_id} | Text: {event.text[:50]}")
-
- target_id = str(ALLOWED_USER_ID).strip()
- if sender_id != target_id:
- logger.debug(f"BOT_SECURITY: Ignored message from {sender_id}")
- return
+ async def process_claude_task(session_id_to_resume: str, queued_msg: QueuedMessage):
+ """
+ Core task processor - handles a single Claude CLI interaction.
+ Can be called directly or by the queue manager.
+ """
+ event = queued_msg.event
+ prompt = queued_msg.prompt
+ status_msg_id = queued_msg.reply_msg_id
+ chat_id = queued_msg.chat_id
+ original_msg_id = queued_msg.msg_id
- # 1. Handle Commands
- if event.text == "/stop":
- await cli_session.stop()
- await event.reply("⏹ **Claude process stopped.**")
- return
-
- # 2. Filter out bot's own status messages and empty text
- if not event.text or any(event.text.startswith(p) for p in ["⏳", "�", "🔧", "✅", "❌", "🚀", "🤖"]):
+ # Get the status message object
+ try:
+ status_msg = await client.get_messages(chat_id, ids=status_msg_id)
+ except Exception as e:
+ logger.error(f"Failed to get status message: {e}")
return
- logger.info(f"BOT_TASK: {event.text}")
- status_msg = await event.reply("⏳ **Launching Claude CLI...**")
-
- # Unified message accumulator - all parts appended in order
- message_parts = [] # List of (type, content) tuples
+ # Unified message accumulator
+ message_parts = []
last_ui_update = 0
+ captured_session_id = session_id_to_resume # May be updated from CLI output
def build_unified_message(status=None):
- """Build a single message from all accumulated parts."""
lines = []
if status:
lines.append(status)
@@ -349,7 +351,6 @@ def register_bot_handlers(client: "TelegramClient"):
for part_type, content in message_parts:
if part_type == "thinking":
- # Truncate thinking for display
display_thinking = content[:1200] + ("..." if len(content) > 1200 else "")
lines.append(f"💭 **Thinking:**\n```\n{display_thinking}\n```")
elif part_type == "tool":
@@ -360,7 +361,6 @@ def register_bot_handlers(client: "TelegramClient"):
lines.append(content)
result = "\n".join(lines)
- # Telegram message limit
if len(result) > 4000:
result = "..." + result[-3997:]
return result
@@ -379,38 +379,53 @@ def register_bot_handlers(client: "TelegramClient"):
logger.debug(f"UI update failed: {e}")
try:
- async for event_data in cli_session.start_task(event.text):
+ # Start or resume the CLI session
+ is_resume = session_id_to_resume is not None
+ log_prefix = f"Resuming session {session_id_to_resume}" if is_resume else "Starting new session"
+ logger.info(f"BOT: {log_prefix} for prompt: {prompt[:50]}...")
+
+ async for event_data in cli_session.start_task(prompt, session_id=session_id_to_resume):
if not isinstance(event_data, dict):
continue
+ # Handle session_info event to capture session ID
+ if event_data.get("type") == "session_info":
+ captured_session_id = event_data.get("session_id")
+ if captured_session_id and not is_resume:
+ # Save the session mapping for new sessions
+ session_store.save_session(
+ session_id=captured_session_id,
+ chat_id=chat_id,
+ initial_msg_id=original_msg_id,
+ )
+ logger.info(f"BOT: Saved new session {captured_session_id} for msg {original_msg_id}")
+ continue
+
parsed = CLIParser.parse_event(event_data)
if event_data.get("type") == "raw":
raw_line = event_data.get("content")
- if not raw_line: continue
+ if not raw_line:
+ continue
if "login" in raw_line.lower():
- await event.reply("⚠️ **Claude requires login. Run `claude` in terminal.**")
+ await client.send_message(chat_id, "⚠️ **Claude requires login. Run `claude` in terminal.**")
continue
if not parsed:
continue
if parsed["type"] == "thinking":
- # Append thinking to unified message
thinking_text = parsed["text"]
message_parts.append(("thinking", thinking_text))
await update_bot_ui("🧠 **Claude is thinking...**")
elif parsed["type"] == "content":
- # Handle thinking if present in combined event
if parsed.get("thinking"):
thinking_text = parsed["thinking"]
logger.debug(f"BOT: Got thinking: {len(thinking_text)} chars")
message_parts.append(("thinking", thinking_text))
- # Append text content
if parsed.get("text"):
logger.debug(f"BOT: Got text content: {len(parsed['text'])} chars")
- # Merge with last content part if exists, else append new
if message_parts and message_parts[-1][0] == "content":
prev_type, prev_content = message_parts[-1]
message_parts[-1] = ("content", prev_content + parsed["text"])
@@ -433,17 +448,106 @@ def register_bot_handlers(client: "TelegramClient"):
if parsed.get("status") == "failed":
await update_bot_ui("❌ **Failed**", force=True)
else:
- # Ensure we have some content for display
if not message_parts:
message_parts.append(("content", "Done."))
await update_bot_ui("✅ **Complete**", force=True)
+
+ # Update session's last message so replies to THIS response also work
+ if captured_session_id and status_msg:
+ session_store.update_last_message(captured_session_id, status_msg.id)
elif parsed["type"] == "error":
message_parts.append(("content", f"**Error:** {parsed['message']}"))
await update_bot_ui("❌ **Error**", force=True)
+
except Exception as e:
- logger.error(f"Bot failed: {e}")
- await event.reply(f"💥 **Failed:** {e}")
+ logger.error(f"Bot task failed: {e}")
+ try:
+ await client.send_message(chat_id, f"💥 **Failed:** {e}")
+ except:
+ pass
+
+ @client.on(events.NewMessage())
+ async def handle_telegram_message(event):
+ sender_id = str(event.sender_id)
+ text_preview = event.text[:50] if event.text else "(empty)"
+ logger.info(f"BOT_EVENT: From {sender_id} | Text: {text_preview}")
+
+ target_id = str(ALLOWED_USER_ID).strip()
+ if sender_id != target_id:
+ logger.debug(f"BOT_SECURITY: Ignored message from {sender_id}")
+ return
+
+ # 1. Handle Commands
+ if event.text == "/stop":
+ await cli_session.stop()
+ await event.reply("⏹ **Claude process stopped.**")
+ return
+
+ if event.text == "/queue":
+ # Show queue status (optional command)
+ await event.reply("📋 **Queue status:** Feature active. Reply to old messages to continue conversations.")
+ return
+
+ # 2. Filter out bot's own status messages and empty text
+ if not event.text or any(event.text.startswith(p) for p in ["⏳", "💭", "🔧", "✅", "❌", "🚀", "🤖", "📋"]):
+ return
+
+ logger.info(f"BOT_TASK: {event.text}")
+
+ # 3. Check if this is a reply to an existing conversation
+ session_id_to_resume = None
+ reply_to_msg_id = event.reply_to_msg_id
+
+ if reply_to_msg_id:
+ # User is replying to a previous message - try to find the session
+ session_id_to_resume = session_store.get_session_by_msg(event.chat_id, reply_to_msg_id)
+ if session_id_to_resume:
+ logger.info(f"BOT: Found session {session_id_to_resume} for reply to msg {reply_to_msg_id}")
+ else:
+ logger.info(f"BOT: No session found for reply to msg {reply_to_msg_id}, starting new session")
+
+ # 4. Send initial status message
+ if session_id_to_resume:
+ if cli_session.is_busy:
+ queue_size = message_queue.get_queue_size(session_id_to_resume) + 1
+ status_msg = await event.reply(f"📋 **Queued** (position {queue_size}) - Claude is busy, will process when ready...")
+ else:
+ status_msg = await event.reply("🔄 **Continuing conversation...**")
+ else:
+ status_msg = await event.reply("⏳ **Launching Claude CLI...**")
+
+ # 5. Create queued message
+ queued_msg = QueuedMessage(
+ prompt=event.text,
+ chat_id=event.chat_id,
+ msg_id=event.id,
+ reply_msg_id=status_msg.id,
+ event=event,
+ )
+
+ # 6. Process or queue based on session state
+ if session_id_to_resume and message_queue.is_session_busy(session_id_to_resume):
+ # Session is busy, queue the message
+ await message_queue.enqueue(
+ session_id=session_id_to_resume,
+ message=queued_msg,
+ processor=process_claude_task,
+ )
+ logger.info(f"BOT: Message queued for busy session {session_id_to_resume}")
+ else:
+ # Process immediately (either new session or free session)
+ if session_id_to_resume:
+ # Use the queue manager to track busy state
+ await message_queue.enqueue(
+ session_id=session_id_to_resume,
+ message=queued_msg,
+ processor=process_claude_task,
+ )
+ else:
+ # New session - process directly
+ # We'll save the session ID once we get it from CLI
+ await process_claude_task(None, queued_msg)
FAST_PREFIX_DETECTION = os.getenv("FAST_PREFIX_DETECTION", "true").lower() == "true"