@bolloon/bolloon-agent 0.1.35 → 0.1.36
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/.playwright-mcp/page-2026-06-16T07-51-45-706Z.yml +130 -0
- package/.playwright-mcp/page-2026-06-16T07-56-44-116Z.yml +131 -0
- package/Bolloon.md +45 -4
- package/Dive-into/CITATION.cff +17 -0
- package/Dive-into/LICENSE +25 -0
- package/Dive-into/README.md +598 -0
- package/Dive-into/README_zh.md +599 -0
- package/Dive-into/assets/context.png +0 -0
- package/Dive-into/assets/extensibility.png +0 -0
- package/Dive-into/assets/iteration.png +0 -0
- package/Dive-into/assets/layered_architecture.png +0 -0
- package/Dive-into/assets/main_structure.png +0 -0
- package/Dive-into/assets/permission.png +0 -0
- package/Dive-into/assets/session_compact.png +0 -0
- package/Dive-into/assets/subagent.png +0 -0
- package/Dive-into/paper/Dive_into_Claude_Code.pdf +0 -0
- package/README.md +1 -1
- package/dist/agents/p2p-chat-tools.js +6 -6
- package/dist/agents/permission-mode.js +115 -0
- package/dist/agents/pi-sdk.js +435 -25
- package/dist/agents/pre-tool-validator.js +194 -0
- package/dist/agents/workflow-pivot-loop.js +113 -12
- package/dist/bollharness/src/scripts/checks/check_doc_freshness.js +1 -1
- package/dist/bollharness/src/scripts/checks/check_doc_links.js +1 -1
- package/dist/bollharness/src/scripts/context_router.js +1 -1
- package/dist/bollharness/src/scripts/deploy-guard.js +1 -1
- package/dist/bollharness/src/scripts/guard_router.js +1 -1
- package/dist/bollharness/src/scripts/hooks/_hook_output.js +1 -1
- package/dist/bollharness/src/scripts/hooks/risk-tracker.js +1 -1
- package/dist/bollharness-integration/context-router.js +2 -2
- package/dist/bollharness-integration/guard-checker.js +1 -1
- package/dist/bootstrap/bootstrap.js +3 -0
- package/dist/bootstrap/context-collector.js +17 -1
- package/dist/bootstrap/context-hierarchy.js +218 -0
- package/dist/bootstrap/lifecycle-hooks.js +86 -24
- package/dist/bootstrap/project-context.js +10 -3
- package/dist/context-compaction/auto-compact.js +144 -0
- package/dist/context-compaction/budget-gate.js +28 -0
- package/dist/context-compaction/budget-reduce.js +35 -0
- package/dist/context-compaction/context-collapse.js +66 -0
- package/dist/context-compaction/index.js +21 -0
- package/dist/context-compaction/microcompact.js +51 -0
- package/dist/context-compaction/pipeline.js +123 -0
- package/dist/context-compaction/snip.js +45 -0
- package/dist/context-compaction/token-estimator.js +35 -0
- package/dist/context-compaction/types.js +19 -0
- package/dist/heartbeat/HealthMonitor.js +3 -2
- package/dist/index.js +38 -2
- package/dist/llm/llm-judgment-client.js +32 -30
- package/dist/llm/pi-ai.js +103 -16
- package/dist/llm/system-prompt/health.js +129 -0
- package/dist/llm/system-prompt/registry.js +246 -0
- package/dist/llm/system-prompt/strip-hibsml.js +51 -0
- package/dist/llm/tool-manifest/ask_user_input.js +35 -0
- package/dist/llm/tool-manifest/bash.js +23 -0
- package/dist/llm/tool-manifest/create_file.js +24 -0
- package/dist/llm/tool-manifest/fetch_sports_data.js +26 -0
- package/dist/llm/tool-manifest/image_search.js +24 -0
- package/dist/llm/tool-manifest/index.js +69 -0
- package/dist/llm/tool-manifest/mcp.js +43 -0
- package/dist/llm/tool-manifest/message_compose.js +31 -0
- package/dist/llm/tool-manifest/places.js +83 -0
- package/dist/llm/tool-manifest/present_files.js +21 -0
- package/dist/llm/tool-manifest/recipe.js +40 -0
- package/dist/llm/tool-manifest/recommend_apps.js +23 -0
- package/dist/llm/tool-manifest/str_replace.js +27 -0
- package/dist/llm/tool-manifest/types.js +7 -0
- package/dist/llm/tool-manifest/view.js +24 -0
- package/dist/llm/tool-manifest/weather.js +27 -0
- package/dist/llm/tool-manifest/web.js +51 -0
- package/dist/network/p2p-direct.js +23 -0
- package/dist/network/source-intent-broadcaster.js +203 -0
- package/dist/network/source-intent.js +100 -0
- package/dist/pi-ecosystem-judgment/adaptive-scan.js +48 -0
- package/dist/pi-ecosystem-judgment/injection-gate.js +54 -12
- package/dist/pi-ecosystem-judgment/value-injection.js +8 -2
- package/dist/security/context-router-tool.js +1 -1
- package/dist/security/input-scanner.js +223 -0
- package/dist/web/client.js +3677 -4161
- package/dist/web/components/p2p/P2PModal.js +188 -0
- package/dist/web/components/p2p/index.js +264 -226
- package/dist/web/components/p2p/p2p-modal.js +657 -0
- package/dist/web/components/p2p/p2p-tools.js +248 -0
- package/dist/web/index.html +58 -67
- package/dist/web/server.js +299 -117
- package/dist/web/style.css +531 -249
- package/dist/web/ui/message-renderer.js +463 -0
- package/dist/web/ui/step-timeline.js +375 -0
- package/lefthook.yml +4 -0
- package/package.json +1 -1
- package/scripts/auto-evolve-loop.ts +105 -0
- package/scripts/build-web.ts +35 -1
- package/scripts/validate-system-prompt.ts +142 -0
- package/src/agents/p2p-chat-tools.ts +6 -6
- package/src/agents/permission-mode.ts +127 -0
- package/src/agents/pi-sdk.ts +461 -28
- package/src/agents/pre-tool-validator.ts +213 -0
- package/src/agents/workflow-pivot-loop.ts +110 -19
- package/src/bollharness/CLAUDE.md +1 -1
- package/src/bollharness/README.md +2 -2
- package/src/bollharness/README.zh-CN.md +2 -2
- package/src/bollharness/reference/boll-reference/scripts/hooks/find-boll-root.sh +2 -2
- package/src/bollharness/scripts/context-fragments/truth-source-hierarchy.md +2 -2
- package/src/bollharness/scripts/context-fragments/version-sources.md +1 -1
- package/src/bollharness/scripts/hooks/find-project-root.sh +4 -4
- package/src/bollharness/src/scripts/checks/check_doc_freshness.ts +1 -1
- package/src/bollharness/src/scripts/checks/check_doc_links.ts +1 -1
- package/src/bollharness/src/scripts/context_router.ts +1 -1
- package/src/bollharness/src/scripts/deploy-guard.ts +1 -1
- package/src/bollharness/src/scripts/guard_router.ts +1 -1
- package/src/bollharness/src/scripts/hooks/_hook_output.ts +1 -1
- package/src/bollharness/src/scripts/hooks/risk-tracker.ts +1 -1
- package/src/bollharness/templates/scaffold/.gitignore.append +1 -1
- package/src/bollharness/templates/scaffold/CLAUDE.md +2 -2
- package/src/bollharness-integration/context-router.ts +2 -2
- package/src/bollharness-integration/guard-checker.ts +1 -1
- package/src/bootstrap/bootstrap.ts +3 -0
- package/src/bootstrap/context-collector.ts +30 -1
- package/src/bootstrap/context-hierarchy.ts +283 -0
- package/src/bootstrap/lifecycle-hooks.ts +139 -26
- package/src/bootstrap/project-context.ts +11 -3
- package/src/context-compaction/auto-compact.ts +153 -0
- package/src/context-compaction/budget-gate.ts +32 -0
- package/src/context-compaction/budget-reduce.ts +37 -0
- package/src/context-compaction/context-collapse.ts +72 -0
- package/src/context-compaction/index.ts +24 -0
- package/src/context-compaction/microcompact.ts +54 -0
- package/src/context-compaction/pipeline.ts +133 -0
- package/src/context-compaction/snip.ts +51 -0
- package/src/context-compaction/token-estimator.ts +36 -0
- package/src/context-compaction/types.ts +99 -0
- package/src/heartbeat/HealthMonitor.ts +3 -2
- package/src/index.ts +36 -2
- package/src/llm/llm-judgment-client.ts +36 -35
- package/src/llm/pi-ai.ts +111 -16
- package/src/llm/system-prompt/health.ts +159 -0
- package/src/llm/system-prompt/layers/channel/local.md +14 -0
- package/src/llm/system-prompt/layers/channel/p2p-agent.md +18 -0
- package/src/llm/system-prompt/layers/channel/p2p-visitor.md +19 -0
- package/src/llm/system-prompt/layers/core/artifacts_storage.md +89 -0
- package/src/llm/system-prompt/layers/core/evenhandedness.md +21 -0
- package/src/llm/system-prompt/layers/core/hibs_reminders.md +15 -0
- package/src/llm/system-prompt/layers/core/identity.md +37 -0
- package/src/llm/system-prompt/layers/core/knowledge.md +17 -0
- package/src/llm/system-prompt/layers/core/memory_system.md +12 -0
- package/src/llm/system-prompt/layers/core/network_filesystem.md +28 -0
- package/src/llm/system-prompt/layers/core/refusal.md +37 -0
- package/src/llm/system-prompt/layers/core/tone.md +31 -0
- package/src/llm/system-prompt/layers/core/tools.thin.md +13 -0
- package/src/llm/system-prompt/layers/core/wellbeing.md +41 -0
- package/src/llm/system-prompt/layers/role/architect.md +20 -0
- package/src/llm/system-prompt/layers/role/expert.md +19 -0
- package/src/llm/system-prompt/layers/role/implementer.md +15 -0
- package/src/llm/system-prompt/layers/role/security.md +15 -0
- package/src/llm/system-prompt/layers/tool/artifacts.md +72 -0
- package/src/llm/system-prompt/layers/tool/bash.md +25 -0
- package/src/llm/system-prompt/layers/tool/hibs_api.md +171 -0
- package/src/llm/system-prompt/layers/tool/image_search.md +70 -0
- package/src/llm/system-prompt/layers/tool/manifest.md +89 -0
- package/src/llm/system-prompt/layers/tool/mcp_apps.md +53 -0
- package/src/llm/system-prompt/layers/tool/web_search.md +83 -0
- package/src/llm/system-prompt/registry.ts +325 -0
- package/src/llm/system-prompt/strip-hibsml.ts +52 -0
- package/src/llm/tool-manifest/ask_user_input.ts +37 -0
- package/src/llm/tool-manifest/bash.ts +25 -0
- package/src/llm/tool-manifest/create_file.ts +26 -0
- package/src/llm/tool-manifest/fetch_sports_data.ts +28 -0
- package/src/llm/tool-manifest/image_search.ts +26 -0
- package/src/llm/tool-manifest/index.ts +88 -0
- package/src/llm/tool-manifest/mcp.ts +46 -0
- package/src/llm/tool-manifest/message_compose.ts +33 -0
- package/src/llm/tool-manifest/places.ts +86 -0
- package/src/llm/tool-manifest/present_files.ts +23 -0
- package/src/llm/tool-manifest/recipe.ts +42 -0
- package/src/llm/tool-manifest/recommend_apps.ts +25 -0
- package/src/llm/tool-manifest/str_replace.ts +29 -0
- package/src/llm/tool-manifest/types.ts +52 -0
- package/src/llm/tool-manifest/view.ts +26 -0
- package/src/llm/tool-manifest/weather.ts +29 -0
- package/src/llm/tool-manifest/web.ts +54 -0
- package/src/network/p2p-direct.ts +22 -0
- package/src/network/source-intent-broadcaster.ts +242 -0
- package/src/network/source-intent.ts +167 -0
- package/src/security/context-router-tool.ts +1 -1
- package/src/security/input-scanner.ts +287 -0
- package/src/web/client.js +271 -2817
- package/src/web/client.ts +4326 -0
- package/src/web/index.html +58 -67
- package/src/web/server.ts +301 -141
- package/src/web/style.css +531 -249
- package/src/web/ui/message-renderer.ts +540 -0
- package/src/web/ui/step-timeline.ts +394 -0
- package/test-results/.last-run.json +6 -0
- package/test-results/src-test-web-loop-status-b-5734c-atus-bar-/346/230/276/347/244/272-spinner-/344/270/215/346/230/276/347/244/272/345/276/252/347/216/257/350/256/241/346/225/260/error-context.md +285 -0
package/src/web/client.js
CHANGED
|
@@ -4,6 +4,8 @@ if (typeof marked === 'undefined') {
|
|
|
4
4
|
}
|
|
5
5
|
|
|
6
6
|
const messagesEl = document.getElementById('messages');
|
|
7
|
+
const agentStatusEl = document.getElementById('agent-status');
|
|
8
|
+
const agentStatusTextEl = document.getElementById('agent-status-text');
|
|
7
9
|
const input = document.getElementById('input');
|
|
8
10
|
const sendBtn = document.getElementById('send');
|
|
9
11
|
const sidebar = document.getElementById('sidebar');
|
|
@@ -21,68 +23,11 @@ let eventSources = new Map(); // channelId -> EventSource
|
|
|
21
23
|
let currentChannelId = null;
|
|
22
24
|
let currentAgentId = '';
|
|
23
25
|
let channels = [];
|
|
24
|
-
let remoteChannels = []; // v3: 远端 channel UI 元数据 (按 peer 分组)
|
|
25
26
|
let isSidebarCollapsed = false;
|
|
26
27
|
let reconnectAttempts = new Map(); // channelId -> attempts
|
|
27
28
|
let reconnectTimers = new Map(); // channelId -> timer
|
|
28
29
|
let heartbeatTimers = new Map(); // channelId -> setInterval handle (防止泄漏)
|
|
29
30
|
let lastUserCommand = ''; // 防止用户消息重复显示
|
|
30
|
-
|
|
31
|
-
// 2026-06-10: P2P peer-group 折叠状态持久化 (跨刷新)
|
|
32
|
-
// key = bolloon.p2p.collapsedPeers, value = JSON array of publicKey hex
|
|
33
|
-
const COLLAPSED_PEERS_KEY = 'bolloon.p2p.collapsedPeers';
|
|
34
|
-
const SEEN_PEERS_KEY = 'bolloon.p2p.seenPeers';
|
|
35
|
-
let collapsedPeers = (function loadCollapsed() {
|
|
36
|
-
try {
|
|
37
|
-
const raw = localStorage.getItem(COLLAPSED_PEERS_KEY);
|
|
38
|
-
return new Set(raw ? JSON.parse(raw) : []);
|
|
39
|
-
} catch { return new Set(); }
|
|
40
|
-
})();
|
|
41
|
-
let seenPeers = (function loadSeen() {
|
|
42
|
-
try {
|
|
43
|
-
const raw = localStorage.getItem(SEEN_PEERS_KEY);
|
|
44
|
-
return new Set(raw ? JSON.parse(raw) : []);
|
|
45
|
-
} catch { return new Set(); }
|
|
46
|
-
})();
|
|
47
|
-
function saveCollapsedPeers() {
|
|
48
|
-
try { localStorage.setItem(COLLAPSED_PEERS_KEY, JSON.stringify([...collapsedPeers])); } catch {}
|
|
49
|
-
}
|
|
50
|
-
function saveSeenPeers() {
|
|
51
|
-
try { localStorage.setItem(SEEN_PEERS_KEY, JSON.stringify([...seenPeers])); } catch {}
|
|
52
|
-
}
|
|
53
|
-
function togglePeerCollapsed(peerPk) {
|
|
54
|
-
if (collapsedPeers.has(peerPk)) {
|
|
55
|
-
collapsedPeers.delete(peerPk);
|
|
56
|
-
} else {
|
|
57
|
-
collapsedPeers.add(peerPk);
|
|
58
|
-
}
|
|
59
|
-
saveCollapsedPeers();
|
|
60
|
-
renderRemoteChannels();
|
|
61
|
-
// 2026-06-10: 通知 header 切换按钮同步图标
|
|
62
|
-
if (typeof window.__syncP2PToggleAllBtn === 'function') window.__syncP2PToggleAllBtn();
|
|
63
|
-
}
|
|
64
|
-
// 2026-06-10: 一键展开/折叠所有 P2P peer (header 按钮调用)
|
|
65
|
-
function expandAllPeers() {
|
|
66
|
-
// 从 remoteChannels + knownPeers 收集所有 publicKey
|
|
67
|
-
const allPks = new Set([
|
|
68
|
-
...knownPeers.map(p => p.publicKey),
|
|
69
|
-
...remoteChannels.map(g => g.peerId)
|
|
70
|
-
]);
|
|
71
|
-
for (const pk of allPks) collapsedPeers.delete(pk);
|
|
72
|
-
saveCollapsedPeers();
|
|
73
|
-
renderRemoteChannels();
|
|
74
|
-
if (typeof window.__syncP2PToggleAllBtn === 'function') window.__syncP2PToggleAllBtn();
|
|
75
|
-
}
|
|
76
|
-
function collapseAllPeers() {
|
|
77
|
-
const allPks = new Set([
|
|
78
|
-
...knownPeers.map(p => p.publicKey),
|
|
79
|
-
...remoteChannels.map(g => g.peerId)
|
|
80
|
-
]);
|
|
81
|
-
for (const pk of allPks) collapsedPeers.add(pk);
|
|
82
|
-
saveCollapsedPeers();
|
|
83
|
-
renderRemoteChannels();
|
|
84
|
-
if (typeof window.__syncP2PToggleAllBtn === 'function') window.__syncP2PToggleAllBtn();
|
|
85
|
-
}
|
|
86
31
|
let lastAiContent = ''; // 防止 AI 消息重复显示
|
|
87
32
|
let messagesContainers = new Map(); // channelId -> messages container div
|
|
88
33
|
let sessionMessages = new Map(); // channelId:sessionId -> messages array
|
|
@@ -154,155 +99,12 @@ async function loadChannels() {
|
|
|
154
99
|
channels.forEach((ch, i) => {
|
|
155
100
|
console.log(` [${i}] ${ch.name} - did: "${ch.did}"`);
|
|
156
101
|
});
|
|
157
|
-
// 2026-06-11: 全部默认不展开 (用户需要手动点 caret 展开 session 列表)
|
|
158
|
-
// 之前默认展开第一个会喧宾夺主, 用户看不到完整 channel 列表
|
|
159
102
|
renderChannels();
|
|
160
103
|
} catch (err) {
|
|
161
104
|
console.error('[加载频道] 失败:', err);
|
|
162
105
|
}
|
|
163
106
|
}
|
|
164
107
|
|
|
165
|
-
// v3: 全局 SSE 监听 (p2p-global channel) - 接收远端 chat.reply 等事件
|
|
166
|
-
let v3GlobalEventSource = null;
|
|
167
|
-
function startV3GlobalSSE() {
|
|
168
|
-
if (v3GlobalEventSource) return;
|
|
169
|
-
try {
|
|
170
|
-
v3GlobalEventSource = new EventSource('/events?channelId=p2p-global');
|
|
171
|
-
v3GlobalEventSource.onmessage = (e) => {
|
|
172
|
-
try {
|
|
173
|
-
const msg = JSON.parse(e.data);
|
|
174
|
-
if (msg.type === 'remote-chat-reply') {
|
|
175
|
-
// 2026-06-10: 复用本地 addMessage 渲染 — 自动 marked + 剥 think/env + 主题样式
|
|
176
|
-
// 之前是 textContent 硬编码灰底, 跟 Step 3 重写的 modal 风格不一致,
|
|
177
|
-
// 而且 SSE 异步回到时 modal 可能已被切到 thinking 占满, 用户看不到 reply.
|
|
178
|
-
const log = document.getElementById('rcm-log');
|
|
179
|
-
const thinkingEl = document.getElementById('rcm-thinking');
|
|
180
|
-
if (thinkingEl) thinkingEl.style.display = 'none'; // 思考结束, 隐藏
|
|
181
|
-
// 也清掉 "对方正在思考..." 行 (流式 token 留下的)
|
|
182
|
-
const liveThinking = document.getElementById('rcm-thinking-live');
|
|
183
|
-
if (liveThinking) liveThinking.remove();
|
|
184
|
-
if (log) {
|
|
185
|
-
if (msg.error) {
|
|
186
|
-
// 错误用 sysmsg 样式 (跟 modal 风格一致)
|
|
187
|
-
const errEl = document.createElement('div');
|
|
188
|
-
errEl.className = 'remote-chat-sysmsg remote-chat-sysmsg-error';
|
|
189
|
-
errEl.textContent = `❌ 对方回复出错: ${msg.error}`;
|
|
190
|
-
log.appendChild(errEl);
|
|
191
|
-
} else {
|
|
192
|
-
// 走本地 addMessage, 跟主聊天框完全一致 (marked + think/env 折叠 + 主题色)
|
|
193
|
-
const prefix = `🤖 远端 AI 回复\n\n`;
|
|
194
|
-
addMessage(prefix + (msg.text || '(空回复)'), 'ai', false, log);
|
|
195
|
-
}
|
|
196
|
-
log.scrollTop = log.scrollHeight;
|
|
197
|
-
} else {
|
|
198
|
-
// modal 没开 → 用右下 toast 提示用户"对方回了, 打开聊天看"
|
|
199
|
-
if (typeof showSimpleToast === 'function') {
|
|
200
|
-
const preview = (msg.text || '').slice(0, 50);
|
|
201
|
-
showSimpleToast(`💬 远端 channel 有新回复: ${preview}${msg.text && msg.text.length > 50 ? '…' : ''}`);
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
} else if (msg.type === 'remote-chat-thinking') {
|
|
205
|
-
// v3 新增: B 端实时显示 A 节点的思考过程
|
|
206
|
-
const phase = msg.phase;
|
|
207
|
-
const log = document.getElementById('rcm-log');
|
|
208
|
-
if (!log) return;
|
|
209
|
-
|
|
210
|
-
if (phase === 'start') {
|
|
211
|
-
// 头部插入"判断力依据"区块 (只第一次)
|
|
212
|
-
const judgments = msg.usedJudgments || { bound: [], candidates: [] };
|
|
213
|
-
const judgmentBlock = document.createElement('div');
|
|
214
|
-
judgmentBlock.className = 'rcm-judgment-block';
|
|
215
|
-
judgmentBlock.style.cssText = 'margin:6px 0;padding:8px 10px;background:#fef3c7;border-left:3px solid #f59e0b;border-radius:4px;font-size:12px;';
|
|
216
|
-
let jh = '<div style="font-weight:600;color:#92400e;margin-bottom:4px;">🛡️ 对方使用的判断力 (来自 ta 的 channel)</div>';
|
|
217
|
-
if (judgments.bound && judgments.bound.length > 0) {
|
|
218
|
-
jh += '<div style="color:#78350f;margin-bottom:4px;"><b>硬绑定</b> (必须遵循):</div>';
|
|
219
|
-
for (const j of judgments.bound) {
|
|
220
|
-
jh += `<div style="margin:2px 0;padding-left:8px;">• <b>${escapeHtml((j.decision || '').slice(0, 80))}</b>${j.reasons && j.reasons.length ? '<br><span style="color:#92400e;font-size:11px;">理由: ' + escapeHtml(j.reasons.join('; ').slice(0, 80)) + '</span>' : ''}</div>`;
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
if (judgments.candidates && judgments.candidates.length > 0) {
|
|
224
|
-
jh += `<div style="color:#78350f;margin-top:4px;"><b>候选池</b> (${judgments.candidates.length} 条, LLM 自选)</div>`;
|
|
225
|
-
}
|
|
226
|
-
log.appendChild(judgmentBlock);
|
|
227
|
-
// "思考中" 区块
|
|
228
|
-
const thinkingEl = document.createElement('div');
|
|
229
|
-
thinkingEl.id = 'rcm-thinking-live';
|
|
230
|
-
thinkingEl.style.cssText = 'margin:6px 0;padding:8px 10px;background:#ede9fe;border-left:3px solid #8b5cf6;border-radius:4px;font-size:12px;color:#5b21b6;font-style:italic;';
|
|
231
|
-
thinkingEl.textContent = '💭 对方正在思考...';
|
|
232
|
-
log.appendChild(thinkingEl);
|
|
233
|
-
log.scrollTop = log.scrollHeight;
|
|
234
|
-
} else if (phase === 'token') {
|
|
235
|
-
// 实时更新思考中的 partial
|
|
236
|
-
const thinkingEl = document.getElementById('rcm-thinking-live');
|
|
237
|
-
if (thinkingEl) {
|
|
238
|
-
thinkingEl.textContent = '💭 对方正在思考: ' + (msg.partial || '').slice(-200);
|
|
239
|
-
log.scrollTop = log.scrollHeight;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
} else if (msg.type === 'cross-mention-received') {
|
|
243
|
-
// v3 新增: A 节点上, 某个 channel 的 LLM @-mention 了另一个 channel, SSE 推过来
|
|
244
|
-
// 在所有打开的 chat modal 上显示"AI 跨渠道 @-mention" 提示
|
|
245
|
-
const allModals = document.querySelectorAll('.rcm-mention-toast, [id^="rcm-log"]');
|
|
246
|
-
for (const log of allModals) {
|
|
247
|
-
if (!log.id) continue;
|
|
248
|
-
const toast = document.createElement('div');
|
|
249
|
-
toast.style.cssText = 'margin:6px 0;padding:8px 10px;background:#fce7f3;border-left:3px solid #ec4899;border-radius:4px;font-size:12px;color:#831843;';
|
|
250
|
-
const fromTxt = msg.source === 'ai-mention-remote' ? `远端节点 ${(msg.fromPublicKey || '').substring(0, 8)}… 的 ${msg.originChannelName}` : `${msg.originChannelName} (本地)`;
|
|
251
|
-
toast.innerHTML = `📡 <b>${fromTxt}</b> @-mention → 当前 channel: <i>${escapeHtml((msg.text || '').slice(0, 100))}</i>${msg.text && msg.text.length > 100 ? '…' : ''}`;
|
|
252
|
-
log.appendChild(toast);
|
|
253
|
-
log.scrollTop = log.scrollHeight;
|
|
254
|
-
}
|
|
255
|
-
} else if (msg.type === 'remote-channel-update') {
|
|
256
|
-
// v3 新增: 远端节点发来新分享 / 删除 / 改名, 立即更新本地 cache
|
|
257
|
-
const peerId = msg.peerId;
|
|
258
|
-
const channels = msg.channels || [];
|
|
259
|
-
const peerName = msg.peerName || null; // 2026-06-10: 同步接收对方名字
|
|
260
|
-
let group = remoteChannels.find(g => g.peerId === peerId);
|
|
261
|
-
if (!group) {
|
|
262
|
-
group = { peerId, channels: [], peerName: peerName || ('peer-' + peerId.substring(0, 8)) };
|
|
263
|
-
remoteChannels.push(group);
|
|
264
|
-
} else if (peerName) {
|
|
265
|
-
group.peerName = peerName; // 更新名字
|
|
266
|
-
}
|
|
267
|
-
group.channels = channels;
|
|
268
|
-
// 2026-06-10: 如果对面告知名字, 同步刷新 knownPeers 列表, 避免陌生 peer 状态
|
|
269
|
-
if (peerName && !knownPeers.find(p => p.publicKey === peerId)) {
|
|
270
|
-
knownPeers.push({
|
|
271
|
-
publicKey: peerId,
|
|
272
|
-
name: peerName,
|
|
273
|
-
addedAt: new Date().toISOString(),
|
|
274
|
-
lastConnectedAt: new Date().toISOString(),
|
|
275
|
-
});
|
|
276
|
-
console.log(`[v3] 远端 ${peerId.substring(0,12)}... 自报名字 = ${peerName}, 已加到 knownPeers`);
|
|
277
|
-
}
|
|
278
|
-
renderRemoteChannels();
|
|
279
|
-
console.log(`[v3] 收到远端 ${peerId.substring(0,12)}... 的 ${channels.length} 个 channel 更新 (name=${peerName || '?'})`);
|
|
280
|
-
} else if (msg.type === 'friend-request') {
|
|
281
|
-
// v3 新增: 收到好友申请
|
|
282
|
-
showFriendRequestModal(msg);
|
|
283
|
-
} else if (msg.type === 'friend-request-ack') {
|
|
284
|
-
// 2026-06-10: 收到对方 ack, 给发送方提示"已送达"
|
|
285
|
-
const pending = window.__pendingFriendRequests;
|
|
286
|
-
if (pending && msg.requestId && pending.has(msg.requestId)) {
|
|
287
|
-
const { name } = pending.get(msg.requestId);
|
|
288
|
-
pending.delete(msg.requestId);
|
|
289
|
-
console.log(`[v3-friend] ✅ ack 收到: ${name} 已收到好友申请`);
|
|
290
|
-
// 简短 toast (右下角), 不阻塞
|
|
291
|
-
showSimpleToast(`📬 ${name} 已收到你的好友申请, 等对方接受`);
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
} catch (err) {
|
|
295
|
-
console.error('[v3] 全局 SSE 解析失败:', err);
|
|
296
|
-
}
|
|
297
|
-
};
|
|
298
|
-
v3GlobalEventSource.onerror = (e) => {
|
|
299
|
-
console.warn('[v3] 全局 SSE 错误');
|
|
300
|
-
};
|
|
301
|
-
} catch (err) {
|
|
302
|
-
console.error('[v3] 启动全局 SSE 失败:', err);
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
|
|
306
108
|
async function createChannel(name) {
|
|
307
109
|
if (!name.trim()) return;
|
|
308
110
|
try {
|
|
@@ -597,50 +399,6 @@ function toggleAgentExpand(channelId, e) {
|
|
|
597
399
|
renderChannels();
|
|
598
400
|
}
|
|
599
401
|
|
|
600
|
-
/**
|
|
601
|
-
* 2026-06-11 性能优化: 切 channel 时用轻量 patch, 不重建整个 sidebar 列表
|
|
602
|
-
* 只更新: (1) active class (2) 当前 session label + count (3) expanded 状态
|
|
603
|
-
* 避免每次切 channel 都 innerHTML='' + 重建 ~10 个 channel 节点
|
|
604
|
-
*/
|
|
605
|
-
function renderChannelsLite(activeChannelId, activeSessionId) {
|
|
606
|
-
if (!channelList) return;
|
|
607
|
-
// 1. 更新所有 .agent-row 的 active class
|
|
608
|
-
channelList.querySelectorAll('.agent-row').forEach(row => {
|
|
609
|
-
const li = row.closest('.agent-group');
|
|
610
|
-
const chId = li?.dataset.channelId;
|
|
611
|
-
row.classList.toggle('active', chId === activeChannelId);
|
|
612
|
-
});
|
|
613
|
-
// 2. 当前 channel 的展开状态: 强制展开, 其他不动
|
|
614
|
-
if (activeChannelId) expandedAgents.add(activeChannelId);
|
|
615
|
-
// 3. 当前 channel 行展开 + 只切 session-item 的 active class (不再 innerHTML 重渲!)
|
|
616
|
-
// 原因: 重渲 innerHTML 会清掉原始 renderChannels 绑的 session-item click handler,
|
|
617
|
-
// 即使补绑也会因为 lite HTML 结构 (.session-dot + .session-msg-count) 跟原始不同
|
|
618
|
-
// 导致"第 1 次点不动 (原始), 第 2 次点才能用 (lite)" 现象
|
|
619
|
-
// 修法: 完全不动 session-list DOM, 只 toggle .active
|
|
620
|
-
const activeLi = channelList.querySelector(`.agent-group[data-channel-id="${activeChannelId}"]`);
|
|
621
|
-
if (activeLi) {
|
|
622
|
-
activeLi.classList.add('expanded');
|
|
623
|
-
// 只切 active class, 不动 innerHTML (避免清掉原始 click handler)
|
|
624
|
-
const ch = channels.find(c => c.id === activeChannelId);
|
|
625
|
-
// 2026-06-11: 原始 renderChannels 已经给 session-item 加了 data-session-id (line 791),
|
|
626
|
-
// 这里先清空所有 .active 再设新的, 避免多个 active 共存 (因为 renderChannels 初始 DOM
|
|
627
|
-
// 上会有一个 active 标记旧 session, 新切 session 容易出现两个 active)
|
|
628
|
-
activeLi.querySelectorAll('.session-item').forEach(sessLi => {
|
|
629
|
-
const sessId = sessLi.dataset.sessionId;
|
|
630
|
-
const shouldBeActive = sessId === activeSessionId;
|
|
631
|
-
sessLi.classList.toggle('active', shouldBeActive);
|
|
632
|
-
});
|
|
633
|
-
// 更新顶部 current session label
|
|
634
|
-
if (ch) {
|
|
635
|
-
const currentSess = Array.isArray(ch.sessions) ? ch.sessions.find(s => s.id === activeSessionId) : null;
|
|
636
|
-
const labelEl = activeLi.querySelector('.agent-current-session');
|
|
637
|
-
if (labelEl) {
|
|
638
|
-
labelEl.textContent = currentSess ? '· ' + formatSessionName(currentSess) : '';
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
|
|
644
402
|
function renderChannels() {
|
|
645
403
|
if (!channelList) return;
|
|
646
404
|
channelList.innerHTML = '';
|
|
@@ -684,9 +442,12 @@ function renderChannels() {
|
|
|
684
442
|
const currentSessLabel = currentSess ? formatSessionName(currentSess) : '';
|
|
685
443
|
const sessionCount = Array.isArray(ch.sessions) ? ch.sessions.length : 0;
|
|
686
444
|
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
445
|
+
const walletBadge = ch.walletAddress
|
|
446
|
+
? `<span class="agent-wallet-badge" title="已绑定钱包: ${escapeHtml(ch.walletAddress)}">⛓</span>`
|
|
447
|
+
: '';
|
|
448
|
+
const toolsBadge = ch.autoInvokeTools
|
|
449
|
+
? `<span class="agent-tools-badge" title="自动工具调用已开启">⚡</span>`
|
|
450
|
+
: '';
|
|
690
451
|
|
|
691
452
|
row.innerHTML = `
|
|
692
453
|
<svg class="agent-caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
@@ -770,7 +531,6 @@ function renderChannels() {
|
|
|
770
531
|
const sessLi = document.createElement('li');
|
|
771
532
|
const isActive = ch.id === currentChannelId && sess.id === ch.currentSessionId;
|
|
772
533
|
sessLi.className = `session-item ${isActive ? 'active' : ''}`;
|
|
773
|
-
sessLi.dataset.sessionId = sess.id; // 2026-06-11: 给 session-item 加上 data-session-id, renderChannelsLite 才能 toggle active class
|
|
774
534
|
sessLi.innerHTML = `
|
|
775
535
|
<span class="session-name" title="${escapeHtml(formatSessionName(sess))}">${escapeHtml(formatSessionName(sess))}</span>
|
|
776
536
|
<button class="session-delete" title="删除会话">×</button>
|
|
@@ -863,11 +623,6 @@ async function selectChannel(channelId, targetSessionId = null) {
|
|
|
863
623
|
currentChannelId = channelId;
|
|
864
624
|
reconnectAttempts.set(channelId, 0);
|
|
865
625
|
|
|
866
|
-
// v3: 盾牌弹窗打开时, 切 channel 要刷列表 (tab 标题 + 已绑/未绑 分组)
|
|
867
|
-
if (typeof judgmentsModal !== 'undefined' && judgmentsModal && judgmentsModal.classList.contains('active')) {
|
|
868
|
-
if (typeof lastJudgmentsCache !== 'undefined') renderJudgments(lastJudgmentsCache);
|
|
869
|
-
}
|
|
870
|
-
|
|
871
626
|
// 找到当前频道和 session
|
|
872
627
|
const channel = channels.find(c => c.id === channelId);
|
|
873
628
|
if (channel) {
|
|
@@ -881,11 +636,7 @@ async function selectChannel(channelId, targetSessionId = null) {
|
|
|
881
636
|
console.log('[selectChannel] 频道:', channel.name, 'session:', currentSessionId);
|
|
882
637
|
}
|
|
883
638
|
|
|
884
|
-
|
|
885
|
-
// renderChannels() 仍然要调 (current session label 等可能变了), 但加一层判断: 如果只是切 channel (没增删), 走 patch 路径
|
|
886
|
-
const t0 = performance.now();
|
|
887
|
-
renderChannelsLite(channelId, currentSessionId);
|
|
888
|
-
console.log(`[selectChannel] renderChannelsLite 耗时 ${(performance.now() - t0).toFixed(1)}ms`);
|
|
639
|
+
renderChannels();
|
|
889
640
|
|
|
890
641
|
// 确保该频道有消息容器
|
|
891
642
|
const container = ensureMessageContainer(channelId);
|
|
@@ -904,19 +655,10 @@ async function selectChannel(channelId, targetSessionId = null) {
|
|
|
904
655
|
try {
|
|
905
656
|
const res = await fetch(`/sessions/${channelId}?sessionId=${encodeURIComponent(currentSessionId)}`);
|
|
906
657
|
const session = await res.json();
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
const tmpContainer = document.createElement('div');
|
|
912
|
-
tmpContainer.style.display = 'none';
|
|
913
|
-
for (const msg of msgs) {
|
|
914
|
-
addMessage(msg.content, msg.type, false, tmpContainer, msg.metadata?.usedJudgmentIds || []);
|
|
915
|
-
}
|
|
916
|
-
while (tmpContainer.firstChild) {
|
|
917
|
-
frag.appendChild(tmpContainer.firstChild);
|
|
918
|
-
}
|
|
919
|
-
container.appendChild(frag);
|
|
658
|
+
if (session.messages && session.messages.length > 0) {
|
|
659
|
+
session.messages.forEach(msg => {
|
|
660
|
+
addMessage(msg.content, msg.type, false, container);
|
|
661
|
+
});
|
|
920
662
|
} else {
|
|
921
663
|
addMessage('你好!我是 Bolloon Agent。有什么我可以帮你的吗?', 'ai', false, container);
|
|
922
664
|
}
|
|
@@ -936,7 +678,7 @@ async function loadSession(channelId, sessionId = null) {
|
|
|
936
678
|
container.innerHTML = '';
|
|
937
679
|
if (session.messages && session.messages.length > 0) {
|
|
938
680
|
session.messages.forEach(msg => {
|
|
939
|
-
addMessage(msg.content, msg.type, false, container
|
|
681
|
+
addMessage(msg.content, msg.type, false, container);
|
|
940
682
|
});
|
|
941
683
|
} else {
|
|
942
684
|
addMessage('你好!我是 Bolloon Agent。有什么我可以帮你的吗?', 'ai', false, container);
|
|
@@ -948,7 +690,7 @@ async function loadSession(channelId, sessionId = null) {
|
|
|
948
690
|
}
|
|
949
691
|
}
|
|
950
692
|
|
|
951
|
-
function addMessage(content, type, save = true, container
|
|
693
|
+
function addMessage(content, type, save = true, container) {
|
|
952
694
|
const msgContainer = container || messagesContainers.get(currentChannelId) || messagesEl;
|
|
953
695
|
|
|
954
696
|
// 浏览器侧内存保护: 单个 channel 的消息容器超过 MAX_MESSAGES_PER_CHANNEL
|
|
@@ -979,6 +721,12 @@ function addMessage(content, type, save = true, container, usedJudgmentIds = [])
|
|
|
979
721
|
const div = document.createElement('div');
|
|
980
722
|
div.className = `message message-${type}`;
|
|
981
723
|
|
|
724
|
+
// 清理工具结果容器(当新的 AI 消息到达时)
|
|
725
|
+
if (type === 'ai' && toolResultContainer) {
|
|
726
|
+
toolResultContainer.remove();
|
|
727
|
+
toolResultContainer = null;
|
|
728
|
+
}
|
|
729
|
+
|
|
982
730
|
// 清理内容:移除 tool call 标记和其他不应该显示的内容
|
|
983
731
|
let cleanContent = content
|
|
984
732
|
.replace(/\[TOOL_CALL\][\s\S]*?\[\/TOOL_CALL\]/g, '')
|
|
@@ -1161,221 +909,203 @@ function addMessage(content, type, save = true, container, usedJudgmentIds = [])
|
|
|
1161
909
|
};
|
|
1162
910
|
|
|
1163
911
|
actionsDiv.appendChild(copyBtn);
|
|
1164
|
-
|
|
1165
|
-
// "存为判断" 按钮: AI 蒸馏 (30-80 字) + 自动演化对齐
|
|
1166
|
-
const saveJudgmentBtn = document.createElement('button');
|
|
1167
|
-
saveJudgmentBtn.className = 'action-btn save-as-judgment';
|
|
1168
|
-
saveJudgmentBtn.title = 'AI 蒸馏为 30-80 字判断力 + 自动演化对齐';
|
|
1169
|
-
saveJudgmentBtn.setAttribute('data-decision', rawContent.substring(0, 800));
|
|
1170
|
-
if (currentChannelId) saveJudgmentBtn.setAttribute('data-channel-id', currentChannelId);
|
|
1171
|
-
saveJudgmentBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L4 6v6c0 5 3.5 9.5 8 10 4.5-.5 8-5 8-10V6l-8-4z"></path><path d="M9 12l2 2 4-4"></path></svg> 蒸馏为判断`;
|
|
1172
|
-
actionsDiv.appendChild(saveJudgmentBtn);
|
|
1173
|
-
if (type === 'ai') {
|
|
1174
|
-
actionsDiv.appendChild(regenerateBtn);
|
|
1175
|
-
}
|
|
912
|
+
actionsDiv.appendChild(regenerateBtn);
|
|
1176
913
|
div.appendChild(actionsDiv);
|
|
1177
914
|
}
|
|
1178
915
|
|
|
1179
|
-
// P0.5: 反向引用链接 (AI 消息) — 极简, 点击跳判断力 modal
|
|
1180
|
-
if (type === 'ai' && Array.isArray(usedJudgmentIds) && usedJudgmentIds.length > 0) {
|
|
1181
|
-
const link = document.createElement('a');
|
|
1182
|
-
link.className = 'used-judgments-link';
|
|
1183
|
-
link.style.cssText = 'display:inline-block;margin-top:4px;font-size:11px;color:#0369a1;text-decoration:underline;cursor:pointer;';
|
|
1184
|
-
link.textContent = `📎 参考 ${usedJudgmentIds.length} 条原则`;
|
|
1185
|
-
link.onclick = (e) => {
|
|
1186
|
-
e.preventDefault();
|
|
1187
|
-
openJudgmentsModalWithFilter(usedJudgmentIds);
|
|
1188
|
-
};
|
|
1189
|
-
div.appendChild(link);
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
916
|
div.appendChild(time);
|
|
1193
917
|
msgContainer.appendChild(div);
|
|
1194
918
|
|
|
1195
919
|
msgContainer.scrollTop = msgContainer.scrollHeight;
|
|
1196
920
|
}
|
|
1197
921
|
|
|
1198
|
-
//
|
|
1199
|
-
//
|
|
1200
|
-
//
|
|
1201
|
-
|
|
1202
|
-
let
|
|
1203
|
-
let timelineRowsEl = null;
|
|
1204
|
-
let currentTokenRow = null;
|
|
1205
|
-
let currentTokenText = '';
|
|
1206
|
-
let lastUsedJudgmentIds = []; // 用于 finalizeTimelineAsMessage 给 addMessage 第 5 参
|
|
1207
|
-
|
|
1208
|
-
const PHASE_TEXT = {
|
|
1209
|
-
gate_compute: '正在检索相关判断力...',
|
|
1210
|
-
gate_done: '已注入 {usedCount} 条原则',
|
|
1211
|
-
d_detect: 'D 触发: 监测对话...',
|
|
1212
|
-
d_distill: 'D 触发: 蒸馏判断力...',
|
|
1213
|
-
d_done: 'D 触发: 已入库',
|
|
1214
|
-
d_skip: 'D 触发: 跳过',
|
|
1215
|
-
d_error: 'D 触发: 错误',
|
|
1216
|
-
};
|
|
922
|
+
// Agent status bar — sits between the message list and the input box.
|
|
923
|
+
// Two visual states: "planning" (spinner) and "executing" (glowing icon).
|
|
924
|
+
// The text alternates to convey the action loop.
|
|
925
|
+
let agentStatusState = null; // 'planning' | 'executing' | null
|
|
926
|
+
let agentStatusTextIdx = 0;
|
|
1217
927
|
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
const abortBtn = document.getElementById('loop-abort-btn');
|
|
1223
|
-
if (abortBtn) abortBtn.addEventListener('click', abortCurrentRun);
|
|
1224
|
-
}
|
|
928
|
+
const AGENT_STATUS_TEXTS = {
|
|
929
|
+
planning: ['正在计划下一步行动', '正在规划任务路径', '正在分析当前状态'],
|
|
930
|
+
executing: ['正在执行下一步行动', '正在执行任务', '正在调用工具'],
|
|
931
|
+
};
|
|
1225
932
|
|
|
1226
|
-
function
|
|
1227
|
-
if (
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
933
|
+
function setAgentStatus(state) {
|
|
934
|
+
if (!agentStatusEl || !agentStatusTextEl) return;
|
|
935
|
+
if (state === null) {
|
|
936
|
+
agentStatusEl.hidden = true;
|
|
937
|
+
agentStatusEl.removeAttribute('data-mode');
|
|
938
|
+
agentStatusState = null;
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
agentStatusEl.hidden = false;
|
|
942
|
+
agentStatusEl.setAttribute('data-mode', state);
|
|
943
|
+
agentStatusState = state;
|
|
944
|
+
// 重排一下文本, 避免长时间停留过于单调
|
|
945
|
+
agentStatusTextIdx = (agentStatusTextIdx + 1) % AGENT_STATUS_TEXTS[state].length;
|
|
946
|
+
agentStatusTextEl.textContent = AGENT_STATUS_TEXTS[state][agentStatusTextIdx];
|
|
1233
947
|
}
|
|
1234
948
|
|
|
1235
|
-
function
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
949
|
+
function showTyping(container) {
|
|
950
|
+
hideTyping();
|
|
951
|
+
// 兼容旧路径: container 参数保留但不再使用, status bar 是全局唯一的
|
|
952
|
+
void container;
|
|
953
|
+
setAgentStatus('planning');
|
|
1239
954
|
}
|
|
1240
955
|
|
|
1241
|
-
function
|
|
1242
|
-
|
|
956
|
+
function hideTyping() {
|
|
957
|
+
setAgentStatus(null);
|
|
958
|
+
// 兜底: 旧版本的 #typing 元素可能还残留在 DOM 里, 顺手清掉
|
|
959
|
+
const old = document.getElementById('typing');
|
|
960
|
+
if (old) old.remove();
|
|
961
|
+
hideStreaming();
|
|
1243
962
|
}
|
|
1244
963
|
|
|
1245
|
-
|
|
1246
|
-
if (timelinePanelEl) timelinePanelEl.scrollTop = timelinePanelEl.scrollHeight;
|
|
1247
|
-
}
|
|
964
|
+
let streamingMessageEl = null;
|
|
1248
965
|
|
|
1249
|
-
function
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
966
|
+
function showStreaming(container) {
|
|
967
|
+
const msgContainer = container || messagesContainers.get(currentChannelId) || messagesEl;
|
|
968
|
+
hideStreaming();
|
|
969
|
+
streamingMessageEl = document.createElement('div');
|
|
970
|
+
streamingMessageEl.className = 'message message-ai';
|
|
971
|
+
streamingMessageEl.id = 'streaming';
|
|
972
|
+
const bubble = document.createElement('div');
|
|
973
|
+
bubble.className = 'bubble bubble-ai streaming-content';
|
|
974
|
+
streamingMessageEl.appendChild(bubble);
|
|
975
|
+
msgContainer.appendChild(streamingMessageEl);
|
|
976
|
+
msgContainer.scrollTop = msgContainer.scrollHeight;
|
|
1258
977
|
}
|
|
1259
978
|
|
|
1260
|
-
function
|
|
1261
|
-
if (
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
currentTokenRow.className = 'loop-row loop-row-token';
|
|
1265
|
-
currentTokenRow.style.cssText = 'padding:2px 0 2px 16px;color:#1f2937;white-space:pre-wrap;word-break:break-word;';
|
|
1266
|
-
currentTokenText = '';
|
|
1267
|
-
timelineRowsEl.appendChild(currentTokenRow);
|
|
979
|
+
function hideStreaming() {
|
|
980
|
+
if (streamingMessageEl) {
|
|
981
|
+
streamingMessageEl.remove();
|
|
982
|
+
streamingMessageEl = null;
|
|
1268
983
|
}
|
|
1269
|
-
currentTokenText += delta;
|
|
1270
|
-
currentTokenRow.textContent = currentTokenText;
|
|
1271
|
-
scrollTimelineToBottom();
|
|
1272
984
|
}
|
|
1273
985
|
|
|
1274
|
-
function
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
row.innerHTML = `<span style="color:#6b7280;">${icon}</span> ${escapeHtml(toolName)} <span class="toggle" style="color:#6b7280;">▸</span>`;
|
|
1282
|
-
row.addEventListener('click', () => {
|
|
1283
|
-
const detail = row.nextElementSibling;
|
|
1284
|
-
if (detail && detail.classList.contains('loop-row-tool-detail')) {
|
|
1285
|
-
const isHidden = detail.style.display === 'none';
|
|
1286
|
-
detail.style.display = isHidden ? 'block' : 'none';
|
|
1287
|
-
const tg = row.querySelector('.toggle');
|
|
1288
|
-
if (tg) tg.textContent = isHidden ? '▾' : '▸';
|
|
986
|
+
function updateStreamingContent(content, container) {
|
|
987
|
+
const msgContainer = container || messagesContainers.get(currentChannelId) || messagesEl;
|
|
988
|
+
if (streamingMessageEl) {
|
|
989
|
+
const bubble = streamingMessageEl.querySelector('.streaming-content');
|
|
990
|
+
if (bubble) {
|
|
991
|
+
bubble.textContent = content;
|
|
992
|
+
msgContainer.scrollTop = msgContainer.scrollHeight;
|
|
1289
993
|
}
|
|
1290
|
-
}
|
|
1291
|
-
timelineRowsEl.appendChild(row);
|
|
1292
|
-
return row;
|
|
1293
|
-
}
|
|
1294
|
-
|
|
1295
|
-
function appendToolDetail(row, content) {
|
|
1296
|
-
if (!row || !timelineRowsEl) return;
|
|
1297
|
-
const detail = document.createElement('div');
|
|
1298
|
-
detail.className = 'loop-row loop-row-tool-detail';
|
|
1299
|
-
detail.style.cssText = 'padding:4px 0 6px 24px;color:#4b5563;font-size:11px;white-space:pre-wrap;word-break:break-word;background:#f3f4f6;border-radius:3px;margin-bottom:4px;';
|
|
1300
|
-
detail.textContent = content;
|
|
1301
|
-
detail.style.display = 'none';
|
|
1302
|
-
timelineRowsEl.insertBefore(detail, row.nextSibling);
|
|
1303
|
-
scrollTimelineToBottom();
|
|
994
|
+
}
|
|
1304
995
|
}
|
|
1305
996
|
|
|
1306
|
-
function
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
997
|
+
function handleStreamEvent(data, container) {
|
|
998
|
+
const msgContainer = container || messagesContainers.get(currentChannelId) || messagesEl;
|
|
999
|
+
// 始终确保有工作流显示区域
|
|
1000
|
+
if (!workflowDisplayEl) {
|
|
1001
|
+
workflowDisplayEl = createWorkflowDisplay();
|
|
1002
|
+
msgContainer.appendChild(workflowDisplayEl);
|
|
1311
1003
|
}
|
|
1312
|
-
return null;
|
|
1313
|
-
}
|
|
1314
1004
|
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
if (
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
if (data.detail && (data.phase === 'd_done' || data.phase === 'd_skip' || data.phase === 'd_error')) {
|
|
1323
|
-
text = `${text} — ${data.detail}`;
|
|
1005
|
+
if (data.streamType === 'thinking') {
|
|
1006
|
+
showStreaming(msgContainer);
|
|
1007
|
+
updateStreamingContent(data.content || '思考中...', msgContainer);
|
|
1008
|
+
} else if (data.streamType === 'token') {
|
|
1009
|
+
showStreaming(msgContainer);
|
|
1010
|
+
const current = streamingMessageEl?.querySelector('.streaming-content')?.textContent || '';
|
|
1011
|
+
updateStreamingContent(current + data.content, msgContainer);
|
|
1324
1012
|
}
|
|
1325
|
-
const status = data.phase.endsWith('_done') || data.phase === 'd_skip' ? 'done'
|
|
1326
|
-
: data.phase === 'd_error' ? 'error' : 'pending';
|
|
1327
|
-
appendPhaseRow(text, status);
|
|
1328
1013
|
}
|
|
1329
1014
|
|
|
1330
|
-
function
|
|
1331
|
-
|
|
1015
|
+
function handleStatusEvent(data, container) {
|
|
1016
|
+
const msgContainer = container || messagesContainers.get(currentChannelId) || messagesEl;
|
|
1017
|
+
// 检查是否是工具调用结果
|
|
1332
1018
|
const content = data.content || '';
|
|
1333
1019
|
const isJsonResult = content.startsWith('{') && content.includes('"success"');
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
// 把 output 挂到上一个同工具的 pending 行
|
|
1339
|
-
pending.dataset.status = 'done';
|
|
1340
|
-
const iconEl = pending.firstElementChild;
|
|
1341
|
-
if (iconEl) iconEl.textContent = '✓';
|
|
1342
|
-
const tg = pending.querySelector('.toggle');
|
|
1343
|
-
if (tg) tg.textContent = '▸';
|
|
1344
|
-
appendToolDetail(pending, content);
|
|
1345
|
-
} else {
|
|
1346
|
-
const status = isJsonResult ? 'done' : 'pending';
|
|
1347
|
-
const row = appendToolRow(data.tool, status);
|
|
1348
|
-
if (isJsonResult) appendToolDetail(row, content);
|
|
1349
|
-
}
|
|
1350
|
-
scrollTimelineToBottom();
|
|
1020
|
+
|
|
1021
|
+
if (isJsonResult) {
|
|
1022
|
+
// 工具结果:折叠显示
|
|
1023
|
+
showToolResult(data.tool, content, msgContainer);
|
|
1351
1024
|
} else {
|
|
1352
|
-
//
|
|
1353
|
-
|
|
1354
|
-
const
|
|
1355
|
-
|
|
1025
|
+
// 普通状态:流式显示
|
|
1026
|
+
showStreaming(msgContainer);
|
|
1027
|
+
const icon = data.tool ? `🔧 ${data.tool}: ` : '';
|
|
1028
|
+
updateStreamingContent(icon + data.content, msgContainer);
|
|
1356
1029
|
}
|
|
1357
1030
|
}
|
|
1358
1031
|
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1032
|
+
// 显示工具调用结果(折叠)
|
|
1033
|
+
let toolResultContainer = null;
|
|
1034
|
+
|
|
1035
|
+
function showToolResult(toolName, resultJson, container) {
|
|
1036
|
+
const msgContainer = container || messagesContainers.get(currentChannelId) || messagesEl;
|
|
1037
|
+
// 清理之前的流式显示
|
|
1038
|
+
hideStreaming();
|
|
1039
|
+
|
|
1040
|
+
// 获取或创建工具结果容器
|
|
1041
|
+
if (!toolResultContainer) {
|
|
1042
|
+
toolResultContainer = document.createElement('div');
|
|
1043
|
+
toolResultContainer.className = 'tool-results-container';
|
|
1044
|
+
msgContainer.appendChild(toolResultContainer);
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// 尝试解析并格式化 JSON
|
|
1048
|
+
let formattedResult = resultJson;
|
|
1049
|
+
try {
|
|
1050
|
+
const parsed = JSON.parse(resultJson);
|
|
1051
|
+
formattedResult = formatToolResult(parsed);
|
|
1052
|
+
} catch {}
|
|
1053
|
+
|
|
1054
|
+
// 创建折叠项
|
|
1055
|
+
const resultEl = document.createElement('div');
|
|
1056
|
+
resultEl.className = 'tool-result-item collapsed';
|
|
1057
|
+
|
|
1058
|
+
const toolDisplayName = toolName || '工具结果';
|
|
1059
|
+
const headerEl = document.createElement('div');
|
|
1060
|
+
headerEl.className = 'tool-result-header';
|
|
1061
|
+
headerEl.innerHTML = `
|
|
1062
|
+
<span class="tool-result-icon">🔧</span>
|
|
1063
|
+
<span class="tool-result-name">${toolDisplayName}</span>
|
|
1064
|
+
<span class="tool-result-toggle">▸</span>
|
|
1065
|
+
`;
|
|
1066
|
+
// 绑定事件处理器(避免内联 onclick)
|
|
1067
|
+
headerEl.addEventListener('click', () => {
|
|
1068
|
+
resultEl.classList.toggle('collapsed');
|
|
1069
|
+
resultEl.classList.toggle('expanded');
|
|
1070
|
+
});
|
|
1364
1071
|
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1072
|
+
const contentEl = document.createElement('div');
|
|
1073
|
+
contentEl.className = 'tool-result-content';
|
|
1074
|
+
contentEl.innerHTML = `<pre>${formattedResult}</pre>`;
|
|
1075
|
+
|
|
1076
|
+
resultEl.appendChild(headerEl);
|
|
1077
|
+
resultEl.appendChild(contentEl);
|
|
1078
|
+
toolResultContainer.appendChild(resultEl);
|
|
1079
|
+
msgContainer.scrollTop = msgContainer.scrollHeight;
|
|
1371
1080
|
}
|
|
1372
1081
|
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1082
|
+
// 格式化工具结果为易读格式
|
|
1083
|
+
function formatToolResult(obj, indent = 0) {
|
|
1084
|
+
const spaces = ' '.repeat(indent);
|
|
1085
|
+
|
|
1086
|
+
if (obj === null || obj === undefined) {
|
|
1087
|
+
return 'null';
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
if (typeof obj === 'object') {
|
|
1091
|
+
if (Array.isArray(obj)) {
|
|
1092
|
+
if (obj.length === 0) return '[]';
|
|
1093
|
+
return obj.map(item => spaces + '- ' + formatToolResult(item, indent + 1)).join('\n');
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
const keys = Object.keys(obj);
|
|
1097
|
+
if (keys.length === 0) return '{}';
|
|
1098
|
+
|
|
1099
|
+
return keys.map(key => {
|
|
1100
|
+
const value = obj[key];
|
|
1101
|
+
if (typeof value === 'object') {
|
|
1102
|
+
return `${spaces}${key}:\n${formatToolResult(value, indent + 1)}`;
|
|
1103
|
+
}
|
|
1104
|
+
return `${spaces}${key}: ${value}`;
|
|
1105
|
+
}).join('\n');
|
|
1377
1106
|
}
|
|
1378
|
-
|
|
1107
|
+
|
|
1108
|
+
return String(obj);
|
|
1379
1109
|
}
|
|
1380
1110
|
|
|
1381
1111
|
// 工作流状态显示
|
|
@@ -1505,9 +1235,10 @@ function handleWorkflowLoopEvent(data, container) {
|
|
|
1505
1235
|
const loopCount = workflowDisplayEl.querySelector('.workflow-loop-count');
|
|
1506
1236
|
const streamsDiv = workflowDisplayEl.querySelector('.workflow-streams');
|
|
1507
1237
|
|
|
1508
|
-
// 更新循环次数
|
|
1238
|
+
// 更新循环次数
|
|
1509
1239
|
if (data.loopCount !== undefined) {
|
|
1510
|
-
|
|
1240
|
+
loopCount.textContent = `循环 #${data.loopCount}`;
|
|
1241
|
+
loopCount.style.display = 'inline';
|
|
1511
1242
|
}
|
|
1512
1243
|
|
|
1513
1244
|
// 显示循环信息
|
|
@@ -1517,7 +1248,8 @@ function handleWorkflowLoopEvent(data, container) {
|
|
|
1517
1248
|
loopEl.innerHTML = `
|
|
1518
1249
|
<div class="loop-header">
|
|
1519
1250
|
<span class="loop-icon">🔁</span>
|
|
1520
|
-
<span
|
|
1251
|
+
<span>循环 ${data.loopCount || '?'}</span>
|
|
1252
|
+
<span class="loop-status">${data.status || ''}</span>
|
|
1521
1253
|
</div>
|
|
1522
1254
|
<div class="loop-content">${data.content}</div>
|
|
1523
1255
|
`;
|
|
@@ -1529,7 +1261,7 @@ function handleWorkflowLoopEvent(data, container) {
|
|
|
1529
1261
|
// 用户命令可视化 - 当用户发送命令时调用
|
|
1530
1262
|
let userCommandDisplayEl = null;
|
|
1531
1263
|
|
|
1532
|
-
function showUserCommand(command, container
|
|
1264
|
+
function showUserCommand(command, container) {
|
|
1533
1265
|
const msgContainer = container || messagesContainers.get(currentChannelId) || messagesEl;
|
|
1534
1266
|
// 先移除之前的消息中的 user bubble(如果有重复的话)
|
|
1535
1267
|
const existingUserBubbles = msgContainer.querySelectorAll('.message-user');
|
|
@@ -1543,17 +1275,12 @@ function showUserCommand(command, container, opts) {
|
|
|
1543
1275
|
// 创建美化版本的命令显示
|
|
1544
1276
|
userCommandDisplayEl = document.createElement('div');
|
|
1545
1277
|
userCommandDisplayEl.className = 'message message-user';
|
|
1546
|
-
// v3 新增: 远端访客消息加 tag (source === 'remote' 表示是 B 通过 P2P 发来的)
|
|
1547
|
-
const sourceTag = (opts && opts.source === 'remote')
|
|
1548
|
-
? `<div style="font-size:10px;color:#6b7280;margin-bottom:2px;">🌐 远端访客${opts.fromPublicKey ? ' (' + opts.fromPublicKey.substring(0, 8) + '…)' : ''} → A 的 channel</div>`
|
|
1549
|
-
: '';
|
|
1550
1278
|
userCommandDisplayEl.innerHTML = `
|
|
1551
1279
|
<div class="user-command-display">
|
|
1552
1280
|
<div class="command-prompt">
|
|
1553
1281
|
<span class="prompt-icon">›</span>
|
|
1554
1282
|
<span class="prompt-text">${command}</span>
|
|
1555
1283
|
</div>
|
|
1556
|
-
${sourceTag}
|
|
1557
1284
|
</div>
|
|
1558
1285
|
`;
|
|
1559
1286
|
|
|
@@ -1567,12 +1294,6 @@ function showUserCommand(command, container, opts) {
|
|
|
1567
1294
|
msgContainer.scrollTop = msgContainer.scrollHeight;
|
|
1568
1295
|
}
|
|
1569
1296
|
|
|
1570
|
-
// ============================================================
|
|
1571
|
-
// 状态条 + phase + queue + abort (UI 体验补丁) — 旧版, 已被 timeline panel 取代
|
|
1572
|
-
// ============================================================
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
1297
|
function connect(channelId) {
|
|
1577
1298
|
const targetChannelId = channelId || currentChannelId;
|
|
1578
1299
|
if (!targetChannelId) return;
|
|
@@ -1666,39 +1387,30 @@ function connect(channelId) {
|
|
|
1666
1387
|
const container = messagesContainers.get(msgChannelId) || messagesEl;
|
|
1667
1388
|
|
|
1668
1389
|
if (data.type === 'user') {
|
|
1669
|
-
|
|
1670
|
-
// 1. sendMessage 已经在客户端 addMessage(text, 'user', true) 渲染成 .bubble-user 气泡
|
|
1671
|
-
// 2. SSE 推 user 又调 showUserCommand → 同时出现气泡 + 装饰条 (双重显示)
|
|
1672
|
-
// 3. 第二次切 channel 时, showUserCommand 会 remove 已有 .message-user 元素 (line 1477),
|
|
1673
|
-
// 但 .bubble-user class 不是 .message-user → 残留装饰条, 表现"模式变了"
|
|
1674
|
-
// 改法: SSE 收到 user 后, 跳过显示 (lastUserCommand 已经匹配, addMessage(save=true) 内部去重)
|
|
1675
|
-
// 但要确保 lastUserCommand 已经设过 — sendMessage 调 addMessage(true) 时会设
|
|
1676
|
-
// 远端 user (source === 'remote') 不会被 sendMessage 渲染, 需要走 addMessage 一次
|
|
1677
|
-
if (data.source === 'remote') {
|
|
1678
|
-
// 远端访客 (B 通过 P2P 发来的), sendMessage 没渲染它, 这里补上气泡
|
|
1679
|
-
addMessage(data.content, 'user', true, container);
|
|
1680
|
-
}
|
|
1681
|
-
// 本地 user 已经由 sendMessage 渲染 + 去重, 这里不再显示
|
|
1390
|
+
showUserCommand(data.content, container);
|
|
1682
1391
|
} else if (data.type === 'ai') {
|
|
1683
|
-
addMessage(data.content, 'ai', true, container
|
|
1392
|
+
addMessage(data.content, 'ai', true, container);
|
|
1393
|
+
hideTyping();
|
|
1684
1394
|
} else if (data.type === 'stream') {
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
}
|
|
1395
|
+
handleStreamEvent(data, container);
|
|
1396
|
+
setAgentStatus('executing');
|
|
1688
1397
|
} else if (data.type === 'regenerating') {
|
|
1689
|
-
// 删旧的最后一条 AI 消息, 准备重新生成
|
|
1690
1398
|
const messages = container.querySelectorAll('.message-ai');
|
|
1691
1399
|
if (messages.length > 0) {
|
|
1692
1400
|
const lastAiMsg = messages[messages.length - 1];
|
|
1693
1401
|
lastAiMsg.remove();
|
|
1694
1402
|
}
|
|
1695
|
-
|
|
1403
|
+
showTyping(container);
|
|
1696
1404
|
} else if (data.type === 'status') {
|
|
1697
|
-
|
|
1405
|
+
handleStatusEvent(data, container);
|
|
1406
|
+
setAgentStatus('executing');
|
|
1698
1407
|
} else if (data.type === 'done') {
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1408
|
+
hideTyping();
|
|
1409
|
+
// AI 回复完, 把最后一条 ai 消息落盘 (兜底, 避免 server saveSession 漏写)
|
|
1410
|
+
const lastAi = container.querySelector('.message-ai:last-of-type .message-content');
|
|
1411
|
+
if (lastAi) {
|
|
1412
|
+
persistLastMessageToServer('ai', lastAi.textContent || '');
|
|
1413
|
+
}
|
|
1702
1414
|
} else if (data.type === 'renamed') {
|
|
1703
1415
|
const channel = channels.find(c => c.id === data.channelId);
|
|
1704
1416
|
if (channel) {
|
|
@@ -1709,6 +1421,7 @@ function connect(channelId) {
|
|
|
1709
1421
|
}
|
|
1710
1422
|
}
|
|
1711
1423
|
} else if (data.type === 'error') {
|
|
1424
|
+
hideTyping();
|
|
1712
1425
|
addMessage('错误: ' + data.content, 'ai', true, container);
|
|
1713
1426
|
} else if (data.type === 'task_status') {
|
|
1714
1427
|
handleTaskStatusEvent(data, container);
|
|
@@ -1716,13 +1429,6 @@ function connect(channelId) {
|
|
|
1716
1429
|
handleWorkflowStepEvent(data, container);
|
|
1717
1430
|
} else if (data.type === 'workflow_loop') {
|
|
1718
1431
|
handleWorkflowLoopEvent(data, container);
|
|
1719
|
-
} else if (data.type === 'phase') {
|
|
1720
|
-
handlePhaseEventTimeline(data);
|
|
1721
|
-
} else if (data.type === 'queue_update') {
|
|
1722
|
-
handleQueueUpdateTimeline(data);
|
|
1723
|
-
} else if (data.type === 'used_judgments' && Array.isArray(data.usedIds)) {
|
|
1724
|
-
// 注入门回传: 保存 usedIds, finalizeTimelineAsMessage 时给 addMessage
|
|
1725
|
-
lastUsedJudgmentIds = data.usedIds;
|
|
1726
1432
|
}
|
|
1727
1433
|
} catch (parseErr) {
|
|
1728
1434
|
console.error('[SSE] 解析错误', parseErr);
|
|
@@ -1734,16 +1440,8 @@ async function sendMessage() {
|
|
|
1734
1440
|
const text = input.value.trim();
|
|
1735
1441
|
if (!text) return;
|
|
1736
1442
|
|
|
1737
|
-
// 2026-06-11: 立即把用户消息渲染成气泡上屏 (走 .bubble-user, 跟本地聊天一致)
|
|
1738
|
-
// 之前只靠 SSE `type: user` 回调显示, 但 addMessage(user) 默认 save=true 走去重, 容易跟 SSE 二次显示冲突/丢失
|
|
1739
|
-
// 现在: sendMessage 自己上屏, SSE `user` 回调来时因为 lastUserCommand 已匹配, 自动跳过 → 不重复
|
|
1740
|
-
const container = messagesContainers.get(currentChannelId) || messagesEl;
|
|
1741
|
-
addMessage(text, 'user', true, container);
|
|
1742
|
-
// 滚动到底
|
|
1743
|
-
if (container) container.scrollTop = container.scrollHeight;
|
|
1744
|
-
|
|
1745
1443
|
input.value = '';
|
|
1746
|
-
|
|
1444
|
+
showTyping();
|
|
1747
1445
|
|
|
1748
1446
|
// 立即把用户消息落盘, 避免切走再切回时丢失
|
|
1749
1447
|
persistLastMessageToServer('user', text);
|
|
@@ -1765,11 +1463,11 @@ async function sendMessage() {
|
|
|
1765
1463
|
});
|
|
1766
1464
|
|
|
1767
1465
|
if (!res.ok) {
|
|
1768
|
-
|
|
1466
|
+
hideTyping();
|
|
1769
1467
|
addMessage('发送失败', 'ai');
|
|
1770
1468
|
}
|
|
1771
1469
|
} catch (err) {
|
|
1772
|
-
|
|
1470
|
+
hideTyping();
|
|
1773
1471
|
addMessage('连接错误', 'ai');
|
|
1774
1472
|
console.error('Send error', err);
|
|
1775
1473
|
}
|
|
@@ -1798,385 +1496,6 @@ input.addEventListener('keydown', (e) => {
|
|
|
1798
1496
|
}
|
|
1799
1497
|
});
|
|
1800
1498
|
|
|
1801
|
-
// ============ v3 新增: @-mention 单选自动补全 (主聊天框 #input) ============
|
|
1802
|
-
let mentionChannels = []; // { id, name, source: 'local'|'remote', ownerPublicKey? }
|
|
1803
|
-
let mentionDropdownEl = null;
|
|
1804
|
-
let mentionHighlightIdx = -1;
|
|
1805
|
-
let mentionQuery = null;
|
|
1806
|
-
let mentionAnchor = -1; // @ 字符的绝对位置 (固定, 直到 dropdown 关闭)
|
|
1807
|
-
let mentionBlockEnd = -1; // 插入区块的终点 (单选模式下 = anchor + 1 + query)
|
|
1808
|
-
let mentionDocMousedownBound = false; // 防止重复注册 document mousedown
|
|
1809
|
-
|
|
1810
|
-
function ensureMentionDocMousedown() {
|
|
1811
|
-
if (mentionDocMousedownBound) return;
|
|
1812
|
-
mentionDocMousedownBound = true;
|
|
1813
|
-
document.addEventListener('mousedown', (e) => {
|
|
1814
|
-
if (mentionDropdownEl && !mentionDropdownEl.contains(e.target) && e.target !== input) {
|
|
1815
|
-
closeMentionDropdown();
|
|
1816
|
-
}
|
|
1817
|
-
});
|
|
1818
|
-
}
|
|
1819
|
-
|
|
1820
|
-
async function refreshMentionChannels() {
|
|
1821
|
-
try {
|
|
1822
|
-
const res = await fetch('/channels');
|
|
1823
|
-
const local = res.ok ? await res.json() : [];
|
|
1824
|
-
const r2 = await fetch('/api/remote-channels');
|
|
1825
|
-
const remoteData = r2.ok ? await r2.json() : { peers: [] };
|
|
1826
|
-
const remote = [];
|
|
1827
|
-
for (const p of (remoteData.peers || [])) {
|
|
1828
|
-
for (const c of (p.channels || [])) {
|
|
1829
|
-
remote.push({ id: c.id, name: c.name, source: 'remote', ownerPublicKey: p.peerId });
|
|
1830
|
-
}
|
|
1831
|
-
}
|
|
1832
|
-
mentionChannels = [
|
|
1833
|
-
...(Array.isArray(local) ? local.map(c => ({ id: c.id, name: c.name, source: 'local' })) : []),
|
|
1834
|
-
...remote
|
|
1835
|
-
];
|
|
1836
|
-
} catch (err) {
|
|
1837
|
-
console.warn('[mention] 加载渠道列表失败:', err);
|
|
1838
|
-
}
|
|
1839
|
-
}
|
|
1840
|
-
|
|
1841
|
-
function closeMentionDropdown() {
|
|
1842
|
-
if (mentionDropdownEl) { mentionDropdownEl.remove(); mentionDropdownEl = null; }
|
|
1843
|
-
mentionHighlightIdx = -1;
|
|
1844
|
-
mentionQuery = null;
|
|
1845
|
-
mentionAnchor = -1;
|
|
1846
|
-
mentionBlockEnd = -1;
|
|
1847
|
-
// 不重置 mentionDocMousedownBound — 监听器是空操作 (mentionDropdownEl === null) 留着无妨, 避免重复绑
|
|
1848
|
-
}
|
|
1849
|
-
|
|
1850
|
-
function getCurrentMentionQuery() {
|
|
1851
|
-
const pos = input.selectionStart || input.value.length;
|
|
1852
|
-
const before = input.value.slice(0, pos);
|
|
1853
|
-
const m = before.match(/@([一-龥A-Za-z0-9_\-]{0,30})$/);
|
|
1854
|
-
return m ? { query: m[1], anchor: pos - m[0].length } : null;
|
|
1855
|
-
}
|
|
1856
|
-
|
|
1857
|
-
function renderMentionDropdown(items) {
|
|
1858
|
-
if (!mentionDropdownEl) {
|
|
1859
|
-
mentionDropdownEl = document.createElement('div');
|
|
1860
|
-
mentionDropdownEl.id = 'mention-dropdown';
|
|
1861
|
-
mentionDropdownEl.style.cssText = 'position:fixed;background:#fff;border:1px solid #d1d5db;border-radius:6px;box-shadow:0 4px 16px rgba(0,0,0,0.15);max-height:240px;overflow-y:auto;z-index:10000;font-size:13px;min-width:240px;';
|
|
1862
|
-
document.body.appendChild(mentionDropdownEl);
|
|
1863
|
-
ensureMentionDocMousedown();
|
|
1864
|
-
}
|
|
1865
|
-
// v3 简化: 单选 + 立即填入输入框
|
|
1866
|
-
const headerHtml = `<div style="padding:6px 10px;background:#f9fafb;border-bottom:1px solid #e5e7eb;font-size:11px;color:#6b7280;display:flex;justify-content:space-between;align-items:center;">
|
|
1867
|
-
<span>💡 点击或回车选中 → 自动填入输入框</span>
|
|
1868
|
-
<span style="color:#9ca3af;">↑↓ 移动</span>
|
|
1869
|
-
</div>`;
|
|
1870
|
-
|
|
1871
|
-
if (items.length === 0) {
|
|
1872
|
-
mentionDropdownEl.innerHTML = headerHtml + '<div style="padding:10px 12px;color:#6b7280;font-size:12px;">没有匹配的渠道</div>';
|
|
1873
|
-
} else {
|
|
1874
|
-
const rows = items.map((c, i) => {
|
|
1875
|
-
const isLocal = c.source === 'local';
|
|
1876
|
-
const tag = isLocal ? '🏠 本地' : '🌐 远端';
|
|
1877
|
-
const owner = !isLocal && c.ownerPublicKey ? ` <span style="color:#9ca3af;font-size:11px;">(${c.ownerPublicKey.substring(0, 8)}…)</span>` : '';
|
|
1878
|
-
// 浅蓝 = 键盘高亮, 白 = 普通
|
|
1879
|
-
const bg = i === mentionHighlightIdx ? '#eff6ff' : '#fff';
|
|
1880
|
-
const borderLeft = i === mentionHighlightIdx ? '3px solid #93c5fd' : '3px solid transparent';
|
|
1881
|
-
return `<div class="mention-item" data-idx="${i}" data-channel-id="${escapeHtml(c.id)}" data-channel-name="${escapeHtml(c.name)}" style="padding:8px 12px;cursor:pointer;background:${bg};border-bottom:1px solid #f3f4f6;display:flex;align-items:center;gap:8px;border-left:${borderLeft};">
|
|
1882
|
-
<span style="font-size:10px;color:${isLocal ? '#059669' : '#2563eb'};background:${isLocal ? '#d1fae5' : '#dbeafe'};padding:1px 6px;border-radius:3px;white-space:nowrap;">${tag}</span>
|
|
1883
|
-
<span style="flex:1;">${escapeHtml(c.name)}</span>${owner}
|
|
1884
|
-
</div>`;
|
|
1885
|
-
}).join('');
|
|
1886
|
-
mentionDropdownEl.innerHTML = headerHtml + rows;
|
|
1887
|
-
mentionDropdownEl.querySelectorAll('.mention-item').forEach((el) => {
|
|
1888
|
-
const idx = parseInt(el.getAttribute('data-idx'));
|
|
1889
|
-
el.onclick = () => {
|
|
1890
|
-
// 单击 → 立即填入输入框 + 关闭 dropdown
|
|
1891
|
-
applyMention(items[idx]);
|
|
1892
|
-
};
|
|
1893
|
-
// v3 关键修复: mouseenter 只更新高亮, 不重建 dropdown — 否则用户实际点击的 element 被销毁,
|
|
1894
|
-
// click 事件落到新 element, 但实际触发的是新 element 的 onclick (空), 而不是被销毁前那个
|
|
1895
|
-
el.onmouseenter = () => {
|
|
1896
|
-
if (mentionHighlightIdx === idx) return;
|
|
1897
|
-
mentionHighlightIdx = idx;
|
|
1898
|
-
// 只更新背景色 + 左边框, 不重建 innerHTML
|
|
1899
|
-
const itemEls = mentionDropdownEl.querySelectorAll('.mention-item');
|
|
1900
|
-
itemEls.forEach((ie, ii) => {
|
|
1901
|
-
const isHi = ii === idx;
|
|
1902
|
-
ie.style.background = isHi ? '#eff6ff' : '#fff';
|
|
1903
|
-
ie.style.borderLeft = isHi ? '3px solid #93c5fd' : '3px solid transparent';
|
|
1904
|
-
});
|
|
1905
|
-
};
|
|
1906
|
-
});
|
|
1907
|
-
}
|
|
1908
|
-
const rect = input.getBoundingClientRect();
|
|
1909
|
-
mentionDropdownEl.style.left = rect.left + 'px';
|
|
1910
|
-
mentionDropdownEl.style.top = 'auto';
|
|
1911
|
-
mentionDropdownEl.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
|
|
1912
|
-
}
|
|
1913
|
-
|
|
1914
|
-
/** v3 单选: 把 @xxx 替换为 @渠道名 + 空格, 关闭 dropdown, 光标放空格后 */
|
|
1915
|
-
function applyMention(channel) {
|
|
1916
|
-
const anchor = mentionAnchor;
|
|
1917
|
-
const blockEnd = mentionBlockEnd >= 0 ? mentionBlockEnd : (anchor + 1 + (mentionQuery || '').length);
|
|
1918
|
-
if (anchor < 0 || anchor > input.value.length || input.value[anchor] !== '@') {
|
|
1919
|
-
closeMentionDropdown();
|
|
1920
|
-
return;
|
|
1921
|
-
}
|
|
1922
|
-
const before = input.value.slice(0, anchor); // 含 @
|
|
1923
|
-
const after = input.value.slice(blockEnd); // query 之后 (可能用户已输入正文)
|
|
1924
|
-
const insert = `@${channel.name} `;
|
|
1925
|
-
input.value = before + insert + after;
|
|
1926
|
-
const newPos = before.length + insert.length;
|
|
1927
|
-
input.focus();
|
|
1928
|
-
input.setSelectionRange(newPos, newPos);
|
|
1929
|
-
closeMentionDropdown();
|
|
1930
|
-
}
|
|
1931
|
-
|
|
1932
|
-
function updateMentionDropdown() {
|
|
1933
|
-
// 2026-06-10 修: 数组空时主动刷一次, 不再静默 return
|
|
1934
|
-
// 之前 `if (!mentionChannels.length) return` 导致初始化 0-8s 窗口按 @ 看不到任何 item
|
|
1935
|
-
if (!mentionChannels.length) {
|
|
1936
|
-
refreshMentionChannels().then(() => {
|
|
1937
|
-
// 拉完再重试一次 (异步, 不阻塞当前键击)
|
|
1938
|
-
if (mentionChannels.length) updateMentionDropdown();
|
|
1939
|
-
});
|
|
1940
|
-
return;
|
|
1941
|
-
}
|
|
1942
|
-
const m = getCurrentMentionQuery();
|
|
1943
|
-
if (!m) { closeMentionDropdown(); return; }
|
|
1944
|
-
// 只在 dropdown 刚打开时设置 anchor (blockEnd 跟着 insert 走)
|
|
1945
|
-
if (mentionAnchor === -1) {
|
|
1946
|
-
mentionAnchor = m.anchor;
|
|
1947
|
-
mentionBlockEnd = m.anchor + 1 + (m.query || '').length;
|
|
1948
|
-
// dropdown 首次打开 → 强制刷一次, 保证 remote 列表最新
|
|
1949
|
-
refreshMentionChannels();
|
|
1950
|
-
}
|
|
1951
|
-
mentionQuery = m.query;
|
|
1952
|
-
const q = m.query.toLowerCase();
|
|
1953
|
-
const items = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
1954
|
-
mentionHighlightIdx = items.length > 0 ? 0 : -1;
|
|
1955
|
-
renderMentionDropdown(items);
|
|
1956
|
-
}
|
|
1957
|
-
|
|
1958
|
-
input.addEventListener('input', () => {
|
|
1959
|
-
updateMentionDropdown();
|
|
1960
|
-
});
|
|
1961
|
-
input.addEventListener('keydown', (e) => {
|
|
1962
|
-
if (!mentionDropdownEl) return;
|
|
1963
|
-
const items = mentionDropdownEl.querySelectorAll('.mention-item');
|
|
1964
|
-
if (e.key === 'ArrowDown') {
|
|
1965
|
-
e.preventDefault();
|
|
1966
|
-
if (items.length === 0) return;
|
|
1967
|
-
mentionHighlightIdx = (mentionHighlightIdx + 1) % items.length;
|
|
1968
|
-
const q = (mentionQuery || '').toLowerCase();
|
|
1969
|
-
const filtered = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
1970
|
-
renderMentionDropdown(filtered);
|
|
1971
|
-
} else if (e.key === 'ArrowUp') {
|
|
1972
|
-
e.preventDefault();
|
|
1973
|
-
if (items.length === 0) return;
|
|
1974
|
-
mentionHighlightIdx = (mentionHighlightIdx - 1 + items.length) % items.length;
|
|
1975
|
-
const q = (mentionQuery || '').toLowerCase();
|
|
1976
|
-
const filtered = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
1977
|
-
renderMentionDropdown(filtered);
|
|
1978
|
-
} else if (e.key === 'Enter' || e.key === 'Tab') {
|
|
1979
|
-
// 单选: Enter/Tab 立即填入 + 关闭 dropdown
|
|
1980
|
-
if (items.length > 0) {
|
|
1981
|
-
e.preventDefault();
|
|
1982
|
-
e.stopPropagation();
|
|
1983
|
-
const q = (mentionQuery || '').toLowerCase();
|
|
1984
|
-
const filtered = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
1985
|
-
const cur = filtered[mentionHighlightIdx];
|
|
1986
|
-
if (cur) applyMention(cur);
|
|
1987
|
-
}
|
|
1988
|
-
} else if (e.key === 'Escape') {
|
|
1989
|
-
e.preventDefault();
|
|
1990
|
-
closeMentionDropdown();
|
|
1991
|
-
}
|
|
1992
|
-
}, true); // capture phase, 先于 sendMessage 那个 keydown
|
|
1993
|
-
|
|
1994
|
-
// 初始化
|
|
1995
|
-
refreshMentionChannels();
|
|
1996
|
-
// 定时刷新 (channel 列表可能变化)
|
|
1997
|
-
setInterval(refreshMentionChannels, 5000);
|
|
1998
|
-
// 远端 channel 列表变化时也刷新 (loadRemoteChannels 是 function declaration, 不能重新赋值)
|
|
1999
|
-
// 用 setInterval 兜底: 每 5s 刷一次 (已经有定时器, 这里不重复)
|
|
2000
|
-
// 实际上 refreshMentionChannels() 已经在 setInterval 里跑了
|
|
2001
|
-
|
|
2002
|
-
// v3 新增: 通用版 @-autocomplete (任意 input 元素都能挂, 比如 B 端的 #rcm-input)
|
|
2003
|
-
function setupMentionAutocomplete(inputEl) {
|
|
2004
|
-
if (!inputEl || inputEl.__mentionBound) return;
|
|
2005
|
-
inputEl.__mentionBound = true;
|
|
2006
|
-
let localQuery = null;
|
|
2007
|
-
let localAnchor = -1; // @ 字符的绝对位置 (固定, 直到 dropdown 关闭)
|
|
2008
|
-
let localBlockEnd = -1; // 插入区块的终点
|
|
2009
|
-
let localHighlight = -1;
|
|
2010
|
-
|
|
2011
|
-
function closeLocal() {
|
|
2012
|
-
if (inputEl.__mentionDD) { inputEl.__mentionDD.remove(); inputEl.__mentionDD = null; }
|
|
2013
|
-
localHighlight = -1; localQuery = null; localAnchor = -1; localBlockEnd = -1;
|
|
2014
|
-
}
|
|
2015
|
-
|
|
2016
|
-
function detectQuery() {
|
|
2017
|
-
const pos = inputEl.selectionStart || inputEl.value.length;
|
|
2018
|
-
const before = inputEl.value.slice(0, pos);
|
|
2019
|
-
const m = before.match(/@([一-龥A-Za-z0-9_\-]{0,30})$/);
|
|
2020
|
-
return m ? { query: m[1], anchor: pos - m[0].length } : null;
|
|
2021
|
-
}
|
|
2022
|
-
|
|
2023
|
-
// v3 单选: 点击 / Enter 立即填入输入框 + 关闭 dropdown
|
|
2024
|
-
function applyLocal(channel) {
|
|
2025
|
-
const anchor = localAnchor;
|
|
2026
|
-
const blockEnd = localBlockEnd >= 0 ? localBlockEnd : (anchor + 1 + (localQuery || '').length);
|
|
2027
|
-
if (anchor < 0 || anchor > inputEl.value.length || inputEl.value[anchor] !== '@') {
|
|
2028
|
-
closeLocal();
|
|
2029
|
-
return;
|
|
2030
|
-
}
|
|
2031
|
-
const before = inputEl.value.slice(0, anchor); // 含 @
|
|
2032
|
-
const after = inputEl.value.slice(blockEnd);
|
|
2033
|
-
const insert = `@${channel.name} `;
|
|
2034
|
-
inputEl.value = before + insert + after;
|
|
2035
|
-
const newPos = before.length + insert.length;
|
|
2036
|
-
inputEl.focus();
|
|
2037
|
-
inputEl.setSelectionRange(newPos, newPos);
|
|
2038
|
-
closeLocal();
|
|
2039
|
-
}
|
|
2040
|
-
|
|
2041
|
-
function renderLocal(items) {
|
|
2042
|
-
if (!inputEl.__mentionDD) {
|
|
2043
|
-
inputEl.__mentionDD = document.createElement('div');
|
|
2044
|
-
inputEl.__mentionDD.style.cssText = 'position:fixed;background:#fff;border:1px solid #d1d5db;border-radius:6px;box-shadow:0 4px 16px rgba(0,0,0,0.15);max-height:240px;overflow-y:auto;z-index:10001;font-size:13px;min-width:240px;';
|
|
2045
|
-
document.body.appendChild(inputEl.__mentionDD);
|
|
2046
|
-
}
|
|
2047
|
-
const headerHtml = `<div style="padding:6px 10px;background:#f9fafb;border-bottom:1px solid #e5e7eb;font-size:11px;color:#6b7280;display:flex;justify-content:space-between;align-items:center;">
|
|
2048
|
-
<span>💡 点击或回车选中 → 自动填入输入框</span>
|
|
2049
|
-
<span style="color:#9ca3af;">↑↓ 移动</span>
|
|
2050
|
-
</div>`;
|
|
2051
|
-
if (items.length === 0) {
|
|
2052
|
-
inputEl.__mentionDD.innerHTML = headerHtml + '<div style="padding:10px 12px;color:#6b7280;font-size:12px;">没有匹配的渠道</div>';
|
|
2053
|
-
} else {
|
|
2054
|
-
inputEl.__mentionDD.innerHTML = headerHtml + items.map((c, i) => {
|
|
2055
|
-
const isLocal = c.source === 'local';
|
|
2056
|
-
const tag = isLocal ? '🏠 本地' : '🌐 远端';
|
|
2057
|
-
const owner = !isLocal && c.ownerPublicKey ? ` <span style="color:#9ca3af;font-size:11px;">(${c.ownerPublicKey.substring(0, 8)}…)</span>` : '';
|
|
2058
|
-
const bg = i === localHighlight ? '#eff6ff' : '#fff';
|
|
2059
|
-
const borderLeft = i === localHighlight ? '3px solid #93c5fd' : '3px solid transparent';
|
|
2060
|
-
return `<div class="mention-item" data-idx="${i}" data-channel-id="${escapeHtml(c.id)}" data-channel-name="${escapeHtml(c.name)}" style="padding:8px 12px;cursor:pointer;background:${bg};border-bottom:1px solid #f3f4f6;display:flex;align-items:center;gap:8px;border-left:${borderLeft};">
|
|
2061
|
-
<span style="font-size:10px;color:${isLocal ? '#059669' : '#2563eb'};background:${isLocal ? '#d1fae5' : '#dbeafe'};padding:1px 6px;border-radius:3px;white-space:nowrap;">${tag}</span>
|
|
2062
|
-
<span style="flex:1;">${escapeHtml(c.name)}</span>${owner}
|
|
2063
|
-
</div>`;
|
|
2064
|
-
}).join('');
|
|
2065
|
-
inputEl.__mentionDD.querySelectorAll('.mention-item').forEach((el) => {
|
|
2066
|
-
const idx = parseInt(el.getAttribute('data-idx'));
|
|
2067
|
-
el.onclick = () => applyLocal(items[idx]);
|
|
2068
|
-
// v3 关键修复: mouseenter 只更新高亮, 不重建 dropdown (同主 input)
|
|
2069
|
-
el.onmouseenter = () => {
|
|
2070
|
-
if (localHighlight === idx) return;
|
|
2071
|
-
localHighlight = idx;
|
|
2072
|
-
const itemEls = inputEl.__mentionDD.querySelectorAll('.mention-item');
|
|
2073
|
-
itemEls.forEach((ie, ii) => {
|
|
2074
|
-
const isHi = ii === idx;
|
|
2075
|
-
ie.style.background = isHi ? '#eff6ff' : '#fff';
|
|
2076
|
-
ie.style.borderLeft = isHi ? '3px solid #93c5fd' : '3px solid transparent';
|
|
2077
|
-
});
|
|
2078
|
-
};
|
|
2079
|
-
});
|
|
2080
|
-
}
|
|
2081
|
-
const rect = inputEl.getBoundingClientRect();
|
|
2082
|
-
inputEl.__mentionDD.style.left = rect.left + 'px';
|
|
2083
|
-
inputEl.__mentionDD.style.top = 'auto';
|
|
2084
|
-
inputEl.__mentionDD.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
|
|
2085
|
-
}
|
|
2086
|
-
|
|
2087
|
-
function update() {
|
|
2088
|
-
// 2026-06-10 修: 与主输入框同步 — 数组空时主动刷新, 首次打开 dropdown 强制刷新
|
|
2089
|
-
if (!mentionChannels.length) {
|
|
2090
|
-
refreshMentionChannels().then(() => {
|
|
2091
|
-
if (mentionChannels.length) update();
|
|
2092
|
-
});
|
|
2093
|
-
return;
|
|
2094
|
-
}
|
|
2095
|
-
const m = detectQuery();
|
|
2096
|
-
if (!m) { closeLocal(); return; }
|
|
2097
|
-
if (localAnchor === -1) {
|
|
2098
|
-
localAnchor = m.anchor;
|
|
2099
|
-
localBlockEnd = m.anchor + 1 + (m.query || '').length;
|
|
2100
|
-
// dropdown 首次打开 → 强制刷一次保证 remote 最新
|
|
2101
|
-
refreshMentionChannels();
|
|
2102
|
-
}
|
|
2103
|
-
localQuery = m.query;
|
|
2104
|
-
const q = m.query.toLowerCase();
|
|
2105
|
-
const items = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
2106
|
-
localHighlight = items.length > 0 ? 0 : -1;
|
|
2107
|
-
renderLocal(items);
|
|
2108
|
-
}
|
|
2109
|
-
|
|
2110
|
-
inputEl.addEventListener('input', update);
|
|
2111
|
-
inputEl.addEventListener('keydown', (e) => {
|
|
2112
|
-
if (!inputEl.__mentionDD) return;
|
|
2113
|
-
const items = inputEl.__mentionDD.querySelectorAll('.mention-item');
|
|
2114
|
-
if (e.key === 'ArrowDown') {
|
|
2115
|
-
e.preventDefault();
|
|
2116
|
-
if (items.length === 0) return;
|
|
2117
|
-
localHighlight = (localHighlight + 1) % items.length;
|
|
2118
|
-
const q = (localQuery || '').toLowerCase();
|
|
2119
|
-
renderLocal(mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8));
|
|
2120
|
-
} else if (e.key === 'ArrowUp') {
|
|
2121
|
-
e.preventDefault();
|
|
2122
|
-
if (items.length === 0) return;
|
|
2123
|
-
localHighlight = (localHighlight - 1 + items.length) % items.length;
|
|
2124
|
-
const q = (localQuery || '').toLowerCase();
|
|
2125
|
-
renderLocal(mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8));
|
|
2126
|
-
} else if (e.key === 'Enter' || e.key === 'Tab') {
|
|
2127
|
-
if (items.length > 0) {
|
|
2128
|
-
e.preventDefault();
|
|
2129
|
-
e.stopPropagation();
|
|
2130
|
-
const q = (localQuery || '').toLowerCase();
|
|
2131
|
-
const filtered = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
2132
|
-
const cur = filtered[localHighlight];
|
|
2133
|
-
if (cur) applyLocal(cur);
|
|
2134
|
-
}
|
|
2135
|
-
} else if (e.key === 'Escape') {
|
|
2136
|
-
e.preventDefault();
|
|
2137
|
-
closeLocal();
|
|
2138
|
-
}
|
|
2139
|
-
}, true);
|
|
2140
|
-
}
|
|
2141
|
-
|
|
2142
|
-
// 拖拽落点: 把判断库里的判断拖到输入框, 直接作为指令发给 AI (走"代我决定"路径).
|
|
2143
|
-
// 用户拖进来后输入框被预填, 点发送就把这条判断作为指令交给当前 agent.
|
|
2144
|
-
const inputArea = document.querySelector('.input-area');
|
|
2145
|
-
if (input && inputArea) {
|
|
2146
|
-
const onDragOver = (e) => {
|
|
2147
|
-
if (e.dataTransfer && Array.from(e.dataTransfer.types || []).includes('application/x-bolloon-judgment')) {
|
|
2148
|
-
e.preventDefault();
|
|
2149
|
-
e.dataTransfer.dropEffect = 'copy';
|
|
2150
|
-
inputArea.classList.add('drop-target');
|
|
2151
|
-
}
|
|
2152
|
-
};
|
|
2153
|
-
const onDragLeave = (e) => {
|
|
2154
|
-
if (e.target === inputArea || !inputArea.contains(e.relatedTarget)) {
|
|
2155
|
-
inputArea.classList.remove('drop-target');
|
|
2156
|
-
}
|
|
2157
|
-
};
|
|
2158
|
-
const onDrop = (e) => {
|
|
2159
|
-
inputArea.classList.remove('drop-target');
|
|
2160
|
-
const raw = e.dataTransfer.getData('application/x-bolloon-judgment');
|
|
2161
|
-
if (!raw) return;
|
|
2162
|
-
e.preventDefault();
|
|
2163
|
-
try {
|
|
2164
|
-
const { id, decision } = JSON.parse(raw);
|
|
2165
|
-
// 预填输入框: 用户可改, 然后发出去 AI 就知道"按这条判断做"
|
|
2166
|
-
const prefix = input.value.trim() ? input.value.trim() + '\n' : '';
|
|
2167
|
-
input.value = `${prefix}按我的判断 #${id?.substring(0, 8) || ''} 执行: ${decision}`;
|
|
2168
|
-
input.focus();
|
|
2169
|
-
// 视觉提示
|
|
2170
|
-
input.style.transition = 'box-shadow 0.3s';
|
|
2171
|
-
input.style.boxShadow = '0 0 0 2px #2563eb';
|
|
2172
|
-
setTimeout(() => { input.style.boxShadow = ''; }, 800);
|
|
2173
|
-
} catch {}
|
|
2174
|
-
};
|
|
2175
|
-
inputArea.addEventListener('dragover', onDragOver);
|
|
2176
|
-
inputArea.addEventListener('dragleave', onDragLeave);
|
|
2177
|
-
inputArea.addEventListener('drop', onDrop);
|
|
2178
|
-
}
|
|
2179
|
-
|
|
2180
1499
|
if (themeToggle) {
|
|
2181
1500
|
themeToggle.addEventListener('click', toggleTheme);
|
|
2182
1501
|
}
|
|
@@ -2613,1841 +1932,53 @@ if (taskModalClose) {
|
|
|
2613
1932
|
taskModalClose.addEventListener('click', hideTaskModal);
|
|
2614
1933
|
}
|
|
2615
1934
|
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
const judgmentReason = document.getElementById('judgment-reason');
|
|
2622
|
-
const judgmentDomain = document.getElementById('judgment-domain');
|
|
2623
|
-
const judgmentStakes = document.getElementById('judgment-stakes');
|
|
2624
|
-
const judgmentSubmitBtn = document.getElementById('judgment-submit-btn');
|
|
2625
|
-
const judgmentError = document.getElementById('judgment-error');
|
|
2626
|
-
const judgmentsList = document.getElementById('judgments-list');
|
|
2627
|
-
const judgmentsBadge = document.getElementById('judgments-badge');
|
|
2628
|
-
|
|
2629
|
-
let judgmentsLoaded = false;
|
|
2630
|
-
|
|
2631
|
-
function showJudgmentsModal() {
|
|
2632
|
-
if (judgmentsModal) judgmentsModal.classList.add('active');
|
|
2633
|
-
if (!judgmentsLoaded) loadJudgments();
|
|
2634
|
-
else renderJudgments(lastJudgmentsCache); // 打开时按当前 channel / tab 重渲
|
|
2635
|
-
}
|
|
2636
|
-
|
|
2637
|
-
function switchJudgmentTab(tab) {
|
|
2638
|
-
currentJudgmentTab = tab;
|
|
2639
|
-
document.querySelectorAll('.judgment-tab').forEach(btn => {
|
|
2640
|
-
const active = btn.dataset.tab === tab;
|
|
2641
|
-
btn.classList.toggle('active', active);
|
|
2642
|
-
btn.style.borderBottomColor = active ? '#2563eb' : 'transparent';
|
|
2643
|
-
btn.style.color = active ? '#2563eb' : '#6b7280';
|
|
1935
|
+
if (taskModal) {
|
|
1936
|
+
taskModal.addEventListener('click', (e) => {
|
|
1937
|
+
if (e.target === taskModal) {
|
|
1938
|
+
hideTaskModal();
|
|
1939
|
+
}
|
|
2644
1940
|
});
|
|
2645
|
-
renderJudgments(lastJudgmentsCache);
|
|
2646
1941
|
}
|
|
2647
1942
|
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
document.querySelectorAll('.judgment-status-tab').forEach(btn => {
|
|
2651
|
-
const active = btn.dataset.status === status;
|
|
2652
|
-
btn.classList.toggle('active', active);
|
|
2653
|
-
btn.style.background = active ? '#2563eb' : '#e5e7eb';
|
|
2654
|
-
btn.style.color = active ? '#fff' : '#374151';
|
|
2655
|
-
});
|
|
2656
|
-
loadJudgments();
|
|
1943
|
+
if (taskAddBtn) {
|
|
1944
|
+
taskAddBtn.addEventListener('click', showCreateTaskModal);
|
|
2657
1945
|
}
|
|
2658
1946
|
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
* - 调 openJudgmentsModal() + 等 loadJudgments() 完成
|
|
2662
|
-
* - 然后用 ids filter lastJudgmentsCache
|
|
2663
|
-
*/
|
|
2664
|
-
function openJudgmentsModalWithFilter(ids) {
|
|
2665
|
-
if (!Array.isArray(ids) || ids.length === 0) return;
|
|
2666
|
-
if (typeof openJudgmentsModal === 'function') {
|
|
2667
|
-
openJudgmentsModal();
|
|
2668
|
-
} else if (judgmentsModal) {
|
|
2669
|
-
judgmentsModal.classList.add('active');
|
|
2670
|
-
}
|
|
2671
|
-
// 等 loadJudgments 完成 (它会 await fetch 然后 renderJudgments)
|
|
2672
|
-
setTimeout(() => {
|
|
2673
|
-
if (typeof lastJudgmentsCache === 'undefined') return;
|
|
2674
|
-
lastJudgmentsCache = (lastJudgmentsCache || []).filter((j) => ids.includes(j.id));
|
|
2675
|
-
if (typeof renderJudgments === 'function') {
|
|
2676
|
-
renderJudgments(lastJudgmentsCache);
|
|
2677
|
-
}
|
|
2678
|
-
}, 150);
|
|
1947
|
+
if (taskExecuteNextBtn) {
|
|
1948
|
+
taskExecuteNextBtn.addEventListener('click', executeNextTask);
|
|
2679
1949
|
}
|
|
2680
1950
|
|
|
2681
|
-
|
|
2682
|
-
|
|
1951
|
+
if (taskCancelBtn) {
|
|
1952
|
+
taskCancelBtn.addEventListener('click', hideCreateTaskModal);
|
|
2683
1953
|
}
|
|
2684
1954
|
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
/**
|
|
2690
|
-
* v3 重做: 渲染判断力列表 (受 tab + 当前 channel 影响)
|
|
2691
|
-
* tab = 'channel': 拆为"已绑定" + "未绑定"两组, 每条带 + / × 按钮
|
|
2692
|
-
* tab = 'global': 全部 judgment 列表, 无 + / × 按钮
|
|
2693
|
-
* 如果没选 channel, 'channel' tab 自动显示提示 + 全部 judgment
|
|
2694
|
-
*/
|
|
2695
|
-
function renderJudgments(items) {
|
|
2696
|
-
if (!judgmentsList) return;
|
|
2697
|
-
const all = items || [];
|
|
2698
|
-
const titleEl = document.getElementById('judgments-list-title');
|
|
2699
|
-
const chNameEl = document.getElementById('judgments-tab-channel-name');
|
|
2700
|
-
const currentCh = currentChannelId
|
|
2701
|
-
? channels.find(c => c.id === currentChannelId)
|
|
2702
|
-
: null;
|
|
2703
|
-
|
|
2704
|
-
if (chNameEl) {
|
|
2705
|
-
chNameEl.textContent = currentCh ? `(${currentCh.name})` : '(未选)';
|
|
2706
|
-
}
|
|
2707
|
-
|
|
2708
|
-
if (all.length === 0) {
|
|
2709
|
-
judgmentsList.innerHTML = '<div class="task-empty">还没有判断, 在上面记录第一条吧</div>';
|
|
2710
|
-
if (titleEl) titleEl.textContent = '本 channel 的判断力';
|
|
2711
|
-
return;
|
|
2712
|
-
}
|
|
2713
|
-
|
|
2714
|
-
if (currentJudgmentTab === 'global') {
|
|
2715
|
-
// 全局 tab: 全部 judgment, 简单列表
|
|
2716
|
-
if (titleEl) titleEl.textContent = `全局判断力 (${all.length} 条)`;
|
|
2717
|
-
judgmentsList.innerHTML = renderJudgmentItems(all, { showBindToggle: false });
|
|
2718
|
-
return;
|
|
2719
|
-
}
|
|
2720
|
-
|
|
2721
|
-
// channel tab: 必须有 channel
|
|
2722
|
-
if (!currentCh) {
|
|
2723
|
-
if (titleEl) titleEl.textContent = '本 channel 的判断力';
|
|
2724
|
-
judgmentsList.innerHTML = `
|
|
2725
|
-
<div style="padding:24px 12px;text-align:center;color:#6b7280;font-size:13px;">
|
|
2726
|
-
请先在左侧选中一个 channel,<br>然后这里会显示已绑定和可加入的判断力。
|
|
2727
|
-
</div>
|
|
2728
|
-
`;
|
|
2729
|
-
return;
|
|
2730
|
-
}
|
|
2731
|
-
|
|
2732
|
-
const boundIds = new Set(
|
|
2733
|
-
Array.isArray(currentCh.bound_judgment_ids) ? currentCh.bound_judgment_ids : []
|
|
2734
|
-
);
|
|
2735
|
-
const bound = all.filter(j => boundIds.has(j.id));
|
|
2736
|
-
const unbound = all.filter(j => !boundIds.has(j.id));
|
|
2737
|
-
|
|
2738
|
-
if (titleEl) titleEl.textContent = `${currentCh.name} 的判断力 (已绑 ${bound.length} / 共 ${all.length})`;
|
|
1955
|
+
if (createTaskModalClose) {
|
|
1956
|
+
createTaskModalClose.addEventListener('click', hideCreateTaskModal);
|
|
1957
|
+
}
|
|
2739
1958
|
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
html += `<div style="font-size:11px;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;padding:14px 4px 4px;">未绑定 (${unbound.length})</div>`;
|
|
2747
|
-
html += renderJudgmentItems(unbound, { showBindToggle: true, isBound: false });
|
|
2748
|
-
}
|
|
2749
|
-
judgmentsList.innerHTML = html;
|
|
1959
|
+
if (createTaskModal) {
|
|
1960
|
+
createTaskModal.addEventListener('click', (e) => {
|
|
1961
|
+
if (e.target === createTaskModal) {
|
|
1962
|
+
hideCreateTaskModal();
|
|
1963
|
+
}
|
|
1964
|
+
});
|
|
2750
1965
|
}
|
|
2751
1966
|
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
return items.map(j => {
|
|
2755
|
-
const reason = (j.reasons && j.reasons[0]) ? escapeHtml(j.reasons[0]) : '';
|
|
2756
|
-
const domain = (j.context && j.context.domain) ? escapeHtml(j.context.domain) : 'general';
|
|
2757
|
-
const stakes = (j.context && j.context.stakes) ? escapeHtml(j.context.stakes) : 'medium';
|
|
2758
|
-
const isSuperseded = j.status === 'superseded';
|
|
2759
|
-
const isRejected = j.status === 'rejected';
|
|
2760
|
-
const dimmedStyle = isSuperseded || isRejected
|
|
2761
|
-
? 'opacity:0.55;background:#f3f4f6;'
|
|
2762
|
-
: '';
|
|
2763
|
-
const statusTag = isSuperseded
|
|
2764
|
-
? `<span style="display:inline-block;background:#fef3c7;color:#92400e;font-size:10px;padding:1px 6px;border-radius:3px;margin-left:6px;" title="已被新判断力演化替代">已过时</span>`
|
|
2765
|
-
: isRejected
|
|
2766
|
-
? `<span style="display:inline-block;background:#fee2e2;color:#991b1b;font-size:10px;padding:1px 6px;border-radius:3px;margin-left:6px;">已拒绝</span>`
|
|
2767
|
-
: '';
|
|
2768
|
-
const evolveNote = isSuperseded && j.supersededBy
|
|
2769
|
-
? `<div style="font-size:10px;color:#6b7280;margin-top:2px;">被新条替代 · ${escapeHtml(j.evolutionReason || 'merged')} · ${escapeHtml(j.evolvedAt || '').substring(0,10)}</div>`
|
|
2770
|
-
: '';
|
|
2771
|
-
const bindBtn = showBindToggle
|
|
2772
|
-
? isBound
|
|
2773
|
-
? `<button class="judgment-toggle-btn" data-id="${escapeHtml(j.id)}" data-action="unbind" title="从当前 channel 移除" style="background:none;border:1px solid #fca5a5;color:#b91c1c;padding:1px 8px;border-radius:3px;cursor:pointer;font-size:11px;">× 移除</button>`
|
|
2774
|
-
: `<button class="judgment-toggle-btn" data-id="${escapeHtml(j.id)}" data-action="bind" title="加进当前 channel" style="background:none;border:1px solid #6b7280;color:#6b7280;padding:1px 8px;border-radius:3px;cursor:pointer;font-size:11px;">+ 加入</button>`
|
|
2775
|
-
: '';
|
|
2776
|
-
return `
|
|
2777
|
-
<div class="task-item completed judgment-row"
|
|
2778
|
-
data-judgment-id="${escapeHtml(j.id)}"
|
|
2779
|
-
draggable="true"
|
|
2780
|
-
style="cursor:grab;${dimmedStyle}">
|
|
2781
|
-
<div class="task-item-header">
|
|
2782
|
-
<label class="judgment-checkbox" style="display:flex;align-items:center;cursor:pointer;margin-right:8px;" onclick="event.stopPropagation();">
|
|
2783
|
-
<input type="checkbox" class="judgment-select-cb" data-id="${escapeHtml(j.id)}" style="cursor:pointer;" onclick="event.stopPropagation();">
|
|
2784
|
-
</label>
|
|
2785
|
-
<div class="task-item-title">
|
|
2786
|
-
<span class="judgment-decision">${escapeHtml(j.decision)}</span>${statusTag}
|
|
2787
|
-
</div>
|
|
2788
|
-
<span class="task-item-status completed">${stakes}</span>
|
|
2789
|
-
</div>
|
|
2790
|
-
${reason ? `<div class="task-item-desc" style="color:#555;font-size:13px;margin-top:4px;">理由: ${reason}</div>` : ''}
|
|
2791
|
-
${evolveNote}
|
|
2792
|
-
<div class="task-item-meta" style="color:#999;font-size:11px;margin-top:4px;display:flex;justify-content:space-between;align-items:center;">
|
|
2793
|
-
<span>${domain} · ${escapeHtml(j.timestamp)} · ${escapeHtml(j.id)}</span>
|
|
2794
|
-
<span style="display:flex;gap:4px;">
|
|
2795
|
-
${bindBtn}
|
|
2796
|
-
<button class="judgment-edit-btn" data-id="${escapeHtml(j.id)}" title="编辑判断" style="background:none;border:1px solid #d1d5db;color:#374151;padding:1px 8px;border-radius:3px;cursor:pointer;font-size:11px;">编辑</button>
|
|
2797
|
-
<button class="judgment-del-btn" data-id="${escapeHtml(j.id)}" title="删除判断" style="background:none;border:1px solid #fca5a5;color:#b91c1c;padding:1px 8px;border-radius:3px;cursor:pointer;font-size:11px;">删除</button>
|
|
2798
|
-
</span>
|
|
2799
|
-
</div>
|
|
2800
|
-
</div>
|
|
2801
|
-
`;
|
|
2802
|
-
}).join('');
|
|
1967
|
+
if (taskCreateBtn) {
|
|
1968
|
+
taskCreateBtn.addEventListener('click', createTask);
|
|
2803
1969
|
}
|
|
2804
1970
|
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
const res = await fetch('/api/judgments/violations?limit=50');
|
|
2811
|
-
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
2812
|
-
const data = await res.json();
|
|
2813
|
-
renderViolations(data.items || []);
|
|
2814
|
-
judgmentsLoaded = true;
|
|
2815
|
-
return;
|
|
1971
|
+
if (taskTypeSelect) {
|
|
1972
|
+
taskTypeSelect.addEventListener('change', () => {
|
|
1973
|
+
const workflowSteps = document.querySelector('.workflow-steps');
|
|
1974
|
+
if (workflowSteps) {
|
|
1975
|
+
workflowSteps.style.display = taskTypeSelect.value === 'workflow' ? 'block' : 'none';
|
|
2816
1976
|
}
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
2817
1979
|
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
const res = await fetch('/api/judgments/adaptive-suggestions');
|
|
2821
|
-
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
2822
|
-
const data = await res.json();
|
|
2823
|
-
renderAdaptiveSuggestions(data);
|
|
2824
|
-
judgmentsLoaded = true;
|
|
2825
|
-
return;
|
|
2826
|
-
}
|
|
2827
|
-
|
|
2828
|
-
// 阶段 2: causal-judge 因果分析
|
|
2829
|
-
if (currentStatusFilter === 'causal') {
|
|
2830
|
-
const res = await fetch('/api/judgments/causal/correlation?topN=10');
|
|
2831
|
-
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
2832
|
-
const data = await res.json();
|
|
2833
|
-
renderCausalAnalysis(data.items || []);
|
|
2834
|
-
judgmentsLoaded = true;
|
|
2835
|
-
return;
|
|
2836
|
-
}
|
|
2837
|
-
|
|
2838
|
-
const res = await fetch('/api/judgments?status=' + encodeURIComponent(currentStatusFilter));
|
|
2839
|
-
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
2840
|
-
const data = await res.json();
|
|
2841
|
-
lastJudgmentsCache = data.judgments || [];
|
|
2842
|
-
renderJudgments(lastJudgmentsCache);
|
|
2843
|
-
if (judgmentsBadge) {
|
|
2844
|
-
// 徽章永远显示 active 数量; 不跟 filter 变
|
|
2845
|
-
// 当 filter=active 时, 主 fetch 已经返回的就是 active 列表, 直接用 data.count
|
|
2846
|
-
// 当 filter=all/superseded 时, 从主列表本地数 active 条 (status ?? 'active' 兼容老数据)
|
|
2847
|
-
let activeCount;
|
|
2848
|
-
if (currentStatusFilter === 'active') {
|
|
2849
|
-
activeCount = data.count;
|
|
2850
|
-
} else {
|
|
2851
|
-
activeCount = lastJudgmentsCache.filter((j) => (j.status ?? 'active') === 'active').length;
|
|
2852
|
-
}
|
|
2853
|
-
if (activeCount > 0) {
|
|
2854
|
-
judgmentsBadge.textContent = activeCount;
|
|
2855
|
-
judgmentsBadge.style.display = '';
|
|
2856
|
-
} else {
|
|
2857
|
-
judgmentsBadge.style.display = 'none';
|
|
2858
|
-
}
|
|
2859
|
-
}
|
|
2860
|
-
judgmentsLoaded = true;
|
|
2861
|
-
} catch (e) {
|
|
2862
|
-
if (judgmentsList) judgmentsList.innerHTML = '<div class="task-empty">加载失败: ' + escapeHtml(e.message) + '</div>';
|
|
2863
|
-
}
|
|
2864
|
-
}
|
|
2865
|
-
|
|
2866
|
-
/**
|
|
2867
|
-
* P3 渲染违规记录 (与 renderJudgments 同位置, 但内容不同)
|
|
2868
|
-
*/
|
|
2869
|
-
function renderViolations(items) {
|
|
2870
|
-
if (!judgmentsList) return;
|
|
2871
|
-
if (!items || items.length === 0) {
|
|
2872
|
-
judgmentsList.innerHTML = '<div class="task-empty">暂无违规记录 (AI 回复未违反注入原则).</div>';
|
|
2873
|
-
return;
|
|
2874
|
-
}
|
|
2875
|
-
judgmentsList.innerHTML = items.map((v) => {
|
|
2876
|
-
const ts = escapeHtml((v.ts || '').substring(0, 19).replace('T', ' '));
|
|
2877
|
-
const userPrev = escapeHtml(v.userInputPreview || '');
|
|
2878
|
-
const aiPrev = escapeHtml(v.aiReplyPreview || '');
|
|
2879
|
-
const principles = (v.result?.violatedPrinciples || []).map((p) =>
|
|
2880
|
-
`<div style="margin-top:3px;padding:4px 8px;background:#fef2f2;border-radius:3px;">
|
|
2881
|
-
<span style="color:#dc2626;">⚠</span> <strong>${escapeHtml(p.principle || '')}</strong>
|
|
2882
|
-
<span style="color:#991b1b;">— ${escapeHtml(p.reason || '')}</span>
|
|
2883
|
-
</div>`
|
|
2884
|
-
).join('');
|
|
2885
|
-
return `
|
|
2886
|
-
<div class="task-item" style="border-left:3px solid #dc2626;padding:8px 12px;background:#fffbfb;">
|
|
2887
|
-
<div style="font-size:11px;color:#6b7280;margin-bottom:4px;">${ts} · confidence=${escapeHtml(String(v.result?.confidence ?? 0))}</div>
|
|
2888
|
-
<div style="font-size:12px;color:#1f2937;"><strong>用户:</strong> ${userPrev}</div>
|
|
2889
|
-
<div style="font-size:12px;color:#1f2937;margin-top:2px;"><strong>AI:</strong> ${aiPrev}</div>
|
|
2890
|
-
<div style="margin-top:6px;">${principles}</div>
|
|
2891
|
-
</div>
|
|
2892
|
-
`;
|
|
2893
|
-
}).join('');
|
|
2894
|
-
}
|
|
2895
|
-
|
|
2896
|
-
/**
|
|
2897
|
-
* 类 B 自适应建议渲染
|
|
2898
|
-
* - rising (绿色 boost 标记): 7 天使用率高于 30 天均值的 1.5 倍
|
|
2899
|
-
* - stale (黄色 deprecate 标记): 90 天未用 + 总使用 < 3
|
|
2900
|
-
* - unused (灰色 review 标记): 30 天未用 + 总使用 < 5
|
|
2901
|
-
* 每条带 "✓ 接受" / "✗ 拒绝" 按钮, 接受会真改库, 拒绝只留痕
|
|
2902
|
-
*/
|
|
2903
|
-
function renderAdaptiveSuggestions(data) {
|
|
2904
|
-
if (!judgmentsList) return;
|
|
2905
|
-
const { judgmentsTotal, usageEntriesScanned, suggestions, scannedAt } = data;
|
|
2906
|
-
const ts = escapeHtml((scannedAt || '').substring(0, 19).replace('T', ' '));
|
|
2907
|
-
|
|
2908
|
-
if (!suggestions || suggestions.length === 0) {
|
|
2909
|
-
judgmentsList.innerHTML = `
|
|
2910
|
-
<div class="task-empty">📊 自适应扫描: 无建议
|
|
2911
|
-
<div style="margin-top:8px;font-size:11px;color:#6b7280;">扫了 ${judgmentsTotal} 条原则, ${usageEntriesScanned} 条使用记录, 都挺健康.</div>
|
|
2912
|
-
<div style="margin-top:4px;font-size:11px;color:#6b7280;">扫描于 ${ts}</div>
|
|
2913
|
-
</div>`;
|
|
2914
|
-
return;
|
|
2915
|
-
}
|
|
2916
|
-
|
|
2917
|
-
const KIND_STYLE = {
|
|
2918
|
-
rising: { color: '#059669', bg: '#ecfdf5', label: '↑ rising', action: 'boost' },
|
|
2919
|
-
stale: { color: '#92400e', bg: '#fef3c7', label: '⏰ stale', action: 'deprecate' },
|
|
2920
|
-
unused: { color: '#6b7280', bg: '#f3f4f6', label: '👀 unused', action: 'review' },
|
|
2921
|
-
};
|
|
2922
|
-
|
|
2923
|
-
const header = `
|
|
2924
|
-
<div style="padding:8px 12px;background:#f9fafb;border-radius:4px;margin-bottom:8px;font-size:11px;color:#374151;">
|
|
2925
|
-
📊 扫描于 ${ts} · ${judgmentsTotal} 条原则 · ${usageEntriesScanned} 条使用记录 · <strong>${suggestions.length}</strong> 条建议
|
|
2926
|
-
<button class="rescan-btn" style="margin-left:8px;background:none;border:1px solid #6b7280;color:#374151;padding:1px 8px;border-radius:3px;cursor:pointer;font-size:11px;">🔄 重新扫描</button>
|
|
2927
|
-
</div>
|
|
2928
|
-
`;
|
|
2929
|
-
|
|
2930
|
-
const rows = suggestions.map((s) => {
|
|
2931
|
-
const style = KIND_STYLE[s.kind] || KIND_STYLE.unused;
|
|
2932
|
-
const m = s.metrics || {};
|
|
2933
|
-
return `
|
|
2934
|
-
<div class="task-item" data-suggestion-key="${escapeHtml(s.key)}"
|
|
2935
|
-
style="border-left:3px solid ${style.color};padding:8px 12px;background:${style.bg};margin-bottom:6px;">
|
|
2936
|
-
<div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;">
|
|
2937
|
-
<span style="color:${style.color};font-weight:600;font-size:12px;">${style.label}</span>
|
|
2938
|
-
<span style="font-size:11px;color:#6b7280;">${s.action === 'boost' ? '建议加权' : s.action === 'deprecate' ? '建议废弃' : '建议审视'}</span>
|
|
2939
|
-
</div>
|
|
2940
|
-
<div style="font-size:12px;color:#1f2937;margin-bottom:4px;"><strong>${escapeHtml(s.decision)}</strong></div>
|
|
2941
|
-
<div style="font-size:11px;color:#6b7280;margin-bottom:6px;">${escapeHtml(s.reason)}</div>
|
|
2942
|
-
<div style="font-size:11px;color:#9ca3af;margin-bottom:6px;">
|
|
2943
|
-
7天 ${m.usage7d || 0} · 30天 ${m.usage30d || 0} · 共 ${m.totalUsage || 0} · 上次用 ${m.daysSinceLastUse || 0} 天前
|
|
2944
|
-
</div>
|
|
2945
|
-
<div style="display:flex;gap:6px;">
|
|
2946
|
-
<button class="adaptive-accept" data-key="${escapeHtml(s.key)}" data-id="${escapeHtml(s.judgmentId)}" data-action-kind="${escapeHtml(s.action)}"
|
|
2947
|
-
style="background:#059669;color:#fff;border:none;padding:2px 10px;border-radius:3px;cursor:pointer;font-size:11px;">✓ 接受</button>
|
|
2948
|
-
<button class="adaptive-reject" data-key="${escapeHtml(s.key)}" data-id="${escapeHtml(s.judgmentId)}" data-action-kind="${escapeHtml(s.action)}"
|
|
2949
|
-
style="background:none;border:1px solid #d1d5db;color:#6b7280;padding:2px 10px;border-radius:3px;cursor:pointer;font-size:11px;">✗ 拒绝</button>
|
|
2950
|
-
</div>
|
|
2951
|
-
</div>
|
|
2952
|
-
`;
|
|
2953
|
-
}).join('');
|
|
2954
|
-
|
|
2955
|
-
judgmentsList.innerHTML = header + rows;
|
|
2956
|
-
|
|
2957
|
-
// 绑定按钮
|
|
2958
|
-
const rescanBtn = judgmentsList.querySelector('.rescan-btn');
|
|
2959
|
-
if (rescanBtn) {
|
|
2960
|
-
rescanBtn.onclick = async () => {
|
|
2961
|
-
rescanBtn.disabled = true;
|
|
2962
|
-
rescanBtn.textContent = '🔄 扫描中...';
|
|
2963
|
-
try {
|
|
2964
|
-
const r = await fetch('/api/judgments/adaptive-suggestions?force=1');
|
|
2965
|
-
if (r.ok) renderAdaptiveSuggestions(await r.json());
|
|
2966
|
-
} catch (err) {
|
|
2967
|
-
console.error('[adaptive] rescan failed:', err);
|
|
2968
|
-
} finally {
|
|
2969
|
-
rescanBtn.disabled = false;
|
|
2970
|
-
rescanBtn.textContent = '🔄 重新扫描';
|
|
2971
|
-
}
|
|
2972
|
-
};
|
|
2973
|
-
}
|
|
2974
|
-
judgmentsList.querySelectorAll('.adaptive-accept').forEach((btn) => {
|
|
2975
|
-
btn.onclick = () => applyAdaptiveSuggestion(btn.dataset.key, btn.dataset.id, btn.dataset.actionKind, 'accept');
|
|
2976
|
-
});
|
|
2977
|
-
judgmentsList.querySelectorAll('.adaptive-reject').forEach((btn) => {
|
|
2978
|
-
btn.onclick = () => applyAdaptiveSuggestion(btn.dataset.key, btn.dataset.id, btn.dataset.actionKind, 'reject');
|
|
2979
|
-
});
|
|
2980
|
-
}
|
|
2981
|
-
|
|
2982
|
-
async function applyAdaptiveSuggestion(key, judgmentId, actionKind, decision) {
|
|
2983
|
-
const row = judgmentsList?.querySelector(`[data-suggestion-key="${key}"]`);
|
|
2984
|
-
if (row) row.style.opacity = '0.5';
|
|
2985
|
-
try {
|
|
2986
|
-
const res = await fetch('/api/judgments/adaptive-apply', {
|
|
2987
|
-
method: 'POST',
|
|
2988
|
-
headers: { 'Content-Type': 'application/json' },
|
|
2989
|
-
body: JSON.stringify({
|
|
2990
|
-
action: decision,
|
|
2991
|
-
suggestion: {
|
|
2992
|
-
key,
|
|
2993
|
-
judgmentId,
|
|
2994
|
-
kind: actionKind,
|
|
2995
|
-
action: actionKind,
|
|
2996
|
-
decision: '',
|
|
2997
|
-
reason: '',
|
|
2998
|
-
metrics: {},
|
|
2999
|
-
scannedAt: new Date().toISOString(),
|
|
3000
|
-
},
|
|
3001
|
-
}),
|
|
3002
|
-
});
|
|
3003
|
-
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
3004
|
-
// 视觉反馈: 隐藏该行
|
|
3005
|
-
if (row) row.style.display = 'none';
|
|
3006
|
-
} catch (err) {
|
|
3007
|
-
if (row) row.style.opacity = '';
|
|
3008
|
-
console.error('[adaptive] apply failed:', err);
|
|
3009
|
-
alert('操作失败: ' + (err && err.message || 'unknown'));
|
|
3010
|
-
}
|
|
3011
|
-
}
|
|
3012
|
-
|
|
3013
|
-
// ============================================================
|
|
3014
|
-
// 阶段 2: causal-judge 渲染
|
|
3015
|
-
// ============================================================
|
|
3016
|
-
|
|
3017
|
-
/**
|
|
3018
|
-
* 渲染关联分析 (top 5 互信息对)
|
|
3019
|
-
* - 显示每对: judgmentA ↔ judgmentB + 互信息 + co-occurrence + 因果方向
|
|
3020
|
-
* - 每条 judgment 旁加"🔬 跑 do-calculus"按钮, 异步显示 causalEffect
|
|
3021
|
-
*/
|
|
3022
|
-
function renderCausalAnalysis(items) {
|
|
3023
|
-
if (!judgmentsList) return;
|
|
3024
|
-
if (!items || items.length === 0) {
|
|
3025
|
-
judgmentsList.innerHTML = `
|
|
3026
|
-
<div class="task-empty">🔍 因果分析: 无高关联对
|
|
3027
|
-
<div style="margin-top:8px;font-size:11px;color:#6b7280;">usage 数据不足 (至少 3 条同现), 或 LLM 不可用. 多用 bolloon 一段时间后重试.</div>
|
|
3028
|
-
</div>`;
|
|
3029
|
-
return;
|
|
3030
|
-
}
|
|
3031
|
-
|
|
3032
|
-
const rows = items.map((p, idx) => `
|
|
3033
|
-
<div class="task-item" data-causal-idx="${idx}" data-judgment-a="${escapeHtml(p.judgmentA)}" data-judgment-b="${escapeHtml(p.judgmentB)}"
|
|
3034
|
-
style="border-left:3px solid #7c3aed;padding:8px 12px;background:#faf5ff;margin-bottom:6px;">
|
|
3035
|
-
<div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;">
|
|
3036
|
-
<span style="color:#7c3aed;font-weight:600;font-size:12px;">${escapeHtml(p.causalDirection)}</span>
|
|
3037
|
-
<span style="font-size:11px;color:#6b7280;">MI=${p.mutualInfo} · co=${p.coOccurrence}</span>
|
|
3038
|
-
</div>
|
|
3039
|
-
<div style="font-size:11px;color:#374151;margin-bottom:4px;">${escapeHtml(p.explanation || '(无 LLM 解释)')}</div>
|
|
3040
|
-
<div style="font-size:10px;color:#9ca3af;">A: ${escapeHtml(p.judgmentA)} ↔ B: ${escapeHtml(p.judgmentB)}</div>
|
|
3041
|
-
<div style="margin-top:6px;display:flex;gap:6px;">
|
|
3042
|
-
<button class="causal-intervention-a" data-jid="${escapeHtml(p.judgmentA)}"
|
|
3043
|
-
style="background:#7c3aed;color:#fff;border:none;padding:2px 10px;border-radius:3px;cursor:pointer;font-size:11px;">🔬 do(A)</button>
|
|
3044
|
-
<button class="causal-intervention-b" data-jid="${escapeHtml(p.judgmentB)}"
|
|
3045
|
-
style="background:#7c3aed;color:#fff;border:none;padding:2px 10px;border-radius:3px;cursor:pointer;font-size:11px;">🔬 do(B)</button>
|
|
3046
|
-
</div>
|
|
3047
|
-
<div class="causal-result" data-jid="" style="display:none;margin-top:6px;padding:6px;background:#f3e8ff;border-radius:3px;font-size:11px;"></div>
|
|
3048
|
-
</div>
|
|
3049
|
-
`).join('');
|
|
3050
|
-
|
|
3051
|
-
judgmentsList.innerHTML = `
|
|
3052
|
-
<div style="padding:8px 12px;background:#f9fafb;border-radius:4px;margin-bottom:8px;font-size:11px;color:#374151;">
|
|
3053
|
-
🔍 关联分析 (top ${items.length} 互信息对) · <span style="color:#7c3aed;">LLM 推断方向</span>
|
|
3054
|
-
<button class="causal-refresh" style="margin-left:8px;background:none;border:1px solid #7c3aed;color:#7c3aed;padding:1px 8px;border-radius:3px;cursor:pointer;font-size:11px;">🔄 重新跑</button>
|
|
3055
|
-
</div>
|
|
3056
|
-
${rows}
|
|
3057
|
-
`;
|
|
3058
|
-
|
|
3059
|
-
// 按钮: 重新跑
|
|
3060
|
-
const refresh = judgmentsList.querySelector('.causal-refresh');
|
|
3061
|
-
if (refresh) {
|
|
3062
|
-
refresh.onclick = async () => {
|
|
3063
|
-
refresh.disabled = true;
|
|
3064
|
-
refresh.textContent = '🔄 跑中...';
|
|
3065
|
-
try {
|
|
3066
|
-
const r = await fetch('/api/judgments/causal/correlation?topN=10');
|
|
3067
|
-
if (r.ok) renderCausalAnalysis((await r.json()).items || []);
|
|
3068
|
-
} finally {
|
|
3069
|
-
refresh.disabled = false;
|
|
3070
|
-
refresh.textContent = '🔄 重新跑';
|
|
3071
|
-
}
|
|
3072
|
-
};
|
|
3073
|
-
}
|
|
3074
|
-
|
|
3075
|
-
// 按钮: 跑 do-calculus
|
|
3076
|
-
judgmentsList.querySelectorAll('.causal-intervention-a, .causal-intervention-b').forEach((btn) => {
|
|
3077
|
-
btn.onclick = async () => {
|
|
3078
|
-
const jid = btn.getAttribute('data-jid');
|
|
3079
|
-
const resultDiv = btn.closest('.task-item')?.querySelector('.causal-result');
|
|
3080
|
-
if (!resultDiv) return;
|
|
3081
|
-
resultDiv.style.display = 'block';
|
|
3082
|
-
resultDiv.textContent = '🔬 跑 do-calculus (LLM 模拟反事实)...';
|
|
3083
|
-
btn.disabled = true;
|
|
3084
|
-
try {
|
|
3085
|
-
const r = await fetch(`/api/judgments/causal/intervention?judgmentId=${encodeURIComponent(jid)}`);
|
|
3086
|
-
if (!r.ok) throw new Error('HTTP ' + r.status);
|
|
3087
|
-
const data = await r.json();
|
|
3088
|
-
const effect = data.causalEffect;
|
|
3089
|
-
const sign = effect > 0 ? '+' : '';
|
|
3090
|
-
const color = Math.abs(effect) > 0.5 ? '#dc2626' : Math.abs(effect) > 0.2 ? '#d97706' : '#059669';
|
|
3091
|
-
resultDiv.innerHTML = `
|
|
3092
|
-
<div style="color:${color};font-weight:600;">do-calculus: causalEffect = ${sign}${effect} (${data.marginalContribution})</div>
|
|
3093
|
-
<div style="color:#374151;margin-top:4px;">${escapeHtml(data.reasoning)}</div>
|
|
3094
|
-
<div style="color:#9ca3af;margin-top:4px;">confidence=${data.confidence}</div>
|
|
3095
|
-
`;
|
|
3096
|
-
} catch (err) {
|
|
3097
|
-
resultDiv.innerHTML = `<div style="color:#dc2626;">失败: ${escapeHtml(err.message)}</div>`;
|
|
3098
|
-
} finally {
|
|
3099
|
-
btn.disabled = false;
|
|
3100
|
-
}
|
|
3101
|
-
};
|
|
3102
|
-
});
|
|
3103
|
-
}
|
|
3104
|
-
|
|
3105
|
-
/** 把 judgment id 加进 / 移出当前 channel.bound_judgment_ids, 然后刷新两边 UI */
|
|
3106
|
-
async function toggleChannelJudgment(judgmentId, action) {
|
|
3107
|
-
if (!currentChannelId) {
|
|
3108
|
-
showJudgmentError('请先选中一个 channel');
|
|
3109
|
-
return;
|
|
3110
|
-
}
|
|
3111
|
-
const ch = channels.find(c => c.id === currentChannelId);
|
|
3112
|
-
if (!ch) return;
|
|
3113
|
-
const set = new Set(Array.isArray(ch.bound_judgment_ids) ? ch.bound_judgment_ids : []);
|
|
3114
|
-
if (action === 'bind') set.add(judgmentId);
|
|
3115
|
-
else set.delete(judgmentId);
|
|
3116
|
-
const next = Array.from(set);
|
|
3117
|
-
try {
|
|
3118
|
-
const res = await fetch(`/channels/${currentChannelId}`, {
|
|
3119
|
-
method: 'PATCH',
|
|
3120
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3121
|
-
body: JSON.stringify({ bound_judgment_ids: next })
|
|
3122
|
-
});
|
|
3123
|
-
if (!res.ok) {
|
|
3124
|
-
const err = await res.json().catch(() => ({}));
|
|
3125
|
-
throw new Error(err.error || `HTTP ${res.status}`);
|
|
3126
|
-
}
|
|
3127
|
-
const updated = await res.json();
|
|
3128
|
-
const idx = channels.findIndex(c => c.id === currentChannelId);
|
|
3129
|
-
if (idx >= 0) channels[idx] = updated;
|
|
3130
|
-
// 弹窗开着就刷新, 关着就跳过
|
|
3131
|
-
if (judgmentsModal && judgmentsModal.classList.contains('active')) {
|
|
3132
|
-
renderJudgments(lastJudgmentsCache);
|
|
3133
|
-
}
|
|
3134
|
-
} catch (err) {
|
|
3135
|
-
showJudgmentError('绑定失败: ' + err.message);
|
|
3136
|
-
}
|
|
3137
|
-
}
|
|
3138
|
-
|
|
3139
|
-
// 列表内编辑/删除 + 拖拽 — 事件委托
|
|
3140
|
-
if (judgmentsList) {
|
|
3141
|
-
judgmentsList.addEventListener('click', async (e) => {
|
|
3142
|
-
const editBtn = e.target.closest && e.target.closest('.judgment-edit-btn');
|
|
3143
|
-
const delBtn = e.target.closest && e.target.closest('.judgment-del-btn');
|
|
3144
|
-
const toggleBtn = e.target.closest && e.target.closest('.judgment-toggle-btn');
|
|
3145
|
-
if (editBtn) {
|
|
3146
|
-
const id = editBtn.getAttribute('data-id');
|
|
3147
|
-
await editJudgment(id);
|
|
3148
|
-
} else if (delBtn) {
|
|
3149
|
-
const id = delBtn.getAttribute('data-id');
|
|
3150
|
-
if (!confirm('确定删除这条判断?')) return;
|
|
3151
|
-
try {
|
|
3152
|
-
const res = await fetch('/api/judgments/' + encodeURIComponent(id), { method: 'DELETE' });
|
|
3153
|
-
const out = await res.json();
|
|
3154
|
-
if (!out.ok) throw new Error(out.error || 'delete failed');
|
|
3155
|
-
await loadJudgments();
|
|
3156
|
-
} catch (err) {
|
|
3157
|
-
showJudgmentError('删除失败: ' + err.message);
|
|
3158
|
-
}
|
|
3159
|
-
} else if (toggleBtn) {
|
|
3160
|
-
const id = toggleBtn.getAttribute('data-id');
|
|
3161
|
-
const action = toggleBtn.getAttribute('data-action');
|
|
3162
|
-
await toggleChannelJudgment(id, action);
|
|
3163
|
-
}
|
|
3164
|
-
});
|
|
3165
|
-
|
|
3166
|
-
// tab 切换
|
|
3167
|
-
document.querySelectorAll('.judgment-tab').forEach(btn => {
|
|
3168
|
-
btn.addEventListener('click', () => switchJudgmentTab(btn.dataset.tab));
|
|
3169
|
-
});
|
|
3170
|
-
|
|
3171
|
-
// status 过滤
|
|
3172
|
-
document.querySelectorAll('.judgment-status-tab').forEach(btn => {
|
|
3173
|
-
btn.addEventListener('click', () => switchStatusFilter(btn.dataset.status));
|
|
3174
|
-
});
|
|
3175
|
-
|
|
3176
|
-
// 拖拽: 每条 judgment 是 drag source, dataTransfer 装 decision text
|
|
3177
|
-
judgmentsList.addEventListener('dragstart', (e) => {
|
|
3178
|
-
const row = e.target.closest && e.target.closest('.judgment-row');
|
|
3179
|
-
if (!row) return;
|
|
3180
|
-
const decision = row.querySelector('.judgment-decision')?.textContent || '';
|
|
3181
|
-
const id = row.getAttribute('data-judgment-id') || '';
|
|
3182
|
-
e.dataTransfer.effectAllowed = 'copy';
|
|
3183
|
-
e.dataTransfer.setData('text/plain', decision);
|
|
3184
|
-
e.dataTransfer.setData('application/x-bolloon-judgment', JSON.stringify({ id, decision }));
|
|
3185
|
-
});
|
|
3186
|
-
|
|
3187
|
-
// 多选 checkbox 变化 → 更新工具栏
|
|
3188
|
-
judgmentsList.addEventListener('change', (e) => {
|
|
3189
|
-
if (e.target.classList && e.target.classList.contains('judgment-select-cb')) {
|
|
3190
|
-
updateBulkDeleteToolbar();
|
|
3191
|
-
}
|
|
3192
|
-
});
|
|
3193
|
-
}
|
|
3194
|
-
|
|
3195
|
-
// 批量选择工具栏: 全选 / 计数 / 启用删除按钮
|
|
3196
|
-
const judgmentSelectAll = document.getElementById('judgment-select-all');
|
|
3197
|
-
const judgmentSelectedCount = document.getElementById('judgment-selected-count');
|
|
3198
|
-
const judgmentBulkDeleteBtn = document.getElementById('judgment-bulk-delete-btn');
|
|
3199
|
-
|
|
3200
|
-
function getSelectedJudgmentIds() {
|
|
3201
|
-
if (!judgmentsList) return [];
|
|
3202
|
-
return Array.from(judgmentsList.querySelectorAll('.judgment-select-cb'))
|
|
3203
|
-
.filter(cb => cb.checked)
|
|
3204
|
-
.map(cb => cb.getAttribute('data-id'))
|
|
3205
|
-
.filter(Boolean);
|
|
3206
|
-
}
|
|
3207
|
-
|
|
3208
|
-
function updateBulkDeleteToolbar() {
|
|
3209
|
-
const ids = getSelectedJudgmentIds();
|
|
3210
|
-
if (judgmentSelectedCount) judgmentSelectedCount.textContent = `已选 ${ids.length}`;
|
|
3211
|
-
if (judgmentBulkDeleteBtn) {
|
|
3212
|
-
judgmentBulkDeleteBtn.disabled = ids.length === 0;
|
|
3213
|
-
judgmentBulkDeleteBtn.style.opacity = ids.length === 0 ? '0.5' : '1';
|
|
3214
|
-
judgmentBulkDeleteBtn.style.cursor = ids.length === 0 ? 'not-allowed' : 'pointer';
|
|
3215
|
-
}
|
|
3216
|
-
// 全选 checkbox 的 indeterminate / checked 状态同步
|
|
3217
|
-
if (judgmentSelectAll && judgmentsList) {
|
|
3218
|
-
const all = judgmentsList.querySelectorAll('.judgment-select-cb');
|
|
3219
|
-
const checked = Array.from(all).filter(cb => cb.checked);
|
|
3220
|
-
judgmentSelectAll.checked = all.length > 0 && checked.length === all.length;
|
|
3221
|
-
judgmentSelectAll.indeterminate = checked.length > 0 && checked.length < all.length;
|
|
3222
|
-
}
|
|
3223
|
-
}
|
|
3224
|
-
|
|
3225
|
-
if (judgmentSelectAll) {
|
|
3226
|
-
judgmentSelectAll.addEventListener('change', (e) => {
|
|
3227
|
-
if (!judgmentsList) return;
|
|
3228
|
-
const checked = e.target.checked;
|
|
3229
|
-
judgmentsList.querySelectorAll('.judgment-select-cb').forEach(cb => { cb.checked = checked; });
|
|
3230
|
-
updateBulkDeleteToolbar();
|
|
3231
|
-
});
|
|
3232
|
-
}
|
|
3233
|
-
|
|
3234
|
-
if (judgmentBulkDeleteBtn) {
|
|
3235
|
-
judgmentBulkDeleteBtn.addEventListener('click', async () => {
|
|
3236
|
-
const ids = getSelectedJudgmentIds();
|
|
3237
|
-
if (ids.length === 0) return;
|
|
3238
|
-
if (!confirm(`确定删除选中的 ${ids.length} 条判断? 此操作不可撤销.`)) return;
|
|
3239
|
-
judgmentBulkDeleteBtn.disabled = true;
|
|
3240
|
-
try {
|
|
3241
|
-
const res = await fetch('/api/judgments/batch-delete', {
|
|
3242
|
-
method: 'POST',
|
|
3243
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3244
|
-
body: JSON.stringify({ ids }),
|
|
3245
|
-
});
|
|
3246
|
-
const out = await res.json();
|
|
3247
|
-
if (!out.ok) throw new Error(out.error || 'failed');
|
|
3248
|
-
showJudgmentOk(`✓ 批量删除 ${out.deleted} 条${out.notFound?.length ? ` (${out.notFound.length} 条未找到)` : ''}`);
|
|
3249
|
-
await loadJudgments();
|
|
3250
|
-
} catch (err) {
|
|
3251
|
-
showJudgmentError('批量删除失败: ' + err.message);
|
|
3252
|
-
} finally {
|
|
3253
|
-
if (judgmentBulkDeleteBtn) judgmentBulkDeleteBtn.disabled = false;
|
|
3254
|
-
}
|
|
3255
|
-
});
|
|
3256
|
-
}
|
|
3257
|
-
|
|
3258
|
-
async function editJudgment(id) {
|
|
3259
|
-
// 简单做法: 用 prompt 弹 3 个字段. 想要更好的体验就用 inline editor, 但 v1 不必.
|
|
3260
|
-
const all = await (await fetch('/api/judgments')).json();
|
|
3261
|
-
const j = (all.judgments || []).find(x => x.id === id);
|
|
3262
|
-
if (!j) { showJudgmentError('找不到该判断 (可能已删除)'); return; }
|
|
3263
|
-
const newDecision = prompt('修改判断 (decision):', j.decision);
|
|
3264
|
-
if (newDecision === null) return;
|
|
3265
|
-
const newReason = prompt('修改理由 (reason, 留空不改):', (j.reasons && j.reasons[0]) || '');
|
|
3266
|
-
const newStakes = prompt('修改风险 (low/medium/high/critical):', (j.context && j.context.stakes) || 'medium');
|
|
3267
|
-
const patch = {
|
|
3268
|
-
decision: newDecision.trim() || j.decision,
|
|
3269
|
-
reasons: newReason !== null ? [newReason.trim()].filter(Boolean) : j.reasons,
|
|
3270
|
-
context: newStakes ? { ...(j.context || {}), stakes: newStakes } : j.context,
|
|
3271
|
-
};
|
|
3272
|
-
try {
|
|
3273
|
-
const res = await fetch('/api/judgments/' + encodeURIComponent(id), {
|
|
3274
|
-
method: 'PATCH',
|
|
3275
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3276
|
-
body: JSON.stringify(patch),
|
|
3277
|
-
});
|
|
3278
|
-
const out = await res.json();
|
|
3279
|
-
if (!out.ok) throw new Error(out.error || 'update failed');
|
|
3280
|
-
showJudgmentOk('✓ 已更新');
|
|
3281
|
-
await loadJudgments();
|
|
3282
|
-
} catch (err) {
|
|
3283
|
-
showJudgmentError('更新失败: ' + err.message);
|
|
3284
|
-
}
|
|
3285
|
-
}
|
|
3286
|
-
|
|
3287
|
-
async function submitJudgment() {
|
|
3288
|
-
if (!judgmentSubmitBtn) return;
|
|
3289
|
-
const decision = (judgmentDecision?.value || '').trim();
|
|
3290
|
-
const reason = (judgmentReason?.value || '').trim();
|
|
3291
|
-
if (!decision) {
|
|
3292
|
-
if (judgmentError) { judgmentError.textContent = '判断不能为空'; judgmentError.style.display = ''; }
|
|
3293
|
-
return;
|
|
3294
|
-
}
|
|
3295
|
-
judgmentSubmitBtn.disabled = true;
|
|
3296
|
-
if (judgmentError) judgmentError.style.display = 'none';
|
|
3297
|
-
try {
|
|
3298
|
-
const res = await fetch('/api/judgments', {
|
|
3299
|
-
method: 'POST',
|
|
3300
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3301
|
-
body: JSON.stringify({
|
|
3302
|
-
decision,
|
|
3303
|
-
reason: reason || undefined,
|
|
3304
|
-
context: { domain: judgmentDomain?.value, stakes: judgmentStakes?.value },
|
|
3305
|
-
}),
|
|
3306
|
-
});
|
|
3307
|
-
const out = await res.json();
|
|
3308
|
-
if (!out.ok) throw new Error(out.error || 'unknown');
|
|
3309
|
-
if (judgmentDecision) judgmentDecision.value = '';
|
|
3310
|
-
if (judgmentReason) judgmentReason.value = '';
|
|
3311
|
-
await loadJudgments();
|
|
3312
|
-
|
|
3313
|
-
// AI 自动委派: fire-and-forget. 根据 domain 找匹配的远端 agent, 触发 agent_delegate 协议.
|
|
3314
|
-
// 失败也不影响本次记录.
|
|
3315
|
-
try {
|
|
3316
|
-
const del = await fetch('/api/judgments/auto-delegate', {
|
|
3317
|
-
method: 'POST',
|
|
3318
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3319
|
-
body: JSON.stringify({
|
|
3320
|
-
judgmentId: out.judgment.id,
|
|
3321
|
-
capability: judgmentDomain?.value || 'general',
|
|
3322
|
-
instruction: `执行判断: ${out.judgment.decision}` + (reason ? ` (理由: ${reason})` : ''),
|
|
3323
|
-
}),
|
|
3324
|
-
});
|
|
3325
|
-
const delOut = await del.json();
|
|
3326
|
-
if (delOut.matched && delOut.sent) {
|
|
3327
|
-
showJudgmentOk(`✓ 已记录并自动委派给 ${delOut.targetAgent.name}`);
|
|
3328
|
-
} else if (delOut.matched) {
|
|
3329
|
-
showJudgmentOk(`✓ 已记录 (匹配到 ${delOut.targetAgent.name}, 但 ${delOut.reason || '未发送'})`);
|
|
3330
|
-
} else {
|
|
3331
|
-
showJudgmentOk('✓ 已记录 (本地, 无匹配远端 agent)');
|
|
3332
|
-
}
|
|
3333
|
-
} catch (e) {
|
|
3334
|
-
console.warn('[judgments] auto-delegate fire failed:', e);
|
|
3335
|
-
}
|
|
3336
|
-
} catch (e) {
|
|
3337
|
-
if (judgmentError) { judgmentError.textContent = '记录失败: ' + e.message; judgmentError.style.display = ''; }
|
|
3338
|
-
} finally {
|
|
3339
|
-
judgmentSubmitBtn.disabled = false;
|
|
3340
|
-
}
|
|
3341
|
-
}
|
|
3342
|
-
|
|
3343
|
-
if (judgmentsBtn) judgmentsBtn.addEventListener('click', showJudgmentsModal);
|
|
3344
|
-
if (judgmentsModalClose) judgmentsModalClose.addEventListener('click', hideJudgmentsModal);
|
|
3345
|
-
if (judgmentsModal) {
|
|
3346
|
-
judgmentsModal.addEventListener('click', (e) => {
|
|
3347
|
-
if (e.target === judgmentsModal) hideJudgmentsModal();
|
|
3348
|
-
});
|
|
3349
|
-
}
|
|
3350
|
-
|
|
3351
|
-
// --- 导入文件 (.json / .yaml / .md / .txt / .html) ---
|
|
3352
|
-
const judgmentImportBtn = document.getElementById('judgment-import-btn');
|
|
3353
|
-
const judgmentImportFile = document.getElementById('judgment-import-file');
|
|
3354
|
-
|
|
3355
|
-
function showJudgmentError(msg) {
|
|
3356
|
-
if (!judgmentError) return;
|
|
3357
|
-
judgmentError.textContent = msg;
|
|
3358
|
-
judgmentError.style.display = '';
|
|
3359
|
-
judgmentError.style.color = '#b91c1c';
|
|
3360
|
-
}
|
|
3361
|
-
function showJudgmentOk(msg) {
|
|
3362
|
-
if (!judgmentError) return;
|
|
3363
|
-
judgmentError.textContent = msg;
|
|
3364
|
-
judgmentError.style.display = '';
|
|
3365
|
-
judgmentError.style.color = '#15803d';
|
|
3366
|
-
}
|
|
3367
|
-
|
|
3368
|
-
function fileToBase64(file) {
|
|
3369
|
-
return new Promise((resolve, reject) => {
|
|
3370
|
-
const r = new FileReader();
|
|
3371
|
-
r.onload = () => {
|
|
3372
|
-
// result is "data:<mime>;base64,<payload>" — strip prefix
|
|
3373
|
-
const s = String(r.result || '');
|
|
3374
|
-
const idx = s.indexOf(',');
|
|
3375
|
-
resolve(idx >= 0 ? s.substring(idx + 1) : s);
|
|
3376
|
-
};
|
|
3377
|
-
r.onerror = () => reject(r.error || new Error('read failed'));
|
|
3378
|
-
r.readAsDataURL(file);
|
|
3379
|
-
});
|
|
3380
|
-
}
|
|
3381
|
-
|
|
3382
|
-
async function importJudgmentFile(file) {
|
|
3383
|
-
if (!file) return;
|
|
3384
|
-
if (judgmentImportBtn) judgmentImportBtn.disabled = true;
|
|
3385
|
-
try {
|
|
3386
|
-
const content = await fileToBase64(file);
|
|
3387
|
-
const res = await fetch('/api/judgments/import', {
|
|
3388
|
-
method: 'POST',
|
|
3389
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3390
|
-
body: JSON.stringify({ filename: file.name, content }),
|
|
3391
|
-
});
|
|
3392
|
-
const out = await res.json();
|
|
3393
|
-
if (!out.ok) throw new Error(out.error || 'import failed');
|
|
3394
|
-
showJudgmentOk(`✓ 导入 ${out.imported} 条${out.failed ? `, ${out.failed} 条失败` : ''}`);
|
|
3395
|
-
await loadJudgments();
|
|
3396
|
-
} catch (e) {
|
|
3397
|
-
showJudgmentError('导入失败: ' + e.message);
|
|
3398
|
-
} finally {
|
|
3399
|
-
if (judgmentImportBtn) judgmentImportBtn.disabled = false;
|
|
3400
|
-
if (judgmentImportFile) judgmentImportFile.value = '';
|
|
3401
|
-
}
|
|
3402
|
-
}
|
|
3403
|
-
|
|
3404
|
-
if (judgmentImportBtn) {
|
|
3405
|
-
judgmentImportBtn.addEventListener('click', () => {
|
|
3406
|
-
if (judgmentImportFile) judgmentImportFile.click();
|
|
3407
|
-
});
|
|
3408
|
-
}
|
|
3409
|
-
if (judgmentImportFile) {
|
|
3410
|
-
judgmentImportFile.addEventListener('change', (e) => {
|
|
3411
|
-
const f = e.target.files && e.target.files[0];
|
|
3412
|
-
if (f) importJudgmentFile(f);
|
|
3413
|
-
});
|
|
3414
|
-
}
|
|
3415
|
-
|
|
3416
|
-
// --- 从对话里 "蒸馏为判断": 事件委托到消息容器, 匹配 .save-as-judgment ---
|
|
3417
|
-
// 两条路径:
|
|
3418
|
-
// 1. 有 data-channel-id → 调 /api/judgments/distill-from-conversation (B 触发, AI 蒸馏 + 演化对齐)
|
|
3419
|
-
// 2. 没有 channelId (老按钮 / 历史数据) → fallback 到老 /api/judgments (直存)
|
|
3420
|
-
document.addEventListener('click', async (e) => {
|
|
3421
|
-
const btn = e.target.closest && e.target.closest('.save-as-judgment');
|
|
3422
|
-
if (!btn) return;
|
|
3423
|
-
e.preventDefault();
|
|
3424
|
-
e.stopPropagation();
|
|
3425
|
-
|
|
3426
|
-
const channelId = btn.getAttribute('data-channel-id');
|
|
3427
|
-
const decision = (btn.getAttribute('data-decision') || '').trim();
|
|
3428
|
-
|
|
3429
|
-
if (channelId) {
|
|
3430
|
-
btn.classList.add('loading');
|
|
3431
|
-
btn.disabled = true;
|
|
3432
|
-
try {
|
|
3433
|
-
const res = await fetch('/api/judgments/distill-from-conversation', {
|
|
3434
|
-
method: 'POST',
|
|
3435
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3436
|
-
body: JSON.stringify({ channelId }),
|
|
3437
|
-
});
|
|
3438
|
-
const out = await res.json();
|
|
3439
|
-
if (!res.ok) throw new Error(out.error || 'HTTP ' + res.status);
|
|
3440
|
-
|
|
3441
|
-
if (!out.triggered) {
|
|
3442
|
-
btn.classList.remove('loading');
|
|
3443
|
-
btn.disabled = false;
|
|
3444
|
-
btn.title = '蒸馏失败: ' + (out.reason || '无内容');
|
|
3445
|
-
return;
|
|
3446
|
-
}
|
|
3447
|
-
|
|
3448
|
-
const j = out.judgment;
|
|
3449
|
-
const ev = out.evolved || { merged: 0, superseded: 0 };
|
|
3450
|
-
btn.classList.remove('loading');
|
|
3451
|
-
btn.classList.add('saved');
|
|
3452
|
-
btn.title = '已蒸馏为判断';
|
|
3453
|
-
|
|
3454
|
-
// inline 确认弹框 (在按钮下方出现, 5 秒后自动消失)
|
|
3455
|
-
showDistillConfirm(btn, {
|
|
3456
|
-
value: j.decision,
|
|
3457
|
-
evidence: (j.reasons && j.reasons[0]) || '',
|
|
3458
|
-
merged: ev.merged,
|
|
3459
|
-
superseded: ev.superseded,
|
|
3460
|
-
onEdit: async (newText) => {
|
|
3461
|
-
try {
|
|
3462
|
-
await fetch('/api/judgments/' + encodeURIComponent(j.id), {
|
|
3463
|
-
method: 'PATCH',
|
|
3464
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3465
|
-
body: JSON.stringify({ decision: newText }),
|
|
3466
|
-
});
|
|
3467
|
-
} catch (err) {
|
|
3468
|
-
console.error('[judgments] edit failed:', err);
|
|
3469
|
-
}
|
|
3470
|
-
},
|
|
3471
|
-
onReject: async () => {
|
|
3472
|
-
try {
|
|
3473
|
-
await fetch('/api/judgments/' + encodeURIComponent(j.id), {
|
|
3474
|
-
method: 'DELETE',
|
|
3475
|
-
});
|
|
3476
|
-
} catch (err) {
|
|
3477
|
-
console.error('[judgments] reject failed:', err);
|
|
3478
|
-
}
|
|
3479
|
-
},
|
|
3480
|
-
});
|
|
3481
|
-
|
|
3482
|
-
// 刷新判断力库缓存
|
|
3483
|
-
setTimeout(() => loadJudgments(), 100);
|
|
3484
|
-
} catch (err) {
|
|
3485
|
-
console.error('[judgments] distill-from-chat failed:', err);
|
|
3486
|
-
btn.classList.remove('loading');
|
|
3487
|
-
btn.disabled = false;
|
|
3488
|
-
btn.title = '蒸馏失败: ' + err.message;
|
|
3489
|
-
}
|
|
3490
|
-
return;
|
|
3491
|
-
}
|
|
3492
|
-
|
|
3493
|
-
// 老路径 fallback (没有 channelId, 直接存原文)
|
|
3494
|
-
if (!decision) return;
|
|
3495
|
-
try {
|
|
3496
|
-
const res = await fetch('/api/judgments', {
|
|
3497
|
-
method: 'POST',
|
|
3498
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3499
|
-
body: JSON.stringify({ decision, reason: '从对话保存' }),
|
|
3500
|
-
});
|
|
3501
|
-
const out = await res.json();
|
|
3502
|
-
if (!out.ok) throw new Error(out.error || 'failed');
|
|
3503
|
-
btn.classList.add('saved');
|
|
3504
|
-
btn.title = '已存为判断';
|
|
3505
|
-
} catch (err) {
|
|
3506
|
-
console.error('[judgments] save-from-chat failed:', err);
|
|
3507
|
-
btn.title = '保存失败: ' + err.message;
|
|
3508
|
-
}
|
|
3509
|
-
});
|
|
3510
|
-
|
|
3511
|
-
/**
|
|
3512
|
-
* inline 蒸馏确认弹框 — 在按钮下方出现, 显示凝练结果 + 演化结果
|
|
3513
|
-
* 5 秒后自动消失, 用户可点 "编辑" / "拒绝"
|
|
3514
|
-
*/
|
|
3515
|
-
function showDistillConfirm(btn, opts) {
|
|
3516
|
-
const { value, evidence, merged, superseded, onEdit, onReject } = opts;
|
|
3517
|
-
const old = document.getElementById('distill-confirm-popup');
|
|
3518
|
-
if (old) old.remove();
|
|
3519
|
-
|
|
3520
|
-
const popup = document.createElement('div');
|
|
3521
|
-
popup.id = 'distill-confirm-popup';
|
|
3522
|
-
popup.style.cssText = `
|
|
3523
|
-
position:absolute; z-index:1000;
|
|
3524
|
-
background:#fff; border:1px solid #d1d5db; border-radius:6px;
|
|
3525
|
-
box-shadow:0 4px 12px rgba(0,0,0,0.1);
|
|
3526
|
-
padding:10px 12px; min-width:280px; max-width:380px;
|
|
3527
|
-
font-size:13px; color:#1f2937;
|
|
3528
|
-
`;
|
|
3529
|
-
let evolveNote = '';
|
|
3530
|
-
if (merged > 0 || superseded > 0) {
|
|
3531
|
-
evolveNote = `<div style="font-size:11px;color:#059669;margin-top:6px;">✓ 演化对齐: ${merged} 条已合并${superseded > 0 ? `, ${superseded} 条已淘汰` : ''}</div>`;
|
|
3532
|
-
}
|
|
3533
|
-
popup.innerHTML = `
|
|
3534
|
-
<div style="font-weight:600;margin-bottom:4px;">已蒸馏为判断力</div>
|
|
3535
|
-
<div style="background:#f9fafb;padding:6px 8px;border-radius:4px;line-height:1.4;">${escapeHtml(value)}</div>
|
|
3536
|
-
${evidence ? `<div style="font-size:11px;color:#6b7280;margin-top:4px;">证据: ${escapeHtml(evidence)}</div>` : ''}
|
|
3537
|
-
${evolveNote}
|
|
3538
|
-
<div style="display:flex;gap:6px;margin-top:8px;">
|
|
3539
|
-
<button class="dc-edit" style="background:none;border:1px solid #d1d5db;color:#374151;padding:2px 10px;border-radius:3px;cursor:pointer;font-size:11px;">编辑</button>
|
|
3540
|
-
<button class="dc-reject" style="background:none;border:1px solid #fca5a5;color:#b91c1c;padding:2px 10px;border-radius:3px;cursor:pointer;font-size:11px;">拒绝</button>
|
|
3541
|
-
<button class="dc-close" style="margin-left:auto;background:none;border:none;color:#6b7280;cursor:pointer;font-size:14px;">×</button>
|
|
3542
|
-
</div>
|
|
3543
|
-
`;
|
|
3544
|
-
|
|
3545
|
-
// 定位
|
|
3546
|
-
const rect = btn.getBoundingClientRect();
|
|
3547
|
-
popup.style.top = (window.scrollY + rect.bottom + 4) + 'px';
|
|
3548
|
-
popup.style.left = (window.scrollX + rect.left) + 'px';
|
|
3549
|
-
document.body.appendChild(popup);
|
|
3550
|
-
|
|
3551
|
-
// 绑定按钮
|
|
3552
|
-
popup.querySelector('.dc-edit').onclick = () => {
|
|
3553
|
-
const newText = prompt('编辑判断力:', value);
|
|
3554
|
-
if (newText && newText.trim() && onEdit) onEdit(newText.trim());
|
|
3555
|
-
popup.remove();
|
|
3556
|
-
};
|
|
3557
|
-
popup.querySelector('.dc-reject').onclick = () => {
|
|
3558
|
-
if (onReject) onReject();
|
|
3559
|
-
popup.remove();
|
|
3560
|
-
};
|
|
3561
|
-
popup.querySelector('.dc-close').onclick = () => popup.remove();
|
|
3562
|
-
setTimeout(() => popup.remove(), 5000);
|
|
3563
|
-
}
|
|
3564
|
-
if (judgmentSubmitBtn) judgmentSubmitBtn.addEventListener('click', submitJudgment);
|
|
3565
|
-
|
|
3566
|
-
// 启动时拉一次, 让徽章显示总数 (不打开 modal 也能看到)
|
|
3567
|
-
loadJudgments();
|
|
3568
|
-
// 后台定期刷新 (与 modal 打开/关闭无关, 任何时候都保持徽章新鲜)
|
|
3569
|
-
setInterval(loadJudgments, 10000);
|
|
3570
|
-
|
|
3571
|
-
// ============================================================================
|
|
3572
|
-
// v3: P2P 好友 (known peers) + 收到的分享
|
|
3573
|
-
// ============================================================================
|
|
3574
|
-
|
|
3575
|
-
let knownPeers = []; // { name, publicKey, lastConnectedAt, addedAt }
|
|
3576
|
-
|
|
3577
|
-
async function loadRemoteChannels() {
|
|
3578
|
-
try {
|
|
3579
|
-
// 1) 拉 known peers (好友列表)
|
|
3580
|
-
const res = await fetch('/api/p2p-peers');
|
|
3581
|
-
if (res.ok) {
|
|
3582
|
-
const data = await res.json();
|
|
3583
|
-
knownPeers = Array.isArray(data.peers) ? data.peers : [];
|
|
3584
|
-
}
|
|
3585
|
-
// 2) 2026-06-10 修: 同时拉 /api/remote-channels, 兜底 SSE 推送漏掉的情况
|
|
3586
|
-
// (页面刷新后 remoteChannels[] = [], 必须主动拉一次才有数据)
|
|
3587
|
-
const r2 = await fetch('/api/remote-channels');
|
|
3588
|
-
if (r2.ok) {
|
|
3589
|
-
const data2 = await r2.json();
|
|
3590
|
-
const peers = Array.isArray(data2.peers) ? data2.peers : [];
|
|
3591
|
-
// 合并到 remoteChannels[]: 按 peerId 覆盖
|
|
3592
|
-
for (const p of peers) {
|
|
3593
|
-
let group = remoteChannels.find(g => g.peerId === p.peerId);
|
|
3594
|
-
if (!group) {
|
|
3595
|
-
group = { peerId: p.peerId, channels: [], peerName: ('peer-' + p.peerId.substring(0, 8)) };
|
|
3596
|
-
remoteChannels.push(group);
|
|
3597
|
-
}
|
|
3598
|
-
group.channels = p.channels || [];
|
|
3599
|
-
}
|
|
3600
|
-
}
|
|
3601
|
-
renderRemoteChannels();
|
|
3602
|
-
// 3) 远端数据可能变化, 同步 @-mention 列表
|
|
3603
|
-
if (typeof refreshMentionChannels === 'function') {
|
|
3604
|
-
refreshMentionChannels();
|
|
3605
|
-
}
|
|
3606
|
-
} catch (err) {
|
|
3607
|
-
console.error('[v3] loadRemoteChannels 失败:', err);
|
|
3608
|
-
}
|
|
3609
|
-
}
|
|
3610
|
-
|
|
3611
|
-
function renderRemoteChannels() {
|
|
3612
|
-
const list = document.getElementById('remote-channel-list');
|
|
3613
|
-
if (!list) return;
|
|
3614
|
-
|
|
3615
|
-
// 按 peerId 分组 channels
|
|
3616
|
-
const channelsByPeer = {};
|
|
3617
|
-
for (const p of remoteChannels) {
|
|
3618
|
-
channelsByPeer[p.peerId] = p.channels || [];
|
|
3619
|
-
}
|
|
3620
|
-
|
|
3621
|
-
// 2026-06-10 修: 之前 UI 只渲染 knownPeers, 但对面 publicKey 可能跟本机 known_peers 不匹配
|
|
3622
|
-
// (例如对面重启 / 换 role / 第一次相连还没加为好友), 导致 remoteChannels 里有数据 UI 却空白.
|
|
3623
|
-
// 修法: 把 remoteChannels 里的 "陌生 peer" (不在 known_peers 里) 也渲染出来, 标记为未加好友.
|
|
3624
|
-
const knownPks = new Set(knownPeers.map(p => p.publicKey));
|
|
3625
|
-
const strangerPeers = remoteChannels
|
|
3626
|
-
.filter(p => !knownPks.has(p.peerId))
|
|
3627
|
-
.map(p => ({
|
|
3628
|
-
publicKey: p.peerId,
|
|
3629
|
-
name: p.peerName || ('未授权 ' + p.peerId.substring(0, 8)),
|
|
3630
|
-
lastConnectedAt: null,
|
|
3631
|
-
_isStranger: true
|
|
3632
|
-
}));
|
|
3633
|
-
const allPeers = [...knownPeers, ...strangerPeers];
|
|
3634
|
-
|
|
3635
|
-
if (allPeers.length === 0) {
|
|
3636
|
-
list.innerHTML = '<li style="color:var(--text-muted);font-size:11px;padding:8px 4px;text-align:center;">(暂无好友, 点 + 添加)</li>';
|
|
3637
|
-
return;
|
|
3638
|
-
}
|
|
3639
|
-
|
|
3640
|
-
const html = allPeers.map(peer => {
|
|
3641
|
-
const peerChannels = channelsByPeer[peer.publicKey] || [];
|
|
3642
|
-
const lastConn = peer.lastConnectedAt
|
|
3643
|
-
? new Date(peer.lastConnectedAt).toLocaleDateString()
|
|
3644
|
-
: (peer._isStranger ? '陌生 peer' : '从未连接');
|
|
3645
|
-
const strangerStyle = peer._isStranger ? 'border:1px dashed var(--border-light);' : '';
|
|
3646
|
-
const strangerIcon = peer._isStranger ? '❔' : '👤';
|
|
3647
|
-
// 2026-06-11: 折叠逻辑 (全不展开)
|
|
3648
|
-
// - 所有 peer 首次见都默认 *折叠* (包括 known_peers 第一个) — 用户一进来看到完整 peer 列表
|
|
3649
|
-
// - 标题栏右侧 "X ch" 提示有内容, 用户点 caret 展开
|
|
3650
|
-
// - 已见过: 沿用 collapsedPeers (用户上次选择)
|
|
3651
|
-
// - "全部展开/折叠" 按钮在 P2P header (id=p2p-toggle-all-btn)
|
|
3652
|
-
if (!seenPeers.has(peer.publicKey)) {
|
|
3653
|
-
seenPeers.add(peer.publicKey);
|
|
3654
|
-
collapsedPeers.add(peer.publicKey); // 全部默认折叠
|
|
3655
|
-
saveSeenPeers();
|
|
3656
|
-
saveCollapsedPeers();
|
|
3657
|
-
}
|
|
3658
|
-
const isCollapsed = collapsedPeers.has(peer.publicKey);
|
|
3659
|
-
const caretChar = '▾'; // CSS rotate -90deg 处理折叠态
|
|
3660
|
-
return `
|
|
3661
|
-
<li class="remote-peer-group ${isCollapsed ? 'collapsed' : ''}" style="margin-bottom:10px;${strangerStyle}">
|
|
3662
|
-
<div class="remote-peer-header" data-peer-name="${escapeHtml(peer.name)}" data-peer-pk="${escapeHtml(peer.publicKey)}"
|
|
3663
|
-
style="display:flex;align-items:center;gap:6px;padding:6px 8px;background:var(--bg-hover);border-radius:4px;cursor:pointer;">
|
|
3664
|
-
<button class="peer-caret-btn" data-toggle-peer="${escapeHtml(peer.publicKey)}" title="折叠/展开"
|
|
3665
|
-
style="background:var(--bg-active);border:1px solid var(--border);color:var(--text);cursor:pointer;width:22px;height:22px;border-radius:4px;font-size:12px;line-height:1;padding:0;display:flex;align-items:center;justify-content:center;flex:0 0 auto;">${caretChar}</button>
|
|
3666
|
-
<span style="font-size:13px;">${strangerIcon}</span>
|
|
3667
|
-
<span style="flex:1;font-size:12px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${escapeHtml(peer.publicKey)}">${escapeHtml(peer.name)}</span>
|
|
3668
|
-
<span style="font-size:9px;color:var(--text-muted);">${peerChannels.length > 0 ? `${peerChannels.length} ch · ` : ''}${lastConn}</span>
|
|
3669
|
-
</div>
|
|
3670
|
-
<div class="remote-peer-channels" style="margin-top:4px;margin-left:8px;">
|
|
3671
|
-
${peerChannels.length === 0
|
|
3672
|
-
? '<div style="font-size:10px;color:var(--text-muted);padding:2px 4px;">(对方还没分享 channel 给你)</div>'
|
|
3673
|
-
: peerChannels.map(c => `
|
|
3674
|
-
<div class="remote-channel-row" data-peer-id="${escapeHtml(peer.publicKey)}" data-channel-id="${escapeHtml(c.id)}"
|
|
3675
|
-
style="display:flex;align-items:center;gap:6px;padding:4px 6px;cursor:pointer;border-radius:4px;font-size:12px;">
|
|
3676
|
-
<span>🤖</span>
|
|
3677
|
-
<span style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${escapeHtml(c.name || '')}">${escapeHtml(c.name || '(未命名)')}</span>
|
|
3678
|
-
</div>
|
|
3679
|
-
`).join('')
|
|
3680
|
-
}
|
|
3681
|
-
</div>
|
|
3682
|
-
</li>
|
|
3683
|
-
`;
|
|
3684
|
-
}).join('');
|
|
3685
|
-
list.innerHTML = html;
|
|
3686
|
-
|
|
3687
|
-
// 2026-06-10: 折叠按钮点击 → 切折叠 (stopPropagation 防止冒泡触发 header 的分享 modal)
|
|
3688
|
-
list.querySelectorAll('.peer-caret-btn[data-toggle-peer]').forEach(btn => {
|
|
3689
|
-
btn.addEventListener('click', (e) => {
|
|
3690
|
-
e.stopPropagation();
|
|
3691
|
-
const pk = btn.getAttribute('data-toggle-peer');
|
|
3692
|
-
togglePeerCollapsed(pk);
|
|
3693
|
-
});
|
|
3694
|
-
});
|
|
3695
|
-
|
|
3696
|
-
// 绑定: 点击 channel → 弹聊天窗口
|
|
3697
|
-
list.querySelectorAll('.remote-channel-row').forEach(row => {
|
|
3698
|
-
row.addEventListener('click', () => {
|
|
3699
|
-
const peerId = row.dataset.peerId;
|
|
3700
|
-
const channelId = row.dataset.channelId;
|
|
3701
|
-
const channelName = row.querySelector('span[title]')?.getAttribute('title') || channelId;
|
|
3702
|
-
console.log('[v3] 点击远端 channel:', peerId.substring(0,12), channelId);
|
|
3703
|
-
openRemoteChannelChat(peerId, channelId, channelName);
|
|
3704
|
-
});
|
|
3705
|
-
});
|
|
3706
|
-
// 绑定: 点击 peer 头部 → 弹分享 modal (让 A 决定分享本机哪些 channel 给这个 peer)
|
|
3707
|
-
list.querySelectorAll('.remote-peer-header').forEach(row => {
|
|
3708
|
-
row.addEventListener('click', (e) => {
|
|
3709
|
-
// 2026-06-10: 防御 — 点 caret 时已 stopPropagation, 但万一冒泡逃逸再挡一道
|
|
3710
|
-
if (e.target.closest('.peer-caret')) return;
|
|
3711
|
-
const peerName = row.dataset.peerName;
|
|
3712
|
-
const peerPk = row.dataset.peerPk;
|
|
3713
|
-
openShareToPeerModal(peerName, peerPk);
|
|
3714
|
-
});
|
|
3715
|
-
});
|
|
3716
|
-
|
|
3717
|
-
// 2026-06-10: 每个 peer 头部双击 → 改名字 / 改备注
|
|
3718
|
-
list.querySelectorAll('.remote-peer-header').forEach(row => {
|
|
3719
|
-
row.addEventListener('dblclick', (e) => {
|
|
3720
|
-
if (e.target.closest('.peer-caret-btn')) return;
|
|
3721
|
-
const peerName = row.dataset.peerName;
|
|
3722
|
-
const peerPk = row.dataset.peerPk;
|
|
3723
|
-
openEditPeerModal(peerName, peerPk);
|
|
3724
|
-
});
|
|
3725
|
-
});
|
|
3726
|
-
|
|
3727
|
-
// 2026-06-10: 渲染完成后同步 header 切换按钮图标
|
|
3728
|
-
if (typeof window.__syncP2PToggleAllBtn === 'function') window.__syncP2PToggleAllBtn();
|
|
3729
|
-
}
|
|
3730
|
-
|
|
3731
|
-
/** v3: 改 peer 名字 / 备注 modal (持久化到 known_peers.json) */
|
|
3732
|
-
async function openEditPeerModal(peerName, peerPublicKey) {
|
|
3733
|
-
document.getElementById('edit-peer-modal')?.remove();
|
|
3734
|
-
// 先读 known_peers 拿到现有 notes
|
|
3735
|
-
let currentNotes = '';
|
|
3736
|
-
let currentName = peerName;
|
|
3737
|
-
try {
|
|
3738
|
-
const r = await fetch('/api/p2p-peers');
|
|
3739
|
-
if (r.ok) {
|
|
3740
|
-
const d = await r.json();
|
|
3741
|
-
const entry = (d.peers || []).find(p => p.publicKey === peerPublicKey);
|
|
3742
|
-
if (entry) {
|
|
3743
|
-
currentName = entry.name || peerName;
|
|
3744
|
-
currentNotes = entry.notes || '';
|
|
3745
|
-
}
|
|
3746
|
-
}
|
|
3747
|
-
} catch {}
|
|
3748
|
-
const html = `
|
|
3749
|
-
<div id="edit-peer-modal" class="friend-req-overlay">
|
|
3750
|
-
<div class="friend-req-shell" style="width:520px;">
|
|
3751
|
-
<div class="friend-req-header">
|
|
3752
|
-
<span style="font-size:18px;">✏️</span>
|
|
3753
|
-
<div style="flex:1;min-width:0;">
|
|
3754
|
-
<div class="friend-req-title">编辑好友</div>
|
|
3755
|
-
<div class="friend-req-meta">publicKey: ${escapeHtml(peerPublicKey.substring(0,16))}…</div>
|
|
3756
|
-
</div>
|
|
3757
|
-
</div>
|
|
3758
|
-
<div class="friend-req-body">
|
|
3759
|
-
<label style="display:block;margin-bottom:6px;font-size:12px;color:var(--text-secondary);">显示名字</label>
|
|
3760
|
-
<input id="epm-name" type="text" value="${escapeHtml(currentName)}"
|
|
3761
|
-
style="width:100%;padding:8px 10px;border:1px solid var(--border);border-radius:4px;background:var(--bg-main);color:var(--text);font-family:inherit;font-size:13px;box-sizing:border-box;margin-bottom:12px;">
|
|
3762
|
-
<label style="display:block;margin-bottom:6px;font-size:12px;color:var(--text-secondary);">备注 (自由文本, 例如合作领域 / 怎么认识的)</label>
|
|
3763
|
-
<textarea id="epm-notes" rows="4" placeholder="例如: 2026-06 合作 LLM 代发验证"
|
|
3764
|
-
style="width:100%;padding:8px 10px;border:1px solid var(--border);border-radius:4px;background:var(--bg-main);color:var(--text);font-family:inherit;font-size:13px;box-sizing:border-box;resize:vertical;">${escapeHtml(currentNotes)}</textarea>
|
|
3765
|
-
</div>
|
|
3766
|
-
<div class="friend-req-actions">
|
|
3767
|
-
<button id="epm-cancel" class="friend-req-btn-deny">取消</button>
|
|
3768
|
-
<button id="epm-save" class="friend-req-btn-accept">保存</button>
|
|
3769
|
-
</div>
|
|
3770
|
-
</div>
|
|
3771
|
-
</div>
|
|
3772
|
-
`;
|
|
3773
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
3774
|
-
const close = () => document.getElementById('edit-peer-modal')?.remove();
|
|
3775
|
-
document.getElementById('epm-cancel').onclick = close;
|
|
3776
|
-
document.getElementById('epm-save').onclick = async () => {
|
|
3777
|
-
const newName = document.getElementById('epm-name').value.trim() || currentName;
|
|
3778
|
-
const newNotes = document.getElementById('epm-notes').value;
|
|
3779
|
-
try {
|
|
3780
|
-
const r = await fetch(`/api/p2p-peers/${encodeURIComponent(peerName)}`, {
|
|
3781
|
-
method: 'PATCH',
|
|
3782
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3783
|
-
body: JSON.stringify({ name: newName, notes: newNotes })
|
|
3784
|
-
});
|
|
3785
|
-
const data = await r.json();
|
|
3786
|
-
if (!r.ok) throw new Error(data.error || 'save failed');
|
|
3787
|
-
console.log('[v3] 改 peer 成功:', newName, '备注:', newNotes);
|
|
3788
|
-
showSimpleToast(`✅ 已保存 ${newName}`);
|
|
3789
|
-
close();
|
|
3790
|
-
// 重新拉 known_peers + 远程 channels 重新渲染
|
|
3791
|
-
const r2 = await fetch('/api/p2p-peers');
|
|
3792
|
-
if (r2.ok) {
|
|
3793
|
-
const d2 = await r2.json();
|
|
3794
|
-
knownPeers = Array.isArray(d2.peers) ? d2.peers : [];
|
|
3795
|
-
}
|
|
3796
|
-
renderRemoteChannels();
|
|
3797
|
-
} catch (err) {
|
|
3798
|
-
console.error('[v3] 保存 peer 失败:', err);
|
|
3799
|
-
alert('保存失败: ' + (err.message || err));
|
|
3800
|
-
}
|
|
3801
|
-
};
|
|
3802
|
-
}
|
|
3803
|
-
|
|
3804
|
-
/** v3: 分享 channel 给指定 peer 的 modal (A 侧用) */
|
|
3805
|
-
/** v3: 分享 channel 给指定 peer 的 modal (A 侧用) — 2026-06-11 改用 Step 3 风格 class */
|
|
3806
|
-
async function openShareToPeerModal(peerName, peerPublicKey) {
|
|
3807
|
-
document.getElementById('share-to-peer-modal')?.remove();
|
|
3808
|
-
let allChannels = [];
|
|
3809
|
-
try {
|
|
3810
|
-
const res = await fetch('/channels');
|
|
3811
|
-
if (res.ok) allChannels = await res.json();
|
|
3812
|
-
} catch (err) { console.error('openShareToPeerModal:', err); }
|
|
3813
|
-
const rows = allChannels.length === 0
|
|
3814
|
-
? '<div class="share-modal-empty">还没有 channel</div>'
|
|
3815
|
-
: allChannels.map(ch => {
|
|
3816
|
-
const isShared = Array.isArray(ch.shared_with_peers) && ch.shared_with_peers.includes(peerPublicKey);
|
|
3817
|
-
return `
|
|
3818
|
-
<label class="share-modal-row">
|
|
3819
|
-
<input type="checkbox" data-cid="${escapeHtml(ch.id)}" ${isShared ? 'checked' : ''} class="share-modal-cb">
|
|
3820
|
-
<div class="share-modal-row-info">
|
|
3821
|
-
<div class="share-modal-row-name">${escapeHtml(ch.name)}</div>
|
|
3822
|
-
<div class="share-modal-row-meta">
|
|
3823
|
-
${isShared ? '✓ 已分享' : '未分享'} · ${escapeHtml(ch.id.slice(0, 24))}…
|
|
3824
|
-
</div>
|
|
3825
|
-
</div>
|
|
3826
|
-
</label>
|
|
3827
|
-
`;
|
|
3828
|
-
}).join('');
|
|
3829
|
-
const html = `
|
|
3830
|
-
<div id="share-to-peer-modal" class="friend-req-overlay">
|
|
3831
|
-
<div class="friend-req-shell share-modal-shell">
|
|
3832
|
-
<div class="friend-req-header">
|
|
3833
|
-
<span style="font-size:18px;">📤</span>
|
|
3834
|
-
<div style="flex:1;min-width:0;">
|
|
3835
|
-
<div class="friend-req-title">分享 channel 给 ${escapeHtml(peerName)}</div>
|
|
3836
|
-
<div class="friend-req-meta">${escapeHtml(peerPublicKey.substring(0,16))}…</div>
|
|
3837
|
-
</div>
|
|
3838
|
-
<button id="spm-close" class="friend-req-btn-close">×</button>
|
|
3839
|
-
</div>
|
|
3840
|
-
<div class="share-modal-hint">勾选要分享的 channel, 对方才能看到</div>
|
|
3841
|
-
<div id="spm-list" class="share-modal-list">${rows}</div>
|
|
3842
|
-
<div class="friend-req-actions">
|
|
3843
|
-
<button id="spm-cancel" class="friend-req-btn-deny">取消</button>
|
|
3844
|
-
<button id="spm-save" class="friend-req-btn-accept">保存分享</button>
|
|
3845
|
-
</div>
|
|
3846
|
-
</div>
|
|
3847
|
-
</div>
|
|
3848
|
-
`;
|
|
3849
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
3850
|
-
const overlay = document.getElementById('share-to-peer-modal');
|
|
3851
|
-
document.getElementById('spm-close').onclick = () => overlay.remove();
|
|
3852
|
-
document.getElementById('spm-cancel').onclick = () => overlay.remove();
|
|
3853
|
-
document.getElementById('spm-save').onclick = async () => {
|
|
3854
|
-
const checkedIds = [...overlay.querySelectorAll('input[type=checkbox][data-cid]:checked')].map(el => el.dataset.cid);
|
|
3855
|
-
// 对每个 channel 单独 PATCH — 设 shared_with_peers 为 checked 列表
|
|
3856
|
-
let ok = 0, fail = 0;
|
|
3857
|
-
for (const ch of allChannels) {
|
|
3858
|
-
const shouldShare = checkedIds.includes(ch.id);
|
|
3859
|
-
const wasShared = Array.isArray(ch.shared_with_peers) && ch.shared_with_peers.includes(peerPublicKey);
|
|
3860
|
-
if (shouldShare === wasShared) continue;
|
|
3861
|
-
const newList = (ch.shared_with_peers || []).filter((p) => p !== peerPublicKey);
|
|
3862
|
-
if (shouldShare) newList.push(peerPublicKey);
|
|
3863
|
-
try {
|
|
3864
|
-
const res = await fetch(`/channels/${encodeURIComponent(ch.id)}`, {
|
|
3865
|
-
method: 'PATCH',
|
|
3866
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3867
|
-
body: JSON.stringify({ shared_with_peers: newList })
|
|
3868
|
-
});
|
|
3869
|
-
if (res.ok) ok++; else fail++;
|
|
3870
|
-
} catch { fail++; }
|
|
3871
|
-
}
|
|
3872
|
-
showSimpleToast(`分享更新完成: 成功 ${ok}, 失败 ${fail}`, ok > 0 ? 'info' : (fail > 0 ? 'error' : 'info'));
|
|
3873
|
-
overlay.remove();
|
|
3874
|
-
};
|
|
3875
|
-
}
|
|
3876
|
-
|
|
3877
|
-
/** v3: 跟远端 channel 聊天的简易弹窗
|
|
3878
|
-
* 2026-06-10 重写: UI 完全对齐本地聊天 (复用 addMessage / .messages / .bubble 整套样式),
|
|
3879
|
-
* marked.parse + cleanThink + cleanEnv 自动生效, 不再裸文本.
|
|
3880
|
-
*/
|
|
3881
|
-
function openRemoteChannelChat(peerPublicKey, channelId, channelName) {
|
|
3882
|
-
// 移除已有 modal
|
|
3883
|
-
document.getElementById('remote-chat-modal')?.remove();
|
|
3884
|
-
const html = `
|
|
3885
|
-
<div id="remote-chat-modal" class="remote-chat-overlay">
|
|
3886
|
-
<div class="remote-chat-shell">
|
|
3887
|
-
<div class="remote-chat-header">
|
|
3888
|
-
<div style="flex:1;min-width:0;">
|
|
3889
|
-
<div class="remote-chat-title">🌐 跟 ${escapeHtml(channelName)} 聊天</div>
|
|
3890
|
-
<div class="remote-chat-meta">远端 peer: ${escapeHtml(peerPublicKey.substring(0,16))}… · ${escapeHtml(channelId)}</div>
|
|
3891
|
-
</div>
|
|
3892
|
-
<button id="rcm-refresh-history" title="重新拉历史" class="remote-chat-btn-secondary">↻ 历史</button>
|
|
3893
|
-
<button id="rcm-close" class="remote-chat-btn-close">×</button>
|
|
3894
|
-
</div>
|
|
3895
|
-
<div id="rcm-thinking" class="remote-chat-thinking" style="display:none;">
|
|
3896
|
-
📥 正在从远端拉历史 + 判断力…
|
|
3897
|
-
</div>
|
|
3898
|
-
<div id="rcm-log" class="messages remote-chat-log"></div>
|
|
3899
|
-
<div class="remote-chat-input-row">
|
|
3900
|
-
<input id="rcm-input" type="text" placeholder="输入消息, 发送到远端 channel..." class="remote-chat-input">
|
|
3901
|
-
<button id="rcm-send" class="remote-chat-btn-send">发送</button>
|
|
3902
|
-
</div>
|
|
3903
|
-
</div>
|
|
3904
|
-
</div>
|
|
3905
|
-
`;
|
|
3906
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
3907
|
-
|
|
3908
|
-
const log = document.getElementById('rcm-log');
|
|
3909
|
-
const inputEl = document.getElementById('rcm-input');
|
|
3910
|
-
const sendBtn = document.getElementById('rcm-send');
|
|
3911
|
-
const thinkingEl = document.getElementById('rcm-thinking');
|
|
3912
|
-
let historyRefreshTimer = null;
|
|
3913
|
-
document.getElementById('rcm-close').onclick = () => {
|
|
3914
|
-
if (historyRefreshTimer) { clearInterval(historyRefreshTimer); historyRefreshTimer = null; }
|
|
3915
|
-
document.getElementById('remote-chat-modal').remove();
|
|
3916
|
-
};
|
|
3917
|
-
document.getElementById('rcm-refresh-history').onclick = () => loadHistory(false);
|
|
3918
|
-
|
|
3919
|
-
// 2026-06-10 改: 直接复用本地 addMessage, 自动获得 marked + think 折叠 + env 折叠 + 主题变量
|
|
3920
|
-
const append = (text, role) => {
|
|
3921
|
-
addMessage(text, role === 'user' ? 'user' : 'ai', false, log);
|
|
3922
|
-
log.scrollTop = log.scrollHeight;
|
|
3923
|
-
};
|
|
3924
|
-
|
|
3925
|
-
// 系统提示用更轻量的样式 (不走 addMessage, 避免被当聊天记录裁剪)
|
|
3926
|
-
const appendSystem = (text, kind = 'info') => {
|
|
3927
|
-
const el = document.createElement('div');
|
|
3928
|
-
el.className = `remote-chat-sysmsg remote-chat-sysmsg-${kind}`;
|
|
3929
|
-
el.textContent = text;
|
|
3930
|
-
log.appendChild(el);
|
|
3931
|
-
log.scrollTop = log.scrollHeight;
|
|
3932
|
-
};
|
|
3933
|
-
|
|
3934
|
-
// v3 新增: 拉 A 端的 channel 历史 (含 messages + judgments)
|
|
3935
|
-
async function loadHistory(isSilent) {
|
|
3936
|
-
if (!document.getElementById('remote-chat-modal')) return; // modal 已关闭
|
|
3937
|
-
|
|
3938
|
-
if (isSilent) {
|
|
3939
|
-
try {
|
|
3940
|
-
const res = await fetch(`/api/remote-channels/chat-history?targetPublicKey=${encodeURIComponent(peerPublicKey)}&channelId=${encodeURIComponent(channelId)}`);
|
|
3941
|
-
if (!res.ok || !document.getElementById('remote-chat-modal')) return;
|
|
3942
|
-
const data = await res.json();
|
|
3943
|
-
const newMsgs = data.messages || [];
|
|
3944
|
-
const oldCount = log.querySelectorAll('.message').length;
|
|
3945
|
-
if (newMsgs.length === oldCount) return;
|
|
3946
|
-
const scrollWasAtBottom = log.scrollTop + log.clientHeight >= log.scrollHeight - 30;
|
|
3947
|
-
renderHistory(data);
|
|
3948
|
-
if (scrollWasAtBottom) {
|
|
3949
|
-
setTimeout(() => { log.scrollTop = log.scrollHeight; }, 50);
|
|
3950
|
-
}
|
|
3951
|
-
} catch (_) { /* 静默失败 */ }
|
|
3952
|
-
return;
|
|
3953
|
-
}
|
|
3954
|
-
|
|
3955
|
-
thinkingEl.style.display = 'block';
|
|
3956
|
-
log.innerHTML = '';
|
|
3957
|
-
try {
|
|
3958
|
-
const res = await fetch(`/api/remote-channels/chat-history?targetPublicKey=${encodeURIComponent(peerPublicKey)}&channelId=${encodeURIComponent(channelId)}`);
|
|
3959
|
-
const data = await res.json();
|
|
3960
|
-
if (!res.ok) {
|
|
3961
|
-
appendSystem(`拉取失败: ${data.error || 'unknown'}`, 'error');
|
|
3962
|
-
thinkingEl.style.display = 'none';
|
|
3963
|
-
return;
|
|
3964
|
-
}
|
|
3965
|
-
renderHistory(data);
|
|
3966
|
-
} catch (err) {
|
|
3967
|
-
appendSystem(`拉取异常: ${err.message}`, 'error');
|
|
3968
|
-
} finally {
|
|
3969
|
-
thinkingEl.style.display = 'none';
|
|
3970
|
-
}
|
|
3971
|
-
}
|
|
3972
|
-
|
|
3973
|
-
function renderHistory(data) {
|
|
3974
|
-
log.innerHTML = '';
|
|
3975
|
-
|
|
3976
|
-
// 1. 显示 judgment 依据 (header) — 保留, 但用 class 化样式
|
|
3977
|
-
const judgments = data.judgments || { bound: [], candidates: [] };
|
|
3978
|
-
if (judgments.bound && judgments.bound.length > 0) {
|
|
3979
|
-
const jh = document.createElement('div');
|
|
3980
|
-
jh.className = 'remote-chat-judgments';
|
|
3981
|
-
let h = `<div class="remote-chat-judgments-title">🛡️ 对方 channel 绑定的判断力 (${judgments.bound.length} 条硬约束)</div>`;
|
|
3982
|
-
for (const j of judgments.bound) {
|
|
3983
|
-
h += `<div class="remote-chat-judgment-item">• <b>${escapeHtml((j.decision || '').slice(0, 100))}</b>${j.domain ? `<span class="remote-chat-judgment-tag"> [${escapeHtml(j.domain)}${j.stakes ? '/' + escapeHtml(j.stakes) : ''}]</span>` : ''}${j.reasons && j.reasons.length ? '<br><span class="remote-chat-judgment-reason">理由: ' + escapeHtml(j.reasons.join('; ').slice(0, 100)) + '</span>' : ''}</div>`;
|
|
3984
|
-
}
|
|
3985
|
-
if (judgments.candidates && judgments.candidates.length > 0) {
|
|
3986
|
-
h += `<div class="remote-chat-judgments-foot">+ ${judgments.candidates.length} 条候选判断力 (LLM 可自选参考)</div>`;
|
|
3987
|
-
}
|
|
3988
|
-
jh.innerHTML = h;
|
|
3989
|
-
log.appendChild(jh);
|
|
3990
|
-
}
|
|
3991
|
-
|
|
3992
|
-
// 2. 显示历史 messages — 完全复用本地 addMessage 渲染
|
|
3993
|
-
const msgs = data.messages || [];
|
|
3994
|
-
if (msgs.length === 0) {
|
|
3995
|
-
appendSystem('还没有历史消息, 在下面发第一条吧', 'info');
|
|
3996
|
-
} else {
|
|
3997
|
-
for (const m of msgs) {
|
|
3998
|
-
// 远端 owner 的 user 消息 vs 远端访客 (B) 的 user 消息 vs A 的 LLM 回复
|
|
3999
|
-
// 全部走 addMessage, 让 marked/think/env 自动处理. 来源用一个小 prefix 标记.
|
|
4000
|
-
const type = m.type === 'user' ? 'user' : 'ai';
|
|
4001
|
-
let prefix = '';
|
|
4002
|
-
if (m.type === 'user') {
|
|
4003
|
-
if (m.source === 'remote') {
|
|
4004
|
-
prefix = `🌐 远端访客${m.fromPublicKey ? ' (' + m.fromPublicKey.substring(0, 8) + '…)' : ''}\n\n`;
|
|
4005
|
-
} else {
|
|
4006
|
-
prefix = `👤 A (内部 owner)\n\n`;
|
|
4007
|
-
}
|
|
4008
|
-
} else {
|
|
4009
|
-
prefix = `🤖 A 的 LLM\n\n`;
|
|
4010
|
-
}
|
|
4011
|
-
addMessage(prefix + (m.content || ''), type, false, log);
|
|
4012
|
-
}
|
|
4013
|
-
setTimeout(() => { log.scrollTop = log.scrollHeight; }, 50);
|
|
4014
|
-
}
|
|
4015
|
-
}
|
|
4016
|
-
|
|
4017
|
-
const doSend = async () => {
|
|
4018
|
-
const text = inputEl.value.trim();
|
|
4019
|
-
if (!text) return;
|
|
4020
|
-
append(text, 'user');
|
|
4021
|
-
inputEl.value = '';
|
|
4022
|
-
sendBtn.disabled = true;
|
|
4023
|
-
sendBtn.textContent = '...';
|
|
4024
|
-
try {
|
|
4025
|
-
const res = await fetch('/api/remote-channels/chat-send', {
|
|
4026
|
-
method: 'POST',
|
|
4027
|
-
headers: { 'Content-Type': 'application/json' },
|
|
4028
|
-
body: JSON.stringify({ targetPublicKey: peerPublicKey, channelId, text })
|
|
4029
|
-
});
|
|
4030
|
-
const data = await res.json();
|
|
4031
|
-
if (!res.ok) throw new Error(data.error || 'send failed');
|
|
4032
|
-
// 不再 appendSystem('已发送...') —— 用户看到自己消息已上屏就知道, 系统提示是噪音
|
|
4033
|
-
} catch (err) {
|
|
4034
|
-
appendSystem('发送失败: ' + (err.message || err), 'error');
|
|
4035
|
-
} finally {
|
|
4036
|
-
sendBtn.disabled = false;
|
|
4037
|
-
sendBtn.textContent = '发送';
|
|
4038
|
-
}
|
|
4039
|
-
};
|
|
4040
|
-
sendBtn.onclick = doSend;
|
|
4041
|
-
inputEl.onkeydown = (e) => { if (e.key === 'Enter') doSend(); };
|
|
4042
|
-
// v3 新增: B 端远端 chat 也支持 @-autocomplete
|
|
4043
|
-
setupMentionAutocomplete(inputEl);
|
|
4044
|
-
inputEl.focus();
|
|
4045
|
-
startV3GlobalSSE();
|
|
4046
|
-
|
|
4047
|
-
// 打开时立即拉历史
|
|
4048
|
-
loadHistory(false);
|
|
4049
|
-
|
|
4050
|
-
// 每 15 秒自动静默刷新, 同步远端 owner 或其他访客的新消息
|
|
4051
|
-
historyRefreshTimer = setInterval(() => loadHistory(true), 15000);
|
|
4052
|
-
}
|
|
4053
|
-
|
|
4054
|
-
// Phase 3: 我的 ID 按钮 → 真 modal (避免 confirm 在某些环境被禁用)
|
|
4055
|
-
const showMyIdBtn = document.getElementById('show-my-p2p-id-btn');
|
|
4056
|
-
if (showMyIdBtn) {
|
|
4057
|
-
showMyIdBtn.addEventListener('click', async (e) => {
|
|
4058
|
-
e.stopPropagation();
|
|
4059
|
-
// 移除已有 modal
|
|
4060
|
-
document.getElementById('my-p2p-id-modal')?.remove();
|
|
4061
|
-
// 立即弹出 loading 状态 modal
|
|
4062
|
-
const html = `
|
|
4063
|
-
<div id="my-p2p-id-modal" style="position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:10003;display:flex;align-items:center;justify-content:center;">
|
|
4064
|
-
<div style="background:#fff;border-radius:8px;width:480px;max-width:92vw;display:flex;flex-direction:column;box-shadow:0 10px 40px rgba(0,0,0,0.2);">
|
|
4065
|
-
<div style="padding:14px 18px;border-bottom:1px solid #e5e7eb;display:flex;align-items:center;justify-content:space-between;">
|
|
4066
|
-
<div style="font-size:15px;font-weight:600;">🪪 我的 P2P 身份</div>
|
|
4067
|
-
<button id="mpim-close" style="background:none;border:none;font-size:20px;color:#6b7280;cursor:pointer;">×</button>
|
|
4068
|
-
</div>
|
|
4069
|
-
<div id="mpim-body" style="padding:16px 18px;">
|
|
4070
|
-
<div style="color:#6b7280;font-size:13px;margin-bottom:10px;">正在获取 publicKey…</div>
|
|
4071
|
-
</div>
|
|
4072
|
-
</div>
|
|
4073
|
-
</div>
|
|
4074
|
-
`;
|
|
4075
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
4076
|
-
document.getElementById('mpim-close').onclick = () => document.getElementById('my-p2p-id-modal').remove();
|
|
4077
|
-
|
|
4078
|
-
try {
|
|
4079
|
-
const res = await fetch('/api/p2p-publickey');
|
|
4080
|
-
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
4081
|
-
const data = await res.json();
|
|
4082
|
-
const pk = data.publicKey || '';
|
|
4083
|
-
const body = document.getElementById('mpim-body');
|
|
4084
|
-
if (!pk || pk.length !== 64) {
|
|
4085
|
-
body.innerHTML = `<div style="color:#b91c1c;font-size:13px;">✗ P2PDirect 还没启动, 刷新页面稍后再试</div>`;
|
|
4086
|
-
return;
|
|
4087
|
-
}
|
|
4088
|
-
body.innerHTML = `
|
|
4089
|
-
<div style="font-size:12px;color:#6b7280;margin-bottom:8px;">把下面这串发给好友, 好友在 P2P 好友区点 "+ 好友" 粘贴即可加你:</div>
|
|
4090
|
-
<div style="display:flex;gap:6px;align-items:center;margin-bottom:12px;">
|
|
4091
|
-
<code id="mpim-pk" style="flex:1;padding:8px 10px;background:#f3f4f6;border:1px solid #d1d5db;border-radius:4px;font-family:monospace;font-size:11px;word-break:break-all;line-height:1.4;">${escapeHtml(pk)}</code>
|
|
4092
|
-
<button id="mpim-copy" style="padding:8px 14px;background:#2563eb;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px;white-space:nowrap;">📋 复制</button>
|
|
4093
|
-
</div>
|
|
4094
|
-
<div id="mpim-status" style="font-size:12px;color:#059669;min-height:16px;"></div>
|
|
4095
|
-
<div style="margin-top:14px;padding-top:12px;border-top:1px solid #e5e7eb;font-size:11px;color:#6b7280;">
|
|
4096
|
-
💡 同一个 role 重启后 publicKey 不会变, 好友不需要重新加你.
|
|
4097
|
-
</div>
|
|
4098
|
-
`;
|
|
4099
|
-
document.getElementById('mpim-copy').onclick = async () => {
|
|
4100
|
-
const statusEl = document.getElementById('mpim-status');
|
|
4101
|
-
try {
|
|
4102
|
-
await navigator.clipboard.writeText(pk);
|
|
4103
|
-
statusEl.textContent = '✓ 已复制到剪贴板';
|
|
4104
|
-
} catch {
|
|
4105
|
-
const ta = document.createElement('textarea');
|
|
4106
|
-
ta.value = pk;
|
|
4107
|
-
ta.style.position = 'fixed';
|
|
4108
|
-
ta.style.opacity = '0';
|
|
4109
|
-
document.body.appendChild(ta);
|
|
4110
|
-
ta.select();
|
|
4111
|
-
try { document.execCommand('copy'); statusEl.textContent = '✓ 已复制 (fallback)'; }
|
|
4112
|
-
catch { statusEl.textContent = '✗ 复制失败, 请手动选中复制'; }
|
|
4113
|
-
document.body.removeChild(ta);
|
|
4114
|
-
}
|
|
4115
|
-
};
|
|
4116
|
-
} catch (err) {
|
|
4117
|
-
const body = document.getElementById('mpim-body');
|
|
4118
|
-
if (body) body.innerHTML = `<div style="color:#b91c1c;font-size:13px;">✗ 获取失败: ${escapeHtml(err.message || String(err))}</div>`;
|
|
4119
|
-
}
|
|
4120
|
-
});
|
|
4121
|
-
}
|
|
4122
|
-
|
|
4123
|
-
// Phase 3 重做: + 添加好友按钮 → 弹窗输入 publicKey + name, 同时 joinPeer
|
|
4124
|
-
const addPeerBtn = document.getElementById('add-p2p-peer-btn');
|
|
4125
|
-
if (addPeerBtn) {
|
|
4126
|
-
addPeerBtn.addEventListener('click', async (e) => {
|
|
4127
|
-
e.stopPropagation();
|
|
4128
|
-
const name = prompt('给这个 P2P 好友起个名字 (如: 同事-张磊)');
|
|
4129
|
-
if (!name) return;
|
|
4130
|
-
const publicKey = prompt('粘贴对方的 P2PDirect publicKey (64 字符 hex):\n\n获取方式: 对方在 http://localhost:54188/api/p2p-publickey');
|
|
4131
|
-
if (!publicKey) return;
|
|
4132
|
-
if (publicKey.length !== 64) {
|
|
4133
|
-
alert('publicKey 长度不对, 应该是 64 字符 hex');
|
|
4134
|
-
return;
|
|
4135
|
-
}
|
|
4136
|
-
try {
|
|
4137
|
-
// v3 新增: 改用 friend-request RPC — 不光 joinPeer, 还发申请到对方
|
|
4138
|
-
// 对方会收到 SSE friend-request 事件, 弹一个申请 modal
|
|
4139
|
-
const res = await fetch('/api/friend-request', {
|
|
4140
|
-
method: 'POST',
|
|
4141
|
-
headers: { 'Content-Type': 'application/json' },
|
|
4142
|
-
body: JSON.stringify({ targetPublicKey: publicKey, name, message: '想加你为 P2P 好友, 共享 channel 协作' })
|
|
4143
|
-
});
|
|
4144
|
-
const data = await res.json();
|
|
4145
|
-
if (res.status === 502) {
|
|
4146
|
-
// 2026-06-10: 区分"对方不在线"和"写失败" — 让用户知道是否需要重试
|
|
4147
|
-
const reason = data.code === 'NO_CONN' ? '对方未在线或 P2P 握手超时' : '写入 P2P 通道失败';
|
|
4148
|
-
alert(`好友申请发送失败: ${reason}\n\n本地已记住对方 publicKey (${publicKey.substring(0,8)}...), 等对方上线后可在 P2P 面板手动重试.`);
|
|
4149
|
-
await loadRemoteChannels();
|
|
4150
|
-
return;
|
|
4151
|
-
}
|
|
4152
|
-
if (!res.ok) throw new Error(data.error || 'connect failed');
|
|
4153
|
-
// 成功 — 但不阻塞地等 ack (ack 经 SSE 'friend-request-ack' 推回, 由 v3GlobalEventSource 处理)
|
|
4154
|
-
window.__pendingFriendRequests = window.__pendingFriendRequests || new Map();
|
|
4155
|
-
if (data.requestId) {
|
|
4156
|
-
window.__pendingFriendRequests.set(data.requestId, { name, publicKey, at: Date.now() });
|
|
4157
|
-
// 8s 后还没 ack → 提示用户对方可能跑旧版 (无 ack 协议)
|
|
4158
|
-
setTimeout(() => {
|
|
4159
|
-
if (window.__pendingFriendRequests.has(data.requestId)) {
|
|
4160
|
-
window.__pendingFriendRequests.delete(data.requestId);
|
|
4161
|
-
console.warn(`[v3-friend] 申请超时未收到 ack (requestId=${data.requestId.substring(0,8)})`);
|
|
4162
|
-
showSimpleToast(`⚠️ 对方未确认收到 (可能是旧版客户端, 申请已发出但无法验证)`, 'warn');
|
|
4163
|
-
}
|
|
4164
|
-
}, 8000);
|
|
4165
|
-
}
|
|
4166
|
-
alert(`已发送好友申请给 ${name} (${publicKey.substring(0, 12)}...)\n对方收到后自己端弹申请 modal, 接受后会出现在 P2P 好友区.`);
|
|
4167
|
-
await loadRemoteChannels();
|
|
4168
|
-
} catch (err) {
|
|
4169
|
-
alert('申请失败: ' + (err.message || err));
|
|
4170
|
-
}
|
|
4171
|
-
});
|
|
4172
|
-
}
|
|
4173
|
-
|
|
4174
|
-
/**
|
|
4175
|
-
* v3 新增: 收到好友申请时, 弹一个 modal 让用户接受或拒绝
|
|
4176
|
-
*/
|
|
4177
|
-
function showFriendRequestModal(req) {
|
|
4178
|
-
// 移除已有 modal
|
|
4179
|
-
document.getElementById('friend-request-modal')?.remove();
|
|
4180
|
-
// 2026-06-10: 同 Step 3 远端 chat modal 一样, 改用 class + CSS 变量, 跟本地风格统一
|
|
4181
|
-
const html = `
|
|
4182
|
-
<div id="friend-request-modal" class="friend-req-overlay">
|
|
4183
|
-
<div class="friend-req-shell">
|
|
4184
|
-
<div class="friend-req-header">
|
|
4185
|
-
<span style="font-size:20px;">🤝</span>
|
|
4186
|
-
<div style="flex:1;min-width:0;">
|
|
4187
|
-
<div class="friend-req-title">好友申请</div>
|
|
4188
|
-
<div class="friend-req-meta">来自 ${escapeHtml(req.fromName)} (${escapeHtml(req.fromPublicKey.substring(0, 16))}…)</div>
|
|
4189
|
-
</div>
|
|
4190
|
-
</div>
|
|
4191
|
-
<div class="friend-req-body">
|
|
4192
|
-
<p style="margin:0 0 8px;">${escapeHtml(req.message || '想加你为 P2P 好友')}</p>
|
|
4193
|
-
<p style="margin:0;color:var(--text-muted);font-size:11px;">接受后: 双方互加好友, 对方分享的 channel 会自动出现在 P2P 好友区.</p>
|
|
4194
|
-
</div>
|
|
4195
|
-
<div class="friend-req-actions">
|
|
4196
|
-
<button id="frm-deny" class="friend-req-btn-deny">拒绝</button>
|
|
4197
|
-
<button id="frm-accept" class="friend-req-btn-accept">接受</button>
|
|
4198
|
-
</div>
|
|
4199
|
-
</div>
|
|
4200
|
-
</div>
|
|
4201
|
-
`;
|
|
4202
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
4203
|
-
const close = () => document.getElementById('friend-request-modal')?.remove();
|
|
4204
|
-
document.getElementById('frm-deny').onclick = close;
|
|
4205
|
-
document.getElementById('frm-accept').onclick = async () => {
|
|
4206
|
-
close();
|
|
4207
|
-
try {
|
|
4208
|
-
const res = await fetch('/api/friend-accept', {
|
|
4209
|
-
method: 'POST',
|
|
4210
|
-
headers: { 'Content-Type': 'application/json' },
|
|
4211
|
-
body: JSON.stringify({ fromPublicKey: req.fromPublicKey, name: req.fromName })
|
|
4212
|
-
});
|
|
4213
|
-
const data = await res.json();
|
|
4214
|
-
if (!res.ok) throw new Error(data.error || 'accept failed');
|
|
4215
|
-
console.log('[v3-friend] 接受了好友申请:', req.fromName);
|
|
4216
|
-
// 立刻拉一次 — 对方刚 accept, ta 的 channel 列表会被推到我们这
|
|
4217
|
-
setTimeout(loadRemoteChannels, 1000);
|
|
4218
|
-
showSimpleToast(`✅ 已接受 ${req.fromName} 的好友申请`);
|
|
4219
|
-
} catch (err) {
|
|
4220
|
-
console.error('[v3-friend] accept 失败:', err);
|
|
4221
|
-
alert('接受失败: ' + (err.message || err));
|
|
4222
|
-
}
|
|
4223
|
-
};
|
|
4224
|
-
}
|
|
4225
|
-
|
|
4226
|
-
/**
|
|
4227
|
-
* 2026-06-10: 简单的右下 toast, 3s 自动消失. 用于 ack / 接受好友 等非阻塞反馈
|
|
4228
|
-
*/
|
|
4229
|
-
function showSimpleToast(text, kind = 'info') {
|
|
4230
|
-
const containerId = 'simple-toast-container';
|
|
4231
|
-
let container = document.getElementById(containerId);
|
|
4232
|
-
if (!container) {
|
|
4233
|
-
container = document.createElement('div');
|
|
4234
|
-
container.id = containerId;
|
|
4235
|
-
container.style.cssText = 'position:fixed;right:16px;bottom:16px;z-index:10005;display:flex;flex-direction:column;gap:8px;max-width:320px;';
|
|
4236
|
-
document.body.appendChild(container);
|
|
4237
|
-
}
|
|
4238
|
-
const el = document.createElement('div');
|
|
4239
|
-
el.className = `simple-toast simple-toast-${kind}`;
|
|
4240
|
-
el.style.cssText = `background:var(--bg-sidebar);color:var(--text);border:1px solid var(--border);padding:10px 14px;border-radius:6px;font-size:12px;box-shadow:0 4px 16px rgba(0,0,0,0.3);font-family:inherit;animation:toast-in .2s ease-out;`;
|
|
4241
|
-
el.textContent = text;
|
|
4242
|
-
container.appendChild(el);
|
|
4243
|
-
setTimeout(() => {
|
|
4244
|
-
el.style.transition = 'opacity .3s, transform .3s';
|
|
4245
|
-
el.style.opacity = '0';
|
|
4246
|
-
el.style.transform = 'translateX(20px)';
|
|
4247
|
-
setTimeout(() => el.remove(), 320);
|
|
4248
|
-
}, 3000);
|
|
4249
|
-
}
|
|
4250
|
-
|
|
4251
|
-
// 2026-06-10: P2P 全部展开/折叠切换按钮 (单按钮, 根据当前多数态切换)
|
|
4252
|
-
const p2pToggleAllBtn = document.getElementById('p2p-toggle-all-btn');
|
|
4253
|
-
if (p2pToggleAllBtn) {
|
|
4254
|
-
// 同步图标/文字: 多数 peer 折叠 → 显示 "⊞ 展开"; 多数展开 → 显示 "⊟ 折叠"
|
|
4255
|
-
function syncToggleAllBtn() {
|
|
4256
|
-
const allPks = new Set([
|
|
4257
|
-
...knownPeers.map(p => p.publicKey),
|
|
4258
|
-
...remoteChannels.map(g => g.peerId)
|
|
4259
|
-
]);
|
|
4260
|
-
if (allPks.size === 0) {
|
|
4261
|
-
p2pToggleAllBtn.textContent = '⊞ 展开';
|
|
4262
|
-
p2pToggleAllBtn.title = '切换全部展开/折叠';
|
|
4263
|
-
return;
|
|
4264
|
-
}
|
|
4265
|
-
let collapsedCount = 0;
|
|
4266
|
-
for (const pk of allPks) if (collapsedPeers.has(pk)) collapsedCount++;
|
|
4267
|
-
const majorityCollapsed = collapsedCount >= allPks.size / 2;
|
|
4268
|
-
if (majorityCollapsed) {
|
|
4269
|
-
p2pToggleAllBtn.textContent = '⊞ 展开';
|
|
4270
|
-
p2pToggleAllBtn.title = '点击展开所有 P2P 好友';
|
|
4271
|
-
} else {
|
|
4272
|
-
p2pToggleAllBtn.textContent = '⊟ 折叠';
|
|
4273
|
-
p2pToggleAllBtn.title = '点击折叠所有 P2P 好友';
|
|
4274
|
-
}
|
|
4275
|
-
}
|
|
4276
|
-
p2pToggleAllBtn.addEventListener('click', (e) => {
|
|
4277
|
-
e.stopPropagation();
|
|
4278
|
-
const allPks = new Set([
|
|
4279
|
-
...knownPeers.map(p => p.publicKey),
|
|
4280
|
-
...remoteChannels.map(g => g.peerId)
|
|
4281
|
-
]);
|
|
4282
|
-
if (allPks.size === 0) return;
|
|
4283
|
-
// 多数折叠 → 全展开; 否则全折叠
|
|
4284
|
-
let collapsedCount = 0;
|
|
4285
|
-
for (const pk of allPks) if (collapsedPeers.has(pk)) collapsedCount++;
|
|
4286
|
-
const majorityCollapsed = collapsedCount >= allPks.size / 2;
|
|
4287
|
-
if (majorityCollapsed) {
|
|
4288
|
-
expandAllPeers();
|
|
4289
|
-
} else {
|
|
4290
|
-
collapseAllPeers();
|
|
4291
|
-
}
|
|
4292
|
-
syncToggleAllBtn();
|
|
4293
|
-
});
|
|
4294
|
-
// 暴露给 renderRemoteChannels 渲染后调用 (保持图标跟实际状态一致)
|
|
4295
|
-
window.__syncP2PToggleAllBtn = syncToggleAllBtn;
|
|
4296
|
-
syncToggleAllBtn(); // 首次同步
|
|
4297
|
-
}
|
|
4298
|
-
|
|
4299
|
-
// v3 双向刷新: 主动向所有好友发 agent.meta.list, 拿到 ta 们分享给我的 channel
|
|
4300
|
-
const refreshSharedBtn = document.getElementById('refresh-shared-btn');
|
|
4301
|
-
if (refreshSharedBtn) {
|
|
4302
|
-
refreshSharedBtn.addEventListener('click', async (e) => {
|
|
4303
|
-
e.stopPropagation();
|
|
4304
|
-
const originalText = refreshSharedBtn.textContent;
|
|
4305
|
-
refreshSharedBtn.disabled = true;
|
|
4306
|
-
refreshSharedBtn.textContent = '...';
|
|
4307
|
-
try {
|
|
4308
|
-
const res = await fetch('/api/remote-channels/refresh', { method: 'POST' });
|
|
4309
|
-
const data = await res.json();
|
|
4310
|
-
if (!res.ok) throw new Error(data.error || 'refresh failed');
|
|
4311
|
-
// 等 1.5s 让 RPC 回复回来 (向所有 peer 广播)
|
|
4312
|
-
await new Promise(r => setTimeout(r, 1500));
|
|
4313
|
-
await loadRemoteChannels();
|
|
4314
|
-
console.log(`[v3] 双向刷新: 向 ${data.peerCount || 0} 个好友发 list 请求`);
|
|
4315
|
-
} catch (err) {
|
|
4316
|
-
alert('刷新失败: ' + (err.message || err));
|
|
4317
|
-
} finally {
|
|
4318
|
-
refreshSharedBtn.disabled = false;
|
|
4319
|
-
refreshSharedBtn.textContent = originalText;
|
|
4320
|
-
}
|
|
4321
|
-
});
|
|
4322
|
-
}
|
|
4323
|
-
|
|
4324
|
-
// 启动时拉一次 + 定期轮询 (SSE 接收 P2P reply 后也会更新)
|
|
4325
|
-
loadRemoteChannels();
|
|
4326
|
-
setInterval(loadRemoteChannels, 8000);
|
|
4327
|
-
// 全局 SSE — 接收 remote-channel-update / remote-chat-reply / friend-request
|
|
4328
|
-
startV3GlobalSSE();
|
|
4329
|
-
|
|
4330
|
-
// ============ v3: 折叠 + 拖拽分隔线 ============
|
|
4331
|
-
|
|
4332
|
-
// 给本地/远端 section 加 flex 修饰类 (CSS variable 驱动比例)
|
|
4333
|
-
const localSection = document.querySelector('.sidebar-section'); // 第一个 section = 本地 channel
|
|
4334
|
-
const remoteSection = document.getElementById('remote-agents-section');
|
|
4335
|
-
if (localSection) localSection.classList.add('local-flex');
|
|
4336
|
-
if (remoteSection) remoteSection.classList.add('remote-flex');
|
|
4337
|
-
|
|
4338
|
-
// 折叠: 点 header 切换 collapsed 类
|
|
4339
|
-
const remoteHeader = document.getElementById('remote-agents-header');
|
|
4340
|
-
if (remoteHeader && remoteSection) {
|
|
4341
|
-
remoteHeader.addEventListener('click', (e) => {
|
|
4342
|
-
// 阻止刷新按钮的事件冒泡在 refreshRemoteBtn 里已处理
|
|
4343
|
-
remoteSection.classList.toggle('collapsed');
|
|
4344
|
-
});
|
|
4345
|
-
}
|
|
4346
|
-
|
|
4347
|
-
// 拖拽分隔线: 鼠标按下开始拖, mousemove 改 --local-flex / --remote-flex, mouseup 结束
|
|
4348
|
-
const splitHandle = document.getElementById('sidebar-split-handle');
|
|
4349
|
-
if (splitHandle && localSection && remoteSection) {
|
|
4350
|
-
// 初始化等分
|
|
4351
|
-
const updateFlexVars = (localRatio, remoteRatio) => {
|
|
4352
|
-
localSection.style.setProperty('--local-flex', String(localRatio));
|
|
4353
|
-
remoteSection.style.setProperty('--remote-flex', String(remoteRatio));
|
|
4354
|
-
};
|
|
4355
|
-
updateFlexVars(1, 1);
|
|
4356
|
-
|
|
4357
|
-
let isDragging = false;
|
|
4358
|
-
let dragStartY = 0;
|
|
4359
|
-
let startLocalFlex = 1;
|
|
4360
|
-
let startRemoteFlex = 1;
|
|
4361
|
-
let sidebarHeight = 0;
|
|
4362
|
-
|
|
4363
|
-
splitHandle.addEventListener('mousedown', (e) => {
|
|
4364
|
-
isDragging = true;
|
|
4365
|
-
splitHandle.classList.add('dragging');
|
|
4366
|
-
dragStartY = e.clientY;
|
|
4367
|
-
// 读当前 CSS variable 拿真实 flex 值
|
|
4368
|
-
const lf = parseFloat(getComputedStyle(localSection).getPropertyValue('--local-flex')) || 1;
|
|
4369
|
-
const rf = parseFloat(getComputedStyle(remoteSection).getPropertyValue('--remote-flex')) || 1;
|
|
4370
|
-
startLocalFlex = lf;
|
|
4371
|
-
startRemoteFlex = rf;
|
|
4372
|
-
// 父容器可用高度 = sidebar-section 总和 (本地+远端+handle)
|
|
4373
|
-
const sidebar = document.querySelector('.sidebar');
|
|
4374
|
-
if (sidebar) sidebarHeight = sidebar.clientHeight;
|
|
4375
|
-
e.preventDefault();
|
|
4376
|
-
document.body.style.cursor = 'ns-resize';
|
|
4377
|
-
});
|
|
4378
|
-
|
|
4379
|
-
document.addEventListener('mousemove', (e) => {
|
|
4380
|
-
if (!isDragging) return;
|
|
4381
|
-
const deltaY = e.clientY - dragStartY;
|
|
4382
|
-
if (sidebarHeight <= 0) return;
|
|
4383
|
-
// deltaY 正 = 鼠标下移 = 拉大本地 / 缩小远端
|
|
4384
|
-
// 转换: 1 像素 ≈ sidebarHeight 中 0.005 的比例
|
|
4385
|
-
const deltaRatio = deltaY / sidebarHeight * 4; // 4 倍灵敏
|
|
4386
|
-
let newLocal = Math.max(0.1, startLocalFlex + deltaRatio);
|
|
4387
|
-
let newRemote = Math.max(0.1, startRemoteFlex - deltaRatio);
|
|
4388
|
-
updateFlexVars(newLocal, newRemote);
|
|
4389
|
-
});
|
|
4390
|
-
|
|
4391
|
-
document.addEventListener('mouseup', () => {
|
|
4392
|
-
if (!isDragging) return;
|
|
4393
|
-
isDragging = false;
|
|
4394
|
-
splitHandle.classList.remove('dragging');
|
|
4395
|
-
document.body.style.cursor = '';
|
|
4396
|
-
});
|
|
4397
|
-
|
|
4398
|
-
// 双击分隔线 = 重置为等分
|
|
4399
|
-
splitHandle.addEventListener('dblclick', () => {
|
|
4400
|
-
updateFlexVars(1, 1);
|
|
4401
|
-
});
|
|
4402
|
-
}
|
|
4403
|
-
|
|
4404
|
-
if (taskModal) {
|
|
4405
|
-
taskModal.addEventListener('click', (e) => {
|
|
4406
|
-
if (e.target === taskModal) {
|
|
4407
|
-
hideTaskModal();
|
|
4408
|
-
}
|
|
4409
|
-
});
|
|
4410
|
-
}
|
|
4411
|
-
|
|
4412
|
-
if (taskAddBtn) {
|
|
4413
|
-
taskAddBtn.addEventListener('click', showCreateTaskModal);
|
|
4414
|
-
}
|
|
4415
|
-
|
|
4416
|
-
if (taskExecuteNextBtn) {
|
|
4417
|
-
taskExecuteNextBtn.addEventListener('click', executeNextTask);
|
|
4418
|
-
}
|
|
4419
|
-
|
|
4420
|
-
if (taskCancelBtn) {
|
|
4421
|
-
taskCancelBtn.addEventListener('click', hideCreateTaskModal);
|
|
4422
|
-
}
|
|
4423
|
-
|
|
4424
|
-
if (createTaskModalClose) {
|
|
4425
|
-
createTaskModalClose.addEventListener('click', hideCreateTaskModal);
|
|
4426
|
-
}
|
|
4427
|
-
|
|
4428
|
-
if (createTaskModal) {
|
|
4429
|
-
createTaskModal.addEventListener('click', (e) => {
|
|
4430
|
-
if (e.target === createTaskModal) {
|
|
4431
|
-
hideCreateTaskModal();
|
|
4432
|
-
}
|
|
4433
|
-
});
|
|
4434
|
-
}
|
|
4435
|
-
|
|
4436
|
-
if (taskCreateBtn) {
|
|
4437
|
-
taskCreateBtn.addEventListener('click', createTask);
|
|
4438
|
-
}
|
|
4439
|
-
|
|
4440
|
-
if (taskTypeSelect) {
|
|
4441
|
-
taskTypeSelect.addEventListener('change', () => {
|
|
4442
|
-
const workflowSteps = document.querySelector('.workflow-steps');
|
|
4443
|
-
if (workflowSteps) {
|
|
4444
|
-
workflowSteps.style.display = taskTypeSelect.value === 'workflow' ? 'block' : 'none';
|
|
4445
|
-
}
|
|
4446
|
-
});
|
|
4447
|
-
}
|
|
4448
|
-
|
|
4449
|
-
// Handle SSE task status updates
|
|
4450
|
-
const originalOnMessage = window.addEventListener ? null : null;
|
|
1980
|
+
// Handle SSE task status updates
|
|
1981
|
+
const originalOnMessage = window.addEventListener ? null : null;
|
|
4451
1982
|
|
|
4452
1983
|
// Extend SSE handler for task updates
|
|
4453
1984
|
const originalConnect = connect;
|
|
@@ -4485,9 +2016,8 @@ const walletUnbindBtn = document.getElementById('wallet-unbind-btn');
|
|
|
4485
2016
|
const walletNewInfo = document.getElementById('wallet-new-info');
|
|
4486
2017
|
const walletListEl = document.getElementById('wallet-list');
|
|
4487
2018
|
|
|
4488
|
-
/**
|
|
2019
|
+
/** 本次会话生成的私钥, 仅用于提示, 永不上传 */
|
|
4489
2020
|
let walletModalPendingSecret = null;
|
|
4490
|
-
let walletModalPendingMnemonic = null;
|
|
4491
2021
|
|
|
4492
2022
|
function openWalletModal() {
|
|
4493
2023
|
if (!walletModal) return;
|
|
@@ -4514,18 +2044,17 @@ function closeWalletModal() {
|
|
|
4514
2044
|
if (walletModalClose) walletModalClose.addEventListener('click', closeWalletModal);
|
|
4515
2045
|
|
|
4516
2046
|
if (walletGenerateBtn) {
|
|
4517
|
-
walletGenerateBtn.addEventListener('click',
|
|
2047
|
+
walletGenerateBtn.addEventListener('click', () => {
|
|
2048
|
+
const { address, privateKeyHex } = generateLocalWallet();
|
|
2049
|
+
walletBindAddress.value = address;
|
|
2050
|
+
walletModalPendingSecret = privateKeyHex;
|
|
4518
2051
|
walletNewInfo.style.display = 'block';
|
|
4519
|
-
walletNewInfo.innerHTML =
|
|
4520
|
-
|
|
4521
|
-
|
|
4522
|
-
|
|
4523
|
-
|
|
4524
|
-
|
|
4525
|
-
walletNewInfo.innerHTML = formatWalletInfoHtml(wallet);
|
|
4526
|
-
} catch (err) {
|
|
4527
|
-
walletNewInfo.innerHTML = '✗ 生成钱包失败: ' + escapeHtml(err.message);
|
|
4528
|
-
}
|
|
2052
|
+
walletNewInfo.innerHTML = `
|
|
2053
|
+
✓ 已生成本地钱包<br>
|
|
2054
|
+
<strong>地址:</strong> <code>${escapeHtml(address)}</code><br>
|
|
2055
|
+
<strong>私钥 (本次会话, 刷新即丢):</strong> <code style="color:#f88;">${escapeHtml(privateKeyHex)}</code><br>
|
|
2056
|
+
<small style="color:#f88;">⚠ 关闭页面后无法找回。仅地址会发送到服务端。</small>
|
|
2057
|
+
`;
|
|
4529
2058
|
});
|
|
4530
2059
|
}
|
|
4531
2060
|
|
|
@@ -4540,40 +2069,12 @@ if (walletBindBtn) {
|
|
|
4540
2069
|
alert('请输入钱包地址或点击「生成」');
|
|
4541
2070
|
return;
|
|
4542
2071
|
}
|
|
4543
|
-
const ch = channels.find(c => c.id === currentChannelId);
|
|
4544
|
-
const did = ch?.did || '';
|
|
4545
|
-
if (!did || did === 'undefined' || did === 'null') {
|
|
4546
|
-
alert('当前智能体还没有生成 DID, 请稍等几秒后重试');
|
|
4547
|
-
return;
|
|
4548
|
-
}
|
|
4549
|
-
|
|
4550
|
-
// 服务端会用 recoverMessage 校验签名, 因此必须用本会话生成的私钥签名
|
|
4551
|
-
// (已绑过的钱包重新签名也会过, 因为 challenge 里有 channelId + DID)
|
|
4552
|
-
if (!walletModalPendingSecret) {
|
|
4553
|
-
alert('请先在「钱包管理」面板点击「生成」或导入私钥, 临时私钥仅在本会话保留');
|
|
4554
|
-
return;
|
|
4555
|
-
}
|
|
4556
|
-
let challenge;
|
|
4557
2072
|
try {
|
|
4558
|
-
|
|
4559
|
-
|
|
4560
|
-
alert('签名失败: ' + err.message);
|
|
4561
|
-
return;
|
|
4562
|
-
}
|
|
4563
|
-
if (challenge.address.toLowerCase() !== address.toLowerCase()) {
|
|
4564
|
-
alert(`签名地址 ${challenge.address} 与输入地址 ${address} 不一致, 拒绝绑定`);
|
|
4565
|
-
return;
|
|
4566
|
-
}
|
|
4567
|
-
|
|
4568
|
-
try {
|
|
4569
|
-
const res = await fetch(`/channels/${currentChannelId}/bind-wallet`, {
|
|
4570
|
-
method: 'POST',
|
|
2073
|
+
const res = await fetch(`/channels/${currentChannelId}`, {
|
|
2074
|
+
method: 'PATCH',
|
|
4571
2075
|
headers: { 'Content-Type': 'application/json' },
|
|
4572
2076
|
body: JSON.stringify({
|
|
4573
|
-
walletAddress:
|
|
4574
|
-
signature: challenge.signature,
|
|
4575
|
-
message: challenge.message,
|
|
4576
|
-
did: challenge.did,
|
|
2077
|
+
walletAddress: address,
|
|
4577
2078
|
autoInvokeTools: !!walletAutoTools.checked
|
|
4578
2079
|
})
|
|
4579
2080
|
});
|
|
@@ -4587,13 +2088,6 @@ if (walletBindBtn) {
|
|
|
4587
2088
|
renderChannels();
|
|
4588
2089
|
renderWalletList();
|
|
4589
2090
|
walletModalPendingSecret = null;
|
|
4590
|
-
walletModalPendingMnemonic = null;
|
|
4591
|
-
walletNewInfo.style.display = 'block';
|
|
4592
|
-
walletNewInfo.innerHTML =
|
|
4593
|
-
'✅ 绑定成功<br>' +
|
|
4594
|
-
'<strong>地址:</strong> <code>' + escapeHtml(updated.walletAddress) + '</code><br>' +
|
|
4595
|
-
'<strong>签名 DID:</strong> <code>' + escapeHtml(did) + '</code><br>' +
|
|
4596
|
-
'<small style="color:#9c9;">服务端已用 recoverMessage 校验签名, 证明你持有该钱包私钥。</small>';
|
|
4597
2091
|
} catch (err) {
|
|
4598
2092
|
alert('绑定失败: ' + err.message);
|
|
4599
2093
|
}
|
|
@@ -4736,31 +2230,26 @@ const agentAddWalletInfo = document.getElementById('agent-add-wallet-info');
|
|
|
4736
2230
|
const agentGenerateWalletBtn = document.getElementById('agent-generate-wallet-btn');
|
|
4737
2231
|
|
|
4738
2232
|
/** 客户端只为提示, 不向服务端发送私钥 */
|
|
4739
|
-
let pendingWalletSecret = null;
|
|
4740
|
-
let pendingWalletMnemonic = null; // 本会话待绑定的助记词, 仅浏览器内存
|
|
2233
|
+
let pendingWalletSecret = null;
|
|
4741
2234
|
|
|
4742
2235
|
function openAgentAddModal(existingChannel) {
|
|
4743
2236
|
if (!agentAddModal) return;
|
|
4744
2237
|
if (existingChannel) {
|
|
4745
2238
|
agentAddTitle.textContent = '配置智能体:' + existingChannel.name;
|
|
4746
2239
|
agentAddName.value = existingChannel.name || '';
|
|
4747
|
-
agentAddName.readOnly =
|
|
4748
|
-
agentAddName.placeholder = '输入新名称';
|
|
2240
|
+
agentAddName.readOnly = true; // 改名走 PATCH
|
|
4749
2241
|
agentAddWallet.value = existingChannel.walletAddress || '';
|
|
4750
2242
|
agentAddAutoTools.checked = !!existingChannel.autoInvokeTools;
|
|
4751
2243
|
agentAddConfirmBtn.dataset.mode = 'update';
|
|
4752
2244
|
agentAddConfirmBtn.dataset.channelId = existingChannel.id;
|
|
4753
|
-
agentAddConfirmBtn.dataset.originalName = existingChannel.name || '';
|
|
4754
2245
|
} else {
|
|
4755
2246
|
agentAddTitle.textContent = '添加智能体';
|
|
4756
2247
|
agentAddName.value = '';
|
|
4757
2248
|
agentAddName.readOnly = false;
|
|
4758
|
-
agentAddName.placeholder = '例如: 交易助手';
|
|
4759
2249
|
agentAddWallet.value = '';
|
|
4760
2250
|
agentAddAutoTools.checked = true;
|
|
4761
2251
|
agentAddConfirmBtn.dataset.mode = 'create';
|
|
4762
2252
|
delete agentAddConfirmBtn.dataset.channelId;
|
|
4763
|
-
delete agentAddConfirmBtn.dataset.originalName;
|
|
4764
2253
|
}
|
|
4765
2254
|
agentAddWalletInfo.style.display = 'none';
|
|
4766
2255
|
agentAddWalletInfo.innerHTML = '';
|
|
@@ -4774,62 +2263,32 @@ function closeAgentAddModal() {
|
|
|
4774
2263
|
pendingWalletSecret = null;
|
|
4775
2264
|
}
|
|
4776
2265
|
|
|
4777
|
-
/**
|
|
4778
|
-
|
|
4779
|
-
|
|
4780
|
-
|
|
4781
|
-
|
|
4782
|
-
|
|
4783
|
-
|
|
4784
|
-
|
|
4785
|
-
return
|
|
4786
|
-
}
|
|
4787
|
-
|
|
4788
|
-
async function importRealWalletByPrivateKey(privateKeyHex) {
|
|
4789
|
-
if (!window.WalletViem) {
|
|
4790
|
-
throw new Error('钱包模块尚未加载, 请稍后重试');
|
|
4791
|
-
}
|
|
4792
|
-
return window.WalletViem.importEVMWallet(privateKeyHex);
|
|
4793
|
-
}
|
|
4794
|
-
|
|
4795
|
-
async function signDIDChallengeAsync(privateKeyHex, did, channelId) {
|
|
4796
|
-
if (!window.WalletViem) {
|
|
4797
|
-
throw new Error('钱包模块尚未加载, 请稍后重试');
|
|
4798
|
-
}
|
|
4799
|
-
return window.WalletViem.signDIDChallenge(privateKeyHex, did, channelId);
|
|
4800
|
-
}
|
|
4801
|
-
|
|
4802
|
-
function formatWalletInfoHtml({ address, privateKey, mnemonic }) {
|
|
4803
|
-
const parts = [
|
|
4804
|
-
'✓ 已生成真实 EVM 钱包 (BIP-39 + secp256k1 + EIP-55)',
|
|
4805
|
-
'<strong>地址:</strong> <code>' + escapeHtml(address) + '</code>',
|
|
4806
|
-
];
|
|
4807
|
-
if (mnemonic) {
|
|
4808
|
-
parts.push(
|
|
4809
|
-
'<strong>助记词 (12 词, 请抄写保存):</strong>',
|
|
4810
|
-
'<code style="color:#fc6;word-break:break-all;">' + escapeHtml(mnemonic) + '</code>'
|
|
4811
|
-
);
|
|
4812
|
-
}
|
|
4813
|
-
parts.push(
|
|
4814
|
-
'<strong>私钥 (0x + 32 字节):</strong>',
|
|
4815
|
-
'<code style="color:#f88;word-break:break-all;">' + escapeHtml(privateKey) + '</code>',
|
|
4816
|
-
'<small style="color:#f88;">⚠ 助记词 + 私钥均仅在本浏览器内存, 关闭页面后无法找回。</small>',
|
|
4817
|
-
'<small style="color:#999;">签名绑定到 channel DID (EIP-191 personal_sign) 会发送到服务端, 用于证明钱包所有权。</small>'
|
|
4818
|
-
);
|
|
4819
|
-
return parts.join('<br>');
|
|
2266
|
+
/** 本地生成一个 EVM 风格地址 — 仅用于演示; 生产应使用 ethers/wagmi 等真实库 */
|
|
2267
|
+
function generateLocalWallet() {
|
|
2268
|
+
const bytes = new Uint8Array(32);
|
|
2269
|
+
crypto.getRandomValues(bytes);
|
|
2270
|
+
const privateKeyHex = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
|
|
2271
|
+
// 简化: 取末 20 字节当 address, 不做 keccak, 仅作为占位
|
|
2272
|
+
const addrBytes = bytes.slice(12);
|
|
2273
|
+
const address = '0x' + Array.from(addrBytes, b => b.toString(16).padStart(2, '0')).join('');
|
|
2274
|
+
return { address, privateKeyHex };
|
|
4820
2275
|
}
|
|
4821
2276
|
|
|
4822
2277
|
if (agentGenerateWalletBtn) {
|
|
4823
|
-
agentGenerateWalletBtn.addEventListener('click',
|
|
4824
|
-
agentAddWalletInfo.style.display = 'block';
|
|
4825
|
-
agentAddWalletInfo.innerHTML = '⏳ 正在生成真实 EVM 钱包...';
|
|
2278
|
+
agentGenerateWalletBtn.addEventListener('click', () => {
|
|
4826
2279
|
try {
|
|
4827
|
-
const
|
|
4828
|
-
agentAddWallet.value =
|
|
4829
|
-
pendingWalletSecret =
|
|
4830
|
-
|
|
4831
|
-
agentAddWalletInfo.innerHTML =
|
|
2280
|
+
const { address, privateKeyHex } = generateLocalWallet();
|
|
2281
|
+
agentAddWallet.value = address;
|
|
2282
|
+
pendingWalletSecret = privateKeyHex;
|
|
2283
|
+
agentAddWalletInfo.style.display = 'block';
|
|
2284
|
+
agentAddWalletInfo.innerHTML = `
|
|
2285
|
+
✓ 已生成本地钱包<br>
|
|
2286
|
+
<strong>地址:</strong> <code>${escapeHtml(address)}</code><br>
|
|
2287
|
+
<strong>私钥 (仅本次会话, 刷新即丢):</strong> <code style="color:#f88;">${escapeHtml(privateKeyHex)}</code><br>
|
|
2288
|
+
<small style="color:#f88;">⚠ 请抄写并妥善保存私钥, 关闭页面后无法找回。仅地址会发送到服务端。</small>
|
|
2289
|
+
`;
|
|
4832
2290
|
} catch (err) {
|
|
2291
|
+
agentAddWalletInfo.style.display = 'block';
|
|
4833
2292
|
agentAddWalletInfo.innerHTML = '✗ 生成钱包失败: ' + escapeHtml(err.message);
|
|
4834
2293
|
}
|
|
4835
2294
|
});
|
|
@@ -4872,16 +2331,10 @@ if (agentAddConfirmBtn) {
|
|
|
4872
2331
|
} else {
|
|
4873
2332
|
// update
|
|
4874
2333
|
const channelId = agentAddConfirmBtn.dataset.channelId;
|
|
4875
|
-
const originalName = agentAddConfirmBtn.dataset.originalName || '';
|
|
4876
|
-
// v3 新增: 名字改了才发 (没改就不发, 保持原状)
|
|
4877
|
-
const body = { walletAddress: walletAddress || null, autoInvokeTools };
|
|
4878
|
-
if (name && name !== originalName) {
|
|
4879
|
-
body.name = name;
|
|
4880
|
-
}
|
|
4881
2334
|
const res = await fetch(`/channels/${channelId}`, {
|
|
4882
2335
|
method: 'PATCH',
|
|
4883
2336
|
headers: { 'Content-Type': 'application/json' },
|
|
4884
|
-
body: JSON.stringify(
|
|
2337
|
+
body: JSON.stringify({ walletAddress: walletAddress || null, autoInvokeTools })
|
|
4885
2338
|
});
|
|
4886
2339
|
if (!res.ok) throw new Error('update failed');
|
|
4887
2340
|
const updated = await res.json();
|
|
@@ -4896,3 +2349,4 @@ if (agentAddConfirmBtn) {
|
|
|
4896
2349
|
}
|
|
4897
2350
|
});
|
|
4898
2351
|
}
|
|
2352
|
+
|