-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRateLimitModal.tsx
More file actions
396 lines (365 loc) · 15.7 KB
/
Copy pathRateLimitModal.tsx
File metadata and controls
396 lines (365 loc) · 15.7 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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AlertCircle, ExternalLink, Clock, RefreshCw, User, ChevronDown, Check, Zap, Star, Plus } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from './ui/dialog';
import { Button } from './ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from './ui/dropdown-menu';
import { Switch } from './ui/switch';
import { Label } from './ui/label';
import { Input } from './ui/input';
import { useRateLimitStore } from '../stores/rate-limit-store';
import { useClaudeProfileStore, loadClaudeProfiles, switchTerminalToProfile } from '../stores/claude-profile-store';
import { useToast } from '../hooks/use-toast';
import { debugError } from '../../shared/utils/debug-logger';
const CLAUDE_UPGRADE_URL = 'https://claude.ai/upgrade';
export function RateLimitModal() {
const { t } = useTranslation('common');
const { isModalOpen, rateLimitInfo, hideRateLimitModal, clearPendingRateLimit } = useRateLimitStore();
const { profiles, activeProfileId, isSwitching } = useClaudeProfileStore();
const { toast } = useToast();
const [selectedProfileId, setSelectedProfileId] = useState<string | null>(null);
const [autoSwitchEnabled, setAutoSwitchEnabled] = useState(false);
const [isLoadingSettings, setIsLoadingSettings] = useState(false);
const [isAddingProfile, setIsAddingProfile] = useState(false);
const [newProfileName, setNewProfileName] = useState('');
const loadAutoSwitchSettings = async () => {
try {
const result = await window.electronAPI.getAutoSwitchSettings();
if (result.success && result.data) {
setAutoSwitchEnabled(result.data.autoSwitchOnRateLimit);
}
} catch (err) {
debugError('[RateLimitModal] Failed to load auto-switch settings:', err);
}
};
// Load profiles and auto-switch settings when modal opens
// biome-ignore lint/correctness/useExhaustiveDependencies: loadAutoSwitchSettings is stable and doesn't need to trigger re-render
useEffect(() => {
if (isModalOpen) {
loadClaudeProfiles();
loadAutoSwitchSettings();
// Pre-select the suggested profile if available
if (rateLimitInfo?.suggestedProfileId) {
setSelectedProfileId(rateLimitInfo.suggestedProfileId);
}
}
}, [isModalOpen, rateLimitInfo?.suggestedProfileId]);
// Reset selection when modal closes
useEffect(() => {
if (!isModalOpen) {
setSelectedProfileId(null);
setIsAddingProfile(false);
setNewProfileName('');
}
}, [isModalOpen]);
const handleAutoSwitchToggle = async (enabled: boolean) => {
setIsLoadingSettings(true);
try {
await window.electronAPI.updateAutoSwitchSettings({
enabled: enabled,
autoSwitchOnRateLimit: enabled
});
setAutoSwitchEnabled(enabled);
} catch (err) {
debugError('[RateLimitModal] Failed to update auto-switch settings:', err);
} finally {
setIsLoadingSettings(false);
}
};
const handleUpgrade = () => {
window.open(CLAUDE_UPGRADE_URL, '_blank');
};
const handleAddProfile = async () => {
if (!newProfileName.trim()) return;
setIsAddingProfile(true);
try {
// Create a new profile - the backend will set the proper configDir
const profileName = newProfileName.trim();
const profileSlug = profileName.toLowerCase().replace(/\s+/g, '-');
const result = await window.electronAPI.saveClaudeProfile({
id: `profile-${Date.now()}`,
name: profileName,
// Use a placeholder - the backend will resolve the actual path
configDir: `~/.claude-profiles/${profileSlug}`,
isDefault: false,
createdAt: new Date()
});
if (result.success && result.data) {
// Reload profiles
loadClaudeProfiles();
setNewProfileName('');
// Close the modal
hideRateLimitModal();
// Direct user to Settings to complete authentication
alert(
`${t('profileCreated.title', { profileName })}\n\n` +
`${t('profileCreated.instructions')}\n` +
`1. ${t('profileCreated.step1')}\n` +
`2. ${t('profileCreated.step2')}\n` +
`3. ${t('profileCreated.step3')}\n\n` +
`${t('profileCreated.footer')}`
);
}
} catch (err) {
debugError('[RateLimitModal] Failed to add profile:', err);
toast({
variant: 'destructive',
title: t('rateLimit.toast.addProfileFailed'),
description: t('rateLimit.toast.tryAgain'),
});
} finally {
setIsAddingProfile(false);
}
};
const handleSwitchProfile = async () => {
if (!selectedProfileId || !rateLimitInfo?.terminalId) return;
const success = await switchTerminalToProfile(rateLimitInfo.terminalId, selectedProfileId);
if (success) {
// Clear the pending rate limit since we successfully switched
clearPendingRateLimit();
}
};
// Get profiles that are not the current rate-limited one
const currentProfileId = rateLimitInfo?.profileId || activeProfileId;
const availableProfiles = profiles.filter(p => p.id !== currentProfileId);
const hasMultipleProfiles = profiles.length > 1;
const selectedProfile = selectedProfileId
? profiles.find(p => p.id === selectedProfileId)
: null;
const currentProfile = profiles.find(p => p.id === currentProfileId);
const suggestedProfile = rateLimitInfo?.suggestedProfileId
? profiles.find(p => p.id === rateLimitInfo.suggestedProfileId)
: null;
// Check if auto-switch already happened
const autoSwitchHappened = rateLimitInfo?.autoSwitchEnabled && suggestedProfile;
return (
<Dialog open={isModalOpen} onOpenChange={(open) => !open && hideRateLimitModal()}>
<DialogContent className="sm:max-w-[520px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-warning">
<AlertCircle className="h-5 w-5" />
{t('rateLimit.modalTitle')}
</DialogTitle>
<DialogDescription>
{t('rateLimit.modalDescription')}
{currentProfile && !currentProfile.isDefault && (
<span className="text-muted-foreground"> ({t('rateLimit.profile', { name: currentProfile.name })})</span>
)}
</DialogDescription>
</DialogHeader>
<div className="py-4 space-y-4">
{/* Auto-switch notification */}
{autoSwitchHappened && (
<div className="flex items-center gap-3 rounded-lg border border-green-500/30 bg-green-500/10 p-4">
<Zap className="h-5 w-5 text-green-500 shrink-0" />
<div>
<p className="text-sm font-medium text-foreground">
{t('rateLimit.autoSwitching', { name: suggestedProfile?.name })}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t('rateLimit.autoSwitchingDescription')}
</p>
</div>
</div>
)}
{/* Reset time info */}
{rateLimitInfo?.resetTime && !autoSwitchHappened && (
<div className="flex items-center gap-3 rounded-lg border border-border bg-muted/50 p-4">
<Clock className="h-5 w-5 text-muted-foreground shrink-0" />
<div>
<p className="text-sm font-medium text-foreground">
{t('rateLimit.resetsTime', { time: rateLimitInfo.resetTime })}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t('rateLimit.usageRestored')}
</p>
</div>
</div>
)}
{/* Profile switching / Add account section - show unless auto-switch happened */}
{!autoSwitchHappened && (
<div className="rounded-lg border border-accent/50 bg-accent/10 p-4">
<h4 className="text-sm font-medium text-foreground mb-2 flex items-center gap-2">
<User className="h-4 w-4" />
{hasMultipleProfiles ? t('rateLimit.switchAccount') : t('rateLimit.useAnotherAccount')}
</h4>
{hasMultipleProfiles ? (
<>
<p className="text-sm text-muted-foreground mb-3">
{suggestedProfile ? (
t('rateLimit.recommended', { name: suggestedProfile.name })
) : (
t('rateLimit.otherSubscriptions')
)}
</p>
<div className="flex items-center gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="flex-1 justify-between">
<span className="truncate flex items-center gap-2">
{selectedProfile?.name || t('rateLimit.selectAccount')}
{selectedProfileId === rateLimitInfo?.suggestedProfileId && (
<Star className="h-3 w-3 text-yellow-500" />
)}
</span>
<ChevronDown className="h-4 w-4 shrink-0 ml-2" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-[220px] bg-popover border border-border shadow-lg">
{availableProfiles.map((profile) => (
<DropdownMenuItem
key={profile.id}
onClick={() => setSelectedProfileId(profile.id)}
className="flex items-center justify-between"
>
<span className="truncate flex items-center gap-2">
{profile.name}
{profile.id === rateLimitInfo?.suggestedProfileId && (
<Star className="h-3 w-3 text-yellow-500" aria-label="Recommended" />
)}
</span>
{selectedProfileId === profile.id && (
<Check className="h-4 w-4 shrink-0" />
)}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => {
// Focus the add account input
const input = document.querySelector('input[placeholder*="Account name"]') as HTMLInputElement;
if (input) input.focus();
}}
className="flex items-center gap-2 text-muted-foreground"
>
<Plus className="h-4 w-4" />
{t('rateLimit.addNewAccount')}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="default"
size="sm"
onClick={handleSwitchProfile}
disabled={!selectedProfileId || isSwitching}
className="gap-2 shrink-0"
>
{isSwitching ? (
<>
<RefreshCw className="h-4 w-4 animate-spin" />
{t('rateLimit.switching')}
</>
) : (
<>
<RefreshCw className="h-4 w-4" />
{t('buttons.switch')}
</>
)}
</Button>
</div>
{selectedProfile?.description && (
<p className="text-xs text-muted-foreground mt-2">
{selectedProfile.description}
</p>
)}
{/* Auto-switch toggle */}
{availableProfiles.length > 0 && (
<div className="flex items-center justify-between mt-4 pt-3 border-t border-border/50">
<Label htmlFor="auto-switch" className="text-xs text-muted-foreground cursor-pointer">
{t('rateLimit.autoSwitchOnRateLimit')}
</Label>
<Switch
id="auto-switch"
checked={autoSwitchEnabled}
onCheckedChange={handleAutoSwitchToggle}
disabled={isLoadingSettings}
/>
</div>
)}
</>
) : (
<p className="text-sm text-muted-foreground mb-3">
{t('rateLimit.addAnotherSubscription')}
</p>
)}
{/* Add new account section */}
<div className={hasMultipleProfiles ? "mt-4 pt-3 border-t border-border/50" : ""}>
<p className="text-xs text-muted-foreground mb-2">
{hasMultipleProfiles ? t('rateLimit.addAnotherAccount') : t('rateLimit.connectAccount')}
</p>
<div className="flex items-center gap-2">
<Input
placeholder={t('rateLimit.accountNamePlaceholder')}
value={newProfileName}
onChange={(e) => setNewProfileName(e.target.value)}
className="flex-1 h-8 text-sm"
onKeyDown={(e) => {
if (e.key === 'Enter' && newProfileName.trim()) {
handleAddProfile();
}
}}
/>
<Button
variant="outline"
size="sm"
onClick={handleAddProfile}
disabled={!newProfileName.trim() || isAddingProfile}
className="gap-1 shrink-0"
>
{isAddingProfile ? (
<RefreshCw className="h-3 w-3 animate-spin" />
) : (
<Plus className="h-3 w-3" />
)}
{t('buttons.add')}
</Button>
</div>
<p className="text-xs text-muted-foreground mt-2">
{t('rateLimit.willOpenLogin')}
</p>
</div>
</div>
)}
{/* Upgrade prompt */}
<div className="rounded-lg border border-primary/30 bg-primary/5 p-4">
<h4 className="text-sm font-medium text-foreground mb-2">
{t('rateLimit.upgradeTitle')}
</h4>
<p className="text-sm text-muted-foreground mb-3">
{t('rateLimit.upgradeDescription')}
</p>
<Button
variant="outline"
size="sm"
className="gap-2"
onClick={handleUpgrade}
aria-label={t('accessibility.upgradeSubscriptionAriaLabel')}
>
<ExternalLink className="h-4 w-4" aria-hidden="true" />
{t('rateLimit.upgradeSubscription')}
<span className="sr-only">({t('accessibility.opensInNewWindow')})</span>
</Button>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={hideRateLimitModal}>
{autoSwitchHappened ? t('buttons.continue') : hasMultipleProfiles ? t('buttons.close') : t('buttons.gotIt')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}