Create or return a persistent GUI chat session.
(
user_id: str,
title: str = "",
session_id: Optional[str] = None,
)
| 287 | |
| 288 | |
| 289 | def create_chat_session( |
| 290 | user_id: str, |
| 291 | title: str = "", |
| 292 | session_id: Optional[str] = None, |
| 293 | ) -> Dict[str, Any]: |
| 294 | """Create or return a persistent GUI chat session.""" |
| 295 | normalized_user_id = _normalize_identifier(user_id) |
| 296 | if not normalized_user_id: |
| 297 | raise ValueError("user_id is required") |
| 298 | |
| 299 | ensure_chat_tables() |
| 300 | normalized_session_id = _normalize_identifier(session_id) or f"chat_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}" |
| 301 | normalized_title = _chat_title_from_content(title) |
| 302 | now = _chat_now() |
| 303 | |
| 304 | conn = get_connection() |
| 305 | cursor = conn.cursor() |
| 306 | cursor.execute( |
| 307 | """ |
| 308 | INSERT OR IGNORE INTO chat_sessions (session_id, user_id, title, created_at, updated_at, message_count) |
| 309 | VALUES (?, ?, ?, ?, ?, 0) |
| 310 | """, |
| 311 | (normalized_session_id, normalized_user_id, normalized_title, now, now), |
| 312 | ) |
| 313 | cursor.execute( |
| 314 | """ |
| 315 | SELECT session_id, user_id, title, created_at, updated_at, message_count |
| 316 | FROM chat_sessions |
| 317 | WHERE user_id = ? AND session_id = ? |
| 318 | """, |
| 319 | (normalized_user_id, normalized_session_id), |
| 320 | ) |
| 321 | row = cursor.fetchone() |
| 322 | conn.commit() |
| 323 | conn.close() |
| 324 | if not row: |
| 325 | raise ValueError("chat session belongs to another user or could not be created") |
| 326 | return _chat_session_row(row) |
| 327 | |
| 328 | |
| 329 | def save_chat_message( |
no test coverage detected