diff --git a/plugins/process-killer/.gitignore b/plugins/process-killer/.gitignore new file mode 100644 index 000000000..f555c6042 --- /dev/null +++ b/plugins/process-killer/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +.DS_Store +*.log + +# 打包结果不进仓库(安装包走 GitHub Releases) +releases/ diff --git a/plugins/process-killer/CHANGELOG.md b/plugins/process-killer/CHANGELOG.md new file mode 100644 index 000000000..96db21c49 --- /dev/null +++ b/plugins/process-killer/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +## 1.0.0 - 2026-11-20 + +- 初次发布到 ZTools 插件市场,插件 ID `process-killer`(进程管家)。 +- 列出进程的 CPU、内存与监听端口,支持按内存 / CPU / 名称 / 端口排序,搜索进程名、路径、PID 或端口。 +- 关闭进程:先发送 SIGTERM(Windows 走 WM_CLOSE),3 秒未退出时提示可强制结束;另有重启 .app、复制路径、在文件夹中显示、查看完整启动命令。 +- 主搜索框直出结果:输入 `kill chrome`、`netstat 8080` 直接列出进程,回车即可关闭。 +- 自动 / 手动刷新开关;关闭进程前弹出确认框,确认后才执行。 +- 支持 macOS 与 Windows 双端。 diff --git a/plugins/process-killer/README.md b/plugins/process-killer/README.md new file mode 100644 index 000000000..f21031e43 --- /dev/null +++ b/plugins/process-killer/README.md @@ -0,0 +1,61 @@ +# 进程管家(process-killer) + +ZTools 插件(ID `process-killer`):搜索进程名或端口,查看 CPU、内存与端口占用,关闭、强制结束或重启进程。支持 macOS 与 Windows。 + +在 ZTools 里输入 `kill`、`关闭进程`、`进程管理`、`进程管家`、`netstat`、`端口占用` 即可打开。 + +## 功能 + +- 列出进程及其 CPU、内存、监听端口,按内存 / CPU / 名称 / 端口排序 +- 搜索进程名、路径、PID 或端口号 +- 关闭(先温和退出,3 秒未退提示可强制结束)、强制结束、重启 .app / .exe、复制路径、文件夹中显示、查看完整启动命令 +- 关闭前弹确认框,确认后才真正结束进程 +- 自动 / 手动刷新开关 +- 主搜索框直接推结果:输入 `kill chrome` 或 `netstat 8080` 即列出,回车关闭 + +## 目录结构 + +本仓库按 [ZToolsCenter/ZTools-plugins](https://github.com/ZToolsCenter/ZTools-plugins) 的目录约定组织,插件 ID 为 `process-killer`: + +```text +src-ztools/ +├── build-plugin.sh 官方 CI 的构建钩子:跑 npm run build +└── ztools/ 插件目录(提交在仓库里,清单所在目录 = 安装包内容) + ├── plugin.json 清单(name / title / version / main / preload / platform …) + ├── logo.png 图标 + ├── index.html 界面入口 + ├── main.js / style.css + └── preload/ Node 侧采集与操作 +``` + +发布 CLI 会把整个工程目录复制成仓库里的 `plugins/process-killer/`,但它复制时会**跳过所有名为 `dist` 的目录**,所以运行时代码放在 `src-ztools/ztools/`;本地构建输出的 `dist/` 是安装包内容,不提交(已在 `.gitignore` 里)。 + +官方 CI 没有 `build-plugin.sh` 时,会把 `src-ztools/` 整份打成安装包;有钩子则先执行构建。两条路径都能拿到正确的安装包结构, + +## 本地开发 + +Node.js >= 20(本机用 nvm 的 v20.19.5)。 + +```sh +npm run build # 把 src-ztools/ztools 整理成 dist/(安装包内容),并核对清单声明的文件 +npm run package # 另外输出 releases/process-killer-<版本>.zip +npm test # 单元测试 +npm run test:ui # Chrome 里跑一遍界面,需要 playwright 与本机 Chrome +``` + +ZTools 开发者工具里的开发模式添加 `src-ztools/ztools/plugin.json` 即可加载本工程。 + +## 发布 + +```sh +ztools publish +``` + +本机已安装 `@ztools-center/plugin-cli`(`~/.nvm/versions/node/v14.21.3/bin/ztools`),token 存在 `~/.config/ztools/cli-config.json`。发布前需要:`plugin.json` 的 version 已升、`CHANGELOG.md` 有对应 `## 版本 - 日期` 段落、工作区干净。 + +## 注意 + +- CPU 取自 `ps` / CIM 的累计百分比,不是瞬时值,与活动监视器口径不同。 +- `lsof`(macOS)/ `netstat`(Windows)看不到无权限用户进程的端口,界面会提示。 +- 只能重启应用包(.app / .exe);命令行程序直接启动会丢环境变量,故明确报错。 +- 关闭系统进程需要更高权限,插件不做提权。 diff --git a/plugins/process-killer/package.json b/plugins/process-killer/package.json new file mode 100644 index 000000000..d82f19fe1 --- /dev/null +++ b/plugins/process-killer/package.json @@ -0,0 +1,23 @@ +{ + "name": "ztools-process-killer", + "private": true, + "version": "1.0.0", + "type": "module", + "description": "ZTools 插件:搜索进程名或端口,关闭/重启/查看进程", + "scripts": { + "build": "node scripts/build-process-killer.mjs", + "package": "node scripts/build-process-killer.mjs --zip", + "test": "node --test test/*.test.cjs", + "test:ui": "node test/ui-smoke.cjs && node test/ui-smoke-win.cjs && node test/auto-refresh.test.cjs" + }, + "dependencies": { + "vite": "^6.0.11", + "vue": "^3.5.13" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^5.2.1", + "@ztools-center/ztools-api-types": "^1.0.1", + "typescript": "^5.3.0", + "vue-tsc": "^2.0.0" + } +} diff --git a/plugins/process-killer/scripts/build-process-killer.mjs b/plugins/process-killer/scripts/build-process-killer.mjs new file mode 100644 index 000000000..64790ac65 --- /dev/null +++ b/plugins/process-killer/scripts/build-process-killer.mjs @@ -0,0 +1,45 @@ +// 把 src-ztools 整理成可安装、可分发的插件目录 +// +// ZTools 插件仓库对静态插件的打包规则是:清单所在目录 = 安装包内容。 +// 同时 src-ztools 这个目录会被发布 CLI 整份复制进插件仓库,而它复制时会跳过 +// 名为 dist 的目录。于是约定: +// src-ztools/plugin.json ← 发布清单(main/preload/logo 指向 runtime/…) +// src-ztools/runtime/ ← 清单 + 图标 + 运行时代码(安装包内容) +// 本地 build 只是把它整理成 dist/,用来打 zip、装进 ZTools 开发者工具试跑。 +import { cp, rm, mkdir, readFile, stat } from 'node:fs/promises' +import { execFileSync } from 'node:child_process' +import path from 'node:path' + +const root = path.resolve(import.meta.dirname, '..') +const src = path.join(root, 'src-ztools') +// 运行时目录:清单与图标在里面,src-ztools/plugin.json 只是发布用的清单 +const pkg = path.join(src, 'runtime') +const out = path.join(root, 'dist') +const manifest = JSON.parse(await readFile(path.join(pkg, 'plugin.json'), 'utf8')) + +await rm(out, { recursive: true, force: true }) +await mkdir(out, { recursive: true }) +await cp(pkg, out, { recursive: true, filter: p => !p.endsWith('.DS_Store') }) + +// 清单声明的文件必须真的存在,否则装上是白屏 +for (const file of [manifest.main, manifest.preload, manifest.logo]) { + if (!file) continue + await stat(path.join(out, file)).catch(() => { + throw new Error('plugin.json 声明的文件不存在: ' + file) + }) +} + +console.log('build ok ->', path.relative(root, out)) + +if (process.argv.includes('--zip')) { + const zip = path.join(root, 'releases', `process-killer-${manifest.version}.zip`) + await mkdir(path.dirname(zip), { recursive: true }) + await rm(zip, { force: true }) + // Windows 自带 tar(bsdtar)也能打 zip,Mac 上用 ditto 保留架构信息 + if (process.platform === 'win32') { + execFileSync('tar.exe', ['-a', '-c', '-f', zip, '-C', out, '.']) + } else { + execFileSync('/usr/bin/ditto', ['-c', '-k', '--norsrc', out, zip]) + } + console.log('zip ->', path.relative(root, zip)) +} diff --git a/plugins/process-killer/src-ztools/build-plugin.sh b/plugins/process-killer/src-ztools/build-plugin.sh new file mode 100755 index 000000000..443b40c1e --- /dev/null +++ b/plugins/process-killer/src-ztools/build-plugin.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# ZTools 插件仓库的官方构建钩子:打包目录由 src-ztools/pkg 决定 +# (scripts/build-plugins.js 只认插件根目录下的 plugin.json, +# 或 main 字段所在目录里确实有 plugin.json,因此运行时代码放在 pkg/) +set -euo pipefail +cd "$(dirname "$0")/.." +node scripts/build-process-killer.mjs diff --git a/plugins/process-killer/src-ztools/plugin.json b/plugins/process-killer/src-ztools/plugin.json new file mode 100644 index 000000000..0c5154082 --- /dev/null +++ b/plugins/process-killer/src-ztools/plugin.json @@ -0,0 +1,31 @@ +{ + "$schema": "node_modules/@ztools-center/ztools-api-types/resource/ztools.schema.json", + "name": "process-killer", + "title": "进程管家", + "description": "搜索进程名或端口,查看 CPU、内存与端口占用,关闭、强制结束或重启进程", + "version": "1.0.0", + "author": "xiewz", + "homepage": "https://github.com/XiewzHub/ztools-process-killer", + "platform": ["win32", "darwin"], + "main": "runtime/index.html", + "preload": "runtime/preload/services.js", + "logo": "runtime/logo.png", + "pluginSetting": { + "height": 560 + }, + "features": [ + { + "code": "kill", + "explain": "搜索进程名或端口,关闭或管理进程", + "icon": "runtime/logo.png", + "cmds": [ + "kill", + "关闭进程", + "进程管理", + "进程管家", + "netstat", + "端口占用" + ] + } + ] +} diff --git a/plugins/process-killer/src-ztools/runtime/index.html b/plugins/process-killer/src-ztools/runtime/index.html new file mode 100644 index 000000000..26b57a43d --- /dev/null +++ b/plugins/process-killer/src-ztools/runtime/index.html @@ -0,0 +1,64 @@ + + + + + + 关闭进程 + + + +
+
+ +
+ + + + +
+ +
+ + + +
+ 进程 + PID + 端口 + CPU + 内存 +
+ +
+ + + + +
+ + + + + + + + + diff --git a/plugins/process-killer/src-ztools/runtime/logo.png b/plugins/process-killer/src-ztools/runtime/logo.png new file mode 100644 index 000000000..a61d8b060 Binary files /dev/null and b/plugins/process-killer/src-ztools/runtime/logo.png differ diff --git a/plugins/process-killer/src-ztools/runtime/main.js b/plugins/process-killer/src-ztools/runtime/main.js new file mode 100644 index 000000000..870a2a091 --- /dev/null +++ b/plugins/process-killer/src-ztools/runtime/main.js @@ -0,0 +1,411 @@ +const svc = window.services || {} + +const state = { + all: [], + rows: [], + keyword: '', + sort: 'mem', + selected: 0, + loading: false, + portWarning: null, + autoRefresh: true, + selectedPid: null +} + +const $ = sel => document.querySelector(sel) +const listEl = $('#list') +const searchEl = $('#search') +const bannerEl = $('#banner') +const emptyEl = $('#empty') +const summaryEl = $('#summary') +const menuEl = $('#menu') +const toastEl = $('#toast') + +const RENDER_LIMIT = 400 + +function fmtMem(rss) { + const mb = rss / 1024 + return mb >= 1024 ? (mb / 1024).toFixed(1) + ' GB' : Math.round(mb) + ' MB' +} + +function sortRows(rows, by) { + const copy = rows.slice() + if (by === 'name') copy.sort((a, b) => a.name.localeCompare(b.name)) + else if (by === 'cpu') copy.sort((a, b) => b.cpu - a.cpu) + else if (by === 'ports') copy.sort((a, b) => b.portCount - a.portCount || b.mem - a.mem) + else copy.sort((a, b) => b.mem - a.mem) + return copy +} + +function matches(p, keyword) { + if (!keyword) return true + const kw = keyword.toLowerCase() + if (/^\d+$/.test(kw)) { + if (String(p.pid).includes(kw)) return true + if (p.listen.some(x => String(x).includes(kw))) return true + if (p.conn.some(x => String(x).includes(kw))) return true + } + return p.name.toLowerCase().includes(kw) || p.path.toLowerCase().includes(kw) +} + +function applyFilter() { + const filtered = state.all.filter(p => matches(p, state.keyword)) + state.rows = sortRows(filtered, state.sort) + if (state.selectedPid != null) { + const idx = state.rows.findIndex(p => p.pid === state.selectedPid) + if (idx >= 0) state.selected = idx + } + if (state.selected >= state.rows.length) state.selected = Math.max(0, state.rows.length - 1) + render() +} + +async function loadIcons() { + const seen = new Set() + for (const row of state.rows.slice(0, RENDER_LIMIT)) { + if (!row.app || seen.has(row.app)) continue + seen.add(row.app) + svc.icon(row.app).then(icon => { + if (!icon) return + document.querySelectorAll('[data-app="' + CSS.escape(row.app) + '"]').forEach(img => { + img.src = icon + img.classList.remove('placeholder') + }) + }) + } +} + +function rowHtml(p, index) { + const ports = p.listen.length ? p.listen.join(', ') : (p.conn.length ? p.conn.length + ' 连接' : '') + return '
' + + '' + + '' + + '' + escapeHtml(p.name) + '' + + '' + escapeHtml(p.path) + '' + + '' + + '' + p.pid + '' + + '' + escapeHtml(ports) + '' + + '' + (p.cpu ? p.cpu.toFixed(1) + '%' : '-') + '' + + '' + fmtMem(p.rss) + '' + + '
' +} + +function escapeHtml(s) { + return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])) +} + +function render() { + const shown = state.rows.slice(0, RENDER_LIMIT) + listEl.innerHTML = shown.map(rowHtml).join('') + emptyEl.hidden = shown.length > 0 + summaryEl.textContent = state.loading + ? '正在读取进程…' + : state.rows.length + ' 个进程' + (state.rows.length > RENDER_LIMIT ? '(显示前 ' + RENDER_LIMIT + ' 个)' : '') + bannerEl.hidden = !state.portWarning + if (state.portWarning) bannerEl.textContent = state.portWarning + loadIcons() + const sel = listEl.querySelector('.row.selected') + if (sel) sel.scrollIntoView({ block: 'nearest' }) +} + +function select(index) { + if (!state.rows.length) return + state.selected = Math.max(0, Math.min(index, state.rows.length - 1)) + state.selectedPid = state.rows[state.selected] ? state.rows[state.selected].pid : null + render() +} + +async function refresh() { + if (state.loading) return + state.loading = true + summaryEl.textContent = '正在读取进程…' + try { + const data = await svc.snapshot() + state.all = data.processes || [] + state.portWarning = data.portWarning || (data.error ? '读取失败:' + data.error : null) + } catch (e) { + // loading 不复位的话,之后每次刷新都会被上面的判断挡掉 + state.portWarning = '读取失败:' + (e && e.message ? e.message : e) + } finally { + state.loading = false + } + applyFilter() +} + +let toastTimer = null +function toast(msg) { + toastEl.textContent = msg + toastEl.hidden = false + clearTimeout(toastTimer) + toastTimer = setTimeout(() => { toastEl.hidden = true }, 2200) +} + +const REASON = { + permission: '权限不足,无法关闭该进程', + gone: '进程已退出', + self: '不能关闭插件自身', + still_alive: '进程未响应关闭请求,可再试强制结束', + invalid_pid: '无效的进程号', + failed: '操作失败', + not_an_app: '该进程不是 .app / .exe,不支持重启', + spawn_failed: '启动失败' +} + +// 杀进程前必须人工确认,避免回车误杀 +function confirmKill(proc, force) { + return new Promise(resolve => { + const box = $('#confirm') + $('#confirm-title').textContent = force ? '确认强制结束进程' : '确认关闭进程' + // 两种机制的说明都写上:Windows 上是 WM_CLOSE / TerminateProcess + $('#confirm-body').textContent = proc.name + ' · PID ' + proc.pid + '\n' + (proc.path || '(读取不到完整路径)') + + (force ? '\n\n强制结束会立即终止进程,不会给进程保存的机会。' : '\n\n只发送关闭请求,进程可以拒绝;3 秒未退出可再尝试强制结束。') + $('#confirm-ok').textContent = force ? '确认强制结束' : '确认关闭' + box.hidden = false + + const done = ok => { + box.hidden = true + $('#confirm-ok').onclick = null + $('#confirm-cancel').onclick = null + box.onclick = null + document.removeEventListener('keydown', onKey, true) + resolve(ok) + } + const onKey = e => { + if (box.hidden) return + if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); done(true) } + else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); done(false) } + } + $('#confirm-ok').onclick = () => done(true) + $('#confirm-cancel').onclick = () => done(false) + box.onclick = e => { if (e.target === box) done(false) } + // 捕获阶段拦截,避免回车穿透到列表的关闭逻辑 + document.addEventListener('keydown', onKey, true) + $('#confirm-cancel').focus() + }) +} + +async function doKill(proc, force) { + if (!(await confirmKill(proc, force))) return + const rowEl = listEl.querySelector('.row[data-pid="' + proc.pid + '"]') + if (rowEl) rowEl.classList.add('removing') + const result = force ? await svc.forceKill(proc.pid) : await svc.kill(proc.pid) + if (result && result.ok) { + // WM_CLOSE 是请对方自己退,对方可能选择不退,提示里说清楚 + const how = result.signal === 'WM_CLOSE' ? '已请求关闭' : '已关闭' + toast(how + ' ' + proc.name + '(' + (result.signal || 'SIGKILL') + ')') + await refresh() + } else { + if (rowEl) rowEl.classList.remove('removing') + toast(REASON[result && result.reason] || '关闭失败') + } +} + +async function doRestart(proc) { + const box = $('#confirm') + $('#confirm-title').textContent = '确认重启进程' + $('#confirm-body').textContent = proc.name + ' · PID ' + proc.pid + '\n' + (proc.path || '(读取不到完整路径)') + '\n\n将先关闭再重新启动。' + $('#confirm-ok').textContent = '确认重启' + if (!(await new Promise(resolve => { + box.hidden = false + const done = ok => { + box.hidden = true + $('#confirm-ok').onclick = null + $('#confirm-cancel').onclick = null + box.onclick = null + document.removeEventListener('keydown', onKey, true) + resolve(ok) + } + const onKey = e => { + if (box.hidden) return + if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); done(true) } + else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); done(false) } + } + $('#confirm-ok').onclick = () => done(true) + $('#confirm-cancel').onclick = () => done(false) + box.onclick = e => { if (e.target === box) done(false) } + document.addEventListener('keydown', onKey, true) + $('#confirm-cancel').focus() + }))) return + const stopped = await svc.kill(proc.pid) + if (stopped && stopped.ok) { + const result = await svc.restart(proc.pid, { app: proc.app }) + toast(result && result.ok ? '已重启 ' + proc.name : '已关闭,但重启失败:' + (REASON[result && result.reason] || '')) + } else if (stopped && stopped.reason === 'gone') { + const result = await svc.restart(proc.pid, { app: proc.app }) + toast(result && result.ok ? '已重启 ' + proc.name : '重启失败:' + (REASON[result && result.reason] || '')) + } else { + toast(REASON[stopped && stopped.reason] || '关闭失败') + } + await refresh() +} + +async function showDetail(proc) { + $('#dialog-title').textContent = proc.name + ' · PID ' + proc.pid + const detail = await svc.detail(proc.pid) + const lines = [ + '路径: ' + proc.path, + '启动命令: ' + (detail.command || '(无)'), + '用户: ' + proc.user, + '父进程: ' + proc.ppid, + '内存: ' + fmtMem(proc.rss) + '(' + proc.mem.toFixed(1) + '%)', + // Windows 的 CPU 是采样差值,别标“累计值” + 'CPU: ' + (proc.cpu ? proc.cpu.toFixed(1) + '%' + (svc.platform === 'win32' ? '' : '(累计值)') : '-'), + '监听端口: ' + (proc.listen.join(', ') || '无'), + '已建立连接端口: ' + (proc.conn.join(', ') || '无'), + '应用包: ' + (proc.app || (svc.platform === 'win32' ? '无(按启动命令重启)' : '非 .app')) + ] + $('#dialog-body').textContent = lines.join('\n') + $('#dialog').hidden = false +} + +function hideDialog() { $('#dialog').hidden = true } + +function copyPath(proc) { + const ok = svc.copy(proc.path) + toast(ok ? '已复制路径' : '复制失败') +} + +function reveal(proc) { + svc.reveal(proc.app || proc.path) +} + +function openMenu(x, y, proc) { + menuEl.innerHTML = [ + '', + '', + '', + '
', + '', + '', + '' + ].join('') + menuEl.hidden = false + const rect = menuEl.getBoundingClientRect() + menuEl.style.left = Math.min(x, window.innerWidth - rect.width - 8) + 'px' + menuEl.style.top = Math.min(y, window.innerHeight - rect.height - 8) + 'px' + menuEl._proc = proc +} + +function closeMenu() { menuEl.hidden = true } + +function selectedProc() { return state.rows[state.selected] } + +function currentProcFromMenu() { return menuEl._proc } + +document.addEventListener('click', e => { + if (!menuEl.hidden && !menuEl.contains(e.target)) closeMenu() +}) + +menuEl.addEventListener('click', async e => { + const btn = e.target.closest('button[data-act]') + if (!btn) return + const proc = currentProcFromMenu() + if (!proc) return + closeMenu() + const act = btn.dataset.act + if (act === 'kill') await doKill(proc, false) + else if (act === 'force') await doKill(proc, true) + else if (act === 'restart') await doRestart(proc) + else if (act === 'detail') await showDetail(proc) + else if (act === 'copy') copyPath(proc) + else if (act === 'reveal') reveal(proc) +}) + +listEl.addEventListener('click', e => { + const row = e.target.closest('.row') + if (!row) return + state.selected = Number(row.dataset.index) + state.selectedPid = state.rows[state.selected] ? state.rows[state.selected].pid : null + render() +}) + +listEl.addEventListener('contextmenu', e => { + const row = e.target.closest('.row') + if (!row) return + e.preventDefault() + const index = Number(row.dataset.index) + state.selected = index + state.selectedPid = state.rows[index] ? state.rows[index].pid : null + render() + openMenu(e.clientX, e.clientY, state.rows[index]) +}) + +listEl.addEventListener('dblclick', e => { + const row = e.target.closest('.row') + if (!row) return + showDetail(state.rows[Number(row.dataset.index)]) +}) + +searchEl.addEventListener('input', () => { + state.keyword = searchEl.value.trim() + state.selected = 0 + state.selectedPid = null + applyFilter() +}) + +document.querySelectorAll('#sorts button').forEach(btn => { + btn.addEventListener('click', () => { + document.querySelectorAll('#sorts button').forEach(b => b.classList.remove('active')) + btn.classList.add('active') + state.sort = btn.dataset.sort + state.rows = sortRows(state.rows, state.sort) + state.selected = 0 + render() + }) +}) + +// 自动刷新:搜索中或选择中不动列表,避免打断操作 +const AUTO_MS = 3000 +let autoTimer = null + +function applyAutoRefresh(on) { + state.autoRefresh = on + const btn = $('#refresh') + btn.classList.toggle('auto', on) + btn.title = on ? '自动刷新中,点击改为手动(Ctrl/⌘+R 随时刷新)' : '手动刷新,点击开启自动刷新(Ctrl/⌘+R 随时刷新)' + clearInterval(autoTimer) + autoTimer = on ? setInterval(refresh, AUTO_MS) : null +} + +$('#refresh').addEventListener('click', () => applyAutoRefresh(!state.autoRefresh)) +$('#dialog-close').addEventListener('click', hideDialog) +$('#dialog').addEventListener('click', e => { if (e.target.id === 'dialog') hideDialog() }) + +document.addEventListener('keydown', async e => { + if (!$('#confirm').hidden) return + if (!$('#dialog').hidden) { + if (e.key === 'Escape') { e.preventDefault(); hideDialog() } + return + } + if (e.key === 'ArrowDown') { e.preventDefault(); select(state.selected + 1) } + else if (e.key === 'ArrowUp') { e.preventDefault(); select(state.selected - 1) } + else if (e.key === 'Enter') { + const proc = selectedProc() + if (!proc) return + e.preventDefault() + if (e.metaKey || e.ctrlKey) await doRestart(proc) + else if (e.shiftKey) await showDetail(proc) + else await doKill(proc, false) + } else if (e.key === 'Escape') { + closeMenu() + } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'r') { + e.preventDefault(); refresh() + } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'c' && selectedProc()) { + const active = document.activeElement + if (active === searchEl) return + copyPath(selectedProc()) + } +}) + +const ztools = window.ztools || window.utools +if (ztools && typeof ztools.onPluginEnter === 'function') { + ztools.onPluginEnter(() => { + searchEl.focus() + refresh() + }) +} + +// Windows 键位:Ctrl+Enter 重启、Ctrl+R 刷新、Ctrl+C 复制;提示栏跟着换 +if (svc.platform === 'win32') $('.hint').textContent = '↑↓ 选择 · ⏎ 关闭 · Ctrl+⏎ 重启 · Shift+⏎ 详情 · Ctrl+C 复制路径' + +applyAutoRefresh(state.autoRefresh) +refresh() diff --git a/plugins/process-killer/src-ztools/runtime/plugin.json b/plugins/process-killer/src-ztools/runtime/plugin.json new file mode 100644 index 000000000..53cafd73b --- /dev/null +++ b/plugins/process-killer/src-ztools/runtime/plugin.json @@ -0,0 +1,31 @@ +{ + "$schema": "node_modules/@ztools-center/ztools-api-types/resource/ztools.schema.json", + "name": "process-killer", + "title": "进程管家", + "description": "搜索进程名或端口,查看 CPU、内存与端口占用,关闭、强制结束或重启进程", + "version": "1.0.0", + "author": "xiewz", + "homepage": "https://github.com/XiewzHub/ztools-process-killer", + "platform": ["win32", "darwin"], + "main": "index.html", + "preload": "preload/services.js", + "logo": "logo.png", + "pluginSetting": { + "height": 560 + }, + "features": [ + { + "code": "kill", + "explain": "搜索进程名或端口,关闭或管理进程", + "icon": "logo.png", + "cmds": [ + "kill", + "关闭进程", + "进程管理", + "进程管家", + "netstat", + "端口占用" + ] + } + ] +} diff --git a/plugins/process-killer/src-ztools/runtime/preload/actions.js b/plugins/process-killer/src-ztools/runtime/preload/actions.js new file mode 100644 index 000000000..d60a385b9 --- /dev/null +++ b/plugins/process-killer/src-ztools/runtime/preload/actions.js @@ -0,0 +1,156 @@ +const { execFile, spawn } = require('node:child_process') +const path = require('node:path') +const fs = require('node:fs') + +const SIGTERM_GRACE_MS = 3000 +const WIN = process.platform === 'win32' +const TASKKILL = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe') + +function sleep(ms) { return new Promise(r => setTimeout(r, ms)) } + +function isAlive(pid) { + try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } +} + +async function waitGone(pid, timeout) { + const deadline = Date.now() + timeout + while (Date.now() < deadline) { + if (!isAlive(pid)) return true + await sleep(100) + } + return !isAlive(pid) +} + +// Windows 没有信号:taskkill 不带 /F 是发 WM_CLOSE 请窗口自己退出,/F 是 TerminateProcess。 +// 不加 /T:拒绝访问的子进程会让整个调用报错 255。退出码:1 没有可关闭的窗口(进程还在), +// 128 是拒绝访问、进程不存在或 -C 没匹配到,看进程还在不在区分 +function taskkill(pid, force) { + return new Promise(resolve => { + const args = ['/PID', String(pid)] + if (force) args.push('/F') + execFile(TASKKILL, args, { encoding: 'utf8', windowsHide: true }, async err => { + if (!err) return resolve(null) + await sleep(150) + if (!isAlive(pid)) return resolve('gone') + resolve(err.code === 1 || err.code === 128 ? 'permission' : 'failed') + }) + }) +} + +// 返回 { ok, pid, signal?, reason? };reason 区分无权限 / 已退出 / 仍需强杀 +async function kill(pid, options = {}) { + const target = Number(pid) + if (!Number.isInteger(target) || target <= 0) return { ok: false, pid: target, reason: 'invalid_pid' } + if (target === process.pid) return { ok: false, pid: target, reason: 'self' } + if (!isAlive(target)) return { ok: false, pid: target, reason: 'gone' } + + if (WIN) { + const why = await taskkill(target, Boolean(options.force)) + if (why) return { ok: false, pid: target, reason: why } + const signal = options.force ? 'TerminateProcess' : 'WM_CLOSE' + if (options.force || await waitGone(target, SIGTERM_GRACE_MS)) return { ok: true, pid: target, signal } + return { ok: false, pid: target, reason: 'still_alive', signal } + } + + try { + process.kill(target, 'SIGTERM') + } catch (e) { + return { ok: false, pid: target, reason: e.code === 'EPERM' ? 'permission' : 'failed', error: e.message } + } + + if (options.force) { + process.kill(target, 'SIGKILL') + return { ok: true, pid: target, signal: 'SIGKILL' } + } + + const gone = await waitGone(target, SIGTERM_GRACE_MS) + if (gone) return { ok: true, pid: target, signal: 'SIGTERM' } + return { ok: false, pid: target, reason: 'still_alive', signal: 'SIGTERM' } +} + +async function forceKill(pid) { + if (WIN) return kill(pid, { force: true }) + try { + process.kill(Number(pid), 'SIGKILL') + return { ok: true, pid: Number(pid), signal: 'SIGKILL' } + } catch (e) { + return { ok: false, pid: Number(pid), reason: e.code === 'EPERM' ? 'permission' : 'failed', error: e.message } + } +} + +// Windows 上命令行里第一个带引号的路径(路径含空格时 Windows 会加引号)就是程序本体 +function exeFromCommandLine(cmd) { + const m = /^"([^"]+\.exe)"/i.exec(cmd || '') + return m ? m[1] : null +} + +function commandLine(pid) { + const exe = WIN ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') : '/bin/ps' + const args = WIN + ? ['-NoProfile', '-NonInteractive', '-Command', '(Get-CimInstance Win32_Process -Filter "ProcessId=' + Number(pid) + '").CommandLine'] + : ['-ww', '-o', 'command=', '-p', String(pid)] + return new Promise(resolve => { + execFile(exe, args, { encoding: WIN ? 'latin1' : 'utf8', maxBuffer: 4 * 1024 * 1024 }, + (err, stdout) => resolve(err ? '' : Buffer.from(String(stdout || ''), WIN ? 'latin1' : 'utf8').toString('utf8').trim())) + }) +} + +// 只重启 .app / .exe:命令行拆分启动会丢环境变量和参数,宁可明确失败 +async function restart(pid, info = {}) { + const cmd = await commandLine(pid) + const app = info.app || (/(\/.*?\.app)\//.exec(cmd) || [])[1] || (WIN ? exeFromCommandLine(cmd) : null) + if (!app || !fs.existsSync(app)) return { ok: false, pid: Number(pid), reason: 'not_an_app' } + try { + // Windows 上不能要求提权启动(UAC 会弹框),拿不到同一个权限就报错 + const child = WIN + ? spawn(app, [], { detached: true, stdio: 'ignore', cwd: path.dirname(app) }) + : spawn('/usr/bin/open', ['-n', app], { detached: true, stdio: 'ignore' }) + child.unref() + return { ok: true, pid: Number(pid), launched: app } + } catch (e) { + return { ok: false, pid: Number(pid), reason: 'spawn_failed', error: e.message } + } +} + +// 从 .icns 中切出最大的 PNG 片段转 base64,供列表显示应用图标 +function icnsToBase64(icnsPath) { + const buf = fs.readFileSync(icnsPath) + const head = Buffer.from([0x89, 0x50, 0x4e, 0x47]) + const tail = Buffer.from([0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82]) + let best = null + let i = buf.indexOf(head) + while (i !== -1) { + const end = buf.indexOf(tail, i) + if (end === -1) break + const chunk = buf.subarray(i, end + tail.length) + if (!best || chunk.length > best.length) best = chunk + i = buf.indexOf(head, end + tail.length) + } + return best ? 'data:image/png;base64,' + best.toString('base64') : null +} + +function iconOf(bundlePath) { + try { + if (!bundlePath) return null + const infoPlist = path.join(bundlePath, 'Contents', 'Info.plist') + if (!fs.existsSync(infoPlist)) return null + const raw = fs.readFileSync(infoPlist, 'utf8') + const m = /CFBundleIconFile<\/key>\s*([^<]+)<\/string>/.exec(raw) + if (!m) return null + let name = m[1].trim() + if (!name.endsWith('.icns')) name += '.icns' + const file = path.join(bundlePath, 'Contents', 'Resources', name) + if (!fs.existsSync(file)) return null + return icnsToBase64(file) + } catch (e) { + return null + } +} + +// Windows 上命令行里第一个带引号的 .exe(路径含空格时 Windows 会给它加引号)就是程序本体 +function exeFromCommandLine(cmd) { + const m = /^"([^"]+\.exe)"/i.exec(cmd || '') + return m ? m[1] : null +} + +module.exports = { kill, forceKill, commandLine, restart, iconOf, isAlive, waitGone, exeFromCommandLine } diff --git a/plugins/process-killer/src-ztools/runtime/preload/collector-win.js b/plugins/process-killer/src-ztools/runtime/preload/collector-win.js new file mode 100644 index 000000000..44bd04eb9 --- /dev/null +++ b/plugins/process-killer/src-ztools/runtime/preload/collector-win.js @@ -0,0 +1,140 @@ +// Windows 采集:进程走 PowerShell/CIM(命令行和中文进程名只有这里有),端口走 netstat -ano +const { execFile, execFileSync } = require('node:child_process') +const path = require('node:path') + +// 全量取回来一次转成 JSON:每条一个对象的管道会把跨机关的时候放大几十倍。 +// 内存用 WorkingSetSize(CIM 的副本,略有延迟),顺序另跑一次 Get-Process +const PS_SCRIPT = [ + 'Get-CimInstance Win32_Process -Filter "ProcessId>0" |', + ' ForEach-Object { [pscustomobject]@{ pid = $_.ProcessId; ppid = $_.ParentProcessId; name = $_.Name; cmd = $_.CommandLine;', + ' rss = [long]($_.WorkingSetSize / 1KB); cpu = [long]$_.KernelModeTime + [long]$_.UserModeTime; start = $_.CreationDate } } |', + ' ConvertTo-Json -Compress' +].join('\n') + +// Get-Process 的输出顺序就是任务管理器默认的顺序(系统进程在前,之后按名称拼音排)。 +// 中文名进程在这里会少 .exe 后缀,名称一律以 CIM 为准 +const ORDER_SCRIPT = 'Get-Process | Out-String -Width 64' + +function parseCim(stdout) { + const text = String(stdout).trim() + if (!text) return [] + let data + try { data = JSON.parse(text) } catch (e) { return [] } + return [].concat(data).filter(p => p && p.pid).map(p => { + const prev = cpuState.get(p.pid) + const now = Date.now() + const cum = Number(p.cpu) || 0 + const result = { + pid: p.pid, ppid: p.ppid || 0, user: '', cpu: cpuPercent(cum, now, prev), + name: String(p.name || ''), path: String(p.cmd || ''), rss: Number(p.rss) || 0 + } + cpuState.set(p.pid, { at: now, cum, start: startOf(p.start) }) + return result + }) +} + +// CIM 的 CreationDate 序列化后是 /Date(毫秒)/,也接受纯 ISO 字符串 +function startOf(v) { + if (!v) return null + if (typeof v === 'string') { + const m = /^\/Date\((\d+)\)\/$/.exec(v) + return m ? new Date(Number(m[1])).toISOString() : v + } + return v.value || null +} + +// 输出刚好 64K 时 PowerShell 被管道堵死,cmd.exe 只能杀掉它——截断要么报错要么给乱码, +// 无论哪种都当作没拿到顺序 +const MAX_CHARS = 60000 + +// 输出全是 ASCII JSON / ASCII 名称,字节当 latin1 读再按 utf8 解,才能拿到中文 +function exec(file, args) { + return new Promise(resolve => { + execFile(file, args, { encoding: 'latin1', maxBuffer: 32 * 1024 * 1024, timeout: 20000, windowsHide: true }, + (err, stdout) => resolve({ ok: !err, stdout: Buffer.from(stdout || '', 'latin1').toString('utf8'), error: err ? err.message : null })) + }) +} + +function psExe() { + return path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') +} + +const psArgs = script => [psExe(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script]] + +async function snapshot() { + const root = process.env.SystemRoot || 'C:\\Windows' + const [cim, order, netstat] = await Promise.all([ + exec(...psArgs(PS_SCRIPT)), + exec(...psArgs(ORDER_SCRIPT)), + exec(path.join(root, 'System32', 'NETSTAT.EXE'), ['-ano']) + ]) + // Get-Process 的表格列:Handles、NPM(K)、PM(K)、WS(K)、CPU(s)、Id、SI、ProcessName, + // Id 后面那格是 SI(纯数字)或名称,CPU(s) 带小数点。列宽随区域和终端变,不按列号取 + const table = order.ok && order.stdout.length < MAX_CHARS ? order.stdout.split(/\r?\n/).filter(line => line.trim()) : [] + const pids = table.length > 3 && /^\s*-+\s/.test(table[2]) + ? table.slice(3).map(line => { + const cells = line.trim().split(/\s+/) + // FindProcessId 是第 6 列;分隔行之后的每一行都一样,按位置取最稳,但要先确认那一格真的是 PID + const pid = Number(cells[5]) + return cells.length >= 7 && Number.isInteger(pid) && pid > 0 ? pid : null + }).filter(Boolean) + : [] + const list = parseCim(cim.stdout) + // 编码对不上时 CIM 那部分可能整段没回来,以 Get-Process 的进程号为底 + const byPid = new Map(list.map(p => [p.pid, p])) + const seen = new Set(pids) + const base = pids.filter(pid => pid > 0).map(pid => byPid.get(pid) || enrich(pid)) + for (const p of list) if (!seen.has(p.pid) && p.pid > 0) base.push(p) + if (!base.length) throw new Error('读取进程列表失败: ' + (cim.error || order.error || 'PowerShell 无输出')) + return { processes: base, ports: netstat.ok ? parseNetstat(netstat.stdout) : null } +} + +// 只补一个进程;拿不到时用 "?" 占位,不冒充原名 +function enrich(pid) { + const placeholder = { pid, ppid: 0, user: '', cpu: 0, name: String(pid) + '?', path: '', rss: 0 } + try { + const out = execFileSync(psExe(), ['-NoProfile', '-NonInteractive', '-Command', + 'Get-Process -Id ' + pid + ' | ForEach-Object { "" + $_.ProcessName + ";" + [int]$_.WorkingSet64 }'], { encoding: 'latin1' }).toString('latin1') + const [name, ws] = Buffer.from(out, 'latin1').toString('utf8').trim().split(';') + return name ? { ...placeholder, name, rss: Math.round((Number(ws) || 0) / 1024) } : placeholder + } catch (e) { + return placeholder + } +} +// netstat -ano 每行:协议 本地地址 外部地址 状态 PID;UDP 没有状态那一列 +const NETSTAT_LINE = /^\s*(TCP|UDP)\s+(\S+)\s+(\S+)\s+([A-Z_]+)?\s*(\d+)\s*$/ + +function parseNetstat(text) { + const map = new Map() + for (const line of String(text).split(/\r?\n/)) { + const m = NETSTAT_LINE.exec(line) + if (!m) continue + const pid = Number(m[5]) + const pm = /:(\d+)$/.exec(m[2]) + if (!pid || !pm) continue + const port = Number(pm[1]) + if (!map.has(pid)) map.set(pid, { listen: new Set(), conn: new Set() }) + const entry = map.get(pid) + const state = m[4] || '' + // UDP 按端口统计,按端口关掉占用它的进程是常见需求 + if (m[1] === 'UDP' || state === 'LISTENING') entry.listen.add(port) + else if (state === 'ESTABLISHED' || state === 'SYN_SENT') entry.conn.add(port) + } + const out = new Map() + for (const [key, v] of map) out.set(key, { listen: [...v.listen].sort((a, b) => a - b), conn: [...v.conn].sort((a, b) => a - b) }) + return out +} + +// CPU 要两次采样才准,而自动刷新每 3 秒跑一次,所以各记各的累计值,用真实间隔算。 +// 累计值单位是 100ns;比例和上次的累计都按秒折算,免得大数相减丢精度 +const cpuState = new Map() +function cpuPercent(cum, now, prev) { + if (!prev || !prev.start || now <= prev.at) return 0 + const dt = (now - prev.at) / 1000 + // 进程刚起来时区间比它的生命周期长,按短的算 + const span = Math.min(dt, (now - Date.parse(prev.start)) / 1000) + const busy = (cum - prev.cum) / 10 ** 7 + return span > 0 ? Math.min(100, Math.max(0, busy / span * 100)) : 0 +} + +module.exports = { parseCim, parseNetstat, snapshot, psArgs, psExe, NETSTAT_LINE, PS_SCRIPT, ORDER_SCRIPT, MAX_CHARS, cpuState, cpuPercent } diff --git a/plugins/process-killer/src-ztools/runtime/preload/collector.js b/plugins/process-killer/src-ztools/runtime/preload/collector.js new file mode 100644 index 000000000..cbab9c989 --- /dev/null +++ b/plugins/process-killer/src-ztools/runtime/preload/collector.js @@ -0,0 +1,96 @@ +const { execFile } = require('node:child_process') + +const MAX_BUFFER = 32 * 1024 * 1024 +const TIMEOUT = 15000 + +function exec(file, args) { + return new Promise(resolve => { + execFile(file, args, { encoding: 'utf8', maxBuffer: MAX_BUFFER, timeout: TIMEOUT, windowsHide: true }, + (err, stdout) => resolve({ ok: !err, stdout: stdout || '', error: err ? err.message : null })) + }) +} + +const PS_ARGS = ['-axo', 'pid=,ppid=,user=,pcpu=,pmem=,rss=,comm='] +const PS_LINE = /^(\d+)\s+(\d+)\s+(\S+)\s+([\d.]+)\s+([\d.]+)\s+(\d+)\s+(.+)$/ + +function parsePs(stdout) { + const list = [] + for (const raw of String(stdout).split('\n')) { + if (!raw.trim()) continue + const m = PS_LINE.exec(raw.trim()) + if (!m) continue + const path = m[7].trim() + list.push({ + pid: Number(m[1]), + ppid: Number(m[2]), + user: m[3], + cpu: Number(m[4]), + mem: Number(m[5]), + rss: Number(m[6]), + path, + name: path.split('/').pop() || path + }) + } + return list +} + +// lsof -F pcn 输出是逐字段一行:p / c / n<地址> +// 地址形如 *:7000、127.0.0.1:6379、[::1]:8080、127.0.0.1:1234->10.0.0.1:5678 +function parseLsof(stdout) { + const map = new Map() + let pid = null + for (const line of String(stdout).split('\n')) { + if (!line) continue + const tag = line[0] + const value = line.slice(1) + if (tag === 'p') { pid = Number(value); continue } + if (tag !== 'n' || !pid) continue + const m = /:(\d+)(?:->(.+))?$/.exec(value) + if (!m) continue + if (!map.has(pid)) map.set(pid, { listen: new Set(), conn: new Set() }) + const entry = map.get(pid) + if (m[2]) entry.conn.add(Number(m[1])) + else entry.listen.add(Number(m[1])) + } + const out = new Map() + for (const [key, v] of map) out.set(key, { listen: [...v.listen].sort((a, b) => a - b), conn: [...v.conn].sort((a, b) => a - b) }) + return out +} + +function merge(processes, ports) { + return processes.map(p => { + const rec = ports.get(p.pid) + const listen = rec ? rec.listen : [] + const conn = rec ? rec.conn : [] + return { ...p, listen, conn, portCount: new Set([...listen, ...conn]).size, app: appBundleOf(p.path) } + }) +} + +function appBundleOf(path) { + const m = /^(.*?\.app)\//.exec(path || '') + return m ? m[1] : null +} + +// Windows:列表里已有 PPID、命令行、内存和 CPU,合并端口后补上内存占比 +function snapshotWindows() { + return require('./collector-win').snapshot().then(({ processes, ports }) => { + const memTotal = require('node:os').totalmem() / 1048576 + return { + processes: merge(processes, ports || new Map()).map(p => ({ ...p, mem: memTotal ? p.rss / memTotal * 100 : 0 })), + portWarning: ports ? null : '端口信息不可用:netstat 执行失败' + } + }) +} + +async function snapshot() { + if (process.platform === 'win32') return snapshotWindows() + const [ps, lsof] = await Promise.all([ + exec('/bin/ps', PS_ARGS), + exec('/usr/sbin/lsof', ['-nP', '-iTCP', '-F', 'pcn']) + ]) + if (!ps.ok) throw new Error('读取进程列表失败: ' + ps.error) + const processes = merge(parsePs(ps.stdout), lsof.ok ? parseLsof(lsof.stdout) : new Map()) + return { processes, portWarning: lsof.ok ? null : '端口信息受限:可能缺少显示其他用户进程的权限' } +} + +module.exports = { exec, parsePs, parseLsof, merge, appBundleOf, snapshot, snapshotWindows, PS_ARGS, PS_LINE } diff --git a/plugins/process-killer/src-ztools/runtime/preload/package.json b/plugins/process-killer/src-ztools/runtime/preload/package.json new file mode 100644 index 000000000..5bbefffba --- /dev/null +++ b/plugins/process-killer/src-ztools/runtime/preload/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/plugins/process-killer/src-ztools/runtime/preload/services.js b/plugins/process-killer/src-ztools/runtime/preload/services.js new file mode 100644 index 000000000..a37ea10a2 --- /dev/null +++ b/plugins/process-killer/src-ztools/runtime/preload/services.js @@ -0,0 +1,46 @@ +const collector = require('./collector') +const actions = require('./actions') + +const z = () => window.ztools || window.utools + +const iconCache = new Map() + +function iconFor(app) { + if (!app) return null + if (iconCache.has(app)) return iconCache.get(app) + const icon = actions.iconOf(app) + iconCache.set(app, icon) + return icon +} + +function safe(fn, fallback) { + return async (...args) => { + try { + return await fn(...args) + } catch (e) { + return typeof fallback === 'function' ? fallback(e) : fallback + } + } +} + +window.services = { + platform: process.platform, + + snapshot: safe(() => collector.snapshot(), e => ({ processes: [], portWarning: null, error: e.message })), + + detail: safe(async pid => ({ pid, command: await actions.commandLine(pid) }), { command: '' }), + + icon: safe(async app => iconFor(app), null), + + kill: safe(pid => actions.kill(pid), e => ({ ok: false, reason: 'failed', error: e.message })), + + forceKill: safe(pid => actions.forceKill(pid), e => ({ ok: false, reason: 'failed', error: e.message })), + + restart: safe((pid, info) => actions.restart(pid, info), e => ({ ok: false, reason: 'failed', error: e.message })), + + copy: text => { try { z().copyText(String(text)); return true } catch (e) { return false } }, + + reveal: fullPath => { try { z().shellShowItemInFolder(fullPath); return true } catch (e) { return false } }, + + notify: text => { try { z().showNotification(String(text)) } catch (e) { /* ignore */ } } +} diff --git a/plugins/process-killer/src-ztools/runtime/style.css b/plugins/process-killer/src-ztools/runtime/style.css new file mode 100644 index 000000000..15334b7d7 --- /dev/null +++ b/plugins/process-killer/src-ztools/runtime/style.css @@ -0,0 +1,252 @@ +:root { + --bg: #ffffff; + --fg: #24292f; + --muted: #6b7280; + --line: #eef0f3; + --hover: #f5f7fa; + --active: #eef4ff; + --accent: #2f6fed; + --danger: #d93025; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #1e1f22; + --fg: #e6e8eb; + --muted: #9aa0a6; + --line: #2c2f33; + --hover: #26282c; + --active: #2a3346; + --accent: #6ea8ff; + } +} + +* { box-sizing: border-box; } + +/* display 会覆盖 hidden,必须显式兜底 */ +[hidden] { display: none !important; } + +html, body { + margin: 0; + height: 100%; + background: var(--bg); + color: var(--fg); + font: 13px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", "Segoe UI", sans-serif; + overflow: hidden; +} + +.app { display: flex; flex-direction: column; height: 100%; } + +.toolbar { + display: flex; + gap: 8px; + align-items: center; + padding: 10px 12px 8px; +} + +.search { + flex: 1; + height: 34px; + padding: 0 12px; + border: 1px solid var(--line); + border-radius: 8px; + background: transparent; + color: inherit; + font: inherit; + font-size: 14px; + outline: none; +} +.search:focus { border-color: var(--accent); } + +.sorts { display: flex; gap: 2px; } + +.sorts button { + height: 30px; + padding: 0 10px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--muted); + font: inherit; + cursor: pointer; +} +.sorts button:hover { background: var(--hover); color: var(--fg); } +.sorts button.active { background: var(--active); color: var(--accent); font-weight: 600; } + +.icon-btn { + width: 30px; + height: 30px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--muted); + font-size: 15px; + cursor: pointer; +} +.icon-btn:hover { background: var(--hover); color: var(--fg); } +.icon-btn.auto { color: var(--accent); background: var(--active); } + +.banner { + margin: 0 12px 8px; + padding: 8px 10px; + border-radius: 8px; + background: #fff4e5; + color: #8a5a00; + font-size: 12px; +} +@media (prefers-color-scheme: dark) { .banner { background: #3a2f1c; color: #f0c97a; } } + +.table-head { + display: grid; + grid-template-columns: 1fr 76px 130px 56px 70px; + gap: 8px; + padding: 6px 12px; + border-bottom: 1px solid var(--line); + color: var(--muted); + font-size: 11px; + text-transform: uppercase; + letter-spacing: .04em; +} + +.list { flex: 1; overflow-y: auto; } + +.row { + display: grid; + grid-template-columns: 1fr 76px 130px 56px 70px; + gap: 8px; + align-items: center; + padding: 7px 12px; + border-bottom: 1px solid var(--line); + cursor: default; + user-select: none; +} +.row:hover { background: var(--hover); } +.row.selected { background: var(--active); } + +.col-name { display: flex; align-items: center; gap: 8px; min-width: 0; } +.name { font-weight: 500; white-space: nowrap; } +.path { color: var(--muted); font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.name-wrap { min-width: 0; display: flex; flex-direction: column; } + +/* 没有 src 时 Chrome 会画个破图图标;Windows 上多数进程没有图标,取到图标(有 src)才显示 */ +.icon { width: 18px; height: 18px; flex: none; border-radius: 4px; object-fit: contain; display: none; } +.icon[src] { display: block; } + +.col-pid, .col-cpu, .col-mem { color: var(--muted); font-variant-numeric: tabular-nums; } +.col-port { color: var(--muted); font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.col-port.has-port { color: var(--accent); font-weight: 500; } + +.empty { padding: 40px; text-align: center; color: var(--muted); } + +.status { + display: flex; + justify-content: space-between; + gap: 12px; + padding: 7px 12px; + border-top: 1px solid var(--line); + color: var(--muted); + font-size: 11px; +} +.hint { opacity: .8; } + +.menu { + position: fixed; + z-index: 20; + min-width: 190px; + padding: 5px; + border: 1px solid var(--line); + border-radius: 10px; + background: var(--bg); + box-shadow: 0 10px 30px rgba(0, 0, 0, .18); +} +.menu button { + display: block; + width: 100%; + padding: 7px 10px; + border: 0; + border-radius: 6px; + background: transparent; + color: inherit; + font: inherit; + text-align: left; + cursor: pointer; +} +.menu button:hover { background: var(--hover); } +.menu button.danger { color: var(--danger); } +.menu .sep { height: 1px; margin: 4px 2px; background: var(--line); } + +.dialog-backdrop { + position: fixed; + inset: 0; + z-index: 30; + display: flex; + align-items: center; + justify-content: center; + background: rgba(0, 0, 0, .35); +} +.dialog { + width: min(680px, 90%); + max-height: 70%; + padding: 16px; + border-radius: 12px; + background: var(--bg); + box-shadow: 0 20px 60px rgba(0, 0, 0, .3); + display: flex; + flex-direction: column; +} +.dialog h3 { margin: 0 0 10px; font-size: 14px; } +.dialog pre { + flex: 1; + margin: 0; + padding: 10px; + border-radius: 8px; + background: var(--hover); + overflow: auto; + font: 12px/1.6 SFMono-Regular, Menlo, monospace; + white-space: pre-wrap; + word-break: break-all; +} +.dialog-actions { display: flex; justify-content: flex-end; margin-top: 12px; } +.dialog-actions button { + padding: 6px 14px; + border: 1px solid var(--line); + border-radius: 7px; + background: transparent; + color: inherit; + font: inherit; + cursor: pointer; +} + +.confirm-dialog { width: min(420px, 86%); } +.confirm-text { + margin: 0; + padding: 10px 12px; + border-radius: 8px; + background: var(--hover); + font-size: 12px; + line-height: 1.7; + word-break: break-all; +} +.dialog-actions { gap: 8px; } +.danger-btn { + border-color: var(--danger) !important; + background: var(--danger) !important; + color: #fff !important; +} +.danger-btn:hover { opacity: .88; } + +.toast { + position: fixed; + left: 50%; + bottom: 44px; + z-index: 40; + transform: translateX(-50%); + max-width: 70%; + padding: 8px 14px; + border-radius: 8px; + background: rgba(24, 26, 30, .92); + color: #fff; + font-size: 12px; +} + +.row.removing { opacity: .45; } diff --git a/plugins/process-killer/test/auto-refresh.test.cjs b/plugins/process-killer/test/auto-refresh.test.cjs new file mode 100644 index 000000000..c3fadbd28 --- /dev/null +++ b/plugins/process-killer/test/auto-refresh.test.cjs @@ -0,0 +1,99 @@ +// 验证:自动刷新不被搜索/选中打断;刷新后选中按 PID 保持 +const path = require('path') +const http = require('http') +const fs = require('fs') +// Windows 上换成本机 Chrome,路径也可用 CHROME_PATH / PLAYWRIGHT_PATH 覆盖 +const { chromium } = require(process.env.PLAYWRIGHT_PATH || require.resolve('playwright')) + +const dist = path.join(__dirname, '..', 'dist') +const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.png': 'image/png' } + +const server = http.createServer((req, res) => { + const f = path.join(dist, decodeURIComponent(req.url.split('?')[0]).replace(/^\/+/, '') || 'index.html') + fs.readFile(f, (e, b) => { + if (e) { res.writeHead(404); return res.end() } + res.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }) + res.end(b) + }) +}) + +;(async () => { + await new Promise(r => server.listen(0, '127.0.0.1', r)) + const port = server.address().port + const chromePath = process.env.CHROME_PATH || (process.platform === 'win32' + ? 'C:/Program Files/Google/Chrome/Application/chrome.exe' + : '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome') + const browser = await chromium.launch({ executablePath: chromePath }) + const page = await browser.newPage({ viewport: { width: 900, height: 560 } }) + const errors = [] + page.on('pageerror', e => errors.push(e.message)) + + await page.addInitScript(() => { + let n = 0 + window.__calls = 0 + const mk = (pid, name, mem) => ({ pid, ppid: 1, user: 'me', cpu: 0, mem, rss: mem * 1024, path: '/bin/' + name, name, listen: [], conn: [], portCount: 0, app: null }) + window.services = { + snapshot: async () => { + n++ + window.__calls = n + // 第 2 次起 alpha 变成最大,触发排序变化 + return { processes: [mk(1, 'alpha', n >= 2 ? 90 : 1), mk(2, 'beta', 50), mk(3, 'gamma', 30)], portWarning: null } + }, + icon: async () => null, + detail: async () => ({ command: 'x' }), + kill: async () => ({ ok: true, signal: 'SIGTERM' }) + } + }) + + await page.goto('http://127.0.0.1:' + port + '/index.html') + await page.waitForSelector('.row') + + const pidList = () => page.$$eval('.row', els => els.map(e => e.dataset.pid)) + const selPid = () => page.$eval('.row.selected', el => el.dataset.pid).catch(() => null) + + const before = await pidList() + const callsStart = await page.evaluate(() => window.__calls) + + // 选中第 3 行 gamma + await page.keyboard.press('ArrowDown') + await page.keyboard.press('ArrowDown') + const selectedBefore = await selPid() + + await page.waitForTimeout(4000) + const after = await pidList() + const selectedAfter = await selPid() + const callsAfterWait = await page.evaluate(() => window.__calls) + + // 搜索状态下继续刷新 + await page.fill('#search', 'a') + await page.waitForTimeout(500) + const callsSearch1 = await page.evaluate(() => window.__calls) + await page.waitForTimeout(4000) + const callsSearch2 = await page.evaluate(() => window.__calls) + const searchStillShows = (await pidList()).length + + const result = { + before, + after, + callsStart, + callsAfterWait, + refreshedWhileSelected: callsAfterWait > callsStart, + reordered: JSON.stringify(before) !== JSON.stringify(after), + selectedBefore, + selectedAfter, + selectionKept: selectedBefore === selectedAfter, + callsSearch1, + callsSearch2, + refreshedWhileSearching: callsSearch2 > callsSearch1, + searchStillShows, + errors + } + console.log(JSON.stringify(result, null, 1)) + + const ok = result.refreshedWhileSelected && result.reordered && result.selectionKept + && result.refreshedWhileSearching && result.searchStillShows > 0 && errors.length === 0 + console.log(ok ? 'AUTO-REFRESH OK' : 'AUTO-REFRESH FAIL') + await browser.close() + server.close() + process.exit(ok ? 0 : 1) +})() diff --git a/plugins/process-killer/test/collector-win.test.cjs b/plugins/process-killer/test/collector-win.test.cjs new file mode 100644 index 000000000..1be2359b0 --- /dev/null +++ b/plugins/process-killer/test/collector-win.test.cjs @@ -0,0 +1,60 @@ +const test = require('node:test') +const assert = require('node:assert') +const win = require('../src-ztools/runtime/preload/collector-win') + +test('parseCim 单个和数组都能解,中文命令行原样保留', () => { + const one = win.parseCim('{"pid":4,"ppid":0,"name":"System","cmd":null,"rss":128,"cpu":0,"start":"2026-11-20T10:00:00.0000000+08:00"}') + assert.equal(one.length, 1) + assert.equal(one[0].path, '') + assert.equal(one[0].rss, 128) + const two = win.parseCim(JSON.stringify([ + { pid: 8, ppid: 4, name: '输入法测试.exe', cmd: '"C:\\a\\输入法测试.exe" -n 60', rss: 2048 }, + { pid: 9, ppid: 8, name: 'x.exe', cmd: 'x', rss: 0 } + ])) + assert.equal(two[0].name, '输入法测试.exe') + assert.ok(two[0].path.includes('输入法测试')) + assert.deepEqual(win.parseCim(''), []) + assert.deepEqual(win.parseCim('Get-CimInstance : 拒绝访问'), []) +}) + +test('cpuPercent 用两次采样的差值,首次为 0,新进程不被放大', () => { + const t0 = Date.now() + const start = new Date(t0 - 60000).toISOString() + const now = t0 + 1000 + const prev = { at: t0, cum: 10e6, start } + assert.equal(win.cpuPercent(100, now, undefined), 0) + // 1 秒内走了 0.5 秒 CPU = 50% + assert.equal(win.cpuPercent(15e6, now, prev), 50) + // 进程刚起来:只活了 0.5 秒、间隔 1 秒,按 0.5 秒算,封顶 100% + assert.equal(win.cpuPercent(15e6, now, { at: t0, cum: 10e6, start: new Date(now - 500).toISOString() }), 100) + // 累计值反而变小(PID 被复用),不出负数 + assert.equal(win.cpuPercent(5e6, now, prev), 0) +}) + +test('parseNetstat 区分监听、连接和 UDP', () => { + const out = [ + '', + '活动连接', + '', + ' 协议 本地地址 外部地址 状态 PID', + ' TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1832', + ' TCP [::]:135 [::]:0 LISTENING 1832', + ' TCP 127.0.0.1:1234 10.0.0.1:443 ESTABLISHED 900', + ' TCP 127.0.0.1:5678 10.0.0.1:80 TIME_WAIT 0', + ' UDP 0.0.0.0:123 *:* 29148', + ' UDP [::1]:5353 *:* 29148' + ].join('\r\n') + const map = win.parseNetstat(out) + assert.deepEqual(map.get(1832).listen, [135]) + assert.deepEqual(map.get(900), { listen: [], conn: [1234] }) + assert.deepEqual(map.get(29148), { listen: [123, 5353], conn: [] }) + assert.equal(map.has(0), false) +}) + +test('exeFromCommandLine 取出命令行开头的 exe', () => { + const { exeFromCommandLine } = require('../src-ztools/runtime/preload/actions') + assert.equal(exeFromCommandLine('"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" --type=renderer'), 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe') + // 没有引号:参数里也可能有 .exe,宁可不认 + assert.equal(exeFromCommandLine('C:\\Windows\\ping.exe -n 60 127.0.0.1'), null) + assert.equal(exeFromCommandLine(''), null) +}) diff --git a/plugins/process-killer/test/collector.test.cjs b/plugins/process-killer/test/collector.test.cjs new file mode 100644 index 000000000..97a2657a7 --- /dev/null +++ b/plugins/process-killer/test/collector.test.cjs @@ -0,0 +1,74 @@ +const test = require('node:test') +const assert = require('node:assert') +const collector = require('../src-ztools/runtime/preload/collector') + +test('parsePs 解析 ps 输出', () => { + const out = [ + ' 180 13227 wenzhuangxie 0.4 0.2 35632 /Applications/Google Chrome Helper', + ' 1 0 root 0.0 0.1 11376 /sbin/launchd' + ].join('\n') + const list = collector.parsePs(out) + assert.equal(list.length, 2) + assert.equal(list[0].pid, 180) + assert.equal(list[0].ppid, 13227) + assert.equal(list[0].user, 'wenzhuangxie') + assert.equal(list[0].cpu, 0.4) + assert.equal(list[0].mem, 0.2) + assert.equal(list[0].rss, 35632) + assert.equal(list[0].name, 'Google Chrome Helper') +}) + +test('parsePs 跳过表头和空行', () => { + assert.deepEqual(collector.parsePs(''), []) + assert.deepEqual(collector.parsePs('\n\n'), []) + assert.deepEqual(collector.parsePs('PID PPID USER %CPU %MEM RSS COMMAND\n'), []) +}) + +test('parseLsof 区分监听与连接', () => { + const out = [ + 'p645', 'cControlCenter', 'n*:7000', 'n*:5000', + 'p838', 'credis-server', 'n127.0.0.1:6379', + 'p900', 'cnode', 'n127.0.0.1:1234->10.0.0.1:5678' + ].join('\n') + const map = collector.parseLsof(out) + assert.deepEqual(map.get(645).listen, [5000, 7000]) + assert.deepEqual(map.get(838).listen, [6379]) + assert.deepEqual(map.get(900).listen, []) + assert.deepEqual(map.get(900).conn, [1234]) +}) + +test('parseLsof 处理 IPv6 地址与空输出', () => { + const map = collector.parseLsof('p42\ncnode\nn[::1]:8080') + assert.deepEqual(map.get(42).listen, [8080]) + assert.equal(collector.parseLsof('').size, 0) +}) + +test('appBundleOf 提取 .app 路径', () => { + assert.equal( + collector.appBundleOf('/Applications/IntelliJ IDEA.app/Contents/MacOS/idea'), + '/Applications/IntelliJ IDEA.app' + ) + assert.equal(collector.appBundleOf('/sbin/launchd'), null) +}) + +test('merge 合并端口计数', () => { + const procs = [{ pid: 1, name: 'a', path: '/a', rss: 100 }] + const ports = new Map([[1, { listen: [8080], conn: [9090] }]]) + const merged = collector.merge(procs, ports) + assert.deepEqual(merged[0].listen, [8080]) + assert.equal(merged[0].portCount, 2) + assert.equal(merged[0].app, null) +}) + +test('snapshot 在真实环境返回进程', async () => { + const data = await collector.snapshot() + assert.ok(Array.isArray(data.processes)) + assert.ok(data.processes.length > 10) + assert.ok(data.processes.every(p => Number.isInteger(p.pid))) + if (process.platform === 'win32') { + // 单看进程号是不是一个进程,才能说明别人真关了我们已经算过的进程 + const self = data.processes.find(p => p.pid === process.pid) + assert.ok(self && self.path.includes('node'), '应能从命令行认出本进程') + assert.ok(data.processes.filter(p => p.listen.length > 0).length >= 1, '至少应有一个监听端口的进程') + } +}) diff --git a/plugins/process-killer/test/ui-smoke-win.cjs b/plugins/process-killer/test/ui-smoke-win.cjs new file mode 100644 index 000000000..f960c0886 --- /dev/null +++ b/plugins/process-killer/test/ui-smoke-win.cjs @@ -0,0 +1,108 @@ +const path = require('path') +const http = require('http') +const fs = require('fs') +const { execFileSync } = require('child_process') + +// playwright 走环境变量:本机没有全局安装,指到已有的那份即可 +const playwrightPath = process.env.PLAYWRIGHT_PATH || require.resolve('playwright') +const { chromium } = require(playwrightPath) +const CHROME = process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe' +const dist = path.join(__dirname, '..', 'dist') +const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.png': 'image/png', '.json': 'application/json' } + +const server = http.createServer((req, res) => { + const file = path.join(dist, decodeURIComponent(req.url.split('?')[0]).replace(/^\/+/, '') || 'index.html') + fs.readFile(file, (err, buf) => { + if (err) { res.writeHead(404); return res.end('not found') } + res.writeHead(200, { 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream' }) + res.end(buf) + }) +}) + +const MOCK = () => { + window.services = { + platform: 'win32', + snapshot: async () => ({ + processes: [ + { pid: 4096, ppid: 1, user: '', cpu: 3.5, mem: 12.4, rss: 4358144, path: '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" --type=renderer', name: 'chrome.exe', listen: [], conn: [9222], portCount: 1, app: null }, + { pid: 8192, ppid: 4096, user: '', cpu: 5.5, mem: 2.0, rss: 350000, path: '"C:\\Program Files\\Redis\\redis-server.exe"', name: 'redis-server.exe', listen: [6379], conn: [], portCount: 1, app: null }, + { pid: 512, ppid: 4, user: '', cpu: 0, mem: 0.1, rss: 12000, path: '', name: 'System Idle Process', listen: [], conn: [], portCount: 0, app: null } + ], + portWarning: null + }), + detail: async () => ({ command: '"C:\\Program Files\\Redis\\redis-server.exe" --port 6379' }), + icon: async () => null, + kill: async pid => ({ ok: false, pid, reason: 'permission' }), + forceKill: async pid => ({ ok: true, pid, signal: 'TerminateProcess' }), + restart: async pid => ({ ok: false, pid, reason: 'not_an_app' }), + copy: () => true, reveal: () => true, notify: () => {} + } +} + +;(async () => { + await new Promise(r => server.listen(0, '127.0.0.1', r)) + const port = server.address().port + const browser = await chromium.launch({ executablePath: CHROME }) + const page = await browser.newPage({ viewport: { width: 900, height: 560 } }) + const errors = [] + page.on('pageerror', e => errors.push(e.message)) + await page.addInitScript(MOCK) + + await page.goto('http://127.0.0.1:' + port + '/index.html') + await page.waitForSelector('.row') + + const rows = await page.$$eval('.row', els => els.map(e => e.dataset.pid)) + const banner = await page.textContent('#banner') + const summary = await page.textContent('#summary') + const hint = await page.textContent('.hint') + + // 端口搜索 + await page.fill('#search', '6379') + await page.waitForFunction(() => document.querySelectorAll('.row').length === 1) + const afterPort = await page.$$eval('.row', els => els.map(e => e.dataset.pid)) + + await page.fill('#search', '') + await page.waitForFunction(() => document.querySelectorAll('.row').length === 3) + // 名称排序,确认表头、端口列都在 + await page.click('#sorts button[data-sort="ports"]') + const portOrder = await page.$$eval('.row', els => els.map(e => e.dataset.pid)) + + // WM_CLOSE 被拒 -> 提示权限不足;再强杀 -> 成功提示 + await page.click('.row[data-pid="4096"]') + await page.keyboard.press('Enter') + await page.waitForSelector('#confirm:not([hidden])') + const confirmBody = await page.textContent('#confirm-body') + await page.click('#confirm-ok') + await page.waitForSelector('#toast:not([hidden])') + const toast = await page.textContent('#toast') + + // 右键菜单:强制结束走 TerminateProcess + await page.click('.row[data-pid="8192"]', { button: 'right' }) + await page.waitForSelector('#menu:not([hidden])') + await page.click('#menu button[data-act="force"]') + await page.waitForSelector('#confirm:not([hidden])') + await page.click('#confirm-ok') + await page.waitForFunction(() => document.querySelector('#toast') && document.querySelector('#toast').textContent.includes('TerminateProcess')) + const toast2 = await page.textContent('#toast') + + // 详情:Windows 上不标“累计值” + await page.click('.row[data-pid="8192"]') + await page.keyboard.press('Shift+Enter') + await page.waitForSelector('#dialog:not([hidden])') + const dialogText = await page.textContent('#dialog-body') + await page.keyboard.press('Escape') + + await page.waitForTimeout(300) + await page.screenshot({ path: path.join(__dirname, '..', 'ui-smoke.png') }) + + await browser.close() + server.close() + + const result = { rows, banner, summary, hint, afterPort, portOrder, confirmBody, toast, toast2, dialogHasCmd: dialogText.includes('--port 6379'), dialogNoCumulative: !dialogText.includes('累计值'), errors } + console.log(JSON.stringify(result, null, 2)) + const ok = rows.length === 3 && afterPort[0] === '8192' && portOrder[0] === '4096' + && toast.includes('权限') && toast2.includes('TerminateProcess') && result.dialogHasCmd && result.dialogNoCumulative + && hint.includes('Ctrl') && hint.includes('Ctrl+⏎') && confirmBody.includes('关闭请求') && errors.length === 0 + console.log(ok ? 'SMOKE OK' : 'SMOKE FAIL') + process.exit(ok ? 0 : 1) +})() diff --git a/plugins/process-killer/test/ui-smoke.cjs b/plugins/process-killer/test/ui-smoke.cjs new file mode 100644 index 000000000..07eca3190 --- /dev/null +++ b/plugins/process-killer/test/ui-smoke.cjs @@ -0,0 +1,105 @@ +// 在真实 Chrome 里经 http 加载 dist,注入 window.services 模拟 preload +const path = require('path') +const http = require('http') +const fs = require('fs') +// playwright 与 Chrome 路径可用 PLAYWRIGHT_PATH / CHROME_PATH 覆盖 +const { chromium } = require(process.env.PLAYWRIGHT_PATH || require.resolve('playwright')) + +const dist = path.join(__dirname, '..', 'dist') +const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.png': 'image/png', '.json': 'application/json' } + +const server = http.createServer((req, res) => { + const file = path.join(dist, decodeURIComponent(req.url.split('?')[0]).replace(/^\/+/, '') || 'index.html') + fs.readFile(file, (err, buf) => { + if (err) { res.writeHead(404); return res.end('not found') } + res.writeHead(200, { 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream' }) + res.end(buf) + }) +}) + +const MOCK = () => { + window.services = { + platform: 'darwin', + snapshot: async () => ({ + processes: [ + { pid: 101, ppid: 1, user: 'me', cpu: 1.5, mem: 4.2, rss: 720896, path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', name: 'Google Chrome', listen: [9222], conn: [], portCount: 1, app: '/Applications/Google Chrome.app' }, + { pid: 202, ppid: 1, user: 'me', cpu: 0.5, mem: 2.0, rss: 350000, path: '/usr/local/bin/redis-server', name: 'redis-server', listen: [6379], conn: [], portCount: 1, app: null }, + { pid: 303, ppid: 1, user: 'root', cpu: 0, mem: 0.1, rss: 12000, path: '/sbin/launchd', name: 'launchd', listen: [], conn: [], portCount: 0, app: null } + ], + portWarning: '端口信息受限:可能缺少显示其他用户进程的权限' + }), + detail: async () => ({ command: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --foo' }), + icon: async () => null, + kill: async pid => ({ ok: false, pid, reason: 'permission' }), + forceKill: async pid => ({ ok: true, pid, signal: 'SIGKILL' }), + restart: async pid => ({ ok: false, pid, reason: 'not_an_app' }), + copy: () => true, reveal: () => true, notify: () => {} + } +} + +;(async () => { + await new Promise(r => server.listen(0, '127.0.0.1', r)) + const port = server.address().port + const browser = await chromium.launch({ + executablePath: process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' + }) + const page = await browser.newPage({ viewport: { width: 900, height: 560 } }) + const errors = [] + page.on('pageerror', e => errors.push(e.message)) + await page.addInitScript(MOCK) + + await page.goto('http://127.0.0.1:' + port + '/index.html') + await page.waitForSelector('.row') + + const rows = await page.$$eval('.row', els => els.map(e => e.dataset.pid)) + const banner = await page.textContent('#banner') + const summary = await page.textContent('#summary') + + await page.fill('#search', 'redis') + await page.waitForFunction(() => document.querySelectorAll('.row').length === 1) + const afterSearch = await page.$$eval('.row', els => els.map(e => e.dataset.pid)) + + await page.fill('#search', '') + await page.waitForFunction(() => document.querySelectorAll('.row').length === 3) + await page.click('#sorts button[data-sort="ports"]') + const portOrder = await page.$$eval('.row', els => els.map(e => e.dataset.pid)) + + // 回车先弹确认框,确认后才真正执行 + await page.keyboard.press('ArrowDown') + await page.keyboard.press('Enter') + await page.waitForSelector('#confirm:not([hidden])') + const confirmShown = await page.textContent('#confirm-title') + + // 取消路径:不应产生任何提示 + await page.click('#confirm-cancel') + const cancelToastHidden = await page.$eval('#toast', el => el.hidden) + + // 确认路径:走真正的 kill + await page.keyboard.press('Enter') + await page.waitForSelector('#confirm:not([hidden])') + await page.click('#confirm-ok') + await page.waitForSelector('#toast:not([hidden])') + const toast = await page.textContent('#toast') + + await page.fill('#search', 'launchd') + await page.waitForFunction(() => document.querySelectorAll('.row').length === 1) + await page.keyboard.press('Shift+Enter') + await page.waitForSelector('#dialog:not([hidden])') + const dialogText = await page.textContent('#dialog-body') + await page.keyboard.press('Escape') + + await page.click('#sorts button[data-sort="mem"]') + await page.waitForTimeout(300) + await page.screenshot({ path: path.join(__dirname, '..', 'ui-smoke.png') }) + + await browser.close() + server.close() + + const result = { rows, banner, summary, afterSearch, portOrder, confirmShown, cancelToastHidden, toast, dialogHasCommand: dialogText.includes('--foo'), errors } + console.log(JSON.stringify(result, null, 2)) + const ok = rows.length === 3 && afterSearch[0] === '202' && portOrder[0] === '101' + && toast.includes('权限') && result.dialogHasCommand && errors.length === 0 && banner.includes('端口') + && confirmShown.includes('确认') && cancelToastHidden + console.log(ok ? 'SMOKE OK' : 'SMOKE FAIL') + process.exit(ok ? 0 : 1) +})() diff --git a/plugins/process-killer/ui-smoke.png b/plugins/process-killer/ui-smoke.png new file mode 100644 index 000000000..7625ec834 Binary files /dev/null and b/plugins/process-killer/ui-smoke.png differ