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