cladogram 0.6.0-beta.1 → 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 +16 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +1544 -127
- package/plugins/agent/style.css +859 -56
- package/plugins/view-controls/style.css +7 -7
- package/src/agent/clado-tools.js +437 -103
- package/src/agent/pi-bridge.js +669 -60
- 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/plugin-ui.css +1 -1
- package/src/html/runtime-api.js +140 -10
- package/src/html/runtime.js +93 -26
- package/src/server/agent.js +46 -8
- package/src/server/assets/library-canvas.js +240 -5
- package/src/server/assets/library.css +428 -12
- 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
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
undo: ico('<path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/>', 12.5),
|
|
7
7
|
plus: ico('<path d="M12 5v14M5 12h14"/>'),
|
|
8
8
|
close: ico('<path d="M18 6 6 18M6 6l12 12"/>'),
|
|
9
|
+
chevDown: ico('<path d="m6 9 6 6 6-6"/>', 12),
|
|
10
|
+
edit: ico('<path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/>', 12),
|
|
11
|
+
archive: ico('<rect x="3" y="4" width="18" height="4" rx="1"/><path d="M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/>', 12),
|
|
12
|
+
trash: ico('<path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M6 6l1 14a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-14"/>', 12),
|
|
9
13
|
cpu: ico('<rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><path d="M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 14h3M1 9h3M1 14h3"/>'),
|
|
10
14
|
users: ico('<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/>'),
|
|
11
15
|
box: ico('<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><path d="M3.27 6.96 12 12.01l8.73-5.05M12 22.08V12"/>'),
|
|
@@ -16,44 +20,219 @@
|
|
|
16
20
|
const TONE_CHIP = { sky: 'clado-chip-sky', emerald: 'clado-chip-mint', violet: 'clado-chip-violet', amber: 'clado-chip-amber' };
|
|
17
21
|
|
|
18
22
|
const CODE_ANALYSIS_PROMPTS = {
|
|
19
|
-
arch: '请先扫描当前项目源码目录结构,识别核心模块、入口文件与数据流边界,然后调用 clado_create 创建一张名为 architecture-overview.md
|
|
20
|
-
req: '请结合当前仓库现状,帮我创建一张名为 feature-design.md
|
|
21
|
-
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 复核。',
|
|
22
26
|
};
|
|
23
27
|
|
|
28
|
+
// ===========================================================================
|
|
29
|
+
// Safe Rich Markdown Renderer (zero external dependencies, strict HTML escape)
|
|
30
|
+
// ===========================================================================
|
|
31
|
+
function renderInline(raw) {
|
|
32
|
+
const codeSlots = [];
|
|
33
|
+
let s = String(raw ?? '').replace(/`([^`\n]+)`/g, (_, inner) => {
|
|
34
|
+
const idx = codeSlots.length;
|
|
35
|
+
codeSlots.push(`<code>${esc(inner)}</code>`);
|
|
36
|
+
return `\u0000CODE${idx}\u0000`;
|
|
37
|
+
});
|
|
38
|
+
s = esc(s);
|
|
39
|
+
// Safe links [label](url)
|
|
40
|
+
s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, label, url) => {
|
|
41
|
+
const cleanUrl = url.replace(/&/g, '&');
|
|
42
|
+
if (/^(https?:\/\/|\/)/i.test(cleanUrl)) {
|
|
43
|
+
return `<a href="${esc(cleanUrl)}" target="_blank" rel="noopener noreferrer">${label}</a>`;
|
|
44
|
+
}
|
|
45
|
+
return `${label} (${url})`;
|
|
46
|
+
});
|
|
47
|
+
// Bold, strikethrough, italic (avoiding snake_case underscores inside words)
|
|
48
|
+
s = s.replace(/\*\*([^*]+?)\*\*/g, '<strong>$1</strong>');
|
|
49
|
+
s = s.replace(/~~([^~]+?)~~/g, '<del>$1</del>');
|
|
50
|
+
s = s.replace(/(^|[\s((【「“',。;:])\*([^*\n]+?)\*(?=[\s))】」”',。;:.,!?]|$)/g, '$1<em>$2</em>');
|
|
51
|
+
s = s.replace(/(^|[\s((【「“',。;:])_([^_\n]+?)_(?=[\s))】」”',。;:.,!?]|$)/g, '$1<em>$2</em>');
|
|
52
|
+
s = s.replace(/\u0000CODE(\d+)\u0000/g, (_, idx) => codeSlots[Number(idx)] || '');
|
|
53
|
+
return s;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function renderMarkdown(raw) {
|
|
57
|
+
const normalized = String(raw ?? '').replace(/\r\n?/g, '\n');
|
|
58
|
+
if (!normalized.trim()) return '';
|
|
59
|
+
|
|
60
|
+
// 1. Extract fenced code blocks (including unclosed trailing fence during streaming)
|
|
61
|
+
const fences = [];
|
|
62
|
+
let text = normalized.replace(/```([a-zA-Z0-9_+-]*)[ \t]*\n([\s\S]*?)(?:```|$)/g, (_, lang, code) => {
|
|
63
|
+
const idx = fences.length;
|
|
64
|
+
const cleanCode = code.replace(/\n$/, '');
|
|
65
|
+
fences.push(
|
|
66
|
+
`<div class="clado-md-pre">`
|
|
67
|
+
+ `<div class="clado-md-pre-head"><span>${esc(lang || 'code')}</span>`
|
|
68
|
+
+ `<button type="button" class="clado-dock-mini-btn" data-copy-code style="padding:1px 6px;font-size:10.5px;">复制</button></div>`
|
|
69
|
+
+ `<pre class="clado-scroll"><code>${esc(cleanCode)}</code></pre></div>`
|
|
70
|
+
);
|
|
71
|
+
return `\n\u0000FENCE${idx}\u0000\n`;
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
const lines = text.split('\n');
|
|
75
|
+
const out = [];
|
|
76
|
+
let i = 0;
|
|
77
|
+
|
|
78
|
+
const isTableSep = line => /^\s*\|?(\s*:?-{3,}:?\s*\|)+\s*:?-{3,}:?\s*\|?\s*$/.test(line);
|
|
79
|
+
const parseTableRow = line => line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(c => c.trim());
|
|
80
|
+
|
|
81
|
+
while (i < lines.length) {
|
|
82
|
+
const line = lines[i];
|
|
83
|
+
const trimmed = line.trim();
|
|
84
|
+
if (!trimmed) { i++; continue; }
|
|
85
|
+
|
|
86
|
+
// Fenced code placeholder
|
|
87
|
+
const fenceMatch = trimmed.match(/^\u0000FENCE(\d+)\u0000$/);
|
|
88
|
+
if (fenceMatch) {
|
|
89
|
+
out.push(fences[Number(fenceMatch[1])] || '');
|
|
90
|
+
i++;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Headings (allow empty/partial heading text during live token streaming like "### ")
|
|
95
|
+
const hMatch = line.match(/^\s{0,3}(#{1,6})\s+(.*)$/);
|
|
96
|
+
if (hMatch) {
|
|
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}>`);
|
|
100
|
+
i++;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Horizontal rule
|
|
105
|
+
if (/^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/.test(line)) {
|
|
106
|
+
out.push('<hr/>');
|
|
107
|
+
i++;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// GFM Table
|
|
112
|
+
if (line.includes('|') && i + 1 < lines.length && isTableSep(lines[i + 1])) {
|
|
113
|
+
const headerCells = parseTableRow(line);
|
|
114
|
+
i += 2;
|
|
115
|
+
const bodyRows = [];
|
|
116
|
+
while (i < lines.length && lines[i].trim() && lines[i].includes('|')) {
|
|
117
|
+
bodyRows.push(parseTableRow(lines[i]));
|
|
118
|
+
i++;
|
|
119
|
+
}
|
|
120
|
+
const thead = `<thead><tr>${headerCells.map(c => `<th>${renderInline(c)}</th>`).join('')}</tr></thead>`;
|
|
121
|
+
const tbody = bodyRows.length
|
|
122
|
+
? `<tbody>${bodyRows.map(r => `<tr>${headerCells.map((_, ci) => `<td>${renderInline(r[ci] || '')}</td>`).join('')}</tr>`).join('')}</tbody>`
|
|
123
|
+
: '';
|
|
124
|
+
out.push(`<div class="clado-scroll" style="overflow-x:auto;"><table>${thead}${tbody}</table></div>`);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Blockquote
|
|
129
|
+
if (/^\s*>\s?/.test(line)) {
|
|
130
|
+
const quoteLines = [];
|
|
131
|
+
while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
|
|
132
|
+
quoteLines.push(lines[i].replace(/^\s*>\s?/, ''));
|
|
133
|
+
i++;
|
|
134
|
+
}
|
|
135
|
+
out.push(`<blockquote>${quoteLines.map(renderInline).join('<br/>')}</blockquote>`);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Unordered list
|
|
140
|
+
if (/^\s*[-*+]\s+/.test(line)) {
|
|
141
|
+
const items = [];
|
|
142
|
+
while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i])) {
|
|
143
|
+
items.push(lines[i].replace(/^\s*[-*+]\s+/, ''));
|
|
144
|
+
i++;
|
|
145
|
+
}
|
|
146
|
+
out.push(`<ul>${items.map(it => `<li>${renderInline(it)}</li>`).join('')}</ul>`);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Ordered list
|
|
151
|
+
if (/^\s*\d+\.\s+/.test(line)) {
|
|
152
|
+
const items = [];
|
|
153
|
+
while (i < lines.length && /^\s*\d+\.\s+/.test(lines[i])) {
|
|
154
|
+
items.push(lines[i].replace(/^\s*\d+\.\s+/, ''));
|
|
155
|
+
i++;
|
|
156
|
+
}
|
|
157
|
+
out.push(`<ol>${items.map(it => `<li>${renderInline(it)}</li>`).join('')}</ol>`);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Paragraph
|
|
162
|
+
const pLines = [];
|
|
163
|
+
while (
|
|
164
|
+
i < lines.length
|
|
165
|
+
&& lines[i].trim()
|
|
166
|
+
&& !/^\u0000FENCE\d+\u0000$/.test(lines[i].trim())
|
|
167
|
+
&& !/^\s{0,3}#{1,6}\s+/.test(lines[i])
|
|
168
|
+
&& !/^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/.test(lines[i])
|
|
169
|
+
&& !/^\s*>\s?/.test(lines[i])
|
|
170
|
+
&& !/^\s*[-*+]\s+/.test(lines[i])
|
|
171
|
+
&& !/^\s*\d+\.\s+/.test(lines[i])
|
|
172
|
+
&& !(lines[i].includes('|') && i + 1 < lines.length && isTableSep(lines[i + 1]))
|
|
173
|
+
) {
|
|
174
|
+
pLines.push(lines[i]);
|
|
175
|
+
i++;
|
|
176
|
+
}
|
|
177
|
+
if (pLines.length) {
|
|
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++;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return out.join('');
|
|
187
|
+
}
|
|
188
|
+
|
|
24
189
|
window.CladoAgentPlugin = (host, actions = {}) => {
|
|
25
190
|
const withWs = actions.withWorkspace || (p => p);
|
|
26
191
|
const stageRoot = () => document.getElementById('clado-stage') || document.body;
|
|
27
192
|
|
|
28
193
|
let meta = null;
|
|
29
194
|
let sessions = [];
|
|
30
|
-
let activeSessionId = '';
|
|
195
|
+
let activeSessionId = localStorage.getItem('clado-active-session') || '';
|
|
31
196
|
let drawerOpen = false;
|
|
32
197
|
let runningSessionId = '';
|
|
33
198
|
let activeAbort = null;
|
|
199
|
+
let stoppingTurn = false;
|
|
200
|
+
let pendingCancelPromise = null;
|
|
34
201
|
let settingsTab = 'extensions';
|
|
35
202
|
let editingProviderId = '';
|
|
203
|
+
let sessionFilter = 'active'; // 'active' | 'archived'
|
|
204
|
+
let renamingSessionId = '';
|
|
205
|
+
let sendMode = localStorage.getItem('clado-send-mode') === 'enter' ? 'enter' : 'ctrl-enter';
|
|
206
|
+
const traceOpenState = new Map(); // msgKey -> boolean
|
|
36
207
|
|
|
37
208
|
// =========================================================================
|
|
38
|
-
// 1. Bottom-Right Role Dock
|
|
209
|
+
// 1. Bottom-Right Role Dock (Resizable + Session Manager + Multiline Composer)
|
|
39
210
|
// =========================================================================
|
|
40
211
|
const dock = document.createElement('div');
|
|
41
212
|
dock.className = 'clado-vnext-dock';
|
|
42
213
|
dock.innerHTML = `
|
|
43
214
|
<div class="clado-dock-drawer collapsed" data-drawer>
|
|
215
|
+
<div class="clado-resize-nw" data-resize="nw" title="拖动调整对话窗口宽高(双击恢复默认)"></div>
|
|
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>
|
|
44
218
|
<div class="clado-dock-aura"></div>
|
|
45
219
|
<div class="clado-dock-inner">
|
|
46
220
|
<div class="clado-dock-head">
|
|
47
221
|
<div class="clado-dock-head-left">
|
|
48
|
-
<
|
|
222
|
+
<button type="button" class="clado-dock-session-trigger" data-session-trigger title="切换、新建、重命名或归档会话">
|
|
223
|
+
<span data-role-title>主架构师</span>
|
|
224
|
+
${ICONS.chevDown}
|
|
225
|
+
</button>
|
|
49
226
|
<span class="clado-chip clado-chip-sky" data-role-phase>设计阶段</span>
|
|
50
227
|
</div>
|
|
51
228
|
<div class="clado-dock-actions">
|
|
229
|
+
<button type="button" class="clado-dock-mini-btn" data-new-session title="在当前角色下开启新会话">${ICONS.plus}<span>新会话</span></button>
|
|
52
230
|
<button type="button" class="clado-dock-mini-btn" data-rollback title="回退画布至上一轮快照">${ICONS.undo}<span>回退</span></button>
|
|
53
231
|
<button type="button" class="clado-dock-mini-btn" data-collapse>收起</button>
|
|
54
232
|
</div>
|
|
55
233
|
</div>
|
|
56
|
-
<div class="clado-
|
|
234
|
+
<div class="clado-session-pop" data-session-pop hidden></div>
|
|
235
|
+
<div class="clado-dock-stream clado-scroll" data-stream></div>
|
|
57
236
|
<div class="clado-dock-handoff">
|
|
58
237
|
<span style="color:var(--clado-ui-subtle);">流转至下一阶段</span>
|
|
59
238
|
<div style="display:flex;align-items:center;gap:6px;">
|
|
@@ -67,11 +246,24 @@
|
|
|
67
246
|
<div class="clado-role-strip" data-role-strip></div>
|
|
68
247
|
|
|
69
248
|
<div class="clado-composer">
|
|
70
|
-
<div class="clado-dock-popover" data-popover hidden></div>
|
|
71
|
-
<
|
|
72
|
-
<
|
|
73
|
-
<
|
|
74
|
-
|
|
249
|
+
<div class="clado-dock-popover clado-scroll" data-popover hidden></div>
|
|
250
|
+
<div class="clado-ctx-bar" data-ctx-bar hidden></div>
|
|
251
|
+
<textarea class="clado-composer-input clado-scroll" data-input rows="1" placeholder="输入需求、敲 / 调命令(Enter 换行,Ctrl+Enter 发送)…"></textarea>
|
|
252
|
+
<div class="clado-composer-bar">
|
|
253
|
+
<div class="clado-composer-left">
|
|
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>
|
|
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>
|
|
260
|
+
</div>
|
|
261
|
+
<div class="clado-composer-right">
|
|
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>
|
|
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>
|
|
265
|
+
</div>
|
|
266
|
+
</div>
|
|
75
267
|
</div>
|
|
76
268
|
`;
|
|
77
269
|
host.mount('bottom-right', dock, 'clado.agent');
|
|
@@ -83,39 +275,192 @@
|
|
|
83
275
|
const stripEl = dock.querySelector('[data-role-strip]');
|
|
84
276
|
const inputEl = dock.querySelector('[data-input]');
|
|
85
277
|
const sendBtn = dock.querySelector('[data-send]');
|
|
278
|
+
const stopBtn = dock.querySelector('[data-stop]');
|
|
279
|
+
const ctxBarEl = dock.querySelector('[data-ctx-bar]');
|
|
280
|
+
const sendModeBtn = dock.querySelector('[data-sendmode]');
|
|
86
281
|
const modelChip = dock.querySelector('[data-model-chip]');
|
|
282
|
+
const ctxMeterBtn = dock.querySelector('[data-ctx-meter]');
|
|
87
283
|
const popoverEl = dock.querySelector('[data-popover]');
|
|
284
|
+
const sessionPopEl = dock.querySelector('[data-session-pop]');
|
|
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
|
+
}
|
|
295
|
+
|
|
296
|
+
// Restore persisted dock dimensions
|
|
297
|
+
function applyDockSize(w, h) {
|
|
298
|
+
if (Number.isFinite(w) && w >= 350 && w <= 880) {
|
|
299
|
+
dock.style.setProperty('--clado-dock-w', Math.round(w) + 'px');
|
|
300
|
+
syncRootDockWidth(w);
|
|
301
|
+
}
|
|
302
|
+
if (Number.isFinite(h) && h >= 160 && h <= 820) {
|
|
303
|
+
dock.style.setProperty('--clado-dock-stream-h', Math.round(h) + 'px');
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
try {
|
|
307
|
+
const saved = JSON.parse(localStorage.getItem('clado-dock-size') || 'null');
|
|
308
|
+
if (saved) applyDockSize(saved.w, saved.h);
|
|
309
|
+
} catch {}
|
|
310
|
+
|
|
311
|
+
function getStageScale() {
|
|
312
|
+
const stage = stageRoot();
|
|
313
|
+
if (!stage || !stage.offsetWidth) return 1;
|
|
314
|
+
const rect = stage.getBoundingClientRect();
|
|
315
|
+
return rect.width > 0 ? (rect.width / stage.offsetWidth) : 1;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Bind NW / N / W Resize Handles (with iframe pointer-event isolation for smooth dragging)
|
|
319
|
+
dock.querySelectorAll('[data-resize]').forEach(handle => {
|
|
320
|
+
const mode = handle.dataset.resize;
|
|
321
|
+
if (mode === 'nw' || mode === 'n') {
|
|
322
|
+
handle.addEventListener('dblclick', e => {
|
|
323
|
+
e.preventDefault();
|
|
324
|
+
e.stopPropagation();
|
|
325
|
+
dock.style.removeProperty('--clado-dock-w');
|
|
326
|
+
dock.style.removeProperty('--clado-dock-stream-h');
|
|
327
|
+
syncRootDockWidth(NaN);
|
|
328
|
+
localStorage.removeItem('clado-dock-size');
|
|
329
|
+
showToast('已恢复默认对话窗口尺寸');
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
handle.addEventListener('pointerdown', e => {
|
|
333
|
+
if (e.button !== 0) return;
|
|
334
|
+
e.preventDefault();
|
|
335
|
+
e.stopPropagation();
|
|
336
|
+
const scale = getStageScale();
|
|
337
|
+
const stage = stageRoot();
|
|
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));
|
|
342
|
+
const startX = e.clientX;
|
|
343
|
+
const startY = e.clientY;
|
|
344
|
+
const startW = dock.offsetWidth || 412;
|
|
345
|
+
const startH = streamEl.offsetHeight || 300;
|
|
346
|
+
let lastW = startW;
|
|
347
|
+
let lastH = startH;
|
|
348
|
+
drawerEl.classList.add('resizing');
|
|
349
|
+
document.body.classList.add('clado-dock-resizing');
|
|
350
|
+
try { handle.setPointerCapture?.(e.pointerId); } catch {}
|
|
351
|
+
|
|
352
|
+
const onMove = ev => {
|
|
353
|
+
const dx = (ev.clientX - startX) / scale;
|
|
354
|
+
const dy = (ev.clientY - startY) / scale;
|
|
355
|
+
if (mode === 'w' || mode === 'nw') {
|
|
356
|
+
lastW = Math.max(350, Math.min(maxW, startW - dx));
|
|
357
|
+
dock.style.setProperty('--clado-dock-w', Math.round(lastW) + 'px');
|
|
358
|
+
syncRootDockWidth(lastW);
|
|
359
|
+
}
|
|
360
|
+
if (mode === 'n' || mode === 'nw') {
|
|
361
|
+
lastH = Math.max(160, Math.min(maxH, startH - dy));
|
|
362
|
+
dock.style.setProperty('--clado-dock-stream-h', Math.round(lastH) + 'px');
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
const onUp = ev => {
|
|
366
|
+
drawerEl.classList.remove('resizing');
|
|
367
|
+
document.body.classList.remove('clado-dock-resizing');
|
|
368
|
+
try { if (ev?.pointerId != null) handle.releasePointerCapture?.(ev.pointerId); } catch {}
|
|
369
|
+
window.removeEventListener('pointermove', onMove);
|
|
370
|
+
window.removeEventListener('pointerup', onUp);
|
|
371
|
+
window.removeEventListener('pointercancel', onUp);
|
|
372
|
+
try {
|
|
373
|
+
localStorage.setItem('clado-dock-size', JSON.stringify({ w: Math.round(lastW), h: Math.round(lastH) }));
|
|
374
|
+
} catch {}
|
|
375
|
+
};
|
|
376
|
+
window.addEventListener('pointermove', onMove);
|
|
377
|
+
window.addEventListener('pointerup', onUp);
|
|
378
|
+
window.addEventListener('pointercancel', onUp);
|
|
379
|
+
});
|
|
380
|
+
});
|
|
88
381
|
|
|
89
382
|
function showToast(msg) {
|
|
90
383
|
window.dispatchEvent(new CustomEvent('clado:toast', { detail: { message: msg } }));
|
|
91
384
|
}
|
|
92
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
|
+
|
|
408
|
+
function autoGrowInput() {
|
|
409
|
+
inputEl.style.height = 'auto';
|
|
410
|
+
const next = Math.min(132, Math.max(22, inputEl.scrollHeight));
|
|
411
|
+
inputEl.style.height = next + 'px';
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function syncSendModeUi() {
|
|
415
|
+
if (runningSessionId) {
|
|
416
|
+
inputEl.placeholder = 'AI 正在运行,输入内容可随时中途插话纠偏…';
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
if (sendMode === 'ctrl-enter') {
|
|
420
|
+
sendModeBtn.textContent = 'Ctrl↵ 发送';
|
|
421
|
+
sendModeBtn.title = '当前:Enter 换行,Ctrl/⌘+Enter 发送(点击切换为 Enter 发送)';
|
|
422
|
+
inputEl.placeholder = '输入需求、敲 / 调命令(Enter 换行,Ctrl+Enter 发送)…';
|
|
423
|
+
} else {
|
|
424
|
+
sendModeBtn.textContent = '↵ 发送';
|
|
425
|
+
sendModeBtn.title = '当前:Enter 发送,Shift+Enter 换行(点击切换为 Ctrl+Enter 发送)';
|
|
426
|
+
inputEl.placeholder = '输入需求、敲 / 调命令(Enter 发送,Shift+Enter 换行)…';
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
syncSendModeUi();
|
|
430
|
+
|
|
93
431
|
function setDrawerOpen(open) {
|
|
94
432
|
drawerOpen = Boolean(open);
|
|
95
433
|
drawerEl.classList.toggle('collapsed', !drawerOpen);
|
|
96
434
|
document.body.dataset.agentDock = drawerOpen ? 'open' : 'closed';
|
|
435
|
+
if (drawerOpen) renderContextChips();
|
|
436
|
+
if (!drawerOpen) closeSessionPop();
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function selectSession(id, openDrawer = true) {
|
|
440
|
+
activeSessionId = id;
|
|
441
|
+
try { localStorage.setItem('clado-active-session', id); } catch {}
|
|
442
|
+
if (openDrawer) setDrawerOpen(true);
|
|
443
|
+
renderRoleStrip();
|
|
444
|
+
renderStream();
|
|
445
|
+
renderContextChips();
|
|
446
|
+
if (!sessionPopEl.hidden) renderSessionPop();
|
|
97
447
|
}
|
|
98
448
|
|
|
99
449
|
function currentSession() {
|
|
100
|
-
return sessions.find(s => s.id === activeSessionId) || sessions[0] || null;
|
|
450
|
+
return sessions.find(s => s.id === activeSessionId) || sessions.find(s => !s.archived) || sessions[0] || null;
|
|
101
451
|
}
|
|
102
452
|
|
|
103
453
|
function renderRoleStrip() {
|
|
104
454
|
stripEl.replaceChildren();
|
|
105
|
-
|
|
106
|
-
|
|
455
|
+
const visible = sessions.filter(s => !s.archived);
|
|
456
|
+
for (const s of visible) {
|
|
107
457
|
const btn = document.createElement('button');
|
|
108
458
|
btn.type = 'button';
|
|
109
459
|
btn.className = 'clado-role-pill' + (s.id === activeSessionId ? ' active' : '');
|
|
110
460
|
btn.dataset.tone = s.tone || 'sky';
|
|
111
461
|
const badge = s.status === 'running' ? ' · 运行中' : (s.summaryBadge ? ' · ' + s.summaryBadge : '');
|
|
112
462
|
btn.textContent = s.title + badge;
|
|
113
|
-
btn.onclick = () =>
|
|
114
|
-
activeSessionId = s.id;
|
|
115
|
-
setDrawerOpen(true);
|
|
116
|
-
renderRoleStrip();
|
|
117
|
-
renderStream();
|
|
118
|
-
};
|
|
463
|
+
btn.onclick = () => selectSession(s.id, true);
|
|
119
464
|
stripEl.append(btn);
|
|
120
465
|
}
|
|
121
466
|
const addBtn = document.createElement('button');
|
|
@@ -123,11 +468,368 @@
|
|
|
123
468
|
addBtn.className = 'clado-role-pill clado-role-add';
|
|
124
469
|
addBtn.title = '新建角色会话';
|
|
125
470
|
addBtn.innerHTML = ICONS.plus;
|
|
126
|
-
addBtn.onclick =
|
|
471
|
+
addBtn.onclick = e => {
|
|
472
|
+
e.stopPropagation();
|
|
473
|
+
closeSessionPop();
|
|
474
|
+
popoverEl.dataset.kind = 'new-role';
|
|
475
|
+
openNewRoleSessionPopover();
|
|
476
|
+
};
|
|
127
477
|
stripEl.append(addBtn);
|
|
128
478
|
}
|
|
129
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
|
+
|
|
586
|
+
function buildToolTrace(msgKey, tools, isRunningMsg) {
|
|
587
|
+
const details = document.createElement('details');
|
|
588
|
+
details.className = 'clado-tool-trace';
|
|
589
|
+
const anyRunning = tools.some(t => t.status === 'running');
|
|
590
|
+
const failedCount = tools.filter(t => t.status === 'failed' || t.isError).length;
|
|
591
|
+
const anyFailed = failedCount > 0;
|
|
592
|
+
const doneCount = tools.filter(t => t.status === 'completed' || t.status === 'failed').length;
|
|
593
|
+
const shouldOpen = traceOpenState.has(msgKey) ? traceOpenState.get(msgKey) : (anyRunning || anyFailed || isRunningMsg);
|
|
594
|
+
if (shouldOpen) details.open = true;
|
|
595
|
+
if (anyFailed && !anyRunning) details.classList.add('clado-tool-trace-err');
|
|
596
|
+
details.addEventListener('toggle', () => {
|
|
597
|
+
traceOpenState.set(msgKey, details.open);
|
|
598
|
+
});
|
|
599
|
+
|
|
600
|
+
const dotCls = anyRunning ? 'clado-dot-pulse' : (anyFailed ? 'clado-dot-err' : 'clado-dot-ok');
|
|
601
|
+
const currentTool = [...tools].reverse().find(t => t.status === 'running') || tools[tools.length - 1];
|
|
602
|
+
const namesPreview = [...new Set(tools.map(t => t.name).filter(Boolean))].slice(0, 3).join(' · ');
|
|
603
|
+
const label = anyRunning
|
|
604
|
+
? `正在执行 ${currentTool?.name || '工具'}${currentTool?.argsSummary ? ' · ' + currentTool.argsSummary : ''} (${doneCount}/${tools.length})`
|
|
605
|
+
: anyFailed
|
|
606
|
+
? `工具调用 (${tools.length} · ${failedCount} 项失败) · ${namesPreview}`
|
|
607
|
+
: `工具调用 (${tools.length}) · ${namesPreview}`;
|
|
608
|
+
|
|
609
|
+
const summary = document.createElement('summary');
|
|
610
|
+
summary.innerHTML = `
|
|
611
|
+
<span style="display:inline-flex;align-items:center;gap:7px;min-width:0;overflow:hidden;">
|
|
612
|
+
<span class="${dotCls}"></span>
|
|
613
|
+
<span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${esc(label)}</span>
|
|
614
|
+
</span>
|
|
615
|
+
<span style="font-size:10.5px;color:var(--clado-ui-subtle);flex:none;">${details.open ? '收起' : '详情'}</span>
|
|
616
|
+
`;
|
|
617
|
+
details.addEventListener('toggle', () => {
|
|
618
|
+
const rightSpan = summary.lastElementChild;
|
|
619
|
+
if (rightSpan) rightSpan.textContent = details.open ? '收起' : '详情';
|
|
620
|
+
});
|
|
621
|
+
details.append(summary);
|
|
622
|
+
|
|
623
|
+
const list = document.createElement('div');
|
|
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']);
|
|
627
|
+
for (const t of tools) {
|
|
628
|
+
const isErr = t.status === 'failed' || t.isError;
|
|
629
|
+
const step = document.createElement('div');
|
|
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';
|
|
639
|
+
step.innerHTML = `
|
|
640
|
+
<div class="clado-tool-step-head">
|
|
641
|
+
<span class="${stepDot}"></span>
|
|
642
|
+
<span class="clado-tool-name">${esc(t.name || 'tool')}</span>
|
|
643
|
+
<span class="clado-tool-args" title="${esc(t.argsSummary || '')}">${esc(t.argsSummary || '')}</span>
|
|
644
|
+
<span class="${statusCls}">${statusTxt}</span>
|
|
645
|
+
</div>
|
|
646
|
+
${t.resultPreview ? `<div class="clado-tool-preview clado-scroll">${esc(t.resultPreview)}</div>` : ''}
|
|
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
|
+
}
|
|
658
|
+
list.append(step);
|
|
659
|
+
}
|
|
660
|
+
details.append(list);
|
|
661
|
+
return details;
|
|
662
|
+
}
|
|
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
|
+
|
|
718
|
+
function buildDecisionCard(sessionId, q) {
|
|
719
|
+
const box = document.createElement('div');
|
|
720
|
+
box.className = 'clado-decision-card';
|
|
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>`;
|
|
722
|
+
const optsWrap = box.querySelector('.clado-decision-opts');
|
|
723
|
+
const opts = Array.isArray(q.options) && q.options.length ? q.options : [{ id: 'confirm', label: '确认继续' }];
|
|
724
|
+
for (let i = 0; i < opts.length; i++) {
|
|
725
|
+
const opt = opts[i];
|
|
726
|
+
const btn = document.createElement('button');
|
|
727
|
+
btn.type = 'button';
|
|
728
|
+
btn.className = 'clado-ui-button ' + (i === 0 ? 'clado-ui-button-primary' : '');
|
|
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);' : '');
|
|
730
|
+
btn.textContent = opt.label;
|
|
731
|
+
btn.onclick = () => submitQuestionAnswer(sessionId, q, opt.label);
|
|
732
|
+
optsWrap.append(btn);
|
|
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
|
+
});
|
|
752
|
+
return box;
|
|
753
|
+
}
|
|
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
|
+
|
|
130
828
|
function renderStream() {
|
|
829
|
+
if (renderStreamTimer) {
|
|
830
|
+
clearTimeout(renderStreamTimer);
|
|
831
|
+
renderStreamTimer = 0;
|
|
832
|
+
}
|
|
131
833
|
const s = currentSession();
|
|
132
834
|
if (!s) return;
|
|
133
835
|
roleTitleEl.textContent = s.title || '主架构师';
|
|
@@ -136,73 +838,292 @@
|
|
|
136
838
|
|
|
137
839
|
const modelLabel = s.model || meta?.activeModelLabel || '配置模型';
|
|
138
840
|
modelChip.textContent = (modelLabel.includes('/') ? modelLabel.split('/').pop() : modelLabel) + ' ▾';
|
|
841
|
+
renderContextMeter();
|
|
842
|
+
|
|
843
|
+
const wasNearBottom = (streamEl.scrollHeight - streamEl.scrollTop - streamEl.clientHeight) < 60;
|
|
139
844
|
|
|
140
845
|
const msgs = Array.isArray(s.messages) ? s.messages : [];
|
|
141
846
|
streamEl.replaceChildren();
|
|
142
847
|
if (!msgs.length) {
|
|
143
848
|
const empty = document.createElement('div');
|
|
144
849
|
empty.className = 'clado-dock-empty';
|
|
145
|
-
empty.innerHTML =
|
|
850
|
+
empty.innerHTML = `当前会话:<strong>${esc(s.title)}</strong>(Pi 1.0 引擎)<br/>可直接描述架构修改、输入 <code>/</code> 调命令,或在画布选中卡片派活交付。<br/>拖动顶部居中横条可调整窗口高度,点击标题可切换或新建会话。`;
|
|
146
851
|
streamEl.append(empty);
|
|
147
852
|
return;
|
|
148
853
|
}
|
|
149
854
|
|
|
150
|
-
|
|
855
|
+
const pendingDecisionCards = [];
|
|
856
|
+
|
|
857
|
+
for (let idx = 0; idx < msgs.length; idx++) {
|
|
858
|
+
const m = msgs[idx];
|
|
859
|
+
const isLast = idx === msgs.length - 1;
|
|
151
860
|
if (m.role === 'user') {
|
|
152
861
|
const div = document.createElement('div');
|
|
153
|
-
div.className = 'clado-msg-user';
|
|
154
|
-
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` : '');
|
|
155
864
|
div.textContent = prefix + (m.text || '');
|
|
156
865
|
streamEl.append(div);
|
|
157
866
|
} else {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
867
|
+
const msgKey = m.id || `${s.id}_${idx}`;
|
|
868
|
+
const isRunningMsg = isLast && s.status === 'running';
|
|
869
|
+
|
|
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
|
+
}
|
|
165
899
|
}
|
|
166
|
-
|
|
167
|
-
|
|
900
|
+
|
|
901
|
+
// 2. Collect questions: answered ones show as compact receipt pill; unanswered ones ONLY show while this turn is actively running
|
|
902
|
+
const qList = [];
|
|
903
|
+
if (Array.isArray(m.questions)) qList.push(...m.questions);
|
|
904
|
+
if (m.question && !qList.some(q => q.questionId === m.question.questionId)) qList.push(m.question);
|
|
905
|
+
|
|
906
|
+
for (const q of qList) {
|
|
907
|
+
if (q.answered) {
|
|
908
|
+
const donePill = document.createElement('div');
|
|
909
|
+
donePill.className = 'clado-decision-done';
|
|
910
|
+
donePill.textContent = '已确认:' + (q.answer || q.question);
|
|
911
|
+
streamEl.append(donePill);
|
|
912
|
+
} else if (isRunningMsg && !q.dismissed) {
|
|
913
|
+
pendingDecisionCards.push(q);
|
|
914
|
+
}
|
|
168
915
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
916
|
+
|
|
917
|
+
// 3. Live activity status pill while running
|
|
918
|
+
if (isRunningMsg) {
|
|
919
|
+
const act = document.createElement('div');
|
|
920
|
+
act.className = 'clado-live-activity';
|
|
921
|
+
act.innerHTML = `<span class="clado-dot-pulse"></span><span>${esc(m.activity || 'Pi 正在思考与执行…')}</span>`;
|
|
922
|
+
streamEl.append(act);
|
|
174
923
|
}
|
|
175
924
|
}
|
|
176
925
|
}
|
|
177
|
-
|
|
926
|
+
|
|
927
|
+
// 4. Pending ask_user decision cards ALWAYS render at the very bottom (only while running)
|
|
928
|
+
for (const q of pendingDecisionCards) {
|
|
929
|
+
streamEl.append(buildDecisionCard(s.id, q));
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
if (runningSessionId === s.id) {
|
|
933
|
+
sendBtn.textContent = pendingDecisionCards.length ? '回复' : '插话';
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
if (wasNearBottom || s.status === 'running' || pendingDecisionCards.length) {
|
|
937
|
+
streamEl.scrollTop = streamEl.scrollHeight;
|
|
938
|
+
}
|
|
178
939
|
}
|
|
179
940
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
941
|
+
// Copy code button & clickable card/tag chip delegation inside stream
|
|
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
|
+
}
|
|
953
|
+
const btn = e.target.closest?.('[data-copy-code]');
|
|
954
|
+
if (!btn) return;
|
|
955
|
+
const code = btn.closest('.clado-md-pre')?.querySelector('pre code')?.textContent || '';
|
|
956
|
+
navigator.clipboard?.writeText(code).catch(() => {});
|
|
957
|
+
const prev = btn.textContent;
|
|
958
|
+
btn.textContent = '已复制';
|
|
959
|
+
setTimeout(() => { btn.textContent = prev; }, 1200);
|
|
960
|
+
showToast('已复制代码块');
|
|
961
|
+
});
|
|
962
|
+
|
|
963
|
+
// =========================================================================
|
|
964
|
+
// Session Manager Popover (Switch / Create / Inline Rename / Archive / Delete)
|
|
965
|
+
// =========================================================================
|
|
966
|
+
function closeSessionPop() {
|
|
967
|
+
sessionPopEl.hidden = true;
|
|
968
|
+
renamingSessionId = '';
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
async function createNewSessionForCurrentRole(roleOverride = null) {
|
|
972
|
+
const cur = currentSession();
|
|
973
|
+
const targetRoleId = roleOverride?.id || cur?.roleId || 'architect';
|
|
974
|
+
const roleObj = roleOverride || (meta?.roles || []).find(r => r.id === targetRoleId) || { id: targetRoleId, name: cur?.title || '主架构师' };
|
|
975
|
+
const sameRoleCount = sessions.filter(s => s.roleId === targetRoleId).length;
|
|
976
|
+
const defaultTitle = `${roleObj.name} · 会话 ${sameRoleCount + 1}`;
|
|
977
|
+
const res = await fetch(withWs('/library/agent/sessions'), {
|
|
978
|
+
method: 'POST',
|
|
979
|
+
headers: { 'content-type': 'application/json' },
|
|
980
|
+
body: JSON.stringify({ roleId: roleObj.id, title: defaultTitle }),
|
|
981
|
+
});
|
|
982
|
+
const data = await res.json();
|
|
983
|
+
if (data?.session) {
|
|
984
|
+
sessions.push(data.session);
|
|
985
|
+
closeSessionPop();
|
|
986
|
+
selectSession(data.session.id, true);
|
|
987
|
+
showToast('已新建会话:' + data.session.title);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
function renderSessionPop() {
|
|
992
|
+
const activeCount = sessions.filter(s => !s.archived).length;
|
|
993
|
+
const archivedCount = sessions.filter(s => s.archived).length;
|
|
994
|
+
const list = sessions
|
|
995
|
+
.filter(s => (sessionFilter === 'archived' ? s.archived : !s.archived))
|
|
996
|
+
.slice()
|
|
997
|
+
.sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));
|
|
998
|
+
|
|
999
|
+
sessionPopEl.innerHTML = `
|
|
1000
|
+
<div style="display:flex;align-items:center;justify-content:space-between;gap:6px;">
|
|
1001
|
+
<div style="display:inline-flex;gap:4px;">
|
|
1002
|
+
<button type="button" class="clado-dock-mini-btn" data-sf="active" style="${sessionFilter === 'active' ? 'background:var(--clado-ui-prism-bg);border-color:var(--clado-ui-prism-border);color:var(--clado-ui-prism-text);' : ''}">进行中 (${activeCount})</button>
|
|
1003
|
+
<button type="button" class="clado-dock-mini-btn" data-sf="archived" style="${sessionFilter === 'archived' ? 'background:var(--clado-ui-prism-bg);border-color:var(--clado-ui-prism-border);color:var(--clado-ui-prism-text);' : ''}">已归档 (${archivedCount})</button>
|
|
1004
|
+
</div>
|
|
1005
|
+
<button type="button" class="clado-ui-button clado-ui-button-primary" data-sp-new style="min-height:24px;padding:2px 9px;font-size:11px;">+ 新建会话</button>
|
|
1006
|
+
</div>
|
|
1007
|
+
<div class="clado-session-list clado-scroll" data-sp-list></div>
|
|
1008
|
+
`;
|
|
1009
|
+
|
|
1010
|
+
sessionPopEl.querySelectorAll('[data-sf]').forEach(btn => {
|
|
1011
|
+
btn.onclick = e => {
|
|
1012
|
+
e.stopPropagation();
|
|
1013
|
+
sessionFilter = btn.dataset.sf;
|
|
1014
|
+
renderSessionPop();
|
|
202
1015
|
};
|
|
203
|
-
|
|
1016
|
+
});
|
|
1017
|
+
sessionPopEl.querySelector('[data-sp-new]').onclick = e => {
|
|
1018
|
+
e.stopPropagation();
|
|
1019
|
+
createNewSessionForCurrentRole();
|
|
1020
|
+
};
|
|
1021
|
+
|
|
1022
|
+
const listEl = sessionPopEl.querySelector('[data-sp-list]');
|
|
1023
|
+
if (!list.length) {
|
|
1024
|
+
listEl.innerHTML = `<div style="padding:14px 8px;text-align:center;font-size:11.5px;color:var(--clado-ui-subtle);">${sessionFilter === 'archived' ? '暂无已归档会话' : '暂无进行中会话'}</div>`;
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
for (const item of list) {
|
|
1029
|
+
const row = document.createElement('div');
|
|
1030
|
+
row.className = 'clado-session-row' + (item.id === activeSessionId ? ' active' : '');
|
|
1031
|
+
const msgCount = Array.isArray(item.messages) ? item.messages.length : 0;
|
|
1032
|
+
|
|
1033
|
+
if (renamingSessionId === item.id) {
|
|
1034
|
+
row.innerHTML = `
|
|
1035
|
+
<input type="text" class="clado-field" data-rename-in value="${esc(item.title)}" style="padding:4px 8px;font-size:12px;border-radius:8px;flex:1;" />
|
|
1036
|
+
<button type="button" class="clado-dock-mini-btn" data-rename-ok style="color:var(--clado-ui-brand);">保存</button>
|
|
1037
|
+
<button type="button" class="clado-dock-mini-btn" data-rename-cancel>取消</button>
|
|
1038
|
+
`;
|
|
1039
|
+
const inp = row.querySelector('[data-rename-in]');
|
|
1040
|
+
const commitRename = async () => {
|
|
1041
|
+
const nextTitle = inp.value.trim();
|
|
1042
|
+
if (!nextTitle) { renamingSessionId = ''; renderSessionPop(); return; }
|
|
1043
|
+
const res = await fetch(withWs('/library/agent/sessions'), {
|
|
1044
|
+
method: 'POST',
|
|
1045
|
+
headers: { 'content-type': 'application/json' },
|
|
1046
|
+
body: JSON.stringify({ action: 'rename', id: item.id, title: nextTitle }),
|
|
1047
|
+
});
|
|
1048
|
+
if (res.ok) {
|
|
1049
|
+
item.title = nextTitle;
|
|
1050
|
+
showToast('已重命名为「' + nextTitle + '」');
|
|
1051
|
+
}
|
|
1052
|
+
renamingSessionId = '';
|
|
1053
|
+
renderRoleStrip();
|
|
1054
|
+
renderStream();
|
|
1055
|
+
renderSessionPop();
|
|
1056
|
+
};
|
|
1057
|
+
row.onclick = e => e.stopPropagation();
|
|
1058
|
+
row.querySelector('[data-rename-ok]').onclick = e => { e.stopPropagation(); commitRename(); };
|
|
1059
|
+
row.querySelector('[data-rename-cancel]').onclick = e => { e.stopPropagation(); renamingSessionId = ''; renderSessionPop(); };
|
|
1060
|
+
inp.addEventListener('keydown', e => {
|
|
1061
|
+
if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); commitRename(); }
|
|
1062
|
+
if (e.key === 'Escape') { e.preventDefault(); renamingSessionId = ''; renderSessionPop(); }
|
|
1063
|
+
});
|
|
1064
|
+
setTimeout(() => { inp.focus(); inp.select(); }, 0);
|
|
1065
|
+
} else {
|
|
1066
|
+
row.innerHTML = `
|
|
1067
|
+
<div style="min-width:0;flex:1;">
|
|
1068
|
+
<div style="font-size:12px;font-weight:580;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${esc(item.title)}</div>
|
|
1069
|
+
<div style="display:flex;align-items:center;gap:6px;margin-top:2px;font-size:10.5px;color:var(--clado-ui-subtle);">
|
|
1070
|
+
<span class="clado-chip ${TONE_CHIP[item.tone] || 'clado-chip-sky'}" style="padding:1px 6px;font-size:10px;">${esc(item.phase || '对话')}</span>
|
|
1071
|
+
<span>${msgCount} 条消息</span>
|
|
1072
|
+
</div>
|
|
1073
|
+
</div>
|
|
1074
|
+
<div class="clado-session-ops">
|
|
1075
|
+
<button type="button" class="clado-dock-mini-btn" data-op="rename" title="重命名" style="padding:3px 5px;">${ICONS.edit}</button>
|
|
1076
|
+
<button type="button" class="clado-dock-mini-btn" data-op="archive" title="${item.archived ? '恢复到进行中' : '归档会话'}" style="padding:3px 5px;">${ICONS.archive}</button>
|
|
1077
|
+
<button type="button" class="clado-dock-mini-btn" data-op="delete" title="删除会话" style="padding:3px 5px;color:#be123c;">${ICONS.trash}</button>
|
|
1078
|
+
</div>
|
|
1079
|
+
`;
|
|
1080
|
+
row.onclick = e => {
|
|
1081
|
+
e.stopPropagation();
|
|
1082
|
+
if (item.archived) {
|
|
1083
|
+
// Unarchive if user clicks an archived session directly, or let them view it
|
|
1084
|
+
selectSession(item.id, true);
|
|
1085
|
+
} else {
|
|
1086
|
+
selectSession(item.id, true);
|
|
1087
|
+
}
|
|
1088
|
+
closeSessionPop();
|
|
1089
|
+
};
|
|
1090
|
+
row.querySelector('[data-op="rename"]').onclick = e => {
|
|
1091
|
+
e.stopPropagation();
|
|
1092
|
+
renamingSessionId = item.id;
|
|
1093
|
+
renderSessionPop();
|
|
1094
|
+
};
|
|
1095
|
+
row.querySelector('[data-op="archive"]').onclick = async e => {
|
|
1096
|
+
e.stopPropagation();
|
|
1097
|
+
const nextArch = !item.archived;
|
|
1098
|
+
await fetch(withWs('/library/agent/sessions'), {
|
|
1099
|
+
method: 'POST',
|
|
1100
|
+
headers: { 'content-type': 'application/json' },
|
|
1101
|
+
body: JSON.stringify({ action: 'archive', id: item.id, archived: nextArch }),
|
|
1102
|
+
});
|
|
1103
|
+
item.archived = nextArch;
|
|
1104
|
+
if (nextArch && activeSessionId === item.id) {
|
|
1105
|
+
const fallback = sessions.find(x => !x.archived);
|
|
1106
|
+
if (fallback) activeSessionId = fallback.id;
|
|
1107
|
+
}
|
|
1108
|
+
showToast(nextArch ? '已归档会话' : '已恢复会话');
|
|
1109
|
+
renderRoleStrip();
|
|
1110
|
+
renderStream();
|
|
1111
|
+
renderSessionPop();
|
|
1112
|
+
};
|
|
1113
|
+
row.querySelector('[data-op="delete"]').onclick = async e => {
|
|
1114
|
+
e.stopPropagation();
|
|
1115
|
+
await fetch(withWs('/library/agent/sessions?id=' + encodeURIComponent(item.id)), { method: 'DELETE' });
|
|
1116
|
+
sessions = sessions.filter(x => x.id !== item.id);
|
|
1117
|
+
if (activeSessionId === item.id) {
|
|
1118
|
+
activeSessionId = sessions.find(x => !x.archived)?.id || sessions[0]?.id || '';
|
|
1119
|
+
}
|
|
1120
|
+
showToast('已删除会话');
|
|
1121
|
+
await refreshMeta();
|
|
1122
|
+
renderSessionPop();
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
listEl.append(row);
|
|
204
1126
|
}
|
|
205
|
-
return box;
|
|
206
1127
|
}
|
|
207
1128
|
|
|
208
1129
|
function closePopover() {
|
|
@@ -248,6 +1169,117 @@
|
|
|
248
1169
|
popoverEl.hidden = false;
|
|
249
1170
|
}
|
|
250
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
|
+
|
|
251
1283
|
function openNewRoleSessionPopover() {
|
|
252
1284
|
popoverEl.replaceChildren();
|
|
253
1285
|
const roles = meta?.roles || [];
|
|
@@ -255,22 +1287,10 @@
|
|
|
255
1287
|
const item = document.createElement('button');
|
|
256
1288
|
item.type = 'button';
|
|
257
1289
|
item.className = 'clado-pop-item';
|
|
258
|
-
item.innerHTML = `<span><strong>${esc(r.name)}</strong> · ${esc(r.phase)}</span><span class="clado-chip ${TONE_CHIP[r.tone] || 'clado-chip-sky'}"
|
|
1290
|
+
item.innerHTML = `<span><strong>${esc(r.name)}</strong> · ${esc(r.phase)}</span><span class="clado-chip ${TONE_CHIP[r.tone] || 'clado-chip-sky'}">新建会话</span>`;
|
|
259
1291
|
item.onclick = async () => {
|
|
260
1292
|
closePopover();
|
|
261
|
-
|
|
262
|
-
method: 'POST',
|
|
263
|
-
headers: { 'content-type': 'application/json' },
|
|
264
|
-
body: JSON.stringify({ roleId: r.id, title: r.name }),
|
|
265
|
-
});
|
|
266
|
-
const data = await res.json();
|
|
267
|
-
if (data?.session) {
|
|
268
|
-
sessions.push(data.session);
|
|
269
|
-
activeSessionId = data.session.id;
|
|
270
|
-
setDrawerOpen(true);
|
|
271
|
-
renderRoleStrip();
|
|
272
|
-
renderStream();
|
|
273
|
-
}
|
|
1293
|
+
await createNewSessionForCurrentRole(r);
|
|
274
1294
|
};
|
|
275
1295
|
popoverEl.append(item);
|
|
276
1296
|
}
|
|
@@ -286,13 +1306,16 @@
|
|
|
286
1306
|
|
|
287
1307
|
function updateSlashPopover() {
|
|
288
1308
|
const val = inputEl.value;
|
|
289
|
-
if (!val.startsWith('/')) {
|
|
1309
|
+
if (!val.startsWith('/') || val.includes('\n')) {
|
|
290
1310
|
if (!popoverEl.hidden && popoverEl.dataset.kind === 'slash') closePopover();
|
|
291
1311
|
return;
|
|
292
1312
|
}
|
|
293
1313
|
const q = val.slice(1).toLowerCase();
|
|
294
1314
|
const prompts = (meta?.ecosystem?.prompts || []).filter(p => !q || p.name.toLowerCase().includes(q));
|
|
295
|
-
if (!prompts.length) {
|
|
1315
|
+
if (!prompts.length) {
|
|
1316
|
+
if (popoverEl.dataset.kind === 'slash') closePopover();
|
|
1317
|
+
return;
|
|
1318
|
+
}
|
|
296
1319
|
popoverEl.dataset.kind = 'slash';
|
|
297
1320
|
popoverEl.replaceChildren();
|
|
298
1321
|
for (const p of prompts.slice(0, 8)) {
|
|
@@ -302,6 +1325,7 @@
|
|
|
302
1325
|
btn.innerHTML = `<span style="font-family:ui-monospace,monospace;">/${esc(p.name)}</span><span style="color:var(--clado-ui-subtle);font-size:11px;">${esc(p.description || p.scope)}</span>`;
|
|
303
1326
|
btn.onclick = () => {
|
|
304
1327
|
inputEl.value = '/' + p.name + ' ';
|
|
1328
|
+
autoGrowInput();
|
|
305
1329
|
closePopover();
|
|
306
1330
|
inputEl.focus();
|
|
307
1331
|
};
|
|
@@ -311,24 +1335,42 @@
|
|
|
311
1335
|
}
|
|
312
1336
|
|
|
313
1337
|
// =========================================================================
|
|
314
|
-
// 2. Streaming Pi Turn &
|
|
1338
|
+
// 2. Streaming Pi Turn, Live Tool Calls & Safe Cancel (Preserving History!)
|
|
315
1339
|
// =========================================================================
|
|
316
1340
|
async function streamAgentRequest(payload, targetSession) {
|
|
317
1341
|
setDrawerOpen(true);
|
|
318
1342
|
const s = targetSession || currentSession();
|
|
319
1343
|
if (!s) return;
|
|
320
1344
|
activeSessionId = s.id;
|
|
1345
|
+
try { localStorage.setItem('clado-active-session', s.id); } catch {}
|
|
321
1346
|
runningSessionId = s.id;
|
|
1347
|
+
stoppingTurn = false;
|
|
1348
|
+
pendingCancelPromise = null;
|
|
322
1349
|
s.status = 'running';
|
|
323
1350
|
s.messages = Array.isArray(s.messages) ? s.messages : [];
|
|
324
|
-
|
|
1351
|
+
const userPromptMsg = {
|
|
1352
|
+
id: 'local_u_' + Date.now(),
|
|
325
1353
|
role: 'user',
|
|
326
1354
|
text: payload.text || (payload.action === 'handoff' ? '按画布定稿契约开始执行' : ''),
|
|
327
1355
|
handoffFrom: payload.fromRoleName || '',
|
|
328
|
-
}
|
|
329
|
-
const liveAssistant = {
|
|
330
|
-
|
|
331
|
-
|
|
1356
|
+
};
|
|
1357
|
+
const liveAssistant = {
|
|
1358
|
+
id: 'local_a_' + Date.now(),
|
|
1359
|
+
role: 'assistant',
|
|
1360
|
+
text: '',
|
|
1361
|
+
tools: [],
|
|
1362
|
+
blocks: [],
|
|
1363
|
+
questions: [],
|
|
1364
|
+
activity: '正在思考并准备上下文…',
|
|
1365
|
+
};
|
|
1366
|
+
s.messages.push(userPromptMsg, liveAssistant);
|
|
1367
|
+
const localSnapshotMsgs = s.messages.slice();
|
|
1368
|
+
|
|
1369
|
+
sendBtn.textContent = '插话';
|
|
1370
|
+
stopBtn.hidden = false;
|
|
1371
|
+
stopBtn.disabled = false;
|
|
1372
|
+
stopBtn.textContent = '停止';
|
|
1373
|
+
syncSendModeUi();
|
|
332
1374
|
renderRoleStrip();
|
|
333
1375
|
renderStream();
|
|
334
1376
|
|
|
@@ -359,58 +1401,214 @@
|
|
|
359
1401
|
if (!line.trim()) continue;
|
|
360
1402
|
let ev;
|
|
361
1403
|
try { ev = JSON.parse(line); } catch { continue; }
|
|
362
|
-
if (ev.type === '
|
|
363
|
-
liveAssistant
|
|
364
|
-
|
|
1404
|
+
if (ev.type === 'thinking') {
|
|
1405
|
+
appendMessageThinking(liveAssistant, ev.text || '');
|
|
1406
|
+
liveAssistant.activity = '正在深度思考…';
|
|
1407
|
+
scheduleRenderStream();
|
|
1408
|
+
} else if (ev.type === 'text') {
|
|
1409
|
+
appendMessageText(liveAssistant, ev.text || '');
|
|
1410
|
+
liveAssistant.activity = '正在生成回复…';
|
|
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();
|
|
1430
|
+
}
|
|
365
1431
|
} else if (ev.type === 'tool') {
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
1432
|
+
const entry = upsertMessageTool(liveAssistant, ev);
|
|
1433
|
+
const stillRunning = [...liveAssistant.tools].reverse().find(t => t.status === 'running');
|
|
1434
|
+
if (stillRunning) {
|
|
1435
|
+
liveAssistant.activity = `正在执行 ${stillRunning.name}${stillRunning.argsSummary ? ' · ' + stillRunning.argsSummary : ''}`;
|
|
1436
|
+
} else if (entry.status === 'failed' || entry.isError) {
|
|
1437
|
+
liveAssistant.activity = `${entry.name || '工具'} 执行失败,正在诊断并修复…`;
|
|
1438
|
+
} else {
|
|
1439
|
+
liveAssistant.activity = '工具执行完成,正在继续…';
|
|
1440
|
+
}
|
|
369
1441
|
renderStream();
|
|
370
1442
|
} else if (ev.type === 'ask_user') {
|
|
371
|
-
liveAssistant.
|
|
1443
|
+
if (!liveAssistant.questions.some(q => q.questionId === ev.questionId)) {
|
|
1444
|
+
liveAssistant.questions.push({
|
|
1445
|
+
questionId: ev.questionId,
|
|
1446
|
+
question: ev.question,
|
|
1447
|
+
options: ev.options || [],
|
|
1448
|
+
answered: false,
|
|
1449
|
+
answer: '',
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
liveAssistant.activity = '等待你的确认…';
|
|
372
1453
|
renderStream();
|
|
373
1454
|
} else if (ev.type === 'focus') {
|
|
374
1455
|
actions.focusCanvas?.(ev.file, ev.heading);
|
|
375
1456
|
} else if (ev.type === 'status') {
|
|
1457
|
+
liveAssistant.activity = ev.text || liveAssistant.activity;
|
|
376
1458
|
showToast(ev.text);
|
|
1459
|
+
renderStream();
|
|
1460
|
+
} else if (ev.type === 'done') {
|
|
1461
|
+
if (ev.usage) s.contextUsage = ev.usage;
|
|
1462
|
+
if (ev.stopped && !liveAssistant.text.includes('已手动停止')) {
|
|
1463
|
+
appendMessageText(liveAssistant, '_(已手动停止,以上内容已保留)_');
|
|
1464
|
+
}
|
|
1465
|
+
liveAssistant.activity = '';
|
|
1466
|
+
dismissPendingQuestions(s);
|
|
1467
|
+
renderStream();
|
|
377
1468
|
} else if (ev.type === 'error') {
|
|
378
|
-
|
|
1469
|
+
appendMessageText(liveAssistant, '提示:' + (ev.message || '执行失败'));
|
|
1470
|
+
liveAssistant.activity = '';
|
|
1471
|
+
dismissPendingQuestions(s);
|
|
379
1472
|
renderStream();
|
|
380
1473
|
}
|
|
381
1474
|
}
|
|
382
1475
|
}
|
|
383
1476
|
} catch (err) {
|
|
384
|
-
if (err.name
|
|
385
|
-
|
|
1477
|
+
if (err.name === 'AbortError' || stoppingTurn) {
|
|
1478
|
+
if (!liveAssistant.text.includes('已手动停止')) {
|
|
1479
|
+
appendMessageText(liveAssistant, '_(已手动停止,以上内容已保留)_');
|
|
1480
|
+
}
|
|
1481
|
+
dismissPendingQuestions(s);
|
|
1482
|
+
renderStream();
|
|
1483
|
+
} else {
|
|
1484
|
+
appendMessageText(liveAssistant, err.message || '执行中断');
|
|
1485
|
+
dismissPendingQuestions(s);
|
|
386
1486
|
renderStream();
|
|
387
1487
|
}
|
|
388
1488
|
} finally {
|
|
1489
|
+
if (pendingCancelPromise) {
|
|
1490
|
+
await pendingCancelPromise.catch(() => {});
|
|
1491
|
+
}
|
|
389
1492
|
s.status = 'idle';
|
|
1493
|
+
liveAssistant.activity = '';
|
|
1494
|
+
dismissPendingQuestions(s);
|
|
390
1495
|
runningSessionId = '';
|
|
391
1496
|
activeAbort = null;
|
|
1497
|
+
stoppingTurn = false;
|
|
1498
|
+
pendingCancelPromise = null;
|
|
392
1499
|
sendBtn.textContent = '发送';
|
|
393
|
-
|
|
1500
|
+
sendBtn.disabled = false;
|
|
1501
|
+
stopBtn.hidden = true;
|
|
1502
|
+
stopBtn.disabled = false;
|
|
1503
|
+
stopBtn.textContent = '停止';
|
|
1504
|
+
syncSendModeUi();
|
|
1505
|
+
|
|
1506
|
+
// Sync from server, but NEVER lose local messages if server hasn't flushed yet
|
|
1507
|
+
const prevCount = localSnapshotMsgs.length;
|
|
1508
|
+
const fresh = await refreshMeta();
|
|
1509
|
+
if (fresh) {
|
|
1510
|
+
const synced = sessions.find(x => x.id === s.id);
|
|
1511
|
+
if (synced && (!Array.isArray(synced.messages) || synced.messages.length < prevCount)) {
|
|
1512
|
+
synced.messages = localSnapshotMsgs;
|
|
1513
|
+
dismissPendingQuestions(synced);
|
|
1514
|
+
renderStream();
|
|
1515
|
+
}
|
|
1516
|
+
} else {
|
|
1517
|
+
renderRoleStrip();
|
|
1518
|
+
renderStream();
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
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();
|
|
394
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);
|
|
395
1547
|
}
|
|
396
1548
|
|
|
397
1549
|
async function handleSend() {
|
|
1550
|
+
const text = inputEl.value.trim();
|
|
398
1551
|
if (runningSessionId) {
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
1552
|
+
const targetId = runningSessionId;
|
|
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;
|
|
1566
|
+
}
|
|
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();
|
|
1591
|
+
}
|
|
1592
|
+
showToast('已发送中途纠偏指令');
|
|
1593
|
+
} catch {
|
|
1594
|
+
showToast('当前回合暂不支持插话,可稍候或点击停止');
|
|
1595
|
+
}
|
|
405
1596
|
return;
|
|
406
1597
|
}
|
|
407
|
-
|
|
1598
|
+
|
|
408
1599
|
if (!text) return;
|
|
409
1600
|
inputEl.value = '';
|
|
1601
|
+
autoGrowInput();
|
|
410
1602
|
closePopover();
|
|
411
1603
|
const s = currentSession();
|
|
412
1604
|
if (!s) return;
|
|
413
|
-
|
|
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
|
+
}
|
|
414
1612
|
await streamAgentRequest({
|
|
415
1613
|
action: 'prompt',
|
|
416
1614
|
session: s.id,
|
|
@@ -451,6 +1649,20 @@
|
|
|
451
1649
|
// Bind dock events
|
|
452
1650
|
dock.querySelector('[data-toggle-drawer]').onclick = () => setDrawerOpen(!drawerOpen);
|
|
453
1651
|
dock.querySelector('[data-collapse]').onclick = () => setDrawerOpen(false);
|
|
1652
|
+
dock.querySelector('[data-new-session]').onclick = e => {
|
|
1653
|
+
e.stopPropagation();
|
|
1654
|
+
createNewSessionForCurrentRole();
|
|
1655
|
+
};
|
|
1656
|
+
sessionTriggerEl.onclick = e => {
|
|
1657
|
+
e.stopPropagation();
|
|
1658
|
+
closePopover();
|
|
1659
|
+
if (!sessionPopEl.hidden) {
|
|
1660
|
+
closeSessionPop();
|
|
1661
|
+
} else {
|
|
1662
|
+
renderSessionPop();
|
|
1663
|
+
sessionPopEl.hidden = false;
|
|
1664
|
+
}
|
|
1665
|
+
};
|
|
454
1666
|
dock.querySelector('[data-rollback]').onclick = async () => {
|
|
455
1667
|
const s = currentSession();
|
|
456
1668
|
if (!s) return;
|
|
@@ -468,16 +1680,80 @@
|
|
|
468
1680
|
});
|
|
469
1681
|
modelChip.onclick = e => {
|
|
470
1682
|
e.stopPropagation();
|
|
471
|
-
|
|
1683
|
+
closeSessionPop();
|
|
1684
|
+
if (!popoverEl.hidden && popoverEl.dataset.kind === 'model') closePopover();
|
|
472
1685
|
else { popoverEl.dataset.kind = 'model'; openModelPopover(); }
|
|
473
1686
|
};
|
|
474
|
-
|
|
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
|
+
}
|
|
1695
|
+
sendModeBtn.onclick = e => {
|
|
1696
|
+
e.stopPropagation();
|
|
1697
|
+
sendMode = sendMode === 'ctrl-enter' ? 'enter' : 'ctrl-enter';
|
|
1698
|
+
try { localStorage.setItem('clado-send-mode', sendMode); } catch {}
|
|
1699
|
+
syncSendModeUi();
|
|
1700
|
+
showToast(sendMode === 'ctrl-enter' ? '已切换:Enter 换行,Ctrl+Enter 发送' : '已切换:Enter 发送,Shift+Enter 换行');
|
|
1701
|
+
};
|
|
1702
|
+
inputEl.addEventListener('focus', () => renderContextChips());
|
|
1703
|
+
inputEl.addEventListener('input', () => {
|
|
1704
|
+
autoGrowInput();
|
|
1705
|
+
updateSlashPopover();
|
|
1706
|
+
});
|
|
475
1707
|
inputEl.addEventListener('keydown', e => {
|
|
476
|
-
if (e.key === '
|
|
477
|
-
|
|
1708
|
+
if (e.key === 'Escape') {
|
|
1709
|
+
closePopover();
|
|
1710
|
+
closeSessionPop();
|
|
1711
|
+
return;
|
|
1712
|
+
}
|
|
1713
|
+
if (e.key === 'Enter' && !e.isComposing) {
|
|
1714
|
+
if (sendMode === 'ctrl-enter') {
|
|
1715
|
+
if (e.ctrlKey || e.metaKey) {
|
|
1716
|
+
e.preventDefault();
|
|
1717
|
+
handleSend();
|
|
1718
|
+
}
|
|
1719
|
+
// plain Enter inserts newline naturally
|
|
1720
|
+
} else {
|
|
1721
|
+
if (!e.shiftKey) {
|
|
1722
|
+
e.preventDefault();
|
|
1723
|
+
handleSend();
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
478
1727
|
});
|
|
479
1728
|
sendBtn.onclick = handleSend;
|
|
480
|
-
|
|
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
|
+
});
|
|
1749
|
+
document.addEventListener('click', e => {
|
|
1750
|
+
if (!dock.contains(e.target)) {
|
|
1751
|
+
closePopover();
|
|
1752
|
+
closeSessionPop();
|
|
1753
|
+
} else if (!sessionPopEl.contains(e.target) && !sessionTriggerEl.contains(e.target)) {
|
|
1754
|
+
closeSessionPop();
|
|
1755
|
+
}
|
|
1756
|
+
});
|
|
481
1757
|
|
|
482
1758
|
// =========================================================================
|
|
483
1759
|
// 3. Unified 5-Tab Settings Center Modal
|
|
@@ -504,7 +1780,7 @@
|
|
|
504
1780
|
</div>
|
|
505
1781
|
<button type="button" class="clado-ui-button" data-close-settings style="width:100%;border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);border-radius:12px;">← 返回画布</button>
|
|
506
1782
|
</aside>
|
|
507
|
-
<main class="clado-settings-body" data-sbody></main>
|
|
1783
|
+
<main class="clado-settings-body clado-scroll" data-sbody></main>
|
|
508
1784
|
</div>
|
|
509
1785
|
`;
|
|
510
1786
|
stageRoot().append(settingsMask);
|
|
@@ -550,35 +1826,164 @@
|
|
|
550
1826
|
}
|
|
551
1827
|
|
|
552
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
|
+
|
|
553
1843
|
sBody.innerHTML = `
|
|
554
1844
|
<div>
|
|
555
1845
|
<div style="font-size:18px;font-weight:630;">模型与供应商</div>
|
|
556
|
-
<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>
|
|
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>
|
|
557
1910
|
</div>
|
|
1911
|
+
|
|
558
1912
|
<div data-provider-list style="display:flex;flex-direction:column;gap:10px;"></div>
|
|
559
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
|
+
|
|
560
1942
|
const list = sBody.querySelector('[data-provider-list]');
|
|
561
1943
|
for (const p of meta.providers || []) {
|
|
562
1944
|
const card = document.createElement('div');
|
|
563
1945
|
card.className = 'clado-well-box';
|
|
564
1946
|
const isEditing = editingProviderId === p.id;
|
|
1947
|
+
const recs = Array.isArray(p.recommendedModels) ? p.recommendedModels : [];
|
|
565
1948
|
card.innerHTML = `
|
|
566
1949
|
<div class="clado-setting-row">
|
|
567
1950
|
<div>
|
|
568
|
-
<div style="display:flex;align-items:center;gap:8px;">
|
|
1951
|
+
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
|
|
569
1952
|
<span style="font-size:13.5px;font-weight:610;">${esc(p.name)}</span>
|
|
570
1953
|
${p.configured ? `<span class="clado-chip clado-chip-mint">已连接${p.maskedKey ? ' · ' + esc(p.maskedKey) : ''}</span>` : '<span class="clado-chip clado-chip-neutral">未配置</span>'}
|
|
571
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>` : ''}
|
|
572
1956
|
</div>
|
|
573
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>
|
|
574
1958
|
</div>
|
|
575
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>
|
|
576
1960
|
</div>
|
|
577
1961
|
${isEditing ? `
|
|
578
|
-
<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
|
+
` : ''}
|
|
579
1971
|
${!p.keyless ? `<input class="clado-field" data-f-key type="password" placeholder="API Key(留空保持不变)" value="${esc(p.maskedKey)}" />` : ''}
|
|
580
1972
|
<input class="clado-field" data-f-url type="text" placeholder="Base URL(可选自定义代理地址)" value="${esc(p.baseUrl)}" />
|
|
581
|
-
<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>
|
|
582
1987
|
<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:4px;">
|
|
583
1988
|
${p.configured ? '<button type="button" class="clado-ui-button" data-del style="color:#be123c;">清除凭据</button>' : '<span></span>'}
|
|
584
1989
|
<button type="button" class="clado-ui-button clado-ui-button-primary" data-save>保存并设为默认</button>
|
|
@@ -591,6 +1996,15 @@
|
|
|
591
1996
|
renderSettings();
|
|
592
1997
|
};
|
|
593
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
|
+
});
|
|
594
2008
|
card.querySelector('[data-save]').onclick = async () => {
|
|
595
2009
|
try {
|
|
596
2010
|
await apiConfig({
|
|
@@ -600,9 +2014,13 @@
|
|
|
600
2014
|
apiKey: card.querySelector('[data-f-key]')?.value || '',
|
|
601
2015
|
baseUrl: card.querySelector('[data-f-url]')?.value || '',
|
|
602
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),
|
|
603
2020
|
setAsDefault: true,
|
|
604
2021
|
});
|
|
605
2022
|
editingProviderId = '';
|
|
2023
|
+
renderContextMeter();
|
|
606
2024
|
renderSettings();
|
|
607
2025
|
showToast('已保存 ' + p.name + ' 并写入 Pi 原生配置');
|
|
608
2026
|
} catch (e) { showToast(e.message); }
|
|
@@ -611,6 +2029,7 @@
|
|
|
611
2029
|
if (delBtn) delBtn.onclick = async () => {
|
|
612
2030
|
await apiConfig({ action: 'delete_provider', providerId: p.id });
|
|
613
2031
|
editingProviderId = '';
|
|
2032
|
+
renderContextMeter();
|
|
614
2033
|
renderSettings();
|
|
615
2034
|
showToast('已清除 ' + p.name + ' 配置');
|
|
616
2035
|
};
|
|
@@ -634,7 +2053,7 @@
|
|
|
634
2053
|
<input class="clado-field" data-r-phase placeholder="阶段标签(如:审计阶段)" />
|
|
635
2054
|
</div>
|
|
636
2055
|
<input class="clado-field" data-r-desc placeholder="一句话职责描述" />
|
|
637
|
-
<textarea class="clado-field" data-r-prompt rows="3" placeholder="系统提示词(决定该角色如何协作修改画布或执行代码)"></textarea>
|
|
2056
|
+
<textarea class="clado-field clado-scroll" data-r-prompt rows="3" placeholder="系统提示词(决定该角色如何协作修改画布或执行代码)"></textarea>
|
|
638
2057
|
<div style="display:flex;justify-content:flex-end;gap:8px;">
|
|
639
2058
|
<button type="button" class="clado-ui-button" data-r-cancel>取消</button>
|
|
640
2059
|
<button type="button" class="clado-ui-button clado-ui-button-primary" data-r-save>保存角色</button>
|
|
@@ -719,7 +2138,6 @@
|
|
|
719
2138
|
};
|
|
720
2139
|
|
|
721
2140
|
const list = sBody.querySelector('[data-ext-list]');
|
|
722
|
-
// Built-in Clado Bridge
|
|
723
2141
|
const bridgeRow = document.createElement('div');
|
|
724
2142
|
bridgeRow.className = 'clado-well-box clado-setting-row';
|
|
725
2143
|
bridgeRow.innerHTML = `
|
|
@@ -735,7 +2153,6 @@
|
|
|
735
2153
|
`;
|
|
736
2154
|
list.append(bridgeRow);
|
|
737
2155
|
|
|
738
|
-
// Pi Packages
|
|
739
2156
|
for (const pkg of eco.packages || []) {
|
|
740
2157
|
const row = document.createElement('div');
|
|
741
2158
|
row.className = 'clado-well-box clado-setting-row';
|
|
@@ -758,7 +2175,6 @@
|
|
|
758
2175
|
list.append(row);
|
|
759
2176
|
}
|
|
760
2177
|
|
|
761
|
-
// Pi MCP Servers
|
|
762
2178
|
for (const m of eco.mcpServers || []) {
|
|
763
2179
|
const row = document.createElement('div');
|
|
764
2180
|
row.className = 'clado-well-box clado-setting-row';
|
|
@@ -787,7 +2203,6 @@
|
|
|
787
2203
|
list.append(row);
|
|
788
2204
|
}
|
|
789
2205
|
|
|
790
|
-
// Pi Skills
|
|
791
2206
|
for (const sk of eco.skills || []) {
|
|
792
2207
|
const row = document.createElement('div');
|
|
793
2208
|
row.className = 'clado-well-box clado-setting-row';
|
|
@@ -806,7 +2221,6 @@
|
|
|
806
2221
|
list.append(row);
|
|
807
2222
|
}
|
|
808
2223
|
|
|
809
|
-
// Pi /Prompts
|
|
810
2224
|
for (const pr of eco.prompts || []) {
|
|
811
2225
|
const row = document.createElement('div');
|
|
812
2226
|
row.className = 'clado-well-box clado-setting-row';
|
|
@@ -825,7 +2239,6 @@
|
|
|
825
2239
|
list.append(row);
|
|
826
2240
|
}
|
|
827
2241
|
|
|
828
|
-
// Optional Canvas Components (e.g. Lo-Fi widget)
|
|
829
2242
|
for (const c of comps) {
|
|
830
2243
|
const row = document.createElement('div');
|
|
831
2244
|
row.className = 'clado-well-box clado-setting-row';
|
|
@@ -859,7 +2272,7 @@
|
|
|
859
2272
|
</div>
|
|
860
2273
|
<button type="button" class="clado-ui-button clado-ui-button-primary" data-save-mem>保存 AGENTS.md</button>
|
|
861
2274
|
</div>
|
|
862
|
-
<textarea class="clado-field" data-mem-text style="flex:1;min-height:360px;font-family:ui-monospace,monospace;line-height:1.65;resize:none;" placeholder="# AGENTS.md - 写下本项目的代码约定、测试命令与架构约束…">${esc(content)}</textarea>
|
|
2275
|
+
<textarea class="clado-field clado-scroll" data-mem-text style="flex:1;min-height:360px;font-family:ui-monospace,monospace;line-height:1.65;resize:none;" placeholder="# AGENTS.md - 写下本项目的代码约定、测试命令与架构约束…">${esc(content)}</textarea>
|
|
863
2276
|
`;
|
|
864
2277
|
sBody.querySelector('[data-save-mem]').onclick = async () => {
|
|
865
2278
|
try {
|
|
@@ -969,7 +2382,7 @@
|
|
|
969
2382
|
meta = data;
|
|
970
2383
|
sessions = Array.isArray(data.sessions) ? data.sessions : [];
|
|
971
2384
|
if (!activeSessionId || !sessions.some(s => s.id === activeSessionId)) {
|
|
972
|
-
activeSessionId = sessions[0]?.id || '';
|
|
2385
|
+
activeSessionId = sessions.find(s => !s.archived)?.id || sessions[0]?.id || '';
|
|
973
2386
|
}
|
|
974
2387
|
renderRoleStrip();
|
|
975
2388
|
renderStream();
|
|
@@ -991,7 +2404,7 @@
|
|
|
991
2404
|
async function startCodeAnalysis(templateKey = 'arch') {
|
|
992
2405
|
const promptText = CODE_ANALYSIS_PROMPTS[templateKey] || CODE_ANALYSIS_PROMPTS.arch;
|
|
993
2406
|
if (!sessions.length) await refreshMeta();
|
|
994
|
-
const arch = sessions.find(s => s.roleId === 'architect') || sessions[0];
|
|
2407
|
+
const arch = sessions.find(s => !s.archived && s.roleId === 'architect') || sessions[0];
|
|
995
2408
|
if (!arch) return;
|
|
996
2409
|
await streamAgentRequest({
|
|
997
2410
|
action: 'prompt',
|
|
@@ -1016,6 +2429,7 @@
|
|
|
1016
2429
|
getMeta: () => meta,
|
|
1017
2430
|
isComponentEnabled,
|
|
1018
2431
|
setDrawerOpen,
|
|
2432
|
+
renderMarkdown,
|
|
1019
2433
|
};
|
|
1020
2434
|
|
|
1021
2435
|
refreshMeta();
|
|
@@ -1028,7 +2442,10 @@
|
|
|
1028
2442
|
refreshMeta,
|
|
1029
2443
|
focusComposer(prefill = '') {
|
|
1030
2444
|
setDrawerOpen(true);
|
|
1031
|
-
if (prefill)
|
|
2445
|
+
if (prefill) {
|
|
2446
|
+
inputEl.value = prefill;
|
|
2447
|
+
autoGrowInput();
|
|
2448
|
+
}
|
|
1032
2449
|
inputEl.focus();
|
|
1033
2450
|
},
|
|
1034
2451
|
};
|