@bolloon/bolloon-agent 0.1.34 → 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/.auto-evolve-calls +1 -0
- package/.last-auto-evolve-baseline +1 -0
- 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 +144 -0
- 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 +687 -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 +117 -0
- package/dist/bootstrap/context-collector.js +312 -0
- package/dist/bootstrap/context-hierarchy.js +218 -0
- package/dist/bootstrap/lifecycle-hooks.js +171 -0
- package/dist/bootstrap/project-context.js +158 -0
- 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 +49 -2
- package/dist/llm/llm-judgment-client.js +32 -30
- package/dist/llm/pi-ai.js +125 -28
- 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 +279 -0
- package/dist/pi-ecosystem-judgment/causal-judge.js +449 -0
- package/dist/pi-ecosystem-judgment/detect-hook.js +168 -0
- package/dist/pi-ecosystem-judgment/distill-prompt.js +226 -0
- package/dist/pi-ecosystem-judgment/evolve-judgment.js +170 -0
- package/dist/pi-ecosystem-judgment/human-value-pipeline.js +21 -0
- package/dist/pi-ecosystem-judgment/human-value-store.js +283 -22
- package/dist/pi-ecosystem-judgment/injection-gate.js +208 -0
- package/dist/pi-ecosystem-judgment/monitor-gate.js +188 -0
- package/dist/pi-ecosystem-judgment/value-injection.js +8 -2
- package/dist/security/builtin-guards.js +124 -0
- package/dist/security/context-router-tool.js +106 -0
- package/dist/security/input-scanner.js +223 -0
- package/dist/security/react-harness.js +143 -0
- package/dist/security/tool-gate.js +235 -0
- package/dist/utils/auto-evolve-policy.js +117 -0
- package/dist/utils/clamp.js +7 -0
- package/dist/utils/double.js +6 -0
- package/dist/web/client.js +3810 -3830
- 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 +60 -49
- package/dist/web/server.js +827 -124
- 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 +33 -0
- package/package.json +3 -2
- package/scripts/auto-evolve-loop.ts +481 -0
- package/scripts/auto-evolve-oneshot.sh +155 -0
- package/scripts/auto-evolve-snapshot.sh +136 -0
- package/scripts/build-web.ts +35 -1
- package/scripts/detect-schema-changes.sh +48 -0
- package/scripts/diff-reviewer.ts +159 -0
- package/scripts/validate-system-prompt.ts +142 -0
- package/scripts/weekly-report.ts +364 -0
- package/src/agents/p2p-chat-tools.ts +6 -6
- package/src/agents/permission-mode.ts +127 -0
- package/src/agents/pi-sdk.ts +741 -30
- 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 +135 -0
- package/src/bootstrap/context-collector.ts +371 -0
- package/src/bootstrap/context-hierarchy.ts +283 -0
- package/src/bootstrap/lifecycle-hooks.ts +289 -0
- package/src/bootstrap/project-context.ts +171 -0
- 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 +47 -2
- package/src/llm/llm-judgment-client.ts +36 -35
- package/src/llm/pi-ai.ts +135 -29
- 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/builtin-guards.ts +162 -0
- package/src/security/context-router-tool.ts +122 -0
- package/src/security/input-scanner.ts +287 -0
- package/src/security/react-harness.ts +177 -0
- package/src/security/tool-gate.ts +294 -0
- package/src/utils/auto-evolve-policy.ts +138 -0
- package/src/utils/clamp.ts +5 -0
- package/src/web/client.js +105 -2187
- package/src/web/client.ts +4326 -0
- package/src/web/index.html +60 -49
- package/src/web/server.ts +894 -148
- 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/staging/auto-evolve/clean-001/.review-verdict +9 -0
- package/staging/auto-evolve/clean-001/clean-001.patch +14 -0
- package/staging/auto-evolve/e2e-001/.patch-id +1 -0
- package/staging/auto-evolve/e2e-001/.review-verdict +12 -0
- package/staging/auto-evolve/e2e-001/e2e-001.patch +11 -0
- package/staging/auto-evolve/test-bad/.review-verdict +12 -0
- package/staging/auto-evolve/test-bad/test-bad.patch +11 -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
|
@@ -23,68 +23,11 @@ let eventSources = new Map(); // channelId -> EventSource
|
|
|
23
23
|
let currentChannelId = null;
|
|
24
24
|
let currentAgentId = '';
|
|
25
25
|
let channels = [];
|
|
26
|
-
let remoteChannels = []; // v3: 远端 channel UI 元数据 (按 peer 分组)
|
|
27
26
|
let isSidebarCollapsed = false;
|
|
28
27
|
let reconnectAttempts = new Map(); // channelId -> attempts
|
|
29
28
|
let reconnectTimers = new Map(); // channelId -> timer
|
|
30
29
|
let heartbeatTimers = new Map(); // channelId -> setInterval handle (防止泄漏)
|
|
31
30
|
let lastUserCommand = ''; // 防止用户消息重复显示
|
|
32
|
-
|
|
33
|
-
// 2026-06-10: P2P peer-group 折叠状态持久化 (跨刷新)
|
|
34
|
-
// key = bolloon.p2p.collapsedPeers, value = JSON array of publicKey hex
|
|
35
|
-
const COLLAPSED_PEERS_KEY = 'bolloon.p2p.collapsedPeers';
|
|
36
|
-
const SEEN_PEERS_KEY = 'bolloon.p2p.seenPeers';
|
|
37
|
-
let collapsedPeers = (function loadCollapsed() {
|
|
38
|
-
try {
|
|
39
|
-
const raw = localStorage.getItem(COLLAPSED_PEERS_KEY);
|
|
40
|
-
return new Set(raw ? JSON.parse(raw) : []);
|
|
41
|
-
} catch { return new Set(); }
|
|
42
|
-
})();
|
|
43
|
-
let seenPeers = (function loadSeen() {
|
|
44
|
-
try {
|
|
45
|
-
const raw = localStorage.getItem(SEEN_PEERS_KEY);
|
|
46
|
-
return new Set(raw ? JSON.parse(raw) : []);
|
|
47
|
-
} catch { return new Set(); }
|
|
48
|
-
})();
|
|
49
|
-
function saveCollapsedPeers() {
|
|
50
|
-
try { localStorage.setItem(COLLAPSED_PEERS_KEY, JSON.stringify([...collapsedPeers])); } catch {}
|
|
51
|
-
}
|
|
52
|
-
function saveSeenPeers() {
|
|
53
|
-
try { localStorage.setItem(SEEN_PEERS_KEY, JSON.stringify([...seenPeers])); } catch {}
|
|
54
|
-
}
|
|
55
|
-
function togglePeerCollapsed(peerPk) {
|
|
56
|
-
if (collapsedPeers.has(peerPk)) {
|
|
57
|
-
collapsedPeers.delete(peerPk);
|
|
58
|
-
} else {
|
|
59
|
-
collapsedPeers.add(peerPk);
|
|
60
|
-
}
|
|
61
|
-
saveCollapsedPeers();
|
|
62
|
-
renderRemoteChannels();
|
|
63
|
-
// 2026-06-10: 通知 header 切换按钮同步图标
|
|
64
|
-
if (typeof window.__syncP2PToggleAllBtn === 'function') window.__syncP2PToggleAllBtn();
|
|
65
|
-
}
|
|
66
|
-
// 2026-06-10: 一键展开/折叠所有 P2P peer (header 按钮调用)
|
|
67
|
-
function expandAllPeers() {
|
|
68
|
-
// 从 remoteChannels + knownPeers 收集所有 publicKey
|
|
69
|
-
const allPks = new Set([
|
|
70
|
-
...knownPeers.map(p => p.publicKey),
|
|
71
|
-
...remoteChannels.map(g => g.peerId)
|
|
72
|
-
]);
|
|
73
|
-
for (const pk of allPks) collapsedPeers.delete(pk);
|
|
74
|
-
saveCollapsedPeers();
|
|
75
|
-
renderRemoteChannels();
|
|
76
|
-
if (typeof window.__syncP2PToggleAllBtn === 'function') window.__syncP2PToggleAllBtn();
|
|
77
|
-
}
|
|
78
|
-
function collapseAllPeers() {
|
|
79
|
-
const allPks = new Set([
|
|
80
|
-
...knownPeers.map(p => p.publicKey),
|
|
81
|
-
...remoteChannels.map(g => g.peerId)
|
|
82
|
-
]);
|
|
83
|
-
for (const pk of allPks) collapsedPeers.add(pk);
|
|
84
|
-
saveCollapsedPeers();
|
|
85
|
-
renderRemoteChannels();
|
|
86
|
-
if (typeof window.__syncP2PToggleAllBtn === 'function') window.__syncP2PToggleAllBtn();
|
|
87
|
-
}
|
|
88
31
|
let lastAiContent = ''; // 防止 AI 消息重复显示
|
|
89
32
|
let messagesContainers = new Map(); // channelId -> messages container div
|
|
90
33
|
let sessionMessages = new Map(); // channelId:sessionId -> messages array
|
|
@@ -156,155 +99,12 @@ async function loadChannels() {
|
|
|
156
99
|
channels.forEach((ch, i) => {
|
|
157
100
|
console.log(` [${i}] ${ch.name} - did: "${ch.did}"`);
|
|
158
101
|
});
|
|
159
|
-
// 2026-06-11: 全部默认不展开 (用户需要手动点 caret 展开 session 列表)
|
|
160
|
-
// 之前默认展开第一个会喧宾夺主, 用户看不到完整 channel 列表
|
|
161
102
|
renderChannels();
|
|
162
103
|
} catch (err) {
|
|
163
104
|
console.error('[加载频道] 失败:', err);
|
|
164
105
|
}
|
|
165
106
|
}
|
|
166
107
|
|
|
167
|
-
// v3: 全局 SSE 监听 (p2p-global channel) - 接收远端 chat.reply 等事件
|
|
168
|
-
let v3GlobalEventSource = null;
|
|
169
|
-
function startV3GlobalSSE() {
|
|
170
|
-
if (v3GlobalEventSource) return;
|
|
171
|
-
try {
|
|
172
|
-
v3GlobalEventSource = new EventSource('/events?channelId=p2p-global');
|
|
173
|
-
v3GlobalEventSource.onmessage = (e) => {
|
|
174
|
-
try {
|
|
175
|
-
const msg = JSON.parse(e.data);
|
|
176
|
-
if (msg.type === 'remote-chat-reply') {
|
|
177
|
-
// 2026-06-10: 复用本地 addMessage 渲染 — 自动 marked + 剥 think/env + 主题样式
|
|
178
|
-
// 之前是 textContent 硬编码灰底, 跟 Step 3 重写的 modal 风格不一致,
|
|
179
|
-
// 而且 SSE 异步回到时 modal 可能已被切到 thinking 占满, 用户看不到 reply.
|
|
180
|
-
const log = document.getElementById('rcm-log');
|
|
181
|
-
const thinkingEl = document.getElementById('rcm-thinking');
|
|
182
|
-
if (thinkingEl) thinkingEl.style.display = 'none'; // 思考结束, 隐藏
|
|
183
|
-
// 也清掉 "对方正在思考..." 行 (流式 token 留下的)
|
|
184
|
-
const liveThinking = document.getElementById('rcm-thinking-live');
|
|
185
|
-
if (liveThinking) liveThinking.remove();
|
|
186
|
-
if (log) {
|
|
187
|
-
if (msg.error) {
|
|
188
|
-
// 错误用 sysmsg 样式 (跟 modal 风格一致)
|
|
189
|
-
const errEl = document.createElement('div');
|
|
190
|
-
errEl.className = 'remote-chat-sysmsg remote-chat-sysmsg-error';
|
|
191
|
-
errEl.textContent = `❌ 对方回复出错: ${msg.error}`;
|
|
192
|
-
log.appendChild(errEl);
|
|
193
|
-
} else {
|
|
194
|
-
// 走本地 addMessage, 跟主聊天框完全一致 (marked + think/env 折叠 + 主题色)
|
|
195
|
-
const prefix = `🤖 远端 AI 回复\n\n`;
|
|
196
|
-
addMessage(prefix + (msg.text || '(空回复)'), 'ai', false, log);
|
|
197
|
-
}
|
|
198
|
-
log.scrollTop = log.scrollHeight;
|
|
199
|
-
} else {
|
|
200
|
-
// modal 没开 → 用右下 toast 提示用户"对方回了, 打开聊天看"
|
|
201
|
-
if (typeof showSimpleToast === 'function') {
|
|
202
|
-
const preview = (msg.text || '').slice(0, 50);
|
|
203
|
-
showSimpleToast(`💬 远端 channel 有新回复: ${preview}${msg.text && msg.text.length > 50 ? '…' : ''}`);
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
} else if (msg.type === 'remote-chat-thinking') {
|
|
207
|
-
// v3 新增: B 端实时显示 A 节点的思考过程
|
|
208
|
-
const phase = msg.phase;
|
|
209
|
-
const log = document.getElementById('rcm-log');
|
|
210
|
-
if (!log) return;
|
|
211
|
-
|
|
212
|
-
if (phase === 'start') {
|
|
213
|
-
// 头部插入"判断力依据"区块 (只第一次)
|
|
214
|
-
const judgments = msg.usedJudgments || { bound: [], candidates: [] };
|
|
215
|
-
const judgmentBlock = document.createElement('div');
|
|
216
|
-
judgmentBlock.className = 'rcm-judgment-block';
|
|
217
|
-
judgmentBlock.style.cssText = 'margin:6px 0;padding:8px 10px;background:#fef3c7;border-left:3px solid #f59e0b;border-radius:4px;font-size:12px;';
|
|
218
|
-
let jh = '<div style="font-weight:600;color:#92400e;margin-bottom:4px;">🛡️ 对方使用的判断力 (来自 ta 的 channel)</div>';
|
|
219
|
-
if (judgments.bound && judgments.bound.length > 0) {
|
|
220
|
-
jh += '<div style="color:#78350f;margin-bottom:4px;"><b>硬绑定</b> (必须遵循):</div>';
|
|
221
|
-
for (const j of judgments.bound) {
|
|
222
|
-
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>`;
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
if (judgments.candidates && judgments.candidates.length > 0) {
|
|
226
|
-
jh += `<div style="color:#78350f;margin-top:4px;"><b>候选池</b> (${judgments.candidates.length} 条, LLM 自选)</div>`;
|
|
227
|
-
}
|
|
228
|
-
log.appendChild(judgmentBlock);
|
|
229
|
-
// "思考中" 区块
|
|
230
|
-
const thinkingEl = document.createElement('div');
|
|
231
|
-
thinkingEl.id = 'rcm-thinking-live';
|
|
232
|
-
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;';
|
|
233
|
-
thinkingEl.textContent = '💭 对方正在思考...';
|
|
234
|
-
log.appendChild(thinkingEl);
|
|
235
|
-
log.scrollTop = log.scrollHeight;
|
|
236
|
-
} else if (phase === 'token') {
|
|
237
|
-
// 实时更新思考中的 partial
|
|
238
|
-
const thinkingEl = document.getElementById('rcm-thinking-live');
|
|
239
|
-
if (thinkingEl) {
|
|
240
|
-
thinkingEl.textContent = '💭 对方正在思考: ' + (msg.partial || '').slice(-200);
|
|
241
|
-
log.scrollTop = log.scrollHeight;
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
} else if (msg.type === 'cross-mention-received') {
|
|
245
|
-
// v3 新增: A 节点上, 某个 channel 的 LLM @-mention 了另一个 channel, SSE 推过来
|
|
246
|
-
// 在所有打开的 chat modal 上显示"AI 跨渠道 @-mention" 提示
|
|
247
|
-
const allModals = document.querySelectorAll('.rcm-mention-toast, [id^="rcm-log"]');
|
|
248
|
-
for (const log of allModals) {
|
|
249
|
-
if (!log.id) continue;
|
|
250
|
-
const toast = document.createElement('div');
|
|
251
|
-
toast.style.cssText = 'margin:6px 0;padding:8px 10px;background:#fce7f3;border-left:3px solid #ec4899;border-radius:4px;font-size:12px;color:#831843;';
|
|
252
|
-
const fromTxt = msg.source === 'ai-mention-remote' ? `远端节点 ${(msg.fromPublicKey || '').substring(0, 8)}… 的 ${msg.originChannelName}` : `${msg.originChannelName} (本地)`;
|
|
253
|
-
toast.innerHTML = `📡 <b>${fromTxt}</b> @-mention → 当前 channel: <i>${escapeHtml((msg.text || '').slice(0, 100))}</i>${msg.text && msg.text.length > 100 ? '…' : ''}`;
|
|
254
|
-
log.appendChild(toast);
|
|
255
|
-
log.scrollTop = log.scrollHeight;
|
|
256
|
-
}
|
|
257
|
-
} else if (msg.type === 'remote-channel-update') {
|
|
258
|
-
// v3 新增: 远端节点发来新分享 / 删除 / 改名, 立即更新本地 cache
|
|
259
|
-
const peerId = msg.peerId;
|
|
260
|
-
const channels = msg.channels || [];
|
|
261
|
-
const peerName = msg.peerName || null; // 2026-06-10: 同步接收对方名字
|
|
262
|
-
let group = remoteChannels.find(g => g.peerId === peerId);
|
|
263
|
-
if (!group) {
|
|
264
|
-
group = { peerId, channels: [], peerName: peerName || ('peer-' + peerId.substring(0, 8)) };
|
|
265
|
-
remoteChannels.push(group);
|
|
266
|
-
} else if (peerName) {
|
|
267
|
-
group.peerName = peerName; // 更新名字
|
|
268
|
-
}
|
|
269
|
-
group.channels = channels;
|
|
270
|
-
// 2026-06-10: 如果对面告知名字, 同步刷新 knownPeers 列表, 避免陌生 peer 状态
|
|
271
|
-
if (peerName && !knownPeers.find(p => p.publicKey === peerId)) {
|
|
272
|
-
knownPeers.push({
|
|
273
|
-
publicKey: peerId,
|
|
274
|
-
name: peerName,
|
|
275
|
-
addedAt: new Date().toISOString(),
|
|
276
|
-
lastConnectedAt: new Date().toISOString(),
|
|
277
|
-
});
|
|
278
|
-
console.log(`[v3] 远端 ${peerId.substring(0,12)}... 自报名字 = ${peerName}, 已加到 knownPeers`);
|
|
279
|
-
}
|
|
280
|
-
renderRemoteChannels();
|
|
281
|
-
console.log(`[v3] 收到远端 ${peerId.substring(0,12)}... 的 ${channels.length} 个 channel 更新 (name=${peerName || '?'})`);
|
|
282
|
-
} else if (msg.type === 'friend-request') {
|
|
283
|
-
// v3 新增: 收到好友申请
|
|
284
|
-
showFriendRequestModal(msg);
|
|
285
|
-
} else if (msg.type === 'friend-request-ack') {
|
|
286
|
-
// 2026-06-10: 收到对方 ack, 给发送方提示"已送达"
|
|
287
|
-
const pending = window.__pendingFriendRequests;
|
|
288
|
-
if (pending && msg.requestId && pending.has(msg.requestId)) {
|
|
289
|
-
const { name } = pending.get(msg.requestId);
|
|
290
|
-
pending.delete(msg.requestId);
|
|
291
|
-
console.log(`[v3-friend] ✅ ack 收到: ${name} 已收到好友申请`);
|
|
292
|
-
// 简短 toast (右下角), 不阻塞
|
|
293
|
-
showSimpleToast(`📬 ${name} 已收到你的好友申请, 等对方接受`);
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
} catch (err) {
|
|
297
|
-
console.error('[v3] 全局 SSE 解析失败:', err);
|
|
298
|
-
}
|
|
299
|
-
};
|
|
300
|
-
v3GlobalEventSource.onerror = (e) => {
|
|
301
|
-
console.warn('[v3] 全局 SSE 错误');
|
|
302
|
-
};
|
|
303
|
-
} catch (err) {
|
|
304
|
-
console.error('[v3] 启动全局 SSE 失败:', err);
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
|
|
308
108
|
async function createChannel(name) {
|
|
309
109
|
if (!name.trim()) return;
|
|
310
110
|
try {
|
|
@@ -599,50 +399,6 @@ function toggleAgentExpand(channelId, e) {
|
|
|
599
399
|
renderChannels();
|
|
600
400
|
}
|
|
601
401
|
|
|
602
|
-
/**
|
|
603
|
-
* 2026-06-11 性能优化: 切 channel 时用轻量 patch, 不重建整个 sidebar 列表
|
|
604
|
-
* 只更新: (1) active class (2) 当前 session label + count (3) expanded 状态
|
|
605
|
-
* 避免每次切 channel 都 innerHTML='' + 重建 ~10 个 channel 节点
|
|
606
|
-
*/
|
|
607
|
-
function renderChannelsLite(activeChannelId, activeSessionId) {
|
|
608
|
-
if (!channelList) return;
|
|
609
|
-
// 1. 更新所有 .agent-row 的 active class
|
|
610
|
-
channelList.querySelectorAll('.agent-row').forEach(row => {
|
|
611
|
-
const li = row.closest('.agent-group');
|
|
612
|
-
const chId = li?.dataset.channelId;
|
|
613
|
-
row.classList.toggle('active', chId === activeChannelId);
|
|
614
|
-
});
|
|
615
|
-
// 2. 当前 channel 的展开状态: 强制展开, 其他不动
|
|
616
|
-
if (activeChannelId) expandedAgents.add(activeChannelId);
|
|
617
|
-
// 3. 当前 channel 行展开 + 只切 session-item 的 active class (不再 innerHTML 重渲!)
|
|
618
|
-
// 原因: 重渲 innerHTML 会清掉原始 renderChannels 绑的 session-item click handler,
|
|
619
|
-
// 即使补绑也会因为 lite HTML 结构 (.session-dot + .session-msg-count) 跟原始不同
|
|
620
|
-
// 导致"第 1 次点不动 (原始), 第 2 次点才能用 (lite)" 现象
|
|
621
|
-
// 修法: 完全不动 session-list DOM, 只 toggle .active
|
|
622
|
-
const activeLi = channelList.querySelector(`.agent-group[data-channel-id="${activeChannelId}"]`);
|
|
623
|
-
if (activeLi) {
|
|
624
|
-
activeLi.classList.add('expanded');
|
|
625
|
-
// 只切 active class, 不动 innerHTML (避免清掉原始 click handler)
|
|
626
|
-
const ch = channels.find(c => c.id === activeChannelId);
|
|
627
|
-
// 2026-06-11: 原始 renderChannels 已经给 session-item 加了 data-session-id (line 791),
|
|
628
|
-
// 这里先清空所有 .active 再设新的, 避免多个 active 共存 (因为 renderChannels 初始 DOM
|
|
629
|
-
// 上会有一个 active 标记旧 session, 新切 session 容易出现两个 active)
|
|
630
|
-
activeLi.querySelectorAll('.session-item').forEach(sessLi => {
|
|
631
|
-
const sessId = sessLi.dataset.sessionId;
|
|
632
|
-
const shouldBeActive = sessId === activeSessionId;
|
|
633
|
-
sessLi.classList.toggle('active', shouldBeActive);
|
|
634
|
-
});
|
|
635
|
-
// 更新顶部 current session label
|
|
636
|
-
if (ch) {
|
|
637
|
-
const currentSess = Array.isArray(ch.sessions) ? ch.sessions.find(s => s.id === activeSessionId) : null;
|
|
638
|
-
const labelEl = activeLi.querySelector('.agent-current-session');
|
|
639
|
-
if (labelEl) {
|
|
640
|
-
labelEl.textContent = currentSess ? '· ' + formatSessionName(currentSess) : '';
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
|
|
646
402
|
function renderChannels() {
|
|
647
403
|
if (!channelList) return;
|
|
648
404
|
channelList.innerHTML = '';
|
|
@@ -686,9 +442,12 @@ function renderChannels() {
|
|
|
686
442
|
const currentSessLabel = currentSess ? formatSessionName(currentSess) : '';
|
|
687
443
|
const sessionCount = Array.isArray(ch.sessions) ? ch.sessions.length : 0;
|
|
688
444
|
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
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
|
+
: '';
|
|
692
451
|
|
|
693
452
|
row.innerHTML = `
|
|
694
453
|
<svg class="agent-caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
@@ -772,7 +531,6 @@ function renderChannels() {
|
|
|
772
531
|
const sessLi = document.createElement('li');
|
|
773
532
|
const isActive = ch.id === currentChannelId && sess.id === ch.currentSessionId;
|
|
774
533
|
sessLi.className = `session-item ${isActive ? 'active' : ''}`;
|
|
775
|
-
sessLi.dataset.sessionId = sess.id; // 2026-06-11: 给 session-item 加上 data-session-id, renderChannelsLite 才能 toggle active class
|
|
776
534
|
sessLi.innerHTML = `
|
|
777
535
|
<span class="session-name" title="${escapeHtml(formatSessionName(sess))}">${escapeHtml(formatSessionName(sess))}</span>
|
|
778
536
|
<button class="session-delete" title="删除会话">×</button>
|
|
@@ -865,11 +623,6 @@ async function selectChannel(channelId, targetSessionId = null) {
|
|
|
865
623
|
currentChannelId = channelId;
|
|
866
624
|
reconnectAttempts.set(channelId, 0);
|
|
867
625
|
|
|
868
|
-
// v3: 盾牌弹窗打开时, 切 channel 要刷列表 (tab 标题 + 已绑/未绑 分组)
|
|
869
|
-
if (typeof judgmentsModal !== 'undefined' && judgmentsModal && judgmentsModal.classList.contains('active')) {
|
|
870
|
-
if (typeof lastJudgmentsCache !== 'undefined') renderJudgments(lastJudgmentsCache);
|
|
871
|
-
}
|
|
872
|
-
|
|
873
626
|
// 找到当前频道和 session
|
|
874
627
|
const channel = channels.find(c => c.id === channelId);
|
|
875
628
|
if (channel) {
|
|
@@ -883,11 +636,7 @@ async function selectChannel(channelId, targetSessionId = null) {
|
|
|
883
636
|
console.log('[selectChannel] 频道:', channel.name, 'session:', currentSessionId);
|
|
884
637
|
}
|
|
885
638
|
|
|
886
|
-
|
|
887
|
-
// renderChannels() 仍然要调 (current session label 等可能变了), 但加一层判断: 如果只是切 channel (没增删), 走 patch 路径
|
|
888
|
-
const t0 = performance.now();
|
|
889
|
-
renderChannelsLite(channelId, currentSessionId);
|
|
890
|
-
console.log(`[selectChannel] renderChannelsLite 耗时 ${(performance.now() - t0).toFixed(1)}ms`);
|
|
639
|
+
renderChannels();
|
|
891
640
|
|
|
892
641
|
// 确保该频道有消息容器
|
|
893
642
|
const container = ensureMessageContainer(channelId);
|
|
@@ -906,19 +655,10 @@ async function selectChannel(channelId, targetSessionId = null) {
|
|
|
906
655
|
try {
|
|
907
656
|
const res = await fetch(`/sessions/${channelId}?sessionId=${encodeURIComponent(currentSessionId)}`);
|
|
908
657
|
const session = await res.json();
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
const tmpContainer = document.createElement('div');
|
|
914
|
-
tmpContainer.style.display = 'none';
|
|
915
|
-
for (const msg of msgs) {
|
|
916
|
-
addMessage(msg.content, msg.type, false, tmpContainer);
|
|
917
|
-
}
|
|
918
|
-
while (tmpContainer.firstChild) {
|
|
919
|
-
frag.appendChild(tmpContainer.firstChild);
|
|
920
|
-
}
|
|
921
|
-
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
|
+
});
|
|
922
662
|
} else {
|
|
923
663
|
addMessage('你好!我是 Bolloon Agent。有什么我可以帮你的吗?', 'ai', false, container);
|
|
924
664
|
}
|
|
@@ -1169,17 +909,7 @@ function addMessage(content, type, save = true, container) {
|
|
|
1169
909
|
};
|
|
1170
910
|
|
|
1171
911
|
actionsDiv.appendChild(copyBtn);
|
|
1172
|
-
|
|
1173
|
-
// "存为判断" 按钮: 把这条消息正文作为 decision 存到判断库
|
|
1174
|
-
const saveJudgmentBtn = document.createElement('button');
|
|
1175
|
-
saveJudgmentBtn.className = 'action-btn save-as-judgment';
|
|
1176
|
-
saveJudgmentBtn.title = '把这条消息存为判断';
|
|
1177
|
-
saveJudgmentBtn.setAttribute('data-decision', rawContent.substring(0, 800)); // 截断防超长
|
|
1178
|
-
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> 存为判断`;
|
|
1179
|
-
actionsDiv.appendChild(saveJudgmentBtn);
|
|
1180
|
-
if (type === 'ai') {
|
|
1181
|
-
actionsDiv.appendChild(regenerateBtn);
|
|
1182
|
-
}
|
|
912
|
+
actionsDiv.appendChild(regenerateBtn);
|
|
1183
913
|
div.appendChild(actionsDiv);
|
|
1184
914
|
}
|
|
1185
915
|
|
|
@@ -1196,8 +926,8 @@ let agentStatusState = null; // 'planning' | 'executing' | null
|
|
|
1196
926
|
let agentStatusTextIdx = 0;
|
|
1197
927
|
|
|
1198
928
|
const AGENT_STATUS_TEXTS = {
|
|
1199
|
-
planning: ['
|
|
1200
|
-
executing: ['
|
|
929
|
+
planning: ['正在计划下一步行动', '正在规划任务路径', '正在分析当前状态'],
|
|
930
|
+
executing: ['正在执行下一步行动', '正在执行任务', '正在调用工具'],
|
|
1201
931
|
};
|
|
1202
932
|
|
|
1203
933
|
function setAgentStatus(state) {
|
|
@@ -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
|
|
|
@@ -1660,19 +1387,7 @@ function connect(channelId) {
|
|
|
1660
1387
|
const container = messagesContainers.get(msgChannelId) || messagesEl;
|
|
1661
1388
|
|
|
1662
1389
|
if (data.type === 'user') {
|
|
1663
|
-
|
|
1664
|
-
// 1. sendMessage 已经在客户端 addMessage(text, 'user', true) 渲染成 .bubble-user 气泡
|
|
1665
|
-
// 2. SSE 推 user 又调 showUserCommand → 同时出现气泡 + 装饰条 (双重显示)
|
|
1666
|
-
// 3. 第二次切 channel 时, showUserCommand 会 remove 已有 .message-user 元素 (line 1477),
|
|
1667
|
-
// 但 .bubble-user class 不是 .message-user → 残留装饰条, 表现"模式变了"
|
|
1668
|
-
// 改法: SSE 收到 user 后, 跳过显示 (lastUserCommand 已经匹配, addMessage(save=true) 内部去重)
|
|
1669
|
-
// 但要确保 lastUserCommand 已经设过 — sendMessage 调 addMessage(true) 时会设
|
|
1670
|
-
// 远端 user (source === 'remote') 不会被 sendMessage 渲染, 需要走 addMessage 一次
|
|
1671
|
-
if (data.source === 'remote') {
|
|
1672
|
-
// 远端访客 (B 通过 P2P 发来的), sendMessage 没渲染它, 这里补上气泡
|
|
1673
|
-
addMessage(data.content, 'user', true, container);
|
|
1674
|
-
}
|
|
1675
|
-
// 本地 user 已经由 sendMessage 渲染 + 去重, 这里不再显示
|
|
1390
|
+
showUserCommand(data.content, container);
|
|
1676
1391
|
} else if (data.type === 'ai') {
|
|
1677
1392
|
addMessage(data.content, 'ai', true, container);
|
|
1678
1393
|
hideTyping();
|
|
@@ -1725,14 +1440,6 @@ async function sendMessage() {
|
|
|
1725
1440
|
const text = input.value.trim();
|
|
1726
1441
|
if (!text) return;
|
|
1727
1442
|
|
|
1728
|
-
// 2026-06-11: 立即把用户消息渲染成气泡上屏 (走 .bubble-user, 跟本地聊天一致)
|
|
1729
|
-
// 之前只靠 SSE `type: user` 回调显示, 但 addMessage(user) 默认 save=true 走去重, 容易跟 SSE 二次显示冲突/丢失
|
|
1730
|
-
// 现在: sendMessage 自己上屏, SSE `user` 回调来时因为 lastUserCommand 已匹配, 自动跳过 → 不重复
|
|
1731
|
-
const container = messagesContainers.get(currentChannelId) || messagesEl;
|
|
1732
|
-
addMessage(text, 'user', true, container);
|
|
1733
|
-
// 滚动到底
|
|
1734
|
-
if (container) container.scrollTop = container.scrollHeight;
|
|
1735
|
-
|
|
1736
1443
|
input.value = '';
|
|
1737
1444
|
showTyping();
|
|
1738
1445
|
|
|
@@ -1789,385 +1496,6 @@ input.addEventListener('keydown', (e) => {
|
|
|
1789
1496
|
}
|
|
1790
1497
|
});
|
|
1791
1498
|
|
|
1792
|
-
// ============ v3 新增: @-mention 单选自动补全 (主聊天框 #input) ============
|
|
1793
|
-
let mentionChannels = []; // { id, name, source: 'local'|'remote', ownerPublicKey? }
|
|
1794
|
-
let mentionDropdownEl = null;
|
|
1795
|
-
let mentionHighlightIdx = -1;
|
|
1796
|
-
let mentionQuery = null;
|
|
1797
|
-
let mentionAnchor = -1; // @ 字符的绝对位置 (固定, 直到 dropdown 关闭)
|
|
1798
|
-
let mentionBlockEnd = -1; // 插入区块的终点 (单选模式下 = anchor + 1 + query)
|
|
1799
|
-
let mentionDocMousedownBound = false; // 防止重复注册 document mousedown
|
|
1800
|
-
|
|
1801
|
-
function ensureMentionDocMousedown() {
|
|
1802
|
-
if (mentionDocMousedownBound) return;
|
|
1803
|
-
mentionDocMousedownBound = true;
|
|
1804
|
-
document.addEventListener('mousedown', (e) => {
|
|
1805
|
-
if (mentionDropdownEl && !mentionDropdownEl.contains(e.target) && e.target !== input) {
|
|
1806
|
-
closeMentionDropdown();
|
|
1807
|
-
}
|
|
1808
|
-
});
|
|
1809
|
-
}
|
|
1810
|
-
|
|
1811
|
-
async function refreshMentionChannels() {
|
|
1812
|
-
try {
|
|
1813
|
-
const res = await fetch('/channels');
|
|
1814
|
-
const local = res.ok ? await res.json() : [];
|
|
1815
|
-
const r2 = await fetch('/api/remote-channels');
|
|
1816
|
-
const remoteData = r2.ok ? await r2.json() : { peers: [] };
|
|
1817
|
-
const remote = [];
|
|
1818
|
-
for (const p of (remoteData.peers || [])) {
|
|
1819
|
-
for (const c of (p.channels || [])) {
|
|
1820
|
-
remote.push({ id: c.id, name: c.name, source: 'remote', ownerPublicKey: p.peerId });
|
|
1821
|
-
}
|
|
1822
|
-
}
|
|
1823
|
-
mentionChannels = [
|
|
1824
|
-
...(Array.isArray(local) ? local.map(c => ({ id: c.id, name: c.name, source: 'local' })) : []),
|
|
1825
|
-
...remote
|
|
1826
|
-
];
|
|
1827
|
-
} catch (err) {
|
|
1828
|
-
console.warn('[mention] 加载渠道列表失败:', err);
|
|
1829
|
-
}
|
|
1830
|
-
}
|
|
1831
|
-
|
|
1832
|
-
function closeMentionDropdown() {
|
|
1833
|
-
if (mentionDropdownEl) { mentionDropdownEl.remove(); mentionDropdownEl = null; }
|
|
1834
|
-
mentionHighlightIdx = -1;
|
|
1835
|
-
mentionQuery = null;
|
|
1836
|
-
mentionAnchor = -1;
|
|
1837
|
-
mentionBlockEnd = -1;
|
|
1838
|
-
// 不重置 mentionDocMousedownBound — 监听器是空操作 (mentionDropdownEl === null) 留着无妨, 避免重复绑
|
|
1839
|
-
}
|
|
1840
|
-
|
|
1841
|
-
function getCurrentMentionQuery() {
|
|
1842
|
-
const pos = input.selectionStart || input.value.length;
|
|
1843
|
-
const before = input.value.slice(0, pos);
|
|
1844
|
-
const m = before.match(/@([一-龥A-Za-z0-9_\-]{0,30})$/);
|
|
1845
|
-
return m ? { query: m[1], anchor: pos - m[0].length } : null;
|
|
1846
|
-
}
|
|
1847
|
-
|
|
1848
|
-
function renderMentionDropdown(items) {
|
|
1849
|
-
if (!mentionDropdownEl) {
|
|
1850
|
-
mentionDropdownEl = document.createElement('div');
|
|
1851
|
-
mentionDropdownEl.id = 'mention-dropdown';
|
|
1852
|
-
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;';
|
|
1853
|
-
document.body.appendChild(mentionDropdownEl);
|
|
1854
|
-
ensureMentionDocMousedown();
|
|
1855
|
-
}
|
|
1856
|
-
// v3 简化: 单选 + 立即填入输入框
|
|
1857
|
-
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;">
|
|
1858
|
-
<span>💡 点击或回车选中 → 自动填入输入框</span>
|
|
1859
|
-
<span style="color:#9ca3af;">↑↓ 移动</span>
|
|
1860
|
-
</div>`;
|
|
1861
|
-
|
|
1862
|
-
if (items.length === 0) {
|
|
1863
|
-
mentionDropdownEl.innerHTML = headerHtml + '<div style="padding:10px 12px;color:#6b7280;font-size:12px;">没有匹配的渠道</div>';
|
|
1864
|
-
} else {
|
|
1865
|
-
const rows = items.map((c, i) => {
|
|
1866
|
-
const isLocal = c.source === 'local';
|
|
1867
|
-
const tag = isLocal ? '🏠 本地' : '🌐 远端';
|
|
1868
|
-
const owner = !isLocal && c.ownerPublicKey ? ` <span style="color:#9ca3af;font-size:11px;">(${c.ownerPublicKey.substring(0, 8)}…)</span>` : '';
|
|
1869
|
-
// 浅蓝 = 键盘高亮, 白 = 普通
|
|
1870
|
-
const bg = i === mentionHighlightIdx ? '#eff6ff' : '#fff';
|
|
1871
|
-
const borderLeft = i === mentionHighlightIdx ? '3px solid #93c5fd' : '3px solid transparent';
|
|
1872
|
-
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};">
|
|
1873
|
-
<span style="font-size:10px;color:${isLocal ? '#059669' : '#2563eb'};background:${isLocal ? '#d1fae5' : '#dbeafe'};padding:1px 6px;border-radius:3px;white-space:nowrap;">${tag}</span>
|
|
1874
|
-
<span style="flex:1;">${escapeHtml(c.name)}</span>${owner}
|
|
1875
|
-
</div>`;
|
|
1876
|
-
}).join('');
|
|
1877
|
-
mentionDropdownEl.innerHTML = headerHtml + rows;
|
|
1878
|
-
mentionDropdownEl.querySelectorAll('.mention-item').forEach((el) => {
|
|
1879
|
-
const idx = parseInt(el.getAttribute('data-idx'));
|
|
1880
|
-
el.onclick = () => {
|
|
1881
|
-
// 单击 → 立即填入输入框 + 关闭 dropdown
|
|
1882
|
-
applyMention(items[idx]);
|
|
1883
|
-
};
|
|
1884
|
-
// v3 关键修复: mouseenter 只更新高亮, 不重建 dropdown — 否则用户实际点击的 element 被销毁,
|
|
1885
|
-
// click 事件落到新 element, 但实际触发的是新 element 的 onclick (空), 而不是被销毁前那个
|
|
1886
|
-
el.onmouseenter = () => {
|
|
1887
|
-
if (mentionHighlightIdx === idx) return;
|
|
1888
|
-
mentionHighlightIdx = idx;
|
|
1889
|
-
// 只更新背景色 + 左边框, 不重建 innerHTML
|
|
1890
|
-
const itemEls = mentionDropdownEl.querySelectorAll('.mention-item');
|
|
1891
|
-
itemEls.forEach((ie, ii) => {
|
|
1892
|
-
const isHi = ii === idx;
|
|
1893
|
-
ie.style.background = isHi ? '#eff6ff' : '#fff';
|
|
1894
|
-
ie.style.borderLeft = isHi ? '3px solid #93c5fd' : '3px solid transparent';
|
|
1895
|
-
});
|
|
1896
|
-
};
|
|
1897
|
-
});
|
|
1898
|
-
}
|
|
1899
|
-
const rect = input.getBoundingClientRect();
|
|
1900
|
-
mentionDropdownEl.style.left = rect.left + 'px';
|
|
1901
|
-
mentionDropdownEl.style.top = 'auto';
|
|
1902
|
-
mentionDropdownEl.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
|
|
1903
|
-
}
|
|
1904
|
-
|
|
1905
|
-
/** v3 单选: 把 @xxx 替换为 @渠道名 + 空格, 关闭 dropdown, 光标放空格后 */
|
|
1906
|
-
function applyMention(channel) {
|
|
1907
|
-
const anchor = mentionAnchor;
|
|
1908
|
-
const blockEnd = mentionBlockEnd >= 0 ? mentionBlockEnd : (anchor + 1 + (mentionQuery || '').length);
|
|
1909
|
-
if (anchor < 0 || anchor > input.value.length || input.value[anchor] !== '@') {
|
|
1910
|
-
closeMentionDropdown();
|
|
1911
|
-
return;
|
|
1912
|
-
}
|
|
1913
|
-
const before = input.value.slice(0, anchor); // 含 @
|
|
1914
|
-
const after = input.value.slice(blockEnd); // query 之后 (可能用户已输入正文)
|
|
1915
|
-
const insert = `@${channel.name} `;
|
|
1916
|
-
input.value = before + insert + after;
|
|
1917
|
-
const newPos = before.length + insert.length;
|
|
1918
|
-
input.focus();
|
|
1919
|
-
input.setSelectionRange(newPos, newPos);
|
|
1920
|
-
closeMentionDropdown();
|
|
1921
|
-
}
|
|
1922
|
-
|
|
1923
|
-
function updateMentionDropdown() {
|
|
1924
|
-
// 2026-06-10 修: 数组空时主动刷一次, 不再静默 return
|
|
1925
|
-
// 之前 `if (!mentionChannels.length) return` 导致初始化 0-8s 窗口按 @ 看不到任何 item
|
|
1926
|
-
if (!mentionChannels.length) {
|
|
1927
|
-
refreshMentionChannels().then(() => {
|
|
1928
|
-
// 拉完再重试一次 (异步, 不阻塞当前键击)
|
|
1929
|
-
if (mentionChannels.length) updateMentionDropdown();
|
|
1930
|
-
});
|
|
1931
|
-
return;
|
|
1932
|
-
}
|
|
1933
|
-
const m = getCurrentMentionQuery();
|
|
1934
|
-
if (!m) { closeMentionDropdown(); return; }
|
|
1935
|
-
// 只在 dropdown 刚打开时设置 anchor (blockEnd 跟着 insert 走)
|
|
1936
|
-
if (mentionAnchor === -1) {
|
|
1937
|
-
mentionAnchor = m.anchor;
|
|
1938
|
-
mentionBlockEnd = m.anchor + 1 + (m.query || '').length;
|
|
1939
|
-
// dropdown 首次打开 → 强制刷一次, 保证 remote 列表最新
|
|
1940
|
-
refreshMentionChannels();
|
|
1941
|
-
}
|
|
1942
|
-
mentionQuery = m.query;
|
|
1943
|
-
const q = m.query.toLowerCase();
|
|
1944
|
-
const items = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
1945
|
-
mentionHighlightIdx = items.length > 0 ? 0 : -1;
|
|
1946
|
-
renderMentionDropdown(items);
|
|
1947
|
-
}
|
|
1948
|
-
|
|
1949
|
-
input.addEventListener('input', () => {
|
|
1950
|
-
updateMentionDropdown();
|
|
1951
|
-
});
|
|
1952
|
-
input.addEventListener('keydown', (e) => {
|
|
1953
|
-
if (!mentionDropdownEl) return;
|
|
1954
|
-
const items = mentionDropdownEl.querySelectorAll('.mention-item');
|
|
1955
|
-
if (e.key === 'ArrowDown') {
|
|
1956
|
-
e.preventDefault();
|
|
1957
|
-
if (items.length === 0) return;
|
|
1958
|
-
mentionHighlightIdx = (mentionHighlightIdx + 1) % items.length;
|
|
1959
|
-
const q = (mentionQuery || '').toLowerCase();
|
|
1960
|
-
const filtered = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
1961
|
-
renderMentionDropdown(filtered);
|
|
1962
|
-
} else if (e.key === 'ArrowUp') {
|
|
1963
|
-
e.preventDefault();
|
|
1964
|
-
if (items.length === 0) return;
|
|
1965
|
-
mentionHighlightIdx = (mentionHighlightIdx - 1 + items.length) % items.length;
|
|
1966
|
-
const q = (mentionQuery || '').toLowerCase();
|
|
1967
|
-
const filtered = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
1968
|
-
renderMentionDropdown(filtered);
|
|
1969
|
-
} else if (e.key === 'Enter' || e.key === 'Tab') {
|
|
1970
|
-
// 单选: Enter/Tab 立即填入 + 关闭 dropdown
|
|
1971
|
-
if (items.length > 0) {
|
|
1972
|
-
e.preventDefault();
|
|
1973
|
-
e.stopPropagation();
|
|
1974
|
-
const q = (mentionQuery || '').toLowerCase();
|
|
1975
|
-
const filtered = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
1976
|
-
const cur = filtered[mentionHighlightIdx];
|
|
1977
|
-
if (cur) applyMention(cur);
|
|
1978
|
-
}
|
|
1979
|
-
} else if (e.key === 'Escape') {
|
|
1980
|
-
e.preventDefault();
|
|
1981
|
-
closeMentionDropdown();
|
|
1982
|
-
}
|
|
1983
|
-
}, true); // capture phase, 先于 sendMessage 那个 keydown
|
|
1984
|
-
|
|
1985
|
-
// 初始化
|
|
1986
|
-
refreshMentionChannels();
|
|
1987
|
-
// 定时刷新 (channel 列表可能变化)
|
|
1988
|
-
setInterval(refreshMentionChannels, 5000);
|
|
1989
|
-
// 远端 channel 列表变化时也刷新 (loadRemoteChannels 是 function declaration, 不能重新赋值)
|
|
1990
|
-
// 用 setInterval 兜底: 每 5s 刷一次 (已经有定时器, 这里不重复)
|
|
1991
|
-
// 实际上 refreshMentionChannels() 已经在 setInterval 里跑了
|
|
1992
|
-
|
|
1993
|
-
// v3 新增: 通用版 @-autocomplete (任意 input 元素都能挂, 比如 B 端的 #rcm-input)
|
|
1994
|
-
function setupMentionAutocomplete(inputEl) {
|
|
1995
|
-
if (!inputEl || inputEl.__mentionBound) return;
|
|
1996
|
-
inputEl.__mentionBound = true;
|
|
1997
|
-
let localQuery = null;
|
|
1998
|
-
let localAnchor = -1; // @ 字符的绝对位置 (固定, 直到 dropdown 关闭)
|
|
1999
|
-
let localBlockEnd = -1; // 插入区块的终点
|
|
2000
|
-
let localHighlight = -1;
|
|
2001
|
-
|
|
2002
|
-
function closeLocal() {
|
|
2003
|
-
if (inputEl.__mentionDD) { inputEl.__mentionDD.remove(); inputEl.__mentionDD = null; }
|
|
2004
|
-
localHighlight = -1; localQuery = null; localAnchor = -1; localBlockEnd = -1;
|
|
2005
|
-
}
|
|
2006
|
-
|
|
2007
|
-
function detectQuery() {
|
|
2008
|
-
const pos = inputEl.selectionStart || inputEl.value.length;
|
|
2009
|
-
const before = inputEl.value.slice(0, pos);
|
|
2010
|
-
const m = before.match(/@([一-龥A-Za-z0-9_\-]{0,30})$/);
|
|
2011
|
-
return m ? { query: m[1], anchor: pos - m[0].length } : null;
|
|
2012
|
-
}
|
|
2013
|
-
|
|
2014
|
-
// v3 单选: 点击 / Enter 立即填入输入框 + 关闭 dropdown
|
|
2015
|
-
function applyLocal(channel) {
|
|
2016
|
-
const anchor = localAnchor;
|
|
2017
|
-
const blockEnd = localBlockEnd >= 0 ? localBlockEnd : (anchor + 1 + (localQuery || '').length);
|
|
2018
|
-
if (anchor < 0 || anchor > inputEl.value.length || inputEl.value[anchor] !== '@') {
|
|
2019
|
-
closeLocal();
|
|
2020
|
-
return;
|
|
2021
|
-
}
|
|
2022
|
-
const before = inputEl.value.slice(0, anchor); // 含 @
|
|
2023
|
-
const after = inputEl.value.slice(blockEnd);
|
|
2024
|
-
const insert = `@${channel.name} `;
|
|
2025
|
-
inputEl.value = before + insert + after;
|
|
2026
|
-
const newPos = before.length + insert.length;
|
|
2027
|
-
inputEl.focus();
|
|
2028
|
-
inputEl.setSelectionRange(newPos, newPos);
|
|
2029
|
-
closeLocal();
|
|
2030
|
-
}
|
|
2031
|
-
|
|
2032
|
-
function renderLocal(items) {
|
|
2033
|
-
if (!inputEl.__mentionDD) {
|
|
2034
|
-
inputEl.__mentionDD = document.createElement('div');
|
|
2035
|
-
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;';
|
|
2036
|
-
document.body.appendChild(inputEl.__mentionDD);
|
|
2037
|
-
}
|
|
2038
|
-
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;">
|
|
2039
|
-
<span>💡 点击或回车选中 → 自动填入输入框</span>
|
|
2040
|
-
<span style="color:#9ca3af;">↑↓ 移动</span>
|
|
2041
|
-
</div>`;
|
|
2042
|
-
if (items.length === 0) {
|
|
2043
|
-
inputEl.__mentionDD.innerHTML = headerHtml + '<div style="padding:10px 12px;color:#6b7280;font-size:12px;">没有匹配的渠道</div>';
|
|
2044
|
-
} else {
|
|
2045
|
-
inputEl.__mentionDD.innerHTML = headerHtml + items.map((c, i) => {
|
|
2046
|
-
const isLocal = c.source === 'local';
|
|
2047
|
-
const tag = isLocal ? '🏠 本地' : '🌐 远端';
|
|
2048
|
-
const owner = !isLocal && c.ownerPublicKey ? ` <span style="color:#9ca3af;font-size:11px;">(${c.ownerPublicKey.substring(0, 8)}…)</span>` : '';
|
|
2049
|
-
const bg = i === localHighlight ? '#eff6ff' : '#fff';
|
|
2050
|
-
const borderLeft = i === localHighlight ? '3px solid #93c5fd' : '3px solid transparent';
|
|
2051
|
-
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};">
|
|
2052
|
-
<span style="font-size:10px;color:${isLocal ? '#059669' : '#2563eb'};background:${isLocal ? '#d1fae5' : '#dbeafe'};padding:1px 6px;border-radius:3px;white-space:nowrap;">${tag}</span>
|
|
2053
|
-
<span style="flex:1;">${escapeHtml(c.name)}</span>${owner}
|
|
2054
|
-
</div>`;
|
|
2055
|
-
}).join('');
|
|
2056
|
-
inputEl.__mentionDD.querySelectorAll('.mention-item').forEach((el) => {
|
|
2057
|
-
const idx = parseInt(el.getAttribute('data-idx'));
|
|
2058
|
-
el.onclick = () => applyLocal(items[idx]);
|
|
2059
|
-
// v3 关键修复: mouseenter 只更新高亮, 不重建 dropdown (同主 input)
|
|
2060
|
-
el.onmouseenter = () => {
|
|
2061
|
-
if (localHighlight === idx) return;
|
|
2062
|
-
localHighlight = idx;
|
|
2063
|
-
const itemEls = inputEl.__mentionDD.querySelectorAll('.mention-item');
|
|
2064
|
-
itemEls.forEach((ie, ii) => {
|
|
2065
|
-
const isHi = ii === idx;
|
|
2066
|
-
ie.style.background = isHi ? '#eff6ff' : '#fff';
|
|
2067
|
-
ie.style.borderLeft = isHi ? '3px solid #93c5fd' : '3px solid transparent';
|
|
2068
|
-
});
|
|
2069
|
-
};
|
|
2070
|
-
});
|
|
2071
|
-
}
|
|
2072
|
-
const rect = inputEl.getBoundingClientRect();
|
|
2073
|
-
inputEl.__mentionDD.style.left = rect.left + 'px';
|
|
2074
|
-
inputEl.__mentionDD.style.top = 'auto';
|
|
2075
|
-
inputEl.__mentionDD.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
|
|
2076
|
-
}
|
|
2077
|
-
|
|
2078
|
-
function update() {
|
|
2079
|
-
// 2026-06-10 修: 与主输入框同步 — 数组空时主动刷新, 首次打开 dropdown 强制刷新
|
|
2080
|
-
if (!mentionChannels.length) {
|
|
2081
|
-
refreshMentionChannels().then(() => {
|
|
2082
|
-
if (mentionChannels.length) update();
|
|
2083
|
-
});
|
|
2084
|
-
return;
|
|
2085
|
-
}
|
|
2086
|
-
const m = detectQuery();
|
|
2087
|
-
if (!m) { closeLocal(); return; }
|
|
2088
|
-
if (localAnchor === -1) {
|
|
2089
|
-
localAnchor = m.anchor;
|
|
2090
|
-
localBlockEnd = m.anchor + 1 + (m.query || '').length;
|
|
2091
|
-
// dropdown 首次打开 → 强制刷一次保证 remote 最新
|
|
2092
|
-
refreshMentionChannels();
|
|
2093
|
-
}
|
|
2094
|
-
localQuery = m.query;
|
|
2095
|
-
const q = m.query.toLowerCase();
|
|
2096
|
-
const items = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
2097
|
-
localHighlight = items.length > 0 ? 0 : -1;
|
|
2098
|
-
renderLocal(items);
|
|
2099
|
-
}
|
|
2100
|
-
|
|
2101
|
-
inputEl.addEventListener('input', update);
|
|
2102
|
-
inputEl.addEventListener('keydown', (e) => {
|
|
2103
|
-
if (!inputEl.__mentionDD) return;
|
|
2104
|
-
const items = inputEl.__mentionDD.querySelectorAll('.mention-item');
|
|
2105
|
-
if (e.key === 'ArrowDown') {
|
|
2106
|
-
e.preventDefault();
|
|
2107
|
-
if (items.length === 0) return;
|
|
2108
|
-
localHighlight = (localHighlight + 1) % items.length;
|
|
2109
|
-
const q = (localQuery || '').toLowerCase();
|
|
2110
|
-
renderLocal(mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8));
|
|
2111
|
-
} else if (e.key === 'ArrowUp') {
|
|
2112
|
-
e.preventDefault();
|
|
2113
|
-
if (items.length === 0) return;
|
|
2114
|
-
localHighlight = (localHighlight - 1 + items.length) % items.length;
|
|
2115
|
-
const q = (localQuery || '').toLowerCase();
|
|
2116
|
-
renderLocal(mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8));
|
|
2117
|
-
} else if (e.key === 'Enter' || e.key === 'Tab') {
|
|
2118
|
-
if (items.length > 0) {
|
|
2119
|
-
e.preventDefault();
|
|
2120
|
-
e.stopPropagation();
|
|
2121
|
-
const q = (localQuery || '').toLowerCase();
|
|
2122
|
-
const filtered = mentionChannels.filter(c => c.name.toLowerCase().includes(q)).slice(0, 8);
|
|
2123
|
-
const cur = filtered[localHighlight];
|
|
2124
|
-
if (cur) applyLocal(cur);
|
|
2125
|
-
}
|
|
2126
|
-
} else if (e.key === 'Escape') {
|
|
2127
|
-
e.preventDefault();
|
|
2128
|
-
closeLocal();
|
|
2129
|
-
}
|
|
2130
|
-
}, true);
|
|
2131
|
-
}
|
|
2132
|
-
|
|
2133
|
-
// 拖拽落点: 把判断库里的判断拖到输入框, 直接作为指令发给 AI (走"代我决定"路径).
|
|
2134
|
-
// 用户拖进来后输入框被预填, 点发送就把这条判断作为指令交给当前 agent.
|
|
2135
|
-
const inputArea = document.querySelector('.input-area');
|
|
2136
|
-
if (input && inputArea) {
|
|
2137
|
-
const onDragOver = (e) => {
|
|
2138
|
-
if (e.dataTransfer && Array.from(e.dataTransfer.types || []).includes('application/x-bolloon-judgment')) {
|
|
2139
|
-
e.preventDefault();
|
|
2140
|
-
e.dataTransfer.dropEffect = 'copy';
|
|
2141
|
-
inputArea.classList.add('drop-target');
|
|
2142
|
-
}
|
|
2143
|
-
};
|
|
2144
|
-
const onDragLeave = (e) => {
|
|
2145
|
-
if (e.target === inputArea || !inputArea.contains(e.relatedTarget)) {
|
|
2146
|
-
inputArea.classList.remove('drop-target');
|
|
2147
|
-
}
|
|
2148
|
-
};
|
|
2149
|
-
const onDrop = (e) => {
|
|
2150
|
-
inputArea.classList.remove('drop-target');
|
|
2151
|
-
const raw = e.dataTransfer.getData('application/x-bolloon-judgment');
|
|
2152
|
-
if (!raw) return;
|
|
2153
|
-
e.preventDefault();
|
|
2154
|
-
try {
|
|
2155
|
-
const { id, decision } = JSON.parse(raw);
|
|
2156
|
-
// 预填输入框: 用户可改, 然后发出去 AI 就知道"按这条判断做"
|
|
2157
|
-
const prefix = input.value.trim() ? input.value.trim() + '\n' : '';
|
|
2158
|
-
input.value = `${prefix}按我的判断 #${id?.substring(0, 8) || ''} 执行: ${decision}`;
|
|
2159
|
-
input.focus();
|
|
2160
|
-
// 视觉提示
|
|
2161
|
-
input.style.transition = 'box-shadow 0.3s';
|
|
2162
|
-
input.style.boxShadow = '0 0 0 2px #2563eb';
|
|
2163
|
-
setTimeout(() => { input.style.boxShadow = ''; }, 800);
|
|
2164
|
-
} catch {}
|
|
2165
|
-
};
|
|
2166
|
-
inputArea.addEventListener('dragover', onDragOver);
|
|
2167
|
-
inputArea.addEventListener('dragleave', onDragLeave);
|
|
2168
|
-
inputArea.addEventListener('drop', onDrop);
|
|
2169
|
-
}
|
|
2170
|
-
|
|
2171
1499
|
if (themeToggle) {
|
|
2172
1500
|
themeToggle.addEventListener('click', toggleTheme);
|
|
2173
1501
|
}
|
|
@@ -2604,1409 +1932,76 @@ if (taskModalClose) {
|
|
|
2604
1932
|
taskModalClose.addEventListener('click', hideTaskModal);
|
|
2605
1933
|
}
|
|
2606
1934
|
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
const judgmentReason = document.getElementById('judgment-reason');
|
|
2613
|
-
const judgmentDomain = document.getElementById('judgment-domain');
|
|
2614
|
-
const judgmentStakes = document.getElementById('judgment-stakes');
|
|
2615
|
-
const judgmentSubmitBtn = document.getElementById('judgment-submit-btn');
|
|
2616
|
-
const judgmentError = document.getElementById('judgment-error');
|
|
2617
|
-
const judgmentsList = document.getElementById('judgments-list');
|
|
2618
|
-
const judgmentsBadge = document.getElementById('judgments-badge');
|
|
2619
|
-
|
|
2620
|
-
let judgmentsLoaded = false;
|
|
2621
|
-
|
|
2622
|
-
function showJudgmentsModal() {
|
|
2623
|
-
if (judgmentsModal) judgmentsModal.classList.add('active');
|
|
2624
|
-
if (!judgmentsLoaded) loadJudgments();
|
|
2625
|
-
else renderJudgments(lastJudgmentsCache); // 打开时按当前 channel / tab 重渲
|
|
2626
|
-
}
|
|
2627
|
-
|
|
2628
|
-
function switchJudgmentTab(tab) {
|
|
2629
|
-
currentJudgmentTab = tab;
|
|
2630
|
-
document.querySelectorAll('.judgment-tab').forEach(btn => {
|
|
2631
|
-
const active = btn.dataset.tab === tab;
|
|
2632
|
-
btn.classList.toggle('active', active);
|
|
2633
|
-
btn.style.borderBottomColor = active ? '#2563eb' : 'transparent';
|
|
2634
|
-
btn.style.color = active ? '#2563eb' : '#6b7280';
|
|
1935
|
+
if (taskModal) {
|
|
1936
|
+
taskModal.addEventListener('click', (e) => {
|
|
1937
|
+
if (e.target === taskModal) {
|
|
1938
|
+
hideTaskModal();
|
|
1939
|
+
}
|
|
2635
1940
|
});
|
|
2636
|
-
renderJudgments(lastJudgmentsCache);
|
|
2637
|
-
}
|
|
2638
|
-
|
|
2639
|
-
function hideJudgmentsModal() {
|
|
2640
|
-
if (judgmentsModal) judgmentsModal.classList.remove('active');
|
|
2641
1941
|
}
|
|
2642
1942
|
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
/**
|
|
2647
|
-
* v3 重做: 渲染判断力列表 (受 tab + 当前 channel 影响)
|
|
2648
|
-
* tab = 'channel': 拆为"已绑定" + "未绑定"两组, 每条带 + / × 按钮
|
|
2649
|
-
* tab = 'global': 全部 judgment 列表, 无 + / × 按钮
|
|
2650
|
-
* 如果没选 channel, 'channel' tab 自动显示提示 + 全部 judgment
|
|
2651
|
-
*/
|
|
2652
|
-
function renderJudgments(items) {
|
|
2653
|
-
if (!judgmentsList) return;
|
|
2654
|
-
const all = items || [];
|
|
2655
|
-
const titleEl = document.getElementById('judgments-list-title');
|
|
2656
|
-
const chNameEl = document.getElementById('judgments-tab-channel-name');
|
|
2657
|
-
const currentCh = currentChannelId
|
|
2658
|
-
? channels.find(c => c.id === currentChannelId)
|
|
2659
|
-
: null;
|
|
2660
|
-
|
|
2661
|
-
if (chNameEl) {
|
|
2662
|
-
chNameEl.textContent = currentCh ? `(${currentCh.name})` : '(未选)';
|
|
2663
|
-
}
|
|
2664
|
-
|
|
2665
|
-
if (all.length === 0) {
|
|
2666
|
-
judgmentsList.innerHTML = '<div class="task-empty">还没有判断, 在上面记录第一条吧</div>';
|
|
2667
|
-
if (titleEl) titleEl.textContent = '本 channel 的判断力';
|
|
2668
|
-
return;
|
|
2669
|
-
}
|
|
2670
|
-
|
|
2671
|
-
if (currentJudgmentTab === 'global') {
|
|
2672
|
-
// 全局 tab: 全部 judgment, 简单列表
|
|
2673
|
-
if (titleEl) titleEl.textContent = `全局判断力 (${all.length} 条)`;
|
|
2674
|
-
judgmentsList.innerHTML = renderJudgmentItems(all, { showBindToggle: false });
|
|
2675
|
-
return;
|
|
2676
|
-
}
|
|
2677
|
-
|
|
2678
|
-
// channel tab: 必须有 channel
|
|
2679
|
-
if (!currentCh) {
|
|
2680
|
-
if (titleEl) titleEl.textContent = '本 channel 的判断力';
|
|
2681
|
-
judgmentsList.innerHTML = `
|
|
2682
|
-
<div style="padding:24px 12px;text-align:center;color:#6b7280;font-size:13px;">
|
|
2683
|
-
请先在左侧选中一个 channel,<br>然后这里会显示已绑定和可加入的判断力。
|
|
2684
|
-
</div>
|
|
2685
|
-
`;
|
|
2686
|
-
return;
|
|
2687
|
-
}
|
|
2688
|
-
|
|
2689
|
-
const boundIds = new Set(
|
|
2690
|
-
Array.isArray(currentCh.bound_judgment_ids) ? currentCh.bound_judgment_ids : []
|
|
2691
|
-
);
|
|
2692
|
-
const bound = all.filter(j => boundIds.has(j.id));
|
|
2693
|
-
const unbound = all.filter(j => !boundIds.has(j.id));
|
|
2694
|
-
|
|
2695
|
-
if (titleEl) titleEl.textContent = `${currentCh.name} 的判断力 (已绑 ${bound.length} / 共 ${all.length})`;
|
|
2696
|
-
|
|
2697
|
-
let html = '';
|
|
2698
|
-
if (bound.length > 0) {
|
|
2699
|
-
html += `<div style="font-size:11px;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;padding:8px 4px 4px;">已绑定 (${bound.length})</div>`;
|
|
2700
|
-
html += renderJudgmentItems(bound, { showBindToggle: true, isBound: true });
|
|
2701
|
-
}
|
|
2702
|
-
if (unbound.length > 0) {
|
|
2703
|
-
html += `<div style="font-size:11px;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;padding:14px 4px 4px;">未绑定 (${unbound.length})</div>`;
|
|
2704
|
-
html += renderJudgmentItems(unbound, { showBindToggle: true, isBound: false });
|
|
2705
|
-
}
|
|
2706
|
-
judgmentsList.innerHTML = html;
|
|
1943
|
+
if (taskAddBtn) {
|
|
1944
|
+
taskAddBtn.addEventListener('click', showCreateTaskModal);
|
|
2707
1945
|
}
|
|
2708
1946
|
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
return items.map(j => {
|
|
2712
|
-
const reason = (j.reasons && j.reasons[0]) ? escapeHtml(j.reasons[0]) : '';
|
|
2713
|
-
const domain = (j.context && j.context.domain) ? escapeHtml(j.context.domain) : 'general';
|
|
2714
|
-
const stakes = (j.context && j.context.stakes) ? escapeHtml(j.context.stakes) : 'medium';
|
|
2715
|
-
const bindBtn = showBindToggle
|
|
2716
|
-
? isBound
|
|
2717
|
-
? `<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>`
|
|
2718
|
-
: `<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>`
|
|
2719
|
-
: '';
|
|
2720
|
-
return `
|
|
2721
|
-
<div class="task-item completed judgment-row"
|
|
2722
|
-
data-judgment-id="${escapeHtml(j.id)}"
|
|
2723
|
-
draggable="true"
|
|
2724
|
-
style="cursor:grab;">
|
|
2725
|
-
<div class="task-item-header">
|
|
2726
|
-
<label class="judgment-checkbox" style="display:flex;align-items:center;cursor:pointer;margin-right:8px;" onclick="event.stopPropagation();">
|
|
2727
|
-
<input type="checkbox" class="judgment-select-cb" data-id="${escapeHtml(j.id)}" style="cursor:pointer;" onclick="event.stopPropagation();">
|
|
2728
|
-
</label>
|
|
2729
|
-
<div class="task-item-title">
|
|
2730
|
-
<span class="judgment-decision">${escapeHtml(j.decision)}</span>
|
|
2731
|
-
</div>
|
|
2732
|
-
<span class="task-item-status completed">${stakes}</span>
|
|
2733
|
-
</div>
|
|
2734
|
-
${reason ? `<div class="task-item-desc" style="color:#555;font-size:13px;margin-top:4px;">理由: ${reason}</div>` : ''}
|
|
2735
|
-
<div class="task-item-meta" style="color:#999;font-size:11px;margin-top:4px;display:flex;justify-content:space-between;align-items:center;">
|
|
2736
|
-
<span>${domain} · ${escapeHtml(j.timestamp)} · ${escapeHtml(j.id)}</span>
|
|
2737
|
-
<span style="display:flex;gap:4px;">
|
|
2738
|
-
${bindBtn}
|
|
2739
|
-
<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>
|
|
2740
|
-
<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>
|
|
2741
|
-
</span>
|
|
2742
|
-
</div>
|
|
2743
|
-
</div>
|
|
2744
|
-
`;
|
|
2745
|
-
}).join('');
|
|
1947
|
+
if (taskExecuteNextBtn) {
|
|
1948
|
+
taskExecuteNextBtn.addEventListener('click', executeNextTask);
|
|
2746
1949
|
}
|
|
2747
1950
|
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
try {
|
|
2751
|
-
const res = await fetch('/api/judgments');
|
|
2752
|
-
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
2753
|
-
const data = await res.json();
|
|
2754
|
-
lastJudgmentsCache = data.judgments || [];
|
|
2755
|
-
renderJudgments(lastJudgmentsCache);
|
|
2756
|
-
if (judgmentsBadge) {
|
|
2757
|
-
if (data.count > 0) {
|
|
2758
|
-
judgmentsBadge.textContent = data.count;
|
|
2759
|
-
judgmentsBadge.style.display = '';
|
|
2760
|
-
} else {
|
|
2761
|
-
judgmentsBadge.style.display = 'none';
|
|
2762
|
-
}
|
|
2763
|
-
}
|
|
2764
|
-
judgmentsLoaded = true;
|
|
2765
|
-
} catch (e) {
|
|
2766
|
-
if (judgmentsList) judgmentsList.innerHTML = '<div class="task-empty">加载失败: ' + escapeHtml(e.message) + '</div>';
|
|
2767
|
-
}
|
|
1951
|
+
if (taskCancelBtn) {
|
|
1952
|
+
taskCancelBtn.addEventListener('click', hideCreateTaskModal);
|
|
2768
1953
|
}
|
|
2769
1954
|
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
if (!currentChannelId) {
|
|
2773
|
-
showJudgmentError('请先选中一个 channel');
|
|
2774
|
-
return;
|
|
2775
|
-
}
|
|
2776
|
-
const ch = channels.find(c => c.id === currentChannelId);
|
|
2777
|
-
if (!ch) return;
|
|
2778
|
-
const set = new Set(Array.isArray(ch.bound_judgment_ids) ? ch.bound_judgment_ids : []);
|
|
2779
|
-
if (action === 'bind') set.add(judgmentId);
|
|
2780
|
-
else set.delete(judgmentId);
|
|
2781
|
-
const next = Array.from(set);
|
|
2782
|
-
try {
|
|
2783
|
-
const res = await fetch(`/channels/${currentChannelId}`, {
|
|
2784
|
-
method: 'PATCH',
|
|
2785
|
-
headers: { 'Content-Type': 'application/json' },
|
|
2786
|
-
body: JSON.stringify({ bound_judgment_ids: next })
|
|
2787
|
-
});
|
|
2788
|
-
if (!res.ok) {
|
|
2789
|
-
const err = await res.json().catch(() => ({}));
|
|
2790
|
-
throw new Error(err.error || `HTTP ${res.status}`);
|
|
2791
|
-
}
|
|
2792
|
-
const updated = await res.json();
|
|
2793
|
-
const idx = channels.findIndex(c => c.id === currentChannelId);
|
|
2794
|
-
if (idx >= 0) channels[idx] = updated;
|
|
2795
|
-
// 弹窗开着就刷新, 关着就跳过
|
|
2796
|
-
if (judgmentsModal && judgmentsModal.classList.contains('active')) {
|
|
2797
|
-
renderJudgments(lastJudgmentsCache);
|
|
2798
|
-
}
|
|
2799
|
-
} catch (err) {
|
|
2800
|
-
showJudgmentError('绑定失败: ' + err.message);
|
|
2801
|
-
}
|
|
1955
|
+
if (createTaskModalClose) {
|
|
1956
|
+
createTaskModalClose.addEventListener('click', hideCreateTaskModal);
|
|
2802
1957
|
}
|
|
2803
1958
|
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
const delBtn = e.target.closest && e.target.closest('.judgment-del-btn');
|
|
2809
|
-
const toggleBtn = e.target.closest && e.target.closest('.judgment-toggle-btn');
|
|
2810
|
-
if (editBtn) {
|
|
2811
|
-
const id = editBtn.getAttribute('data-id');
|
|
2812
|
-
await editJudgment(id);
|
|
2813
|
-
} else if (delBtn) {
|
|
2814
|
-
const id = delBtn.getAttribute('data-id');
|
|
2815
|
-
if (!confirm('确定删除这条判断?')) return;
|
|
2816
|
-
try {
|
|
2817
|
-
const res = await fetch('/api/judgments/' + encodeURIComponent(id), { method: 'DELETE' });
|
|
2818
|
-
const out = await res.json();
|
|
2819
|
-
if (!out.ok) throw new Error(out.error || 'delete failed');
|
|
2820
|
-
await loadJudgments();
|
|
2821
|
-
} catch (err) {
|
|
2822
|
-
showJudgmentError('删除失败: ' + err.message);
|
|
2823
|
-
}
|
|
2824
|
-
} else if (toggleBtn) {
|
|
2825
|
-
const id = toggleBtn.getAttribute('data-id');
|
|
2826
|
-
const action = toggleBtn.getAttribute('data-action');
|
|
2827
|
-
await toggleChannelJudgment(id, action);
|
|
1959
|
+
if (createTaskModal) {
|
|
1960
|
+
createTaskModal.addEventListener('click', (e) => {
|
|
1961
|
+
if (e.target === createTaskModal) {
|
|
1962
|
+
hideCreateTaskModal();
|
|
2828
1963
|
}
|
|
2829
1964
|
});
|
|
1965
|
+
}
|
|
2830
1966
|
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
});
|
|
2835
|
-
|
|
2836
|
-
// 拖拽: 每条 judgment 是 drag source, dataTransfer 装 decision text
|
|
2837
|
-
judgmentsList.addEventListener('dragstart', (e) => {
|
|
2838
|
-
const row = e.target.closest && e.target.closest('.judgment-row');
|
|
2839
|
-
if (!row) return;
|
|
2840
|
-
const decision = row.querySelector('.judgment-decision')?.textContent || '';
|
|
2841
|
-
const id = row.getAttribute('data-judgment-id') || '';
|
|
2842
|
-
e.dataTransfer.effectAllowed = 'copy';
|
|
2843
|
-
e.dataTransfer.setData('text/plain', decision);
|
|
2844
|
-
e.dataTransfer.setData('application/x-bolloon-judgment', JSON.stringify({ id, decision }));
|
|
2845
|
-
});
|
|
1967
|
+
if (taskCreateBtn) {
|
|
1968
|
+
taskCreateBtn.addEventListener('click', createTask);
|
|
1969
|
+
}
|
|
2846
1970
|
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
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';
|
|
2851
1976
|
}
|
|
2852
1977
|
});
|
|
2853
1978
|
}
|
|
2854
1979
|
|
|
2855
|
-
//
|
|
2856
|
-
const
|
|
2857
|
-
const judgmentSelectedCount = document.getElementById('judgment-selected-count');
|
|
2858
|
-
const judgmentBulkDeleteBtn = document.getElementById('judgment-bulk-delete-btn');
|
|
2859
|
-
|
|
2860
|
-
function getSelectedJudgmentIds() {
|
|
2861
|
-
if (!judgmentsList) return [];
|
|
2862
|
-
return Array.from(judgmentsList.querySelectorAll('.judgment-select-cb'))
|
|
2863
|
-
.filter(cb => cb.checked)
|
|
2864
|
-
.map(cb => cb.getAttribute('data-id'))
|
|
2865
|
-
.filter(Boolean);
|
|
2866
|
-
}
|
|
1980
|
+
// Handle SSE task status updates
|
|
1981
|
+
const originalOnMessage = window.addEventListener ? null : null;
|
|
2867
1982
|
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
judgmentBulkDeleteBtn.style.opacity = ids.length === 0 ? '0.5' : '1';
|
|
2874
|
-
judgmentBulkDeleteBtn.style.cursor = ids.length === 0 ? 'not-allowed' : 'pointer';
|
|
2875
|
-
}
|
|
2876
|
-
// 全选 checkbox 的 indeterminate / checked 状态同步
|
|
2877
|
-
if (judgmentSelectAll && judgmentsList) {
|
|
2878
|
-
const all = judgmentsList.querySelectorAll('.judgment-select-cb');
|
|
2879
|
-
const checked = Array.from(all).filter(cb => cb.checked);
|
|
2880
|
-
judgmentSelectAll.checked = all.length > 0 && checked.length === all.length;
|
|
2881
|
-
judgmentSelectAll.indeterminate = checked.length > 0 && checked.length < all.length;
|
|
2882
|
-
}
|
|
2883
|
-
}
|
|
1983
|
+
// Extend SSE handler for task updates
|
|
1984
|
+
const originalConnect = connect;
|
|
1985
|
+
connect = async function() {
|
|
1986
|
+
// Call original connect
|
|
1987
|
+
await originalConnect();
|
|
2884
1988
|
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
if (!judgmentsList) return;
|
|
2888
|
-
const checked = e.target.checked;
|
|
2889
|
-
judgmentsList.querySelectorAll('.judgment-select-cb').forEach(cb => { cb.checked = checked; });
|
|
2890
|
-
updateBulkDeleteToolbar();
|
|
2891
|
-
});
|
|
2892
|
-
}
|
|
1989
|
+
// Reconnect SSE for task updates
|
|
1990
|
+
const taskEventSource = new EventSource('/events');
|
|
2893
1991
|
|
|
2894
|
-
|
|
2895
|
-
judgmentBulkDeleteBtn.addEventListener('click', async () => {
|
|
2896
|
-
const ids = getSelectedJudgmentIds();
|
|
2897
|
-
if (ids.length === 0) return;
|
|
2898
|
-
if (!confirm(`确定删除选中的 ${ids.length} 条判断? 此操作不可撤销.`)) return;
|
|
2899
|
-
judgmentBulkDeleteBtn.disabled = true;
|
|
1992
|
+
taskEventSource.onmessage = (e) => {
|
|
2900
1993
|
try {
|
|
2901
|
-
const
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
if (!out.ok) throw new Error(out.error || 'failed');
|
|
2908
|
-
showJudgmentOk(`✓ 批量删除 ${out.deleted} 条${out.notFound?.length ? ` (${out.notFound.length} 条未找到)` : ''}`);
|
|
2909
|
-
await loadJudgments();
|
|
2910
|
-
} catch (err) {
|
|
2911
|
-
showJudgmentError('批量删除失败: ' + err.message);
|
|
2912
|
-
} finally {
|
|
2913
|
-
if (judgmentBulkDeleteBtn) judgmentBulkDeleteBtn.disabled = false;
|
|
2914
|
-
}
|
|
2915
|
-
});
|
|
2916
|
-
}
|
|
1994
|
+
const data = JSON.parse(e.data);
|
|
1995
|
+
if (data.type === 'task_status') {
|
|
1996
|
+
loadTasks();
|
|
1997
|
+
}
|
|
1998
|
+
} catch {}
|
|
1999
|
+
};
|
|
2917
2000
|
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
const all = await (await fetch('/api/judgments')).json();
|
|
2921
|
-
const j = (all.judgments || []).find(x => x.id === id);
|
|
2922
|
-
if (!j) { showJudgmentError('找不到该判断 (可能已删除)'); return; }
|
|
2923
|
-
const newDecision = prompt('修改判断 (decision):', j.decision);
|
|
2924
|
-
if (newDecision === null) return;
|
|
2925
|
-
const newReason = prompt('修改理由 (reason, 留空不改):', (j.reasons && j.reasons[0]) || '');
|
|
2926
|
-
const newStakes = prompt('修改风险 (low/medium/high/critical):', (j.context && j.context.stakes) || 'medium');
|
|
2927
|
-
const patch = {
|
|
2928
|
-
decision: newDecision.trim() || j.decision,
|
|
2929
|
-
reasons: newReason !== null ? [newReason.trim()].filter(Boolean) : j.reasons,
|
|
2930
|
-
context: newStakes ? { ...(j.context || {}), stakes: newStakes } : j.context,
|
|
2001
|
+
taskEventSource.onerror = () => {
|
|
2002
|
+
taskEventSource.close();
|
|
2931
2003
|
};
|
|
2932
|
-
|
|
2933
|
-
const res = await fetch('/api/judgments/' + encodeURIComponent(id), {
|
|
2934
|
-
method: 'PATCH',
|
|
2935
|
-
headers: { 'Content-Type': 'application/json' },
|
|
2936
|
-
body: JSON.stringify(patch),
|
|
2937
|
-
});
|
|
2938
|
-
const out = await res.json();
|
|
2939
|
-
if (!out.ok) throw new Error(out.error || 'update failed');
|
|
2940
|
-
showJudgmentOk('✓ 已更新');
|
|
2941
|
-
await loadJudgments();
|
|
2942
|
-
} catch (err) {
|
|
2943
|
-
showJudgmentError('更新失败: ' + err.message);
|
|
2944
|
-
}
|
|
2945
|
-
}
|
|
2946
|
-
|
|
2947
|
-
async function submitJudgment() {
|
|
2948
|
-
if (!judgmentSubmitBtn) return;
|
|
2949
|
-
const decision = (judgmentDecision?.value || '').trim();
|
|
2950
|
-
const reason = (judgmentReason?.value || '').trim();
|
|
2951
|
-
if (!decision) {
|
|
2952
|
-
if (judgmentError) { judgmentError.textContent = '判断不能为空'; judgmentError.style.display = ''; }
|
|
2953
|
-
return;
|
|
2954
|
-
}
|
|
2955
|
-
judgmentSubmitBtn.disabled = true;
|
|
2956
|
-
if (judgmentError) judgmentError.style.display = 'none';
|
|
2957
|
-
try {
|
|
2958
|
-
const res = await fetch('/api/judgments', {
|
|
2959
|
-
method: 'POST',
|
|
2960
|
-
headers: { 'Content-Type': 'application/json' },
|
|
2961
|
-
body: JSON.stringify({
|
|
2962
|
-
decision,
|
|
2963
|
-
reason: reason || undefined,
|
|
2964
|
-
context: { domain: judgmentDomain?.value, stakes: judgmentStakes?.value },
|
|
2965
|
-
}),
|
|
2966
|
-
});
|
|
2967
|
-
const out = await res.json();
|
|
2968
|
-
if (!out.ok) throw new Error(out.error || 'unknown');
|
|
2969
|
-
if (judgmentDecision) judgmentDecision.value = '';
|
|
2970
|
-
if (judgmentReason) judgmentReason.value = '';
|
|
2971
|
-
await loadJudgments();
|
|
2972
|
-
|
|
2973
|
-
// AI 自动委派: fire-and-forget. 根据 domain 找匹配的远端 agent, 触发 agent_delegate 协议.
|
|
2974
|
-
// 失败也不影响本次记录.
|
|
2975
|
-
try {
|
|
2976
|
-
const del = await fetch('/api/judgments/auto-delegate', {
|
|
2977
|
-
method: 'POST',
|
|
2978
|
-
headers: { 'Content-Type': 'application/json' },
|
|
2979
|
-
body: JSON.stringify({
|
|
2980
|
-
judgmentId: out.judgment.id,
|
|
2981
|
-
capability: judgmentDomain?.value || 'general',
|
|
2982
|
-
instruction: `执行判断: ${out.judgment.decision}` + (reason ? ` (理由: ${reason})` : ''),
|
|
2983
|
-
}),
|
|
2984
|
-
});
|
|
2985
|
-
const delOut = await del.json();
|
|
2986
|
-
if (delOut.matched && delOut.sent) {
|
|
2987
|
-
showJudgmentOk(`✓ 已记录并自动委派给 ${delOut.targetAgent.name}`);
|
|
2988
|
-
} else if (delOut.matched) {
|
|
2989
|
-
showJudgmentOk(`✓ 已记录 (匹配到 ${delOut.targetAgent.name}, 但 ${delOut.reason || '未发送'})`);
|
|
2990
|
-
} else {
|
|
2991
|
-
showJudgmentOk('✓ 已记录 (本地, 无匹配远端 agent)');
|
|
2992
|
-
}
|
|
2993
|
-
} catch (e) {
|
|
2994
|
-
console.warn('[judgments] auto-delegate fire failed:', e);
|
|
2995
|
-
}
|
|
2996
|
-
} catch (e) {
|
|
2997
|
-
if (judgmentError) { judgmentError.textContent = '记录失败: ' + e.message; judgmentError.style.display = ''; }
|
|
2998
|
-
} finally {
|
|
2999
|
-
judgmentSubmitBtn.disabled = false;
|
|
3000
|
-
}
|
|
3001
|
-
}
|
|
3002
|
-
|
|
3003
|
-
if (judgmentsBtn) judgmentsBtn.addEventListener('click', showJudgmentsModal);
|
|
3004
|
-
if (judgmentsModalClose) judgmentsModalClose.addEventListener('click', hideJudgmentsModal);
|
|
3005
|
-
if (judgmentsModal) {
|
|
3006
|
-
judgmentsModal.addEventListener('click', (e) => {
|
|
3007
|
-
if (e.target === judgmentsModal) hideJudgmentsModal();
|
|
3008
|
-
});
|
|
3009
|
-
}
|
|
3010
|
-
|
|
3011
|
-
// --- 导入文件 (.json / .yaml / .md / .txt / .html) ---
|
|
3012
|
-
const judgmentImportBtn = document.getElementById('judgment-import-btn');
|
|
3013
|
-
const judgmentImportFile = document.getElementById('judgment-import-file');
|
|
3014
|
-
|
|
3015
|
-
function showJudgmentError(msg) {
|
|
3016
|
-
if (!judgmentError) return;
|
|
3017
|
-
judgmentError.textContent = msg;
|
|
3018
|
-
judgmentError.style.display = '';
|
|
3019
|
-
judgmentError.style.color = '#b91c1c';
|
|
3020
|
-
}
|
|
3021
|
-
function showJudgmentOk(msg) {
|
|
3022
|
-
if (!judgmentError) return;
|
|
3023
|
-
judgmentError.textContent = msg;
|
|
3024
|
-
judgmentError.style.display = '';
|
|
3025
|
-
judgmentError.style.color = '#15803d';
|
|
3026
|
-
}
|
|
3027
|
-
|
|
3028
|
-
function fileToBase64(file) {
|
|
3029
|
-
return new Promise((resolve, reject) => {
|
|
3030
|
-
const r = new FileReader();
|
|
3031
|
-
r.onload = () => {
|
|
3032
|
-
// result is "data:<mime>;base64,<payload>" — strip prefix
|
|
3033
|
-
const s = String(r.result || '');
|
|
3034
|
-
const idx = s.indexOf(',');
|
|
3035
|
-
resolve(idx >= 0 ? s.substring(idx + 1) : s);
|
|
3036
|
-
};
|
|
3037
|
-
r.onerror = () => reject(r.error || new Error('read failed'));
|
|
3038
|
-
r.readAsDataURL(file);
|
|
3039
|
-
});
|
|
3040
|
-
}
|
|
3041
|
-
|
|
3042
|
-
async function importJudgmentFile(file) {
|
|
3043
|
-
if (!file) return;
|
|
3044
|
-
if (judgmentImportBtn) judgmentImportBtn.disabled = true;
|
|
3045
|
-
try {
|
|
3046
|
-
const content = await fileToBase64(file);
|
|
3047
|
-
const res = await fetch('/api/judgments/import', {
|
|
3048
|
-
method: 'POST',
|
|
3049
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3050
|
-
body: JSON.stringify({ filename: file.name, content }),
|
|
3051
|
-
});
|
|
3052
|
-
const out = await res.json();
|
|
3053
|
-
if (!out.ok) throw new Error(out.error || 'import failed');
|
|
3054
|
-
showJudgmentOk(`✓ 导入 ${out.imported} 条${out.failed ? `, ${out.failed} 条失败` : ''}`);
|
|
3055
|
-
await loadJudgments();
|
|
3056
|
-
} catch (e) {
|
|
3057
|
-
showJudgmentError('导入失败: ' + e.message);
|
|
3058
|
-
} finally {
|
|
3059
|
-
if (judgmentImportBtn) judgmentImportBtn.disabled = false;
|
|
3060
|
-
if (judgmentImportFile) judgmentImportFile.value = '';
|
|
3061
|
-
}
|
|
3062
|
-
}
|
|
3063
|
-
|
|
3064
|
-
if (judgmentImportBtn) {
|
|
3065
|
-
judgmentImportBtn.addEventListener('click', () => {
|
|
3066
|
-
if (judgmentImportFile) judgmentImportFile.click();
|
|
3067
|
-
});
|
|
3068
|
-
}
|
|
3069
|
-
if (judgmentImportFile) {
|
|
3070
|
-
judgmentImportFile.addEventListener('change', (e) => {
|
|
3071
|
-
const f = e.target.files && e.target.files[0];
|
|
3072
|
-
if (f) importJudgmentFile(f);
|
|
3073
|
-
});
|
|
3074
|
-
}
|
|
3075
|
-
|
|
3076
|
-
// --- 从对话里 "存为判断": 事件委托到消息容器, 匹配 .save-as-judgment ---
|
|
3077
|
-
document.addEventListener('click', async (e) => {
|
|
3078
|
-
const btn = e.target.closest && e.target.closest('.save-as-judgment');
|
|
3079
|
-
if (!btn) return;
|
|
3080
|
-
e.preventDefault();
|
|
3081
|
-
e.stopPropagation();
|
|
3082
|
-
const decision = (btn.getAttribute('data-decision') || '').trim();
|
|
3083
|
-
if (!decision) return;
|
|
3084
|
-
try {
|
|
3085
|
-
const res = await fetch('/api/judgments', {
|
|
3086
|
-
method: 'POST',
|
|
3087
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3088
|
-
body: JSON.stringify({ decision, reason: '从对话保存' }),
|
|
3089
|
-
});
|
|
3090
|
-
const out = await res.json();
|
|
3091
|
-
if (!out.ok) throw new Error(out.error || 'failed');
|
|
3092
|
-
btn.classList.add('saved');
|
|
3093
|
-
btn.title = '已存为判断';
|
|
3094
|
-
// 顶部徽章会通过 setInterval 拉新数据, 不用手动触发
|
|
3095
|
-
} catch (err) {
|
|
3096
|
-
console.error('[judgments] save-from-chat failed:', err);
|
|
3097
|
-
btn.title = '保存失败: ' + err.message;
|
|
3098
|
-
}
|
|
3099
|
-
});
|
|
3100
|
-
if (judgmentSubmitBtn) judgmentSubmitBtn.addEventListener('click', submitJudgment);
|
|
3101
|
-
|
|
3102
|
-
// 启动时拉一次, 让徽章显示总数 (不打开 modal 也能看到)
|
|
3103
|
-
loadJudgments();
|
|
3104
|
-
// 后台定期刷新 (与 modal 打开/关闭无关, 任何时候都保持徽章新鲜)
|
|
3105
|
-
setInterval(loadJudgments, 10000);
|
|
3106
|
-
|
|
3107
|
-
// ============================================================================
|
|
3108
|
-
// v3: P2P 好友 (known peers) + 收到的分享
|
|
3109
|
-
// ============================================================================
|
|
3110
|
-
|
|
3111
|
-
let knownPeers = []; // { name, publicKey, lastConnectedAt, addedAt }
|
|
3112
|
-
|
|
3113
|
-
async function loadRemoteChannels() {
|
|
3114
|
-
try {
|
|
3115
|
-
// 1) 拉 known peers (好友列表)
|
|
3116
|
-
const res = await fetch('/api/p2p-peers');
|
|
3117
|
-
if (res.ok) {
|
|
3118
|
-
const data = await res.json();
|
|
3119
|
-
knownPeers = Array.isArray(data.peers) ? data.peers : [];
|
|
3120
|
-
}
|
|
3121
|
-
// 2) 2026-06-10 修: 同时拉 /api/remote-channels, 兜底 SSE 推送漏掉的情况
|
|
3122
|
-
// (页面刷新后 remoteChannels[] = [], 必须主动拉一次才有数据)
|
|
3123
|
-
const r2 = await fetch('/api/remote-channels');
|
|
3124
|
-
if (r2.ok) {
|
|
3125
|
-
const data2 = await r2.json();
|
|
3126
|
-
const peers = Array.isArray(data2.peers) ? data2.peers : [];
|
|
3127
|
-
// 合并到 remoteChannels[]: 按 peerId 覆盖
|
|
3128
|
-
for (const p of peers) {
|
|
3129
|
-
let group = remoteChannels.find(g => g.peerId === p.peerId);
|
|
3130
|
-
if (!group) {
|
|
3131
|
-
group = { peerId: p.peerId, channels: [], peerName: ('peer-' + p.peerId.substring(0, 8)) };
|
|
3132
|
-
remoteChannels.push(group);
|
|
3133
|
-
}
|
|
3134
|
-
group.channels = p.channels || [];
|
|
3135
|
-
}
|
|
3136
|
-
}
|
|
3137
|
-
renderRemoteChannels();
|
|
3138
|
-
// 3) 远端数据可能变化, 同步 @-mention 列表
|
|
3139
|
-
if (typeof refreshMentionChannels === 'function') {
|
|
3140
|
-
refreshMentionChannels();
|
|
3141
|
-
}
|
|
3142
|
-
} catch (err) {
|
|
3143
|
-
console.error('[v3] loadRemoteChannels 失败:', err);
|
|
3144
|
-
}
|
|
3145
|
-
}
|
|
3146
|
-
|
|
3147
|
-
function renderRemoteChannels() {
|
|
3148
|
-
const list = document.getElementById('remote-channel-list');
|
|
3149
|
-
if (!list) return;
|
|
3150
|
-
|
|
3151
|
-
// 按 peerId 分组 channels
|
|
3152
|
-
const channelsByPeer = {};
|
|
3153
|
-
for (const p of remoteChannels) {
|
|
3154
|
-
channelsByPeer[p.peerId] = p.channels || [];
|
|
3155
|
-
}
|
|
3156
|
-
|
|
3157
|
-
// 2026-06-10 修: 之前 UI 只渲染 knownPeers, 但对面 publicKey 可能跟本机 known_peers 不匹配
|
|
3158
|
-
// (例如对面重启 / 换 role / 第一次相连还没加为好友), 导致 remoteChannels 里有数据 UI 却空白.
|
|
3159
|
-
// 修法: 把 remoteChannels 里的 "陌生 peer" (不在 known_peers 里) 也渲染出来, 标记为未加好友.
|
|
3160
|
-
const knownPks = new Set(knownPeers.map(p => p.publicKey));
|
|
3161
|
-
const strangerPeers = remoteChannels
|
|
3162
|
-
.filter(p => !knownPks.has(p.peerId))
|
|
3163
|
-
.map(p => ({
|
|
3164
|
-
publicKey: p.peerId,
|
|
3165
|
-
name: p.peerName || ('未授权 ' + p.peerId.substring(0, 8)),
|
|
3166
|
-
lastConnectedAt: null,
|
|
3167
|
-
_isStranger: true
|
|
3168
|
-
}));
|
|
3169
|
-
const allPeers = [...knownPeers, ...strangerPeers];
|
|
3170
|
-
|
|
3171
|
-
if (allPeers.length === 0) {
|
|
3172
|
-
list.innerHTML = '<li style="color:var(--text-muted);font-size:11px;padding:8px 4px;text-align:center;">(暂无好友, 点 + 添加)</li>';
|
|
3173
|
-
return;
|
|
3174
|
-
}
|
|
3175
|
-
|
|
3176
|
-
const html = allPeers.map(peer => {
|
|
3177
|
-
const peerChannels = channelsByPeer[peer.publicKey] || [];
|
|
3178
|
-
const lastConn = peer.lastConnectedAt
|
|
3179
|
-
? new Date(peer.lastConnectedAt).toLocaleDateString()
|
|
3180
|
-
: (peer._isStranger ? '陌生 peer' : '从未连接');
|
|
3181
|
-
const strangerStyle = peer._isStranger ? 'border:1px dashed var(--border-light);' : '';
|
|
3182
|
-
const strangerIcon = peer._isStranger ? '❔' : '👤';
|
|
3183
|
-
// 2026-06-11: 折叠逻辑 (全不展开)
|
|
3184
|
-
// - 所有 peer 首次见都默认 *折叠* (包括 known_peers 第一个) — 用户一进来看到完整 peer 列表
|
|
3185
|
-
// - 标题栏右侧 "X ch" 提示有内容, 用户点 caret 展开
|
|
3186
|
-
// - 已见过: 沿用 collapsedPeers (用户上次选择)
|
|
3187
|
-
// - "全部展开/折叠" 按钮在 P2P header (id=p2p-toggle-all-btn)
|
|
3188
|
-
if (!seenPeers.has(peer.publicKey)) {
|
|
3189
|
-
seenPeers.add(peer.publicKey);
|
|
3190
|
-
collapsedPeers.add(peer.publicKey); // 全部默认折叠
|
|
3191
|
-
saveSeenPeers();
|
|
3192
|
-
saveCollapsedPeers();
|
|
3193
|
-
}
|
|
3194
|
-
const isCollapsed = collapsedPeers.has(peer.publicKey);
|
|
3195
|
-
const caretChar = '▾'; // CSS rotate -90deg 处理折叠态
|
|
3196
|
-
return `
|
|
3197
|
-
<li class="remote-peer-group ${isCollapsed ? 'collapsed' : ''}" style="margin-bottom:10px;${strangerStyle}">
|
|
3198
|
-
<div class="remote-peer-header" data-peer-name="${escapeHtml(peer.name)}" data-peer-pk="${escapeHtml(peer.publicKey)}"
|
|
3199
|
-
style="display:flex;align-items:center;gap:6px;padding:6px 8px;background:var(--bg-hover);border-radius:4px;cursor:pointer;">
|
|
3200
|
-
<button class="peer-caret-btn" data-toggle-peer="${escapeHtml(peer.publicKey)}" title="折叠/展开"
|
|
3201
|
-
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>
|
|
3202
|
-
<span style="font-size:13px;">${strangerIcon}</span>
|
|
3203
|
-
<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>
|
|
3204
|
-
<span style="font-size:9px;color:var(--text-muted);">${peerChannels.length > 0 ? `${peerChannels.length} ch · ` : ''}${lastConn}</span>
|
|
3205
|
-
</div>
|
|
3206
|
-
<div class="remote-peer-channels" style="margin-top:4px;margin-left:8px;">
|
|
3207
|
-
${peerChannels.length === 0
|
|
3208
|
-
? '<div style="font-size:10px;color:var(--text-muted);padding:2px 4px;">(对方还没分享 channel 给你)</div>'
|
|
3209
|
-
: peerChannels.map(c => `
|
|
3210
|
-
<div class="remote-channel-row" data-peer-id="${escapeHtml(peer.publicKey)}" data-channel-id="${escapeHtml(c.id)}"
|
|
3211
|
-
style="display:flex;align-items:center;gap:6px;padding:4px 6px;cursor:pointer;border-radius:4px;font-size:12px;">
|
|
3212
|
-
<span>🤖</span>
|
|
3213
|
-
<span style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${escapeHtml(c.name || '')}">${escapeHtml(c.name || '(未命名)')}</span>
|
|
3214
|
-
</div>
|
|
3215
|
-
`).join('')
|
|
3216
|
-
}
|
|
3217
|
-
</div>
|
|
3218
|
-
</li>
|
|
3219
|
-
`;
|
|
3220
|
-
}).join('');
|
|
3221
|
-
list.innerHTML = html;
|
|
3222
|
-
|
|
3223
|
-
// 2026-06-10: 折叠按钮点击 → 切折叠 (stopPropagation 防止冒泡触发 header 的分享 modal)
|
|
3224
|
-
list.querySelectorAll('.peer-caret-btn[data-toggle-peer]').forEach(btn => {
|
|
3225
|
-
btn.addEventListener('click', (e) => {
|
|
3226
|
-
e.stopPropagation();
|
|
3227
|
-
const pk = btn.getAttribute('data-toggle-peer');
|
|
3228
|
-
togglePeerCollapsed(pk);
|
|
3229
|
-
});
|
|
3230
|
-
});
|
|
3231
|
-
|
|
3232
|
-
// 绑定: 点击 channel → 弹聊天窗口
|
|
3233
|
-
list.querySelectorAll('.remote-channel-row').forEach(row => {
|
|
3234
|
-
row.addEventListener('click', () => {
|
|
3235
|
-
const peerId = row.dataset.peerId;
|
|
3236
|
-
const channelId = row.dataset.channelId;
|
|
3237
|
-
const channelName = row.querySelector('span[title]')?.getAttribute('title') || channelId;
|
|
3238
|
-
console.log('[v3] 点击远端 channel:', peerId.substring(0,12), channelId);
|
|
3239
|
-
openRemoteChannelChat(peerId, channelId, channelName);
|
|
3240
|
-
});
|
|
3241
|
-
});
|
|
3242
|
-
// 绑定: 点击 peer 头部 → 弹分享 modal (让 A 决定分享本机哪些 channel 给这个 peer)
|
|
3243
|
-
list.querySelectorAll('.remote-peer-header').forEach(row => {
|
|
3244
|
-
row.addEventListener('click', (e) => {
|
|
3245
|
-
// 2026-06-10: 防御 — 点 caret 时已 stopPropagation, 但万一冒泡逃逸再挡一道
|
|
3246
|
-
if (e.target.closest('.peer-caret')) return;
|
|
3247
|
-
const peerName = row.dataset.peerName;
|
|
3248
|
-
const peerPk = row.dataset.peerPk;
|
|
3249
|
-
openShareToPeerModal(peerName, peerPk);
|
|
3250
|
-
});
|
|
3251
|
-
});
|
|
3252
|
-
|
|
3253
|
-
// 2026-06-10: 每个 peer 头部双击 → 改名字 / 改备注
|
|
3254
|
-
list.querySelectorAll('.remote-peer-header').forEach(row => {
|
|
3255
|
-
row.addEventListener('dblclick', (e) => {
|
|
3256
|
-
if (e.target.closest('.peer-caret-btn')) return;
|
|
3257
|
-
const peerName = row.dataset.peerName;
|
|
3258
|
-
const peerPk = row.dataset.peerPk;
|
|
3259
|
-
openEditPeerModal(peerName, peerPk);
|
|
3260
|
-
});
|
|
3261
|
-
});
|
|
3262
|
-
|
|
3263
|
-
// 2026-06-10: 渲染完成后同步 header 切换按钮图标
|
|
3264
|
-
if (typeof window.__syncP2PToggleAllBtn === 'function') window.__syncP2PToggleAllBtn();
|
|
3265
|
-
}
|
|
3266
|
-
|
|
3267
|
-
/** v3: 改 peer 名字 / 备注 modal (持久化到 known_peers.json) */
|
|
3268
|
-
async function openEditPeerModal(peerName, peerPublicKey) {
|
|
3269
|
-
document.getElementById('edit-peer-modal')?.remove();
|
|
3270
|
-
// 先读 known_peers 拿到现有 notes
|
|
3271
|
-
let currentNotes = '';
|
|
3272
|
-
let currentName = peerName;
|
|
3273
|
-
try {
|
|
3274
|
-
const r = await fetch('/api/p2p-peers');
|
|
3275
|
-
if (r.ok) {
|
|
3276
|
-
const d = await r.json();
|
|
3277
|
-
const entry = (d.peers || []).find(p => p.publicKey === peerPublicKey);
|
|
3278
|
-
if (entry) {
|
|
3279
|
-
currentName = entry.name || peerName;
|
|
3280
|
-
currentNotes = entry.notes || '';
|
|
3281
|
-
}
|
|
3282
|
-
}
|
|
3283
|
-
} catch {}
|
|
3284
|
-
const html = `
|
|
3285
|
-
<div id="edit-peer-modal" class="friend-req-overlay">
|
|
3286
|
-
<div class="friend-req-shell" style="width:520px;">
|
|
3287
|
-
<div class="friend-req-header">
|
|
3288
|
-
<span style="font-size:18px;">✏️</span>
|
|
3289
|
-
<div style="flex:1;min-width:0;">
|
|
3290
|
-
<div class="friend-req-title">编辑好友</div>
|
|
3291
|
-
<div class="friend-req-meta">publicKey: ${escapeHtml(peerPublicKey.substring(0,16))}…</div>
|
|
3292
|
-
</div>
|
|
3293
|
-
</div>
|
|
3294
|
-
<div class="friend-req-body">
|
|
3295
|
-
<label style="display:block;margin-bottom:6px;font-size:12px;color:var(--text-secondary);">显示名字</label>
|
|
3296
|
-
<input id="epm-name" type="text" value="${escapeHtml(currentName)}"
|
|
3297
|
-
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;">
|
|
3298
|
-
<label style="display:block;margin-bottom:6px;font-size:12px;color:var(--text-secondary);">备注 (自由文本, 例如合作领域 / 怎么认识的)</label>
|
|
3299
|
-
<textarea id="epm-notes" rows="4" placeholder="例如: 2026-06 合作 LLM 代发验证"
|
|
3300
|
-
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>
|
|
3301
|
-
</div>
|
|
3302
|
-
<div class="friend-req-actions">
|
|
3303
|
-
<button id="epm-cancel" class="friend-req-btn-deny">取消</button>
|
|
3304
|
-
<button id="epm-save" class="friend-req-btn-accept">保存</button>
|
|
3305
|
-
</div>
|
|
3306
|
-
</div>
|
|
3307
|
-
</div>
|
|
3308
|
-
`;
|
|
3309
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
3310
|
-
const close = () => document.getElementById('edit-peer-modal')?.remove();
|
|
3311
|
-
document.getElementById('epm-cancel').onclick = close;
|
|
3312
|
-
document.getElementById('epm-save').onclick = async () => {
|
|
3313
|
-
const newName = document.getElementById('epm-name').value.trim() || currentName;
|
|
3314
|
-
const newNotes = document.getElementById('epm-notes').value;
|
|
3315
|
-
try {
|
|
3316
|
-
const r = await fetch(`/api/p2p-peers/${encodeURIComponent(peerName)}`, {
|
|
3317
|
-
method: 'PATCH',
|
|
3318
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3319
|
-
body: JSON.stringify({ name: newName, notes: newNotes })
|
|
3320
|
-
});
|
|
3321
|
-
const data = await r.json();
|
|
3322
|
-
if (!r.ok) throw new Error(data.error || 'save failed');
|
|
3323
|
-
console.log('[v3] 改 peer 成功:', newName, '备注:', newNotes);
|
|
3324
|
-
showSimpleToast(`✅ 已保存 ${newName}`);
|
|
3325
|
-
close();
|
|
3326
|
-
// 重新拉 known_peers + 远程 channels 重新渲染
|
|
3327
|
-
const r2 = await fetch('/api/p2p-peers');
|
|
3328
|
-
if (r2.ok) {
|
|
3329
|
-
const d2 = await r2.json();
|
|
3330
|
-
knownPeers = Array.isArray(d2.peers) ? d2.peers : [];
|
|
3331
|
-
}
|
|
3332
|
-
renderRemoteChannels();
|
|
3333
|
-
} catch (err) {
|
|
3334
|
-
console.error('[v3] 保存 peer 失败:', err);
|
|
3335
|
-
alert('保存失败: ' + (err.message || err));
|
|
3336
|
-
}
|
|
3337
|
-
};
|
|
3338
|
-
}
|
|
3339
|
-
|
|
3340
|
-
/** v3: 分享 channel 给指定 peer 的 modal (A 侧用) */
|
|
3341
|
-
/** v3: 分享 channel 给指定 peer 的 modal (A 侧用) — 2026-06-11 改用 Step 3 风格 class */
|
|
3342
|
-
async function openShareToPeerModal(peerName, peerPublicKey) {
|
|
3343
|
-
document.getElementById('share-to-peer-modal')?.remove();
|
|
3344
|
-
let allChannels = [];
|
|
3345
|
-
try {
|
|
3346
|
-
const res = await fetch('/channels');
|
|
3347
|
-
if (res.ok) allChannels = await res.json();
|
|
3348
|
-
} catch (err) { console.error('openShareToPeerModal:', err); }
|
|
3349
|
-
const rows = allChannels.length === 0
|
|
3350
|
-
? '<div class="share-modal-empty">还没有 channel</div>'
|
|
3351
|
-
: allChannels.map(ch => {
|
|
3352
|
-
const isShared = Array.isArray(ch.shared_with_peers) && ch.shared_with_peers.includes(peerPublicKey);
|
|
3353
|
-
return `
|
|
3354
|
-
<label class="share-modal-row">
|
|
3355
|
-
<input type="checkbox" data-cid="${escapeHtml(ch.id)}" ${isShared ? 'checked' : ''} class="share-modal-cb">
|
|
3356
|
-
<div class="share-modal-row-info">
|
|
3357
|
-
<div class="share-modal-row-name">${escapeHtml(ch.name)}</div>
|
|
3358
|
-
<div class="share-modal-row-meta">
|
|
3359
|
-
${isShared ? '✓ 已分享' : '未分享'} · ${escapeHtml(ch.id.slice(0, 24))}…
|
|
3360
|
-
</div>
|
|
3361
|
-
</div>
|
|
3362
|
-
</label>
|
|
3363
|
-
`;
|
|
3364
|
-
}).join('');
|
|
3365
|
-
const html = `
|
|
3366
|
-
<div id="share-to-peer-modal" class="friend-req-overlay">
|
|
3367
|
-
<div class="friend-req-shell share-modal-shell">
|
|
3368
|
-
<div class="friend-req-header">
|
|
3369
|
-
<span style="font-size:18px;">📤</span>
|
|
3370
|
-
<div style="flex:1;min-width:0;">
|
|
3371
|
-
<div class="friend-req-title">分享 channel 给 ${escapeHtml(peerName)}</div>
|
|
3372
|
-
<div class="friend-req-meta">${escapeHtml(peerPublicKey.substring(0,16))}…</div>
|
|
3373
|
-
</div>
|
|
3374
|
-
<button id="spm-close" class="friend-req-btn-close">×</button>
|
|
3375
|
-
</div>
|
|
3376
|
-
<div class="share-modal-hint">勾选要分享的 channel, 对方才能看到</div>
|
|
3377
|
-
<div id="spm-list" class="share-modal-list">${rows}</div>
|
|
3378
|
-
<div class="friend-req-actions">
|
|
3379
|
-
<button id="spm-cancel" class="friend-req-btn-deny">取消</button>
|
|
3380
|
-
<button id="spm-save" class="friend-req-btn-accept">保存分享</button>
|
|
3381
|
-
</div>
|
|
3382
|
-
</div>
|
|
3383
|
-
</div>
|
|
3384
|
-
`;
|
|
3385
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
3386
|
-
const overlay = document.getElementById('share-to-peer-modal');
|
|
3387
|
-
document.getElementById('spm-close').onclick = () => overlay.remove();
|
|
3388
|
-
document.getElementById('spm-cancel').onclick = () => overlay.remove();
|
|
3389
|
-
document.getElementById('spm-save').onclick = async () => {
|
|
3390
|
-
const checkedIds = [...overlay.querySelectorAll('input[type=checkbox][data-cid]:checked')].map(el => el.dataset.cid);
|
|
3391
|
-
// 对每个 channel 单独 PATCH — 设 shared_with_peers 为 checked 列表
|
|
3392
|
-
let ok = 0, fail = 0;
|
|
3393
|
-
for (const ch of allChannels) {
|
|
3394
|
-
const shouldShare = checkedIds.includes(ch.id);
|
|
3395
|
-
const wasShared = Array.isArray(ch.shared_with_peers) && ch.shared_with_peers.includes(peerPublicKey);
|
|
3396
|
-
if (shouldShare === wasShared) continue;
|
|
3397
|
-
const newList = (ch.shared_with_peers || []).filter((p) => p !== peerPublicKey);
|
|
3398
|
-
if (shouldShare) newList.push(peerPublicKey);
|
|
3399
|
-
try {
|
|
3400
|
-
const res = await fetch(`/channels/${encodeURIComponent(ch.id)}`, {
|
|
3401
|
-
method: 'PATCH',
|
|
3402
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3403
|
-
body: JSON.stringify({ shared_with_peers: newList })
|
|
3404
|
-
});
|
|
3405
|
-
if (res.ok) ok++; else fail++;
|
|
3406
|
-
} catch { fail++; }
|
|
3407
|
-
}
|
|
3408
|
-
showSimpleToast(`分享更新完成: 成功 ${ok}, 失败 ${fail}`, ok > 0 ? 'info' : (fail > 0 ? 'error' : 'info'));
|
|
3409
|
-
overlay.remove();
|
|
3410
|
-
};
|
|
3411
|
-
}
|
|
3412
|
-
|
|
3413
|
-
/** v3: 跟远端 channel 聊天的简易弹窗
|
|
3414
|
-
* 2026-06-10 重写: UI 完全对齐本地聊天 (复用 addMessage / .messages / .bubble 整套样式),
|
|
3415
|
-
* marked.parse + cleanThink + cleanEnv 自动生效, 不再裸文本.
|
|
3416
|
-
*/
|
|
3417
|
-
function openRemoteChannelChat(peerPublicKey, channelId, channelName) {
|
|
3418
|
-
// 移除已有 modal
|
|
3419
|
-
document.getElementById('remote-chat-modal')?.remove();
|
|
3420
|
-
const html = `
|
|
3421
|
-
<div id="remote-chat-modal" class="remote-chat-overlay">
|
|
3422
|
-
<div class="remote-chat-shell">
|
|
3423
|
-
<div class="remote-chat-header">
|
|
3424
|
-
<div style="flex:1;min-width:0;">
|
|
3425
|
-
<div class="remote-chat-title">🌐 跟 ${escapeHtml(channelName)} 聊天</div>
|
|
3426
|
-
<div class="remote-chat-meta">远端 peer: ${escapeHtml(peerPublicKey.substring(0,16))}… · ${escapeHtml(channelId)}</div>
|
|
3427
|
-
</div>
|
|
3428
|
-
<button id="rcm-refresh-history" title="重新拉历史" class="remote-chat-btn-secondary">↻ 历史</button>
|
|
3429
|
-
<button id="rcm-close" class="remote-chat-btn-close">×</button>
|
|
3430
|
-
</div>
|
|
3431
|
-
<div id="rcm-thinking" class="remote-chat-thinking" style="display:none;">
|
|
3432
|
-
📥 正在从远端拉历史 + 判断力…
|
|
3433
|
-
</div>
|
|
3434
|
-
<div id="rcm-log" class="messages remote-chat-log"></div>
|
|
3435
|
-
<div class="remote-chat-input-row">
|
|
3436
|
-
<input id="rcm-input" type="text" placeholder="输入消息, 发送到远端 channel..." class="remote-chat-input">
|
|
3437
|
-
<button id="rcm-send" class="remote-chat-btn-send">发送</button>
|
|
3438
|
-
</div>
|
|
3439
|
-
</div>
|
|
3440
|
-
</div>
|
|
3441
|
-
`;
|
|
3442
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
3443
|
-
|
|
3444
|
-
const log = document.getElementById('rcm-log');
|
|
3445
|
-
const inputEl = document.getElementById('rcm-input');
|
|
3446
|
-
const sendBtn = document.getElementById('rcm-send');
|
|
3447
|
-
const thinkingEl = document.getElementById('rcm-thinking');
|
|
3448
|
-
let historyRefreshTimer = null;
|
|
3449
|
-
document.getElementById('rcm-close').onclick = () => {
|
|
3450
|
-
if (historyRefreshTimer) { clearInterval(historyRefreshTimer); historyRefreshTimer = null; }
|
|
3451
|
-
document.getElementById('remote-chat-modal').remove();
|
|
3452
|
-
};
|
|
3453
|
-
document.getElementById('rcm-refresh-history').onclick = () => loadHistory(false);
|
|
3454
|
-
|
|
3455
|
-
// 2026-06-10 改: 直接复用本地 addMessage, 自动获得 marked + think 折叠 + env 折叠 + 主题变量
|
|
3456
|
-
const append = (text, role) => {
|
|
3457
|
-
addMessage(text, role === 'user' ? 'user' : 'ai', false, log);
|
|
3458
|
-
log.scrollTop = log.scrollHeight;
|
|
3459
|
-
};
|
|
3460
|
-
|
|
3461
|
-
// 系统提示用更轻量的样式 (不走 addMessage, 避免被当聊天记录裁剪)
|
|
3462
|
-
const appendSystem = (text, kind = 'info') => {
|
|
3463
|
-
const el = document.createElement('div');
|
|
3464
|
-
el.className = `remote-chat-sysmsg remote-chat-sysmsg-${kind}`;
|
|
3465
|
-
el.textContent = text;
|
|
3466
|
-
log.appendChild(el);
|
|
3467
|
-
log.scrollTop = log.scrollHeight;
|
|
3468
|
-
};
|
|
3469
|
-
|
|
3470
|
-
// v3 新增: 拉 A 端的 channel 历史 (含 messages + judgments)
|
|
3471
|
-
async function loadHistory(isSilent) {
|
|
3472
|
-
if (!document.getElementById('remote-chat-modal')) return; // modal 已关闭
|
|
3473
|
-
|
|
3474
|
-
if (isSilent) {
|
|
3475
|
-
try {
|
|
3476
|
-
const res = await fetch(`/api/remote-channels/chat-history?targetPublicKey=${encodeURIComponent(peerPublicKey)}&channelId=${encodeURIComponent(channelId)}`);
|
|
3477
|
-
if (!res.ok || !document.getElementById('remote-chat-modal')) return;
|
|
3478
|
-
const data = await res.json();
|
|
3479
|
-
const newMsgs = data.messages || [];
|
|
3480
|
-
const oldCount = log.querySelectorAll('.message').length;
|
|
3481
|
-
if (newMsgs.length === oldCount) return;
|
|
3482
|
-
const scrollWasAtBottom = log.scrollTop + log.clientHeight >= log.scrollHeight - 30;
|
|
3483
|
-
renderHistory(data);
|
|
3484
|
-
if (scrollWasAtBottom) {
|
|
3485
|
-
setTimeout(() => { log.scrollTop = log.scrollHeight; }, 50);
|
|
3486
|
-
}
|
|
3487
|
-
} catch (_) { /* 静默失败 */ }
|
|
3488
|
-
return;
|
|
3489
|
-
}
|
|
3490
|
-
|
|
3491
|
-
thinkingEl.style.display = 'block';
|
|
3492
|
-
log.innerHTML = '';
|
|
3493
|
-
try {
|
|
3494
|
-
const res = await fetch(`/api/remote-channels/chat-history?targetPublicKey=${encodeURIComponent(peerPublicKey)}&channelId=${encodeURIComponent(channelId)}`);
|
|
3495
|
-
const data = await res.json();
|
|
3496
|
-
if (!res.ok) {
|
|
3497
|
-
appendSystem(`拉取失败: ${data.error || 'unknown'}`, 'error');
|
|
3498
|
-
thinkingEl.style.display = 'none';
|
|
3499
|
-
return;
|
|
3500
|
-
}
|
|
3501
|
-
renderHistory(data);
|
|
3502
|
-
} catch (err) {
|
|
3503
|
-
appendSystem(`拉取异常: ${err.message}`, 'error');
|
|
3504
|
-
} finally {
|
|
3505
|
-
thinkingEl.style.display = 'none';
|
|
3506
|
-
}
|
|
3507
|
-
}
|
|
3508
|
-
|
|
3509
|
-
function renderHistory(data) {
|
|
3510
|
-
log.innerHTML = '';
|
|
3511
|
-
|
|
3512
|
-
// 1. 显示 judgment 依据 (header) — 保留, 但用 class 化样式
|
|
3513
|
-
const judgments = data.judgments || { bound: [], candidates: [] };
|
|
3514
|
-
if (judgments.bound && judgments.bound.length > 0) {
|
|
3515
|
-
const jh = document.createElement('div');
|
|
3516
|
-
jh.className = 'remote-chat-judgments';
|
|
3517
|
-
let h = `<div class="remote-chat-judgments-title">🛡️ 对方 channel 绑定的判断力 (${judgments.bound.length} 条硬约束)</div>`;
|
|
3518
|
-
for (const j of judgments.bound) {
|
|
3519
|
-
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>`;
|
|
3520
|
-
}
|
|
3521
|
-
if (judgments.candidates && judgments.candidates.length > 0) {
|
|
3522
|
-
h += `<div class="remote-chat-judgments-foot">+ ${judgments.candidates.length} 条候选判断力 (LLM 可自选参考)</div>`;
|
|
3523
|
-
}
|
|
3524
|
-
jh.innerHTML = h;
|
|
3525
|
-
log.appendChild(jh);
|
|
3526
|
-
}
|
|
3527
|
-
|
|
3528
|
-
// 2. 显示历史 messages — 完全复用本地 addMessage 渲染
|
|
3529
|
-
const msgs = data.messages || [];
|
|
3530
|
-
if (msgs.length === 0) {
|
|
3531
|
-
appendSystem('还没有历史消息, 在下面发第一条吧', 'info');
|
|
3532
|
-
} else {
|
|
3533
|
-
for (const m of msgs) {
|
|
3534
|
-
// 远端 owner 的 user 消息 vs 远端访客 (B) 的 user 消息 vs A 的 LLM 回复
|
|
3535
|
-
// 全部走 addMessage, 让 marked/think/env 自动处理. 来源用一个小 prefix 标记.
|
|
3536
|
-
const type = m.type === 'user' ? 'user' : 'ai';
|
|
3537
|
-
let prefix = '';
|
|
3538
|
-
if (m.type === 'user') {
|
|
3539
|
-
if (m.source === 'remote') {
|
|
3540
|
-
prefix = `🌐 远端访客${m.fromPublicKey ? ' (' + m.fromPublicKey.substring(0, 8) + '…)' : ''}\n\n`;
|
|
3541
|
-
} else {
|
|
3542
|
-
prefix = `👤 A (内部 owner)\n\n`;
|
|
3543
|
-
}
|
|
3544
|
-
} else {
|
|
3545
|
-
prefix = `🤖 A 的 LLM\n\n`;
|
|
3546
|
-
}
|
|
3547
|
-
addMessage(prefix + (m.content || ''), type, false, log);
|
|
3548
|
-
}
|
|
3549
|
-
setTimeout(() => { log.scrollTop = log.scrollHeight; }, 50);
|
|
3550
|
-
}
|
|
3551
|
-
}
|
|
3552
|
-
|
|
3553
|
-
const doSend = async () => {
|
|
3554
|
-
const text = inputEl.value.trim();
|
|
3555
|
-
if (!text) return;
|
|
3556
|
-
append(text, 'user');
|
|
3557
|
-
inputEl.value = '';
|
|
3558
|
-
sendBtn.disabled = true;
|
|
3559
|
-
sendBtn.textContent = '...';
|
|
3560
|
-
try {
|
|
3561
|
-
const res = await fetch('/api/remote-channels/chat-send', {
|
|
3562
|
-
method: 'POST',
|
|
3563
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3564
|
-
body: JSON.stringify({ targetPublicKey: peerPublicKey, channelId, text })
|
|
3565
|
-
});
|
|
3566
|
-
const data = await res.json();
|
|
3567
|
-
if (!res.ok) throw new Error(data.error || 'send failed');
|
|
3568
|
-
// 不再 appendSystem('已发送...') —— 用户看到自己消息已上屏就知道, 系统提示是噪音
|
|
3569
|
-
} catch (err) {
|
|
3570
|
-
appendSystem('发送失败: ' + (err.message || err), 'error');
|
|
3571
|
-
} finally {
|
|
3572
|
-
sendBtn.disabled = false;
|
|
3573
|
-
sendBtn.textContent = '发送';
|
|
3574
|
-
}
|
|
3575
|
-
};
|
|
3576
|
-
sendBtn.onclick = doSend;
|
|
3577
|
-
inputEl.onkeydown = (e) => { if (e.key === 'Enter') doSend(); };
|
|
3578
|
-
// v3 新增: B 端远端 chat 也支持 @-autocomplete
|
|
3579
|
-
setupMentionAutocomplete(inputEl);
|
|
3580
|
-
inputEl.focus();
|
|
3581
|
-
startV3GlobalSSE();
|
|
3582
|
-
|
|
3583
|
-
// 打开时立即拉历史
|
|
3584
|
-
loadHistory(false);
|
|
3585
|
-
|
|
3586
|
-
// 每 15 秒自动静默刷新, 同步远端 owner 或其他访客的新消息
|
|
3587
|
-
historyRefreshTimer = setInterval(() => loadHistory(true), 15000);
|
|
3588
|
-
}
|
|
3589
|
-
|
|
3590
|
-
// Phase 3: 我的 ID 按钮 → 真 modal (避免 confirm 在某些环境被禁用)
|
|
3591
|
-
const showMyIdBtn = document.getElementById('show-my-p2p-id-btn');
|
|
3592
|
-
if (showMyIdBtn) {
|
|
3593
|
-
showMyIdBtn.addEventListener('click', async (e) => {
|
|
3594
|
-
e.stopPropagation();
|
|
3595
|
-
// 移除已有 modal
|
|
3596
|
-
document.getElementById('my-p2p-id-modal')?.remove();
|
|
3597
|
-
// 立即弹出 loading 状态 modal
|
|
3598
|
-
const html = `
|
|
3599
|
-
<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;">
|
|
3600
|
-
<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);">
|
|
3601
|
-
<div style="padding:14px 18px;border-bottom:1px solid #e5e7eb;display:flex;align-items:center;justify-content:space-between;">
|
|
3602
|
-
<div style="font-size:15px;font-weight:600;">🪪 我的 P2P 身份</div>
|
|
3603
|
-
<button id="mpim-close" style="background:none;border:none;font-size:20px;color:#6b7280;cursor:pointer;">×</button>
|
|
3604
|
-
</div>
|
|
3605
|
-
<div id="mpim-body" style="padding:16px 18px;">
|
|
3606
|
-
<div style="color:#6b7280;font-size:13px;margin-bottom:10px;">正在获取 publicKey…</div>
|
|
3607
|
-
</div>
|
|
3608
|
-
</div>
|
|
3609
|
-
</div>
|
|
3610
|
-
`;
|
|
3611
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
3612
|
-
document.getElementById('mpim-close').onclick = () => document.getElementById('my-p2p-id-modal').remove();
|
|
3613
|
-
|
|
3614
|
-
try {
|
|
3615
|
-
const res = await fetch('/api/p2p-publickey');
|
|
3616
|
-
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
3617
|
-
const data = await res.json();
|
|
3618
|
-
const pk = data.publicKey || '';
|
|
3619
|
-
const body = document.getElementById('mpim-body');
|
|
3620
|
-
if (!pk || pk.length !== 64) {
|
|
3621
|
-
body.innerHTML = `<div style="color:#b91c1c;font-size:13px;">✗ P2PDirect 还没启动, 刷新页面稍后再试</div>`;
|
|
3622
|
-
return;
|
|
3623
|
-
}
|
|
3624
|
-
body.innerHTML = `
|
|
3625
|
-
<div style="font-size:12px;color:#6b7280;margin-bottom:8px;">把下面这串发给好友, 好友在 P2P 好友区点 "+ 好友" 粘贴即可加你:</div>
|
|
3626
|
-
<div style="display:flex;gap:6px;align-items:center;margin-bottom:12px;">
|
|
3627
|
-
<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>
|
|
3628
|
-
<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>
|
|
3629
|
-
</div>
|
|
3630
|
-
<div id="mpim-status" style="font-size:12px;color:#059669;min-height:16px;"></div>
|
|
3631
|
-
<div style="margin-top:14px;padding-top:12px;border-top:1px solid #e5e7eb;font-size:11px;color:#6b7280;">
|
|
3632
|
-
💡 同一个 role 重启后 publicKey 不会变, 好友不需要重新加你.
|
|
3633
|
-
</div>
|
|
3634
|
-
`;
|
|
3635
|
-
document.getElementById('mpim-copy').onclick = async () => {
|
|
3636
|
-
const statusEl = document.getElementById('mpim-status');
|
|
3637
|
-
try {
|
|
3638
|
-
await navigator.clipboard.writeText(pk);
|
|
3639
|
-
statusEl.textContent = '✓ 已复制到剪贴板';
|
|
3640
|
-
} catch {
|
|
3641
|
-
const ta = document.createElement('textarea');
|
|
3642
|
-
ta.value = pk;
|
|
3643
|
-
ta.style.position = 'fixed';
|
|
3644
|
-
ta.style.opacity = '0';
|
|
3645
|
-
document.body.appendChild(ta);
|
|
3646
|
-
ta.select();
|
|
3647
|
-
try { document.execCommand('copy'); statusEl.textContent = '✓ 已复制 (fallback)'; }
|
|
3648
|
-
catch { statusEl.textContent = '✗ 复制失败, 请手动选中复制'; }
|
|
3649
|
-
document.body.removeChild(ta);
|
|
3650
|
-
}
|
|
3651
|
-
};
|
|
3652
|
-
} catch (err) {
|
|
3653
|
-
const body = document.getElementById('mpim-body');
|
|
3654
|
-
if (body) body.innerHTML = `<div style="color:#b91c1c;font-size:13px;">✗ 获取失败: ${escapeHtml(err.message || String(err))}</div>`;
|
|
3655
|
-
}
|
|
3656
|
-
});
|
|
3657
|
-
}
|
|
3658
|
-
|
|
3659
|
-
// Phase 3 重做: + 添加好友按钮 → 弹窗输入 publicKey + name, 同时 joinPeer
|
|
3660
|
-
const addPeerBtn = document.getElementById('add-p2p-peer-btn');
|
|
3661
|
-
if (addPeerBtn) {
|
|
3662
|
-
addPeerBtn.addEventListener('click', async (e) => {
|
|
3663
|
-
e.stopPropagation();
|
|
3664
|
-
const name = prompt('给这个 P2P 好友起个名字 (如: 同事-张磊)');
|
|
3665
|
-
if (!name) return;
|
|
3666
|
-
const publicKey = prompt('粘贴对方的 P2PDirect publicKey (64 字符 hex):\n\n获取方式: 对方在 http://localhost:54188/api/p2p-publickey');
|
|
3667
|
-
if (!publicKey) return;
|
|
3668
|
-
if (publicKey.length !== 64) {
|
|
3669
|
-
alert('publicKey 长度不对, 应该是 64 字符 hex');
|
|
3670
|
-
return;
|
|
3671
|
-
}
|
|
3672
|
-
try {
|
|
3673
|
-
// v3 新增: 改用 friend-request RPC — 不光 joinPeer, 还发申请到对方
|
|
3674
|
-
// 对方会收到 SSE friend-request 事件, 弹一个申请 modal
|
|
3675
|
-
const res = await fetch('/api/friend-request', {
|
|
3676
|
-
method: 'POST',
|
|
3677
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3678
|
-
body: JSON.stringify({ targetPublicKey: publicKey, name, message: '想加你为 P2P 好友, 共享 channel 协作' })
|
|
3679
|
-
});
|
|
3680
|
-
const data = await res.json();
|
|
3681
|
-
if (res.status === 502) {
|
|
3682
|
-
// 2026-06-10: 区分"对方不在线"和"写失败" — 让用户知道是否需要重试
|
|
3683
|
-
const reason = data.code === 'NO_CONN' ? '对方未在线或 P2P 握手超时' : '写入 P2P 通道失败';
|
|
3684
|
-
alert(`好友申请发送失败: ${reason}\n\n本地已记住对方 publicKey (${publicKey.substring(0,8)}...), 等对方上线后可在 P2P 面板手动重试.`);
|
|
3685
|
-
await loadRemoteChannels();
|
|
3686
|
-
return;
|
|
3687
|
-
}
|
|
3688
|
-
if (!res.ok) throw new Error(data.error || 'connect failed');
|
|
3689
|
-
// 成功 — 但不阻塞地等 ack (ack 经 SSE 'friend-request-ack' 推回, 由 v3GlobalEventSource 处理)
|
|
3690
|
-
window.__pendingFriendRequests = window.__pendingFriendRequests || new Map();
|
|
3691
|
-
if (data.requestId) {
|
|
3692
|
-
window.__pendingFriendRequests.set(data.requestId, { name, publicKey, at: Date.now() });
|
|
3693
|
-
// 8s 后还没 ack → 提示用户对方可能跑旧版 (无 ack 协议)
|
|
3694
|
-
setTimeout(() => {
|
|
3695
|
-
if (window.__pendingFriendRequests.has(data.requestId)) {
|
|
3696
|
-
window.__pendingFriendRequests.delete(data.requestId);
|
|
3697
|
-
console.warn(`[v3-friend] 申请超时未收到 ack (requestId=${data.requestId.substring(0,8)})`);
|
|
3698
|
-
showSimpleToast(`⚠️ 对方未确认收到 (可能是旧版客户端, 申请已发出但无法验证)`, 'warn');
|
|
3699
|
-
}
|
|
3700
|
-
}, 8000);
|
|
3701
|
-
}
|
|
3702
|
-
alert(`已发送好友申请给 ${name} (${publicKey.substring(0, 12)}...)\n对方收到后自己端弹申请 modal, 接受后会出现在 P2P 好友区.`);
|
|
3703
|
-
await loadRemoteChannels();
|
|
3704
|
-
} catch (err) {
|
|
3705
|
-
alert('申请失败: ' + (err.message || err));
|
|
3706
|
-
}
|
|
3707
|
-
});
|
|
3708
|
-
}
|
|
3709
|
-
|
|
3710
|
-
/**
|
|
3711
|
-
* v3 新增: 收到好友申请时, 弹一个 modal 让用户接受或拒绝
|
|
3712
|
-
*/
|
|
3713
|
-
function showFriendRequestModal(req) {
|
|
3714
|
-
// 移除已有 modal
|
|
3715
|
-
document.getElementById('friend-request-modal')?.remove();
|
|
3716
|
-
// 2026-06-10: 同 Step 3 远端 chat modal 一样, 改用 class + CSS 变量, 跟本地风格统一
|
|
3717
|
-
const html = `
|
|
3718
|
-
<div id="friend-request-modal" class="friend-req-overlay">
|
|
3719
|
-
<div class="friend-req-shell">
|
|
3720
|
-
<div class="friend-req-header">
|
|
3721
|
-
<span style="font-size:20px;">🤝</span>
|
|
3722
|
-
<div style="flex:1;min-width:0;">
|
|
3723
|
-
<div class="friend-req-title">好友申请</div>
|
|
3724
|
-
<div class="friend-req-meta">来自 ${escapeHtml(req.fromName)} (${escapeHtml(req.fromPublicKey.substring(0, 16))}…)</div>
|
|
3725
|
-
</div>
|
|
3726
|
-
</div>
|
|
3727
|
-
<div class="friend-req-body">
|
|
3728
|
-
<p style="margin:0 0 8px;">${escapeHtml(req.message || '想加你为 P2P 好友')}</p>
|
|
3729
|
-
<p style="margin:0;color:var(--text-muted);font-size:11px;">接受后: 双方互加好友, 对方分享的 channel 会自动出现在 P2P 好友区.</p>
|
|
3730
|
-
</div>
|
|
3731
|
-
<div class="friend-req-actions">
|
|
3732
|
-
<button id="frm-deny" class="friend-req-btn-deny">拒绝</button>
|
|
3733
|
-
<button id="frm-accept" class="friend-req-btn-accept">接受</button>
|
|
3734
|
-
</div>
|
|
3735
|
-
</div>
|
|
3736
|
-
</div>
|
|
3737
|
-
`;
|
|
3738
|
-
document.body.insertAdjacentHTML('beforeend', html);
|
|
3739
|
-
const close = () => document.getElementById('friend-request-modal')?.remove();
|
|
3740
|
-
document.getElementById('frm-deny').onclick = close;
|
|
3741
|
-
document.getElementById('frm-accept').onclick = async () => {
|
|
3742
|
-
close();
|
|
3743
|
-
try {
|
|
3744
|
-
const res = await fetch('/api/friend-accept', {
|
|
3745
|
-
method: 'POST',
|
|
3746
|
-
headers: { 'Content-Type': 'application/json' },
|
|
3747
|
-
body: JSON.stringify({ fromPublicKey: req.fromPublicKey, name: req.fromName })
|
|
3748
|
-
});
|
|
3749
|
-
const data = await res.json();
|
|
3750
|
-
if (!res.ok) throw new Error(data.error || 'accept failed');
|
|
3751
|
-
console.log('[v3-friend] 接受了好友申请:', req.fromName);
|
|
3752
|
-
// 立刻拉一次 — 对方刚 accept, ta 的 channel 列表会被推到我们这
|
|
3753
|
-
setTimeout(loadRemoteChannels, 1000);
|
|
3754
|
-
showSimpleToast(`✅ 已接受 ${req.fromName} 的好友申请`);
|
|
3755
|
-
} catch (err) {
|
|
3756
|
-
console.error('[v3-friend] accept 失败:', err);
|
|
3757
|
-
alert('接受失败: ' + (err.message || err));
|
|
3758
|
-
}
|
|
3759
|
-
};
|
|
3760
|
-
}
|
|
3761
|
-
|
|
3762
|
-
/**
|
|
3763
|
-
* 2026-06-10: 简单的右下 toast, 3s 自动消失. 用于 ack / 接受好友 等非阻塞反馈
|
|
3764
|
-
*/
|
|
3765
|
-
function showSimpleToast(text, kind = 'info') {
|
|
3766
|
-
const containerId = 'simple-toast-container';
|
|
3767
|
-
let container = document.getElementById(containerId);
|
|
3768
|
-
if (!container) {
|
|
3769
|
-
container = document.createElement('div');
|
|
3770
|
-
container.id = containerId;
|
|
3771
|
-
container.style.cssText = 'position:fixed;right:16px;bottom:16px;z-index:10005;display:flex;flex-direction:column;gap:8px;max-width:320px;';
|
|
3772
|
-
document.body.appendChild(container);
|
|
3773
|
-
}
|
|
3774
|
-
const el = document.createElement('div');
|
|
3775
|
-
el.className = `simple-toast simple-toast-${kind}`;
|
|
3776
|
-
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;`;
|
|
3777
|
-
el.textContent = text;
|
|
3778
|
-
container.appendChild(el);
|
|
3779
|
-
setTimeout(() => {
|
|
3780
|
-
el.style.transition = 'opacity .3s, transform .3s';
|
|
3781
|
-
el.style.opacity = '0';
|
|
3782
|
-
el.style.transform = 'translateX(20px)';
|
|
3783
|
-
setTimeout(() => el.remove(), 320);
|
|
3784
|
-
}, 3000);
|
|
3785
|
-
}
|
|
3786
|
-
|
|
3787
|
-
// 2026-06-10: P2P 全部展开/折叠切换按钮 (单按钮, 根据当前多数态切换)
|
|
3788
|
-
const p2pToggleAllBtn = document.getElementById('p2p-toggle-all-btn');
|
|
3789
|
-
if (p2pToggleAllBtn) {
|
|
3790
|
-
// 同步图标/文字: 多数 peer 折叠 → 显示 "⊞ 展开"; 多数展开 → 显示 "⊟ 折叠"
|
|
3791
|
-
function syncToggleAllBtn() {
|
|
3792
|
-
const allPks = new Set([
|
|
3793
|
-
...knownPeers.map(p => p.publicKey),
|
|
3794
|
-
...remoteChannels.map(g => g.peerId)
|
|
3795
|
-
]);
|
|
3796
|
-
if (allPks.size === 0) {
|
|
3797
|
-
p2pToggleAllBtn.textContent = '⊞ 展开';
|
|
3798
|
-
p2pToggleAllBtn.title = '切换全部展开/折叠';
|
|
3799
|
-
return;
|
|
3800
|
-
}
|
|
3801
|
-
let collapsedCount = 0;
|
|
3802
|
-
for (const pk of allPks) if (collapsedPeers.has(pk)) collapsedCount++;
|
|
3803
|
-
const majorityCollapsed = collapsedCount >= allPks.size / 2;
|
|
3804
|
-
if (majorityCollapsed) {
|
|
3805
|
-
p2pToggleAllBtn.textContent = '⊞ 展开';
|
|
3806
|
-
p2pToggleAllBtn.title = '点击展开所有 P2P 好友';
|
|
3807
|
-
} else {
|
|
3808
|
-
p2pToggleAllBtn.textContent = '⊟ 折叠';
|
|
3809
|
-
p2pToggleAllBtn.title = '点击折叠所有 P2P 好友';
|
|
3810
|
-
}
|
|
3811
|
-
}
|
|
3812
|
-
p2pToggleAllBtn.addEventListener('click', (e) => {
|
|
3813
|
-
e.stopPropagation();
|
|
3814
|
-
const allPks = new Set([
|
|
3815
|
-
...knownPeers.map(p => p.publicKey),
|
|
3816
|
-
...remoteChannels.map(g => g.peerId)
|
|
3817
|
-
]);
|
|
3818
|
-
if (allPks.size === 0) return;
|
|
3819
|
-
// 多数折叠 → 全展开; 否则全折叠
|
|
3820
|
-
let collapsedCount = 0;
|
|
3821
|
-
for (const pk of allPks) if (collapsedPeers.has(pk)) collapsedCount++;
|
|
3822
|
-
const majorityCollapsed = collapsedCount >= allPks.size / 2;
|
|
3823
|
-
if (majorityCollapsed) {
|
|
3824
|
-
expandAllPeers();
|
|
3825
|
-
} else {
|
|
3826
|
-
collapseAllPeers();
|
|
3827
|
-
}
|
|
3828
|
-
syncToggleAllBtn();
|
|
3829
|
-
});
|
|
3830
|
-
// 暴露给 renderRemoteChannels 渲染后调用 (保持图标跟实际状态一致)
|
|
3831
|
-
window.__syncP2PToggleAllBtn = syncToggleAllBtn;
|
|
3832
|
-
syncToggleAllBtn(); // 首次同步
|
|
3833
|
-
}
|
|
3834
|
-
|
|
3835
|
-
// v3 双向刷新: 主动向所有好友发 agent.meta.list, 拿到 ta 们分享给我的 channel
|
|
3836
|
-
const refreshSharedBtn = document.getElementById('refresh-shared-btn');
|
|
3837
|
-
if (refreshSharedBtn) {
|
|
3838
|
-
refreshSharedBtn.addEventListener('click', async (e) => {
|
|
3839
|
-
e.stopPropagation();
|
|
3840
|
-
const originalText = refreshSharedBtn.textContent;
|
|
3841
|
-
refreshSharedBtn.disabled = true;
|
|
3842
|
-
refreshSharedBtn.textContent = '...';
|
|
3843
|
-
try {
|
|
3844
|
-
const res = await fetch('/api/remote-channels/refresh', { method: 'POST' });
|
|
3845
|
-
const data = await res.json();
|
|
3846
|
-
if (!res.ok) throw new Error(data.error || 'refresh failed');
|
|
3847
|
-
// 等 1.5s 让 RPC 回复回来 (向所有 peer 广播)
|
|
3848
|
-
await new Promise(r => setTimeout(r, 1500));
|
|
3849
|
-
await loadRemoteChannels();
|
|
3850
|
-
console.log(`[v3] 双向刷新: 向 ${data.peerCount || 0} 个好友发 list 请求`);
|
|
3851
|
-
} catch (err) {
|
|
3852
|
-
alert('刷新失败: ' + (err.message || err));
|
|
3853
|
-
} finally {
|
|
3854
|
-
refreshSharedBtn.disabled = false;
|
|
3855
|
-
refreshSharedBtn.textContent = originalText;
|
|
3856
|
-
}
|
|
3857
|
-
});
|
|
3858
|
-
}
|
|
3859
|
-
|
|
3860
|
-
// 启动时拉一次 + 定期轮询 (SSE 接收 P2P reply 后也会更新)
|
|
3861
|
-
loadRemoteChannels();
|
|
3862
|
-
setInterval(loadRemoteChannels, 8000);
|
|
3863
|
-
// 全局 SSE — 接收 remote-channel-update / remote-chat-reply / friend-request
|
|
3864
|
-
startV3GlobalSSE();
|
|
3865
|
-
|
|
3866
|
-
// ============ v3: 折叠 + 拖拽分隔线 ============
|
|
3867
|
-
|
|
3868
|
-
// 给本地/远端 section 加 flex 修饰类 (CSS variable 驱动比例)
|
|
3869
|
-
const localSection = document.querySelector('.sidebar-section'); // 第一个 section = 本地 channel
|
|
3870
|
-
const remoteSection = document.getElementById('remote-agents-section');
|
|
3871
|
-
if (localSection) localSection.classList.add('local-flex');
|
|
3872
|
-
if (remoteSection) remoteSection.classList.add('remote-flex');
|
|
3873
|
-
|
|
3874
|
-
// 折叠: 点 header 切换 collapsed 类
|
|
3875
|
-
const remoteHeader = document.getElementById('remote-agents-header');
|
|
3876
|
-
if (remoteHeader && remoteSection) {
|
|
3877
|
-
remoteHeader.addEventListener('click', (e) => {
|
|
3878
|
-
// 阻止刷新按钮的事件冒泡在 refreshRemoteBtn 里已处理
|
|
3879
|
-
remoteSection.classList.toggle('collapsed');
|
|
3880
|
-
});
|
|
3881
|
-
}
|
|
3882
|
-
|
|
3883
|
-
// 拖拽分隔线: 鼠标按下开始拖, mousemove 改 --local-flex / --remote-flex, mouseup 结束
|
|
3884
|
-
const splitHandle = document.getElementById('sidebar-split-handle');
|
|
3885
|
-
if (splitHandle && localSection && remoteSection) {
|
|
3886
|
-
// 初始化等分
|
|
3887
|
-
const updateFlexVars = (localRatio, remoteRatio) => {
|
|
3888
|
-
localSection.style.setProperty('--local-flex', String(localRatio));
|
|
3889
|
-
remoteSection.style.setProperty('--remote-flex', String(remoteRatio));
|
|
3890
|
-
};
|
|
3891
|
-
updateFlexVars(1, 1);
|
|
3892
|
-
|
|
3893
|
-
let isDragging = false;
|
|
3894
|
-
let dragStartY = 0;
|
|
3895
|
-
let startLocalFlex = 1;
|
|
3896
|
-
let startRemoteFlex = 1;
|
|
3897
|
-
let sidebarHeight = 0;
|
|
3898
|
-
|
|
3899
|
-
splitHandle.addEventListener('mousedown', (e) => {
|
|
3900
|
-
isDragging = true;
|
|
3901
|
-
splitHandle.classList.add('dragging');
|
|
3902
|
-
dragStartY = e.clientY;
|
|
3903
|
-
// 读当前 CSS variable 拿真实 flex 值
|
|
3904
|
-
const lf = parseFloat(getComputedStyle(localSection).getPropertyValue('--local-flex')) || 1;
|
|
3905
|
-
const rf = parseFloat(getComputedStyle(remoteSection).getPropertyValue('--remote-flex')) || 1;
|
|
3906
|
-
startLocalFlex = lf;
|
|
3907
|
-
startRemoteFlex = rf;
|
|
3908
|
-
// 父容器可用高度 = sidebar-section 总和 (本地+远端+handle)
|
|
3909
|
-
const sidebar = document.querySelector('.sidebar');
|
|
3910
|
-
if (sidebar) sidebarHeight = sidebar.clientHeight;
|
|
3911
|
-
e.preventDefault();
|
|
3912
|
-
document.body.style.cursor = 'ns-resize';
|
|
3913
|
-
});
|
|
3914
|
-
|
|
3915
|
-
document.addEventListener('mousemove', (e) => {
|
|
3916
|
-
if (!isDragging) return;
|
|
3917
|
-
const deltaY = e.clientY - dragStartY;
|
|
3918
|
-
if (sidebarHeight <= 0) return;
|
|
3919
|
-
// deltaY 正 = 鼠标下移 = 拉大本地 / 缩小远端
|
|
3920
|
-
// 转换: 1 像素 ≈ sidebarHeight 中 0.005 的比例
|
|
3921
|
-
const deltaRatio = deltaY / sidebarHeight * 4; // 4 倍灵敏
|
|
3922
|
-
let newLocal = Math.max(0.1, startLocalFlex + deltaRatio);
|
|
3923
|
-
let newRemote = Math.max(0.1, startRemoteFlex - deltaRatio);
|
|
3924
|
-
updateFlexVars(newLocal, newRemote);
|
|
3925
|
-
});
|
|
3926
|
-
|
|
3927
|
-
document.addEventListener('mouseup', () => {
|
|
3928
|
-
if (!isDragging) return;
|
|
3929
|
-
isDragging = false;
|
|
3930
|
-
splitHandle.classList.remove('dragging');
|
|
3931
|
-
document.body.style.cursor = '';
|
|
3932
|
-
});
|
|
3933
|
-
|
|
3934
|
-
// 双击分隔线 = 重置为等分
|
|
3935
|
-
splitHandle.addEventListener('dblclick', () => {
|
|
3936
|
-
updateFlexVars(1, 1);
|
|
3937
|
-
});
|
|
3938
|
-
}
|
|
3939
|
-
|
|
3940
|
-
if (taskModal) {
|
|
3941
|
-
taskModal.addEventListener('click', (e) => {
|
|
3942
|
-
if (e.target === taskModal) {
|
|
3943
|
-
hideTaskModal();
|
|
3944
|
-
}
|
|
3945
|
-
});
|
|
3946
|
-
}
|
|
3947
|
-
|
|
3948
|
-
if (taskAddBtn) {
|
|
3949
|
-
taskAddBtn.addEventListener('click', showCreateTaskModal);
|
|
3950
|
-
}
|
|
3951
|
-
|
|
3952
|
-
if (taskExecuteNextBtn) {
|
|
3953
|
-
taskExecuteNextBtn.addEventListener('click', executeNextTask);
|
|
3954
|
-
}
|
|
3955
|
-
|
|
3956
|
-
if (taskCancelBtn) {
|
|
3957
|
-
taskCancelBtn.addEventListener('click', hideCreateTaskModal);
|
|
3958
|
-
}
|
|
3959
|
-
|
|
3960
|
-
if (createTaskModalClose) {
|
|
3961
|
-
createTaskModalClose.addEventListener('click', hideCreateTaskModal);
|
|
3962
|
-
}
|
|
3963
|
-
|
|
3964
|
-
if (createTaskModal) {
|
|
3965
|
-
createTaskModal.addEventListener('click', (e) => {
|
|
3966
|
-
if (e.target === createTaskModal) {
|
|
3967
|
-
hideCreateTaskModal();
|
|
3968
|
-
}
|
|
3969
|
-
});
|
|
3970
|
-
}
|
|
3971
|
-
|
|
3972
|
-
if (taskCreateBtn) {
|
|
3973
|
-
taskCreateBtn.addEventListener('click', createTask);
|
|
3974
|
-
}
|
|
3975
|
-
|
|
3976
|
-
if (taskTypeSelect) {
|
|
3977
|
-
taskTypeSelect.addEventListener('change', () => {
|
|
3978
|
-
const workflowSteps = document.querySelector('.workflow-steps');
|
|
3979
|
-
if (workflowSteps) {
|
|
3980
|
-
workflowSteps.style.display = taskTypeSelect.value === 'workflow' ? 'block' : 'none';
|
|
3981
|
-
}
|
|
3982
|
-
});
|
|
3983
|
-
}
|
|
3984
|
-
|
|
3985
|
-
// Handle SSE task status updates
|
|
3986
|
-
const originalOnMessage = window.addEventListener ? null : null;
|
|
3987
|
-
|
|
3988
|
-
// Extend SSE handler for task updates
|
|
3989
|
-
const originalConnect = connect;
|
|
3990
|
-
connect = async function() {
|
|
3991
|
-
// Call original connect
|
|
3992
|
-
await originalConnect();
|
|
3993
|
-
|
|
3994
|
-
// Reconnect SSE for task updates
|
|
3995
|
-
const taskEventSource = new EventSource('/events');
|
|
3996
|
-
|
|
3997
|
-
taskEventSource.onmessage = (e) => {
|
|
3998
|
-
try {
|
|
3999
|
-
const data = JSON.parse(e.data);
|
|
4000
|
-
if (data.type === 'task_status') {
|
|
4001
|
-
loadTasks();
|
|
4002
|
-
}
|
|
4003
|
-
} catch {}
|
|
4004
|
-
};
|
|
4005
|
-
|
|
4006
|
-
taskEventSource.onerror = () => {
|
|
4007
|
-
taskEventSource.close();
|
|
4008
|
-
};
|
|
4009
|
-
};
|
|
2004
|
+
};
|
|
4010
2005
|
|
|
4011
2006
|
// =====================================================
|
|
4012
2007
|
// 钱包管理 (header 钱包按钮 → 全局管理面板)
|
|
@@ -4021,9 +2016,8 @@ const walletUnbindBtn = document.getElementById('wallet-unbind-btn');
|
|
|
4021
2016
|
const walletNewInfo = document.getElementById('wallet-new-info');
|
|
4022
2017
|
const walletListEl = document.getElementById('wallet-list');
|
|
4023
2018
|
|
|
4024
|
-
/**
|
|
2019
|
+
/** 本次会话生成的私钥, 仅用于提示, 永不上传 */
|
|
4025
2020
|
let walletModalPendingSecret = null;
|
|
4026
|
-
let walletModalPendingMnemonic = null;
|
|
4027
2021
|
|
|
4028
2022
|
function openWalletModal() {
|
|
4029
2023
|
if (!walletModal) return;
|
|
@@ -4050,18 +2044,17 @@ function closeWalletModal() {
|
|
|
4050
2044
|
if (walletModalClose) walletModalClose.addEventListener('click', closeWalletModal);
|
|
4051
2045
|
|
|
4052
2046
|
if (walletGenerateBtn) {
|
|
4053
|
-
walletGenerateBtn.addEventListener('click',
|
|
2047
|
+
walletGenerateBtn.addEventListener('click', () => {
|
|
2048
|
+
const { address, privateKeyHex } = generateLocalWallet();
|
|
2049
|
+
walletBindAddress.value = address;
|
|
2050
|
+
walletModalPendingSecret = privateKeyHex;
|
|
4054
2051
|
walletNewInfo.style.display = 'block';
|
|
4055
|
-
walletNewInfo.innerHTML =
|
|
4056
|
-
|
|
4057
|
-
|
|
4058
|
-
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
walletNewInfo.innerHTML = formatWalletInfoHtml(wallet);
|
|
4062
|
-
} catch (err) {
|
|
4063
|
-
walletNewInfo.innerHTML = '✗ 生成钱包失败: ' + escapeHtml(err.message);
|
|
4064
|
-
}
|
|
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
|
+
`;
|
|
4065
2058
|
});
|
|
4066
2059
|
}
|
|
4067
2060
|
|
|
@@ -4076,40 +2069,12 @@ if (walletBindBtn) {
|
|
|
4076
2069
|
alert('请输入钱包地址或点击「生成」');
|
|
4077
2070
|
return;
|
|
4078
2071
|
}
|
|
4079
|
-
const ch = channels.find(c => c.id === currentChannelId);
|
|
4080
|
-
const did = ch?.did || '';
|
|
4081
|
-
if (!did || did === 'undefined' || did === 'null') {
|
|
4082
|
-
alert('当前智能体还没有生成 DID, 请稍等几秒后重试');
|
|
4083
|
-
return;
|
|
4084
|
-
}
|
|
4085
|
-
|
|
4086
|
-
// 服务端会用 recoverMessage 校验签名, 因此必须用本会话生成的私钥签名
|
|
4087
|
-
// (已绑过的钱包重新签名也会过, 因为 challenge 里有 channelId + DID)
|
|
4088
|
-
if (!walletModalPendingSecret) {
|
|
4089
|
-
alert('请先在「钱包管理」面板点击「生成」或导入私钥, 临时私钥仅在本会话保留');
|
|
4090
|
-
return;
|
|
4091
|
-
}
|
|
4092
|
-
let challenge;
|
|
4093
2072
|
try {
|
|
4094
|
-
|
|
4095
|
-
|
|
4096
|
-
alert('签名失败: ' + err.message);
|
|
4097
|
-
return;
|
|
4098
|
-
}
|
|
4099
|
-
if (challenge.address.toLowerCase() !== address.toLowerCase()) {
|
|
4100
|
-
alert(`签名地址 ${challenge.address} 与输入地址 ${address} 不一致, 拒绝绑定`);
|
|
4101
|
-
return;
|
|
4102
|
-
}
|
|
4103
|
-
|
|
4104
|
-
try {
|
|
4105
|
-
const res = await fetch(`/channels/${currentChannelId}/bind-wallet`, {
|
|
4106
|
-
method: 'POST',
|
|
2073
|
+
const res = await fetch(`/channels/${currentChannelId}`, {
|
|
2074
|
+
method: 'PATCH',
|
|
4107
2075
|
headers: { 'Content-Type': 'application/json' },
|
|
4108
2076
|
body: JSON.stringify({
|
|
4109
|
-
walletAddress:
|
|
4110
|
-
signature: challenge.signature,
|
|
4111
|
-
message: challenge.message,
|
|
4112
|
-
did: challenge.did,
|
|
2077
|
+
walletAddress: address,
|
|
4113
2078
|
autoInvokeTools: !!walletAutoTools.checked
|
|
4114
2079
|
})
|
|
4115
2080
|
});
|
|
@@ -4123,13 +2088,6 @@ if (walletBindBtn) {
|
|
|
4123
2088
|
renderChannels();
|
|
4124
2089
|
renderWalletList();
|
|
4125
2090
|
walletModalPendingSecret = null;
|
|
4126
|
-
walletModalPendingMnemonic = null;
|
|
4127
|
-
walletNewInfo.style.display = 'block';
|
|
4128
|
-
walletNewInfo.innerHTML =
|
|
4129
|
-
'✅ 绑定成功<br>' +
|
|
4130
|
-
'<strong>地址:</strong> <code>' + escapeHtml(updated.walletAddress) + '</code><br>' +
|
|
4131
|
-
'<strong>签名 DID:</strong> <code>' + escapeHtml(did) + '</code><br>' +
|
|
4132
|
-
'<small style="color:#9c9;">服务端已用 recoverMessage 校验签名, 证明你持有该钱包私钥。</small>';
|
|
4133
2091
|
} catch (err) {
|
|
4134
2092
|
alert('绑定失败: ' + err.message);
|
|
4135
2093
|
}
|
|
@@ -4272,31 +2230,26 @@ const agentAddWalletInfo = document.getElementById('agent-add-wallet-info');
|
|
|
4272
2230
|
const agentGenerateWalletBtn = document.getElementById('agent-generate-wallet-btn');
|
|
4273
2231
|
|
|
4274
2232
|
/** 客户端只为提示, 不向服务端发送私钥 */
|
|
4275
|
-
let pendingWalletSecret = null;
|
|
4276
|
-
let pendingWalletMnemonic = null; // 本会话待绑定的助记词, 仅浏览器内存
|
|
2233
|
+
let pendingWalletSecret = null;
|
|
4277
2234
|
|
|
4278
2235
|
function openAgentAddModal(existingChannel) {
|
|
4279
2236
|
if (!agentAddModal) return;
|
|
4280
2237
|
if (existingChannel) {
|
|
4281
2238
|
agentAddTitle.textContent = '配置智能体:' + existingChannel.name;
|
|
4282
2239
|
agentAddName.value = existingChannel.name || '';
|
|
4283
|
-
agentAddName.readOnly =
|
|
4284
|
-
agentAddName.placeholder = '输入新名称';
|
|
2240
|
+
agentAddName.readOnly = true; // 改名走 PATCH
|
|
4285
2241
|
agentAddWallet.value = existingChannel.walletAddress || '';
|
|
4286
2242
|
agentAddAutoTools.checked = !!existingChannel.autoInvokeTools;
|
|
4287
2243
|
agentAddConfirmBtn.dataset.mode = 'update';
|
|
4288
2244
|
agentAddConfirmBtn.dataset.channelId = existingChannel.id;
|
|
4289
|
-
agentAddConfirmBtn.dataset.originalName = existingChannel.name || '';
|
|
4290
2245
|
} else {
|
|
4291
2246
|
agentAddTitle.textContent = '添加智能体';
|
|
4292
2247
|
agentAddName.value = '';
|
|
4293
2248
|
agentAddName.readOnly = false;
|
|
4294
|
-
agentAddName.placeholder = '例如: 交易助手';
|
|
4295
2249
|
agentAddWallet.value = '';
|
|
4296
2250
|
agentAddAutoTools.checked = true;
|
|
4297
2251
|
agentAddConfirmBtn.dataset.mode = 'create';
|
|
4298
2252
|
delete agentAddConfirmBtn.dataset.channelId;
|
|
4299
|
-
delete agentAddConfirmBtn.dataset.originalName;
|
|
4300
2253
|
}
|
|
4301
2254
|
agentAddWalletInfo.style.display = 'none';
|
|
4302
2255
|
agentAddWalletInfo.innerHTML = '';
|
|
@@ -4310,62 +2263,32 @@ function closeAgentAddModal() {
|
|
|
4310
2263
|
pendingWalletSecret = null;
|
|
4311
2264
|
}
|
|
4312
2265
|
|
|
4313
|
-
/**
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
return
|
|
4322
|
-
}
|
|
4323
|
-
|
|
4324
|
-
async function importRealWalletByPrivateKey(privateKeyHex) {
|
|
4325
|
-
if (!window.WalletViem) {
|
|
4326
|
-
throw new Error('钱包模块尚未加载, 请稍后重试');
|
|
4327
|
-
}
|
|
4328
|
-
return window.WalletViem.importEVMWallet(privateKeyHex);
|
|
4329
|
-
}
|
|
4330
|
-
|
|
4331
|
-
async function signDIDChallengeAsync(privateKeyHex, did, channelId) {
|
|
4332
|
-
if (!window.WalletViem) {
|
|
4333
|
-
throw new Error('钱包模块尚未加载, 请稍后重试');
|
|
4334
|
-
}
|
|
4335
|
-
return window.WalletViem.signDIDChallenge(privateKeyHex, did, channelId);
|
|
4336
|
-
}
|
|
4337
|
-
|
|
4338
|
-
function formatWalletInfoHtml({ address, privateKey, mnemonic }) {
|
|
4339
|
-
const parts = [
|
|
4340
|
-
'✓ 已生成真实 EVM 钱包 (BIP-39 + secp256k1 + EIP-55)',
|
|
4341
|
-
'<strong>地址:</strong> <code>' + escapeHtml(address) + '</code>',
|
|
4342
|
-
];
|
|
4343
|
-
if (mnemonic) {
|
|
4344
|
-
parts.push(
|
|
4345
|
-
'<strong>助记词 (12 词, 请抄写保存):</strong>',
|
|
4346
|
-
'<code style="color:#fc6;word-break:break-all;">' + escapeHtml(mnemonic) + '</code>'
|
|
4347
|
-
);
|
|
4348
|
-
}
|
|
4349
|
-
parts.push(
|
|
4350
|
-
'<strong>私钥 (0x + 32 字节):</strong>',
|
|
4351
|
-
'<code style="color:#f88;word-break:break-all;">' + escapeHtml(privateKey) + '</code>',
|
|
4352
|
-
'<small style="color:#f88;">⚠ 助记词 + 私钥均仅在本浏览器内存, 关闭页面后无法找回。</small>',
|
|
4353
|
-
'<small style="color:#999;">签名绑定到 channel DID (EIP-191 personal_sign) 会发送到服务端, 用于证明钱包所有权。</small>'
|
|
4354
|
-
);
|
|
4355
|
-
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 };
|
|
4356
2275
|
}
|
|
4357
2276
|
|
|
4358
2277
|
if (agentGenerateWalletBtn) {
|
|
4359
|
-
agentGenerateWalletBtn.addEventListener('click',
|
|
4360
|
-
agentAddWalletInfo.style.display = 'block';
|
|
4361
|
-
agentAddWalletInfo.innerHTML = '⏳ 正在生成真实 EVM 钱包...';
|
|
2278
|
+
agentGenerateWalletBtn.addEventListener('click', () => {
|
|
4362
2279
|
try {
|
|
4363
|
-
const
|
|
4364
|
-
agentAddWallet.value =
|
|
4365
|
-
pendingWalletSecret =
|
|
4366
|
-
|
|
4367
|
-
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
|
+
`;
|
|
4368
2290
|
} catch (err) {
|
|
2291
|
+
agentAddWalletInfo.style.display = 'block';
|
|
4369
2292
|
agentAddWalletInfo.innerHTML = '✗ 生成钱包失败: ' + escapeHtml(err.message);
|
|
4370
2293
|
}
|
|
4371
2294
|
});
|
|
@@ -4408,16 +2331,10 @@ if (agentAddConfirmBtn) {
|
|
|
4408
2331
|
} else {
|
|
4409
2332
|
// update
|
|
4410
2333
|
const channelId = agentAddConfirmBtn.dataset.channelId;
|
|
4411
|
-
const originalName = agentAddConfirmBtn.dataset.originalName || '';
|
|
4412
|
-
// v3 新增: 名字改了才发 (没改就不发, 保持原状)
|
|
4413
|
-
const body = { walletAddress: walletAddress || null, autoInvokeTools };
|
|
4414
|
-
if (name && name !== originalName) {
|
|
4415
|
-
body.name = name;
|
|
4416
|
-
}
|
|
4417
2334
|
const res = await fetch(`/channels/${channelId}`, {
|
|
4418
2335
|
method: 'PATCH',
|
|
4419
2336
|
headers: { 'Content-Type': 'application/json' },
|
|
4420
|
-
body: JSON.stringify(
|
|
2337
|
+
body: JSON.stringify({ walletAddress: walletAddress || null, autoInvokeTools })
|
|
4421
2338
|
});
|
|
4422
2339
|
if (!res.ok) throw new Error('update failed');
|
|
4423
2340
|
const updated = await res.json();
|
|
@@ -4432,3 +2349,4 @@ if (agentAddConfirmBtn) {
|
|
|
4432
2349
|
}
|
|
4433
2350
|
});
|
|
4434
2351
|
}
|
|
2352
|
+
|