File size: 8,270 Bytes
d0878a6
ffcad5d
 
 
 
 
 
 
 
 
d0878a6
 
 
 
 
 
 
 
 
ffcad5d
 
 
d0878a6
 
ffcad5d
 
 
d0878a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffcad5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0878a6
 
 
 
 
 
 
ffcad5d
 
 
 
 
 
 
 
 
 
 
 
 
 
d0878a6
ffcad5d
 
 
 
 
 
 
 
 
 
 
 
 
 
d0878a6
ffcad5d
 
d0878a6
ffcad5d
 
 
d0878a6
ffcad5d
 
 
 
d0878a6
ffcad5d
 
 
 
 
d0878a6
ffcad5d
 
 
d0878a6
ffcad5d
 
 
d0878a6
 
 
 
 
 
 
 
 
ffcad5d
 
 
 
 
 
d0878a6
 
 
ffcad5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0878a6
ffcad5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad7840f
ffcad5d
 
d0878a6
 
 
 
ffcad5d
 
 
 
 
 
 
 
 
 
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { ThemeProvider } from './contexts/ThemeContext';
import { AppConfigProvider } from './contexts/AppConfigContext';
import HomePage from './pages/HomePage';
import ChatPage from './pages/ChatPage';
import AuthPage from './pages/AuthPage';
import CanvasPage from './pages/CanvasPage';
import JourneyPage from './pages/JourneyPage';
import UserGuide from './components/UserGuide';
import './styles/components.css';
import {
  chatActiveState,
  chatStarterState,
  homeState,
  mapPopState,
  sameHistoryState,
} from './utils/chatHistoryNav';

let didSeedRestoredChatHistory = false;

