cladogram 0.6.0-beta.2 → 0.6.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/clado.js +34 -2
- package/docs/release.md +8 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +826 -106
- package/plugins/agent/style.css +448 -38
- package/src/agent/clado-tools.js +437 -103
- package/src/agent/pi-bridge.js +517 -42
- package/src/agent/pi-config.js +367 -31
- package/src/html/canvas-chain.js +26 -2
- package/src/html/canvas-focus.js +19 -13
- package/src/html/canvas-live-diff.js +927 -0
- package/src/html/canvas-ui.css +365 -0
- package/src/html/canvas-wires.js +5 -1
- package/src/html/page.js +1 -1
- package/src/html/runtime-api.js +140 -10
- package/src/html/runtime.js +93 -26
- package/src/server/agent.js +40 -8
- package/src/server/assets/library-canvas.js +240 -5
- package/src/server/assets/library.css +416 -0
- package/src/server/assets/library.html +2 -0
- package/src/server/assets/library.js +703 -14
- package/src/server/code-inspect.js +183 -0
- package/src/server/mcp.js +4 -4
- package/src/server/workspace.js +260 -18
- package/src/workspace/graph-snapshot.js +695 -0
- package/src/workspace/service.js +11 -1
package/plugins/agent/index.js
CHANGED
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
const TONE_CHIP = { sky: 'clado-chip-sky', emerald: 'clado-chip-mint', violet: 'clado-chip-violet', amber: 'clado-chip-amber' };
|
|
21
21
|
|
|
22
22
|
const CODE_ANALYSIS_PROMPTS = {
|
|
23
|
-
arch: '请先扫描当前项目源码目录结构,识别核心模块、入口文件与数据流边界,然后调用 clado_create 创建一张名为 architecture-overview.md
|
|
24
|
-
req: '请结合当前仓库现状,帮我创建一张名为 feature-design.md
|
|
25
|
-
qa: '
|
|
23
|
+
arch: '请先扫描当前项目源码目录结构,识别核心模块、入口文件与数据流边界,然后调用 clado_create 创建一张名为 architecture-overview.md 的卡片模式网状架构画布:让入口契约、编排路由、并行模块与底层存储从左到右连成完整网状结构并标注语义 Tag;写完后必须调用 clado_graph 复核零孤立卡与零断链,并用 canvas_focus 聚焦入口卡。',
|
|
24
|
+
req: '请结合当前仓库现状,帮我创建一张名为 feature-design.md 的新需求拆解画布,包含入口契约、核心分支、状态流转与数据落点卡片,用跨卡内链与语义 Tag 连成端到端网状图,写完后用 clado_graph 复核连线健康度。',
|
|
25
|
+
qa: '请阅读当前仓库核心模块与已有测试,使用 test-cases 模板创建一张名为 test-matrix.md 的测试与压测矩阵画布,列出主链路、并发边界与异常回归检查项并连成清晰网络,最后用 clado_graph 复核。',
|
|
26
26
|
};
|
|
27
27
|
|
|
28
28
|
// ===========================================================================
|
|
@@ -91,11 +91,12 @@
|
|
|
91
91
|
continue;
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
// Headings
|
|
95
|
-
const hMatch = line.match(/^\s{0,3}(#{1,
|
|
94
|
+
// Headings (allow empty/partial heading text during live token streaming like "### ")
|
|
95
|
+
const hMatch = line.match(/^\s{0,3}(#{1,6})\s+(.*)$/);
|
|
96
96
|
if (hMatch) {
|
|
97
|
-
const lvl = hMatch[1].length;
|
|
98
|
-
|
|
97
|
+
const lvl = Math.min(4, hMatch[1].length);
|
|
98
|
+
const headingText = hMatch[2].replace(/\s+#*\s*$/, '').trim();
|
|
99
|
+
out.push(`<h${lvl}>${headingText ? renderInline(headingText) : ' '}</h${lvl}>`);
|
|
99
100
|
i++;
|
|
100
101
|
continue;
|
|
101
102
|
}
|
|
@@ -163,7 +164,7 @@
|
|
|
163
164
|
i < lines.length
|
|
164
165
|
&& lines[i].trim()
|
|
165
166
|
&& !/^\u0000FENCE\d+\u0000$/.test(lines[i].trim())
|
|
166
|
-
&& !/^\s{0,3}#{1,
|
|
167
|
+
&& !/^\s{0,3}#{1,6}\s+/.test(lines[i])
|
|
167
168
|
&& !/^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/.test(lines[i])
|
|
168
169
|
&& !/^\s*>\s?/.test(lines[i])
|
|
169
170
|
&& !/^\s*[-*+]\s+/.test(lines[i])
|
|
@@ -175,6 +176,10 @@
|
|
|
175
176
|
}
|
|
176
177
|
if (pLines.length) {
|
|
177
178
|
out.push(`<p>${pLines.map(renderInline).join('<br/>')}</p>`);
|
|
179
|
+
} else {
|
|
180
|
+
// Hard invariant: ALWAYS advance cursor so partial streaming markdown can never infinite-loop
|
|
181
|
+
out.push(`<p>${renderInline(lines[i])}</p>`);
|
|
182
|
+
i++;
|
|
178
183
|
}
|
|
179
184
|
}
|
|
180
185
|
|
|
@@ -208,8 +213,8 @@
|
|
|
208
213
|
dock.innerHTML = `
|
|
209
214
|
<div class="clado-dock-drawer collapsed" data-drawer>
|
|
210
215
|
<div class="clado-resize-nw" data-resize="nw" title="拖动调整对话窗口宽高(双击恢复默认)"></div>
|
|
211
|
-
<div class="clado-resize-n" data-resize="n" title="
|
|
212
|
-
<div class="clado-resize-w" data-resize="w" title="
|
|
216
|
+
<div class="clado-resize-n" data-resize="n" title="上下拖动调整对话高度(双击恢复默认)"><span class="clado-resize-grip"></span></div>
|
|
217
|
+
<div class="clado-resize-w" data-resize="w" title="左右拖动调整对话宽度"><span class="clado-resize-grip-v"></span></div>
|
|
213
218
|
<div class="clado-dock-aura"></div>
|
|
214
219
|
<div class="clado-dock-inner">
|
|
215
220
|
<div class="clado-dock-head">
|
|
@@ -242,14 +247,20 @@
|
|
|
242
247
|
|
|
243
248
|
<div class="clado-composer">
|
|
244
249
|
<div class="clado-dock-popover clado-scroll" data-popover hidden></div>
|
|
250
|
+
<div class="clado-ctx-bar" data-ctx-bar hidden></div>
|
|
245
251
|
<textarea class="clado-composer-input clado-scroll" data-input rows="1" placeholder="输入需求、敲 / 调命令(Enter 换行,Ctrl+Enter 发送)…"></textarea>
|
|
246
252
|
<div class="clado-composer-bar">
|
|
247
253
|
<div class="clado-composer-left">
|
|
248
254
|
<button type="button" class="clado-ui-button" data-toggle-drawer style="width:26px;height:26px;padding:0;min-height:26px;color:var(--clado-ui-brand);" title="展开或收起角色会话">${ICONS.sparkle}</button>
|
|
249
255
|
<button type="button" class="clado-model-chip" data-model-chip title="切换模型或配置供应商">配置模型 ▾</button>
|
|
256
|
+
<button type="button" class="clado-ctx-meter" data-ctx-meter title="查看模型上下文余量、思考强度与自动压缩策略">
|
|
257
|
+
<span class="clado-ctx-meter-track"><span class="clado-ctx-meter-fill" style="width:0%;"></span></span>
|
|
258
|
+
<span data-ctx-meter-txt>剩 100%</span>
|
|
259
|
+
</button>
|
|
250
260
|
</div>
|
|
251
261
|
<div class="clado-composer-right">
|
|
252
262
|
<button type="button" class="clado-sendmode-btn" data-sendmode title="点击切换发送快捷键">Ctrl↵ 发送</button>
|
|
263
|
+
<button type="button" class="clado-stop-btn" data-stop hidden title="停止当前 AI 执行并保留已生成内容">停止</button>
|
|
253
264
|
<button type="button" class="clado-ui-button clado-ui-button-primary" data-send style="min-height:26px;padding:3px 13px;font-size:12px;">发送</button>
|
|
254
265
|
</div>
|
|
255
266
|
</div>
|
|
@@ -264,18 +275,31 @@
|
|
|
264
275
|
const stripEl = dock.querySelector('[data-role-strip]');
|
|
265
276
|
const inputEl = dock.querySelector('[data-input]');
|
|
266
277
|
const sendBtn = dock.querySelector('[data-send]');
|
|
278
|
+
const stopBtn = dock.querySelector('[data-stop]');
|
|
279
|
+
const ctxBarEl = dock.querySelector('[data-ctx-bar]');
|
|
267
280
|
const sendModeBtn = dock.querySelector('[data-sendmode]');
|
|
268
281
|
const modelChip = dock.querySelector('[data-model-chip]');
|
|
282
|
+
const ctxMeterBtn = dock.querySelector('[data-ctx-meter]');
|
|
269
283
|
const popoverEl = dock.querySelector('[data-popover]');
|
|
270
284
|
const sessionPopEl = dock.querySelector('[data-session-pop]');
|
|
271
285
|
const sessionTriggerEl = dock.querySelector('[data-session-trigger]');
|
|
286
|
+
let pinnedSnippet = null; // { file, node, text }
|
|
287
|
+
|
|
288
|
+
function syncRootDockWidth(w) {
|
|
289
|
+
if (Number.isFinite(w)) {
|
|
290
|
+
document.documentElement.style.setProperty('--clado-dock-w', Math.round(w) + 'px');
|
|
291
|
+
} else {
|
|
292
|
+
document.documentElement.style.removeProperty('--clado-dock-w');
|
|
293
|
+
}
|
|
294
|
+
}
|
|
272
295
|
|
|
273
296
|
// Restore persisted dock dimensions
|
|
274
297
|
function applyDockSize(w, h) {
|
|
275
|
-
if (Number.isFinite(w) && w >= 350 && w <=
|
|
298
|
+
if (Number.isFinite(w) && w >= 350 && w <= 880) {
|
|
276
299
|
dock.style.setProperty('--clado-dock-w', Math.round(w) + 'px');
|
|
300
|
+
syncRootDockWidth(w);
|
|
277
301
|
}
|
|
278
|
-
if (Number.isFinite(h) && h >= 160 && h <=
|
|
302
|
+
if (Number.isFinite(h) && h >= 160 && h <= 820) {
|
|
279
303
|
dock.style.setProperty('--clado-dock-stream-h', Math.round(h) + 'px');
|
|
280
304
|
}
|
|
281
305
|
}
|
|
@@ -291,15 +315,16 @@
|
|
|
291
315
|
return rect.width > 0 ? (rect.width / stage.offsetWidth) : 1;
|
|
292
316
|
}
|
|
293
317
|
|
|
294
|
-
// Bind NW / N / W Resize Handles
|
|
318
|
+
// Bind NW / N / W Resize Handles (with iframe pointer-event isolation for smooth dragging)
|
|
295
319
|
dock.querySelectorAll('[data-resize]').forEach(handle => {
|
|
296
320
|
const mode = handle.dataset.resize;
|
|
297
|
-
if (mode === 'nw') {
|
|
321
|
+
if (mode === 'nw' || mode === 'n') {
|
|
298
322
|
handle.addEventListener('dblclick', e => {
|
|
299
323
|
e.preventDefault();
|
|
300
324
|
e.stopPropagation();
|
|
301
325
|
dock.style.removeProperty('--clado-dock-w');
|
|
302
326
|
dock.style.removeProperty('--clado-dock-stream-h');
|
|
327
|
+
syncRootDockWidth(NaN);
|
|
303
328
|
localStorage.removeItem('clado-dock-size');
|
|
304
329
|
showToast('已恢复默认对话窗口尺寸');
|
|
305
330
|
});
|
|
@@ -310,8 +335,10 @@
|
|
|
310
335
|
e.stopPropagation();
|
|
311
336
|
const scale = getStageScale();
|
|
312
337
|
const stage = stageRoot();
|
|
313
|
-
const
|
|
314
|
-
const
|
|
338
|
+
const stageW = stage.offsetWidth || window.innerWidth;
|
|
339
|
+
const stageH = stage.offsetHeight || window.innerHeight;
|
|
340
|
+
const maxW = Math.min(880, Math.max(420, stageW - 48));
|
|
341
|
+
const maxH = Math.min(820, Math.max(260, stageH - 200));
|
|
315
342
|
const startX = e.clientX;
|
|
316
343
|
const startY = e.clientY;
|
|
317
344
|
const startW = dock.offsetWidth || 412;
|
|
@@ -319,7 +346,8 @@
|
|
|
319
346
|
let lastW = startW;
|
|
320
347
|
let lastH = startH;
|
|
321
348
|
drawerEl.classList.add('resizing');
|
|
322
|
-
|
|
349
|
+
document.body.classList.add('clado-dock-resizing');
|
|
350
|
+
try { handle.setPointerCapture?.(e.pointerId); } catch {}
|
|
323
351
|
|
|
324
352
|
const onMove = ev => {
|
|
325
353
|
const dx = (ev.clientX - startX) / scale;
|
|
@@ -327,14 +355,17 @@
|
|
|
327
355
|
if (mode === 'w' || mode === 'nw') {
|
|
328
356
|
lastW = Math.max(350, Math.min(maxW, startW - dx));
|
|
329
357
|
dock.style.setProperty('--clado-dock-w', Math.round(lastW) + 'px');
|
|
358
|
+
syncRootDockWidth(lastW);
|
|
330
359
|
}
|
|
331
360
|
if (mode === 'n' || mode === 'nw') {
|
|
332
361
|
lastH = Math.max(160, Math.min(maxH, startH - dy));
|
|
333
362
|
dock.style.setProperty('--clado-dock-stream-h', Math.round(lastH) + 'px');
|
|
334
363
|
}
|
|
335
364
|
};
|
|
336
|
-
const onUp =
|
|
365
|
+
const onUp = ev => {
|
|
337
366
|
drawerEl.classList.remove('resizing');
|
|
367
|
+
document.body.classList.remove('clado-dock-resizing');
|
|
368
|
+
try { if (ev?.pointerId != null) handle.releasePointerCapture?.(ev.pointerId); } catch {}
|
|
338
369
|
window.removeEventListener('pointermove', onMove);
|
|
339
370
|
window.removeEventListener('pointerup', onUp);
|
|
340
371
|
window.removeEventListener('pointercancel', onUp);
|
|
@@ -352,6 +383,28 @@
|
|
|
352
383
|
window.dispatchEvent(new CustomEvent('clado:toast', { detail: { message: msg } }));
|
|
353
384
|
}
|
|
354
385
|
|
|
386
|
+
function renderContextChips() {
|
|
387
|
+
if (!ctxBarEl) return;
|
|
388
|
+
const ctx = actions.readContext ? (actions.readContext() || {}) : {};
|
|
389
|
+
const chips = [];
|
|
390
|
+
if (ctx.file) {
|
|
391
|
+
chips.push(`<span class="clado-ctx-chip"><span class="clado-ctx-chip-txt">${esc(ctx.file)}</span></span>`);
|
|
392
|
+
}
|
|
393
|
+
if (Array.isArray(ctx.selection) && ctx.selection.length) {
|
|
394
|
+
chips.push(`<span class="clado-ctx-chip"><span class="clado-ctx-chip-txt">已选 ${ctx.selection.length} 张卡片</span></span>`);
|
|
395
|
+
}
|
|
396
|
+
if (pinnedSnippet && pinnedSnippet.text) {
|
|
397
|
+
const nodeTag = Array.isArray(pinnedSnippet.node) && pinnedSnippet.node.length ? pinnedSnippet.node[pinnedSnippet.node.length - 1] + ' · ' : '';
|
|
398
|
+
chips.push(`<span class="clado-ctx-chip is-snippet"><span class="clado-ctx-chip-txt">${esc(nodeTag + '「' + pinnedSnippet.text.slice(0, 32) + '」')}</span><button type="button" class="clado-ctx-chip-x" data-clear-snippet title="移除片段上下文">×</button></span>`);
|
|
399
|
+
}
|
|
400
|
+
ctxBarEl.innerHTML = chips.join('');
|
|
401
|
+
ctxBarEl.hidden = chips.length === 0;
|
|
402
|
+
const clearBtn = ctxBarEl.querySelector('[data-clear-snippet]');
|
|
403
|
+
if (clearBtn) {
|
|
404
|
+
clearBtn.onclick = () => { pinnedSnippet = null; renderContextChips(); };
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
355
408
|
function autoGrowInput() {
|
|
356
409
|
inputEl.style.height = 'auto';
|
|
357
410
|
const next = Math.min(132, Math.max(22, inputEl.scrollHeight));
|
|
@@ -359,6 +412,10 @@
|
|
|
359
412
|
}
|
|
360
413
|
|
|
361
414
|
function syncSendModeUi() {
|
|
415
|
+
if (runningSessionId) {
|
|
416
|
+
inputEl.placeholder = 'AI 正在运行,输入内容可随时中途插话纠偏…';
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
362
419
|
if (sendMode === 'ctrl-enter') {
|
|
363
420
|
sendModeBtn.textContent = 'Ctrl↵ 发送';
|
|
364
421
|
sendModeBtn.title = '当前:Enter 换行,Ctrl/⌘+Enter 发送(点击切换为 Enter 发送)';
|
|
@@ -375,6 +432,7 @@
|
|
|
375
432
|
drawerOpen = Boolean(open);
|
|
376
433
|
drawerEl.classList.toggle('collapsed', !drawerOpen);
|
|
377
434
|
document.body.dataset.agentDock = drawerOpen ? 'open' : 'closed';
|
|
435
|
+
if (drawerOpen) renderContextChips();
|
|
378
436
|
if (!drawerOpen) closeSessionPop();
|
|
379
437
|
}
|
|
380
438
|
|
|
@@ -384,6 +442,7 @@
|
|
|
384
442
|
if (openDrawer) setDrawerOpen(true);
|
|
385
443
|
renderRoleStrip();
|
|
386
444
|
renderStream();
|
|
445
|
+
renderContextChips();
|
|
387
446
|
if (!sessionPopEl.hidden) renderSessionPop();
|
|
388
447
|
}
|
|
389
448
|
|
|
@@ -418,14 +477,122 @@
|
|
|
418
477
|
stripEl.append(addBtn);
|
|
419
478
|
}
|
|
420
479
|
|
|
480
|
+
function appendMessageThinking(msg, delta) {
|
|
481
|
+
if (!delta) return;
|
|
482
|
+
if (!Array.isArray(msg.blocks)) msg.blocks = [];
|
|
483
|
+
const last = msg.blocks[msg.blocks.length - 1];
|
|
484
|
+
if (last && last.type === 'thinking') {
|
|
485
|
+
last.text += delta;
|
|
486
|
+
} else {
|
|
487
|
+
msg.blocks.push({ type: 'thinking', text: delta });
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function appendMessageText(msg, delta) {
|
|
492
|
+
if (!delta) return;
|
|
493
|
+
if (!Array.isArray(msg.blocks)) msg.blocks = [];
|
|
494
|
+
const last = msg.blocks[msg.blocks.length - 1];
|
|
495
|
+
if (last && last.type === 'text') {
|
|
496
|
+
last.text += delta;
|
|
497
|
+
msg.text = (msg.text || '') + delta;
|
|
498
|
+
} else {
|
|
499
|
+
msg.blocks.push({ type: 'text', text: delta });
|
|
500
|
+
const prev = msg.text || '';
|
|
501
|
+
const sep = prev && !prev.endsWith('\n\n') && !delta.startsWith('\n') ? '\n\n' : '';
|
|
502
|
+
msg.text = prev + sep + delta;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function upsertMessageTool(msg, ev) {
|
|
507
|
+
if (!Array.isArray(msg.tools)) msg.tools = [];
|
|
508
|
+
if (!Array.isArray(msg.blocks)) msg.blocks = [];
|
|
509
|
+
const existing = msg.tools.find(t => t.id === ev.id);
|
|
510
|
+
if (existing) {
|
|
511
|
+
if (ev.status) existing.status = ev.status;
|
|
512
|
+
if (ev.isError !== undefined) existing.isError = Boolean(ev.isError);
|
|
513
|
+
if (ev.argsSummary) existing.argsSummary = ev.argsSummary;
|
|
514
|
+
if (ev.resultPreview !== undefined) existing.resultPreview = ev.resultPreview;
|
|
515
|
+
return existing;
|
|
516
|
+
}
|
|
517
|
+
const entry = {
|
|
518
|
+
id: ev.id,
|
|
519
|
+
name: ev.name || ev.title || 'tool',
|
|
520
|
+
argsSummary: ev.argsSummary || '',
|
|
521
|
+
resultPreview: ev.resultPreview || '',
|
|
522
|
+
status: ev.status || 'running',
|
|
523
|
+
isError: Boolean(ev.isError || ev.status === 'failed'),
|
|
524
|
+
};
|
|
525
|
+
msg.tools.push(entry);
|
|
526
|
+
const last = msg.blocks[msg.blocks.length - 1];
|
|
527
|
+
if (last && last.type === 'tools') {
|
|
528
|
+
last.tools.push(entry);
|
|
529
|
+
} else {
|
|
530
|
+
msg.blocks.push({ type: 'tools', tools: [entry] });
|
|
531
|
+
}
|
|
532
|
+
return entry;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function buildThinkingTrace(msgKey, text) {
|
|
536
|
+
const details = document.createElement('details');
|
|
537
|
+
details.className = 'clado-thinking-trace';
|
|
538
|
+
if (traceOpenState.get(msgKey)) details.open = true;
|
|
539
|
+
details.addEventListener('toggle', () => { traceOpenState.set(msgKey, details.open); });
|
|
540
|
+
const chars = String(text || '').trim().length;
|
|
541
|
+
const summary = document.createElement('summary');
|
|
542
|
+
summary.innerHTML = `<span>思考过程 (${chars} 字)</span><span style="font-size:10px;opacity:.72;">${details.open ? '收起' : '展开'}</span>`;
|
|
543
|
+
details.addEventListener('toggle', () => {
|
|
544
|
+
if (summary.lastElementChild) summary.lastElementChild.textContent = details.open ? '收起' : '展开';
|
|
545
|
+
});
|
|
546
|
+
const body = document.createElement('div');
|
|
547
|
+
body.className = 'clado-thinking-body clado-scroll';
|
|
548
|
+
body.textContent = String(text || '').trim();
|
|
549
|
+
details.append(summary, body);
|
|
550
|
+
return details;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function decorateCanvasRefs(containerEl) {
|
|
554
|
+
const entities = actions.getCanvasEntities ? actions.getCanvasEntities() : null;
|
|
555
|
+
if (!entities) return;
|
|
556
|
+
const cardSet = new Set();
|
|
557
|
+
(entities.cards || []).forEach(c => { if (c?.title) cardSet.add(c.title); });
|
|
558
|
+
(entities.sections || []).forEach(sec => { if (sec?.title) cardSet.add(sec.title); });
|
|
559
|
+
const tagSet = new Set((entities.tags || []).map(t => t.id).filter(Boolean));
|
|
560
|
+
if (!cardSet.size && !tagSet.size) return;
|
|
561
|
+
|
|
562
|
+
containerEl.querySelectorAll('code').forEach(codeEl => {
|
|
563
|
+
if (codeEl.closest('pre')) return;
|
|
564
|
+
const raw = (codeEl.textContent || '').trim();
|
|
565
|
+
if (!raw) return;
|
|
566
|
+
if (raw.startsWith('#') && tagSet.has(raw.slice(1))) {
|
|
567
|
+
const btn = document.createElement('button');
|
|
568
|
+
btn.type = 'button';
|
|
569
|
+
btn.className = 'clado-chat-ref is-tag';
|
|
570
|
+
btn.dataset.refTag = raw.slice(1);
|
|
571
|
+
btn.title = '点击定位到画布语义锚点 ' + raw;
|
|
572
|
+
btn.textContent = raw;
|
|
573
|
+
codeEl.replaceWith(btn);
|
|
574
|
+
} else if (cardSet.has(raw)) {
|
|
575
|
+
const btn = document.createElement('button');
|
|
576
|
+
btn.type = 'button';
|
|
577
|
+
btn.className = 'clado-chat-ref is-card';
|
|
578
|
+
btn.dataset.refCard = raw;
|
|
579
|
+
btn.title = '点击飞向画布卡片「' + raw + '」';
|
|
580
|
+
btn.textContent = raw;
|
|
581
|
+
codeEl.replaceWith(btn);
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
|
|
421
586
|
function buildToolTrace(msgKey, tools, isRunningMsg) {
|
|
422
587
|
const details = document.createElement('details');
|
|
423
588
|
details.className = 'clado-tool-trace';
|
|
424
589
|
const anyRunning = tools.some(t => t.status === 'running');
|
|
425
|
-
const
|
|
590
|
+
const failedCount = tools.filter(t => t.status === 'failed' || t.isError).length;
|
|
591
|
+
const anyFailed = failedCount > 0;
|
|
426
592
|
const doneCount = tools.filter(t => t.status === 'completed' || t.status === 'failed').length;
|
|
427
|
-
const shouldOpen = traceOpenState.has(msgKey) ? traceOpenState.get(msgKey) : (anyRunning || isRunningMsg);
|
|
593
|
+
const shouldOpen = traceOpenState.has(msgKey) ? traceOpenState.get(msgKey) : (anyRunning || anyFailed || isRunningMsg);
|
|
428
594
|
if (shouldOpen) details.open = true;
|
|
595
|
+
if (anyFailed && !anyRunning) details.classList.add('clado-tool-trace-err');
|
|
429
596
|
details.addEventListener('toggle', () => {
|
|
430
597
|
traceOpenState.set(msgKey, details.open);
|
|
431
598
|
});
|
|
@@ -435,7 +602,9 @@
|
|
|
435
602
|
const namesPreview = [...new Set(tools.map(t => t.name).filter(Boolean))].slice(0, 3).join(' · ');
|
|
436
603
|
const label = anyRunning
|
|
437
604
|
? `正在执行 ${currentTool?.name || '工具'}${currentTool?.argsSummary ? ' · ' + currentTool.argsSummary : ''} (${doneCount}/${tools.length})`
|
|
438
|
-
:
|
|
605
|
+
: anyFailed
|
|
606
|
+
? `工具调用 (${tools.length} · ${failedCount} 项失败) · ${namesPreview}`
|
|
607
|
+
: `工具调用 (${tools.length}) · ${namesPreview}`;
|
|
439
608
|
|
|
440
609
|
const summary = document.createElement('summary');
|
|
441
610
|
summary.innerHTML = `
|
|
@@ -453,30 +622,103 @@
|
|
|
453
622
|
|
|
454
623
|
const list = document.createElement('div');
|
|
455
624
|
list.className = 'clado-tool-list';
|
|
625
|
+
const CANVAS_TOOLS = new Set(['clado_create', 'clado_update', 'clado_nodes', 'clado_links', 'clado_graph', 'clado_read']);
|
|
626
|
+
const CODE_TOOLS = new Set(['edit', 'write', 'read']);
|
|
456
627
|
for (const t of tools) {
|
|
628
|
+
const isErr = t.status === 'failed' || t.isError;
|
|
457
629
|
const step = document.createElement('div');
|
|
458
|
-
|
|
459
|
-
const
|
|
460
|
-
const
|
|
630
|
+
const isCanvasTool = CANVAS_TOOLS.has(t.name) && t.argsSummary;
|
|
631
|
+
const isCodeTool = CODE_TOOLS.has(t.name) && t.argsSummary && !/\.mdc?$/i.test(t.argsSummary);
|
|
632
|
+
const clickable = isCanvasTool || isCodeTool;
|
|
633
|
+
step.className = 'clado-tool-step' + (isErr ? ' clado-tool-step-err' : '') + (clickable ? ' is-clickable' : '');
|
|
634
|
+
if (isCodeTool) step.title = '点击在右侧代码抽屉查看 ' + t.argsSummary;
|
|
635
|
+
else if (isCanvasTool) step.title = '点击在画布定位 ' + t.argsSummary;
|
|
636
|
+
const stepDot = t.status === 'running' ? 'clado-dot-pulse' : (isErr ? 'clado-dot-err' : 'clado-dot-ok');
|
|
637
|
+
const statusTxt = t.status === 'running' ? '执行中' : (isErr ? '失败' : '完成');
|
|
638
|
+
const statusCls = isErr ? 'clado-tool-status-err' : 'clado-tool-status-muted';
|
|
461
639
|
step.innerHTML = `
|
|
462
640
|
<div class="clado-tool-step-head">
|
|
463
641
|
<span class="${stepDot}"></span>
|
|
464
642
|
<span class="clado-tool-name">${esc(t.name || 'tool')}</span>
|
|
465
643
|
<span class="clado-tool-args" title="${esc(t.argsSummary || '')}">${esc(t.argsSummary || '')}</span>
|
|
466
|
-
<span
|
|
644
|
+
<span class="${statusCls}">${statusTxt}</span>
|
|
467
645
|
</div>
|
|
468
646
|
${t.resultPreview ? `<div class="clado-tool-preview clado-scroll">${esc(t.resultPreview)}</div>` : ''}
|
|
469
647
|
`;
|
|
648
|
+
if (clickable) {
|
|
649
|
+
step.onclick = () => {
|
|
650
|
+
if (isCodeTool) {
|
|
651
|
+
actions.openCodeFile?.(t.argsSummary);
|
|
652
|
+
} else if (isCanvasTool) {
|
|
653
|
+
if (/\.mdc?$/i.test(t.argsSummary)) actions.focusCanvas?.(t.argsSummary, '');
|
|
654
|
+
else actions.focusCanvas?.(null, t.argsSummary);
|
|
655
|
+
}
|
|
656
|
+
};
|
|
657
|
+
}
|
|
470
658
|
list.append(step);
|
|
471
659
|
}
|
|
472
660
|
details.append(list);
|
|
473
661
|
return details;
|
|
474
662
|
}
|
|
475
663
|
|
|
664
|
+
function dismissPendingQuestions(session) {
|
|
665
|
+
if (!session || !Array.isArray(session.messages)) return false;
|
|
666
|
+
let changed = false;
|
|
667
|
+
for (const m of session.messages) {
|
|
668
|
+
if (Array.isArray(m.questions)) {
|
|
669
|
+
for (const q of m.questions) {
|
|
670
|
+
if (q && !q.answered && !q.dismissed) {
|
|
671
|
+
q.dismissed = true;
|
|
672
|
+
changed = true;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
if (m.question && !m.question.answered && !m.question.dismissed) {
|
|
677
|
+
m.question.dismissed = true;
|
|
678
|
+
changed = true;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
return changed;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function getActivePendingQuestion(session) {
|
|
685
|
+
if (!session || session.status !== 'running' || !Array.isArray(session.messages) || !session.messages.length) return null;
|
|
686
|
+
const last = session.messages[session.messages.length - 1];
|
|
687
|
+
if (!last || last.role !== 'assistant') return null;
|
|
688
|
+
if (Array.isArray(last.questions)) {
|
|
689
|
+
for (let i = last.questions.length - 1; i >= 0; i--) {
|
|
690
|
+
const q = last.questions[i];
|
|
691
|
+
if (q && !q.answered && !q.dismissed) return q;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
if (last.question && !last.question.answered && !last.question.dismissed) return last.question;
|
|
695
|
+
return null;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
async function submitQuestionAnswer(sessionId, q, answerText) {
|
|
699
|
+
const ans = String(answerText || '').trim();
|
|
700
|
+
if (!ans || !q || q.answered || q.dismissed) return false;
|
|
701
|
+
q.answered = true;
|
|
702
|
+
q.answer = ans;
|
|
703
|
+
renderStream();
|
|
704
|
+
try {
|
|
705
|
+
await fetch(withWs('/library/agent'), {
|
|
706
|
+
method: 'POST',
|
|
707
|
+
headers: { 'content-type': 'application/json' },
|
|
708
|
+
body: JSON.stringify({ action: 'answer', session: sessionId, questionId: q.questionId, answer: ans }),
|
|
709
|
+
});
|
|
710
|
+
showToast('已确认:' + (ans.length > 28 ? ans.slice(0, 28) + '…' : ans));
|
|
711
|
+
return true;
|
|
712
|
+
} catch {
|
|
713
|
+
showToast('回答提交失败,请重试');
|
|
714
|
+
return false;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
476
718
|
function buildDecisionCard(sessionId, q) {
|
|
477
719
|
const box = document.createElement('div');
|
|
478
720
|
box.className = 'clado-decision-card';
|
|
479
|
-
box.innerHTML = `<div class="clado-decision-q">${esc(q.question)}</div><div class="clado-decision-opts"></div>`;
|
|
721
|
+
box.innerHTML = `<div class="clado-decision-q">${esc(q.question)}</div><div class="clado-decision-opts"></div><div class="clado-decision-custom"><input type="text" class="clado-decision-input" placeholder="或直接输入你的自定义回答(回车提交)…" /><button type="button" class="clado-ui-button clado-decision-submit">回答</button></div>`;
|
|
480
722
|
const optsWrap = box.querySelector('.clado-decision-opts');
|
|
481
723
|
const opts = Array.isArray(q.options) && q.options.length ? q.options : [{ id: 'confirm', label: '确认继续' }];
|
|
482
724
|
for (let i = 0; i < opts.length; i++) {
|
|
@@ -486,23 +728,108 @@
|
|
|
486
728
|
btn.className = 'clado-ui-button ' + (i === 0 ? 'clado-ui-button-primary' : '');
|
|
487
729
|
btn.style.cssText = 'min-height:28px;padding:4px 12px;font-size:11.5px;' + (i > 0 ? 'border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);color:var(--clado-ui-text);' : '');
|
|
488
730
|
btn.textContent = opt.label;
|
|
489
|
-
btn.onclick =
|
|
490
|
-
q.answered = true;
|
|
491
|
-
q.answer = opt.label;
|
|
492
|
-
renderStream();
|
|
493
|
-
await fetch(withWs('/library/agent'), {
|
|
494
|
-
method: 'POST',
|
|
495
|
-
headers: { 'content-type': 'application/json' },
|
|
496
|
-
body: JSON.stringify({ action: 'answer', session: sessionId, questionId: q.questionId, answer: opt.label }),
|
|
497
|
-
});
|
|
498
|
-
showToast('已确认:' + opt.label);
|
|
499
|
-
};
|
|
731
|
+
btn.onclick = () => submitQuestionAnswer(sessionId, q, opt.label);
|
|
500
732
|
optsWrap.append(btn);
|
|
501
733
|
}
|
|
734
|
+
const customInput = box.querySelector('.clado-decision-input');
|
|
735
|
+
const customBtn = box.querySelector('.clado-decision-submit');
|
|
736
|
+
const submitCustom = () => {
|
|
737
|
+
const val = customInput.value.trim();
|
|
738
|
+
if (!val) {
|
|
739
|
+
customInput.focus();
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
submitQuestionAnswer(sessionId, q, val);
|
|
743
|
+
};
|
|
744
|
+
customBtn.onclick = submitCustom;
|
|
745
|
+
customInput.addEventListener('keydown', e => {
|
|
746
|
+
if (e.key === 'Enter' && !e.isComposing) {
|
|
747
|
+
e.preventDefault();
|
|
748
|
+
e.stopPropagation();
|
|
749
|
+
submitCustom();
|
|
750
|
+
}
|
|
751
|
+
});
|
|
502
752
|
return box;
|
|
503
753
|
}
|
|
504
754
|
|
|
755
|
+
function formatTokenCount(n) {
|
|
756
|
+
const v = Number(n) || 0;
|
|
757
|
+
if (v >= 1_000_000) {
|
|
758
|
+
const m = v / 1_000_000;
|
|
759
|
+
return (m >= 10 || Math.abs(m - Math.round(m)) < 0.05 ? Math.round(m) : m.toFixed(1)) + 'M';
|
|
760
|
+
}
|
|
761
|
+
if (v >= 1000) {
|
|
762
|
+
const k = v / 1000;
|
|
763
|
+
return (k >= 100 ? Math.round(k) : k.toFixed(1)) + 'K';
|
|
764
|
+
}
|
|
765
|
+
return String(Math.round(v));
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function resolveContextSnapshot(session) {
|
|
769
|
+
const s = session || currentSession();
|
|
770
|
+
const rt = meta?.runtimeSettings || {};
|
|
771
|
+
const modelSpec = s?.model || (meta?.defaultProvider && meta?.defaultModel ? `${meta.defaultProvider}/${meta.defaultModel}` : '');
|
|
772
|
+
const matchedModel = (meta?.configuredModels || []).find(m => m.id === modelSpec || m.model === modelSpec);
|
|
773
|
+
const fallbackTotal = matchedModel?.contextWindow || meta?.activeContextWindow || 128000;
|
|
774
|
+
const u = s?.contextUsage;
|
|
775
|
+
const contextWindow = u?.contextWindow || fallbackTotal;
|
|
776
|
+
const tokens = typeof u?.tokens === 'number' ? u.tokens : 0;
|
|
777
|
+
const usedPercent = typeof u?.usedPercent === 'number'
|
|
778
|
+
? Math.min(100, Math.max(0, u.usedPercent))
|
|
779
|
+
: Math.min(100, Math.max(0, Number(((tokens / Math.max(1, contextWindow)) * 100).toFixed(1))));
|
|
780
|
+
const remainingTokens = typeof u?.remainingTokens === 'number'
|
|
781
|
+
? u.remainingTokens
|
|
782
|
+
: Math.max(0, contextWindow - tokens);
|
|
783
|
+
const remainingPercent = typeof u?.remainingPercent === 'number'
|
|
784
|
+
? Math.max(0, Math.min(100, u.remainingPercent))
|
|
785
|
+
: Number(Math.max(0, 100 - usedPercent).toFixed(1));
|
|
786
|
+
return {
|
|
787
|
+
tokens,
|
|
788
|
+
contextWindow,
|
|
789
|
+
maxTokens: u?.maxTokens || matchedModel?.maxTokens || meta?.activeMaxTokens || 16384,
|
|
790
|
+
remainingTokens,
|
|
791
|
+
usedPercent,
|
|
792
|
+
remainingPercent,
|
|
793
|
+
compactionEnabled: rt.compactionEnabled !== false,
|
|
794
|
+
compactAtPercent: rt.compactionTriggerPercent || u?.compactAtPercent || 85,
|
|
795
|
+
keepRecentTokens: rt.keepRecentTokens || u?.keepRecentTokens || 20000,
|
|
796
|
+
thinkingLevel: rt.thinkingLevel || u?.thinkingLevel || 'medium',
|
|
797
|
+
transport: rt.transport || u?.transport || 'auto',
|
|
798
|
+
cost: u?.cost || 0,
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function renderContextMeter() {
|
|
803
|
+
if (!ctxMeterBtn) return;
|
|
804
|
+
const snap = resolveContextSnapshot();
|
|
805
|
+
const fill = ctxMeterBtn.querySelector('.clado-ctx-meter-fill');
|
|
806
|
+
const txt = ctxMeterBtn.querySelector('[data-ctx-meter-txt]');
|
|
807
|
+
const pct = Math.max(0, Math.min(100, snap.usedPercent));
|
|
808
|
+
if (fill) fill.style.width = pct + '%';
|
|
809
|
+
ctxMeterBtn.classList.toggle('is-warn', pct >= 65 && pct < snap.compactAtPercent);
|
|
810
|
+
ctxMeterBtn.classList.toggle('is-danger', pct >= snap.compactAtPercent);
|
|
811
|
+
if (txt) {
|
|
812
|
+
txt.textContent = snap.tokens > 0
|
|
813
|
+
? `${formatTokenCount(snap.tokens)}/${formatTokenCount(snap.contextWindow)} · 剩${Math.round(snap.remainingPercent)}%`
|
|
814
|
+
: `${formatTokenCount(snap.contextWindow)} · 剩100%`;
|
|
815
|
+
}
|
|
816
|
+
ctxMeterBtn.title = `上下文:已用 ${snap.tokens.toLocaleString()} / 总计 ${snap.contextWindow.toLocaleString()} tokens(剩余 ${snap.remainingTokens.toLocaleString()},${snap.remainingPercent}%)· 思考:${snap.thinkingLevel} · 自动压缩:${snap.compactionEnabled ? snap.compactAtPercent + '%' : '关闭'}(点击查看与调整)`;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
let renderStreamTimer = 0;
|
|
820
|
+
function scheduleRenderStream() {
|
|
821
|
+
if (renderStreamTimer) return;
|
|
822
|
+
renderStreamTimer = setTimeout(() => {
|
|
823
|
+
renderStreamTimer = 0;
|
|
824
|
+
requestAnimationFrame(() => renderStream());
|
|
825
|
+
}, 48);
|
|
826
|
+
}
|
|
827
|
+
|
|
505
828
|
function renderStream() {
|
|
829
|
+
if (renderStreamTimer) {
|
|
830
|
+
clearTimeout(renderStreamTimer);
|
|
831
|
+
renderStreamTimer = 0;
|
|
832
|
+
}
|
|
506
833
|
const s = currentSession();
|
|
507
834
|
if (!s) return;
|
|
508
835
|
roleTitleEl.textContent = s.title || '主架构师';
|
|
@@ -511,6 +838,7 @@
|
|
|
511
838
|
|
|
512
839
|
const modelLabel = s.model || meta?.activeModelLabel || '配置模型';
|
|
513
840
|
modelChip.textContent = (modelLabel.includes('/') ? modelLabel.split('/').pop() : modelLabel) + ' ▾';
|
|
841
|
+
renderContextMeter();
|
|
514
842
|
|
|
515
843
|
const wasNearBottom = (streamEl.scrollHeight - streamEl.scrollTop - streamEl.clientHeight) < 60;
|
|
516
844
|
|
|
@@ -519,7 +847,7 @@
|
|
|
519
847
|
if (!msgs.length) {
|
|
520
848
|
const empty = document.createElement('div');
|
|
521
849
|
empty.className = 'clado-dock-empty';
|
|
522
|
-
empty.innerHTML = `当前会话:<strong>${esc(s.title)}</strong>(Pi 1.0 引擎)<br/>可直接描述架构修改、输入 <code>/</code> 调命令,或在画布选中卡片派活交付。<br
|
|
850
|
+
empty.innerHTML = `当前会话:<strong>${esc(s.title)}</strong>(Pi 1.0 引擎)<br/>可直接描述架构修改、输入 <code>/</code> 调命令,或在画布选中卡片派活交付。<br/>拖动顶部居中横条可调整窗口高度,点击标题可切换或新建会话。`;
|
|
523
851
|
streamEl.append(empty);
|
|
524
852
|
return;
|
|
525
853
|
}
|
|
@@ -531,28 +859,46 @@
|
|
|
531
859
|
const isLast = idx === msgs.length - 1;
|
|
532
860
|
if (m.role === 'user') {
|
|
533
861
|
const div = document.createElement('div');
|
|
534
|
-
div.className = 'clado-msg-user';
|
|
535
|
-
const prefix = m.handoffFrom ? `[交接自 ${m.handoffFrom}]\n` : '';
|
|
862
|
+
div.className = 'clado-msg-user' + (m.isSteer ? ' is-steer' : '');
|
|
863
|
+
const prefix = m.isSteer ? '[中途纠偏] ' : (m.handoffFrom ? `[交接自 ${m.handoffFrom}]\n` : '');
|
|
536
864
|
div.textContent = prefix + (m.text || '');
|
|
537
865
|
streamEl.append(div);
|
|
538
866
|
} else {
|
|
539
867
|
const msgKey = m.id || `${s.id}_${idx}`;
|
|
540
868
|
const isRunningMsg = isLast && s.status === 'running';
|
|
541
869
|
|
|
542
|
-
// 1.
|
|
543
|
-
if (Array.isArray(m.
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
870
|
+
// 1. Render ordered interleaved blocks (thinking -> text -> tools -> text -> ...)
|
|
871
|
+
if (Array.isArray(m.blocks) && m.blocks.length) {
|
|
872
|
+
for (let bIdx = 0; bIdx < m.blocks.length; bIdx++) {
|
|
873
|
+
const block = m.blocks[bIdx];
|
|
874
|
+
const isLastBlock = bIdx === m.blocks.length - 1;
|
|
875
|
+
if (block?.type === 'thinking' && block.text && block.text.trim()) {
|
|
876
|
+
streamEl.append(buildThinkingTrace(`${msgKey}_th${bIdx}`, block.text));
|
|
877
|
+
} else if (block?.type === 'tools' && Array.isArray(block.tools) && block.tools.length) {
|
|
878
|
+
streamEl.append(buildToolTrace(`${msgKey}_b${bIdx}`, block.tools, isRunningMsg && isLastBlock));
|
|
879
|
+
} else if (block?.type === 'text' && block.text && block.text.trim()) {
|
|
880
|
+
const div = document.createElement('div');
|
|
881
|
+
div.className = 'clado-msg-assistant clado-md';
|
|
882
|
+
div.innerHTML = renderMarkdown(block.text);
|
|
883
|
+
decorateCanvasRefs(div);
|
|
884
|
+
streamEl.append(div);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
} else {
|
|
888
|
+
// Backward-compatible fallback for older persisted sessions without blocks
|
|
889
|
+
if (Array.isArray(m.tools) && m.tools.length) {
|
|
890
|
+
streamEl.append(buildToolTrace(msgKey, m.tools, isRunningMsg));
|
|
891
|
+
}
|
|
892
|
+
if (m.text) {
|
|
893
|
+
const div = document.createElement('div');
|
|
894
|
+
div.className = 'clado-msg-assistant clado-md';
|
|
895
|
+
div.innerHTML = renderMarkdown(m.text);
|
|
896
|
+
decorateCanvasRefs(div);
|
|
897
|
+
streamEl.append(div);
|
|
898
|
+
}
|
|
553
899
|
}
|
|
554
900
|
|
|
555
|
-
//
|
|
901
|
+
// 2. Collect questions: answered ones show as compact receipt pill; unanswered ones ONLY show while this turn is actively running
|
|
556
902
|
const qList = [];
|
|
557
903
|
if (Array.isArray(m.questions)) qList.push(...m.questions);
|
|
558
904
|
if (m.question && !qList.some(q => q.questionId === m.question.questionId)) qList.push(m.question);
|
|
@@ -563,12 +909,12 @@
|
|
|
563
909
|
donePill.className = 'clado-decision-done';
|
|
564
910
|
donePill.textContent = '已确认:' + (q.answer || q.question);
|
|
565
911
|
streamEl.append(donePill);
|
|
566
|
-
} else {
|
|
912
|
+
} else if (isRunningMsg && !q.dismissed) {
|
|
567
913
|
pendingDecisionCards.push(q);
|
|
568
914
|
}
|
|
569
915
|
}
|
|
570
916
|
|
|
571
|
-
//
|
|
917
|
+
// 3. Live activity status pill while running
|
|
572
918
|
if (isRunningMsg) {
|
|
573
919
|
const act = document.createElement('div');
|
|
574
920
|
act.className = 'clado-live-activity';
|
|
@@ -578,18 +924,32 @@
|
|
|
578
924
|
}
|
|
579
925
|
}
|
|
580
926
|
|
|
581
|
-
//
|
|
927
|
+
// 4. Pending ask_user decision cards ALWAYS render at the very bottom (only while running)
|
|
582
928
|
for (const q of pendingDecisionCards) {
|
|
583
929
|
streamEl.append(buildDecisionCard(s.id, q));
|
|
584
930
|
}
|
|
585
931
|
|
|
932
|
+
if (runningSessionId === s.id) {
|
|
933
|
+
sendBtn.textContent = pendingDecisionCards.length ? '回复' : '插话';
|
|
934
|
+
}
|
|
935
|
+
|
|
586
936
|
if (wasNearBottom || s.status === 'running' || pendingDecisionCards.length) {
|
|
587
937
|
streamEl.scrollTop = streamEl.scrollHeight;
|
|
588
938
|
}
|
|
589
939
|
}
|
|
590
940
|
|
|
591
|
-
// Copy code button delegation inside stream
|
|
941
|
+
// Copy code button & clickable card/tag chip delegation inside stream
|
|
592
942
|
streamEl.addEventListener('click', e => {
|
|
943
|
+
const refTag = e.target.closest?.('[data-ref-tag]');
|
|
944
|
+
if (refTag) {
|
|
945
|
+
actions.focusTag?.(refTag.dataset.refTag);
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
const refCard = e.target.closest?.('[data-ref-card]');
|
|
949
|
+
if (refCard) {
|
|
950
|
+
actions.focusCanvas?.(null, refCard.dataset.refCard);
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
593
953
|
const btn = e.target.closest?.('[data-copy-code]');
|
|
594
954
|
if (!btn) return;
|
|
595
955
|
const code = btn.closest('.clado-md-pre')?.querySelector('pre code')?.textContent || '';
|
|
@@ -809,6 +1169,117 @@
|
|
|
809
1169
|
popoverEl.hidden = false;
|
|
810
1170
|
}
|
|
811
1171
|
|
|
1172
|
+
function openContextPopover() {
|
|
1173
|
+
popoverEl.replaceChildren();
|
|
1174
|
+
const s = currentSession();
|
|
1175
|
+
const snap = resolveContextSnapshot(s);
|
|
1176
|
+
const barColor = snap.usedPercent >= snap.compactAtPercent
|
|
1177
|
+
? '#ef4444'
|
|
1178
|
+
: (snap.usedPercent >= 65 ? '#f59e0b' : '#10b981');
|
|
1179
|
+
const THINK_LABELS = [
|
|
1180
|
+
['off', '关闭'],
|
|
1181
|
+
['low', '低'],
|
|
1182
|
+
['medium', '中'],
|
|
1183
|
+
['high', '高'],
|
|
1184
|
+
['xhigh', '极高'],
|
|
1185
|
+
['max', '极限'],
|
|
1186
|
+
];
|
|
1187
|
+
const TRANS_LABELS = [
|
|
1188
|
+
['auto', '自动流式'],
|
|
1189
|
+
['sse', 'SSE 流式'],
|
|
1190
|
+
['websocket', 'WebSocket'],
|
|
1191
|
+
];
|
|
1192
|
+
|
|
1193
|
+
const card = document.createElement('div');
|
|
1194
|
+
card.className = 'clado-ctx-pop-card';
|
|
1195
|
+
card.innerHTML = `
|
|
1196
|
+
<div class="clado-ctx-pop-head">
|
|
1197
|
+
<strong>上下文窗口与运行参数</strong>
|
|
1198
|
+
<span style="font-family:ui-monospace,monospace;font-size:11px;color:var(--clado-ui-muted);">已用 ${snap.usedPercent}% · 剩 ${snap.remainingPercent}%</span>
|
|
1199
|
+
</div>
|
|
1200
|
+
<div class="clado-ctx-pop-bar"><i style="width:${Math.min(100, snap.usedPercent)}%;background:${barColor};"></i></div>
|
|
1201
|
+
<div class="clado-ctx-pop-stats">
|
|
1202
|
+
<div class="clado-ctx-stat"><div class="clado-ctx-stat-k">已用</div><div class="clado-ctx-stat-v">${esc(formatTokenCount(snap.tokens))}</div></div>
|
|
1203
|
+
<div class="clado-ctx-stat"><div class="clado-ctx-stat-k">剩余</div><div class="clado-ctx-stat-v">${esc(formatTokenCount(snap.remainingTokens))}</div></div>
|
|
1204
|
+
<div class="clado-ctx-stat"><div class="clado-ctx-stat-k">总容量</div><div class="clado-ctx-stat-v">${esc(formatTokenCount(snap.contextWindow))}</div></div>
|
|
1205
|
+
</div>
|
|
1206
|
+
<div style="font-size:11px;color:var(--clado-ui-subtle);">
|
|
1207
|
+
自动压缩:${snap.compactionEnabled ? `开启(达到 <strong>${snap.compactAtPercent}%</strong> 触发,保留最近 ${formatTokenCount(snap.keepRecentTokens)})` : '已关闭'} · 最大输出 ${formatTokenCount(snap.maxTokens)}
|
|
1208
|
+
</div>
|
|
1209
|
+
<div>
|
|
1210
|
+
<div style="font-size:10.5px;color:var(--clado-ui-subtle);margin-bottom:4px;">思考强度(Reasoning Effort)</div>
|
|
1211
|
+
<div class="clado-ctx-pills" data-quick-think>
|
|
1212
|
+
${THINK_LABELS.map(([id, label]) => `<button type="button" class="clado-ctx-pill-btn ${snap.thinkingLevel === id ? 'active' : ''}" data-think="${id}">${label}</button>`).join('')}
|
|
1213
|
+
</div>
|
|
1214
|
+
</div>
|
|
1215
|
+
<div>
|
|
1216
|
+
<div style="font-size:10.5px;color:var(--clado-ui-subtle);margin-bottom:4px;">流式传输方式</div>
|
|
1217
|
+
<div class="clado-ctx-pills" data-quick-trans>
|
|
1218
|
+
${TRANS_LABELS.map(([id, label]) => `<button type="button" class="clado-ctx-pill-btn ${snap.transport === id ? 'active' : ''}" data-trans="${id}">${label}</button>`).join('')}
|
|
1219
|
+
</div>
|
|
1220
|
+
</div>
|
|
1221
|
+
<div style="display:flex;align-items:center;justify-content:space-between;gap:6px;padding-top:4px;border-top:1px solid var(--clado-ui-edge);">
|
|
1222
|
+
<button type="button" class="clado-ui-button" data-compact-now style="min-height:26px;padding:3px 10px;font-size:11px;border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);">立即压缩上下文</button>
|
|
1223
|
+
<button type="button" class="clado-ui-button clado-ui-button-primary" data-open-rt style="min-height:26px;padding:3px 10px;font-size:11px;">完整模型与压缩设置 →</button>
|
|
1224
|
+
</div>
|
|
1225
|
+
`;
|
|
1226
|
+
|
|
1227
|
+
card.querySelectorAll('[data-think]').forEach(btn => {
|
|
1228
|
+
btn.onclick = async e => {
|
|
1229
|
+
e.stopPropagation();
|
|
1230
|
+
try {
|
|
1231
|
+
await apiConfig({ action: 'save_runtime_settings', thinkingLevel: btn.dataset.think });
|
|
1232
|
+
renderContextMeter();
|
|
1233
|
+
openContextPopover();
|
|
1234
|
+
showToast('思考强度已切换为:' + btn.textContent);
|
|
1235
|
+
} catch (err) { showToast(err.message); }
|
|
1236
|
+
};
|
|
1237
|
+
});
|
|
1238
|
+
card.querySelectorAll('[data-trans]').forEach(btn => {
|
|
1239
|
+
btn.onclick = async e => {
|
|
1240
|
+
e.stopPropagation();
|
|
1241
|
+
try {
|
|
1242
|
+
await apiConfig({ action: 'save_runtime_settings', transport: btn.dataset.trans });
|
|
1243
|
+
renderContextMeter();
|
|
1244
|
+
openContextPopover();
|
|
1245
|
+
showToast('流式传输已切换为:' + btn.textContent);
|
|
1246
|
+
} catch (err) { showToast(err.message); }
|
|
1247
|
+
};
|
|
1248
|
+
});
|
|
1249
|
+
card.querySelector('[data-compact-now]').onclick = async e => {
|
|
1250
|
+
e.stopPropagation();
|
|
1251
|
+
if (!s) return;
|
|
1252
|
+
const btn = e.currentTarget;
|
|
1253
|
+
btn.disabled = true;
|
|
1254
|
+
btn.textContent = '压缩中…';
|
|
1255
|
+
try {
|
|
1256
|
+
const res = await fetch(withWs('/library/agent/sessions'), {
|
|
1257
|
+
method: 'POST',
|
|
1258
|
+
headers: { 'content-type': 'application/json' },
|
|
1259
|
+
body: JSON.stringify({ action: 'compact', id: s.id }),
|
|
1260
|
+
});
|
|
1261
|
+
const data = await res.json();
|
|
1262
|
+
if (!res.ok) throw new Error(data.error || '压缩失败');
|
|
1263
|
+
if (data.contextUsage) s.contextUsage = data.contextUsage;
|
|
1264
|
+
renderContextMeter();
|
|
1265
|
+
showToast(data.skipped ? (data.reason || '暂无历史需要压缩') : '上下文压缩完成');
|
|
1266
|
+
closePopover();
|
|
1267
|
+
} catch (err) {
|
|
1268
|
+
showToast(err.message || '压缩失败');
|
|
1269
|
+
btn.disabled = false;
|
|
1270
|
+
btn.textContent = '立即压缩上下文';
|
|
1271
|
+
}
|
|
1272
|
+
};
|
|
1273
|
+
card.querySelector('[data-open-rt]').onclick = e => {
|
|
1274
|
+
e.stopPropagation();
|
|
1275
|
+
closePopover();
|
|
1276
|
+
openSettings('models');
|
|
1277
|
+
};
|
|
1278
|
+
|
|
1279
|
+
popoverEl.append(card);
|
|
1280
|
+
popoverEl.hidden = false;
|
|
1281
|
+
}
|
|
1282
|
+
|
|
812
1283
|
function openNewRoleSessionPopover() {
|
|
813
1284
|
popoverEl.replaceChildren();
|
|
814
1285
|
const roles = meta?.roles || [];
|
|
@@ -888,13 +1359,18 @@
|
|
|
888
1359
|
role: 'assistant',
|
|
889
1360
|
text: '',
|
|
890
1361
|
tools: [],
|
|
1362
|
+
blocks: [],
|
|
891
1363
|
questions: [],
|
|
892
1364
|
activity: '正在思考并准备上下文…',
|
|
893
1365
|
};
|
|
894
1366
|
s.messages.push(userPromptMsg, liveAssistant);
|
|
895
1367
|
const localSnapshotMsgs = s.messages.slice();
|
|
896
1368
|
|
|
897
|
-
sendBtn.textContent = '
|
|
1369
|
+
sendBtn.textContent = '插话';
|
|
1370
|
+
stopBtn.hidden = false;
|
|
1371
|
+
stopBtn.disabled = false;
|
|
1372
|
+
stopBtn.textContent = '停止';
|
|
1373
|
+
syncSendModeUi();
|
|
898
1374
|
renderRoleStrip();
|
|
899
1375
|
renderStream();
|
|
900
1376
|
|
|
@@ -926,32 +1402,41 @@
|
|
|
926
1402
|
let ev;
|
|
927
1403
|
try { ev = JSON.parse(line); } catch { continue; }
|
|
928
1404
|
if (ev.type === 'thinking') {
|
|
1405
|
+
appendMessageThinking(liveAssistant, ev.text || '');
|
|
929
1406
|
liveAssistant.activity = '正在深度思考…';
|
|
930
|
-
|
|
1407
|
+
scheduleRenderStream();
|
|
931
1408
|
} else if (ev.type === 'text') {
|
|
932
|
-
liveAssistant
|
|
1409
|
+
appendMessageText(liveAssistant, ev.text || '');
|
|
933
1410
|
liveAssistant.activity = '正在生成回复…';
|
|
934
|
-
|
|
935
|
-
} else if (ev.type === '
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
1411
|
+
scheduleRenderStream();
|
|
1412
|
+
} else if (ev.type === 'usage' && ev.usage) {
|
|
1413
|
+
s.contextUsage = ev.usage;
|
|
1414
|
+
renderContextMeter();
|
|
1415
|
+
} else if (ev.type === 'model') {
|
|
1416
|
+
if (ev.contextWindow && !s.contextUsage) {
|
|
1417
|
+
s.contextUsage = {
|
|
1418
|
+
tokens: 0,
|
|
1419
|
+
contextWindow: ev.contextWindow,
|
|
1420
|
+
maxTokens: ev.maxTokens || 16384,
|
|
1421
|
+
remainingTokens: ev.contextWindow,
|
|
1422
|
+
usedPercent: 0,
|
|
1423
|
+
remainingPercent: 100,
|
|
1424
|
+
thinkingLevel: ev.thinkingLevel || meta?.runtimeSettings?.thinkingLevel || 'medium',
|
|
1425
|
+
transport: ev.transport || meta?.runtimeSettings?.transport || 'auto',
|
|
1426
|
+
compactionEnabled: meta?.runtimeSettings?.compactionEnabled !== false,
|
|
1427
|
+
compactAtPercent: meta?.runtimeSettings?.compactionTriggerPercent || 85,
|
|
1428
|
+
};
|
|
1429
|
+
renderContextMeter();
|
|
949
1430
|
}
|
|
1431
|
+
} else if (ev.type === 'tool') {
|
|
1432
|
+
const entry = upsertMessageTool(liveAssistant, ev);
|
|
950
1433
|
const stillRunning = [...liveAssistant.tools].reverse().find(t => t.status === 'running');
|
|
951
1434
|
if (stillRunning) {
|
|
952
1435
|
liveAssistant.activity = `正在执行 ${stillRunning.name}${stillRunning.argsSummary ? ' · ' + stillRunning.argsSummary : ''}`;
|
|
1436
|
+
} else if (entry.status === 'failed' || entry.isError) {
|
|
1437
|
+
liveAssistant.activity = `${entry.name || '工具'} 执行失败,正在诊断并修复…`;
|
|
953
1438
|
} else {
|
|
954
|
-
liveAssistant.activity = '
|
|
1439
|
+
liveAssistant.activity = '工具执行完成,正在继续…';
|
|
955
1440
|
}
|
|
956
1441
|
renderStream();
|
|
957
1442
|
} else if (ev.type === 'ask_user') {
|
|
@@ -973,14 +1458,17 @@
|
|
|
973
1458
|
showToast(ev.text);
|
|
974
1459
|
renderStream();
|
|
975
1460
|
} else if (ev.type === 'done') {
|
|
1461
|
+
if (ev.usage) s.contextUsage = ev.usage;
|
|
976
1462
|
if (ev.stopped && !liveAssistant.text.includes('已手动停止')) {
|
|
977
|
-
|
|
1463
|
+
appendMessageText(liveAssistant, '_(已手动停止,以上内容已保留)_');
|
|
978
1464
|
}
|
|
979
1465
|
liveAssistant.activity = '';
|
|
1466
|
+
dismissPendingQuestions(s);
|
|
980
1467
|
renderStream();
|
|
981
1468
|
} else if (ev.type === 'error') {
|
|
982
|
-
|
|
1469
|
+
appendMessageText(liveAssistant, '提示:' + (ev.message || '执行失败'));
|
|
983
1470
|
liveAssistant.activity = '';
|
|
1471
|
+
dismissPendingQuestions(s);
|
|
984
1472
|
renderStream();
|
|
985
1473
|
}
|
|
986
1474
|
}
|
|
@@ -988,11 +1476,13 @@
|
|
|
988
1476
|
} catch (err) {
|
|
989
1477
|
if (err.name === 'AbortError' || stoppingTurn) {
|
|
990
1478
|
if (!liveAssistant.text.includes('已手动停止')) {
|
|
991
|
-
|
|
1479
|
+
appendMessageText(liveAssistant, '_(已手动停止,以上内容已保留)_');
|
|
992
1480
|
}
|
|
1481
|
+
dismissPendingQuestions(s);
|
|
993
1482
|
renderStream();
|
|
994
1483
|
} else {
|
|
995
|
-
|
|
1484
|
+
appendMessageText(liveAssistant, err.message || '执行中断');
|
|
1485
|
+
dismissPendingQuestions(s);
|
|
996
1486
|
renderStream();
|
|
997
1487
|
}
|
|
998
1488
|
} finally {
|
|
@@ -1001,12 +1491,17 @@
|
|
|
1001
1491
|
}
|
|
1002
1492
|
s.status = 'idle';
|
|
1003
1493
|
liveAssistant.activity = '';
|
|
1494
|
+
dismissPendingQuestions(s);
|
|
1004
1495
|
runningSessionId = '';
|
|
1005
1496
|
activeAbort = null;
|
|
1006
1497
|
stoppingTurn = false;
|
|
1007
1498
|
pendingCancelPromise = null;
|
|
1008
1499
|
sendBtn.textContent = '发送';
|
|
1009
1500
|
sendBtn.disabled = false;
|
|
1501
|
+
stopBtn.hidden = true;
|
|
1502
|
+
stopBtn.disabled = false;
|
|
1503
|
+
stopBtn.textContent = '停止';
|
|
1504
|
+
syncSendModeUi();
|
|
1010
1505
|
|
|
1011
1506
|
// Sync from server, but NEVER lose local messages if server hasn't flushed yet
|
|
1012
1507
|
const prevCount = localSnapshotMsgs.length;
|
|
@@ -1015,6 +1510,7 @@
|
|
|
1015
1510
|
const synced = sessions.find(x => x.id === s.id);
|
|
1016
1511
|
if (synced && (!Array.isArray(synced.messages) || synced.messages.length < prevCount)) {
|
|
1017
1512
|
synced.messages = localSnapshotMsgs;
|
|
1513
|
+
dismissPendingQuestions(synced);
|
|
1018
1514
|
renderStream();
|
|
1019
1515
|
}
|
|
1020
1516
|
} else {
|
|
@@ -1024,43 +1520,95 @@
|
|
|
1024
1520
|
}
|
|
1025
1521
|
}
|
|
1026
1522
|
|
|
1523
|
+
async function handleStop() {
|
|
1524
|
+
if (!runningSessionId || stoppingTurn) return;
|
|
1525
|
+
stoppingTurn = true;
|
|
1526
|
+
stopBtn.textContent = '停止中…';
|
|
1527
|
+
stopBtn.disabled = true;
|
|
1528
|
+
const targetId = runningSessionId;
|
|
1529
|
+
const s = sessions.find(x => x.id === targetId);
|
|
1530
|
+
dismissPendingQuestions(s);
|
|
1531
|
+
const lastMsg = s?.messages?.[s.messages.length - 1];
|
|
1532
|
+
if (lastMsg && lastMsg.role === 'assistant') {
|
|
1533
|
+
lastMsg.activity = '正在停止并保留已生成内容…';
|
|
1534
|
+
renderStream();
|
|
1535
|
+
}
|
|
1536
|
+
pendingCancelPromise = fetch(withWs('/library/agent'), {
|
|
1537
|
+
method: 'POST',
|
|
1538
|
+
headers: { 'content-type': 'application/json' },
|
|
1539
|
+
body: JSON.stringify({ action: 'cancel', session: targetId }),
|
|
1540
|
+
}).catch(() => {});
|
|
1541
|
+
await pendingCancelPromise;
|
|
1542
|
+
setTimeout(() => {
|
|
1543
|
+
if (runningSessionId === targetId && activeAbort) {
|
|
1544
|
+
activeAbort.abort();
|
|
1545
|
+
}
|
|
1546
|
+
}, 1200);
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1027
1549
|
async function handleSend() {
|
|
1550
|
+
const text = inputEl.value.trim();
|
|
1028
1551
|
if (runningSessionId) {
|
|
1029
|
-
if (stoppingTurn) return;
|
|
1030
|
-
stoppingTurn = true;
|
|
1031
|
-
sendBtn.textContent = '停止中…';
|
|
1032
|
-
sendBtn.disabled = true;
|
|
1033
1552
|
const targetId = runningSessionId;
|
|
1034
|
-
const
|
|
1035
|
-
const
|
|
1036
|
-
if (
|
|
1037
|
-
|
|
1038
|
-
|
|
1553
|
+
const runningSession = sessions.find(x => x.id === targetId);
|
|
1554
|
+
const pendingQ = getActivePendingQuestion(runningSession);
|
|
1555
|
+
if (pendingQ) {
|
|
1556
|
+
if (!text) {
|
|
1557
|
+
showToast('请点击上方选项,或直接输入你的自定义回答后发送');
|
|
1558
|
+
inputEl.focus();
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
inputEl.value = '';
|
|
1562
|
+
autoGrowInput();
|
|
1563
|
+
closePopover();
|
|
1564
|
+
await submitQuestionAnswer(targetId, pendingQ, text);
|
|
1565
|
+
return;
|
|
1039
1566
|
}
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1567
|
+
if (!text) {
|
|
1568
|
+
showToast('输入内容可中途插话纠偏,或点击左侧「停止」中止执行');
|
|
1569
|
+
inputEl.focus();
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
inputEl.value = '';
|
|
1573
|
+
autoGrowInput();
|
|
1574
|
+
closePopover();
|
|
1575
|
+
try {
|
|
1576
|
+
const res = await fetch(withWs('/library/agent'), {
|
|
1577
|
+
method: 'POST',
|
|
1578
|
+
headers: { 'content-type': 'application/json' },
|
|
1579
|
+
body: JSON.stringify({ action: 'steer', session: targetId, text }),
|
|
1580
|
+
});
|
|
1581
|
+
if (!res.ok) throw new Error('插话失败');
|
|
1582
|
+
if (runningSession && Array.isArray(runningSession.messages)) {
|
|
1583
|
+
const insertAt = Math.max(0, runningSession.messages.length - 1);
|
|
1584
|
+
runningSession.messages.splice(insertAt, 0, {
|
|
1585
|
+
id: 'local_steer_' + Date.now(),
|
|
1586
|
+
role: 'user',
|
|
1587
|
+
text,
|
|
1588
|
+
isSteer: true,
|
|
1589
|
+
});
|
|
1590
|
+
renderStream();
|
|
1051
1591
|
}
|
|
1052
|
-
|
|
1592
|
+
showToast('已发送中途纠偏指令');
|
|
1593
|
+
} catch {
|
|
1594
|
+
showToast('当前回合暂不支持插话,可稍候或点击停止');
|
|
1595
|
+
}
|
|
1053
1596
|
return;
|
|
1054
1597
|
}
|
|
1055
1598
|
|
|
1056
|
-
const text = inputEl.value.trim();
|
|
1057
1599
|
if (!text) return;
|
|
1058
1600
|
inputEl.value = '';
|
|
1059
1601
|
autoGrowInput();
|
|
1060
1602
|
closePopover();
|
|
1061
1603
|
const s = currentSession();
|
|
1062
1604
|
if (!s) return;
|
|
1063
|
-
|
|
1605
|
+
dismissPendingQuestions(s);
|
|
1606
|
+
const canvas = actions.readContext ? (actions.readContext() || {}) : {};
|
|
1607
|
+
if (pinnedSnippet && pinnedSnippet.text) {
|
|
1608
|
+
canvas.textSnippet = { ...pinnedSnippet };
|
|
1609
|
+
pinnedSnippet = null;
|
|
1610
|
+
renderContextChips();
|
|
1611
|
+
}
|
|
1064
1612
|
await streamAgentRequest({
|
|
1065
1613
|
action: 'prompt',
|
|
1066
1614
|
session: s.id,
|
|
@@ -1136,6 +1684,14 @@
|
|
|
1136
1684
|
if (!popoverEl.hidden && popoverEl.dataset.kind === 'model') closePopover();
|
|
1137
1685
|
else { popoverEl.dataset.kind = 'model'; openModelPopover(); }
|
|
1138
1686
|
};
|
|
1687
|
+
if (ctxMeterBtn) {
|
|
1688
|
+
ctxMeterBtn.onclick = e => {
|
|
1689
|
+
e.stopPropagation();
|
|
1690
|
+
closeSessionPop();
|
|
1691
|
+
if (!popoverEl.hidden && popoverEl.dataset.kind === 'context') closePopover();
|
|
1692
|
+
else { popoverEl.dataset.kind = 'context'; openContextPopover(); }
|
|
1693
|
+
};
|
|
1694
|
+
}
|
|
1139
1695
|
sendModeBtn.onclick = e => {
|
|
1140
1696
|
e.stopPropagation();
|
|
1141
1697
|
sendMode = sendMode === 'ctrl-enter' ? 'enter' : 'ctrl-enter';
|
|
@@ -1143,6 +1699,7 @@
|
|
|
1143
1699
|
syncSendModeUi();
|
|
1144
1700
|
showToast(sendMode === 'ctrl-enter' ? '已切换:Enter 换行,Ctrl+Enter 发送' : '已切换:Enter 发送,Shift+Enter 换行');
|
|
1145
1701
|
};
|
|
1702
|
+
inputEl.addEventListener('focus', () => renderContextChips());
|
|
1146
1703
|
inputEl.addEventListener('input', () => {
|
|
1147
1704
|
autoGrowInput();
|
|
1148
1705
|
updateSlashPopover();
|
|
@@ -1169,6 +1726,26 @@
|
|
|
1169
1726
|
}
|
|
1170
1727
|
});
|
|
1171
1728
|
sendBtn.onclick = handleSend;
|
|
1729
|
+
stopBtn.onclick = handleStop;
|
|
1730
|
+
|
|
1731
|
+
window.addEventListener('clado:agent-prefill', ev => {
|
|
1732
|
+
const d = ev.detail || {};
|
|
1733
|
+
setDrawerOpen(true);
|
|
1734
|
+
if (d.selectedText) {
|
|
1735
|
+
pinnedSnippet = { file: d.file || '', node: d.node || null, text: d.selectedText };
|
|
1736
|
+
}
|
|
1737
|
+
renderContextChips();
|
|
1738
|
+
if (d.prompt) {
|
|
1739
|
+
inputEl.value = d.prompt;
|
|
1740
|
+
} else if (d.mode === 'edit' && d.selectedText) {
|
|
1741
|
+
inputEl.value = '请优化或重写我框选的这段内容,使其更清晰准确:';
|
|
1742
|
+
} else if (d.mode === 'ask' && d.selectedText) {
|
|
1743
|
+
inputEl.value = '请结合上下游卡片解释我框选的这段内容:';
|
|
1744
|
+
}
|
|
1745
|
+
autoGrowInput();
|
|
1746
|
+
inputEl.focus();
|
|
1747
|
+
inputEl.setSelectionRange?.(inputEl.value.length, inputEl.value.length);
|
|
1748
|
+
});
|
|
1172
1749
|
document.addEventListener('click', e => {
|
|
1173
1750
|
if (!dock.contains(e.target)) {
|
|
1174
1751
|
closePopover();
|
|
@@ -1249,35 +1826,164 @@
|
|
|
1249
1826
|
}
|
|
1250
1827
|
|
|
1251
1828
|
function renderModelsTab() {
|
|
1829
|
+
const rt = meta.runtimeSettings || {
|
|
1830
|
+
thinkingLevel: 'medium',
|
|
1831
|
+
transport: 'auto',
|
|
1832
|
+
hideThinkingBlock: false,
|
|
1833
|
+
compactionEnabled: true,
|
|
1834
|
+
compactionTriggerPercent: 85,
|
|
1835
|
+
keepRecentTokens: 20000,
|
|
1836
|
+
retryEnabled: true,
|
|
1837
|
+
maxRetries: 3,
|
|
1838
|
+
cacheWarming: 'off',
|
|
1839
|
+
};
|
|
1840
|
+
const activeCtx = meta.activeContextWindow || 128000;
|
|
1841
|
+
const calcReserve = pct => Math.max(4096, Math.round(activeCtx * (1 - pct / 100)));
|
|
1842
|
+
|
|
1252
1843
|
sBody.innerHTML = `
|
|
1253
1844
|
<div>
|
|
1254
1845
|
<div style="font-size:18px;font-weight:630;">模型与供应商</div>
|
|
1255
|
-
<div style="font-size:12.5px;color:var(--clado-ui-muted);margin-top:4px;">直写 Pi 原生 <code style="font-family:ui-monospace,monospace;">auth.json</code> 与 <code style="font-family:ui-monospace,monospace;">
|
|
1846
|
+
<div style="font-size:12.5px;color:var(--clado-ui-muted);margin-top:4px;">直写 Pi 原生 <code style="font-family:ui-monospace,monospace;">auth.json</code>、<code style="font-family:ui-monospace,monospace;">models.json</code> 与 <code style="font-family:ui-monospace,monospace;">settings.json</code>,统一配置官方模型、上下文压缩、思考强度与流式传输。</div>
|
|
1256
1847
|
</div>
|
|
1848
|
+
|
|
1849
|
+
<div class="clado-well-box" data-runtime-box style="display:flex;flex-direction:column;gap:12px;">
|
|
1850
|
+
<div class="clado-setting-row">
|
|
1851
|
+
<div>
|
|
1852
|
+
<div style="font-size:13.5px;font-weight:610;">运行参数与上下文策略</div>
|
|
1853
|
+
<div style="font-size:11.5px;color:var(--clado-ui-muted);margin-top:2px;">当前默认模型上下文上限:<strong>${esc(formatTokenCount(activeCtx))}</strong>(${activeCtx.toLocaleString()} tokens)</div>
|
|
1854
|
+
</div>
|
|
1855
|
+
<button type="button" class="clado-ui-button clado-ui-button-primary" data-rt-save style="min-height:28px;padding:4px 12px;font-size:12px;">保存运行参数</button>
|
|
1856
|
+
</div>
|
|
1857
|
+
|
|
1858
|
+
<div class="clado-rt-grid">
|
|
1859
|
+
<div class="clado-rt-field">
|
|
1860
|
+
<div class="clado-rt-label"><span>思考强度(Thinking Level)</span></div>
|
|
1861
|
+
<select class="clado-field" data-rt-think>
|
|
1862
|
+
<option value="off" ${rt.thinkingLevel === 'off' ? 'selected' : ''}>off · 关闭思考</option>
|
|
1863
|
+
<option value="minimal" ${rt.thinkingLevel === 'minimal' ? 'selected' : ''}>minimal · 极简思考</option>
|
|
1864
|
+
<option value="low" ${rt.thinkingLevel === 'low' ? 'selected' : ''}>low · 轻量思考</option>
|
|
1865
|
+
<option value="medium" ${rt.thinkingLevel === 'medium' ? 'selected' : ''}>medium · 均衡(默认)</option>
|
|
1866
|
+
<option value="high" ${rt.thinkingLevel === 'high' ? 'selected' : ''}>high · 深度思考</option>
|
|
1867
|
+
<option value="xhigh" ${rt.thinkingLevel === 'xhigh' ? 'selected' : ''}>xhigh · 超高强度</option>
|
|
1868
|
+
<option value="max" ${rt.thinkingLevel === 'max' ? 'selected' : ''}>max · 极限推理</option>
|
|
1869
|
+
</select>
|
|
1870
|
+
</div>
|
|
1871
|
+
<div class="clado-rt-field">
|
|
1872
|
+
<div class="clado-rt-label"><span>流式传输模式(Transport)</span></div>
|
|
1873
|
+
<select class="clado-field" data-rt-trans>
|
|
1874
|
+
<option value="auto" ${rt.transport === 'auto' ? 'selected' : ''}>auto · 自动流式(推荐)</option>
|
|
1875
|
+
<option value="sse" ${rt.transport === 'sse' ? 'selected' : ''}>sse · 强制 SSE 流式返回</option>
|
|
1876
|
+
<option value="websocket" ${rt.transport === 'websocket' ? 'selected' : ''}>websocket · WebSocket 持久流</option>
|
|
1877
|
+
<option value="websocket-cached" ${rt.transport === 'websocket-cached' ? 'selected' : ''}>websocket-cached · WS 缓存流</option>
|
|
1878
|
+
</select>
|
|
1879
|
+
</div>
|
|
1880
|
+
<div class="clado-rt-field">
|
|
1881
|
+
<div class="clado-rt-label">
|
|
1882
|
+
<span>自动压缩触发阈值</span>
|
|
1883
|
+
<span data-rt-pct-lbl style="font-family:ui-monospace,monospace;color:var(--clado-ui-text);">${rt.compactionTriggerPercent}%(约预留 ${formatTokenCount(calcReserve(rt.compactionTriggerPercent))})</span>
|
|
1884
|
+
</div>
|
|
1885
|
+
<input class="clado-field" data-rt-pct type="range" min="50" max="95" step="5" value="${rt.compactionTriggerPercent}" style="padding:4px 0;accent-color:var(--clado-ui-brand);" />
|
|
1886
|
+
</div>
|
|
1887
|
+
<div class="clado-rt-field">
|
|
1888
|
+
<div class="clado-rt-label"><span>压缩保留最近 Tokens</span></div>
|
|
1889
|
+
<input class="clado-field" data-rt-keep type="number" min="2048" max="256000" step="1024" value="${rt.keepRecentTokens}" />
|
|
1890
|
+
</div>
|
|
1891
|
+
<div class="clado-rt-field">
|
|
1892
|
+
<div class="clado-rt-label"><span>缓存预热策略(Cache Warming)</span></div>
|
|
1893
|
+
<select class="clado-field" data-rt-cache>
|
|
1894
|
+
<option value="off" ${rt.cacheWarming === 'off' ? 'selected' : ''}>off · 关闭(省费用)</option>
|
|
1895
|
+
<option value="streaming" ${rt.cacheWarming === 'streaming' ? 'selected' : ''}>streaming · 流式保活</option>
|
|
1896
|
+
<option value="idle" ${rt.cacheWarming === 'idle' ? 'selected' : ''}>idle · 空闲持续预热</option>
|
|
1897
|
+
</select>
|
|
1898
|
+
</div>
|
|
1899
|
+
<div class="clado-rt-field">
|
|
1900
|
+
<div class="clado-rt-label"><span>网络异常最大重试次数</span></div>
|
|
1901
|
+
<input class="clado-field" data-rt-retries type="number" min="0" max="10" step="1" value="${rt.maxRetries}" />
|
|
1902
|
+
</div>
|
|
1903
|
+
</div>
|
|
1904
|
+
|
|
1905
|
+
<div class="clado-rt-checks">
|
|
1906
|
+
<label><input type="checkbox" data-rt-comp-on ${rt.compactionEnabled ? 'checked' : ''} /> 启用自动上下文压缩</label>
|
|
1907
|
+
<label><input type="checkbox" data-rt-retry-on ${rt.retryEnabled ? 'checked' : ''} /> 启用网络波动自动重试</label>
|
|
1908
|
+
<label><input type="checkbox" data-rt-hide-think ${rt.hideThinkingBlock ? 'checked' : ''} /> 默认隐藏思考过程块</label>
|
|
1909
|
+
</div>
|
|
1910
|
+
</div>
|
|
1911
|
+
|
|
1257
1912
|
<div data-provider-list style="display:flex;flex-direction:column;gap:10px;"></div>
|
|
1258
1913
|
`;
|
|
1914
|
+
|
|
1915
|
+
const rtBox = sBody.querySelector('[data-runtime-box]');
|
|
1916
|
+
const pctInput = rtBox.querySelector('[data-rt-pct]');
|
|
1917
|
+
const pctLbl = rtBox.querySelector('[data-rt-pct-lbl]');
|
|
1918
|
+
pctInput.addEventListener('input', () => {
|
|
1919
|
+
const v = Number(pctInput.value) || 85;
|
|
1920
|
+
pctLbl.textContent = `${v}%(约预留 ${formatTokenCount(calcReserve(v))})`;
|
|
1921
|
+
});
|
|
1922
|
+
rtBox.querySelector('[data-rt-save]').onclick = async () => {
|
|
1923
|
+
try {
|
|
1924
|
+
await apiConfig({
|
|
1925
|
+
action: 'save_runtime_settings',
|
|
1926
|
+
thinkingLevel: rtBox.querySelector('[data-rt-think]').value,
|
|
1927
|
+
transport: rtBox.querySelector('[data-rt-trans]').value,
|
|
1928
|
+
compactionEnabled: rtBox.querySelector('[data-rt-comp-on]').checked,
|
|
1929
|
+
compactionTriggerPercent: Number(pctInput.value) || 85,
|
|
1930
|
+
keepRecentTokens: Number(rtBox.querySelector('[data-rt-keep]').value) || 20000,
|
|
1931
|
+
cacheWarming: rtBox.querySelector('[data-rt-cache]').value,
|
|
1932
|
+
retryEnabled: rtBox.querySelector('[data-rt-retry-on]').checked,
|
|
1933
|
+
maxRetries: Number(rtBox.querySelector('[data-rt-retries]').value) || 3,
|
|
1934
|
+
hideThinkingBlock: rtBox.querySelector('[data-rt-hide-think]').checked,
|
|
1935
|
+
});
|
|
1936
|
+
renderContextMeter();
|
|
1937
|
+
renderSettings();
|
|
1938
|
+
showToast('已保存运行参数并写入 Pi 原生 settings.json');
|
|
1939
|
+
} catch (e) { showToast(e.message); }
|
|
1940
|
+
};
|
|
1941
|
+
|
|
1259
1942
|
const list = sBody.querySelector('[data-provider-list]');
|
|
1260
1943
|
for (const p of meta.providers || []) {
|
|
1261
1944
|
const card = document.createElement('div');
|
|
1262
1945
|
card.className = 'clado-well-box';
|
|
1263
1946
|
const isEditing = editingProviderId === p.id;
|
|
1947
|
+
const recs = Array.isArray(p.recommendedModels) ? p.recommendedModels : [];
|
|
1264
1948
|
card.innerHTML = `
|
|
1265
1949
|
<div class="clado-setting-row">
|
|
1266
1950
|
<div>
|
|
1267
|
-
<div style="display:flex;align-items:center;gap:8px;">
|
|
1951
|
+
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
|
|
1268
1952
|
<span style="font-size:13.5px;font-weight:610;">${esc(p.name)}</span>
|
|
1269
1953
|
${p.configured ? `<span class="clado-chip clado-chip-mint">已连接${p.maskedKey ? ' · ' + esc(p.maskedKey) : ''}</span>` : '<span class="clado-chip clado-chip-neutral">未配置</span>'}
|
|
1270
1954
|
${meta.defaultProvider === p.id ? `<span class="clado-chip clado-chip-sky">默认 · ${esc(meta.defaultModel)}</span>` : ''}
|
|
1955
|
+
${p.contextWindow ? `<span class="clado-chip clado-chip-neutral">${esc(formatTokenCount(p.contextWindow))} 上下文</span>` : ''}
|
|
1271
1956
|
</div>
|
|
1272
1957
|
<div style="font-family:ui-monospace,monospace;font-size:11.5px;color:var(--clado-ui-muted);margin-top:3px;">${esc(p.baseUrl || p.hint)}</div>
|
|
1273
1958
|
</div>
|
|
1274
1959
|
<button type="button" class="clado-ui-button" data-edit style="border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);">${isEditing ? '收起' : '配置'}</button>
|
|
1275
1960
|
</div>
|
|
1276
1961
|
${isEditing ? `
|
|
1277
|
-
<div style="margin-top:12px;padding-top:12px;border-top:1px solid var(--clado-ui-edge);display:grid;gap:
|
|
1962
|
+
<div style="margin-top:12px;padding-top:12px;border-top:1px solid var(--clado-ui-edge);display:grid;gap:9px;">
|
|
1963
|
+
${recs.length ? `
|
|
1964
|
+
<div>
|
|
1965
|
+
<div style="font-size:11px;color:var(--clado-ui-subtle);margin-bottom:5px;">官方最新模型快选(点击自动填充模型 ID 与官方上下文容量)</div>
|
|
1966
|
+
<div class="clado-model-presets">
|
|
1967
|
+
${recs.map(rm => `<button type="button" class="clado-model-preset-chip ${rm.id === p.defaultModel ? 'active' : ''}" data-pick-model="${esc(rm.id)}" data-pick-ctx="${rm.contextWindow || 128000}" data-pick-max="${rm.maxTokens || 16384}" data-pick-reas="${rm.reasoning ? '1' : '0'}" title="${esc(rm.label)}">${esc(rm.id)} · ${esc(formatTokenCount(rm.contextWindow || 128000))}</button>`).join('')}
|
|
1968
|
+
</div>
|
|
1969
|
+
</div>
|
|
1970
|
+
` : ''}
|
|
1278
1971
|
${!p.keyless ? `<input class="clado-field" data-f-key type="password" placeholder="API Key(留空保持不变)" value="${esc(p.maskedKey)}" />` : ''}
|
|
1279
1972
|
<input class="clado-field" data-f-url type="text" placeholder="Base URL(可选自定义代理地址)" value="${esc(p.baseUrl)}" />
|
|
1280
|
-
<input class="clado-field" data-f-model type="text" placeholder="默认模型 ID(如 ${esc(p.defaultModel || '
|
|
1973
|
+
<input class="clado-field" data-f-model type="text" placeholder="默认模型 ID(如 ${esc(p.defaultModel || 'deepseek-flash')})" value="${esc(p.defaultModel)}" />
|
|
1974
|
+
<div class="clado-rt-grid">
|
|
1975
|
+
<div class="clado-rt-field">
|
|
1976
|
+
<div class="clado-rt-label"><span>最大上下文窗口(Context Window)</span></div>
|
|
1977
|
+
<input class="clado-field" data-f-ctx type="number" min="4096" max="4000000" step="1000" value="${p.contextWindow || 128000}" />
|
|
1978
|
+
</div>
|
|
1979
|
+
<div class="clado-rt-field">
|
|
1980
|
+
<div class="clado-rt-label"><span>最大单次输出(Max Tokens)</span></div>
|
|
1981
|
+
<input class="clado-field" data-f-maxout type="number" min="1024" max="512000" step="1024" value="${p.maxTokens || 16384}" />
|
|
1982
|
+
</div>
|
|
1983
|
+
</div>
|
|
1984
|
+
<div class="clado-rt-checks">
|
|
1985
|
+
<label><input type="checkbox" data-f-reas ${p.reasoning ? 'checked' : ''} /> 该模型支持思考/推理模式(Thinking / Reasoning)</label>
|
|
1986
|
+
</div>
|
|
1281
1987
|
<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:4px;">
|
|
1282
1988
|
${p.configured ? '<button type="button" class="clado-ui-button" data-del style="color:#be123c;">清除凭据</button>' : '<span></span>'}
|
|
1283
1989
|
<button type="button" class="clado-ui-button clado-ui-button-primary" data-save>保存并设为默认</button>
|
|
@@ -1290,6 +1996,15 @@
|
|
|
1290
1996
|
renderSettings();
|
|
1291
1997
|
};
|
|
1292
1998
|
if (isEditing) {
|
|
1999
|
+
card.querySelectorAll('[data-pick-model]').forEach(btn => {
|
|
2000
|
+
btn.onclick = () => {
|
|
2001
|
+
card.querySelector('[data-f-model]').value = btn.dataset.pickModel;
|
|
2002
|
+
card.querySelector('[data-f-ctx]').value = btn.dataset.pickCtx;
|
|
2003
|
+
card.querySelector('[data-f-maxout]').value = btn.dataset.pickMax;
|
|
2004
|
+
card.querySelector('[data-f-reas]').checked = btn.dataset.pickReas === '1';
|
|
2005
|
+
card.querySelectorAll('[data-pick-model]').forEach(b => b.classList.toggle('active', b === btn));
|
|
2006
|
+
};
|
|
2007
|
+
});
|
|
1293
2008
|
card.querySelector('[data-save]').onclick = async () => {
|
|
1294
2009
|
try {
|
|
1295
2010
|
await apiConfig({
|
|
@@ -1299,9 +2014,13 @@
|
|
|
1299
2014
|
apiKey: card.querySelector('[data-f-key]')?.value || '',
|
|
1300
2015
|
baseUrl: card.querySelector('[data-f-url]')?.value || '',
|
|
1301
2016
|
defaultModel: card.querySelector('[data-f-model]')?.value || '',
|
|
2017
|
+
contextWindow: Number(card.querySelector('[data-f-ctx]')?.value) || undefined,
|
|
2018
|
+
maxTokens: Number(card.querySelector('[data-f-maxout]')?.value) || undefined,
|
|
2019
|
+
reasoning: Boolean(card.querySelector('[data-f-reas]')?.checked),
|
|
1302
2020
|
setAsDefault: true,
|
|
1303
2021
|
});
|
|
1304
2022
|
editingProviderId = '';
|
|
2023
|
+
renderContextMeter();
|
|
1305
2024
|
renderSettings();
|
|
1306
2025
|
showToast('已保存 ' + p.name + ' 并写入 Pi 原生配置');
|
|
1307
2026
|
} catch (e) { showToast(e.message); }
|
|
@@ -1310,6 +2029,7 @@
|
|
|
1310
2029
|
if (delBtn) delBtn.onclick = async () => {
|
|
1311
2030
|
await apiConfig({ action: 'delete_provider', providerId: p.id });
|
|
1312
2031
|
editingProviderId = '';
|
|
2032
|
+
renderContextMeter();
|
|
1313
2033
|
renderSettings();
|
|
1314
2034
|
showToast('已清除 ' + p.name + ' 配置');
|
|
1315
2035
|
};
|