cladogram 0.5.5-beta.6 → 0.5.5-beta.7

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.
@@ -1,4 +1,44 @@
1
1
  (() => {
2
+ const PALETTES = {
3
+ blue: { muted: '#85c3ff', vivid: '#3b82f6', glow: 'rgba(59, 130, 246, 0.14)', tagClass: 'clado-tag-blue' },
4
+ teal: { muted: '#6be6c1', vivid: '#10b981', glow: 'rgba(16, 185, 129, 0.14)', tagClass: 'clado-tag-teal' },
5
+ violet: { muted: '#c0a9ff', vivid: '#8b5cf6', glow: 'rgba(139, 92, 246, 0.14)', tagClass: 'clado-tag-violet' },
6
+ amber: { muted: '#ffd275', vivid: '#f59e0b', glow: 'rgba(245, 158, 11, 0.14)', tagClass: 'clado-tag-amber' },
7
+ cyan: { muted: '#6ad9ff', vivid: '#0ea5e9', glow: 'rgba(14, 165, 233, 0.14)', tagClass: 'clado-tag-blue' },
8
+ rose: { muted: '#ffa3cf', vivid: '#f43f5e', glow: 'rgba(244, 63, 94, 0.14)', tagClass: 'clado-tag-violet' },
9
+ };
10
+
11
+ const PERSONA_META = {
12
+ architect: { label: '研发架构师', pal: 'blue', defaultMode: 'design' },
13
+ coder: { label: '后端实现者', pal: 'teal', defaultMode: 'design' },
14
+ qa: { label: 'QA 测试专家', pal: 'violet', defaultMode: 'qa' },
15
+ auditor: { label: '验收审计官', pal: 'amber', defaultMode: 'audit' },
16
+ custom: { label: '自定义分身', pal: 'cyan', defaultMode: 'general' },
17
+ };
18
+
19
+ const CANVAS_MEM_CYCLE = [
20
+ ['delta', '智能增量'],
21
+ ['outline', '仅大纲'],
22
+ ['full', '每次全量'],
23
+ ['off', '关闭'],
24
+ ];
25
+ const TIME_MODE_CYCLE = [
26
+ ['none', '不注入'],
27
+ ['date_only', '仅日期'],
28
+ ['tail_exact', '尾部精确时间'],
29
+ ['system_head', '系统头时间'],
30
+ ];
31
+ const TTL_CYCLE = [
32
+ [6, '6 小时'],
33
+ [24, '24 小时'],
34
+ [0, '不自动归档'],
35
+ ];
36
+ const PERM_CYCLE = [
37
+ ['readonly_free', '只读免审'],
38
+ ['ask_always', '每次询问'],
39
+ ['allow_all', '自动允许'],
40
+ ];
41
+
2
42
  window.CladoAgentPlugin = (host, {
3
43
  readCanvas,
4
44
  viewId,
@@ -9,102 +49,242 @@
9
49
  setFollowAi = () => {},
10
50
  focusTarget = () => {},
11
51
  }) => {
12
- const metaEndpoint = endpoint.replace(/(\/library\/agent)(?=\?|$)/, '$1/meta');
13
- const sessionsEndpoint = endpoint.replace(/(\/library\/agent)(?=\?|$)/, '$1/sessions');
14
- const sessionUrl = id => {
15
- if (!id) return sessionsEndpoint;
16
- return sessionsEndpoint + (sessionsEndpoint.includes('?') ? '&' : '?') + 'id=' + encodeURIComponent(id);
52
+ const subEndpoint = suffix => endpoint.replace(/(\/library\/agent)(?=\?|$)/, '$1' + suffix);
53
+ const metaEndpoint = subEndpoint('/meta');
54
+ const sessionsEndpoint = subEndpoint('/sessions');
55
+ const configEndpoint = subEndpoint('/config');
56
+ const withParams = (base, params) => {
57
+ const entries = Object.entries(params || {}).filter(([, v]) => v !== undefined && v !== null && v !== '');
58
+ if (!entries.length) return base;
59
+ const qs = new URLSearchParams(entries).toString();
60
+ return base + (base.includes('?') ? '&' : '?') + qs;
17
61
  };
62
+ const sessionUrl = (id, extra = {}) => withParams(sessionsEndpoint, { ...(id ? { id } : {}), ...extra });
18
63
 
19
- const root = document.createElement('div');
20
- root.className = 'clado-agent';
21
- root.innerHTML = `
22
- <button class="clado-ui-glass clado-ui-button clado-agent-launch" type="button" aria-expanded="false" aria-controls="clado-agent-panel">
23
- <svg aria-hidden="true" viewBox="0 0 24 24"><path d="M10 20h4m-4-3h4v-2c0-.7.3-1.2.9-1.7a4.5 4.5 0 1 0-5.8 0c.6.5.9 1 .9 1.7zM18 3v4m-2-2h4"/></svg>
24
- 灵感
25
- </button>
26
- <section id="clado-agent-panel" class="clado-ui-glass clado-ui-glass-panel clado-agent-panel" aria-labelledby="clado-agent-title" hidden>
27
- <span class="clado-ai-aura" aria-hidden="true"></span>
28
- <div class="clado-agent-panel-body">
29
- <header>
30
- <div class="clado-agent-heading"><h2 id="clado-agent-title">灵感</h2><small class="clado-agent-provider"></small></div>
31
- <div class="clado-agent-header-actions">
32
- <button type="button" class="clado-ui-button clado-agent-follow" aria-pressed="${initialFollowAi ? 'true' : 'false'}" title="跟随 AI 视角:AI 定位或修改卡片时平滑平移镜头">跟随</button>
33
- <button type="button" class="clado-ui-button clado-agent-history" aria-expanded="false" title="切换历史会话">历史</button>
34
- <button type="button" class="clado-ui-button clado-agent-new">新对话</button>
35
- <button type="button" class="clado-ui-button clado-agent-close" aria-label="关闭 灵感 对话">×</button>
64
+ // 1. 右下角收起态悬浮球(最小化时显示,与左下角文档目录对称共存)
65
+ const orbWrap = document.createElement('div');
66
+ orbWrap.className = 'clado-agent-orb-wrap';
67
+ orbWrap.innerHTML = `
68
+ <button type="button" class="clado-agent-orb clado-agent-glass" aria-label="展开灵感坞">
69
+ <span class="clado-agent-orb-star" aria-hidden="true">✦</span>
70
+ <span class="clado-agent-orb-text">灵感</span>
71
+ </button>`;
72
+ host.mount('bottom-right', orbWrap, 'clado.agent');
73
+
74
+ // 2. 底部居中冰晶毛玻璃灵感坞(PC 与移动端统一形态)
75
+ const dock = document.createElement('div');
76
+ dock.className = 'clado-agent-dock';
77
+ dock.innerHTML = `
78
+ <div class="clado-collapse-wrap closed" data-role="cmd-wrap">
79
+ <div class="clado-collapse-inner">
80
+ <div class="clado-cmd-approve-bar clado-agent-glass">
81
+ <div class="clado-cmd-approve-copy">
82
+ <strong data-role="cmd-who">会话</strong> 请求 <code data-role="cmd-code"></code>
83
+ </div>
84
+ <div class="clado-cmd-approve-actions">
85
+ <button type="button" class="clado-cmd-btn allow" data-cmd-decision="allow">允许</button>
86
+ <button type="button" class="clado-cmd-btn session" data-cmd-decision="session_allow">免审</button>
87
+ <button type="button" class="clado-cmd-btn deny" data-cmd-decision="deny">拒绝</button>
36
88
  </div>
37
- </header>
38
- <div class="clado-agent-sessions" hidden></div>
39
- <div class="clado-agent-modes" role="group" aria-label="工作模式">
40
- <button type="button" class="clado-ui-button clado-agent-chip" data-workflow="design" aria-pressed="true">架构设计</button>
41
- <button type="button" class="clado-ui-button clado-agent-chip" data-workflow="qa" aria-pressed="false">测试用例</button>
42
- <button type="button" class="clado-ui-button clado-agent-chip" data-workflow="audit" aria-pressed="false">Diff 验收</button>
43
- <button type="button" class="clado-ui-button clado-agent-chip" data-workflow="dispatch" aria-pressed="false">派发开发</button>
44
89
  </div>
45
- <div class="clado-agent-persona-bar">
46
- <label for="clado-agent-persona">人设</label>
47
- <select id="clado-agent-persona" class="clado-agent-select">
48
- <option value="architect">研发架构师</option>
49
- <option value="qa">QA 测试专家</option>
50
- <option value="auditor">验收审计官</option>
51
- </select>
90
+ </div>
91
+ </div>
92
+
93
+ <div class="clado-single-wrap" data-role="single-wrap">
94
+ <div class="clado-single-clip">
95
+ <section id="clado-agent-panel" class="clado-single-panel clado-agent-panel clado-agent-glass" aria-label="会话详情">
96
+ <span class="clado-ai-aura" aria-hidden="true"></span>
97
+ <div class="clado-sp-body-fade" data-role="sp-inner">
98
+ <div class="clado-sp-header">
99
+ <div class="clado-sp-title-group">
100
+ <strong class="clado-sp-name" data-role="sp-name">架构师</strong>
101
+ <span class="clado-tag-pill clado-tag-blue" data-role="sp-persona-tag">研发架构师</span>
102
+ </div>
103
+ <div class="clado-sp-actions">
104
+ <div class="clado-tab-group" role="group" aria-label="规划或执行模式">
105
+ <button type="button" class="clado-tab-btn" data-exec-mode="plan">规划</button>
106
+ <button type="button" class="clado-tab-btn active" data-exec-mode="act">执行</button>
107
+ </div>
108
+ <button type="button" class="clado-icon-act" data-role="follow-btn" aria-pressed="${initialFollowAi ? 'true' : 'false'}" title="AI 修改卡片时自动跟随镜头">跟随</button>
109
+ <button type="button" class="clado-icon-act" data-role="open-settings" title="Agent 设置与记忆调试">设置</button>
110
+ <button type="button" class="clado-icon-act" data-role="archive-btn" title="归档当前会话">归档</button>
111
+ <button type="button" class="clado-icon-act del" data-role="delete-btn" title="删除当前会话">删除</button>
112
+ <button type="button" class="clado-icon-act" data-role="close-single" aria-label="收起详情">收起 ⌄</button>
113
+ </div>
114
+ </div>
115
+
116
+ <div class="clado-sp-subbar">
117
+ <div class="clado-sp-workflows" role="group" aria-label="协作工作流">
118
+ <button type="button" class="clado-tab-btn active" data-workflow="design">架构设计</button>
119
+ <button type="button" class="clado-tab-btn" data-workflow="qa">测试用例</button>
120
+ <button type="button" class="clado-tab-btn" data-workflow="audit">Diff 验收</button>
121
+ <button type="button" class="clado-tab-btn" data-workflow="dispatch">派发开发</button>
122
+ </div>
123
+ <div class="clado-sp-executor-wrap" data-role="executor-wrap" hidden>
124
+ <select class="clado-agent-select" data-role="executor-select" aria-label="ACP 执行器"></select>
125
+ </div>
126
+ </div>
127
+
128
+ <div class="clado-collapse-wrap closed" data-role="plan-banner-wrap">
129
+ <div class="clado-collapse-inner">
130
+ <div class="clado-plan-banner">只读规划中:已拦截写画布与写命令,仅允许探针读取与拆解步骤。</div>
131
+ </div>
132
+ </div>
133
+
134
+ <div class="clado-todo-box" data-role="todo-box" hidden>
135
+ <div class="clado-todo-head">
136
+ <span class="clado-todo-summary" data-role="todo-summary"></span>
137
+ <span class="clado-todo-arrow" data-role="todo-arrow">展开 ▾</span>
138
+ </div>
139
+ <div class="clado-collapse-wrap closed" data-role="todo-collapse">
140
+ <div class="clado-collapse-inner">
141
+ <div class="clado-todo-list" data-role="todo-list"></div>
142
+ </div>
143
+ </div>
144
+ </div>
145
+
146
+ <div class="clado-agent-log" role="log" aria-label="会话消息" aria-live="off"></div>
147
+ <p class="clado-agent-status" role="status" hidden></p>
148
+ </div>
149
+ </section>
150
+ </div>
151
+ </div>
152
+
153
+ <div class="clado-peer-cluster" data-role="peer-cluster" role="tablist" aria-label="活跃与历史会话"></div>
154
+
155
+ <form class="clado-agent-shell clado-agent-glass" data-role="agent-shell">
156
+ <button type="button" class="clado-agent-min-btn" data-role="minimize-btn" title="收起灵感" aria-label="收起灵感">✦</button>
157
+ <input type="text" class="clado-agent-input" aria-label="给 灵感 的消息" maxlength="12000" autocomplete="off" />
158
+ <button type="button" class="clado-agent-stop-btn" data-role="stop-btn" hidden>停止</button>
159
+ <button type="submit" class="clado-agent-send-btn" data-role="send-btn" disabled>发送</button>
160
+ <div class="clado-edge-aura" aria-hidden="true">
161
+ <div class="clado-edge-aura-bloom"></div>
162
+ <div class="clado-edge-aura-line"><div class="clado-edge-aura-runner"></div></div>
163
+ </div>
164
+ </form>`;
165
+ host.mount('bottom-center', dock, 'clado.agent');
166
+
167
+ // 3. 顶层上下文菜单、设置调试面板与轻提示气泡(直挂 body,零祖先裁剪)
168
+ const ctxMenu = document.createElement('div');
169
+ ctxMenu.className = 'clado-agent-ctx-menu';
170
+ document.body.append(ctxMenu);
171
+
172
+ const configView = document.createElement('div');
173
+ configView.className = 'clado-agent-overlay';
174
+ configView.innerHTML = `
175
+ <div class="clado-panel-container clado-agent-glass clado-cfg-stage">
176
+ <div class="clado-cfg-page" data-role="cfg-home">
177
+ <div style="display:flex;align-items:center;justify-content:space-between;padding:0 4px 10px;">
178
+ <span style="font-size:16px;font-weight:700;">Agent 设置</span>
179
+ <button type="button" class="clado-tab-btn active" data-cfg-act="close-settings" style="padding:5px 12px;font-size:12px;">完成</button>
180
+ </div>
181
+
182
+ <div class="clado-group-title">上下文与记忆</div>
183
+ <div class="clado-settings-group" style="margin-bottom:13px;">
184
+ <div class="clado-s-row clickable" data-cfg-act="cycle" data-cfg-kind="canvas">
185
+ <span class="clado-s-title">画布实时记忆</span>
186
+ <span class="clado-s-val"><span data-cfg-val="canvas">智能增量</span> <span style="opacity:.45;">›</span></span>
187
+ </div>
188
+ <div class="clado-s-row clickable" data-cfg-act="cycle" data-cfg-kind="time">
189
+ <span class="clado-s-title">时间信息注入</span>
190
+ <span class="clado-s-val"><span data-cfg-val="time">仅日期</span> <span style="opacity:.45;">›</span></span>
191
+ </div>
192
+ <div class="clado-s-row">
193
+ <span class="clado-s-title">工作区全局目录索引</span>
194
+ <button type="button" class="clado-switch-btn on" data-cfg-act="toggle-map" aria-label="工作区全局目录索引"><i></i></button>
195
+ </div>
196
+ <div class="clado-s-row clickable" data-cfg-act="open-sub" data-sub="memory">
197
+ <span class="clado-s-title">持久记忆 (memory.md)</span>
198
+ <span class="clado-s-val"><span data-cfg-val="memory">已开启 · 编辑</span> <span style="opacity:.45;">›</span></span>
199
+ </div>
200
+ </div>
201
+
202
+ <div class="clado-group-title">人设与会话生命周期</div>
203
+ <div class="clado-settings-group" style="margin-bottom:13px;">
204
+ <div class="clado-s-row clickable" data-cfg-act="open-sub" data-sub="persona">
205
+ <span class="clado-s-title">人设与分身初始上下文</span>
206
+ <span class="clado-s-val"><span>4 套模板</span> <span style="opacity:.45;">›</span></span>
207
+ </div>
208
+ <div class="clado-s-row clickable" data-cfg-act="open-sub" data-sub="compact">
209
+ <span class="clado-s-title">上下文压缩提示词</span>
210
+ <span class="clado-s-val"><span data-cfg-val="compact">75% 触发 · 编辑</span> <span style="opacity:.45;">›</span></span>
211
+ </div>
212
+ <div class="clado-s-row clickable" data-cfg-act="cycle" data-cfg-kind="ttl">
213
+ <span class="clado-s-title">空闲会话自动归档</span>
214
+ <span class="clado-s-val"><span data-cfg-val="ttl">24 小时</span> <span style="opacity:.45;">›</span></span>
215
+ </div>
52
216
  </div>
53
- <div class="clado-agent-executor-bar" hidden>
54
- <label for="clado-agent-executor">执行器</label>
55
- <select id="clado-agent-executor" class="clado-agent-select"></select>
217
+
218
+ <div class="clado-group-title">安全与调试</div>
219
+ <div class="clado-settings-group">
220
+ <div class="clado-s-row clickable" data-cfg-act="cycle" data-cfg-kind="perm">
221
+ <span class="clado-s-title">命令行执行权限</span>
222
+ <span class="clado-s-val"><span data-cfg-val="perm">只读免审</span> <span style="opacity:.45;">›</span></span>
223
+ </div>
224
+ <div class="clado-s-row clickable" data-cfg-act="open-sub" data-sub="cache">
225
+ <span class="clado-s-title">前缀缓存命中状态</span>
226
+ <span class="clado-s-val"><span data-cfg-val="cache" style="color:#059669;font-weight:600;">99.4% 命中</span> <span style="opacity:.45;">›</span></span>
227
+ </div>
56
228
  </div>
57
- <div class="clado-agent-log" role="log" aria-label="对话消息" aria-live="off"></div>
58
- <p class="clado-agent-status" role="status" hidden></p>
59
- <form>
60
- <textarea aria-label="给 灵感 的消息" placeholder="给 灵感 发一条消息…" rows="2" maxlength="12000"></textarea>
61
- <button class="clado-ui-button clado-agent-stop" type="button" hidden>停止</button>
62
- <button class="clado-ui-button clado-ui-button-primary clado-agent-send" type="submit" disabled>发送</button>
63
- </form>
64
229
  </div>
65
- </section>`;
66
- host.mount('bottom-right', root, 'clado.agent');
67
-
68
- const find = selector => root.querySelector(selector);
69
- const panel = find('section'), trigger = find('.clado-agent-launch'), log = find('.clado-agent-log');
70
- const input = find('textarea'), send = find('.clado-agent-send'), stop = find('.clado-agent-stop');
71
- const providerLabel = find('.clado-agent-provider');
72
- const followBtn = find('.clado-agent-follow'), historyBtn = find('.clado-agent-history');
73
- const sessionsDrawer = find('.clado-agent-sessions');
74
- const personaBar = find('.clado-agent-persona-bar'), personaSelect = find('#clado-agent-persona');
75
- const executorBar = find('.clado-agent-executor-bar'), executorSelect = find('#clado-agent-executor');
76
- const chips = [...root.querySelectorAll('.clado-agent-chip')];
77
- const reset = find('.clado-agent-new'), status = find('.clado-agent-status'), form = find('form');
78
-
79
- const defaultPlaceholder = placeholder || '给 灵感 发一条消息…';
80
- const workflowHints = {
81
- design: defaultPlaceholder,
82
- qa: '描述需要补充或评审的测试用例范围…',
83
- audit: '输入要核对的变更点,或直接回车核对当前 Git Diff…',
84
- dispatch: '可选补充开发要求;留空将按当前画布规格直接派发给 ACP 执行器…',
85
- };
86
- const workflowDefaultPersona = { design: 'architect', qa: 'qa', audit: 'auditor' };
87
- input.placeholder = workflowHints.design;
88
- providerLabel.textContent = agentName;
89
230
 
90
- let session = crypto.randomUUID(), running = false, stopping = false, workflow = 'design';
91
- let persona = 'architect', personaLockedByUser = false;
92
- let followAi = !!initialFollowAi;
93
- let meta = { engine: 'acp', provider: 'openai', builtinConfigured: false, model: '', executors: [], personas: [], sessions: [] };
94
- const toolStates = { pending: '等待中', in_progress: '运行中', completed: '已完成', failed: '失败' };
231
+ <div class="clado-cfg-sub-page" data-role="cfg-sub">
232
+ <div style="display:flex;align-items:center;justify-content:space-between;padding:0 2px;">
233
+ <button type="button" class="clado-tab-btn active" data-cfg-act="close-sub" style="padding:5px 10px;font-size:12px;">← 返回</button>
234
+ <strong data-role="sub-title" style="font-size:14px;">编辑</strong>
235
+ <button type="button" class="clado-tab-btn active" data-role="sub-reset" data-cfg-act="reset-sub" style="padding:5px 10px;font-size:12px;">恢复默认</button>
236
+ </div>
237
+ <div class="clado-settings-group" data-role="sub-body" style="padding:14px;display:flex;flex-direction:column;gap:12px;"></div>
238
+ </div>
239
+ </div>`;
240
+ document.body.append(configView);
95
241
 
96
- const request = (data, keepalive = false) => fetch(endpoint, {
97
- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(data), keepalive,
98
- });
99
- const canSubmit = () => !running && (workflow === 'dispatch' || workflow === 'audit' || !!input.value.trim());
100
- const personaDotColors = { architect: '#3b82f6', qa: '#10b981', auditor: '#8b5cf6' };
101
- const personaDefaultSummaries = {
102
- architect: '关注系统边界、调用链与幂等演进',
103
- qa: '推导边界条件、并发竞争与回归用例树',
104
- auditor: '严格核对代码 Diff 与设计契约偏差',
105
- };
242
+ const toastEl = document.createElement('div');
243
+ toastEl.className = 'clado-agent-toast';
244
+ document.body.append(toastEl);
245
+
246
+ // 4. DOM 引用与基础工具函数
247
+ const orbBtn = orbWrap.querySelector('.clado-agent-orb');
248
+ const orbText = orbWrap.querySelector('.clado-agent-orb-text');
249
+ const cmdWrap = dock.querySelector('[data-role="cmd-wrap"]');
250
+ const cmdWho = dock.querySelector('[data-role="cmd-who"]');
251
+ const cmdCode = dock.querySelector('[data-role="cmd-code"]');
252
+ const singleWrap = dock.querySelector('[data-role="single-wrap"]');
253
+ const panel = dock.querySelector('#clado-agent-panel');
254
+ const spInner = dock.querySelector('[data-role="sp-inner"]');
255
+ const spName = dock.querySelector('[data-role="sp-name"]');
256
+ const spPersonaTag = dock.querySelector('[data-role="sp-persona-tag"]');
257
+ const execModeBtns = [...dock.querySelectorAll('[data-exec-mode]')];
258
+ const workflowBtns = [...dock.querySelectorAll('[data-workflow]')];
259
+ const followBtn = dock.querySelector('[data-role="follow-btn"]');
260
+ const executorWrap = dock.querySelector('[data-role="executor-wrap"]');
261
+ const executorSelect = dock.querySelector('[data-role="executor-select"]');
262
+ const planBannerWrap = dock.querySelector('[data-role="plan-banner-wrap"]');
263
+ const todoBox = dock.querySelector('[data-role="todo-box"]');
264
+ const todoSummary = dock.querySelector('[data-role="todo-summary"]');
265
+ const todoArrow = dock.querySelector('[data-role="todo-arrow"]');
266
+ const todoCollapse = dock.querySelector('[data-role="todo-collapse"]');
267
+ const todoList = dock.querySelector('[data-role="todo-list"]');
268
+ const log = dock.querySelector('.clado-agent-log');
269
+ const statusEl = dock.querySelector('.clado-agent-status');
270
+ const peerClusterEl = dock.querySelector('[data-role="peer-cluster"]');
271
+ const shell = dock.querySelector('[data-role="agent-shell"]');
272
+ const input = dock.querySelector('.clado-agent-input');
273
+ const stopBtn = dock.querySelector('[data-role="stop-btn"]');
274
+ const sendBtn = dock.querySelector('[data-role="send-btn"]');
275
+
276
+ let toastTimer = null;
277
+ function showToast(msg) {
278
+ if (!msg) return;
279
+ toastEl.textContent = msg;
280
+ toastEl.classList.add('show');
281
+ if (toastTimer) clearTimeout(toastTimer);
282
+ toastTimer = setTimeout(() => toastEl.classList.remove('show'), 2300);
283
+ }
284
+
285
+ // 自研毛玻璃下拉组件(供 ACP 执行器选择等使用)
106
286
  const glassDropdowns = [];
107
- function attachGlassDropdown(selectEl, { dotColors = {}, fallbackSummaries = {}, defaultDot = '#64748b' } = {}) {
287
+ function attachGlassDropdown(selectEl, { dotColors = {}, fallbackSummaries = {}, defaultDot = '#10b981' } = {}) {
108
288
  selectEl.classList.add('clado-agent-select-native');
109
289
  selectEl.tabIndex = -1;
110
290
  selectEl.setAttribute('aria-hidden', 'true');
@@ -128,7 +308,7 @@
128
308
  const dotEl = trigger.querySelector('.clado-glass-dropdown-dot');
129
309
  const labelEl = trigger.querySelector('.clado-glass-dropdown-label');
130
310
 
131
- const setOpen = (open) => {
311
+ const setDropdownOpen = open => {
132
312
  if (open && selectEl.disabled) return;
133
313
  if (open) {
134
314
  for (const other of glassDropdowns) {
@@ -145,9 +325,8 @@
145
325
  const opts = [...selectEl.options];
146
326
  const activeVal = selectEl.value;
147
327
  const currentOpt = opts.find(o => o.value === activeVal) || opts[0];
148
- const color = (currentOpt && dotColors[currentOpt.value]) || defaultDot;
149
- dotEl.style.background = color;
150
- labelEl.textContent = currentOpt ? currentOpt.textContent : '';
328
+ dotEl.style.background = (currentOpt && dotColors[currentOpt.value]) || defaultDot;
329
+ labelEl.textContent = currentOpt ? currentOpt.textContent : '默认执行器';
151
330
  menu.replaceChildren();
152
331
  for (const opt of opts) {
153
332
  const item = document.createElement('button');
@@ -156,7 +335,6 @@
156
335
  item.setAttribute('role', 'option');
157
336
  const selected = opt.value === activeVal;
158
337
  item.setAttribute('aria-selected', String(selected));
159
- if (selected) item.setAttribute('aria-current', 'page');
160
338
  const itemDot = document.createElement('span');
161
339
  itemDot.className = 'clado-glass-dropdown-dot';
162
340
  itemDot.style.background = dotColors[opt.value] || defaultDot;
@@ -181,318 +359,758 @@
181
359
  selectEl.dispatchEvent(new Event('change', { bubbles: true }));
182
360
  }
183
361
  sync();
184
- setOpen(false);
362
+ setDropdownOpen(false);
185
363
  };
186
364
  menu.append(item);
187
365
  }
188
366
  };
189
367
 
190
- trigger.onclick = (event) => {
191
- event.stopPropagation();
192
- setOpen(menu.hidden);
368
+ trigger.onclick = ev => {
369
+ ev.stopPropagation();
370
+ setDropdownOpen(menu.hidden);
193
371
  };
194
- const api = { wrap, menu, sync, setOpen };
372
+ const api = { wrap, menu, sync, setOpen: setDropdownOpen };
195
373
  glassDropdowns.push(api);
196
374
  sync();
197
375
  return api;
198
376
  }
199
377
 
200
- const personaDropdown = attachGlassDropdown(personaSelect, {
201
- dotColors: personaDotColors,
202
- fallbackSummaries: personaDefaultSummaries,
203
- defaultDot: '#3b82f6',
204
- });
205
- const executorDropdown = attachGlassDropdown(executorSelect, {
206
- defaultDot: '#10b981',
378
+ const executorDropdown = attachGlassDropdown(executorSelect, { defaultDot: '#10b981' });
379
+
380
+ // 5. 核心状态
381
+ const defaultPlaceholder = placeholder || '写下一个想法…(长按上方会话可新建/归档)';
382
+ const workflowHints = {
383
+ design: defaultPlaceholder,
384
+ qa: '描述需要补充或评审的测试用例范围…',
385
+ audit: '输入要核对的变更点,或直接回车核对当前 Git Diff…',
386
+ dispatch: '可选补充开发要求;留空将按当前画布规格派发给 ACP 执行器…',
387
+ };
388
+
389
+ let minimized = false;
390
+ try { minimized = sessionStorage.getItem('clado-agent-minimized') === '1'; } catch {}
391
+ let singlePanelOpen = false;
392
+ let todoExpanded = false;
393
+ let followAi = !!initialFollowAi;
394
+
395
+ let session = crypto.randomUUID();
396
+ let running = false;
397
+ let stopping = false;
398
+ let streamingSessionId = '';
399
+ let workflow = 'design';
400
+ let persona = 'architect';
401
+ let execMode = 'act';
402
+
403
+ let meta = {
404
+ engine: 'acp',
405
+ provider: 'openai',
406
+ builtinConfigured: false,
407
+ model: '',
408
+ executors: [],
409
+ personas: [],
410
+ sessions: [],
411
+ };
412
+
413
+ // 会话列表与完整记录缓存
414
+ let sessionsList = [];
415
+ let archivedList = [];
416
+ const sessionRecords = new Map();
417
+ const pillDomMap = new Map();
418
+ // 记录同伴呼叫高亮过期时间 id -> { pal, until, seenAt }
419
+ const calledFlashMap = new Map();
420
+ let activePendingCmd = null; // { sessionId, sessionTitle, cmd }
421
+
422
+ const toolStates = { pending: '等待中', in_progress: '运行中', completed: '已完成', failed: '失败' };
423
+ const request = (data, keepalive = false) => fetch(endpoint, {
424
+ method: 'POST',
425
+ headers: { 'content-type': 'application/json' },
426
+ body: JSON.stringify(data),
427
+ keepalive,
207
428
  });
208
- document.addEventListener('pointerdown', event => {
209
- for (const dd of glassDropdowns) {
210
- if (!dd.menu.hidden && !dd.wrap.contains(event.target)) dd.setOpen(false);
429
+
430
+ function syncDockPresence() {
431
+ dock.classList.toggle('minimized', minimized);
432
+ orbBtn.classList.toggle('show', minimized);
433
+ document.body.dataset.agentDock = minimized ? 'minimized' : 'open';
434
+ try { sessionStorage.setItem('clado-agent-minimized', minimized ? '1' : '0'); } catch {}
435
+ }
436
+ syncDockPresence();
437
+
438
+ function setMinimized(next) {
439
+ minimized = !!next;
440
+ if (minimized) closeCtxMenu();
441
+ syncDockPresence();
442
+ if (!minimized) {
443
+ requestAnimationFrame(() => updatePeerEdgeFade());
444
+ }
445
+ }
446
+
447
+ // 6. 会话排序、30s 静息判定与胶囊横向丝滑拖拽 + 边缘淡入淡出
448
+ const toEpochMs = v => (typeof v === 'number' ? v : (Date.parse(v || '') || 0));
449
+
450
+ function getIdleSeconds(s) {
451
+ if (s.running || (running && streamingSessionId === s.id)) return 0;
452
+ const ts = toEpochMs(s.lastActiveAt) || toEpochMs(s.updatedAt);
453
+ if (!ts) return 9999;
454
+ return Math.max(0, Math.floor((Date.now() - ts) / 1000));
455
+ }
456
+
457
+ function isSessionActive(s) {
458
+ if (s.archived) return false;
459
+ return Boolean(s.running) || (running && streamingSessionId === s.id) || getIdleSeconds(s) < 30;
460
+ }
461
+
462
+ function formatIdleText(s) {
463
+ if (s.archived) return '已归档';
464
+ const secs = getIdleSeconds(s);
465
+ if (secs < 30 || s.running || (running && streamingSessionId === s.id)) {
466
+ return s.liveStatus || (s.pendingCommand ? '待审批命令…' : s.hasPendingQuestion ? '待你拍板…' : '活跃中…');
467
+ }
468
+ if (secs < 60) return `${secs}s 前`;
469
+ if (secs < 3600) return `${Math.floor(secs / 60)}m 前`;
470
+ if (secs < 86400) return `${Math.floor(secs / 3600)}h 前`;
471
+ return `${Math.floor(secs / 86400)}d 前`;
472
+ }
473
+
474
+ function getSortedVisibleSessions() {
475
+ return sessionsList
476
+ .filter(s => !s.archived)
477
+ .slice()
478
+ .sort((a, b) => {
479
+ const actA = isSessionActive(a);
480
+ const actB = isSessionActive(b);
481
+ if (actA !== actB) return actA ? -1 : 1;
482
+ const tA = toEpochMs(a.lastActiveAt) || toEpochMs(a.updatedAt);
483
+ const tB = toEpochMs(b.lastActiveAt) || toEpochMs(b.updatedAt);
484
+ return tB - tA;
485
+ });
486
+ }
487
+
488
+ let peerScrollX = 0;
489
+ let stripDown = false;
490
+ let stripMoved = false;
491
+ let stripStartX = 0;
492
+ let stripStartScroll = 0;
493
+ let edgeFadeRaf = 0;
494
+
495
+ function getPeerMaxScroll() {
496
+ const pills = [...peerClusterEl.querySelectorAll('.clado-peer-pill')];
497
+ if (!pills.length) return 0;
498
+ let totalW = 0;
499
+ for (const p of pills) totalW += p.offsetWidth;
500
+ totalW += 6 * Math.max(0, pills.length - 1);
501
+ return Math.max(0, totalW - peerClusterEl.clientWidth);
502
+ }
503
+
504
+ function setPeerScrollX(nextX) {
505
+ const maxS = getPeerMaxScroll();
506
+ peerScrollX = Math.max(0, Math.min(maxS, nextX));
507
+ const pills = [...peerClusterEl.querySelectorAll('.clado-peer-pill')];
508
+ pills.forEach((p, idx) => {
509
+ p.style.marginLeft = idx === 0 && peerScrollX > 0 ? (-peerScrollX) + 'px' : '';
510
+ });
511
+ updatePeerEdgeFade();
512
+ }
513
+
514
+ function updatePeerEdgeFade() {
515
+ const boxRect = peerClusterEl.getBoundingClientRect();
516
+ const W = boxRect.width;
517
+ if (W <= 80) return;
518
+
519
+ const maxS = getPeerMaxScroll();
520
+ if (peerScrollX > maxS) {
521
+ peerScrollX = maxS;
522
+ const first = peerClusterEl.querySelector('.clado-peer-pill');
523
+ if (first) first.style.marginLeft = peerScrollX > 0 ? (-peerScrollX) + 'px' : '';
211
524
  }
525
+
526
+ const hasLeft = peerScrollX > 2;
527
+ const hasRight = peerScrollX < maxS - 2;
528
+ const leftZone = 36;
529
+ const rightZone = 44;
530
+
531
+ peerClusterEl.querySelectorAll('.clado-peer-pill').forEach(pill => {
532
+ const r = pill.getBoundingClientRect();
533
+ if (r.width <= 0) return;
534
+ const relLeft = r.left - boxRect.left;
535
+ const relRight = r.right - boxRect.left;
536
+
537
+ if (relRight <= 0.5 || relLeft >= W - 0.5) {
538
+ pill.style.visibility = 'hidden';
539
+ pill.style.pointerEvents = 'none';
540
+ return;
541
+ }
542
+ if (pill.style.visibility) {
543
+ pill.style.visibility = '';
544
+ pill.style.pointerEvents = '';
545
+ }
546
+
547
+ const touchLeft = hasLeft && relLeft < leftZone;
548
+ const touchRight = hasRight && relRight > W - rightZone;
549
+ if (!touchLeft && !touchRight) {
550
+ if (pill.style.maskImage || pill.style.webkitMaskImage) {
551
+ pill.style.maskImage = '';
552
+ pill.style.webkitMaskImage = '';
553
+ }
554
+ return;
555
+ }
556
+
557
+ const l0 = (-relLeft).toFixed(1);
558
+ const l1 = (leftZone - relLeft).toFixed(1);
559
+ const r0 = (W - rightZone - relLeft).toFixed(1);
560
+ const r1 = (W - relLeft).toFixed(1);
561
+ let grad;
562
+ if (touchLeft && touchRight) {
563
+ grad = `linear-gradient(90deg, transparent ${l0}px, #000 ${l1}px, #000 ${r0}px, transparent ${r1}px)`;
564
+ } else if (touchLeft) {
565
+ grad = `linear-gradient(90deg, transparent ${l0}px, #000 ${l1}px)`;
566
+ } else {
567
+ grad = `linear-gradient(90deg, #000 ${r0}px, transparent ${r1}px)`;
568
+ }
569
+ pill.style.webkitMaskImage = grad;
570
+ pill.style.maskImage = grad;
571
+ });
572
+ }
573
+
574
+ function scheduleEdgeFadeFrames(durationMs = 380) {
575
+ cancelAnimationFrame(edgeFadeRaf);
576
+ const t0 = performance.now();
577
+ const tick = now => {
578
+ updatePeerEdgeFade();
579
+ if (now - t0 < durationMs) edgeFadeRaf = requestAnimationFrame(tick);
580
+ };
581
+ edgeFadeRaf = requestAnimationFrame(tick);
582
+ }
583
+
584
+ window.addEventListener('resize', () => setPeerScrollX(peerScrollX));
585
+ peerClusterEl.addEventListener('pointerenter', () => scheduleEdgeFadeFrames(380), true);
586
+ peerClusterEl.addEventListener('pointerleave', () => scheduleEdgeFadeFrames(380), true);
587
+ peerClusterEl.addEventListener('pointerdown', e => {
588
+ if (e.button === 2) return;
589
+ stripDown = true;
590
+ stripMoved = false;
591
+ stripStartX = e.clientX;
592
+ stripStartScroll = peerScrollX;
212
593
  });
213
- document.addEventListener('keydown', event => {
214
- if (event.key === 'Escape') {
215
- for (const dd of glassDropdowns) {
216
- if (!dd.menu.hidden) dd.setOpen(false);
594
+ window.addEventListener('pointermove', e => {
595
+ if (!stripDown) return;
596
+ const dx = e.clientX - stripStartX;
597
+ if (Math.abs(dx) > 5) stripMoved = true;
598
+ if (stripMoved) setPeerScrollX(stripStartScroll - dx);
599
+ });
600
+ const endStripDrag = () => {
601
+ stripDown = false;
602
+ setTimeout(() => { stripMoved = false; }, 0);
603
+ };
604
+ window.addEventListener('pointerup', endStripDrag);
605
+ window.addEventListener('pointercancel', endStripDrag);
606
+ peerClusterEl.addEventListener('wheel', e => {
607
+ const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
608
+ if (delta !== 0) {
609
+ e.preventDefault();
610
+ setPeerScrollX(peerScrollX + delta);
611
+ }
612
+ }, { passive: false });
613
+
614
+ function bindPillGestures(btn, getSessionItem) {
615
+ btn.addEventListener('contextmenu', e => {
616
+ e.preventDefault();
617
+ e.stopPropagation();
618
+ openSessionContextMenu(getSessionItem(), e.clientX, e.clientY);
619
+ });
620
+ let pTimer = null;
621
+ let pStartX = 0;
622
+ btn.addEventListener('pointerdown', e => {
623
+ if (e.button === 2) return;
624
+ pStartX = e.clientX;
625
+ pTimer = setTimeout(() => {
626
+ pTimer = null;
627
+ openSessionContextMenu(getSessionItem(), e.clientX, e.clientY);
628
+ }, 440);
629
+ });
630
+ btn.addEventListener('pointermove', e => {
631
+ if (pTimer && Math.abs(e.clientX - pStartX) > 6) {
632
+ clearTimeout(pTimer);
633
+ pTimer = null;
217
634
  }
635
+ });
636
+ btn.addEventListener('pointerup', () => { if (pTimer) clearTimeout(pTimer); });
637
+ btn.addEventListener('pointerleave', () => { if (pTimer) clearTimeout(pTimer); });
638
+ }
639
+
640
+ function ensurePillElement(s) {
641
+ let btn = pillDomMap.get(s.id);
642
+ if (!btn) {
643
+ btn = document.createElement('button');
644
+ btn.type = 'button';
645
+ btn.className = 'clado-peer-pill';
646
+ btn.dataset.sessionId = s.id;
647
+ btn.setAttribute('role', 'tab');
648
+ btn.innerHTML = '<span class="p-name"></span><span class="p-live"></span>';
649
+ bindPillGestures(btn, () => sessionsList.find(x => x.id === s.id) || s);
650
+ btn.addEventListener('click', () => {
651
+ if (stripMoved) return;
652
+ if (singlePanelOpen && session === s.id) closeSinglePanel();
653
+ else openSinglePanel(s.id);
654
+ });
655
+ pillDomMap.set(s.id, btn);
218
656
  }
219
- });
220
657
 
221
- const syncActions = () => {
222
- panel.classList.toggle('clado-ai-working', running);
223
- send.disabled = !canSubmit();
224
- send.textContent = workflow === 'dispatch' ? '派发' : '发送';
225
- stop.hidden = !running;
226
- stop.disabled = stopping;
227
- reset.disabled = running;
228
- historyBtn.disabled = running;
229
- input.readOnly = running;
230
- const isDispatch = workflow === 'dispatch';
231
- executorBar.hidden = !isDispatch;
232
- personaBar.hidden = isDispatch;
233
- executorSelect.disabled = running;
234
- personaSelect.disabled = running;
235
- personaDropdown.sync();
236
- executorDropdown.sync();
237
- for (const chip of chips) chip.disabled = running;
238
- };
239
- const showStatus = text => {
240
- if (status.textContent !== text) status.textContent = text;
241
- status.hidden = !text;
242
- };
243
- function scroll() { log.scrollTop = log.scrollHeight; }
658
+ const pMeta = PERSONA_META[s.persona] || PERSONA_META.architect;
659
+ const pal = PALETTES[s.pal || pMeta.pal] || PALETTES.blue;
660
+ btn.style.setProperty('--c-muted', pal.muted);
661
+ btn.style.setProperty('--c-vivid', pal.vivid);
662
+ btn.style.setProperty('--c-glow', pal.glow);
244
663
 
245
- followBtn.onclick = () => {
246
- followAi = !followAi;
247
- followBtn.setAttribute('aria-pressed', String(followAi));
248
- setFollowAi(followAi);
249
- };
664
+ const flash = calledFlashMap.get(s.id);
665
+ const isFlashing = Boolean(flash && flash.until > Date.now());
666
+ if (isFlashing) {
667
+ const cp = PALETTES[flash.pal] || PALETTES.blue;
668
+ btn.style.setProperty('--caller-color', cp.vivid);
669
+ btn.style.setProperty('--caller-glow', cp.glow);
670
+ }
250
671
 
251
- personaSelect.onchange = () => {
252
- persona = personaSelect.value || 'architect';
253
- personaLockedByUser = true;
254
- personaDropdown.sync();
255
- };
256
- executorSelect.onchange = () => {
257
- executorDropdown.sync();
258
- };
672
+ const active = isSessionActive(s);
673
+ const focused = singlePanelOpen && session === s.id;
674
+ btn.classList.toggle('is-active', active);
675
+ btn.classList.toggle('is-dormant', !active);
676
+ btn.classList.toggle('is-focused', focused);
677
+ btn.classList.toggle('called-flash', isFlashing && !focused);
678
+ btn.setAttribute('aria-selected', String(focused));
259
679
 
260
- function selectWorkflow(nextWorkflow) {
261
- workflow = nextWorkflow;
262
- for (const item of chips) item.setAttribute('aria-pressed', String(item.dataset.workflow === workflow));
263
- input.placeholder = workflowHints[workflow] || defaultPlaceholder;
264
- if (!personaLockedByUser && workflowDefaultPersona[workflow]) {
265
- persona = workflowDefaultPersona[workflow];
266
- personaSelect.value = persona;
680
+ btn.querySelector('.p-name').textContent = s.title || pMeta.label;
681
+ btn.querySelector('.p-live').textContent = '· ' + formatIdleText(s);
682
+ return btn;
683
+ }
684
+
685
+ function renderPeerCluster(animateReorder = false) {
686
+ const visible = getSortedVisibleSessions();
687
+ let activeCount = 0;
688
+
689
+ const firstRects = new Map();
690
+ if (animateReorder) {
691
+ peerClusterEl.querySelectorAll('.clado-peer-pill[data-session-id]').forEach(el => {
692
+ firstRects.set(el.dataset.sessionId, el.getBoundingClientRect().left);
693
+ });
267
694
  }
695
+
696
+ if (visible.length && !visible.some(s => s.id === session) && !running) {
697
+ session = visible[0].id;
698
+ }
699
+
700
+ const visibleIds = new Set(visible.map(v => v.id));
701
+ [...peerClusterEl.children].forEach(ch => {
702
+ if (!ch.dataset.sessionId || !visibleIds.has(ch.dataset.sessionId)) ch.remove();
703
+ });
704
+
705
+ if (visible.length === 0) {
706
+ const emptyBtn = document.createElement('button');
707
+ emptyBtn.type = 'button';
708
+ emptyBtn.className = 'clado-peer-pill is-active';
709
+ emptyBtn.style.setProperty('--c-muted', PALETTES.blue.muted);
710
+ emptyBtn.style.setProperty('--c-vivid', PALETTES.blue.vivid);
711
+ emptyBtn.style.setProperty('--c-glow', PALETTES.blue.glow);
712
+ emptyBtn.innerHTML = '<span class="p-name">+ 新建会话</span>';
713
+ bindPillGestures(emptyBtn, () => null);
714
+ emptyBtn.onclick = () => {
715
+ if (stripMoved) return;
716
+ createNewSession('architect');
717
+ };
718
+ peerClusterEl.append(emptyBtn);
719
+ } else {
720
+ for (const s of visible) {
721
+ if (isSessionActive(s)) activeCount++;
722
+ const btn = ensurePillElement(s);
723
+ peerClusterEl.append(btn);
724
+ }
725
+ }
726
+
727
+ if (animateReorder && firstRects.size > 0) {
728
+ setPeerScrollX(0);
729
+ for (const s of visible) {
730
+ const btn = pillDomMap.get(s.id);
731
+ const prevLeft = firstRects.get(s.id);
732
+ if (!btn || prevLeft === undefined) continue;
733
+ const dx = prevLeft - btn.getBoundingClientRect().left;
734
+ if (Math.abs(dx) > 2) {
735
+ btn.style.transition = 'none';
736
+ btn.style.transform = `translate3d(${dx}px, 0, 0)`;
737
+ requestAnimationFrame(() => {
738
+ btn.style.transition = '';
739
+ btn.style.transform = '';
740
+ });
741
+ }
742
+ }
743
+ } else {
744
+ setPeerScrollX(peerScrollX);
745
+ }
746
+
747
+ scheduleEdgeFadeFrames(400);
748
+ orbText.textContent = activeCount > 0 ? `灵感 · ${activeCount} 活跃` : '灵感';
749
+ syncCommandBanner();
268
750
  syncActions();
269
751
  }
270
752
 
271
- async function loadMeta() {
272
- try {
273
- const res = await fetch(metaEndpoint, { cache: 'no-store' });
274
- if (!res.ok) return;
275
- meta = await res.json();
276
- const providerTag = meta.provider === 'anthropic' ? 'Anthropic' : 'OpenAI';
277
- providerLabel.textContent = meta.engine === 'builtin'
278
- ? `${providerTag} · ${meta.model || 'LLM'}`
279
- : `ACP · ${agentName}`;
280
- if (Array.isArray(meta.personas) && meta.personas.length) {
281
- const prev = personaSelect.value || persona;
282
- personaSelect.replaceChildren();
283
- for (const p of meta.personas) {
284
- const opt = document.createElement('option');
285
- opt.value = p.id;
286
- opt.textContent = p.name;
287
- opt.title = p.summary || '';
288
- personaSelect.append(opt);
289
- }
290
- if (meta.personas.some(p => p.id === prev)) personaSelect.value = prev;
291
- else if (meta.defaultPersona && meta.personas.some(p => p.id === meta.defaultPersona)) {
292
- persona = meta.defaultPersona;
293
- personaSelect.value = persona;
753
+ function ingestSessionList(incoming, animate = false) {
754
+ if (!Array.isArray(incoming)) return;
755
+ const now = Date.now();
756
+ let scheduledClear = 0;
757
+ for (const item of incoming) {
758
+ if (item.calledBy?.at) {
759
+ const prev = calledFlashMap.get(item.id);
760
+ const age = now - item.calledBy.at;
761
+ if (age < 5000 && (!prev || prev.seenAt !== item.calledBy.at)) {
762
+ const until = now + 3600;
763
+ calledFlashMap.set(item.id, {
764
+ pal: item.calledBy.pal || 'blue',
765
+ until,
766
+ seenAt: item.calledBy.at,
767
+ });
768
+ scheduledClear = Math.max(scheduledClear, 3650);
294
769
  }
295
770
  }
296
- const list = Array.isArray(meta.executors) ? meta.executors : [];
297
- const previous = executorSelect.value;
298
- executorSelect.replaceChildren();
299
- if (!list.length) {
300
- const opt = document.createElement('option');
301
- opt.value = '';
302
- opt.textContent = '未配置 ACP 执行器';
303
- executorSelect.append(opt);
771
+ }
772
+ sessionsList = incoming;
773
+ renderPeerCluster(animate);
774
+ if (scheduledClear > 0) {
775
+ setTimeout(() => renderPeerCluster(false), scheduledClear);
776
+ }
777
+ }
778
+
779
+ // 7. 命令审批条同步与处理
780
+ function syncCommandBanner() {
781
+ let candidate = activePendingCmd;
782
+ if (!candidate) {
783
+ const curRec = sessionRecords.get(session);
784
+ if (curRec?.pendingCommand) {
785
+ candidate = {
786
+ sessionId: curRec.id,
787
+ sessionTitle: curRec.title || '当前会话',
788
+ cmd: curRec.pendingCommand,
789
+ };
304
790
  } else {
305
- for (const item of list) {
306
- const opt = document.createElement('option');
307
- opt.value = item.id;
308
- opt.textContent = item.name + (item.source === 'plugin' ? '(插件)' : '');
309
- executorSelect.append(opt);
791
+ const waitingSummary = sessionsList.find(s => !s.archived && s.pendingCommand);
792
+ if (waitingSummary) {
793
+ candidate = {
794
+ sessionId: waitingSummary.id,
795
+ sessionTitle: waitingSummary.title || '协作分身',
796
+ cmd: waitingSummary.pendingCommand,
797
+ };
310
798
  }
311
- if (previous && list.some(item => item.id === previous)) executorSelect.value = previous;
312
799
  }
313
- personaDropdown.sync();
314
- executorDropdown.sync();
800
+ }
801
+
802
+ if (!candidate || !candidate.cmd) {
803
+ cmdWrap.classList.add('closed');
804
+ return;
805
+ }
806
+ cmdWho.textContent = candidate.sessionTitle || '会话';
807
+ cmdCode.textContent = candidate.cmd.command || '';
808
+ cmdWrap.dataset.sessionId = candidate.sessionId;
809
+ cmdWrap.dataset.commandId = candidate.cmd.id;
810
+ cmdWrap.classList.remove('closed');
811
+ }
812
+
813
+ dock.querySelectorAll('[data-cmd-decision]').forEach(btn => {
814
+ btn.onclick = () => {
815
+ if (running) return;
816
+ const targetSid = cmdWrap.dataset.sessionId || session;
817
+ const commandId = cmdWrap.dataset.commandId;
818
+ const cmdText = cmdCode.textContent || '';
819
+ const decision = btn.dataset.cmdDecision;
820
+ if (!commandId) return;
821
+ activePendingCmd = null;
822
+ const rec = sessionRecords.get(targetSid);
823
+ if (rec) rec.pendingCommand = null;
824
+ cmdWrap.classList.add('closed');
825
+ session = targetSid;
826
+ openSinglePanel(targetSid);
827
+ const labelMap = { allow: '允许执行', session_allow: '本会话免审执行', deny: '拒绝执行' };
828
+ streamTurn({
829
+ action: 'command_decision',
830
+ session: targetSid,
831
+ commandId,
832
+ decision,
833
+ mode: workflow === 'dispatch' ? 'design' : workflow,
834
+ execMode,
835
+ persona,
836
+ canvas: readCanvas(),
837
+ viewId,
838
+ }, {
839
+ humanText: `${labelMap[decision] || decision}:${cmdText}`,
840
+ humanLabel: '你(命令审批)',
841
+ });
842
+ };
843
+ });
844
+
845
+ // 8. 长按 / 右键会话菜单(新建、归档、恢复归档、删除、设置)
846
+ function closeCtxMenu() {
847
+ ctxMenu.classList.remove('open');
848
+ }
849
+
850
+ function positionCtxMenu(x, y) {
851
+ ctxMenu.style.left = '-999px';
852
+ ctxMenu.style.top = '-999px';
853
+ ctxMenu.classList.add('open');
854
+ const rect = ctxMenu.getBoundingClientRect();
855
+ const left = Math.min(window.innerWidth - rect.width - 10, Math.max(10, x - rect.width / 2));
856
+ const top = Math.max(12, y - rect.height - 12);
857
+ ctxMenu.style.left = left + 'px';
858
+ ctxMenu.style.top = top + 'px';
859
+ }
860
+
861
+ function addCtxHeader(label, sub) {
862
+ const d = document.createElement('div');
863
+ d.className = 'clado-ctx-badge';
864
+ const l = document.createElement('span');
865
+ l.textContent = label;
866
+ const r = document.createElement('span');
867
+ r.style.opacity = '.75';
868
+ r.textContent = sub || '';
869
+ d.append(l, r);
870
+ ctxMenu.append(d);
871
+ }
872
+
873
+ function addCtxItem(text, fn, danger = false) {
874
+ const b = document.createElement('button');
875
+ b.type = 'button';
876
+ b.className = 'clado-ctx-btn' + (danger ? ' danger' : '');
877
+ b.textContent = text;
878
+ b.onclick = ev => {
879
+ ev.stopPropagation();
880
+ closeCtxMenu();
881
+ fn();
882
+ };
883
+ ctxMenu.append(b);
884
+ }
885
+
886
+ async function refreshArchivedSessions() {
887
+ try {
888
+ const res = await fetch(sessionUrl('', { includeArchived: '1' }), { cache: 'no-store' });
889
+ if (!res.ok) return;
890
+ const data = await res.json();
891
+ const all = Array.isArray(data.sessions) ? data.sessions : [];
892
+ archivedList = all.filter(s => s.archived);
315
893
  } catch {}
316
894
  }
317
895
 
318
- async function refreshSessionsDrawer() {
319
- sessionsDrawer.replaceChildren();
320
- const loading = document.createElement('div');
321
- loading.className = 'clado-agent-sessions-empty';
322
- loading.textContent = '加载历史会话…';
323
- sessionsDrawer.append(loading);
896
+ function openSessionContextMenu(targetSession, x, y) {
897
+ ctxMenu.replaceChildren();
898
+ addCtxHeader('会话菜单', targetSession ? (targetSession.title || '当前会话') : '会话管理');
899
+ addCtxItem('+ 新建架构会话', () => createNewSession('architect'));
900
+ addCtxItem('+ 新建实现分身', () => createNewSession('coder'));
901
+ addCtxItem('+ 新建测试分身', () => createNewSession('qa'));
902
+ addCtxItem('+ 新建审计分身', () => createNewSession('auditor'));
903
+ addCtxItem('⚙ Agent 设置与记忆', () => openSettingsOverlay());
904
+ addCtxItem('🧩 插件市场', () => window.dispatchEvent(new CustomEvent('clado:open-market')));
905
+
906
+ if (targetSession && targetSession.id) {
907
+ addCtxItem('归档此会话', () => archiveSessionById(targetSession.id));
908
+ }
909
+ for (const arch of archivedList.slice(0, 4)) {
910
+ addCtxItem(`恢复归档:${arch.title || '历史会话'}`, () => unarchiveSessionById(arch.id));
911
+ }
912
+ if (targetSession && targetSession.id) {
913
+ addCtxItem('删除此会话', () => deleteSessionById(targetSession.id), true);
914
+ }
915
+ positionCtxMenu(x, y);
916
+
917
+ // 异步刷新归档列表供下次或即时使用
918
+ refreshArchivedSessions();
919
+ }
920
+
921
+ peerClusterEl.addEventListener('contextmenu', e => {
922
+ if (e.target.closest('.clado-peer-pill')) return;
923
+ e.preventDefault();
924
+ openSessionContextMenu(null, e.clientX, e.clientY);
925
+ });
926
+
927
+ async function createNewSession(nextPersona = 'architect') {
928
+ const pMeta = PERSONA_META[nextPersona] || PERSONA_META.architect;
324
929
  try {
325
- const res = await fetch(sessionsEndpoint, { cache: 'no-store' });
326
- const data = res.ok ? await res.json() : { sessions: [] };
327
- const items = Array.isArray(data.sessions) ? data.sessions : [];
328
- sessionsDrawer.replaceChildren();
329
- if (!items.length) {
330
- const empty = document.createElement('div');
331
- empty.className = 'clado-agent-sessions-empty';
332
- empty.textContent = '暂无已保存的对话记录';
333
- sessionsDrawer.append(empty);
334
- return;
930
+ const res = await fetch(sessionsEndpoint, {
931
+ method: 'POST',
932
+ headers: { 'content-type': 'application/json' },
933
+ body: JSON.stringify({
934
+ action: 'create',
935
+ persona: nextPersona,
936
+ pal: pMeta.pal,
937
+ mode: pMeta.defaultMode,
938
+ execMode: nextPersona === 'auditor' ? 'plan' : 'act',
939
+ }),
940
+ });
941
+ if (res.ok) {
942
+ const { session: created } = await res.json();
943
+ if (created?.id) {
944
+ sessionRecords.set(created.id, created);
945
+ session = created.id;
946
+ persona = created.persona || nextPersona;
947
+ execMode = created.execMode || 'act';
948
+ selectWorkflow(created.mode || pMeta.defaultMode);
949
+ await refreshSessionsList(true);
950
+ openSinglePanel(created.id);
951
+ showToast(`已新建「${created.title}」`);
952
+ input.focus();
953
+ return;
954
+ }
335
955
  }
336
- for (const item of items) {
337
- const row = document.createElement('div');
338
- row.className = 'clado-agent-session-row' + (item.id === session ? ' active' : '');
339
- const openBtn = document.createElement('button');
340
- openBtn.type = 'button';
341
- openBtn.className = 'clado-agent-session-open';
342
- const titleSpan = document.createElement('span');
343
- titleSpan.className = 'clado-agent-session-title';
344
- titleSpan.textContent = item.title || '未命名会话';
345
- const metaSpan = document.createElement('small');
346
- metaSpan.textContent = [
347
- item.hasPendingQuestion ? '待确认' : '',
348
- item.messageCount ? item.messageCount + ' 条消息' : '',
349
- ].filter(Boolean).join(' · ') || '空会话';
350
- if (item.hasPendingQuestion) metaSpan.classList.add('waiting');
351
- openBtn.append(titleSpan, metaSpan);
352
- openBtn.onclick = () => loadSession(item.id);
353
- const delBtn = document.createElement('button');
354
- delBtn.type = 'button';
355
- delBtn.className = 'clado-agent-session-del';
356
- delBtn.setAttribute('aria-label', '删除会话');
357
- delBtn.textContent = '×';
358
- delBtn.onclick = async ev => {
359
- ev.stopPropagation();
360
- try {
361
- const delRes = await fetch(sessionUrl(item.id), { method: 'DELETE' });
362
- if (delRes.ok) {
363
- if (item.id === session) {
364
- session = crypto.randomUUID();
365
- log.replaceChildren();
366
- }
367
- refreshSessionsDrawer();
368
- }
369
- } catch {}
370
- };
371
- row.append(openBtn, delBtn);
372
- sessionsDrawer.append(row);
956
+ } catch {}
957
+ // 离线/兜底本地新建
958
+ session = crypto.randomUUID();
959
+ persona = nextPersona;
960
+ execMode = nextPersona === 'auditor' ? 'plan' : 'act';
961
+ selectWorkflow(pMeta.defaultMode);
962
+ log.replaceChildren();
963
+ openSinglePanel(session);
964
+ input.focus();
965
+ }
966
+
967
+ async function archiveSessionById(id) {
968
+ if (!id) return;
969
+ const target = sessionsList.find(s => s.id === id);
970
+ try {
971
+ const res = await fetch(sessionsEndpoint, {
972
+ method: 'POST',
973
+ headers: { 'content-type': 'application/json' },
974
+ body: JSON.stringify({ action: 'archive', id }),
975
+ });
976
+ if (res.ok) {
977
+ if (singlePanelOpen && session === id) closeSinglePanel();
978
+ await Promise.all([refreshSessionsList(true), refreshArchivedSessions()]);
979
+ showToast(`已归档「${target?.title || '会话'}」(长按胶囊可恢复)`);
373
980
  }
374
- } catch {
375
- sessionsDrawer.replaceChildren();
376
- const err = document.createElement('div');
377
- err.className = 'clado-agent-sessions-empty';
378
- err.textContent = '读取历史会话失败';
379
- sessionsDrawer.append(err);
380
- }
981
+ } catch {}
381
982
  }
382
983
 
383
- function setHistoryOpen(open) {
384
- sessionsDrawer.hidden = !open;
385
- historyBtn.setAttribute('aria-expanded', String(open));
386
- if (open) refreshSessionsDrawer();
984
+ async function unarchiveSessionById(id) {
985
+ if (!id) return;
986
+ try {
987
+ const res = await fetch(sessionsEndpoint, {
988
+ method: 'POST',
989
+ headers: { 'content-type': 'application/json' },
990
+ body: JSON.stringify({ action: 'unarchive', id }),
991
+ });
992
+ if (res.ok) {
993
+ const { session: restored } = await res.json();
994
+ await Promise.all([refreshSessionsList(true), refreshArchivedSessions()]);
995
+ if (restored?.id) openSinglePanel(restored.id);
996
+ showToast(`已恢复「${restored?.title || '会话'}」`);
997
+ }
998
+ } catch {}
387
999
  }
388
- historyBtn.onclick = () => setHistoryOpen(sessionsDrawer.hidden);
389
1000
 
390
- async function loadSession(id) {
391
- if (running) return;
1001
+ async function deleteSessionById(id) {
1002
+ if (!id) return;
1003
+ const target = sessionsList.find(s => s.id === id);
392
1004
  try {
393
- const res = await fetch(sessionUrl(id), { cache: 'no-store' });
394
- if (!res.ok) return;
395
- const { session: record } = await res.json();
396
- if (!record) return;
397
- session = record.id;
398
- if (record.mode && workflowHints[record.mode]) selectWorkflow(record.mode);
399
- if (record.persona) {
400
- persona = record.persona;
401
- personaSelect.value = persona;
402
- personaDropdown.sync();
403
- }
404
- log.replaceChildren();
405
- for (const msg of record.uiMessages || []) {
406
- if (msg.role === 'human') {
407
- const bubble = message('human', msg.text || '', msg.isAnswer ? '你(已确认)' : '你');
408
- if (msg.canvas?.file) {
409
- const ctx = document.createElement('small');
410
- ctx.textContent = [msg.canvas.file.split('/').pop(), msg.canvas.selectionCount ? msg.canvas.selectionCount + ' 个选中标题' : ''].filter(Boolean).join(' · ');
411
- ctx.title = msg.canvas.file;
412
- bubble.item.append(ctx);
413
- }
414
- } else if (msg.role === 'assistant') {
415
- const bubble = message('assistant', msg.text || '');
416
- if (msg.thinking) {
417
- const details = createThinkingBlock(msg.thinking);
418
- bubble.item.insertBefore(details, bubble.body);
419
- }
420
- if (!msg.text) bubble.body.hidden = true;
421
- if (Array.isArray(msg.changes) && msg.changes.length) {
422
- bubble.item.append(createChangesCard(msg.changes));
423
- }
424
- if (msg.question) {
425
- bubble.item.append(createQuestionCard(msg.question));
426
- }
427
- }
1005
+ const res = await fetch(sessionUrl(id), { method: 'DELETE' });
1006
+ if (res.ok) {
1007
+ sessionRecords.delete(id);
1008
+ pillDomMap.delete(id);
1009
+ if (singlePanelOpen && session === id) closeSinglePanel();
1010
+ if (session === id) session = crypto.randomUUID();
1011
+ await refreshSessionsList(true);
1012
+ showToast(`已删除「${target?.title || '会话'}」`);
428
1013
  }
429
- setHistoryOpen(false);
430
- showStatus(record.pendingQuestion ? '等待你的确认后继续执行' : '');
431
- scroll();
432
1014
  } catch {}
433
1015
  }
434
1016
 
435
- for (const chip of chips) {
436
- chip.onclick = () => {
437
- if (running) return;
438
- selectWorkflow(chip.dataset.workflow);
439
- if (workflow === 'dispatch') loadMeta();
440
- };
1017
+ // 9. 单人视角详情抽屉与消息渲染
1018
+ function syncExecModeUI(nextMode) {
1019
+ execMode = nextMode === 'plan' ? 'plan' : 'act';
1020
+ for (const b of execModeBtns) {
1021
+ b.classList.toggle('active', b.dataset.execMode === execMode);
1022
+ }
1023
+ planBannerWrap.classList.toggle('closed', execMode !== 'plan');
441
1024
  }
442
1025
 
443
- function setOpen(open) {
444
- panel.hidden = !open;
445
- trigger.setAttribute('aria-expanded', String(open));
446
- if (open) { loadMeta(); syncActions(); input.focus(); scroll(); }
447
- else setHistoryOpen(false);
1026
+ function renderTodos(todos) {
1027
+ const list = Array.isArray(todos) ? todos : [];
1028
+ if (!list.length) {
1029
+ todoBox.hidden = true;
1030
+ return;
1031
+ }
1032
+ todoBox.hidden = false;
1033
+ const doneCount = list.filter(t => t.status === 'completed').length;
1034
+ const current = list.find(t => t.status === 'in_progress') || list.find(t => t.status !== 'completed') || list.at(-1);
1035
+ const curLabel = current?.text || current?.content || '执行中';
1036
+ todoSummary.textContent = `步骤 ${doneCount}/${list.length} · ${curLabel}`;
1037
+ todoList.replaceChildren();
1038
+ list.forEach((t, i) => {
1039
+ const row = document.createElement('div');
1040
+ const mark = t.status === 'completed' ? '✓' : t.status === 'in_progress' ? '●' : '○';
1041
+ row.textContent = `${mark} ${i + 1}. ${t.text || t.content || ''}`;
1042
+ todoList.append(row);
1043
+ });
448
1044
  }
449
- trigger.onclick = () => setOpen(panel.hidden);
450
- find('.clado-agent-close').onclick = () => { setOpen(false); trigger.focus(); };
451
- panel.onkeydown = event => {
452
- if (event.key === 'Escape') { event.stopPropagation(); setOpen(false); trigger.focus(); }
1045
+
1046
+ todoBox.onclick = () => {
1047
+ todoExpanded = !todoExpanded;
1048
+ todoCollapse.classList.toggle('closed', !todoExpanded);
1049
+ todoArrow.textContent = todoExpanded ? '收起 ▴' : '展开 ▾';
453
1050
  };
454
- input.oninput = syncActions;
455
- input.onkeydown = event => {
456
- if (event.key === 'Enter' && !event.shiftKey && !event.isComposing && event.keyCode !== 229) {
457
- event.preventDefault();
458
- if (!send.disabled) form.requestSubmit();
1051
+
1052
+ function showStatus(text) {
1053
+ if (statusEl.textContent !== text) statusEl.textContent = text;
1054
+ statusEl.hidden = !text;
1055
+ }
1056
+
1057
+ function scrollLog() {
1058
+ log.scrollTop = log.scrollHeight;
1059
+ }
1060
+
1061
+ function canSubmit() {
1062
+ const curRunning = running && streamingSessionId === session;
1063
+ if (curRunning) {
1064
+ // 内置运行时支持实时插话纠偏(Steer)
1065
+ return meta.engine === 'builtin' && Boolean(input.value.trim());
459
1066
  }
460
- };
461
- reset.onclick = () => {
462
- request({ action: 'close', session }, true).catch(() => {});
463
- session = crypto.randomUUID();
464
- personaLockedByUser = false;
465
- setHistoryOpen(false);
466
- log.replaceChildren();
467
- showStatus('');
468
- input.focus();
469
- };
470
- stop.onclick = async () => {
471
- if (!running || stopping) return;
472
- stopping = true;
473
- syncActions();
474
- try {
475
- if (!(await request({ action: 'cancel', session })).ok) throw new Error();
476
- } catch {
477
- if (running) showStatus('暂时无法停止,请重试。');
478
- stopping = false;
479
- syncActions();
1067
+ if (running) return false;
1068
+ return workflow === 'dispatch' || workflow === 'audit' || Boolean(input.value.trim());
1069
+ }
1070
+
1071
+ function syncActions() {
1072
+ const anyRunning = running || sessionsList.some(s => !s.archived && s.running);
1073
+ const curSummary = sessionsList.find(s => s.id === session);
1074
+ const curRunning = (running && streamingSessionId === session) || Boolean(curSummary?.running);
1075
+
1076
+ panel.classList.toggle('clado-ai-working', anyRunning);
1077
+ shell.classList.toggle('working', anyRunning);
1078
+
1079
+ stopBtn.hidden = !curRunning;
1080
+ stopBtn.disabled = stopping;
1081
+
1082
+ sendBtn.disabled = !canSubmit();
1083
+ if (curRunning && meta.engine === 'builtin') {
1084
+ sendBtn.textContent = '插话';
1085
+ } else if (workflow === 'dispatch') {
1086
+ sendBtn.textContent = '派发';
1087
+ } else {
1088
+ sendBtn.textContent = '发送';
480
1089
  }
481
- };
482
- addEventListener('pagehide', event => {
483
- if (!event.persisted) request({ action: 'close', session }, true).catch(() => {});
484
- });
485
1090
 
486
- function message(author, text, labelOverride) {
487
- const item = document.createElement('div');
488
- item.className = 'clado-agent-message ' + author;
489
- const label = document.createElement('strong');
490
- label.textContent = labelOverride || (author === 'human' ? '你' : (meta.engine === 'builtin' ? 'Clado Agent' : agentName));
491
- const body = document.createElement('p');
492
- body.textContent = text;
493
- item.append(label, body);
494
- log.append(item);
495
- return { item, body };
1091
+ const isDispatch = workflow === 'dispatch';
1092
+ executorWrap.hidden = !isDispatch;
1093
+ executorSelect.disabled = running;
1094
+ executorDropdown.sync();
1095
+
1096
+ const curName = curSummary?.title || PERSONA_META[persona]?.label || '灵感';
1097
+ if (curRunning && meta.engine === 'builtin') {
1098
+ input.placeholder = `向「${curName}」插话纠偏(下一步立即生效)…`;
1099
+ } else if (workflow !== 'design') {
1100
+ input.placeholder = workflowHints[workflow] || defaultPlaceholder;
1101
+ } else if (curSummary) {
1102
+ input.placeholder = `继续与「${curName}」对话(长按会话管理)…`;
1103
+ } else {
1104
+ input.placeholder = defaultPlaceholder;
1105
+ }
1106
+ }
1107
+
1108
+ function selectWorkflow(nextWorkflow) {
1109
+ workflow = workflowHints[nextWorkflow] ? nextWorkflow : 'design';
1110
+ for (const b of workflowBtns) {
1111
+ b.classList.toggle('active', b.dataset.workflow === workflow);
1112
+ }
1113
+ syncActions();
496
1114
  }
497
1115
 
498
1116
  function createThinkingBlock(initialText = '') {
@@ -506,32 +1124,55 @@
506
1124
  return details;
507
1125
  }
508
1126
 
509
- function createChangesCard(items) {
510
- const card = document.createElement('div');
511
- card.className = 'clado-agent-changes';
512
- const title = document.createElement('div');
513
- title.className = 'clado-agent-changes-title';
514
- title.textContent = `本轮画布变更(${items.length} 项 · 点击定位)`;
515
- card.append(title);
516
- const list = document.createElement('div');
517
- list.className = 'clado-agent-changes-list';
518
- for (const change of items) {
1127
+ function createChangesRow(items, checkpointId, targetSessionId, rolledBack = false) {
1128
+ const row = document.createElement('div');
1129
+ row.className = 'clado-changes-row';
1130
+ const chips = document.createElement('div');
1131
+ chips.className = 'clado-changes-chips';
1132
+ for (const change of items || []) {
519
1133
  const btn = document.createElement('button');
520
1134
  btn.type = 'button';
521
- btn.className = 'clado-agent-change-item';
522
- const dot = document.createElement('span');
523
- dot.className = 'dot';
524
- const text = document.createElement('span');
525
- text.textContent = change.label || change.file || '画布更新';
526
- btn.append(dot, text);
1135
+ btn.className = 'clado-tool-chip';
1136
+ btn.textContent = (change.label || change.file || '画布更新') + ' ↗';
527
1137
  btn.onclick = () => focusTarget(change.file, change.node, change.label);
528
- list.append(btn);
1138
+ chips.append(btn);
529
1139
  }
530
- card.append(list);
531
- return card;
1140
+ row.append(chips);
1141
+
1142
+ if (checkpointId) {
1143
+ const rb = document.createElement('button');
1144
+ rb.type = 'button';
1145
+ rb.className = 'clado-tool-chip rollback' + (rolledBack ? ' done' : '');
1146
+ rb.textContent = rolledBack ? '已回退' : '↺ 回退此轮';
1147
+ rb.disabled = rolledBack;
1148
+ rb.onclick = async () => {
1149
+ if (rb.disabled || running) return;
1150
+ rb.disabled = true;
1151
+ try {
1152
+ const res = await fetch(sessionsEndpoint, {
1153
+ method: 'POST',
1154
+ headers: { 'content-type': 'application/json' },
1155
+ body: JSON.stringify({ action: 'rollback', id: targetSessionId || session, checkpointId }),
1156
+ });
1157
+ if (!res.ok) {
1158
+ const err = await res.json().catch(() => ({}));
1159
+ throw new Error(err.error || '回退失败');
1160
+ }
1161
+ rb.classList.add('done');
1162
+ rb.textContent = '已回退';
1163
+ showToast('已回退此轮画布修改');
1164
+ refreshSessionsList(false);
1165
+ } catch (err) {
1166
+ rb.disabled = false;
1167
+ showToast(err.message || '回退失败');
1168
+ }
1169
+ };
1170
+ row.append(rb);
1171
+ }
1172
+ return row;
532
1173
  }
533
1174
 
534
- function createQuestionCard(q) {
1175
+ function createQuestionCard(q, targetSessionId) {
535
1176
  const card = document.createElement('div');
536
1177
  card.className = 'clado-agent-question' + (q.answered ? ' answered' : '');
537
1178
  const badge = document.createElement('div');
@@ -562,21 +1203,22 @@
562
1203
  chosen.className = 'clado-agent-question-answered';
563
1204
  chosen.textContent = '已选:' + clean;
564
1205
  card.append(chosen);
565
- const canvas = readCanvas();
1206
+ const sid = targetSessionId || session;
1207
+ session = sid;
566
1208
  streamTurn({
567
1209
  action: 'answer',
568
- session,
1210
+ session: sid,
569
1211
  questionId: q.id,
570
1212
  choiceId: choiceId || undefined,
571
1213
  answer: clean,
572
1214
  mode: workflow === 'dispatch' ? 'design' : workflow,
1215
+ execMode,
573
1216
  persona,
574
- canvas,
1217
+ canvas: readCanvas(),
575
1218
  viewId,
576
1219
  }, {
577
1220
  humanText: clean,
578
1221
  humanLabel: '你(已确认)',
579
- isDispatch: false,
580
1222
  });
581
1223
  };
582
1224
 
@@ -611,11 +1253,14 @@
611
1253
  field.placeholder = '或输入你的补充决策…';
612
1254
  const okBtn = document.createElement('button');
613
1255
  okBtn.type = 'button';
614
- okBtn.className = 'clado-ui-button clado-agent-option-submit';
1256
+ okBtn.className = 'clado-tab-btn active';
615
1257
  okBtn.textContent = '确认';
616
1258
  okBtn.onclick = () => submitChoice('custom', field.value);
617
1259
  field.onkeydown = ev => {
618
- if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); submitChoice('custom', field.value); }
1260
+ if (ev.key === 'Enter' && !ev.isComposing) {
1261
+ ev.preventDefault();
1262
+ submitChoice('custom', field.value);
1263
+ }
619
1264
  };
620
1265
  controls.push(field, okBtn);
621
1266
  customRow.append(field, okBtn);
@@ -624,28 +1269,285 @@
624
1269
  return card;
625
1270
  }
626
1271
 
627
- async function streamTurn(payload, { humanText, humanLabel, canvas, assistantLabel, isDispatch = false }) {
628
- running = true;
629
- setHistoryOpen(false);
1272
+ function appendMessageBubble(author, text, labelOverride) {
1273
+ const empty = log.querySelector('.clado-agent-log-empty');
1274
+ if (empty) empty.remove();
1275
+ const item = document.createElement('div');
1276
+ item.className = 'clado-agent-message ' + author;
1277
+ if (author === 'human') {
1278
+ if (labelOverride && labelOverride !== '你') {
1279
+ const label = document.createElement('strong');
1280
+ label.textContent = labelOverride;
1281
+ item.append(label);
1282
+ }
1283
+ } else if (labelOverride) {
1284
+ const label = document.createElement('strong');
1285
+ label.textContent = labelOverride;
1286
+ item.append(label);
1287
+ }
1288
+ const body = document.createElement('p');
1289
+ body.textContent = text;
1290
+ item.append(body);
1291
+ log.append(item);
1292
+ return { item, body };
1293
+ }
1294
+
1295
+ function renderRecordIntoDrawer(record) {
1296
+ const pKey = record.persona || persona || 'architect';
1297
+ const pMeta = PERSONA_META[pKey] || PERSONA_META.architect;
1298
+ const pal = PALETTES[record.pal || pMeta.pal] || PALETTES.blue;
1299
+
1300
+ persona = pKey;
1301
+ spName.textContent = record.title || pMeta.label;
1302
+ spPersonaTag.textContent = pMeta.label;
1303
+ spPersonaTag.className = 'clado-tag-pill ' + pal.tagClass;
1304
+
1305
+ syncExecModeUI(record.execMode || 'act');
1306
+ if (record.mode && workflowHints[record.mode]) selectWorkflow(record.mode);
1307
+ renderTodos(record.todos || []);
1308
+
1309
+ // 若当前正流式输出该会话,不覆盖正在流式追加的实时 DOM
1310
+ if (running && streamingSessionId === record.id) return;
1311
+
1312
+ log.replaceChildren();
1313
+ const uiMsgs = Array.isArray(record.uiMessages) ? record.uiMessages : [];
1314
+ const checkpointsMap = new Map((record.checkpoints || []).map(c => [c.id, c]));
1315
+
1316
+ if (!uiMsgs.length) {
1317
+ const empty = document.createElement('div');
1318
+ empty.className = 'clado-agent-log-empty';
1319
+ empty.textContent = '会话已就绪,在下方输入想法即可开始协作(长按会话胶囊可新建分身或归档)。';
1320
+ log.append(empty);
1321
+ } else {
1322
+ for (const msg of uiMsgs) {
1323
+ if (msg.role === 'peer_in' || msg.role === 'peer_out') {
1324
+ const card = document.createElement('div');
1325
+ card.className = 'clado-peer-call-card';
1326
+ const head = document.createElement('div');
1327
+ head.className = 'clado-peer-call-head';
1328
+ head.textContent = msg.role === 'peer_in'
1329
+ ? `来自「${msg.fromName || '同伴'}」的${msg.kind === 'notify' ? '通知' : '呼叫'}`
1330
+ : `已呼叫「${msg.toName || '同伴'}」`;
1331
+ const body = document.createElement('div');
1332
+ body.textContent = msg.text || '';
1333
+ card.append(head, body);
1334
+ log.append(card);
1335
+ } else if (msg.role === 'human') {
1336
+ const lbl = msg.isSteer ? '你 · 插话纠偏' : msg.isAnswer ? '你 · 已确认' : '';
1337
+ const bubble = appendMessageBubble('human', msg.text || '', lbl);
1338
+ if (msg.canvas?.file) {
1339
+ const ctx = document.createElement('small');
1340
+ ctx.textContent = [
1341
+ msg.canvas.file.split('/').pop(),
1342
+ msg.canvas.selectionCount ? `${msg.canvas.selectionCount} 个选中标题` : '',
1343
+ ].filter(Boolean).join(' · ');
1344
+ bubble.item.append(ctx);
1345
+ }
1346
+ } else if (msg.role === 'assistant') {
1347
+ const bubble = appendMessageBubble('assistant', msg.text || '');
1348
+ if (msg.thinking) {
1349
+ const details = createThinkingBlock(msg.thinking);
1350
+ bubble.item.insertBefore(details, bubble.body);
1351
+ }
1352
+ if (!msg.text) bubble.body.hidden = true;
1353
+ if ((Array.isArray(msg.changes) && msg.changes.length) || msg.checkpointId) {
1354
+ const cp = msg.checkpointId ? checkpointsMap.get(msg.checkpointId) : null;
1355
+ bubble.item.append(createChangesRow(msg.changes || [], msg.checkpointId, record.id, Boolean(cp?.rolledBack)));
1356
+ }
1357
+ if (msg.question) {
1358
+ bubble.item.append(createQuestionCard(msg.question, record.id));
1359
+ }
1360
+ }
1361
+ }
1362
+ }
1363
+
1364
+ showStatus(
1365
+ record.pendingCommand
1366
+ ? `等待审批命令:${record.pendingCommand.command}`
1367
+ : record.pendingQuestion
1368
+ ? '等待你的确认后继续执行'
1369
+ : ''
1370
+ );
1371
+ scrollLog();
1372
+ }
1373
+
1374
+ async function fetchSessionDetail(id) {
1375
+ if (!id) return null;
1376
+ try {
1377
+ const res = await fetch(sessionUrl(id), { cache: 'no-store' });
1378
+ if (!res.ok) return null;
1379
+ const { session: record } = await res.json();
1380
+ if (record) sessionRecords.set(record.id, record);
1381
+ return record || null;
1382
+ } catch {
1383
+ return null;
1384
+ }
1385
+ }
1386
+
1387
+ async function openSinglePanel(targetId) {
1388
+ const switching = singlePanelOpen && session !== targetId;
1389
+ session = targetId;
1390
+ singlePanelOpen = true;
1391
+ singleWrap.classList.add('open');
1392
+ renderPeerCluster(false);
1393
+
1394
+ const summary = sessionsList.find(s => s.id === targetId);
1395
+ const cached = sessionRecords.get(targetId);
1396
+
1397
+ const applyView = rec => {
1398
+ if (rec) {
1399
+ renderRecordIntoDrawer(rec);
1400
+ } else {
1401
+ renderRecordIntoDrawer({
1402
+ id: targetId,
1403
+ title: summary?.title || PERSONA_META[persona]?.label || '新会话',
1404
+ persona: summary?.persona || persona,
1405
+ pal: summary?.pal || PERSONA_META[persona]?.pal || 'blue',
1406
+ mode: summary?.mode || workflow,
1407
+ execMode: summary?.execMode || execMode,
1408
+ todos: [],
1409
+ uiMessages: [],
1410
+ });
1411
+ }
1412
+ };
1413
+
1414
+ if (switching) {
1415
+ spInner.classList.add('switching');
1416
+ setTimeout(() => {
1417
+ applyView(cached);
1418
+ spInner.classList.remove('switching');
1419
+ }, 110);
1420
+ } else {
1421
+ applyView(cached);
1422
+ }
1423
+
1424
+ if (summary) {
1425
+ const latest = await fetchSessionDetail(targetId);
1426
+ if (latest && singlePanelOpen && session === targetId) {
1427
+ renderRecordIntoDrawer(latest);
1428
+ syncCommandBanner();
1429
+ }
1430
+ }
1431
+ syncActions();
1432
+ }
1433
+
1434
+ function closeSinglePanel() {
1435
+ singlePanelOpen = false;
1436
+ singleWrap.classList.remove('open');
1437
+ renderPeerCluster(false);
1438
+ }
1439
+
1440
+ // 10. 详情抽屉按钮交互
1441
+ dock.querySelector('[data-role="close-single"]').onclick = () => closeSinglePanel();
1442
+ dock.querySelector('[data-role="archive-btn"]').onclick = () => archiveSessionById(session);
1443
+ dock.querySelector('[data-role="delete-btn"]').onclick = () => deleteSessionById(session);
1444
+ dock.querySelector('[data-role="open-settings"]').onclick = () => openSettingsOverlay();
1445
+ dock.querySelector('[data-role="minimize-btn"]').onclick = () => setMinimized(true);
1446
+ orbBtn.onclick = () => setMinimized(false);
1447
+
1448
+ followBtn.onclick = () => {
1449
+ followAi = !followAi;
1450
+ followBtn.setAttribute('aria-pressed', String(followAi));
1451
+ setFollowAi(followAi);
1452
+ showToast(followAi ? '已开启镜头跟随 AI' : '已关闭镜头跟随');
1453
+ };
1454
+
1455
+ execModeBtns.forEach(btn => {
1456
+ btn.onclick = async () => {
1457
+ const next = btn.dataset.execMode === 'plan' ? 'plan' : 'act';
1458
+ syncExecModeUI(next);
1459
+ const rec = sessionRecords.get(session);
1460
+ if (rec) rec.execMode = next;
1461
+ try {
1462
+ await fetch(sessionsEndpoint, {
1463
+ method: 'POST',
1464
+ headers: { 'content-type': 'application/json' },
1465
+ body: JSON.stringify({ action: 'exec_mode', id: session, execMode: next }),
1466
+ });
1467
+ } catch {}
1468
+ };
1469
+ });
1470
+
1471
+ workflowBtns.forEach(btn => {
1472
+ btn.onclick = () => {
1473
+ if (running) return;
1474
+ selectWorkflow(btn.dataset.workflow);
1475
+ if (workflow === 'dispatch') loadMeta();
1476
+ };
1477
+ });
1478
+
1479
+ stopBtn.onclick = async () => {
1480
+ if (stopping) return;
1481
+ stopping = true;
630
1482
  syncActions();
1483
+ try {
1484
+ await request({ action: 'cancel', session });
1485
+ } catch {
1486
+ showStatus('暂时无法停止,请重试。');
1487
+ } finally {
1488
+ stopping = false;
1489
+ syncActions();
1490
+ }
1491
+ };
1492
+
1493
+ // 11. 流式对话与插话(Steer)闭环
1494
+ async function streamTurn(payload, { humanText, humanLabel, canvas, assistantLabel, isDispatch = false } = {}) {
1495
+ const targetSid = payload.session || session;
1496
+ running = true;
1497
+ streamingSessionId = targetSid;
1498
+ session = targetSid;
631
1499
 
632
- const user = message('human', humanText, humanLabel);
633
- if (canvas) {
634
- const context = document.createElement('small');
635
- context.textContent = [canvas.file.split('/').pop(), canvas.selection.length ? canvas.selection.length + ' 个选中标题' : ''].filter(Boolean).join(' · ');
636
- context.title = canvas.file;
637
- user.item.append(context);
1500
+ if (!singlePanelOpen) {
1501
+ singlePanelOpen = true;
1502
+ singleWrap.classList.add('open');
638
1503
  }
639
- const reply = message('assistant', '', assistantLabel);
1504
+
1505
+ // 乐观确保胶囊出现在会话条第 1 位
1506
+ if (!sessionsList.some(s => s.id === targetSid)) {
1507
+ const pMeta = PERSONA_META[persona] || PERSONA_META.architect;
1508
+ sessionsList.unshift({
1509
+ id: targetSid,
1510
+ title: (humanText || pMeta.label).slice(0, 22),
1511
+ persona,
1512
+ pal: pMeta.pal,
1513
+ mode: workflow,
1514
+ execMode,
1515
+ running: true,
1516
+ liveStatus: '处理中…',
1517
+ lastActiveAt: new Date().toISOString(),
1518
+ });
1519
+ } else {
1520
+ const hit = sessionsList.find(s => s.id === targetSid);
1521
+ if (hit) {
1522
+ hit.running = true;
1523
+ hit.liveStatus = '处理中…';
1524
+ hit.lastActiveAt = new Date().toISOString();
1525
+ }
1526
+ }
1527
+ renderPeerCluster(true);
1528
+
1529
+ const userBubble = appendMessageBubble('human', humanText || '', humanLabel);
1530
+ if (canvas?.file) {
1531
+ const ctx = document.createElement('small');
1532
+ ctx.textContent = [
1533
+ canvas.file.split('/').pop(),
1534
+ canvas.selection?.length ? `${canvas.selection.length} 个选中标题` : '',
1535
+ ].filter(Boolean).join(' · ');
1536
+ userBubble.item.append(ctx);
1537
+ }
1538
+
1539
+ const reply = appendMessageBubble('assistant', '', assistantLabel);
640
1540
  reply.item.hidden = true;
641
1541
  reply.body.hidden = true;
642
1542
  const replyText = reply.body.appendChild(document.createTextNode(''));
643
1543
  let thinkingPre = null;
1544
+ let pendingChanges = [];
1545
+ let turnCheckpointId = null;
644
1546
  const tools = new Map();
645
1547
  let finished = false;
646
1548
 
647
1549
  const apply = update => {
648
- const follow = log.scrollHeight - log.scrollTop - log.clientHeight < 48;
1550
+ const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 56;
649
1551
  if (update.type === 'thinking' && update.text) {
650
1552
  reply.item.hidden = false;
651
1553
  if (!thinkingPre) {
@@ -653,47 +1555,82 @@
653
1555
  reply.item.insertBefore(details, reply.body);
654
1556
  thinkingPre = details.querySelector('pre');
655
1557
  }
656
- thinkingPre.appendData ? thinkingPre.appendData(update.text) : (thinkingPre.textContent += update.text);
657
- } else if (update.type === 'text') {
1558
+ thinkingPre.textContent += update.text;
1559
+ } else if (update.type === 'text' && update.text) {
658
1560
  reply.item.hidden = false;
659
1561
  reply.body.hidden = false;
660
1562
  replyText.appendData(update.text);
661
- } else if (update.type === 'changes' && Array.isArray(update.items) && update.items.length) {
662
- reply.item.hidden = false;
663
- reply.item.append(createChangesCard(update.items));
1563
+ } else if (update.type === 'todos' && Array.isArray(update.todos)) {
1564
+ renderTodos(update.todos);
1565
+ } else if (update.type === 'changes' && Array.isArray(update.items)) {
1566
+ pendingChanges = update.items;
1567
+ } else if (update.type === 'checkpoint' && update.checkpoint?.id) {
1568
+ turnCheckpointId = update.checkpoint.id;
664
1569
  } else if (update.type === 'question' && update.question) {
665
1570
  reply.item.hidden = false;
666
- reply.item.append(createQuestionCard(update.question));
1571
+ reply.item.append(createQuestionCard(update.question, targetSid));
1572
+ } else if (update.type === 'command_approval' && (update.approval || update.command)) {
1573
+ const curTitle = sessionsList.find(s => s.id === targetSid)?.title || spName.textContent || '当前会话';
1574
+ activePendingCmd = {
1575
+ sessionId: targetSid,
1576
+ sessionTitle: curTitle,
1577
+ cmd: update.approval || update.command,
1578
+ };
1579
+ syncCommandBanner();
1580
+ } else if (update.type === 'peer_event') {
1581
+ reply.item.hidden = false;
1582
+ const card = document.createElement('div');
1583
+ card.className = 'clado-peer-call-card';
1584
+ const head = document.createElement('div');
1585
+ head.className = 'clado-peer-call-head';
1586
+ head.textContent = `已呼叫「${update.toName || update.name || '同伴分身'}」`;
1587
+ const body = document.createElement('div');
1588
+ body.textContent = update.text || update.task || '';
1589
+ card.append(head, body);
1590
+ reply.item.append(card);
667
1591
  } else if (update.type === 'status') {
668
1592
  showStatus(update.text);
1593
+ const hit = sessionsList.find(s => s.id === targetSid);
1594
+ if (hit && update.text) {
1595
+ hit.liveStatus = update.text;
1596
+ const pill = pillDomMap.get(targetSid);
1597
+ if (pill) pill.querySelector('.p-live').textContent = '· ' + update.text;
1598
+ }
669
1599
  } else if (update.type === 'tool') {
670
1600
  const title = update.title || tools.get(update.id);
671
1601
  if (title) {
672
1602
  tools.set(update.id, title);
673
- showStatus([title, toolStates[update.status]].filter(Boolean).join(' · '));
1603
+ const line = [title.split('.').pop(), toolStates[update.status]].filter(Boolean).join(' · ');
1604
+ showStatus(line);
674
1605
  }
675
1606
  } else if (update.type === 'error') {
676
1607
  throw new Error(update.text);
677
1608
  } else if (update.type === 'done') {
678
1609
  finished = true;
1610
+ if (pendingChanges.length || turnCheckpointId) {
1611
+ reply.item.hidden = false;
1612
+ reply.item.append(createChangesRow(pendingChanges, turnCheckpointId, targetSid, false));
1613
+ }
679
1614
  const labels = {
680
1615
  cancelled: '已停止',
681
1616
  awaiting_user: '等待你的确认后继续执行',
1617
+ awaiting_command: '等待你审批命令后继续执行',
682
1618
  max_tokens: '已达到本轮输出上限',
683
1619
  max_turn_requests: '已达到本轮请求上限',
684
- refusal: '拒绝执行本轮请求',
1620
+ refusal: '已拒绝执行本轮请求',
685
1621
  };
686
1622
  showStatus(labels[update.reason] || (isDispatch ? '执行器已完成,可切到「Diff 验收」核对代码变更' : ''));
687
1623
  }
688
- if (follow) scroll();
1624
+ if (nearBottom) scrollLog();
689
1625
  };
690
1626
 
691
- showStatus(isDispatch ? `正在派发给 ${assistantLabel || agentName}` : '正在连接 灵感');
692
- scroll();
1627
+ showStatus(isDispatch ? `正在派发给 ${assistantLabel || agentName}…` : '正在连接 灵感…');
1628
+ scrollLog();
1629
+
693
1630
  try {
694
1631
  const response = await request(payload);
695
1632
  if (!response.ok) {
696
- const failure = await response.json();
1633
+ const failure = await response.json().catch(() => ({}));
697
1634
  throw new Error(failure.error || '发送失败。');
698
1635
  }
699
1636
  const reader = response.body.getReader();
@@ -706,7 +1643,9 @@
706
1643
  buffer += decoder.decode(value, { stream: true });
707
1644
  const records = buffer.split('\n');
708
1645
  buffer = records.pop();
709
- for (const record of records) if (record) apply(JSON.parse(record));
1646
+ for (const record of records) {
1647
+ if (record.trim()) apply(JSON.parse(record));
1648
+ }
710
1649
  }
711
1650
  buffer += decoder.decode();
712
1651
  if (buffer.trim()) apply(JSON.parse(buffer));
@@ -719,24 +1658,57 @@
719
1658
  showStatus(error.message || '运行失败。');
720
1659
  } finally {
721
1660
  if (reply.item.hidden) reply.item.remove();
722
- running = stopping = false;
1661
+ running = false;
1662
+ stopping = false;
1663
+ streamingSessionId = '';
1664
+ await Promise.all([
1665
+ refreshSessionsList(false),
1666
+ fetchSessionDetail(targetSid),
1667
+ ]);
1668
+ if (singlePanelOpen && session === targetSid && sessionRecords.has(targetSid)) {
1669
+ renderRecordIntoDrawer(sessionRecords.get(targetSid));
1670
+ }
1671
+ syncCommandBanner();
723
1672
  syncActions();
724
- if (!panel.hidden) input.focus();
725
1673
  }
726
1674
  }
727
1675
 
728
- form.onsubmit = async event => {
1676
+ input.addEventListener('input', syncActions);
1677
+ input.addEventListener('keydown', event => {
1678
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing && event.keyCode !== 229) {
1679
+ event.preventDefault();
1680
+ if (!sendBtn.disabled) shell.requestSubmit();
1681
+ }
1682
+ });
1683
+
1684
+ shell.onsubmit = async event => {
729
1685
  event.preventDefault();
730
1686
  if (!canSubmit()) return;
731
- const isDispatch = workflow === 'dispatch';
732
1687
  const rawText = input.value.trim();
1688
+
1689
+ // 运行中实时插话(Steer)
1690
+ if (running && streamingSessionId === session && meta.engine === 'builtin' && rawText) {
1691
+ input.value = '';
1692
+ syncActions();
1693
+ try {
1694
+ const res = await request({ action: 'steer', session, text: rawText });
1695
+ if (res.ok) {
1696
+ appendMessageBubble('human', rawText, '你 · 插话纠偏');
1697
+ scrollLog();
1698
+ showToast('已插话,将在当前步骤完成后立即生效');
1699
+ }
1700
+ } catch {}
1701
+ return;
1702
+ }
1703
+
1704
+ const isDispatch = workflow === 'dispatch';
733
1705
  const text = rawText || (workflow === 'audit' ? '请核对当前本地 Git Diff 与画布设计契约、测试用例的差异,并给出验收结论。' : '');
734
1706
  const canvas = readCanvas();
735
1707
  input.value = '';
736
1708
  const executorName = executorSelect.selectedOptions?.[0]?.textContent || agentName;
737
1709
  const payload = isDispatch
738
1710
  ? { action: 'dispatch', session, executorId: executorSelect.value || undefined, text: rawText, canvas, viewId }
739
- : { action: 'prompt', session, mode: workflow, persona, text, canvas, viewId };
1711
+ : { action: 'prompt', session, mode: workflow, execMode, persona, text, canvas, viewId };
740
1712
  await streamTurn(payload, {
741
1713
  humanText: isDispatch ? `[派发开发 → ${executorName}] ${rawText || '按当前画布规格实现代码并运行测试'}` : text,
742
1714
  canvas,
@@ -744,5 +1716,421 @@
744
1716
  isDispatch,
745
1717
  });
746
1718
  };
1719
+
1720
+ // 12. 极简「Agent 设置」与上下文调试面板(对接 /library/agent/config)
1721
+ let debugState = {
1722
+ config: {
1723
+ canvasMemory: 'delta',
1724
+ timeInjection: 'date_only',
1725
+ workspaceMap: true,
1726
+ memoryEnabled: true,
1727
+ autoArchiveHours: 24,
1728
+ commandPermission: 'readonly_free',
1729
+ compactThresholdPct: 75,
1730
+ compactPrompt: '',
1731
+ personas: {},
1732
+ },
1733
+ memory: { text: '', inherited: [] },
1734
+ telemetry: null,
1735
+ };
1736
+ let currentSub = null;
1737
+ let activePersonaTab = 'architect';
1738
+ const cfgHomeEl = configView.querySelector('[data-role="cfg-home"]');
1739
+ const cfgSubEl = configView.querySelector('[data-role="cfg-sub"]');
1740
+ const subTitleEl = configView.querySelector('[data-role="sub-title"]');
1741
+ const subResetBtn = configView.querySelector('[data-role="sub-reset"]');
1742
+ const subBodyEl = configView.querySelector('[data-role="sub-body"]');
1743
+
1744
+ function syncConfigSummaryUI() {
1745
+ const c = debugState.config;
1746
+ const findLabel = (arr, val, fallback) => (arr.find(([k]) => k === val) || [null, fallback])[1];
1747
+ configView.querySelector('[data-cfg-val="canvas"]').textContent = findLabel(CANVAS_MEM_CYCLE, c.canvasMemory, '智能增量');
1748
+ configView.querySelector('[data-cfg-val="time"]').textContent = findLabel(TIME_MODE_CYCLE, c.timeInjection, '仅日期');
1749
+ configView.querySelector('[data-cfg-val="ttl"]').textContent = findLabel(TTL_CYCLE, c.autoArchiveHours, '24 小时');
1750
+ configView.querySelector('[data-cfg-val="perm"]').textContent = findLabel(PERM_CYCLE, c.commandPermission, '只读免审');
1751
+ configView.querySelector('[data-cfg-val="memory"]').textContent = c.memoryEnabled ? '已开启 · 编辑' : '已关闭';
1752
+ configView.querySelector('[data-cfg-val="compact"]').textContent = `${c.compactThresholdPct || 75}% 触发 · 编辑`;
1753
+ configView.querySelector('[data-cfg-act="toggle-map"]').classList.toggle('on', c.workspaceMap !== false);
1754
+
1755
+ const cacheEl = configView.querySelector('[data-cfg-val="cache"]');
1756
+ const rate = debugState.telemetry?.hitRatePct ?? (c.timeInjection === 'system_head' ? 0 : c.canvasMemory === 'full' ? 78.8 : 99.4);
1757
+ if (c.timeInjection === 'system_head') {
1758
+ cacheEl.textContent = `${rate}% (系统头破缓存)`;
1759
+ cacheEl.style.color = 'var(--clado-agent-danger)';
1760
+ } else if (c.canvasMemory === 'full') {
1761
+ cacheEl.textContent = `${rate}% 命中`;
1762
+ cacheEl.style.color = '#d97706';
1763
+ } else {
1764
+ cacheEl.textContent = `${rate}% 命中`;
1765
+ cacheEl.style.color = '#059669';
1766
+ }
1767
+ }
1768
+
1769
+ async function loadDebugConfig() {
1770
+ try {
1771
+ const res = await fetch(configEndpoint, { cache: 'no-store' });
1772
+ if (!res.ok) return;
1773
+ const data = await res.json();
1774
+ if (data.config) debugState.config = data.config;
1775
+ if (data.memory) debugState.memory = data.memory;
1776
+ if (data.telemetry) debugState.telemetry = data.telemetry;
1777
+ syncConfigSummaryUI();
1778
+ } catch {}
1779
+ }
1780
+
1781
+ async function saveDebugPatch(patch) {
1782
+ debugState.config = { ...debugState.config, ...patch };
1783
+ syncConfigSummaryUI();
1784
+ try {
1785
+ const res = await fetch(configEndpoint, {
1786
+ method: 'POST',
1787
+ headers: { 'content-type': 'application/json' },
1788
+ body: JSON.stringify({ action: 'save_config', patch }),
1789
+ });
1790
+ if (res.ok) {
1791
+ const data = await res.json();
1792
+ if (data.config) debugState.config = data.config;
1793
+ if (data.telemetry) debugState.telemetry = data.telemetry;
1794
+ syncConfigSummaryUI();
1795
+ }
1796
+ } catch {}
1797
+ }
1798
+
1799
+ function openSettingsOverlay() {
1800
+ closeCfgSub();
1801
+ configView.classList.add('show');
1802
+ dock.hidden = true;
1803
+ loadDebugConfig();
1804
+ }
1805
+
1806
+ function closeSettingsOverlay() {
1807
+ configView.classList.remove('show');
1808
+ dock.hidden = false;
1809
+ requestAnimationFrame(() => updatePeerEdgeFade());
1810
+ }
1811
+
1812
+ function closeCfgSub() {
1813
+ currentSub = null;
1814
+ cfgSubEl.classList.remove('active');
1815
+ cfgHomeEl.classList.remove('pushed-out');
1816
+ }
1817
+
1818
+ function renderPersonaSubBody() {
1819
+ const personas = debugState.config.personas || {};
1820
+ const cur = personas[activePersonaTab] || { name: PERSONA_META[activePersonaTab]?.label || activePersonaTab, prompt: '', initContext: '' };
1821
+ const keys = ['architect', 'coder', 'qa', 'auditor'];
1822
+ subBodyEl.innerHTML = `
1823
+ <div class="clado-tab-group" style="display:grid;grid-template-columns:repeat(4,1fr);width:100%;">
1824
+ ${keys.map(k => `<button type="button" class="clado-tab-btn ${k === activePersonaTab ? 'active' : ''}" data-pick-persona="${k}" style="padding:5px 4px;font-size:11.5px;">${(PERSONA_META[k]?.label || k).slice(0, 4)}</button>`).join('')}
1825
+ </div>
1826
+ <div>
1827
+ <div style="font-size:12px;color:var(--clado-ui-muted);margin-bottom:5px;">角色提示词</div>
1828
+ <textarea class="clado-clean-textarea" data-field="persona-prompt" rows="4"></textarea>
1829
+ </div>
1830
+ <div>
1831
+ <div style="font-size:12px;color:var(--clado-ui-muted);margin-bottom:5px;">派出分身默认携带上下文</div>
1832
+ <textarea class="clado-clean-textarea" data-field="persona-ctx" rows="3"></textarea>
1833
+ </div>
1834
+ <button type="button" class="clado-tab-btn active" data-save-persona style="height:34px;font-size:12.5px;">保存当前人设模板</button>`;
1835
+ const promptArea = subBodyEl.querySelector('[data-field="persona-prompt"]');
1836
+ const ctxArea = subBodyEl.querySelector('[data-field="persona-ctx"]');
1837
+ promptArea.value = cur.prompt || '';
1838
+ ctxArea.value = cur.initContext || '';
1839
+
1840
+ subBodyEl.querySelectorAll('[data-pick-persona]').forEach(b => {
1841
+ b.onclick = () => {
1842
+ activePersonaTab = b.dataset.pickPersona;
1843
+ renderPersonaSubBody();
1844
+ };
1845
+ });
1846
+ subBodyEl.querySelector('[data-save-persona]').onclick = async () => {
1847
+ const nextPersonas = {
1848
+ ...(debugState.config.personas || {}),
1849
+ [activePersonaTab]: {
1850
+ ...cur,
1851
+ prompt: promptArea.value,
1852
+ initContext: ctxArea.value,
1853
+ },
1854
+ };
1855
+ await saveDebugPatch({ personas: nextPersonas });
1856
+ showToast('已保存人设与分身初始上下文');
1857
+ };
1858
+ }
1859
+
1860
+ function openCfgSub(sub) {
1861
+ currentSub = sub;
1862
+ subResetBtn.style.visibility = sub === 'cache' ? 'hidden' : 'visible';
1863
+
1864
+ if (sub === 'memory') {
1865
+ subTitleEl.textContent = '持久记忆 (memory.md)';
1866
+ const inheritedFiles = Array.isArray(debugState.memory?.inherited) ? debugState.memory.inherited.map(i => i.file) : [];
1867
+ const inheritedHint = inheritedFiles.length
1868
+ ? `已检测到根目录 ${inheritedFiles.join(' / ')} 并自动只读继承。`
1869
+ : '保存于当前工作区 .clado/memory.md,同时支持只读继承根目录 AGENTS.md。';
1870
+ subBodyEl.innerHTML = `
1871
+ <div style="display:flex;align-items:center;justify-content:space-between;">
1872
+ <span style="font-size:13px;font-weight:550;">启用工作区持久记忆</span>
1873
+ <button type="button" class="clado-switch-btn ${debugState.config.memoryEnabled !== false ? 'on' : ''}" data-mem-toggle><i></i></button>
1874
+ </div>
1875
+ <textarea class="clado-clean-textarea" data-mem-area rows="6" placeholder="- 记录项目核心架构约定、禁止事项与统一规范…"></textarea>
1876
+ <div style="font-size:11.5px;color:var(--clado-ui-muted);">${inheritedHint}</div>
1877
+ <button type="button" class="clado-tab-btn active" data-mem-save style="height:34px;font-size:12.5px;">保存 memory.md</button>`;
1878
+ const area = subBodyEl.querySelector('[data-mem-area]');
1879
+ area.value = debugState.memory?.text || '';
1880
+ const sw = subBodyEl.querySelector('[data-mem-toggle]');
1881
+ sw.onclick = () => {
1882
+ const next = !sw.classList.contains('on');
1883
+ sw.classList.toggle('on', next);
1884
+ saveDebugPatch({ memoryEnabled: next });
1885
+ };
1886
+ subBodyEl.querySelector('[data-mem-save]').onclick = async () => {
1887
+ try {
1888
+ const res = await fetch(configEndpoint, {
1889
+ method: 'POST',
1890
+ headers: { 'content-type': 'application/json' },
1891
+ body: JSON.stringify({ action: 'save_memory', text: area.value }),
1892
+ });
1893
+ if (res.ok) {
1894
+ const data = await res.json();
1895
+ if (data.memory) debugState.memory = data.memory;
1896
+ if (data.telemetry) debugState.telemetry = data.telemetry;
1897
+ syncConfigSummaryUI();
1898
+ showToast('已保存工作区 memory.md');
1899
+ }
1900
+ } catch {}
1901
+ };
1902
+ } else if (sub === 'persona') {
1903
+ subTitleEl.textContent = '人设与初始上下文';
1904
+ renderPersonaSubBody();
1905
+ } else if (sub === 'compact') {
1906
+ subTitleEl.textContent = '上下文压缩';
1907
+ const pct = debugState.config.compactThresholdPct || 75;
1908
+ subBodyEl.innerHTML = `
1909
+ <div style="display:flex;align-items:center;justify-content:space-between;">
1910
+ <span style="font-size:13px;font-weight:550;">触发阈值:<span data-compact-pct>${pct}%</span></span>
1911
+ <input data-compact-range type="range" min="50" max="90" step="5" value="${pct}" style="width:130px;accent-color:var(--clado-ui-brand);" />
1912
+ </div>
1913
+ <textarea class="clado-clean-textarea" data-compact-area rows="6"></textarea>
1914
+ <div style="display:flex;gap:8px;">
1915
+ <button type="button" class="clado-tab-btn active" data-compact-save style="flex:1;height:34px;font-size:12.5px;">保存配置</button>
1916
+ <button type="button" class="clado-cmd-btn allow" data-compact-test style="flex:1;height:34px;font-size:12.5px;">测试压缩效果</button>
1917
+ </div>`;
1918
+ const rng = subBodyEl.querySelector('[data-compact-range]');
1919
+ const pctSpan = subBodyEl.querySelector('[data-compact-pct]');
1920
+ const area = subBodyEl.querySelector('[data-compact-area]');
1921
+ area.value = debugState.config.compactPrompt || '';
1922
+ rng.oninput = () => { pctSpan.textContent = rng.value + '%'; };
1923
+ subBodyEl.querySelector('[data-compact-save]').onclick = async () => {
1924
+ await saveDebugPatch({
1925
+ compactThresholdPct: Number(rng.value),
1926
+ compactPrompt: area.value,
1927
+ });
1928
+ showToast('已保存上下文压缩策略');
1929
+ };
1930
+ subBodyEl.querySelector('[data-compact-test]').onclick = async () => {
1931
+ try {
1932
+ const res = await fetch(configEndpoint, {
1933
+ method: 'POST',
1934
+ headers: { 'content-type': 'application/json' },
1935
+ body: JSON.stringify({ action: 'test_compact', sessionId: session }),
1936
+ });
1937
+ if (res.ok) {
1938
+ const r = await res.json();
1939
+ showToast(`压缩测试:${r.beforeTurns} 轮 → ${r.afterTurns} 轮(${r.beforeTokens} → ${r.afterTokens} tok)`);
1940
+ }
1941
+ } catch {}
1942
+ };
1943
+ } else if (sub === 'cache') {
1944
+ subTitleEl.textContent = '缓存分段明细';
1945
+ const t = debugState.telemetry;
1946
+ const sysBroken = Boolean(t?.brokenBySystemTime || debugState.config.timeInjection === 'system_head');
1947
+ if (t) {
1948
+ subBodyEl.innerHTML = [
1949
+ ['第 1 段 · 冰封静态头', t.seg1Tokens, sysBroken ? '失效' : '命中'],
1950
+ ['第 2 段 · 工作区目录索引', t.seg2Tokens, sysBroken ? '失效' : '命中'],
1951
+ ['第 3 段 · 历史与画布基线', t.seg3Tokens, sysBroken ? '失效' : '命中'],
1952
+ ['第 4 段 · 尾部增量与状态', t.seg4Tokens, '新增'],
1953
+ ].map(([label, tok, st]) => `<div style="display:flex;justify-content:space-between;font-size:13px;"><span>${label}</span><strong>${tok} tok (${st})</strong></div>`).join('');
1954
+ } else {
1955
+ subBodyEl.innerHTML = '<div style="font-size:12.5px;color:var(--clado-ui-muted);">暂无分段采样数据。</div>';
1956
+ }
1957
+ }
1958
+
1959
+ cfgHomeEl.classList.add('pushed-out');
1960
+ cfgSubEl.classList.add('active');
1961
+ }
1962
+
1963
+ configView.addEventListener('click', async ev => {
1964
+ if (ev.target === configView) {
1965
+ closeSettingsOverlay();
1966
+ return;
1967
+ }
1968
+ const el = ev.target.closest('[data-cfg-act]');
1969
+ if (!el) return;
1970
+ const act = el.dataset.cfgAct;
1971
+ if (act === 'close-settings') {
1972
+ closeSettingsOverlay();
1973
+ } else if (act === 'cycle') {
1974
+ const kind = el.dataset.cfgKind;
1975
+ const cycleNext = (arr, cur) => {
1976
+ const i = arr.findIndex(([k]) => k === cur);
1977
+ return arr[(i + 1) % arr.length][0];
1978
+ };
1979
+ if (kind === 'canvas') await saveDebugPatch({ canvasMemory: cycleNext(CANVAS_MEM_CYCLE, debugState.config.canvasMemory) });
1980
+ else if (kind === 'time') await saveDebugPatch({ timeInjection: cycleNext(TIME_MODE_CYCLE, debugState.config.timeInjection) });
1981
+ else if (kind === 'ttl') await saveDebugPatch({ autoArchiveHours: cycleNext(TTL_CYCLE, debugState.config.autoArchiveHours) });
1982
+ else if (kind === 'perm') await saveDebugPatch({ commandPermission: cycleNext(PERM_CYCLE, debugState.config.commandPermission) });
1983
+ } else if (act === 'toggle-map') {
1984
+ const next = !el.classList.contains('on');
1985
+ await saveDebugPatch({ workspaceMap: next });
1986
+ } else if (act === 'open-sub') {
1987
+ openCfgSub(el.dataset.sub);
1988
+ } else if (act === 'close-sub') {
1989
+ closeCfgSub();
1990
+ } else if (act === 'reset-sub') {
1991
+ if (!currentSub) return;
1992
+ const section = currentSub === 'persona' ? 'personas' : currentSub;
1993
+ try {
1994
+ if (currentSub === 'memory') {
1995
+ await fetch(configEndpoint, {
1996
+ method: 'POST',
1997
+ headers: { 'content-type': 'application/json' },
1998
+ body: JSON.stringify({ action: 'save_memory', text: '' }),
1999
+ });
2000
+ } else {
2001
+ const res = await fetch(configEndpoint, {
2002
+ method: 'POST',
2003
+ headers: { 'content-type': 'application/json' },
2004
+ body: JSON.stringify({ action: 'reset', section }),
2005
+ });
2006
+ if (res.ok) {
2007
+ const data = await res.json();
2008
+ if (data.config) debugState.config = data.config;
2009
+ if (data.telemetry) debugState.telemetry = data.telemetry;
2010
+ }
2011
+ }
2012
+ await loadDebugConfig();
2013
+ openCfgSub(currentSub);
2014
+ showToast('已恢复默认设置');
2015
+ } catch {}
2016
+ }
2017
+ });
2018
+
2019
+ // 13. 元信息、SSE 实时会话同步与 1s 静息推进定时器
2020
+ async function loadMeta() {
2021
+ try {
2022
+ const res = await fetch(metaEndpoint, { cache: 'no-store' });
2023
+ if (!res.ok) return;
2024
+ meta = await res.json();
2025
+ if (meta.defaultPersona && PERSONA_META[meta.defaultPersona]) {
2026
+ persona = meta.defaultPersona;
2027
+ }
2028
+ const list = Array.isArray(meta.executors) ? meta.executors : [];
2029
+ const prev = executorSelect.value;
2030
+ executorSelect.replaceChildren();
2031
+ if (!list.length) {
2032
+ const opt = document.createElement('option');
2033
+ opt.value = '';
2034
+ opt.textContent = '未配置 ACP 执行器';
2035
+ executorSelect.append(opt);
2036
+ } else {
2037
+ for (const item of list) {
2038
+ const opt = document.createElement('option');
2039
+ opt.value = item.id;
2040
+ opt.textContent = item.name + (item.source === 'plugin' ? '(插件)' : '');
2041
+ executorSelect.append(opt);
2042
+ }
2043
+ if (prev && list.some(item => item.id === prev)) executorSelect.value = prev;
2044
+ }
2045
+ executorDropdown.sync();
2046
+
2047
+ if (Array.isArray(meta.sessions)) {
2048
+ ingestSessionList(meta.sessions, false);
2049
+ }
2050
+ } catch {}
2051
+ }
2052
+
2053
+ async function refreshSessionsList(animate = false) {
2054
+ try {
2055
+ const res = await fetch(sessionsEndpoint, { cache: 'no-store' });
2056
+ if (!res.ok) return;
2057
+ const data = await res.json();
2058
+ if (Array.isArray(data.sessions)) {
2059
+ ingestSessionList(data.sessions, animate);
2060
+ }
2061
+ } catch {}
2062
+ }
2063
+
2064
+ window.addEventListener('clado:agent-sessions', ev => {
2065
+ const incoming = ev.detail?.sessions;
2066
+ if (Array.isArray(incoming)) {
2067
+ ingestSessionList(incoming, true);
2068
+ if (singlePanelOpen && session) {
2069
+ fetchSessionDetail(session).then(rec => {
2070
+ if (rec && singlePanelOpen && session === rec.id && !(running && streamingSessionId === rec.id)) {
2071
+ renderRecordIntoDrawer(rec);
2072
+ }
2073
+ });
2074
+ }
2075
+ }
2076
+ });
2077
+
2078
+ window.addEventListener('clado:send-selection', ev => {
2079
+ const names = ev.detail?.names || '';
2080
+ setMinimized(false);
2081
+ openSinglePanel(session);
2082
+ if (names && !input.value.trim()) {
2083
+ input.value = `结合 [${names}] 优化设计:`;
2084
+ }
2085
+ syncActions();
2086
+ input.focus();
2087
+ });
2088
+
2089
+ // 每秒检查是否有会话跨越 30s 活跃/静息分界线,平滑收缩状态字与重排
2090
+ const idleTick = setInterval(() => {
2091
+ if (!sessionsList.length) return;
2092
+ let crossedBoundary = false;
2093
+ for (const s of sessionsList) {
2094
+ if (s.archived) continue;
2095
+ const pill = pillDomMap.get(s.id);
2096
+ if (!pill) continue;
2097
+ const wasActive = pill.classList.contains('is-active');
2098
+ const nowActive = isSessionActive(s);
2099
+ if (wasActive !== nowActive) crossedBoundary = true;
2100
+ }
2101
+ if (crossedBoundary) renderPeerCluster(true);
2102
+ }, 1000);
2103
+
2104
+ document.addEventListener('pointerdown', event => {
2105
+ if (!ctxMenu.contains(event.target)) closeCtxMenu();
2106
+ for (const dd of glassDropdowns) {
2107
+ if (!dd.menu.hidden && !dd.wrap.contains(event.target)) dd.setOpen(false);
2108
+ }
2109
+ });
2110
+
2111
+ document.addEventListener('keydown', event => {
2112
+ if (event.key === 'Escape') {
2113
+ closeCtxMenu();
2114
+ for (const dd of glassDropdowns) {
2115
+ if (!dd.menu.hidden) dd.setOpen(false);
2116
+ }
2117
+ if (configView.classList.contains('show')) {
2118
+ if (currentSub) closeCfgSub();
2119
+ else closeSettingsOverlay();
2120
+ } else if (singlePanelOpen) {
2121
+ closeSinglePanel();
2122
+ }
2123
+ }
2124
+ });
2125
+
2126
+ addEventListener('pagehide', event => {
2127
+ clearInterval(idleTick);
2128
+ if (!event.persisted) request({ action: 'close', session }, true).catch(() => {});
2129
+ });
2130
+
2131
+ // 初始化加载
2132
+ renderPeerCluster(false);
2133
+ loadMeta();
2134
+ refreshArchivedSessions();
747
2135
  };
748
2136
  })();