File size: 5,371 Bytes
daa81fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dbea29
daa81fb
 
 
 
 
93312fc
daa81fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import streamlit as st
from app.chat import (
    create_chat_session,
    list_chat_sessions,
    ensure_chat_session,
    delete_chat_session,
    delete_all_chat_sessions,
)
from app.db import supabase


def render_sidebar_sessions():
    """Render the sidebar: sessions list/search/pagination, actions, and logout.
    Assumes st.session_state['user'] exists.
    """
    st.sidebar.header("Percakapan")
    if st.sidebar.button("βž• New Chat", use_container_width=True):
        uid = st.session_state["user"]["id"]
        new_sid = create_chat_session(uid, title="Percakapan Baru")
        st.session_state["session_id"] = new_sid
        for k in ["history", "generated", "past", "input_text", "tts_output", "tts_played"]:
            if k in st.session_state:
                del st.session_state[k]
        st.rerun()

    # Search and pagination controls
    search_query = st.sidebar.text_input("Cari sesi", value=st.session_state.get("session_search", ""))
    st.session_state["session_search"] = search_query

    page_size = st.sidebar.selectbox("Jumlah per halaman", [5, 10, 20, 50], index=1, key="session_page_size")
    current_page = st.session_state.get("session_page", 0)

    # Fetch sessions
    try:
        sessions = list_chat_sessions(st.session_state["user"]["id"], limit=1000)
    except Exception as e:
        st.sidebar.error(f"Tidak dapat memuat sesi: {e}")
        sessions = []

    # Filter by search
    if search_query:
        sq = search_query.lower()
        sessions = [s for s in sessions if sq in (s.get("title") or "").lower() or sq in s.get("id", "").lower()]

    # Pagination
    total = len(sessions)
    start = current_page * page_size
    end = start + page_size
    page_sessions = sessions[start:end]

    cols = st.sidebar.columns([1, 3, 1])
    disable_prev = current_page <= 0
    disable_next = end >= total
    if cols[0].button("←", disabled=disable_prev):
        st.session_state["session_page"] = max(0, current_page - 1)
        st.rerun()
    cols[1].markdown(f"Halaman {current_page + 1} / {max(1, (total + page_size - 1) // page_size)}")
    if cols[2].button("β†’", disabled=disable_next):
        st.session_state["session_page"] = current_page + 1
        st.rerun()

    # List sessions with select and delete
    for s in page_sessions:
        sid = s["id"]
        title = s.get("title") or sid
        row = st.sidebar.container()
        subcols = row.columns([6, 1])
        if subcols[0].button(title, key=f"select_{sid}"):
            st.session_state["session_id"] = sid
            ensure_chat_session(st.session_state["user"]["id"], sid)  # ensure selected session exists
            # Clear local caches if switching
            for k in ["history", "generated", "past"]:
                if k in st.session_state:
                    del st.session_state[k]
            st.rerun()
        if subcols[1].button("❌", key=f"del_{sid}"):
            try:
                ok = delete_chat_session(st.session_state["user"]["id"], sid)
                if ok:
                    # If deleting active, choose next one or create new
                    if st.session_state.get("session_id") == sid:
                        remaining = [x for x in sessions if x["id"] != sid]
                        if remaining:
                            st.session_state["session_id"] = remaining[0]["id"]
                        else:
                            st.session_state["session_id"] = create_chat_session(st.session_state["user"]["id"], title="Percakapan Baru")
                    for k in ["history", "generated", "past"]:
                        if k in st.session_state:
                            del st.session_state[k]
                    st.success("Sesi dihapus")
                    st.rerun()
                else:
                    st.error("Gagal menghapus sesi")
            except Exception as e:
                st.error(f"Gagal menghapus: {e}")

    st.sidebar.divider()
    with st.sidebar.expander("Hapus Semua Percakapan", expanded=False):
        confirm = st.checkbox("Saya yakin ingin menghapus semua percakapan", key="confirm_delete_all")
        if st.button("Hapus Semua", type="primary", disabled=not confirm):
            try:
                ok = delete_all_chat_sessions(st.session_state["user"]["id"])
                if ok:
                    st.session_state["session_id"] = create_chat_session(st.session_state["user"]["id"], title="Percakapan Baru")
                    for k in ["history", "generated", "past"]:
                        if k in st.session_state:
                            del st.session_state[k]
                    st.success("Semua percakapan dihapus")
                    st.rerun()
                else:
                    st.error("Gagal menghapus semua percakapan")
            except Exception as e:
                st.error(f"Gagal menghapus semua: {e}")

    st.sidebar.divider()
    if st.sidebar.button("Logout"):
        try:
            supabase.auth.sign_out()
        except Exception:
            pass
        for k in [
            "user", "history", "generated", "past", "input_text",
            "tts_output", "tts_played", "vector_store", "session_id", "sb_session"
        ]:
            if k in st.session_state:
                del st.session_state[k]
        st.success("Anda telah logout")
        st.rerun()