-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathChatView.tsx
More file actions
1884 lines (1726 loc) · 61.6 KB
/
Copy pathChatView.tsx
File metadata and controls
1884 lines (1726 loc) · 61.6 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, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"
import { useDeepCompareEffect, useEvent } from "react-use"
import { Virtuoso, type VirtuosoHandle } from "react-virtuoso"
import removeMd from "remove-markdown"
import useSound from "use-sound"
import { LRUCache } from "lru-cache"
import { useDebounceEffect } from "@src/utils/useDebounceEffect"
import { appendImages } from "@src/utils/imageUtils"
import { getCostBreakdownIfNeeded } from "@src/utils/costFormatting"
import { batchNearby } from "@src/utils/batchNearby"
import { isBoundary, isIgnorableBetweenTargets } from "@src/utils/chatBatchingPredicates"
import type { ClineAsk, ClineSayTool, ClineMessage, ExtensionMessage, AudioType, SuggestionItem } from "@roo-code/types"
import { getCompletionCheckpoint, getSuggestionMode, isRetiredProvider } from "@roo-code/types"
import { findLast } from "@roo/array"
import { combineApiRequests } from "@roo/combineApiRequests"
import { combineCommandSequences } from "@roo/combineCommandSequences"
import { getApiMetrics } from "@roo/getApiMetrics"
import { getAllModes } from "@roo/modes"
import { ProfileValidator } from "@roo/ProfileValidator"
import { getLatestTodo } from "@roo/todo"
import { vscode } from "@src/utils/vscode"
import { useAppTranslation } from "@src/i18n/TranslationContext"
import { useExtensionState } from "@src/context/ExtensionStateContext"
import { useSelectedModel } from "@src/components/ui/hooks/useSelectedModel"
import RooHero from "@src/components/welcome/RooHero"
import RooTips from "@src/components/welcome/RooTips"
import { StandardTooltip, Button } from "@src/components/ui"
import TelemetryBanner from "../common/TelemetryBanner"
import VersionIndicator from "../common/VersionIndicator"
import HistoryPreview from "../history/HistoryPreview"
import Announcement from "./Announcement"
import ChatRow from "./ChatRow"
import WarningRow from "./WarningRow"
import { ChatTextArea } from "./ChatTextArea"
import TaskHeader from "./TaskHeader"
import ProfileViolationWarning from "./ProfileViolationWarning"
import { CheckpointWarning } from "./CheckpointWarning"
import { QueuedMessages } from "./QueuedMessages"
import { WorktreeSelector } from "./WorktreeSelector"
import FileChangesPanel from "./FileChangesPanel"
import { useScrollLifecycle } from "@src/hooks/useScrollLifecycle"
export interface ChatViewProps {
isHidden: boolean
showAnnouncement: boolean
hideAnnouncement: () => void
}
export interface ChatViewRef {
acceptInput: () => void
}
export const MAX_IMAGES_PER_MESSAGE = 20 // This is the Anthropic limit.
const CHAT_DEFAULT_ITEM_HEIGHT = 180
const CHAT_VIEWPORT_BUFFER = {
top: 600,
bottom: 800,
} as const
const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0
const ChatViewComponent: React.ForwardRefRenderFunction<ChatViewRef, ChatViewProps> = (
{ isHidden, showAnnouncement, hideAnnouncement },
ref,
) => {
const [audioBaseUri] = useState(() => {
return (window as unknown as { AUDIO_BASE_URI?: string }).AUDIO_BASE_URI || ""
})
const { t } = useAppTranslation()
const modeShortcutText = `${isMac ? "⌘" : "Ctrl"} + . ${t("chat:forNextMode")}, ${isMac ? "⌘" : "Ctrl"} + Shift + . ${t("chat:forPreviousMode")}`
const {
clineMessages: messages,
currentTaskItem,
currentTaskTodos,
taskHistory,
apiConfiguration,
organizationAllowList,
mode,
setMode,
alwaysAllowModeSwitch,
customModes,
soundEnabled,
soundVolume,
messageQueue = [],
showWorktreesInHomeScreen,
telemetrySetting,
} = useExtensionState()
// Show a WarningRow when the user sends a message with a retired provider.
const [showRetiredProviderWarning, setShowRetiredProviderWarning] = useState(false)
// When the provider changes, clear the retired-provider warning.
const providerName = apiConfiguration?.apiProvider
useEffect(() => {
setShowRetiredProviderWarning(false)
}, [providerName])
const messagesRef = useRef(messages)
useEffect(() => {
messagesRef.current = messages
}, [messages])
// Leaving this less safe version here since if the first message is not a
// task, then the extension is in a bad state and needs to be debugged (see
// Cline.abort).
const task = useMemo(() => messages.at(0), [messages])
const latestTodos = useMemo(() => {
// First check if we have initial todos from the state (for new subtasks)
if (currentTaskTodos && currentTaskTodos.length > 0) {
// Check if there are any todo updates in messages
const messageBasedTodos = getLatestTodo(messages)
// If there are message-based todos, they take precedence (user has updated them)
if (messageBasedTodos && messageBasedTodos.length > 0) {
return messageBasedTodos
}
// Otherwise use the initial todos from state
return currentTaskTodos
}
// Fall back to extracting from messages
return getLatestTodo(messages)
}, [messages, currentTaskTodos])
const modifiedMessages = useMemo(() => combineApiRequests(combineCommandSequences(messages.slice(1))), [messages])
const completionCheckpoint = useMemo(() => getCompletionCheckpoint(messages), [messages])
const completionResultTs = useMemo(() => {
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i]
if (message?.type === "say" && message.say === "completion_result") {
return message.ts
}
// Zero-text ask completion rows are hidden by visibleMessages below, so attach
// actions to the latest renderable completion row while the extension host
// still derives the checkpoint target from authoritative task state.
if (message?.type === "ask" && message.ask === "completion_result" && (message.text ?? "") !== "") {
return message.ts
}
}
return undefined
}, [messages])
// Has to be after api_req_finished are all reduced into api_req_started messages.
const apiMetrics = useMemo(() => getApiMetrics(modifiedMessages), [modifiedMessages])
const [inputValue, setInputValue] = useState("")
const inputValueRef = useRef(inputValue)
const textAreaRef = useRef<HTMLTextAreaElement>(null)
const [sendingDisabled, setSendingDisabled] = useState(false)
const [selectedImages, setSelectedImages] = useState<string[]>([])
// We need to hold on to the ask because useEffect > lastMessage will always
// let us know when an ask comes in and handle it, but by the time
// handleMessage is called, the last message might not be the ask anymore
// (it could be a say that followed).
const [clineAsk, setClineAsk] = useState<ClineAsk | undefined>(undefined)
const [enableButtons, setEnableButtons] = useState<boolean>(false)
const [primaryButtonText, setPrimaryButtonText] = useState<string | undefined>(undefined)
const [secondaryButtonText, setSecondaryButtonText] = useState<string | undefined>(undefined)
const [_didClickCancel, setDidClickCancel] = useState(false)
const virtuosoRef = useRef<VirtuosoHandle>(null)
const [expandedRows, setExpandedRows] = useState<Record<number, boolean>>({})
const prevExpandedRowsRef = useRef<Record<number, boolean>>()
const scrollContainerRef = useRef<HTMLDivElement>(null)
const lastTtsRef = useRef<string>("")
const [wasStreaming, setWasStreaming] = useState<boolean>(false)
const [checkpointWarning, setCheckpointWarning] = useState<
{ type: "WAIT_TIMEOUT" | "INIT_TIMEOUT"; timeout: number } | undefined
>(undefined)
const [isCondensing, setIsCondensing] = useState<boolean>(false)
const [showAnnouncementModal, setShowAnnouncementModal] = useState(false)
const everVisibleMessagesTsRef = useRef<LRUCache<number, boolean>>(
new LRUCache({
max: 100,
ttl: 1000 * 60 * 5,
}),
)
const autoApproveTimeoutRef = useRef<NodeJS.Timeout | null>(null)
const userRespondedRef = useRef<boolean>(false)
const [currentFollowUpTs, setCurrentFollowUpTs] = useState<number | null>(null)
const [aggregatedCostsMap, setAggregatedCostsMap] = useState<
Map<
string,
{
totalCost: number
ownCost: number
childrenCost: number
}
>
>(new Map())
const clineAskRef = useRef(clineAsk)
useEffect(() => {
clineAskRef.current = clineAsk
}, [clineAsk])
// Keep inputValueRef in sync with inputValue state
useEffect(() => {
inputValueRef.current = inputValue
}, [inputValue])
// Compute whether auto-approval is paused (user is typing in a followup)
const isFollowUpAutoApprovalPaused = useMemo(() => {
return !!(inputValue && inputValue.trim().length > 0 && clineAsk === "followup")
}, [inputValue, clineAsk])
// Cancel auto-approval timeout when user starts typing
useEffect(() => {
// Only send cancel if there's actual input (user is typing)
// and we have a pending follow-up question
if (isFollowUpAutoApprovalPaused) {
vscode.postMessage({ type: "cancelAutoApproval" })
}
}, [isFollowUpAutoApprovalPaused])
const isProfileDisabled = useMemo(
() => !!apiConfiguration && !ProfileValidator.isProfileAllowed(apiConfiguration, organizationAllowList),
[apiConfiguration, organizationAllowList],
)
// UI layout depends on the last 2 messages (since it relies on the content
// of these messages, we are deep comparing) i.e. the button state after
// hitting button sets enableButtons to false, and this effect otherwise
// would have to true again even if messages didn't change.
const lastMessage = useMemo(() => messages.at(-1), [messages])
const secondLastMessage = useMemo(() => messages.at(-2), [messages])
const volume = typeof soundVolume === "number" ? soundVolume : 0.5
const [playNotification] = useSound(`${audioBaseUri}/notification.wav`, { volume, soundEnabled, interrupt: true })
const [playCelebration] = useSound(`${audioBaseUri}/celebration.wav`, { volume, soundEnabled, interrupt: true })
const [playProgressLoop] = useSound(`${audioBaseUri}/progress_loop.wav`, { volume, soundEnabled, interrupt: true })
const lastPlayedRef = useRef<Record<string, number>>({})
const playSound = useCallback(
(audioType: AudioType) => {
if (!soundEnabled) {
return
}
const now = Date.now()
const lastPlayed = lastPlayedRef.current[audioType] ?? 0
if (now - lastPlayed < 100) {
return
} // debounce: skip if played within 100ms
lastPlayedRef.current[audioType] = now
switch (audioType) {
case "notification":
playNotification()
break
case "celebration":
playCelebration()
break
case "progress_loop":
playProgressLoop()
break
default:
console.warn(`Unknown audio type: ${audioType}`)
}
},
[soundEnabled, playNotification, playCelebration, playProgressLoop],
)
function playTts(text: string) {
vscode.postMessage({ type: "playTts", text })
}
useDeepCompareEffect(() => {
// if last message is an ask, show user ask UI
// if user finished a task, then start a new task with a new conversation history since in this moment that the extension is waiting for user response, the user could close the extension and the conversation history would be lost.
// basically as long as a task is active, the conversation history will be persisted
if (lastMessage) {
switch (lastMessage.type) {
case "ask":
// Skip button setup when the ask was already resolved by the backend
// before the state snapshot reached the webview. isAnswered:true is
// stamped on the message atomically with addToClineMessages, so the
// webview never needs to show -- and then clear -- approval buttons.
if (lastMessage.isAnswered) {
break
}
// Reset user response flag when a new ask arrives to allow auto-approval
userRespondedRef.current = false
const isPartial = lastMessage.partial === true
switch (lastMessage.ask) {
case "api_req_failed":
playSound("progress_loop")
setSendingDisabled(true)
setClineAsk("api_req_failed")
setEnableButtons(true)
setPrimaryButtonText(t("chat:retry.title"))
setSecondaryButtonText(t("chat:startNewTask.title"))
break
case "mistake_limit_reached":
playSound("progress_loop")
setSendingDisabled(false)
setClineAsk("mistake_limit_reached")
setEnableButtons(true)
setPrimaryButtonText(t("chat:proceedAnyways.title"))
setSecondaryButtonText(t("chat:startNewTask.title"))
break
case "followup":
setSendingDisabled(isPartial)
setClineAsk("followup")
// setting enable buttons to `false` would trigger a focus grab when
// the text area is enabled which is undesirable.
// We have no buttons for this tool, so no problem having them "enabled"
// to workaround this issue. See #1358.
setEnableButtons(true)
setPrimaryButtonText(undefined)
setSecondaryButtonText(undefined)
break
case "tool":
setSendingDisabled(isPartial)
setClineAsk("tool")
setEnableButtons(!isPartial)
const tool = JSON.parse(lastMessage.text || "{}") as ClineSayTool
switch (tool.tool) {
case "editedExistingFile":
case "appliedDiff":
case "newFileCreated":
if (tool.batchDiffs && Array.isArray(tool.batchDiffs)) {
setPrimaryButtonText(t("chat:edit-batch.approve.title"))
setSecondaryButtonText(t("chat:edit-batch.deny.title"))
} else {
setPrimaryButtonText(t("chat:save.title"))
setSecondaryButtonText(t("chat:reject.title"))
}
break
case "generateImage":
setPrimaryButtonText(t("chat:save.title"))
setSecondaryButtonText(t("chat:reject.title"))
break
case "finishTask":
setPrimaryButtonText(t("chat:completeSubtaskAndReturn"))
setSecondaryButtonText(undefined)
break
case "readFile":
if (tool.batchFiles && Array.isArray(tool.batchFiles)) {
setPrimaryButtonText(t("chat:read-batch.approve.title"))
setSecondaryButtonText(t("chat:read-batch.deny.title"))
} else {
setPrimaryButtonText(t("chat:approve.title"))
setSecondaryButtonText(t("chat:reject.title"))
}
break
case "listFilesTopLevel":
case "listFilesRecursive":
if (tool.batchDirs && Array.isArray(tool.batchDirs)) {
setPrimaryButtonText(t("chat:list-batch.approve.title"))
setSecondaryButtonText(t("chat:list-batch.deny.title"))
} else {
setPrimaryButtonText(t("chat:approve.title"))
setSecondaryButtonText(t("chat:reject.title"))
}
break
default:
setPrimaryButtonText(t("chat:approve.title"))
setSecondaryButtonText(t("chat:reject.title"))
break
}
break
case "command":
setSendingDisabled(isPartial)
setClineAsk("command")
setEnableButtons(!isPartial)
setPrimaryButtonText(t("chat:runCommand.title"))
setSecondaryButtonText(t("chat:reject.title"))
break
case "command_output":
setSendingDisabled(false)
setClineAsk("command_output")
setEnableButtons(true)
setPrimaryButtonText(t("chat:proceedWhileRunning.title"))
setSecondaryButtonText(t("chat:killCommand.title"))
break
case "use_mcp_server":
setSendingDisabled(isPartial)
setClineAsk("use_mcp_server")
setEnableButtons(!isPartial)
setPrimaryButtonText(t("chat:approve.title"))
setSecondaryButtonText(t("chat:reject.title"))
break
case "completion_result":
// Extension waiting for feedback, but we can just present a new task button.
// Kilo-style change inspection/restoration buttons are rendered inline on the completion row.
// Only play celebration sound if there are no queued messages.
if (!isPartial && messageQueue.length === 0) {
playSound("celebration")
}
setSendingDisabled(isPartial)
setClineAsk("completion_result")
setEnableButtons(!isPartial)
setPrimaryButtonText(t("chat:startNewTask.title"))
setSecondaryButtonText(undefined)
break
case "resume_task":
setSendingDisabled(false)
setClineAsk("resume_task")
setEnableButtons(true)
// For completed subtasks, show "Start New Task" instead of "Resume"
// A subtask is considered completed if:
// - It has a parentTaskId AND
// - Its messages contain a completion_result (either ask or say)
const isCompletedSubtask =
currentTaskItem?.parentTaskId &&
messages.some(
(msg) => msg.ask === "completion_result" || msg.say === "completion_result",
)
if (isCompletedSubtask) {
setPrimaryButtonText(t("chat:startNewTask.title"))
setSecondaryButtonText(undefined)
} else {
setPrimaryButtonText(t("chat:resumeTask.title"))
setSecondaryButtonText(t("chat:terminate.title"))
}
setDidClickCancel(false) // special case where we reset the cancel button state
break
case "resume_completed_task":
setSendingDisabled(false)
setClineAsk("resume_completed_task")
setEnableButtons(true)
setPrimaryButtonText(t("chat:startNewTask.title"))
setSecondaryButtonText(undefined)
setDidClickCancel(false)
break
}
break
case "say":
// Don't want to reset since there could be a "say" after
// an "ask" while ask is waiting for response.
switch (lastMessage.say) {
case "api_req_retry_delayed":
case "api_req_rate_limit_wait":
setSendingDisabled(true)
break
case "api_req_started":
// Clear button state when a new API request starts
// This fixes buttons persisting when the task continues
setSendingDisabled(true)
// Note: Do NOT clear selectedImages here. This handler fires
// every time the backend starts an API call, which would wipe
// images the user has pasted while the chat is in progress.
// Images are already cleared in the appropriate user-action
// handlers (handleSendMessage, handlePrimaryButtonClick, etc.).
setClineAsk(undefined)
setEnableButtons(false)
setPrimaryButtonText(undefined)
setSecondaryButtonText(undefined)
break
case "api_req_finished":
case "error":
case "text":
case "command_output":
// A non-partial command_output say means the command
// finished; clear any lingering Proceed/Kill controls
// from the interactive ask so they don't stay up after
// completion.
if (lastMessage.partial !== true && clineAskRef.current === "command_output") {
setClineAsk(undefined)
setEnableButtons(false)
setPrimaryButtonText(undefined)
setSecondaryButtonText(undefined)
}
break
case "mcp_server_request_started":
case "mcp_server_response":
case "completion_result":
break
}
break
}
}
}, [lastMessage, secondLastMessage])
// Update button text when messages change (e.g., completion_result is added) for subtasks in resume_task state
useEffect(() => {
if (clineAsk === "resume_task" && currentTaskItem?.parentTaskId) {
const hasCompletionResult = messages.some(
(msg) => msg.ask === "completion_result" || msg.say === "completion_result",
)
if (hasCompletionResult) {
setPrimaryButtonText(t("chat:startNewTask.title"))
setSecondaryButtonText(undefined)
}
}
}, [clineAsk, currentTaskItem?.parentTaskId, messages, t])
useEffect(() => {
if (messages.length === 0) {
setSendingDisabled(false)
setClineAsk(undefined)
setEnableButtons(false)
setPrimaryButtonText(undefined)
setSecondaryButtonText(undefined)
}
}, [messages.length])
// Reset UI states when task changes. Scroll lifecycle is handled by
// useScrollLifecycle which has its own effect keyed on taskTs.
useEffect(() => {
setExpandedRows({})
everVisibleMessagesTsRef.current.clear()
setCurrentFollowUpTs(null)
setIsCondensing(false)
if (autoApproveTimeoutRef.current) {
clearTimeout(autoApproveTimeoutRef.current)
autoApproveTimeoutRef.current = null
}
userRespondedRef.current = false
}, [task?.ts])
const taskTs = task?.ts
// Request aggregated costs when task changes and has childIds
useEffect(() => {
if (taskTs && currentTaskItem?.childIds && currentTaskItem.childIds.length > 0) {
vscode.postMessage({
type: "getTaskWithAggregatedCosts",
text: currentTaskItem.id,
})
}
}, [taskTs, currentTaskItem?.id, currentTaskItem?.childIds])
useEffect(() => {
if (isHidden) {
everVisibleMessagesTsRef.current.clear()
}
}, [isHidden])
useEffect(() => {
const cache = everVisibleMessagesTsRef.current
return () => {
cache.clear()
}
}, [])
const isStreaming = useMemo(() => {
// Checking clineAsk isn't enough since messages effect may be called
// again for a tool for example, set clineAsk to its value, and if the
// next message is not an ask then it doesn't reset. This is likely due
// to how much more often we're updating messages as compared to before,
// and should be resolved with optimizations as it's likely a rendering
// bug. But as a final guard for now, the cancel button will show if the
// last message is not an ask.
const isLastAsk = !!modifiedMessages.at(-1)?.ask
const isToolCurrentlyAsking =
isLastAsk && clineAsk !== undefined && enableButtons && primaryButtonText !== undefined
if (isToolCurrentlyAsking) {
return false
}
const isLastMessagePartial = modifiedMessages.at(-1)?.partial === true
if (isLastMessagePartial) {
return true
} else {
const lastApiReqStarted = findLast(
modifiedMessages,
(message: ClineMessage) => message.say === "api_req_started",
)
if (
lastApiReqStarted &&
lastApiReqStarted.text !== null &&
lastApiReqStarted.text !== undefined &&
lastApiReqStarted.say === "api_req_started"
) {
const cost = JSON.parse(lastApiReqStarted.text).cost
if (cost === undefined) {
return true // API request has not finished yet.
}
}
}
return false
}, [modifiedMessages, clineAsk, enableButtons, primaryButtonText])
const markFollowUpAsAnswered = useCallback(() => {
const lastFollowUpMessage = messagesRef.current.findLast((msg: ClineMessage) => msg.ask === "followup")
if (lastFollowUpMessage) {
setCurrentFollowUpTs(lastFollowUpMessage.ts)
}
}, [])
const handleChatReset = useCallback(() => {
// Clear any pending auto-approval timeout
if (autoApproveTimeoutRef.current) {
clearTimeout(autoApproveTimeoutRef.current)
autoApproveTimeoutRef.current = null
}
// Reset user response flag for new message
userRespondedRef.current = false
// Only reset message-specific state, preserving mode.
setInputValue("")
setSendingDisabled(true)
setSelectedImages([])
setClineAsk(undefined)
setEnableButtons(false)
// Do not reset mode here as it should persist.
// setPrimaryButtonText(undefined)
// setSecondaryButtonText(undefined)
}, [])
/**
* Handles sending messages to the extension
* @param text - The message text to send
* @param images - Array of image data URLs to send with the message
*/
const handleSendMessage = useCallback(
(text: string, images: string[]) => {
text = text.trim()
if (text || images.length > 0) {
// Intercept when the active provider is retired — show a
// WarningRow instead of sending anything to the backend.
if (apiConfiguration?.apiProvider && isRetiredProvider(apiConfiguration.apiProvider)) {
setShowRetiredProviderWarning(true)
return
}
// Queue message if:
// - Task is busy (sendingDisabled)
// - API request in progress (isStreaming)
// - Queue has items (preserve message order during drain)
// - Command is running (command_output) - user's message should be queued for AI, not sent to terminal
if (
sendingDisabled ||
isStreaming ||
messageQueue.length > 0 ||
clineAskRef.current === "command_output"
) {
try {
console.log("queueMessage", text, images)
vscode.postMessage({ type: "queueMessage", text, images })
setInputValue("")
setSelectedImages([])
} catch (error) {
console.error(
`Failed to queue message: ${error instanceof Error ? error.message : String(error)}`,
)
}
return
}
// Mark that user has responded - this prevents any pending auto-approvals.
userRespondedRef.current = true
if (messagesRef.current.length === 0) {
vscode.postMessage({ type: "newTask", text, images })
} else if (clineAskRef.current) {
if (clineAskRef.current === "followup") {
markFollowUpAsAnswered()
}
// Use clineAskRef.current
switch (
clineAskRef.current // Use clineAskRef.current
) {
case "followup":
case "tool":
case "command": // User can provide feedback to a tool or command use.
case "use_mcp_server":
case "completion_result": // If this happens then the user has feedback for the completion result.
case "resume_task":
case "resume_completed_task":
case "mistake_limit_reached":
vscode.postMessage({
type: "askResponse",
askResponse: "messageResponse",
text,
images,
})
break
// There is no other case that a textfield should be enabled.
}
} else {
// This is a new message in an ongoing task.
vscode.postMessage({ type: "askResponse", askResponse: "messageResponse", text, images })
}
handleChatReset()
}
},
[
handleChatReset,
markFollowUpAsAnswered,
sendingDisabled,
isStreaming,
messageQueue.length,
apiConfiguration?.apiProvider,
], // messagesRef and clineAskRef are stable
)
const handleSetChatBoxMessage = useCallback(
(text: string, images: string[]) => {
// Avoid nested template literals by breaking down the logic
let newValue = text
if (inputValue !== "") {
newValue = inputValue + " " + text
}
setInputValue(newValue)
setSelectedImages([...selectedImages, ...images])
},
[inputValue, selectedImages],
)
const startNewTask = useCallback(() => {
setShowRetiredProviderWarning(false)
vscode.postMessage({ type: "clearTask" })
}, [])
// Handle stop button click from textarea
const handleStopTask = useCallback(() => {
vscode.postMessage({ type: "cancelTask" })
setDidClickCancel(true)
}, [setDidClickCancel])
// Handle enqueue button click from textarea
const handleEnqueueCurrentMessage = useCallback(() => {
const text = inputValue.trim()
if (text || selectedImages.length > 0) {
vscode.postMessage({
type: "queueMessage",
text,
images: selectedImages,
})
setInputValue("")
setSelectedImages([])
}
}, [inputValue, selectedImages])
// Resets the approval button UI to its hidden/disabled state. Shared by the
// manual click handlers and by the backend-driven clearApprovalButtons
// message so auto-approved/denied asks hide the buttons through the same
// pathway a manual click uses.
const clearApprovalButtons = useCallback(() => {
setSendingDisabled(true)
setClineAsk(undefined)
setEnableButtons(false)
setPrimaryButtonText(undefined)
setSecondaryButtonText(undefined)
}, [])
// This logic depends on the useEffect[messages] above to set clineAsk,
// after which buttons are shown and we then send an askResponse to the
// extension.
const handlePrimaryButtonClick = useCallback(
(text?: string, images?: string[]) => {
// Mark that user has responded
userRespondedRef.current = true
const trimmedInput = text?.trim()
switch (clineAsk) {
case "api_req_failed":
case "command":
case "tool":
case "use_mcp_server":
case "mistake_limit_reached":
// Only send text/images if they exist
if (trimmedInput || (images && images.length > 0)) {
vscode.postMessage({
type: "askResponse",
askResponse: "yesButtonClicked",
text: trimmedInput,
images: images,
})
// Clear input state after sending
setInputValue("")
setSelectedImages([])
} else {
vscode.postMessage({ type: "askResponse", askResponse: "yesButtonClicked" })
}
break
case "resume_task":
// For completed subtasks (tasks with a parentTaskId and a completion_result),
// start a new task instead of resuming since the subtask is done
const isCompletedSubtaskForClick =
currentTaskItem?.parentTaskId &&
messagesRef.current.some(
(msg) => msg.ask === "completion_result" || msg.say === "completion_result",
)
if (isCompletedSubtaskForClick) {
startNewTask()
} else {
// Only send text/images if they exist
if (trimmedInput || (images && images.length > 0)) {
vscode.postMessage({
type: "askResponse",
askResponse: "yesButtonClicked",
text: trimmedInput,
images: images,
})
// Clear input state after sending
setInputValue("")
setSelectedImages([])
} else {
vscode.postMessage({ type: "askResponse", askResponse: "yesButtonClicked" })
}
}
break
case "completion_result":
startNewTask()
break
case "resume_completed_task":
// Waiting for feedback, but we can just present a new task button
startNewTask()
break
case "command_output":
vscode.postMessage({ type: "terminalOperation", terminalOperation: "continue" })
break
}
clearApprovalButtons()
},
[clineAsk, startNewTask, currentTaskItem?.parentTaskId, clearApprovalButtons],
)
const handleSecondaryButtonClick = useCallback(
(text?: string, images?: string[]) => {
// Mark that user has responded
userRespondedRef.current = true
const trimmedInput = text?.trim()
if (isStreaming) {
vscode.postMessage({ type: "cancelTask" })
setDidClickCancel(true)
return
}
switch (clineAsk) {
case "api_req_failed":
case "mistake_limit_reached":
case "resume_task":
startNewTask()
break
case "command":
case "tool":
case "use_mcp_server":
// Only send text/images if they exist
if (trimmedInput || (images && images.length > 0)) {
vscode.postMessage({
type: "askResponse",
askResponse: "noButtonClicked",
text: trimmedInput,
images: images,
})
// Clear input state after sending
setInputValue("")
setSelectedImages([])
} else {
// Responds to the API with a "This operation failed" and lets it try again
vscode.postMessage({ type: "askResponse", askResponse: "noButtonClicked" })
}
break
case "command_output":
vscode.postMessage({ type: "terminalOperation", terminalOperation: "abort" })
break
}
clearApprovalButtons()
},
[clineAsk, startNewTask, isStreaming, setDidClickCancel, clearApprovalButtons],
)
const { info: model } = useSelectedModel(apiConfiguration)
const selectImages = useCallback(() => vscode.postMessage({ type: "selectImages" }), [])
const shouldDisableImages = !model?.supportsImages || selectedImages.length >= MAX_IMAGES_PER_MESSAGE
const handleMessage = useCallback(
(e: MessageEvent) => {
const message: ExtensionMessage = e.data
switch (message.type) {
case "action":
switch (message.action!) {
case "didBecomeVisible":
if (!isHidden && !sendingDisabled && !enableButtons) {
textAreaRef.current?.focus()
}
break
case "focusInput":
textAreaRef.current?.focus()
break
}
break
case "selectedImages":
// Only handle selectedImages if it's not for editing context
// When context is "edit", ChatRow will handle the images
if (message.context !== "edit") {
setSelectedImages((prevImages: string[]) =>
appendImages(prevImages, message.images, MAX_IMAGES_PER_MESSAGE),
)
}
break
case "invoke":
switch (message.invoke!) {
case "newChat":
handleChatReset()
break
case "sendMessage":
handleSendMessage(message.text ?? "", message.images ?? [])
break
case "setChatBoxMessage":
handleSetChatBoxMessage(message.text ?? "", message.images ?? [])
break
case "primaryButtonClick":
handlePrimaryButtonClick(message.text ?? "", message.images ?? [])
break
case "secondaryButtonClick":
handleSecondaryButtonClick(message.text ?? "", message.images ?? [])
break
}
break
case "condenseTaskContextStarted":
// Handle both manual and automatic condensation start
// We don't check the task ID because:
// 1. There can only be one active task at a time
// 2. Task switching resets isCondensing to false (see useEffect with task?.ts dependency)
// 3. For new tasks, currentTaskItem may not be populated yet due to async state updates
if (message.text) {
setIsCondensing(true)
// Note: sendingDisabled is only set for manual condensation via handleCondenseContext
// Automatic condensation doesn't disable sending since the task is already running
}
break
case "condenseTaskContextResponse":
// Same reasoning as above - we trust this is for the current task
if (message.text) {
if (isCondensing && sendingDisabled) {
setSendingDisabled(false)
}
setIsCondensing(false)
}
break
case "checkpointInitWarning":
setCheckpointWarning(message.checkpointWarning)
break
case "interactionRequired":
playSound("notification")
break
case "taskWithAggregatedCosts":
if (message.text && message.aggregatedCosts) {
setAggregatedCostsMap((prev) => {
const newMap = new Map(prev)
newMap.set(message.text!, message.aggregatedCosts!)
return newMap
})
}
break
}
// textAreaRef.current is not explicitly required here since React
// guarantees that ref will be stable across re-renders, and we're
// not using its value but its reference.
},
[
isCondensing,
isHidden,
sendingDisabled,
enableButtons,
handleChatReset,
handleSendMessage,
handleSetChatBoxMessage,
handlePrimaryButtonClick,
handleSecondaryButtonClick,
setCheckpointWarning,
playSound,
],
)
useEvent("message", handleMessage)
const visibleMessages = useMemo(() => {
// Pre-compute checkpoint hashes that have associated user messages for O(1) lookup
const userMessageCheckpointHashes = new Set<string>()
modifiedMessages.forEach((msg) => {
if (
msg.say === "user_feedback" &&