-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
735 lines (690 loc) · 24.4 KB
/
Copy pathindex.html
File metadata and controls
735 lines (690 loc) · 24.4 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
<!--
Claude Code Web — Frontend
前端页面:单文件 HTML,无需构建,直接由 Express 提供服务
Features / 功能:
- claude.ai-inspired design / 参考 claude.ai 的暖色调设计
- Dark mode with localStorage / 深色模式(持久化)
- SSE streaming display / SSE 流式消息展示
- File upload (click + drag & drop) / 文件上传(点击 + 拖拽)
- File download links in messages / 消息中的文件下载链接
- Mobile responsive / 移动端适配
- Simple Markdown rendering / 简易 Markdown 渲染
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Claude Code Web</title>
<style>
/* ═══ CSS Variables / CSS 变量 ═══
Light theme by default, .dark class overrides
默认亮色主题,.dark 类覆盖为暗色 */
:root {
--bg: #f5f1eb;
--bg2: #eae5dc;
--surface: #ffffff;
--border: #d4cfc7;
--border-light: #e8e4dc;
--accent: #c96442;
--accent-hover: #b5573a;
--text: #2d2b28;
--text2: #6b6560;
--text3: #9b9590;
--user-bg: #f0ece6;
--code-bg: #2d2b28;
--radius: 16px;
--radius-sm: 10px;
--max-w: 720px;
--shadow: 0 1px 3px rgba(0,0,0,0.06);
}
.dark {
--bg: #1a1816;
--bg2: #242220;
--surface: #2d2b28;
--border: #3d3a36;
--border-light: #353230;
--text: #e8e4dc;
--text2: #9b9590;
--text3: #6b6560;
--user-bg: #353230;
--code-bg: #1a1816;
--shadow: 0 1px 3px rgba(0,0,0,0.2);
}
* { margin:0; padding:0; box-sizing:border-box; }
body {
font-family: "Söhne", -apple-system, "Segoe UI", Roboto, "Noto Sans SC", "Helvetica Neue", sans-serif;
background: var(--bg);
color: var(--text);
height: 100dvh;
display: flex;
flex-direction: column;
transition: background .3s, color .3s;
}
/* ═══ Top Bar ═══ */
.topbar {
display: flex;
align-items: center;
padding: 10px 16px;
background: var(--bg);
border-bottom: 1px solid var(--border-light);
gap: 10px;
flex-shrink: 0;
z-index: 10;
}
.topbar .logo {
width: 28px; height: 28px;
background: var(--accent);
border-radius: 8px;
display: flex; align-items: center; justify-content: center;
color: #fff; font-weight: 700; font-size: 14px;
flex-shrink: 0;
}
.topbar .title {
font-size: 15px; font-weight: 600; flex: 1;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.topbar .session-id {
font-size: 11px; color: var(--text3); font-family: monospace;
max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.tb-btn {
background: none; border: 1px solid var(--border);
color: var(--text2); border-radius: var(--radius-sm);
padding: 5px 12px; font-size: 13px; cursor: pointer;
transition: all .15s; display: flex; align-items: center; gap: 5px;
}
.tb-btn:hover { background: var(--bg2); color: var(--text); }
.tb-btn svg { width: 14px; height: 14px; }
/* ═══ Messages Area ═══ */
.messages {
flex: 1;
overflow-y: auto;
padding: 24px 16px;
scroll-behavior: smooth;
}
.messages::-webkit-scrollbar { width: 4px; }
.messages::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
/* ═══ Message ═══ */
.msg {
max-width: var(--max-w);
margin: 0 auto 20px;
display: flex;
gap: 12px;
align-items: flex-start;
}
.msg .avatar {
width: 28px; height: 28px;
border-radius: 8px;
flex-shrink: 0;
display: flex; align-items: center; justify-content: center;
font-size: 13px; font-weight: 600;
margin-top: 2px;
}
.msg.user .avatar {
background: var(--accent);
color: #fff;
}
.msg.ai .avatar {
background: var(--bg2);
border: 1px solid var(--border);
color: var(--accent);
}
.msg .bubble {
flex: 1;
min-width: 0;
}
.msg .name {
font-size: 13px;
font-weight: 600;
margin-bottom: 4px;
color: var(--text);
}
.msg .body {
font-size: 14.5px;
line-height: 1.7;
word-break: break-word;
white-space: pre-wrap;
color: var(--text);
}
/* Code */
.msg .body code {
background: var(--user-bg);
padding: 1px 5px;
border-radius: 4px;
font-size: 13px;
font-family: "JetBrains Mono", "Fira Code", "SF Mono", Menlo, monospace;
}
.msg .body pre {
background: var(--code-bg);
color: #e8e4dc;
padding: 14px 16px;
border-radius: var(--radius-sm);
overflow-x: auto;
margin: 8px 0;
font-size: 13px;
line-height: 1.5;
}
.msg .body pre code {
background: none; padding: 0; color: inherit;
}
/* Tool tag */
.tool-tag {
display: inline-flex; align-items: center; gap: 4px;
background: var(--bg2);
border: 1px solid var(--border-light);
padding: 2px 10px;
border-radius: 6px;
font-size: 12px;
color: var(--text2);
margin: 4px 0;
}
.tool-tag::before { content: "⚙"; font-size: 11px; }
/* ═══ Typing Indicator ═══ */
.typing-wrap {
display: none;
max-width: var(--max-w);
margin: 0 auto 20px;
}
.typing-wrap.on { display: flex; gap: 12px; align-items: flex-start; }
.typing-wrap .avatar {
width: 28px; height: 28px;
border-radius: 8px;
background: var(--bg2);
border: 1px solid var(--border);
display: flex; align-items: center; justify-content: center;
color: var(--accent);
font-size: 13px; font-weight: 600;
flex-shrink: 0;
}
.typing-dots {
display: flex; gap: 4px; padding: 12px 0;
}
.typing-dots span {
width: 6px; height: 6px; border-radius: 50%;
background: var(--text3);
animation: bounce .9s infinite;
}
.typing-dots span:nth-child(2) { animation-delay: .15s; }
.typing-dots span:nth-child(3) { animation-delay: .3s; }
@keyframes bounce {
0%, 60%, 100% { transform: translateY(0); }
30% { transform: translateY(-5px); }
}
/* ═══ Welcome (empty state) ═══ */
.welcome {
max-width: var(--max-w);
margin: 60px auto;
text-align: center;
padding: 0 20px;
}
.welcome .w-logo {
width: 52px; height: 52px;
background: var(--accent);
border-radius: 14px;
display: inline-flex; align-items: center; justify-content: center;
color: #fff; font-size: 24px; font-weight: 700;
margin-bottom: 16px;
}
.welcome h2 {
font-size: 22px; font-weight: 600; margin-bottom: 8px;
}
.welcome p {
font-size: 14px; color: var(--text2); line-height: 1.6;
}
/* ═══ Input Area ═══ */
.input-area {
flex-shrink: 0;
padding: 12px 16px 16px;
background: var(--bg);
}
.input-box {
max-width: var(--max-w);
margin: 0 auto;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 10px 12px;
display: flex;
flex-direction: column;
transition: border-color .2s;
}
.input-box:focus-within { border-color: var(--accent); }
.input-box textarea {
width: 100%;
background: none;
color: var(--text);
border: none;
font-size: 14.5px;
font-family: inherit;
line-height: 1.55;
resize: none;
min-height: 24px;
max-height: 160px;
outline: none;
padding: 0;
}
.input-box textarea::placeholder { color: var(--text3); }
.input-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 6px;
margin-top: 8px;
}
.send-btn {
width: 34px; height: 34px;
border-radius: 10px;
border: none;
background: var(--accent);
color: #fff;
cursor: pointer;
display: flex; align-items: center; justify-content: center;
transition: background .15s, opacity .15s;
}
.send-btn:hover { background: var(--accent-hover); }
.send-btn:disabled { opacity: .3; cursor: not-allowed; }
.send-btn svg { width: 18px; height: 18px; }
.cancel-btn {
display: none;
height: 34px;
border-radius: 10px;
border: 1px solid var(--border);
background: var(--surface);
color: var(--text2);
cursor: pointer;
padding: 0 14px;
font-size: 13px;
transition: all .15s;
}
.cancel-btn:hover { background: var(--bg2); }
/* ═══ File Attach ═══ */
.attach-btn {
width: 34px; height: 34px;
border-radius: 10px;
border: 1px solid var(--border);
background: none;
color: var(--text2);
cursor: pointer;
display: flex; align-items: center; justify-content: center;
transition: all .15s;
flex-shrink: 0;
}
.attach-btn:hover { background: var(--bg2); color: var(--text); }
.attach-btn svg { width: 16px; height: 16px; }
.file-chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 6px;
}
.file-chips:empty { display: none; margin: 0; }
.file-chip {
display: inline-flex;
align-items: center;
gap: 5px;
background: var(--bg2);
border: 1px solid var(--border-light);
border-radius: 8px;
padding: 4px 10px;
font-size: 12px;
color: var(--text2);
max-width: 200px;
}
.file-chip .fc-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-chip .fc-size { color: var(--text3); flex-shrink: 0; }
.file-chip .fc-remove {
cursor: pointer;
color: var(--text3);
font-size: 14px;
line-height: 1;
flex-shrink: 0;
}
.file-chip .fc-remove:hover { color: var(--accent); }
.drag-overlay {
display: none;
position: fixed;
inset: 0;
background: rgba(201,100,66,0.08);
border: 2px dashed var(--accent);
border-radius: var(--radius);
z-index: 100;
align-items: center;
justify-content: center;
pointer-events: none;
}
.drag-overlay.on { display: flex; }
.drag-overlay span {
background: var(--surface);
padding: 12px 24px;
border-radius: var(--radius);
font-size: 15px;
color: var(--accent);
font-weight: 600;
box-shadow: var(--shadow);
}
/* File link in messages */
.file-link {
display: inline-flex;
align-items: center;
gap: 5px;
background: var(--bg2);
border: 1px solid var(--border-light);
padding: 4px 12px;
border-radius: 8px;
font-size: 13px;
color: var(--accent);
text-decoration: none;
margin: 4px 0;
transition: all .15s;
}
.file-link:hover { background: var(--border-light); }
.file-link::before { content: "📎"; font-size: 12px; }
.input-hint {
max-width: var(--max-w);
margin: 8px auto 0;
font-size: 11px;
color: var(--text3);
text-align: center;
}
/* ═══ Mobile ═══ */
@media (max-width: 640px) {
.topbar .session-id { display: none; }
.msg { gap: 8px; }
.msg .avatar { width: 24px; height: 24px; font-size: 11px; border-radius: 6px; }
.welcome { margin: 30px auto; }
.welcome h2 { font-size: 18px; }
}
</style>
</head>
<body>
<!-- Top Bar -->
<div class="topbar">
<div class="logo">C</div>
<span class="title">Claude</span>
<span class="session-id" id="sidLabel"></span>
<button class="tb-btn" id="newBtn" title="新对话">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
新对话
</button>
<button class="tb-btn" id="themeBtn" title="切换主题">
<svg id="themeIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
</button>
</div>
<!-- Messages -->
<div class="messages" id="msgs">
<div class="welcome" id="welcome">
<div class="w-logo">C</div>
<h2>有什么可以帮你的?</h2>
<p>通过 Claude Code CLI 运行,支持连续对话、工具调用、代码执行。</p>
</div>
</div>
<!-- Typing Indicator -->
<div class="typing-wrap" id="typing">
<div class="avatar">C</div>
<div class="typing-dots"><span></span><span></span><span></span></div>
</div>
<!-- Input -->
<div class="input-area">
<div class="input-box" id="inputBox">
<div class="file-chips" id="fileChips"></div>
<textarea id="input" placeholder="给 Claude 发送消息…" rows="1"></textarea>
<div class="input-actions">
<button class="attach-btn" id="attachBtn" title="附件">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>
</button>
<button class="cancel-btn" id="cancelBtn">停止生成</button>
<button class="send-btn" id="sendBtn" title="发送">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
</button>
</div>
<input type="file" id="fileInput" multiple hidden>
</div>
<div class="drag-overlay" id="dragOverlay"><span>拖放文件到这里</span></div>
<div class="input-hint">Claude Code CLI · Enter 发送 · Shift+Enter 换行 · 支持拖拽或点击📎上传文件</div>
</div>
<script>
// ═══════════════════════════════════════════════════════
// Claude Code Web — Frontend JavaScript
// 前端 JS:处理消息发送、SSE 流式接收、文件上传、主题切换
// ═══════════════════════════════════════════════════════
// DOM references / DOM 元素引用
const $ = id => document.getElementById(id);
const msgsEl = $('msgs'); // Message container / 消息容器
const typingEl = $('typing'); // Typing indicator / 正在输入指示器
const inputEl = $('input'); // Text input / 文本输入框
const sendBtn = $('sendBtn'); // Send button / 发送按钮
const cancelBtn = $('cancelBtn'); // Cancel button / 取消按钮
const newBtn = $('newBtn'); // New chat button / 新对话按钮
const sidLabel = $('sidLabel'); // Session ID display / 会话 ID 显示
const welcomeEl = $('welcome'); // Welcome screen / 欢迎页面
const themeBtn = $('themeBtn'); // Theme toggle / 主题切换按钮
const attachBtn = $('attachBtn'); // File attach button / 文件附件按钮
const fileInput = $('fileInput'); // Hidden file input / 隐藏的文件输入
const fileChips = $('fileChips'); // Attached file chips / 已附加文件标签
const dragOverlay = $('dragOverlay');// Drag & drop overlay / 拖拽覆盖层
// State / 状态
let sessionId = null; // Current session ID for multi-turn / 当前会话 ID(用于连续对话)
let currentReq = null; // Current request ID for cancellation / 当前请求 ID(用于取消)
let busy = false; // Whether a request is in progress / 是否正在请求中
let attachedFiles = []; // Uploaded files pending send / 待发送的已上传文件 [{id, name, size, path}]
// Auth token from URL query / 从 URL 参数获取认证令牌
const token = new URLSearchParams(location.search).get('token') || '';
// ── Theme toggle / 主题切换 ──
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark' || (!savedTheme && matchMedia('(prefers-color-scheme:dark)').matches)) {
document.body.classList.add('dark');
}
themeBtn.addEventListener('click', () => {
document.body.classList.toggle('dark');
localStorage.setItem('theme', document.body.classList.contains('dark') ? 'dark' : 'light');
});
// ── New Chat / 新对话 ──
// Resets session, clears messages, shows welcome screen
// 重置会话、清空消息、显示欢迎页
newBtn.addEventListener('click', () => {
sessionId = null;
sidLabel.textContent = '';
msgsEl.innerHTML = '';
msgsEl.appendChild(welcomeEl);
welcomeEl.style.display = '';
clearAttached();
});
// ═══════════════════════════════════════════════════════
// File Upload / 文件上传
// Files are uploaded to /api/upload first, then attached to chat message
// 文件先上传到 /api/upload,然后随聊天消息一起发送
// ═══════════════════════════════════════════════════════
// Format file size for display / 格式化文件大小
function formatSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
function renderChips() {
fileChips.innerHTML = '';
attachedFiles.forEach((f, i) => {
const chip = document.createElement('div');
chip.className = 'file-chip';
chip.innerHTML = `<span class="fc-name">${f.name}</span><span class="fc-size">${formatSize(f.size)}</span><span class="fc-remove" data-i="${i}">×</span>`;
fileChips.appendChild(chip);
});
}
function clearAttached() {
attachedFiles = [];
fileChips.innerHTML = '';
fileInput.value = '';
}
fileChips.addEventListener('click', e => {
const rm = e.target.closest('.fc-remove');
if (rm) {
attachedFiles.splice(Number(rm.dataset.i), 1);
renderChips();
}
});
async function uploadFiles(fileList) {
if (!fileList.length) return;
const fd = new FormData();
for (const f of fileList) fd.append('files', f);
try {
const headers = {};
if (token) headers['X-Auth-Token'] = token;
const resp = await fetch('/api/upload' + (token ? '?token=' + token : ''), {
method: 'POST', headers, body: fd,
});
const data = await resp.json();
if (data.ok && data.files) {
attachedFiles.push(...data.files);
renderChips();
} else {
alert('上传失败: ' + (data.error || '未知错误'));
}
} catch (err) {
alert('上传失败: ' + err.message);
}
}
attachBtn.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', () => {
if (fileInput.files.length) uploadFiles(fileInput.files);
fileInput.value = '';
});
// ── Drag & Drop / 拖拽上传 ──
// Shows overlay when dragging files over the page / 拖拽文件到页面时显示覆盖层
let dragCounter = 0;
document.addEventListener('dragenter', e => { e.preventDefault(); dragCounter++; dragOverlay.classList.add('on'); });
document.addEventListener('dragleave', e => { e.preventDefault(); dragCounter--; if (dragCounter <= 0) { dragCounter = 0; dragOverlay.classList.remove('on'); } });
document.addEventListener('dragover', e => e.preventDefault());
document.addEventListener('drop', e => {
e.preventDefault();
dragCounter = 0;
dragOverlay.classList.remove('on');
if (e.dataTransfer.files.length) uploadFiles(e.dataTransfer.files);
});
// ── Add Message to UI / 添加消息到界面 ──
// Creates a message bubble with avatar / 创建带头像的消息气泡
function addMsg(role, content) {
welcomeEl.style.display = 'none';
const isUser = role === 'user';
const div = document.createElement('div');
div.className = `msg ${isUser ? 'user' : 'ai'}`;
div.innerHTML = `
<div class="avatar">${isUser ? 'Y' : 'C'}</div>
<div class="bubble">
<div class="name">${isUser ? 'You' : 'Claude'}</div>
<div class="body"></div>
</div>`;
div.querySelector('.body').innerHTML = content;
msgsEl.appendChild(div);
msgsEl.scrollTop = msgsEl.scrollHeight;
return div;
}
// ── Simple Markdown renderer / 简易 Markdown 渲染 ──
// Supports: code blocks, inline code, bold, italic, file download links
// 支持:代码块、行内代码、粗体、斜体、文件下载链接
function md(t) {
let html = t
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/```(\w*)\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.+?)\*/g, '<em>$1</em>');
// 渲染文件下载链接: [下载 filename](/api/files/xxx)
html = html.replace(/\[([^\]]*)\]\((\/api\/files\/[^)]+)\)/g,
'<a class="file-link" href="$2" target="_blank" download>$1</a>');
return html;
}
// ═══════════════════════════════════════════════════════
// Send message / 发送消息
// 1. Upload attached files info to /api/chat
// 2. Read SSE stream and update UI in real-time
// 3. Save session ID for multi-turn conversation
//
// 流程:发消息 → 读 SSE 流 → 实时更新界面 → 保存会话 ID
// ═══════════════════════════════════════════════════════
async function send() {
const text = inputEl.value.trim();
if (!text || busy) return;
inputEl.value = '';
inputEl.style.height = 'auto';
// 显示用户消息(含附件标签)
let userHtml = md(text);
if (attachedFiles.length) {
const chipHtml = attachedFiles.map(f => `<span class="file-chip"><span class="fc-name">${f.name}</span><span class="fc-size">${formatSize(f.size)}</span></span>`).join('');
userHtml = `<div style="margin-bottom:6px">${chipHtml}</div>` + userHtml;
}
addMsg('user', userHtml);
// 准备文件列表
const filesToSend = attachedFiles.length ? attachedFiles.map(f => ({ id: f.id, path: f.path })) : undefined;
clearAttached();
setBusy(true);
const aiDiv = addMsg('ai', '');
const bodyEl = aiDiv.querySelector('.body');
let full = '';
try {
const headers = { 'Content-Type': 'application/json' };
if (token) headers['X-Auth-Token'] = token;
const resp = await fetch('/api/chat', {
method: 'POST', headers,
body: JSON.stringify({ message: text, sessionId, files: filesToSend }),
});
const reader = resp.body.getReader();
const dec = new TextDecoder();
let buf = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
const lines = buf.split('\n');
buf = lines.pop() || '';
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
try {
const e = JSON.parse(line.slice(6));
if (e.type === 'meta') currentReq = e.reqId;
else if (e.type === 'text') { full += e.text; bodyEl.innerHTML = md(full); msgsEl.scrollTop = msgsEl.scrollHeight; }
else if (e.type === 'tool') { full += `\n`; bodyEl.innerHTML = md(full) + `<div class="tool-tag">${e.tool}</div>`; }
else if (e.type === 'session') { sessionId = e.sessionId; sidLabel.textContent = e.sessionId.slice(0,8) + '…'; }
else if (e.type === 'error') { full += `\n${e.error}`; bodyEl.innerHTML = md(full); }
} catch {}
}
}
} catch (err) {
bodyEl.innerHTML = `<span style="color:var(--accent)">连接失败: ${err.message}</span>`;
} finally {
setBusy(false);
if (!full.trim()) bodyEl.innerHTML = '<span style="color:var(--text3)">无响应</span>';
}
}
function setBusy(v) {
busy = v;
sendBtn.disabled = v;
cancelBtn.style.display = v ? 'inline-flex' : 'none';
typingEl.classList.toggle('on', v);
if (!v) currentReq = null;
}
// ── Cancel ongoing request / 取消正在进行的请求 ──
cancelBtn.addEventListener('click', async () => {
if (!currentReq) return;
const h = { 'Content-Type': 'application/json' };
if (token) h['X-Auth-Token'] = token;
fetch('/api/cancel', { method: 'POST', headers: h, body: JSON.stringify({ reqId: currentReq }) });
});
// ── Event bindings / 事件绑定 ──
// Enter to send, Shift+Enter for newline, auto-resize textarea
// Enter 发送,Shift+Enter 换行,自动调整输入框高度
sendBtn.addEventListener('click', send);
inputEl.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); }
});
inputEl.addEventListener('input', () => {
inputEl.style.height = 'auto';
inputEl.style.height = Math.min(inputEl.scrollHeight, 160) + 'px';
});
</script>
</body>
</html>