openprototype 1.6.0 → 1.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +138 -0
- package/package.json +1 -1
- package/runtime/shell/agent-panel.css +97 -5
- package/runtime/shell/agent-panel.js +314 -32
package/bin/cli.js
CHANGED
|
@@ -111,6 +111,75 @@ const ONBOARDING_BODY = [
|
|
|
111
111
|
'<script src="/_kit/shell/onboarding.js"></script>',
|
|
112
112
|
'<!-- onboarding:end -->'
|
|
113
113
|
].join('\n');
|
|
114
|
+
const LAN_ADDRESS_HELPER_MARK = 'async function loadLanAddress()';
|
|
115
|
+
const LAN_ADDRESS_HELPER = `async function loadLanAddress() {
|
|
116
|
+
const parts = window.location.pathname.split('/').filter(Boolean);
|
|
117
|
+
const productAt = parts.indexOf('product');
|
|
118
|
+
const productId = productAt >= 0 ? decodeURIComponent(parts[productAt + 1] || '') : '';
|
|
119
|
+
const surface = productAt >= 0 ? decodeURIComponent(parts[productAt + 2] || '') : '';
|
|
120
|
+
const params = new URLSearchParams({ productId, surface });
|
|
121
|
+
const res = await fetch('/api/lan-address?' + params.toString(), { cache: 'no-store' });
|
|
122
|
+
const data = await res.json().catch(() => ({}));
|
|
123
|
+
if (!res.ok || !data.ok) throw new Error(data.error || '局域网地址读取失败');
|
|
124
|
+
return String(data.lanAddress || '').trim();
|
|
125
|
+
}`;
|
|
126
|
+
const LAN_ADDRESS_CLICK = ` document.getElementById('copyAddressBtn').addEventListener('click', async () => {
|
|
127
|
+
try {
|
|
128
|
+
const lanAddress = await loadLanAddress();
|
|
129
|
+
if (!lanAddress) {
|
|
130
|
+
showToast('请先在 proto-kit.config.json 配置该产品当前端的 lanAddress');
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
copyText(lanAddress, '局域网地址已复制到剪贴板');
|
|
134
|
+
} catch (err) {
|
|
135
|
+
showToast(err.message || '局域网地址读取失败');
|
|
136
|
+
}
|
|
137
|
+
});`;
|
|
138
|
+
const LEGACY_LAN_ADDRESS_MARK = 'openprototype:lan-address:start';
|
|
139
|
+
const LEGACY_LAN_ADDRESS_BLOCK = `<!-- openprototype:lan-address:start -->
|
|
140
|
+
<script>
|
|
141
|
+
(() => {
|
|
142
|
+
const button = document.getElementById('prototypeCopyAddress');
|
|
143
|
+
const toast = document.getElementById('prototypeToast');
|
|
144
|
+
if (!button || !toast) return;
|
|
145
|
+
const showToast = message => {
|
|
146
|
+
toast.textContent = message;
|
|
147
|
+
toast.classList.add('is-visible');
|
|
148
|
+
window.setTimeout(() => toast.classList.remove('is-visible'), 1800);
|
|
149
|
+
};
|
|
150
|
+
button.addEventListener('click', async event => {
|
|
151
|
+
event.preventDefault();
|
|
152
|
+
event.stopImmediatePropagation();
|
|
153
|
+
try {
|
|
154
|
+
const parts = window.location.pathname.split('/').filter(Boolean);
|
|
155
|
+
const productAt = parts.indexOf('product');
|
|
156
|
+
const params = new URLSearchParams({
|
|
157
|
+
productId: productAt >= 0 ? decodeURIComponent(parts[productAt + 1] || '') : '',
|
|
158
|
+
surface: productAt >= 0 ? decodeURIComponent(parts[productAt + 2] || '') : ''
|
|
159
|
+
});
|
|
160
|
+
const res = await fetch('/api/lan-address?' + params.toString(), { cache: 'no-store' });
|
|
161
|
+
const data = await res.json().catch(() => ({}));
|
|
162
|
+
if (!res.ok || !data.ok) throw new Error(data.error || '局域网地址读取失败');
|
|
163
|
+
const lanAddress = String(data.lanAddress || '').trim();
|
|
164
|
+
if (!lanAddress) throw new Error('请先在 proto-kit.config.json 配置该产品当前端的 lanAddress');
|
|
165
|
+
try {
|
|
166
|
+
await navigator.clipboard.writeText(lanAddress);
|
|
167
|
+
} catch {
|
|
168
|
+
const textarea = document.createElement('textarea');
|
|
169
|
+
textarea.value = lanAddress;
|
|
170
|
+
document.body.appendChild(textarea);
|
|
171
|
+
textarea.select();
|
|
172
|
+
document.execCommand('copy');
|
|
173
|
+
textarea.remove();
|
|
174
|
+
}
|
|
175
|
+
showToast('局域网地址已复制到剪贴板');
|
|
176
|
+
} catch (err) {
|
|
177
|
+
showToast(err.message || '局域网地址读取失败');
|
|
178
|
+
}
|
|
179
|
+
}, true);
|
|
180
|
+
})();
|
|
181
|
+
</script>
|
|
182
|
+
<!-- openprototype:lan-address:end -->`;
|
|
114
183
|
|
|
115
184
|
/** 列出 product/<id>/<root>/index.html —— 已生成的产品壳 */
|
|
116
185
|
function listProductShells(projectRoot) {
|
|
@@ -161,6 +230,74 @@ function patchShellOnboarding(projectRoot) {
|
|
|
161
230
|
return patched;
|
|
162
231
|
}
|
|
163
232
|
|
|
233
|
+
/**
|
|
234
|
+
* 把旧产品壳的“复制地址”迁移到运行时 /api/lan-address。
|
|
235
|
+
* 只识别脚手架的 copyAddressBtn 和旧导航的 prototypeCopyAddress;其他定制壳不动。
|
|
236
|
+
*/
|
|
237
|
+
function patchShellLanAddress(projectRoot) {
|
|
238
|
+
let patched = 0;
|
|
239
|
+
const oldClick = / document\.getElementById\('copyAddressBtn'\)\.addEventListener\('click', \(\) => \{\s*copyText\((?:window\.location\.href|NAVIGATOR_ADDRESS),\s*'[^']*'\);\s*\}\);/;
|
|
240
|
+
const initAnchor = "window.addEventListener('DOMContentLoaded', async () => {";
|
|
241
|
+
|
|
242
|
+
for (const shell of listProductShells(projectRoot)) {
|
|
243
|
+
const rel = path.relative(projectRoot, shell);
|
|
244
|
+
let html = fs.readFileSync(shell, 'utf8');
|
|
245
|
+
|
|
246
|
+
if (/id=(['"])prototypeCopyAddress\1/.test(html)) {
|
|
247
|
+
if (html.includes(LEGACY_LAN_ADDRESS_MARK)) {
|
|
248
|
+
info(C.dim(' 跳过(已有局域网复制): ') + rel);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const legacyScript = /<script\b[^>]*\bsrc=(['"])\/scripts\/prototype-agent\/prototype-navigator\.js[^'"]*\1[^>]*><\/script>/i;
|
|
252
|
+
const legacyMatch = html.match(legacyScript);
|
|
253
|
+
if (!legacyMatch) {
|
|
254
|
+
info(C.dim(' 跳过(旧导航结构不认识): ') + rel);
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
html = html.replace(
|
|
258
|
+
/(<button\b[^>]*\bid=(['"])prototypeCopyAddress\2[^>]*>)[\s\S]*?(<\/button>)/i,
|
|
259
|
+
'$1复制局域网地址$3'
|
|
260
|
+
);
|
|
261
|
+
html = html.replace(legacyMatch[0], legacyMatch[0] + '\n' + LEGACY_LAN_ADDRESS_BLOCK);
|
|
262
|
+
fs.writeFileSync(shell, html);
|
|
263
|
+
ok('已迁移局域网复制功能 ' + rel);
|
|
264
|
+
patched++;
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (!/id=(['"])copyAddressBtn\1/.test(html)) continue;
|
|
269
|
+
|
|
270
|
+
const nextLabel = html.replace(
|
|
271
|
+
/(<button\b[^>]*\bid=(['"])copyAddressBtn\2[^>]*>)[\s\S]*?(<\/button>)/i,
|
|
272
|
+
'$1复制局域网地址$3'
|
|
273
|
+
);
|
|
274
|
+
if (html.includes(LAN_ADDRESS_HELPER_MARK)) {
|
|
275
|
+
if (nextLabel !== html) {
|
|
276
|
+
fs.writeFileSync(shell, nextLabel);
|
|
277
|
+
ok('已更新局域网复制文案 ' + rel);
|
|
278
|
+
patched++;
|
|
279
|
+
} else {
|
|
280
|
+
info(C.dim(' 跳过(已有局域网复制): ') + rel);
|
|
281
|
+
}
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (!oldClick.test(html) || !html.includes(initAnchor)) {
|
|
285
|
+
info(C.dim(' 跳过(复制逻辑不是已知旧版本): ') + rel);
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
html = nextLabel.replace(initAnchor, LAN_ADDRESS_HELPER + '\n\n' + initAnchor);
|
|
290
|
+
html = html.replace(oldClick, LAN_ADDRESS_CLICK);
|
|
291
|
+
if (!html.includes('copyText(NAVIGATOR_ADDRESS')) {
|
|
292
|
+
html = html.replace(/^\s*const NAVIGATOR_ADDRESS = [^\n]+;\n/m, '');
|
|
293
|
+
}
|
|
294
|
+
fs.writeFileSync(shell, html);
|
|
295
|
+
ok('已迁移局域网复制功能 ' + rel);
|
|
296
|
+
patched++;
|
|
297
|
+
}
|
|
298
|
+
return patched;
|
|
299
|
+
}
|
|
300
|
+
|
|
164
301
|
/** 新项目 package.json 里本框架的依赖版本(已发布 npm,语义化版本管理) */
|
|
165
302
|
function kitDependencySpec() {
|
|
166
303
|
const pkg = readJson(path.join(PKG_ROOT, 'package.json'), {});
|
|
@@ -243,6 +380,7 @@ async function cmdInit() {
|
|
|
243
380
|
} else info(C.dim(' 跳过(已存在): ') + CONFIG_FILENAME);
|
|
244
381
|
|
|
245
382
|
patchShellOnboarding(root);
|
|
383
|
+
patchShellLanAddress(root);
|
|
246
384
|
|
|
247
385
|
// 合并 package.json 脚本(不覆盖用户已有脚本)
|
|
248
386
|
const pkgPath = path.join(root, 'package.json');
|
package/package.json
CHANGED
|
@@ -48,6 +48,7 @@
|
|
|
48
48
|
.agent-panel.is-collapsed .agent-resizer,
|
|
49
49
|
.agent-panel.is-collapsed .agent-header-main,
|
|
50
50
|
.agent-panel.is-collapsed .agent-new-chat,
|
|
51
|
+
.agent-panel.is-collapsed .agent-thread-bar,
|
|
51
52
|
.agent-panel.is-collapsed .agent-context,
|
|
52
53
|
.agent-panel.is-collapsed .agent-messages,
|
|
53
54
|
.agent-panel.is-collapsed .agent-composer {
|
|
@@ -138,6 +139,48 @@
|
|
|
138
139
|
writing-mode: vertical-rl;
|
|
139
140
|
}
|
|
140
141
|
|
|
142
|
+
.agent-thread-bar {
|
|
143
|
+
min-height: 38px;
|
|
144
|
+
flex: 0 0 auto;
|
|
145
|
+
display: flex;
|
|
146
|
+
align-items: center;
|
|
147
|
+
gap: 7px;
|
|
148
|
+
padding: 6px 12px;
|
|
149
|
+
border-bottom: 1px solid #edf0f5;
|
|
150
|
+
background: #fff;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
.agent-thread-label,
|
|
154
|
+
.agent-thread-count {
|
|
155
|
+
flex: 0 0 auto;
|
|
156
|
+
color: #7b8495;
|
|
157
|
+
font-size: 10px;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
.agent-thread-select {
|
|
161
|
+
min-width: 0;
|
|
162
|
+
height: 26px;
|
|
163
|
+
flex: 1;
|
|
164
|
+
padding: 0 24px 0 7px;
|
|
165
|
+
border: 1px solid #dfe5ee;
|
|
166
|
+
border-radius: 5px;
|
|
167
|
+
outline: 0;
|
|
168
|
+
background: #fafbfc;
|
|
169
|
+
color: #3f4754;
|
|
170
|
+
font: inherit;
|
|
171
|
+
font-size: 11px;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
.agent-thread-select:hover,
|
|
175
|
+
.agent-thread-select:focus {
|
|
176
|
+
border-color: #91caff;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
.agent-thread-select:disabled {
|
|
180
|
+
cursor: wait;
|
|
181
|
+
opacity: .65;
|
|
182
|
+
}
|
|
183
|
+
|
|
141
184
|
.agent-context {
|
|
142
185
|
flex: 0 0 auto;
|
|
143
186
|
padding: 10px 12px;
|
|
@@ -263,12 +306,8 @@
|
|
|
263
306
|
white-space: nowrap;
|
|
264
307
|
}
|
|
265
308
|
|
|
266
|
-
.agent-tool {
|
|
267
|
-
display: flex;
|
|
268
|
-
align-items: center;
|
|
269
|
-
gap: 7px;
|
|
309
|
+
.agent-tool-group {
|
|
270
310
|
margin-top: 5px;
|
|
271
|
-
padding: 5px 7px;
|
|
272
311
|
border: 1px solid #e4e9f0;
|
|
273
312
|
border-radius: 5px;
|
|
274
313
|
background: #fafbfc;
|
|
@@ -276,6 +315,56 @@
|
|
|
276
315
|
font-size: 10px;
|
|
277
316
|
}
|
|
278
317
|
|
|
318
|
+
.agent-tool-summary {
|
|
319
|
+
display: flex;
|
|
320
|
+
align-items: center;
|
|
321
|
+
gap: 7px;
|
|
322
|
+
min-height: 28px;
|
|
323
|
+
padding: 5px 7px;
|
|
324
|
+
cursor: pointer;
|
|
325
|
+
list-style: none;
|
|
326
|
+
user-select: none;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
.agent-tool-summary::-webkit-details-marker { display: none; }
|
|
330
|
+
.agent-tool-summary::marker { content: ""; }
|
|
331
|
+
|
|
332
|
+
.agent-tool-summary-label {
|
|
333
|
+
flex: 1;
|
|
334
|
+
min-width: 0;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
.agent-tool-summary-hint {
|
|
338
|
+
flex: 0 0 auto;
|
|
339
|
+
color: #8a94a5;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
.agent-tool-summary-hint::after {
|
|
343
|
+
content: "›";
|
|
344
|
+
display: inline-block;
|
|
345
|
+
margin-left: 4px;
|
|
346
|
+
transition: transform .15s ease;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
.agent-tool-group[open] .agent-tool-summary-hint::after {
|
|
350
|
+
transform: rotate(90deg);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
.agent-tool-list {
|
|
354
|
+
padding: 0 7px 7px 20px;
|
|
355
|
+
border-top: 1px solid #edf0f4;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
.agent-tool {
|
|
359
|
+
display: flex;
|
|
360
|
+
align-items: center;
|
|
361
|
+
gap: 7px;
|
|
362
|
+
padding: 5px 0;
|
|
363
|
+
color: #687386;
|
|
364
|
+
font-size: 10px;
|
|
365
|
+
overflow-wrap: anywhere;
|
|
366
|
+
}
|
|
367
|
+
|
|
279
368
|
.agent-tool-status {
|
|
280
369
|
width: 6px;
|
|
281
370
|
height: 6px;
|
|
@@ -287,6 +376,9 @@
|
|
|
287
376
|
.agent-tool.is-running .agent-tool-status { background: #1677ff; }
|
|
288
377
|
.agent-tool.is-complete .agent-tool-status { background: #18b54a; }
|
|
289
378
|
.agent-tool.is-error .agent-tool-status { background: #d91f2f; }
|
|
379
|
+
.agent-tool-summary.is-running .agent-tool-status { background: #1677ff; }
|
|
380
|
+
.agent-tool-summary.is-complete .agent-tool-status { background: #18b54a; }
|
|
381
|
+
.agent-tool-summary.is-error .agent-tool-status { background: #d91f2f; }
|
|
290
382
|
|
|
291
383
|
.agent-request-card,
|
|
292
384
|
.agent-diff-card {
|
|
@@ -2,16 +2,55 @@
|
|
|
2
2
|
const KIT = window.PROTO_KIT || {};
|
|
3
3
|
const NS = (KIT.productId || 'proto') + '-navigator';
|
|
4
4
|
const SESSION_KEY = NS + '-agent-session';
|
|
5
|
+
const THREADS_KEY = NS + '-agent-threads';
|
|
5
6
|
const WIDTH_KEY = NS + '-agent-width';
|
|
6
7
|
const COLLAPSED_KEY = NS + '-agent-collapsed';
|
|
7
8
|
const DEFAULT_WIDTH = 380;
|
|
8
9
|
const MIN_WIDTH = 320;
|
|
9
10
|
const MAX_WIDTH = 600;
|
|
10
11
|
const HISTORY_REFRESH_DELAY = 180;
|
|
12
|
+
const BACKGROUND_STATUS_DELAY = 1600;
|
|
11
13
|
const agentStorage = window['localStorage'];
|
|
12
14
|
|
|
15
|
+
function loadStoredThreads() {
|
|
16
|
+
let threads = [];
|
|
17
|
+
try {
|
|
18
|
+
const stored = JSON.parse(agentStorage.getItem(THREADS_KEY) || '[]');
|
|
19
|
+
if (Array.isArray(stored)) {
|
|
20
|
+
threads = stored.filter(item => item && item.id).map((item, index) => ({
|
|
21
|
+
id: String(item.id),
|
|
22
|
+
title: String(item.title || `对话 ${index + 1}`),
|
|
23
|
+
createdAt: Number(item.createdAt || Date.now()),
|
|
24
|
+
running: false,
|
|
25
|
+
unread: false,
|
|
26
|
+
taskContext: null
|
|
27
|
+
}));
|
|
28
|
+
}
|
|
29
|
+
} catch (err) {
|
|
30
|
+
threads = [];
|
|
31
|
+
}
|
|
32
|
+
const legacyId = agentStorage.getItem(SESSION_KEY) || '';
|
|
33
|
+
if (legacyId && !threads.some(item => item.id === legacyId)) {
|
|
34
|
+
threads.push({
|
|
35
|
+
id: legacyId,
|
|
36
|
+
title: `对话 ${threads.length + 1}`,
|
|
37
|
+
createdAt: Date.now(),
|
|
38
|
+
running: false,
|
|
39
|
+
unread: false,
|
|
40
|
+
taskContext: null
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return threads;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const storedThreads = loadStoredThreads();
|
|
47
|
+
const storedSessionId = agentStorage.getItem(SESSION_KEY) || '';
|
|
48
|
+
|
|
13
49
|
const state = {
|
|
14
|
-
sessionId:
|
|
50
|
+
sessionId: storedThreads.some(item => item.id === storedSessionId)
|
|
51
|
+
? storedSessionId
|
|
52
|
+
: (storedThreads[storedThreads.length - 1] || {}).id || '',
|
|
53
|
+
threads: storedThreads,
|
|
15
54
|
currentContext: { htmlPath: '', prdPath: '', title: '' },
|
|
16
55
|
taskContext: null,
|
|
17
56
|
eventSource: null,
|
|
@@ -23,8 +62,10 @@
|
|
|
23
62
|
statusText: '正在连接 OpenCode…',
|
|
24
63
|
refreshTimer: null,
|
|
25
64
|
statusPollTimer: null,
|
|
65
|
+
backgroundStatusTimer: null,
|
|
26
66
|
taskStartedAt: 0,
|
|
27
|
-
optimisticMessage: ''
|
|
67
|
+
optimisticMessage: '',
|
|
68
|
+
expandedToolGroups: new Set()
|
|
28
69
|
};
|
|
29
70
|
|
|
30
71
|
let refs = {};
|
|
@@ -56,6 +97,11 @@
|
|
|
56
97
|
' <button class="agent-header-btn agent-new-chat" id="agentNewChatBtn" type="button">新对话</button>',
|
|
57
98
|
' <button class="agent-header-btn agent-toggle" id="agentToggleBtn" type="button">收起</button>',
|
|
58
99
|
'</div>',
|
|
100
|
+
'<div class="agent-thread-bar">',
|
|
101
|
+
' <span class="agent-thread-label">对话</span>',
|
|
102
|
+
' <select class="agent-thread-select" id="agentThreadSelect" aria-label="切换 Agent 对话"></select>',
|
|
103
|
+
' <span class="agent-thread-count" id="agentThreadCount"></span>',
|
|
104
|
+
'</div>',
|
|
59
105
|
'<div class="agent-context">',
|
|
60
106
|
' <div class="agent-context-label">本条消息将携带</div>',
|
|
61
107
|
' <div class="agent-context-chip"><span class="agent-context-kind">页面</span><span class="agent-context-value" id="agentHtmlContext">请先从左侧选择页面</span></div>',
|
|
@@ -82,6 +128,8 @@
|
|
|
82
128
|
statusText: document.getElementById('agentStatusText'),
|
|
83
129
|
newChat: document.getElementById('agentNewChatBtn'),
|
|
84
130
|
toggle: document.getElementById('agentToggleBtn'),
|
|
131
|
+
threadSelect: document.getElementById('agentThreadSelect'),
|
|
132
|
+
threadCount: document.getElementById('agentThreadCount'),
|
|
85
133
|
htmlContext: document.getElementById('agentHtmlContext'),
|
|
86
134
|
prdContext: document.getElementById('agentPrdContext'),
|
|
87
135
|
quickAction: document.getElementById('agentPrdUpdateBtn'),
|
|
@@ -98,6 +146,106 @@
|
|
|
98
146
|
refs.statusText.textContent = text;
|
|
99
147
|
}
|
|
100
148
|
|
|
149
|
+
function currentThread() {
|
|
150
|
+
return state.threads.find(item => item.id === state.sessionId) || null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function persistThreads() {
|
|
154
|
+
const stored = state.threads.map(item => ({
|
|
155
|
+
id: item.id,
|
|
156
|
+
title: item.title,
|
|
157
|
+
createdAt: item.createdAt
|
|
158
|
+
}));
|
|
159
|
+
agentStorage.setItem(THREADS_KEY, JSON.stringify(stored));
|
|
160
|
+
if (state.sessionId) agentStorage.setItem(SESSION_KEY, state.sessionId);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function renderThreadSwitcher() {
|
|
164
|
+
if (!refs.threadSelect) return;
|
|
165
|
+
refs.threadSelect.replaceChildren();
|
|
166
|
+
state.threads.forEach((thread, index) => {
|
|
167
|
+
const option = document.createElement('option');
|
|
168
|
+
option.value = thread.id;
|
|
169
|
+
const status = thread.running ? ' · 处理中' : thread.unread ? ' · 已完成' : '';
|
|
170
|
+
option.textContent = `${thread.title || `对话 ${index + 1}`}${status}`;
|
|
171
|
+
refs.threadSelect.appendChild(option);
|
|
172
|
+
});
|
|
173
|
+
refs.threadSelect.value = state.sessionId;
|
|
174
|
+
refs.threadCount.textContent = state.threads.length ? `${state.threads.length} 个` : '';
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function detachActiveSession() {
|
|
178
|
+
clearTimeout(state.refreshTimer);
|
|
179
|
+
clearTimeout(state.statusPollTimer);
|
|
180
|
+
state.refreshTimer = null;
|
|
181
|
+
state.statusPollTimer = null;
|
|
182
|
+
if (state.eventSource) state.eventSource.close();
|
|
183
|
+
state.eventSource = null;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function activateThread(thread) {
|
|
187
|
+
state.sessionId = thread.id;
|
|
188
|
+
thread.unread = false;
|
|
189
|
+
state.taskContext = thread.taskContext || null;
|
|
190
|
+
state.messages = [];
|
|
191
|
+
state.pending = { permissions: [], questions: [] };
|
|
192
|
+
state.diff = [];
|
|
193
|
+
state.optimisticMessage = '';
|
|
194
|
+
state.expandedToolGroups.clear();
|
|
195
|
+
state.running = Boolean(thread.running);
|
|
196
|
+
state.taskStartedAt = state.running ? Date.now() : 0;
|
|
197
|
+
refs.stop.hidden = !state.running;
|
|
198
|
+
refs.send.hidden = state.running;
|
|
199
|
+
persistThreads();
|
|
200
|
+
renderThreadSwitcher();
|
|
201
|
+
renderMessages();
|
|
202
|
+
updateContextDisplay();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function nextThreadTitle() {
|
|
206
|
+
return `对话 ${state.threads.length + 1}`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function scheduleBackgroundStatusPoll() {
|
|
210
|
+
if (state.backgroundStatusTimer || !state.connected) return;
|
|
211
|
+
const hasBackgroundWork = state.threads.some(thread => thread.id !== state.sessionId && thread.running);
|
|
212
|
+
if (!hasBackgroundWork) return;
|
|
213
|
+
state.backgroundStatusTimer = setTimeout(async () => {
|
|
214
|
+
state.backgroundStatusTimer = null;
|
|
215
|
+
const activeId = state.sessionId;
|
|
216
|
+
const backgroundThreads = state.threads.filter(thread => thread.id !== activeId && thread.running);
|
|
217
|
+
await Promise.all(backgroundThreads.map(async thread => {
|
|
218
|
+
try {
|
|
219
|
+
const data = await api(`/api/agent/sessions/${thread.id}/status`);
|
|
220
|
+
if (thread.id !== state.sessionId && data.status && data.status.type === 'idle') {
|
|
221
|
+
thread.running = false;
|
|
222
|
+
thread.unread = true;
|
|
223
|
+
reloadTaskPreview(thread.taskContext);
|
|
224
|
+
}
|
|
225
|
+
} catch (err) {
|
|
226
|
+
// A background thread can be checked again after the next foreground action.
|
|
227
|
+
}
|
|
228
|
+
}));
|
|
229
|
+
persistThreads();
|
|
230
|
+
renderThreadSwitcher();
|
|
231
|
+
scheduleBackgroundStatusPoll();
|
|
232
|
+
}, BACKGROUND_STATUS_DELAY);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function restoreBackgroundThreadStatuses() {
|
|
236
|
+
const backgroundThreads = state.threads.filter(thread => thread.id !== state.sessionId);
|
|
237
|
+
await Promise.all(backgroundThreads.map(async thread => {
|
|
238
|
+
try {
|
|
239
|
+
const data = await api(`/api/agent/sessions/${thread.id}/status`);
|
|
240
|
+
thread.running = Boolean(data.status && data.status.type !== 'idle');
|
|
241
|
+
} catch (err) {
|
|
242
|
+
thread.running = false;
|
|
243
|
+
}
|
|
244
|
+
}));
|
|
245
|
+
renderThreadSwitcher();
|
|
246
|
+
scheduleBackgroundStatusPoll();
|
|
247
|
+
}
|
|
248
|
+
|
|
101
249
|
function applyPanelWidth(width, persist) {
|
|
102
250
|
const viewportLimit = Math.max(MIN_WIDTH, window.innerWidth - 290 - 560);
|
|
103
251
|
const nextWidth = Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, viewportLimit, Number(width) || DEFAULT_WIDTH));
|
|
@@ -170,7 +318,56 @@
|
|
|
170
318
|
return element;
|
|
171
319
|
}
|
|
172
320
|
|
|
173
|
-
function
|
|
321
|
+
function renderToolGroup(toolParts, groupKey) {
|
|
322
|
+
const details = document.createElement('details');
|
|
323
|
+
details.className = 'agent-tool-group';
|
|
324
|
+
details.open = state.expandedToolGroups.has(groupKey);
|
|
325
|
+
|
|
326
|
+
const statuses = toolParts.map(part => part.state && part.state.status ? part.state.status : 'pending');
|
|
327
|
+
const hasError = statuses.includes('error');
|
|
328
|
+
const isRunning = statuses.some(status => status !== 'completed' && status !== 'error');
|
|
329
|
+
const summary = document.createElement('summary');
|
|
330
|
+
summary.className = `agent-tool-summary is-${hasError ? 'error' : isRunning ? 'running' : 'complete'}`;
|
|
331
|
+
const summaryDot = document.createElement('span');
|
|
332
|
+
summaryDot.className = 'agent-tool-status';
|
|
333
|
+
summary.appendChild(summaryDot);
|
|
334
|
+
appendText(
|
|
335
|
+
summary,
|
|
336
|
+
'agent-tool-summary-label',
|
|
337
|
+
hasError ? `${toolParts.length} 个操作中有失败` : isRunning ? `正在执行 ${toolParts.length} 个操作…` : `已执行 ${toolParts.length} 个操作`
|
|
338
|
+
);
|
|
339
|
+
const hint = document.createElement('span');
|
|
340
|
+
hint.className = 'agent-tool-summary-hint';
|
|
341
|
+
hint.textContent = details.open ? '收起明细' : '查看明细';
|
|
342
|
+
summary.appendChild(hint);
|
|
343
|
+
details.appendChild(summary);
|
|
344
|
+
details.addEventListener('toggle', () => {
|
|
345
|
+
hint.textContent = details.open ? '收起明细' : '查看明细';
|
|
346
|
+
if (details.open) state.expandedToolGroups.add(groupKey);
|
|
347
|
+
else state.expandedToolGroups.delete(groupKey);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
const list = document.createElement('div');
|
|
351
|
+
list.className = 'agent-tool-list';
|
|
352
|
+
toolParts.forEach(part => {
|
|
353
|
+
const status = part.state && part.state.status ? part.state.status : 'pending';
|
|
354
|
+
const tool = document.createElement('div');
|
|
355
|
+
const statusClass = status === 'completed' ? 'complete' : status === 'error' ? 'error' : 'running';
|
|
356
|
+
tool.className = `agent-tool is-${statusClass}`;
|
|
357
|
+
const dot = document.createElement('span');
|
|
358
|
+
dot.className = 'agent-tool-status';
|
|
359
|
+
tool.appendChild(dot);
|
|
360
|
+
const fallbackTitle = part.tool === 'question'
|
|
361
|
+
? (status === 'completed' ? '已收到回答' : status === 'error' ? '提问失败' : '等待你的回答')
|
|
362
|
+
: (part.tool || '执行工具');
|
|
363
|
+
appendText(tool, '', (part.state && part.state.title) || fallbackTitle);
|
|
364
|
+
list.appendChild(tool);
|
|
365
|
+
});
|
|
366
|
+
details.appendChild(list);
|
|
367
|
+
return details;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function renderMessage(item, fallbackKey) {
|
|
174
371
|
const info = item.info || item;
|
|
175
372
|
const role = info.role || 'assistant';
|
|
176
373
|
const parts = Array.isArray(item.parts) ? item.parts : [];
|
|
@@ -192,20 +389,23 @@
|
|
|
192
389
|
}
|
|
193
390
|
if (parsed.text) appendText(wrapper, 'agent-message-body', parsed.text);
|
|
194
391
|
|
|
195
|
-
toolParts.
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
392
|
+
if (toolParts.length) {
|
|
393
|
+
const groupKey = String(info.id || item.id || fallbackKey || 'tool-group');
|
|
394
|
+
wrapper.appendChild(renderToolGroup(toolParts, groupKey));
|
|
395
|
+
}
|
|
396
|
+
return wrapper;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function renderToolMessageBatch(items, fallbackKey) {
|
|
400
|
+
const first = items[0] || {};
|
|
401
|
+
const firstInfo = first.info || first;
|
|
402
|
+
const toolParts = items.flatMap(item => (item.parts || []).filter(part => part.type === 'tool'));
|
|
403
|
+
if (!toolParts.length) return null;
|
|
404
|
+
const wrapper = document.createElement('div');
|
|
405
|
+
wrapper.className = 'agent-message is-assistant';
|
|
406
|
+
appendText(wrapper, 'agent-message-role', 'OpenCode');
|
|
407
|
+
const groupKey = String(firstInfo.id || first.id || fallbackKey || 'tool-batch');
|
|
408
|
+
wrapper.appendChild(renderToolGroup(toolParts, groupKey));
|
|
209
409
|
return wrapper;
|
|
210
410
|
}
|
|
211
411
|
|
|
@@ -325,10 +525,32 @@
|
|
|
325
525
|
const diffCard = renderDiff();
|
|
326
526
|
if (diffCard) refs.messages.appendChild(diffCard);
|
|
327
527
|
|
|
328
|
-
|
|
329
|
-
|
|
528
|
+
let toolBatch = [];
|
|
529
|
+
let toolBatchStart = 0;
|
|
530
|
+
const flushToolBatch = () => {
|
|
531
|
+
if (!toolBatch.length) return;
|
|
532
|
+
const message = renderToolMessageBatch(toolBatch, `tool-batch-${toolBatchStart}`);
|
|
533
|
+
if (message) refs.messages.appendChild(message);
|
|
534
|
+
toolBatch = [];
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
state.messages.forEach((item, index) => {
|
|
538
|
+
const info = item.info || item;
|
|
539
|
+
const parts = Array.isArray(item.parts) ? item.parts : [];
|
|
540
|
+
const hasText = parts.some(part => part.type === 'text' && part.text);
|
|
541
|
+
const hasTools = parts.some(part => part.type === 'tool');
|
|
542
|
+
const isAssistant = (info.role || 'assistant') === 'assistant';
|
|
543
|
+
if (isAssistant && !hasText && !hasTools) return;
|
|
544
|
+
if (isAssistant && !hasText && hasTools) {
|
|
545
|
+
if (!toolBatch.length) toolBatchStart = index;
|
|
546
|
+
toolBatch.push(item);
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
flushToolBatch();
|
|
550
|
+
const message = renderMessage(item, `message-${index}`);
|
|
330
551
|
if (message) refs.messages.appendChild(message);
|
|
331
552
|
});
|
|
553
|
+
flushToolBatch();
|
|
332
554
|
|
|
333
555
|
if (state.optimisticMessage) {
|
|
334
556
|
const message = renderMessage({
|
|
@@ -354,14 +576,18 @@
|
|
|
354
576
|
function setRunning(running) {
|
|
355
577
|
if (running && !state.running) state.taskStartedAt = Date.now();
|
|
356
578
|
state.running = running;
|
|
579
|
+
const thread = currentThread();
|
|
580
|
+
if (thread) thread.running = running;
|
|
357
581
|
refs.stop.hidden = !running;
|
|
358
582
|
refs.send.hidden = running;
|
|
359
|
-
refs.newChat.disabled = running;
|
|
360
583
|
if (running) {
|
|
361
584
|
setStatus('running', 'OpenCode 正在处理…');
|
|
362
585
|
scheduleStatusPoll();
|
|
586
|
+
scheduleBackgroundStatusPoll();
|
|
363
587
|
}
|
|
364
588
|
else if (state.connected) setStatus('ready', state.statusText.includes('失败') ? state.statusText : 'OpenCode 已连接');
|
|
589
|
+
persistThreads();
|
|
590
|
+
renderThreadSwitcher();
|
|
365
591
|
updateContextDisplay();
|
|
366
592
|
}
|
|
367
593
|
|
|
@@ -437,11 +663,12 @@
|
|
|
437
663
|
}
|
|
438
664
|
}
|
|
439
665
|
|
|
440
|
-
function reloadTaskPreview() {
|
|
441
|
-
|
|
666
|
+
function reloadTaskPreview(taskContext) {
|
|
667
|
+
const context = taskContext || state.taskContext;
|
|
668
|
+
if (!context || state.currentContext.htmlPath !== context.htmlPath) return;
|
|
442
669
|
const frame = document.getElementById('previewFrame');
|
|
443
670
|
if (!frame) return;
|
|
444
|
-
const baseUrl =
|
|
671
|
+
const baseUrl = context.htmlPath;
|
|
445
672
|
frame.src = baseUrl + (baseUrl.includes('?') ? '&' : '?') + `_agentReload=${Date.now()}`;
|
|
446
673
|
}
|
|
447
674
|
|
|
@@ -490,19 +717,56 @@
|
|
|
490
717
|
}
|
|
491
718
|
|
|
492
719
|
async function createSession() {
|
|
720
|
+
const threadTitle = nextThreadTitle();
|
|
493
721
|
const data = await api('/api/agent/sessions', {
|
|
494
722
|
method: 'POST',
|
|
495
723
|
headers: { 'Content-Type': 'application/json' },
|
|
496
|
-
body: JSON.stringify({ title:
|
|
724
|
+
body: JSON.stringify({ title: `${KIT.productTitle || '原型'} · ${threadTitle}` })
|
|
497
725
|
});
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
726
|
+
detachActiveSession();
|
|
727
|
+
const thread = {
|
|
728
|
+
id: data.session.id,
|
|
729
|
+
title: threadTitle,
|
|
730
|
+
createdAt: Date.now(),
|
|
731
|
+
running: false,
|
|
732
|
+
unread: false,
|
|
733
|
+
taskContext: null
|
|
734
|
+
};
|
|
735
|
+
state.threads.push(thread);
|
|
736
|
+
activateThread(thread);
|
|
504
737
|
connectEvents();
|
|
505
|
-
|
|
738
|
+
setStatus('ready', '已开始新对话');
|
|
739
|
+
scheduleBackgroundStatusPoll();
|
|
740
|
+
return thread;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
async function switchSession(sessionId) {
|
|
744
|
+
const thread = state.threads.find(item => item.id === sessionId);
|
|
745
|
+
if (!thread || thread.id === state.sessionId) return;
|
|
746
|
+
refs.threadSelect.disabled = true;
|
|
747
|
+
detachActiveSession();
|
|
748
|
+
activateThread(thread);
|
|
749
|
+
setStatus(thread.running ? 'running' : 'ready', thread.running ? '正在恢复任务状态…' : '正在载入对话…');
|
|
750
|
+
try {
|
|
751
|
+
const restored = await refreshHistory();
|
|
752
|
+
if (!restored) {
|
|
753
|
+
state.threads = state.threads.filter(item => item.id !== thread.id);
|
|
754
|
+
persistThreads();
|
|
755
|
+
await createSession();
|
|
756
|
+
setStatus('ready', '原对话已失效,已新建对话');
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
connectEvents();
|
|
760
|
+
const data = await api(`/api/agent/sessions/${state.sessionId}/status`);
|
|
761
|
+
setRunning(data.status && data.status.type !== 'idle');
|
|
762
|
+
await Promise.all([refreshPending(), refreshDiff()]);
|
|
763
|
+
} catch (err) {
|
|
764
|
+
setStatus('error', `切换对话失败:${err.message}`);
|
|
765
|
+
} finally {
|
|
766
|
+
refs.threadSelect.disabled = false;
|
|
767
|
+
renderThreadSwitcher();
|
|
768
|
+
scheduleBackgroundStatusPoll();
|
|
769
|
+
}
|
|
506
770
|
}
|
|
507
771
|
|
|
508
772
|
async function ensureSession() {
|
|
@@ -512,12 +776,15 @@
|
|
|
512
776
|
}
|
|
513
777
|
const restored = await refreshHistory();
|
|
514
778
|
if (!restored) {
|
|
779
|
+
state.threads = state.threads.filter(item => item.id !== state.sessionId);
|
|
780
|
+
persistThreads();
|
|
515
781
|
await createSession();
|
|
516
782
|
return;
|
|
517
783
|
}
|
|
518
784
|
connectEvents();
|
|
519
785
|
const data = await api(`/api/agent/sessions/${state.sessionId}/status`);
|
|
520
786
|
setRunning(data.status && data.status.type !== 'idle');
|
|
787
|
+
scheduleBackgroundStatusPoll();
|
|
521
788
|
}
|
|
522
789
|
|
|
523
790
|
async function sendMessage(message) {
|
|
@@ -526,6 +793,16 @@
|
|
|
526
793
|
try {
|
|
527
794
|
if (!state.sessionId) await createSession();
|
|
528
795
|
state.taskContext = { ...state.currentContext };
|
|
796
|
+
const thread = currentThread();
|
|
797
|
+
if (thread) {
|
|
798
|
+
thread.taskContext = { ...state.taskContext };
|
|
799
|
+
if (/^对话 \d+$/.test(thread.title)) {
|
|
800
|
+
const conciseTitle = text.replace(/\s+/g, ' ').slice(0, 18);
|
|
801
|
+
if (conciseTitle) thread.title = conciseTitle;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
persistThreads();
|
|
805
|
+
renderThreadSwitcher();
|
|
529
806
|
state.optimisticMessage = [
|
|
530
807
|
'[导航器上下文]',
|
|
531
808
|
`页面:${state.taskContext.htmlPath}`,
|
|
@@ -597,13 +874,16 @@
|
|
|
597
874
|
setCollapsed(!refs.panel.classList.contains('is-collapsed'), true);
|
|
598
875
|
});
|
|
599
876
|
refs.newChat.addEventListener('click', async () => {
|
|
877
|
+
refs.newChat.disabled = true;
|
|
600
878
|
try {
|
|
601
879
|
await createSession();
|
|
602
|
-
setStatus('ready', '已开始新对话');
|
|
603
880
|
} catch (err) {
|
|
604
881
|
setStatus('error', `新建对话失败:${err.message}`);
|
|
882
|
+
} finally {
|
|
883
|
+
refs.newChat.disabled = false;
|
|
605
884
|
}
|
|
606
885
|
});
|
|
886
|
+
refs.threadSelect.addEventListener('change', () => switchSession(refs.threadSelect.value));
|
|
607
887
|
refs.send.addEventListener('click', () => sendMessage(refs.input.value));
|
|
608
888
|
refs.stop.addEventListener('click', abortTask);
|
|
609
889
|
refs.quickAction.addEventListener('click', () => sendMessage('请只根据当前 PRD 中所有红色标记的内容更新当前 HTML/JS 原型及必要的 mock/constants;不要修改 PRD 本身,也不要处理未标红的历史内容。'));
|
|
@@ -646,6 +926,7 @@
|
|
|
646
926
|
bindEvents();
|
|
647
927
|
applyPanelWidth(agentStorage.getItem(WIDTH_KEY) || DEFAULT_WIDTH, false);
|
|
648
928
|
setCollapsed(agentStorage.getItem(COLLAPSED_KEY) === '1', false);
|
|
929
|
+
renderThreadSwitcher();
|
|
649
930
|
renderMessages();
|
|
650
931
|
updateContextDisplay();
|
|
651
932
|
|
|
@@ -655,6 +936,7 @@
|
|
|
655
936
|
setStatus('ready', `OpenCode ${status.version} · ${status.model}`);
|
|
656
937
|
updateContextDisplay();
|
|
657
938
|
await ensureSession();
|
|
939
|
+
await restoreBackgroundThreadStatuses();
|
|
658
940
|
await refreshPending();
|
|
659
941
|
} catch (err) {
|
|
660
942
|
state.connected = false;
|