@xiangyixie/dsh-superagent 0.12.0 → 0.14.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.
@@ -0,0 +1,1618 @@
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">
6
+ <title>Superagent Console</title>
7
+ <style>
8
+ :root {
9
+ color-scheme: dark;
10
+ --bg: #0b0f12;
11
+ --panel: #11171c;
12
+ --panel-2: #151d23;
13
+ --line: #233039;
14
+ --line-soft: #1a242b;
15
+ --text: #e7eef4;
16
+ --muted: #8b9aa7;
17
+ --faint: #5f707c;
18
+ --accent: #5eead4;
19
+ --accent-ink: #06231f;
20
+ --amber: #f6c177;
21
+ --amber-soft: rgba(246, 193, 119, .10);
22
+ --red: #ff7b72;
23
+ --green: #63d6a4;
24
+ --blue: #7fb4ff;
25
+ --radius: 14px;
26
+ --mono: ui-monospace, "Cascadia Code", "SFMono-Regular", Consolas, monospace;
27
+ --sans: ui-sans-serif, -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
28
+ }
29
+ * { box-sizing: border-box; }
30
+ html, body { height: 100%; }
31
+ body {
32
+ margin: 0;
33
+ background:
34
+ radial-gradient(900px 480px at 12% -10%, rgba(94, 234, 212, .07), transparent 60%),
35
+ radial-gradient(720px 420px at 100% 0%, rgba(127, 180, 255, .05), transparent 55%),
36
+ var(--bg);
37
+ color: var(--text);
38
+ font: 14px/1.55 var(--sans);
39
+ -webkit-font-smoothing: antialiased;
40
+ }
41
+ button, input, textarea { font: inherit; color: inherit; }
42
+ button { cursor: pointer; }
43
+ .mono { font-family: var(--mono); }
44
+ .muted { color: var(--muted); }
45
+
46
+ .shell { height: 100%; display: flex; flex-direction: column; }
47
+ .topbar {
48
+ flex: 0 0 58px;
49
+ display: flex; align-items: center; gap: 18px;
50
+ padding: 0 20px;
51
+ border-bottom: 1px solid var(--line-soft);
52
+ background: rgba(11, 15, 18, .82);
53
+ backdrop-filter: blur(10px);
54
+ }
55
+ .brand { display: flex; align-items: center; gap: 10px; min-width: 176px; }
56
+ .mark {
57
+ width: 30px; height: 30px; border-radius: 9px;
58
+ display: grid; place-items: center;
59
+ background: linear-gradient(145deg, var(--accent), #2aa99a);
60
+ color: var(--accent-ink);
61
+ font-weight: 800; font-size: 15px;
62
+ box-shadow: 0 0 0 1px rgba(94, 234, 212, .35), 0 8px 24px rgba(94, 234, 212, .12);
63
+ }
64
+ .brand strong { display: block; font-size: 14px; letter-spacing: .2px; }
65
+ .brand span { display: block; color: var(--faint); font-size: 11px; letter-spacing: .12em; text-transform: uppercase; }
66
+ .topbar-mid { display: flex; align-items: center; gap: 10px; min-width: 0; flex: 1; }
67
+ .badge {
68
+ display: inline-flex; align-items: center; gap: 6px;
69
+ height: 24px; padding: 0 9px; border-radius: 999px;
70
+ border: 1px solid var(--line); background: var(--panel);
71
+ color: var(--muted); font-size: 12px; white-space: nowrap;
72
+ }
73
+ .badge.chat { color: var(--green); border-color: rgba(99, 214, 164, .32); background: rgba(99, 214, 164, .08); }
74
+ .badge.off { color: var(--amber); border-color: rgba(246, 193, 119, .32); background: var(--amber-soft); }
75
+ .badge .pulse { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
76
+ .session-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
77
+ .topbar-actions { display: flex; align-items: center; gap: 12px; }
78
+ .conn { display: inline-flex; align-items: center; gap: 7px; color: var(--faint); font-size: 12px; white-space: nowrap; }
79
+ .conn i { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); }
80
+ .conn.live i { background: var(--green); box-shadow: 0 0 0 4px rgba(99, 214, 164, .12); }
81
+ .conn.warn i { background: var(--amber); }
82
+ .btn {
83
+ height: 30px; padding: 0 12px; border-radius: 8px;
84
+ border: 1px solid var(--line); background: var(--panel); color: var(--muted);
85
+ font-size: 12px;
86
+ }
87
+ .btn:hover { color: var(--text); border-color: #35464f; background: #172028; }
88
+ .btn:disabled { opacity: .45; cursor: default; }
89
+
90
+ .grid {
91
+ flex: 1; min-height: 0;
92
+ display: grid; grid-template-columns: minmax(0, 1fr) 392px;
93
+ gap: 14px; padding: 14px 18px 18px;
94
+ }
95
+ .panel {
96
+ min-height: 0; display: flex; flex-direction: column;
97
+ border: 1px solid var(--line-soft); border-radius: var(--radius);
98
+ background: linear-gradient(180deg, var(--panel), #0f1519);
99
+ overflow: hidden;
100
+ }
101
+ .chat-head {
102
+ display: flex; align-items: flex-start; justify-content: space-between; gap: 12px;
103
+ padding: 16px 20px 13px; border-bottom: 1px solid var(--line-soft);
104
+ }
105
+ .chat-head h1 { margin: 0; font-size: 15px; letter-spacing: .1px; }
106
+ .chat-head p { margin: 4px 0 0; color: var(--faint); font-size: 12px; }
107
+ .chat-head p strong { color: var(--muted); font-weight: 600; }
108
+ .typing { display: inline-flex; align-items: center; gap: 5px; color: var(--muted); font-size: 12px; }
109
+ .typing span { width: 5px; height: 5px; border-radius: 50%; background: var(--accent); animation: blink 1.2s infinite; }
110
+ .typing span:nth-child(2) { animation-delay: .18s; }
111
+ .typing span:nth-child(3) { animation-delay: .36s; }
112
+ @keyframes blink { 0%, 80%, 100% { opacity: .2; transform: translateY(0); } 40% { opacity: 1; transform: translateY(-2px); } }
113
+
114
+ .messages {
115
+ flex: 1; min-height: 0; overflow-y: auto;
116
+ padding: 20px 20px 26px; scroll-behavior: smooth;
117
+ }
118
+ .messages::-webkit-scrollbar, .run-list::-webkit-scrollbar, pre::-webkit-scrollbar { width: 10px; height: 10px; }
119
+ .messages::-webkit-scrollbar-thumb, .run-list::-webkit-scrollbar-thumb, pre::-webkit-scrollbar-thumb {
120
+ background: #26343d; border: 3px solid transparent; background-clip: padding-box; border-radius: 999px;
121
+ }
122
+ .msg { display: flex; flex-direction: column; max-width: 820px; margin: 0 0 18px; animation: rise .18s ease-out; }
123
+ @keyframes rise { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
124
+ .msg.user { margin-left: auto; align-items: flex-end; }
125
+ .msg.assistant { margin-right: auto; align-items: flex-start; }
126
+ .who { margin: 0 4px 5px; color: var(--faint); font-size: 11px; letter-spacing: .05em; }
127
+ .bubble {
128
+ position: relative; max-width: 100%;
129
+ padding: 10px 13px; border-radius: 12px;
130
+ border: 1px solid var(--line-soft); background: var(--panel-2);
131
+ white-space: pre-wrap; word-break: break-word;
132
+ }
133
+ .msg.user .bubble {
134
+ background: linear-gradient(180deg, rgba(94, 234, 212, .13), rgba(94, 234, 212, .07));
135
+ border-color: rgba(94, 234, 212, .26);
136
+ border-bottom-right-radius: 4px;
137
+ }
138
+ .msg.assistant .bubble { border-bottom-left-radius: 4px; }
139
+ .msg.pending .bubble { opacity: .72; }
140
+ .msg.failed .bubble { border-color: rgba(255, 123, 114, .48); }
141
+ .msg .text { min-height: 1em; }
142
+ .msg .text .para { white-space: pre-wrap; }
143
+ .msg .text pre {
144
+ margin: 8px 0; padding: 10px 11px; border-radius: 8px;
145
+ border: 1px solid var(--line); background: #0a0f12;
146
+ overflow: auto; font: 12px/1.6 var(--mono); white-space: pre;
147
+ }
148
+ .msg .text .cursor {
149
+ display: inline-block; width: 7px; height: 15px; margin-left: 2px;
150
+ background: var(--accent); vertical-align: -2px; animation: caret 1s steps(2) infinite;
151
+ }
152
+ @keyframes caret { 50% { opacity: 0; } }
153
+ .msg .meta { margin: 5px 4px 0; color: var(--faint); font-size: 11px; }
154
+ .msg .meta .failed { color: var(--red); }
155
+ .reasoning { margin-top: 8px; border-top: 1px dashed var(--line); padding-top: 7px; }
156
+ .reasoning summary { color: var(--faint); font-size: 11px; cursor: pointer; }
157
+ .reasoning pre { margin: 6px 0 0; color: var(--muted); font: 12px/1.6 var(--mono); white-space: pre-wrap; }
158
+ .tools { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 9px; }
159
+ .tool {
160
+ display: inline-flex; align-items: center; gap: 6px;
161
+ padding: 3px 8px; border-radius: 999px;
162
+ border: 1px solid var(--line); background: #0e1418;
163
+ color: var(--muted); font: 11px/1.5 var(--mono);
164
+ }
165
+ .tool .tdot { width: 6px; height: 6px; border-radius: 50%; background: var(--blue); }
166
+ .tool.ok .tdot { background: var(--green); }
167
+ .tool.err .tdot { background: var(--red); }
168
+ .tool.running .tdot { background: var(--amber); animation: blink 1.1s infinite; }
169
+ .tool details { display: inline; }
170
+ .tool summary { color: var(--faint); cursor: pointer; list-style: none; }
171
+ .tool summary::-webkit-details-marker { display: none; }
172
+ .tool pre { max-width: 520px; max-height: 180px; overflow: auto; margin: 6px 0 0; font: 11px/1.5 var(--mono); white-space: pre-wrap; }
173
+ .tool .targs {
174
+ max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
175
+ color: var(--faint); font-size: 10.5px;
176
+ }
177
+ .tool.err { border-color: #5a2c2c; }
178
+ .tool .err-mark { color: var(--red); }
179
+
180
+ .empty { max-width: 560px; margin: 7vh auto 0; text-align: center; }
181
+ .empty .orb {
182
+ width: 58px; height: 58px; margin: 0 auto 18px; border-radius: 18px;
183
+ display: grid; place-items: center;
184
+ background: linear-gradient(145deg, rgba(94, 234, 212, .22), rgba(47, 126, 115, .18));
185
+ border: 1px solid rgba(94, 234, 212, .3);
186
+ color: var(--accent); font-size: 24px; font-weight: 800;
187
+ box-shadow: 0 18px 50px rgba(94, 234, 212, .08);
188
+ }
189
+ .empty h1 { margin: 0 0 8px; font-size: 23px; letter-spacing: -.02em; }
190
+ .empty p { margin: 0 auto 18px; max-width: 460px; color: var(--muted); }
191
+ .examples { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }
192
+ .examples button {
193
+ padding: 7px 11px; border-radius: 999px;
194
+ border: 1px solid var(--line); background: var(--panel); color: var(--muted);
195
+ font-size: 12px;
196
+ }
197
+ .examples button:hover { color: var(--text); border-color: rgba(94, 234, 212, .35); }
198
+ .empty.unavailable .orb { background: var(--amber-soft); border-color: rgba(246, 193, 119, .35); color: var(--amber); }
199
+ .empty.unavailable h1 { font-size: 20px; }
200
+ .empty .reason {
201
+ margin-top: 12px; padding: 10px 12px; border-radius: 10px;
202
+ border: 1px solid rgba(246, 193, 119, .28); background: var(--amber-soft);
203
+ color: #e8c690; font-size: 12px; text-align: left; white-space: pre-wrap;
204
+ }
205
+
206
+ .composer { padding: 12px 14px 14px; border-top: 1px solid var(--line-soft); background: #0e1418; }
207
+ .composer-box {
208
+ border: 1px solid var(--line); border-radius: 12px; background: #0a1014;
209
+ transition: border-color .15s, box-shadow .15s;
210
+ }
211
+ .composer-box:focus-within { border-color: rgba(94, 234, 212, .42); box-shadow: 0 0 0 3px rgba(94, 234, 212, .07); }
212
+ .composer textarea {
213
+ display: block; width: 100%; min-height: 46px; max-height: 180px;
214
+ padding: 12px 13px 4px; border: 0; outline: 0; resize: none;
215
+ background: transparent; color: var(--text);
216
+ }
217
+ .composer textarea::placeholder { color: var(--faint); }
218
+ .composer-bar { display: flex; align-items: center; gap: 10px; padding: 4px 8px 8px 10px; }
219
+ .segmented { display: inline-flex; padding: 2px; border-radius: 8px; background: #111a20; border: 1px solid var(--line-soft); }
220
+ .segmented button {
221
+ height: 24px; padding: 0 8px; border: 0; border-radius: 6px;
222
+ background: transparent; color: var(--faint); font-size: 11px;
223
+ }
224
+ .segmented button.active { background: #1d2a31; color: var(--text); }
225
+ .hint { flex: 1; color: var(--faint); font-size: 11px; text-align: right; }
226
+ .send {
227
+ width: 32px; height: 32px; border-radius: 9px; border: 1px solid rgba(94, 234, 212, .4);
228
+ background: linear-gradient(145deg, var(--accent), #35c7b5); color: var(--accent-ink);
229
+ font-size: 17px; font-weight: 800; line-height: 1;
230
+ }
231
+ .send:disabled { opacity: .35; cursor: default; }
232
+ .composer.note { color: var(--faint); font-size: 12px; text-align: center; padding: 18px; }
233
+
234
+ .runs-head {
235
+ display: flex; align-items: flex-start; justify-content: space-between; gap: 10px;
236
+ padding: 16px 17px 13px; border-bottom: 1px solid var(--line-soft);
237
+ }
238
+ .runs-head h2 { margin: 0; font-size: 14px; }
239
+ .runs-head p { margin: 3px 0 0; color: var(--faint); font-size: 11px; }
240
+ .count {
241
+ min-width: 24px; height: 22px; padding: 0 7px; border-radius: 999px;
242
+ display: inline-grid; place-items: center;
243
+ background: #172129; border: 1px solid var(--line); color: var(--muted);
244
+ font: 11px var(--mono);
245
+ }
246
+ .tools:empty { display: none; }
247
+ .tools-panel { border-bottom: 1px solid var(--line-soft); padding: 10px 14px; }
248
+ .tools-panel summary {
249
+ display: flex; align-items: center; gap: 8px; cursor: pointer;
250
+ color: var(--muted); font-size: 12px; list-style: none;
251
+ }
252
+ .tools-panel summary::-webkit-details-marker { display: none; }
253
+ .tools-panel summary::before { content: "▸"; color: var(--faint); font-size: 10px; }
254
+ .tools-panel[open] summary::before { content: "▾"; }
255
+ .tools-panel .count { margin-left: auto; }
256
+ .tools-note { margin: 7px 0 0; color: var(--faint); font-size: 11px; line-height: 1.6; }
257
+ .tool-list { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 7px; max-height: 132px; overflow-y: auto; }
258
+ .tool-name {
259
+ padding: 2px 6px; border-radius: 6px; border: 1px solid var(--line);
260
+ background: #121a20; color: var(--muted); font: 10.5px var(--mono);
261
+ }
262
+ .tool-name.on { border-color: #2c5a48; color: #9fe0c2; }
263
+ .run-list { flex: 1; min-height: 0; overflow-y: auto; padding: 12px; }
264
+ .run-empty { padding: 26px 18px; color: var(--faint); text-align: center; font-size: 12px; line-height: 1.7; }
265
+ .run-empty .line { display: block; width: 30px; height: 1px; margin: 12px auto; background: var(--line); }
266
+ .run {
267
+ position: relative; margin-bottom: 10px; padding: 12px;
268
+ border: 1px solid var(--line-soft); border-radius: 11px;
269
+ background: #10161b;
270
+ }
271
+ .run::before {
272
+ content: ""; position: absolute; left: 0; top: 11px; bottom: 11px; width: 2px; border-radius: 2px;
273
+ background: var(--line);
274
+ }
275
+ .run.running::before { background: var(--amber); }
276
+ .run.completed::before { background: var(--green); }
277
+ .run.failed::before, .run.interrupted::before { background: var(--red); }
278
+ .run-top { display: flex; align-items: flex-start; gap: 8px; }
279
+ .run-title { flex: 1; min-width: 0; }
280
+ .run-title h3 { margin: 0; font-size: 12.5px; font-weight: 600; line-height: 1.45; word-break: break-word; }
281
+ .run-title p { margin: 3px 0 0; color: var(--faint); font: 10.5px var(--mono); }
282
+ .status-pill {
283
+ flex: none; padding: 2px 7px; border-radius: 999px;
284
+ border: 1px solid var(--line); color: var(--muted); font-size: 10.5px; white-space: nowrap;
285
+ }
286
+ .status-pill.running { color: var(--amber); border-color: rgba(246, 193, 119, .32); background: var(--amber-soft); }
287
+ .status-pill.completed { color: var(--green); border-color: rgba(99, 214, 164, .32); background: rgba(99, 214, 164, .07); }
288
+ .status-pill.failed, .status-pill.interrupted { color: var(--red); border-color: rgba(255, 123, 114, .32); background: rgba(255, 123, 114, .07); }
289
+ .run-meta { display: flex; flex-wrap: wrap; gap: 10px; margin: 9px 0 0; color: var(--faint); font-size: 11px; }
290
+ .run-meta b { color: var(--muted); font-weight: 600; }
291
+ .progress { height: 3px; margin: 9px 0 0; border-radius: 999px; background: #1b252c; overflow: hidden; }
292
+ .progress i { display: block; height: 100%; width: 0; background: linear-gradient(90deg, #3dc6b5, var(--accent)); transition: width .3s; }
293
+ .subtasks { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 9px; }
294
+ .subtask {
295
+ max-width: 100%; padding: 2px 7px; border-radius: 6px;
296
+ border: 1px solid var(--line-soft); color: var(--faint); font-size: 10.5px;
297
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
298
+ }
299
+ .subtask.completed { color: var(--green); border-color: rgba(99, 214, 164, .22); }
300
+ .subtask.running { color: var(--amber); border-color: rgba(246, 193, 119, .22); }
301
+ .subtask.failed { color: var(--red); border-color: rgba(255, 123, 114, .22); }
302
+ .attention-card {
303
+ margin-top: 10px; padding: 10px; border-radius: 9px;
304
+ border: 1px solid rgba(246, 193, 119, .36); background: var(--amber-soft);
305
+ }
306
+ .attention-card .kicker {
307
+ color: var(--amber); font: 10px var(--mono); letter-spacing: .08em; text-transform: uppercase;
308
+ }
309
+ .attention-card p { margin: 5px 0 0; color: #edd7b2; font-size: 12px; line-height: 1.55; white-space: pre-wrap; }
310
+ .attention-card .reason { color: #b9a789; font-size: 11px; }
311
+ .options { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
312
+ .options button {
313
+ padding: 4px 9px; border-radius: 7px;
314
+ border: 1px solid rgba(246, 193, 119, .38); background: rgba(246, 193, 119, .08);
315
+ color: #f3d8ac; font-size: 11px;
316
+ }
317
+ .options button:hover { background: rgba(246, 193, 119, .18); }
318
+ .options button:disabled { opacity: .45; }
319
+ .free { display: flex; gap: 6px; margin-top: 7px; }
320
+ .free input {
321
+ flex: 1; min-width: 0; height: 29px; padding: 0 8px;
322
+ border: 1px solid rgba(246, 193, 119, .28); border-radius: 7px;
323
+ background: rgba(10, 15, 18, .65); color: var(--text); font-size: 11.5px; outline: 0;
324
+ }
325
+ .free input:focus { border-color: rgba(246, 193, 119, .55); }
326
+ .free button {
327
+ height: 29px; padding: 0 9px; border-radius: 7px; border: 1px solid rgba(246, 193, 119, .4);
328
+ background: rgba(246, 193, 119, .14); color: #f3d8ac; font-size: 11px;
329
+ }
330
+ .report { margin-top: 9px; border-top: 1px dashed var(--line-soft); padding-top: 8px; }
331
+ .report summary { color: var(--muted); font-size: 11px; cursor: pointer; }
332
+ .report pre {
333
+ max-height: 280px; overflow: auto; margin: 7px 0 0; padding: 9px;
334
+ border-radius: 8px; border: 1px solid var(--line-soft); background: #0a0f12;
335
+ color: var(--muted); font: 11px/1.6 var(--mono); white-space: pre-wrap; word-break: break-word;
336
+ }
337
+ .run-actions { display: flex; gap: 8px; margin-top: 8px; }
338
+ .run-actions button {
339
+ height: 25px; padding: 0 8px; border-radius: 6px;
340
+ border: 1px solid var(--line); background: transparent; color: var(--faint); font-size: 10.5px;
341
+ }
342
+ .run-actions button:hover { color: var(--text); border-color: #35464f; }
343
+
344
+ .toasts { position: fixed; left: 50%; bottom: 22px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 8px; z-index: 30; pointer-events: none; }
345
+ .toast {
346
+ max-width: 520px; padding: 9px 13px; border-radius: 9px;
347
+ border: 1px solid var(--line); background: #182229; color: var(--text);
348
+ box-shadow: 0 12px 36px rgba(0, 0, 0, .35); font-size: 12px;
349
+ animation: rise .16s ease-out;
350
+ }
351
+ .toast.err { border-color: rgba(255, 123, 114, .4); color: #ffc0bb; }
352
+ .toast.ok { border-color: rgba(99, 214, 164, .35); }
353
+
354
+ .gate {
355
+ position: fixed; inset: 0; z-index: 40; display: grid; place-items: center;
356
+ background: rgba(7, 10, 12, .86); backdrop-filter: blur(8px); padding: 20px;
357
+ }
358
+ .gate[hidden] { display: none; }
359
+ .gate-card {
360
+ width: min(420px, 100%); padding: 24px; border-radius: 16px;
361
+ border: 1px solid var(--line); background: var(--panel);
362
+ box-shadow: 0 30px 90px rgba(0, 0, 0, .5);
363
+ }
364
+ .gate-card .mark { margin-bottom: 14px; }
365
+ .gate-card h1 { margin: 0 0 6px; font-size: 18px; }
366
+ .gate-card p { margin: 0 0 16px; color: var(--muted); font-size: 12px; line-height: 1.7; }
367
+ .gate-card label { display: block; color: var(--faint); font-size: 11px; }
368
+ .gate-card input {
369
+ display: block; width: 100%; height: 38px; margin-top: 6px; padding: 0 10px;
370
+ border: 1px solid var(--line); border-radius: 8px; background: #0a1014; color: var(--text); outline: 0;
371
+ }
372
+ .gate-card input:focus { border-color: rgba(94, 234, 212, .48); }
373
+ .gate-card button {
374
+ width: 100%; height: 38px; margin-top: 12px; border-radius: 8px; border: 1px solid rgba(94, 234, 212, .4);
375
+ background: linear-gradient(145deg, var(--accent), #35c7b5); color: var(--accent-ink); font-weight: 700;
376
+ }
377
+ .gate-card .error { margin: 10px 0 0; color: var(--red); font-size: 12px; min-height: 1em; }
378
+
379
+ dialog {
380
+ width: min(860px, calc(100vw - 40px)); max-height: calc(100vh - 60px);
381
+ padding: 0; border: 1px solid var(--line); border-radius: 14px;
382
+ background: var(--panel); color: var(--text);
383
+ box-shadow: 0 40px 120px rgba(0, 0, 0, .6);
384
+ }
385
+ dialog::backdrop { background: rgba(5, 8, 10, .72); backdrop-filter: blur(4px); }
386
+ .dialog-head { display: flex; align-items: flex-start; gap: 12px; padding: 16px 18px; border-bottom: 1px solid var(--line-soft); }
387
+ .dialog-head h2 { flex: 1; margin: 0; font-size: 14px; line-height: 1.5; }
388
+ .dialog-head button { border: 0; background: transparent; color: var(--muted); font-size: 18px; line-height: 1; }
389
+ .dialog-body { padding: 16px 18px 20px; overflow: auto; max-height: calc(100vh - 180px); }
390
+ .dialog-meta { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 12px; color: var(--faint); font-size: 11px; }
391
+ .dialog-body pre {
392
+ margin: 0; padding: 13px; border-radius: 9px; border: 1px solid var(--line-soft);
393
+ background: #0a0f12; font: 12px/1.65 var(--mono); white-space: pre-wrap; word-break: break-word;
394
+ }
395
+
396
+ @media (max-width: 980px) {
397
+ .grid { grid-template-columns: 1fr; grid-template-rows: minmax(0, 1fr) minmax(240px, 44vh); }
398
+ .topbar-mid .session-label { display: none; }
399
+ }
400
+ @media (max-width: 620px) {
401
+ .grid { padding: 10px; gap: 10px; }
402
+ .topbar { padding: 0 12px; }
403
+ .topbar-actions .conn { display: none; }
404
+ .brand { min-width: 0; }
405
+ .brand div span { display: none; }
406
+ .hint { display: none; }
407
+ .messages { padding: 16px 14px 22px; }
408
+ }
409
+ </style>
410
+ </head>
411
+ <body>
412
+ <div class="shell">
413
+ <header class="topbar">
414
+ <div class="brand">
415
+ <div class="mark">S</div>
416
+ <div><strong>Superagent</strong><span>Console</span></div>
417
+ </div>
418
+ <div class="topbar-mid">
419
+ <span id="modeBadge" class="badge"><span class="pulse"></span><span id="modeText">连接中</span></span>
420
+ <span id="sessionLabel" class="session-label mono" title="Host Session id">no session</span>
421
+ </div>
422
+ <div class="topbar-actions">
423
+ <span id="conn" class="conn"><i></i><span id="connText">连接中</span></span>
424
+ <button id="newChat" class="btn" type="button" disabled>新对话</button>
425
+ </div>
426
+ </header>
427
+
428
+ <main class="grid">
429
+ <section class="panel" aria-label="对话">
430
+ <div class="chat-head">
431
+ <div>
432
+ <h1>对话</h1>
433
+ <p>真实 Host Session · <strong>这是对话会话,不是 run 指挥台</strong></p>
434
+ </div>
435
+ <div id="typing" class="typing" hidden><span></span><span></span><span></span><em id="typingText" style="font-style:normal;margin-left:3px">运行中</em></div>
436
+ </div>
437
+ <div id="messages" class="messages" aria-live="polite"></div>
438
+ <form id="composer" class="composer" autocomplete="off">
439
+ <div class="composer-box">
440
+ <textarea id="input" rows="1" placeholder="和 Superagent 说话,例如:先查清登录失败的根因,再把它拆成 run 修掉" disabled></textarea>
441
+ <div class="composer-bar">
442
+ <div class="segmented" role="group" aria-label="发送方式">
443
+ <button type="button" data-mode="queue" class="active">排队</button>
444
+ <button type="button" data-mode="steer">插话</button>
445
+ </div>
446
+ <span class="hint">Enter 发送 · Shift+Enter 换行</span>
447
+ <button id="send" class="send" type="submit" aria-label="发送" disabled>↑</button>
448
+ </div>
449
+ </div>
450
+ </form>
451
+ </section>
452
+
453
+ <aside class="panel" aria-label="派生的 runs">
454
+ <div class="runs-head">
455
+ <div><h2>派生的 runs</h2><p>这个对话启动的子任务</p></div>
456
+ <span id="runCount" class="count">0</span>
457
+ </div>
458
+ <details id="toolsPanel" class="tools-panel" open>
459
+ <summary><span>这个会话挂载的工具</span><span id="toolCount" class="count">—</span></summary>
460
+ <p id="toolNote" class="tools-note">加载中…</p>
461
+ <div id="toolList" class="tool-list"></div>
462
+ </details>
463
+ <div id="runs" class="run-list"></div>
464
+ </aside>
465
+ </main>
466
+ </div>
467
+
468
+ <div id="gate" class="gate" hidden>
469
+ <form id="gateForm" class="gate-card">
470
+ <div class="mark">S</div>
471
+ <h1>连接 Superagent Console</h1>
472
+ <p>从宿主状态目录的 <code>console.json</code> 读取一次性 token。控制台只监听 127.0.0.1,token 每次启动都会重新生成。</p>
473
+ <label for="tokenInput">访问令牌</label>
474
+ <input id="tokenInput" type="password" autocomplete="off" spellcheck="false" placeholder="粘贴 token">
475
+ <button type="submit">连接</button>
476
+ <p id="gateError" class="error"></p>
477
+ </form>
478
+ </div>
479
+
480
+ <div id="toasts" class="toasts" aria-live="polite"></div>
481
+
482
+ <dialog id="reportDialog">
483
+ <div class="dialog-head">
484
+ <h2 id="dialogTitle">报告</h2>
485
+ <button id="dialogClose" type="button" aria-label="关闭">×</button>
486
+ </div>
487
+ <div class="dialog-body">
488
+ <div id="dialogMeta" class="dialog-meta"></div>
489
+ <pre id="dialogReport"></pre>
490
+ </div>
491
+ </dialog>
492
+
493
+ <script>
494
+ (() => {
495
+ 'use strict'
496
+
497
+ const TOKEN_KEY = 'dsh-superagent-console-token'
498
+ const $ = id => document.getElementById(id)
499
+ const messagesEl = $('messages')
500
+ const runsEl = $('runs')
501
+ const inputEl = $('input')
502
+ const sendEl = $('send')
503
+ const composerEl = $('composer')
504
+ const typingEl = $('typing')
505
+ const typingTextEl = $('typingText')
506
+ const modeBadgeEl = $('modeBadge')
507
+ const modeTextEl = $('modeText')
508
+ const sessionLabelEl = $('sessionLabel')
509
+ const connEl = $('conn')
510
+ const connTextEl = $('connText')
511
+ const newChatEl = $('newChat')
512
+ const runCountEl = $('runCount')
513
+ const gateEl = $('gate')
514
+ const gateFormEl = $('gateForm')
515
+ const gateErrorEl = $('gateError')
516
+ const tokenInputEl = $('tokenInput')
517
+ const toastsEl = $('toasts')
518
+ const reportDialogEl = $('reportDialog')
519
+ const dialogTitleEl = $('dialogTitle')
520
+ const dialogMetaEl = $('dialogMeta')
521
+ const dialogReportEl = $('dialogReport')
522
+
523
+ const STATE = {
524
+ token: '',
525
+ mode: 'loading',
526
+ capabilities: null,
527
+ sessionId: null,
528
+ runs: [],
529
+ messages: [],
530
+ running: false,
531
+ pendingInput: [],
532
+ conn: 'connecting',
533
+ streamAbort: null,
534
+ reconnectTimer: null,
535
+ sending: false,
536
+ sendMode: 'queue',
537
+ messageSeq: 0,
538
+ currentAssistant: null,
539
+ toolCalls: new Map(),
540
+ drafts: new Map(),
541
+ busyAnswers: new Set(),
542
+ autoScroll: true,
543
+ booted: false,
544
+ }
545
+
546
+ function el(tag, className, text) {
547
+ const node = document.createElement(tag)
548
+ if (className) node.className = className
549
+ if (text !== undefined && text !== null) node.textContent = text
550
+ return node
551
+ }
552
+
553
+ function messageOf(error) {
554
+ if (!error) return '未知错误'
555
+ return error.message || String(error)
556
+ }
557
+
558
+ function shortId(id) {
559
+ if (typeof id !== 'string') return ''
560
+ return id.length > 18 ? `${id.slice(0, 8)}…${id.slice(-6)}` : id
561
+ }
562
+
563
+ function timeLabel(value) {
564
+ const ms = typeof value === 'number' ? value : Date.parse(value)
565
+ if (!Number.isFinite(ms)) return ''
566
+ try {
567
+ return new Date(ms).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
568
+ } catch {
569
+ return ''
570
+ }
571
+ }
572
+
573
+ function formatTokens(value) {
574
+ const n = Number(value)
575
+ if (!Number.isFinite(n) || n <= 0) return '—'
576
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
577
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`
578
+ return String(Math.round(n))
579
+ }
580
+
581
+ function statusText(status) {
582
+ const map = {
583
+ queued: '排队中', planning: '规划中', running: '运行中', aggregating: '汇总中',
584
+ completed: '已完成', failed: '失败', cancelled: '已取消', interrupted: '已中断',
585
+ blocked: '已阻塞',
586
+ }
587
+ return map[status] || status || '未知'
588
+ }
589
+
590
+ function statusClass(status) {
591
+ if (status === 'completed') return 'completed'
592
+ if (status === 'failed' || status === 'cancelled' || status === 'interrupted' || status === 'blocked') return 'failed'
593
+ if (status === 'queued') return 'queued'
594
+ return 'running'
595
+ }
596
+
597
+ function contentText(content) {
598
+ if (typeof content === 'string') return content
599
+ if (!Array.isArray(content)) return ''
600
+ return content
601
+ .filter(part => part && part.type === 'text' && typeof part.text === 'string')
602
+ .map(part => part.text)
603
+ .join('')
604
+ }
605
+
606
+ function pushToast(text, kind = '') {
607
+ const node = el('div', `toast ${kind}`.trim(), text)
608
+ toastsEl.append(node)
609
+ setTimeout(() => {
610
+ node.style.opacity = '0'
611
+ node.style.transition = 'opacity .18s'
612
+ setTimeout(() => node.remove(), 220)
613
+ }, 3600)
614
+ }
615
+
616
+ function setConn(state, text) {
617
+ STATE.conn = state
618
+ connEl.className = `conn ${state === 'live' ? 'live' : state === 'warn' ? 'warn' : ''}`.trim()
619
+ connTextEl.textContent = text
620
+ }
621
+
622
+ function setMode(mode, capabilities) {
623
+ STATE.mode = mode
624
+ STATE.capabilities = capabilities || STATE.capabilities
625
+ const chat = mode === 'chat'
626
+ modeBadgeEl.className = `badge ${chat ? 'chat' : 'off'}`
627
+ modeTextEl.textContent = chat ? '对话会话' : mode === 'loading' ? '连接中' : '未连接'
628
+ newChatEl.disabled = !chat
629
+ inputEl.disabled = !chat
630
+ updateSend()
631
+ }
632
+
633
+ function updateSend() {
634
+ const hasText = inputEl.value.trim().length > 0
635
+ sendEl.disabled = STATE.mode !== 'chat' || !hasText || STATE.sending
636
+ }
637
+
638
+ function setTyping(running, label) {
639
+ STATE.running = running
640
+ typingEl.hidden = !running
641
+ if (label) typingTextEl.textContent = label
642
+ }
643
+
644
+ function setSession(sessionId) {
645
+ STATE.sessionId = sessionId
646
+ sessionLabelEl.textContent = sessionId ? `session ${shortId(sessionId)}` : 'no session'
647
+ sessionLabelEl.title = sessionId || 'Host Session id'
648
+ }
649
+
650
+ function scrollToEnd() {
651
+ if (!STATE.autoScroll) return
652
+ messagesEl.scrollTop = messagesEl.scrollHeight
653
+ }
654
+
655
+ function renderText(container, text, streaming) {
656
+ container.textContent = ''
657
+ const value = typeof text === 'string' ? text : ''
658
+ const parts = value.split(/```/)
659
+ parts.forEach((part, index) => {
660
+ if (index % 2 === 1) {
661
+ const pre = el('pre')
662
+ const code = el('code')
663
+ code.textContent = part.replace(/^[a-zA-Z0-9_+-]*\n/, '')
664
+ pre.append(code)
665
+ container.append(pre)
666
+ } else if (part) {
667
+ const block = el('div', 'para')
668
+ block.textContent = part
669
+ container.append(block)
670
+ }
671
+ })
672
+ if (streaming) container.append(el('span', 'cursor'))
673
+ }
674
+
675
+ function messageElement(message) {
676
+ const article = el('article', `msg ${message.role}${message.pending ? ' pending' : ''}${message.failed ? ' failed' : ''}`)
677
+ article.dataset.id = message.id
678
+ const who = el('div', 'who', message.role === 'user' ? '你' : 'Superagent')
679
+ const bubble = el('div', 'bubble')
680
+ const text = el('div', 'text')
681
+ renderText(text, message.text, message.streaming)
682
+ bubble.append(text)
683
+
684
+ if (message.reasoning) {
685
+ const details = el('details', 'reasoning')
686
+ details.append(el('summary', '', '思考过程'))
687
+ const pre = el('pre', '', message.reasoning)
688
+ details.append(pre)
689
+ bubble.append(details)
690
+ }
691
+
692
+ // Always attach the container: tool calls usually arrive after the message
693
+ // element is built, and a detached container would swallow every chip.
694
+ const tools = el('div', 'tools')
695
+ if (Array.isArray(message.tools) && message.tools.length > 0) {
696
+ for (const tool of message.tools) {
697
+ tools.append(toolChip(tool))
698
+ }
699
+ }
700
+ bubble.append(tools)
701
+
702
+ const meta = el('div', 'meta')
703
+ const when = message.at ? timeLabel(message.at) : ''
704
+ meta.textContent = when
705
+ if (message.pending) meta.append(el('span', '', ' · 发送中'))
706
+ if (message.failed) meta.append(el('span', 'failed', ' · 发送失败'))
707
+ if (message.interrupted) meta.append(el('span', '', ' · 已中断'))
708
+
709
+ article.append(who, bubble, meta)
710
+ message.el = article
711
+ message.textEl = text
712
+ message.bubbleEl = bubble
713
+ message.toolsEl = tools
714
+ message.metaEl = meta
715
+ return article
716
+ }
717
+
718
+ function summarizeArgs(value) {
719
+ if (value === undefined || value === null) return ''
720
+ let text
721
+ if (typeof value === 'string') text = value
722
+ else {
723
+ try { text = JSON.stringify(value) } catch { text = String(value) }
724
+ }
725
+ return text.replace(/\s+/g, ' ').trim().slice(0, 110)
726
+ }
727
+
728
+ function toolChip(tool) {
729
+ const chip = el('span', `tool ${tool.status || 'running'}`.trim())
730
+ chip.dataset.callId = tool.callId || ''
731
+ chip.append(el('span', 'tdot'))
732
+ chip.append(el('span', '', tool.name || 'tool'))
733
+ const args = summarizeArgs(tool.arguments)
734
+ if (args) {
735
+ const code = el('code', 'targs', args)
736
+ code.title = typeof tool.arguments === 'string' ? tool.arguments.slice(0, 2000) : args
737
+ chip.append(code)
738
+ }
739
+ const failed = tool.status === 'err'
740
+ if (tool.done) {
741
+ const details = el('details')
742
+ details.append(el('summary', failed ? 'err-mark' : '', failed ? '失败原因' : '结果'))
743
+ details.append(el('pre', '', tool.result || (failed ? '工具没有返回错误文本。' : '')))
744
+ chip.append(details)
745
+ }
746
+ return chip
747
+ }
748
+
749
+ function refreshMessage(message) {
750
+ if (!message || !message.el) return
751
+ message.el.classList.toggle('pending', Boolean(message.pending))
752
+ message.el.classList.toggle('failed', Boolean(message.failed))
753
+ renderText(message.textEl, message.text, message.streaming)
754
+ if (message.metaEl) {
755
+ message.metaEl.textContent = message.at ? timeLabel(message.at) : ''
756
+ if (message.pending) message.metaEl.append(el('span', '', ' · 发送中'))
757
+ if (message.failed) message.metaEl.append(el('span', 'failed', ' · 发送失败'))
758
+ if (message.interrupted) message.metaEl.append(el('span', '', ' · 已中断'))
759
+ }
760
+ }
761
+
762
+ function addMessage(role, text, options = {}) {
763
+ const message = {
764
+ id: options.id || `m${++STATE.messageSeq}`,
765
+ role,
766
+ text: text || '',
767
+ reasoning: options.reasoning || '',
768
+ streaming: options.streaming === true,
769
+ pending: options.pending === true,
770
+ failed: false,
771
+ interrupted: false,
772
+ at: options.at || Date.now(),
773
+ tools: [],
774
+ }
775
+ STATE.messages.push(message)
776
+ messagesEl.append(messageElement(message))
777
+ if (role === 'assistant') STATE.currentAssistant = message
778
+ scrollToEnd()
779
+ return message
780
+ }
781
+
782
+ function clearMessages() {
783
+ STATE.messages = []
784
+ STATE.currentAssistant = null
785
+ STATE.toolCalls.clear()
786
+ messagesEl.textContent = ''
787
+ }
788
+
789
+ function renderEmpty() {
790
+ if (STATE.messages.length > 0) return
791
+ const wrap = el('div', 'empty')
792
+ wrap.id = 'empty'
793
+ if (STATE.mode !== 'chat') {
794
+ wrap.classList.add('unavailable')
795
+ wrap.append(el('div', 'orb', '!'))
796
+ wrap.append(el('h1', '', '对话不可用'))
797
+ wrap.append(el('p', '', '这个宿主没有提供可对话的 Session。控制台不会画一个假聊天框。'))
798
+ if (STATE.capabilities?.reason) wrap.append(el('div', 'reason', STATE.capabilities.reason))
799
+ messagesEl.append(wrap)
800
+ return
801
+ }
802
+ wrap.append(el('div', 'orb', 'S'))
803
+ wrap.append(el('h1', '', '今天想推进什么?'))
804
+ wrap.append(el('p', '', '这是一个真实的 Host Session,可以直接说话、追问。让它把工作拆成 run 后,右侧会实时出现子任务、成本和需要你决定的问题。'))
805
+ const examples = el('div', 'examples')
806
+ const samples = [
807
+ '先查清登录失败的根因,再拆成 run 修掉',
808
+ '把这次重构拆成并行子任务,最后汇总',
809
+ '跑一个 run 检查最近的改动有没有回归',
810
+ ]
811
+ for (const sample of samples) {
812
+ const button = el('button', '', sample)
813
+ button.type = 'button'
814
+ button.addEventListener('click', () => {
815
+ inputEl.value = sample
816
+ autoGrow()
817
+ updateSend()
818
+ inputEl.focus()
819
+ })
820
+ examples.append(button)
821
+ }
822
+ wrap.append(examples)
823
+ messagesEl.append(wrap)
824
+ }
825
+
826
+ function removeEmpty() {
827
+ const node = $('empty')
828
+ if (node) node.remove()
829
+ }
830
+
831
+ function autoGrow() {
832
+ inputEl.style.height = 'auto'
833
+ inputEl.style.height = `${Math.min(180, Math.max(46, inputEl.scrollHeight))}px`
834
+ }
835
+
836
+ // ---------- rendering runs ----------
837
+
838
+ function draftKey(runId, attentionId) {
839
+ return `${runId}::${attentionId || 'single'}`
840
+ }
841
+
842
+ function renderRuns() {
843
+ const active = document.activeElement
844
+ const activeKey = active && active.dataset ? active.dataset.draftKey : null
845
+ const activeValue = activeKey ? active.value : null
846
+ const activeStart = activeKey && typeof active.selectionStart === 'number' ? active.selectionStart : null
847
+
848
+ runsEl.textContent = ''
849
+ runCountEl.textContent = String(STATE.runs.length)
850
+ if (STATE.runs.length === 0) {
851
+ const empty = el('div', 'run-empty')
852
+ empty.append(el('div', '', '还没有 run。'))
853
+ empty.append(el('span', 'line'))
854
+ empty.append(el('div', '', '让它把工作拆出去,例如:帮我把登录失败的根因查清楚并修复。'))
855
+ runsEl.append(empty)
856
+ return
857
+ }
858
+
859
+ for (const run of STATE.runs) {
860
+ runsEl.append(runElement(run))
861
+ }
862
+
863
+ if (activeKey) {
864
+ const next = runsEl.querySelector(`[data-draft-key="${cssEscape(activeKey)}"]`)
865
+ if (next) {
866
+ next.focus()
867
+ if (activeValue !== null) next.value = activeValue
868
+ if (activeStart !== null) {
869
+ try { next.setSelectionRange(activeStart, activeStart) } catch {}
870
+ }
871
+ }
872
+ }
873
+ }
874
+
875
+ function cssEscape(value) {
876
+ if (window.CSS && typeof window.CSS.escape === 'function') return window.CSS.escape(value)
877
+ return String(value).replace(/["\\]/g, '\\$&')
878
+ }
879
+
880
+ function runElement(run) {
881
+ const card = el('article', `run ${statusClass(run.status)}`)
882
+ card.dataset.runId = run.id
883
+
884
+ const top = el('div', 'run-top')
885
+ const title = el('div', 'run-title')
886
+ title.append(el('h3', '', run.goal || '(no goal)'))
887
+ title.append(el('p', '', `${shortId(run.id)} · ${timeLabel(run.createdAt)}`))
888
+ top.append(title)
889
+ top.append(el('span', `status-pill ${statusClass(run.status)}`, statusText(run.status)))
890
+ card.append(top)
891
+
892
+ const meta = el('div', 'run-meta')
893
+ if (run.cost) {
894
+ const cost = el('span')
895
+ cost.append(el('b', '', run.cost.text || '—'))
896
+ cost.append(document.createTextNode(` 成本${run.cost.complete ? '' : '(部分未定价)'}`))
897
+ meta.append(cost)
898
+ }
899
+ if (run.usage) {
900
+ const usage = el('span')
901
+ usage.append(el('b', '', formatTokens(run.usage.totalTokens)))
902
+ usage.append(document.createTextNode(' tokens'))
903
+ meta.append(usage)
904
+ }
905
+ const total = Array.isArray(run.subtasks) ? run.subtasks.length : 0
906
+ const done = Array.isArray(run.subtasks) ? run.subtasks.filter(s => s.status === 'completed').length : 0
907
+ if (total > 0) {
908
+ const progress = el('span')
909
+ progress.append(el('b', '', `${done}/${total}`))
910
+ progress.append(document.createTextNode(' 子任务'))
911
+ meta.append(progress)
912
+ }
913
+ card.append(meta)
914
+
915
+ if (total > 0) {
916
+ const bar = el('div', 'progress')
917
+ const fill = el('i')
918
+ fill.style.width = `${Math.round((done / total) * 100)}%`
919
+ bar.append(fill)
920
+ card.append(bar)
921
+
922
+ const subtasks = el('div', 'subtasks')
923
+ for (const subtask of run.subtasks.slice(0, 8)) {
924
+ const chip = el('span', `subtask ${subtask.status || ''}`.trim(), subtask.title || `subtask ${subtask.index ?? ''}`)
925
+ chip.title = `${subtask.status || 'unknown'}${subtask.childId ? ` · ${subtask.childId}` : ''}`
926
+ subtasks.append(chip)
927
+ }
928
+ if (total > 8) subtasks.append(el('span', 'subtask', `+${total - 8}`))
929
+ card.append(subtasks)
930
+ }
931
+
932
+ if (Array.isArray(run.attention) && run.attention.length > 0) {
933
+ for (const item of run.attention) {
934
+ card.append(attentionElement(run, item))
935
+ }
936
+ }
937
+
938
+ if (run.report) {
939
+ const details = el('details', 'report')
940
+ details.append(el('summary', '', `报告 · ${run.reportTruncated ? '前段预览' : '完整'}`))
941
+ details.append(el('pre', '', run.report))
942
+ card.append(details)
943
+ }
944
+
945
+ const actions = el('div', 'run-actions')
946
+ const reportButton = el('button', '', '查看完整报告')
947
+ reportButton.type = 'button'
948
+ reportButton.addEventListener('click', () => openReport(run.id))
949
+ actions.append(reportButton)
950
+ card.append(actions)
951
+
952
+ return card
953
+ }
954
+
955
+ function attentionElement(run, item) {
956
+ const card = el('div', 'attention-card')
957
+ card.append(el('div', 'kicker', `需要你决定${item.id ? ` · ${item.id}` : ''}`))
958
+ card.append(el('p', '', item.question || '运行中的任务在等一个决定'))
959
+ if (item.reason) card.append(el('p', 'reason', item.reason))
960
+
961
+ const key = draftKey(run.id, item.id)
962
+ const busy = STATE.busyAnswers.has(key)
963
+ const options = el('div', 'options')
964
+ if (Array.isArray(item.options)) {
965
+ for (const option of item.options) {
966
+ const button = el('button', '', option)
967
+ button.type = 'button'
968
+ button.disabled = busy
969
+ button.addEventListener('click', () => submitAnswer(run.id, item.id, option, key))
970
+ options.append(button)
971
+ }
972
+ }
973
+ if (options.childElementCount > 0) card.append(options)
974
+
975
+ const free = el('div', 'free')
976
+ const field = el('input')
977
+ field.type = 'text'
978
+ field.placeholder = '或输入自己的决定'
979
+ field.dataset.draftKey = key
980
+ field.value = STATE.drafts.get(key) || ''
981
+ field.disabled = busy
982
+ field.addEventListener('input', () => {
983
+ STATE.drafts.set(key, field.value)
984
+ })
985
+ field.addEventListener('keydown', event => {
986
+ if (event.key === 'Enter' && !event.isComposing) {
987
+ event.preventDefault()
988
+ const value = field.value.trim()
989
+ if (value) submitAnswer(run.id, item.id, value, key)
990
+ }
991
+ })
992
+ const submit = el('button', '', busy ? '提交中' : '提交')
993
+ submit.type = 'button'
994
+ submit.disabled = busy
995
+ submit.addEventListener('click', () => {
996
+ const value = field.value.trim()
997
+ if (value) submitAnswer(run.id, item.id, value, key)
998
+ })
999
+ free.append(field, submit)
1000
+ card.append(free)
1001
+ return card
1002
+ }
1003
+
1004
+ async function submitAnswer(runId, attentionId, answer, key) {
1005
+ if (STATE.busyAnswers.has(key)) return
1006
+ STATE.busyAnswers.add(key)
1007
+ renderRuns()
1008
+ try {
1009
+ await api('/api/console/answer', {
1010
+ method: 'POST',
1011
+ body: { sessionId: STATE.sessionId, runId, attentionId, answer },
1012
+ })
1013
+ STATE.drafts.delete(key)
1014
+ pushToast('决定已提交,run 会在下一个边界应用。', 'ok')
1015
+ } catch (error) {
1016
+ pushToast(`提交失败:${messageOf(error)}`, 'err')
1017
+ } finally {
1018
+ STATE.busyAnswers.delete(key)
1019
+ renderRuns()
1020
+ }
1021
+ }
1022
+
1023
+ async function openReport(runId) {
1024
+ try {
1025
+ const data = await api(`/api/console/runs/${encodeURIComponent(runId)}`)
1026
+ dialogTitleEl.textContent = data.goal || '报告'
1027
+ dialogMetaEl.textContent = ''
1028
+ const meta = [
1029
+ `状态 ${statusText(data.status)}`,
1030
+ data.cost?.text ? `成本 ${data.cost.text}` : null,
1031
+ data.usage ? `${formatTokens(data.usage.totalTokens)} tokens` : null,
1032
+ data.finishedAt ? `结束 ${timeLabel(data.finishedAt)}` : null,
1033
+ ].filter(Boolean)
1034
+ for (const value of meta) dialogMetaEl.append(el('span', '', value))
1035
+ dialogReportEl.textContent = data.report || '(这个 run 还没有报告)'
1036
+ reportDialogEl.showModal()
1037
+ } catch (error) {
1038
+ pushToast(`读取报告失败:${messageOf(error)}`, 'err')
1039
+ }
1040
+ }
1041
+
1042
+ // ---------- SSE ----------
1043
+
1044
+ function handleFrame(frame) {
1045
+ if (!frame || typeof frame !== 'object') return
1046
+ switch (frame.type) {
1047
+ case 'hello':
1048
+ setSession(frame.sessionId)
1049
+ setMode(frame.mode === 'chat' ? 'chat' : 'unavailable', frame.capabilities)
1050
+ setConn('live', '已连接')
1051
+ break
1052
+ case 'session':
1053
+ if (frame.sessionId && frame.sessionId !== STATE.sessionId) {
1054
+ setSession(frame.sessionId)
1055
+ clearMessages()
1056
+ renderEmpty()
1057
+ }
1058
+ break
1059
+ case 'stream.snapshot':
1060
+ clearMessages()
1061
+ if (frame.header && frame.header.id) setSession(frame.header.id)
1062
+ for (const record of Array.isArray(frame.records) ? frame.records : []) {
1063
+ if (record && record.type === 'event' && record.event) handleSessionEvent(record.event)
1064
+ }
1065
+ removeEmpty()
1066
+ if (STATE.messages.length === 0) renderEmpty()
1067
+ scrollToEnd()
1068
+ break
1069
+ case 'session.event':
1070
+ handleSessionEvent(frame.event)
1071
+ break
1072
+ case 'assistant.frame':
1073
+ handleAssistantFrame(frame.frame)
1074
+ break
1075
+ case 'session.state':
1076
+ applySessionState(frame.state)
1077
+ break
1078
+ case 'accepted':
1079
+ for (let i = STATE.messages.length - 1; i >= 0; i -= 1) {
1080
+ const message = STATE.messages[i]
1081
+ if (message.role === 'user' && message.pending && message.text === frame.text) {
1082
+ message.pending = false
1083
+ message.at = Date.now()
1084
+ refreshMessage(message)
1085
+ break
1086
+ }
1087
+ }
1088
+ break
1089
+ case 'runs':
1090
+ STATE.runs = Array.isArray(frame.runs) ? frame.runs : []
1091
+ renderRuns()
1092
+ break
1093
+ case 'answered':
1094
+ pushToast(`已提交 ${frame.attentionId || '决定'}。`, 'ok')
1095
+ break
1096
+ case 'error':
1097
+ if (frame.code === 'follow-failed' || frame.code === 'state-failed') {
1098
+ setConn('warn', '流中断')
1099
+ }
1100
+ pushToast(frame.message || '控制台流发生错误', 'err')
1101
+ break
1102
+ case 'truncated':
1103
+ pushToast('有一段历史过大,已截断显示。', 'err')
1104
+ break
1105
+ case 'closed':
1106
+ setConn('warn', '已关闭')
1107
+ break
1108
+ default:
1109
+ break
1110
+ }
1111
+ }
1112
+
1113
+ function handleSessionEvent(event) {
1114
+ if (!event || typeof event !== 'object') return
1115
+ const data = event.data && typeof event.data === 'object' ? event.data : {}
1116
+ switch (event.type) {
1117
+ case 'turn/start':
1118
+ setTyping(true, '运行中')
1119
+ break
1120
+ case 'turn/end':
1121
+ setTyping(false)
1122
+ if (STATE.currentAssistant) {
1123
+ STATE.currentAssistant.streaming = false
1124
+ refreshMessage(STATE.currentAssistant)
1125
+ STATE.currentAssistant = null
1126
+ }
1127
+ break
1128
+ case 'user/message': {
1129
+ if (data.source && data.source.kind && data.source.kind !== 'user') break
1130
+ const text = contentText(data.content).trim()
1131
+ if (!text) break
1132
+ removeEmpty()
1133
+ let matched = null
1134
+ for (let i = STATE.messages.length - 1; i >= 0; i -= 1) {
1135
+ const message = STATE.messages[i]
1136
+ if (message.role === 'user' && message.pending && message.text.trim() === text) {
1137
+ matched = message
1138
+ break
1139
+ }
1140
+ }
1141
+ if (matched) {
1142
+ matched.pending = false
1143
+ matched.at = event.time || Date.now()
1144
+ refreshMessage(matched)
1145
+ } else {
1146
+ addMessage('user', text, { at: event.time || Date.now() })
1147
+ }
1148
+ setTyping(true, '运行中')
1149
+ break
1150
+ }
1151
+ case 'assistant/message': {
1152
+ const finalText = contentText(data.message?.content)
1153
+ const reasoning = contentText((data.message?.content || []).filter(part => part && part.type === 'reasoning'))
1154
+ removeEmpty()
1155
+ let target = STATE.currentAssistant
1156
+ if (!target || (!target.streaming && target.text)) {
1157
+ target = addMessage('assistant', finalText, { at: event.time || Date.now(), reasoning })
1158
+ } else {
1159
+ if (finalText) target.text = finalText
1160
+ if (reasoning) target.reasoning = reasoning
1161
+ target.streaming = false
1162
+ target.at = event.time || target.at
1163
+ refreshMessage(target)
1164
+ }
1165
+ if (data.interrupted === true) {
1166
+ target.interrupted = true
1167
+ refreshMessage(target)
1168
+ }
1169
+ const calls = Array.isArray(data.message?.content)
1170
+ ? data.message.content.filter(part => part && part.type === 'tool-call')
1171
+ : []
1172
+ for (const call of calls) {
1173
+ upsertTool(target, {
1174
+ callId: call.id || call.callId,
1175
+ name: call.name || 'tool',
1176
+ status: 'ok',
1177
+ arguments: call.arguments,
1178
+ })
1179
+ }
1180
+ STATE.currentAssistant = null
1181
+ break
1182
+ }
1183
+ case 'tool/call':
1184
+ removeEmpty()
1185
+ if (!STATE.currentAssistant) addMessage('assistant', '', { at: event.time || Date.now(), streaming: true })
1186
+ upsertTool(STATE.currentAssistant, {
1187
+ callId: data.callId,
1188
+ name: data.name || 'tool',
1189
+ status: 'running',
1190
+ arguments: data.arguments,
1191
+ })
1192
+ break
1193
+ case 'tool/result': {
1194
+ // The host carries the call id on the tool message, not on the event.
1195
+ const callId = data.callId || data.message?.toolCallId || data.message?.source?.callId
1196
+ const call = STATE.toolCalls.get(callId)
1197
+ if (!call) break
1198
+ call.status = data.message?.isError ? 'err' : 'ok'
1199
+ call.done = true
1200
+ call.result = contentText(data.message?.content).slice(0, 4000)
1201
+ const message = call.message
1202
+ if (message && message.toolsEl) {
1203
+ const chip = message.toolsEl.querySelector(`[data-call-id="${cssEscape(callId || '')}"]`)
1204
+ if (chip) chip.replaceWith(toolChip(call))
1205
+ }
1206
+ break
1207
+ }
1208
+ case 'step/start':
1209
+ setTyping(true, '运行中')
1210
+ break
1211
+ case 'step/end':
1212
+ break
1213
+ default:
1214
+ break
1215
+ }
1216
+ }
1217
+
1218
+ function upsertTool(message, tool) {
1219
+ if (!message) return
1220
+ tool.message = message
1221
+ tool.done = tool.done === true
1222
+ const existing = STATE.toolCalls.get(tool.callId)
1223
+ if (existing) {
1224
+ Object.assign(existing, tool)
1225
+ } else {
1226
+ STATE.toolCalls.set(tool.callId, tool)
1227
+ message.tools = message.tools || []
1228
+ message.tools.push(tool)
1229
+ }
1230
+ if (message.toolsEl) {
1231
+ const key = tool.callId || ''
1232
+ const current = message.toolsEl.querySelector(`[data-call-id="${cssEscape(key)}"]`)
1233
+ const chip = toolChip(existing || tool)
1234
+ if (current) current.replaceWith(chip)
1235
+ else message.toolsEl.append(chip)
1236
+ }
1237
+ scrollToEnd()
1238
+ }
1239
+
1240
+ function handleAssistantFrame(frame) {
1241
+ if (!frame || typeof frame !== 'object') return
1242
+ if (frame.type === 'start') {
1243
+ removeEmpty()
1244
+ const message = addMessage('assistant', '', { streaming: true, at: Date.now() })
1245
+ STATE.currentAssistant = message
1246
+ setTyping(true, '生成中')
1247
+ return
1248
+ }
1249
+ if (frame.type === 'chunk' && frame.chunk) {
1250
+ const chunk = frame.chunk
1251
+ if (chunk.type === 'text-delta') {
1252
+ if (!STATE.currentAssistant) addMessage('assistant', '', { streaming: true, at: Date.now() })
1253
+ STATE.currentAssistant.text += chunk.text || ''
1254
+ refreshMessage(STATE.currentAssistant)
1255
+ scrollToEnd()
1256
+ } else if (chunk.type === 'reasoning-delta') {
1257
+ if (!STATE.currentAssistant) addMessage('assistant', '', { streaming: true, at: Date.now() })
1258
+ STATE.currentAssistant.reasoning = (STATE.currentAssistant.reasoning || '') + (chunk.text || '')
1259
+ refreshMessage(STATE.currentAssistant)
1260
+ } else if (chunk.type === 'tool-call-delta') {
1261
+ if (!STATE.currentAssistant) addMessage('assistant', '', { streaming: true, at: Date.now() })
1262
+ upsertTool(STATE.currentAssistant, {
1263
+ callId: chunk.id,
1264
+ name: chunk.name || 'tool',
1265
+ status: 'running',
1266
+ arguments: chunk.argumentsDelta || '',
1267
+ })
1268
+ }
1269
+ return
1270
+ }
1271
+ if (frame.type === 'end') {
1272
+ if (STATE.currentAssistant) {
1273
+ STATE.currentAssistant.streaming = false
1274
+ refreshMessage(STATE.currentAssistant)
1275
+ }
1276
+ setTyping(false)
1277
+ }
1278
+ }
1279
+
1280
+ function applySessionState(state) {
1281
+ if (!state || typeof state !== 'object') return
1282
+ STATE.pendingInput = Array.isArray(state.pendingInput) ? state.pendingInput : []
1283
+ if (STATE.pendingInput.includes('approval')) setTyping(true, '等待审批')
1284
+ else if (STATE.pendingInput.includes('question')) setTyping(true, '等待回答')
1285
+ else setTyping(state.running === true, state.queue && state.queue.length ? `运行中 · 队列 ${state.queue.length}` : '运行中')
1286
+ }
1287
+
1288
+ // ---------- API ----------
1289
+
1290
+ async function api(path, options = {}) {
1291
+ const headers = { authorization: `Bearer ${STATE.token}` }
1292
+ if (options.body !== undefined) headers['content-type'] = 'application/json'
1293
+ const response = await fetch(path, {
1294
+ method: options.method || 'GET',
1295
+ headers,
1296
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
1297
+ signal: options.signal,
1298
+ })
1299
+ let payload = null
1300
+ try {
1301
+ payload = await response.json()
1302
+ } catch {
1303
+ payload = null
1304
+ }
1305
+ if (!response.ok) {
1306
+ const error = new Error(payload?.error?.summary || payload?.error?.detail || `HTTP ${response.status}`)
1307
+ error.status = response.status
1308
+ error.code = payload?.error?.id
1309
+ error.hint = payload?.error?.hint
1310
+ throw error
1311
+ }
1312
+ return payload?.data
1313
+ }
1314
+
1315
+ function applyBootstrap(data) {
1316
+ STATE.booted = true
1317
+ setMode(data.mode === 'chat' ? 'chat' : 'unavailable', data.capabilities)
1318
+ if (data.sessionId) setSession(data.sessionId)
1319
+ STATE.runs = Array.isArray(data.runs) ? data.runs : []
1320
+ renderRuns()
1321
+ if (STATE.messages.length === 0) renderEmpty()
1322
+ loadTools()
1323
+ }
1324
+
1325
+ const toolCountEl = $('toolCount')
1326
+ const toolNoteEl = $('toolNote')
1327
+ const toolListEl = $('toolList')
1328
+
1329
+ /** Group a tool by the capability it would give the conversation. */
1330
+ function toolGroup(name) {
1331
+ if (name.startsWith('browser_')) return 'browser'
1332
+ if (name.startsWith('desktop_')) return 'desktop'
1333
+ if (/3d|blender|mesh|gltf|glb|fbx|stl|obj|step|cad/i.test(name)) return '3d'
1334
+ return 'other'
1335
+ }
1336
+
1337
+ function renderTools(data) {
1338
+ toolListEl.textContent = ''
1339
+ toolCountEl.textContent = '—'
1340
+ const tools = Array.isArray(data?.tools) ? data.tools : null
1341
+ if (!tools) {
1342
+ if (data == null) toolNoteEl.textContent = '加载中…'
1343
+ else if (data.reason === 'no-session') toolNoteEl.textContent = '还没有会话。'
1344
+ else toolNoteEl.textContent = `读不到工具清单:${data.reason || '宿主未返回'}`
1345
+ return
1346
+ }
1347
+ toolCountEl.textContent = String(tools.length)
1348
+ const counts = { browser: 0, desktop: 0, '3d': 0 }
1349
+ for (const tool of tools) {
1350
+ const group = toolGroup(tool.name)
1351
+ if (group in counts) counts[group] += 1
1352
+ const chip = el('span', `tool-name${group === 'browser' || group === 'desktop' ? ' on' : ''}`, tool.name)
1353
+ if (tool.description) chip.title = tool.description
1354
+ toolListEl.append(chip)
1355
+ }
1356
+ toolNoteEl.textContent = [
1357
+ `浏览器控制:${counts.browser ? `${counts.browser} 个 browser_* 工具` : '未挂载'}`,
1358
+ `桌面控制:${counts.desktop ? `${counts.desktop} 个 desktop_* 工具` : '未挂载'}`,
1359
+ `3D 建模:${counts['3d']
1360
+ ? `${counts['3d']} 个相关工具`
1361
+ : `未发现专用工具${tools.some(tool => tool.name === 'bash' || tool.name === 'pwsh')
1362
+ ? '(可经 shell 调 headless Blender)'
1363
+ : ''}`}`,
1364
+ ].join(' · ')
1365
+ }
1366
+
1367
+ async function loadTools() {
1368
+ if (!STATE.sessionId || STATE.mode !== 'chat') return
1369
+ try {
1370
+ renderTools(await api(`/api/console/tools?sessionId=${encodeURIComponent(STATE.sessionId)}`))
1371
+ } catch (error) {
1372
+ renderTools({ reason: messageOf(error) })
1373
+ }
1374
+ }
1375
+
1376
+ async function bootstrap() {
1377
+ try {
1378
+ const data = await api('/api/console/bootstrap', { method: 'POST' })
1379
+ applyBootstrap(data)
1380
+ if (data.mode === 'chat' && data.sessionId) connectEvents()
1381
+ else setConn('warn', '未连接')
1382
+ } catch (error) {
1383
+ if (error.status === 401) {
1384
+ showGate('令牌无效或已轮换,请重新读取 console.json。')
1385
+ return
1386
+ }
1387
+ setMode('unavailable', { chat: false, reason: `${messageOf(error)}${error.hint ? `\n${error.hint}` : ''}` })
1388
+ setConn('warn', '连接失败')
1389
+ renderEmpty()
1390
+ pushToast(`无法启动对话:${messageOf(error)}`, 'err')
1391
+ }
1392
+ }
1393
+
1394
+ async function connectEvents() {
1395
+ if (!STATE.sessionId) return
1396
+ if (STATE.streamAbort) STATE.streamAbort.abort()
1397
+ const controller = new AbortController()
1398
+ STATE.streamAbort = controller
1399
+ setConn('warn', '连接流中')
1400
+ try {
1401
+ const response = await fetch(`/api/console/events?sessionId=${encodeURIComponent(STATE.sessionId)}`, {
1402
+ headers: { authorization: `Bearer ${STATE.token}` },
1403
+ signal: controller.signal,
1404
+ })
1405
+ if (!response.ok) {
1406
+ const payload = await response.json().catch(() => null)
1407
+ const error = new Error(payload?.error?.summary || `HTTP ${response.status}`)
1408
+ error.status = response.status
1409
+ throw error
1410
+ }
1411
+ setConn('live', '已连接')
1412
+ const reader = response.body.getReader()
1413
+ const decoder = new TextDecoder()
1414
+ let buffer = ''
1415
+ while (true) {
1416
+ const { value, done } = await reader.read()
1417
+ if (done) break
1418
+ buffer += decoder.decode(value, { stream: true })
1419
+ let cut = buffer.indexOf('\n\n')
1420
+ while (cut >= 0) {
1421
+ const block = buffer.slice(0, cut)
1422
+ buffer = buffer.slice(cut + 2)
1423
+ for (const line of block.split('\n')) {
1424
+ if (!line.startsWith('data:')) continue
1425
+ const raw = line.slice(5).trimStart()
1426
+ if (!raw) continue
1427
+ try {
1428
+ handleFrame(JSON.parse(raw))
1429
+ } catch {
1430
+ // A malformed frame is ignored; the next one may be valid.
1431
+ }
1432
+ }
1433
+ cut = buffer.indexOf('\n\n')
1434
+ }
1435
+ }
1436
+ if (!controller.signal.aborted) {
1437
+ setConn('warn', '重连中')
1438
+ scheduleReconnect()
1439
+ }
1440
+ } catch (error) {
1441
+ if (controller.signal.aborted) return
1442
+ if (error.status === 401) {
1443
+ showGate('令牌无效或已轮换,请重新读取 console.json。')
1444
+ return
1445
+ }
1446
+ setConn('warn', '重连中')
1447
+ scheduleReconnect()
1448
+ }
1449
+ }
1450
+
1451
+ function scheduleReconnect() {
1452
+ if (STATE.reconnectTimer) return
1453
+ STATE.reconnectTimer = setTimeout(() => {
1454
+ STATE.reconnectTimer = null
1455
+ if (STATE.mode === 'chat' && STATE.sessionId) connectEvents()
1456
+ }, 1200)
1457
+ }
1458
+
1459
+ // ---------- composer ----------
1460
+
1461
+ async function sendMessage() {
1462
+ const text = inputEl.value.trim()
1463
+ if (!text || STATE.sending || STATE.mode !== 'chat') return
1464
+ STATE.sending = true
1465
+ updateSend()
1466
+ inputEl.value = ''
1467
+ autoGrow()
1468
+ removeEmpty()
1469
+ const optimistic = addMessage('user', text, { pending: true, at: Date.now() })
1470
+ try {
1471
+ await api('/api/console/message', {
1472
+ method: 'POST',
1473
+ body: { sessionId: STATE.sessionId, text, mode: STATE.sendMode },
1474
+ })
1475
+ optimistic.pending = false
1476
+ refreshMessage(optimistic)
1477
+ } catch (error) {
1478
+ optimistic.pending = false
1479
+ optimistic.failed = true
1480
+ refreshMessage(optimistic)
1481
+ pushToast(`发送失败:${messageOf(error)}`, 'err')
1482
+ } finally {
1483
+ STATE.sending = false
1484
+ updateSend()
1485
+ inputEl.focus()
1486
+ }
1487
+ }
1488
+
1489
+ async function newConversation() {
1490
+ if (STATE.mode !== 'chat') return
1491
+ newChatEl.disabled = true
1492
+ try {
1493
+ const data = await api('/api/console/session', { method: 'POST' })
1494
+ if (STATE.streamAbort) STATE.streamAbort.abort()
1495
+ setSession(data.sessionId)
1496
+ clearMessages()
1497
+ STATE.runs = []
1498
+ renderRuns()
1499
+ renderEmpty()
1500
+ renderTools(null)
1501
+ loadTools()
1502
+ pushToast('已开始新对话。', 'ok')
1503
+ connectEvents()
1504
+ } catch (error) {
1505
+ pushToast(`无法新建对话:${messageOf(error)}`, 'err')
1506
+ } finally {
1507
+ newChatEl.disabled = STATE.mode !== 'chat'
1508
+ }
1509
+ }
1510
+
1511
+ // ---------- gate ----------
1512
+
1513
+ function showGate(errorText) {
1514
+ gateEl.hidden = false
1515
+ gateErrorEl.textContent = errorText || ''
1516
+ setTimeout(() => tokenInputEl.focus(), 30)
1517
+ }
1518
+
1519
+ function hideGate() {
1520
+ gateEl.hidden = true
1521
+ }
1522
+
1523
+ function readTokenFromUrl() {
1524
+ const url = new URL(window.location.href)
1525
+ const queryToken = url.searchParams.get('token')
1526
+ if (queryToken) {
1527
+ STATE.token = queryToken
1528
+ try { sessionStorage.setItem(TOKEN_KEY, queryToken) } catch {}
1529
+ url.searchParams.delete('token')
1530
+ window.history.replaceState({}, '', url.pathname + url.search + url.hash)
1531
+ return true
1532
+ }
1533
+ return false
1534
+ }
1535
+
1536
+ function loadStoredToken() {
1537
+ try {
1538
+ return sessionStorage.getItem(TOKEN_KEY) || ''
1539
+ } catch {
1540
+ return ''
1541
+ }
1542
+ }
1543
+
1544
+ // ---------- wiring ----------
1545
+
1546
+ messagesEl.addEventListener('scroll', () => {
1547
+ const distance = messagesEl.scrollHeight - messagesEl.scrollTop - messagesEl.clientHeight
1548
+ STATE.autoScroll = distance < 80
1549
+ })
1550
+
1551
+ inputEl.addEventListener('input', () => {
1552
+ autoGrow()
1553
+ updateSend()
1554
+ })
1555
+
1556
+ inputEl.addEventListener('keydown', event => {
1557
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
1558
+ event.preventDefault()
1559
+ sendMessage()
1560
+ }
1561
+ })
1562
+
1563
+ composerEl.addEventListener('submit', event => {
1564
+ event.preventDefault()
1565
+ sendMessage()
1566
+ })
1567
+
1568
+ for (const button of document.querySelectorAll('.segmented button')) {
1569
+ button.addEventListener('click', () => {
1570
+ STATE.sendMode = button.dataset.mode === 'steer' ? 'steer' : 'queue'
1571
+ for (const peer of document.querySelectorAll('.segmented button')) {
1572
+ peer.classList.toggle('active', peer === button)
1573
+ }
1574
+ })
1575
+ }
1576
+
1577
+ newChatEl.addEventListener('click', newConversation)
1578
+ $('dialogClose').addEventListener('click', () => reportDialogEl.close())
1579
+ reportDialogEl.addEventListener('click', event => {
1580
+ if (event.target === reportDialogEl) reportDialogEl.close()
1581
+ })
1582
+
1583
+ gateFormEl.addEventListener('submit', event => {
1584
+ event.preventDefault()
1585
+ const token = tokenInputEl.value.trim()
1586
+ if (!token) return
1587
+ STATE.token = token
1588
+ try { sessionStorage.setItem(TOKEN_KEY, token) } catch {}
1589
+ tokenInputEl.value = ''
1590
+ hideGate()
1591
+ bootstrap()
1592
+ })
1593
+
1594
+ // A token pasted as the page URL is consumed once and removed from the address
1595
+ // bar; it never goes into a log or a referrer.
1596
+ if (readTokenFromUrl()) {
1597
+ hideGate()
1598
+ bootstrap()
1599
+ } else {
1600
+ const stored = loadStoredToken()
1601
+ if (stored) {
1602
+ STATE.token = stored
1603
+ hideGate()
1604
+ bootstrap()
1605
+ } else {
1606
+ setMode('loading', null)
1607
+ setConn('warn', '需要 token')
1608
+ showGate('')
1609
+ }
1610
+ }
1611
+
1612
+ setInterval(() => {
1613
+ if (STATE.mode === 'chat' && !STATE.sessionId) bootstrap()
1614
+ }, 15_000)
1615
+ })()
1616
+ </script>
1617
+ </body>
1618
+ </html>