-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathchat.tsx
More file actions
1568 lines (1433 loc) · 49.6 KB
/
chat.tsx
File metadata and controls
1568 lines (1433 loc) · 49.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 { RECONNECTION_MESSAGE_DURATION_MS } from '@codebuff/sdk'
import open from 'open'
import { useQueryClient } from '@tanstack/react-query'
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
useTransition,
} from 'react'
import { useShallow } from 'zustand/react/shallow'
import { getAdsEnabled } from './commands/ads'
import { routeUserPrompt, addBashMessageToHistory } from './commands/router'
import { AdBanner } from './components/ad-banner'
import { ChatInputBar } from './components/chat-input-bar'
import { BottomStatusLine } from './components/bottom-status-line'
import { areCreditsRestored } from './components/out-of-credits-banner'
import { LoadPreviousButton } from './components/load-previous-button'
import { MessageWithAgents } from './components/message-with-agents'
import { PendingBashMessage } from './components/pending-bash-message'
import { StatusBar } from './components/status-bar'
import { TopBanner } from './components/top-banner'
import { SLASH_COMMANDS } from './data/slash-commands'
import { useAgentValidation } from './hooks/use-agent-validation'
import { useAskUserBridge } from './hooks/use-ask-user-bridge'
import { authQueryKeys } from './hooks/use-auth-query'
import { useChatInput } from './hooks/use-chat-input'
import { useClaudeQuotaQuery } from './hooks/use-claude-quota-query'
import {
useChatKeyboard,
type ChatKeyboardHandlers,
} from './hooks/use-chat-keyboard'
import { useClipboard } from './hooks/use-clipboard'
import { useConnectionStatus } from './hooks/use-connection-status'
import { useElapsedTime } from './hooks/use-elapsed-time'
import { useGravityAd } from './hooks/use-gravity-ad'
import { useEvent } from './hooks/use-event'
import { useExitHandler } from './hooks/use-exit-handler'
import { useInputHistory } from './hooks/use-input-history'
import { useMessageQueue, type QueuedMessage } from './hooks/use-message-queue'
import { usePublishMutation } from './hooks/use-publish-mutation'
import { useQueueControls } from './hooks/use-queue-controls'
import { useQueueUi } from './hooks/use-queue-ui'
import { useChatScrollbox } from './hooks/use-scroll-management'
import { useSendMessage } from './hooks/use-send-message'
import { useSuggestionEngine } from './hooks/use-suggestion-engine'
import { useTerminalDimensions } from './hooks/use-terminal-dimensions'
import { useTerminalLayout } from './hooks/use-terminal-layout'
import { useTheme } from './hooks/use-theme'
import { useTimeout } from './hooks/use-timeout'
import { useUsageMonitor } from './hooks/use-usage-monitor'
import { WEBSITE_URL } from './login/constants'
import { getProjectRoot } from './project-files'
import { useChatStore } from './state/chat-store'
import { useFeedbackStore } from './state/feedback-store'
import { usePublishStore } from './state/publish-store'
import {
addClipboardPlaceholder,
addPendingImageFromFile,
validateAndAddImage,
} from './utils/add-pending-image'
import { createChatScrollAcceleration } from './utils/chat-scroll-accel'
import { showClipboardMessage } from './utils/clipboard'
import { readClipboardImage } from './utils/clipboard-image'
import { getInputModeConfig } from './utils/input-modes'
import {
type ChatKeyboardState,
createDefaultChatKeyboardState,
} from './utils/keyboard-actions'
import { loadLocalAgents } from './utils/local-agent-registry'
import { buildMessageTree } from './utils/message-tree-utils'
import {
getStatusIndicatorState,
type AuthStatus,
} from './utils/status-indicator-state'
import { getClaudeOAuthStatus } from './utils/claude-oauth'
import { createPasteHandler } from './utils/strings'
import { computeInputLayoutMetrics } from './utils/text-layout'
import { createMarkdownPalette } from './utils/theme-system'
import type { CommandResult } from './commands/command-registry'
import type { MultilineInputHandle } from './components/multiline-input'
import type { ContentBlock } from './types/chat'
import type { SendMessageFn } from './types/contracts/send-message'
import type { User } from './utils/auth'
import type { AgentMode } from './utils/constants'
import type { FileTreeNode } from '@codebuff/common/util/file'
import type { ScrollBoxRenderable } from '@opentui/core'
import type { UseMutationResult } from '@tanstack/react-query'
import type { Dispatch, SetStateAction } from 'react'
export const Chat = ({
headerContent,
initialPrompt,
agentId,
fileTree,
inputRef,
setIsAuthenticated,
setUser,
logoutMutation,
continueChat,
continueChatId,
authStatus,
initialMode,
gitRoot,
onSwitchToGitRoot,
}: {
headerContent: React.ReactNode
initialPrompt: string | null
agentId?: string
fileTree: FileTreeNode[]
inputRef: React.MutableRefObject<MultilineInputHandle | null>
setIsAuthenticated: Dispatch<SetStateAction<boolean | null>>
setUser: Dispatch<SetStateAction<User | null>>
logoutMutation: UseMutationResult<boolean, Error, void, unknown>
continueChat: boolean
continueChatId?: string
authStatus: AuthStatus
initialMode?: AgentMode
gitRoot?: string | null
onSwitchToGitRoot?: () => void
}) => {
const scrollRef = useRef<ScrollBoxRenderable | null>(null)
const [hasOverflow, setHasOverflow] = useState(false)
const hasOverflowRef = useRef(false)
// Message pagination - show last N messages with "Load previous" button
const MESSAGE_BATCH_SIZE = 15
const [visibleMessageCount, setVisibleMessageCount] =
useState(MESSAGE_BATCH_SIZE)
const queryClient = useQueryClient()
const [, startUiTransition] = useTransition()
const [showReconnectionMessage, setShowReconnectionMessage] = useState(false)
const reconnectionTimeout = useTimeout()
const [forceFileOnlyMentions, setForceFileOnlyMentions] = useState(false)
const { separatorWidth, terminalWidth, terminalHeight } =
useTerminalDimensions()
const { height: heightLayout, width: widthLayout } = useTerminalLayout()
const isCompactHeight = heightLayout.is('xs')
const isNarrowWidth = widthLayout.is('xs')
const messageAvailableWidth = separatorWidth
const theme = useTheme()
const markdownPalette = useMemo(() => createMarkdownPalette(theme), [theme])
const { validate: validateAgents } = useAgentValidation()
// Subscribe to ask_user bridge to trigger form display
useAskUserBridge()
// Monitor usage data and auto-show banner when thresholds are crossed
useUsageMonitor()
const {
inputValue,
cursorPosition,
lastEditDueToNav,
setInputValue,
inputFocused,
setInputFocused,
slashSelectedIndex,
setSlashSelectedIndex,
agentSelectedIndex,
setAgentSelectedIndex,
streamingAgents: rawStreamingAgents,
focusedAgentId,
setFocusedAgentId,
messages,
setMessages,
activeSubagents,
isChainInProgress,
agentMode,
setAgentMode,
toggleAgentMode,
isRetrying,
} = useChatStore(
useShallow((store) => ({
inputValue: store.inputValue,
cursorPosition: store.cursorPosition,
lastEditDueToNav: store.lastEditDueToNav,
setInputValue: store.setInputValue,
inputFocused: store.inputFocused,
setInputFocused: store.setInputFocused,
slashSelectedIndex: store.slashSelectedIndex,
setSlashSelectedIndex: store.setSlashSelectedIndex,
agentSelectedIndex: store.agentSelectedIndex,
setAgentSelectedIndex: store.setAgentSelectedIndex,
streamingAgents: store.streamingAgents,
focusedAgentId: store.focusedAgentId,
setFocusedAgentId: store.setFocusedAgentId,
messages: store.messages,
setMessages: store.setMessages,
activeSubagents: store.activeSubagents,
isChainInProgress: store.isChainInProgress,
agentMode: store.agentMode,
setAgentMode: store.setAgentMode,
toggleAgentMode: store.toggleAgentMode,
isRetrying: store.isRetrying,
})),
)
// Stabilize streamingAgents reference - only create new Set when content changes
const streamingAgentsKey = useMemo(
() => Array.from(rawStreamingAgents).sort().join(','),
[rawStreamingAgents],
)
const streamingAgents = useMemo(
() => rawStreamingAgents,
[streamingAgentsKey],
)
const pendingBashMessages = useChatStore((state) => state.pendingBashMessages)
// Refs for tracking state across renders
const activeAgentStreamsRef = useRef<number>(0)
const isChainInProgressRef = useRef<boolean>(isChainInProgress)
const activeSubagentsRef = useRef<Set<string>>(activeSubagents)
const abortControllerRef = useRef<AbortController | null>(null)
const sendMessageRef = useRef<SendMessageFn>()
const { statusMessage } = useClipboard()
const handleReconnection = useCallback(
(isInitialConnection: boolean) => {
// Invalidate auth queries so we refetch with current credentials
queryClient.invalidateQueries({ queryKey: authQueryKeys.all })
startUiTransition(() => {
if (!isInitialConnection) {
setShowReconnectionMessage(true)
reconnectionTimeout.setTimeout(
'reconnection-message',
() => {
startUiTransition(() => {
setShowReconnectionMessage(false)
})
},
RECONNECTION_MESSAGE_DURATION_MS,
)
}
})
},
[queryClient, reconnectionTimeout, startUiTransition],
)
const isConnected = useConnectionStatus(handleReconnection)
const mainAgentTimer = useElapsedTime()
const { ad, reportActivity } = useGravityAd()
const timerStartTime = mainAgentTimer.startTime
// Set initial mode from CLI flag on mount
useEffect(() => {
if (initialMode) {
setAgentMode(initialMode)
}
}, [initialMode, setAgentMode])
// Sync refs with state
useEffect(() => {
isChainInProgressRef.current = isChainInProgress
}, [isChainInProgress])
useEffect(() => {
activeSubagentsRef.current = activeSubagents
}, [activeSubagents])
// Reset visible message count when messages are cleared or conversation changes
useEffect(() => {
if (messages.length <= MESSAGE_BATCH_SIZE) {
setVisibleMessageCount(MESSAGE_BATCH_SIZE)
}
}, [messages.length])
const isUserCollapsingRef = useRef<boolean>(false)
const handleCollapseToggle = useCallback(
(id: string) => {
// Set flag to prevent auto-scroll during user-initiated collapse
isUserCollapsingRef.current = true
// Find and toggle the block's isCollapsed property
setMessages((prevMessages) => {
return prevMessages.map((message) => {
// Handle agent variant messages
if (message.variant === 'agent' && message.id === id) {
const wasCollapsed = message.metadata?.isCollapsed ?? false
return {
...message,
metadata: {
...message.metadata,
isCollapsed: !wasCollapsed,
userOpened: wasCollapsed, // Mark as user-opened if expanding
},
}
}
// Handle blocks within messages
if (!message.blocks) return message
const updateBlocksRecursively = (
blocks: ContentBlock[],
): ContentBlock[] => {
let foundTarget = false
const result = blocks.map((block) => {
// Handle thinking blocks - just match by thinkingId
if (block.type === 'text' && block.thinkingId === id) {
foundTarget = true
const wasCollapsed = block.isCollapsed ?? false
return {
...block,
isCollapsed: !wasCollapsed,
userOpened: wasCollapsed, // Mark as user-opened if expanding
}
}
// Handle agent blocks
if (block.type === 'agent' && block.agentId === id) {
foundTarget = true
const wasCollapsed = block.isCollapsed ?? false
return {
...block,
isCollapsed: !wasCollapsed,
userOpened: wasCollapsed, // Mark as user-opened if expanding
}
}
// Handle tool blocks
if (block.type === 'tool' && block.toolCallId === id) {
foundTarget = true
const wasCollapsed = block.isCollapsed ?? false
return {
...block,
isCollapsed: !wasCollapsed,
userOpened: wasCollapsed, // Mark as user-opened if expanding
}
}
// Handle agent-list blocks
if (block.type === 'agent-list' && block.id === id) {
foundTarget = true
const wasCollapsed = block.isCollapsed ?? false
return {
...block,
isCollapsed: !wasCollapsed,
userOpened: wasCollapsed, // Mark as user-opened if expanding
}
}
// Recursively update nested blocks inside agent blocks
if (block.type === 'agent' && block.blocks) {
const updatedBlocks = updateBlocksRecursively(block.blocks)
// Only create new block if nested blocks actually changed
if (updatedBlocks !== block.blocks) {
foundTarget = true
return {
...block,
blocks: updatedBlocks,
}
}
}
return block
})
// Return original array reference if nothing changed
return foundTarget ? result : blocks
}
return {
...message,
blocks: updateBlocksRecursively(message.blocks),
}
})
})
// Reset flag after state update completes
setTimeout(() => {
isUserCollapsingRef.current = false
}, 0)
},
[setMessages],
)
const isUserCollapsing = useCallback(() => {
return isUserCollapsingRef.current
}, [])
const { scrollToLatest, scrollboxProps, isAtBottom } = useChatScrollbox(
scrollRef,
messages,
isUserCollapsing,
)
// Check if content has overflowed and needs scrolling
useEffect(() => {
const scrollbox = scrollRef.current
if (!scrollbox) return
const checkOverflow = () => {
const contentHeight = scrollbox.scrollHeight
const viewportHeight = scrollbox.viewport.height
const isOverflowing = contentHeight > viewportHeight
// Only update state if overflow status actually changed
if (hasOverflowRef.current !== isOverflowing) {
hasOverflowRef.current = isOverflowing
setHasOverflow(isOverflowing)
}
}
// Check initially and whenever scroll state changes
checkOverflow()
scrollbox.verticalScrollBar.on('change', checkOverflow)
return () => {
scrollbox.verticalScrollBar.off('change', checkOverflow)
}
}, [])
const inertialScrollAcceleration = useMemo(
() => createChatScrollAcceleration(),
[],
)
const appliedScrollboxProps = inertialScrollAcceleration
? { ...scrollboxProps, scrollAcceleration: inertialScrollAcceleration }
: scrollboxProps
const localAgents = useMemo(() => loadLocalAgents(agentMode), [agentMode])
const inputMode = useChatStore((state) => state.inputMode)
const setInputMode = useChatStore((state) => state.setInputMode)
const askUserState = useChatStore((state) => state.askUserState)
// Filter slash commands based on current ads state - only show the option that changes state
const filteredSlashCommands = useMemo(() => {
const adsEnabled = getAdsEnabled()
return SLASH_COMMANDS.filter((cmd) => {
if (cmd.id === 'ads:enable') return !adsEnabled
if (cmd.id === 'ads:disable') return adsEnabled
return true
})
}, [inputValue]) // Re-evaluate when input changes (user may have just toggled)
const {
slashContext,
mentionContext,
slashMatches,
agentMatches,
fileMatches,
slashSuggestionItems,
agentSuggestionItems,
fileSuggestionItems,
} = useSuggestionEngine({
disableAgentSuggestions: forceFileOnlyMentions || inputMode !== 'default',
inputValue: inputMode === 'bash' ? '' : inputValue,
cursorPosition,
slashCommands: filteredSlashCommands,
localAgents,
fileTree,
currentAgentMode: agentMode,
})
useEffect(() => {
if (!mentionContext.active) {
setForceFileOnlyMentions(false)
}
}, [mentionContext.active])
// Reset suggestion menu indexes when context changes
useEffect(() => {
if (!slashContext.active) {
setSlashSelectedIndex(0)
return
}
setSlashSelectedIndex(0)
}, [slashContext.active, slashContext.query, setSlashSelectedIndex])
useEffect(() => {
if (slashMatches.length > 0 && slashSelectedIndex >= slashMatches.length) {
setSlashSelectedIndex(slashMatches.length - 1)
}
if (slashMatches.length === 0 && slashSelectedIndex !== 0) {
setSlashSelectedIndex(0)
}
}, [slashMatches.length, slashSelectedIndex, setSlashSelectedIndex])
useEffect(() => {
if (!mentionContext.active) {
setAgentSelectedIndex(0)
return
}
setAgentSelectedIndex(0)
}, [mentionContext.active, mentionContext.query, setAgentSelectedIndex])
useEffect(() => {
const totalMatches = agentMatches.length + fileMatches.length
if (totalMatches > 0 && agentSelectedIndex >= totalMatches) {
setAgentSelectedIndex(totalMatches - 1)
}
if (totalMatches === 0 && agentSelectedIndex !== 0) {
setAgentSelectedIndex(0)
}
}, [
agentMatches.length,
fileMatches.length,
agentSelectedIndex,
setAgentSelectedIndex,
])
const openFileMenuWithTab = useCallback(() => {
const safeCursor = Math.max(0, Math.min(cursorPosition, inputValue.length))
let wordStart = safeCursor
while (wordStart > 0 && !/\s/.test(inputValue[wordStart - 1])) {
wordStart--
}
const before = inputValue.slice(0, wordStart)
const wordAtCursor = inputValue.slice(wordStart, safeCursor)
const after = inputValue.slice(safeCursor)
const mentionWord = wordAtCursor.startsWith('@')
? wordAtCursor
: `@${wordAtCursor}`
const text = `${before}${mentionWord}${after}`
const nextCursor = before.length + mentionWord.length
setInputValue({
text,
cursorPosition: nextCursor,
lastEditDueToNav: false,
})
setForceFileOnlyMentions(true)
}, [cursorPosition, inputValue, setInputValue])
const { saveToHistory, navigateUp, navigateDown } = useInputHistory(
inputValue,
setInputValue,
{ inputMode, setInputMode },
)
const {
queuedMessages,
streamStatus,
queuePaused,
streamMessageIdRef,
addToQueue,
stopStreaming,
setStreamStatus,
setCanProcessQueue,
pauseQueue,
resumeQueue,
clearQueue,
isQueuePausedRef,
} = useMessageQueue(
(message: QueuedMessage) =>
sendMessageRef.current?.({
content: message.content,
agentMode,
images: message.images,
}) ?? Promise.resolve(),
isChainInProgressRef,
activeAgentStreamsRef,
)
const {
queuedCount,
shouldShowQueuePreview,
queuePreviewTitle,
pausedQueueText,
inputPlaceholder,
} = useQueueUi({
queuePaused,
queuedMessages,
separatorWidth,
terminalWidth,
})
const { handleCtrlC: baseHandleCtrlC, nextCtrlCWillExit } = useExitHandler({
inputValue,
setInputValue,
})
const { handleCtrlC, ensureQueueActiveBeforeSubmit } = useQueueControls({
queuePaused,
queuedCount,
clearQueue,
resumeQueue,
inputHasText: Boolean(inputValue),
baseHandleCtrlC,
})
// Derive boolean flags from streamStatus for convenience
const isWaitingForResponse = streamStatus === 'waiting'
const isStreaming = streamStatus !== 'idle'
// When streaming completes, flush any pending bash commands into history (ghost mode only)
// Non-ghost mode commands are already in history and will be cleared when user sends next message
useEffect(() => {
if (
!isStreaming &&
!streamMessageIdRef.current &&
!isChainInProgressRef.current &&
pendingBashMessages.length > 0
) {
// Only flush ghost mode commands (those not already added to history) to UI
const ghostModeMessages = pendingBashMessages.filter(
(msg) => !msg.isRunning && !msg.addedToHistory,
)
// Add ghost mode messages to UI history
for (const msg of ghostModeMessages) {
addBashMessageToHistory({
command: msg.command,
stdout: msg.stdout,
stderr: msg.stderr ?? null,
exitCode: msg.exitCode,
cwd: msg.cwd || process.cwd(),
setMessages,
})
}
// Mark ghost mode messages as added to history (so they don't show as ghost UI)
// but keep them in pendingBashMessages so they get sent to LLM with next user message
if (ghostModeMessages.length > 0) {
const ghostIds = new Set(ghostModeMessages.map((m) => m.id))
useChatStore.setState((state) => ({
pendingBashMessages: state.pendingBashMessages.map((m) =>
ghostIds.has(m.id) ? { ...m, addedToHistory: true } : m,
),
}))
}
}
}, [isStreaming, pendingBashMessages, setMessages])
// Timer events are currently tracked but not used for UI updates
// Future: Could be used for analytics or debugging
const { sendMessage, clearMessages } = useSendMessage({
inputRef,
activeSubagentsRef,
isChainInProgressRef,
setStreamStatus,
setCanProcessQueue,
abortControllerRef,
agentId,
onBeforeMessageSend: validateAgents,
mainAgentTimer,
scrollToLatest,
onTimerEvent: () => {}, // No-op for now
isQueuePausedRef,
resumeQueue,
continueChat,
continueChatId,
})
sendMessageRef.current = sendMessage
const onSubmitPrompt = useEvent(
async (
content: string,
mode: AgentMode,
options?: { preserveInputValue?: boolean },
) => {
ensureQueueActiveBeforeSubmit()
const preserveInput = options?.preserveInputValue === true
const previousInputValue = preserveInput
? (() => {
const {
inputValue: text,
cursorPosition,
lastEditDueToNav,
} = useChatStore.getState()
return { text, cursorPosition, lastEditDueToNav }
})()
: null
const preservedPendingImages =
preserveInput && useChatStore.getState().pendingImages.length > 0
? [...useChatStore.getState().pendingImages]
: null
if (preserveInput && preservedPendingImages) {
useChatStore.getState().clearPendingImages()
}
try {
const result = await routeUserPrompt({
abortControllerRef,
agentMode: mode,
inputRef,
inputValue: content,
isChainInProgressRef,
isStreaming,
logoutMutation,
streamMessageIdRef,
addToQueue,
clearMessages,
saveToHistory,
scrollToLatest,
sendMessage,
setCanProcessQueue,
setInputFocused,
setInputValue,
setIsAuthenticated,
setMessages,
setUser,
stopStreaming,
})
return result
} finally {
if (previousInputValue) {
setInputValue({
text: previousInputValue.text,
cursorPosition: previousInputValue.cursorPosition,
lastEditDueToNav: previousInputValue.lastEditDueToNav,
})
}
if (preserveInput && preservedPendingImages) {
const currentPending = useChatStore.getState().pendingImages
if (currentPending.length === 0) {
useChatStore.setState((state) => {
state.pendingImages = preservedPendingImages
})
}
}
}
},
)
// Handle followup suggestion clicks
useEffect(() => {
const handleFollowupClick = (event: Event) => {
const customEvent = event as CustomEvent<{
prompt: string
index: number
toolCallId: string
}>
const { prompt, index, toolCallId } = customEvent.detail
// Mark this followup as clicked (persisted per toolCallId)
useChatStore.getState().markFollowupClicked(toolCallId, index)
// Send the followup prompt directly, preserving the user's current input
void onSubmitPrompt(prompt, agentMode, {
preserveInputValue: true,
})
}
globalThis.addEventListener('codebuff:send-followup', handleFollowupClick)
return () => {
globalThis.removeEventListener(
'codebuff:send-followup',
handleFollowupClick,
)
}
}, [onSubmitPrompt, agentMode])
// handleSlashItemClick is defined later after feedback/publish stores are available
const handleMentionItemClick = useCallback(
(index: number) => {
if (mentionContext.startIndex < 0) return
let replacement: string
if (index < agentMatches.length) {
const selected = agentMatches[index]
if (!selected) return
replacement = `@${selected.displayName} `
} else {
const fileIndex = index - agentMatches.length
const selectedFile = fileMatches[fileIndex]
if (!selectedFile) return
replacement = `@${selectedFile.filePath} `
}
const before = inputValue.slice(0, mentionContext.startIndex)
const after = inputValue.slice(
mentionContext.startIndex + 1 + mentionContext.query.length,
)
setInputValue({
text: before + replacement + after,
cursorPosition: before.length + replacement.length,
lastEditDueToNav: false,
})
setAgentSelectedIndex(0)
},
[
mentionContext,
agentMatches,
fileMatches,
inputValue,
setInputValue,
setAgentSelectedIndex,
],
)
const { inputWidth, handleBuildFast, handleBuildMax } = useChatInput({
setInputValue,
agentMode,
setAgentMode,
separatorWidth,
initialPrompt,
onSubmitPrompt,
isCompactHeight,
isNarrowWidth,
})
const {
feedbackMode,
openFeedbackForMessage,
closeFeedback,
saveCurrentInput,
restoreSavedInput,
setFeedbackText,
} = useFeedbackStore(
useShallow((state) => ({
feedbackMode: state.feedbackMode,
openFeedbackForMessage: state.openFeedbackForMessage,
closeFeedback: state.closeFeedback,
saveCurrentInput: state.saveCurrentInput,
restoreSavedInput: state.restoreSavedInput,
setFeedbackText: state.setFeedbackText,
})),
)
const { publishMode, openPublishMode, closePublish, preSelectAgents } =
usePublishStore(
useShallow((state) => ({
publishMode: state.publishMode,
openPublishMode: state.openPublishMode,
closePublish: state.closePublish,
preSelectAgents: state.preSelectAgents,
})),
)
const publishMutation = usePublishMutation()
const handleCommandResult = useCallback(
(result?: CommandResult) => {
if (!result) return
if (result.openFeedbackMode) {
// Save the feedback text that was set by the command handler before opening feedback mode
const { feedbackText, feedbackCursor } = useFeedbackStore.getState()
saveCurrentInput('', 0)
openFeedbackForMessage(null)
// Restore the prefilled text after openFeedbackForMessage resets it
if (feedbackText) {
useFeedbackStore.getState().setFeedbackText(feedbackText)
useFeedbackStore.getState().setFeedbackCursor(feedbackCursor)
}
}
if (result.openPublishMode) {
if (result.preSelectAgents && result.preSelectAgents.length > 0) {
// preSelectAgents already sets publishMode: true, so don't call openPublishMode
// which would reset the selectedAgentIds
preSelectAgents(result.preSelectAgents)
} else {
openPublishMode()
}
}
},
[
saveCurrentInput,
openFeedbackForMessage,
openPublishMode,
preSelectAgents,
],
)
// Click handler for slash menu items - executes command immediately
const handleSlashItemClick = useCallback(
async (index: number) => {
const selected = slashMatches[index]
if (!selected) return
// Execute the selected slash command immediately
const commandString = `/${selected.id}`
setSlashSelectedIndex(0)
const result = await onSubmitPrompt(commandString, agentMode)
handleCommandResult(result)
},
[
slashMatches,
setSlashSelectedIndex,
onSubmitPrompt,
agentMode,
handleCommandResult,
],
)
const inputValueRef = useRef(inputValue)
const cursorPositionRef = useRef(cursorPosition)
useEffect(() => {
inputValueRef.current = inputValue
}, [inputValue])
// Report activity on input changes for ad rotation (debounced via separate effect)
const lastReportedActivityRef = useRef<number>(0)
useEffect(() => {
const now = Date.now()
// Throttle to max once per second to avoid excessive calls
if (now - lastReportedActivityRef.current > 1000) {
lastReportedActivityRef.current = now
reportActivity()
}
}, [inputValue, reportActivity])
useEffect(() => {
cursorPositionRef.current = cursorPosition
}, [cursorPosition])
const handleOpenFeedbackForMessage = useCallback(
(
id: string | null,
options?: {
category?: string
footerMessage?: string
errors?: Array<{ id: string; message: string }>
},
) => {
saveCurrentInput(inputValueRef.current, cursorPositionRef.current)
openFeedbackForMessage(id, options)
},
[saveCurrentInput, openFeedbackForMessage],
)
const handleMessageFeedback = useCallback(
(
id: string,
options?: {
category?: string
footerMessage?: string
errors?: Array<{ id: string; message: string }>
},
) => {
handleOpenFeedbackForMessage(id, options)
},
[handleOpenFeedbackForMessage],
)
const handleExitFeedback = useCallback(() => {
const { value, cursor } = restoreSavedInput()
setInputValue({
text: value,
cursorPosition: cursor,
lastEditDueToNav: false,
})
setInputFocused(true)
}, [restoreSavedInput, setInputValue, setInputFocused])
const handleCloseFeedback = useCallback(() => {
closeFeedback()
handleExitFeedback()
}, [closeFeedback, handleExitFeedback])
const handleExitPublish = useCallback(() => {
closePublish()
setInputFocused(true)
}, [closePublish, setInputFocused])
const handlePublish = useCallback(
async (agentIds: string[]) => {
await publishMutation.mutateAsync(agentIds)
},
[publishMutation],
)
// Ensure bracketed paste events target the active chat input
useEffect(() => {
if (feedbackMode) {
inputRef.current?.focus()
return
}
if (!askUserState) {
inputRef.current?.focus()
}
}, [feedbackMode, askUserState, inputRef])
const handleSubmit = useCallback(async () => {
// Report activity for ad rotation
reportActivity()
const result = await onSubmitPrompt(inputValue, agentMode)
handleCommandResult(result)
}, [
onSubmitPrompt,
inputValue,
agentMode,
handleCommandResult,
reportActivity,
])
const totalMentionMatches = agentMatches.length + fileMatches.length