This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathCodeIndexPopover.tsx
More file actions
1763 lines (1651 loc) · 63.7 KB
/
Copy pathCodeIndexPopover.tsx
File metadata and controls
1763 lines (1651 loc) · 63.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useMemo, useCallback, useRef } from "react"
import { Trans } from "react-i18next"
import { z } from "zod"
import {
VSCodeButton,
VSCodeTextField,
VSCodeDropdown,
VSCodeOption,
VSCodeLink,
VSCodeCheckbox,
} from "@vscode/webview-ui-toolkit/react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { AlertTriangle } from "lucide-react"
import { type IndexingStatus, type EmbedderProvider, CODEBASE_INDEX_DEFAULTS } from "@roo-code/types"
import { vscode } from "@src/utils/vscode"
import { useExtensionState } from "@src/context/ExtensionStateContext"
import { useAppTranslation } from "@src/i18n/TranslationContext"
import { buildDocLink } from "@src/utils/docLinks"
import { cn } from "@src/lib/utils"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
Popover,
PopoverContent,
Slider,
StandardTooltip,
Button,
} from "@src/components/ui"
import { useRooPortal } from "@src/components/ui/hooks/useRooPortal"
import { useEscapeKey } from "@src/hooks/useEscapeKey"
import {
useOpenRouterModelProviders,
OPENROUTER_DEFAULT_PROVIDER_NAME,
} from "@src/components/ui/hooks/useOpenRouterModelProviders"
// Default URLs for providers
const DEFAULT_QDRANT_URL = "http://localhost:6333"
const DEFAULT_OLLAMA_URL = "http://localhost:11434"
interface CodeIndexPopoverProps {
children: React.ReactNode
indexingStatus: IndexingStatus
}
interface LocalCodeIndexSettings {
// Global state settings
codebaseIndexEnabled: boolean
codebaseIndexQdrantUrl: string
codebaseIndexEmbedderProvider: EmbedderProvider
codebaseIndexEmbedderBaseUrl?: string
codebaseIndexEmbedderModelId: string
codebaseIndexEmbedderModelDimension?: number // Generic dimension for all providers
codebaseIndexSearchMaxResults?: number
codebaseIndexSearchMinScore?: number
// Bedrock-specific settings
codebaseIndexBedrockRegion?: string
codebaseIndexBedrockProfile?: string
// Secret settings (start empty, will be loaded separately)
codeIndexOpenAiKey?: string
codeIndexQdrantApiKey?: string
codebaseIndexOpenAiCompatibleBaseUrl?: string
codebaseIndexOpenAiCompatibleApiKey?: string
codebaseIndexGeminiApiKey?: string
codebaseIndexMistralApiKey?: string
codebaseIndexVercelAiGatewayApiKey?: string
codebaseIndexOpenRouterApiKey?: string
codebaseIndexOpenRouterSpecificProvider?: string
}
// Validation schema for codebase index settings
const createValidationSchema = (provider: EmbedderProvider, t: any) => {
const baseSchema = z.object({
codebaseIndexEnabled: z.boolean(),
codebaseIndexQdrantUrl: z
.string()
.min(1, t("settings:codeIndex.validation.qdrantUrlRequired"))
.url(t("settings:codeIndex.validation.invalidQdrantUrl")),
codeIndexQdrantApiKey: z.string().optional(),
})
switch (provider) {
case "openai":
return baseSchema.extend({
codeIndexOpenAiKey: z.string().min(1, t("settings:codeIndex.validation.openaiApiKeyRequired")),
codebaseIndexEmbedderModelId: z
.string()
.min(1, t("settings:codeIndex.validation.modelSelectionRequired")),
})
case "ollama":
return baseSchema.extend({
codebaseIndexEmbedderBaseUrl: z
.string()
.min(1, t("settings:codeIndex.validation.ollamaBaseUrlRequired"))
.url(t("settings:codeIndex.validation.invalidOllamaUrl")),
codebaseIndexEmbedderModelId: z.string().min(1, t("settings:codeIndex.validation.modelIdRequired")),
codebaseIndexEmbedderModelDimension: z
.number()
.min(1, t("settings:codeIndex.validation.modelDimensionRequired"))
.optional(),
})
case "openai-compatible":
return baseSchema.extend({
codebaseIndexOpenAiCompatibleBaseUrl: z
.string()
.min(1, t("settings:codeIndex.validation.baseUrlRequired"))
.url(t("settings:codeIndex.validation.invalidBaseUrl")),
codebaseIndexOpenAiCompatibleApiKey: z
.string()
.min(1, t("settings:codeIndex.validation.apiKeyRequired")),
codebaseIndexEmbedderModelId: z.string().min(1, t("settings:codeIndex.validation.modelIdRequired")),
codebaseIndexEmbedderModelDimension: z
.number()
.min(1, t("settings:codeIndex.validation.modelDimensionRequired")),
})
case "gemini":
return baseSchema.extend({
codebaseIndexGeminiApiKey: z.string().min(1, t("settings:codeIndex.validation.geminiApiKeyRequired")),
codebaseIndexEmbedderModelId: z
.string()
.min(1, t("settings:codeIndex.validation.modelSelectionRequired")),
})
case "mistral":
return baseSchema.extend({
codebaseIndexMistralApiKey: z.string().min(1, t("settings:codeIndex.validation.mistralApiKeyRequired")),
codebaseIndexEmbedderModelId: z
.string()
.min(1, t("settings:codeIndex.validation.modelSelectionRequired")),
})
case "vercel-ai-gateway":
return baseSchema.extend({
codebaseIndexVercelAiGatewayApiKey: z
.string()
.min(1, t("settings:codeIndex.validation.vercelAiGatewayApiKeyRequired")),
codebaseIndexEmbedderModelId: z
.string()
.min(1, t("settings:codeIndex.validation.modelSelectionRequired")),
})
case "bedrock":
return baseSchema.extend({
codebaseIndexBedrockRegion: z.string().min(1, t("settings:codeIndex.validation.bedrockRegionRequired")),
codebaseIndexBedrockProfile: z.string().optional(),
codebaseIndexEmbedderModelId: z
.string()
.min(1, t("settings:codeIndex.validation.modelSelectionRequired")),
})
case "openrouter":
return baseSchema.extend({
codebaseIndexOpenRouterApiKey: z
.string()
.min(1, t("settings:codeIndex.validation.openRouterApiKeyRequired")),
codebaseIndexEmbedderModelId: z
.string()
.min(1, t("settings:codeIndex.validation.modelSelectionRequired")),
})
default:
return baseSchema
}
}
export const CodeIndexPopover: React.FC<CodeIndexPopoverProps> = ({
children,
indexingStatus: externalIndexingStatus,
}) => {
const SECRET_PLACEHOLDER = "••••••••••••••••"
const { t } = useAppTranslation()
const { codebaseIndexConfig, codebaseIndexModels, cwd, apiConfiguration } = useExtensionState()
const [open, setOpen] = useState(false)
const [isAdvancedSettingsOpen, setIsAdvancedSettingsOpen] = useState(false)
const [isSetupSettingsOpen, setIsSetupSettingsOpen] = useState(false)
const [indexingStatus, setIndexingStatus] = useState<IndexingStatus>(externalIndexingStatus)
const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "saved" | "error">("idle")
const [saveError, setSaveError] = useState<string | null>(null)
// Form validation state
const [formErrors, setFormErrors] = useState<Record<string, string>>({})
// Discard changes dialog state
const [isDiscardDialogShow, setDiscardDialogShow] = useState(false)
const confirmDialogHandler = useRef<(() => void) | null>(null)
// Default settings template
const getDefaultSettings = (): LocalCodeIndexSettings => ({
codebaseIndexEnabled: true,
codebaseIndexQdrantUrl: "",
codebaseIndexEmbedderProvider: "openai",
codebaseIndexEmbedderBaseUrl: "",
codebaseIndexEmbedderModelId: "",
codebaseIndexEmbedderModelDimension: undefined,
codebaseIndexSearchMaxResults: CODEBASE_INDEX_DEFAULTS.DEFAULT_SEARCH_RESULTS,
codebaseIndexSearchMinScore: CODEBASE_INDEX_DEFAULTS.DEFAULT_SEARCH_MIN_SCORE,
codebaseIndexBedrockRegion: "",
codebaseIndexBedrockProfile: "",
codeIndexOpenAiKey: "",
codeIndexQdrantApiKey: "",
codebaseIndexOpenAiCompatibleBaseUrl: "",
codebaseIndexOpenAiCompatibleApiKey: "",
codebaseIndexGeminiApiKey: "",
codebaseIndexMistralApiKey: "",
codebaseIndexVercelAiGatewayApiKey: "",
codebaseIndexOpenRouterApiKey: "",
codebaseIndexOpenRouterSpecificProvider: "",
})
// Initial settings state - stores the settings when popover opens
const [initialSettings, setInitialSettings] = useState<LocalCodeIndexSettings>(getDefaultSettings())
// Current settings state - tracks user changes
const [currentSettings, setCurrentSettings] = useState<LocalCodeIndexSettings>(getDefaultSettings())
// Update indexing status from parent
useEffect(() => {
setIndexingStatus(externalIndexingStatus)
}, [externalIndexingStatus])
// Initialize settings from global state
useEffect(() => {
if (codebaseIndexConfig) {
const settings = {
codebaseIndexEnabled: codebaseIndexConfig.codebaseIndexEnabled ?? true,
codebaseIndexQdrantUrl: codebaseIndexConfig.codebaseIndexQdrantUrl || "",
codebaseIndexEmbedderProvider: codebaseIndexConfig.codebaseIndexEmbedderProvider || "openai",
codebaseIndexEmbedderBaseUrl: codebaseIndexConfig.codebaseIndexEmbedderBaseUrl || "",
codebaseIndexEmbedderModelId: codebaseIndexConfig.codebaseIndexEmbedderModelId || "",
codebaseIndexEmbedderModelDimension:
codebaseIndexConfig.codebaseIndexEmbedderModelDimension || undefined,
codebaseIndexSearchMaxResults:
codebaseIndexConfig.codebaseIndexSearchMaxResults ?? CODEBASE_INDEX_DEFAULTS.DEFAULT_SEARCH_RESULTS,
codebaseIndexSearchMinScore:
codebaseIndexConfig.codebaseIndexSearchMinScore ?? CODEBASE_INDEX_DEFAULTS.DEFAULT_SEARCH_MIN_SCORE,
codebaseIndexBedrockRegion: codebaseIndexConfig.codebaseIndexBedrockRegion || "",
codebaseIndexBedrockProfile: codebaseIndexConfig.codebaseIndexBedrockProfile || "",
codeIndexOpenAiKey: "",
codeIndexQdrantApiKey: "",
codebaseIndexOpenAiCompatibleBaseUrl: codebaseIndexConfig.codebaseIndexOpenAiCompatibleBaseUrl || "",
codebaseIndexOpenAiCompatibleApiKey: "",
codebaseIndexGeminiApiKey: "",
codebaseIndexMistralApiKey: "",
codebaseIndexVercelAiGatewayApiKey: "",
codebaseIndexOpenRouterApiKey: "",
codebaseIndexOpenRouterSpecificProvider:
codebaseIndexConfig.codebaseIndexOpenRouterSpecificProvider || "",
}
setInitialSettings(settings)
setCurrentSettings(settings)
// Request secret status to check if secrets exist
vscode.postMessage({ type: "requestCodeIndexSecretStatus" })
}
}, [codebaseIndexConfig])
// Request initial indexing status
useEffect(() => {
if (open) {
vscode.postMessage({ type: "requestIndexingStatus" })
vscode.postMessage({ type: "requestCodeIndexSecretStatus" })
}
const handleMessage = (event: MessageEvent) => {
if (event.data.type === "workspaceUpdated") {
// When workspace changes, request updated indexing status
if (open) {
vscode.postMessage({ type: "requestIndexingStatus" })
vscode.postMessage({ type: "requestCodeIndexSecretStatus" })
}
}
}
window.addEventListener("message", handleMessage)
return () => window.removeEventListener("message", handleMessage)
}, [open])
// Use a ref to capture current settings for the save handler
const currentSettingsRef = useRef(currentSettings)
currentSettingsRef.current = currentSettings
// Listen for indexing status updates and save responses
useEffect(() => {
const handleMessage = (event: MessageEvent<any>) => {
if (event.data.type === "indexingStatusUpdate") {
if (!event.data.values.workspacePath || event.data.values.workspacePath === cwd) {
setIndexingStatus({
systemStatus: event.data.values.systemStatus,
message: event.data.values.message || "",
processedItems: event.data.values.processedItems,
totalItems: event.data.values.totalItems,
currentItemUnit: event.data.values.currentItemUnit || "items",
})
}
} else if (event.data.type === "codeIndexSettingsSaved") {
if (event.data.success) {
setSaveStatus("saved")
// Update initial settings to match current settings after successful save
// This ensures hasUnsavedChanges becomes false
const savedSettings = { ...currentSettingsRef.current }
setInitialSettings(savedSettings)
// Also update current settings to maintain consistency
setCurrentSettings(savedSettings)
// Request secret status to ensure we have the latest state
// This is important to maintain placeholder display after save
vscode.postMessage({ type: "requestCodeIndexSecretStatus" })
setSaveStatus("idle")
} else {
setSaveStatus("error")
setSaveError(event.data.error || t("settings:codeIndex.saveError"))
// Clear error message after 5 seconds
setSaveStatus("idle")
setSaveError(null)
}
}
}
window.addEventListener("message", handleMessage)
return () => window.removeEventListener("message", handleMessage)
}, [t, cwd])
// Listen for secret status
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
if (event.data.type === "codeIndexSecretStatus") {
// Update settings to show placeholders for existing secrets
const secretStatus = event.data.values
// Update both current and initial settings based on what secrets exist
const updateWithSecrets = (prev: LocalCodeIndexSettings): LocalCodeIndexSettings => {
const updated = { ...prev }
// Only update to placeholder if the field is currently empty or already a placeholder
// This preserves user input when they're actively editing
if (!prev.codeIndexOpenAiKey || prev.codeIndexOpenAiKey === SECRET_PLACEHOLDER) {
updated.codeIndexOpenAiKey = secretStatus.hasOpenAiKey ? SECRET_PLACEHOLDER : ""
}
if (!prev.codeIndexQdrantApiKey || prev.codeIndexQdrantApiKey === SECRET_PLACEHOLDER) {
updated.codeIndexQdrantApiKey = secretStatus.hasQdrantApiKey ? SECRET_PLACEHOLDER : ""
}
if (
!prev.codebaseIndexOpenAiCompatibleApiKey ||
prev.codebaseIndexOpenAiCompatibleApiKey === SECRET_PLACEHOLDER
) {
updated.codebaseIndexOpenAiCompatibleApiKey = secretStatus.hasOpenAiCompatibleApiKey
? SECRET_PLACEHOLDER
: ""
}
if (!prev.codebaseIndexGeminiApiKey || prev.codebaseIndexGeminiApiKey === SECRET_PLACEHOLDER) {
updated.codebaseIndexGeminiApiKey = secretStatus.hasGeminiApiKey ? SECRET_PLACEHOLDER : ""
}
if (!prev.codebaseIndexMistralApiKey || prev.codebaseIndexMistralApiKey === SECRET_PLACEHOLDER) {
updated.codebaseIndexMistralApiKey = secretStatus.hasMistralApiKey ? SECRET_PLACEHOLDER : ""
}
if (
!prev.codebaseIndexVercelAiGatewayApiKey ||
prev.codebaseIndexVercelAiGatewayApiKey === SECRET_PLACEHOLDER
) {
updated.codebaseIndexVercelAiGatewayApiKey = secretStatus.hasVercelAiGatewayApiKey
? SECRET_PLACEHOLDER
: ""
}
if (
!prev.codebaseIndexOpenRouterApiKey ||
prev.codebaseIndexOpenRouterApiKey === SECRET_PLACEHOLDER
) {
updated.codebaseIndexOpenRouterApiKey = secretStatus.hasOpenRouterApiKey
? SECRET_PLACEHOLDER
: ""
}
return updated
}
// Only update settings if we're not in the middle of saving
// After save is complete (saved status), we still want to update to maintain consistency
if (saveStatus === "idle" || saveStatus === "saved") {
setCurrentSettings(updateWithSecrets)
setInitialSettings(updateWithSecrets)
}
}
}
window.addEventListener("message", handleMessage)
return () => window.removeEventListener("message", handleMessage)
}, [saveStatus])
// Generic comparison function that detects changes between initial and current settings
const hasUnsavedChanges = useMemo(() => {
// Get all keys from both objects to handle any field
const allKeys = [...Object.keys(initialSettings), ...Object.keys(currentSettings)] as Array<
keyof LocalCodeIndexSettings
>
// Use a Set to ensure unique keys
const uniqueKeys = Array.from(new Set(allKeys))
for (const key of uniqueKeys) {
const currentValue = currentSettings[key]
const initialValue = initialSettings[key]
// For secret fields, check if the value has been modified from placeholder
if (currentValue === SECRET_PLACEHOLDER) {
// If it's still showing placeholder, no change
continue
}
// Compare values - handles all types including undefined
if (currentValue !== initialValue) {
return true
}
}
return false
}, [currentSettings, initialSettings])
const updateSetting = (key: keyof LocalCodeIndexSettings, value: any) => {
setCurrentSettings((prev) => ({ ...prev, [key]: value }))
// Clear validation error for this field when user starts typing
if (formErrors[key]) {
setFormErrors((prev) => {
const newErrors = { ...prev }
delete newErrors[key]
return newErrors
})
}
}
// Validation function
const validateSettings = (): boolean => {
const schema = createValidationSchema(currentSettings.codebaseIndexEmbedderProvider, t)
// Prepare data for validation
const dataToValidate: any = {}
for (const [key, value] of Object.entries(currentSettings)) {
// For secret fields with placeholder values, treat them as valid (they exist in backend)
if (value === SECRET_PLACEHOLDER) {
// Add a dummy value that will pass validation for these fields
if (
key === "codeIndexOpenAiKey" ||
key === "codebaseIndexOpenAiCompatibleApiKey" ||
key === "codebaseIndexGeminiApiKey" ||
key === "codebaseIndexMistralApiKey" ||
key === "codebaseIndexVercelAiGatewayApiKey" ||
key === "codebaseIndexOpenRouterApiKey"
) {
dataToValidate[key] = "placeholder-valid"
}
} else {
dataToValidate[key] = value
}
}
try {
// Validate using the schema
schema.parse(dataToValidate)
setFormErrors({})
return true
} catch (error) {
if (error instanceof z.ZodError) {
const errors: Record<string, string> = {}
error.errors.forEach((err) => {
if (err.path[0]) {
errors[err.path[0] as string] = err.message
}
})
setFormErrors(errors)
}
return false
}
}
// Discard changes functionality
const checkUnsavedChanges = useCallback(
(then: () => void) => {
if (hasUnsavedChanges) {
confirmDialogHandler.current = then
setDiscardDialogShow(true)
} else {
then()
}
},
[hasUnsavedChanges],
)
const onConfirmDialogResult = useCallback(
(confirm: boolean) => {
if (confirm) {
// Discard changes: Reset to initial settings
setCurrentSettings(initialSettings)
setFormErrors({}) // Clear any validation errors
confirmDialogHandler.current?.() // Execute the pending action (e.g., close popover)
}
setDiscardDialogShow(false)
},
[initialSettings],
)
// Handle popover close with unsaved changes check
const handlePopoverClose = useCallback(() => {
checkUnsavedChanges(() => {
setOpen(false)
})
}, [checkUnsavedChanges])
// Use the shared ESC key handler hook - respects unsaved changes logic
useEscapeKey(open, handlePopoverClose)
const handleSaveSettings = () => {
// Validate settings before saving
if (!validateSettings()) {
return
}
setSaveStatus("saving")
setSaveError(null)
// Prepare settings to save
const settingsToSave: any = {}
// Keys whose string values should be trimmed before saving
const trimKeys = new Set([
"codebaseIndexQdrantUrl",
"codebaseIndexEmbedderBaseUrl",
"codebaseIndexOpenAiCompatibleBaseUrl",
"codebaseIndexEmbedderModelId",
"codebaseIndexQdrantApiKey",
])
// Iterate through all current settings
for (const [key, value] of Object.entries(currentSettings)) {
// For secret fields with placeholder, don't send the placeholder
// but also don't send an empty string - just skip the field
// This tells the backend to keep the existing secret
if (value === SECRET_PLACEHOLDER) {
// Skip sending placeholder values - backend will preserve existing secrets
continue
}
// Trim whitespace from URL and identifier fields to prevent silent failures
if (trimKeys.has(key) && typeof value === "string") {
settingsToSave[key] = value.trim()
} else {
// Include all other fields, including empty strings (which clear secrets)
settingsToSave[key] = value
}
}
// Always include codebaseIndexEnabled to ensure it's persisted
settingsToSave.codebaseIndexEnabled = currentSettings.codebaseIndexEnabled
// Save settings to backend
vscode.postMessage({
type: "saveCodeIndexSettingsAtomic",
codeIndexSettings: settingsToSave,
})
}
const progressPercentage = useMemo(
() =>
indexingStatus.totalItems > 0
? Math.round((indexingStatus.processedItems / indexingStatus.totalItems) * 100)
: 0,
[indexingStatus.processedItems, indexingStatus.totalItems],
)
const transformStyleString = `translateX(-${100 - progressPercentage}%)`
const getAvailableModels = () => {
if (!codebaseIndexModels) return []
const models =
codebaseIndexModels[currentSettings.codebaseIndexEmbedderProvider as keyof typeof codebaseIndexModels]
return models ? Object.keys(models) : []
}
// Fetch OpenRouter model providers for embedding model
const { data: openRouterEmbeddingProviders } = useOpenRouterModelProviders(
currentSettings.codebaseIndexEmbedderProvider === "openrouter"
? currentSettings.codebaseIndexEmbedderModelId
: undefined,
undefined,
{
enabled:
currentSettings.codebaseIndexEmbedderProvider === "openrouter" &&
!!currentSettings.codebaseIndexEmbedderModelId,
},
)
const portalContainer = useRooPortal("roo-portal")
return (
<>
<Popover
open={open}
onOpenChange={(newOpen) => {
if (!newOpen) {
// User is trying to close the popover
handlePopoverClose()
} else {
setOpen(newOpen)
}
}}>
{children}
<PopoverContent
className="w-[calc(100vw-32px)] max-w-[450px] max-h-[80vh] overflow-y-auto p-0"
align="end"
alignOffset={0}
side="bottom"
sideOffset={5}
collisionPadding={16}
avoidCollisions={true}
container={portalContainer}>
<div className="p-3 border-b border-vscode-dropdown-border cursor-default">
<div className="flex flex-row items-center gap-1 p-0 mt-0 mb-1 w-full">
<h4 className="m-0 pb-2 flex-1">{t("settings:codeIndex.title")}</h4>
</div>
<p className="my-0 pr-4 text-sm w-full">
<Trans i18nKey="settings:codeIndex.description">
<VSCodeLink
href={buildDocLink("features/experimental/codebase-indexing", "settings")}
style={{ display: "inline" }}
/>
</Trans>
</p>
</div>
<div className="p-4">
{/* Enable/Disable Toggle */}
<div className="mb-4">
<div className="flex items-center gap-2">
<VSCodeCheckbox
checked={currentSettings.codebaseIndexEnabled}
onChange={(e: any) => updateSetting("codebaseIndexEnabled", e.target.checked)}>
<span className="font-medium">{t("settings:codeIndex.enableLabel")}</span>
</VSCodeCheckbox>
<StandardTooltip content={t("settings:codeIndex.enableDescription")}>
<span className="codicon codicon-info text-xs text-vscode-descriptionForeground cursor-help" />
</StandardTooltip>
</div>
</div>
{/* Status Section */}
<div className="space-y-2">
<h4 className="text-sm font-medium">{t("settings:codeIndex.statusTitle")}</h4>
<div className="text-sm text-vscode-descriptionForeground">
<span
className={cn("inline-block w-3 h-3 rounded-full mr-2", {
"bg-gray-400": indexingStatus.systemStatus === "Standby",
"bg-yellow-500 animate-pulse": indexingStatus.systemStatus === "Indexing",
"bg-green-500": indexingStatus.systemStatus === "Indexed",
"bg-red-500": indexingStatus.systemStatus === "Error",
})}
/>
{t(`settings:codeIndex.indexingStatuses.${indexingStatus.systemStatus.toLowerCase()}`)}
{indexingStatus.message ? ` - ${indexingStatus.message}` : ""}
</div>
{indexingStatus.systemStatus === "Indexing" && (
<div className="mt-2">
<ProgressPrimitive.Root
className="relative h-2 w-full overflow-hidden rounded-full bg-secondary"
value={progressPercentage}>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-transform duration-300 ease-in-out"
style={{
transform: transformStyleString,
}}
/>
</ProgressPrimitive.Root>
</div>
)}
</div>
{/* Setup Settings Disclosure */}
<div className="mt-4">
<button
onClick={() => setIsSetupSettingsOpen(!isSetupSettingsOpen)}
className="flex items-center text-xs text-vscode-foreground hover:text-vscode-textLink-foreground focus:outline-none"
aria-expanded={isSetupSettingsOpen}>
<span
className={`codicon codicon-${isSetupSettingsOpen ? "chevron-down" : "chevron-right"} mr-1`}></span>
<span className="text-base font-semibold">
{t("settings:codeIndex.setupConfigLabel")}
</span>
</button>
{isSetupSettingsOpen && (
<div className="mt-4 space-y-4">
{/* Embedder Provider Section */}
<div className="space-y-2">
<label className="text-sm font-medium">
{t("settings:codeIndex.embedderProviderLabel")}
</label>
<Select
value={currentSettings.codebaseIndexEmbedderProvider}
onValueChange={(value: EmbedderProvider) => {
updateSetting("codebaseIndexEmbedderProvider", value)
// Clear model selection when switching providers
updateSetting("codebaseIndexEmbedderModelId", "")
// Auto-populate Region and Profile when switching to Bedrock
// if the main API provider is also configured for Bedrock
if (
value === "bedrock" &&
apiConfiguration?.apiProvider === "bedrock"
) {
// Only populate if currently empty
if (
!currentSettings.codebaseIndexBedrockRegion &&
apiConfiguration.awsRegion
) {
updateSetting(
"codebaseIndexBedrockRegion",
apiConfiguration.awsRegion,
)
}
if (
!currentSettings.codebaseIndexBedrockProfile &&
apiConfiguration.awsProfile
) {
updateSetting(
"codebaseIndexBedrockProfile",
apiConfiguration.awsProfile,
)
}
}
}}>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="openai">
{t("settings:codeIndex.openaiProvider")}
</SelectItem>
<SelectItem value="ollama">
{t("settings:codeIndex.ollamaProvider")}
</SelectItem>
<SelectItem value="openai-compatible">
{t("settings:codeIndex.openaiCompatibleProvider")}
</SelectItem>
<SelectItem value="gemini">
{t("settings:codeIndex.geminiProvider")}
</SelectItem>
<SelectItem value="mistral">
{t("settings:codeIndex.mistralProvider")}
</SelectItem>
<SelectItem value="vercel-ai-gateway">
{t("settings:codeIndex.vercelAiGatewayProvider")}
</SelectItem>
<SelectItem value="bedrock">
{t("settings:codeIndex.bedrockProvider")}
</SelectItem>
<SelectItem value="openrouter">
{t("settings:codeIndex.openRouterProvider")}
</SelectItem>
</SelectContent>
</Select>
</div>
{/* Provider-specific settings */}
{currentSettings.codebaseIndexEmbedderProvider === "openai" && (
<>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("settings:codeIndex.openAiKeyLabel")}
</label>
<VSCodeTextField
type="password"
value={currentSettings.codeIndexOpenAiKey || ""}
onInput={(e: any) =>
updateSetting("codeIndexOpenAiKey", e.target.value)
}
placeholder={t("settings:codeIndex.openAiKeyPlaceholder")}
className={cn("w-full", {
"border-red-500": formErrors.codeIndexOpenAiKey,
})}
/>
{formErrors.codeIndexOpenAiKey && (
<p className="text-xs text-vscode-errorForeground mt-1 mb-0">
{formErrors.codeIndexOpenAiKey}
</p>
)}
</div>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("settings:codeIndex.modelLabel")}
</label>
<VSCodeDropdown
value={currentSettings.codebaseIndexEmbedderModelId}
onChange={(e: any) =>
updateSetting("codebaseIndexEmbedderModelId", e.target.value)
}
className={cn("w-full", {
"border-red-500": formErrors.codebaseIndexEmbedderModelId,
})}>
<VSCodeOption value="" className="p-2">
{t("settings:codeIndex.selectModel")}
</VSCodeOption>
{getAvailableModels().map((modelId) => {
const model =
codebaseIndexModels?.[
currentSettings.codebaseIndexEmbedderProvider as keyof typeof codebaseIndexModels
]?.[modelId]
return (
<VSCodeOption key={modelId} value={modelId} className="p-2">
{modelId}{" "}
{model
? t("settings:codeIndex.modelDimensions", {
dimension: model.dimension,
})
: ""}
</VSCodeOption>
)
})}
</VSCodeDropdown>
{formErrors.codebaseIndexEmbedderModelId && (
<p className="text-xs text-vscode-errorForeground mt-1 mb-0">
{formErrors.codebaseIndexEmbedderModelId}
</p>
)}
</div>
</>
)}
{currentSettings.codebaseIndexEmbedderProvider === "ollama" && (
<>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("settings:codeIndex.ollamaBaseUrlLabel")}
</label>
<VSCodeTextField
value={currentSettings.codebaseIndexEmbedderBaseUrl || ""}
onInput={(e: any) =>
updateSetting("codebaseIndexEmbedderBaseUrl", e.target.value)
}
onBlur={(e: any) => {
// Set default Ollama URL if field is empty
if (!e.target.value.trim()) {
e.target.value = DEFAULT_OLLAMA_URL
updateSetting(
"codebaseIndexEmbedderBaseUrl",
DEFAULT_OLLAMA_URL,
)
}
}}
placeholder={t("settings:codeIndex.ollamaUrlPlaceholder")}
className={cn("w-full", {
"border-red-500": formErrors.codebaseIndexEmbedderBaseUrl,
})}
/>
{formErrors.codebaseIndexEmbedderBaseUrl && (
<p className="text-xs text-vscode-errorForeground mt-1 mb-0">
{formErrors.codebaseIndexEmbedderBaseUrl}
</p>
)}
</div>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("settings:codeIndex.modelLabel")}
</label>
<VSCodeTextField
value={currentSettings.codebaseIndexEmbedderModelId || ""}
onInput={(e: any) =>
updateSetting("codebaseIndexEmbedderModelId", e.target.value)
}
placeholder={t("settings:codeIndex.modelPlaceholder")}
className={cn("w-full", {
"border-red-500": formErrors.codebaseIndexEmbedderModelId,
})}
/>
{formErrors.codebaseIndexEmbedderModelId && (
<p className="text-xs text-vscode-errorForeground mt-1 mb-0">
{formErrors.codebaseIndexEmbedderModelId}
</p>
)}
</div>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("settings:codeIndex.modelDimensionLabel")}
</label>
<VSCodeTextField
value={
currentSettings.codebaseIndexEmbedderModelDimension?.toString() ||
""
}
onInput={(e: any) => {
const value = e.target.value
? parseInt(e.target.value, 10) || undefined
: undefined
updateSetting("codebaseIndexEmbedderModelDimension", value)
}}
placeholder={t("settings:codeIndex.modelDimensionPlaceholder")}
className={cn("w-full", {
"border-red-500":
formErrors.codebaseIndexEmbedderModelDimension,
})}
/>
{formErrors.codebaseIndexEmbedderModelDimension && (
<p className="text-xs text-vscode-errorForeground mt-1 mb-0">
{formErrors.codebaseIndexEmbedderModelDimension}
</p>
)}
</div>
</>
)}
{currentSettings.codebaseIndexEmbedderProvider === "openai-compatible" && (
<>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("settings:codeIndex.openAiCompatibleBaseUrlLabel")}
</label>
<VSCodeTextField
value={currentSettings.codebaseIndexOpenAiCompatibleBaseUrl || ""}
onInput={(e: any) =>
updateSetting(
"codebaseIndexOpenAiCompatibleBaseUrl",
e.target.value,
)
}
placeholder={t(
"settings:codeIndex.openAiCompatibleBaseUrlPlaceholder",
)}
className={cn("w-full", {
"border-red-500":
formErrors.codebaseIndexOpenAiCompatibleBaseUrl,
})}
/>
{formErrors.codebaseIndexOpenAiCompatibleBaseUrl && (
<p className="text-xs text-vscode-errorForeground mt-1 mb-0">
{formErrors.codebaseIndexOpenAiCompatibleBaseUrl}
</p>
)}
</div>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("settings:codeIndex.openAiCompatibleApiKeyLabel")}
</label>
<VSCodeTextField
type="password"
value={currentSettings.codebaseIndexOpenAiCompatibleApiKey || ""}
onInput={(e: any) =>
updateSetting(
"codebaseIndexOpenAiCompatibleApiKey",
e.target.value,
)
}
placeholder={t(
"settings:codeIndex.openAiCompatibleApiKeyPlaceholder",
)}
className={cn("w-full", {
"border-red-500":
formErrors.codebaseIndexOpenAiCompatibleApiKey,
})}
/>
{formErrors.codebaseIndexOpenAiCompatibleApiKey && (
<p className="text-xs text-vscode-errorForeground mt-1 mb-0">
{formErrors.codebaseIndexOpenAiCompatibleApiKey}
</p>
)}
</div>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("settings:codeIndex.modelLabel")}
</label>
<VSCodeTextField
value={currentSettings.codebaseIndexEmbedderModelId || ""}
onInput={(e: any) =>
updateSetting("codebaseIndexEmbedderModelId", e.target.value)
}
placeholder={t("settings:codeIndex.modelPlaceholder")}
className={cn("w-full", {
"border-red-500": formErrors.codebaseIndexEmbedderModelId,