File size: 9,186 Bytes
6a7089a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d286842
6a7089a
 
d286842
 
 
 
 
 
 
 
 
 
6a7089a
 
 
 
 
d286842
 
 
 
 
6a7089a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import { useEffect, useState } from "react";
import {
  BrowserRouter,
  Routes,
  Route,
  Navigate,
  useLocation,
  useNavigate,
} from "react-router-dom";
import { useAppStore } from "./stores/useAppStore";
import { NavBar } from "./components/molecules";
import { LoginPage, MonitoringPage, ProfilesPage, SettingsPage } from "./pages";
import * as api from "./services/api";
import {
  AUTH_REQUIRED_EVENT,
  clearStoredAuthToken,
  getStoredAuthToken,
  setStoredAuthToken,
} from "./services/auth";

type AuthMode = "probing" | "required" | "open" | "unreachable";
const AUTH_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000] as const;

function AppContent() {
  const {
    setInstances,
    setProfiles,
    setAgents,
    setServerInfo,
    applyMonitoringSnapshot,
    settings,
  } = useAppStore();
  const location = useLocation();
  const navigate = useNavigate();
  const memoryMetricsEnabled = settings.monitoring?.memoryMetrics ?? false;
  // Auto-login from ?token= query parameter (e.g. from wizard URL)
  // or injected meta tag for Hugging Face Spaces integration
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    let urlToken = params.get("token");
    if (!urlToken) {
      const meta = document.querySelector("meta[name='pinchtab-token']");
      const metaContent = meta?.getAttribute("content") || "";
      // Exclude the unreplaced template literal from injection
      if (metaContent && metaContent !== "{{PINCHTAB_TOKEN_INJECT}}") {
        urlToken = metaContent;
      }
    }
    
    if (urlToken) {
      setStoredAuthToken(urlToken);
      const clean = new URL(window.location.href);
      clean.searchParams.delete("token");
      window.history.replaceState({}, "", clean.pathname + clean.hash);
      // Let the main login flow handle reload if necessary, but actually
      // if we just updated localStorage we want to reload so state is updated
      if (getStoredAuthToken() !== urlToken) {
        window.location.reload();
      }
    }
  }, []);

  const authToken = getStoredAuthToken();
  const hasStoredToken = authToken !== "";
  const [authMode, setAuthMode] = useState<AuthMode>(
    hasStoredToken ? "required" : "probing",
  );
  const [authRetryCount, setAuthRetryCount] = useState(0);
  const dashboardAccessible = hasStoredToken || authMode === "open";
  const loginRequired = !hasStoredToken && authMode === "required";

  useEffect(() => {
    document.documentElement.setAttribute("data-site-mode", "agent");
  }, []);

  useEffect(() => {
    if (hasStoredToken) {
      setAuthMode("required");
      setAuthRetryCount(0);
      return;
    }

    if (authMode === "open" || authMode === "unreachable") {
      return;
    }

    let cancelled = false;
    api
      .probeBackendAuth()
      .then((result) => {
        if (cancelled) {
          return;
        }
        setAuthMode(result.requiresAuth ? "required" : "open");
        setAuthRetryCount(0);
        if (result.health) {
          setServerInfo(result.health);
        }
      })
      .catch((error) => {
        if (cancelled) {
          return;
        }
        console.error("Failed to probe backend auth", error);
        setAuthMode("unreachable");
      });

    return () => {
      cancelled = true;
    };
  }, [authMode, hasStoredToken, setServerInfo]);

  useEffect(() => {
    if (
      hasStoredToken ||
      authMode !== "unreachable" ||
      authRetryCount >= AUTH_RETRY_DELAYS_MS.length
    ) {
      return;
    }

    const timer = window.setTimeout(() => {
      setAuthRetryCount((count) => count + 1);
      setAuthMode("probing");
    }, AUTH_RETRY_DELAYS_MS[authRetryCount]);

    return () => {
      window.clearTimeout(timer);
    };
  }, [authMode, authRetryCount, hasStoredToken]);

  useEffect(() => {
    const handleAuthRequired = () => {
      clearStoredAuthToken();
      setAuthMode("required");
      setAuthRetryCount(0);
      navigate("/login", {
        replace: true,
        state: { from: location.pathname },
      });
    };
    window.addEventListener(AUTH_REQUIRED_EVENT, handleAuthRequired);
    return () =>
      window.removeEventListener(AUTH_REQUIRED_EVENT, handleAuthRequired);
  }, [location.pathname, navigate]);

  useEffect(() => {
    if (loginRequired && location.pathname !== "/login") {
      navigate("/login", {
        replace: true,
        state: { from: location.pathname },
      });
    }
  }, [location.pathname, loginRequired, navigate]);

  // Initial load
  useEffect(() => {
    if (!dashboardAccessible) {
      return;
    }
    const load = async () => {
      try {
        const [instances, profiles, health] = await Promise.all([
          api.fetchInstances(),
          api.fetchProfiles(),
          api.fetchHealth(),
        ]);
        setInstances(instances);
        setProfiles(profiles);
        setServerInfo(health);
      } catch (e) {
        console.error("Failed to load initial data", e);
      }
    };
    load();
  }, [dashboardAccessible, setInstances, setProfiles, setServerInfo]);

  // Subscribe to SSE events
  useEffect(() => {
    if (!dashboardAccessible) {
      return;
    }
    const unsubscribe = api.subscribeToEvents(
      {
        onInit: (agents) => {
          setAgents(agents);
        },
        onSystem: (event) => {
          console.log("System event:", event);
        },
        onAgent: (event) => {
          console.log("Agent event:", event);
        },
        onMonitoring: (snapshot) => {
          applyMonitoringSnapshot(snapshot, memoryMetricsEnabled);
        },
      },
      {
        includeMemory: memoryMetricsEnabled,
      },
    );

    return unsubscribe;
  }, [
    dashboardAccessible,
    applyMonitoringSnapshot,
    memoryMetricsEnabled,
    setAgents,
    setInstances,
    setProfiles,
  ]);

  if (!hasStoredToken && authMode === "probing") {
    return (
      <div className="flex min-h-screen items-center justify-center bg-bg-app px-4">
        <div className="rounded-sm border border-border-subtle bg-black/10 px-4 py-3 text-sm text-text-muted">
          Checking server authentication...
        </div>
      </div>
    );
  }

  if (!hasStoredToken && authMode === "unreachable") {
    const nextRetryDelay =
      authRetryCount < AUTH_RETRY_DELAYS_MS.length
        ? AUTH_RETRY_DELAYS_MS[authRetryCount]
        : null;

    return (
      <div className="flex min-h-screen items-center justify-center bg-bg-app px-4">
        <div className="max-w-md space-y-3 rounded-sm border border-border-subtle bg-black/10 px-4 py-3 text-sm text-text-muted">
          <div>
            PinchTab is restarting or unreachable.
            {nextRetryDelay !== null
              ? ` Retrying in ${Math.ceil(nextRetryDelay / 1000)}s...`
              : " Automatic retries stopped."}
          </div>
          {nextRetryDelay === null && (
            <div className="flex justify-end gap-2">
              <button
                type="button"
                className="rounded-sm border border-border-subtle px-3 py-2 text-sm text-text-primary transition-all duration-150 hover:border-primary/30 hover:bg-bg-elevated"
                onClick={() => {
                  setAuthRetryCount(0);
                  setAuthMode("probing");
                }}
              >
                Retry now
              </button>
              <button
                type="button"
                className="rounded-sm border border-border-subtle px-3 py-2 text-sm text-text-primary transition-all duration-150 hover:border-primary/30 hover:bg-bg-elevated"
                onClick={() => window.location.reload()}
              >
                Refresh
              </button>
            </div>
          )}
        </div>
      </div>
    );
  }

  if (loginRequired) {
    return (
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route path="*" element={<Navigate to="/login" replace />} />
      </Routes>
    );
  }

  return (
    <div className="dashboard-shell flex h-screen flex-col bg-bg-app">
      <NavBar />
      <main className="dashboard-grid flex-1 overflow-hidden">
        <Routes>
          <Route
            path="/"
            element={<Navigate to="/dashboard/monitoring" replace />}
          />
          <Route
            path="/login"
            element={<Navigate to="/dashboard/monitoring" replace />}
          />
          <Route
            path="/dashboard"
            element={<Navigate to="/dashboard/monitoring" replace />}
          />
          <Route path="/dashboard/monitoring" element={<MonitoringPage />} />
          <Route path="/dashboard/profiles" element={<ProfilesPage />} />
          <Route
            path="/dashboard/agents"
            element={<Navigate to="/dashboard/monitoring" replace />}
          />
          <Route path="/dashboard/settings" element={<SettingsPage />} />
          <Route
            path="*"
            element={<Navigate to="/dashboard/monitoring" replace />}
          />
        </Routes>
      </main>
    </div>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <AppContent />
    </BrowserRouter>
  );
}