-
Notifications
You must be signed in to change notification settings - Fork 613
Expand file tree
/
Copy pathApp.tsx
More file actions
287 lines (253 loc) · 8.58 KB
/
App.tsx
File metadata and controls
287 lines (253 loc) · 8.58 KB
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
import SubscribedApp from "./_pages/SubscribedApp"
import { UpdateNotification } from "./components/UpdateNotification"
import {
QueryClient,
QueryClientProvider
} from "@tanstack/react-query"
import { useEffect, useState, useCallback } from "react"
import {
Toast,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport
} from "./components/ui/toast"
import { ToastContext } from "./contexts/toast"
import { WelcomeScreen } from "./components/WelcomeScreen"
import { SettingsDialog } from "./components/Settings/SettingsDialog"
// Create a React Query client
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 0,
gcTime: Infinity,
retry: 1,
refetchOnWindowFocus: false
},
mutations: {
retry: 1
}
}
})
// Root component that provides the QueryClient
function App() {
const [toastState, setToastState] = useState({
open: false,
title: "",
description: "",
variant: "neutral" as "neutral" | "success" | "error"
})
const [credits, setCredits] = useState<number>(999) // Unlimited credits
const [currentLanguage, setCurrentLanguage] = useState<string>("python")
const [isInitialized, setIsInitialized] = useState(false)
const [hasApiKey, setHasApiKey] = useState(false)
const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false)
// Note: Model selection is now handled via separate extraction/solution/debugging model settings
const [isSettingsOpen, setIsSettingsOpen] = useState(false)
// Set unlimited credits
const updateCredits = useCallback(() => {
setCredits(999) // No credit limit in this version
window.__CREDITS__ = 999
}, [])
// Helper function to safely update language
const updateLanguage = useCallback((newLanguage: string) => {
setCurrentLanguage(newLanguage)
window.__LANGUAGE__ = newLanguage
}, [])
// Helper function to mark initialization complete
const markInitialized = useCallback(() => {
setIsInitialized(true)
window.__IS_INITIALIZED__ = true
}, [])
// Show toast method
const showToast = useCallback(
(
title: string,
description: string,
variant: "neutral" | "success" | "error"
) => {
setToastState({
open: true,
title,
description,
variant
})
},
[]
)
// Check for OpenAI API key and prompt if not found
useEffect(() => {
const checkApiKey = async () => {
try {
const hasKey = await window.electronAPI.checkApiKey()
setHasApiKey(hasKey)
if (!hasKey) {
showToast("API Key Required", "Please set up your API key in settings to use the application.", "neutral")
}
} catch (error) {
console.error("Failed to check API key:", error)
}
}
if (isInitialized) {
checkApiKey()
}
}, [isInitialized, showToast])
// Initialize dropdown handler
useEffect(() => {
if (isInitialized) {
// Process all types of dropdown elements with a shorter delay
const timer = setTimeout(() => {
// Find both native select elements and custom dropdowns
const selectElements = document.querySelectorAll('select');
const customDropdowns = document.querySelectorAll('.dropdown-trigger, [role="combobox"], button:has(.dropdown)');
// Enable native selects
selectElements.forEach(dropdown => {
dropdown.disabled = false;
});
// Enable custom dropdowns by removing any disabled attributes
customDropdowns.forEach(dropdown => {
if (dropdown instanceof HTMLElement) {
dropdown.removeAttribute('disabled');
dropdown.setAttribute('aria-disabled', 'false');
}
});
console.log(`Enabled ${selectElements.length} select elements and ${customDropdowns.length} custom dropdowns`);
}, 1000);
return () => clearTimeout(timer);
}
}, [isInitialized]);
// Listen for settings dialog open requests
useEffect(() => {
const unsubscribeSettings = window.electronAPI.onShowSettings(() => {
console.log("Show settings dialog requested");
setIsSettingsOpen(true);
});
return () => {
unsubscribeSettings();
};
}, []);
// Initialize basic app state
useEffect(() => {
// Load config and set values
const initializeApp = async () => {
try {
// Set unlimited credits
updateCredits()
// Load config including language and model settings
const config = await window.electronAPI.getConfig()
// Load language preference
if (config && config.language) {
updateLanguage(config.language)
} else {
updateLanguage("python")
}
// Model settings are now managed through the settings dialog
// and stored in config as extractionModel, solutionModel, and debuggingModel
markInitialized()
} catch (error) {
console.error("Failed to initialize app:", error)
// Fallback to defaults
updateLanguage("python")
markInitialized()
}
}
initializeApp()
// Event listeners for process events
const onApiKeyInvalid = () => {
showToast(
"API Key Invalid",
"Your OpenAI API key appears to be invalid or has insufficient credits",
"error"
)
setApiKeyDialogOpen(true)
}
// Setup API key invalid listener
window.electronAPI.onApiKeyInvalid(onApiKeyInvalid)
// Define a no-op handler for solution success
const unsubscribeSolutionSuccess = window.electronAPI.onSolutionSuccess(
() => {
console.log("Solution success - no credits deducted in this version")
// No credit deduction in this version
}
)
// Cleanup function
return () => {
window.electronAPI.removeListener("API_KEY_INVALID", onApiKeyInvalid)
unsubscribeSolutionSuccess()
window.__IS_INITIALIZED__ = false
setIsInitialized(false)
}
}, [updateCredits, updateLanguage, markInitialized, showToast])
// API Key dialog management
const handleOpenSettings = useCallback(() => {
console.log('Opening settings dialog');
setIsSettingsOpen(true);
}, []);
const handleCloseSettings = useCallback((open: boolean) => {
console.log('Settings dialog state changed:', open);
setIsSettingsOpen(open);
}, []);
const handleApiKeySave = useCallback(async (apiKey: string) => {
try {
await window.electronAPI.updateConfig({ apiKey })
setHasApiKey(true)
showToast("Success", "API key saved successfully", "success")
// Reload app after a short delay to reinitialize with the new API key
setTimeout(() => {
window.location.reload()
}, 1500)
} catch (error) {
console.error("Failed to save API key:", error)
showToast("Error", "Failed to save API key", "error")
}
}, [showToast])
return (
<QueryClientProvider client={queryClient}>
<ToastProvider>
<ToastContext.Provider value={{ showToast }}>
<div className="relative">
{isInitialized ? (
hasApiKey ? (
<SubscribedApp
credits={credits}
currentLanguage={currentLanguage}
setLanguage={updateLanguage}
/>
) : (
<WelcomeScreen onOpenSettings={handleOpenSettings} />
)
) : (
<div className="min-h-screen bg-black flex items-center justify-center">
<div className="flex flex-col items-center gap-3">
<div className="w-6 h-6 border-2 border-white/20 border-t-white/80 rounded-full animate-spin"></div>
<p className="text-white/60 text-sm">
Initializing...
</p>
</div>
</div>
)}
<UpdateNotification />
</div>
{/* Settings Dialog */}
<SettingsDialog
open={isSettingsOpen}
onOpenChange={handleCloseSettings}
/>
<Toast
open={toastState.open}
onOpenChange={(open) =>
setToastState((prev) => ({ ...prev, open }))
}
variant={toastState.variant}
duration={1500}
>
<ToastTitle>{toastState.title}</ToastTitle>
<ToastDescription>{toastState.description}</ToastDescription>
</Toast>
<ToastViewport />
</ToastContext.Provider>
</ToastProvider>
</QueryClientProvider>
)
}
export default App