-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathChat.jsx
More file actions
1637 lines (1552 loc) · 69 KB
/
Copy pathChat.jsx
File metadata and controls
1637 lines (1552 loc) · 69 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 { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import { useParams, useOutletContext, useNavigate, useLocation } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { fromState } from '../utils/editorNav'
import { useChat } from '../hooks/useChat'
import ModelSelector from '../components/ModelSelector'
import { renderMarkdown, highlightAll, enhanceCodeBlocks } from '../utils/markdown'
import { extractCodeArtifacts, renderMarkdownWithArtifacts } from '../utils/artifacts'
import CanvasPanel from '../components/CanvasPanel'
import Toggle from '../components/Toggle'
import { fileToBase64, modelsApi, mcpApi } from '../utils/api'
import { CAP_CHAT } from '../utils/capabilities'
import { useMCPClient } from '../hooks/useMCPClient'
import MCPAppFrame from '../components/MCPAppFrame'
import UnifiedMCPDropdown from '../components/UnifiedMCPDropdown'
import { loadClientMCPServers } from '../utils/mcpClientStorage'
import ConfirmDialog from '../components/ConfirmDialog'
import ChatsMenu from '../components/ChatsMenu'
import { useAuth } from '../context/AuthContext'
import { useOperations } from '../hooks/useOperations'
import { relativeTime } from '../utils/format'
import { copyToClipboard } from '../utils/clipboard'
const FOCUS_MODE_KEY = 'localai_chat_focus_mode'
function getLastMessagePreview(chat) {
if (!chat.history || chat.history.length === 0) return ''
for (let i = chat.history.length - 1; i >= 0; i--) {
const msg = chat.history[i]
if (msg.role === 'user' || msg.role === 'assistant') {
const text = typeof msg.content === 'string' ? msg.content : msg.content?.[0]?.text || ''
return text.slice(0, 40).replace(/\n/g, ' ')
}
}
return ''
}
function serializeChatAsMarkdown(chat) {
let md = `# ${chat.name}\n\n`
md += `Model: ${chat.model || 'Unknown'}\n`
md += `Date: ${new Date(chat.createdAt).toLocaleString()}\n\n---\n\n`
for (const msg of chat.history) {
if (msg.role === 'user') {
const text = typeof msg.content === 'string' ? msg.content : msg.content?.[0]?.text || ''
md += `## User\n\n${text}\n\n`
} else if (msg.role === 'assistant') {
md += `## Assistant\n\n${msg.content}\n\n`
} else if (msg.role === 'thinking' || msg.role === 'reasoning') {
md += `<details><summary>Thinking</summary>\n\n${msg.content}\n\n</details>\n\n`
}
}
return md
}
function downloadChatAsMarkdown(chat) {
const blob = new Blob([serializeChatAsMarkdown(chat)], { type: 'text/markdown' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${chat.name.replace(/[^a-zA-Z0-9]/g, '_')}.md`
a.click()
URL.revokeObjectURL(url)
}
function formatToolContent(raw) {
try {
const data = JSON.parse(raw)
const name = data.name || 'unknown'
let params = data.arguments || data.input || data.result || data.parameters || {}
if (typeof params === 'string') {
try { params = JSON.parse(params) } catch (_) { /* keep as string */ }
}
const entries = typeof params === 'object' && params !== null ? Object.entries(params) : []
return { name, entries, fallback: null }
} catch (_e) {
return { name: null, entries: [], fallback: raw }
}
}
function ToolParams({ entries, fallback }) {
if (fallback) {
return <span className="chat-activity-item-text">{fallback}</span>
}
if (entries.length === 0) return null
return (
<div className="chat-activity-params">
{entries.map(([k, v]) => {
const val = typeof v === 'string' ? v : JSON.stringify(v, null, 2)
const isLong = val.length > 120
return (
<div key={k} className="chat-activity-param">
<span className="chat-activity-param-key">{k}:</span>
<span className={`chat-activity-param-val${isLong ? ' chat-activity-param-val-long' : ''}`}>{val}</span>
</div>
)
})}
</div>
)
}
function ActivityGroup({ items, updateChatSettings, activeChat, getClientForTool }) {
const { t } = useTranslation('chat')
const [expanded, setExpanded] = useState(false)
const contentRef = useRef(null)
useEffect(() => {
if (expanded && contentRef.current) highlightAll(contentRef.current)
}, [expanded])
if (!items || items.length === 0) return null
// Separate out tool_result items that have appUI — they render outside the collapsed group
const appUIItems = items.filter(item => item.role === 'tool_result' && item.appUI)
const regularItems = items.filter(item => !(item.role === 'tool_result' && item.appUI))
const labels = regularItems.map(item => {
if (item.role === 'thinking' || item.role === 'reasoning') return t('activity.thought')
if (item.role === 'tool_call') {
try { return JSON.parse(item.content)?.name || t('activity.tool') } catch (_e) { return t('activity.tool') }
}
if (item.role === 'tool_result') {
try { return t('activity.toolResult', { name: JSON.parse(item.content)?.name || t('activity.tool') }) } catch (_e) { return t('activity.result') }
}
return item.role
})
const summary = labels.join(' → ')
return (
<>
{regularItems.length > 0 && (
<div className="chat-message chat-message-assistant">
<div className="chat-message-avatar">
<i className="fas fa-cogs" />
</div>
<div className="chat-activity-group">
<button className="chat-activity-toggle" onClick={() => setExpanded(!expanded)}>
<span className="chat-activity-summary">{summary}</span>
<i className={`fas fa-chevron-${expanded ? 'up' : 'down'}`} />
</button>
{expanded && (
<div className="chat-activity-details" ref={contentRef}>
{regularItems.map((item, idx) => {
if (item.role === 'thinking' || item.role === 'reasoning') {
return (
<div key={idx} className="chat-activity-item chat-activity-thinking">
<span className="chat-activity-item-label">{t('activity.thought')}</span>
<div className="chat-activity-item-content"
dangerouslySetInnerHTML={{ __html: renderMarkdown(item.content || '') }} />
</div>
)
}
const isCall = item.role === 'tool_call'
const parsed = formatToolContent(item.content)
return (
<div key={idx} className={`chat-activity-item ${isCall ? 'chat-activity-tool-call' : 'chat-activity-tool-result'}`}>
<span className="chat-activity-item-label">{labels[idx]}</span>
<ToolParams entries={parsed.entries} fallback={parsed.fallback} />
</div>
)
})}
</div>
)}
</div>
</div>
)}
{appUIItems.map((item, idx) => (
<div key={`appui-${idx}`} className="chat-message chat-message-assistant">
<div className="chat-message-avatar">
<i className="fas fa-puzzle-piece" />
</div>
<div className="chat-message-bubble">
<span className="chat-message-model">{item.appUI.toolName}</span>
<MCPAppFrame
toolName={item.appUI.toolName}
toolInput={item.appUI.toolInput}
toolResult={item.appUI.toolResult}
mcpClient={getClientForTool?.(item.appUI.toolName) || null}
toolDefinition={item.appUI.toolDefinition}
appHtml={item.appUI.html}
resourceMeta={item.appUI.meta}
/>
</div>
</div>
))}
</>
)
}
function StreamingActivity({ reasoning, toolCalls, hasResponse }) {
const { t } = useTranslation('chat')
const hasContent = reasoning || (toolCalls && toolCalls.length > 0)
if (!hasContent) return null
const contentRef = useRef(null)
const [manualCollapse, setManualCollapse] = useState(null)
// Auto-expand while thinking or tool-calling, auto-collapse when response starts
const autoExpanded = (reasoning || (toolCalls && toolCalls.length > 0)) && !hasResponse
const expanded = manualCollapse !== null ? !manualCollapse : autoExpanded
// Scroll to bottom of thinking content as it streams
useEffect(() => {
if (expanded && contentRef.current) {
contentRef.current.scrollTop = contentRef.current.scrollHeight
}
}, [reasoning, expanded])
// Reset manual override when streaming state changes significantly
useEffect(() => {
setManualCollapse(null)
}, [hasResponse])
const lastTool = toolCalls && toolCalls.length > 0 ? toolCalls[toolCalls.length - 1] : null
const label = reasoning
? t('activity.thinking')
: lastTool
? (lastTool.type === 'tool_call' ? lastTool.name : t('activity.toolResult', { name: lastTool.name }))
: ''
return (
<div className="chat-message chat-message-assistant">
<div className="chat-message-avatar">
<i className="fas fa-cogs" />
</div>
<div className="chat-activity-group chat-activity-streaming">
<button className="chat-activity-toggle" onClick={() => setManualCollapse(expanded)}>
<span className={`chat-activity-summary${!expanded ? ' chat-activity-shimmer' : ''}`}>
{label}
</span>
<i className={`fas fa-chevron-${expanded ? 'up' : 'down'}`} />
</button>
{expanded && reasoning && (
<div className="chat-activity-details">
<div className="chat-activity-item chat-activity-thinking">
<div className="chat-activity-item-content chat-activity-live" ref={contentRef}
dangerouslySetInnerHTML={{ __html: renderMarkdown(reasoning) }} />
</div>
</div>
)}
{expanded && toolCalls && toolCalls.length > 0 && (
<div className="chat-activity-details">
{toolCalls.map((tc, idx) => {
if (tc.type === 'tool_result') {
return (
<div key={idx} className="chat-activity-item chat-activity-tool-result">
<span className="chat-activity-item-label">{t('activity.toolResult', { name: tc.name })}</span>
<div className="chat-activity-item-content"
dangerouslySetInnerHTML={{ __html: renderMarkdown(tc.result || '') }} />
</div>
)
}
const parsed = formatToolContent(JSON.stringify(tc, null, 2))
return (
<div key={idx} className="chat-activity-item chat-activity-tool-call">
<span className="chat-activity-item-label">{tc.name || tc.type}</span>
<ToolParams entries={parsed.entries} fallback={parsed.fallback} />
</div>
)
})}
</div>
)}
</div>
</div>
)
}
function UserMessageContent({ content, files }) {
const text = typeof content === 'string' ? content : content?.[0]?.text || ''
return (
<>
<div className="wrap-anywhere">{text}</div>
{files && files.length > 0 && (
<div className="chat-message-files">
{files.map((f, i) => (
<span key={i} className="chat-file-inline">
<i className={`fas ${f.type === 'image' ? 'fa-image' : f.type === 'audio' ? 'fa-headphones' : f.type === 'video' ? 'fa-film' : 'fa-file'}`} />
{f.name}
</span>
))}
</div>
)}
{Array.isArray(content) && content.filter(c => c.type === 'image_url').map((img, i) => (
<img key={i} src={img.image_url.url} alt="attached" className="chat-inline-image" />
))}
{Array.isArray(content) && content.filter(c => c.type === 'video_url').map((vid, i) => (
<video key={i} src={vid.video_url.url} controls className="chat-inline-video" />
))}
</>
)
}
function editableMessageText(message) {
if (typeof message.content === 'string') return message.content
if (!Array.isArray(message.content)) return null
const textBlock = message.content.find(block => block?.type === 'text')
return typeof textBlock?.text === 'string' ? textBlock.text : null
}
// formatLoadEta renders the server's remaining-seconds estimate. The server
// omits it entirely until its observed transfer rate is meaningful, so anything
// arriving here is worth showing.
function formatLoadEta(seconds) {
if (!Number.isFinite(seconds) || seconds <= 0) return ''
if (seconds < 60) return `${Math.round(seconds)}s`
const minutes = Math.round(seconds / 60)
if (minutes < 60) return `${minutes} min`
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
}
function withEditedMessageText(message, text) {
if (typeof message.content === 'string') return { ...message, content: text }
const textIndex = message.content.findIndex(block => block?.type === 'text')
return {
...message,
content: message.content.map((block, index) =>
index === textIndex ? { ...block, text } : block
),
}
}
export default function Chat() {
const { model: urlModel } = useParams()
const { addToast } = useOutletContext()
const navigate = useNavigate()
const location = useLocation()
const { t } = useTranslation('chat')
const { isAdmin } = useAuth()
const { operations } = useOperations()
const {
chats, activeChat, activeChatId, isStreaming, streamingChatId, streamingContent,
streamingReasoning, streamingToolCalls, tokensPerSecond, maxTokensPerSecond, modelLoading,
addChat, forkChat, switchChat, deleteChat, deleteAllChats, renameChat, updateChatSettings,
sendMessage, stopGeneration, clearHistory, getContextUsagePercent, addMessage,
} = useChat(urlModel || '')
// Detect active staging operation for the current chat's model
const stagingOp = useMemo(() => {
if (!isStreaming || !activeChat?.model) return null
return operations.find(op => op.taskType === 'staging' && op.name === activeChat.model) || null
}, [operations, isStreaming, activeChat?.model])
// What to show instead of the thinking dots while the model is not up yet.
// The load job wins over the staging operation: it is authoritative across
// frontend replicas and names the phase (installing / staging / loading),
// where the operation only knows about a byte transfer this replica is
// performing. The operation stays as the fallback for a transfer with no job
// attached to this request (a reconciler scale-up, for instance).
const loadProgress = useMemo(() => {
if (modelLoading) {
const eta = formatLoadEta(modelLoading.eta_seconds)
return {
label: t(`streaming.modelState.${modelLoading.state}`, t('streaming.transferring'))
+ (modelLoading.node ? ` ${t('streaming.onNode', { node: modelLoading.node })}` : ''),
progress: modelLoading.progress || 0,
detail: eta ? t('streaming.eta', { value: eta }) : '',
}
}
if (stagingOp) {
return {
label: stagingOp.nodeName
? t('streaming.transferringTo', { node: stagingOp.nodeName })
: t('streaming.transferring'),
progress: stagingOp.progress || 0,
detail: stagingOp.message || '',
}
}
return null
}, [modelLoading, stagingOp, t])
const [input, setInput] = useState('')
const [files, setFiles] = useState([])
const [showSettings, setShowSettings] = useState(false)
const [mcpAvailable, setMcpAvailable] = useState(false)
const [mcpServerList, setMcpServerList] = useState([])
const [mcpServersLoading, setMcpServersLoading] = useState(false)
const [mcpServerListError, setMcpServerListError] = useState('')
const [mcpPromptList, setMcpPromptList] = useState([])
const [mcpPromptsLoading, setMcpPromptsLoading] = useState(false)
const [mcpPromptArgsDialog, setMcpPromptArgsDialog] = useState(null)
const [mcpPromptArgsValues, setMcpPromptArgsValues] = useState({})
const [mcpResourceList, setMcpResourceList] = useState([])
const [mcpResourcesLoading, setMcpResourcesLoading] = useState(false)
const [modelInfo, setModelInfo] = useState(null)
const [showModelInfo, setShowModelInfo] = useState(false)
const [canvasMode, setCanvasMode] = useState(false)
const [canvasOpen, setCanvasOpen] = useState(false)
const [selectedArtifactId, setSelectedArtifactId] = useState(null)
const [clientMCPServers, setClientMCPServers] = useState(() => loadClientMCPServers())
const [confirmDialog, setConfirmDialog] = useState(null)
const [completionGlowIdx, setCompletionGlowIdx] = useState(-1)
const [editingMessageIndex, setEditingMessageIndex] = useState(null)
const [messageEditDraft, setMessageEditDraft] = useState('')
const prevStreamingRef = useRef(false)
const {
connect: mcpConnect, disconnect: mcpDisconnect, disconnectAll: mcpDisconnectAll,
getToolsForLLM, isClientTool, executeTool, connectionStatuses, getConnectedTools,
hasAppUI, getAppResource, getClientForTool, getToolDefinition,
} = useMCPClient()
const messagesEndRef = useRef(null)
const fileInputRef = useRef(null)
const messagesRef = useRef(null)
const textareaRef = useRef(null)
const stickToBottomRef = useRef(true)
const [scrolledUp, setScrolledUp] = useState(false)
const chatsMenuRef = useRef(null)
// Focus mode: once a conversation has at least one message we slim the
// surrounding chrome (collapse the global app rail, fade non-essential
// header items). Esc gives the user back the full chrome for the rest of
// this session. The settings drawer offers a persistent opt-out.
const isInConversation = (activeChat?.history?.length || 0) > 0
const [focusOverride, setFocusOverride] = useState(false)
const [focusModeEnabled, setFocusModeEnabled] = useState(() => {
try { return localStorage.getItem(FOCUS_MODE_KEY) !== 'false' } catch (_) { return true }
})
const focusActive = focusModeEnabled && isInConversation && !focusOverride
const prevAppCollapseRef = useRef(null)
const toggleFocusMode = (next) => {
setFocusModeEnabled(next)
try { localStorage.setItem(FOCUS_MODE_KEY, String(next)) } catch (_) {}
}
const artifacts = useMemo(
() => canvasMode ? extractCodeArtifacts(activeChat?.history, 'role', 'assistant') : [],
[activeChat?.history, canvasMode]
)
const prevArtifactCountRef = useRef(0)
useEffect(() => {
prevArtifactCountRef.current = artifacts.length
}, [activeChat?.id])
useEffect(() => {
if (artifacts.length > prevArtifactCountRef.current && artifacts.length > 0) {
setSelectedArtifactId(artifacts[artifacts.length - 1].id)
if (!canvasOpen) setCanvasOpen(true)
}
prevArtifactCountRef.current = artifacts.length
}, [artifacts])
// Completion glow: when streaming finishes, briefly highlight last assistant message
useEffect(() => {
if (prevStreamingRef.current && !isStreaming && activeChat?.history?.length > 0) {
const lastIdx = activeChat.history.length - 1
if (activeChat.history[lastIdx]?.role === 'assistant') {
setCompletionGlowIdx(lastIdx)
const timer = setTimeout(() => setCompletionGlowIdx(-1), 600)
return () => clearTimeout(timer)
}
}
prevStreamingRef.current = isStreaming
}, [isStreaming, activeChat?.history?.length])
// Check MCP availability and fetch model config (admin-only endpoint)
useEffect(() => {
const model = activeChat?.model
if (!model || !isAdmin) { setMcpAvailable(false); setModelInfo(null); return }
let cancelled = false
modelsApi.getConfigJson(model).then(cfg => {
if (cancelled) return
setModelInfo(cfg)
if (cfg?.context_size > 0 && activeChat) {
updateChatSettings(activeChat.id, { contextSize: cfg.context_size })
}
const hasMcp = !!(cfg?.mcp?.remote || cfg?.mcp?.stdio)
setMcpAvailable(hasMcp)
if (!hasMcp && activeChat?.mcpMode) {
updateChatSettings(activeChat.id, { mcpMode: false, mcpServers: [] })
}
}).catch(() => { if (!cancelled) { setMcpAvailable(false); setModelInfo(null) } })
return () => { cancelled = true }
}, [activeChat?.model, isAdmin])
const fetchMcpServers = useCallback(async () => {
const model = activeChat?.model
if (!model) return
setMcpServersLoading(true)
setMcpServerListError('')
try {
const data = await mcpApi.listServers(model)
const servers = data?.servers || []
setMcpServerList(servers)
// A previously selected server may become unavailable between requests.
// Remove it from request metadata while leaving it visible with its error.
if (activeChat) {
const unavailable = new Set(servers.filter(server => server.error).map(server => server.name))
const current = activeChat.mcpServers || []
const availableSelection = current.filter(name => !unavailable.has(name))
if (availableSelection.length !== current.length) {
updateChatSettings(activeChat.id, { mcpServers: availableSelection })
}
}
} catch (e) {
setMcpServerList([])
setMcpServerListError(e.body?.message || e.message || 'Failed to discover MCP servers')
} finally {
setMcpServersLoading(false)
}
}, [activeChat, updateChatSettings])
const toggleMcpServer = useCallback((serverName) => {
if (!activeChat) return
const current = activeChat.mcpServers || []
const next = current.includes(serverName)
? current.filter(s => s !== serverName)
: [...current, serverName]
updateChatSettings(activeChat.id, { mcpServers: next })
}, [activeChat, updateChatSettings])
const fetchMcpPrompts = useCallback(async () => {
const model = activeChat?.model
if (!model) return
setMcpPromptsLoading(true)
try {
const data = await mcpApi.listPrompts(model)
setMcpPromptList(Array.isArray(data) ? data : [])
} catch (_e) {
setMcpPromptList([])
} finally {
setMcpPromptsLoading(false)
}
}, [activeChat?.model])
const fetchMcpResources = useCallback(async () => {
const model = activeChat?.model
if (!model) return
setMcpResourcesLoading(true)
try {
const data = await mcpApi.listResources(model)
setMcpResourceList(Array.isArray(data) ? data : [])
} catch (_e) {
setMcpResourceList([])
} finally {
setMcpResourcesLoading(false)
}
}, [activeChat?.model])
const handleSelectPrompt = useCallback(async (prompt) => {
if (prompt.arguments && prompt.arguments.length > 0) {
setMcpPromptArgsDialog(prompt)
setMcpPromptArgsValues({})
return
}
// No arguments, expand immediately
const model = activeChat?.model
if (!model) return
try {
const result = await mcpApi.getPrompt(model, prompt.name, {})
if (result?.messages) {
for (const msg of result.messages) {
addMessage(activeChat.id, { role: msg.role || 'user', content: msg.content })
}
}
} catch (e) {
addMessage(activeChat.id, { role: 'system', content: `Failed to expand prompt: ${e.message}` })
}
}, [activeChat?.model, activeChat?.id, addMessage])
const handleExpandPromptWithArgs = useCallback(async () => {
if (!mcpPromptArgsDialog) return
const model = activeChat?.model
if (!model) return
try {
const result = await mcpApi.getPrompt(model, mcpPromptArgsDialog.name, mcpPromptArgsValues)
if (result?.messages) {
for (const msg of result.messages) {
addMessage(activeChat.id, { role: msg.role || 'user', content: msg.content })
}
}
} catch (e) {
addMessage(activeChat.id, { role: 'system', content: `Failed to expand prompt: ${e.message}` })
}
setMcpPromptArgsDialog(null)
setMcpPromptArgsValues({})
}, [activeChat?.model, activeChat?.id, mcpPromptArgsDialog, mcpPromptArgsValues, addMessage])
const toggleMcpResource = useCallback((uri) => {
if (!activeChat) return
const current = activeChat.mcpResources || []
const next = current.includes(uri)
? current.filter(u => u !== uri)
: [...current, uri]
updateChatSettings(activeChat.id, { mcpResources: next })
}, [activeChat, updateChatSettings])
// Auto-connect/disconnect client MCP servers based on chat's active list
const activeMCPIds = activeChat?.clientMCPServers || []
useEffect(() => {
const activeSet = new Set(activeMCPIds)
for (const server of clientMCPServers) {
const status = connectionStatuses[server.id]?.status
if (activeSet.has(server.id) && status !== 'connected' && status !== 'connecting') {
mcpConnect(server)
} else if (!activeSet.has(server.id) && (status === 'connected' || status === 'connecting')) {
mcpDisconnect(server.id)
}
}
}, [activeMCPIds.join(','), clientMCPServers])
const handleClientMCPServerAdded = useCallback((server) => {
setClientMCPServers(loadClientMCPServers())
const current = activeChat?.clientMCPServers || []
if (activeChat) updateChatSettings(activeChat.id, { clientMCPServers: [...current, server.id] })
}, [activeChat, updateChatSettings])
const handleClientMCPServerRemoved = useCallback(async (id) => {
await mcpDisconnect(id)
setClientMCPServers(loadClientMCPServers())
if (activeChat) {
const current = activeChat.clientMCPServers || []
updateChatSettings(activeChat.id, { clientMCPServers: current.filter(s => s !== id) })
}
}, [activeChat, mcpDisconnect, updateChatSettings])
const handleClientMCPToggle = useCallback((serverId) => {
if (!activeChat) return
const current = activeChat.clientMCPServers || []
const next = current.includes(serverId) ? current.filter(s => s !== serverId) : [...current, serverId]
updateChatSettings(activeChat.id, { clientMCPServers: next })
}, [activeChat, updateChatSettings])
const startMessageEdit = useCallback((index, message) => {
const text = editableMessageText(message)
if (text === null) return
setEditingMessageIndex(index)
setMessageEditDraft(text)
}, [])
const cancelMessageEdit = useCallback(() => {
setEditingMessageIndex(null)
setMessageEditDraft('')
}, [])
const saveMessageEdit = useCallback(() => {
if (!activeChat || isStreaming || editingMessageIndex === null || !messageEditDraft.trim()) return
const message = activeChat.history[editingMessageIndex]
if (!message || editableMessageText(message) === null) return
const history = activeChat.history.map((item, index) =>
index === editingMessageIndex ? withEditedMessageText(item, messageEditDraft) : item
)
updateChatSettings(activeChat.id, { history })
cancelMessageEdit()
}, [activeChat, isStreaming, editingMessageIndex, messageEditDraft, updateChatSettings, cancelMessageEdit])
useEffect(() => {
cancelMessageEdit()
}, [activeChat?.id, isStreaming, cancelMessageEdit])
// Load initial message from home page
const homeDataProcessed = useRef(false)
useEffect(() => {
if (homeDataProcessed.current) return
const stored = localStorage.getItem('localai_index_chat_data')
if (stored) {
homeDataProcessed.current = true
try {
const data = JSON.parse(stored)
localStorage.removeItem('localai_index_chat_data')
// Two entry shapes from Home:
// - "compose-and-send": data.message present → open new chat,
// prefill the composer, click submit.
// - "open-assistant": no message, just data.localaiAssistant → open
// a fresh chat already in admin mode so the wizard can fire.
const hasMessage = !!data.message
const wantsAssistant = !!data.localaiAssistant
if (hasMessage || wantsAssistant) {
let targetChat = activeChat
if (data.newChat) {
targetChat = addChat(data.model || '', '', data.mcpMode || false)
} else {
if (data.model && activeChat) {
updateChatSettings(activeChat.id, { model: data.model })
}
if (data.mcpMode && activeChat) {
updateChatSettings(activeChat.id, { mcpMode: true })
}
}
if (data.mcpServers?.length > 0 && targetChat) {
updateChatSettings(targetChat.id, { mcpServers: data.mcpServers })
}
if (data.clientMCPServers?.length > 0 && targetChat) {
updateChatSettings(targetChat.id, { clientMCPServers: data.clientMCPServers })
}
if (wantsAssistant && targetChat) {
updateChatSettings(targetChat.id, { localaiAssistant: true })
}
if (hasMessage) {
setInput(data.message)
if (data.files) setFiles(data.files)
setTimeout(() => {
const submitBtn = document.getElementById('chat-submit-btn')
submitBtn?.click()
}, 100)
}
}
} catch (_e) { /* ignore */ }
}
}, [])
// Track whether the user is pinned to the bottom. If they scroll up
// while a response is streaming, stop forcing them back down.
useEffect(() => {
const el = messagesRef.current
if (!el) return
const onScroll = () => {
const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight
stickToBottomRef.current = distanceFromBottom < 80
setScrolledUp(distanceFromBottom > 160)
}
el.addEventListener('scroll', onScroll, { passive: true })
return () => el.removeEventListener('scroll', onScroll)
}, [])
// Auto-scroll only when the user hasn't scrolled away from the bottom.
useEffect(() => {
if (!stickToBottomRef.current) return
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
}, [activeChat?.history, streamingContent, streamingReasoning, streamingToolCalls])
// When switching chats, snap to bottom and re-pin. Also reset the
// user's focus-mode override — each chat starts fresh.
useEffect(() => {
stickToBottomRef.current = true
setScrolledUp(false)
messagesEndRef.current?.scrollIntoView({ behavior: 'auto' })
setFocusOverride(false)
}, [activeChat?.id])
// Auto-collapse the global app rail when a conversation begins, and
// restore the previous collapsed state when the user goes back to an
// empty chat (or overrides focus with Esc). We feed into the existing
// sidebar-collapse event bus so App.jsx needs no awareness of focus mode.
useEffect(() => {
if (focusActive) {
if (prevAppCollapseRef.current === null) {
try {
prevAppCollapseRef.current = localStorage.getItem('localai_sidebar_collapsed') === 'true'
} catch (_) { prevAppCollapseRef.current = false }
}
window.dispatchEvent(new CustomEvent('sidebar-collapse', { detail: { collapsed: true } }))
} else if (prevAppCollapseRef.current !== null) {
window.dispatchEvent(new CustomEvent('sidebar-collapse', { detail: { collapsed: prevAppCollapseRef.current } }))
prevAppCollapseRef.current = null
}
}, [focusActive])
// Global keybindings: Cmd/Ctrl+K opens the chats menu; Esc exits focus
// mode while it is engaged (without closing any open dialogs first).
useEffect(() => {
const onKey = (e) => {
const isMod = e.metaKey || e.ctrlKey
if (isMod && (e.key === 'k' || e.key === 'K')) {
e.preventDefault()
chatsMenuRef.current?.toggle()
return
}
if (e.key === 'Escape' && focusActive) {
// Don't fight the chats menu / settings drawer / dialogs — they
// each handle their own Esc and stop propagation when open.
setFocusOverride(true)
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [focusActive])
// Highlight code blocks + add per-block copy buttons. A MutationObserver on
// the messages container is more reliable than render-keyed effects: it fires
// for loaded/switched chats AND for streaming token updates, regardless of
// render timing. The observer is disconnected while we mutate so our own
// highlight/enhance edits don't retrigger it.
useEffect(() => {
const el = messagesRef.current
if (!el) return
let obs
const run = () => {
obs?.disconnect()
highlightAll(el)
enhanceCodeBlocks(el)
obs?.observe(el, { childList: true, subtree: true })
}
obs = new MutationObserver(run)
run()
return () => obs.disconnect()
}, [activeChat?.id])
// Auto-grow textarea
const autoGrowTextarea = useCallback(() => {
const el = textareaRef.current
if (!el) return
el.style.height = 'auto'
el.style.height = Math.min(el.scrollHeight, 200) + 'px'
}, [])
useEffect(() => {
autoGrowTextarea()
}, [input, autoGrowTextarea])
// Event delegation for artifact cards
useEffect(() => {
const el = messagesRef.current
if (!el || !canvasMode) return
const handler = (e) => {
const openBtn = e.target.closest('.artifact-card-open')
const downloadBtn = e.target.closest('.artifact-card-download')
const card = e.target.closest('.artifact-card')
if (downloadBtn) {
e.stopPropagation()
const id = downloadBtn.dataset.artifactId
const artifact = artifacts.find(a => a.id === id)
if (artifact?.code) {
const blob = new Blob([artifact.code], { type: 'text/plain' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = artifact.title || 'download.txt'
a.click()
URL.revokeObjectURL(url)
}
return
}
if (openBtn || card) {
const id = (openBtn || card).dataset.artifactId
if (id) {
setSelectedArtifactId(id)
setCanvasOpen(true)
}
}
}
el.addEventListener('click', handler)
return () => el.removeEventListener('click', handler)
}, [canvasMode, artifacts])
const handleFileChange = useCallback(async (e) => {
const newFiles = []
for (const file of e.target.files) {
const base64 = await fileToBase64(file)
const entry = { name: file.name, type: file.type, base64 }
if (!file.type.startsWith('image/') && !file.type.startsWith('audio/') && !file.type.startsWith('video/')) {
entry.textContent = await file.text().catch(() => '')
}
newFiles.push(entry)
}
setFiles(prev => [...prev, ...newFiles])
e.target.value = ''
}, [])
const handlePaste = useCallback(async (e) => {
const items = e.clipboardData?.items
if (!items) return
const images = Array.from(items)
.filter(item => item.kind === 'file' && item.type.startsWith('image/'))
.map(item => item.getAsFile())
.filter(Boolean)
if (images.length === 0) return
// A pasted image attaches as a file rather than inserting into the text.
e.preventDefault()
// Clipboard images arrive unnamed or as a generic "image.png"; give each
// a unique, typed name so multiple pastes don't collide.
const newFiles = await Promise.all(images.map(async (file, i) => {
const name = (file.name && file.name !== 'image.png')
? file.name
: `pasted-image-${i + 1}.${(file.type.split('/')[1] || 'png').replace('+xml', '')}`
return { name, type: file.type, base64: await fileToBase64(file) }
}))
setFiles(prev => [...prev, ...newFiles])
}, [])
const handleSend = useCallback(async () => {
const msg = input.trim()
if (!msg && files.length === 0) return
if (!activeChat?.model) {
addToast(t('toasts.selectModel'), 'warning')
return
}
setInput('')
setFiles([])
const tools = getToolsForLLM()
const mcpOptions = tools.length > 0 ? {
clientMCPTools: tools,
isClientTool: (name) => isClientTool(name),
executeTool: (name, args) => executeTool(name, args),
maxToolTurns: 10,
getToolAppUI: async (toolName, toolInput, toolResultText) => {
if (!hasAppUI(toolName)) return null
const resource = await getAppResource(toolName)
if (!resource) return null
return {
html: resource.html,
meta: resource.meta,
toolName,
toolInput,
toolDefinition: getToolDefinition(toolName),
toolResult: { content: [{ type: 'text', text: toolResultText }] },
}
},
} : {}
await sendMessage(msg, files, mcpOptions)
}, [input, files, activeChat, sendMessage, addToast, getToolsForLLM, isClientTool, executeTool, hasAppUI, getAppResource, getToolDefinition])
const handleRegenerate = useCallback(async (targetIndex) => {
if (!activeChat || isStreaming) return
const history = activeChat.history
const end = typeof targetIndex === 'number' ? targetIndex : history.length
// Nearest user message at or before the target answer.
let userIdx = -1
for (let i = Math.min(end, history.length) - 1; i >= 0; i--) {
if (history[i].role === 'user') { userIdx = i; break }
}
if (userIdx === -1) return
// Reuse the original message's content verbatim (not re-extracted text):
// it already has any file text / image_url / audio_url / video_url parts
// embedded from when it was first sent, which display-only file metadata
// can't reconstruct.
const userContent = history[userIdx].content
const userFiles = history[userIdx].files || []
// Drop the user turn and everything after it; sendMessage re-appends it.
// Thread the truncated history through explicitly: updateChatSettings only
// schedules a state update, so sendMessage's closure would otherwise read
// the stale pre-truncation history for the outbound API payload.
const baseHistory = history.slice(0, userIdx)
updateChatSettings(activeChat.id, { history: baseHistory })
await sendMessage(userContent, userFiles, { baseHistory, prebuiltContent: true })
}, [activeChat, isStreaming, sendMessage, updateChatSettings])
const handleKeyDown = (e) => {
// Only Enter (no modifiers, no IME composition) sends.
// Shift+Enter, Ctrl+Enter, Meta+Enter, Alt+Enter all fall through to default textarea behavior (newline).
if (
e.key === 'Enter' &&
!e.shiftKey &&
!e.ctrlKey &&
!e.metaKey &&
!e.altKey &&
!e.nativeEvent?.isComposing &&
e.keyCode !== 229
) {
e.preventDefault()
handleSend()
}
}
const copyMessage = async (content) => {
const text = typeof content === 'string' ? content : content?.[0]?.text || ''
const ok = await copyToClipboard(text)
if (ok) {
addToast(t('toasts.copied'), 'success', 2000)
} else {
addToast(t('toasts.copyFailed'), 'error', 3000)
}
}
const copyChatAsMarkdown = async (chat) => {
const ok = await copyToClipboard(serializeChatAsMarkdown(chat))
addToast(ok ? t('toasts.chatCopied') : t('toasts.copyFailed'), ok ? 'success' : 'error', ok ? 2000 : 3000)
}
const contextPercent = getContextUsagePercent()
// Recent chats for the empty state — exclude the current chat and any
// empty placeholders, keep the four most recently updated.
const recentChats = chats
.filter(c => c.id !== activeChatId && (c.history?.length || 0) > 0)
.slice(0, 4)
const promptDeleteAll = () => setConfirmDialog({
title: t('deleteAllDialog.title'),
message: t('deleteAllDialog.message'),
confirmLabel: t('deleteAllDialog.confirm'),
danger: true,
onConfirm: () => { setConfirmDialog(null); deleteAllChats() },
})
if (!activeChat) return null
const layoutClasses = [
'chat-layout',
isInConversation ? 'chat--has-messages' : '',
focusActive ? 'chat--focus' : '',
].filter(Boolean).join(' ')
return (
<div className={layoutClasses}>
{/* Chat main area */}
<div className="chat-main">
{/* Header */}
<div className="chat-header">
<ChatsMenu
ref={chatsMenuRef}
chats={chats}
activeChatId={activeChatId}
streamingChatId={streamingChatId}
onSelect={switchChat}
onNew={() => addChat(activeChat.model)}
onDelete={deleteChat}