function App() {
  const [currentView, setCurrentView] = useState('home');
  const [chatNavView, setChatNavView] = useState(null);
  const [chatStarterNonce, setChatStarterNonce] = useState(0);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState(null);
  const [authToken, setAuthToken] = useState(null);
  const historyStateRef = useRef(null);
  const chatNavViewRef = useRef(null);
  chatNavViewRef.current = chatNavView;

  const applyHistoryState = useCallback((state, { fromPop = false, replace = false } = {}) => {
    const mapped = mapPopState(state);
    if (!fromPop) {
      if (sameHistoryState(historyStateRef.current, state)) {
        setCurrentView(mapped.currentView);
        setChatNavView(mapped.chatNavView);
        return;
      }
      if (replace) {
        window.history.replaceState(state, '');
      } else {
        window.history.pushState(state, '');
      }
    }
    historyStateRef.current = state || null;
    setCurrentView(mapped.currentView);
    if (mapped.chatNavView === 'starter' && chatNavViewRef.current === 'active') {
      setChatStarterNonce((n) => n + 1);
    }
    setChatNavView(mapped.chatNavView);
  }, []);

  useEffect(() => {
    const onPop = (event) => {
      applyHistoryState(event.state, { fromPop: true });
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, [applyHistoryState]);

  useEffect(() => {
    let cancelled = false;
    const token = localStorage.getItem('authToken');
    const userData = localStorage.getItem('user');

    if (!token || !userData) return undefined;

    let parsedUser;
    try {
      parsedUser = JSON.parse(userData);
    } catch {
      localStorage.removeItem('authToken');
      localStorage.removeItem('user');
      return undefined;
    }

    // Restore UI immediately, then prove the JWT still works. Stale tokens
    // (rotated secret, deleted guest, etc.) previously left the user in chat
    // with every API call 401'ing and send silently failing.
    setAuthToken(token);
    setUser(parsedUser);
    setIsAuthenticated(true);
    if (!didSeedRestoredChatHistory) {
      didSeedRestoredChatHistory = true;
      applyHistoryState(chatStarterState());
    } else {
      setCurrentView('chat');
      setChatNavView('starter');
    }

    (async () => {
      try {
        const apiUrl = process.env.REACT_APP_API_URL || '';
        const resp = await fetch(`${apiUrl}/auth/me`, {
          headers: { Authorization: `Bearer ${token}` },
        });
        if (cancelled) return;
        if (!resp.ok) {
          localStorage.removeItem('authToken');
          localStorage.removeItem('user');
          setUser(null);
          setAuthToken(null);
          setIsAuthenticated(false);
          applyHistoryState(homeState(), { replace: true });
          return;
        }
        const me = await resp.json();
        if (cancelled || !me) return;
        setUser(me);
        try {
          localStorage.setItem('user', JSON.stringify(me));
        } catch { /* ignore quota */ }
      } catch {
        // Network blip — keep optimistic session; next API call will re-check.
      }
    })();

    return () => { cancelled = true; };
  }, [applyHistoryState]);

  const navigateToAuth = () => {
    applyHistoryState({ view: 'auth' });
  };

  const navigateToJourney = () => {
    applyHistoryState({ view: 'journey' });
  };

  const navigateToCanvas = (canvasView) => {
    if (canvasView === 'journey') {
      applyHistoryState({ view: 'journey' });
      return;
    }
    if (['insights', 'workspace', 'deliverables'].includes(canvasView)) {
      localStorage.setItem('canvas-view-v2', canvasView);
    }
    applyHistoryState({ view: 'canvas' });
  };

  const navigateToChat = () => {
    applyHistoryState(chatStarterState());
  };

  const navigateToHome = () => {
    applyHistoryState(homeState());
  };

  const handleChatBecameActive = (sessionId) => {
    applyHistoryState(chatActiveState(sessionId));
  };

  const handleChatReturnedToStarter = () => {
    applyHistoryState(chatStarterState(), { replace: true });
  };

  const handleAuthSuccess = (userData, token) => {
    setUser(userData);
    setAuthToken(token);
    setIsAuthenticated(true);
    applyHistoryState(chatStarterState(), {
      replace: historyStateRef.current?.view === 'auth',
    });
  };

  const handleSignOut = () => {
    localStorage.removeItem('authToken');
    localStorage.removeItem('user');
    try {
      localStorage.removeItem('canvas-layout-v2');
      localStorage.removeItem('canvas-states-v2');
      localStorage.removeItem('canvas-deliverables-v2');
      localStorage.removeItem('canvas-view-v2');
      localStorage.removeItem('canvas-task-status-v1');
    } catch { /* ignore */ }
    setUser(null);
    setAuthToken(null);
    setIsAuthenticated(false);
    applyHistoryState(homeState(), { replace: true });
  };

  return (
    <AppConfigProvider>

      <ThemeProvider>

        <div className="App">

          {currentView === 'home' && (

            <HomePage

              onNavigateToHome={navigateToHome}

              onNavigateToChat={isAuthenticated ? navigateToChat : navigateToAuth}

              onNavigateToCanvas={isAuthenticated ? navigateToCanvas : navigateToAuth}

              onNavigateToJourney={isAuthenticated ? navigateToJourney : navigateToAuth}

              onExploreAsGuest={handleAuthSuccess}

              isAuthenticated={isAuthenticated}

            />

          )}

          {currentView === 'auth' && (

            <AuthPage onAuthSuccess={handleAuthSuccess} />

          )}

          {currentView === 'canvas' && isAuthenticated && (

            <CanvasPage

              user={user}

              authToken={authToken}

              onNavigateToHome={navigateToHome}

              onNavigateToChat={navigateToChat}

              onNavigateToJourney={navigateToJourney}

              onNavigateToCanvas={navigateToCanvas}

              onSignOut={handleSignOut}

              onUserUpdate={setUser}

            />

          )}

          {currentView === 'journey' && isAuthenticated && (

            <JourneyPage

              user={user}

              authToken={authToken}

              onNavigateToHome={navigateToHome}

              onNavigateToChat={navigateToChat}

              onNavigateToCanvas={navigateToCanvas}

              onNavigateToJourney={navigateToJourney}

              onSignOut={handleSignOut}

              onUserUpdate={setUser}

            />

          )}

          {currentView === 'chat' && isAuthenticated && (

            <ChatPage

              user={user}

              authToken={authToken}

              onNavigateToHome={navigateToHome}

              onNavigateToCanvas={navigateToCanvas}

              onNavigateToJourney={navigateToJourney}

              onNavigateToSignup={navigateToAuth}

              onSignOut={handleSignOut}

              onUserUpdate={setUser}

              chatNavView={chatNavView}

              chatStarterNonce={chatStarterNonce}

              onChatBecameActive={handleChatBecameActive}

              onChatReturnedToStarter={handleChatReturnedToStarter}

            />

          )}

          <UserGuide />

        </div>

      </ThemeProvider>

    </AppConfigProvider>
  );
}

export default App;