mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 拓展中心机器人模板
This commit is contained in:
1 parent
49e2dab2a6
commit
fb1a1c9bb0
10 files changed
+320
-181
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.group-chat-bot",
|
||||
"name": "群聊机器人",
|
||||
"name": "群聊机器人 - 模板(如需使用请找授权你的人",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.6.0",
|
||||
|
||||
@@ -92,17 +92,12 @@ let hostCanSend = true
|
||||
let sendMaskDismissed = false
|
||||
|
||||
function syncSendCapabilityGating() {
|
||||
const botEnabledEl = document.getElementById('bot-enabled')
|
||||
const saveBtnEl = document.getElementById('save-config-btn')
|
||||
const autoSendBtn = document.getElementById('test-send-auto-btn')
|
||||
const textSendBtn = document.getElementById('test-send-text-btn')
|
||||
const voiceSendBtn = document.getElementById('test-send-voice-btn')
|
||||
|
||||
if (!hostCanSend) {
|
||||
if (botEnabledEl) {
|
||||
botEnabledEl.checked = false
|
||||
botEnabledEl.disabled = true
|
||||
}
|
||||
if (saveBtnEl) {
|
||||
saveBtnEl.disabled = true
|
||||
saveBtnEl.title = '当前暂无发送能力,仅可预览界面,无法保存启用'
|
||||
@@ -111,7 +106,6 @@ function syncSendCapabilityGating() {
|
||||
if (textSendBtn) textSendBtn.disabled = true
|
||||
if (voiceSendBtn) voiceSendBtn.disabled = true
|
||||
} else {
|
||||
if (botEnabledEl) botEnabledEl.disabled = false
|
||||
if (saveBtnEl) {
|
||||
saveBtnEl.disabled = false
|
||||
saveBtnEl.title = ''
|
||||
@@ -192,9 +186,8 @@ function normalizeConfig(raw) {
|
||||
const rawGroups = input.groups && typeof input.groups === 'object' ? input.groups : {}
|
||||
for (const [groupId, value] of Object.entries(rawGroups)) {
|
||||
const item = value && typeof value === 'object' ? value : {}
|
||||
if (item.enabled === false) continue
|
||||
groups[groupId] = {
|
||||
enabled: true,
|
||||
enabled: item.enabled !== false,
|
||||
name: String(item.name || '').slice(0, 64),
|
||||
personaId: validPersonaIds.has(item.personaId) ? item.personaId : defaultPersonaId,
|
||||
deliveryMode: ['inherit', 'text_only', 'voice_only', 'random_mix'].includes(
|
||||
@@ -208,7 +201,7 @@ function normalizeConfig(raw) {
|
||||
|
||||
return {
|
||||
version: 1,
|
||||
enabled: input.enabled === true,
|
||||
enabled: true,
|
||||
defaultPersonaId,
|
||||
triggerMode: ['mention', 'wake_word', 'mention_or_wake', 'ambient'].includes(input.triggerMode)
|
||||
? input.triggerMode
|
||||
@@ -554,71 +547,69 @@ function populatePersonaForm() {
|
||||
|
||||
/* ---------- 群聊选择与单群配置 ---------- */
|
||||
|
||||
function renderRosterChips() {
|
||||
const container = document.getElementById('roster-chips')
|
||||
const ids = Object.keys(config.groups)
|
||||
container.textContent = ''
|
||||
container.hidden = ids.length === 0
|
||||
|
||||
for (const id of ids) {
|
||||
const chip = document.createElement('span')
|
||||
chip.className = 'roster-chip'
|
||||
const label = document.createElement('span')
|
||||
label.textContent = groupDisplayName(id)
|
||||
label.title = id
|
||||
const removeBtn = document.createElement('button')
|
||||
removeBtn.type = 'button'
|
||||
removeBtn.textContent = '×'
|
||||
removeBtn.setAttribute('aria-label', `移除 ${groupDisplayName(id)}`)
|
||||
removeBtn.addEventListener('click', (event) => {
|
||||
event.stopPropagation()
|
||||
delete config.groups[id]
|
||||
renderRosterChips()
|
||||
renderRosterMenu()
|
||||
renderGroupTable()
|
||||
renderGroupDropdowns()
|
||||
})
|
||||
chip.append(label, removeBtn)
|
||||
container.append(chip)
|
||||
function ensureGroupEntry(id, name) {
|
||||
if (!config.groups[id]) {
|
||||
config.groups[id] = {
|
||||
enabled: true,
|
||||
name: name || '',
|
||||
personaId: config.defaultPersonaId,
|
||||
deliveryMode: 'inherit',
|
||||
memoryEnabled: true
|
||||
}
|
||||
}
|
||||
return config.groups[id]
|
||||
}
|
||||
|
||||
function renderRosterMenu() {
|
||||
const menu = document.getElementById('roster-menu')
|
||||
if (menu.hidden) return
|
||||
const query = document.getElementById('roster-search').value.trim().toLowerCase()
|
||||
menu.textContent = ''
|
||||
function selectedGroupIds() {
|
||||
return Object.keys(config.groups)
|
||||
}
|
||||
|
||||
/** 下拉按钮文案:没选时说清楚,选了就给数量。 */
|
||||
function renderRosterToggle() {
|
||||
const btn = document.getElementById('roster-toggle')
|
||||
if (!btn) return
|
||||
const count = selectedGroupIds().length
|
||||
btn.textContent = count === 0 ? '选择群聊…' : `已选 ${count} 个群聊`
|
||||
}
|
||||
|
||||
/** 下拉里的全量群列表,勾选即加入表格,取消即移出。 */
|
||||
function renderRosterOptions() {
|
||||
const box = document.getElementById('roster-options')
|
||||
if (!box) return
|
||||
const searchEl = document.getElementById('roster-search')
|
||||
const query = String(searchEl && searchEl.value ? searchEl.value : '').trim().toLowerCase()
|
||||
box.textContent = ''
|
||||
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'roster-empty'
|
||||
|
||||
if (rosterError) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'roster-empty'
|
||||
empty.textContent = rosterError
|
||||
menu.append(empty)
|
||||
box.append(empty)
|
||||
return
|
||||
}
|
||||
|
||||
if (!allGroups.length) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'roster-empty'
|
||||
empty.textContent = '暂无可选群会话(需先连接本地微信库并开启群列表读取权限)'
|
||||
menu.append(empty)
|
||||
empty.textContent = '暂未读取到群会话,请点「刷新群列表」并确认已授予群列表读取权限'
|
||||
box.append(empty)
|
||||
return
|
||||
}
|
||||
|
||||
const matched = allGroups.filter((group) => {
|
||||
if (!group || !group.id) return false
|
||||
if (!query) return true
|
||||
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
|
||||
return (
|
||||
group.id.toLowerCase().includes(query) ||
|
||||
String(group.name || '').toLowerCase().includes(query)
|
||||
)
|
||||
})
|
||||
|
||||
if (!matched.length) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'roster-empty'
|
||||
empty.textContent = '没有匹配的微信群聊'
|
||||
menu.append(empty)
|
||||
box.append(empty)
|
||||
return
|
||||
}
|
||||
|
||||
for (const group of matched.slice(0, 200)) {
|
||||
for (const group of matched.slice(0, 300)) {
|
||||
const row = document.createElement('label')
|
||||
row.className = 'roster-option'
|
||||
const checkbox = document.createElement('input')
|
||||
@@ -626,39 +617,36 @@ function renderRosterMenu() {
|
||||
checkbox.checked = Boolean(config.groups[group.id])
|
||||
checkbox.addEventListener('change', () => {
|
||||
if (checkbox.checked) {
|
||||
config.groups[group.id] = {
|
||||
enabled: true,
|
||||
name: group.name || '',
|
||||
personaId: config.defaultPersonaId,
|
||||
deliveryMode: 'inherit',
|
||||
memoryEnabled: true
|
||||
}
|
||||
ensureGroupEntry(group.id, group.name)
|
||||
} else {
|
||||
delete config.groups[group.id]
|
||||
}
|
||||
renderRosterChips()
|
||||
renderRosterToggle()
|
||||
renderGroupTable()
|
||||
renderGroupDropdowns()
|
||||
})
|
||||
const text = document.createElement('span')
|
||||
text.textContent =
|
||||
group.name && group.name !== group.id ? `${group.name} (${group.id})` : group.id
|
||||
group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
|
||||
row.append(checkbox, text)
|
||||
menu.append(row)
|
||||
box.append(row)
|
||||
}
|
||||
}
|
||||
|
||||
/** 只渲染已选中的群;每行的「生效」控制该群是否接话。 */
|
||||
function renderGroupTable() {
|
||||
const listEl = document.getElementById('group-list')
|
||||
const emptyEl = document.getElementById('group-empty')
|
||||
listEl.textContent = ''
|
||||
const ids = Object.keys(config.groups)
|
||||
const ids = selectedGroupIds()
|
||||
emptyEl.hidden = ids.length > 0
|
||||
|
||||
for (const id of ids) {
|
||||
const groupCfg = config.groups[id]
|
||||
const entry = config.groups[id] || null
|
||||
const active = Boolean(entry && entry.enabled === true)
|
||||
|
||||
const row = document.createElement('div')
|
||||
row.className = 'group-row'
|
||||
row.className = active ? 'group-row' : 'group-row is-off'
|
||||
|
||||
const title = document.createElement('div')
|
||||
title.className = 'group-title'
|
||||
@@ -667,6 +655,23 @@ function renderGroupTable() {
|
||||
sub.textContent = id
|
||||
title.append(sub)
|
||||
|
||||
const enableWrap = document.createElement('label')
|
||||
enableWrap.className = 'check'
|
||||
enableWrap.style.marginTop = '0'
|
||||
const enableCheck = document.createElement('input')
|
||||
enableCheck.type = 'checkbox'
|
||||
enableCheck.checked = active
|
||||
enableCheck.title = active ? '取消后该群不再回复' : '勾选后该群开始接话'
|
||||
enableCheck.addEventListener('change', () => {
|
||||
if (enableCheck.checked) {
|
||||
ensureGroupEntry(id, '').enabled = true
|
||||
} else {
|
||||
config.groups[id].enabled = false
|
||||
}
|
||||
renderGroupTable()
|
||||
})
|
||||
enableWrap.append(enableCheck)
|
||||
|
||||
const personaSelect = document.createElement('select')
|
||||
for (const persona of config.personas) {
|
||||
const opt = document.createElement('option')
|
||||
@@ -674,9 +679,9 @@ function renderGroupTable() {
|
||||
opt.textContent = persona.name
|
||||
personaSelect.append(opt)
|
||||
}
|
||||
personaSelect.value = groupCfg.personaId
|
||||
personaSelect.value = (entry && entry.personaId) || config.defaultPersonaId
|
||||
personaSelect.addEventListener('change', () => {
|
||||
config.groups[id].personaId = personaSelect.value
|
||||
ensureGroupEntry(id, '').personaId = personaSelect.value
|
||||
})
|
||||
|
||||
const modeSelect = document.createElement('select')
|
||||
@@ -686,15 +691,15 @@ function renderGroupTable() {
|
||||
{ value: 'text_only', label: '仅回复文字' },
|
||||
{ value: 'voice_only', label: '仅发送语音' }
|
||||
]
|
||||
for (const item of modes) {
|
||||
for (const mode of modes) {
|
||||
const opt = document.createElement('option')
|
||||
opt.value = item.value
|
||||
opt.textContent = item.label
|
||||
opt.value = mode.value
|
||||
opt.textContent = mode.label
|
||||
modeSelect.append(opt)
|
||||
}
|
||||
modeSelect.value = groupCfg.deliveryMode || 'inherit'
|
||||
modeSelect.value = (entry && entry.deliveryMode) || 'inherit'
|
||||
modeSelect.addEventListener('change', () => {
|
||||
config.groups[id].deliveryMode = modeSelect.value
|
||||
ensureGroupEntry(id, '').deliveryMode = modeSelect.value
|
||||
})
|
||||
|
||||
const memoryWrap = document.createElement('label')
|
||||
@@ -702,9 +707,9 @@ function renderGroupTable() {
|
||||
memoryWrap.style.marginTop = '0'
|
||||
const memoryCheck = document.createElement('input')
|
||||
memoryCheck.type = 'checkbox'
|
||||
memoryCheck.checked = groupCfg.memoryEnabled !== false
|
||||
memoryCheck.checked = !entry || entry.memoryEnabled !== false
|
||||
memoryCheck.addEventListener('change', () => {
|
||||
config.groups[id].memoryEnabled = memoryCheck.checked
|
||||
ensureGroupEntry(id, '').memoryEnabled = memoryCheck.checked
|
||||
})
|
||||
const memorySpan = document.createElement('span')
|
||||
memorySpan.textContent = '开启'
|
||||
@@ -719,7 +724,7 @@ function renderGroupTable() {
|
||||
void loadGroupMemoryToForm(id)
|
||||
})
|
||||
|
||||
row.append(title, personaSelect, modeSelect, memoryWrap, memoryBtn)
|
||||
row.append(title, enableWrap, personaSelect, modeSelect, memoryWrap, memoryBtn)
|
||||
listEl.append(row)
|
||||
}
|
||||
}
|
||||
@@ -874,7 +879,6 @@ function syncConditionalFields() {
|
||||
}
|
||||
|
||||
function syncFormFromConfig() {
|
||||
document.getElementById('bot-enabled').checked = config.enabled === true
|
||||
document.getElementById('trigger-mode').value = config.triggerMode
|
||||
document.getElementById('wake-words').value = config.wakeWords.join(', ')
|
||||
document.getElementById('ambient-chance').value = String(config.ambientReplyChance)
|
||||
@@ -901,7 +905,7 @@ function syncFormFromConfig() {
|
||||
editingPersonaId = config.defaultPersonaId || config.personas[0].id
|
||||
renderPersonaSelectors()
|
||||
populatePersonaForm()
|
||||
renderRosterChips()
|
||||
renderRosterToggle()
|
||||
renderGroupTable()
|
||||
renderGroupDropdowns()
|
||||
syncConditionalFields()
|
||||
@@ -909,7 +913,8 @@ function syncFormFromConfig() {
|
||||
|
||||
function collectConfigFromForm() {
|
||||
commitCurrentPersona()
|
||||
config.enabled = document.getElementById('bot-enabled').checked
|
||||
// 是否启用由扩展中心决定,配置层恒为开启。
|
||||
config.enabled = true
|
||||
config.defaultPersonaId = document.getElementById('default-persona-select').value
|
||||
config.triggerMode = document.getElementById('trigger-mode').value
|
||||
config.wakeWords = document
|
||||
@@ -980,8 +985,8 @@ async function loadGroupsRoster() {
|
||||
allGroups = []
|
||||
rosterError = `读取群列表受限:${error.message}`
|
||||
}
|
||||
renderRosterChips()
|
||||
renderRosterMenu()
|
||||
renderRosterToggle()
|
||||
renderRosterOptions()
|
||||
renderGroupTable()
|
||||
renderGroupDropdowns()
|
||||
}
|
||||
@@ -1099,22 +1104,24 @@ document.getElementById('persona-delete-btn').addEventListener('click', () => {
|
||||
setBanner('已删除该人格,关联群聊已切回默认人格。', 'ok')
|
||||
})
|
||||
|
||||
const rosterPicker = document.getElementById('roster-picker')
|
||||
const rosterToggle = document.getElementById('roster-toggle')
|
||||
const rosterSearch = document.getElementById('roster-search')
|
||||
const rosterMenu = document.getElementById('roster-menu')
|
||||
|
||||
rosterSearch.addEventListener('focus', () => {
|
||||
rosterMenu.hidden = false
|
||||
renderRosterMenu()
|
||||
function setRosterOpen(open) {
|
||||
rosterMenu.hidden = !open
|
||||
rosterToggle.setAttribute('aria-expanded', open ? 'true' : 'false')
|
||||
if (open) renderRosterOptions()
|
||||
}
|
||||
|
||||
rosterToggle.addEventListener('click', (event) => {
|
||||
event.stopPropagation()
|
||||
setRosterOpen(rosterMenu.hidden)
|
||||
})
|
||||
rosterSearch.addEventListener('input', () => {
|
||||
rosterMenu.hidden = false
|
||||
renderRosterMenu()
|
||||
})
|
||||
document.addEventListener('click', (event) => {
|
||||
if (!rosterPicker.contains(event.target)) {
|
||||
rosterMenu.hidden = true
|
||||
}
|
||||
rosterSearch.addEventListener('input', () => renderRosterOptions())
|
||||
rosterMenu.addEventListener('click', (event) => event.stopPropagation())
|
||||
document.addEventListener('click', () => {
|
||||
if (!rosterMenu.hidden) setRosterOpen(false)
|
||||
})
|
||||
|
||||
document.getElementById('reload-groups-btn').addEventListener('click', async () => {
|
||||
@@ -1311,7 +1318,7 @@ async function initializePage() {
|
||||
document.getElementById('memory-group-select').value = groupIds[0]
|
||||
await loadGroupMemoryToForm(groupIds[0])
|
||||
}
|
||||
setBanner('群聊机器人配置已就绪。默认处于关闭状态,配置完成后勾选启用并保存即可。')
|
||||
setBanner('群聊机器人配置已就绪。选中群聊并勾选「生效」后保存,即可开始接话。')
|
||||
}
|
||||
|
||||
initializePage().catch((error) => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>群聊机器人设置</title>
|
||||
<title>群聊机器人 - 模板(如需使用请找授权你的人</title>
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
</head>
|
||||
<body>
|
||||
@@ -12,7 +12,7 @@
|
||||
<div>
|
||||
<p class="eyebrow">TraceMemo 官方扩展模板 · com.example.group-chat-bot</p>
|
||||
<div class="hero-title-row">
|
||||
<h1>群聊机器人</h1>
|
||||
<h1>群聊机器人 - 模板(如需使用请找授权你的人</h1>
|
||||
<span id="hero-send-warn" class="send-warn-badge" hidden>
|
||||
<span class="send-warn-bang" aria-hidden="true">!</span>
|
||||
当前暂无发送能力
|
||||
@@ -205,10 +205,7 @@
|
||||
|
||||
<section class="card">
|
||||
<h2>触发策略、节奏与安全防护</h2>
|
||||
<label class="check">
|
||||
<input id="bot-enabled" type="checkbox" />
|
||||
<span>启用群聊机器人自动接话(需同时在扩展中心启用本扩展并选择生效群聊)</span>
|
||||
</label>
|
||||
<p class="hint">扩展在扩展中心启用后即开始接话,接话范围由下方勾选的群聊决定。</p>
|
||||
|
||||
<div class="grid two">
|
||||
<label class="field">
|
||||
@@ -322,28 +319,39 @@
|
||||
<div>
|
||||
<h2>生效群聊与单群策略</h2>
|
||||
<p class="hint">
|
||||
只对下方勾选的群聊生效。可为每个群单独分配人格、回复形式(文字/语音/随机)与群聊记忆。
|
||||
先在上方下拉里挑选群聊,选中的会列在下方;每行的「生效」控制该群是否接话。人格、回复形式与群记忆可按群单独设置。
|
||||
</p>
|
||||
</div>
|
||||
<button id="reload-groups-btn" type="button" class="ghost">刷新群列表</button>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<span>搜索并添加微信群聊</span>
|
||||
<span>选择群聊</span>
|
||||
<div id="roster-picker" class="roster-picker">
|
||||
<div id="roster-chips" class="roster-chips" hidden></div>
|
||||
<input
|
||||
id="roster-search"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
placeholder="输入群名称或 chatroom ID 搜索并勾选…"
|
||||
/>
|
||||
<div id="roster-menu" class="roster-menu" hidden></div>
|
||||
<button
|
||||
id="roster-toggle"
|
||||
type="button"
|
||||
class="roster-toggle"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
>
|
||||
选择群聊…
|
||||
</button>
|
||||
<div id="roster-menu" class="roster-menu" hidden>
|
||||
<input
|
||||
id="roster-search"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
placeholder="搜索群名称或 chatroom ID…"
|
||||
/>
|
||||
<div id="roster-options"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="group-table-header">
|
||||
<span>群聊名称</span>
|
||||
<span>生效</span>
|
||||
<span>绑定人格</span>
|
||||
<span>回复形式</span>
|
||||
<span>群记忆</span>
|
||||
@@ -351,7 +359,7 @@
|
||||
</div>
|
||||
<div id="group-list" class="group-list"></div>
|
||||
<p id="group-empty" class="empty-hint">
|
||||
暂未选择任何群聊。请在上方搜索框中选择需要启用机器人的群聊。
|
||||
还未选择群聊。请在上方下拉中选择需要接话的群聊。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -156,6 +156,7 @@ h2 {
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
white-space: normal;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
@@ -342,7 +343,12 @@ button.primary:hover:not(:disabled) {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
button.ghost {
|
||||
.card-header > button {
|
||||
flex: 0 0 auto;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ghost {
|
||||
background: transparent;
|
||||
border-color: var(--border);
|
||||
color: var(--text);
|
||||
@@ -356,30 +362,29 @@ button.ghost.danger {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.roster-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.roster-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 9px;
|
||||
border-radius: 999px;
|
||||
/* 下拉开关:外观对齐同排 select,右侧给个箭头。 */
|
||||
.roster-toggle {
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface-subtle);
|
||||
font-size: 12px;
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.roster-chip button {
|
||||
padding: 0 3px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
.roster-toggle::after {
|
||||
content: '▾';
|
||||
float: right;
|
||||
color: var(--muted);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.roster-options {
|
||||
margin-top: 4px;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.roster-menu {
|
||||
@@ -419,7 +424,7 @@ button.ghost.danger {
|
||||
|
||||
.group-table-header {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(140px, 1.4fr) minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
|
||||
grid-template-columns: minmax(140px, 1.4fr) 64px minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
|
||||
gap: 8px;
|
||||
margin-top: 14px;
|
||||
padding: 0 8px 6px;
|
||||
@@ -437,7 +442,7 @@ button.ghost.danger {
|
||||
|
||||
.group-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(140px, 1.4fr) minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
|
||||
grid-template-columns: minmax(140px, 1.4fr) 64px minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
padding: 8px;
|
||||
@@ -446,6 +451,15 @@ button.ghost.danger {
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
|
||||
/* 未勾选生效的群:整行降透明,但仍可编辑人格/回复形式。 */
|
||||
.group-row.is-off {
|
||||
opacity: 0.62;
|
||||
}
|
||||
|
||||
.group-row.is-off:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.group-title {
|
||||
font-weight: 500;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
"bytes": 33471
|
||||
},
|
||||
"group-chat-bot@1.0.0": {
|
||||
"sha256": "7ba441c89a04d386ff97c854278bc9af3dbd8d6e8e10d1dba48b7ac9c3497d26",
|
||||
"bytes": 23997
|
||||
"sha256": "5c2d7409011184b85980a37955347537cd9530860f81b644ec995971d5af6f66",
|
||||
"bytes": 24751
|
||||
},
|
||||
"keyword-bot@1.0.0": {
|
||||
"sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d",
|
||||
|
||||
@@ -87,6 +87,13 @@ function crc32(buffer) {
|
||||
return (crc ^ 0xffffffff) >>> 0
|
||||
}
|
||||
|
||||
/** 归一化 CRLF:Windows 检出与 macOS 基线必须产出同一份字节,否则 sha256 必然不匹配。 */
|
||||
function normalizeLineEndings(buffer) {
|
||||
if (buffer.includes(0)) return buffer
|
||||
if (!buffer.includes(0x0d)) return buffer
|
||||
return Buffer.from(buffer.toString('latin1').replace(/\r\n/g, '\n'), 'latin1')
|
||||
}
|
||||
|
||||
function isSafeRelativePath(value) {
|
||||
if (typeof value !== 'string' || !value || value.length > 240) return false
|
||||
if (value.includes('\0')) return false
|
||||
@@ -129,7 +136,10 @@ function collectTemplateFiles(spec, sourceRoot = SOURCE_ROOT) {
|
||||
if (!isSafeRelativePath(relative)) {
|
||||
throw new Error(`模板内文件路径不合法:${spec.dir}/${relative}`)
|
||||
}
|
||||
files.push({ path: relative, data: fs.readFileSync(path.join(directory, entry.name)) })
|
||||
files.push({
|
||||
path: relative,
|
||||
data: normalizeLineEndings(fs.readFileSync(path.join(directory, entry.name)))
|
||||
})
|
||||
}
|
||||
}
|
||||
walk(root, '')
|
||||
|
||||
@@ -43,6 +43,8 @@ const EVENT_REFILL_PER_SECOND = 60
|
||||
const GRACEFUL_EXIT_MS = 2_500
|
||||
/** 结束进程树之后等待 exit 事件的时间。 */
|
||||
const FORCE_EXIT_MS = 3_000
|
||||
/** taskkill 的等待上限:卡住时按降级处理,不能拖死停用流程。 */
|
||||
const TASKKILL_TIMEOUT_MS = 5_000
|
||||
|
||||
/** stderr 采样窗口:只把有代表性的片段写进日志,避免日志洪水拖住主进程。 */
|
||||
const STDERR_WINDOW_MS = 10_000
|
||||
@@ -324,7 +326,7 @@ export class ExtensionHost {
|
||||
}
|
||||
|
||||
this.dependencies.onLog?.('warn', '扩展未在预期时间内退出,正在结束进程树')
|
||||
this.killTree(child)
|
||||
await this.killTree(child)
|
||||
if (!(await this.waitForExit(child, this.dependencies.forceExitMs ?? FORCE_EXIT_MS))) {
|
||||
this.dependencies.onLog?.('error', '扩展进程树未能退出,可能有子进程仍在运行')
|
||||
}
|
||||
@@ -332,7 +334,7 @@ export class ExtensionHost {
|
||||
}
|
||||
|
||||
/** 结束进程树;Windows 的 taskkill /T 必须在父进程存活时执行,否则找不到孙进程。 */
|
||||
private killTree(child: ExtensionHostChild): void {
|
||||
private async killTree(child: ExtensionHostChild): Promise<void> {
|
||||
const pid = child.pid
|
||||
if (!pid) {
|
||||
try {
|
||||
@@ -342,10 +344,15 @@ export class ExtensionHost {
|
||||
}
|
||||
return
|
||||
}
|
||||
const result = killProcessTree(pid)
|
||||
if (result !== 'group' && process.platform !== 'win32') {
|
||||
this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程')
|
||||
const result = await killProcessTree(pid, {
|
||||
timeoutMs: this.dependencies.forceExitMs ?? TASKKILL_TIMEOUT_MS
|
||||
})
|
||||
if (result === 'group') return
|
||||
if (process.platform === 'win32') {
|
||||
this.dependencies.onLog?.('warn', '结束扩展进程树失败,可能有子进程仍在运行')
|
||||
return
|
||||
}
|
||||
this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程')
|
||||
}
|
||||
|
||||
private waitForExit(child: ExtensionHostChild, timeoutMs: number): Promise<boolean> {
|
||||
@@ -874,27 +881,19 @@ export class ExtensionHost {
|
||||
}
|
||||
}
|
||||
|
||||
/** 结束 `pid` 对应的进程树;`taskkill`:Windows 进程树,必须在父进程仍存活时调用。 */
|
||||
export function killProcessTree(
|
||||
/** 结束进程树;taskkill 只在 exit 0 时算成功,发起成功不算。 */
|
||||
export type ProcessTreeKillResult = 'group' | 'taskkill' | 'fallback'
|
||||
|
||||
export async function killProcessTree(
|
||||
pid: number | undefined,
|
||||
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals } = {}
|
||||
): 'group' | 'taskkill' | 'fallback' {
|
||||
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals; timeoutMs?: number } = {}
|
||||
): Promise<ProcessTreeKillResult> {
|
||||
if (!pid) return 'fallback'
|
||||
const platform = options.platform ?? process.platform
|
||||
const signal = options.signal ?? 'SIGKILL'
|
||||
|
||||
if (platform === 'win32') {
|
||||
try {
|
||||
const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], {
|
||||
windowsHide: true,
|
||||
stdio: 'ignore'
|
||||
})
|
||||
killer.on('error', () => undefined)
|
||||
killer.unref?.()
|
||||
return 'taskkill'
|
||||
} catch {
|
||||
return 'fallback'
|
||||
}
|
||||
return killWindowsProcessTree(pid, options.timeoutMs ?? TASKKILL_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -910,6 +909,46 @@ export function killProcessTree(
|
||||
}
|
||||
}
|
||||
|
||||
/** Windows:等 taskkill 真实退出,只认 exit code 0。 */
|
||||
function killWindowsProcessTree(
|
||||
pid: number,
|
||||
timeoutMs: number
|
||||
): Promise<'taskkill' | 'fallback'> {
|
||||
return new Promise((resolve) => {
|
||||
let killer: ChildProcess
|
||||
try {
|
||||
killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], {
|
||||
windowsHide: true,
|
||||
stdio: 'ignore'
|
||||
})
|
||||
} catch {
|
||||
// 无法启动 taskkill(极少数受限环境):只能退化为「主进程可能已退出」。
|
||||
resolve('fallback')
|
||||
return
|
||||
}
|
||||
|
||||
let settled = false
|
||||
const finish = (result: 'taskkill' | 'fallback'): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
resolve(result)
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
killer.kill()
|
||||
} catch {
|
||||
// 已经退出。
|
||||
}
|
||||
finish('fallback')
|
||||
}, timeoutMs)
|
||||
|
||||
killer.on('error', () => finish('fallback'))
|
||||
killer.on('exit', (code) => finish(code === 0 ? 'taskkill' : 'fallback'))
|
||||
})
|
||||
}
|
||||
|
||||
/** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */
|
||||
export function forkExtensionHost(
|
||||
scriptPath: string
|
||||
|
||||
@@ -705,6 +705,9 @@ function logSendDiagnostic(
|
||||
console.log(`[SendDiag] ${stage} ${JSON.stringify(detail)}`)
|
||||
}
|
||||
|
||||
/** 能力轮询会反复打这些端点,成功时不计入发送诊断,否则日志被探测刷满。 */
|
||||
const WINDOWS_PROBE_ENDPOINTS = new Set(['/getLoginInfo'])
|
||||
|
||||
/** 发送完成后**保留**图片临时文件的时长(毫秒)。默认 `0` = 立刻删除(现行行为)。 */
|
||||
const WINDOWS_TEMP_IMAGE_GRACE_MS = 0
|
||||
|
||||
@@ -740,12 +743,15 @@ async function requestWindowsHook(
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
if (method !== 'GET') init.body = JSON.stringify(body)
|
||||
logSendDiagnostic('hook-request', {
|
||||
endpoint,
|
||||
method,
|
||||
// 只报 payload 里有没有内容,不报内容本身。
|
||||
hasPayload: method !== 'GET' ? init.body !== undefined : false
|
||||
})
|
||||
const isProbe = WINDOWS_PROBE_ENDPOINTS.has(endpoint)
|
||||
if (!isProbe) {
|
||||
logSendDiagnostic('hook-request', {
|
||||
endpoint,
|
||||
method,
|
||||
// 只报 payload 里有没有内容,不报内容本身。
|
||||
hasPayload: method !== 'GET' ? init.body !== undefined : false
|
||||
})
|
||||
}
|
||||
const response = await requestWithTimeout(`http://${host}${endpoint}`, init, timeoutMs)
|
||||
const responseText = await response.text()
|
||||
if (!response.ok) {
|
||||
@@ -760,14 +766,16 @@ async function requestWindowsHook(
|
||||
throw new WindowsHookHttpError(response.status, responseText)
|
||||
}
|
||||
const parsed = parseWindowsHookResponse(responseText, method === 'POST')
|
||||
logSendDiagnostic('hook-response', {
|
||||
endpoint,
|
||||
httpStatus: response.status,
|
||||
ok: true,
|
||||
ret: typeof parsed.ret === 'number' ? parsed.ret : null,
|
||||
retMessageLength: String(parsed.retmsg ?? parsed.msg ?? '').length,
|
||||
elapsedMs: Date.now() - startedAt
|
||||
})
|
||||
if (!isProbe) {
|
||||
logSendDiagnostic('hook-response', {
|
||||
endpoint,
|
||||
httpStatus: response.status,
|
||||
ok: true,
|
||||
ret: typeof parsed.ret === 'number' ? parsed.ret : null,
|
||||
retMessageLength: String(parsed.retmsg ?? parsed.msg ?? '').length,
|
||||
elapsedMs: Date.now() - startedAt
|
||||
})
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
|
||||
@@ -105,6 +105,9 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
|
||||
}
|
||||
}
|
||||
|
||||
/** 发送能力探活间隔:轮询只为点亮导航红点,低频足够。 */
|
||||
const SEND_CAPABILITY_POLL_MS = 30 * 60 * 1000
|
||||
|
||||
export function PrimaryNavigation({
|
||||
activePage,
|
||||
onPageChange
|
||||
@@ -125,10 +128,16 @@ export function PrimaryNavigation({
|
||||
.catch(() => undefined)
|
||||
}
|
||||
checkSendCapability()
|
||||
const timer = window.setInterval(checkSendCapability, 8_000)
|
||||
const timer = window.setInterval(checkSendCapability, SEND_CAPABILITY_POLL_MS)
|
||||
// 半小时才轮一次,红点会过期;窗口重新可见时补查一次,成本可忽略。
|
||||
const onVisibilityChange = (): void => {
|
||||
if (!document.hidden) checkSendCapability()
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
return () => {
|
||||
disposed = true
|
||||
window.clearInterval(timer)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
}
|
||||
}, [activePage])
|
||||
|
||||
|
||||
@@ -93,20 +93,19 @@ describe('killProcessTree', () => {
|
||||
await sleep(100)
|
||||
expect(isAlive(grandchildPid)).toBe(true)
|
||||
|
||||
expect(killProcessTree(parent.pid)).toBe('group')
|
||||
expect(await killProcessTree(parent.pid)).toBe('group')
|
||||
await sleep(300)
|
||||
expect(isAlive(grandchildPid)).toBe(false)
|
||||
expect(isAlive(parent.pid as number)).toBe(false)
|
||||
})
|
||||
|
||||
it('不存在的 pid 返回 fallback 且不抛错', () => {
|
||||
expect(() => killProcessTree(999_999_999)).not.toThrow()
|
||||
expect(killProcessTree(999_999_999)).toBe('fallback')
|
||||
expect(killProcessTree(undefined)).toBe('fallback')
|
||||
it('不存在的 pid 返回 fallback 且不抛错', async () => {
|
||||
// 不存在的 PID 会让 taskkill 以 128 退出,断言必须落在真实结果上。
|
||||
await expect(killProcessTree(999_999_999)).resolves.toBe('fallback')
|
||||
await expect(killProcessTree(undefined)).resolves.toBe('fallback')
|
||||
})
|
||||
|
||||
it('只结束指定组,不影响另一个进程组', async () => {
|
||||
if (process.platform === 'win32') return
|
||||
it.skipIf(process.platform === 'win32')('只结束指定组,不影响另一个进程组', async () => {
|
||||
const dir = tempRoot()
|
||||
const script = path.join(dir, 'parent.js')
|
||||
fs.writeFileSync(script, 'setInterval(() => {}, 1000)')
|
||||
@@ -116,11 +115,56 @@ describe('killProcessTree', () => {
|
||||
spawned.push(first.pid as number, second.pid as number)
|
||||
await sleep(120)
|
||||
|
||||
killProcessTree(first.pid)
|
||||
await killProcessTree(first.pid)
|
||||
await sleep(300)
|
||||
expect(isAlive(first.pid as number)).toBe(false)
|
||||
expect(isAlive(second.pid as number)).toBe(true)
|
||||
})
|
||||
|
||||
/** 覆盖 Windows 进程树:父+孙都被结束,且不波及无关进程。 */
|
||||
it.skipIf(process.platform !== 'win32')(
|
||||
'Windows 结束父进程树时连带孙进程,且不影响无关进程',
|
||||
async () => {
|
||||
const dir = tempRoot()
|
||||
const script = path.join(dir, 'tree-parent.js')
|
||||
fs.writeFileSync(
|
||||
script,
|
||||
`const { spawn } = require('node:child_process')
|
||||
const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {
|
||||
stdio: 'ignore'
|
||||
})
|
||||
process.send({ grandchild: child.pid })
|
||||
setInterval(() => {}, 1000)`
|
||||
)
|
||||
|
||||
const parent = spawn(process.execPath, [script], {
|
||||
stdio: ['ignore', 'ignore', 'ignore', 'ipc']
|
||||
})
|
||||
spawned.push(parent.pid as number)
|
||||
|
||||
const grandchildPid = await new Promise<number>((resolve) => {
|
||||
parent.on('message', (message) => resolve((message as { grandchild: number }).grandchild))
|
||||
})
|
||||
spawned.push(grandchildPid)
|
||||
|
||||
// 无关进程:验证杀树不会波及别的扩展。
|
||||
const bystander = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {
|
||||
stdio: 'ignore'
|
||||
})
|
||||
spawned.push(bystander.pid as number)
|
||||
|
||||
await sleep(200)
|
||||
expect(isAlive(grandchildPid)).toBe(true)
|
||||
expect(isAlive(bystander.pid as number)).toBe(true)
|
||||
|
||||
expect(await killProcessTree(parent.pid)).toBe('taskkill')
|
||||
|
||||
await sleep(600)
|
||||
expect(isAlive(parent.pid as number)).toBe(false)
|
||||
expect(isAlive(grandchildPid)).toBe(false)
|
||||
expect(isAlive(bystander.pid as number)).toBe(true)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
describe('extension host 进程生命周期', () => {
|
||||
|
||||
Reference in new issue
Block a user