@wendongfly/zihi 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/daemon.js +23 -0
- package/bin/zihi.js +603 -0
- package/dist/admin.html +297 -0
- package/dist/attach.js +2 -0
- package/dist/chat.html +2254 -0
- package/dist/client-dist/socket.io.esm.min.js +7 -0
- package/dist/client-dist/socket.io.js +4955 -0
- package/dist/client-dist/socket.io.min.js +7 -0
- package/dist/client-dist/socket.io.msgpack.min.js +7 -0
- package/dist/files.html +722 -0
- package/dist/icon.png +0 -0
- package/dist/icon.svg +4 -0
- package/dist/index.html +976 -0
- package/dist/index.js +485 -0
- package/dist/lib/ansi_up.js +431 -0
- package/dist/lib/xterm/LICENSE +21 -0
- package/dist/lib/xterm/README.md +230 -0
- package/dist/lib/xterm/css/xterm.css +209 -0
- package/dist/lib/xterm/lib/xterm.js +2 -0
- package/dist/lib/xterm/lib/xterm.js.map +1 -0
- package/dist/lib/xterm/package.json +100 -0
- package/dist/lib/xterm/src/browser/AccessibilityManager.ts +300 -0
- package/dist/lib/xterm/src/browser/Clipboard.ts +93 -0
- package/dist/lib/xterm/src/browser/ColorContrastCache.ts +34 -0
- package/dist/lib/xterm/src/browser/Lifecycle.ts +33 -0
- package/dist/lib/xterm/src/browser/Linkifier2.ts +416 -0
- package/dist/lib/xterm/src/browser/LocalizableStrings.ts +12 -0
- package/dist/lib/xterm/src/browser/OscLinkProvider.ts +128 -0
- package/dist/lib/xterm/src/browser/RenderDebouncer.ts +83 -0
- package/dist/lib/xterm/src/browser/ScreenDprMonitor.ts +72 -0
- package/dist/lib/xterm/src/browser/Terminal.ts +1305 -0
- package/dist/lib/xterm/src/browser/TimeBasedDebouncer.ts +86 -0
- package/dist/lib/xterm/src/browser/Types.d.ts +181 -0
- package/dist/lib/xterm/src/browser/Viewport.ts +401 -0
- package/dist/lib/xterm/src/browser/decorations/BufferDecorationRenderer.ts +134 -0
- package/dist/lib/xterm/src/browser/decorations/ColorZoneStore.ts +117 -0
- package/dist/lib/xterm/src/browser/decorations/OverviewRulerRenderer.ts +219 -0
- package/dist/lib/xterm/src/browser/input/CompositionHelper.ts +246 -0
- package/dist/lib/xterm/src/browser/input/Mouse.ts +54 -0
- package/dist/lib/xterm/src/browser/input/MoveToCell.ts +249 -0
- package/dist/lib/xterm/src/browser/public/Terminal.ts +260 -0
- package/dist/lib/xterm/src/browser/renderer/dom/DomRenderer.ts +506 -0
- package/dist/lib/xterm/src/browser/renderer/dom/DomRendererRowFactory.ts +522 -0
- package/dist/lib/xterm/src/browser/renderer/dom/WidthCache.ts +157 -0
- package/dist/lib/xterm/src/browser/renderer/shared/CellColorResolver.ts +137 -0
- package/dist/lib/xterm/src/browser/renderer/shared/CharAtlasCache.ts +96 -0
- package/dist/lib/xterm/src/browser/renderer/shared/CharAtlasUtils.ts +75 -0
- package/dist/lib/xterm/src/browser/renderer/shared/Constants.ts +14 -0
- package/dist/lib/xterm/src/browser/renderer/shared/CursorBlinkStateManager.ts +146 -0
- package/dist/lib/xterm/src/browser/renderer/shared/CustomGlyphs.ts +687 -0
- package/dist/lib/xterm/src/browser/renderer/shared/DevicePixelObserver.ts +41 -0
- package/dist/lib/xterm/src/browser/renderer/shared/README.md +1 -0
- package/dist/lib/xterm/src/browser/renderer/shared/RendererUtils.ts +58 -0
- package/dist/lib/xterm/src/browser/renderer/shared/SelectionRenderModel.ts +91 -0
- package/dist/lib/xterm/src/browser/renderer/shared/TextureAtlas.ts +1082 -0
- package/dist/lib/xterm/src/browser/renderer/shared/Types.d.ts +173 -0
- package/dist/lib/xterm/src/browser/selection/SelectionModel.ts +144 -0
- package/dist/lib/xterm/src/browser/selection/Types.d.ts +15 -0
- package/dist/lib/xterm/src/browser/services/CharSizeService.ts +102 -0
- package/dist/lib/xterm/src/browser/services/CharacterJoinerService.ts +339 -0
- package/dist/lib/xterm/src/browser/services/CoreBrowserService.ts +33 -0
- package/dist/lib/xterm/src/browser/services/MouseService.ts +46 -0
- package/dist/lib/xterm/src/browser/services/RenderService.ts +284 -0
- package/dist/lib/xterm/src/browser/services/SelectionService.ts +1029 -0
- package/dist/lib/xterm/src/browser/services/Services.ts +138 -0
- package/dist/lib/xterm/src/browser/services/ThemeService.ts +237 -0
- package/dist/lib/xterm/src/common/CircularList.ts +241 -0
- package/dist/lib/xterm/src/common/Clone.ts +23 -0
- package/dist/lib/xterm/src/common/Color.ts +356 -0
- package/dist/lib/xterm/src/common/CoreTerminal.ts +284 -0
- package/dist/lib/xterm/src/common/EventEmitter.ts +73 -0
- package/dist/lib/xterm/src/common/InputHandler.ts +3443 -0
- package/dist/lib/xterm/src/common/Lifecycle.ts +108 -0
- package/dist/lib/xterm/src/common/MultiKeyMap.ts +42 -0
- package/dist/lib/xterm/src/common/Platform.ts +43 -0
- package/dist/lib/xterm/src/common/SortedList.ts +118 -0
- package/dist/lib/xterm/src/common/TaskQueue.ts +166 -0
- package/dist/lib/xterm/src/common/TypedArrayUtils.ts +17 -0
- package/dist/lib/xterm/src/common/Types.d.ts +553 -0
- package/dist/lib/xterm/src/common/WindowsMode.ts +27 -0
- package/dist/lib/xterm/src/common/buffer/AttributeData.ts +196 -0
- package/dist/lib/xterm/src/common/buffer/Buffer.ts +654 -0
- package/dist/lib/xterm/src/common/buffer/BufferLine.ts +520 -0
- package/dist/lib/xterm/src/common/buffer/BufferRange.ts +13 -0
- package/dist/lib/xterm/src/common/buffer/BufferReflow.ts +223 -0
- package/dist/lib/xterm/src/common/buffer/BufferSet.ts +134 -0
- package/dist/lib/xterm/src/common/buffer/CellData.ts +94 -0
- package/dist/lib/xterm/src/common/buffer/Constants.ts +149 -0
- package/dist/lib/xterm/src/common/buffer/Marker.ts +43 -0
- package/dist/lib/xterm/src/common/buffer/Types.d.ts +52 -0
- package/dist/lib/xterm/src/common/data/Charsets.ts +256 -0
- package/dist/lib/xterm/src/common/data/EscapeSequences.ts +153 -0
- package/dist/lib/xterm/src/common/input/Keyboard.ts +398 -0
- package/dist/lib/xterm/src/common/input/TextDecoder.ts +346 -0
- package/dist/lib/xterm/src/common/input/UnicodeV6.ts +132 -0
- package/dist/lib/xterm/src/common/input/WriteBuffer.ts +246 -0
- package/dist/lib/xterm/src/common/input/XParseColor.ts +80 -0
- package/dist/lib/xterm/src/common/parser/Constants.ts +58 -0
- package/dist/lib/xterm/src/common/parser/DcsParser.ts +192 -0
- package/dist/lib/xterm/src/common/parser/EscapeSequenceParser.ts +792 -0
- package/dist/lib/xterm/src/common/parser/OscParser.ts +238 -0
- package/dist/lib/xterm/src/common/parser/Params.ts +229 -0
- package/dist/lib/xterm/src/common/parser/Types.d.ts +274 -0
- package/dist/lib/xterm/src/common/public/AddonManager.ts +53 -0
- package/dist/lib/xterm/src/common/public/BufferApiView.ts +35 -0
- package/dist/lib/xterm/src/common/public/BufferLineApiView.ts +29 -0
- package/dist/lib/xterm/src/common/public/BufferNamespaceApi.ts +36 -0
- package/dist/lib/xterm/src/common/public/ParserApi.ts +37 -0
- package/dist/lib/xterm/src/common/public/UnicodeApi.ts +27 -0
- package/dist/lib/xterm/src/common/services/BufferService.ts +151 -0
- package/dist/lib/xterm/src/common/services/CharsetService.ts +34 -0
- package/dist/lib/xterm/src/common/services/CoreMouseService.ts +318 -0
- package/dist/lib/xterm/src/common/services/CoreService.ts +87 -0
- package/dist/lib/xterm/src/common/services/DecorationService.ts +140 -0
- package/dist/lib/xterm/src/common/services/InstantiationService.ts +85 -0
- package/dist/lib/xterm/src/common/services/LogService.ts +124 -0
- package/dist/lib/xterm/src/common/services/OptionsService.ts +201 -0
- package/dist/lib/xterm/src/common/services/OscLinkService.ts +115 -0
- package/dist/lib/xterm/src/common/services/ServiceRegistry.ts +49 -0
- package/dist/lib/xterm/src/common/services/Services.ts +342 -0
- package/dist/lib/xterm/src/common/services/UnicodeService.ts +86 -0
- package/dist/lib/xterm/src/headless/Terminal.ts +136 -0
- package/dist/lib/xterm/src/headless/public/Terminal.ts +195 -0
- package/dist/lib/xterm/typings/xterm.d.ts +1844 -0
- package/dist/lib/xterm-fit/LICENSE +19 -0
- package/dist/lib/xterm-fit/README.md +24 -0
- package/dist/lib/xterm-fit/lib/xterm-addon-fit.js +2 -0
- package/dist/lib/xterm-fit/lib/xterm-addon-fit.js.map +1 -0
- package/dist/lib/xterm-fit/package.json +26 -0
- package/dist/lib/xterm-fit/src/FitAddon.ts +89 -0
- package/dist/lib/xterm-fit/typings/xterm-addon-fit.d.ts +55 -0
- package/dist/lib/xterm-links/LICENSE +19 -0
- package/dist/lib/xterm-links/README.md +21 -0
- package/dist/lib/xterm-links/lib/xterm-addon-web-links.js +2 -0
- package/dist/lib/xterm-links/lib/xterm-addon-web-links.js.map +1 -0
- package/dist/lib/xterm-links/package.json +26 -0
- package/dist/lib/xterm-links/src/WebLinkProvider.ts +198 -0
- package/dist/lib/xterm-links/src/WebLinksAddon.ts +57 -0
- package/dist/lib/xterm-links/typings/xterm-addon-web-links.d.ts +53 -0
- package/dist/login.html +163 -0
- package/dist/manifest.json +12 -0
- package/dist/package.json +1 -0
- package/dist/sw.js +127 -0
- package/dist/sync.html +816 -0
- package/package.json +47 -0
package/dist/chat.html
ADDED
|
@@ -0,0 +1,2254 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover">
|
|
6
|
+
<meta name="theme-color" content="#0d1117">
|
|
7
|
+
<meta name="apple-mobile-web-app-capable" content="yes">
|
|
8
|
+
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
|
9
|
+
<link rel="manifest" href="/manifest.json">
|
|
10
|
+
<link rel="apple-touch-icon" href="/icon.png">
|
|
11
|
+
<title>weHi 会话</title>
|
|
12
|
+
<script src="/socket.io/socket.io.js"></script>
|
|
13
|
+
<style>
|
|
14
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
15
|
+
html, body { height: 100%; background: #0d1117; color: #e6edf3; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; overflow: hidden; }
|
|
16
|
+
body { display: flex; flex-direction: column; }
|
|
17
|
+
|
|
18
|
+
/* ── 顶部栏 ─────────────────────────────── */
|
|
19
|
+
#top-bar { display: flex; align-items: center; padding: 0.5rem 0.75rem; background: #161b22; border-bottom: 1px solid #30363d; flex-shrink: 0; gap: 0.5rem; padding-top: max(0.5rem, env(safe-area-inset-top)); }
|
|
20
|
+
#title-group { flex: 1; overflow: hidden; min-width: 0; }
|
|
21
|
+
#session-title { font-size: 0.9rem; font-weight: 600; color: #58a6ff; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
22
|
+
#session-cwd { font-size: 0.68rem; color: #8b949e; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: 'SF Mono', 'Consolas', monospace; }
|
|
23
|
+
.top-btn { display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; background: transparent; color: #8b949e; border: none; border-radius: 8px; cursor: pointer; transition: all 0.15s; flex-shrink: 0; }
|
|
24
|
+
.top-btn:hover { background: #21262d; color: #e6edf3; }
|
|
25
|
+
.top-btn:active { transform: scale(0.92); }
|
|
26
|
+
|
|
27
|
+
/* ── 状态栏 ─────────────────────────────── */
|
|
28
|
+
#status-bar { display: flex; align-items: center; gap: 0.6rem; padding: 0.3rem 0.75rem; background: #0d1117; border-bottom: 1px solid #21262d; font-size: 0.72rem; overflow-x: auto; flex-shrink: 0; scrollbar-width: none; }
|
|
29
|
+
#status-bar::-webkit-scrollbar { display: none; }
|
|
30
|
+
.sb-item { display: inline-flex; align-items: center; gap: 0.25rem; white-space: nowrap; }
|
|
31
|
+
.sb-dot { width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0; }
|
|
32
|
+
.sb-dot.idle { background: #3fb950; }
|
|
33
|
+
.sb-dot.thinking { background: #d29922; animation: pulse 1s infinite; }
|
|
34
|
+
.sb-dot.working { background: #58a6ff; animation: pulse 1s infinite; }
|
|
35
|
+
.sb-dot.waiting { background: #f0883e; animation: pulse 0.6s infinite; }
|
|
36
|
+
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
37
|
+
#control-badge { padding: 0.15rem 0.5rem; border-radius: 10px; cursor: pointer; user-select: none; border: 1px solid; }
|
|
38
|
+
#control-badge.controlling { background: #0d3321; color: #3fb950; border-color: #238636; }
|
|
39
|
+
#control-badge.readonly { background: #21262d; color: #8b949e; border-color: #30363d; }
|
|
40
|
+
#viewer-count { color: #8b949e; }
|
|
41
|
+
|
|
42
|
+
/* ── 聊天区 ─────────────────────────────── */
|
|
43
|
+
#chat-area { flex: 1; overflow-y: auto; padding: 0.75rem; -webkit-overflow-scrolling: touch; scrollbar-width: thin; scrollbar-color: #21262d transparent; }
|
|
44
|
+
#chat-area::-webkit-scrollbar { width: 6px; }
|
|
45
|
+
#chat-area::-webkit-scrollbar-track { background: transparent; }
|
|
46
|
+
#chat-area::-webkit-scrollbar-thumb { background: #21262d; border-radius: 3px; }
|
|
47
|
+
#chat-area::-webkit-scrollbar-thumb:hover { background: #30363d; }
|
|
48
|
+
@media (min-width: 768px) { #chat-area { max-width: 900px; margin: 0 auto; width: 100%; } }
|
|
49
|
+
.msg { margin-bottom: 0.5rem; animation: fadeIn 0.15s ease; }
|
|
50
|
+
@keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
|
|
51
|
+
|
|
52
|
+
/* 用户输入气泡 */
|
|
53
|
+
.msg-input { display: flex; justify-content: flex-end; }
|
|
54
|
+
.msg-input .bubble { background: #1f6feb; color: #fff; padding: 0.5rem 0.75rem; border-radius: 12px 12px 4px 12px; max-width: 85%; font-family: 'SF Mono', 'Cascadia Code', 'Consolas', monospace; font-size: 0.85rem; word-break: break-word; white-space: pre-wrap; }
|
|
55
|
+
.msg-input .meta { font-size: 0.65rem; color: #8b949e; text-align: right; margin-top: 2px; padding-right: 4px; }
|
|
56
|
+
|
|
57
|
+
/* Claude 文本回复 */
|
|
58
|
+
.msg-assistant { padding: 0.4rem 0; }
|
|
59
|
+
.msg-assistant .content { font-size: 0.88rem; line-height: 1.65; color: #e6edf3; }
|
|
60
|
+
.msg-assistant .content code { background: #21262d; padding: 0.12em 0.35em; border-radius: 4px; font-size: 0.82em; font-family: 'SF Mono', 'Consolas', monospace; }
|
|
61
|
+
.msg-assistant .content pre { background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 0.6rem 0.75rem; overflow-x: auto; margin: 0.5rem 0; font-family: 'SF Mono', 'Consolas', monospace; font-size: 0.8rem; line-height: 1.35; }
|
|
62
|
+
.msg-assistant .content pre code { background: none; padding: 0; }
|
|
63
|
+
.msg-assistant .content ul, .msg-assistant .content ol { padding-left: 1.5rem; margin: 0.3rem 0; }
|
|
64
|
+
.msg-assistant .content strong { color: #fff; }
|
|
65
|
+
|
|
66
|
+
/* 工具调用组 */
|
|
67
|
+
.msg-tool-group { border-left: 3px solid #58a6ff; margin-left: 0.3rem; padding-left: 0.6rem; margin-bottom: 0.3rem; }
|
|
68
|
+
.tool-group-header { display: flex; align-items: center; gap: 0.35rem; cursor: pointer; font-size: 0.78rem; color: #58a6ff; padding: 0.25rem 0; user-select: none; }
|
|
69
|
+
.tool-group-header:hover { color: #79c0ff; }
|
|
70
|
+
.tool-expand-btn { margin-left: auto; font-size: 0.68rem; color: #8b949e; background: #21262d; border: 1px solid #30363d; border-radius: 4px; padding: 0.1rem 0.4rem; cursor: pointer; white-space: nowrap; }
|
|
71
|
+
.tool-expand-btn:hover { color: #e6edf3; border-color: #58a6ff; }
|
|
72
|
+
.tool-group-header .arrow { transition: transform 0.15s; font-size: 0.65rem; }
|
|
73
|
+
.tool-group-header .arrow.open { transform: rotate(90deg); }
|
|
74
|
+
.tool-group-body { display: none; }
|
|
75
|
+
.tool-group-body.open { display: block; }
|
|
76
|
+
/* 工具调用卡片 */
|
|
77
|
+
.msg-tool { margin-bottom: 0.2rem; }
|
|
78
|
+
.tool-header { display: flex; align-items: center; gap: 0.35rem; cursor: pointer; font-size: 0.78rem; color: #58a6ff; padding: 0.25rem 0; user-select: none; }
|
|
79
|
+
.tool-header:hover { color: #79c0ff; }
|
|
80
|
+
.tool-header .arrow { transition: transform 0.15s; font-size: 0.65rem; }
|
|
81
|
+
.tool-header .arrow.open { transform: rotate(90deg); }
|
|
82
|
+
.tool-body { display: none; background: #161b22; border: 1px solid #21262d; border-radius: 6px; padding: 0.5rem; margin-top: 0.2rem; font-family: 'SF Mono', 'Consolas', monospace; font-size: 0.75rem; line-height: 1.3; overflow-x: auto; white-space: pre-wrap; word-break: break-all; max-height: 300px; overflow-y: auto; }
|
|
83
|
+
.tool-body.open { display: block; }
|
|
84
|
+
|
|
85
|
+
/* 权限请求卡片 */
|
|
86
|
+
.msg-permission { background: #1c1500; border: 1px solid #d29922; border-radius: 8px; padding: 0.65rem 0.75rem; font-size: 0.82rem; }
|
|
87
|
+
.msg-permission .perm-title { color: #d29922; font-weight: 600; margin-bottom: 0.3rem; }
|
|
88
|
+
.msg-permission .perm-detail { color: #e6edf3; font-family: 'SF Mono', 'Consolas', monospace; font-size: 0.78rem; margin-bottom: 0.5rem; white-space: pre-wrap; }
|
|
89
|
+
.perm-actions { display: flex; gap: 0.4rem; flex-wrap: wrap; }
|
|
90
|
+
.perm-actions button { padding: 0.35rem 0.8rem; border-radius: 6px; font-size: 0.78rem; cursor: pointer; border: none; }
|
|
91
|
+
.btn-allow { background: #238636; color: #fff; }
|
|
92
|
+
.btn-allow:hover { background: #2ea043; }
|
|
93
|
+
.btn-deny { background: #21262d; color: #f85149; border: 1px solid #30363d !important; }
|
|
94
|
+
|
|
95
|
+
/* 权限弹窗 modal */
|
|
96
|
+
#perm-modal { display: none; position: fixed; inset: 0; z-index: 90; align-items: flex-end; justify-content: center; }
|
|
97
|
+
#perm-modal.open { display: flex; }
|
|
98
|
+
#perm-modal-backdrop { position: absolute; inset: 0; background: rgba(0,0,0,0.55); }
|
|
99
|
+
#perm-modal-box { position: relative; background: #161b22; border-radius: 16px 16px 0 0; width: 100%; max-width: 480px; padding: 1rem 1rem; padding-bottom: max(1rem, env(safe-area-inset-bottom)); z-index: 1; animation: slideUp 0.25s ease; border-top: 3px solid #d29922; }
|
|
100
|
+
@keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
|
|
101
|
+
#perm-modal-box .pm-icon { text-align: center; font-size: 1.6rem; margin-bottom: 0.4rem; }
|
|
102
|
+
#perm-modal-box .pm-title { text-align: center; font-size: 0.95rem; font-weight: 600; color: #d29922; margin-bottom: 0.6rem; }
|
|
103
|
+
#perm-modal-box .pm-tool { text-align: center; font-size: 0.78rem; color: #8b949e; margin-bottom: 0.3rem; }
|
|
104
|
+
#perm-modal-box .pm-detail { background: #0d1117; border: 1px solid #21262d; border-radius: 8px; padding: 0.6rem 0.75rem; font-family: 'SF Mono', 'Consolas', monospace; font-size: 0.78rem; line-height: 1.4; color: #e6edf3; white-space: pre-wrap; word-break: break-all; max-height: 200px; overflow-y: auto; margin-bottom: 0.75rem; }
|
|
105
|
+
#perm-modal-box .pm-actions { display: flex; gap: 0.5rem; }
|
|
106
|
+
#perm-modal-box .pm-actions button { flex: 1; padding: 0.6rem; border-radius: 10px; font-size: 0.88rem; font-weight: 600; cursor: pointer; border: none; transition: all 0.15s; }
|
|
107
|
+
#perm-modal-box .pm-actions button:active { transform: scale(0.96); }
|
|
108
|
+
#perm-modal-box .pm-btn-allow { background: #238636; color: #fff; }
|
|
109
|
+
#perm-modal-box .pm-btn-allow:hover { background: #2ea043; }
|
|
110
|
+
#perm-modal-box .pm-btn-deny { background: #21262d; color: #f85149; border: 1px solid #30363d; }
|
|
111
|
+
#perm-modal-box .pm-btn-deny:hover { background: #30363d; }
|
|
112
|
+
#perm-modal-box .pm-queue { text-align: center; font-size: 0.7rem; color: #8b949e; margin-top: 0.5rem; }
|
|
113
|
+
|
|
114
|
+
#mode-badge { padding: 0.15rem 0.5rem; border-radius: 10px; background: #21262d; border: 1px solid #30363d; cursor: pointer; user-select: none; }
|
|
115
|
+
#mode-badge:hover { background: #30363d; }
|
|
116
|
+
|
|
117
|
+
/* Diff 视图 */
|
|
118
|
+
.msg-diff { font-family: 'SF Mono', 'Consolas', monospace; font-size: 0.78rem; background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 0.5rem 0.6rem; overflow-x: auto; line-height: 1.35; }
|
|
119
|
+
.diff-add { color: #3fb950; background: rgba(46,160,67,0.1); }
|
|
120
|
+
.diff-del { color: #f85149; background: rgba(248,81,73,0.1); }
|
|
121
|
+
.diff-hunk { color: #8b949e; }
|
|
122
|
+
.diff-file { color: #d2a8ff; font-weight: 600; margin-bottom: 0.2rem; }
|
|
123
|
+
|
|
124
|
+
/* 思考中 */
|
|
125
|
+
.msg-thinking { padding: 0.35rem 0; color: #8b949e; font-size: 0.8rem; }
|
|
126
|
+
.thinking-header { display: flex; align-items: center; gap: 0.4rem; cursor: pointer; user-select: none; }
|
|
127
|
+
.thinking-header:hover { color: #c9d1d9; }
|
|
128
|
+
.thinking-header .arrow { transition: transform 0.15s; font-size: 0.6rem; }
|
|
129
|
+
.thinking-header .arrow.open { transform: rotate(90deg); }
|
|
130
|
+
.thinking-dots { display: inline-flex; gap: 3px; }
|
|
131
|
+
.thinking-dots span { width: 5px; height: 5px; background: #8b949e; border-radius: 50%; animation: blink 1.4s infinite; }
|
|
132
|
+
.thinking-dots span:nth-child(2) { animation-delay: 0.2s; }
|
|
133
|
+
.thinking-dots span:nth-child(3) { animation-delay: 0.4s; }
|
|
134
|
+
@keyframes blink { 0%,80%,100% { opacity: 0.3; } 40% { opacity: 1; } }
|
|
135
|
+
.thinking-body { display: none; margin-top: 0.3rem; padding: 0.4rem 0.6rem; background: #161b22; border: 1px solid #21262d; border-radius: 6px; font-size: 0.75rem; line-height: 1.4; white-space: pre-wrap; word-break: break-word; max-height: 200px; overflow-y: auto; color: #8b949e; scrollbar-width: thin; scrollbar-color: #21262d transparent; }
|
|
136
|
+
.thinking-body::-webkit-scrollbar { width: 4px; }
|
|
137
|
+
.thinking-body::-webkit-scrollbar-thumb { background: #21262d; border-radius: 2px; }
|
|
138
|
+
.thinking-body.open { display: block; }
|
|
139
|
+
|
|
140
|
+
/* 错误消息 */
|
|
141
|
+
.msg-error { background: #1c0a0a; border: 1px solid #f8514933; border-radius: 8px; padding: 0.5rem 0.7rem; color: #f85149; font-size: 0.82rem; }
|
|
142
|
+
|
|
143
|
+
/* 原始输出(降级) */
|
|
144
|
+
.msg-raw .code-block { background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 0.6rem 0.75rem; font-family: 'SF Mono', 'Consolas', monospace; font-size: 0.8rem; line-height: 1.35; white-space: pre-wrap; word-break: break-all; overflow-x: auto; }
|
|
145
|
+
|
|
146
|
+
/* 历史和状态 */
|
|
147
|
+
.msg-history .code-block { background: #0d1117; border: 1px solid #21262d; border-radius: 8px; padding: 0.6rem 0.75rem; font-family: 'SF Mono', 'Consolas', monospace; font-size: 0.75rem; line-height: 1.3; white-space: pre-wrap; word-break: break-all; color: #8b949e; max-height: 300px; overflow-y: auto; }
|
|
148
|
+
.msg-history .meta { font-size: 0.65rem; color: #484f58; margin-bottom: 4px; }
|
|
149
|
+
.msg-status { text-align: center; font-size: 0.75rem; color: #8b949e; padding: 0.5rem 0; }
|
|
150
|
+
|
|
151
|
+
/* ── 输入栏 ─────────────────────────────── */
|
|
152
|
+
#input-area { background: #161b22; border-top: 1px solid #30363d; flex-shrink: 0; padding: 0.5rem 0.75rem 0.35rem; }
|
|
153
|
+
#input-area.no-shortcuts { padding-bottom: max(0.5rem, env(safe-area-inset-bottom)); }
|
|
154
|
+
#input-box { background: #0d1117; border: 1px solid #30363d; border-radius: 12px; transition: border-color 0.2s; overflow: hidden; position: relative; }
|
|
155
|
+
#img-preview { display: none; align-items: center; gap: 0.5rem; padding: 0.5rem 0.75rem; border-bottom: 1px solid #21262d; background: #161b22; }
|
|
156
|
+
#img-preview.show { display: flex; }
|
|
157
|
+
#img-preview img { width: 48px; height: 48px; object-fit: cover; border-radius: 6px; border: 1px solid #30363d; }
|
|
158
|
+
#img-preview .img-info { flex: 1; font-size: 0.78rem; color: #8b949e; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
159
|
+
#img-preview .img-remove { width: 24px; height: 24px; border-radius: 50%; border: none; background: #21262d; color: #8b949e; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 14px; flex-shrink: 0; }
|
|
160
|
+
#img-preview .img-remove:hover { background: #f85149; color: #fff; }
|
|
161
|
+
#input-box.focused { border-color: #58a6ff; }
|
|
162
|
+
#input-box.disabled { opacity: 0.5; pointer-events: none; }
|
|
163
|
+
#cmd-input { display: block; width: 100%; background: transparent; color: #e6edf3; border: none; padding: 0.6rem 0.75rem 0.3rem; font-family: 'SF Mono', 'Cascadia Code', 'Consolas', monospace; font-size: 0.85rem; outline: none; resize: none; line-height: 1.4; max-height: 120px; overflow-y: auto; }
|
|
164
|
+
#cmd-input::placeholder { color: #484f58; }
|
|
165
|
+
#input-toolbar { display: flex; align-items: center; padding: 0.25rem 0.4rem 0.4rem; gap: 0.15rem; }
|
|
166
|
+
#input-toolbar .spacer { flex: 1; }
|
|
167
|
+
.tb-btn { display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 8px; border: none; background: transparent; color: #8b949e; cursor: pointer; transition: all 0.15s; flex-shrink: 0; }
|
|
168
|
+
.tb-btn:hover { background: #21262d; color: #e6edf3; }
|
|
169
|
+
.tb-btn:active { transform: scale(0.92); }
|
|
170
|
+
.tb-btn.active { color: #58a6ff; }
|
|
171
|
+
.tb-btn.recording { color: #f85149; animation: pulse 1s infinite; }
|
|
172
|
+
.tb-btn svg { width: 18px; height: 18px; }
|
|
173
|
+
#send-btn { color: #3fb950; }
|
|
174
|
+
#send-btn:hover { background: rgba(63,185,80,0.12); color: #3fb950; }
|
|
175
|
+
#send-btn:disabled { opacity: 0.3; cursor: not-allowed; }
|
|
176
|
+
#send-btn:disabled:hover { background: transparent; }
|
|
177
|
+
#cancel-btn { display: none; color: #f85149; }
|
|
178
|
+
#cancel-btn:hover { background: rgba(248,81,73,0.12); color: #f85149; }
|
|
179
|
+
#cancel-btn.show { display: inline-flex; }
|
|
180
|
+
#readonly-overlay { display: none; text-align: center; padding: 0.6rem; font-size: 0.8rem; color: #8b949e; background: #161b22; }
|
|
181
|
+
|
|
182
|
+
/* ── 快捷键栏 ───────────────────────────── */
|
|
183
|
+
#shortcut-bar { background: #161b22; border-top: 1px solid #21262d; padding: 0.35rem 0.5rem; padding-bottom: max(0.35rem, env(safe-area-inset-bottom)); flex-shrink: 0; overflow: hidden; }
|
|
184
|
+
#shortcut-bar > div { display: flex; align-items: center; gap: 0.35rem; overflow-x: auto; scrollbar-width: none; }
|
|
185
|
+
#shortcut-bar > div::-webkit-scrollbar { display: none; }
|
|
186
|
+
.sk { background: #21262d; color: #e6edf3; border: 1px solid #30363d; border-radius: 6px; padding: 0.3rem 0.55rem; font-size: 0.75rem; font-family: 'SF Mono', 'Consolas', monospace; cursor: pointer; white-space: nowrap; flex-shrink: 0; user-select: none; -webkit-user-select: none; touch-action: manipulation; }
|
|
187
|
+
.sk:active { background: #30363d; transform: scale(0.95); }
|
|
188
|
+
.sk:disabled { opacity: 0.4; cursor: not-allowed; }
|
|
189
|
+
.sk.sk-claude { color: #d2a8ff; border-color: #d2a8ff33; background: #d2a8ff11; }
|
|
190
|
+
|
|
191
|
+
/* ── 设置面板 ───────────────────────────── */
|
|
192
|
+
#settings-backdrop { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 60; }
|
|
193
|
+
#settings-backdrop.open { display: block; }
|
|
194
|
+
#settings-panel { position: fixed; top: 0; right: -320px; width: 300px; max-width: 85vw; height: 100%; background: #161b22; border-left: 1px solid #30363d; z-index: 61; transition: right 0.25s ease; overflow-y: auto; padding: 1rem; }
|
|
195
|
+
#settings-panel.open { right: 0; }
|
|
196
|
+
.panel-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; font-size: 1rem; font-weight: 600; }
|
|
197
|
+
.panel-close { background: none; border: none; color: #8b949e; font-size: 1.2rem; cursor: pointer; }
|
|
198
|
+
.setting-group { margin-bottom: 1.2rem; }
|
|
199
|
+
.setting-group h4 { font-size: 0.75rem; color: #8b949e; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 0.5rem; }
|
|
200
|
+
.setting-toggle { display: flex; justify-content: space-between; align-items: center; padding: 0.5rem 0; font-size: 0.85rem; cursor: pointer; }
|
|
201
|
+
.setting-toggle input[type=checkbox] { width: 36px; height: 20px; appearance: none; -webkit-appearance: none; background: #30363d; border-radius: 10px; position: relative; cursor: pointer; transition: background 0.2s; }
|
|
202
|
+
.setting-toggle input[type=checkbox]:checked { background: #238636; }
|
|
203
|
+
.setting-toggle input[type=checkbox]::after { content: ''; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; background: #fff; border-radius: 50%; transition: left 0.2s; }
|
|
204
|
+
.setting-toggle input[type=checkbox]:checked::after { left: 18px; }
|
|
205
|
+
|
|
206
|
+
/* ── 底部选择面板 ─────────────────────── */
|
|
207
|
+
.action-sheet { display: none; position: fixed; inset: 0; z-index: 80; }
|
|
208
|
+
.action-sheet.open { display: flex; align-items: flex-end; justify-content: center; }
|
|
209
|
+
.action-sheet-backdrop { position: absolute; inset: 0; background: rgba(0,0,0,0.5); }
|
|
210
|
+
.action-sheet-box { position: relative; background: #161b22; border-radius: 16px 16px 0 0; width: 100%; max-width: 480px; padding: 0.75rem 1rem; padding-bottom: max(1rem, env(safe-area-inset-bottom)); z-index: 1; }
|
|
211
|
+
.action-sheet-title { font-size: 0.85rem; font-weight: 600; color: #e6edf3; padding: 0.5rem 0; text-align: center; border-bottom: 1px solid #21262d; margin-bottom: 0.5rem; }
|
|
212
|
+
.action-sheet-item { display: flex; align-items: center; justify-content: space-between; padding: 0.65rem 0.5rem; border-radius: 8px; cursor: pointer; font-size: 0.85rem; color: #e6edf3; transition: background 0.1s; }
|
|
213
|
+
.action-sheet-item:hover { background: #21262d; }
|
|
214
|
+
.action-sheet-item:active { background: #30363d; }
|
|
215
|
+
.action-sheet-item .desc { font-size: 0.72rem; color: #8b949e; }
|
|
216
|
+
.action-sheet-item .check { color: #3fb950; font-size: 0.9rem; }
|
|
217
|
+
.action-sheet-cancel { display: block; width: 100%; margin-top: 0.5rem; padding: 0.65rem; background: #21262d; border: none; border-radius: 10px; color: #8b949e; font-size: 0.85rem; cursor: pointer; text-align: center; }
|
|
218
|
+
.mem-file { margin-bottom: 0.5rem; border: 1px solid #21262d; border-radius: 8px; overflow: hidden; }
|
|
219
|
+
.mem-file-header { display: flex; align-items: center; gap: 0.35rem; padding: 0.4rem 0.6rem; background: #21262d; cursor: pointer; font-size: 0.75rem; color: #58a6ff; user-select: none; }
|
|
220
|
+
.mem-file-header:hover { background: #30363d; }
|
|
221
|
+
.mem-file-header .arrow { transition: transform 0.15s; font-size: 0.6rem; }
|
|
222
|
+
.mem-file-header .arrow.open { transform: rotate(90deg); }
|
|
223
|
+
.mem-file-body { display: none; padding: 0.5rem 0.6rem; background: #0d1117; font-family: 'SF Mono','Consolas',monospace; font-size: 0.72rem; line-height: 1.5; white-space: pre-wrap; word-break: break-word; color: #c9d1d9; max-height: 300px; overflow-y: auto; }
|
|
224
|
+
.mem-file-body.open { display: block; }
|
|
225
|
+
.slash-inp { width: 100%; padding: 0.65rem 0.8rem; background: #0d1117; border: 1px solid #30363d; border-radius: 10px; color: #e6edf3; font-size: 0.9rem; outline: none; }
|
|
226
|
+
.slash-inp:focus { border-color: #f97316; }
|
|
227
|
+
|
|
228
|
+
/* ── QR弹窗 / 状态遮罩 ──────────────── */
|
|
229
|
+
#qr-modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 100; align-items: center; justify-content: center; }
|
|
230
|
+
#qr-modal.open { display: flex; }
|
|
231
|
+
#qr-box { background: #161b22; border: 1px solid #30363d; border-radius: 12px; padding: 1.5rem; text-align: center; max-width: 320px; width: 90%; }
|
|
232
|
+
#qr-box h3 { margin-bottom: 1rem; font-size: 0.95rem; }
|
|
233
|
+
#qr-box img { width: 100%; max-width: 240px; border-radius: 8px; background: #fff; padding: 8px; }
|
|
234
|
+
#qr-box .close-btn { margin-top: 1rem; background: #21262d; color: #e6edf3; border: 1px solid #30363d; border-radius: 6px; padding: 0.5rem 1.5rem; cursor: pointer; font-size: 0.9rem; }
|
|
235
|
+
#status-overlay { position: fixed; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(13,17,23,0.85); color: #8b949e; font-size: 0.9rem; z-index: 50; }
|
|
236
|
+
#status-overlay.hidden { display: none; }
|
|
237
|
+
</style>
|
|
238
|
+
</head>
|
|
239
|
+
<body>
|
|
240
|
+
|
|
241
|
+
<div id="top-bar">
|
|
242
|
+
<div id="title-group">
|
|
243
|
+
<div id="session-title">加载中...</div>
|
|
244
|
+
<div id="session-cwd"></div>
|
|
245
|
+
</div>
|
|
246
|
+
<button class="top-btn" onclick="openFiles()" title="文件" style="font-size:0.7rem;color:var(--muted)">文件</button>
|
|
247
|
+
<button class="top-btn" id="sync-btn" onclick="openSync()" title="同步" style="display:none;font-size:0.7rem;color:var(--muted)">同步</button>
|
|
248
|
+
<button class="top-btn" onclick="showUsage()" title="用量" style="font-size:0.7rem;color:var(--muted)">用量</button>
|
|
249
|
+
<button class="top-btn" onclick="openSettings()" title="设置">
|
|
250
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 01-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>
|
|
251
|
+
</button>
|
|
252
|
+
<button class="top-btn" onclick="goBack()" title="返回">
|
|
253
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg>
|
|
254
|
+
</button>
|
|
255
|
+
</div>
|
|
256
|
+
|
|
257
|
+
<div id="status-bar">
|
|
258
|
+
<span class="sb-item" id="work-status"><span class="sb-dot idle"></span> 空闲</span>
|
|
259
|
+
<span id="mode-badge" onclick="switchMode()">默认</span>
|
|
260
|
+
<span id="control-badge" class="readonly" style="display:none">只读</span>
|
|
261
|
+
<span id="viewer-count" class="sb-item"></span>
|
|
262
|
+
<span id="update-badge" style="display:none;color:#d29922;cursor:pointer" onclick="location.href='/'">⬆ 有更新</span>
|
|
263
|
+
</div>
|
|
264
|
+
|
|
265
|
+
<div id="chat-area"></div>
|
|
266
|
+
|
|
267
|
+
<div id="input-area">
|
|
268
|
+
<div id="readonly-overlay" style="display:none"></div>
|
|
269
|
+
<div id="input-box">
|
|
270
|
+
<div id="img-preview">
|
|
271
|
+
<img id="img-preview-thumb" src="" alt="">
|
|
272
|
+
<span class="img-info">已添加图片,输入文字后发送</span>
|
|
273
|
+
<button class="img-remove" onclick="clearPendingImage()" title="移除图片">×</button>
|
|
274
|
+
</div>
|
|
275
|
+
<textarea id="cmd-input" rows="1" placeholder="输入消息..." autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
|
|
276
|
+
<div id="input-toolbar">
|
|
277
|
+
<button class="tb-btn" id="btn-photo" onclick="openCamera()" title="拍照">
|
|
278
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"/><circle cx="12" cy="13" r="4"/></svg>
|
|
279
|
+
</button>
|
|
280
|
+
<div class="spacer"></div>
|
|
281
|
+
<button class="tb-btn" id="voice-btn" onclick="toggleVoice()" title="语音输入">
|
|
282
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/><path d="M19 10v2a7 7 0 01-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
|
|
283
|
+
</button>
|
|
284
|
+
<button class="tb-btn" id="send-btn" onclick="sendCommand()" title="发送">
|
|
285
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" 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>
|
|
286
|
+
</button>
|
|
287
|
+
<button class="tb-btn" id="cancel-btn" onclick="cancelAgent()" title="取消 (Esc)">
|
|
288
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
|
|
289
|
+
</button>
|
|
290
|
+
</div>
|
|
291
|
+
</div>
|
|
292
|
+
</div>
|
|
293
|
+
|
|
294
|
+
<div id="shortcut-bar" style="display:none">
|
|
295
|
+
<div id="sk-claude-agent">
|
|
296
|
+
<button class="sk sk-claude" onclick="openModelSheet()">模型</button>
|
|
297
|
+
<button class="sk sk-claude" onclick="doSlashCmd('/plan')">计划</button>
|
|
298
|
+
<button class="sk sk-claude" onclick="doSlashCmd('/compact')">压缩</button>
|
|
299
|
+
<button class="sk sk-claude" onclick="openResumeSheet()">恢复</button>
|
|
300
|
+
<button class="sk sk-claude" onclick="doClear()">清除</button>
|
|
301
|
+
<button class="sk sk-claude" onclick="doSlashCmd('/rename')">命名</button>
|
|
302
|
+
<button class="sk sk-claude" onclick="openGitSheet()" style="color:#3fb950">提交</button>
|
|
303
|
+
<button class="sk sk-claude" onclick="showMemory()">记忆</button>
|
|
304
|
+
</div>
|
|
305
|
+
</div>
|
|
306
|
+
|
|
307
|
+
<!-- 设置面板 -->
|
|
308
|
+
<div id="settings-backdrop" onclick="closeSettings()"></div>
|
|
309
|
+
<div id="settings-panel">
|
|
310
|
+
<div class="panel-header"><span>设置</span><button class="panel-close" onclick="closeSettings()">✕</button></div>
|
|
311
|
+
<div class="setting-group">
|
|
312
|
+
<h4>显示</h4>
|
|
313
|
+
<label class="setting-toggle"><span>解析终端输出</span><input type="checkbox" id="set-parse" checked></label>
|
|
314
|
+
<label class="setting-toggle"><span>显示思考过程</span><input type="checkbox" id="set-thinking" checked></label>
|
|
315
|
+
<label class="setting-toggle"><span>工具调用默认折叠</span><input type="checkbox" id="set-collapse" checked></label>
|
|
316
|
+
</div>
|
|
317
|
+
</div>
|
|
318
|
+
|
|
319
|
+
<!-- QR弹窗 -->
|
|
320
|
+
<div id="qr-modal">
|
|
321
|
+
<div id="qr-box">
|
|
322
|
+
<h3>扫码在其他设备打开此会话</h3>
|
|
323
|
+
<img id="qr-img" src="" alt="QR Code"><br>
|
|
324
|
+
<button class="close-btn" onclick="closeQR()">关闭</button>
|
|
325
|
+
</div>
|
|
326
|
+
</div>
|
|
327
|
+
|
|
328
|
+
<!-- 模型选择面板 -->
|
|
329
|
+
<div id="model-sheet" class="action-sheet">
|
|
330
|
+
<div class="action-sheet-backdrop" onclick="closeModelSheet()"></div>
|
|
331
|
+
<div class="action-sheet-box">
|
|
332
|
+
<div class="action-sheet-title">选择模型</div>
|
|
333
|
+
<div id="model-list"></div>
|
|
334
|
+
<button class="action-sheet-cancel" onclick="closeModelSheet()">取消</button>
|
|
335
|
+
</div>
|
|
336
|
+
</div>
|
|
337
|
+
|
|
338
|
+
<!-- 恢复会话面板 -->
|
|
339
|
+
<div id="resume-sheet" class="action-sheet">
|
|
340
|
+
<div class="action-sheet-backdrop" onclick="closeResumeSheet()"></div>
|
|
341
|
+
<div class="action-sheet-box">
|
|
342
|
+
<div class="action-sheet-title">恢复 Claude 会话</div>
|
|
343
|
+
<div id="resume-list" style="max-height:50vh;overflow-y:auto"></div>
|
|
344
|
+
<button class="action-sheet-cancel" onclick="closeResumeSheet()">取消</button>
|
|
345
|
+
</div>
|
|
346
|
+
</div>
|
|
347
|
+
|
|
348
|
+
<!-- 斜杠命令面板 -->
|
|
349
|
+
<div id="slash-sheet" class="action-sheet">
|
|
350
|
+
<div class="action-sheet-backdrop" onclick="closeSlashSheet()"></div>
|
|
351
|
+
<div class="action-sheet-box">
|
|
352
|
+
<div class="action-sheet-title" id="slash-title">命令</div>
|
|
353
|
+
<div style="padding:0.3rem 0.2rem">
|
|
354
|
+
<input id="slash-input" class="slash-inp" placeholder="输入参数(可选)" autocomplete="off">
|
|
355
|
+
</div>
|
|
356
|
+
<button class="action-sheet-cancel" style="background:#f97316;color:#fff;font-weight:600;margin-bottom:0.4rem" onclick="submitSlashCmd()">发送</button>
|
|
357
|
+
<button class="action-sheet-cancel" onclick="closeSlashSheet()">取消</button>
|
|
358
|
+
</div>
|
|
359
|
+
</div>
|
|
360
|
+
|
|
361
|
+
<div id="git-sheet" class="action-sheet">
|
|
362
|
+
<div class="action-sheet-backdrop" onclick="closeGitSheet()"></div>
|
|
363
|
+
<div class="action-sheet-box">
|
|
364
|
+
<div class="action-sheet-title">提交代码到 GitLab</div>
|
|
365
|
+
<div style="padding:0.3rem 0.2rem;display:flex;flex-direction:column;gap:0.4rem">
|
|
366
|
+
<input id="git-url" class="slash-inp" placeholder="GitLab 仓库地址 (https://gitlab.com/...)" autocomplete="off">
|
|
367
|
+
<div style="display:flex;gap:0.4rem">
|
|
368
|
+
<input id="git-user" class="slash-inp" placeholder="用户名" autocomplete="off" style="flex:1">
|
|
369
|
+
<input id="git-pass" class="slash-inp" placeholder="密码/Token" type="password" autocomplete="off" style="flex:1">
|
|
370
|
+
</div>
|
|
371
|
+
<div style="display:flex;gap:0.4rem">
|
|
372
|
+
<input id="git-branch" class="slash-inp" placeholder="分支 (默认 main)" autocomplete="off" style="flex:1">
|
|
373
|
+
<input id="git-msg" class="slash-inp" placeholder="提交说明" autocomplete="off" style="flex:2">
|
|
374
|
+
</div>
|
|
375
|
+
<label style="display:flex;align-items:center;gap:0.4rem;font-size:0.75rem;color:#8b949e;padding:0 0.2rem">
|
|
376
|
+
<input type="checkbox" id="git-save" checked> 记住此项目的仓库信息
|
|
377
|
+
</label>
|
|
378
|
+
</div>
|
|
379
|
+
<button id="git-submit-btn" class="action-sheet-cancel" style="background:#3fb950;color:#000;font-weight:600;margin-bottom:0.4rem" onclick="submitGitPush()">提交并推送</button>
|
|
380
|
+
<button class="action-sheet-cancel" onclick="closeGitSheet()">取消</button>
|
|
381
|
+
</div>
|
|
382
|
+
</div>
|
|
383
|
+
|
|
384
|
+
<div id="memory-sheet" class="action-sheet">
|
|
385
|
+
<div class="action-sheet-backdrop" onclick="closeMemorySheet()"></div>
|
|
386
|
+
<div class="action-sheet-box" style="max-height:80vh;display:flex;flex-direction:column">
|
|
387
|
+
<div class="action-sheet-title">Claude 记忆</div>
|
|
388
|
+
<div id="memory-content" style="flex:1;overflow-y:auto;padding:0.3rem 0;font-size:0.78rem;color:#c9d1d9;scrollbar-width:thin">
|
|
389
|
+
<div style="text-align:center;color:#8b949e;padding:2rem 0">加载中...</div>
|
|
390
|
+
</div>
|
|
391
|
+
<button class="action-sheet-cancel" onclick="closeMemorySheet()">关闭</button>
|
|
392
|
+
</div>
|
|
393
|
+
</div>
|
|
394
|
+
|
|
395
|
+
<!-- 权限授权弹窗 -->
|
|
396
|
+
<div id="perm-modal">
|
|
397
|
+
<div id="perm-modal-backdrop"></div>
|
|
398
|
+
<div id="perm-modal-box">
|
|
399
|
+
<div class="pm-icon">🛡️</div>
|
|
400
|
+
<div class="pm-title" id="pm-title">请求权限</div>
|
|
401
|
+
<div class="pm-tool" id="pm-tool"></div>
|
|
402
|
+
<div class="pm-detail" id="pm-detail"></div>
|
|
403
|
+
<div class="pm-actions">
|
|
404
|
+
<button class="pm-btn-deny" id="pm-btn-deny">拒绝</button>
|
|
405
|
+
<button class="pm-btn-allow" id="pm-btn-allow">允许</button>
|
|
406
|
+
<button class="pm-btn-allow" id="pm-btn-allow-all" style="background:#1f6feb">后续都允许</button>
|
|
407
|
+
</div>
|
|
408
|
+
<div class="pm-queue" id="pm-queue" style="display:none"></div>
|
|
409
|
+
</div>
|
|
410
|
+
</div>
|
|
411
|
+
|
|
412
|
+
<div id="status-overlay">连接中...</div>
|
|
413
|
+
|
|
414
|
+
<script>
|
|
415
|
+
// 全局错误捕获:如果 module 脚本崩溃,显示错误而不是卡在"连接中"
|
|
416
|
+
window.addEventListener('error', function(e) {
|
|
417
|
+
var ov = document.getElementById('status-overlay');
|
|
418
|
+
if (ov && !ov.classList.contains('hidden')) {
|
|
419
|
+
ov.innerHTML = '<div>加载失败</div><div style="font-size:0.75rem;margin-top:0.5rem;color:#f85149">' +
|
|
420
|
+
(e.message || '未知错误') + '</div>' +
|
|
421
|
+
'<button onclick="location.href=\'/\'" style="margin-top:1rem;padding:0.5rem 1.5rem;border:1px solid #8b949e;border-radius:8px;background:transparent;color:#c9d1d9;cursor:pointer">返回首页</button>';
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
window.addEventListener('unhandledrejection', function(e) {
|
|
425
|
+
var ov = document.getElementById('status-overlay');
|
|
426
|
+
if (ov && !ov.classList.contains('hidden')) {
|
|
427
|
+
ov.innerHTML = '<div>加载失败</div><div style="font-size:0.75rem;margin-top:0.5rem;color:#f85149">' +
|
|
428
|
+
(e.reason?.message || e.reason || '未知错误') + '</div>' +
|
|
429
|
+
'<button onclick="location.href=\'/\'" style="margin-top:1rem;padding:0.5rem 1.5rem;border:1px solid #8b949e;border-radius:8px;background:transparent;color:#c9d1d9;cursor:pointer">返回首页</button>';
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
</script>
|
|
433
|
+
<script type="module">
|
|
434
|
+
let ansi;
|
|
435
|
+
try {
|
|
436
|
+
const { AnsiUp } = await import('/lib/ansi_up.js');
|
|
437
|
+
ansi = new AnsiUp();
|
|
438
|
+
ansi.use_classes = false;
|
|
439
|
+
} catch (e) {
|
|
440
|
+
// AnsiUp 加载失败时用简单的 fallback
|
|
441
|
+
console.error('[zihi] AnsiUp 加载失败:', e);
|
|
442
|
+
ansi = { ansi_to_html: (t) => t.replace(/</g, '<'), use_classes: false };
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// ── Service Worker 注册 ──
|
|
446
|
+
if ('serviceWorker' in navigator) {
|
|
447
|
+
navigator.serviceWorker.register('/sw.js').then((reg) => {
|
|
448
|
+
console.log('[SW] 已注册');
|
|
449
|
+
// 监听 SW 发来的权限响应(用户点击通知按钮)
|
|
450
|
+
navigator.serviceWorker.addEventListener('message', (e) => {
|
|
451
|
+
if (e.data?.type === 'permission-response' && window.respondAgentPermission) {
|
|
452
|
+
window.respondAgentPermission(e.data.requestId, e.data.allow);
|
|
453
|
+
}
|
|
454
|
+
});
|
|
455
|
+
}).catch((err) => console.warn('[SW] 注册失败:', err));
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// ── 通知权限请求 ──
|
|
459
|
+
const _hasNotification = typeof Notification !== 'undefined';
|
|
460
|
+
let _notifyPermission = _hasNotification ? (Notification.permission || 'default') : 'denied';
|
|
461
|
+
async function requestNotifyPermission() {
|
|
462
|
+
if (!_hasNotification) return;
|
|
463
|
+
if (_notifyPermission === 'default') {
|
|
464
|
+
_notifyPermission = await Notification.requestPermission();
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function showPermissionNotification(toolName, detail, reqId, sessionUrl) {
|
|
469
|
+
if (!_hasNotification || _notifyPermission !== 'granted') return;
|
|
470
|
+
if (document.visibilityState === 'visible') return; // 页面在前台时不弹通知
|
|
471
|
+
const n = new Notification(`${toolName} 请求权限`, {
|
|
472
|
+
body: detail.slice(0, 120),
|
|
473
|
+
tag: 'zihi-perm-' + reqId,
|
|
474
|
+
requireInteraction: true,
|
|
475
|
+
data: { requestId: reqId, sessionUrl },
|
|
476
|
+
});
|
|
477
|
+
n.onclick = () => { window.focus(); n.close(); };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// ── 离线历史缓存 (IndexedDB) ──
|
|
481
|
+
const IDB_NAME = 'zihi_history';
|
|
482
|
+
const IDB_STORE = 'messages';
|
|
483
|
+
let _idb = null;
|
|
484
|
+
|
|
485
|
+
function openHistoryDB() {
|
|
486
|
+
return new Promise((resolve, reject) => {
|
|
487
|
+
const req = indexedDB.open(IDB_NAME, 1);
|
|
488
|
+
req.onupgradeneeded = (e) => {
|
|
489
|
+
const db = e.target.result;
|
|
490
|
+
if (!db.objectStoreNames.contains(IDB_STORE)) {
|
|
491
|
+
const store = db.createObjectStore(IDB_STORE, { keyPath: 'id', autoIncrement: true });
|
|
492
|
+
store.createIndex('sessionId', 'sessionId', { unique: false });
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
req.onsuccess = () => { _idb = req.result; resolve(_idb); };
|
|
496
|
+
req.onerror = () => reject(req.error);
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
async function saveMessageToHistory(sessionId, msg) {
|
|
501
|
+
if (!_idb) return;
|
|
502
|
+
try {
|
|
503
|
+
const tx = _idb.transaction(IDB_STORE, 'readwrite');
|
|
504
|
+
tx.objectStore(IDB_STORE).add({ sessionId, msg, ts: Date.now() });
|
|
505
|
+
} catch {}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
async function loadOfflineHistory(sessionId) {
|
|
509
|
+
if (!_idb) return [];
|
|
510
|
+
return new Promise((resolve) => {
|
|
511
|
+
try {
|
|
512
|
+
const tx = _idb.transaction(IDB_STORE, 'readonly');
|
|
513
|
+
const idx = tx.objectStore(IDB_STORE).index('sessionId');
|
|
514
|
+
const req = idx.getAll(sessionId);
|
|
515
|
+
req.onsuccess = () => resolve(req.result || []);
|
|
516
|
+
req.onerror = () => resolve([]);
|
|
517
|
+
} catch { resolve([]); }
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async function clearSessionHistory(sessionId) {
|
|
522
|
+
if (!_idb) return;
|
|
523
|
+
try {
|
|
524
|
+
const tx = _idb.transaction(IDB_STORE, 'readwrite');
|
|
525
|
+
const store = tx.objectStore(IDB_STORE);
|
|
526
|
+
const idx = store.index('sessionId');
|
|
527
|
+
const req = idx.openCursor(sessionId);
|
|
528
|
+
req.onsuccess = (e) => {
|
|
529
|
+
const cursor = e.target.result;
|
|
530
|
+
if (cursor) { cursor.delete(); cursor.continue(); }
|
|
531
|
+
};
|
|
532
|
+
} catch {}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// 初始化 IndexedDB
|
|
536
|
+
openHistoryDB().catch(() => {});
|
|
537
|
+
|
|
538
|
+
fetch('/api/me').then(r => r.json()).catch(() => {});
|
|
539
|
+
window.showUsage = async () => {
|
|
540
|
+
try {
|
|
541
|
+
const res = await fetch('/api/usage');
|
|
542
|
+
const data = await res.json();
|
|
543
|
+
const C = 'style="margin-bottom:1rem;padding:0.8rem 1rem;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);border-radius:10px"';
|
|
544
|
+
const H = 'style="font-size:0.9rem;font-weight:700;margin-bottom:0.5rem;color:#e6edf3"';
|
|
545
|
+
const T = 'style="font-size:0.82rem;color:#b1bac4;line-height:1.6"';
|
|
546
|
+
let html = '<div style="padding:1.5rem">';
|
|
547
|
+
html += '<h3 style="margin:0 0 1.2rem;font-size:1.1rem;color:#fff;text-align:center">Claude 用量</h3>';
|
|
548
|
+
if (data.rateLimit) {
|
|
549
|
+
const rl = data.rateLimit;
|
|
550
|
+
const resetTime = new Date(rl.resetsAt * 1000);
|
|
551
|
+
const remaining = Math.max(0, Math.ceil((resetTime - Date.now()) / 60000));
|
|
552
|
+
const hours = Math.floor(remaining / 60);
|
|
553
|
+
const mins = remaining % 60;
|
|
554
|
+
const timeStr = hours > 0 ? `${hours}小时${mins}分钟` : `${mins}分钟`;
|
|
555
|
+
const statusColor = rl.status === 'allowed' ? '#3fb950' : '#f85149';
|
|
556
|
+
const statusText = rl.status === 'allowed' ? '正常可用' : '已达上限';
|
|
557
|
+
html += `<div ${C}>`;
|
|
558
|
+
html += `<div ${H}>5 小时配额窗口</div>`;
|
|
559
|
+
html += `<div ${T}><span style="color:${statusColor};font-weight:700;font-size:0.95rem">${rl.status === 'allowed' ? '●' : '●'} ${statusText}</span></div>`;
|
|
560
|
+
html += `<div ${T}>窗口重置: <b style="color:#e6edf3">${timeStr}后</b>(${resetTime.toLocaleTimeString('zh-CN', {hour:'2-digit',minute:'2-digit'})})</div>`;
|
|
561
|
+
html += '</div>';
|
|
562
|
+
} else {
|
|
563
|
+
html += `<div ${C}><div ${H}>5 小时配额窗口</div><div ${T}>发送一条 Agent 消息后可查看</div></div>`;
|
|
564
|
+
}
|
|
565
|
+
if (data.activeSessions?.length) {
|
|
566
|
+
html += `<div ${C}><div ${H}>当前会话</div>`;
|
|
567
|
+
for (const s of data.activeSessions) {
|
|
568
|
+
if (!s.usage) continue;
|
|
569
|
+
const u = s.usage;
|
|
570
|
+
html += `<div ${T}><b style="color:#e6edf3">${s.title}</b> (${s.owner || '管理员'})</div>`;
|
|
571
|
+
// 上下文使用率
|
|
572
|
+
const CTX_LIMIT = 200000; // 200K context window
|
|
573
|
+
const lastIn = u.lastInputTokens || 0;
|
|
574
|
+
if (lastIn > 0) {
|
|
575
|
+
const pct = Math.min(100, Math.round(lastIn / CTX_LIMIT * 100));
|
|
576
|
+
const barColor = pct >= 80 ? '#f85149' : pct >= 60 ? '#d29922' : '#3fb950';
|
|
577
|
+
const label = pct >= 80 ? '接近极限,建议 /compact' : pct >= 60 ? '较高' : '正常';
|
|
578
|
+
html += `<div style="margin:0.4rem 0 0.2rem"><div style="font-size:0.72rem;color:#8b949e;margin-bottom:0.2rem">上下文 <b style="color:${barColor}">${(lastIn/1000).toFixed(0)}K</b> / ${CTX_LIMIT/1000}K (${pct}%) — ${label}</div>`;
|
|
579
|
+
html += `<div style="width:100%;height:5px;background:#21262d;border-radius:3px;overflow:hidden"><div style="width:${pct}%;height:100%;background:${barColor};border-radius:3px"></div></div></div>`;
|
|
580
|
+
}
|
|
581
|
+
html += `<div style="font-size:0.78rem;color:#8b949e;margin:0.2rem 0 0.3rem;line-height:1.5">查询 <b style="color:#b1bac4">${u.queryCount}</b>次 输入 <b style="color:#b1bac4">${((u.totalInputTokens+u.totalCacheReadTokens)/1000).toFixed(0)}K</b> 输出 <b style="color:#b1bac4">${(u.totalOutputTokens/1000).toFixed(0)}K</b> 费用 <b style="color:#b1bac4">$${u.totalCostUSD.toFixed(4)}</b></div>`;
|
|
582
|
+
if (u.modelUsage) { for (const [m, mu] of Object.entries(u.modelUsage)) { html += `<div style="font-size:0.72rem;color:#6e7681;line-height:1.4"> ${m.replace(/claude-/,'').replace(/-\d{8}$/,'').replace(/\[.*\]/,'')} ${(mu.inputTokens/1000).toFixed(0)}K/${(mu.outputTokens/1000).toFixed(0)}K $${mu.costUSD.toFixed(4)}</div>`; } }
|
|
583
|
+
}
|
|
584
|
+
html += '</div>';
|
|
585
|
+
}
|
|
586
|
+
html += '<button onclick="this.closest(\'[data-usage-overlay]\').remove()" style="margin-top:0.8rem;width:100%;padding:0.7rem;background:#f97316;color:#fff;border:none;border-radius:10px;cursor:pointer;font-size:0.9rem;font-weight:600">关闭</button></div>';
|
|
587
|
+
const overlay = document.createElement('div');
|
|
588
|
+
overlay.setAttribute('data-usage-overlay', '');
|
|
589
|
+
overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);z-index:999;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px)';
|
|
590
|
+
overlay.onclick = (e) => { if (e.target === overlay) overlay.remove(); };
|
|
591
|
+
const box = document.createElement('div');
|
|
592
|
+
box.style.cssText = 'background:#161b22;border:1px solid rgba(255,255,255,0.12);border-radius:16px;max-height:80vh;overflow-y:auto;width:90%;max-width:420px;box-shadow:0 16px 48px rgba(0,0,0,0.4)';
|
|
593
|
+
box.innerHTML = html;
|
|
594
|
+
overlay.appendChild(box);
|
|
595
|
+
document.body.appendChild(overlay);
|
|
596
|
+
} catch (err) { alert('获取用量失败: ' + err.message); }
|
|
597
|
+
};
|
|
598
|
+
|
|
599
|
+
// ── 状态 ──────────────────────────────────────
|
|
600
|
+
const SESSION_ID = location.pathname.split('/').pop();
|
|
601
|
+
const chatArea = document.getElementById('chat-area');
|
|
602
|
+
const cmdInput = document.getElementById('cmd-input');
|
|
603
|
+
const sendBtn = document.getElementById('send-btn');
|
|
604
|
+
const cancelBtn = document.getElementById('cancel-btn');
|
|
605
|
+
const overlay = document.getElementById('status-overlay');
|
|
606
|
+
const readonlyOverlay = document.getElementById('readonly-overlay');
|
|
607
|
+
const inputBox = document.getElementById('input-box');
|
|
608
|
+
const shortcutBar = document.getElementById('shortcut-bar');
|
|
609
|
+
|
|
610
|
+
// textarea 自适应高度
|
|
611
|
+
cmdInput.addEventListener('input', () => {
|
|
612
|
+
cmdInput.style.height = 'auto';
|
|
613
|
+
cmdInput.style.height = Math.min(cmdInput.scrollHeight, 120) + 'px';
|
|
614
|
+
});
|
|
615
|
+
cmdInput.addEventListener('focus', () => {
|
|
616
|
+
inputBox.classList.add('focused');
|
|
617
|
+
if (!isController && canTakeControl()) socket.emit('take-control', { sessionId: SESSION_ID });
|
|
618
|
+
});
|
|
619
|
+
cmdInput.addEventListener('blur', () => inputBox.classList.remove('focused'));
|
|
620
|
+
|
|
621
|
+
let currentSession = null;
|
|
622
|
+
let isController = false;
|
|
623
|
+
let myRole = 'viewer';
|
|
624
|
+
let claudeSession = false; // 是否为 Claude Code 会话
|
|
625
|
+
let workState = 'idle';
|
|
626
|
+
|
|
627
|
+
// 设置
|
|
628
|
+
const DEFAULT_SETTINGS = { parseOutput: true, showThinking: true, collapseTools: true };
|
|
629
|
+
let settings = loadSettings();
|
|
630
|
+
|
|
631
|
+
function loadSettings() { try { return { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem('zihi_chat_settings')) }; } catch { return { ...DEFAULT_SETTINGS }; } }
|
|
632
|
+
function saveSettings() { localStorage.setItem('zihi_chat_settings', JSON.stringify(settings)); }
|
|
633
|
+
|
|
634
|
+
// 输出累积
|
|
635
|
+
let outputBuffer = '';
|
|
636
|
+
let outputTimer = null;
|
|
637
|
+
const OUTPUT_DELAY = 600; // 输出合并延迟(ms),越大越少DOM操作
|
|
638
|
+
const MAX_MESSAGES = 150; // 聊天区最大消息数
|
|
639
|
+
|
|
640
|
+
// 命令历史
|
|
641
|
+
const cmdHistory = [];
|
|
642
|
+
let historyIdx = -1;
|
|
643
|
+
|
|
644
|
+
// 思考指示器引用(用于原地更新)
|
|
645
|
+
let thinkingEl = null;
|
|
646
|
+
|
|
647
|
+
// ── ANSI 工具 ──────────────────────────────────
|
|
648
|
+
function stripAnsi(text) {
|
|
649
|
+
return text.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/\x1b\][^\x07]*\x07/g, '').replace(/\x1b[()][AB012]/g, '').replace(/\x1b[>=<]/g, '').replace(/\r/g, '');
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function cleanText(text) {
|
|
653
|
+
let c = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
654
|
+
c = c.split('\n').map(l => l.trimEnd()).join('\n');
|
|
655
|
+
return c.replace(/^\n+/, '').replace(/\n+$/, '');
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function renderAnsiHtml(text) { return ansi.ansi_to_html(cleanText(text)); }
|
|
659
|
+
|
|
660
|
+
// ── 简易 Markdown ──────────────────────────────
|
|
661
|
+
function escHtml(s) { return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
|
662
|
+
|
|
663
|
+
function renderMarkdown(text) {
|
|
664
|
+
const lines = text.split('\n');
|
|
665
|
+
let html = '';
|
|
666
|
+
let inCode = false, codeLang = '', codeLines = [];
|
|
667
|
+
|
|
668
|
+
for (const line of lines) {
|
|
669
|
+
if (!inCode && /^```(\w*)/.test(line)) {
|
|
670
|
+
inCode = true; codeLang = line.match(/^```(\w*)/)[1]; codeLines = [];
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
if (inCode && line.trim() === '```') {
|
|
674
|
+
html += `<pre><code>${escHtml(codeLines.join('\n'))}</code></pre>`;
|
|
675
|
+
inCode = false; continue;
|
|
676
|
+
}
|
|
677
|
+
if (inCode) { codeLines.push(line); continue; }
|
|
678
|
+
|
|
679
|
+
let l = escHtml(line);
|
|
680
|
+
// 标题
|
|
681
|
+
if (/^### /.test(l)) { html += `<h4>${l.slice(4)}</h4>`; continue; }
|
|
682
|
+
if (/^## /.test(l)) { html += `<h3>${l.slice(3)}</h3>`; continue; }
|
|
683
|
+
if (/^# /.test(l)) { html += `<h2>${l.slice(2)}</h2>`; continue; }
|
|
684
|
+
// 行内格式
|
|
685
|
+
l = l.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
|
|
686
|
+
l = l.replace(/\*(.+?)\*/g, '<em>$1</em>');
|
|
687
|
+
l = l.replace(/`([^`]+)`/g, '<code>$1</code>');
|
|
688
|
+
// 列表
|
|
689
|
+
if (/^- /.test(l)) { html += `<li>${l.slice(2)}</li>`; continue; }
|
|
690
|
+
if (/^\d+\. /.test(l)) { html += `<li>${l.replace(/^\d+\.\s*/, '')}</li>`; continue; }
|
|
691
|
+
|
|
692
|
+
html += l + '<br>';
|
|
693
|
+
}
|
|
694
|
+
if (inCode) html += `<pre><code>${escHtml(codeLines.join('\n'))}</code></pre>`;
|
|
695
|
+
// 包裹连续 li 为 ul
|
|
696
|
+
html = html.replace(/(<li>[\s\S]*?<\/li>)(?![\s\S]*?<li>)/g, (m) => `<ul>${m}</ul>`);
|
|
697
|
+
return html;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// ── 块分类器 ──────────────────────────────────
|
|
701
|
+
function isClaudeSession(session) {
|
|
702
|
+
const cmd = (session.initCmd || '').toLowerCase();
|
|
703
|
+
const title = (session.title || '').toLowerCase();
|
|
704
|
+
return cmd.includes('claude') || title.includes('claude');
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function classifyBlock(raw) {
|
|
708
|
+
const clean = stripAnsi(raw).trim();
|
|
709
|
+
if (!clean) return { type: 'empty' };
|
|
710
|
+
|
|
711
|
+
// 思考状态 — 提取思考内容(spinner后的文字)
|
|
712
|
+
if (/^(\s*[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]|Thinking)/i.test(clean)) {
|
|
713
|
+
const content = clean.replace(/^[\s⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]+/, '').replace(/^Thinking\S*\s*/i, '').trim();
|
|
714
|
+
return { type: 'thinking', content };
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// 权限请求
|
|
718
|
+
// Diff
|
|
719
|
+
const lines = clean.split('\n');
|
|
720
|
+
const hasDiffMarkers = lines.some(l => /^[+-](?![-+]{2})/.test(l)) && lines.some(l => /^@@/.test(l) || /^(---|[\+]{3})\s/.test(l));
|
|
721
|
+
if (hasDiffMarkers) return { type: 'diff' };
|
|
722
|
+
|
|
723
|
+
// 工具调用(Claude Code 使用 box-drawing 字符或特定标签)
|
|
724
|
+
if (/^[╭┌│╰┘╮┐└┤├]/.test(lines[0]?.trim()) ||
|
|
725
|
+
/^\s*(Read|Edit|Write|Bash|Grep|Glob|WebFetch|WebSearch|LSP|TodoRead|TodoWrite|Agent)\s*[:(]/i.test(lines[0]?.trim())) {
|
|
726
|
+
return { type: 'tool', name: extractToolName(clean) };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// 错误
|
|
730
|
+
if (/^(Error|✗|✘|ERROR|error:)/i.test(clean.trim())) return { type: 'error' };
|
|
731
|
+
|
|
732
|
+
// 成功
|
|
733
|
+
if (/^(✓|✔|Done|Success|Created|Updated|已完成|已创建)/i.test(clean.trim())) return { type: 'success' };
|
|
734
|
+
|
|
735
|
+
// 提示符
|
|
736
|
+
if (lines.length <= 2 && /^[>❯$]\s*$/.test(clean)) return { type: 'prompt' };
|
|
737
|
+
|
|
738
|
+
// 默认:文本
|
|
739
|
+
return { type: 'text' };
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
function extractToolName(clean) {
|
|
743
|
+
const m = clean.match(/^\s*(Read|Edit|Write|Bash|Grep|Glob|WebFetch|WebSearch|LSP|TodoRead|TodoWrite|Agent)/i);
|
|
744
|
+
return m ? m[1] : '工具';
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
const TOOL_ICONS = { Read:'📄', Edit:'✏️', Write:'📝', Bash:'💻', Grep:'🔍', Glob:'📂', WebFetch:'🌐', WebSearch:'🔎', LSP:'🔧', Agent:'🤖' };
|
|
748
|
+
|
|
749
|
+
// ── 消息渲染 ──────────────────────────────────
|
|
750
|
+
function addInputMessage(text) {
|
|
751
|
+
endStream(); endToolGroup();
|
|
752
|
+
const msg = document.createElement('div');
|
|
753
|
+
msg.className = 'msg msg-input';
|
|
754
|
+
msg.innerHTML = `<div><div class="bubble">${escHtml(text)}</div><div class="meta">${formatTime(new Date())}</div></div>`;
|
|
755
|
+
chatArea.appendChild(msg);
|
|
756
|
+
trimMessages();
|
|
757
|
+
scrollToBottom();
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
function addStatusMessage(text) {
|
|
761
|
+
endStream(); endToolGroup();
|
|
762
|
+
const msg = document.createElement('div');
|
|
763
|
+
msg.className = 'msg msg-status';
|
|
764
|
+
msg.textContent = '— ' + text + ' —';
|
|
765
|
+
chatArea.appendChild(msg);
|
|
766
|
+
trimMessages();
|
|
767
|
+
scrollToBottom();
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
let _streamEl = null; // 当前流式输出的 assistant 元素
|
|
771
|
+
let _streamText = ''; // 累积的原始文本
|
|
772
|
+
|
|
773
|
+
function addAssistantMessage(raw) {
|
|
774
|
+
removeThinking(); endToolGroup();
|
|
775
|
+
const clean = stripAnsi(raw).trim();
|
|
776
|
+
if (!clean) return;
|
|
777
|
+
|
|
778
|
+
// 流式追加:如果上一个消息还是 assistant 且在活跃状态,合并
|
|
779
|
+
if (_streamEl && chatArea.contains(_streamEl)) {
|
|
780
|
+
_streamText += '\n' + clean;
|
|
781
|
+
const content = _streamEl.querySelector('.content');
|
|
782
|
+
if (content) content.innerHTML = renderMarkdown(_streamText);
|
|
783
|
+
scrollToBottom();
|
|
784
|
+
setWorkState('working');
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// 新建 assistant 消息
|
|
789
|
+
_streamText = clean;
|
|
790
|
+
const msg = document.createElement('div');
|
|
791
|
+
msg.className = 'msg msg-assistant';
|
|
792
|
+
const content = document.createElement('div');
|
|
793
|
+
content.className = 'content';
|
|
794
|
+
content.innerHTML = renderMarkdown(clean);
|
|
795
|
+
msg.appendChild(content);
|
|
796
|
+
chatArea.appendChild(msg);
|
|
797
|
+
_streamEl = msg;
|
|
798
|
+
trimMessages();
|
|
799
|
+
scrollToBottom();
|
|
800
|
+
setWorkState('working');
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// 流式增量追加(content_block_delta)
|
|
804
|
+
function appendStream(text) {
|
|
805
|
+
endToolGroup();
|
|
806
|
+
if (_streamEl && chatArea.contains(_streamEl)) {
|
|
807
|
+
_streamText += text;
|
|
808
|
+
const content = _streamEl.querySelector('.content');
|
|
809
|
+
if (content) content.innerHTML = renderMarkdown(_streamText);
|
|
810
|
+
scrollToBottom();
|
|
811
|
+
} else {
|
|
812
|
+
// 还没有流式容器,新建一个
|
|
813
|
+
_streamText = text;
|
|
814
|
+
const msg = document.createElement('div');
|
|
815
|
+
msg.className = 'msg msg-assistant';
|
|
816
|
+
const content = document.createElement('div');
|
|
817
|
+
content.className = 'content';
|
|
818
|
+
content.innerHTML = renderMarkdown(text);
|
|
819
|
+
msg.appendChild(content);
|
|
820
|
+
chatArea.appendChild(msg);
|
|
821
|
+
_streamEl = msg;
|
|
822
|
+
trimMessages();
|
|
823
|
+
scrollToBottom();
|
|
824
|
+
}
|
|
825
|
+
setWorkState('working');
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
function appendThinking(text) {
|
|
829
|
+
if (!thinkingEl) { showThinking(text); return; }
|
|
830
|
+
const content = thinkingEl.querySelector('.thinking-content');
|
|
831
|
+
if (content) { content.textContent += text; scrollToBottom(); }
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// 当收到非 assistant 类型的消息时,结束流式追加
|
|
835
|
+
function endStream() { _streamEl = null; _streamText = ''; }
|
|
836
|
+
|
|
837
|
+
let _toolGroupEl = null; // 当前工具组容器
|
|
838
|
+
let _toolGroupCount = 0;
|
|
839
|
+
|
|
840
|
+
function addToolMessage(raw, toolName) {
|
|
841
|
+
removeThinking();
|
|
842
|
+
const icon = TOOL_ICONS[toolName] || '🔧';
|
|
843
|
+
const collapsed = settings.collapseTools;
|
|
844
|
+
|
|
845
|
+
// 创建单个工具项
|
|
846
|
+
const toolItem = document.createElement('div');
|
|
847
|
+
toolItem.className = 'msg-tool';
|
|
848
|
+
const header = document.createElement('div');
|
|
849
|
+
header.className = 'tool-header';
|
|
850
|
+
header.innerHTML = `<span class="arrow ${collapsed ? '' : 'open'}">▶</span> ${icon} ${escHtml(toolName)}`;
|
|
851
|
+
const body = document.createElement('div');
|
|
852
|
+
body.className = `tool-body ${collapsed ? '' : 'open'}`;
|
|
853
|
+
body.innerHTML = renderAnsiHtml(raw);
|
|
854
|
+
header.onclick = () => { body.classList.toggle('open'); header.querySelector('.arrow').classList.toggle('open'); };
|
|
855
|
+
toolItem.appendChild(header);
|
|
856
|
+
toolItem.appendChild(body);
|
|
857
|
+
|
|
858
|
+
// 合并到现有工具组,或创建新组
|
|
859
|
+
const last = chatArea.lastElementChild;
|
|
860
|
+
if (last?.classList.contains('msg-tool-group') && last === _toolGroupEl) {
|
|
861
|
+
// 追加到现有组
|
|
862
|
+
_toolGroupCount++;
|
|
863
|
+
const groupBody = last.querySelector('.tool-group-body');
|
|
864
|
+
groupBody.appendChild(toolItem);
|
|
865
|
+
// 更新组头计数和展开按钮
|
|
866
|
+
const countSpan = last.querySelector('.tool-group-count');
|
|
867
|
+
if (countSpan) countSpan.textContent = `🔧 ${_toolGroupCount} 个工具调用`;
|
|
868
|
+
} else {
|
|
869
|
+
// 创建新的工具组
|
|
870
|
+
_toolGroupCount = 1;
|
|
871
|
+
const group = document.createElement('div');
|
|
872
|
+
group.className = 'msg msg-tool-group';
|
|
873
|
+
const groupHeader = document.createElement('div');
|
|
874
|
+
groupHeader.className = 'tool-group-header';
|
|
875
|
+
groupHeader.innerHTML = `<span class="arrow">▶</span> <span class="tool-group-count">🔧 1 个工具调用</span>`;
|
|
876
|
+
const expandBtn = document.createElement('button');
|
|
877
|
+
expandBtn.className = 'tool-expand-btn';
|
|
878
|
+
expandBtn.textContent = '展开全部';
|
|
879
|
+
groupHeader.appendChild(expandBtn);
|
|
880
|
+
const groupBody = document.createElement('div');
|
|
881
|
+
groupBody.className = 'tool-group-body';
|
|
882
|
+
groupBody.appendChild(toolItem);
|
|
883
|
+
// 点击组头:只展开/收起组
|
|
884
|
+
groupHeader.onclick = (e) => {
|
|
885
|
+
if (e.target === expandBtn) return;
|
|
886
|
+
groupBody.classList.toggle('open');
|
|
887
|
+
groupHeader.querySelector('.arrow').classList.toggle('open');
|
|
888
|
+
};
|
|
889
|
+
// 点击展开/收起全部按钮
|
|
890
|
+
expandBtn.onclick = (e) => {
|
|
891
|
+
e.stopPropagation();
|
|
892
|
+
const allOpen = groupBody.classList.contains('open') && !groupBody.querySelector('.tool-body:not(.open)');
|
|
893
|
+
if (allOpen) {
|
|
894
|
+
// 全部收起
|
|
895
|
+
groupBody.classList.remove('open');
|
|
896
|
+
groupHeader.querySelector('.arrow').classList.remove('open');
|
|
897
|
+
groupBody.querySelectorAll('.tool-body').forEach(b => b.classList.remove('open'));
|
|
898
|
+
groupBody.querySelectorAll('.tool-header .arrow').forEach(a => a.classList.remove('open'));
|
|
899
|
+
expandBtn.textContent = '展开全部';
|
|
900
|
+
} else {
|
|
901
|
+
// 全部展开
|
|
902
|
+
groupBody.classList.add('open');
|
|
903
|
+
groupHeader.querySelector('.arrow').classList.add('open');
|
|
904
|
+
groupBody.querySelectorAll('.tool-body').forEach(b => b.classList.add('open'));
|
|
905
|
+
groupBody.querySelectorAll('.tool-header .arrow').forEach(a => a.classList.add('open'));
|
|
906
|
+
expandBtn.textContent = '收起全部';
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
group.appendChild(groupHeader);
|
|
910
|
+
group.appendChild(groupBody);
|
|
911
|
+
chatArea.appendChild(group);
|
|
912
|
+
_toolGroupEl = group;
|
|
913
|
+
trimMessages();
|
|
914
|
+
}
|
|
915
|
+
scrollToBottom();
|
|
916
|
+
setWorkState('working');
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
// 非工具消息时结束工具组
|
|
920
|
+
function endToolGroup() { _toolGroupEl = null; _toolGroupCount = 0; }
|
|
921
|
+
|
|
922
|
+
function addDiffMessage(raw) {
|
|
923
|
+
removeThinking();
|
|
924
|
+
const lines = stripAnsi(raw).split('\n');
|
|
925
|
+
let html = '';
|
|
926
|
+
for (const line of lines) {
|
|
927
|
+
if (/^(---|\+\+\+)\s/.test(line)) html += `<div class="diff-file">${escHtml(line)}</div>`;
|
|
928
|
+
else if (/^@@/.test(line)) html += `<div class="diff-hunk">${escHtml(line)}</div>`;
|
|
929
|
+
else if (/^\+/.test(line)) html += `<div class="diff-add">${escHtml(line)}</div>`;
|
|
930
|
+
else if (/^-/.test(line)) html += `<div class="diff-del">${escHtml(line)}</div>`;
|
|
931
|
+
else html += `<div>${escHtml(line)}</div>`;
|
|
932
|
+
}
|
|
933
|
+
const msg = document.createElement('div');
|
|
934
|
+
msg.className = 'msg msg-diff';
|
|
935
|
+
msg.innerHTML = html;
|
|
936
|
+
chatArea.appendChild(msg);
|
|
937
|
+
trimMessages();
|
|
938
|
+
scrollToBottom();
|
|
939
|
+
setWorkState('working');
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
function addErrorMessage(raw) {
|
|
943
|
+
removeThinking();
|
|
944
|
+
const msg = document.createElement('div');
|
|
945
|
+
msg.className = 'msg msg-error';
|
|
946
|
+
msg.textContent = stripAnsi(raw).trim();
|
|
947
|
+
chatArea.appendChild(msg);
|
|
948
|
+
trimMessages();
|
|
949
|
+
scrollToBottom();
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
let _thinkingText = '';
|
|
953
|
+
|
|
954
|
+
function showThinking(content) {
|
|
955
|
+
if (!settings.showThinking && !thinkingEl) return;
|
|
956
|
+
|
|
957
|
+
const cleanContent = content ? stripAnsi(content).trim() : '';
|
|
958
|
+
|
|
959
|
+
if (thinkingEl) {
|
|
960
|
+
// 追加思考内容
|
|
961
|
+
if (cleanContent) {
|
|
962
|
+
_thinkingText += (_thinkingText ? '\n' : '') + cleanContent;
|
|
963
|
+
const body = thinkingEl.querySelector('.thinking-body');
|
|
964
|
+
if (body) {
|
|
965
|
+
body.textContent = _thinkingText;
|
|
966
|
+
body.scrollTop = body.scrollHeight;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
scrollToBottom();
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
_thinkingText = cleanContent;
|
|
974
|
+
thinkingEl = document.createElement('div');
|
|
975
|
+
thinkingEl.className = 'msg msg-thinking';
|
|
976
|
+
|
|
977
|
+
const header = document.createElement('div');
|
|
978
|
+
header.className = 'thinking-header';
|
|
979
|
+
header.innerHTML = '<span class="arrow">▶</span> 思考中 <span class="thinking-dots"><span></span><span></span><span></span></span>';
|
|
980
|
+
|
|
981
|
+
const body = document.createElement('div');
|
|
982
|
+
body.className = 'thinking-body';
|
|
983
|
+
if (_thinkingText) body.textContent = _thinkingText;
|
|
984
|
+
|
|
985
|
+
header.onclick = () => {
|
|
986
|
+
body.classList.toggle('open');
|
|
987
|
+
header.querySelector('.arrow').classList.toggle('open');
|
|
988
|
+
};
|
|
989
|
+
|
|
990
|
+
thinkingEl.appendChild(header);
|
|
991
|
+
thinkingEl.appendChild(body);
|
|
992
|
+
chatArea.appendChild(thinkingEl);
|
|
993
|
+
scrollToBottom();
|
|
994
|
+
setWorkState('thinking');
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
function removeThinking() {
|
|
998
|
+
if (thinkingEl) {
|
|
999
|
+
// 如果有思考内容,保留为折叠状态(去掉动画dots)
|
|
1000
|
+
if (_thinkingText) {
|
|
1001
|
+
const dots = thinkingEl.querySelector('.thinking-dots');
|
|
1002
|
+
if (dots) dots.remove();
|
|
1003
|
+
const header = thinkingEl.querySelector('.thinking-header');
|
|
1004
|
+
if (header) {
|
|
1005
|
+
const arrow = header.querySelector('.arrow');
|
|
1006
|
+
// 更新文字为"思考完成"
|
|
1007
|
+
header.innerHTML = '';
|
|
1008
|
+
header.appendChild(arrow);
|
|
1009
|
+
header.append(' 思考过程');
|
|
1010
|
+
}
|
|
1011
|
+
} else {
|
|
1012
|
+
thinkingEl.remove();
|
|
1013
|
+
}
|
|
1014
|
+
thinkingEl = null;
|
|
1015
|
+
_thinkingText = '';
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
function addRawOutput(raw) {
|
|
1020
|
+
endStream(); endToolGroup();
|
|
1021
|
+
removeThinking();
|
|
1022
|
+
if (!stripAnsi(raw).trim()) return;
|
|
1023
|
+
// 合并到上一个 raw 输出块(避免 DOM 碎片化)
|
|
1024
|
+
const last = chatArea.lastElementChild;
|
|
1025
|
+
if (last?.classList.contains('msg-raw')) {
|
|
1026
|
+
const block = last.querySelector('.code-block');
|
|
1027
|
+
if (block) {
|
|
1028
|
+
block.innerHTML += renderAnsiHtml(raw);
|
|
1029
|
+
// 限制单块行数
|
|
1030
|
+
const lines = block.innerHTML.split('\n');
|
|
1031
|
+
if (lines.length > 300) block.innerHTML = lines.slice(-200).join('\n');
|
|
1032
|
+
scrollToBottom();
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
const msg = document.createElement('div');
|
|
1037
|
+
msg.className = 'msg msg-raw';
|
|
1038
|
+
const block = document.createElement('div');
|
|
1039
|
+
block.className = 'code-block';
|
|
1040
|
+
block.innerHTML = renderAnsiHtml(raw);
|
|
1041
|
+
msg.appendChild(block);
|
|
1042
|
+
chatArea.appendChild(msg);
|
|
1043
|
+
trimMessages();
|
|
1044
|
+
scrollToBottom();
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
function addHistoryBlock(raw) {
|
|
1048
|
+
if (!stripAnsi(raw).trim()) return;
|
|
1049
|
+
let lines = raw.split('\n');
|
|
1050
|
+
if (lines.length > 200) lines = lines.slice(-200);
|
|
1051
|
+
const msg = document.createElement('div');
|
|
1052
|
+
msg.className = 'msg msg-history';
|
|
1053
|
+
msg.innerHTML = `<div class="meta">历史输出</div><div class="code-block">${renderAnsiHtml(lines.join('\n'))}</div>`;
|
|
1054
|
+
chatArea.appendChild(msg);
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
// ── 权限弹窗队列管理 ──────────────────────────────
|
|
1058
|
+
const permQueue = [];
|
|
1059
|
+
let permModalOpen = false;
|
|
1060
|
+
|
|
1061
|
+
function showPermModal(item) {
|
|
1062
|
+
const modal = document.getElementById('perm-modal');
|
|
1063
|
+
document.getElementById('pm-title').textContent = `${item.toolName} 请求权限`;
|
|
1064
|
+
document.getElementById('pm-tool').textContent = item.toolLabel || '';
|
|
1065
|
+
document.getElementById('pm-detail').textContent = item.detail;
|
|
1066
|
+
const queueEl = document.getElementById('pm-queue');
|
|
1067
|
+
if (permQueue.length > 0) {
|
|
1068
|
+
queueEl.textContent = `还有 ${permQueue.length} 个权限请求等待处理`;
|
|
1069
|
+
queueEl.style.display = '';
|
|
1070
|
+
} else {
|
|
1071
|
+
queueEl.style.display = 'none';
|
|
1072
|
+
}
|
|
1073
|
+
document.getElementById('pm-btn-allow').onclick = () => respondPermModal(item.reqId, true, item.toolName, false);
|
|
1074
|
+
document.getElementById('pm-btn-deny').onclick = () => respondPermModal(item.reqId, false, item.toolName, false);
|
|
1075
|
+
document.getElementById('pm-btn-allow-all').onclick = () => respondPermModal(item.reqId, true, item.toolName, true);
|
|
1076
|
+
modal.classList.add('open');
|
|
1077
|
+
permModalOpen = true;
|
|
1078
|
+
if (navigator.vibrate) navigator.vibrate(100);
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
function closePermModal() {
|
|
1082
|
+
document.getElementById('perm-modal').classList.remove('open');
|
|
1083
|
+
permModalOpen = false;
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
function respondPermModal(requestId, allow, toolName, approveAll) {
|
|
1087
|
+
if (!isController) { addStatusMessage('你没有控制权,无法操作'); return; }
|
|
1088
|
+
socket.emit('agent:permission', { requestId, allow, toolName, approveAll });
|
|
1089
|
+
const inlineActions = document.querySelector(`.perm-actions[data-reqid="${requestId}"]`);
|
|
1090
|
+
if (inlineActions) inlineActions.innerHTML = allow
|
|
1091
|
+
? (approveAll ? '<span style="color:#58a6ff">✓ 后续都允许</span>' : '<span style="color:#3fb950">✓ 已允许</span>')
|
|
1092
|
+
: '<span style="color:#f85149">✗ 已拒绝</span>';
|
|
1093
|
+
if (approveAll) addStatusMessage(`已设置 ${toolName || '所有工具'} 后续自动允许`);
|
|
1094
|
+
closePermModal();
|
|
1095
|
+
setWorkState('working');
|
|
1096
|
+
// "后续都允许"时自动批准队列中的同类请求
|
|
1097
|
+
if (allow && approveAll) {
|
|
1098
|
+
const remaining = [];
|
|
1099
|
+
for (const item of permQueue) {
|
|
1100
|
+
if (item.toolName === toolName || !toolName) {
|
|
1101
|
+
socket.emit('agent:permission', { requestId: item.reqId, allow: true, toolName: item.toolName, approveAll: false });
|
|
1102
|
+
const ia = document.querySelector(`.perm-actions[data-reqid="${item.reqId}"]`);
|
|
1103
|
+
if (ia) ia.innerHTML = '<span style="color:#58a6ff">✓ 自动允许</span>';
|
|
1104
|
+
} else {
|
|
1105
|
+
remaining.push(item);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
permQueue.length = 0;
|
|
1109
|
+
permQueue.push(...remaining);
|
|
1110
|
+
}
|
|
1111
|
+
if (permQueue.length > 0) {
|
|
1112
|
+
const next = permQueue.shift();
|
|
1113
|
+
setTimeout(() => showPermModal(next), 200);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
function enqueuePermission(reqId, toolName, detail, toolLabel) {
|
|
1118
|
+
const item = { reqId, toolName, detail, toolLabel };
|
|
1119
|
+
if (!permModalOpen) {
|
|
1120
|
+
showPermModal(item);
|
|
1121
|
+
} else {
|
|
1122
|
+
permQueue.push(item);
|
|
1123
|
+
const queueEl = document.getElementById('pm-queue');
|
|
1124
|
+
queueEl.textContent = `还有 ${permQueue.length} 个权限请求等待处理`;
|
|
1125
|
+
queueEl.style.display = '';
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
document.getElementById('perm-modal-backdrop').addEventListener('click', () => {
|
|
1130
|
+
// 不自动关闭,必须明确选择
|
|
1131
|
+
});
|
|
1132
|
+
|
|
1133
|
+
window.respondAgentPermission = function(requestId, allow, btn, toolName) {
|
|
1134
|
+
if (!isController) { addStatusMessage('你没有控制权,无法操作'); return; }
|
|
1135
|
+
const approveAll = !!toolName;
|
|
1136
|
+
socket.emit('agent:permission', { requestId, allow, toolName, approveAll });
|
|
1137
|
+
const actions = btn.closest('.perm-actions');
|
|
1138
|
+
if (actions) actions.innerHTML = allow
|
|
1139
|
+
? (approveAll ? '<span style="color:#58a6ff">✓ 后续都允许</span>' : '<span style="color:#3fb950">✓ 已允许</span>')
|
|
1140
|
+
: '<span style="color:#f85149">✗ 已拒绝</span>';
|
|
1141
|
+
if (approveAll) addStatusMessage(`已设置 ${toolName} 后续自动允许`);
|
|
1142
|
+
setWorkState('working');
|
|
1143
|
+
if (permModalOpen) {
|
|
1144
|
+
closePermModal();
|
|
1145
|
+
if (permQueue.length > 0) {
|
|
1146
|
+
const next = permQueue.shift();
|
|
1147
|
+
setTimeout(() => showPermModal(next), 200);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
|
|
1152
|
+
// ── 输出处理 ──────────────────────────────────
|
|
1153
|
+
function flushOutput() {
|
|
1154
|
+
if (!outputBuffer) return;
|
|
1155
|
+
const raw = outputBuffer;
|
|
1156
|
+
outputBuffer = '';
|
|
1157
|
+
clearTimeout(outputTimer);
|
|
1158
|
+
processOutput(raw);
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
function processOutput(raw) {
|
|
1162
|
+
if (!stripAnsi(raw).trim()) return;
|
|
1163
|
+
|
|
1164
|
+
// 非 Claude 会话或解析关闭:原始输出
|
|
1165
|
+
if (!claudeSession || !settings.parseOutput) {
|
|
1166
|
+
addRawOutput(raw);
|
|
1167
|
+
return;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
// Claude 会话:分类并渲染
|
|
1171
|
+
const result = classifyBlock(raw);
|
|
1172
|
+
switch (result.type) {
|
|
1173
|
+
case 'thinking': showThinking(result.content); break;
|
|
1174
|
+
case 'tool': endStream(); addToolMessage(raw, result.name); break;
|
|
1175
|
+
case 'diff': endStream(); addDiffMessage(raw); break;
|
|
1176
|
+
case 'error': endStream(); addErrorMessage(raw); break;
|
|
1177
|
+
case 'prompt': endStream(); removeThinking(); setWorkState('idle'); break;
|
|
1178
|
+
case 'empty': break;
|
|
1179
|
+
case 'success':
|
|
1180
|
+
case 'text': addAssistantMessage(raw); break;
|
|
1181
|
+
default: addRawOutput(raw); break;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
// ── 工作状态 ──────────────────────────────────
|
|
1186
|
+
let workStateTimer = null;
|
|
1187
|
+
function setWorkState(state) {
|
|
1188
|
+
if (workState === state) return;
|
|
1189
|
+
workState = state;
|
|
1190
|
+
clearTimeout(workStateTimer);
|
|
1191
|
+
const el = document.getElementById('work-status');
|
|
1192
|
+
const STATES = {
|
|
1193
|
+
idle: { text: '空闲', dot: 'idle' },
|
|
1194
|
+
thinking: { text: '思考中...', dot: 'thinking' },
|
|
1195
|
+
working: { text: '执行中...', dot: 'working' },
|
|
1196
|
+
waiting: { text: '等待确认', dot: 'waiting' },
|
|
1197
|
+
};
|
|
1198
|
+
const s = STATES[state] || STATES.idle;
|
|
1199
|
+
el.innerHTML = `<span class="sb-dot ${s.dot}"></span> ${s.text}`;
|
|
1200
|
+
// 自动回归空闲
|
|
1201
|
+
if (state === 'working') workStateTimer = setTimeout(() => setWorkState('idle'), 5000);
|
|
1202
|
+
// Agent 模式下忙时显示取消按钮,隐藏发送按钮
|
|
1203
|
+
if (currentSession?.mode === 'agent') {
|
|
1204
|
+
const busy = state !== 'idle';
|
|
1205
|
+
cancelBtn.classList.toggle('show', busy);
|
|
1206
|
+
sendBtn.style.display = busy ? 'none' : '';
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// ── 权限模式 ──────────────────────────────────
|
|
1211
|
+
let currentMode = 'default';
|
|
1212
|
+
const MODES = [
|
|
1213
|
+
{ id: 'default', label: '交互审批' },
|
|
1214
|
+
{ id: 'acceptEdits', label: '自动编辑' },
|
|
1215
|
+
{ id: 'bypassPermissions', label: '全自动' },
|
|
1216
|
+
];
|
|
1217
|
+
|
|
1218
|
+
function updateModeUI() {
|
|
1219
|
+
const m = MODES.find(x => x.id === currentMode) || MODES[0];
|
|
1220
|
+
document.getElementById('mode-badge').textContent = m.label;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
window.switchMode = function() {
|
|
1224
|
+
if (!isController) return;
|
|
1225
|
+
const idx = MODES.findIndex(x => x.id === currentMode);
|
|
1226
|
+
currentMode = MODES[(idx + 1) % MODES.length].id;
|
|
1227
|
+
updateModeUI();
|
|
1228
|
+
socket.emit('set-mode', { sessionId: SESSION_ID, mode: currentMode });
|
|
1229
|
+
addStatusMessage(`权限模式已切换为:${MODES.find(x => x.id === currentMode)?.label}`);
|
|
1230
|
+
};
|
|
1231
|
+
|
|
1232
|
+
function updateShortcutBar() {
|
|
1233
|
+
if (!currentSession) { shortcutBar.style.display = 'none'; return; }
|
|
1234
|
+
shortcutBar.style.display = '';
|
|
1235
|
+
document.getElementById('input-area').classList.toggle('no-shortcuts', false);
|
|
1236
|
+
document.getElementById('sk-claude-agent').style.display = 'flex';
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
// ── Socket.IO ──────────────────────────────────
|
|
1240
|
+
const socket = io({
|
|
1241
|
+
transports: ['polling', 'websocket'],
|
|
1242
|
+
reconnection: true,
|
|
1243
|
+
reconnectionAttempts: Infinity,
|
|
1244
|
+
reconnectionDelay: 1000,
|
|
1245
|
+
reconnectionDelayMax: 10000,
|
|
1246
|
+
timeout: 30000,
|
|
1247
|
+
});
|
|
1248
|
+
let isScrollbackPhase = false;
|
|
1249
|
+
|
|
1250
|
+
function showOverlay(text, showBack = false) {
|
|
1251
|
+
overlay.innerHTML = '';
|
|
1252
|
+
overlay.classList.remove('hidden');
|
|
1253
|
+
const msg = document.createElement('div');
|
|
1254
|
+
msg.textContent = text;
|
|
1255
|
+
overlay.appendChild(msg);
|
|
1256
|
+
if (showBack) {
|
|
1257
|
+
const btn = document.createElement('button');
|
|
1258
|
+
btn.textContent = '返回首页';
|
|
1259
|
+
btn.style.cssText = 'margin-top:1rem;padding:0.5rem 1.5rem;border:1px solid #8b949e;border-radius:8px;background:transparent;color:#c9d1d9;cursor:pointer;font-size:0.9rem';
|
|
1260
|
+
btn.onclick = () => window.location.href = '/';
|
|
1261
|
+
overlay.appendChild(btn);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
let _reconnectFails = 0;
|
|
1266
|
+
let _joinTimer = null;
|
|
1267
|
+
|
|
1268
|
+
// 初始连接超时:5秒后显示返回按钮
|
|
1269
|
+
let _initTimer = setTimeout(() => {
|
|
1270
|
+
if (!overlay.classList.contains('hidden')) {
|
|
1271
|
+
showOverlay('连接超时,请检查网络', true);
|
|
1272
|
+
}
|
|
1273
|
+
}, 8000);
|
|
1274
|
+
|
|
1275
|
+
socket.on('connect', () => {
|
|
1276
|
+
_reconnectFails = 0;
|
|
1277
|
+
showOverlay('正在加入会话...');
|
|
1278
|
+
socket.emit('join', SESSION_ID);
|
|
1279
|
+
// 加入超时:5秒内没收到 joined 则提示
|
|
1280
|
+
clearTimeout(_joinTimer);
|
|
1281
|
+
_joinTimer = setTimeout(() => {
|
|
1282
|
+
if (!overlay.classList.contains('hidden')) {
|
|
1283
|
+
showOverlay('会话加入超时,可能已被删除', true);
|
|
1284
|
+
}
|
|
1285
|
+
}, 8000);
|
|
1286
|
+
});
|
|
1287
|
+
socket.on('connect_error', () => {
|
|
1288
|
+
clearTimeout(_initTimer);
|
|
1289
|
+
_reconnectFails++;
|
|
1290
|
+
showOverlay(_reconnectFails >= 3 ? '连接失败,请检查网络' : `正在重连... (${_reconnectFails})`, _reconnectFails >= 3);
|
|
1291
|
+
// 连续失败 3 次后加载离线历史
|
|
1292
|
+
if (_reconnectFails === 3) {
|
|
1293
|
+
loadOfflineHistory(SESSION_ID).then((records) => {
|
|
1294
|
+
if (!records.length) return;
|
|
1295
|
+
showOverlay('离线模式 — 显示缓存历史', true);
|
|
1296
|
+
overlay.classList.add('hidden');
|
|
1297
|
+
for (const r of records.slice(-100)) {
|
|
1298
|
+
const msg = r.msg;
|
|
1299
|
+
if (msg.type === 'assistant' && msg.message?.content) {
|
|
1300
|
+
for (const b of msg.message.content) {
|
|
1301
|
+
if (b.type === 'text' && b.text) addAssistantMessage(b.text);
|
|
1302
|
+
}
|
|
1303
|
+
} else if (msg.type === 'result') {
|
|
1304
|
+
addStatusMessage('完成' + (msg.total_cost_usd ? ` ($${msg.total_cost_usd.toFixed(4)})` : ''));
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
addStatusMessage('⚡ 离线缓存 — 以上为历史记录');
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
});
|
|
1311
|
+
socket.on('disconnect', () => {
|
|
1312
|
+
showOverlay('已断开连接,正在重连...');
|
|
1313
|
+
// 断开 5 秒后仍未重连则显示返回按钮
|
|
1314
|
+
setTimeout(() => {
|
|
1315
|
+
if (!socket.connected && !overlay.classList.contains('hidden')) {
|
|
1316
|
+
showOverlay('连接已断开', true);
|
|
1317
|
+
}
|
|
1318
|
+
}, 6000);
|
|
1319
|
+
});
|
|
1320
|
+
|
|
1321
|
+
// ── 移动端连接保活 ──────────────────────────────
|
|
1322
|
+
// 页面切换到前台时立即检查连接
|
|
1323
|
+
document.addEventListener('visibilitychange', () => {
|
|
1324
|
+
if (!document.hidden) {
|
|
1325
|
+
if (!socket.connected) {
|
|
1326
|
+
showOverlay('正在重新连接...');
|
|
1327
|
+
socket.disconnect(); // 先断开旧连接
|
|
1328
|
+
socket.connect(); // 重新建立
|
|
1329
|
+
// 恢复超时保护
|
|
1330
|
+
setTimeout(() => {
|
|
1331
|
+
if (!overlay.classList.contains('hidden')) {
|
|
1332
|
+
showOverlay('重连失败,请检查网络', true);
|
|
1333
|
+
}
|
|
1334
|
+
}, 8000);
|
|
1335
|
+
} else {
|
|
1336
|
+
// 连接还在,重新 join 确保状态同步
|
|
1337
|
+
socket.emit('join', SESSION_ID);
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
});
|
|
1341
|
+
|
|
1342
|
+
// 网络恢复时立即重连
|
|
1343
|
+
window.addEventListener('online', () => {
|
|
1344
|
+
if (!socket.connected) {
|
|
1345
|
+
showOverlay('网络已恢复,正在重连...');
|
|
1346
|
+
socket.connect();
|
|
1347
|
+
}
|
|
1348
|
+
});
|
|
1349
|
+
window.addEventListener('offline', () => {
|
|
1350
|
+
showOverlay('网络已断开,等待恢复...');
|
|
1351
|
+
});
|
|
1352
|
+
|
|
1353
|
+
// 应用层心跳:每 15 秒检查连接状态
|
|
1354
|
+
setInterval(() => {
|
|
1355
|
+
if (!document.hidden && !socket.connected) {
|
|
1356
|
+
socket.connect();
|
|
1357
|
+
}
|
|
1358
|
+
}, 15000);
|
|
1359
|
+
|
|
1360
|
+
socket.on('joined', (session) => {
|
|
1361
|
+
clearTimeout(_initTimer);
|
|
1362
|
+
clearTimeout(_joinTimer);
|
|
1363
|
+
currentSession = session;
|
|
1364
|
+
overlay.classList.add('hidden');
|
|
1365
|
+
// 请求通知权限(不阻塞)
|
|
1366
|
+
try { requestNotifyPermission(); } catch {}
|
|
1367
|
+
document.title = session.title + ' — weHi';
|
|
1368
|
+
document.getElementById('session-title').textContent = session.title;
|
|
1369
|
+
if (session.cwd) document.getElementById('session-cwd').textContent = session.cwd;
|
|
1370
|
+
updateViewers(session.viewers);
|
|
1371
|
+
if (session.role) myRole = session.role;
|
|
1372
|
+
updateControlUI(session.controlHolder === socket.id, session.controlHolderName);
|
|
1373
|
+
|
|
1374
|
+
claudeSession = isClaudeSession(session) || session.mode === 'agent';
|
|
1375
|
+
currentMode = session.permissionMode || 'default';
|
|
1376
|
+
updateModeUI();
|
|
1377
|
+
updateShortcutBar();
|
|
1378
|
+
|
|
1379
|
+
// 更新输入框占位符
|
|
1380
|
+
cmdInput.placeholder = session.mode === 'agent' ? '输入消息...' : '输入命令...';
|
|
1381
|
+
|
|
1382
|
+
// 如果没人控制且有权限,自动获取控制权
|
|
1383
|
+
if (!session.controlHolder && canTakeControl()) {
|
|
1384
|
+
socket.emit('take-control', { sessionId: SESSION_ID });
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// PTY 模式的滚动缓冲区回放
|
|
1388
|
+
if (session.mode !== 'agent') {
|
|
1389
|
+
isScrollbackPhase = true;
|
|
1390
|
+
setTimeout(() => { isScrollbackPhase = false; }, 200);
|
|
1391
|
+
}
|
|
1392
|
+
});
|
|
1393
|
+
|
|
1394
|
+
socket.on('output', (data) => {
|
|
1395
|
+
if (isScrollbackPhase) { addHistoryBlock(data); return; }
|
|
1396
|
+
outputBuffer += data;
|
|
1397
|
+
clearTimeout(outputTimer);
|
|
1398
|
+
outputTimer = setTimeout(flushOutput, OUTPUT_DELAY);
|
|
1399
|
+
});
|
|
1400
|
+
|
|
1401
|
+
socket.on('session-exit', ({ code }) => { flushOutput(); addStatusMessage(`会话已退出 (code ${code})`); cmdInput.disabled = true; sendBtn.disabled = true; setWorkState('idle'); });
|
|
1402
|
+
socket.on('sessions', (sessions) => { const s = sessions.find(x => x.id === SESSION_ID); if (s) updateViewers(s.viewers); });
|
|
1403
|
+
socket.on('error', ({ message }) => { showOverlay('错误: ' + message, true); });
|
|
1404
|
+
|
|
1405
|
+
// 控制权事件
|
|
1406
|
+
socket.on('control-changed', ({ sessionId, holder, holderName }) => {
|
|
1407
|
+
if (sessionId !== SESSION_ID) return;
|
|
1408
|
+
updateControlUI(holder === socket.id, holderName);
|
|
1409
|
+
if (holder) addStatusMessage(holder === socket.id ? '你已获取控制权' : `${holderName || '其他用户'} 获取了控制权`);
|
|
1410
|
+
else addStatusMessage('控制权已释放');
|
|
1411
|
+
});
|
|
1412
|
+
socket.on('control-denied', ({ reason }) => addStatusMessage('无法获取控制: ' + reason));
|
|
1413
|
+
socket.on('mode-changed', ({ sessionId, mode }) => { if (sessionId === SESSION_ID) { currentMode = mode; updateModeUI(); } });
|
|
1414
|
+
socket.on('kicked', ({ reason }) => { addStatusMessage(reason || '你已被管理员踢出'); setTimeout(() => location.href = '/', 2000); });
|
|
1415
|
+
|
|
1416
|
+
// ── Agent 模式事件 ──────────────────────────────
|
|
1417
|
+
socket.on('agent:message', (msg) => {
|
|
1418
|
+
if (!msg) return;
|
|
1419
|
+
// 离线缓存:保存消息到 IndexedDB
|
|
1420
|
+
saveMessageToHistory(SESSION_ID, msg);
|
|
1421
|
+
switch (msg.type) {
|
|
1422
|
+
case 'system':
|
|
1423
|
+
if (msg.subtype === 'init') {
|
|
1424
|
+
addStatusMessage('Claude 会话已初始化');
|
|
1425
|
+
setWorkState('working');
|
|
1426
|
+
} else if (msg.subtype === 'interrupted') {
|
|
1427
|
+
addStatusMessage('查询已中断');
|
|
1428
|
+
setWorkState('idle');
|
|
1429
|
+
}
|
|
1430
|
+
break;
|
|
1431
|
+
case 'assistant':
|
|
1432
|
+
removeThinking();
|
|
1433
|
+
if (msg.message?.content) {
|
|
1434
|
+
for (const block of msg.message.content) {
|
|
1435
|
+
if (block.type === 'thinking' && block.thinking) {
|
|
1436
|
+
showThinking(block.thinking);
|
|
1437
|
+
} else if (block.type === 'text' && block.text) {
|
|
1438
|
+
addAssistantMessage(block.text);
|
|
1439
|
+
} else if (block.type === 'tool_use') {
|
|
1440
|
+
addToolMessage(JSON.stringify(block.input || {}, null, 2), block.name || '工具');
|
|
1441
|
+
} else if (block.type === 'tool_result') {
|
|
1442
|
+
const content = typeof block.content === 'string' ? block.content : JSON.stringify(block.content);
|
|
1443
|
+
addRawOutput(content);
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
setWorkState('working');
|
|
1448
|
+
break;
|
|
1449
|
+
case 'control_request':
|
|
1450
|
+
removeThinking();
|
|
1451
|
+
if (msg.request) {
|
|
1452
|
+
const toolName = msg.request.tool_name || '未知工具';
|
|
1453
|
+
const input = msg.request.input || {};
|
|
1454
|
+
const detail = toolName === 'Bash' ? (input.command || JSON.stringify(input))
|
|
1455
|
+
: toolName === 'Edit' ? `${input.file_path || ''}\n${input.old_string ? '替换: ' + input.old_string.slice(0, 120) : ''}`
|
|
1456
|
+
: toolName === 'Write' ? `${input.file_path || ''}`
|
|
1457
|
+
: toolName === 'Read' ? `${input.file_path || ''}`
|
|
1458
|
+
: JSON.stringify(input, null, 2);
|
|
1459
|
+
const reqId = msg.request_id || msg.request?.request_id || msg.uuid;
|
|
1460
|
+
const toolLabels = { Bash: '执行命令', Edit: '编辑文件', Write: '写入文件', Read: '读取文件', Glob: '搜索文件', Grep: '搜索内容' };
|
|
1461
|
+
const toolLabel = toolLabels[toolName] || toolName;
|
|
1462
|
+
const el = document.createElement('div');
|
|
1463
|
+
el.className = 'msg msg-permission';
|
|
1464
|
+
el.innerHTML = `<div class="perm-title">${escHtml(toolName)} 请求权限</div><div class="perm-detail">${escHtml(detail)}</div>
|
|
1465
|
+
<div class="perm-actions" data-reqid="${escHtml(reqId)}" data-tool="${escHtml(toolName)}">
|
|
1466
|
+
<button class="btn-allow" onclick="respondAgentPermission('${escHtml(reqId)}', true, this)">允许</button>
|
|
1467
|
+
<button class="btn-allow" onclick="respondAgentPermission('${escHtml(reqId)}', true, this, '${escHtml(toolName)}')" style="background:#1f6feb">后续都允许</button>
|
|
1468
|
+
<button class="btn-deny" onclick="respondAgentPermission('${escHtml(reqId)}', false, this)">拒绝</button>
|
|
1469
|
+
</div>`;
|
|
1470
|
+
chatArea.appendChild(el);
|
|
1471
|
+
trimMessages();
|
|
1472
|
+
scrollToBottom();
|
|
1473
|
+
setWorkState('waiting');
|
|
1474
|
+
enqueuePermission(reqId, toolName, detail, toolLabel);
|
|
1475
|
+
// 浏览器通知(页面在后��时)
|
|
1476
|
+
showPermissionNotification(toolName, detail, reqId, location.href);
|
|
1477
|
+
}
|
|
1478
|
+
break;
|
|
1479
|
+
case 'result':
|
|
1480
|
+
removeThinking();
|
|
1481
|
+
setWorkState('idle');
|
|
1482
|
+
const cost = msg.total_cost_usd ? ` ($${msg.total_cost_usd.toFixed(4)})` : '';
|
|
1483
|
+
addStatusMessage(`完成${cost}`);
|
|
1484
|
+
break;
|
|
1485
|
+
case 'content_block_start':
|
|
1486
|
+
// 流式内容块开始(tool_use 时显示工具名)
|
|
1487
|
+
if (msg.content_block?.type === 'tool_use') {
|
|
1488
|
+
addToolMessage('', msg.content_block.name || '工具');
|
|
1489
|
+
} else if (msg.content_block?.type === 'thinking') {
|
|
1490
|
+
showThinking('');
|
|
1491
|
+
}
|
|
1492
|
+
setWorkState('working');
|
|
1493
|
+
break;
|
|
1494
|
+
case 'content_block_delta':
|
|
1495
|
+
// 流式内容增量
|
|
1496
|
+
if (msg.delta?.type === 'text_delta' && msg.delta.text) {
|
|
1497
|
+
appendStream(msg.delta.text);
|
|
1498
|
+
} else if (msg.delta?.type === 'thinking_delta' && msg.delta.thinking) {
|
|
1499
|
+
appendThinking(msg.delta.thinking);
|
|
1500
|
+
} else if (msg.delta?.type === 'input_json_delta' && msg.delta.partial_json) {
|
|
1501
|
+
// 工具参数流式增量,暂不显示
|
|
1502
|
+
}
|
|
1503
|
+
break;
|
|
1504
|
+
case 'content_block_stop':
|
|
1505
|
+
endStream();
|
|
1506
|
+
break;
|
|
1507
|
+
case 'message_start':
|
|
1508
|
+
setWorkState('working');
|
|
1509
|
+
break;
|
|
1510
|
+
case 'message_delta':
|
|
1511
|
+
// 消息结束原因等
|
|
1512
|
+
break;
|
|
1513
|
+
case 'message_stop':
|
|
1514
|
+
break;
|
|
1515
|
+
case 'tool_use':
|
|
1516
|
+
// 独立工具调用消息
|
|
1517
|
+
addToolMessage(JSON.stringify(msg.input || {}, null, 2), msg.name || '工具');
|
|
1518
|
+
setWorkState('working');
|
|
1519
|
+
break;
|
|
1520
|
+
case 'tool_result':
|
|
1521
|
+
// 独立工具结果消息
|
|
1522
|
+
if (msg.content) {
|
|
1523
|
+
const text = typeof msg.content === 'string' ? msg.content
|
|
1524
|
+
: Array.isArray(msg.content) ? msg.content.map(b => b.text || '').join('\n')
|
|
1525
|
+
: JSON.stringify(msg.content);
|
|
1526
|
+
if (text.trim()) addRawOutput(text);
|
|
1527
|
+
}
|
|
1528
|
+
setWorkState('working');
|
|
1529
|
+
break;
|
|
1530
|
+
case 'rate_limit_event':
|
|
1531
|
+
case 'control_response':
|
|
1532
|
+
break; // 忽略
|
|
1533
|
+
default:
|
|
1534
|
+
// 未知消息类型,仅在有实质内容时显示
|
|
1535
|
+
if (msg.type !== 'user') {
|
|
1536
|
+
// 静默忽略常见的生命周期消息
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
});
|
|
1540
|
+
|
|
1541
|
+
socket.on('agent:history', (history) => {
|
|
1542
|
+
for (const msg of history) {
|
|
1543
|
+
endStream(); // 每条历史消息都是独立的,不要流式合并
|
|
1544
|
+
if (msg.type === 'user' && msg.content) {
|
|
1545
|
+
addInputMessage(msg.content);
|
|
1546
|
+
} else if (msg.type === 'assistant' && msg.message?.content) {
|
|
1547
|
+
// 将同一条 assistant 消息的所有 text block 合并为一条
|
|
1548
|
+
const texts = [];
|
|
1549
|
+
for (const block of msg.message.content) {
|
|
1550
|
+
if (block.type === 'thinking' && block.thinking) { showThinking(block.thinking); removeThinking(); }
|
|
1551
|
+
else if (block.type === 'text' && block.text) texts.push(block.text);
|
|
1552
|
+
else if (block.type === 'tool_use') addToolMessage(JSON.stringify(block.input || {}, null, 2), block.name || '工具');
|
|
1553
|
+
}
|
|
1554
|
+
if (texts.length) {
|
|
1555
|
+
const combined = texts.join('\n\n');
|
|
1556
|
+
const el = document.createElement('div');
|
|
1557
|
+
el.className = 'msg msg-assistant';
|
|
1558
|
+
const content = document.createElement('div');
|
|
1559
|
+
content.className = 'content';
|
|
1560
|
+
content.innerHTML = renderMarkdown(combined);
|
|
1561
|
+
el.appendChild(content);
|
|
1562
|
+
chatArea.appendChild(el);
|
|
1563
|
+
}
|
|
1564
|
+
} else if (msg.type === 'result') {
|
|
1565
|
+
const cost = msg.total_cost_usd ? ` ($${msg.total_cost_usd.toFixed(4)})` : '';
|
|
1566
|
+
addStatusMessage(`完成${cost}`);
|
|
1567
|
+
// 上下文预警
|
|
1568
|
+
if (msg.usage) {
|
|
1569
|
+
const ctxTokens = (msg.usage.input_tokens || 0) + (msg.usage.cache_read_input_tokens || 0);
|
|
1570
|
+
const CTX_LIMIT = 200000;
|
|
1571
|
+
const pct = Math.round(ctxTokens / CTX_LIMIT * 100);
|
|
1572
|
+
if (pct >= 90) {
|
|
1573
|
+
addStatusMessage(`\u26a0\ufe0f 上下文已达 ${pct}%(${(ctxTokens/1000).toFixed(0)}K/${CTX_LIMIT/1000}K),即将溢出!建议发送 /compact 压缩上下文`);
|
|
1574
|
+
} else if (pct >= 75) {
|
|
1575
|
+
addStatusMessage(`\u26a0 上下文 ${pct}%(${(ctxTokens/1000).toFixed(0)}K/${CTX_LIMIT/1000}K),建议适时 /compact`);
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
scrollToBottom();
|
|
1581
|
+
});
|
|
1582
|
+
|
|
1583
|
+
socket.on('agent:busy', (busy) => {
|
|
1584
|
+
if (busy) { showThinking(); setWorkState('thinking'); }
|
|
1585
|
+
else { removeThinking(); setWorkState('idle'); }
|
|
1586
|
+
});
|
|
1587
|
+
|
|
1588
|
+
socket.on('agent:error', ({ message }) => {
|
|
1589
|
+
removeThinking();
|
|
1590
|
+
addErrorMessage(message);
|
|
1591
|
+
setWorkState('idle');
|
|
1592
|
+
});
|
|
1593
|
+
|
|
1594
|
+
// ── 待发送图片 ──────────────────────────────────
|
|
1595
|
+
let _pendingImage = null; // { path, blobUrl }
|
|
1596
|
+
|
|
1597
|
+
window.clearPendingImage = function() {
|
|
1598
|
+
if (_pendingImage?.blobUrl) URL.revokeObjectURL(_pendingImage.blobUrl);
|
|
1599
|
+
_pendingImage = null;
|
|
1600
|
+
document.getElementById('img-preview').classList.remove('show');
|
|
1601
|
+
cmdInput.placeholder = currentSession?.mode === 'agent' ? '输入消息...' : '输入命令...';
|
|
1602
|
+
};
|
|
1603
|
+
|
|
1604
|
+
window.cancelAgent = function() {
|
|
1605
|
+
if (currentSession?.mode === 'agent' && workState !== 'idle') {
|
|
1606
|
+
socket.emit('agent:interrupt', { sessionId: SESSION_ID });
|
|
1607
|
+
}
|
|
1608
|
+
};
|
|
1609
|
+
|
|
1610
|
+
function setPendingImage(path, blobUrl) {
|
|
1611
|
+
_pendingImage = { path, blobUrl };
|
|
1612
|
+
const preview = document.getElementById('img-preview');
|
|
1613
|
+
document.getElementById('img-preview-thumb').src = blobUrl || '';
|
|
1614
|
+
preview.classList.add('show');
|
|
1615
|
+
cmdInput.placeholder = '输入文字描述后发送,或直接发送分析图片...';
|
|
1616
|
+
cmdInput.focus();
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
// ── 输入处理 ──────────────────────────────────
|
|
1620
|
+
window.sendCommand = sendCommand;
|
|
1621
|
+
function sendCommand() {
|
|
1622
|
+
const text = cmdInput.value.trim();
|
|
1623
|
+
if (!text && !_pendingImage) return;
|
|
1624
|
+
|
|
1625
|
+
if (!isController) {
|
|
1626
|
+
if (canTakeControl()) { socket.emit('take-control', { sessionId: SESSION_ID }); }
|
|
1627
|
+
else { addStatusMessage('其他用户控制中,无法发送'); return; }
|
|
1628
|
+
}
|
|
1629
|
+
endStream();
|
|
1630
|
+
|
|
1631
|
+
const imgPath = _pendingImage?.path || null;
|
|
1632
|
+
const userText = text;
|
|
1633
|
+
const displayText = imgPath ? `📷 ${userText || '分析图片'}` : text;
|
|
1634
|
+
|
|
1635
|
+
addInputMessage(displayText);
|
|
1636
|
+
|
|
1637
|
+
if (currentSession?.mode === 'agent') {
|
|
1638
|
+
const prompt = imgPath
|
|
1639
|
+
? `用户上传了一张图片,路径是 ${imgPath},请用 Read 工具读取这张图片。用户的要求是:${userText || '描述图片内容'}`
|
|
1640
|
+
: text;
|
|
1641
|
+
socket.emit('agent:query', { prompt });
|
|
1642
|
+
showThinking();
|
|
1643
|
+
} else {
|
|
1644
|
+
const input = imgPath
|
|
1645
|
+
? (userText ? `${userText} ${imgPath}` : imgPath)
|
|
1646
|
+
: text;
|
|
1647
|
+
socket.emit('input', input + '\r');
|
|
1648
|
+
}
|
|
1649
|
+
cmdHistory.unshift(imgPath ? `[图片] ${userText}` : text);
|
|
1650
|
+
if (cmdHistory.length > 100) cmdHistory.pop();
|
|
1651
|
+
historyIdx = -1;
|
|
1652
|
+
cmdInput.value = '';
|
|
1653
|
+
cmdInput.style.height = 'auto';
|
|
1654
|
+
clearPendingImage();
|
|
1655
|
+
cmdInput.focus();
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
cmdInput.addEventListener('keydown', (e) => {
|
|
1659
|
+
if (e.key === 'Escape') {
|
|
1660
|
+
e.preventDefault();
|
|
1661
|
+
if (currentSession?.mode === 'agent' && workState !== 'idle') {
|
|
1662
|
+
socket.emit('agent:interrupt', { sessionId: SESSION_ID });
|
|
1663
|
+
return;
|
|
1664
|
+
}
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1667
|
+
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendCommand(); }
|
|
1668
|
+
else if (e.key === 'ArrowUp' && !cmdInput.value) { if (historyIdx < cmdHistory.length - 1) { historyIdx++; cmdInput.value = cmdHistory[historyIdx]; } e.preventDefault(); }
|
|
1669
|
+
else if (e.key === 'ArrowDown' && !cmdInput.value) { if (historyIdx > 0) { historyIdx--; cmdInput.value = cmdHistory[historyIdx]; } else if (historyIdx === 0) { historyIdx = -1; cmdInput.value = ''; } e.preventDefault(); }
|
|
1670
|
+
});
|
|
1671
|
+
|
|
1672
|
+
// ── 快捷键 ──────────────────────────────────
|
|
1673
|
+
const SEQ = { 'ctrl-c': '\x03', 'ctrl-d': '\x04', 'tab': '\t', 'up': '\x1b[A', 'down': '\x1b[B', 'right': '\x1b[C', 'left': '\x1b[D', 'esc': '\x1b', 'ctrl-a': '\x01', 'ctrl-e': '\x05', 'ctrl-k': '\x0b', 'ctrl-u': '\x15', 'ctrl-r': '\x12', 'alt-.': '\x1b.' };
|
|
1674
|
+
document.querySelectorAll('.sk[data-send]').forEach(btn => {
|
|
1675
|
+
const send = () => { if (!isController) return; socket.emit('input', SEQ[btn.dataset.send] || btn.dataset.send); };
|
|
1676
|
+
btn.addEventListener('touchend', (e) => { e.preventDefault(); send(); });
|
|
1677
|
+
btn.addEventListener('click', send);
|
|
1678
|
+
});
|
|
1679
|
+
// Claude 命令快捷按钮
|
|
1680
|
+
document.querySelectorAll('.sk[data-cmd]').forEach(btn => {
|
|
1681
|
+
const send = () => { if (!isController) return; cmdInput.value = btn.dataset.cmd; sendCommand(); };
|
|
1682
|
+
btn.addEventListener('touchend', (e) => { e.preventDefault(); send(); });
|
|
1683
|
+
btn.addEventListener('click', send);
|
|
1684
|
+
});
|
|
1685
|
+
|
|
1686
|
+
// ── 控制权 ──────────────────────────────────
|
|
1687
|
+
function canTakeControl() { return myRole === 'admin' || myRole === 'operator'; }
|
|
1688
|
+
window.toggleControl = function() { if (isController) socket.emit('release-control', { sessionId: SESSION_ID }); else if (canTakeControl()) socket.emit('take-control', { sessionId: SESSION_ID }); };
|
|
1689
|
+
|
|
1690
|
+
function updateControlUI(controlling, holderName) {
|
|
1691
|
+
isController = controlling;
|
|
1692
|
+
const badge = document.getElementById('control-badge');
|
|
1693
|
+
if (controlling) {
|
|
1694
|
+
badge.className = 'controlling'; badge.id = 'control-badge';
|
|
1695
|
+
badge.textContent = '控制中';
|
|
1696
|
+
readonlyOverlay.style.display = 'none'; inputBox.style.display = '';
|
|
1697
|
+
inputBox.classList.remove('disabled');
|
|
1698
|
+
cmdInput.disabled = false; sendBtn.disabled = false;
|
|
1699
|
+
document.querySelectorAll('.sk').forEach(b => b.disabled = false);
|
|
1700
|
+
} else {
|
|
1701
|
+
badge.className = 'readonly'; badge.id = 'control-badge';
|
|
1702
|
+
badge.textContent = holderName ? (canTakeControl() ? '获取控制' : `${holderName} 控制中`) : (canTakeControl() ? '获取控制' : '只读');
|
|
1703
|
+
if (!canTakeControl()) { readonlyOverlay.style.display = 'block'; inputBox.style.display = 'none'; }
|
|
1704
|
+
else { readonlyOverlay.style.display = 'none'; inputBox.style.display = ''; inputBox.classList.remove('disabled'); cmdInput.disabled = false; sendBtn.disabled = false; }
|
|
1705
|
+
document.querySelectorAll('.sk').forEach(b => b.disabled = !canTakeControl());
|
|
1706
|
+
}
|
|
1707
|
+
updateShortcutBar();
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
// ── 设置面板 ──────────────────────────────────
|
|
1711
|
+
window.openSettings = function() { document.getElementById('settings-backdrop').classList.add('open'); document.getElementById('settings-panel').classList.add('open'); syncSettingsUI(); };
|
|
1712
|
+
window.closeSettings = function() { document.getElementById('settings-backdrop').classList.remove('open'); document.getElementById('settings-panel').classList.remove('open'); };
|
|
1713
|
+
|
|
1714
|
+
function syncSettingsUI() {
|
|
1715
|
+
document.getElementById('set-parse').checked = settings.parseOutput;
|
|
1716
|
+
document.getElementById('set-thinking').checked = settings.showThinking;
|
|
1717
|
+
document.getElementById('set-collapse').checked = settings.collapseTools;
|
|
1718
|
+
}
|
|
1719
|
+
document.getElementById('set-parse').addEventListener('change', (e) => { settings.parseOutput = e.target.checked; saveSettings(); });
|
|
1720
|
+
document.getElementById('set-thinking').addEventListener('change', (e) => { settings.showThinking = e.target.checked; saveSettings(); });
|
|
1721
|
+
document.getElementById('set-collapse').addEventListener('change', (e) => { settings.collapseTools = e.target.checked; saveSettings(); });
|
|
1722
|
+
|
|
1723
|
+
// ── 辅助 ──────────────────────────────────────
|
|
1724
|
+
function updateViewers(count) { document.getElementById('viewer-count').textContent = count > 1 ? `${count} 人在线` : ''; }
|
|
1725
|
+
window.goBack = function() { window.location.href = '/'; };
|
|
1726
|
+
window.openFiles = function() { window.open('/files?session=' + SESSION_ID, '_blank'); };
|
|
1727
|
+
window.openSync = function() { window.open('/sync?session=' + SESSION_ID, '_blank'); };
|
|
1728
|
+
// 仅桌面浏览器显示同步按钮
|
|
1729
|
+
if ('showDirectoryPicker' in window) {
|
|
1730
|
+
document.getElementById('sync-btn').style.display = '';
|
|
1731
|
+
}
|
|
1732
|
+
function scrollToBottom() { requestAnimationFrame(() => { chatArea.scrollTop = chatArea.scrollHeight; }); }
|
|
1733
|
+
function trimMessages() {
|
|
1734
|
+
const msgs = chatArea.querySelectorAll('.msg');
|
|
1735
|
+
if (msgs.length > MAX_MESSAGES) {
|
|
1736
|
+
const remove = msgs.length - MAX_MESSAGES;
|
|
1737
|
+
for (let i = 0; i < remove; i++) msgs[i].remove();
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
function formatTime(d) { return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' }); }
|
|
1741
|
+
|
|
1742
|
+
// ── 二维码 ──────────────────────────────────
|
|
1743
|
+
window.showQR = function() { document.getElementById('qr-img').src = `/qr/${SESSION_ID}`; document.getElementById('qr-modal').classList.add('open'); };
|
|
1744
|
+
window.closeQR = function() { document.getElementById('qr-modal').classList.remove('open'); };
|
|
1745
|
+
|
|
1746
|
+
// ── 模型选择 ──────────────────────────────────
|
|
1747
|
+
const MODELS = [
|
|
1748
|
+
{ id: 'claude-sonnet-4-6-20250627', label: 'Sonnet 4.6', desc: '快速、高性价比' },
|
|
1749
|
+
{ id: 'claude-opus-4-6-20250627', label: 'Opus 4.6', desc: '最强推理能力' },
|
|
1750
|
+
{ id: 'claude-sonnet-4-20250514', label: 'Sonnet 4', desc: '均衡性能' },
|
|
1751
|
+
{ id: 'claude-opus-4-20250514', label: 'Opus 4', desc: '强推理能力' },
|
|
1752
|
+
{ id: 'claude-haiku-4-5-20251001', label: 'Haiku 4.5', desc: '最快响应速度' },
|
|
1753
|
+
];
|
|
1754
|
+
let currentModelId = '';
|
|
1755
|
+
|
|
1756
|
+
window.openModelSheet = function() {
|
|
1757
|
+
const list = document.getElementById('model-list');
|
|
1758
|
+
list.innerHTML = '';
|
|
1759
|
+
MODELS.forEach(m => {
|
|
1760
|
+
const item = document.createElement('div');
|
|
1761
|
+
item.className = 'action-sheet-item';
|
|
1762
|
+
const isCurrent = currentModelId && m.id.includes(currentModelId);
|
|
1763
|
+
item.innerHTML = `<div><div>${m.label}</div><div class="desc">${m.desc}</div></div>${isCurrent ? '<span class="check">✓</span>' : ''}`;
|
|
1764
|
+
item.onclick = () => selectModel(m);
|
|
1765
|
+
list.appendChild(item);
|
|
1766
|
+
});
|
|
1767
|
+
document.getElementById('model-sheet').classList.add('open');
|
|
1768
|
+
};
|
|
1769
|
+
window.closeModelSheet = function() {
|
|
1770
|
+
document.getElementById('model-sheet').classList.remove('open');
|
|
1771
|
+
};
|
|
1772
|
+
function selectModel(m) {
|
|
1773
|
+
closeModelSheet();
|
|
1774
|
+
if (!isController) { if (canTakeControl()) socket.emit('take-control', { sessionId: SESSION_ID }); else { addStatusMessage('其他用户控制中'); return; } }
|
|
1775
|
+
if (currentSession?.mode === 'agent') {
|
|
1776
|
+
// Agent 模式:通过命令设置
|
|
1777
|
+
cmdInput.value = '/model ' + m.id;
|
|
1778
|
+
sendCommand();
|
|
1779
|
+
} else {
|
|
1780
|
+
// PTY 模式:发送 Escape 清除当前输入,再输入命令
|
|
1781
|
+
socket.emit('input', '\x03');
|
|
1782
|
+
setTimeout(() => {
|
|
1783
|
+
socket.emit('input', '/model ' + m.id + '\r');
|
|
1784
|
+
addInputMessage('/model ' + m.label);
|
|
1785
|
+
}, 100);
|
|
1786
|
+
}
|
|
1787
|
+
currentModelId = m.id;
|
|
1788
|
+
addStatusMessage('模型已切换为 ' + m.label);
|
|
1789
|
+
}
|
|
1790
|
+
document.getElementById('qr-modal').addEventListener('click', (e) => { if (e.target === e.currentTarget) window.closeQR(); });
|
|
1791
|
+
|
|
1792
|
+
// ── 恢复会话 ──────────────────────────────────
|
|
1793
|
+
window.openResumeSheet = async function() {
|
|
1794
|
+
if (!isController) { if (canTakeControl()) socket.emit('take-control', { sessionId: SESSION_ID }); else { addStatusMessage('其他用户控制中'); return; } }
|
|
1795
|
+
const list = document.getElementById('resume-list');
|
|
1796
|
+
list.innerHTML = '<div style="text-align:center;padding:1rem;color:#8b949e">加载中...</div>';
|
|
1797
|
+
document.getElementById('resume-sheet').classList.add('open');
|
|
1798
|
+
try {
|
|
1799
|
+
const res = await fetch('/api/claude-sessions');
|
|
1800
|
+
const sessions = await res.json();
|
|
1801
|
+
list.innerHTML = '';
|
|
1802
|
+
if (!sessions.length) {
|
|
1803
|
+
list.innerHTML = '<div style="text-align:center;padding:1rem;color:#8b949e">没有找到可恢复的会话</div>';
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
sessions.slice(0, 15).forEach(s => {
|
|
1807
|
+
const item = document.createElement('div');
|
|
1808
|
+
item.className = 'action-sheet-item';
|
|
1809
|
+
const time = s.updatedAt ? new Date(s.updatedAt).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : '未知';
|
|
1810
|
+
const proj = s.projectDir ? decodeURIComponent(s.projectDir).split(/[\\/]/).pop() : '';
|
|
1811
|
+
const title = s.summary || s.sessionId?.slice(0, 12) || '未命名';
|
|
1812
|
+
item.innerHTML = `<div style="min-width:0;flex:1"><div style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escHtml(title)}</div><div class="desc">${proj ? proj + ' · ' : ''}${time} · ${s.messageCount || 0} 条消息</div></div>`;
|
|
1813
|
+
item.onclick = () => resumeSession(s);
|
|
1814
|
+
list.appendChild(item);
|
|
1815
|
+
});
|
|
1816
|
+
} catch (e) {
|
|
1817
|
+
list.innerHTML = `<div style="text-align:center;padding:1rem;color:#f85149">加载失败: ${e.message}</div>`;
|
|
1818
|
+
}
|
|
1819
|
+
};
|
|
1820
|
+
window.closeResumeSheet = function() {
|
|
1821
|
+
document.getElementById('resume-sheet').classList.remove('open');
|
|
1822
|
+
};
|
|
1823
|
+
function resumeSession(s) {
|
|
1824
|
+
closeResumeSheet();
|
|
1825
|
+
const id = s.sessionId;
|
|
1826
|
+
const label = s.summary ? s.summary.slice(0, 30) : id.slice(0, 8);
|
|
1827
|
+
if (currentSession?.mode === 'agent') {
|
|
1828
|
+
cmdInput.value = '/resume ' + id;
|
|
1829
|
+
sendCommand();
|
|
1830
|
+
} else {
|
|
1831
|
+
socket.emit('input', '\x03');
|
|
1832
|
+
setTimeout(() => {
|
|
1833
|
+
socket.emit('input', '/resume ' + id + '\r');
|
|
1834
|
+
addInputMessage('/resume ' + label);
|
|
1835
|
+
}, 100);
|
|
1836
|
+
}
|
|
1837
|
+
addStatusMessage('正在恢复会话 ' + label + '...');
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
// ── 压缩对话 ──────────────────────────────────
|
|
1841
|
+
window.doCompact = function() {
|
|
1842
|
+
if (!isController) { if (canTakeControl()) socket.emit('take-control', { sessionId: SESSION_ID }); else { addStatusMessage('其他用户控制中'); return; } }
|
|
1843
|
+
if (currentSession?.mode === 'agent') {
|
|
1844
|
+
cmdInput.value = '/compact';
|
|
1845
|
+
sendCommand();
|
|
1846
|
+
} else {
|
|
1847
|
+
socket.emit('input', '\x03');
|
|
1848
|
+
setTimeout(() => {
|
|
1849
|
+
socket.emit('input', '/compact\r');
|
|
1850
|
+
addInputMessage('/compact');
|
|
1851
|
+
}, 100);
|
|
1852
|
+
}
|
|
1853
|
+
addStatusMessage('正在压缩对话上下文...');
|
|
1854
|
+
};
|
|
1855
|
+
|
|
1856
|
+
// ── 清除会话 ──────────────────────────────────
|
|
1857
|
+
window.doClear = function() {
|
|
1858
|
+
chatArea.innerHTML = '';
|
|
1859
|
+
endStream();
|
|
1860
|
+
if (!isController && canTakeControl()) socket.emit('take-control', { sessionId: SESSION_ID });
|
|
1861
|
+
socket.emit('agent:query', { prompt: '/clear' });
|
|
1862
|
+
clearSessionHistory(SESSION_ID); // 同时清除离线缓存
|
|
1863
|
+
addStatusMessage('已清除对话和 Claude 上下文');
|
|
1864
|
+
};
|
|
1865
|
+
|
|
1866
|
+
// ── 会话命名 ──────────────────────────────────
|
|
1867
|
+
let _slashCmd = null;
|
|
1868
|
+
const _slashTitles = { '/plan': '计划模式', '/compact': '压缩上下文', '/rename': '重命名会话' };
|
|
1869
|
+
const _slashHints = { '/plan': '输入计划描述...', '/compact': '输入压缩提示...', '/rename': '输入新名称...' };
|
|
1870
|
+
window.doSlashCmd = function(cmd) {
|
|
1871
|
+
_slashCmd = cmd;
|
|
1872
|
+
document.getElementById('slash-title').textContent = _slashTitles[cmd] || cmd;
|
|
1873
|
+
const inp = document.getElementById('slash-input');
|
|
1874
|
+
inp.placeholder = _slashHints[cmd] || '输入参数(可选)';
|
|
1875
|
+
inp.value = '';
|
|
1876
|
+
document.getElementById('slash-sheet').classList.add('open');
|
|
1877
|
+
setTimeout(() => inp.focus(), 100);
|
|
1878
|
+
};
|
|
1879
|
+
window.closeSlashSheet = function() {
|
|
1880
|
+
document.getElementById('slash-sheet').classList.remove('open');
|
|
1881
|
+
_slashCmd = null;
|
|
1882
|
+
};
|
|
1883
|
+
window.submitSlashCmd = function() {
|
|
1884
|
+
if (!_slashCmd) return;
|
|
1885
|
+
const input = document.getElementById('slash-input').value.trim();
|
|
1886
|
+
const prompt_text = input ? `${_slashCmd} ${input}` : _slashCmd;
|
|
1887
|
+
// /rename 同时更新 zihi 会话标题
|
|
1888
|
+
if (_slashCmd === '/rename' && input) {
|
|
1889
|
+
socket.emit('rename', { sessionId: SESSION_ID, title: input });
|
|
1890
|
+
}
|
|
1891
|
+
closeSlashSheet();
|
|
1892
|
+
if (!isController && canTakeControl()) socket.emit('take-control', { sessionId: SESSION_ID });
|
|
1893
|
+
socket.emit('agent:query', { prompt: prompt_text });
|
|
1894
|
+
addInputMessage(prompt_text);
|
|
1895
|
+
showThinking();
|
|
1896
|
+
};
|
|
1897
|
+
// Enter 键提交
|
|
1898
|
+
document.getElementById('slash-input')?.addEventListener('keydown', (e) => {
|
|
1899
|
+
if (e.key === 'Enter') { e.preventDefault(); submitSlashCmd(); }
|
|
1900
|
+
});
|
|
1901
|
+
|
|
1902
|
+
window.doRename = function() {
|
|
1903
|
+
const current = document.getElementById('session-title').textContent;
|
|
1904
|
+
const newName = prompt('输入新名称', current);
|
|
1905
|
+
if (newName && newName.trim() && newName.trim() !== current) {
|
|
1906
|
+
socket.emit('rename', { sessionId: SESSION_ID, title: newName.trim() });
|
|
1907
|
+
}
|
|
1908
|
+
};
|
|
1909
|
+
socket.on('session-renamed', ({ sessionId, title }) => {
|
|
1910
|
+
if (sessionId !== SESSION_ID) return;
|
|
1911
|
+
document.getElementById('session-title').textContent = title;
|
|
1912
|
+
document.title = title + ' — weHi';
|
|
1913
|
+
addStatusMessage('会话已命名为: ' + title);
|
|
1914
|
+
});
|
|
1915
|
+
|
|
1916
|
+
// ── Git 提交推送 ──────────────────────────────
|
|
1917
|
+
const GIT_STORAGE_KEY = 'zihi-git-' + SESSION_ID;
|
|
1918
|
+
|
|
1919
|
+
window.openGitSheet = async function() {
|
|
1920
|
+
// 从 localStorage 恢复保存的信息
|
|
1921
|
+
const saved = JSON.parse(localStorage.getItem(GIT_STORAGE_KEY) || '{}');
|
|
1922
|
+
document.getElementById('git-url').value = saved.url || '';
|
|
1923
|
+
document.getElementById('git-user').value = saved.username || '';
|
|
1924
|
+
document.getElementById('git-pass').value = saved.password || '';
|
|
1925
|
+
document.getElementById('git-branch').value = saved.branch || '';
|
|
1926
|
+
document.getElementById('git-msg').value = '';
|
|
1927
|
+
|
|
1928
|
+
// 尝试从服务器获取已配置的 remote 信息
|
|
1929
|
+
if (!saved.url) {
|
|
1930
|
+
try {
|
|
1931
|
+
const resp = await fetch(`/api/git/info?sessionId=${SESSION_ID}`);
|
|
1932
|
+
const info = await resp.json();
|
|
1933
|
+
if (info.url) document.getElementById('git-url').value = info.url;
|
|
1934
|
+
if (info.branch) document.getElementById('git-branch').value = info.branch;
|
|
1935
|
+
if (info.username) document.getElementById('git-user').value = info.username;
|
|
1936
|
+
} catch {}
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
document.getElementById('git-sheet').classList.add('open');
|
|
1940
|
+
setTimeout(() => document.getElementById('git-msg').focus(), 100);
|
|
1941
|
+
};
|
|
1942
|
+
|
|
1943
|
+
window.closeGitSheet = function() {
|
|
1944
|
+
document.getElementById('git-sheet').classList.remove('open');
|
|
1945
|
+
};
|
|
1946
|
+
|
|
1947
|
+
window.submitGitPush = async function() {
|
|
1948
|
+
const url = document.getElementById('git-url').value.trim();
|
|
1949
|
+
const username = document.getElementById('git-user').value.trim();
|
|
1950
|
+
const password = document.getElementById('git-pass').value.trim();
|
|
1951
|
+
const branch = document.getElementById('git-branch').value.trim() || 'main';
|
|
1952
|
+
const message = document.getElementById('git-msg').value.trim();
|
|
1953
|
+
const save = document.getElementById('git-save').checked;
|
|
1954
|
+
|
|
1955
|
+
if (!message) { document.getElementById('git-msg').focus(); return; }
|
|
1956
|
+
|
|
1957
|
+
// 保存凭据
|
|
1958
|
+
if (save && url) {
|
|
1959
|
+
localStorage.setItem(GIT_STORAGE_KEY, JSON.stringify({ url, username, password, branch }));
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
const btn = document.getElementById('git-submit-btn');
|
|
1963
|
+
btn.disabled = true;
|
|
1964
|
+
btn.textContent = '提交中...';
|
|
1965
|
+
|
|
1966
|
+
try {
|
|
1967
|
+
const resp = await fetch('/api/git/push', {
|
|
1968
|
+
method: 'POST',
|
|
1969
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1970
|
+
body: JSON.stringify({ sessionId: SESSION_ID, url: url || undefined, username: username || undefined, password: password || undefined, message, branch }),
|
|
1971
|
+
});
|
|
1972
|
+
const data = await resp.json();
|
|
1973
|
+
closeGitSheet();
|
|
1974
|
+
if (data.ok) {
|
|
1975
|
+
addStatusMessage(data.message);
|
|
1976
|
+
} else {
|
|
1977
|
+
addStatusMessage('提交失败: ' + data.error);
|
|
1978
|
+
}
|
|
1979
|
+
} catch (e) {
|
|
1980
|
+
addStatusMessage('提交失败: ' + e.message);
|
|
1981
|
+
} finally {
|
|
1982
|
+
btn.disabled = false;
|
|
1983
|
+
btn.textContent = '提交并推送';
|
|
1984
|
+
}
|
|
1985
|
+
};
|
|
1986
|
+
|
|
1987
|
+
// Enter 键在提交说明框提交
|
|
1988
|
+
document.getElementById('git-msg')?.addEventListener('keydown', (e) => {
|
|
1989
|
+
if (e.key === 'Enter') { e.preventDefault(); submitGitPush(); }
|
|
1990
|
+
});
|
|
1991
|
+
|
|
1992
|
+
// ── Claude 记忆查看 ──────────────────────────────
|
|
1993
|
+
window.showMemory = async function() {
|
|
1994
|
+
const container = document.getElementById('memory-content');
|
|
1995
|
+
container.innerHTML = '<div style="text-align:center;color:#8b949e;padding:2rem 0">加载中...</div>';
|
|
1996
|
+
document.getElementById('memory-sheet').classList.add('open');
|
|
1997
|
+
|
|
1998
|
+
try {
|
|
1999
|
+
const resp = await fetch(`/api/memory?sessionId=${SESSION_ID}`);
|
|
2000
|
+
const data = await resp.json();
|
|
2001
|
+
const files = data.files || [];
|
|
2002
|
+
|
|
2003
|
+
if (files.length === 0) {
|
|
2004
|
+
container.innerHTML = '<div style="text-align:center;color:#8b949e;padding:2rem 0">暂无记忆文件</div>';
|
|
2005
|
+
return;
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
container.innerHTML = '';
|
|
2009
|
+
for (const f of files) {
|
|
2010
|
+
const card = document.createElement('div');
|
|
2011
|
+
card.className = 'mem-file';
|
|
2012
|
+
const header = document.createElement('div');
|
|
2013
|
+
header.className = 'mem-file-header';
|
|
2014
|
+
header.innerHTML = `<span class="arrow">▶</span> ${escHtml(f.name)}`;
|
|
2015
|
+
const body = document.createElement('div');
|
|
2016
|
+
body.className = 'mem-file-body';
|
|
2017
|
+
body.textContent = f.content;
|
|
2018
|
+
header.onclick = () => { body.classList.toggle('open'); header.querySelector('.arrow').classList.toggle('open'); };
|
|
2019
|
+
card.appendChild(header);
|
|
2020
|
+
card.appendChild(body);
|
|
2021
|
+
container.appendChild(card);
|
|
2022
|
+
}
|
|
2023
|
+
} catch (e) {
|
|
2024
|
+
container.innerHTML = `<div style="text-align:center;color:#f85149;padding:2rem 0">加载失败: ${escHtml(e.message)}</div>`;
|
|
2025
|
+
}
|
|
2026
|
+
};
|
|
2027
|
+
|
|
2028
|
+
window.closeMemorySheet = function() {
|
|
2029
|
+
document.getElementById('memory-sheet').classList.remove('open');
|
|
2030
|
+
};
|
|
2031
|
+
|
|
2032
|
+
// ── Agent 模式快捷功能 ──────────────────────────
|
|
2033
|
+
let _totalAgentCost = 0;
|
|
2034
|
+
// 追踪 result 消息中的费用
|
|
2035
|
+
window.showAgentCost = function() {
|
|
2036
|
+
// 从聊天区收集所有费用状态消息
|
|
2037
|
+
const msgs = chatArea.querySelectorAll('.msg-status');
|
|
2038
|
+
let total = 0;
|
|
2039
|
+
msgs.forEach(el => {
|
|
2040
|
+
const m = el.textContent.match(/\$([0-9.]+)/);
|
|
2041
|
+
if (m) total += parseFloat(m[1]);
|
|
2042
|
+
});
|
|
2043
|
+
addStatusMessage(`当前会话累计费用: $${total.toFixed(4)}`);
|
|
2044
|
+
};
|
|
2045
|
+
|
|
2046
|
+
window.showAgentHistory = function() {
|
|
2047
|
+
// 统计当前聊天区的消息数量
|
|
2048
|
+
const inputs = chatArea.querySelectorAll('.msg-input').length;
|
|
2049
|
+
const assistants = chatArea.querySelectorAll('.msg-assistant').length;
|
|
2050
|
+
const tools = chatArea.querySelectorAll('.msg-tool').length;
|
|
2051
|
+
addStatusMessage(`会话统计: ${inputs} 条提问, ${assistants} 条回复, ${tools} 次工具调用`);
|
|
2052
|
+
};
|
|
2053
|
+
|
|
2054
|
+
// ── 拍照上传 ──────────────────────────────────
|
|
2055
|
+
window.openCamera = async function() {
|
|
2056
|
+
const input = document.createElement('input'); input.type = 'file'; input.accept = 'image/*';
|
|
2057
|
+
input.onchange = async () => {
|
|
2058
|
+
const file = input.files?.[0]; if (!file) return;
|
|
2059
|
+
const btn = document.getElementById('btn-photo'); btn.classList.add('active'); btn.disabled = true;
|
|
2060
|
+
try {
|
|
2061
|
+
const img = new Image(); const url = URL.createObjectURL(file);
|
|
2062
|
+
const blob = await new Promise((resolve, reject) => {
|
|
2063
|
+
img.onload = () => { URL.revokeObjectURL(url); let {width:w, height:h} = img;
|
|
2064
|
+
// 压缩策略:长边限制 1024px,JPEG 质量 0.7,适合截图分析
|
|
2065
|
+
const M = 1024;
|
|
2066
|
+
if(w>M||h>M){if(w>=h){h=Math.round(h*M/w);w=M}else{w=Math.round(w*M/h);h=M}}
|
|
2067
|
+
const c=document.createElement('canvas');c.width=w;c.height=h;c.getContext('2d').drawImage(img,0,0,w,h);
|
|
2068
|
+
c.toBlob(b=>b?resolve(b):reject(new Error('toBlob failed')),'image/jpeg',0.7); };
|
|
2069
|
+
img.onerror=reject; img.src=url; });
|
|
2070
|
+
const form = new FormData(); form.append('image', blob, 'photo.jpg');
|
|
2071
|
+
const res = await fetch(`/upload?sessionId=${SESSION_ID}`, { method: 'POST', body: form }); const data = await res.json();
|
|
2072
|
+
if (data.path) {
|
|
2073
|
+
// 暂存图片,等用户输入文字后一起发送
|
|
2074
|
+
const thumbUrl = URL.createObjectURL(blob);
|
|
2075
|
+
setPendingImage(data.path, thumbUrl);
|
|
2076
|
+
}
|
|
2077
|
+
else addStatusMessage('上传失败: ' + (data.error || '未知'));
|
|
2078
|
+
} catch (e) { addStatusMessage('出错: ' + e.message); }
|
|
2079
|
+
finally { btn.classList.remove('active'); btn.disabled = false; }
|
|
2080
|
+
}; input.click();
|
|
2081
|
+
};
|
|
2082
|
+
|
|
2083
|
+
// ── 语音输入 ──────────────────────────────────
|
|
2084
|
+
let recognition = null;
|
|
2085
|
+
let isRecording = false;
|
|
2086
|
+
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
2087
|
+
const VOICE_FALLBACK_KEY = 'zihi_voice_fallback';
|
|
2088
|
+
|
|
2089
|
+
// 检测语音支持级别
|
|
2090
|
+
function detectVoiceSupport() {
|
|
2091
|
+
if (!SpeechRecognition) return 'none';
|
|
2092
|
+
const ua = navigator.userAgent;
|
|
2093
|
+
// iOS (iPhone/iPad/iPod) 走 Apple Siri,中国可用
|
|
2094
|
+
if (/iPhone|iPad|iPod/i.test(ua)) return 'native';
|
|
2095
|
+
// macOS Safari 也走 Siri
|
|
2096
|
+
if (/Macintosh.*Safari/i.test(ua) && !/Chrome/i.test(ua)) return 'native';
|
|
2097
|
+
// 其他有 API 的浏览器(Android Chrome、国产浏览器等)依赖 Google,不可靠
|
|
2098
|
+
return 'unreliable';
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
const _voiceSupport = detectVoiceSupport();
|
|
2102
|
+
|
|
2103
|
+
function showVoiceFallbackTip() {
|
|
2104
|
+
const ua = navigator.userAgent;
|
|
2105
|
+
if (/Firefox/i.test(ua)) {
|
|
2106
|
+
addStatusMessage('Firefox 不支持语音识别,请使用 Chrome/Safari 或键盘上的 🎤 语音输入');
|
|
2107
|
+
} else if (/Android/i.test(ua)) {
|
|
2108
|
+
addStatusMessage('语音识别不可用,请点击键盘上的 🎤 麦克风图标使用输入法语音');
|
|
2109
|
+
} else {
|
|
2110
|
+
addStatusMessage('语音识别不可用,请使用输入法的语音功能(键盘上的 🎤)');
|
|
2111
|
+
}
|
|
2112
|
+
cmdInput.focus();
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
window.toggleVoice = function() {
|
|
2116
|
+
// 完全不支持
|
|
2117
|
+
if (_voiceSupport === 'none') {
|
|
2118
|
+
showVoiceFallbackTip();
|
|
2119
|
+
return;
|
|
2120
|
+
}
|
|
2121
|
+
|
|
2122
|
+
// 非 HTTPS 且非 localhost 时,语音识别无法工作
|
|
2123
|
+
if (location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
|
|
2124
|
+
const httpsUrl = location.href.replace(/^http:/, 'https:').replace(':' + location.port, ':3443');
|
|
2125
|
+
addStatusMessage('语音识别需要 HTTPS,请通过 HTTPS 地址访问');
|
|
2126
|
+
return;
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
// 之前失败过,直接显示回退提示(避免反复失败)
|
|
2130
|
+
if (_voiceSupport === 'unreliable' && localStorage.getItem(VOICE_FALLBACK_KEY)) {
|
|
2131
|
+
showVoiceFallbackTip();
|
|
2132
|
+
addStatusMessage('(长按语音按钮可重试语音识别)');
|
|
2133
|
+
return;
|
|
2134
|
+
}
|
|
2135
|
+
|
|
2136
|
+
if (isRecording) {
|
|
2137
|
+
recognition.stop();
|
|
2138
|
+
return;
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
recognition = new SpeechRecognition();
|
|
2142
|
+
recognition.lang = 'zh-CN';
|
|
2143
|
+
recognition.interimResults = true;
|
|
2144
|
+
recognition.continuous = false;
|
|
2145
|
+
recognition.maxAlternatives = 1;
|
|
2146
|
+
|
|
2147
|
+
const voiceBtn = document.getElementById('voice-btn');
|
|
2148
|
+
const savedValue = cmdInput.value;
|
|
2149
|
+
let hasResult = false;
|
|
2150
|
+
let gotAudio = false;
|
|
2151
|
+
let errorOccurred = false;
|
|
2152
|
+
let networkTimeout = null;
|
|
2153
|
+
|
|
2154
|
+
function stopRecording() {
|
|
2155
|
+
isRecording = false;
|
|
2156
|
+
clearTimeout(networkTimeout);
|
|
2157
|
+
voiceBtn.classList.remove('recording');
|
|
2158
|
+
cmdInput.placeholder = currentSession?.mode === 'agent' ? '输入消息...' : '输入命令...';
|
|
2159
|
+
}
|
|
2160
|
+
|
|
2161
|
+
recognition.onstart = () => {
|
|
2162
|
+
isRecording = true;
|
|
2163
|
+
hasResult = false;
|
|
2164
|
+
gotAudio = false;
|
|
2165
|
+
errorOccurred = false;
|
|
2166
|
+
voiceBtn.classList.add('recording');
|
|
2167
|
+
cmdInput.placeholder = '正在听...';
|
|
2168
|
+
// 不可靠环境下设置超时:3秒内没结果视为失败
|
|
2169
|
+
if (_voiceSupport === 'unreliable') {
|
|
2170
|
+
networkTimeout = setTimeout(() => {
|
|
2171
|
+
if (!hasResult && !errorOccurred) {
|
|
2172
|
+
recognition.abort();
|
|
2173
|
+
localStorage.setItem(VOICE_FALLBACK_KEY, '1');
|
|
2174
|
+
stopRecording();
|
|
2175
|
+
addStatusMessage('语音服务连接超时,请使用输入法的语音功能(键盘上的 🎤)');
|
|
2176
|
+
}
|
|
2177
|
+
}, 3000);
|
|
2178
|
+
}
|
|
2179
|
+
};
|
|
2180
|
+
|
|
2181
|
+
recognition.onaudiostart = () => { gotAudio = true; };
|
|
2182
|
+
|
|
2183
|
+
recognition.onresult = (e) => {
|
|
2184
|
+
hasResult = true;
|
|
2185
|
+
clearTimeout(networkTimeout);
|
|
2186
|
+
let interim = '', final = '';
|
|
2187
|
+
for (let i = e.resultIndex; i < e.results.length; i++) {
|
|
2188
|
+
if (e.results[i].isFinal) final += e.results[i][0].transcript;
|
|
2189
|
+
else interim += e.results[i][0].transcript;
|
|
2190
|
+
}
|
|
2191
|
+
cmdInput.value = savedValue + final + interim;
|
|
2192
|
+
};
|
|
2193
|
+
|
|
2194
|
+
recognition.onend = () => {
|
|
2195
|
+
stopRecording();
|
|
2196
|
+
if (!errorOccurred && !hasResult) {
|
|
2197
|
+
if (!gotAudio) {
|
|
2198
|
+
addStatusMessage('未检测到麦克风音频,请检查麦克风是否正常');
|
|
2199
|
+
} else {
|
|
2200
|
+
addStatusMessage('未识别到语音内容,请重试');
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
cmdInput.focus();
|
|
2204
|
+
};
|
|
2205
|
+
|
|
2206
|
+
recognition.onerror = (e) => {
|
|
2207
|
+
errorOccurred = true;
|
|
2208
|
+
console.warn('[语音识别错误]', e.error, e.message);
|
|
2209
|
+
stopRecording();
|
|
2210
|
+
if (e.error === 'network' || e.error === 'service-not-allowed') {
|
|
2211
|
+
// 记住失败状态,下次直接显示回退提示
|
|
2212
|
+
localStorage.setItem(VOICE_FALLBACK_KEY, '1');
|
|
2213
|
+
addStatusMessage('语音服务连接失败,请使用输入法的语音功能(键盘上的 🎤)');
|
|
2214
|
+
} else if (e.error === 'not-allowed') {
|
|
2215
|
+
addStatusMessage('麦克风权限被拒绝,请在浏览器设置中允许');
|
|
2216
|
+
} else if (e.error === 'no-speech') {
|
|
2217
|
+
addStatusMessage('未检测到语音,请对着麦克风说话后重试');
|
|
2218
|
+
} else if (e.error === 'audio-capture') {
|
|
2219
|
+
addStatusMessage('无法捕获音频,请检查麦克风设备');
|
|
2220
|
+
} else if (e.error !== 'aborted') {
|
|
2221
|
+
addStatusMessage('语音识别失败: ' + e.error);
|
|
2222
|
+
}
|
|
2223
|
+
};
|
|
2224
|
+
|
|
2225
|
+
try {
|
|
2226
|
+
recognition.start();
|
|
2227
|
+
} catch (e) {
|
|
2228
|
+
stopRecording();
|
|
2229
|
+
addStatusMessage('语音识别启动失败: ' + e.message);
|
|
2230
|
+
}
|
|
2231
|
+
};
|
|
2232
|
+
|
|
2233
|
+
// 长按语音按钮重置回退状态,允许重试
|
|
2234
|
+
document.getElementById('voice-btn').addEventListener('contextmenu', (e) => {
|
|
2235
|
+
e.preventDefault();
|
|
2236
|
+
localStorage.removeItem(VOICE_FALLBACK_KEY);
|
|
2237
|
+
addStatusMessage('语音识别已重置,点击 🎤 重试');
|
|
2238
|
+
});
|
|
2239
|
+
|
|
2240
|
+
cmdInput.focus();
|
|
2241
|
+
|
|
2242
|
+
// ── 版本更新检查 ──────────────────────────────
|
|
2243
|
+
(async function checkUpdate() {
|
|
2244
|
+
try {
|
|
2245
|
+
const resp = await fetch('/api/version');
|
|
2246
|
+
if (!resp.ok) return;
|
|
2247
|
+
const data = await resp.json();
|
|
2248
|
+
if (data.updateAvailable) document.getElementById('update-badge').style.display = '';
|
|
2249
|
+
} catch {}
|
|
2250
|
+
setTimeout(checkUpdate, 10 * 60 * 1000);
|
|
2251
|
+
})();
|
|
2252
|
+
</script>
|
|
2253
|
+
</body>
|
|
2254
|
+
</html>
|