-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathwebviewMessageHandler.ts
More file actions
3633 lines (3263 loc) · 117 KB
/
webviewMessageHandler.ts
File metadata and controls
3633 lines (3263 loc) · 117 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 { safeWriteJson } from "../../utils/safeWriteJson"
import * as path from "path"
import * as os from "os"
import * as fs from "fs/promises"
import { getRooDirectoriesForCwd } from "../../services/roo-config/index.js"
import pWaitFor from "p-wait-for"
import * as vscode from "vscode"
import {
type Language,
type GlobalState,
type ClineMessage,
type TelemetrySetting,
type UserSettingsConfig,
type ModelRecord,
type WebviewMessage,
type EditQueuedMessagePayload,
TelemetryEventName,
RooCodeSettings,
ExperimentId,
checkoutDiffPayloadSchema,
checkoutRestorePayloadSchema,
} from "@roo-code/types"
import { customToolRegistry } from "@roo-code/core"
import { CloudService } from "@roo-code/cloud"
import { TelemetryService } from "@roo-code/telemetry"
import { type ApiMessage } from "../task-persistence/apiMessages"
import { saveTaskMessages } from "../task-persistence"
import { ClineProvider } from "./ClineProvider"
import { BrowserSessionPanelManager } from "./BrowserSessionPanelManager"
import { handleCheckpointRestoreOperation } from "./checkpointRestoreHandler"
import { generateErrorDiagnostics } from "./diagnosticsHandler"
import {
handleRequestSkills,
handleCreateSkill,
handleDeleteSkill,
handleMoveSkill,
handleOpenSkillFile,
} from "./skillsMessageHandler"
import { changeLanguage, t } from "../../i18n"
import { Package } from "../../shared/package"
import { type RouterName, toRouterName } from "../../shared/api"
import { MessageEnhancer } from "./messageEnhancer"
import { checkExistKey } from "../../shared/checkExistApiConfig"
import { experimentDefault } from "../../shared/experiments"
import { Terminal } from "../../integrations/terminal/Terminal"
import { openFile } from "../../integrations/misc/open-file"
import { openImage, saveImage } from "../../integrations/misc/image-handler"
import { selectImages } from "../../integrations/misc/process-images"
import { getTheme } from "../../integrations/theme/getTheme"
import { discoverChromeHostUrl, tryChromeHostUrl } from "../../services/browser/browserDiscovery"
import { searchWorkspaceFiles } from "../../services/search/file-search"
import { fileExistsAtPath } from "../../utils/fs"
import { playTts, setTtsEnabled, setTtsSpeed, stopTts } from "../../utils/tts"
import { searchCommits } from "../../utils/git"
import { exportSettings, importSettingsWithFeedback } from "../config/importExport"
import { getOpenAiModels } from "../../api/providers/openai"
import { getVsCodeLmModels } from "../../api/providers/vscode-lm"
import { openMention } from "../mentions"
import { resolveImageMentions } from "../mentions/resolveImageMentions"
import { RooIgnoreController } from "../ignore/RooIgnoreController"
import { getWorkspacePath } from "../../utils/path"
import { Mode, defaultModeSlug } from "../../shared/modes"
import { getModels, flushModels } from "../../api/providers/fetchers/modelCache"
import { GetModelsOptions } from "../../shared/api"
import { generateSystemPrompt } from "./generateSystemPrompt"
import { resolveDefaultSaveUri, saveLastExportPath } from "../../utils/export"
import { getCommand } from "../../utils/commands"
const ALLOWED_VSCODE_SETTINGS = new Set(["terminal.integrated.inheritEnv"])
import { MarketplaceManager, MarketplaceItemType } from "../../services/marketplace"
import { setPendingTodoList } from "../tools/UpdateTodoListTool"
import {
handleListWorktrees,
handleCreateWorktree,
handleDeleteWorktree,
handleSwitchWorktree,
handleGetAvailableBranches,
handleGetWorktreeDefaults,
handleGetWorktreeIncludeStatus,
handleCheckBranchWorktreeInclude,
handleCreateWorktreeInclude,
handleCheckoutBranch,
} from "./worktree"
export const webviewMessageHandler = async (
provider: ClineProvider,
message: WebviewMessage,
marketplaceManager?: MarketplaceManager,
) => {
// Utility functions provided for concise get/update of global state via contextProxy API.
const getGlobalState = <K extends keyof GlobalState>(key: K) => provider.contextProxy.getValue(key)
const updateGlobalState = async <K extends keyof GlobalState>(key: K, value: GlobalState[K]) =>
await provider.contextProxy.setValue(key, value)
const getCurrentCwd = () => {
return provider.getCurrentTask()?.cwd || provider.cwd
}
/**
* Resolves image file mentions in incoming messages.
* Matches read_file behavior: respects size limits and model capabilities.
*/
const resolveIncomingImages = async (payload: { text?: string; images?: string[] }) => {
const text = payload.text ?? ""
const images = payload.images
const currentTask = provider.getCurrentTask()
const state = await provider.getState()
const resolved = await resolveImageMentions({
text,
images,
cwd: getCurrentCwd(),
rooIgnoreController: currentTask?.rooIgnoreController,
maxImageFileSize: state.maxImageFileSize,
maxTotalImageSize: state.maxTotalImageSize,
})
return resolved
}
/**
* Shared utility to find message indices based on timestamp.
* When multiple messages share the same timestamp (e.g., after condense),
* this function prefers non-summary messages to ensure user operations
* target the intended message rather than the summary.
*/
const findMessageIndices = (messageTs: number, currentCline: any) => {
// Find the exact message by timestamp, not the first one after a cutoff
const messageIndex = currentCline.clineMessages.findIndex((msg: ClineMessage) => msg.ts === messageTs)
// Find all matching API messages by timestamp
const allApiMatches = currentCline.apiConversationHistory
.map((msg: ApiMessage, idx: number) => ({ msg, idx }))
.filter(({ msg }: { msg: ApiMessage }) => msg.ts === messageTs)
// Prefer non-summary message if multiple matches exist (handles timestamp collision after condense)
const preferred = allApiMatches.find(({ msg }: { msg: ApiMessage }) => !msg.isSummary) || allApiMatches[0]
const apiConversationHistoryIndex = preferred?.idx ?? -1
return { messageIndex, apiConversationHistoryIndex }
}
/**
* Fallback: find first API history index at or after a timestamp.
* Used when the exact user message isn't present in apiConversationHistory (e.g., after condense).
*/
const findFirstApiIndexAtOrAfter = (ts: number, currentCline: any) => {
if (typeof ts !== "number") return -1
return currentCline.apiConversationHistory.findIndex(
(msg: ApiMessage) => typeof msg?.ts === "number" && (msg.ts as number) >= ts,
)
}
/**
* Handles message deletion operations with user confirmation
*/
const handleDeleteOperation = async (messageTs: number): Promise<void> => {
// Check if there's a checkpoint before this message
const currentCline = provider.getCurrentTask()
let hasCheckpoint = false
if (!currentCline) {
await vscode.window.showErrorMessage(t("common:errors.message.no_active_task_to_delete"))
return
}
const { messageIndex } = findMessageIndices(messageTs, currentCline)
if (messageIndex !== -1) {
// Find the last checkpoint before this message
const checkpoints = currentCline.clineMessages.filter(
(msg) => msg.say === "checkpoint_saved" && msg.ts > messageTs,
)
hasCheckpoint = checkpoints.length > 0
}
// Send message to webview to show delete confirmation dialog
await provider.postMessageToWebview({
type: "showDeleteMessageDialog",
messageTs,
hasCheckpoint,
})
}
/**
* Handles confirmed message deletion from webview dialog
*/
const handleDeleteMessageConfirm = async (messageTs: number, restoreCheckpoint?: boolean): Promise<void> => {
const currentCline = provider.getCurrentTask()
if (!currentCline) {
console.error("[handleDeleteMessageConfirm] No current cline available")
return
}
const { messageIndex, apiConversationHistoryIndex } = findMessageIndices(messageTs, currentCline)
// Determine API truncation index with timestamp fallback if exact match not found
let apiIndexToUse = apiConversationHistoryIndex
const tsThreshold = currentCline.clineMessages[messageIndex]?.ts
if (apiIndexToUse === -1 && typeof tsThreshold === "number") {
apiIndexToUse = findFirstApiIndexAtOrAfter(tsThreshold, currentCline)
}
if (messageIndex === -1) {
await vscode.window.showErrorMessage(t("common:errors.message.message_not_found", { messageTs }))
return
}
try {
const targetMessage = currentCline.clineMessages[messageIndex]
// If checkpoint restoration is requested, find and restore to the last checkpoint before this message
if (restoreCheckpoint) {
// Find the last checkpoint before this message
const checkpoints = currentCline.clineMessages.filter(
(msg) => msg.say === "checkpoint_saved" && msg.ts > messageTs,
)
const nextCheckpoint = checkpoints[0]
if (nextCheckpoint && nextCheckpoint.text) {
await handleCheckpointRestoreOperation({
provider,
currentCline,
messageTs: targetMessage.ts!,
messageIndex,
checkpoint: { hash: nextCheckpoint.text },
operation: "delete",
})
} else {
// No checkpoint found before this message
console.log("[handleDeleteMessageConfirm] No checkpoint found before message")
vscode.window.showWarningMessage("No checkpoint found before this message")
}
} else {
// For non-checkpoint deletes, preserve checkpoint associations for remaining messages
// Store checkpoints from messages that will be preserved
const preservedCheckpoints = new Map<number, any>()
for (let i = 0; i < messageIndex; i++) {
const msg = currentCline.clineMessages[i]
if (msg?.checkpoint && msg.ts) {
preservedCheckpoints.set(msg.ts, msg.checkpoint)
}
}
// Delete this message and all subsequent messages using MessageManager
await currentCline.messageManager.rewindToTimestamp(targetMessage.ts!, { includeTargetMessage: false })
// Restore checkpoint associations for preserved messages
for (const [ts, checkpoint] of preservedCheckpoints) {
const msgIndex = currentCline.clineMessages.findIndex((msg) => msg.ts === ts)
if (msgIndex !== -1) {
currentCline.clineMessages[msgIndex].checkpoint = checkpoint
}
}
// Save the updated messages with restored checkpoints
await saveTaskMessages({
messages: currentCline.clineMessages,
taskId: currentCline.taskId,
globalStoragePath: provider.contextProxy.globalStorageUri.fsPath,
})
// Update the UI to reflect the deletion
await provider.postStateToWebview()
}
} catch (error) {
console.error("Error in delete message:", error)
vscode.window.showErrorMessage(
t("common:errors.message.error_deleting_message", {
error: error instanceof Error ? error.message : String(error),
}),
)
}
}
/**
* Handles message editing operations with user confirmation
*/
const handleEditOperation = async (messageTs: number, editedContent: string, images?: string[]): Promise<void> => {
// Check if there's a checkpoint before this message
const currentCline = provider.getCurrentTask()
let hasCheckpoint = false
if (currentCline) {
const { messageIndex } = findMessageIndices(messageTs, currentCline)
if (messageIndex !== -1) {
// Find the last checkpoint before this message
const checkpoints = currentCline.clineMessages.filter(
(msg) => msg.say === "checkpoint_saved" && msg.ts > messageTs,
)
hasCheckpoint = checkpoints.length > 0
} else {
console.log("[webviewMessageHandler] Edit - Message not found in clineMessages!")
}
} else {
console.log("[webviewMessageHandler] Edit - No currentCline available!")
}
// Send message to webview to show edit confirmation dialog
await provider.postMessageToWebview({
type: "showEditMessageDialog",
messageTs,
text: editedContent,
hasCheckpoint,
images,
})
}
/**
* Handles confirmed message editing from webview dialog
*/
const handleEditMessageConfirm = async (
messageTs: number,
editedContent: string,
restoreCheckpoint?: boolean,
images?: string[],
): Promise<void> => {
const currentCline = provider.getCurrentTask()
if (!currentCline) {
console.error("[handleEditMessageConfirm] No current cline available")
return
}
// Use findMessageIndices to find messages based on timestamp
const { messageIndex, apiConversationHistoryIndex } = findMessageIndices(messageTs, currentCline)
if (messageIndex === -1) {
const errorMessage = t("common:errors.message.message_not_found", { messageTs })
console.error("[handleEditMessageConfirm]", errorMessage)
await vscode.window.showErrorMessage(errorMessage)
return
}
try {
const targetMessage = currentCline.clineMessages[messageIndex]
// If checkpoint restoration is requested, find and restore to the last checkpoint before this message
if (restoreCheckpoint) {
// Find the last checkpoint before this message
const checkpoints = currentCline.clineMessages.filter(
(msg) => msg.say === "checkpoint_saved" && msg.ts > messageTs,
)
const nextCheckpoint = checkpoints[0]
if (nextCheckpoint && nextCheckpoint.text) {
await handleCheckpointRestoreOperation({
provider,
currentCline,
messageTs: targetMessage.ts!,
messageIndex,
checkpoint: { hash: nextCheckpoint.text },
operation: "edit",
editData: {
editedContent,
images,
apiConversationHistoryIndex,
},
})
// The task will be cancelled and reinitialized by checkpointRestore
// The pending edit will be processed in the reinitialized task
return
} else {
// No checkpoint found before this message
console.log("[handleEditMessageConfirm] No checkpoint found before message")
vscode.window.showWarningMessage("No checkpoint found before this message")
// Continue with non-checkpoint edit
}
}
// For non-checkpoint edits, remove the ORIGINAL user message being edited and all subsequent messages
// Determine the correct starting index to delete from (prefer the last preceding user_feedback message)
let deleteFromMessageIndex = messageIndex
let deleteFromApiIndex = apiConversationHistoryIndex
// Find the nearest preceding user message to ensure we replace the original, not just the assistant reply
for (let i = messageIndex; i >= 0; i--) {
const m = currentCline.clineMessages[i]
if (m?.say === "user_feedback") {
deleteFromMessageIndex = i
// Align API history truncation to the same user message timestamp if present
const userTs = m.ts
if (typeof userTs === "number") {
const apiIdx = currentCline.apiConversationHistory.findIndex(
(am: ApiMessage) => am.ts === userTs,
)
if (apiIdx !== -1) {
deleteFromApiIndex = apiIdx
}
}
break
}
}
// Timestamp fallback for API history when exact user message isn't present
if (deleteFromApiIndex === -1) {
const tsThresholdForEdit = currentCline.clineMessages[deleteFromMessageIndex]?.ts
if (typeof tsThresholdForEdit === "number") {
deleteFromApiIndex = findFirstApiIndexAtOrAfter(tsThresholdForEdit, currentCline)
}
}
// Store checkpoints from messages that will be preserved
const preservedCheckpoints = new Map<number, any>()
for (let i = 0; i < deleteFromMessageIndex; i++) {
const msg = currentCline.clineMessages[i]
if (msg?.checkpoint && msg.ts) {
preservedCheckpoints.set(msg.ts, msg.checkpoint)
}
}
// Delete the original (user) message and all subsequent messages using MessageManager
const rewindTs = currentCline.clineMessages[deleteFromMessageIndex]?.ts
if (rewindTs) {
await currentCline.messageManager.rewindToTimestamp(rewindTs, { includeTargetMessage: false })
}
// Restore checkpoint associations for preserved messages
for (const [ts, checkpoint] of preservedCheckpoints) {
const msgIndex = currentCline.clineMessages.findIndex((msg) => msg.ts === ts)
if (msgIndex !== -1) {
currentCline.clineMessages[msgIndex].checkpoint = checkpoint
}
}
// Save the updated messages with restored checkpoints
await saveTaskMessages({
messages: currentCline.clineMessages,
taskId: currentCline.taskId,
globalStoragePath: provider.contextProxy.globalStorageUri.fsPath,
})
// Update the UI to reflect the deletion
await provider.postStateToWebview()
await currentCline.submitUserMessage(editedContent, images)
} catch (error) {
console.error("Error in edit message:", error)
vscode.window.showErrorMessage(
t("common:errors.message.error_editing_message", {
error: error instanceof Error ? error.message : String(error),
}),
)
}
}
/**
* Handles message modification operations (delete or edit) with confirmation dialog
* @param messageTs Timestamp of the message to operate on
* @param operation Type of operation ('delete' or 'edit')
* @param editedContent New content for edit operations
* @returns Promise<void>
*/
const handleMessageModificationsOperation = async (
messageTs: number,
operation: "delete" | "edit",
editedContent?: string,
images?: string[],
): Promise<void> => {
if (operation === "delete") {
await handleDeleteOperation(messageTs)
} else if (operation === "edit" && editedContent) {
await handleEditOperation(messageTs, editedContent, images)
}
}
switch (message.type) {
case "webviewDidLaunch":
// Load custom modes first
const customModes = await provider.customModesManager.getCustomModes()
await updateGlobalState("customModes", customModes)
provider.postStateToWebview()
provider.workspaceTracker?.initializeFilePaths() // Don't await.
getTheme().then((theme) => provider.postMessageToWebview({ type: "theme", text: JSON.stringify(theme) }))
// If MCP Hub is already initialized, update the webview with
// current server list.
const mcpHub = provider.getMcpHub()
if (mcpHub) {
provider.postMessageToWebview({ type: "mcpServers", mcpServers: mcpHub.getAllServers() })
}
provider.providerSettingsManager
.listConfig()
.then(async (listApiConfig) => {
if (!listApiConfig) {
return
}
if (listApiConfig.length === 1) {
// Check if first time init then sync with exist config.
if (!checkExistKey(listApiConfig[0])) {
const { apiConfiguration } = await provider.getState()
await provider.providerSettingsManager.saveConfig(
listApiConfig[0].name ?? "default",
apiConfiguration,
)
listApiConfig[0].apiProvider = apiConfiguration.apiProvider
}
}
const currentConfigName = getGlobalState("currentApiConfigName")
if (currentConfigName) {
if (!(await provider.providerSettingsManager.hasConfig(currentConfigName))) {
// Current config name not valid, get first config in list.
const name = listApiConfig[0]?.name
await updateGlobalState("currentApiConfigName", name)
if (name) {
await provider.activateProviderProfile({ name })
return
}
}
}
await Promise.all([
await updateGlobalState("listApiConfigMeta", listApiConfig),
await provider.postMessageToWebview({ type: "listApiConfig", listApiConfig }),
])
})
.catch((error) =>
provider.log(
`Error list api configuration: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
),
)
// Enable telemetry by default (when unset) or when explicitly enabled
provider.getStateToPostToWebview().then((state) => {
const { telemetrySetting } = state
const isOptedIn = telemetrySetting !== "disabled"
TelemetryService.instance.updateTelemetryState(isOptedIn)
})
provider.isViewLaunched = true
break
case "newTask":
// Initializing new instance of Cline will make sure that any
// agentically running promises in old instance don't affect our new
// task. This essentially creates a fresh slate for the new task.
try {
const resolved = await resolveIncomingImages({ text: message.text, images: message.images })
await provider.createTask(resolved.text, resolved.images)
// Task created successfully - notify the UI to reset
await provider.postMessageToWebview({ type: "invoke", invoke: "newChat" })
} catch (error) {
// For all errors, reset the UI and show error
await provider.postMessageToWebview({ type: "invoke", invoke: "newChat" })
// Show error to user
vscode.window.showErrorMessage(
`Failed to create task: ${error instanceof Error ? error.message : String(error)}`,
)
}
break
case "customInstructions":
await provider.updateCustomInstructions(message.text)
break
case "askResponse":
{
const resolved = await resolveIncomingImages({ text: message.text, images: message.images })
provider
.getCurrentTask()
?.handleWebviewAskResponse(message.askResponse!, resolved.text, resolved.images)
}
break
case "updateSettings":
if (message.updatedSettings) {
for (const [key, value] of Object.entries(message.updatedSettings)) {
let newValue = value
if (key === "language") {
newValue = value ?? "en"
changeLanguage(newValue as Language)
} else if (key === "allowedCommands") {
const commands = value ?? []
newValue = Array.isArray(commands)
? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0)
: []
await vscode.workspace
.getConfiguration(Package.name)
.update("allowedCommands", newValue, vscode.ConfigurationTarget.Global)
} else if (key === "deniedCommands") {
const commands = value ?? []
newValue = Array.isArray(commands)
? commands.filter((cmd) => typeof cmd === "string" && cmd.trim().length > 0)
: []
await vscode.workspace
.getConfiguration(Package.name)
.update("deniedCommands", newValue, vscode.ConfigurationTarget.Global)
} else if (key === "ttsEnabled") {
newValue = value ?? true
setTtsEnabled(newValue as boolean)
} else if (key === "ttsSpeed") {
newValue = value ?? 1.0
setTtsSpeed(newValue as number)
} else if (key === "terminalShellIntegrationTimeout") {
if (value !== undefined) {
Terminal.setShellIntegrationTimeout(value as number)
}
} else if (key === "terminalShellIntegrationDisabled") {
if (value !== undefined) {
Terminal.setShellIntegrationDisabled(value as boolean)
}
} else if (key === "terminalCommandDelay") {
if (value !== undefined) {
Terminal.setCommandDelay(value as number)
}
} else if (key === "terminalPowershellCounter") {
if (value !== undefined) {
Terminal.setPowershellCounter(value as boolean)
}
} else if (key === "terminalZshClearEolMark") {
if (value !== undefined) {
Terminal.setTerminalZshClearEolMark(value as boolean)
}
} else if (key === "terminalZshOhMy") {
if (value !== undefined) {
Terminal.setTerminalZshOhMy(value as boolean)
}
} else if (key === "terminalZshP10k") {
if (value !== undefined) {
Terminal.setTerminalZshP10k(value as boolean)
}
} else if (key === "terminalZdotdir") {
if (value !== undefined) {
Terminal.setTerminalZdotdir(value as boolean)
}
} else if (key === "mcpEnabled") {
newValue = value ?? true
const mcpHub = provider.getMcpHub()
if (mcpHub) {
await mcpHub.handleMcpEnabledChange(newValue as boolean)
}
} else if (key === "experiments") {
if (!value) {
continue
}
newValue = {
...(getGlobalState("experiments") ?? experimentDefault),
...(value as Record<ExperimentId, boolean>),
}
} else if (key === "customSupportPrompts") {
if (!value) {
continue
}
}
await provider.contextProxy.setValue(key as keyof RooCodeSettings, newValue)
}
await provider.postStateToWebview()
}
break
case "terminalOperation":
if (message.terminalOperation) {
provider.getCurrentTask()?.handleTerminalOperation(message.terminalOperation)
}
break
case "clearTask":
// Clear task resets the current session. Delegation flows are
// handled via metadata; parent resumption occurs through
// reopenParentFromDelegation, not via finishSubTask.
await provider.clearTask()
await provider.postStateToWebview()
break
case "didShowAnnouncement":
await updateGlobalState("lastShownAnnouncementId", provider.latestAnnouncementId)
await provider.postStateToWebview()
break
case "selectImages":
const images = await selectImages()
await provider.postMessageToWebview({
type: "selectedImages",
images,
context: message.context,
messageTs: message.messageTs,
})
break
case "exportCurrentTask":
const currentTaskId = provider.getCurrentTask()?.taskId
if (currentTaskId) {
provider.exportTaskWithId(currentTaskId)
}
break
case "shareCurrentTask":
const shareTaskId = provider.getCurrentTask()?.taskId
const clineMessages = provider.getCurrentTask()?.clineMessages
if (!shareTaskId) {
vscode.window.showErrorMessage(t("common:errors.share_no_active_task"))
break
}
try {
const visibility = message.visibility || "organization"
const result = await CloudService.instance.shareTask(shareTaskId, visibility, clineMessages)
if (result.success && result.shareUrl) {
// Show success notification
const messageKey =
visibility === "public"
? "common:info.public_share_link_copied"
: "common:info.organization_share_link_copied"
vscode.window.showInformationMessage(t(messageKey))
// Send success feedback to webview for inline display
await provider.postMessageToWebview({
type: "shareTaskSuccess",
visibility,
text: result.shareUrl,
})
} else {
// Handle error
const errorMessage = result.error || "Failed to create share link"
if (errorMessage.includes("Authentication")) {
vscode.window.showErrorMessage(t("common:errors.share_auth_required"))
} else if (errorMessage.includes("sharing is not enabled")) {
vscode.window.showErrorMessage(t("common:errors.share_not_enabled"))
} else if (errorMessage.includes("not found")) {
vscode.window.showErrorMessage(t("common:errors.share_task_not_found"))
} else {
vscode.window.showErrorMessage(errorMessage)
}
}
} catch (error) {
provider.log(`[shareCurrentTask] Unexpected error: ${error}`)
vscode.window.showErrorMessage(t("common:errors.share_task_failed"))
}
break
case "showTaskWithId":
provider.showTaskWithId(message.text!)
break
case "condenseTaskContextRequest":
provider.condenseTaskContext(message.text!)
break
case "deleteTaskWithId":
provider.deleteTaskWithId(message.text!)
break
case "deleteMultipleTasksWithIds": {
const ids = message.ids
if (Array.isArray(ids)) {
// Process in batches of 20 (or another reasonable number)
const batchSize = 20
const results = []
// Only log start and end of the operation
console.log(`Batch deletion started: ${ids.length} tasks total`)
for (let i = 0; i < ids.length; i += batchSize) {
const batch = ids.slice(i, i + batchSize)
const batchPromises = batch.map(async (id) => {
try {
await provider.deleteTaskWithId(id)
return { id, success: true }
} catch (error) {
// Keep error logging for debugging purposes
console.log(
`Failed to delete task ${id}: ${error instanceof Error ? error.message : String(error)}`,
)
return { id, success: false }
}
})
// Process each batch in parallel but wait for completion before starting the next batch
const batchResults = await Promise.all(batchPromises)
results.push(...batchResults)
// Update the UI after each batch to show progress
await provider.postStateToWebview()
}
// Log final results
const successCount = results.filter((r) => r.success).length
const failCount = results.length - successCount
console.log(
`Batch deletion completed: ${successCount}/${ids.length} tasks successful, ${failCount} tasks failed`,
)
}
break
}
case "exportTaskWithId":
provider.exportTaskWithId(message.text!)
break
case "getTaskWithAggregatedCosts": {
try {
const taskId = message.text
if (!taskId) {
throw new Error("Task ID is required")
}
const result = await provider.getTaskWithAggregatedCosts(taskId)
await provider.postMessageToWebview({
type: "taskWithAggregatedCosts",
// IMPORTANT: ChatView stores aggregatedCostsMap keyed by message.text (taskId)
// so we must include it here.
text: taskId,
historyItem: result.historyItem,
aggregatedCosts: result.aggregatedCosts,
})
} catch (error) {
console.error("Error getting task with aggregated costs:", error)
await provider.postMessageToWebview({
type: "taskWithAggregatedCosts",
// Include taskId when available for correlation in UI logs.
text: message.text,
error: error instanceof Error ? error.message : String(error),
})
}
break
}
case "importSettings": {
await importSettingsWithFeedback({
providerSettingsManager: provider.providerSettingsManager,
contextProxy: provider.contextProxy,
customModesManager: provider.customModesManager,
provider: provider,
})
break
}
case "exportSettings":
await exportSettings({
providerSettingsManager: provider.providerSettingsManager,
contextProxy: provider.contextProxy,
})
break
case "resetState":
await provider.resetState()
break
case "flushRouterModels":
const routerNameFlush: RouterName = toRouterName(message.text)
// Note: flushRouterModels is a generic flush without credentials
// For providers that need credentials, use their specific handlers
await flushModels({ provider: routerNameFlush } as GetModelsOptions, true)
break
case "requestRouterModels":
const { apiConfiguration } = await provider.getState()
// Optional single provider filter from webview
const requestedProvider = message?.values?.provider
const providerFilter = requestedProvider ? toRouterName(requestedProvider) : undefined
// Optional refresh flag to flush cache before fetching (useful for providers requiring credentials)
const shouldRefresh = message?.values?.refresh === true
const routerModels: Record<RouterName, ModelRecord> = providerFilter
? ({} as Record<RouterName, ModelRecord>)
: {
openrouter: {},
"vercel-ai-gateway": {},
huggingface: {},
litellm: {},
deepinfra: {},
"io-intelligence": {},
requesty: {},
unbound: {},
ollama: {},
lmstudio: {},
roo: {},
chutes: {},
}
const safeGetModels = async (options: GetModelsOptions): Promise<ModelRecord> => {
try {
return await getModels(options)
} catch (error) {
console.error(
`Failed to fetch models in webviewMessageHandler requestRouterModels for ${options.provider}:`,
error,
)
throw error // Re-throw to be caught by Promise.allSettled.
}
}
// Base candidates (only those handled by this aggregate fetcher)
const candidates: { key: RouterName; options: GetModelsOptions }[] = [
{ key: "openrouter", options: { provider: "openrouter" } },
{
key: "requesty",
options: {
provider: "requesty",
apiKey: apiConfiguration.requestyApiKey,
baseUrl: apiConfiguration.requestyBaseUrl,
},
},
{ key: "unbound", options: { provider: "unbound", apiKey: apiConfiguration.unboundApiKey } },
{ key: "vercel-ai-gateway", options: { provider: "vercel-ai-gateway" } },
{
key: "deepinfra",
options: {
provider: "deepinfra",
apiKey: apiConfiguration.deepInfraApiKey,
baseUrl: apiConfiguration.deepInfraBaseUrl,
},
},
{
key: "roo",
options: {
provider: "roo",
baseUrl: process.env.ROO_CODE_PROVIDER_URL ?? "https://api.roocode.com/proxy",
apiKey: CloudService.hasInstance()
? CloudService.instance.authService?.getSessionToken()
: undefined,
},
},
{
key: "chutes",
options: { provider: "chutes", apiKey: apiConfiguration.chutesApiKey },
},
]
// IO Intelligence is conditional on api key
if (apiConfiguration.ioIntelligenceApiKey) {
candidates.push({
key: "io-intelligence",
options: { provider: "io-intelligence", apiKey: apiConfiguration.ioIntelligenceApiKey },
})
}
// LiteLLM is conditional on baseUrl+apiKey
const litellmApiKey = apiConfiguration.litellmApiKey || message?.values?.litellmApiKey
const litellmBaseUrl = apiConfiguration.litellmBaseUrl || message?.values?.litellmBaseUrl
if (litellmApiKey && litellmBaseUrl) {
// If explicit credentials are provided in message.values (from Refresh Models button),
// flush the cache first to ensure we fetch fresh data with the new credentials
if (message?.values?.litellmApiKey || message?.values?.litellmBaseUrl) {
await flushModels({ provider: "litellm", apiKey: litellmApiKey, baseUrl: litellmBaseUrl }, true)
}
candidates.push({
key: "litellm",
options: { provider: "litellm", apiKey: litellmApiKey, baseUrl: litellmBaseUrl },
})
}
// Apply single provider filter if specified
const modelFetchPromises = providerFilter
? candidates.filter(({ key }) => key === providerFilter)
: candidates
// If refresh flag is set and we have a specific provider, flush its cache first
if (shouldRefresh && providerFilter && modelFetchPromises.length > 0) {
const targetCandidate = modelFetchPromises[0]
await flushModels(targetCandidate.options, true)
}
const results = await Promise.allSettled(
modelFetchPromises.map(async ({ key, options }) => {
const models = await safeGetModels(options)
return { key, models } // The key is `ProviderName` here.
}),
)
results.forEach((result, index) => {
const routerName = modelFetchPromises[index].key
if (result.status === "fulfilled") {
routerModels[routerName] = result.value.models
// Ollama and LM Studio settings pages still need these events. They are not fetched here.
} else {
// Handle rejection: Post a specific error message for this provider.
const errorMessage = result.reason instanceof Error ? result.reason.message : String(result.reason)
console.error(`Error fetching models for ${routerName}:`, result.reason)
routerModels[routerName] = {} // Ensure it's an empty object in the main routerModels message.
provider.postMessageToWebview({
type: "singleRouterModelFetchResponse",
success: false,
error: errorMessage,
values: { provider: routerName },
})
}
})
provider.postMessageToWebview({
type: "routerModels",
routerModels,