diff --git a/src/basic_memory/importers/chatgpt_importer.py b/src/basic_memory/importers/chatgpt_importer.py index 9332a1cae..6baab91fb 100644 --- a/src/basic_memory/importers/chatgpt_importer.py +++ b/src/basic_memory/importers/chatgpt_importer.py @@ -17,6 +17,23 @@ UNKNOWN_DATE_SENTINEL = 86400.0 +def _is_hidden_message(message: dict[str, Any]) -> bool: + """Return whether a ChatGPT message is flagged as visually hidden.""" + metadata = message.get("metadata") + return isinstance(metadata, dict) and bool(metadata.get("is_visually_hidden_from_conversation")) + + +def _extract_part_text(part: Any) -> str | None: + """Extract displayable text from one entry of a ChatGPT `parts` array.""" + if isinstance(part, str): + return part + if isinstance(part, dict): + text = part.get("text") + if isinstance(text, str): + return text + return None + + class ChatGPTImporter(Importer[ChatImportResult]): """Service for importing ChatGPT conversations.""" @@ -90,10 +107,8 @@ async def import_data( msg_count = sum( 1 for node in chat["mapping"].values() - if node.get("message") - and not node.get("message", {}) - .get("metadata", {}) - .get("is_visually_hidden_from_conversation") + if isinstance(node.get("message"), dict) + and not _is_hidden_message(node["message"]) ) chats_imported += 1 @@ -277,7 +292,7 @@ def _format_chat_markdown( # Format each message for msg in messages: # Skip hidden messages - if msg.get("metadata", {}).get("is_visually_hidden_from_conversation"): + if _is_hidden_message(msg): continue # Get author and timestamp @@ -297,7 +312,7 @@ def _format_chat_markdown( return "\n".join(lines) - def _get_message_content(self, message: Dict[str, Any]) -> str: # pragma: no cover + def _get_message_content(self, message: Dict[str, Any]) -> str: """Extract clean message content. Args: @@ -306,14 +321,30 @@ def _get_message_content(self, message: Dict[str, Any]) -> str: # pragma: no co Returns: Cleaned message content. """ - if not message or "content" not in message: + if not message: + return "" + + content = message.get("content") + if not isinstance(content, dict): return "" - content = message["content"] - if content.get("content_type") == "text": - return "\n".join(content.get("parts", [])) - elif content.get("content_type") == "code": - return f"```{content.get('language', '')}\n{content.get('text', '')}\n```" + content_type = content.get("content_type") + # Trigger: ChatGPT exports encode plain and attachment-bearing turns as + # "text" or "multimodal_text", where `parts` may mix strings with + # structured asset/quote dicts or null entries. + # Why: calling "\n".join() directly on `parts` raises TypeError and aborts + # the whole export, while ignoring "multimodal_text" drops user text. + # Outcome: preserve all textual parts and skip null or non-text objects. + if content_type in ("text", "multimodal_text"): + parts = content.get("parts") + if not isinstance(parts, list): + return "" + text_parts = [text for part in parts if (text := _extract_part_text(part)) is not None] + return "\n".join(text_parts) + if content_type == "code": + language = content.get("language") or "" + text = content.get("text") or "" + return f"```{language}\n{text}\n```" return "" def _traverse_messages( diff --git a/src/basic_memory/importers/claude_conversations_importer.py b/src/basic_memory/importers/claude_conversations_importer.py index b208e7b48..7e0f8b32b 100644 --- a/src/basic_memory/importers/claude_conversations_importer.py +++ b/src/basic_memory/importers/claude_conversations_importer.py @@ -185,25 +185,41 @@ def _format_chat_markdown( lines.append(f"### {msg['sender'].title()} ({ts})") # Handle message content - content = msg.get("text", "") - if msg.get("content"): - # Filter out None values before joining - content = " ".join( - str(c.get("text", "")) - for c in msg["content"] - if c and c.get("text") is not None - ) + # Trigger: Claude exports can carry non-text content blocks (thinking, + # tool_use) alongside a populated top-level `text`, or set + # `text` to null with an empty or absent `content` list. + # Why: unconditionally replacing `text` with joined `content` erases + # replies when no block has text, and appending None crashes join. + # Outcome: prefer extracted text blocks when non-empty; otherwise fall + # back to `text` or an empty string. + fallback_text = msg.get("text") + content = fallback_text if isinstance(fallback_text, str) else "" + raw_blocks = msg.get("content") + if isinstance(raw_blocks, list): + block_texts = [ + str(block["text"]) + for block in raw_blocks + if isinstance(block, dict) and block.get("text") is not None + ] + joined_blocks = " ".join(block_texts) + if joined_blocks.strip(): + content = joined_blocks lines.append(content) # Handle attachments - attachments = msg.get("attachments", []) - for attachment in attachments: - if "file_name" in attachment: - lines.append(f"\n**Attachment: {attachment['file_name']}**") - if "extracted_content" in attachment: - lines.append("```") - lines.append(attachment["extracted_content"]) - lines.append("```") + attachments = msg.get("attachments") + if isinstance(attachments, list): + for attachment in attachments: + if not isinstance(attachment, dict): + continue + file_name = attachment.get("file_name") + if file_name: + lines.append(f"\n**Attachment: {file_name}**") + extracted_content = attachment.get("extracted_content") + if extracted_content is not None: + lines.append("```") + lines.append(str(extracted_content)) + lines.append("```") # Add spacing between messages lines.append("") diff --git a/tests/cli/test_import_chatgpt.py b/tests/cli/test_import_chatgpt.py index 53d29603c..46f3bc6b4 100644 --- a/tests/cli/test_import_chatgpt.py +++ b/tests/cli/test_import_chatgpt.py @@ -355,3 +355,143 @@ def test_import_chatgpt_untitled_conversations_without_ids_stay_distinct( "20250111-Untitled_conversation_root_a.md", "20250111-Untitled_conversation_root_b.md", ] + + +def test_import_chatgpt_multimodal_and_null_fields(tmp_path): + """Import multimodal_text, mixed parts, null content/metadata, and code safely (#2230).""" + config = get_project_config() + config.home = tmp_path + + conversation = { + "title": "Multimodal Export", + "conversation_id": "conv-multimodal-1", + "create_time": 1736616594.0, + "update_time": 1736616603.0, + "mapping": { + "root": {"id": "root", "parent": None, "message": None, "children": ["m1"]}, + "m1": { + "id": "m1", + "parent": "root", + "message": { + "id": "m1", + "author": {"role": "user"}, + "create_time": 1736616594.0, + "content": { + "content_type": "multimodal_text", + "parts": [ + { + "content_type": "image_asset_pointer", + "asset_pointer": "file-service://file-123", + }, + "What is in this diagram?", + { + "content_type": "audio_transcription", + "text": "And explain the arrows.", + }, + ], + }, + "metadata": None, + }, + "children": ["m2"], + }, + "m2": { + "id": "m2", + "parent": "m1", + "message": { + "id": "m2", + "author": {"role": "assistant"}, + "create_time": 1736616596.0, + "content": { + "content_type": "text", + "parts": [None, {"content_type": "tether_quote"}, "Here is the breakdown."], + }, + "metadata": {}, + }, + "children": ["m3"], + }, + "m3": { + "id": "m3", + "parent": "m2", + "message": { + "id": "m3", + "author": {"role": "assistant"}, + "create_time": 1736616597.0, + "content": {"content_type": "text", "parts": None}, + "metadata": None, + }, + "children": ["m4"], + }, + "m4": { + "id": "m4", + "parent": "m3", + "message": { + "id": "m4", + "author": {"role": "assistant"}, + "create_time": 1736616598.0, + "content": None, + "metadata": {}, + }, + "children": ["m5"], + }, + "m5": { + "id": "m5", + "parent": "m4", + "message": { + "id": "m5", + "author": {"role": "assistant"}, + "create_time": 1736616599.0, + "content": {"content_type": "code", "language": None, "text": None}, + "metadata": {}, + }, + "children": ["m6"], + }, + "m6": { + "id": "m6", + "parent": "m5", + "message": { + "id": "m6", + "author": {"role": "assistant"}, + "create_time": 1736616600.0, + "content": {"content_type": "thoughts", "thoughts": []}, + "metadata": {}, + }, + "children": ["m7"], + }, + "m7": { + "id": "m7", + "parent": "m6", + "message": { + "id": "m7", + "author": {"role": "system"}, + "create_time": 1736616601.0, + "content": {"content_type": "text", "parts": ["Hidden system note"]}, + "metadata": {"is_visually_hidden_from_conversation": True}, + }, + "children": [], + }, + }, + } + json_file = tmp_path / "conversations.json" + json_file.write_text(json.dumps([conversation]), encoding="utf-8") + + result = runner.invoke(app, ["import", "chatgpt", str(json_file), "--folder", "chats"]) + assert result.exit_code == 0, result.output + assert "Imported 1 conversations" in result.output + assert "Containing 6 messages" in result.output + + expected_date = datetime.fromtimestamp(1736616594.0).astimezone().strftime("%Y%m%d") + conv_path = tmp_path / "chats" / f"{expected_date}-Multimodal_Export.md" + assert conv_path.exists() + content = conv_path.read_text(encoding="utf-8") + assert "What is in this diagram?\nAnd explain the arrows." in content + assert "Here is the breakdown." in content + assert "Hidden system note" not in content + assert "```None" not in content + + +def test_chatgpt_get_message_content_empty_message(): + """Empty message dicts return empty content without raising.""" + from basic_memory.importers.chatgpt_importer import ChatGPTImporter + + importer = ChatGPTImporter.__new__(ChatGPTImporter) + assert importer._get_message_content({}) == "" diff --git a/tests/cli/test_import_claude_conversations.py b/tests/cli/test_import_claude_conversations.py index 7e8e5352a..0d9e2f273 100644 --- a/tests/cli/test_import_claude_conversations.py +++ b/tests/cli/test_import_claude_conversations.py @@ -201,3 +201,68 @@ def test_import_conversation_with_none_text_values(tmp_path): content = conv_path.read_text(encoding="utf-8") assert "Valid text here" in content assert "More valid text" in content + + +def test_import_conversation_with_null_fields_and_non_text_blocks(tmp_path): + """Handle null text/attachments/extracted_content and preserve text over thinking blocks (#2230).""" + conversation = { + "uuid": "test-uuid-2230", + "name": "Thinking And Null Fields", + "created_at": "2025-01-05T20:55:32.499880+00:00", + "updated_at": "2025-01-05T20:56:39.477600+00:00", + "chat_messages": [ + { + "uuid": "msg-1", + "text": None, + "sender": "human", + "created_at": "2025-01-05T20:55:32.499880+00:00", + "content": [], + "attachments": None, + }, + { + "uuid": "msg-2", + "text": "Final answer", + "sender": "assistant", + "created_at": "2025-01-05T20:55:40.123456+00:00", + "content": [ + {"type": "thinking", "thinking": "Step 1..."}, + {"type": "tool_use", "name": "search"}, + ], + "attachments": [ + {"file_name": "diagram.png", "extracted_content": None}, + "malformed-entry", + {"file_name": None, "extracted_content": "orphan"}, + ], + }, + { + "uuid": "msg-3", + "text": "Fallback summary", + "sender": "assistant", + "created_at": "2025-01-05T20:55:50.123456+00:00", + "content": [ + {"type": "text", "text": ""}, + {"type": "thinking", "thinking": "Done"}, + ], + }, + ], + } + + json_file = tmp_path / "thinking_and_nulls.json" + json_file.write_text(json.dumps([conversation]), encoding="utf-8") + + config = get_project_config() + config.home = tmp_path + + result = runner.invoke(app, ["import", "claude", "conversations", str(json_file)]) + assert result.exit_code == 0, result.output + assert "Imported 1 conversations" in result.output + assert "Containing 3 messages" in result.output + + conv_path = tmp_path / "conversations/20250105-Thinking_And_Null_Fields.md" + assert conv_path.exists() + content = conv_path.read_text(encoding="utf-8") + assert "Final answer" in content + assert "Fallback summary" in content + assert "**Attachment: diagram.png**" in content + assert "**Attachment: None**" not in content + assert "```" not in content