File size: 3,613 Bytes
e586655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05fd38f
 
 
 
 
 
 
 
 
 
e586655
05fd38f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e586655
05fd38f
e586655
05fd38f
 
e586655
 
 
 
05fd38f
e586655
 
05fd38f
 
 
 
 
e586655
 
 
 
05fd38f
 
 
 
 
 
 
 
e586655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
130
131
132
133
134
135
136
import { useState, useEffect } from "react";

export interface Session {
  id: string;
  name: string;
  messages: Message[];
}

export interface Message {
  id: string;
  from: "user" | "ai";
  content: string;
}

const SESSION_STORAGE_KEY = "webzero_sessions";
const CURRENT_SESSION_ID_KEY = "webzero_current_session_id";

export function useSessions() {
  const [sessions, setSessions] = useState<Session[]>(() => {
    if (typeof window === "undefined") return [];
    try {
      const storedSessions = localStorage.getItem(SESSION_STORAGE_KEY);
      return storedSessions ? JSON.parse(storedSessions) : [];
    } catch (error) {
      console.error("Failed to parse sessions from localStorage:", error);
      return [];
    }
  });

  const [currentSessionId, setCurrentSessionId] = useState<string | null>(
    () => {
      if (typeof window === "undefined") return null;
      try {
        const storedId = localStorage.getItem(CURRENT_SESSION_ID_KEY);
        return storedId && sessions.some((s) => s.id === storedId)
          ? storedId
          : sessions[0]?.id || null;
      } catch (error) {
        console.error(
          "Failed to retrieve currentSessionId from localStorage:",
          error
        );
        return sessions[0]?.id || null;
      }
    }
  );

  useEffect(() => {
    if (sessions.length === 0) {
      const newSession = createNewSessionObject();
      setSessions([newSession]);
      setCurrentSessionId(newSession.id);
    }
  }, [sessions]);

  useEffect(() => {
    try {
      localStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(sessions));
    } catch (error) {
      console.error("Failed to save sessions to localStorage:", error);
    }
  }, [sessions]);

  useEffect(() => {
    if (currentSessionId) {
      try {
        localStorage.setItem(CURRENT_SESSION_ID_KEY, currentSessionId);
      } catch (error) {
        console.error(
          "Failed to save currentSessionId to localStorage:",
          error
        );
      }
    }
  }, [currentSessionId]);

  const createNewSessionObject = (): Session => ({
    id: Date.now().toString(),
    name: `Session ${sessions.length + 1}`,
    messages: [],
  });

  const createNewSession = () => {
    const newSession = createNewSessionObject();
    setSessions((prevSessions) => [...prevSessions, newSession]);
    setCurrentSessionId(newSession.id);
  };

  const switchSession = (sessionId: string) => {
    setCurrentSessionId(sessionId);
  };

  const updateSessionMessages = (sessionId: string, messages: Message[]) => {
    setSessions((prevSessions) =>
      prevSessions.map((session) =>
        session.id === sessionId ? { ...session, messages } : session
      )
    );
  };

  const deleteSession = (sessionId: string) => {
    setSessions((prevSessions) => {
      const updatedSessions = prevSessions.filter(
        (session) => session.id !== sessionId
      );
      if (updatedSessions.length === 0) {
        const newSession = createNewSessionObject();
        setCurrentSessionId(newSession.id);
        return [newSession];
      }
      if (currentSessionId === sessionId) {
        setCurrentSessionId(updatedSessions[0].id);
      }
      return updatedSessions;
    });
  };

  const renameSession = (sessionId: string, newName: string) => {
    setSessions((prevSessions) =>
      prevSessions.map((session) =>
        session.id === sessionId ? { ...session, name: newName } : session
      )
    );
  };

  return {
    sessions,
    currentSessionId,
    createNewSession,
    switchSession,
    updateSessionMessages,
    deleteSession,
    renameSession,
  };
}