(self, username: str, data: dict)
| 1229 | return await self.get_session(username, session_id) |
| 1230 | |
| 1231 | async def create_thread(self, username: str, data: dict) -> dict: |
| 1232 | session_id = data.get("session_id") |
| 1233 | parent_message_id = data.get("parent_message_id") |
| 1234 | selected_text = str(data.get("selected_text") or "").strip() |
| 1235 | if not session_id: |
| 1236 | raise ChatServiceError("Missing key: session_id") |
| 1237 | if parent_message_id is None: |
| 1238 | raise ChatServiceError("Missing key: parent_message_id") |
| 1239 | if not selected_text: |
| 1240 | raise ChatServiceError("Missing key: selected_text") |
| 1241 | |
| 1242 | try: |
| 1243 | parent_message_id = int(parent_message_id) |
| 1244 | except (TypeError, ValueError) as exc: |
| 1245 | raise ChatServiceError("Invalid key: parent_message_id") from exc |
| 1246 | |
| 1247 | session = await self.db.get_platform_session_by_id(session_id) |
| 1248 | if not session: |
| 1249 | raise ChatServiceError(f"Session {session_id} not found") |
| 1250 | if session.creator != username: |
| 1251 | raise ChatServiceError("Permission denied") |
| 1252 | |
| 1253 | parent_record = await self.db.get_platform_message_history_by_id( |
| 1254 | parent_message_id |
| 1255 | ) |
| 1256 | if ( |
| 1257 | not parent_record |
| 1258 | or parent_record.platform_id != session.platform_id |
| 1259 | or parent_record.user_id != session_id |
| 1260 | ): |
| 1261 | raise ChatServiceError("Parent message not found") |
| 1262 | if not isinstance(parent_record.content, dict): |
| 1263 | raise ChatServiceError("Invalid parent message content") |
| 1264 | if parent_record.content.get("type") != "bot": |
| 1265 | raise ChatServiceError("Only bot messages can create threads") |
| 1266 | |
| 1267 | checkpoint_id = parent_record.llm_checkpoint_id |
| 1268 | if not checkpoint_id: |
| 1269 | raise ChatServiceError("Parent message is not linked to LLM history") |
| 1270 | |
| 1271 | existing = await self.db.get_webchat_thread_by_parent_message_and_text( |
| 1272 | parent_session_id=session_id, |
| 1273 | parent_message_id=parent_message_id, |
| 1274 | selected_text=selected_text, |
| 1275 | creator=username, |
| 1276 | ) |
| 1277 | if existing: |
| 1278 | return serialize_thread(existing) |
| 1279 | |
| 1280 | conversation_id, history = await self.load_current_conversation_history(session) |
| 1281 | turn_range = find_turn_range(history, checkpoint_id) |
| 1282 | if not conversation_id or not turn_range: |
| 1283 | raise ChatServiceError("Linked checkpoint not found") |
| 1284 | |
| 1285 | _start, end = turn_range |
| 1286 | base_history = history[: end + 1] |
| 1287 | thread = await self.db.create_webchat_thread( |
| 1288 | creator=username, |
no test coverage detected