@yumind-ai/harness 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +80 -2
- package/cli.js +179 -0
- package/package.json +38 -4
- package/public/index.html +1534 -0
|
@@ -0,0 +1,1534 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN" data-theme="dark">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<title>Yu Harness · Agent 调度框架</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root{
|
|
9
|
+
--bg:#0e1015; --panel:#151922; --panel-2:#1b202b; --panel-3:#212836; --line:#28303e;
|
|
10
|
+
--text:#e7eaf0; --muted:#8b93a6; --accent:#6ea8fe; --accent-dim:#23304a;
|
|
11
|
+
--ok:#4ade80; --warn:#fbbf24; --err:#f87171; --radius:10px;
|
|
12
|
+
--code-bg:#11161f; --shadow:0 8px 24px rgba(0,0,0,.35);
|
|
13
|
+
}
|
|
14
|
+
html[data-theme="light"]{
|
|
15
|
+
--bg:#f5f7fb; --panel:#ffffff; --panel-2:#f1f4f9; --panel-3:#e8edf6; --line:#dbe2ee;
|
|
16
|
+
--text:#1a2233; --muted:#64708a; --accent:#2f6fdd; --accent-dim:#e2ecfb;
|
|
17
|
+
--ok:#15803d; --warn:#b45309; --err:#dc2626; --code-bg:#f6f8fc;
|
|
18
|
+
--shadow:0 8px 24px rgba(20,30,50,.10);
|
|
19
|
+
}
|
|
20
|
+
*{box-sizing:border-box}
|
|
21
|
+
html,body{height:100%}
|
|
22
|
+
body{
|
|
23
|
+
margin:0;background:var(--bg);color:var(--text);
|
|
24
|
+
font:14px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
|
|
25
|
+
display:flex;flex-direction:column;overflow:hidden;
|
|
26
|
+
transition:background .2s,color .2s;
|
|
27
|
+
}
|
|
28
|
+
::-webkit-scrollbar { width: 6px; height: 6px; }
|
|
29
|
+
::-webkit-scrollbar-track { background: transparent; }
|
|
30
|
+
::-webkit-scrollbar-thumb { background: var(--line); border-radius: 4px; }
|
|
31
|
+
::-webkit-scrollbar-thumb:hover { background: var(--muted); }
|
|
32
|
+
|
|
33
|
+
header{
|
|
34
|
+
display:flex;align-items:center;justify-content:space-between;gap:12px;
|
|
35
|
+
padding:10px 16px;border-bottom:1px solid var(--line);background:var(--panel);
|
|
36
|
+
z-index: 10; flex-shrink: 0;
|
|
37
|
+
}
|
|
38
|
+
.header-left, .header-right { display: flex; align-items: center; gap: 12px; }
|
|
39
|
+
.brand{font-weight:700;letter-spacing:.3px; display:flex; align-items:center; gap:8px;user-select:none;}
|
|
40
|
+
.brand svg { color: var(--accent); }
|
|
41
|
+
.brand span{color:var(--muted);font-weight:400;font-size:12px;}
|
|
42
|
+
|
|
43
|
+
.icon-btn {
|
|
44
|
+
background: transparent; border: none; color: var(--muted); cursor: pointer;
|
|
45
|
+
padding: 6px; border-radius: 6px; display: flex; align-items: center; justify-content: center;
|
|
46
|
+
transition: all 0.2s;
|
|
47
|
+
}
|
|
48
|
+
.icon-btn:hover { background: var(--panel-2); color: var(--text); }
|
|
49
|
+
.icon-btn:disabled { opacity:.4; cursor:not-allowed; }
|
|
50
|
+
.icon-btn:disabled:hover { background: transparent; color: var(--muted); }
|
|
51
|
+
.icon-btn svg { width: 18px; height: 18px; }
|
|
52
|
+
|
|
53
|
+
button.primary{
|
|
54
|
+
background:var(--accent);border:1px solid var(--accent);color:#0b1020;font-weight:600;
|
|
55
|
+
padding:6px 12px;border-radius:8px;cursor:pointer;display:flex;align-items:center;gap:6px;
|
|
56
|
+
transition: all 0.2s; font: inherit;
|
|
57
|
+
}
|
|
58
|
+
button.primary:hover{filter:brightness(1.08)}
|
|
59
|
+
button.primary:disabled{opacity:.45;cursor:not-allowed;filter:none}
|
|
60
|
+
button.ghost{
|
|
61
|
+
background:var(--panel-2);border:1px solid var(--line);color:var(--text);font-weight:500;
|
|
62
|
+
padding:6px 10px;border-radius:8px;cursor:pointer;display:inline-flex;align-items:center;gap:6px;
|
|
63
|
+
transition: all .2s; font: inherit; font-size:12.5px;
|
|
64
|
+
}
|
|
65
|
+
button.ghost:hover{background:var(--panel-3)}
|
|
66
|
+
button.ghost svg{width:14px;height:14px}
|
|
67
|
+
|
|
68
|
+
#status{color:var(--muted);font-size:12px;min-width:64px;text-align:right;white-space:nowrap;}
|
|
69
|
+
.badge{
|
|
70
|
+
font-size:11px;padding:2px 7px;border-radius:999px;border:1px solid var(--line);
|
|
71
|
+
color:var(--muted);background:var(--panel-2);white-space:nowrap
|
|
72
|
+
}
|
|
73
|
+
.badge.live{color:var(--ok);border-color:color-mix(in srgb, var(--ok) 45%, transparent)}
|
|
74
|
+
|
|
75
|
+
main{flex:1;min-height:0;display:flex;overflow:hidden;position:relative;}
|
|
76
|
+
|
|
77
|
+
.panel{background:var(--panel);display:flex;flex-direction:column;transition:width 0.28s ease, border 0.28s ease;}
|
|
78
|
+
#leftPanel { width: 300px; border-right:1px solid var(--line); overflow-y:auto; flex-shrink: 0; }
|
|
79
|
+
#leftPanel.collapsed { width: 0; border-right: none; overflow: hidden; }
|
|
80
|
+
#rightPanel { width: 330px; border-left:1px solid var(--line); flex-shrink: 0; }
|
|
81
|
+
#rightPanel.collapsed { width: 0; border-left: none; overflow: hidden; }
|
|
82
|
+
|
|
83
|
+
.panel-inner { padding: 14px; min-width: 300px; }
|
|
84
|
+
|
|
85
|
+
.panel h3{font-size:12px;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);margin:0 0 10px; display:flex; align-items:center; gap:6px;}
|
|
86
|
+
.field{margin-bottom:10px}
|
|
87
|
+
.field label{display:block;font-size:12px;color:var(--muted);margin-bottom:4px}
|
|
88
|
+
.field input, .field select, .field textarea{
|
|
89
|
+
width:100%;background:var(--panel-2);border:1px solid var(--line);color:var(--text);
|
|
90
|
+
padding:7px 9px;border-radius:8px;font:inherit;outline:none;
|
|
91
|
+
}
|
|
92
|
+
.field textarea{resize:vertical;min-height:52px;font-size:12.5px}
|
|
93
|
+
.field input:focus, .field select:focus, .field textarea:focus{border-color:var(--accent)}
|
|
94
|
+
.hint{font-size:11px;color:var(--muted);line-height:1.5;margin:8px 0 0}
|
|
95
|
+
|
|
96
|
+
.conv-list { display: flex; flex-direction: column; gap: 4px; margin-bottom: 8px; max-height: 260px; overflow-y: auto; }
|
|
97
|
+
.conv-item {
|
|
98
|
+
display: flex; align-items: center; justify-content: space-between; gap:6px;
|
|
99
|
+
padding: 8px 10px; border-radius: 8px; cursor: pointer; color: var(--muted);
|
|
100
|
+
transition: all 0.2s; font-size: 13px;
|
|
101
|
+
}
|
|
102
|
+
.conv-item:hover { background: var(--panel-2); color: var(--text); }
|
|
103
|
+
.conv-item.active { background: var(--accent-dim); color: var(--text); border-left: 3px solid var(--accent); }
|
|
104
|
+
.conv-item .title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; }
|
|
105
|
+
.conv-item .meta { font-size:10.5px; color:var(--muted); opacity:.75; white-space:nowrap }
|
|
106
|
+
.conv-item .del-btn { opacity:0; color:var(--err); cursor:pointer; padding:2px; display:flex }
|
|
107
|
+
.conv-item:hover .del-btn { opacity:.9 }
|
|
108
|
+
.conv-item .del-btn svg { width: 14px; height: 14px; }
|
|
109
|
+
.conv-empty{font-size:12px;color:var(--muted);padding:6px 2px}
|
|
110
|
+
|
|
111
|
+
#center{display:flex;flex-direction:column;min-height:0;background:var(--bg);flex:1;min-width:0;}
|
|
112
|
+
|
|
113
|
+
#messages{flex:1;min-height:0;overflow:auto;padding:18px 18px 8px;display:flex;flex-direction:column;gap:12px;scroll-behavior:smooth}
|
|
114
|
+
.msg{max-width:min(86%, 820px);padding:11px 14px;border-radius:var(--radius);word-break:break-word;position:relative;animation:fade .18s ease}
|
|
115
|
+
@keyframes fade{from{opacity:0;transform:translateY(3px)}to{opacity:1;transform:none}}
|
|
116
|
+
.msg.user{align-self:flex-end;background:var(--accent-dim);border:1px solid var(--line);white-space:pre-wrap}
|
|
117
|
+
.msg.assistant{align-self:flex-start;background:var(--panel-2);border:1px solid var(--line)}
|
|
118
|
+
.msg.error{align-self:stretch;background:color-mix(in srgb, var(--err) 12%, transparent);border:1px solid color-mix(in srgb, var(--err) 45%, transparent);color:var(--err);white-space:pre-wrap}
|
|
119
|
+
.msg.thinking{align-self:flex-start;background:transparent;color:var(--muted);font-style:italic;border:1px dashed var(--line)}
|
|
120
|
+
|
|
121
|
+
.msg.assistant p{margin:0 0 .6em} .msg.assistant p:last-child{margin-bottom:0}
|
|
122
|
+
.msg.assistant h1,.msg.assistant h2,.msg.assistant h3,.msg.assistant h4{margin:.7em 0 .4em;line-height:1.3}
|
|
123
|
+
.msg.assistant h1{font-size:1.25em} .msg.assistant h2{font-size:1.15em} .msg.assistant h3{font-size:1.05em}
|
|
124
|
+
.msg.assistant ul,.msg.assistant ol{margin:.4em 0 .7em;padding-left:1.4em}
|
|
125
|
+
.msg.assistant li{margin:.15em 0}
|
|
126
|
+
.msg.assistant blockquote{margin:.5em 0;padding:.2em .8em;border-left:3px solid var(--line);color:var(--muted)}
|
|
127
|
+
.msg.assistant hr{border:0;border-top:1px solid var(--line);margin:.9em 0}
|
|
128
|
+
.msg.assistant a{color:var(--accent);text-decoration:none;border-bottom:1px solid color-mix(in srgb, var(--accent) 40%, transparent)}
|
|
129
|
+
.msg.assistant a:hover{border-bottom-color:var(--accent)}
|
|
130
|
+
.msg.assistant code{background:var(--code-bg);border:1px solid var(--line);border-radius:5px;padding:1px 5px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12.5px}
|
|
131
|
+
.msg.assistant strong{font-weight:650}
|
|
132
|
+
|
|
133
|
+
.code-wrap{margin:.6em 0;border:1px solid var(--line);border-radius:9px;overflow:hidden;background:var(--code-bg)}
|
|
134
|
+
.code-head{display:flex;justify-content:space-between;align-items:center;padding:5px 9px;background:var(--panel-3);font-size:11px;color:var(--muted);font-family:ui-monospace,Menlo,monospace}
|
|
135
|
+
.code-copy{background:transparent;border:none;color:var(--muted);cursor:pointer;font-size:11px;padding:2px 6px;border-radius:5px;font-family:inherit}
|
|
136
|
+
.code-copy:hover{background:var(--panel-2);color:var(--text)}
|
|
137
|
+
.code-wrap pre{margin:0;padding:10px 11px;overflow-x:auto}
|
|
138
|
+
.code-wrap code{background:none;border:none;padding:0;font-size:12.3px;line-height:1.55}
|
|
139
|
+
|
|
140
|
+
.msg-tools{display:flex;gap:6px;margin-top:8px;opacity:0;transition:opacity .15s}
|
|
141
|
+
.msg.assistant:hover .msg-tools{opacity:1}
|
|
142
|
+
.msg-tools button{background:transparent;border:1px solid var(--line);color:var(--muted);font-size:11px;padding:2px 8px;border-radius:6px;cursor:pointer}
|
|
143
|
+
.msg-tools button:hover{background:var(--panel-3);color:var(--text)}
|
|
144
|
+
|
|
145
|
+
.cursor::after{content:"▍";color:var(--accent);animation:blink 1s steps(2,start) infinite;margin-left:1px}
|
|
146
|
+
@keyframes blink{to{visibility:hidden}}
|
|
147
|
+
|
|
148
|
+
.tool-card{
|
|
149
|
+
align-self:stretch;max-width:min(86%, 820px);background:var(--panel-2);border:1px solid var(--line);border-left:3px solid var(--warn);
|
|
150
|
+
border-radius:var(--radius);padding:8px 10px;font-size:12px;
|
|
151
|
+
}
|
|
152
|
+
.tool-card.ok{border-left-color:var(--ok)}
|
|
153
|
+
.tool-card .tool-head{display:flex;justify-content:space-between;gap:8px;margin-bottom:4px;color:var(--warn);font-weight:600;cursor:pointer}
|
|
154
|
+
.tool-card.ok .tool-head{color:var(--ok)}
|
|
155
|
+
.tool-card .tool-body{display:none}
|
|
156
|
+
.tool-card.open .tool-body{display:block}
|
|
157
|
+
.tool-card pre{
|
|
158
|
+
margin:0;white-space:pre-wrap;word-break:break-word;color:var(--muted);
|
|
159
|
+
font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11.5px;max-height:320px;overflow:auto;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
#composer{display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--line);background:var(--panel);align-items:flex-end}
|
|
163
|
+
#input{
|
|
164
|
+
flex:1;resize:none;min-height:46px;max-height:180px;background:var(--panel-2);
|
|
165
|
+
border:1px solid var(--line);color:var(--text);border-radius:10px;
|
|
166
|
+
padding:11px 12px;font:inherit;outline:none;line-height:1.5;
|
|
167
|
+
}
|
|
168
|
+
#input:focus{border-color:var(--accent)}
|
|
169
|
+
.composer-actions{display:flex;flex-direction:column;gap:6px;align-items:stretch}
|
|
170
|
+
.composer-hint{font-size:11px;color:var(--muted);text-align:center;white-space:nowrap}
|
|
171
|
+
|
|
172
|
+
.tabs{display:flex;gap:4px;border-bottom:1px solid var(--line);margin-bottom:10px}
|
|
173
|
+
.tab{flex:1;background:transparent;border:none;border-bottom:2px solid transparent;color:var(--muted);padding:7px 4px;cursor:pointer;font-size:12px;font:inherit;font-size:12px}
|
|
174
|
+
.tab.active{color:var(--text);border-bottom-color:var(--accent)}
|
|
175
|
+
.tab-pane{display:none}
|
|
176
|
+
.tab-pane.active{display:block}
|
|
177
|
+
|
|
178
|
+
.trace-tools{display:flex;gap:6px;margin-bottom:8px}
|
|
179
|
+
.trace-item{
|
|
180
|
+
font-size:12px;padding:6px 8px;border-left:2px solid var(--line);
|
|
181
|
+
margin-bottom:6px;background:var(--panel-2);border-radius:0 8px 8px 0;
|
|
182
|
+
}
|
|
183
|
+
.trace-item .t-head{display:flex;justify-content:space-between;gap:8px;margin-bottom:2px}
|
|
184
|
+
.trace-item .t-kind{font-weight:600}
|
|
185
|
+
.trace-item .t-time{color:var(--muted);font-size:11px}
|
|
186
|
+
.trace-item pre{
|
|
187
|
+
margin:0;white-space:pre-wrap;word-break:break-word;color:var(--muted);
|
|
188
|
+
font-family:ui-monospace,Menlo,monospace;font-size:11px;max-height:220px;overflow:auto;
|
|
189
|
+
}
|
|
190
|
+
.k-accent{border-left-color:var(--accent)} .k-accent .t-kind{color:var(--accent)}
|
|
191
|
+
.k-ok{border-left-color:var(--ok)} .k-ok .t-kind{color:var(--ok)}
|
|
192
|
+
.k-warn{border-left-color:var(--warn)} .k-warn .t-kind{color:var(--warn)}
|
|
193
|
+
.k-err{border-left-color:var(--err)} .k-err .t-kind{color:var(--err)}
|
|
194
|
+
.trace-empty{font-size:12px;color:var(--muted);padding:6px 2px}
|
|
195
|
+
|
|
196
|
+
.tool-item{
|
|
197
|
+
display:flex;align-items:flex-start;gap:8px;padding:8px;
|
|
198
|
+
border:1px solid var(--line);border-radius:8px;margin-bottom:8px;
|
|
199
|
+
background:var(--panel-2);cursor:pointer;
|
|
200
|
+
}
|
|
201
|
+
.tool-item input{margin-top:3px;accent-color:var(--accent)}
|
|
202
|
+
.tool-item .ti-name{font-weight:600;font-size:13px}
|
|
203
|
+
.tool-item .ti-desc{font-size:11px;color:var(--muted);line-height:1.4}
|
|
204
|
+
|
|
205
|
+
.file-row{display:flex;align-items:center;gap:6px;padding:6px 8px;border-radius:7px;font-size:12px;cursor:pointer}
|
|
206
|
+
.file-row:hover{background:var(--panel-2)}
|
|
207
|
+
.file-row .fname{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,Menlo,monospace}
|
|
208
|
+
.file-row .fmeta{font-size:10.5px;color:var(--muted)}
|
|
209
|
+
|
|
210
|
+
.toast{
|
|
211
|
+
position:fixed;left:50%;bottom:26px;transform:translateX(-50%) translateY(10px);
|
|
212
|
+
background:var(--panel-3);color:var(--text);border:1px solid var(--line);
|
|
213
|
+
padding:8px 14px;border-radius:9px;font-size:12.5px;box-shadow:var(--shadow);
|
|
214
|
+
opacity:0;pointer-events:none;transition:all .22s;z-index:100
|
|
215
|
+
}
|
|
216
|
+
.toast.show{opacity:1;transform:translateX(-50%) translateY(0)}
|
|
217
|
+
|
|
218
|
+
.search-box{position:relative;margin-bottom:8px}
|
|
219
|
+
.search-box input{
|
|
220
|
+
width:100%;background:var(--panel-2);border:1px solid var(--line);color:var(--text);
|
|
221
|
+
padding:6px 9px 6px 28px;border-radius:8px;font:inherit;font-size:12.5px;outline:none;
|
|
222
|
+
}
|
|
223
|
+
.search-box input:focus{border-color:var(--accent)}
|
|
224
|
+
.search-box svg{position:absolute;left:8px;top:50%;transform:translateY(-50%);width:14px;height:14px;color:var(--muted)}
|
|
225
|
+
|
|
226
|
+
.modal-mask{position:fixed;inset:0;background:rgba(0,0,0,.5);display:none;align-items:center;justify-content:center;z-index:200;padding:24px}
|
|
227
|
+
.modal-mask.show{display:flex}
|
|
228
|
+
.modal{background:var(--panel);border:1px solid var(--line);border-radius:14px;box-shadow:var(--shadow);width:min(680px,100%);max-height:80vh;display:flex;flex-direction:column;overflow:hidden}
|
|
229
|
+
.modal-head{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid var(--line);font-weight:600}
|
|
230
|
+
.modal-body{padding:14px 16px;overflow:auto}
|
|
231
|
+
.modal-body pre{margin:0;white-space:pre-wrap;word-break:break-word;font-family:ui-monospace,Menlo,monospace;font-size:12px;color:var(--muted)}
|
|
232
|
+
kbd{background:var(--panel-3);border:1px solid var(--line);border-bottom-width:2px;border-radius:5px;padding:1px 5px;font-size:11px;font-family:ui-monospace,Menlo,monospace}
|
|
233
|
+
.kv{display:flex;justify-content:space-between;gap:10px;font-size:12.5px;padding:4px 0;border-bottom:1px dashed var(--line)}
|
|
234
|
+
.kv:last-child{border-bottom:none}
|
|
235
|
+
</style>
|
|
236
|
+
</head>
|
|
237
|
+
<body>
|
|
238
|
+
<header>
|
|
239
|
+
<div class="header-left">
|
|
240
|
+
<button id="btnToggleLeft" class="icon-btn" title="收起/展开左侧栏 (Ctrl+B)">
|
|
241
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
|
|
242
|
+
</button>
|
|
243
|
+
<div class="brand">
|
|
244
|
+
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"></path></svg>
|
|
245
|
+
Yu Harness <span>Agent 调度框架</span>
|
|
246
|
+
</div>
|
|
247
|
+
</div>
|
|
248
|
+
<div class="header-right">
|
|
249
|
+
<span id="modelBadge" class="badge" title="当前模型">未配置模型</span>
|
|
250
|
+
<span id="status">就绪</span>
|
|
251
|
+
<button id="btnTheme" class="icon-btn" title="切换深浅色主题">
|
|
252
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>
|
|
253
|
+
</button>
|
|
254
|
+
<button id="btnStop" class="icon-btn" disabled title="停止生成 (Esc)">
|
|
255
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="6" width="12" height="12"></rect></svg>
|
|
256
|
+
</button>
|
|
257
|
+
<button id="btnToggleRight" class="icon-btn" title="收起/展开右侧栏 (Ctrl+J)">
|
|
258
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
|
|
259
|
+
</button>
|
|
260
|
+
</div>
|
|
261
|
+
</header>
|
|
262
|
+
<main>
|
|
263
|
+
<aside id="leftPanel" class="panel">
|
|
264
|
+
<div class="panel-inner">
|
|
265
|
+
<button id="btnNewConv" class="primary" style="width:100%; justify-content:center; margin-bottom:10px;">
|
|
266
|
+
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
|
|
267
|
+
新建对话
|
|
268
|
+
</button>
|
|
269
|
+
|
|
270
|
+
<div class="search-box">
|
|
271
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
|
|
272
|
+
<input id="convSearch" placeholder="搜索对话…" />
|
|
273
|
+
</div>
|
|
274
|
+
<div class="conv-list" id="convList"></div>
|
|
275
|
+
|
|
276
|
+
<div style="display:flex;gap:6px;margin-bottom:4px">
|
|
277
|
+
<button id="btnExport" class="ghost" style="flex:1;justify-content:center" title="导出当前对话为 Markdown">
|
|
278
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
|
|
279
|
+
导出
|
|
280
|
+
</button>
|
|
281
|
+
<button id="btnImport" class="ghost" style="flex:1;justify-content:center" title="从 JSON 备份导入全部对话">
|
|
282
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
|
|
283
|
+
导入
|
|
284
|
+
</button>
|
|
285
|
+
<button id="btnSettings" class="ghost" style="justify-content:center" title="快捷键与关于">
|
|
286
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
|
|
287
|
+
</button>
|
|
288
|
+
</div>
|
|
289
|
+
<input id="importFile" type="file" accept="application/json" style="display:none" />
|
|
290
|
+
<hr style="border:0; border-top:1px solid var(--line); margin:14px 0;">
|
|
291
|
+
|
|
292
|
+
<h3>工作区 (Workspace)</h3>
|
|
293
|
+
<button id="btnSelectWorkspace" class="ghost" style="width:100%;margin-bottom:8px; justify-content:center;">
|
|
294
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>
|
|
295
|
+
选择本地文件夹
|
|
296
|
+
</button>
|
|
297
|
+
<div id="workspaceStatus" class="hint" style="margin-bottom:14px;">未绑定(使用浏览器虚拟文件系统)</div>
|
|
298
|
+
|
|
299
|
+
<h3>Provider</h3>
|
|
300
|
+
<div class="field"><label for="baseURL">Base URL</label><input id="baseURL" placeholder="http://localhost:8787/v1" /></div>
|
|
301
|
+
<div class="field"><label for="apiKey">API Key</label><input id="apiKey" type="password" placeholder="sk-..." autocomplete="off" /></div>
|
|
302
|
+
<div class="field"><label for="model">Model</label><input id="model" placeholder="模型名称" /></div>
|
|
303
|
+
<div class="field" style="display:flex;gap:8px">
|
|
304
|
+
<div style="flex:1"><label for="temperature">Temperature</label><input id="temperature" type="number" step="0.1" min="0" max="2" value="0.3" /></div>
|
|
305
|
+
<div style="flex:1"><label for="maxSteps">最大步数</label><input id="maxSteps" type="number" min="1" max="50" value="8" /></div>
|
|
306
|
+
</div>
|
|
307
|
+
<div class="field"><label for="systemPrompt">系统提示词(可选)</label><textarea id="systemPrompt" placeholder="例如:你是一个严谨的工程助手,回答简洁。"></textarea></div>
|
|
308
|
+
<label class="tool-item" style="cursor:pointer">
|
|
309
|
+
<input type="checkbox" id="streamToggle" />
|
|
310
|
+
<div><div class="ti-name">流式输出</div><div class="ti-desc">逐字显示模型回复(需 Provider 支持 SSE)</div></div>
|
|
311
|
+
</label>
|
|
312
|
+
|
|
313
|
+
<h3 style="margin-top:16px">工具(插件)</h3>
|
|
314
|
+
<div id="toolList"></div>
|
|
315
|
+
</div>
|
|
316
|
+
</aside>
|
|
317
|
+
|
|
318
|
+
<section id="center">
|
|
319
|
+
<div id="messages"></div>
|
|
320
|
+
<div id="composer">
|
|
321
|
+
<textarea id="input" placeholder="输入内容… Enter 发送,Shift+Enter 换行,Esc 停止"></textarea>
|
|
322
|
+
<div class="composer-actions">
|
|
323
|
+
<button id="btnSend" class="primary">
|
|
324
|
+
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
|
|
325
|
+
发送
|
|
326
|
+
</button>
|
|
327
|
+
<div class="composer-hint" id="tokenHint">0 字</div>
|
|
328
|
+
</div>
|
|
329
|
+
</div>
|
|
330
|
+
</section>
|
|
331
|
+
|
|
332
|
+
<aside id="rightPanel" class="panel">
|
|
333
|
+
<div class="panel-inner" style="display:flex;flex-direction:column;height:100%;min-height:0">
|
|
334
|
+
<div class="tabs">
|
|
335
|
+
<button class="tab active" data-tab="trace">运行轨迹</button>
|
|
336
|
+
<button class="tab" data-tab="files">文件</button>
|
|
337
|
+
</div>
|
|
338
|
+
<div class="tab-pane active" id="pane-trace" style="overflow-y:auto;flex:1;min-height:0">
|
|
339
|
+
<div class="trace-tools">
|
|
340
|
+
<button id="btnClearTrace" class="ghost" style="flex:1;justify-content:center">清空</button>
|
|
341
|
+
<button id="btnCopyTrace" class="ghost" style="flex:1;justify-content:center">复制 JSON</button>
|
|
342
|
+
</div>
|
|
343
|
+
<div id="trace"></div>
|
|
344
|
+
</div>
|
|
345
|
+
<div class="tab-pane" id="pane-files" style="overflow-y:auto;flex:1;min-height:0">
|
|
346
|
+
<div class="trace-tools">
|
|
347
|
+
<button id="btnRefreshVfs" class="ghost" style="flex:1;justify-content:center">刷新</button>
|
|
348
|
+
<button id="btnClearVfs" class="ghost" style="flex:1;justify-content:center">清空虚拟文件</button>
|
|
349
|
+
</div>
|
|
350
|
+
<div id="vfsList"></div>
|
|
351
|
+
</div>
|
|
352
|
+
</div>
|
|
353
|
+
</aside>
|
|
354
|
+
</main>
|
|
355
|
+
|
|
356
|
+
<div class="toast" id="toast"></div>
|
|
357
|
+
|
|
358
|
+
<div class="modal-mask" id="modalMask">
|
|
359
|
+
<div class="modal">
|
|
360
|
+
<div class="modal-head"><span id="modalTitle">关于</span>
|
|
361
|
+
<button class="icon-btn" id="modalClose" title="关闭">
|
|
362
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
|
363
|
+
</button>
|
|
364
|
+
</div>
|
|
365
|
+
<div class="modal-body" id="modalBody"></div>
|
|
366
|
+
</div>
|
|
367
|
+
</div>
|
|
368
|
+
|
|
369
|
+
<script>
|
|
370
|
+
(() => {
|
|
371
|
+
'use strict';
|
|
372
|
+
|
|
373
|
+
/* ==================================================================
|
|
374
|
+
* 0. 基础工具
|
|
375
|
+
* ================================================================== */
|
|
376
|
+
const $ = (s) => document.querySelector(s);
|
|
377
|
+
const el = (tag, cls, text) => {
|
|
378
|
+
const n = document.createElement(tag);
|
|
379
|
+
if (cls) n.className = cls;
|
|
380
|
+
if (text != null) n.textContent = text;
|
|
381
|
+
return n;
|
|
382
|
+
};
|
|
383
|
+
const escapeHtml = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
384
|
+
|
|
385
|
+
let toastTimer = null;
|
|
386
|
+
function toast(msg) {
|
|
387
|
+
const t = $('#toast');
|
|
388
|
+
t.textContent = msg;
|
|
389
|
+
t.classList.add('show');
|
|
390
|
+
clearTimeout(toastTimer);
|
|
391
|
+
toastTimer = setTimeout(() => t.classList.remove('show'), 2200);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
async function copyText(text) {
|
|
395
|
+
try {
|
|
396
|
+
await navigator.clipboard.writeText(text);
|
|
397
|
+
return true;
|
|
398
|
+
} catch {
|
|
399
|
+
const ta = el('textarea');
|
|
400
|
+
ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0';
|
|
401
|
+
document.body.appendChild(ta); ta.select();
|
|
402
|
+
let ok = false;
|
|
403
|
+
try { ok = document.execCommand('copy'); } catch {}
|
|
404
|
+
ta.remove();
|
|
405
|
+
return ok;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/* ==================================================================
|
|
410
|
+
* 1. 状态与持久化
|
|
411
|
+
* ================================================================== */
|
|
412
|
+
const CFG_KEY = 'yu-harness-config';
|
|
413
|
+
const defaultCfg = {
|
|
414
|
+
baseURL: 'http://localhost:8787/v1',
|
|
415
|
+
apiKey: 'local',
|
|
416
|
+
model: 'YuMind',
|
|
417
|
+
temperature: 0.3,
|
|
418
|
+
maxSteps: 8,
|
|
419
|
+
systemPrompt: '',
|
|
420
|
+
stream: true,
|
|
421
|
+
theme: 'dark',
|
|
422
|
+
toolEnabled: {}
|
|
423
|
+
};
|
|
424
|
+
let cfg = { ...defaultCfg, ...JSON.parse(localStorage.getItem(CFG_KEY) || '{}') };
|
|
425
|
+
const saveCfg = () => { try { localStorage.setItem(CFG_KEY, JSON.stringify(cfg)); } catch {} };
|
|
426
|
+
|
|
427
|
+
const CONV_KEY = 'yu-harness-convs';
|
|
428
|
+
const ACTIVE_KEY = 'yu-harness-active';
|
|
429
|
+
let conversations = [];
|
|
430
|
+
try { conversations = JSON.parse(localStorage.getItem(CONV_KEY) || '[]'); } catch { conversations = []; }
|
|
431
|
+
if (!Array.isArray(conversations)) conversations = [];
|
|
432
|
+
let activeConvId = localStorage.getItem(ACTIVE_KEY) || null;
|
|
433
|
+
let convFilter = '';
|
|
434
|
+
|
|
435
|
+
function saveConvs() {
|
|
436
|
+
try {
|
|
437
|
+
// FileSystemHandle 无法序列化,持久化时剔除
|
|
438
|
+
const safe = conversations.map(c => ({
|
|
439
|
+
id: c.id, title: c.title, history: c.history || [],
|
|
440
|
+
traces: (c.traces || []).slice(-300), workspaceName: c.workspaceName || '',
|
|
441
|
+
updatedAt: c.updatedAt || Date.now()
|
|
442
|
+
}));
|
|
443
|
+
localStorage.setItem(CONV_KEY, JSON.stringify(safe));
|
|
444
|
+
localStorage.setItem(ACTIVE_KEY, activeConvId || '');
|
|
445
|
+
} catch (e) {
|
|
446
|
+
toast('本地存储写入失败:' + e.message);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const getActiveConv = () => conversations.find(c => c.id === activeConvId);
|
|
451
|
+
|
|
452
|
+
/* ==================================================================
|
|
453
|
+
* 2. Markdown 渲染(零依赖,先转义再套标签,天然防注入)
|
|
454
|
+
* ================================================================== */
|
|
455
|
+
function codeBlockHtml(lang, code) {
|
|
456
|
+
const label = lang || 'text';
|
|
457
|
+
return `<div class="code-wrap"><div class="code-head"><span>${escapeHtml(label)}</span>`
|
|
458
|
+
+ `<button class="code-copy" type="button">复制</button></div>`
|
|
459
|
+
+ `<pre><code>${escapeHtml(code.replace(/\n$/, ''))}</code></pre></div>`;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function inlineMd(text) {
|
|
463
|
+
let s = escapeHtml(text);
|
|
464
|
+
const hold = [];
|
|
465
|
+
// 行内代码
|
|
466
|
+
s = s.replace(/`([^`\n]+)`/g, (m, c) => { hold.push(`<code>${c}</code>`); return `\u0000${hold.length - 1}\u0000`; });
|
|
467
|
+
// 图片 -> 链接(本地应用不自动加载外链图片)
|
|
468
|
+
s = s.replace(/!\[([^\]]*)\]\((https?:\/\/[^\s)]+)\)/g, '[$1]($2)');
|
|
469
|
+
// 链接
|
|
470
|
+
s = s.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,
|
|
471
|
+
'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
|
|
472
|
+
// 粗体 / 斜体 / 删除线
|
|
473
|
+
s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
|
474
|
+
s = s.replace(/__([^_]+)__/g, '<strong>$1</strong>');
|
|
475
|
+
s = s.replace(/(^|[^*\w])\*([^*\n]+)\*/g, '$1<em>$2</em>');
|
|
476
|
+
s = s.replace(/~~([^~]+)~~/g, '<del>$1</del>');
|
|
477
|
+
// 还原行内代码
|
|
478
|
+
s = s.replace(/\u0000(\d+)\u0000/g, (m, i) => hold[+i]);
|
|
479
|
+
return s;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function mdToHtml(src) {
|
|
483
|
+
if (!src) return '';
|
|
484
|
+
const text = String(src).replace(/\r\n?/g, '\n');
|
|
485
|
+
const blocks = [];
|
|
486
|
+
// 抽出围栏代码块,避免被块级语法误伤
|
|
487
|
+
const withPlaceholders = text.replace(/```([^\n`]*)\n([\s\S]*?)(?:```|$)/g, (m, lang, code) => {
|
|
488
|
+
blocks.push({ lang: (lang || '').trim(), code });
|
|
489
|
+
return `\n\u0001${blocks.length - 1}\u0001\n`;
|
|
490
|
+
});
|
|
491
|
+
|
|
492
|
+
const lines = withPlaceholders.split('\n');
|
|
493
|
+
const out = [];
|
|
494
|
+
let para = [], list = null, quote = [];
|
|
495
|
+
|
|
496
|
+
const flushPara = () => { if (para.length) { out.push('<p>' + para.join('<br>') + '</p>'); para = []; } };
|
|
497
|
+
const flushList = () => {
|
|
498
|
+
if (list) { out.push(`<${list.type}>` + list.items.map(i => `<li>${i}</li>`).join('') + `</${list.type}>`); list = null; }
|
|
499
|
+
};
|
|
500
|
+
const flushQuote = () => { if (quote.length) { out.push('<blockquote>' + quote.join('<br>') + '</blockquote>'); quote = []; } };
|
|
501
|
+
const flushAll = () => { flushPara(); flushList(); flushQuote(); };
|
|
502
|
+
|
|
503
|
+
for (const line of lines) {
|
|
504
|
+
const codeRef = line.match(/^\u0001(\d+)\u0001$/);
|
|
505
|
+
if (codeRef) {
|
|
506
|
+
flushAll();
|
|
507
|
+
const b = blocks[+codeRef[1]];
|
|
508
|
+
out.push(codeBlockHtml(b.lang, b.code));
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
if (!line.trim()) { flushAll(); continue; }
|
|
512
|
+
|
|
513
|
+
const h = line.match(/^(#{1,6})\s+(.*)$/);
|
|
514
|
+
if (h) { flushAll(); out.push(`<h${h[1].length}>${inlineMd(h[2])}</h${h[1].length}>`); continue; }
|
|
515
|
+
|
|
516
|
+
if (/^\s*(?:---+|\*\*\*+|___+)\s*$/.test(line)) { flushAll(); out.push('<hr>'); continue; }
|
|
517
|
+
|
|
518
|
+
const q = line.match(/^\s*>\s?(.*)$/);
|
|
519
|
+
if (q) { flushPara(); flushList(); quote.push(inlineMd(q[1])); continue; }
|
|
520
|
+
|
|
521
|
+
const ul = line.match(/^\s*[-*+]\s+(.*)$/);
|
|
522
|
+
if (ul) {
|
|
523
|
+
flushPara(); flushQuote();
|
|
524
|
+
if (!list || list.type !== 'ul') { flushList(); list = { type: 'ul', items: [] }; }
|
|
525
|
+
list.items.push(inlineMd(ul[1])); continue;
|
|
526
|
+
}
|
|
527
|
+
const ol = line.match(/^\s*\d+[.)]\s+(.*)$/);
|
|
528
|
+
if (ol) {
|
|
529
|
+
flushPara(); flushQuote();
|
|
530
|
+
if (!list || list.type !== 'ol') { flushList(); list = { type: 'ol', items: [] }; }
|
|
531
|
+
list.items.push(inlineMd(ol[1])); continue;
|
|
532
|
+
}
|
|
533
|
+
flushList(); flushQuote();
|
|
534
|
+
para.push(inlineMd(line));
|
|
535
|
+
}
|
|
536
|
+
flushAll();
|
|
537
|
+
return out.join('\n');
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/* ==================================================================
|
|
541
|
+
* 3. 会话模型
|
|
542
|
+
* ================================================================== */
|
|
543
|
+
const messagesEl = $('#messages'), traceEl = $('#trace'), convListEl = $('#convList');
|
|
544
|
+
const scrollBottom = (node) => { node.scrollTop = node.scrollHeight; };
|
|
545
|
+
const nearBottom = (node) => node.scrollHeight - node.scrollTop - node.clientHeight < 120;
|
|
546
|
+
|
|
547
|
+
function renderConvList() {
|
|
548
|
+
convListEl.innerHTML = '';
|
|
549
|
+
const q = convFilter.trim().toLowerCase();
|
|
550
|
+
const shown = conversations.filter(c => !q || (c.title || '').toLowerCase().includes(q));
|
|
551
|
+
if (!shown.length) {
|
|
552
|
+
convListEl.appendChild(el('div', 'conv-empty', q ? '没有匹配的对话' : '还没有对话,点上方「新建对话」'));
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
shown.forEach(c => {
|
|
556
|
+
const div = el('div', 'conv-item' + (c.id === activeConvId ? ' active' : ''));
|
|
557
|
+
div.title = `${c.title || '新对话'} · ${(c.history || []).length} 条消息`;
|
|
558
|
+
div.onclick = () => switchConversation(c.id);
|
|
559
|
+
|
|
560
|
+
const title = el('span', 'title', c.title || '新对话');
|
|
561
|
+
title.ondblclick = (e) => {
|
|
562
|
+
e.stopPropagation();
|
|
563
|
+
const next = prompt('重命名对话', c.title || '');
|
|
564
|
+
if (next != null && next.trim()) { c.title = next.trim().slice(0, 60); saveConvs(); renderConvList(); }
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
const delBtn = el('span', 'del-btn');
|
|
568
|
+
delBtn.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`;
|
|
569
|
+
delBtn.title = '删除对话';
|
|
570
|
+
delBtn.onclick = (e) => {
|
|
571
|
+
e.stopPropagation();
|
|
572
|
+
if (!confirm(`删除对话「${c.title || '新对话'}」?此操作不可撤销。`)) return;
|
|
573
|
+
conversations = conversations.filter(x => x.id !== c.id);
|
|
574
|
+
if (activeConvId === c.id) activeConvId = conversations[0]?.id || null;
|
|
575
|
+
if (!activeConvId) createConversation(); else switchConversation(activeConvId);
|
|
576
|
+
saveConvs();
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
div.appendChild(title);
|
|
580
|
+
div.appendChild(delBtn);
|
|
581
|
+
convListEl.appendChild(div);
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function addMessage(role, content) {
|
|
586
|
+
const div = el('div', 'msg ' + role);
|
|
587
|
+
if (role === 'assistant') div.innerHTML = mdToHtml(content);
|
|
588
|
+
else div.textContent = content;
|
|
589
|
+
messagesEl.appendChild(div);
|
|
590
|
+
scrollBottom(messagesEl);
|
|
591
|
+
return div;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function addAssistantActions(node, rawText) {
|
|
595
|
+
const bar = el('div', 'msg-tools');
|
|
596
|
+
const copyBtn = el('button', null, '复制');
|
|
597
|
+
copyBtn.onclick = async () => { await copyText(rawText); toast('已复制'); };
|
|
598
|
+
const regen = el('button', null, '重新生成');
|
|
599
|
+
regen.onclick = () => regenerate(rawText);
|
|
600
|
+
bar.appendChild(copyBtn);
|
|
601
|
+
bar.appendChild(regen);
|
|
602
|
+
node.appendChild(bar);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function addToolCard(name, args, output, ok) {
|
|
606
|
+
const card = el('div', 'tool-card' + (ok ? ' ok' : ''));
|
|
607
|
+
const head = el('div', 'tool-head');
|
|
608
|
+
head.innerHTML = `<span><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-2px;margin-right:4px;"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>${escapeHtml(name)}</span>`
|
|
609
|
+
+ `<span>${ok ? '成功' : '失败'} · 展开</span>`;
|
|
610
|
+
head.onclick = () => card.classList.toggle('open');
|
|
611
|
+
const body = el('div', 'tool-body');
|
|
612
|
+
const pre = el('pre', null, `参数: ${JSON.stringify(args, null, 2)}\n\n结果: ${String(output).slice(0, 4000)}`);
|
|
613
|
+
body.appendChild(pre);
|
|
614
|
+
card.appendChild(head); card.appendChild(body);
|
|
615
|
+
messagesEl.appendChild(card);
|
|
616
|
+
scrollBottom(messagesEl);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const kindMap = {
|
|
620
|
+
'user.message': ['用户输入', 'k-accent'],
|
|
621
|
+
'agent.step': ['Agent 步骤', 'k-accent'],
|
|
622
|
+
'provider.request': ['请求模型', 'k-accent'],
|
|
623
|
+
'provider.response': ['模型响应', 'k-ok'],
|
|
624
|
+
'assistant.message': ['模型回复', ''],
|
|
625
|
+
'tool.call': ['工具调用', 'k-warn'],
|
|
626
|
+
'tool.result': ['工具结果', 'k-ok'],
|
|
627
|
+
'agent.done': ['完成', 'k-ok'],
|
|
628
|
+
'agent.error': ['错误', 'k-err'],
|
|
629
|
+
'agent.abort': ['已中止', 'k-warn']
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
function addTrace(evt, appendToState = true) {
|
|
633
|
+
if (appendToState) {
|
|
634
|
+
const conv = getActiveConv();
|
|
635
|
+
if (conv) {
|
|
636
|
+
if (!conv.traces) conv.traces = [];
|
|
637
|
+
conv.traces.push(evt);
|
|
638
|
+
if (conv.traces.length > 300) conv.traces.splice(0, conv.traces.length - 300);
|
|
639
|
+
saveConvs();
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
const [label, cls] = kindMap[evt.type] || [evt.type, ''];
|
|
643
|
+
const div = el('div', 'trace-item ' + cls);
|
|
644
|
+
const head = el('div', 't-head');
|
|
645
|
+
head.innerHTML = `<span class="t-kind">${escapeHtml(label)}</span><span class="t-time">${new Date(evt.ts).toLocaleTimeString('zh-CN', { hour12: false })}</span>`;
|
|
646
|
+
const pre = el('pre', null, JSON.stringify(evt.detail, null, 2).slice(0, 700));
|
|
647
|
+
div.appendChild(head); div.appendChild(pre);
|
|
648
|
+
traceEl.appendChild(div);
|
|
649
|
+
if (nearBottom(traceEl)) scrollBottom(traceEl);
|
|
650
|
+
|
|
651
|
+
if (evt.type === 'tool.result') {
|
|
652
|
+
addToolCard(evt.detail.name, evt.detail.args, evt.detail.output, evt.detail.ok);
|
|
653
|
+
refreshVfs();
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function renderTraces(conv) {
|
|
658
|
+
traceEl.innerHTML = '';
|
|
659
|
+
const traces = conv.traces || [];
|
|
660
|
+
if (!traces.length) {
|
|
661
|
+
traceEl.appendChild(el('div', 'trace-empty', '本次对话还没有运行记录。'));
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
traces.forEach(evt => addTrace(evt, false));
|
|
665
|
+
scrollBottom(traceEl);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/* ==================================================================
|
|
669
|
+
* 4. 会话切换
|
|
670
|
+
* ================================================================== */
|
|
671
|
+
function renderHistoryMessages(conv) {
|
|
672
|
+
messagesEl.innerHTML = '';
|
|
673
|
+
const history = (conv && conv.history) || [];
|
|
674
|
+
if (!history.length) {
|
|
675
|
+
addMessage('assistant', '**Yu Harness 已就绪。** 配置左侧 Provider 后即可对话;也可以绑定本地文件夹,让我读写真实文件。');
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
history.forEach(m => {
|
|
679
|
+
if (m.role === 'user') {
|
|
680
|
+
addMessage('user', m.content || '');
|
|
681
|
+
} else if (m.role === 'assistant' && (m.content || '').trim()) {
|
|
682
|
+
const node = addMessage('assistant', m.content);
|
|
683
|
+
addAssistantActions(node, m.content);
|
|
684
|
+
} else if (m.role === 'tool') {
|
|
685
|
+
addToolCard(m.name || '工具', {}, String(m.content || '').slice(0, 1200), true);
|
|
686
|
+
}
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function switchConversation(id) {
|
|
691
|
+
if (busy) { toast('正在生成,请先停止(Esc)'); return; }
|
|
692
|
+
activeConvId = id;
|
|
693
|
+
saveConvs();
|
|
694
|
+
renderConvList();
|
|
695
|
+
|
|
696
|
+
const conv = getActiveConv();
|
|
697
|
+
if (!conv) return;
|
|
698
|
+
|
|
699
|
+
renderHistoryMessages(conv);
|
|
700
|
+
renderTraces(conv);
|
|
701
|
+
updateWorkspaceUI(conv);
|
|
702
|
+
scrollBottom(messagesEl);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
function createConversation() {
|
|
706
|
+
if (busy) { toast('正在生成,请先停止(Esc)'); return; }
|
|
707
|
+
const id = 'conv_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
|
|
708
|
+
const conv = { id, title: '新对话', history: [], traces: [], workspaceName: '', updatedAt: Date.now() };
|
|
709
|
+
conversations.unshift(conv);
|
|
710
|
+
switchConversation(id);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/* ==================================================================
|
|
714
|
+
* 5. 工作区(File System Access API)
|
|
715
|
+
* ================================================================== */
|
|
716
|
+
async function selectWorkspace() {
|
|
717
|
+
if (!window.showDirectoryPicker) {
|
|
718
|
+
toast('当前浏览器不支持 File System Access API,请用最新版 Edge / Chrome');
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
try {
|
|
722
|
+
const handle = await window.showDirectoryPicker({ mode: 'readwrite' });
|
|
723
|
+
const conv = getActiveConv();
|
|
724
|
+
conv.workspaceHandle = handle;
|
|
725
|
+
conv.workspaceName = handle.name;
|
|
726
|
+
saveConvs();
|
|
727
|
+
updateWorkspaceUI(conv);
|
|
728
|
+
toast(`已绑定文件夹:${handle.name}`);
|
|
729
|
+
} catch (err) {
|
|
730
|
+
if (err.name !== 'AbortError') toast('选择文件夹失败:' + err.message);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function updateWorkspaceUI(conv) {
|
|
735
|
+
const node = $('#workspaceStatus');
|
|
736
|
+
if (conv && conv.workspaceHandle) {
|
|
737
|
+
node.innerHTML = `✅ 已绑定:<strong>${escapeHtml(conv.workspaceHandle.name)}</strong>`;
|
|
738
|
+
node.style.color = 'var(--ok)';
|
|
739
|
+
} else if (conv && conv.workspaceName) {
|
|
740
|
+
node.innerHTML = `⚠️ 已断开:<strong>${escapeHtml(conv.workspaceName)}</strong>(重新点击授权)`;
|
|
741
|
+
node.style.color = 'var(--warn)';
|
|
742
|
+
} else {
|
|
743
|
+
node.innerHTML = '未绑定(使用浏览器虚拟文件系统)';
|
|
744
|
+
node.style.color = 'var(--muted)';
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
async function readFileFromWorkspace(conv, filename) {
|
|
749
|
+
if (!conv.workspaceHandle) throw new Error('未绑定真实工作区');
|
|
750
|
+
const fh = await conv.workspaceHandle.getFileHandle(filename);
|
|
751
|
+
return await (await fh.getFile()).text();
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
async function writeFileToWorkspace(conv, filename, content) {
|
|
755
|
+
if (!conv.workspaceHandle) throw new Error('未绑定真实工作区');
|
|
756
|
+
const fh = await conv.workspaceHandle.getFileHandle(filename, { create: true });
|
|
757
|
+
const w = await fh.createWritable();
|
|
758
|
+
await w.write(content);
|
|
759
|
+
await w.close();
|
|
760
|
+
return `已写入真实文件:${filename}(${String(content).length} 字符)`;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
async function listWorkspace(conv) {
|
|
764
|
+
if (!conv.workspaceHandle) throw new Error('未绑定真实工作区');
|
|
765
|
+
const names = [];
|
|
766
|
+
for await (const [name, handle] of conv.workspaceHandle.entries()) {
|
|
767
|
+
names.push(handle.kind === 'directory' ? name + '/' : name);
|
|
768
|
+
}
|
|
769
|
+
return names.sort().join('\n') || '(空文件夹)';
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/* ==================================================================
|
|
773
|
+
* 6. 虚拟文件系统
|
|
774
|
+
* ================================================================== */
|
|
775
|
+
const VFS_KEY = 'yu-harness-vfs';
|
|
776
|
+
const vfsLoad = () => { try { return JSON.parse(localStorage.getItem(VFS_KEY) || '{}'); } catch { return {}; } };
|
|
777
|
+
const vfsSave = (o) => localStorage.setItem(VFS_KEY, JSON.stringify(o));
|
|
778
|
+
|
|
779
|
+
function refreshVfs() {
|
|
780
|
+
const box = $('#vfsList');
|
|
781
|
+
if (!box) return;
|
|
782
|
+
box.innerHTML = '';
|
|
783
|
+
const fs = vfsLoad();
|
|
784
|
+
const keys = Object.keys(fs).sort();
|
|
785
|
+
if (!keys.length) {
|
|
786
|
+
box.appendChild(el('div', 'trace-empty', '虚拟文件为空。绑定真实文件夹后,file_write 会直接写入磁盘。'));
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
keys.forEach(k => {
|
|
790
|
+
const row = el('div', 'file-row');
|
|
791
|
+
row.title = '点击预览';
|
|
792
|
+
const name = el('span', 'fname', k);
|
|
793
|
+
const meta = el('span', 'fmeta', `${String(fs[k]).length}B`);
|
|
794
|
+
row.appendChild(name); row.appendChild(meta);
|
|
795
|
+
row.onclick = () => {
|
|
796
|
+
openModal(k, `<pre>${escapeHtml(String(fs[k]).slice(0, 6000))}</pre>`);
|
|
797
|
+
};
|
|
798
|
+
box.appendChild(row);
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/* ==================================================================
|
|
803
|
+
* 7. 工具注册表
|
|
804
|
+
* ================================================================== */
|
|
805
|
+
const tools = new Map();
|
|
806
|
+
const registerTool = (t) => tools.set(t.name, t);
|
|
807
|
+
const isEnabled = (t) => (cfg.toolEnabled && typeof cfg.toolEnabled[t.name] === 'boolean') ? cfg.toolEnabled[t.name] : t.enabled !== false;
|
|
808
|
+
const toolDefs = () => [...tools.values()].filter(isEnabled)
|
|
809
|
+
.map(t => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } }));
|
|
810
|
+
|
|
811
|
+
async function executeTool(name, args) {
|
|
812
|
+
const t = tools.get(name);
|
|
813
|
+
if (!t) throw new Error(`未知工具: ${name}`);
|
|
814
|
+
if (!isEnabled(t)) throw new Error(`工具已禁用: ${name}`);
|
|
815
|
+
return await t.run(args || {});
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
registerTool({
|
|
819
|
+
name: 'calculator',
|
|
820
|
+
description: '计算简单数学表达式(四则运算、括号、取余、幂)',
|
|
821
|
+
enabled: true,
|
|
822
|
+
parameters: { type: 'object', properties: { expression: { type: 'string', description: '例如 (2+3)*4/2 或 2**10' } }, required: ['expression'] },
|
|
823
|
+
async run({ expression }) {
|
|
824
|
+
const src = String(expression).trim();
|
|
825
|
+
if (!/^[\d+\-*/().%\s]+$/.test(src)) throw new Error('表达式只允许数字与 + - * / ( ) % 运算符');
|
|
826
|
+
const val = Function('"use strict";return (' + src.replace(/\*\*/g, '**') + ')')();
|
|
827
|
+
if (typeof val !== 'number' || !isFinite(val)) throw new Error('结果不是有限数值');
|
|
828
|
+
return String(val);
|
|
829
|
+
}
|
|
830
|
+
});
|
|
831
|
+
|
|
832
|
+
registerTool({
|
|
833
|
+
name: 'now',
|
|
834
|
+
description: '获取当前日期时间,可指定 IANA 时区(如 Asia/Shanghai)',
|
|
835
|
+
enabled: true,
|
|
836
|
+
parameters: { type: 'object', properties: { tz: { type: 'string' } } },
|
|
837
|
+
async run({ tz }) {
|
|
838
|
+
try {
|
|
839
|
+
return new Date().toLocaleString('zh-CN', tz ? { timeZone: tz, hour12: false } : { hour12: false });
|
|
840
|
+
} catch {
|
|
841
|
+
throw new Error('无效的时区标识:' + tz);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
});
|
|
845
|
+
|
|
846
|
+
registerTool({
|
|
847
|
+
name: 'file_write',
|
|
848
|
+
description: '写入文件。已绑定真实文件夹时写入磁盘,否则写入浏览器虚拟文件系统',
|
|
849
|
+
enabled: true,
|
|
850
|
+
parameters: {
|
|
851
|
+
type: 'object',
|
|
852
|
+
properties: { path: { type: 'string', description: '文件路径/文件名' }, content: { type: 'string', description: '文件内容' } },
|
|
853
|
+
required: ['path', 'content']
|
|
854
|
+
},
|
|
855
|
+
async run({ path, content }) {
|
|
856
|
+
const conv = getActiveConv();
|
|
857
|
+
if (conv && conv.workspaceHandle) return await writeFileToWorkspace(conv, path, content);
|
|
858
|
+
const fs = vfsLoad();
|
|
859
|
+
fs[path] = String(content);
|
|
860
|
+
vfsSave(fs);
|
|
861
|
+
refreshVfs();
|
|
862
|
+
return `已写入虚拟文件 ${path}(${String(content).length} 字符)`;
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
|
|
866
|
+
registerTool({
|
|
867
|
+
name: 'file_read',
|
|
868
|
+
description: '读取文件。已绑定真实文件夹时读磁盘,否则读浏览器虚拟文件系统',
|
|
869
|
+
enabled: true,
|
|
870
|
+
parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
|
|
871
|
+
async run({ path }) {
|
|
872
|
+
const conv = getActiveConv();
|
|
873
|
+
if (conv && conv.workspaceHandle) return await readFileFromWorkspace(conv, path);
|
|
874
|
+
const fs = vfsLoad();
|
|
875
|
+
if (!(path in fs)) throw new Error(`文件不存在:${path}`);
|
|
876
|
+
return fs[path];
|
|
877
|
+
}
|
|
878
|
+
});
|
|
879
|
+
|
|
880
|
+
registerTool({
|
|
881
|
+
name: 'file_list',
|
|
882
|
+
description: '列出当前工作区中的文件(需已绑定真实文件夹)',
|
|
883
|
+
enabled: true,
|
|
884
|
+
parameters: { type: 'object', properties: {} },
|
|
885
|
+
async run() { return await listWorkspace(getActiveConv()); }
|
|
886
|
+
});
|
|
887
|
+
|
|
888
|
+
/* ==================================================================
|
|
889
|
+
* 8. Provider(支持 SSE 流式与非流式)
|
|
890
|
+
* ================================================================== */
|
|
891
|
+
function buildBody(messages, defs, stream) {
|
|
892
|
+
const body = {
|
|
893
|
+
model: cfg.model || 'model',
|
|
894
|
+
temperature: Number(cfg.temperature) || 0,
|
|
895
|
+
stream: !!stream,
|
|
896
|
+
messages: messages.map(m => {
|
|
897
|
+
const out = { role: m.role, content: m.content == null ? '' : m.content };
|
|
898
|
+
if (m.tool_calls) out.tool_calls = m.tool_calls;
|
|
899
|
+
if (m.tool_call_id) out.tool_call_id = m.tool_call_id;
|
|
900
|
+
if (m.name) out.name = m.name;
|
|
901
|
+
return out;
|
|
902
|
+
})
|
|
903
|
+
};
|
|
904
|
+
if (defs && defs.length) body.tools = defs;
|
|
905
|
+
return body;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
function endpoint() {
|
|
909
|
+
const base = (cfg.baseURL || '').trim().replace(/\/+$/, '');
|
|
910
|
+
if (!base) throw new Error('请填写 Base URL');
|
|
911
|
+
return base.endsWith('/chat/completions') ? base : base + '/chat/completions';
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
function headers() {
|
|
915
|
+
const h = { 'Content-Type': 'application/json' };
|
|
916
|
+
if (cfg.apiKey) h['Authorization'] = 'Bearer ' + cfg.apiKey;
|
|
917
|
+
return h;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function mergeToolCallDeltas(acc, deltas) {
|
|
921
|
+
for (const d of deltas) {
|
|
922
|
+
const i = d.index == null ? acc.length : d.index;
|
|
923
|
+
if (!acc[i]) acc[i] = { id: '', type: 'function', function: { name: '', arguments: '' } };
|
|
924
|
+
const t = acc[i];
|
|
925
|
+
if (d.id) t.id = d.id;
|
|
926
|
+
if (d.type) t.type = d.type;
|
|
927
|
+
if (d.function?.name) t.function.name += d.function.name;
|
|
928
|
+
if (d.function?.arguments) t.function.arguments += d.function.arguments;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
async function openaiChat({ messages, tools: defs, signal, onToken }) {
|
|
933
|
+
const wantStream = cfg.stream !== false;
|
|
934
|
+
const url = endpoint();
|
|
935
|
+
|
|
936
|
+
let res;
|
|
937
|
+
try {
|
|
938
|
+
res = await fetch(url, {
|
|
939
|
+
method: 'POST',
|
|
940
|
+
headers: headers(),
|
|
941
|
+
body: JSON.stringify(buildBody(messages, defs, wantStream)),
|
|
942
|
+
signal
|
|
943
|
+
});
|
|
944
|
+
} catch (e) {
|
|
945
|
+
if (e.name === 'AbortError') throw e;
|
|
946
|
+
throw new Error(`网络请求失败:${e.message}(检查 Base URL / 服务是否启动)`);
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
if (!res.ok) {
|
|
950
|
+
const text = await res.text().catch(() => '');
|
|
951
|
+
throw new Error(`HTTP ${res.status} ${res.statusText}\n${text.slice(0, 800)}`);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
const ctype = (res.headers.get('content-type') || '').toLowerCase();
|
|
955
|
+
|
|
956
|
+
// 服务端忽略了 stream:true、或本身就是非流式请求 → 一次性 JSON
|
|
957
|
+
const looksLikeSse = ctype.includes('event-stream');
|
|
958
|
+
if (!wantStream || (!looksLikeSse && ctype.includes('application/json'))) {
|
|
959
|
+
const data = JSON.parse(await res.text());
|
|
960
|
+
const msg = data.choices?.[0]?.message;
|
|
961
|
+
if (!msg) throw new Error('响应缺少 choices[0].message');
|
|
962
|
+
return { message: msg };
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
// SSE 解析
|
|
966
|
+
const reader = res.body.getReader();
|
|
967
|
+
const decoder = new TextDecoder('utf-8');
|
|
968
|
+
let buf = '', content = '', reasoning = '';
|
|
969
|
+
const acc = [];
|
|
970
|
+
let finished = false;
|
|
971
|
+
|
|
972
|
+
const handleLine = (rawLine) => {
|
|
973
|
+
const line = rawLine.replace(/\r$/, '');
|
|
974
|
+
if (!line || line.startsWith(':')) return;
|
|
975
|
+
if (!line.startsWith('data:')) return;
|
|
976
|
+
const payload = line.slice(5).trim();
|
|
977
|
+
if (payload === '[DONE]') { finished = true; return; }
|
|
978
|
+
let json;
|
|
979
|
+
try { json = JSON.parse(payload); } catch { return; }
|
|
980
|
+
const choice = json.choices?.[0];
|
|
981
|
+
if (!choice) return;
|
|
982
|
+
const delta = choice.delta || {};
|
|
983
|
+
if (delta.reasoning_content) reasoning += delta.reasoning_content;
|
|
984
|
+
if (typeof delta.content === 'string' && delta.content) {
|
|
985
|
+
content += delta.content;
|
|
986
|
+
onToken && onToken({ type: 'content', text: delta.content, content, reasoning });
|
|
987
|
+
}
|
|
988
|
+
if (Array.isArray(delta.tool_calls) && delta.tool_calls.length) {
|
|
989
|
+
mergeToolCallDeltas(acc, delta.tool_calls);
|
|
990
|
+
onToken && onToken({ type: 'tool_call' });
|
|
991
|
+
}
|
|
992
|
+
};
|
|
993
|
+
|
|
994
|
+
while (!finished) {
|
|
995
|
+
const { done, value } = await reader.read();
|
|
996
|
+
if (done) break;
|
|
997
|
+
buf += decoder.decode(value, { stream: true });
|
|
998
|
+
let nl;
|
|
999
|
+
while (!finished && (nl = buf.indexOf('\n')) >= 0) {
|
|
1000
|
+
handleLine(buf.slice(0, nl));
|
|
1001
|
+
buf = buf.slice(nl + 1);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
if (buf.trim()) handleLine(buf);
|
|
1005
|
+
|
|
1006
|
+
const toolCalls = acc.filter(t => t && t.function.name)
|
|
1007
|
+
.map(t => ({ id: t.id || 'call_' + Math.random().toString(36).slice(2, 10), type: 'function', function: { name: t.function.name, arguments: t.function.arguments || '{}' } }));
|
|
1008
|
+
|
|
1009
|
+
if (!content && !toolCalls.length) {
|
|
1010
|
+
throw new Error('流式响应为空(服务端可能不支持 SSE,试试关闭「流式输出」)');
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
return { message: { role: 'assistant', content, tool_calls: toolCalls.length ? toolCalls : undefined, reasoning_content: reasoning || undefined } };
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
function normalizeToolCalls(msg) {
|
|
1017
|
+
if (Array.isArray(msg.tool_calls) && msg.tool_calls.length) {
|
|
1018
|
+
return msg.tool_calls.map(tc => ({
|
|
1019
|
+
id: tc.id || 'call_' + Math.random().toString(36).slice(2, 10),
|
|
1020
|
+
type: 'function',
|
|
1021
|
+
function: {
|
|
1022
|
+
name: tc.function?.name || tc.name,
|
|
1023
|
+
arguments: typeof tc.function?.arguments === 'string' ? tc.function.arguments : JSON.stringify(tc.function?.arguments ?? {})
|
|
1024
|
+
}
|
|
1025
|
+
})).filter(tc => tc.function.name);
|
|
1026
|
+
}
|
|
1027
|
+
return [];
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
/* ==================================================================
|
|
1031
|
+
* 9. Agent Runner
|
|
1032
|
+
* ================================================================== */
|
|
1033
|
+
class AgentRunner {
|
|
1034
|
+
constructor({ provider, initialMessages = [], maxSteps = 8, onToken }) {
|
|
1035
|
+
this.provider = provider;
|
|
1036
|
+
this.messages = initialMessages.slice();
|
|
1037
|
+
this.maxSteps = maxSteps;
|
|
1038
|
+
this.onToken = onToken;
|
|
1039
|
+
this.abort = null;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
cancel() { this.abort?.abort(); }
|
|
1043
|
+
|
|
1044
|
+
async run(userText, onEvent) {
|
|
1045
|
+
const emit = (type, detail = {}) => onEvent?.({ type, detail, ts: Date.now() });
|
|
1046
|
+
this.abort = new AbortController();
|
|
1047
|
+
|
|
1048
|
+
if (cfg.systemPrompt && cfg.systemPrompt.trim() && !this.messages.some(m => m.role === 'system')) {
|
|
1049
|
+
this.messages.unshift({ role: 'system', content: cfg.systemPrompt.trim() });
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
this.messages.push({ role: 'user', content: userText });
|
|
1053
|
+
emit('user.message', { content: userText });
|
|
1054
|
+
|
|
1055
|
+
for (let step = 0; step < this.maxSteps; step++) {
|
|
1056
|
+
emit('agent.step', { step: step + 1, of: this.maxSteps });
|
|
1057
|
+
const defs = toolDefs();
|
|
1058
|
+
emit('provider.request', { model: cfg.model, stream: cfg.stream !== false, tools: defs.map(d => d.function.name) });
|
|
1059
|
+
|
|
1060
|
+
const t0 = performance.now();
|
|
1061
|
+
let res;
|
|
1062
|
+
try {
|
|
1063
|
+
res = await this.provider.chat({ messages: this.messages, tools: defs, signal: this.abort.signal, onToken: this.onToken });
|
|
1064
|
+
} catch (e) {
|
|
1065
|
+
if (e.name === 'AbortError' || /aborted/i.test(e.message || '')) {
|
|
1066
|
+
emit('agent.abort', { step: step + 1 });
|
|
1067
|
+
return '(已停止生成)';
|
|
1068
|
+
}
|
|
1069
|
+
emit('agent.error', { message: e.message });
|
|
1070
|
+
throw e;
|
|
1071
|
+
}
|
|
1072
|
+
const ms = Math.round(performance.now() - t0);
|
|
1073
|
+
|
|
1074
|
+
const msg = res.message || {};
|
|
1075
|
+
const toolCalls = normalizeToolCalls(msg);
|
|
1076
|
+
this.messages.push({ role: 'assistant', content: msg.content ?? '', ...(toolCalls.length ? { tool_calls: toolCalls } : {}) });
|
|
1077
|
+
emit('provider.response', { ms, chars: (msg.content || '').length, toolCalls: toolCalls.map(t => t.function.name) });
|
|
1078
|
+
emit('assistant.message', { content: msg.content ?? '', toolCalls: toolCalls.map(t => ({ name: t.function.name, args: t.function.arguments })) });
|
|
1079
|
+
|
|
1080
|
+
if (!toolCalls.length) {
|
|
1081
|
+
emit('agent.done', { steps: step + 1, chars: (msg.content || '').length });
|
|
1082
|
+
return msg.content ?? '';
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
for (const tc of toolCalls) {
|
|
1086
|
+
const name = tc.function?.name;
|
|
1087
|
+
let args = {};
|
|
1088
|
+
try { args = JSON.parse(tc.function?.arguments || '{}'); }
|
|
1089
|
+
catch { args = {}; }
|
|
1090
|
+
emit('tool.call', { id: tc.id, name, args });
|
|
1091
|
+
let output, ok = true;
|
|
1092
|
+
try { output = await executeTool(name, args); }
|
|
1093
|
+
catch (e) { ok = false; output = `错误:${e.message}`; }
|
|
1094
|
+
emit('tool.result', { id: tc.id, name, args, ok, output: String(output).slice(0, 4000) });
|
|
1095
|
+
this.messages.push({ role: 'tool', tool_call_id: tc.id, name, content: String(output) });
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
emit('agent.done', { steps: this.maxSteps, note: '达到最大步数' });
|
|
1099
|
+
return `(达到最大步数 ${this.maxSteps},输出被截断)`;
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/* ==================================================================
|
|
1104
|
+
* 10. 主交互
|
|
1105
|
+
* ================================================================== */
|
|
1106
|
+
let busy = false, currentRunner = null;
|
|
1107
|
+
|
|
1108
|
+
function renderTools() {
|
|
1109
|
+
const box = $('#toolList');
|
|
1110
|
+
box.innerHTML = '';
|
|
1111
|
+
for (const t of tools.values()) {
|
|
1112
|
+
const item = el('label', 'tool-item');
|
|
1113
|
+
const cb = el('input');
|
|
1114
|
+
cb.type = 'checkbox';
|
|
1115
|
+
cb.checked = isEnabled(t);
|
|
1116
|
+
cb.addEventListener('change', () => {
|
|
1117
|
+
cfg.toolEnabled = cfg.toolEnabled || {};
|
|
1118
|
+
cfg.toolEnabled[t.name] = cb.checked;
|
|
1119
|
+
saveCfg();
|
|
1120
|
+
});
|
|
1121
|
+
const meta = el('div');
|
|
1122
|
+
meta.innerHTML = `<div class="ti-name">${escapeHtml(t.name)}</div><div class="ti-desc">${escapeHtml(t.description)}</div>`;
|
|
1123
|
+
item.appendChild(cb); item.appendChild(meta);
|
|
1124
|
+
box.appendChild(item);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
function setBusy(v) {
|
|
1129
|
+
busy = v;
|
|
1130
|
+
$('#btnSend').disabled = v;
|
|
1131
|
+
$('#btnStop').disabled = !v;
|
|
1132
|
+
$('#status').textContent = v ? '运行中…' : '就绪';
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
async function send() {
|
|
1136
|
+
if (busy) return;
|
|
1137
|
+
const input = $('#input');
|
|
1138
|
+
const text = input.value.trim();
|
|
1139
|
+
if (!text) return;
|
|
1140
|
+
|
|
1141
|
+
let conv = getActiveConv();
|
|
1142
|
+
if (!conv) { createConversation(); conv = getActiveConv(); }
|
|
1143
|
+
if (!conv) return;
|
|
1144
|
+
|
|
1145
|
+
const baseHistory = conv.history ? conv.history.slice() : [];
|
|
1146
|
+
input.value = '';
|
|
1147
|
+
autoGrow();
|
|
1148
|
+
updateTokenHint();
|
|
1149
|
+
await runTurn(conv, baseHistory, text);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
async function regenerate(userText) {
|
|
1153
|
+
if (busy) return;
|
|
1154
|
+
const conv = getActiveConv();
|
|
1155
|
+
if (!conv) return;
|
|
1156
|
+
const hist = conv.history || [];
|
|
1157
|
+
// 截断到最后一条用户消息之前,作为新的上下文
|
|
1158
|
+
let cut = hist.length;
|
|
1159
|
+
for (let i = hist.length - 1; i >= 0; i--) {
|
|
1160
|
+
if (hist[i].role === 'user') { cut = i; break; }
|
|
1161
|
+
}
|
|
1162
|
+
const context = hist.slice(0, cut);
|
|
1163
|
+
const lastUser = hist[cut]?.content || userText || '';
|
|
1164
|
+
conv.history = context;
|
|
1165
|
+
saveConvs();
|
|
1166
|
+
renderHistoryMessages(conv);
|
|
1167
|
+
await runTurn(conv, context, lastUser, { skipEcho: true });
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
function scheduleMarkdown(node, getText, isDone) {
|
|
1171
|
+
let pending = false;
|
|
1172
|
+
return () => {
|
|
1173
|
+
if (pending) return;
|
|
1174
|
+
pending = true;
|
|
1175
|
+
requestAnimationFrame(() => {
|
|
1176
|
+
pending = false;
|
|
1177
|
+
const stick = nearBottom(messagesEl);
|
|
1178
|
+
node.innerHTML = mdToHtml(getText());
|
|
1179
|
+
node.classList.toggle('cursor', !isDone());
|
|
1180
|
+
if (stick) scrollBottom(messagesEl);
|
|
1181
|
+
});
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
async function runTurn(conv, baseHistory, userText, opts = {}) {
|
|
1186
|
+
if (!opts.skipEcho) addMessage('user', userText);
|
|
1187
|
+
if (!conv.title || conv.title === '新对话') {
|
|
1188
|
+
conv.title = userText.slice(0, 18) + (userText.length > 18 ? '…' : '');
|
|
1189
|
+
renderConvList();
|
|
1190
|
+
}
|
|
1191
|
+
if (!conv.traces) conv.traces = [];
|
|
1192
|
+
|
|
1193
|
+
setBusy(true);
|
|
1194
|
+
const thinkDiv = addMessage('thinking', '模型思考中…');
|
|
1195
|
+
|
|
1196
|
+
// 跨步骤累积的展示文本;每步的流式增量单独跟踪
|
|
1197
|
+
let displayText = '';
|
|
1198
|
+
let stepAcc = '';
|
|
1199
|
+
let streamNode = null;
|
|
1200
|
+
let scheduleStream = () => {};
|
|
1201
|
+
|
|
1202
|
+
const ensureStreamNode = () => {
|
|
1203
|
+
if (streamNode) return;
|
|
1204
|
+
thinkDiv.remove();
|
|
1205
|
+
streamNode = el('div', 'msg assistant');
|
|
1206
|
+
scheduleStream = scheduleMarkdown(streamNode, () => displayText || '…', () => false);
|
|
1207
|
+
messagesEl.appendChild(streamNode);
|
|
1208
|
+
};
|
|
1209
|
+
|
|
1210
|
+
const onToken = (ev) => {
|
|
1211
|
+
if (ev.type !== 'content') return;
|
|
1212
|
+
ensureStreamNode();
|
|
1213
|
+
stepAcc = ev.content;
|
|
1214
|
+
const prev = displayText;
|
|
1215
|
+
displayText = (prev ? prev + '\n\n' : '') + stepAcc;
|
|
1216
|
+
scheduleStream();
|
|
1217
|
+
};
|
|
1218
|
+
|
|
1219
|
+
const onEvent = (evt) => {
|
|
1220
|
+
addTrace(evt);
|
|
1221
|
+
|
|
1222
|
+
if (evt.type === 'agent.step') {
|
|
1223
|
+
stepAcc = '';
|
|
1224
|
+
$('#status').textContent = `第 ${evt.detail.step}/${evt.detail.of} 步…`;
|
|
1225
|
+
}
|
|
1226
|
+
if (evt.type === 'assistant.message') {
|
|
1227
|
+
const full = evt.detail.content || '';
|
|
1228
|
+
// 非流式(或该步未走流式)时,用完整回复兜底
|
|
1229
|
+
if (!stepAcc && full) {
|
|
1230
|
+
ensureStreamNode();
|
|
1231
|
+
displayText = (displayText ? displayText + '\n\n' : '') + full;
|
|
1232
|
+
scheduleStream();
|
|
1233
|
+
}
|
|
1234
|
+
if (!full && !stepAcc && streamNode && !displayText) {
|
|
1235
|
+
// 纯工具调用步:不显示空气泡
|
|
1236
|
+
streamNode.remove();
|
|
1237
|
+
streamNode = null;
|
|
1238
|
+
scheduleStream = () => {};
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
if (evt.type === 'tool.call') {
|
|
1242
|
+
$('#status').textContent = `调用工具 ${evt.detail.name}…`;
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
1245
|
+
|
|
1246
|
+
const runner = new AgentRunner({
|
|
1247
|
+
provider: { name: 'openai-compatible', chat: openaiChat },
|
|
1248
|
+
initialMessages: baseHistory,
|
|
1249
|
+
maxSteps: Number(cfg.maxSteps) || 8,
|
|
1250
|
+
onToken
|
|
1251
|
+
});
|
|
1252
|
+
currentRunner = runner;
|
|
1253
|
+
|
|
1254
|
+
try {
|
|
1255
|
+
const final = await runner.run(userText, onEvent);
|
|
1256
|
+
conv.history = runner.messages.filter(m => m.role !== 'system');
|
|
1257
|
+
conv.updatedAt = Date.now();
|
|
1258
|
+
saveConvs();
|
|
1259
|
+
|
|
1260
|
+
thinkDiv.remove();
|
|
1261
|
+
if (!displayText && final) {
|
|
1262
|
+
displayText = final;
|
|
1263
|
+
ensureStreamNode();
|
|
1264
|
+
}
|
|
1265
|
+
if (streamNode) {
|
|
1266
|
+
streamNode.classList.remove('cursor');
|
|
1267
|
+
if (displayText) {
|
|
1268
|
+
streamNode.innerHTML = mdToHtml(displayText);
|
|
1269
|
+
addAssistantActions(streamNode, displayText);
|
|
1270
|
+
} else {
|
|
1271
|
+
streamNode.remove();
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
setBusy(false);
|
|
1275
|
+
$('#status').textContent = '就绪';
|
|
1276
|
+
} catch (e) {
|
|
1277
|
+
thinkDiv.remove();
|
|
1278
|
+
if (streamNode) streamNode.classList.remove('cursor');
|
|
1279
|
+
addMessage('error', '请求失败:' + e.message);
|
|
1280
|
+
// 保留已成功的工具往返,丢弃失败的空助手消息
|
|
1281
|
+
conv.history = runner.messages.filter(m => m.role !== 'system' && !(m.role === 'assistant' && !m.content && m.tool_calls));
|
|
1282
|
+
saveConvs();
|
|
1283
|
+
setBusy(false);
|
|
1284
|
+
$('#status').textContent = '出错';
|
|
1285
|
+
} finally {
|
|
1286
|
+
currentRunner = null;
|
|
1287
|
+
scrollBottom(messagesEl);
|
|
1288
|
+
updateTokenHint();
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
/* ==================================================================
|
|
1293
|
+
* 11. 导出 / 导入
|
|
1294
|
+
* ================================================================== */
|
|
1295
|
+
function download(filename, content, mime = 'text/plain;charset=utf-8') {
|
|
1296
|
+
const blob = new Blob([content], { type: mime });
|
|
1297
|
+
const a = el('a');
|
|
1298
|
+
a.href = URL.createObjectURL(blob);
|
|
1299
|
+
a.download = filename;
|
|
1300
|
+
document.body.appendChild(a);
|
|
1301
|
+
a.click();
|
|
1302
|
+
setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 1000);
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
function exportCurrent() {
|
|
1306
|
+
const conv = getActiveConv();
|
|
1307
|
+
if (!conv) return;
|
|
1308
|
+
const lines = [`# ${conv.title || '对话'}`, '', `> 导出时间:${new Date().toLocaleString('zh-CN')}`, ''];
|
|
1309
|
+
(conv.history || []).forEach(m => {
|
|
1310
|
+
if (m.role === 'user') lines.push(`## 🧑 用户`, '', m.content || '', '');
|
|
1311
|
+
else if (m.role === 'assistant' && (m.content || '').trim()) lines.push(`## 🤖 助手`, '', m.content, '');
|
|
1312
|
+
else if (m.role === 'tool') lines.push(`<details><summary>工具:${m.name || ''}</summary>`, '', '```', String(m.content).slice(0, 3000), '```', '', '</details>', '');
|
|
1313
|
+
});
|
|
1314
|
+
const name = (conv.title || 'conversation').replace(/[\\/:*?"<>|]/g, '_').slice(0, 40);
|
|
1315
|
+
download(`${name}.md`, lines.join('\n'), 'text/markdown;charset=utf-8');
|
|
1316
|
+
toast('已导出 Markdown');
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
function importConvs(file) {
|
|
1320
|
+
const reader = new FileReader();
|
|
1321
|
+
reader.onload = () => {
|
|
1322
|
+
try {
|
|
1323
|
+
const data = JSON.parse(reader.result);
|
|
1324
|
+
const list = Array.isArray(data) ? data : (Array.isArray(data.conversations) ? data.conversations : null);
|
|
1325
|
+
if (!list) throw new Error('文件格式不是 Yu Harness 备份');
|
|
1326
|
+
let n = 0;
|
|
1327
|
+
list.forEach(c => {
|
|
1328
|
+
if (!c || !Array.isArray(c.history)) return;
|
|
1329
|
+
conversations.unshift({
|
|
1330
|
+
id: 'conv_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
|
|
1331
|
+
title: c.title || '导入的对话',
|
|
1332
|
+
history: c.history,
|
|
1333
|
+
traces: Array.isArray(c.traces) ? c.traces : [],
|
|
1334
|
+
workspaceName: '',
|
|
1335
|
+
updatedAt: Date.now()
|
|
1336
|
+
});
|
|
1337
|
+
n++;
|
|
1338
|
+
});
|
|
1339
|
+
saveConvs();
|
|
1340
|
+
renderConvList();
|
|
1341
|
+
if (conversations[0]) switchConversation(conversations[0].id);
|
|
1342
|
+
toast(`已导入 ${n} 个对话`);
|
|
1343
|
+
} catch (e) {
|
|
1344
|
+
toast('导入失败:' + e.message);
|
|
1345
|
+
}
|
|
1346
|
+
};
|
|
1347
|
+
reader.readAsText(file);
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/* ==================================================================
|
|
1351
|
+
* 12. UI 辅助
|
|
1352
|
+
* ================================================================== */
|
|
1353
|
+
function openModal(title, html) {
|
|
1354
|
+
$('#modalTitle').textContent = title;
|
|
1355
|
+
$('#modalBody').innerHTML = html;
|
|
1356
|
+
$('#modalMask').classList.add('show');
|
|
1357
|
+
}
|
|
1358
|
+
const closeModal = () => $('#modalMask').classList.remove('show');
|
|
1359
|
+
|
|
1360
|
+
function autoGrow() {
|
|
1361
|
+
const t = $('#input');
|
|
1362
|
+
t.style.height = 'auto';
|
|
1363
|
+
t.style.height = Math.min(t.scrollHeight, 180) + 'px';
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
function updateTokenHint() {
|
|
1367
|
+
const text = $('#input').value;
|
|
1368
|
+
const conv = getActiveConv();
|
|
1369
|
+
const msgs = conv?.history || [];
|
|
1370
|
+
const totalChars = msgs.reduce((n, m) => n + String(m.content || '').length, 0);
|
|
1371
|
+
$('#tokenHint').textContent = `${text.length} 字 · 历史 ${totalChars} 字`;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
function applyTheme() {
|
|
1375
|
+
document.documentElement.dataset.theme = cfg.theme === 'light' ? 'light' : 'dark';
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
function syncUI() {
|
|
1379
|
+
$('#baseURL').value = cfg.baseURL || '';
|
|
1380
|
+
$('#apiKey').value = cfg.apiKey || '';
|
|
1381
|
+
$('#model').value = cfg.model || '';
|
|
1382
|
+
$('#temperature').value = cfg.temperature;
|
|
1383
|
+
$('#maxSteps').value = cfg.maxSteps;
|
|
1384
|
+
$('#systemPrompt').value = cfg.systemPrompt || '';
|
|
1385
|
+
$('#streamToggle').checked = cfg.stream !== false;
|
|
1386
|
+
$('#modelBadge').textContent = cfg.model || '未配置模型';
|
|
1387
|
+
$('#modelBadge').classList.toggle('live', !!(cfg.baseURL && cfg.model));
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
function bindConfig() {
|
|
1391
|
+
['baseURL', 'apiKey', 'model'].forEach(id => {
|
|
1392
|
+
document.getElementById(id).addEventListener('input', e => {
|
|
1393
|
+
cfg[id] = e.target.value;
|
|
1394
|
+
saveCfg();
|
|
1395
|
+
$('#modelBadge').textContent = cfg.model || '未配置模型';
|
|
1396
|
+
$('#modelBadge').classList.toggle('live', !!(cfg.baseURL && cfg.model));
|
|
1397
|
+
});
|
|
1398
|
+
});
|
|
1399
|
+
['temperature', 'maxSteps'].forEach(id => {
|
|
1400
|
+
document.getElementById(id).addEventListener('input', e => {
|
|
1401
|
+
cfg[id] = Number(e.target.value);
|
|
1402
|
+
saveCfg();
|
|
1403
|
+
});
|
|
1404
|
+
});
|
|
1405
|
+
$('#systemPrompt').addEventListener('input', e => { cfg.systemPrompt = e.target.value; saveCfg(); });
|
|
1406
|
+
$('#streamToggle').addEventListener('change', e => { cfg.stream = e.target.checked; saveCfg(); });
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
/* ==================================================================
|
|
1410
|
+
* 13. 事件绑定
|
|
1411
|
+
* ================================================================== */
|
|
1412
|
+
$('#btnToggleLeft').onclick = () => $('#leftPanel').classList.toggle('collapsed');
|
|
1413
|
+
$('#btnToggleRight').onclick = () => $('#rightPanel').classList.toggle('collapsed');
|
|
1414
|
+
$('#btnNewConv').onclick = createConversation;
|
|
1415
|
+
$('#btnSelectWorkspace').onclick = selectWorkspace;
|
|
1416
|
+
$('#btnSend').onclick = send;
|
|
1417
|
+
$('#btnStop').onclick = () => {
|
|
1418
|
+
currentRunner?.cancel();
|
|
1419
|
+
$('#status').textContent = '停止中…';
|
|
1420
|
+
};
|
|
1421
|
+
$('#btnTheme').onclick = () => {
|
|
1422
|
+
cfg.theme = cfg.theme === 'light' ? 'dark' : 'light';
|
|
1423
|
+
saveCfg();
|
|
1424
|
+
applyTheme();
|
|
1425
|
+
};
|
|
1426
|
+
$('#btnExport').onclick = exportCurrent;
|
|
1427
|
+
$('#btnImport').onclick = () => $('#importFile').click();
|
|
1428
|
+
$('#importFile').onchange = (e) => {
|
|
1429
|
+
const f = e.target.files?.[0];
|
|
1430
|
+
if (f) importConvs(f);
|
|
1431
|
+
e.target.value = '';
|
|
1432
|
+
};
|
|
1433
|
+
$('#btnSettings').onclick = () => openModal('快捷键与关于', `
|
|
1434
|
+
<div class="kv"><span>发送消息</span><span><kbd>Enter</kbd></span></div>
|
|
1435
|
+
<div class="kv"><span>换行</span><span><kbd>Shift</kbd> + <kbd>Enter</kbd></span></div>
|
|
1436
|
+
<div class="kv"><span>停止生成</span><span><kbd>Esc</kbd></span></div>
|
|
1437
|
+
<div class="kv"><span>新建对话</span><span><kbd>Ctrl</kbd> + <kbd>N</kbd></span></div>
|
|
1438
|
+
<div class="kv"><span>聚焦搜索</span><span><kbd>Ctrl</kbd> + <kbd>K</kbd></span></div>
|
|
1439
|
+
<div class="kv"><span>收起左 / 右栏</span><span><kbd>Ctrl</kbd> + <kbd>B</kbd> / <kbd>Ctrl</kbd> + <kbd>J</kbd></span></div>
|
|
1440
|
+
<div class="kv"><span>对话重命名</span><span>双击左侧标题</span></div>
|
|
1441
|
+
<p class="hint" style="margin-top:14px">Yu Harness 是纯前端单页应用:会话、配置、虚拟文件都存在浏览器 localStorage 中,不上传任何服务器。真实文件读写通过 File System Access API,仅在你手动授权的文件夹内生效。</p>
|
|
1442
|
+
<p class="hint">本地文件:<code>@yumind-ai/harness</code> · 启动命令 <code>npx -y @yumind-ai/harness run web</code></p>
|
|
1443
|
+
`);
|
|
1444
|
+
$('#modalClose').onclick = closeModal;
|
|
1445
|
+
$('#modalMask').onclick = (e) => { if (e.target === $('#modalMask')) closeModal(); };
|
|
1446
|
+
|
|
1447
|
+
$('#convSearch').addEventListener('input', (e) => {
|
|
1448
|
+
convFilter = e.target.value;
|
|
1449
|
+
renderConvList();
|
|
1450
|
+
});
|
|
1451
|
+
|
|
1452
|
+
document.querySelectorAll('.tab').forEach(tab => {
|
|
1453
|
+
tab.onclick = () => {
|
|
1454
|
+
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
|
1455
|
+
document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
|
|
1456
|
+
tab.classList.add('active');
|
|
1457
|
+
$('#pane-' + tab.dataset.tab).classList.add('active');
|
|
1458
|
+
if (tab.dataset.tab === 'files') refreshVfs();
|
|
1459
|
+
};
|
|
1460
|
+
});
|
|
1461
|
+
|
|
1462
|
+
$('#btnClearTrace').onclick = () => {
|
|
1463
|
+
const conv = getActiveConv();
|
|
1464
|
+
if (!conv) return;
|
|
1465
|
+
conv.traces = [];
|
|
1466
|
+
saveConvs();
|
|
1467
|
+
renderTraces(conv);
|
|
1468
|
+
};
|
|
1469
|
+
$('#btnCopyTrace').onclick = async () => {
|
|
1470
|
+
const conv = getActiveConv();
|
|
1471
|
+
if (!conv) return;
|
|
1472
|
+
await copyText(JSON.stringify(conv.traces || [], null, 2));
|
|
1473
|
+
toast('轨迹 JSON 已复制');
|
|
1474
|
+
};
|
|
1475
|
+
$('#btnRefreshVfs').onclick = refreshVfs;
|
|
1476
|
+
$('#btnClearVfs').onclick = () => {
|
|
1477
|
+
if (!confirm('清空浏览器内的所有虚拟文件?')) return;
|
|
1478
|
+
vfsSave({});
|
|
1479
|
+
refreshVfs();
|
|
1480
|
+
toast('虚拟文件已清空');
|
|
1481
|
+
};
|
|
1482
|
+
|
|
1483
|
+
// 代码块复制(事件委托)
|
|
1484
|
+
messagesEl.addEventListener('click', async (e) => {
|
|
1485
|
+
const btn = e.target.closest('.code-copy');
|
|
1486
|
+
if (!btn) return;
|
|
1487
|
+
const code = btn.closest('.code-wrap')?.querySelector('code')?.textContent || '';
|
|
1488
|
+
await copyText(code);
|
|
1489
|
+
btn.textContent = '已复制';
|
|
1490
|
+
setTimeout(() => { btn.textContent = '复制'; }, 1400);
|
|
1491
|
+
});
|
|
1492
|
+
|
|
1493
|
+
const inputEl = $('#input');
|
|
1494
|
+
inputEl.addEventListener('input', () => { autoGrow(); updateTokenHint(); });
|
|
1495
|
+
inputEl.addEventListener('keydown', (e) => {
|
|
1496
|
+
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
|
|
1497
|
+
});
|
|
1498
|
+
|
|
1499
|
+
document.addEventListener('keydown', (e) => {
|
|
1500
|
+
if (e.key === 'Escape') {
|
|
1501
|
+
if ($('#modalMask').classList.contains('show')) { closeModal(); return; }
|
|
1502
|
+
if (busy) { currentRunner?.cancel(); $('#status').textContent = '停止中…'; }
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
if (!(e.ctrlKey || e.metaKey)) return;
|
|
1506
|
+
const k = e.key.toLowerCase();
|
|
1507
|
+
if (k === 'n') { e.preventDefault(); createConversation(); }
|
|
1508
|
+
else if (k === 'k') { e.preventDefault(); $('#convSearch').focus(); $('#convSearch').select(); }
|
|
1509
|
+
else if (k === 'b') { e.preventDefault(); $('#leftPanel').classList.toggle('collapsed'); }
|
|
1510
|
+
else if (k === 'j') { e.preventDefault(); $('#rightPanel').classList.toggle('collapsed'); }
|
|
1511
|
+
});
|
|
1512
|
+
|
|
1513
|
+
/* ==================================================================
|
|
1514
|
+
* 14. 启动
|
|
1515
|
+
* ================================================================== */
|
|
1516
|
+
applyTheme();
|
|
1517
|
+
syncUI();
|
|
1518
|
+
bindConfig();
|
|
1519
|
+
renderTools();
|
|
1520
|
+
refreshVfs();
|
|
1521
|
+
|
|
1522
|
+
if (!conversations.length) {
|
|
1523
|
+
createConversation();
|
|
1524
|
+
} else {
|
|
1525
|
+
const found = conversations.find(c => c.id === activeConvId) || conversations[0];
|
|
1526
|
+
switchConversation(found.id);
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
// 便于控制台调试
|
|
1530
|
+
window.YuHarness = { cfg, get conversations() { return conversations; }, tools, openaiChat, mdToHtml };
|
|
1531
|
+
})();
|
|
1532
|
+
</script>
|
|
1533
|
+
</body>
|
|
1534
|
+
</html>
|