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
fixed thinking not appearing in messages
Alishahryar131357ab86a34
diff --git a/cli/parser.py b/cli/parser.pyindex f556f56b..1fed6da9 100644--- a/cli/parser.py+++ b/cli/parser.py@@ -10,7 +10,7 @@ class CLIParser:"""Helper to structure raw CLI events."""@staticmethod- def parse_event(event: Dict) -> Optional[Dict]:+ def parse_event(event: Dict) -> List[Dict]:"""Parse a CLI event and return a structured result.@@ -18,12 +18,13 @@ class CLIParser:event: Raw event dictionary from CLIReturns:- Parsed event dict or None if not a recognized event type+ List of parsed event dicts. Empty list if not recognized."""if not isinstance(event, dict):- return None+ return []etype = event.get("type")+ results = []# 1. Handle full messages (assistant or result)msg_obj = None@@ -53,6 +54,13 @@ class CLIParser:elif ctype == "tool_use":tool_calls.append(c)+ # Prioritize thinking first+ if thinking_parts:+ results.append(+ {"type": "thinking", "text": "\n".join(thinking_parts)}+ )++ # Then tools or subagentsif tool_calls:# Check for subagents (Task tool)subagents = [@@ -61,28 +69,25 @@ class CLIParser:if t.get("name") == "Task"]if subagents:- return {"type": "subagent_start", "tasks": subagents}- return {"type": "tool_start", "tools": tool_calls}+ results.append({"type": "subagent_start", "tasks": subagents})+ else:+ results.append({"type": "tool_start", "tools": tool_calls})- # Return combined result if we have content- result = {}- if thinking_parts:- result["thinking"] = "\n".join(thinking_parts)+ # Then text content if anyif parts:- result["text"] = "".join(parts)- if result:- result["type"] = "content"- return result+ results.append({"type": "content", "text": "".join(parts)})++ if results:+ return results# 2. Handle streaming deltasif etype == "content_block_delta":delta = event.get("delta", {})- if not isinstance(delta, dict):- return None- if delta.get("type") == "text_delta":- return {"type": "content", "text": delta.get("text", "")}- if delta.get("type") == "thinking_delta":- return {"type": "thinking", "text": delta.get("thinking", "")}+ if isinstance(delta, dict):+ if delta.get("type") == "text_delta":+ return [{"type": "content", "text": delta.get("text", "")}]+ if delta.get("type") == "thinking_delta":+ return [{"type": "thinking", "text": delta.get("thinking", "")}]# 3. Handle tool usage startif etype == "content_block_start":@@ -90,18 +95,20 @@ class CLIParser:if isinstance(block, dict) and block.get("type") == "tool_use":if block.get("name") == "Task":desc = block.get("input", {}).get("description", "Subagent")- return {"type": "subagent_start", "tasks": [desc]}- return {"type": "tool_start", "tools": [block]}+ return [{"type": "subagent_start", "tasks": [desc]}]+ return [{"type": "tool_start", "tools": [block]}]# 4. Handle errors and exitif etype == "error":err = event.get("error")msg = err.get("message") if isinstance(err, dict) else str(err)- return {"type": "error", "message": msg}+ return [{"type": "error", "message": msg}]elif etype == "exit":- return {- "type": "complete",- "status": "success" if event.get("code") == 0 else "failed",- }-- return None+ return [+ {+ "type": "complete",+ "status": "success" if event.get("code") == 0 else "failed",+ }+ ]++ return []diff --git a/messaging/handler.py b/messaging/handler.pyindex 0c9c5099..65ab9bdf 100644--- a/messaging/handler.py+++ b/messaging/handler.py@@ -129,8 +129,15 @@ class ClaudeMessageHandler:status_msg_id = queued.status_message_idchat_id = incoming.chat_id- # Unified message accumulator- message_parts: List[Tuple[str, str]] = []+ # specific components for structured display+ components = {+ "thinking": [], # List[str]+ "tools": [], # List[str]+ "subagents": [], # List[str]+ "content": [], # List[str]+ "errors": [], # List[str]+ }+last_ui_update = 0.0captured_session_id = (session_id_to_resume@@ -155,7 +162,7 @@ class ClaudeMessageHandler:returntry:- display = self._build_message(message_parts, status)+ display = self._build_message(components, status)if display:await self.platform.edit_message(chat_id, status_msg_id, display, parse_mode="markdown"@@ -179,7 +186,7 @@ class ClaudeMessageHandler:else:captured_session_id = session_or_temp_idexcept RuntimeError as e:- message_parts.append(("error", str(e)))+ components["errors"].append(str(e))await update_ui("⏳ **Session limit reached**", force=True)return@@ -206,82 +213,121 @@ class ClaudeMessageHandler:)continue- parsed = CLIParser.parse_event(event_data)-- if not parsed:- continue-- if parsed["type"] == "thinking":- message_parts.append(("thinking", parsed["text"]))- await update_ui("🧠 **Claude is thinking...**")-- elif parsed["type"] == "content":- if parsed.get("text"):- if message_parts and message_parts[-1][0] == "content":- msg_type, content = message_parts[-1]- message_parts[-1] = ("content", content + parsed["text"])- else:- message_parts.append(("content", parsed["text"]))- await update_ui("🧠 **Claude is working...**")-- elif parsed["type"] == "tool_start":- names = [t.get("name") for t in parsed["tools"]]- message_parts.append(("tool", ", ".join(names)))- await update_ui("⏳ **Executing tools...**")-- elif parsed["type"] == "complete":- if not message_parts:- message_parts.append(("content", "Done."))- await update_ui("✅ **Complete**", force=True)-- # Update session's last message- if captured_session_id:- self.session_store.update_last_message(- captured_session_id, status_msg_id+ parsed_list = CLIParser.parse_event(event_data)++ for parsed in parsed_list:+ if parsed["type"] == "thinking":+ # append to the last thinking block if valid, or just simple list+ components["thinking"].append(parsed["text"])+ await update_ui("🧠 **Claude is thinking...**")++ elif parsed["type"] == "content":+ if parsed.get("text"):+ components["content"].append(parsed["text"])+ await update_ui("🧠 **Claude is working...**")++ elif parsed["type"] == "tool_start":+ names = [t.get("name") for t in parsed.get("tools", [])]+ components["tools"].extend(names)+ await update_ui("⏳ **Executing tools...**")++ elif parsed["type"] == "subagent_start":+ tasks = parsed.get("tasks", [])+ components["subagents"].extend(tasks)+ await update_ui("🤖 **Subagent working...**")++ elif parsed["type"] == "complete":+ if not any(components.values()):+ components["content"].append("Done.")+ await update_ui("✅ **Complete**", force=True)++ # Update session's last message+ if captured_session_id:+ self.session_store.update_last_message(+ captured_session_id, status_msg_id+ )++ elif parsed["type"] == "error":+ components["errors"].append(+ parsed.get("message", "Unknown error"))-- elif parsed["type"] == "error":- message_parts.append(- ("error", parsed.get("message", "Unknown error"))- )- await update_ui("❌ **Error**", force=True)+ await update_ui("❌ **Error**", force=True)except asyncio.CancelledError:- message_parts.append(("error", "Task was cancelled"))+ components["errors"].append("Task was cancelled")await update_ui("❌ **Cancelled**", force=True)except Exception as e:logger.error(f"Task failed: {e}")- message_parts.append(("error", str(e)[:200]))+ components["errors"].append(str(e)[:200])await update_ui("💥 **Task Failed**", force=True)def _build_message(self,- parts: List[Tuple[str, str]],+ components: dict,status: Optional[str] = None,) -> str:- """Build unified message from parts."""+ """+ Build unified message with specific order:+ 1. Thinking+ 2. Tools+ 3. Subagents+ 4. Content+ 5. Errors+ 6. Status (Bottom)+ """lines = []++ # 1. Thinking+ if components["thinking"]:+ full_thinking = "".join(components["thinking"])+ # limit thinking length visually+ display = full_thinking+ if len(display) > 800:+ display = display[:795] + "..."+ lines.append(f"💭 **Thinking:**\n```\n{display}\n```")++ # 2. Tools+ if components["tools"]:+ # Unique tools to avoid clutter+ unique_tools = []+ seen = set()+ for t in components["tools"]:+ if t not in seen:+ unique_tools.append(t)+ seen.add(t)+ lines.append(f"🛠 **Tools:** `{', '.join(unique_tools)}`")++ # 3. Subagents+ if components["subagents"]:+ for task in components["subagents"]:+ lines.append(f"🤖 **Subagent:** `{task}`")++ # 4. Content+ if components["content"]:+ # Join content parts+ full_content = "".join(components["content"])+ lines.append(full_content)++ # 5. Errors+ if components["errors"]:+ for err in components["errors"]:+ lines.append(f"⚠️ **Error:** `{err}`")++ # 6. Status (Bottom)if status:+ lines.append("") # spacerlines.append(status)- lines.append("")-- for part_type, content in parts:- if part_type == "thinking":- display = content[:1200] + ("..." if len(content) > 1200 else "")- lines.append(f"💭 **Thinking:**\n```\n{display}\n```")- elif part_type == "tool":- lines.append(f"🔧 **Tools:** `{content}`")- elif part_type == "content":- lines.append(content)- elif part_type == "error":- lines.append(f"⚠️ {content}")result = "\n".join(lines)- # Truncate if too long++ # Truncate if too long (Telegram limit ~4096)+ # We leave some bufferif len(result) > 3800:result = "..." + result[-3795:]- if result.count("```") % 2 != 0:- result += "\n```"+ # basic attempt to fix unclosed code blocks if we truncated the top+ # but usually we want to preserve the bottom (content/status)+ pass+return resultdef _get_initial_status(self, session_id: Optional[str]) -> str:diff --git a/tests/test_cli.py b/tests/test_cli.pyindex 4ca6cddc..78d328eb 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -16,8 +16,9 @@ class TestCLIParser:"message": {"content": [{"type": "text", "text": "Hello, world!"}]},}result = CLIParser.parse_event(event)- assert result["type"] == "content"- assert result["text"] == "Hello, world!"+ assert len(result) == 1+ assert result[0]["type"] == "content"+ assert result[0]["text"] == "Hello, world!"def test_parse_thinking_content(self):"""Test parsing thinking content."""@@ -30,8 +31,31 @@ class TestCLIParser:},}result = CLIParser.parse_event(event)- assert result["type"] == "content"- assert result["thinking"] == "Let me think..."+ assert len(result) == 1+ assert result[0]["type"] == "thinking"+ assert (+ result[0]["text"] == "Let me think...\n"+ or result[0]["text"] == "Let me think..."+ )++ def test_parse_multiple_content(self):+ """Test parsing mixed content (thinking + tools)."""+ from cli.parser import CLIParser++ event = {+ "type": "assistant",+ "message": {+ "content": [+ {"type": "thinking", "thinking": "Thinking..."},+ {"type": "tool_use", "name": "ls", "input": {}},+ ]+ },+ }+ result = CLIParser.parse_event(event)+ assert len(result) == 2+ assert result[0]["type"] == "thinking"+ assert result[0]["text"] == "Thinking..."+ assert result[1]["type"] == "tool_start"def test_parse_tool_use(self):"""Test parsing tool use content."""@@ -50,9 +74,10 @@ class TestCLIParser:},}result = CLIParser.parse_event(event)- assert result["type"] == "tool_start"- assert len(result["tools"]) == 1- assert result["tools"][0]["name"] == "read_file"+ assert len(result) == 1+ assert result[0]["type"] == "tool_start"+ assert len(result[0]["tools"]) == 1+ assert result[0]["tools"][0]["name"] == "read_file"def test_parse_text_delta(self):"""Test parsing streaming text delta."""@@ -63,8 +88,9 @@ class TestCLIParser:"delta": {"type": "text_delta", "text": "streaming text"},}result = CLIParser.parse_event(event)- assert result["type"] == "content"- assert result["text"] == "streaming text"+ assert len(result) == 1+ assert result[0]["type"] == "content"+ assert result[0]["text"] == "streaming text"def test_parse_thinking_delta(self):"""Test parsing streaming thinking delta."""@@ -75,8 +101,9 @@ class TestCLIParser:"delta": {"type": "thinking_delta", "thinking": "thinking..."},}result = CLIParser.parse_event(event)- assert result["type"] == "thinking"- assert result["text"] == "thinking..."+ assert len(result) == 1+ assert result[0]["type"] == "thinking"+ assert result[0]["text"] == "thinking..."def test_parse_error(self):"""Test parsing error event."""@@ -84,8 +111,8 @@ class TestCLIParser:event = {"type": "error", "error": {"message": "Something went wrong"}}result = CLIParser.parse_event(event)- assert result["type"] == "error"- assert result["message"] == "Something went wrong"+ assert result[0]["type"] == "error"+ assert result[0]["message"] == "Something went wrong"def test_parse_exit_success(self):"""Test parsing exit event with success."""@@ -93,8 +120,8 @@ class TestCLIParser:event = {"type": "exit", "code": 0}result = CLIParser.parse_event(event)- assert result["type"] == "complete"- assert result["status"] == "success"+ assert result[0]["type"] == "complete"+ assert result[0]["status"] == "success"def test_parse_exit_failure(self):"""Test parsing exit event with failure."""@@ -102,22 +129,22 @@ class TestCLIParser:event = {"type": "exit", "code": 1}result = CLIParser.parse_event(event)- assert result["type"] == "complete"- assert result["status"] == "failed"+ assert result[0]["type"] == "complete"+ assert result[0]["status"] == "failed"def test_parse_invalid_event(self):- """Test parsing returns None for unrecognized event."""+ """Test parsing returns empty list for unrecognized event."""from cli.parser import CLIParserresult = CLIParser.parse_event({"type": "unknown"})- assert result is None+ assert result == []def test_parse_non_dict(self):- """Test parsing returns None for non-dict input."""+ """Test parsing returns empty list for non-dict input."""from cli.parser import CLIParserresult = CLIParser.parse_event("not a dict")- assert result is None+ assert result == []class TestCLISession:diff --git a/tests/test_handler_format.py b/tests/test_handler_format.pynew file mode 100644index 00000000..34c76fb8--- /dev/null+++ b/tests/test_handler_format.py@@ -0,0 +1,89 @@+import pytest+from unittest.mock import MagicMock+from messaging.handler import ClaudeMessageHandler+++def handler():+ platform = MagicMock()+ cli = MagicMock()+ store = MagicMock()+ queue = MagicMock()+ return ClaudeMessageHandler(platform, cli, store, queue)+++def test_build_message_structure(handler):+ """Verify the order of message components."""+ components = {+ "thinking": ["Thinking process..."],+ "tools": ["list_files", "read_file"],+ "subagents": ["Searching codebase...", "Analyzing dependencies..."],+ "content": ["Here is the file content."],+ "errors": ["Some error happened"],+ }+ status = "✅ **Complete**"++ msg = handler._build_message(components, status)++ print(f"Generated Message:\n{msg}")++ # Check existence+ assert "Thinking process..." in msg+ assert "list_files" in msg+ assert "read_file" in msg+ assert "Searching codebase..." in msg+ assert "Here is the file content." in msg+ assert "Some error happened" in msg+ assert "✅ **Complete**" in msg++ # Check headers+ assert "💭 **Thinking:**" in msg+ assert "🛠 **Tools:**" in msg+ assert "🤖 **Subagent:**" in msg+ assert "⚠️ **Error:**" in msg++ # Check Order: Thinking -> Tools -> Subagents -> Content -> Errors -> Status+ p_thinking = msg.find("Thinking process...")+ p_tools = msg.find("🛠 **Tools:**")+ p_subagents = msg.find("🤖 **Subagent:**")+ p_content = msg.find("Here is the file content.")+ p_errors = msg.find("⚠️ **Error:**")+ p_status = msg.find("✅ **Complete**")++ assert p_thinking < p_tools, "Thinking should come before Tools"+ assert p_tools < p_subagents, "Tools should come before Subagents"+ assert p_subagents < p_content, "Subagents should come before Content"+ assert p_content < p_errors, "Content should come before Errors"+ assert p_errors < p_status, "Errors should come before Status"+++def test_build_message_simple(handler):+ """Verify simple message with just content."""+ components = {+ "thinking": [],+ "tools": [],+ "subagents": [],+ "content": ["Simple message."],+ "errors": [],+ }+ msg = handler._build_message(components, "Ready")++ assert "Simple message." in msg+ assert "Ready" in msg+ assert "💭" not in msg+ assert "🛠" not in msg+++def test_subagents_formatting(handler):+ """Verify subagents formatting."""+ components = {+ "thinking": [],+ "tools": [],+ "subagents": ["Task 1", "Task 2"],+ "content": [],+ "errors": [],+ }+ msg = handler._build_message(components)++ assert "🤖 **Subagent:** `Task 1`" in msg+ assert "🤖 **Subagent:** `Task 2`" in msgdiff --git a/wrapper/api.py b/wrapper/api.pyindex beb5519a..8283e686 100644--- a/wrapper/api.py+++ b/wrapper/api.py@@ -61,9 +61,10 @@ async def websocket_endpoint(websocket: WebSocket):# Start Claude session and stream events backasync for event in session.start_task(task):- parsed = CLIParser.parse_event(event)- if parsed:- await websocket.send_json(parsed)+ parsed_list = CLIParser.parse_event(event)+ if parsed_list:+ for parsed in parsed_list:+ await websocket.send_json(parsed)else:# Send raw for debugging if it's unknown but relevantif event.get("type") in ["system", "result"]: