Xinfan Chen
2026-03-27 cf749073df5f64572a00680f1d22680ded9cc3cf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# -*- coding: utf-8 -*-
import json
import os
import time
 
class SessionManager:
    """Manages chat sessions persistence"""
    def __init__(self, data_dir="code/data"):
        self.data_dir = data_dir
        if not os.path.exists(data_dir):
            os.makedirs(data_dir)
 
    def _get_file(self, session_id):
        return os.path.join(self.data_dir, f"{session_id}.json")
 
    def list_sessions(self):
        """List all sessions ordered by modification time"""
        sessions = []
        if not os.path.exists(self.data_dir):
            return sessions
 
        files = [f for f in os.listdir(self.data_dir) if f.endswith('.json')]
        for f in files:
            try:
                path = os.path.join(self.data_dir, f)
                with open(path, 'r', encoding='utf-8') as fs:
                    data = json.load(fs)
                    # title, id, last_updated
                    sessions.append({
                        "id": data.get("id"),
                        "title": data.get("title", "Untitled"),
                        "date": "7days", # Simplification. Real logic would calc date diff
                        "timestamp": os.path.getmtime(path)
                    })
            except Exception:
                continue
        
        # Sort by timestamp desc
        sessions.sort(key=lambda x: x['timestamp'], reverse=True)
        return sessions
 
    def get_session(self, session_id):
        """Get full history of a session"""
        path = self._get_file(session_id)
        if os.path.exists(path):
            try:
                with open(path, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception:
                pass
        return None
 
    def save_session(self, session_id, title, messages, asset_library=None):
        """Save or update session"""
        data = {
            "id": session_id,
            "title": title,
            "last_updated": time.time(),
            "messages": messages,
            "asset_library": asset_library or {}
        }
        with open(self._get_file(session_id), 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)