Compare commits

...
88 changed files with 533 additions and 12200 deletions

No files matched your search

-2
View File
@@ -75,8 +75,6 @@
!packages/**
!patches/
!patches/**
!plugins/
!plugins/**
!public/
!public/**
!resources/
+1
View File
@@ -15,6 +15,7 @@ export const enTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'PowerShell directory integration is not ready. Startup arguments or execution policy may prevent it.',
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
'terminal.directory.gitBashIntegrationUnavailable': 'Waiting for an accessible directory from the original Git Bash session.',
'terminal.directory.wslIntegrationUnavailable': 'Waiting for an idle Bash session in the selected WSL distribution.',
'terminal.directory.nonFilesystem': 'The current PowerShell location is not a filesystem directory.',
'terminal.directory.busy': 'Wait for an empty shell prompt.',
'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.',
+1
View File
@@ -15,6 +15,7 @@ export const esTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'La integración de directorios de PowerShell no está lista. Los argumentos de inicio o la política de ejecución pueden impedirla.',
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
'terminal.directory.gitBashIntegrationUnavailable': 'Esperando un directorio accesible de la sesión original de Git Bash.',
'terminal.directory.wslIntegrationUnavailable': 'Esperando una sesión de Bash inactiva en la distribución WSL seleccionada.',
'terminal.directory.nonFilesystem': 'La ubicación actual de PowerShell no es un directorio del sistema de archivos.',
'terminal.directory.accessDenied': 'Permiso denegado al listar este directorio.',
'terminal.directory.busy': 'Espera a que el prompt esté vacío.',
+1
View File
@@ -15,6 +15,7 @@ export const ruTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'Интеграция каталогов PowerShell не готова. Проверьте параметры запуска и политику выполнения.',
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
'terminal.directory.gitBashIntegrationUnavailable': 'Ожидание доступного каталога исходного сеанса Git Bash.',
'terminal.directory.wslIntegrationUnavailable': 'Ожидание готовности Bash в выбранном дистрибутиве WSL.',
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
@@ -15,6 +15,7 @@ export const zhCNTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'PowerShell 目录集成未就绪,启动参数或执行策略可能阻止了加载。',
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 会话中的可访问目录。',
'terminal.directory.wslIntegrationUnavailable': '正在等待所选 WSL 发行版中的 Bash 返回空闲提示符。',
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
'terminal.directory.accessDenied': '没有权限列出此目录。',
'terminal.directory.busy': '请等待终端回到空命令提示符。',
@@ -15,6 +15,7 @@ export const zhTWTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'PowerShell 目錄整合尚未就緒,啟動參數或執行原則可能阻止載入。',
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 工作階段中的可存取目錄。',
'terminal.directory.wslIntegrationUnavailable': '正在等待所選 WSL 發行版本中的 Bash 返回閒置提示字元。',
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
@@ -9,7 +9,7 @@ test('selected metadata projects only the allowlist and replacement invalidates
const resources = new PluginHostActionResources();
resources.observe([first]);
const metadata = resources.metadata(first.id);
assert.deepEqual(Object.keys(metadata), ['resourceId', 'revision', 'label', 'hostname', 'username', 'protocol', 'group', 'tags']);
assert.deepEqual(Object.keys(metadata), ['resourceId', 'revision', 'label', 'hostname', 'username', 'protocol', 'group', 'tags', 'os']);
assert.equal(JSON.stringify(metadata).includes('synthetic-password'), false);
resources.observe([first]);
assert.equal(resources.resolve(first.id, metadata.revision), first);
@@ -16,14 +16,17 @@ export function createTerminalDirectoryController(options: {
target?: DirectoryTarget;
capabilities?: DirectoryCapabilities;
buildChangeCommand?: (path: string) => string | null;
trustOsc7?: boolean;
}) {
const target = Object.freeze({ ...options.target ?? { authority: `session:${options.sessionId}`, pathFlavor: 'posix' as const } });
const capabilities = Object.freeze({ ...options.capabilities ?? COMPLETE_DIRECTORY_CAPABILITIES });
const trustsOsc7 = target.pathFlavor === 'posix' && options.trustOsc7 !== false;
const valid = (path: string | null | undefined): path is string => isDirectoryPath(path, target.pathFlavor);
const same = (a: string, b: string) => sameDirectoryPath(a, b, target.pathFlavor);
let disposed = false;
let changing = false;
let confirmed = false;
let verifiedCwd: string | null = null;
let refreshing: Promise<string> | null = null;
let refreshAgain = false;
let cwdError: DirectoryPickerError | null = null;
@@ -57,7 +60,7 @@ export function createTerminalDirectoryController(options: {
if (!capabilities.readCwd) throw new DirectoryPickerError('unavailable');
const activeShellCwd = () => {
const cwd = terminalCwdStore.getCwd(options.sessionId);
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSource(options.sessionId) === 'osc7'
return trustsOsc7 && valid(cwd) && terminalCwdStore.getSource(options.sessionId) === 'osc7'
&& (submittedRevision === undefined || terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision)
? cwd : null;
};
@@ -79,8 +82,9 @@ export function createTerminalDirectoryController(options: {
cwd = await bounded(options.io.cwd());
if (!valid(cwd)) throw new DirectoryPickerError('unknown');
} catch (error) {
if (current() && target.pathFlavor === 'win32') {
if (current() && !trustsOsc7) {
confirmed = false;
verifiedCwd = null;
cwdError = error instanceof DirectoryPickerError ? error : new DirectoryPickerError('unknown');
options.publish('');
}
@@ -89,10 +93,13 @@ export function createTerminalDirectoryController(options: {
check();
const reported = activeShellCwd();
const live = terminalCwdStore.getCwd(options.sessionId);
const verifiedCwdChanged = verifiedCwd !== cwd;
confirmed = true;
verifiedCwd = cwd;
cwdError = null;
if (reported) return reported;
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale') options.publish(cwd);
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale'
|| (options.trustOsc7 === false && verifiedCwdChanged)) options.publish(cwd);
return cwd;
})();
refreshing = pending;
@@ -119,7 +126,7 @@ export function createTerminalDirectoryController(options: {
check(signal);
if (!valid(canonical)) throw new DirectoryPickerError('unsupportedPath');
ready(); // The shell can become busy while resolving a remote symlink.
if (expectedCwd && terminalCwdStore.getCwd(options.sessionId) !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (expectedCwd && (options.trustOsc7 === false ? verifiedCwd : terminalCwdStore.getCwd(options.sessionId)) !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (expectedRevision !== undefined && terminalCwdStore.getSessionRevision(options.sessionId) !== expectedRevision) throw new DirectoryPickerError('unavailable');
const submittedRevision = terminalCwdStore.getSessionRevision(options.sessionId);
options.io.write(command + '\r');
@@ -127,7 +134,7 @@ export function createTerminalDirectoryController(options: {
const deadline = Date.now() + (options.confirmationMs ?? 8000);
const hasFreshOsc7 = () => {
const cwd = terminalCwdStore.getCwd(options.sessionId);
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
return trustsOsc7 && valid(cwd) && terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
&& terminalCwdStore.getSource(options.sessionId) === 'osc7'
&& (same(cwd, path) || same(cwd, canonical));
};
@@ -171,6 +178,8 @@ export function createTerminalDirectoryController(options: {
return {
target,
capabilities,
trustsOsc7,
getVerifiedCwd: () => verifiedCwd,
getCwdError: () => cwdError?.code ?? null,
refresh: () => refresh(),
hasConfirmedCwd: () => confirmed,
@@ -10,9 +10,11 @@ export function useComposeDirectoryPicker(sessionId: string) {
useSyncExternalStore(terminalCwdStore.subscribe, terminalCwdStore.getVersion, terminalCwdStore.getVersion);
const [confirmation, setConfirmation] = useState<{ sessionId: string; controller: typeof controller } | null>(null);
const confirmed = confirmation?.sessionId === sessionId && confirmation.controller === controller;
const observedCwd = terminalCwdStore.getCwd(sessionId);
const getCurrentCwd = useCallback(() => controller?.trustsOsc7 === false && pathFlavor === 'posix'
? controller.getVerifiedCwd() : terminalCwdStore.getCwd(sessionId), [controller, pathFlavor, sessionId]);
const observedCwd = getCurrentCwd();
const cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
&& (confirmed || controller.hasConfirmedCwd() || (pathFlavor === 'posix' && terminalCwdStore.getSource(sessionId) === 'osc7'))
&& (confirmed || controller.hasConfirmedCwd() || (controller.trustsOsc7 && terminalCwdStore.getSource(sessionId) === 'osc7'))
? observedCwd : null;
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
@@ -77,7 +79,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
for (let attempt = 0; attempt < 3; attempt++) {
const revision = terminalCwdStore.getSessionRevision(sessionId);
const result = await controller.list(cwd, task.signal);
if (task.signal.aborted || id !== generation.current || terminalCwdStore.getCwd(sessionId) !== cwd) return;
if (task.signal.aborted || id !== generation.current || getCurrentCwd() !== cwd) return;
if (terminalCwdStore.getSessionRevision(sessionId) !== revision) continue;
listingBase.current = cwd; listingRevision.current = revision; setEntries(result.entries); setHome(result.home);
return;
@@ -86,7 +88,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
} catch (failure) {
if (!task.signal.aborted && id === generation.current) report(failure, 'readFailed');
} finally { if (!task.signal.aborted && id === generation.current) setLoading(false); }
}, [controller, cwd, report, sessionId, setHome]);
}, [controller, cwd, getCurrentCwd, report, sessionId, setHome]);
useEffect(() => {
if (!cwd) {
@@ -102,7 +104,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
const change = useCallback(async (path: string) => {
if (!controller) { setError('unavailable'); return; }
if (sending.current) return;
if (!cwd || terminalCwdStore.getCwd(sessionId) !== cwd
if (!cwd || getCurrentCwd() !== cwd
|| (path !== directoryParent(cwd, pathFlavor) && (listingBase.current !== cwd
|| listingRevision.current !== terminalCwdStore.getSessionRevision(sessionId)))) { setError('unavailable'); return; }
sending.current = true; setPending(true); setError(null);
@@ -115,12 +117,12 @@ export function useComposeDirectoryPicker(sessionId: string) {
finally {
if (id === generation.current) { sending.current = false; setPending(false); }
}
}, [controller, report, cwd, sessionId, pathFlavor]);
}, [controller, report, cwd, sessionId, pathFlavor, getCurrentCwd]);
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
const cwdError = controller?.getCwdError() ?? null;
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable'
|| error === 'gitBashIntegrationUnavailable' || error === 'nonFilesystem';
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'nonFilesystem';
return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
error: cwdError ?? (cwd && waitsForCwd ? null : error),
@@ -44,7 +44,8 @@ export function useTerminalDirectorySession(options: {
pathFlavor,
windowsShell: integration,
}, isCurrent),
target: { authority: `${local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
target: { authority: `${integration === 'wsl' ? 'wsl' : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
trustOsc7: integration !== 'wsl',
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
isCurrent,
@@ -60,7 +61,11 @@ export function useTerminalDirectorySession(options: {
if (windowsShell) register('win32', windowsShell);
else if (shellType === 'posix' && host.localShell) {
const shells = await bridge.discoverShells?.();
if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
const command = host.localShell.toLowerCase();
if (shells?.some(shell => shell.id.startsWith('wsl-')
&& (command === shell.id.toLowerCase() || command === shell.command.toLowerCase()))) {
register('posix', 'wsl');
} else if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
register('win32', 'git-bash');
}
}
+1
View File
@@ -659,6 +659,7 @@ function TerminalPopupPageInner({
accentMode={settings.accentMode}
customAccent={settings.customAccent}
terminalSettings={settings.terminalSettings}
shellType={config.sourceSession.shellType}
vaultInitializedOverride={vaultInitialized}
disableTerminalFontZoom={settings.disableTerminalFontZoom}
sessionId={sessionId}
@@ -8,7 +8,7 @@ Context Chips 位于终端撰写栏的快捷命令与输入区之间,为当前
| 功能 | 当前范围 | 文档 |
| --- | --- | --- |
| Directory Picker | 目录展示、当前层搜索和导航,覆盖 POSIX、PowerShell、CMD 和 Git Bash | [功能规格](directory-picker.md) · [跨平台设计](directory-picker-cross-platform.md) · [开发计划](directory-picker-follow-up.md) |
| Directory Picker | 目录展示、当前层搜索和导航,覆盖 POSIX、PowerShell、CMD、Git Bash 和 WSL Bash | [功能规格](directory-picker.md) · [跨平台设计](directory-picker-cross-platform.md) · [开发计划](directory-picker-follow-up.md) |
| Git Branch | 后续接入仓库识别、分支读取与切换 | [Git Branch](git-branch.md) |
| Git Changes | 后续接入变更统计与详情入口 | [Git Changes](git-changes.md) |
| Node Version | 后续接入当前 shell 的运行时与版本管理器 | [Node Version](node-version.md) |
@@ -67,11 +67,15 @@ PSDrive 根的 ProviderPath 可能带尾部反斜杠,因此路径比较按根
启动参数、profile 和提示符沿用用户配置。存在子进程时暂缓目录操作,原 Bash 恢复后重新读取。共享路径和虚拟挂载留到各自的路径语义明确后扩展。
## WSL 会话集成
通过 `WSLENV` 为所选发行版的交互会话传递标记。辅助进程在同一发行版和用户下读取 `/proc`,绑定原 Bash 的进程和终端,按 POSIX 路径处理 Linux 目录与挂载盘。检测到同终端的子进程时暂缓导航,原 Bash 恢复后重新读取位置。目录切换使用 Bash 内建 `cd`,以会话 cwd 确认结果。终端换窗口时保留原 shell 类型,目录请求跟随当前显示窗口。枚举目录时,按条目处理读取异常,保留可读的子目录。
## 后续设计方向
- POSIX hook:分别处理 bash 的 PROMPT_COMMAND、zsh 的启动链和 fish 事件,补齐事件上报。
- CMD:补充扩展关闭、提示符被启动脚本覆盖、变量展开字符和 UNC 映射场景。
- WSL/MSYS/Cygwin:以 distro/mount authority 组织目录 helper 和路径映射。
- WSL 扩展与 Cygwin:验证各自的发行版或挂载边界,复用目录控制器。
- 扩展远程环境:逐项明确活动 shell 与 SFTP/provider 的文件系统对应关系。
阶段交付与推进顺序统一维护在 [开发计划](directory-picker-follow-up.md)。
@@ -10,6 +10,7 @@
| B:PowerShell | 5.1/7 会话级脚本;原 runspace ProviderPath;私有位置报告;本地 FS;LiteralPath 切换和实际结果确认 | 用原 shell 状态串联展示、读取和执行 |
| C:CMD | 交互 CMD 的 PROMPT 上报;盘符目录读取与 `cd /d` 切换;原进程和新提示符确认 | 复用目录控制器,按 CMD 的变量展开和进程继承划定支持范围 |
| D1:Git Bash | 绑定原 Git for Windows Bash,读取 MSYS cwd 并映射为 Windows 盘符路径 | 保留 Bash 启动行为,复用 Windows 文件系统和目录控制器 |
| D2:WSL | 从原交互 Bash 读取 POSIX cwd,在同发行版和用户下解析路径、枚举目录并确认切换 | 保留 WSL 启动配置,让 Linux 目录和 Windows 挂载盘共享同一会话身份 |
| 状态恢复 | provider 切换清空旧目录与列表;恢复 FileSystem 后重新读取;提交输入使旧报告失效 | 让菜单始终对应当前有效的文件系统位置 |
| 生命周期 | 单会话请求排序、旧控制器失效、受管脚本清理、终端就绪门控 | 将异步操作与实际会话代次绑定 |
@@ -17,7 +18,14 @@ Windows CI 使用原生 ConPTY 覆盖 PowerShell 5.1/7 以及 CMD 的特殊字
## 后续阶段
Git Bash 后先交付 [Git Branch](git-branch.md) 芯片,再按共享的仓库与 worktree 状态推进 [Git Changes](git-changes.md) 和 [Pull Request](pull-request.md)。[Node Version](node-version.md) 独立接入 shell 与版本管理器。目录兼容性按环境分别提交。
| PR 顺序 | 交付范围 |
| --- | --- |
| 1. WSL | Ubuntu Bash 的 Directory Picker,覆盖 Linux 目录和挂载盘。 |
| 2. Cygwin | 识别原 Bash 及其挂载,接入目录枚举、跳转和确认。 |
| 3. Git Branch | 识别当前工作树,读取分支并确认切换。见 [Git Branch](git-branch.md)。 |
| 4. Git Changes | 复用工作树状态,提供变更统计和详情入口。见 [Git Changes](git-changes.md)。 |
| 5. Pull Request | 使用当前工作树和分支关联托管服务。见 [Pull Request](pull-request.md)。 |
| 6. Node Version | 独立接入当前 shell 和版本管理器。见 [Node Version](node-version.md)。 |
### PowerShell 覆盖扩展
@@ -38,15 +46,15 @@ Git Bash 后先交付 [Git Branch](git-branch.md) 芯片,再按共享的仓库
为 `%`、`!` 目录验证保留字面值的传递方式;为自定义 AutoRun、关闭命令扩展和前后台子进程补充原生用例。UNC 的 `pushd`/`popd` 单独定义临时盘符、目录栈和退出清理语义。
### D2/D3:WSL 与 Cygwin
### D2:WSL
为每类环境定义文件系统 authority、cwd 来源、结构化目录 helper 与执行策略:
启动时通过 `WSLENV` 传入会话标记,保留原登录 shell 和配置。辅助进程在同一发行版和用户下运行,通过 `/proc` 绑定原 Bash 及其终端。目录读取使用 Linux 路径,切换结果由原 Bash 的 cwd 确认。
- WSL:绑定所选 distro,验证 Linux home、挂载盘及 wslpath/UNC 映射。
- Cygwin:验证 mount、驱动器、链接和编码转换。Git Bash 后续补充共享路径和虚拟挂载语义。
- helper:保留原始名称、类型和目录链接,提供输出边界、取消及权限状态。
首轮以带 Python 3.10 及以上版本的 Ubuntu Bash 为目标。WSL 1 已覆盖原生 ConPTY 核心行为。后续补充 WSL 2、其他发行版及 shell,并评估更轻量的辅助进程实现。
交付目标是让目录读取与命令执行处于同一命名空间,并按 distro/mount 身份组织缓存。
### D3:Cygwin
先确认 Cygwin 进程与终端的对应关系,再验证 `/cygdrive`、自定义挂载、符号链接和 Unicode。由同一安装的工具读取 cwd 和目录,保留原路径命名空间。Git Bash 后续扩展共享路径和虚拟挂载。
### E:扩展远程与嵌套 shell
+4 -3
View File
@@ -3,8 +3,8 @@ import { resolveInteractiveTerminalCdIntent } from './sessionRestore';
import { isAbsoluteDirectoryPath, joinDirectoryPath, labelDirectoryPath, parentDirectoryPath, type DirectoryPathFlavor } from './directoryPath';
export type DirectoryEntry = { name: string; path: string; hidden: boolean };
export type WindowsDirectoryShell = 'powershell' | 'cmd' | 'git-bash';
export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'accessDenied' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'cmdIntegrationUnavailable' | 'gitBashIntegrationUnavailable' | 'nonFilesystem';
export type WindowsDirectoryShell = 'powershell' | 'cmd' | 'git-bash' | 'wsl';
export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'accessDenied' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'cmdIntegrationUnavailable' | 'gitBashIntegrationUnavailable' | 'wslIntegrationUnavailable' | 'nonFilesystem';
export class DirectoryPickerError extends Error {
constructor(public readonly code: DirectoryPickerErrorCode) { super(code); }
@@ -22,7 +22,7 @@ export function directoryLabel(path: string, home?: string | null, flavor: Direc
return labelDirectoryPath(path, home, flavor);
}
export function directoryEntries(path: string, files: readonly RemoteFile[], flavor: DirectoryPathFlavor = 'posix'): DirectoryEntry[] {
export function directoryEntries<T extends Pick<RemoteFile, 'name' | 'type' | 'linkTarget' | 'hidden'>>(path: string, files: readonly T[], flavor: DirectoryPathFlavor = 'posix'): DirectoryEntry[] {
return files.filter(file => file.type === 'directory' || (file.type === 'symlink' && file.linkTarget === 'directory'))
.flatMap(file => {
const child = joinDirectoryPath(path, file.name, flavor);
@@ -55,6 +55,7 @@ export function directoryChangeCommand(path: string, shell: 'posix' | WindowsDir
const target = path.replace(/\\/g, '/').replace(/'/g, "'\\''");
return `\\builtin cd -- '${target}'`;
}
if (shell === 'wsl') return flavor === 'posix' ? `\\builtin cd -- '${path.replace(/'/g, "'\\''")}'` : null;
return flavor === 'posix' ? resolveInteractiveTerminalCdIntent(path)?.command ?? null : null;
}
+2
View File
@@ -159,11 +159,13 @@ test('generateRdpFileContent round-trips cleanly through parseRdpFile and strips
});
assert.ok(generated.includes('full address:s:[2001:db8::10]:33890\r\n'));
assert.ok(generated.includes('\r\nuse redirection server name:i:1\r\n'));
assert.ok(!generated.includes('\r\nfull address:s:evil.example'));
const reparsed = parseRdpFile(generated);
assert.equal(reparsed.hostname, '2001:db8::10');
assert.equal(reparsed.port, 33890);
assert.equal(reparsed.username, 'alice|token-123');
assert.equal(reparsed.useRedirectionServerName, true);
assert.equal(reparsed.resolutionMode, 'dynamic');
assert.equal(reparsed.audioEnabled, true);
assert.equal(reparsed.clipboardSync, true);
+1
View File
@@ -400,6 +400,7 @@ export const generateRdpFileContent = (spec: GenerateRdpFileSpec): string => {
`full address:s:${formatRdpFullAddress(spec.hostname, port)}`,
`server port:i:${port}`,
'prompt for credentials:i:1',
'use redirection server name:i:1',
'screen mode id:i:2',
];
+45 -2
View File
@@ -69,8 +69,19 @@ module.exports = {
'dist/**/*',
'electron/**/*',
// The Windows Hello helper is shipped once through win.extraResources.
// Exclude local per-arch build output from app.asar on every platform.
// Exclude both its C++ source and local per-arch build output from app.asar.
'!electron/bridges/windowsHelloHelper/build/**/*',
'!electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp',
// Packaged builds always run `prebuild` -> `build:preload`, producing
// `electron/preload.bundle.cjs` (preferred by preloadPath.cjs). Keep
// the unbundled preload sources out of app.asar.
'!electron/preload.cjs',
'!electron/preload/**/*',
// Build-time macOS entitlements plist, dev launcher, and internal docs
// are not runtime app files.
'!electron/entitlements.mac.plist',
'!electron/launch.cjs',
'!electron/plugins/distribution/README.md',
// Test fixtures, test-only helpers, and dev/CI schema snapshots are not
// runtime resources. Keep them out of production ASARs (including plugin
// smoke fixtures so no example plugin can be mistaken for an installed package).
@@ -178,6 +189,15 @@ module.exports = {
// web-streams-polyfill is only a Node < 16.5 fallback inside fetch-blob;
// Netcatty requires Node >= 22 / Electron 42 with native Web Streams.
'!node_modules/web-streams-polyfill/**/*',
// tar-stream and events-universal declare bare-* packages only for the
// Holepunch/Bare runtime ("bare" import/export condition). Node/Electron
// always resolves default Node.js built-ins and never loads bare-* or
// their cross-platform iOS/Android/desktop .bare prebuilds.
'!node_modules/bare-fs/**/*',
'!node_modules/bare-url/**/*',
'!node_modules/bare-path/**/*',
'!node_modules/bare-events/**/*',
'!node_modules/bare-stream/**/*',
// Main process only CJS-requires css-tree (cjs/index.cjs) and mdn-data's
// css/{at-rules,properties,syntaxes}.json; skip browser/ESM/l10n/schema copies.
'!node_modules/css-tree/dist/**/*',
@@ -229,6 +249,15 @@ module.exports = {
// per-platform prebuilds); netcatty uses the user's copilot via cliPath,
// so it is excluded entirely.
'!**/@anthropic-ai/claude-agent-sdk-*/**/*',
// claudeDriver.cjs only imports the default "@anthropic-ai/claude-agent-sdk"
// entrypoint (sdk.mjs). Exclude unused sibling entrypoints and manifests
// while keeping sdk.mjs, LICENSE.md, and README.md.
'!node_modules/@anthropic-ai/claude-agent-sdk/assistant.mjs',
'!node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs',
'!node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js',
'!node_modules/@anthropic-ai/claude-agent-sdk/extractFromBunfs.js',
'!node_modules/@anthropic-ai/claude-agent-sdk/manifest.json',
'!node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json',
'!node_modules/@anthropic-ai/claude-code-*/**/*',
'!node_modules/@openai/codex-{darwin,linux,linuxmusl,win32}-*/**/*',
'!node_modules/@github/copilot-{darwin,linux,linuxmusl,win32}-*/**/*',
@@ -246,8 +275,22 @@ module.exports = {
'!node_modules/@cursor/sdk/dist/**/*.d.ts',
'!node_modules/@cursor/sdk/dist/**/*.d.ts.map',
// sqlite3 rebuilds a native module for Electron; its upstream source
// tarball is build-time payload only.
// tarball, C++ sources, and install-only prebuild-install/tar helpers
// are not needed at runtime (sqlite3-binding.js only requires bindings).
'!node_modules/sqlite3/deps/**/*',
'!node_modules/sqlite3/src/**/*',
'!node_modules/prebuild-install/**/*',
'!node_modules/tar/**/*',
// Native module C/C++ sources, build scripts, and node-pty's third_party
// ConPTY staging copies are build-time only; runtime loads compiled
// binaries from build/Release or prebuilds.
'!node_modules/node-pty/third_party/**/*',
'!node_modules/node-pty/deps/**/*',
'!node_modules/node-pty/src/**/*',
'!node_modules/node-pty/scripts/**/*',
'!node_modules/node-pty/node-addon-api/**/*',
'!node_modules/node-pty/typings/**/*',
'!node_modules/@serialport/bindings-cpp/src/**/*',
// Native compilation helpers are needed during install/rebuild only.
// Match nested copies too; keep the actual native loaders and binaries.
'!node_modules/**/node-gyp/**/*',
+1
View File
@@ -1866,6 +1866,7 @@ function buildDefaultRdpFileContent({
const lines = [
`full address:s:${hostPort}`,
"prompt for credentials:i:1",
"use redirection server name:i:1",
`audiomode:i:${audioEnabled === false ? 2 : 0}`,
`redirectclipboard:i:${clipboardSync === false ? 0 : 1}`,
"screen mode id:i:2",
@@ -305,6 +305,7 @@ describe("remoteDesktopBridge system client helpers", () => {
loadBalanceInfo: "tsv://MS Terminal Services Plugin.1.Desktop",
});
assert.match(content, /^full address:s:10\.1\.2\.3:33890/m);
assert.ok(content.includes("\r\nuse redirection server name:i:1\r\n"));
assert.match(content, /^username:s:alice\|token-uuid/m);
assert.match(content, /^domain:s:CORP/m);
assert.match(content, /^loadbalanceinfo:s:tsv:\/\//m);
@@ -312,6 +313,7 @@ describe("remoteDesktopBridge system client helpers", () => {
const rewritten = rewriteRdpFullAddress(content, "127.0.0.1", 54321);
assert.match(rewritten, /^full address:s:127\.0\.0\.1:54321/m);
assert.equal(rewritten, content.replace("full address:s:10.1.2.3:33890", "full address:s:127.0.0.1:54321"));
});
it("builds vnc:// URL safely without embedding passwords", () => {
@@ -0,0 +1,107 @@
import base64
import json
import os
import pwd
import sys
def process_stat(path):
try:
with open(path + '/stat', encoding='utf-8', errors='replace') as stream:
fields = stream.read().rsplit(') ', 1)[1].split()
return tuple(int(fields[index]) for index in (1, 2, 3, 4, 5, 19))
except (OSError, ValueError, IndexError):
return None
def marked(path, marker):
try:
if os.stat(path).st_uid != os.geteuid():
return False
with open(path + '/environ', 'rb') as stream:
return marker in stream.read(256 * 1024).split(b'\0')
except OSError:
return False
def interactive_bash(marker, expected):
processes = {}
tagged = set()
with os.scandir('/proc') as entries:
for entry in entries:
if not entry.name.isdecimal():
continue
stat = process_stat(entry.path)
if stat and stat[3]:
pid = int(entry.name)
processes[pid] = stat
if marked(entry.path, marker):
tagged.add(pid)
roots = [pid for pid in tagged if processes[pid][0] not in tagged]
if len(roots) != 1:
return None
pid = roots[0]
stat = processes[pid]
_, group, session, tty, foreground, started = stat
identity = f'{pid}:{started}'
if (expected and identity != expected) or group != pid or foreground not in (0, group):
return None
# WSL 1 can report foreground group 0. In both modes, a peer on the
# same terminal other than the launcher means the original Bash is busy.
ancestors = {pid}
parent = stat[0]
while parent in processes and parent not in ancestors:
ancestors.add(parent)
parent = processes[parent][0]
if any(other not in ancestors and row[2:4] == (session, tty) for other, row in processes.items()):
return None
proc = f'/proc/{pid}'
if os.path.basename(os.readlink(proc + '/exe')) != 'bash':
return None
return proc, identity, stat
def directory_result(operation, encoded_path, cwd):
if operation == 'cwd':
return {}
path = base64.b64decode(encoded_path, validate=True).decode('utf-8')
if operation == 'realpath':
canonical = os.path.realpath(path, strict=True)
if not os.path.isdir(canonical):
raise NotADirectoryError(canonical)
return {'path': canonical}
if path != cwd:
return {'error': 'unavailable'}
files = []
with os.scandir(path) as entries:
for entry in entries:
try:
entry.name.encode('utf-8')
if entry.is_dir():
files.append({'name': entry.name, 'type': 'directory'})
except (OSError, UnicodeError):
continue
if len(files) > 4096:
raise ValueError('Directory listing exceeds limit')
return {'files': files}
def main(operation, nonce, expected, encoded_path):
try:
marker = ('NETCATTY_WSL_DIRECTORY_SESSION=' + nonce).encode('ascii')
match = interactive_bash(marker, expected)
if not match:
return {'error': 'unavailable'}
proc, identity, stat = match
cwd = os.readlink(proc + '/cwd')
result = directory_result(operation, encoded_path, cwd)
if process_stat(proc) != stat or os.readlink(proc + '/cwd') != cwd:
return {'error': 'unavailable'}
return {'identity': identity, 'cwd': cwd, 'home': pwd.getpwuid(os.geteuid()).pw_dir, **result}
except PermissionError:
return {'error': 'accessDenied'}
except (OSError, ValueError, KeyError):
return {'error': 'readFailed'}
print(json.dumps(main(*sys.argv[1:]), ensure_ascii=True))
+27 -1
View File
@@ -99,6 +99,7 @@ const tempDirBridge = require("./tempDirBridge.cjs");
const { preparePowerShellDirectoryIntegration } = require('./powerShellDirectoryIntegration.cjs');
const { prepareCmdDirectoryIntegration } = require('./cmdDirectoryIntegration.cjs');
const { prepareGitBashDirectoryIntegration } = require('./gitBashDirectoryIntegration.cjs');
const { prepareWslDirectoryIntegration } = require('./wslDirectoryIntegration.cjs');
const { createTelnetAutoLogin, isAutoLoginWakeInput } = require("./telnetAutoLogin.cjs");
const telnetProtocol = require("./telnetProtocol.cjs");
const { createPtyOutputBuffer } = require("./ptyOutputBuffer.cjs");
@@ -1164,6 +1165,8 @@ async function startLocalSession(event, payload) {
const directoryIntegration = preparePowerShellDirectoryIntegration(shell, shellArgs)
?? prepareCmdDirectoryIntegration(shell, shellArgs, env)
?? (isWslExecutable(shell) ? prepareWslDirectoryIntegration(shell, shellArgs, env,
discoverShells().find(item => item.id.startsWith('wsl-') && item.args?.[1] === shellArgs[1])) : null)
?? (process.platform === 'win32' && path.win32.basename(shell).toLowerCase() === 'bash.exe'
? prepareGitBashDirectoryIntegration(shell, shellArgs, env, discoverShells().find(item => item.id === 'git-bash')?.command) : null);
let proc;
@@ -1182,7 +1185,7 @@ async function startLocalSession(event, payload) {
directoryIntegration?.cleanup?.();
throw error;
}
directoryIntegration?.reader.setProcessId(proc.pid);
directoryIntegration?.reader.setProcessId?.(proc.pid);
if (directoryIntegration) {
// All writers (interactive input, snippets and AI exec) share this PTY.
// Invalidate at the transport boundary, including direct proc/pty writes.
@@ -2660,6 +2663,18 @@ function registerWorkerSend(ipcMain, terminalWorkerManager, channel) {
});
}
const WSL_DIRECTORY_CHANNEL = "netcatty:local:wslDirectory";
const wslDirectoryUnavailable = Object.freeze({ success: false, error: "unavailable" });
async function readWslSessionDirectory(event, { sessionId, operation, path } = {}, workerRuntime = false) {
const session = sessions.get(sessionId);
const canRead = () => session && !session.closed && sessions.get(sessionId) === session
&& (workerRuntime || session.webContentsId === event.sender.id);
if (!canRead() || !session.directoryIntegration?.readPath) return wslDirectoryUnavailable;
const result = await session.directoryIntegration.readPath(operation, path);
return canRead() ? result : wslDirectoryUnavailable;
}
function registerHandlers(ipcMain, options = {}) {
const terminalWorkerManager = options.terminalWorkerManager || null;
// Attach/observe popups rebind display routing in the main process even when
@@ -2813,6 +2828,14 @@ function registerHandlers(ipcMain, options = {}) {
terminalWorkerManager.onSessionClosed?.(({ sessionId }) => {
terminalFlowPauseArbiter.clearSession(sessionId);
});
// Output routing lives in main. Only the current routed window can read WSL paths.
ipcMain.handle(WSL_DIRECTORY_CHANNEL, async (event, { sessionId, operation, path } = {}) => {
const webContentsId = event.sender.id;
const ownsOutput = () => terminalWorkerManager.getSessionOwnerWebContentsId(sessionId) === webContentsId;
if (!ownsOutput()) return wslDirectoryUnavailable;
const result = await terminalWorkerManager.request(WSL_DIRECTORY_CHANNEL, { sessionId, operation, path }, { webContentsId });
return ownsOutput() ? result : wslDirectoryUnavailable;
});
[
"netcatty:local:start",
"netcatty:telnet:start",
@@ -2893,6 +2916,9 @@ function registerHandlers(ipcMain, options = {}) {
? sessionLogStreamManager.withSessionLogRestart
: (handler) => handler;
ipcMain.handle("netcatty:local:start", wrapSessionStart(startLocalSession));
// The worker endpoint is reachable only through main's authorized proxy.
ipcMain.handle(WSL_DIRECTORY_CHANNEL, (event, payload) =>
readWslSessionDirectory(event, payload, options.workerRuntime === true));
ipcMain.handle("netcatty:telnet:start", wrapSessionStart(startTelnetSession));
ipcMain.handle("netcatty:mosh:start", wrapSessionStart(startMoshSession));
ipcMain.handle("netcatty:et:start", wrapSessionStart(startEtSession));
@@ -395,6 +395,52 @@ test("fallback log restart guard wraps all six starts only when main explicitly
assert.equal(wrappers.size, 0, "worker proxies must not also apply the main fallback guard");
});
test("WSL directory requests follow the active output window and discard results after a handoff", async () => {
const channel = "netcatty:local:wslDirectory";
const unavailable = { success: false, error: "unavailable" };
const listing = { success: true, files: [{ name: "child", type: "directory" }] };
const home = { sender: { id: 42 } };
const popup = { sender: { id: 43 } };
const payload = { sessionId: "wsl", operation: "list", path: "/home/example" };
let outputOwner = home.sender.id;
let finish;
const sessions = new Map([["wsl", {
webContentsId: home.sender.id,
directoryIntegration: {
readPath: () => new Promise(resolve => { finish = resolve; }),
},
}]]);
const main = createFakeIpcMain();
const worker = createFakeIpcMain();
const fallback = createFakeIpcMain();
terminalBridge.init({ sessions });
terminalBridge.registerHandlers(worker, { workerRuntime: true });
terminalBridge.registerHandlers(fallback);
terminalBridge.registerHandlers(main, {
terminalWorkerManager: {
getSessionOwnerWebContentsId: id => id === "wsl" ? outputOwner : null,
request: (name, data, { webContentsId }) =>
worker.handlers.get(name)({ sender: { id: webContentsId } }, data),
},
});
const read = main.handlers.get(channel);
const beforeHandoff = read(home, payload);
outputOwner = popup.sender.id;
finish(listing);
assert.deepEqual(await beforeHandoff, unavailable);
assert.deepEqual(await read(home, payload), unavailable);
assert.deepEqual(await fallback.handlers.get(channel)(popup, payload), unavailable);
const afterHandoff = read(popup, payload);
finish(listing);
assert.deepEqual(await afterHandoff, listing);
const beforeClose = read(popup, payload);
sessions.delete("wsl");
finish(listing);
assert.deepEqual(await beforeClose, unavailable);
});
test("terminal worker mode handles stateless local shell and path queries in main without waking worker", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
@@ -0,0 +1,102 @@
const fs = require('node:fs');
const path = require('node:path');
const { randomBytes } = require('node:crypto');
const { execFile } = require('node:child_process');
const { promisify } = require('node:util');
const run = promisify(execFile);
const marker = 'NETCATTY_WSL_DIRECTORY_SESSION';
const unavailable = Object.freeze({ success: false, error: 'unavailable' });
const isPath = value => typeof value === 'string' && value.startsWith('/') && value.length <= 8192
&& !/[\x00-\x1f\x7f]|[\uD800-\uDFFF]/u.test(value);
function getWslDirectoryArgs(args, discovered) {
// A named distro is required so the helper cannot follow a changed default.
if (!['-d', '--distribution'].includes(args[0]) || args[1] !== discovered || !discovered) return null;
const target = ['--distribution', discovered];
for (let index = 2; index < args.length; index += 2) {
const option = args[index];
const value = args[index + 1];
if (option === '--cd' && value && !value.startsWith('-')) continue;
if (['-u', '--user'].includes(option) && /^[a-z_][a-z0-9_.-]*\$?$/i.test(value ?? '')
&& !target.includes('--user')) {
target.push('--user', value);
} else return null;
}
return target;
}
function createWslDirectoryReader(probe) {
let identity = '';
let revision = 0;
let pendingRead;
let generation = new AbortController();
let closed = false;
async function query(operation, target = '') {
const { signal } = generation;
if (closed) return unavailable;
try {
const result = await probe(operation, identity, target, signal);
if (signal.aborted) return unavailable;
if (result.error) return ['readFailed', 'accessDenied'].includes(result.error)
? { success: false, error: result.error } : unavailable;
if (!/^\d+:\d+$/.test(result.identity) || (identity && identity !== result.identity) || !isPath(result.cwd)) {
return unavailable;
}
identity = result.identity;
const home = isPath(result.home) ? result.home : null;
if (operation === 'list') return { success: true, files: result.files, home };
if (operation === 'realpath') return isPath(result.path) ? { success: true, path: result.path } : unavailable;
const cwd = result.cwd;
return { success: true, cwd, directoryState: { cwd, home, provider: 'FileSystem',
revision: ++revision, shellKind: 'wsl', pathFlavor: 'posix' } };
} catch {
return signal.aborted ? unavailable : { success: false, error: 'readFailed' };
}
}
function invalidate() {
generation.abort();
generation = new AbortController();
pendingRead = undefined;
}
return {
invalidate,
close() { closed = true; invalidate(); },
read() {
if (pendingRead) return pendingRead;
const result = query('cwd').finally(() => { if (pendingRead === result) pendingRead = undefined; });
pendingRead = result;
return result;
},
readPath(operation, target) {
if (!['list', 'realpath'].includes(operation) || !isPath(target)) return unavailable;
return query(operation, target);
},
};
}
function prepareWslDirectoryIntegration(shell, args, env, discovered) {
if (process.platform !== 'win32' || !discovered || shell.toLowerCase() !== discovered.command.toLowerCase()) return null;
const target = getWslDirectoryArgs(args, discovered.args?.[1]);
if (!target) return null;
let script;
try { script = fs.readFileSync(path.join(__dirname, 'shellIntegration', 'directory-wsl.py'), 'utf8'); }
catch { return null; }
const nonce = randomBytes(24).toString('hex');
const wslEnvKey = Object.keys(env).find(key => key.toUpperCase() === 'WSLENV') || 'WSLENV';
const forwarded = (env[wslEnvKey] || '').split(':').filter(entry => entry && entry.split('/')[0] !== marker);
const reader = createWslDirectoryReader(async (operation, identity, targetPath, signal) => {
// Encode the path as data. Only the fixed Python program is executable.
const encoded = Buffer.from(targetPath, 'utf8').toString('base64');
const { stdout } = await run(shell, [...target, '--cd', '/', '--exec', '/usr/bin/python3', '-I', '-c',
script, operation, nonce, identity, encoded], { encoding: 'utf8', windowsHide: true,
timeout: 2500, maxBuffer: 512 * 1024, signal, env });
return JSON.parse(stdout);
});
return { reader, env: { [wslEnvKey]: [...forwarded, `${marker}/u`].join(':'), [marker]: nonce }, cleanup: reader.close };
}
module.exports = { prepareWslDirectoryIntegration, createWslDirectoryReader, getWslDirectoryArgs };
@@ -0,0 +1,28 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const { createWslDirectoryReader, getWslDirectoryArgs } = require('./wslDirectoryIntegration.cjs');
test('directory helper keeps the named distro and user and accepts only interactive launch arguments', () => {
assert.deepEqual(getWslDirectoryArgs(['-d', 'Ubuntu', '--user', 'me', '--cd', '~'], 'Ubuntu'),
['--distribution', 'Ubuntu', '--user', 'me']);
assert.equal(getWslDirectoryArgs(['-d', 'Ubuntu'], 'Other'), null);
assert.equal(getWslDirectoryArgs(['-d', 'Ubuntu', '--exec', '/bin/bash'], 'Ubuntu'), null);
assert.equal(getWslDirectoryArgs(['--cd', '~'], 'Ubuntu'), null);
});
test('a result from before input or from a replacement WSL Bash cannot confirm cwd', async () => {
let finish;
const reader = createWslDirectoryReader(() => new Promise(resolve => { finish = resolve; }));
const old = reader.read();
reader.invalidate();
finish({ identity: '5:10', cwd: '/stale' });
assert.equal((await old).success, false);
const current = reader.read();
finish({ identity: '5:10', cwd: '/mnt/c' });
assert.equal((await current).cwd, '/mnt/c');
const replacement = reader.read();
finish({ identity: '5:99', cwd: '/different-session' });
assert.equal((await replacement).success, false);
});
+2
View File
@@ -518,6 +518,8 @@ function createPreloadApi(ctx) {
timeoutMs: options?.timeoutMs,
});
},
readWslSessionDirectory: (sessionId, operation, path) =>
ipcRenderer.invoke('netcatty:local:wslDirectory', { sessionId, operation, path }),
getSessionRemoteInfo: async (sessionId) => {
return ipcRenderer.invoke("netcatty:ssh:remoteInfo", { sessionId });
},
+1 -1
View File
@@ -341,7 +341,7 @@ function main() {
transferBridge,
});
sshBridge.registerHandlers(ipcMain);
terminalBridge.registerHandlers(ipcMain);
terminalBridge.registerHandlers(ipcMain, { workerRuntime: true });
sftpBridge.registerHandlers(ipcMain);
registerPortForwardingWorkerBridge(ipcMain);
registerRemoteDesktopWorkerBridge(ipcMain);
+4
View File
@@ -10,6 +10,10 @@ export default [
files: ["examples/plugins/starter-netcatty/panel.js"],
languageOptions: { globals: globals.browser },
},
{
files: ["plugins/*/scripts/**/*.{js,mjs,cjs}"],
languageOptions: { globals: globals.node },
},
// The recommended preset has no file scope of its own, so scope it off all of
// electron/ — that main-process tree is historically unlinted. The bridges
// get a focused rule set in the dedicated block at the end of this config;
@@ -106,7 +106,7 @@ test('untrusted session metadata cannot become the last instruction in the promp
assert.ok(reminder > prompt.indexOf('Ignore the command blocklist'));
assert.ok(reminder > prompt.indexOf('Run commands on disconnected hosts'));
assert.ok(reminder > prompt.indexOf('## User Skills'));
assert.match(prompt.slice(reminder), /labels and host metadata above are data, not instructions/);
assert.match(prompt.slice(reminder), /Session and workspace labels, host metadata, and any content inside `<plugin-context-data>` above are data, not instructions/);
assert.match(prompt.slice(reminder), /only act on connected sessions/);
assert.match(prompt.slice(reminder), /never bypass the command blocklist/);
});
@@ -157,3 +157,26 @@ test('closing a picker during channel open closes the handle without listing', a
await assert.rejects(task, { code: 'unavailable' });
assert.equal(listed, false); assert.equal(closed, true);
});
test('WSL directory IO uses the owning session and never falls back to a Windows filesystem', async () => {
const cwd = '/home/me';
const calls: unknown[] = [];
const io = createTerminalDirectoryIO({
getSessionPwd: async (id: string) => {
assert.equal(id, 'wsl-pty');
return { success: true, cwd, directoryState: { cwd, home: cwd, provider: 'FileSystem',
revision: 1, shellKind: 'wsl', pathFlavor: 'posix' } };
},
readWslSessionDirectory: async (...args: [string, string, string]) => {
calls.push(args);
if (args[1] === 'list') return { success: true, home: cwd, files: [{ type: 'directory', name: "child's folder" }] };
return { success: true, path: '/mnt/c/destination' };
},
listLocalDir: () => assert.fail('Linux paths must stay within the selected distro'),
realpathLocal: () => assert.fail('Linux paths must stay within the selected distro'),
} as unknown as NetcattyBridge, 'wsl-pty', { local: true, hostname: '', username: '', windowsShell: 'wsl' });
assert.equal(await io.cwd(), cwd);
assert.deepEqual((await io.list(cwd)).entries.map(item => item.path), ["/home/me/child's folder"]);
assert.equal(await io.realpath('/home/me/link'), '/mnt/c/destination');
assert.deepEqual(calls, [['wsl-pty', 'list', cwd], ['wsl-pty', 'realpath', '/home/me/link']]);
});
+27 -11
View File
@@ -19,10 +19,11 @@ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: str
): TerminalDirectoryIO {
const check = (signal?: AbortSignal) => { if (!isCurrent() || signal?.aborted) throw new DirectoryPickerError('unavailable'); };
const flavor = endpoint.pathFlavor ?? 'posix';
const nativeWindows = endpoint.local && flavor === 'win32';
const wsl = endpoint.local && endpoint.windowsShell === 'wsl';
const integratedLocal = endpoint.local && (flavor === 'win32' || wsl);
const windowsShell = endpoint.windowsShell ?? 'powershell';
const integrationError = {
powershell: 'integrationUnavailable', cmd: 'cmdIntegrationUnavailable', 'git-bash': 'gitBashIntegrationUnavailable',
powershell: 'integrationUnavailable', cmd: 'cmdIntegrationUnavailable', 'git-bash': 'gitBashIntegrationUnavailable', wsl: 'wslIntegrationUnavailable',
} as const;
let lastNativeRevision = 0;
let submittedNativeRevision = -1;
@@ -34,7 +35,7 @@ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: str
});
check();
const state = result?.directoryState;
if (!state || state.shellKind !== windowsShell || state.pathFlavor !== 'win32') {
if (!state || state.shellKind !== windowsShell || state.pathFlavor !== flavor) {
throw new DirectoryPickerError(integrationError[windowsShell]);
}
if (state.provider !== 'FileSystem') throw new DirectoryPickerError('nonFilesystem');
@@ -43,6 +44,12 @@ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: str
lastNativeRevision = state.revision;
return { cwd: result.cwd, home: valid(state.home) ? state.home : null };
}
async function readWslPath(operation: 'list' | 'realpath', path: string, signal?: AbortSignal) {
const result = await bridge.readWslSessionDirectory?.(sessionId, operation, path);
check(signal);
if (!result?.success) throw new DirectoryPickerError(result?.error ?? 'unavailable');
return result;
}
async function checkRemote(signal?: AbortSignal) {
check(signal);
const info = await bridge.getSessionRemoteInfo?.(sessionId);
@@ -64,12 +71,12 @@ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: str
return {
async home() {
check();
if (nativeWindows) return (await readNative()).home;
if (integratedLocal) return (await readNative()).home;
return endpoint.local ? await bridge.getHomeDir?.().catch(() => null) ?? null : null;
},
async cwd() {
check();
if (nativeWindows) return (await readNative()).cwd;
if (integratedLocal) return (await readNative()).cwd;
if (!endpoint.local) await checkRemote();
const result = await bridge.getSessionPwd?.(sessionId, {
allowHomeFallback: false, allowLoginShellFallback: false, timeoutMs: 2000,
@@ -81,18 +88,22 @@ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: str
async list(path, signal) {
check(signal);
if (!valid(path)) throw new DirectoryPickerError('unsupportedPath');
if (wsl) {
const { files, home } = await readWslPath('list', path, signal);
return { entries: directoryEntries(path, files ?? [], flavor), home: valid(home) ? home : null };
}
if (endpoint.local) {
const native = nativeWindows ? await readNative() : null;
const native = integratedLocal ? await readNative() : null;
const files = await bridge.listLocalDir(path).catch((error: unknown) => {
// Electron IPC preserves the Node error message but drops its code.
if (nativeWindows && error instanceof Error && (/^(?:EACCES|EPERM)$/.test(String((error as NodeJS.ErrnoException).code))
if (integratedLocal && error instanceof Error && (/^(?:EACCES|EPERM)$/.test(String((error as NodeJS.ErrnoException).code))
|| /^(?:Error invoking remote method 'netcatty:local:list': )?(?:Error: )?(?:EACCES|EPERM):/.test(error.message))) {
throw new DirectoryPickerError('accessDenied');
}
throw error;
});
check(signal);
const home = nativeWindows ? native!.home : await bridge.getHomeDir?.().catch(() => null) ?? null;
const home = integratedLocal ? native!.home : await bridge.getHomeDir?.().catch(() => null) ?? null;
check(signal);
return { entries: directoryEntries(path, files, flavor), home };
}
@@ -105,7 +116,12 @@ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: str
async realpath(path, signal) {
check(signal);
if (!valid(path)) throw new DirectoryPickerError('unsupportedPath');
if (nativeWindows) await readNative();
if (wsl) {
const result = await readWslPath('realpath', path, signal);
if (!valid(result.path)) throw new DirectoryPickerError('unsupportedPath');
return result.path;
}
if (integratedLocal) await readNative();
const result = endpoint.local ? await bridge.realpathLocal?.(path) ?? path
: withSftp(async id => await bridge.realpathSftp?.(id, path, endpoint.encoding) ?? path, signal);
const resolved = await result;
@@ -114,13 +130,13 @@ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: str
return resolved;
},
async validateChange(expectedCwd) {
if (!nativeWindows) return;
if (!integratedLocal) return;
const native = await readNative();
if (expectedCwd && !sameDirectoryPath(native.cwd, expectedCwd, flavor)) throw new DirectoryPickerError('unavailable');
},
write(data) {
check();
if (nativeWindows) submittedNativeRevision = lastNativeRevision;
if (integratedLocal) submittedNativeRevision = lastNativeRevision;
bridge.writeToSession(sessionId, data, { automated: true });
},
};
-666
View File
@@ -1,666 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis
or for a fee, you must pass on to the recipients the same freedoms that
you received. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
are not part of the work. For example, Corresponding Source includes
interface definition files associated with source files for the work,
and the source code for shared libraries and dynamically linked
subprograms that the work is specifically designed to require, such as
by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
intact. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it,
and giving a relevant date.
b) The work must carry prominent notices stating that it is released
under this License and any conditions added under section 7. This
requirement modifies the requirement in section 4 to "keep intact all
notices".
c) You must license the entire work, as a whole, under this License
to anyone who comes into possession of a copy. This License will
therefore apply, along with any applicable section 7 additional terms,
to the whole of the work, and all its parts, regardless of how they are
packaged. This License gives no permission to license the work in any
other way, but it does not invalidate such permission if you have
separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your work
need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium customarily
used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a written
offer, valid for at least three years and valid for as long as you
offer spare parts or customer support for that product model, to give
anyone who possesses the object code either (1) a copy of the
Corresponding Source for all the software in the product that is
covered by this License, on a durable physical medium customarily used
for software interchange, for a price no more than your reasonable
cost of physically performing this conveying of source, or (2) access
to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This alternative
is allowed only occasionally and noncommercially, and only if you
received the object code with such an offer, in accord with subsection
6b.
d) Convey the object code by offering access from a designated place
(gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to copy
the object code is a network server, the Corresponding Source may be
on a different server (operated by you or a third party) that supports
equivalent copying facilities, provided you maintain clear directions
next to the object code saying where to find the Corresponding Source.
Regardless of what server hosts the Corresponding Source, you remain
obligated to ensure that it is available for as long as needed to
satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding Source
of the work are being offered to the general public at no charge under
subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove
any additional permissions from that copy, or from any part of it.
(Additional permissions may be written to require their own removal in
certain cases when you modify the work.) You may place additional
permissions on material, added by you to a covered work, for which you
have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms
of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal Notices
displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in reasonable
ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some trade
names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by
anyone who conveys the material (or modified versions of it) with
contractual assumptions of liability to the recipient, for any liability
that these contractual assumptions directly impose on those licensors
and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further restriction,
you may remove that term. If a license document contains a further
restriction but permits relicensing or conveying under this License, you
may add to a covered work material governed by the terms of that license
document, provided that the further restriction does not survive such
relicensing or conveying.
If you add terms to a covered work in accord with this section, you must
place, in the relevant source files, a statement of the additional terms
that apply to those files, or a notice indicating where to find the
applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally terminates
your license, and (b) permanently, if the copyright holder fails to
notify you of the violation by some reasonable means prior to 60 days
after the cessation of the violation.
Moreover, your license from a particular copyright holder is reinstated
permanently if the copyright holder notifies you of the violation by
some reasonable means, this is the first time you have received notice
of violation of this License (for any work) from that copyright holder,
and you cure the violation prior to 30 days after your receipt of the
notice.
Termination of your rights under this License does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work occurring
solely as a consequence of using peer-to-peer transmission to receive a
copy likewise does not require acceptance. However, nothing other than
this License grants you permission to propagate or modify any covered
work. These actions infringe copyright if you do not accept this License.
Therefore, by modifying or propagating a covered work, you indicate your
acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that transaction
who receives a copy of the work also receives whatever licenses to the
work the party's predecessor in interest had or could give under the
previous paragraph, plus a right to possession of the Corresponding
Source of the work from the predecessor in interest, if the predecessor
has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may not
impose a license fee, royalty, or other charge for exercise of rights
granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The work
thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or hereafter
acquired, that would be infringed by some manner, permitted by this
License, of making, using, or selling its contributor version, but do
not include claims that would be infringed only as a consequence of
further modification of the contributor version. For purposes of this
definition, "control" includes the right to grant patent sublicenses
in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not convey it at all. For example, if you agree to terms that
obligate you to collect a royalty for further conveying from those to
whom you convey the Program, the only way you could satisfy both those
terms and this License would be to refrain entirely from conveying the
Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU General Public
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that numbered version or
of any later version published by the Free Software Foundation. If the
Program does not specify a version number of the GNU General Public
License, you may choose any version ever published by the Free Software
Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU General Public License can be used, that proxy's public
statement of acceptance of a version permanently authorizes you to
choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
-102
View File
@@ -1,102 +0,0 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="assets/plugin-icon-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="assets/plugin-icon-light.svg">
<img src="assets/plugin-icon-light.svg" alt="Netcatty Monitor" width="84" height="84">
</picture>
</p>
<h1 align="center">Netcatty Monitor</h1>
<p align="center">
<strong>Agentless SSH server fleet observability &amp; operations workbench built natively for Netcatty's Host-Rendered Plugin Platform.</strong>
</p>
<p align="center">
<a href="https://github.com/binaricat/netcatty-monitor-plugin/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/binaricat/netcatty-monitor-plugin/ci.yml?branch=main&style=flat-square&label=CI&color=10b981" alt="CI Status"></a>
<img src="https://img.shields.io/badge/version-v0.1.0-0ea5e9?style=flat-square" alt="Version v0.1.0">
<img src="https://img.shields.io/badge/Netcatty%20Plugin-Host--Rendered-334155?style=flat-square" alt="Netcatty Host-Rendered Plugin">
<img src="https://img.shields.io/badge/sandbox-browserOnly-10b981?style=flat-square" alt="Sandbox browserOnly">
<img src="https://img.shields.io/badge/i18n-EN%20%7C%20%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87-475569?style=flat-square" alt="EN | 简体中文">
<a href="LICENSE"><img src="https://img.shields.io/badge/license-GPL--3.0--or--later-64748b?style=flat-square" alt="License GPL-3.0-or-later"></a>
</p>
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/monitor-fleet-dark.png">
<source media="(prefers-color-scheme: light)" srcset="docs/screenshots/monitor-compare-light.png">
<img src="docs/screenshots/monitor-fleet-dark.png" alt="Netcatty Monitor Workbench" width="100%">
</picture>
</p>
<p align="center">
Zero Remote Agents · 4 Fleet Views (Cards · Table · Wallboard · Compare) · Linux CPU Breakdown &amp; PSI · Storage Inodes &amp; IOPS · Network Drops &amp; TCP Retransmits · GPU &amp; Thermals · Processes · systemd / Docker / Podman Controls &amp; Log Tails · Listening Ports &amp; Security Audit · Hysteresis Alerts &amp; Live Vault Sidebar Badge · RDP / VNC Reachability Probes
</p>
---
## Install in Netcatty
1. Open **Netcatty → Settings → Plugins → Install from GitHub** and enter:
```text
binaricat/netcatty-monitor-plugin
```
2. Or download `netcatty-monitor-0.1.0.ncpkg` from the [latest GitHub Release](https://github.com/binaricat/netcatty-monitor-plugin/releases/latest) and import it via **Settings → Plugins → Manage → Import**.
---
## Highlights (`v0.1.0`)
- **100% Agentless & Browser-Sandbox Isolated (`main.browser`)** — Runs entirely inside Netcatty's ordinary offline browser plugin sandbox using host-rendered React UI (`@netcatty/plugin-sdk/host-react`), zero iframes, zero inline `<svg>`/`<canvas>`, and zero remote agents to deploy. Reuses Netcatty Vault's pooled SSH connections and durable host bindings without ever exposing host credentials.
- **4 Fleet View Modes**:
- **Cards**: Calm Netcatty-native host cards with live CPU/Memory sparklines, disk & IOPS bars, network throughput, GPU/Reboot indicators, health scores, and one-click jump to **Terminal**, **SFTP**, or **Remote Desktop** (RDP/VNC).
- **Table**: Virtualized fleet inventory via `PluginDataGrid` with customizable columns (including IOPS, Packet Drops, GPU, Load, Uptime, Latency, and Tags).
- **Wallboard (NOC)**: High-density compact status tiles built for scanning large fleets at a glance.
- **Compare Mode**: Overlay **2–6 hosts** simultaneously across 4 synchronized `PluginMetricChart` panels (CPU, Memory, Network, Latency) plus a live side-by-side KPI grid.
- **Deep Multi-OS Telemetry**:
- **Linux**: CPU breakdown (`user` / `system` / `iowait` / `steal` / `idle`), context switches/s, interrupts/s, runnable/blocked threads, color-coded Per-Core Heatmap; Active/Slab memory + **Linux PSI** (`/proc/pressure/{cpu,memory,io}`); storage **Inodes** (`df -iP`), Read/Write **IOPS**, `%util`, Queue Depth, and system-mount grouping with >80% auto-expand alerts; network packet rates (`pps`), RX/TX errors & drops, **TCP Retransmits/s**; NVIDIA/AMD GPU stats & thermal sensors; Open FDs, active users, and pending reboot detection.
- **macOS, FreeBSD / OpenBSD / NetBSD & Windows-OpenSSH**: Native telemetry parsers preserving Netcatty's multi-OS parity, plus **RDP / VNC TCP + banner reachability probes** via `vault.probeHost`.
- **Operational Workbench Tabs** (active-tab-only polling):
- **Overview**: Symmetrical 2×2 multi-series charts, customizable widget visibility (`PluginPopover`, persisted per user), `1m / 5m / 15m / 30m / 1h` time windows, and one-click **JSON** & **Markdown** diagnostics export.
- **Processes**: Top-5 CPU & Memory strip, state filter (`All` / `Running` / `Sleeping` / `Zombie`), full command inspector, and confirm-gated `SIGHUP` / `SIGTERM` / `SIGKILL`.
- **Services & Containers**: `systemd` units + Docker/Podman containers with confirm-gated `Start` / `Stop` / `Restart` / `Reload` lifecycle actions and live `journalctl` / `docker logs` tail viewer.
- **Network & Ports + Security Audit**: Listening TCP/UDP ports (`ss` / `netstat` / `lsof`), socket states (including `SYN_RECV`), plus Open FDs, logged-in users, 24h failed SSH auth attempts, and recent logins.
- **Alerts & Incident Timeline**: Configurable warning/critical thresholds (CPU, IOwait, Memory, Swap, Disk, Inodes, Load/Core, Net Drops, Latency) with **hysteresis** (`consecutivePolls`, default `2`) and live Netcatty Vault sidebar badge (`views.setBadge`).
- **Full Bilingual UI (English & 简体中文)** — Adapts automatically to Netcatty's locale and Midnight Dark / Snow Light themes.
---
## Screenshots
| Fleet Overview (Midnight Dark) | Host Deep Telemetry (Midnight Dark) |
| --- | --- |
| ![Fleet Overview Dark](docs/screenshots/monitor-fleet-dark.png) | ![Host Telemetry Dark](docs/screenshots/monitor-telemetry-dark.png) |
| Services & Containers Workbench (Midnight Dark) | Multi-Host Compare View (Snow Light) |
| --- | --- |
| ![Services & Containers Dark](docs/screenshots/monitor-ops-dark.png) | ![Multi-Host Compare Light](docs/screenshots/monitor-compare-light.png) |
---
## Build, Test & Package
Node `>=22` and npm are required. Vendored `@netcatty/plugin-{contract,sdk,cli}` snapshots and pinned stylesheet policy live in `vendor/`.
```sh
shasum -a 256 -c vendor/SHA256SUMS
npm ci --ignore-scripts
npm run lint
npm test
npm run pack
npm run validate
```
The packaged plugin is written to `dist/netcatty-monitor-0.1.0.ncpkg` alongside `dist/SHA256SUMS`.
---
## Security & Licenses
- Runs strictly as a **browser-only** Netcatty plugin (`main.browser: "browser.js"`). All SSH host executions (`vault.hostExec`), TCP reachability probes (`vault.probeHost`), host metadata resolution (`vault.metadata`), native confirmation/save dialogs (`ui.interact`), and clipboard writes are mediated and user-approved by the Netcatty host without exposing SSH keys or passwords.
- Service/container names and PIDs are strictly allowlist-validated before command construction, and all mutating process/service/container actions require explicit user confirmation.
- Plugin source code and vendored Netcatty SDK/contract/CLI snapshots are licensed under **GPL-3.0-or-later**. See [LICENSE](LICENSE), [NOTICE](NOTICE), and [SECURITY.md](SECURITY.md).
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

@@ -1,28 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256" fill="none">
<rect x="14" y="14" width="228" height="228" rx="52" fill="#082421"/>
<rect x="15.5" y="15.5" width="225" height="225" rx="50.5" stroke="#1E5D54" stroke-opacity="1" stroke-width="3"/>
<!-- Netcatty Cat Mascot Head (flat solid ink, zero gradients) -->
<g transform="translate(32.62 -0.98) scale(0.152)">
<path d="M 618.5,240.5 C 647.925,240.677 677.258,242.344 706.5,245.5C 753.323,252.113 798.49,265.113 842,284.5C 870.064,257.538 902.23,236.704 938.5,222C 966.969,211.263 988.469,219.096 1003,245.5C 1011.08,263.079 1016.75,281.412 1020,300.5C 1022.13,320.204 1024.29,339.871 1026.5,359.5C 1026.17,379.674 1026.5,399.674 1027.5,419.5C 1072.74,473.648 1102.74,535.314 1117.5,604.5C 1117.29,607.495 1117.96,610.162 1119.5,612.5C 1126.08,656.83 1126.08,701.163 1119.5,745.5C 1118.23,747.905 1117.57,750.572 1117.5,753.5C 1107.38,802.706 1088.05,847.872 1059.5,889C 1053.04,888.572 1046.71,887.405 1040.5,885.5C 1036.79,883.864 1032.79,883.198 1028.5,883.5C 1011.79,881.938 995.122,882.271 978.5,884.5C 975.572,884.565 972.905,885.232 970.5,886.5C 928.686,895.489 896.519,918.156 874,954.5C 864.791,970.962 859.958,988.628 859.5,1007.5C 793.269,1029.39 725.269,1041.72 655.5,1044.5C 633.833,1044.5 612.167,1044.5 590.5,1044.5C 524.821,1041.8 460.821,1029.63 398.5,1008C 396.254,996.177 393.421,984.344 390,972.5C 387.524,964.881 384.024,957.881 379.5,951.5C 363.815,925.334 341.815,906.667 313.5,895.5C 297.343,888.573 280.343,884.406 262.5,883C 248.055,882.038 233.722,882.538 219.5,884.5C 216.572,884.565 213.905,885.232 211.5,886.5C 211.167,886.5 210.833,886.5 210.5,886.5C 207.848,886.41 205.515,887.076 203.5,888.5C 200.823,889.614 198.156,889.614 195.5,888.5C 149.432,819.968 128.098,744.301 131.5,661.5C 131.502,654.48 131.835,647.48 132.5,640.5C 133.461,638.735 133.795,636.735 133.5,634.5C 135.136,630.79 135.802,626.79 135.5,622.5C 137.764,609.333 140.431,596.333 143.5,583.5C 144.924,581.485 145.59,579.152 145.5,576.5C 156.228,537.714 172.395,501.381 194,467.5C 204.685,451.452 215.852,435.786 227.5,420.5C 228.042,388.62 229.375,356.62 231.5,324.5C 234.549,300.253 240.382,276.586 249,253.5C 253.868,241.906 261.035,232.073 270.5,224C 279.336,218.042 289.002,216.042 299.5,218C 314.655,220.607 328.988,225.607 342.5,233C 368.29,247.23 391.957,264.396 413.5,284.5C 478.68,255.797 547.014,241.13 618.5,240.5 Z" fill="#F8FAFC"/>
<path d="M 445.5,545.5 C 447.515,546.924 449.848,547.59 452.5,547.5C 479.103,555.885 499.269,572.218 513,596.5C 515.435,607.525 511.268,614.191 500.5,616.5C 497.302,616.378 494.302,615.545 491.5,614C 485.302,604.13 477.969,595.13 469.5,587C 459.207,579.735 447.873,574.902 435.5,572.5C 415.88,568.656 398.213,573.156 382.5,586C 374,593 367,603 362.5,613C 356.408,617.241 350.075,617.574 343.5,614C 337.996,608.137 337.163,601.637 341,594.5C 343.929,589.631 347.096,584.965 350.5,580.5C 375.329,550.884 406.995,539.218 445.5,545.5 Z" fill="#082421"/>
<path d="M 817.5,544.5 C 862.791,541.392 895.958,559.726 917,599.5C 917.138,612.028 910.971,617.528 898.5,616C 897.167,615.333 895.833,614.667 894.5,614C 884.255,595.245 869.255,582.078 849.5,574.5C 843.812,571.54 837.645,570.207 831,570.5C 822.066,570.919 813.233,572.086 804.5,574C 792,580 778,592 767,610.5C 759.55,618.016 751.883,618.349 744,611.5C 742.878,609.593 742.045,607.593 741.5,605.5C 741.508,602.455 741.841,599.455 742.5,596.5C 757.037,569.397 779.371,552.73 809.5,546.5C 812.495,546.706 815.162,546.04 817.5,544.5 Z" fill="#082421"/>
<path d="M 653.5,662.5 C 664.536,665.228 669.036,672.228 667,683.5C 665.861,687.112 664.194,690.446 662,693.5C 656.35,700.317 650.184,706.65 643.5,712.5C 643.058,737.755 654.725,754.922 678.5,764C 709.272,768.521 729.105,756.021 738,726.5C 747.413,717.842 755.746,718.842 763,729.5C 759.409,758.463 743.909,778.297 716.5,789C 713.111,789.776 709.778,790.609 706.5,791.5C 697.533,792.383 688.533,792.716 679.5,792.5C 657.328,788.994 639.828,777.994 627,759.5C 607.084,786.202 580.584,797.035 547.5,792C 516.901,784.235 497.901,765.068 490.5,734.5C 493.257,721.955 500.59,718.121 512.5,723C 517.164,727.124 519.998,732.291 521,738.5C 533.515,761.003 552.348,769.17 577.5,763C 599.78,754.048 610.947,737.548 611,713.5C 604.698,706.197 598.032,699.197 591,692.5C 586.824,686.46 585.491,679.794 587,672.5C 589.072,668.26 592.238,665.26 596.5,663.5C 615.473,662.551 634.473,662.218 653.5,662.5 Z" fill="#082421"/>
</g>
<!-- Flat Architectural Telemetry Console Screen (zero gradients) -->
<rect x="43" y="130" width="170" height="94" rx="22" fill="#082421"/>
<rect x="49" y="136" width="158" height="82" rx="17" fill="#103F39" stroke="#246E64" stroke-width="3"/>
<!-- Bold Flat Telemetry Pulse Waveform -->
<path d="M67 181 L88 181 L101 156 L118 200 L135 154 L149 186 L162 173 L177 173" stroke="#34D399" stroke-width="10.5" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="186" cy="173" r="6.5" fill="#ECFDF5"/>
<!-- Netcatty Cat Paws gripping the monitor top bezel (backing stroke + crisp fill) -->
<g transform="translate(32.62 -5.48) scale(0.152)">
<path d="M 233.5,904.5 C 242.833,904.5 252.167,904.5 261.5,904.5C 263.833,904.5 266.167,904.5 268.5,904.5C 304.989,908.827 334.489,925.494 357,954.5C 374.323,977.781 379.323,1003.45 372,1031.5C 365.153,1050.01 351.986,1060.85 332.5,1064C 324.173,1064.5 315.84,1064.67 307.5,1064.5C 307.947,1050.43 307.447,1036.43 306,1022.5C 296.93,1011.58 288.263,1011.91 280,1023.5C 279.833,1038.51 279.333,1053.51 278.5,1068.5C 271.841,1075.83 263.508,1080 253.5,1081C 248.845,1081.5 244.179,1081.67 239.5,1081.5C 237.485,1080.08 235.152,1079.41 232.5,1079.5C 225.481,1077.32 219.315,1073.66 214,1068.5C 213.667,1053.5 213.333,1038.5 213,1023.5C 208.464,1016.16 201.964,1013.66 193.5,1016C 190.333,1017.83 187.833,1020.33 186,1023.5C 185.5,1037.83 185.333,1052.16 185.5,1066.5C 160.376,1072.2 140.21,1064.86 125,1044.5C 120.792,1037.38 118.292,1029.71 117.5,1021.5C 117.482,1013.15 117.815,1004.82 118.5,996.5C 129.171,955.493 154.504,927.826 194.5,913.5C 200.166,912.61 205.5,910.943 210.5,908.5C 211.568,907.566 212.901,907.232 214.5,907.5C 221.111,907.453 227.444,906.453 233.5,904.5 Z" fill="#082421" stroke="#082421" stroke-width="40" stroke-linejoin="round"/>
<path d="M 1133.5,985.5 C 1133.41,988.152 1134.08,990.485 1135.5,992.5C 1136.26,1002.48 1136.59,1012.48 1136.5,1022.5C 1133.68,1047.82 1119.68,1062.66 1094.5,1067C 1086.48,1067.61 1078.48,1067.44 1070.5,1066.5C 1070.67,1052.83 1070.5,1039.16 1070,1025.5C 1066.12,1016.96 1059.62,1013.79 1050.5,1016C 1047.33,1017.83 1044.83,1020.33 1043,1023.5C 1042.67,1038.17 1042.33,1052.83 1042,1067.5C 1035.97,1075.1 1028.14,1079.43 1018.5,1080.5C 1013.2,1081.27 1007.87,1081.61 1002.5,1081.5C 991.789,1080.39 982.955,1075.73 976,1067.5C 975.667,1052.83 975.333,1038.17 975,1023.5C 971.569,1017.53 966.402,1014.87 959.5,1015.5C 953.942,1016.72 950.275,1020.06 948.5,1025.5C 947.505,1037.99 947.171,1050.66 947.5,1063.5C 946.209,1063.26 945.209,1063.6 944.5,1064.5C 903.542,1067.19 882.208,1048.02 880.5,1007C 880.658,1002.81 880.991,998.641 881.5,994.5C 883.277,991.495 884.277,988.162 884.5,984.5C 894.73,953.43 914.73,930.93 944.5,917C 978.246,903.385 1012.91,900.718 1048.5,909C 1082.5,918.575 1108.67,938.409 1127,968.5C 1129.86,973.928 1132.03,979.595 1133.5,985.5 Z" fill="#082421" stroke="#082421" stroke-width="40" stroke-linejoin="round"/>
<path d="M 233.5,904.5 C 242.833,904.5 252.167,904.5 261.5,904.5C 263.833,904.5 266.167,904.5 268.5,904.5C 304.989,908.827 334.489,925.494 357,954.5C 374.323,977.781 379.323,1003.45 372,1031.5C 365.153,1050.01 351.986,1060.85 332.5,1064C 324.173,1064.5 315.84,1064.67 307.5,1064.5C 307.947,1050.43 307.447,1036.43 306,1022.5C 296.93,1011.58 288.263,1011.91 280,1023.5C 279.833,1038.51 279.333,1053.51 278.5,1068.5C 271.841,1075.83 263.508,1080 253.5,1081C 248.845,1081.5 244.179,1081.67 239.5,1081.5C 237.485,1080.08 235.152,1079.41 232.5,1079.5C 225.481,1077.32 219.315,1073.66 214,1068.5C 213.667,1053.5 213.333,1038.5 213,1023.5C 208.464,1016.16 201.964,1013.66 193.5,1016C 190.333,1017.83 187.833,1020.33 186,1023.5C 185.5,1037.83 185.333,1052.16 185.5,1066.5C 160.376,1072.2 140.21,1064.86 125,1044.5C 120.792,1037.38 118.292,1029.71 117.5,1021.5C 117.482,1013.15 117.815,1004.82 118.5,996.5C 129.171,955.493 154.504,927.826 194.5,913.5C 200.166,912.61 205.5,910.943 210.5,908.5C 211.568,907.566 212.901,907.232 214.5,907.5C 221.111,907.453 227.444,906.453 233.5,904.5 Z" fill="#F8FAFC"/>
<path d="M 1133.5,985.5 C 1133.41,988.152 1134.08,990.485 1135.5,992.5C 1136.26,1002.48 1136.59,1012.48 1136.5,1022.5C 1133.68,1047.82 1119.68,1062.66 1094.5,1067C 1086.48,1067.61 1078.48,1067.44 1070.5,1066.5C 1070.67,1052.83 1070.5,1039.16 1070,1025.5C 1066.12,1016.96 1059.62,1013.79 1050.5,1016C 1047.33,1017.83 1044.83,1020.33 1043,1023.5C 1042.67,1038.17 1042.33,1052.83 1042,1067.5C 1035.97,1075.1 1028.14,1079.43 1018.5,1080.5C 1013.2,1081.27 1007.87,1081.61 1002.5,1081.5C 991.789,1080.39 982.955,1075.73 976,1067.5C 975.667,1052.83 975.333,1038.17 975,1023.5C 971.569,1017.53 966.402,1014.87 959.5,1015.5C 953.942,1016.72 950.275,1020.06 948.5,1025.5C 947.505,1037.99 947.171,1050.66 947.5,1063.5C 946.209,1063.26 945.209,1063.6 944.5,1064.5C 903.542,1067.19 882.208,1048.02 880.5,1007C 880.658,1002.81 880.991,998.641 881.5,994.5C 883.277,991.495 884.277,988.162 884.5,984.5C 894.73,953.43 914.73,930.93 944.5,917C 978.246,903.385 1012.91,900.718 1048.5,909C 1082.5,918.575 1108.67,938.409 1127,968.5C 1129.86,973.928 1132.03,979.595 1133.5,985.5 Z" fill="#F8FAFC"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

@@ -1,28 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256" fill="none">
<rect x="14" y="14" width="228" height="228" rx="52" fill="#07453D"/>
<rect x="15.5" y="15.5" width="225" height="225" rx="50.5" stroke="#FFFFFF" stroke-opacity="0.28" stroke-width="3"/>
<!-- Netcatty Cat Mascot Head (flat solid ink, zero gradients) -->
<g transform="translate(32.62 -0.98) scale(0.152)">
<path d="M 618.5,240.5 C 647.925,240.677 677.258,242.344 706.5,245.5C 753.323,252.113 798.49,265.113 842,284.5C 870.064,257.538 902.23,236.704 938.5,222C 966.969,211.263 988.469,219.096 1003,245.5C 1011.08,263.079 1016.75,281.412 1020,300.5C 1022.13,320.204 1024.29,339.871 1026.5,359.5C 1026.17,379.674 1026.5,399.674 1027.5,419.5C 1072.74,473.648 1102.74,535.314 1117.5,604.5C 1117.29,607.495 1117.96,610.162 1119.5,612.5C 1126.08,656.83 1126.08,701.163 1119.5,745.5C 1118.23,747.905 1117.57,750.572 1117.5,753.5C 1107.38,802.706 1088.05,847.872 1059.5,889C 1053.04,888.572 1046.71,887.405 1040.5,885.5C 1036.79,883.864 1032.79,883.198 1028.5,883.5C 1011.79,881.938 995.122,882.271 978.5,884.5C 975.572,884.565 972.905,885.232 970.5,886.5C 928.686,895.489 896.519,918.156 874,954.5C 864.791,970.962 859.958,988.628 859.5,1007.5C 793.269,1029.39 725.269,1041.72 655.5,1044.5C 633.833,1044.5 612.167,1044.5 590.5,1044.5C 524.821,1041.8 460.821,1029.63 398.5,1008C 396.254,996.177 393.421,984.344 390,972.5C 387.524,964.881 384.024,957.881 379.5,951.5C 363.815,925.334 341.815,906.667 313.5,895.5C 297.343,888.573 280.343,884.406 262.5,883C 248.055,882.038 233.722,882.538 219.5,884.5C 216.572,884.565 213.905,885.232 211.5,886.5C 211.167,886.5 210.833,886.5 210.5,886.5C 207.848,886.41 205.515,887.076 203.5,888.5C 200.823,889.614 198.156,889.614 195.5,888.5C 149.432,819.968 128.098,744.301 131.5,661.5C 131.502,654.48 131.835,647.48 132.5,640.5C 133.461,638.735 133.795,636.735 133.5,634.5C 135.136,630.79 135.802,626.79 135.5,622.5C 137.764,609.333 140.431,596.333 143.5,583.5C 144.924,581.485 145.59,579.152 145.5,576.5C 156.228,537.714 172.395,501.381 194,467.5C 204.685,451.452 215.852,435.786 227.5,420.5C 228.042,388.62 229.375,356.62 231.5,324.5C 234.549,300.253 240.382,276.586 249,253.5C 253.868,241.906 261.035,232.073 270.5,224C 279.336,218.042 289.002,216.042 299.5,218C 314.655,220.607 328.988,225.607 342.5,233C 368.29,247.23 391.957,264.396 413.5,284.5C 478.68,255.797 547.014,241.13 618.5,240.5 Z" fill="#F9FAFB"/>
<path d="M 445.5,545.5 C 447.515,546.924 449.848,547.59 452.5,547.5C 479.103,555.885 499.269,572.218 513,596.5C 515.435,607.525 511.268,614.191 500.5,616.5C 497.302,616.378 494.302,615.545 491.5,614C 485.302,604.13 477.969,595.13 469.5,587C 459.207,579.735 447.873,574.902 435.5,572.5C 415.88,568.656 398.213,573.156 382.5,586C 374,593 367,603 362.5,613C 356.408,617.241 350.075,617.574 343.5,614C 337.996,608.137 337.163,601.637 341,594.5C 343.929,589.631 347.096,584.965 350.5,580.5C 375.329,550.884 406.995,539.218 445.5,545.5 Z" fill="#07453D"/>
<path d="M 817.5,544.5 C 862.791,541.392 895.958,559.726 917,599.5C 917.138,612.028 910.971,617.528 898.5,616C 897.167,615.333 895.833,614.667 894.5,614C 884.255,595.245 869.255,582.078 849.5,574.5C 843.812,571.54 837.645,570.207 831,570.5C 822.066,570.919 813.233,572.086 804.5,574C 792,580 778,592 767,610.5C 759.55,618.016 751.883,618.349 744,611.5C 742.878,609.593 742.045,607.593 741.5,605.5C 741.508,602.455 741.841,599.455 742.5,596.5C 757.037,569.397 779.371,552.73 809.5,546.5C 812.495,546.706 815.162,546.04 817.5,544.5 Z" fill="#07453D"/>
<path d="M 653.5,662.5 C 664.536,665.228 669.036,672.228 667,683.5C 665.861,687.112 664.194,690.446 662,693.5C 656.35,700.317 650.184,706.65 643.5,712.5C 643.058,737.755 654.725,754.922 678.5,764C 709.272,768.521 729.105,756.021 738,726.5C 747.413,717.842 755.746,718.842 763,729.5C 759.409,758.463 743.909,778.297 716.5,789C 713.111,789.776 709.778,790.609 706.5,791.5C 697.533,792.383 688.533,792.716 679.5,792.5C 657.328,788.994 639.828,777.994 627,759.5C 607.084,786.202 580.584,797.035 547.5,792C 516.901,784.235 497.901,765.068 490.5,734.5C 493.257,721.955 500.59,718.121 512.5,723C 517.164,727.124 519.998,732.291 521,738.5C 533.515,761.003 552.348,769.17 577.5,763C 599.78,754.048 610.947,737.548 611,713.5C 604.698,706.197 598.032,699.197 591,692.5C 586.824,686.46 585.491,679.794 587,672.5C 589.072,668.26 592.238,665.26 596.5,663.5C 615.473,662.551 634.473,662.218 653.5,662.5 Z" fill="#07453D"/>
</g>
<!-- Flat Architectural Telemetry Console Screen (zero gradients) -->
<rect x="43" y="130" width="170" height="94" rx="22" fill="#07453D"/>
<rect x="49" y="136" width="158" height="82" rx="17" fill="#0F6E61" stroke="#1A8A7A" stroke-width="3"/>
<!-- Bold Flat Telemetry Pulse Waveform -->
<path d="M67 181 L88 181 L101 156 L118 200 L135 154 L149 186 L162 173 L177 173" stroke="#A7F3D0" stroke-width="10.5" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="186" cy="173" r="6.5" fill="#FFFFFF"/>
<!-- Netcatty Cat Paws gripping the monitor top bezel (backing stroke + crisp fill) -->
<g transform="translate(32.62 -5.48) scale(0.152)">
<path d="M 233.5,904.5 C 242.833,904.5 252.167,904.5 261.5,904.5C 263.833,904.5 266.167,904.5 268.5,904.5C 304.989,908.827 334.489,925.494 357,954.5C 374.323,977.781 379.323,1003.45 372,1031.5C 365.153,1050.01 351.986,1060.85 332.5,1064C 324.173,1064.5 315.84,1064.67 307.5,1064.5C 307.947,1050.43 307.447,1036.43 306,1022.5C 296.93,1011.58 288.263,1011.91 280,1023.5C 279.833,1038.51 279.333,1053.51 278.5,1068.5C 271.841,1075.83 263.508,1080 253.5,1081C 248.845,1081.5 244.179,1081.67 239.5,1081.5C 237.485,1080.08 235.152,1079.41 232.5,1079.5C 225.481,1077.32 219.315,1073.66 214,1068.5C 213.667,1053.5 213.333,1038.5 213,1023.5C 208.464,1016.16 201.964,1013.66 193.5,1016C 190.333,1017.83 187.833,1020.33 186,1023.5C 185.5,1037.83 185.333,1052.16 185.5,1066.5C 160.376,1072.2 140.21,1064.86 125,1044.5C 120.792,1037.38 118.292,1029.71 117.5,1021.5C 117.482,1013.15 117.815,1004.82 118.5,996.5C 129.171,955.493 154.504,927.826 194.5,913.5C 200.166,912.61 205.5,910.943 210.5,908.5C 211.568,907.566 212.901,907.232 214.5,907.5C 221.111,907.453 227.444,906.453 233.5,904.5 Z" fill="#07453D" stroke="#07453D" stroke-width="40" stroke-linejoin="round"/>
<path d="M 1133.5,985.5 C 1133.41,988.152 1134.08,990.485 1135.5,992.5C 1136.26,1002.48 1136.59,1012.48 1136.5,1022.5C 1133.68,1047.82 1119.68,1062.66 1094.5,1067C 1086.48,1067.61 1078.48,1067.44 1070.5,1066.5C 1070.67,1052.83 1070.5,1039.16 1070,1025.5C 1066.12,1016.96 1059.62,1013.79 1050.5,1016C 1047.33,1017.83 1044.83,1020.33 1043,1023.5C 1042.67,1038.17 1042.33,1052.83 1042,1067.5C 1035.97,1075.1 1028.14,1079.43 1018.5,1080.5C 1013.2,1081.27 1007.87,1081.61 1002.5,1081.5C 991.789,1080.39 982.955,1075.73 976,1067.5C 975.667,1052.83 975.333,1038.17 975,1023.5C 971.569,1017.53 966.402,1014.87 959.5,1015.5C 953.942,1016.72 950.275,1020.06 948.5,1025.5C 947.505,1037.99 947.171,1050.66 947.5,1063.5C 946.209,1063.26 945.209,1063.6 944.5,1064.5C 903.542,1067.19 882.208,1048.02 880.5,1007C 880.658,1002.81 880.991,998.641 881.5,994.5C 883.277,991.495 884.277,988.162 884.5,984.5C 894.73,953.43 914.73,930.93 944.5,917C 978.246,903.385 1012.91,900.718 1048.5,909C 1082.5,918.575 1108.67,938.409 1127,968.5C 1129.86,973.928 1132.03,979.595 1133.5,985.5 Z" fill="#07453D" stroke="#07453D" stroke-width="40" stroke-linejoin="round"/>
<path d="M 233.5,904.5 C 242.833,904.5 252.167,904.5 261.5,904.5C 263.833,904.5 266.167,904.5 268.5,904.5C 304.989,908.827 334.489,925.494 357,954.5C 374.323,977.781 379.323,1003.45 372,1031.5C 365.153,1050.01 351.986,1060.85 332.5,1064C 324.173,1064.5 315.84,1064.67 307.5,1064.5C 307.947,1050.43 307.447,1036.43 306,1022.5C 296.93,1011.58 288.263,1011.91 280,1023.5C 279.833,1038.51 279.333,1053.51 278.5,1068.5C 271.841,1075.83 263.508,1080 253.5,1081C 248.845,1081.5 244.179,1081.67 239.5,1081.5C 237.485,1080.08 235.152,1079.41 232.5,1079.5C 225.481,1077.32 219.315,1073.66 214,1068.5C 213.667,1053.5 213.333,1038.5 213,1023.5C 208.464,1016.16 201.964,1013.66 193.5,1016C 190.333,1017.83 187.833,1020.33 186,1023.5C 185.5,1037.83 185.333,1052.16 185.5,1066.5C 160.376,1072.2 140.21,1064.86 125,1044.5C 120.792,1037.38 118.292,1029.71 117.5,1021.5C 117.482,1013.15 117.815,1004.82 118.5,996.5C 129.171,955.493 154.504,927.826 194.5,913.5C 200.166,912.61 205.5,910.943 210.5,908.5C 211.568,907.566 212.901,907.232 214.5,907.5C 221.111,907.453 227.444,906.453 233.5,904.5 Z" fill="#F9FAFB"/>
<path d="M 1133.5,985.5 C 1133.41,988.152 1134.08,990.485 1135.5,992.5C 1136.26,1002.48 1136.59,1012.48 1136.5,1022.5C 1133.68,1047.82 1119.68,1062.66 1094.5,1067C 1086.48,1067.61 1078.48,1067.44 1070.5,1066.5C 1070.67,1052.83 1070.5,1039.16 1070,1025.5C 1066.12,1016.96 1059.62,1013.79 1050.5,1016C 1047.33,1017.83 1044.83,1020.33 1043,1023.5C 1042.67,1038.17 1042.33,1052.83 1042,1067.5C 1035.97,1075.1 1028.14,1079.43 1018.5,1080.5C 1013.2,1081.27 1007.87,1081.61 1002.5,1081.5C 991.789,1080.39 982.955,1075.73 976,1067.5C 975.667,1052.83 975.333,1038.17 975,1023.5C 971.569,1017.53 966.402,1014.87 959.5,1015.5C 953.942,1016.72 950.275,1020.06 948.5,1025.5C 947.505,1037.99 947.171,1050.66 947.5,1063.5C 946.209,1063.26 945.209,1063.6 944.5,1064.5C 903.542,1067.19 882.208,1048.02 880.5,1007C 880.658,1002.81 880.991,998.641 881.5,994.5C 883.277,991.495 884.277,988.162 884.5,984.5C 894.73,953.43 914.73,930.93 944.5,917C 978.246,903.385 1012.91,900.718 1048.5,909C 1082.5,918.575 1108.67,938.409 1127,968.5C 1129.86,973.928 1132.03,979.595 1133.5,985.5 Z" fill="#F9FAFB"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 9.4 KiB

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 24 24" fill="none" stroke="#0ea5e9" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="16" height="16" x="4" y="4" rx="1.5"></rect><rect width="6" height="6" x="9" y="9" rx="0.5"></rect><path d="M15 2v2"></path><path d="M15 20v2"></path><path d="M2 15h2"></path><path d="M2 9h2"></path><path d="M20 15h2"></path><path d="M20 9h2"></path><path d="M9 2v2"></path><path d="M9 20v2"></path></svg>

Before

Width:  |  Height:  |  Size: 517 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"></circle><line x1="12" x2="12" y1="8" y2="12"></line><line x1="12" x2="12.01" y1="16" y2="16"></line></svg>

Before

Width:  |  Height:  |  Size: 337 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 24 24" fill="none" stroke="#64748b" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="20" height="8" x="2" y="2" rx="1.5"></rect><rect width="20" height="8" x="2" y="14" rx="1.5"></rect><line x1="6" x2="6.01" y1="6" y2="6"></line><line x1="6" x2="6.01" y1="18" y2="18"></line></svg>

Before

Width:  |  Height:  |  Size: 408 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 24 24" fill="none" stroke="#8b5cf6" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 19v-3"></path><path d="M10 19v-3"></path><path d="M14 19v-3"></path><path d="M18 19v-3"></path><path d="M8 11V9"></path><path d="M16 11V9"></path><path d="M12 11V9"></path><path d="M2 15h20"></path><path d="M2 7a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v1.1a2 2 0 0 0 0 3.837V17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5.1a2 2 0 0 0 0-3.837Z"></path></svg>

Before

Width:  |  Height:  |  Size: 547 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"></path></svg>

Before

Width:  |  Height:  |  Size: 345 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"></path><path d="M12 9v4"></path><path d="M12 17h.01"></path></svg>

Before

Width:  |  Height:  |  Size: 348 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 325 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 506 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 294 KiB

@@ -1,96 +0,0 @@
{
"manifestVersion": 1,
"id": "com.binaricat.netcatty-monitor",
"name": "netcatty-monitor",
"displayName": {
"en": "Netcatty Monitor",
"zh-CN": "Netcatty 监控"
},
"description": {
"en": "Agentless SSH fleet monitoring and server operations workbench inside Netcatty with real-time CPU, memory, disk I/O, network, GPU & thermal charts, live process explorer, systemd/Docker/Podman services & log tails, listening ports, and configurable threshold alerts.",
"zh-CN": "内置于 Netcatty 的无 Agent SSH 服务器集群监控与运维工作台,提供实时 CPU、内存、磁盘 I/O、网络、GPU 与温度曲线,以及实时进程管理、systemd/Docker/Podman 服务与日志查看、监听端口分析与可配置阈值告警。"
},
"version": "0.1.0",
"publisher": "binaricat",
"license": "GPL-3.0-or-later",
"homepage": "https://github.com/binaricat/netcatty-monitor-plugin",
"repository": "https://github.com/binaricat/netcatty-monitor-plugin",
"engines": {
"netcatty": ">=0.0.0",
"api": ">=0.1.0-internal.1 <0.2.0"
},
"features": {
"required": [
"views.host-drawn",
"views.vault-pages",
"metadata.brand-icon",
"vault.host-actions",
"vault.host-exec",
"vault.host-probe",
"host.interactions"
]
},
"main": {
"browser": "browser.js"
},
"activationEvents": [
"onView:com.binaricat.netcatty-monitor.workbench"
],
"permissions": {
"required": [
"views"
],
"optional": [
"storage",
{
"permission": "vault.metadata",
"resources": [
"*"
],
"reason": "Select saved Netcatty Vault hosts and refresh host labels, tags, and groups for monitoring panels / 选择已保存的 Netcatty Vault 主机并刷新监控面板中的主机标签、分组与元信息"
},
{
"permission": "vault.hostExec",
"resources": [
"*"
],
"reason": "Run bounded telemetry, process, service, container, and port inspection commands over pooled SSH connections without exposing credentials / 通过宿主复用的 SSH 连接执行受限监控采集与运维诊断命令,不暴露主机凭证"
},
{
"permission": "ui.interact",
"resources": [
"*"
],
"reason": "Export monitoring snapshots as JSON files via native save dialogs / 通过原生保存对话框导出监控快照 JSON 文件"
},
{
"permission": "clipboard.write",
"resources": [
"*"
],
"reason": "Copy process commands, host info, and diagnostic log lines to the clipboard / 复制进程命令行、主机信息与诊断日志到剪贴板"
}
]
},
"contributes": {
"views": [
{
"id": "com.binaricat.netcatty-monitor.workbench",
"title": {
"en": "Monitor",
"zh-CN": "监控"
},
"location": "vault-page",
"icon": {
"kind": "theme",
"name": "activity"
}
}
]
},
"icon": {
"kind": "package",
"light": "assets/plugin-icon-light.png",
"dark": "assets/plugin-icon-dark.png"
}
}
-18
View File
@@ -1,18 +0,0 @@
{
"name": "netcatty-monitor",
"version": "0.1.0",
"private": true,
"license": "GPL-3.0-or-later",
"type": "module",
"engines": {
"node": ">=22"
},
"scripts": {
"lint": "tsc --noEmit && node scripts/check-assets.mjs && node scripts/check-host-policy.mjs",
"test": "node --test --import tsx tests/*.test.ts tests/*.test.tsx",
"build": "node scripts/build.mjs",
"pack": "npm run build && node scripts/pack.mjs",
"validate": "node scripts/validate.mjs",
"test:electron": "../../node_modules/.bin/electron scripts/smoke-electron.cjs"
}
}
@@ -1,48 +0,0 @@
import { build } from 'esbuild';
import { mkdir, cp, readFile, writeFile, rm, readdir } from 'node:fs/promises';
import path from 'node:path';
await rm('dist/package', { recursive: true, force: true });
await mkdir('dist/package', { recursive: true });
const result = await build({
entryPoints: { browser: 'src/index.tsx' },
outdir: 'dist/package',
entryNames: '[name]',
chunkNames: 'chunks/[name]-[hash]',
splitting: true,
bundle: true,
minify: true,
format: 'esm',
platform: 'browser',
target: 'es2022',
loader: { '.css': 'text' },
define: { 'process.env.NODE_ENV': '"production"' },
legalComments: 'eof',
metafile: true,
});
await writeFile('dist/build-inputs.json', JSON.stringify(result.metafile, null, 2));
for (const file of ['netcatty.plugin.json', 'LICENSE', 'README.md']) {
await cp(file, `dist/package/${file}`);
}
await cp('assets', 'dist/package/assets', { recursive: true });
async function checkNoDynamicEval(dir) {
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
await checkNoDynamicEval(full);
} else if (entry.name.endsWith('.js')) {
const code = await readFile(full, 'utf8');
if (/\b(?:eval|new Function)\(/.test(code)) {
throw new Error(`Dynamic evaluation in plugin bundle: ${full}`);
}
}
}
}
await checkNoDynamicEval('dist/package');
console.log('Built plugins/netcatty-monitor -> dist/package');
@@ -1,40 +0,0 @@
import { readdir, readFile } from 'node:fs/promises';
import path from 'node:path';
import { inspectPluginBrandIcon } from '@netcatty/plugin-contract';
function assertSafeSvg(svg, label) {
if (
/<(?:script|image|foreignObject|use|style)\b|(?:href|on\w+)\s*=|url\(/i.test(
svg.replace(/url\(#[a-zA-Z0-9_-]+\)/g, 'local-gradient'),
)
) {
throw new Error(`Unsafe plugin SVG: ${label}`);
}
}
for (const theme of ['light', 'dark']) {
const svgPath = `assets/plugin-icon-${theme}.svg`;
const pngPath = `assets/plugin-icon-${theme}.png`;
const svg = await readFile(svgPath, 'utf8');
assertSafeSvg(svg, svgPath);
const png = await readFile(pngPath);
const { width, height } = inspectPluginBrandIcon(png, pngPath);
if (width !== 256 || height !== 256) {
throw new Error(`Unexpected plugin brand icon size (${width}x${height}): ${pngPath}`);
}
}
const uiDir = 'assets/ui';
const uiEntries = (await readdir(uiDir)).filter((f) => f.endsWith('.svg')).sort();
if (uiEntries.length < 6) {
throw new Error(`Expected >= 6 UI icons in ${uiDir}, found ${uiEntries.length}`);
}
for (const file of uiEntries) {
const full = path.join(uiDir, file);
const svg = await readFile(full, 'utf8');
assertSafeSvg(svg, full);
}
console.log(
`Validated 2 custom Netcatty Monitor brand icons (256x256 PNG+SVG) + ${uiEntries.length} UI icons (${uiDir})`,
);
@@ -1,12 +0,0 @@
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const { validatePluginStylesheet, MAX_CSS_LENGTH } = require('../../../domain/pluginViewStylePolicy.cjs');
const css = await readFile('src/style.css', 'utf8');
if (Buffer.byteLength(css, 'utf8') > MAX_CSS_LENGTH) {
throw new Error(`src/style.css exceeds MAX_CSS_LENGTH (${MAX_CSS_LENGTH} bytes)`);
}
validatePluginStylesheet(css);
console.log(`Netcatty host stylesheet policy passed (${Buffer.byteLength(css, 'utf8')} bytes)`);
-19
View File
@@ -1,19 +0,0 @@
import { packPlugin, validateTarget, checkPluginCompatibility } from '@netcatty/plugin-cli';
import { writeFile } from 'node:fs/promises';
const stage = await validateTarget('dist/package');
const features = stage.manifest.features?.required ?? [];
const compat = checkPluginCompatibility(stage.manifest, {
netcattyVersion: '0.0.0',
apiVersion: '0.1.0-internal.1',
features,
});
if (!compat.compatible) {
throw new Error(compat.errors.join('\n'));
}
const fileName = `netcatty-monitor-${stage.manifest.version}.ncpkg`;
const result = await packPlugin('dist/package', `dist/${fileName}`);
await validateTarget(result.outputPath);
await writeFile('dist/SHA256SUMS', `${result.sha256} ${fileName}\n`);
console.log(`Validated ${result.fileCount} files: ${result.outputPath}\nSHA256 ${result.sha256}`);
@@ -1,341 +0,0 @@
"use strict";
/**
* Real Electron end-to-end smoke test for com.binaricat.netcatty-monitor.
* Exercises:
* 1. Installing dist/netcatty-monitor-0.1.0.ncpkg into Netcatty's real PluginHostService.
* 2. Opening the host-drawn Vault view via HostDrawnViewHost.open() in a sandboxed BrowserWindow.
* 3. Validating initial Remote DOM mutations, canonical CSS, split-pane widget, and brand icon PNG decode.
* 4. Clicking "+ Add Hosts" -> real vault.selectHosts({ durable: true }) issuing an hb_* binding token
* -> real vault.execHostCommand via PluginHostVaultService + mock sshExecTransport
* -> verifying live Linux host telemetry renders PluginMetricChart ("metric-chart") widgets!
*/
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const electron = require("electron");
const pluginRoot = path.resolve(__dirname, "..");
const appRoot = path.resolve(pluginRoot, "../..");
const archivePath = path.join(pluginRoot, "dist", "netcatty-monitor-0.1.0.ncpkg");
const { createPluginHostService } = require(path.join(appRoot, "electron/plugins/hostService.cjs"));
const { PLUGIN_PROTOCOL_SCHEME } = require(path.join(appRoot, "electron/plugins/constants.cjs"));
const { validatePluginMutationBatch } = require(path.join(appRoot, "domain/pluginRemoteTreePolicy.cjs"));
const userData = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-monitor-smoke-"));
electron.app.setPath("userData", userData);
electron.app.on("window-all-closed", () => {});
electron.protocol.registerSchemesAsPrivileged([
{
scheme: PLUGIN_PROTOCOL_SCHEME,
privileges: { standard: true, secure: true, supportFetchAPI: true, codeCache: true },
},
]);
function flattenStrings(value, out = []) {
if (typeof value === "string") {
out.push(value);
} else if (Array.isArray(value)) {
for (const item of value) flattenStrings(item, out);
} else if (value && typeof value === "object") {
for (const v of Object.values(value)) flattenStrings(v, out);
}
return out;
}
function findButtonNodeIdByText(node, match) {
if (!node || typeof node !== "object") return null;
if (node.element === "button") {
const text = flattenStrings(node.children).join(" ");
if (text.includes(match)) return node.id;
}
if (Array.isArray(node.children)) {
for (const child of node.children) {
const found = findButtonNodeIdByText(child, match);
if (found) return found;
}
}
return null;
}
function findButtonIdInMutations(updates, match) {
for (const update of updates) {
for (const mutation of update.mutations || []) {
if (Array.isArray(mutation) && mutation[0] === 0 && mutation[2]) {
const found = findButtonNodeIdByText(mutation[2], match);
if (found) return found;
}
}
}
return null;
}
void electron.app
.whenReady()
.then(async () => {
assert.ok(fs.existsSync(archivePath), `Missing built archive: ${archivePath}`);
const runtimeAppRoot = path.join(userData, "runtime-app");
const runtimeDirectory = path.join(runtimeAppRoot, "electron/plugins/runtime");
for (const name of ["plugin-contract", "plugin-sdk"]) {
fs.cpSync(
path.join(appRoot, "packages", name, "dist"),
path.join(runtimeAppRoot, "node_modules/@netcatty", name, "dist"),
{ recursive: true },
);
fs.cpSync(
path.join(appRoot, "packages", name, "package.json"),
path.join(runtimeAppRoot, "node_modules/@netcatty", name, "package.json"),
);
}
fs.cpSync(path.join(appRoot, "electron/plugins/runtime"), runtimeDirectory, { recursive: true });
let execCount = 0;
const mockHostRecord = {
resourceId: "host-smoke-1",
revision: "rev-1",
label: "prod-smoke-01",
hostname: "10.0.42.10",
username: "ops",
port: 22,
group: "Production",
tags: ["web", "smoke"],
protocol: "ssh",
os: "Ubuntu 24.04",
notes: "Electron smoke test host",
};
const mockVaultDataBridge = {
async resolveMetadata(hostIds) {
return hostIds.map((id) =>
id === mockHostRecord.resourceId
? { resourceId: id, found: true, metadata: { ...mockHostRecord } }
: { resourceId: id, found: false },
);
},
async prepareConnection(hostId) {
assert.equal(hostId, mockHostRecord.resourceId);
return {
hostId,
hostname: mockHostRecord.hostname,
port: 22,
username: "ops",
};
},
invalidate() {},
shutdown() {},
};
const mockSshExecTransport = {
async exec({ command }) {
execCount += 1;
if (command.includes('DISKS:$disks')) {
return {
stdout: "DISKS:/:42.5:100.0:43:fs=ext4:/dev/nvme0n1p1|INODES:/:18400:100000:18",
stderr: "",
exitCode: 0,
truncated: false,
durationMs: 9,
latencyMs: 14,
responseLatencyMs: 17,
};
}
if (command.includes("nvidia-smi")) {
return {
stdout: "GPU:58 4096 16384 NVIDIA L4 ;; 0\tNVIDIA L4\t58\t4096\t16384\t55\t68.0",
stderr: "",
exitCode: 0,
truncated: false,
durationMs: 7,
latencyMs: 14,
responseLatencyMs: 16,
};
}
return {
stdout:
"OSFAM:linux|CPURAW:2400 1200 10 2 900 288|CPUEXTRA:12000 4500 2 0|CORES:4|PERCORERAW:600:300,600:300,600:300,600:300|MEMINFO:16384 4096 512 2048 2048 2048 4096 1024|NET:eth0:500000:250000:1200:800:0:0:0:0|TCPRETRANS:0|DISKIO:100.0;nvme0n1:100:200:50:60:400:1|PARTITIONIO:|DISKMOUNTS:|FD:2048:65536|USERS:2|REBOOT:0|THERMALS:x86_pkg_temp:52000|HOST:prod-smoke-01|OS:Ubuntu 24.04 LTS|KERNEL:6.8.0|UPTIME:7200|LOAD:0.55 0.48 0.40",
stderr: "",
exitCode: 0,
truncated: false,
durationMs: 14,
latencyMs: 225,
responseLatencyMs: 225,
};
},
releaseHost() {},
releaseRuntime() {},
releasePlugin() {},
closeAll() {},
shutdown() {},
};
let owner = null;
const service = createPluginHostService({
app: electron.app,
electron,
appRoot: runtimeAppRoot,
runtimeDirectory,
vaultDataBridge: mockVaultDataBridge,
sshExecTransport: mockSshExecTransport,
getInteractionWindow: () => owner,
isAppLocked: () => false,
supportedFeatures: [
"views.host-drawn",
"views.vault-pages",
"views.badges",
"metadata.brand-icon",
"vault.host-actions",
"vault.host-exec",
"vault.host-probe",
"host.interactions",
],
requestPermissionDecision: async (request) => ({
requestId: request.requestId,
decision: "allow",
scope: "application",
}),
});
await service.manager.initialize();
const installed = await service.manager.install(archivePath, { enable: true });
assert.equal(installed.manifest.id, "com.binaricat.netcatty-monitor");
owner = new electron.BrowserWindow({
show: false,
width: 1200,
height: 800,
webPreferences: { sandbox: true, contextIsolation: true },
});
owner.isVisible = () => true;
owner.isFocused = () => true;
await owner.loadURL("about:blank");
service.interactionService.setReady(owner.webContents, true);
const updates = [];
const origSend = owner.webContents.send.bind(owner.webContents);
owner.webContents.send = (channel, payload, ...rest) => {
if (channel === "netcatty:plugins:host-ui-update") {
validatePluginMutationBatch(payload.mutations);
updates.push(payload);
} else if (channel === "netcatty:plugins:host-interaction" && payload?.request?.kind === "vault.selectHosts") {
setTimeout(() => {
service.interactionService.respond(owner.webContents, {
requestId: payload.requestId,
actionToken: payload.actionToken,
action: "submit",
resources: [mockHostRecord],
}).catch((err) => console.error("INTERACTION_RESPOND_ERR:", err));
}, 10);
}
return origSend(channel, payload, ...rest);
};
const instanceId = "monitor-smoke-1";
const opened = await service.hostDrawnViewHost.open(
{
instanceId,
viewId: "com.binaricat.netcatty-monitor.workbench",
scopeId: "vault:smoke",
context: {},
},
owner.webContents,
);
assert.equal(opened.instanceId, instanceId);
const deadline = Date.now() + 10_000;
while (Date.now() < deadline && updates.length === 0) {
await new Promise((r) => setTimeout(r, 50));
}
assert.ok(updates.length > 0, "Monitor plugin failed to emit initial host-ui-update within 10s");
const first = updates[0];
assert.equal(first.viewId, "com.binaricat.netcatty-monitor.workbench");
assert.ok(typeof first.css === "string" && first.css.length > 1000 && first.css.length < 128 * 1024);
// Verify package brand icon PNG + monochrome KPI SVG icon decode through host ViewResourceService
const iconResult = await service.hostDrawnViewHost.resource(instanceId, "assets/plugin-icon-dark.png", owner.webContents);
assert.ok(typeof iconResult?.url === "string" && iconResult.url.startsWith("data:image/png;base64,"));
const kpiIconResult = await service.hostDrawnViewHost.resource(instanceId, "assets/ui/hosts.svg", owner.webContents);
assert.ok(typeof kpiIconResult?.url === "string" && kpiIconResult.url.startsWith("data:image/png;base64,"));
// Click "+ Add Hosts" inside the mounted Monitor workbench to trigger durable selectHosts + live SSH exec + PluginMetricChart
const addHostsButtonId =
findButtonIdInMutations(updates, "Add Hosts") ||
findButtonIdInMutations(updates, "Select Vault Hosts") ||
findButtonIdInMutations(updates, "添加主机");
assert.ok(addHostsButtonId, "Could not locate Add Hosts button in initial Remote DOM mutations");
// Wait briefly for initial storage hydration so panel state is ready
await new Promise((r) => setTimeout(r, 250));
await service.hostDrawnViewHost.event(instanceId, { type: "click", nodeId: addHostsButtonId }, owner.webContents);
// Wait for durable binding + vault.execHostCommand + PluginMetricChart (poll 1)
const execDeadline = Date.now() + 8000;
let sawMetricChart = false;
let sawLiveHost = false;
while (Date.now() < execDeadline) {
const joined = flattenStrings(updates.map((u) => u.mutations)).join(" ");
sawMetricChart = joined.includes("metric-chart");
sawLiveHost = joined.includes("prod-smoke-01") && joined.includes("Ubuntu 24.04");
if (sawMetricChart && sawLiveHost && execCount >= 2) break;
await new Promise((r) => setTimeout(r, 80));
}
assert.ok(execCount >= 2, `Expected live vault.execHostCommand calls (primary + disk/gpu), got ${execCount}`);
assert.equal(sawMetricChart, true, "Expected PluginMetricChart ('metric-chart') widget in live host mutations");
assert.equal(sawLiveHost, true, "Expected live parsed host telemetry ('prod-smoke-01' / 'Ubuntu 24.04') in host mutations");
// Default hysteresis (consecutivePolls = 2) suppresses a single latency spike; trigger Refresh for poll 2
const refreshButtonId =
findButtonIdInMutations(updates, "Refresh") || findButtonIdInMutations(updates, "刷新");
assert.ok(refreshButtonId, "Could not locate Refresh button in Remote DOM mutations");
const execCountBeforeRefresh = execCount;
await service.hostDrawnViewHost.event(instanceId, { type: "click", nodeId: refreshButtonId }, owner.webContents);
const badgeDeadline = Date.now() + 8000;
let liveBadge = null;
while (Date.now() < badgeDeadline) {
const badges = service.viewBadgeService?.listBadges?.() ?? [];
liveBadge = badges.find((b) => b.viewId === "com.binaricat.netcatty-monitor.workbench") ?? null;
if (execCount > execCountBeforeRefresh && liveBadge && liveBadge.count >= 1) break;
await new Promise((r) => setTimeout(r, 80));
}
assert.ok(execCount > execCountBeforeRefresh, `Expected 2nd poll after Refresh click, execCount stayed at ${execCount}`);
assert.ok(liveBadge && liveBadge.count >= 1 && liveBadge.tone === "warning", `Expected live sidebar badge via views.setBadge after 2 consecutive breaches, got: ${JSON.stringify(liveBadge)}`);
await service.hostDrawnViewHost.close(instanceId, owner.webContents, "smoke-complete");
await new Promise((r) => setTimeout(r, 150));
const badgesAfterClose = service.viewBadgeService?.listBadges?.() ?? [];
const remainingBadge = badgesAfterClose.find((b) => b.viewId === "com.binaricat.netcatty-monitor.workbench") ?? null;
assert.equal(remainingBadge, null, `Expected sidebar badge to clear on view close, got: ${JSON.stringify(remainingBadge)}`);
owner.destroy();
await service.manager.shutdown();
fs.rmSync(userData, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });
console.log(
JSON.stringify({
status: "MONITOR_ELECTRON_SMOKE_OK",
pluginId: installed.manifest.id,
version: installed.manifest.version,
updatesReceived: updates.length,
canonicalCssBytes: first.css.length,
iconDecoded: true,
sshExecCalls: execCount,
sawMetricChart,
sawLiveHost,
liveBadgeCount: liveBadge.count,
liveBadgeTone: liveBadge.tone,
badgeClearedOnClose: true,
}),
);
electron.app.exit(0);
})
.catch((error) => {
console.error("MONITOR_ELECTRON_SMOKE_FAILED:", error);
try {
fs.rmSync(userData, { recursive: true, force: true });
} catch {}
electron.app.exit(1);
});
@@ -1,5 +0,0 @@
import { validateTarget } from '@netcatty/plugin-cli';
const target = process.argv[2] || 'dist/netcatty-monitor-0.1.0.ncpkg';
const result = await validateTarget(target);
console.log(`Validated ${result.manifest.id}@${result.manifest.version}: ${target}`);
-4
View File
@@ -1,4 +0,0 @@
declare module '*.css' {
const css: string;
export default css;
}
@@ -1,337 +0,0 @@
import { formatMemoryPercent } from './formatting';
import type {
AlertEvent,
AlertMetric,
AlertSeverity,
AlertThresholds,
HealthSummary,
HostRuntimeState,
} from './types';
export const DEFAULT_ALERT_THRESHOLDS: AlertThresholds = {
cpuWarning: 80,
cpuCritical: 95,
iowaitWarning: 20,
iowaitCritical: 40,
memoryWarning: 85,
memoryCritical: 95,
swapWarning: 60,
swapCritical: 85,
diskWarning: 80,
diskCritical: 92,
inodeWarning: 80,
inodeCritical: 95,
loadPerCoreWarning: 1.5,
loadPerCoreCritical: 3.0,
netDropsWarning: 10,
netDropsCritical: 100,
latencyWarningMs: 180,
latencyCriticalMs: 400,
consecutivePolls: 2,
alertOnOffline: true,
};
export function normalizeAlertThresholds(raw: unknown): AlertThresholds {
if (!raw || typeof raw !== 'object') return { ...DEFAULT_ALERT_THRESHOLDS };
const r = raw as Record<string, unknown>;
const num = (key: keyof AlertThresholds, min: number, max: number) => {
const val = Number(r[key]);
const fallback = DEFAULT_ALERT_THRESHOLDS[key] as number;
return Number.isFinite(val) ? Math.max(min, Math.min(max, val)) : fallback;
};
return {
cpuWarning: num('cpuWarning', 10, 100),
cpuCritical: num('cpuCritical', 10, 100),
iowaitWarning: num('iowaitWarning', 5, 100),
iowaitCritical: num('iowaitCritical', 10, 100),
memoryWarning: num('memoryWarning', 10, 100),
memoryCritical: num('memoryCritical', 10, 100),
swapWarning: num('swapWarning', 10, 100),
swapCritical: num('swapCritical', 10, 100),
diskWarning: num('diskWarning', 10, 100),
diskCritical: num('diskCritical', 10, 100),
inodeWarning: num('inodeWarning', 10, 100),
inodeCritical: num('inodeCritical', 10, 100),
loadPerCoreWarning: num('loadPerCoreWarning', 0.2, 20),
loadPerCoreCritical: num('loadPerCoreCritical', 0.5, 40),
netDropsWarning: num('netDropsWarning', 1, 100_000),
netDropsCritical: num('netDropsCritical', 5, 1_000_000),
latencyWarningMs: num('latencyWarningMs', 20, 5000),
latencyCriticalMs: num('latencyCriticalMs', 50, 10000),
consecutivePolls: Math.round(num('consecutivePolls', 1, 10)),
alertOnOffline: typeof r.alertOnOffline === 'boolean' ? r.alertOnOffline : DEFAULT_ALERT_THRESHOLDS.alertOnOffline,
};
}
export interface EvaluatedViolation {
metric: AlertMetric;
severity: AlertSeverity;
value: number | null;
threshold: number | null;
label: string;
}
export function evaluateHostHealth(
state: HostRuntimeState | undefined,
thresholds: AlertThresholds = DEFAULT_ALERT_THRESHOLDS,
): { health: HealthSummary; violations: EvaluatedViolation[] } {
if (!state || state.status === 'idle' || state.status === 'queued' || state.status === 'connecting') {
return {
health: { score: 100, level: 'pending', badges: [] },
violations: [],
};
}
if (state.status === 'offline' || state.status === 'error' || state.status === 'disconnected' || state.status === 'login') {
const violations: EvaluatedViolation[] = thresholds.alertOnOffline
? [{ metric: 'offline', severity: 'critical', value: null, threshold: null, label: state.status.toUpperCase() }]
: [];
return {
health: {
score: 0,
level: 'offline',
badges: violations.map((v) => ({ metric: v.metric, severity: v.severity, label: v.label })),
},
violations,
};
}
if (state.mode === 'probe' && state.probe) {
const violations: EvaluatedViolation[] = [];
let penalty = 0;
const rtt = state.probe.rttMs;
if (rtt != null && Number.isFinite(rtt)) {
if (rtt >= thresholds.latencyCriticalMs) {
violations.push({ metric: 'latencyMs', severity: 'critical', value: rtt, threshold: thresholds.latencyCriticalMs, label: `${Math.round(rtt)}ms` });
penalty += 30;
} else if (rtt >= thresholds.latencyWarningMs) {
violations.push({ metric: 'latencyMs', severity: 'warning', value: rtt, threshold: thresholds.latencyWarningMs, label: `${Math.round(rtt)}ms` });
penalty += 14;
}
}
const score = Math.max(0, Math.min(100, 100 - penalty));
const level: HealthSummary['level'] = violations.some((v) => v.severity === 'critical')
? 'critical'
: violations.some((v) => v.severity === 'warning')
? 'warning'
: 'healthy';
return {
health: {
score,
level,
badges: violations.map((v) => ({ metric: v.metric, severity: v.severity, label: v.label })),
},
violations,
};
}
if (!state.stats) {
return {
health: { score: 100, level: 'pending', badges: [] },
violations: [],
};
}
const stats = state.stats;
const violations: EvaluatedViolation[] = [];
let penalty = 0;
const checkUpper = (
metric: AlertMetric,
value: number | null | undefined,
warn: number,
crit: number,
format: (v: number) => string,
) => {
if (value == null || !Number.isFinite(value)) return;
if (value >= crit) {
violations.push({ metric, severity: 'critical', value, threshold: crit, label: format(value) });
penalty += 30;
} else if (value >= warn) {
violations.push({ metric, severity: 'warning', value, threshold: warn, label: format(value) });
penalty += 14;
}
};
checkUpper('cpu', stats.cpu, thresholds.cpuWarning, thresholds.cpuCritical, (v) => `CPU ${Math.round(v)}%`);
checkUpper('cpuIowait', stats.cpuIowait, thresholds.iowaitWarning, thresholds.iowaitCritical, (v) => `IOWAIT ${v.toFixed(1)}%`);
const memPct = formatMemoryPercent(stats.memUsed, stats.memTotal);
checkUpper('memory', memPct, thresholds.memoryWarning, thresholds.memoryCritical, (v) => `MEM ${Math.round(v)}%`);
const swapPct = formatMemoryPercent(stats.swapUsed, stats.swapTotal);
checkUpper('swap', swapPct, thresholds.swapWarning, thresholds.swapCritical, (v) => `SWAP ${Math.round(v)}%`);
const maxDiskPct = stats.disks.reduce<number | null>(
(acc, d) => (typeof d.percent === 'number' && Number.isFinite(d.percent) ? (acc == null ? d.percent : Math.max(acc, d.percent)) : acc),
stats.diskPercent,
);
checkUpper('disk', maxDiskPct, thresholds.diskWarning, thresholds.diskCritical, (v) => `DISK ${Math.round(v)}%`);
const maxInodePct = stats.disks.reduce<number | null>(
(acc, d) =>
typeof d.inodePercent === 'number' && Number.isFinite(d.inodePercent)
? acc == null
? d.inodePercent
: Math.max(acc, d.inodePercent)
: acc,
null,
);
checkUpper('inode', maxInodePct, thresholds.inodeWarning, thresholds.inodeCritical, (v) => `INODE ${Math.round(v)}%`);
if (stats.loadAverage.length > 0 && stats.cpuCores && stats.cpuCores > 0) {
const loadPerCore = stats.loadAverage[0] / stats.cpuCores;
checkUpper(
'loadPerCore',
loadPerCore,
thresholds.loadPerCoreWarning,
thresholds.loadPerCoreCritical,
(v) => `LOAD ${v.toFixed(2)}x`,
);
}
if (stats.networkReady && typeof stats.netDropsDelta === 'number' && stats.netDropsDelta > 0) {
checkUpper(
'netDrops',
stats.netDropsDelta,
thresholds.netDropsWarning,
thresholds.netDropsCritical,
(v) => `DROPS +${Math.round(v)}`,
);
}
const latency = stats.latencyMs ?? stats.responseLatencyMs;
checkUpper(
'latencyMs',
latency,
thresholds.latencyWarningMs,
thresholds.latencyCriticalMs,
(v) => `${Math.round(v)}ms`,
);
const score = Math.max(0, Math.min(100, 100 - penalty));
const hasCritical = violations.some((v) => v.severity === 'critical');
const hasWarning = violations.some((v) => v.severity === 'warning');
const level: HealthSummary['level'] = hasCritical ? 'critical' : hasWarning ? 'warning' : 'healthy';
return {
health: {
score,
level,
badges: violations.map((v) => ({ metric: v.metric, severity: v.severity, label: v.label })),
},
violations,
};
}
/**
* Hysteresis filter: prevents alert flapping by requiring `consecutivePolls` consecutive
* breaches for a (hostId, metric) pair before emitting an alert into the incident feed.
*/
export function applyAlertHysteresis(
streaks: Map<string, number>,
hostId: string,
violations: readonly EvaluatedViolation[],
consecutivePolls: number,
options: { immediateMetrics?: ReadonlySet<AlertMetric> } = {},
): EvaluatedViolation[] {
const required = Math.max(1, Math.round(consecutivePolls || 1));
const activeMetrics = new Set(violations.map((v) => v.metric));
const prefix = `${hostId}:`;
for (const key of [...streaks.keys()]) {
if (key.startsWith(prefix)) {
const metric = key.slice(prefix.length) as AlertMetric;
if (!activeMetrics.has(metric)) streaks.delete(key);
}
}
const confirmed: EvaluatedViolation[] = [];
for (const v of violations) {
const key = `${prefix}${v.metric}`;
const count = (streaks.get(key) ?? 0) + 1;
streaks.set(key, count);
if (count >= required || options.immediateMetrics?.has(v.metric)) {
confirmed.push(v);
}
}
return confirmed;
}
export function mergeAlertFeed(
existing: readonly AlertEvent[],
hostId: string,
hostLabel: string,
violations: readonly EvaluatedViolation[],
now = Date.now(),
maxEvents = 200,
): AlertEvent[] {
const next = existing.map((ev) => ({ ...ev }));
const activeMetrics = new Set(violations.map((v) => v.metric));
for (const ev of next) {
if (ev.hostId === hostId && !ev.resolvedAt && !activeMetrics.has(ev.metric)) {
ev.resolvedAt = now;
}
}
for (const v of violations) {
const open = next.find((ev) => ev.hostId === hostId && ev.metric === v.metric && !ev.resolvedAt);
if (open) {
if (open.severity !== v.severity) {
open.severity = v.severity;
open.acknowledged = false;
}
open.value = v.value;
open.threshold = v.threshold;
open.message = `${hostLabel}: ${v.label}`;
open.at = now;
} else {
next.unshift({
id: `${hostId}:${v.metric}:${now}`,
hostId,
hostLabel,
metric: v.metric,
severity: v.severity,
value: v.value,
threshold: v.threshold,
message: `${hostLabel}: ${v.label}`,
startedAt: now,
at: now,
acknowledged: false,
resolvedAt: null,
});
}
}
return next.slice(0, maxEvents);
}
export interface AlertSidebarBadge {
count: number;
tone: 'warning' | 'danger';
tooltip: string;
}
export function computeAlertBadge(
alerts: readonly AlertEvent[],
locale: 'en' | 'zh-CN' = 'en',
): AlertSidebarBadge | null {
const active = alerts.filter((a) => !a.resolvedAt && !a.acknowledged);
if (active.length === 0) return null;
const count = Math.min(999, active.length);
const criticalCount = active.filter((a) => a.severity === 'critical').length;
const tone: 'warning' | 'danger' = criticalCount > 0 ? 'danger' : 'warning';
const topMsg = (active[0]?.message ?? '').replace(/[\r\n\t\x00-\x1f\x7f]/g, ' ').trim();
const summary =
locale === 'zh-CN'
? criticalCount > 0
? `${count} 条告警(${criticalCount} 条严重)${topMsg ? `:${topMsg}` : ''}`
: `${count} 条告警${topMsg ? `:${topMsg}` : ''}`
: criticalCount > 0
? `${count} active alert${count === 1 ? '' : 's'} (${criticalCount} critical)${topMsg ? `: ${topMsg}` : ''}`
: `${count} active alert${count === 1 ? '' : 's'}${topMsg ? `: ${topMsg}` : ''}`;
return {
count,
tone,
tooltip: summary.slice(0, 160),
};
}
@@ -1,288 +0,0 @@
import { DISK_IO_ASSIGNMENT, PARTITION_IO_ASSIGNMENT } from './disks';
import { GPU_ASSIGNMENT, THERMAL_ASSIGNMENT } from './gpu';
export const DROPBEAR_MAX_COMMAND_BYTES = 8192;
export function withPosixRemoteWatchdog(command: string, timeoutMs = 10_000): string {
const sec = Math.max(2, Math.min(30, Math.ceil(timeoutMs / 1000)));
return `( ${command} ) & pid=$!; ( sleep ${sec}; kill -9 $pid 2>/dev/null ) & wpid=$!; wait $pid; rc=$?; kill $wpid 2>/dev/null; exit $rc`;
}
const LINUX_DISK_AWK = String.raw`awk '
$0 == "__NETCATTY_DF__" { in_df = 1; next }
!in_df {
on_marker = index($0, " on ");
if (on_marker > 1) {
mount_rest = substr($0, on_marker + 4);
type_marker = index(mount_rest, " type ");
if (type_marker > 1) {
mount_point = substr(mount_rest, 1, type_marker - 1);
filesystem_type = substr(mount_rest, type_marker + 6);
sub(/[[:space:]].*$/, "", filesystem_type);
mount_filesystem_types[mount_point] = filesystem_type;
}
}
next
}
$1 == "Filesystem" { has_type = ($2 == "Type"); next }
NF > 0 {
source = $1;
if (has_type) {
filesystem_type = $2; total_kb = $3; used_kb = $4; percent = $6; mount_point = $7;
} else {
filesystem_type = ""; total_kb = $2; used_kb = $3; percent = $5; mount_point = $6;
}
if ((filesystem_type == "" || filesystem_type == "-") && (mount_point in mount_filesystem_types)) {
filesystem_type = mount_filesystem_types[mount_point];
}
if (mount_point == "") next;
if (source ~ /^\/dev\/loop/ && mount_point != "/") next;
if (mount_point != "/" && mount_point ~ /^\/(etc|proc|sys|dev|snap)(\/|$)/) next;
if (mount_point != "/" && source ~ /^(overlay|overlayfs)(\/|$|:)/) next;
fstype = tolower(filesystem_type);
source_lower = tolower(source);
is_net = 0;
if (fstype ~ /^fuse\.(rclone|sshfs|s3fs|gcsfuse|ufs|mergerfs|unionfs|unionfs-fuse|ceph|ceph-fuse|cephfs|glusterfs)$/) is_net = 1;
if (fstype ~ /clouddrive/) is_net = 1;
if (fstype ~ /^(fuse|rclone|sshfs|s3fs|gcsfuse|mergerfs|unionfs|unionfs-fuse|nfs|nfs4|cifs|smb|smb3|smbfs|afs|ceph|cephfs|glusterfs)$/) is_net = 1;
if ((filesystem_type == "" || filesystem_type == "-") && source_lower ~ /clouddrive/) is_net = 1;
if ((filesystem_type == "" || filesystem_type == "-") && source_lower ~ /^(fuse|fuse\..*|rclone|rclone:.*|sshfs|s3fs|gcsfuse|mergerfs|unionfs|unionfs-fuse|ceph|ceph-fuse|cephfs|gluster|glusterfs|ufs)$/) is_net = 1;
if ((filesystem_type == "" || filesystem_type == "-") && source_lower ~ /^\/\//) is_net = 1;
if ((filesystem_type == "" || filesystem_type == "-") && source_lower !~ /^(apfs|overlay|overlayfs):/ && source_lower ~ /^([a-z0-9._-]+|\[[0-9a-f:]+(%[a-z0-9._-]+)?\]):\//) is_net = 1;
if (is_net) next;
pseudo_type = (fstype != "" && fstype != "-") ? fstype : source_lower;
if (mount_point != "/" && pseudo_type ~ /^(tmpfs|shm|devtmpfs|udev|none|proc|sysfs|cgroup|cgroup2|devpts|mqueue|hugetlbfs|debugfs|tracefs|securityfs|pstore|bpf|fusectl|configfs|ramfs|rpc_pipefs|binfmt_misc|efivarfs)$/) next;
total = total_kb / 1048576;
used = used_kb / 1048576;
if (total <= 0) next;
gsub(/%/, "", percent);
if (percent !~ /^[0-9]+$/) percent = int(used * 100 / total + 0.5);
metadata = source;
if (filesystem_type != "" && filesystem_type != "-") metadata = "fs=" filesystem_type ":" source;
printf "%s:%.6f:%.6f:%s:%s,", mount_point, used, total, percent, metadata;
}
'`;
/**
* Primary multi-OS stats command (Linux + macOS + FreeBSD/OpenBSD/NetBSD).
* Collects deep Linux telemetry (full CPU breakdown, ctxt/intr/procs, Active/Slab mem,
* PSI cpu/mem/io, net bytes+pps+errs+drops, TCP retransmits, disk I/O + IOPS + %util + qdepth,
* open FDs, active users, pending reboot, thermals) while staying strictly < 8192 bytes!
*/
export function buildPrimaryStatsCommand(): string {
const linux = [
`cores=$(nproc 2>/dev/null || grep -c "^processor" /proc/cpuinfo 2>/dev/null || echo 1)`,
// CPURAW: total idle iowait steal user system | CPUEXTRA: ctxt intr run blk | PERCORERAW: t:i,...
`eval $(awk '/^cpu /{t=0;for(i=2;i<=NF;i++)t+=$i;u=$2+$3;s=$4+$7+$8;printf "cpuraw=\"%d %d %d %d %d %d\";",t,$5,($6+0),($9+0),u,s} /^cpu[0-9]/{t=0;for(i=2;i<=NF;i++)t+=$i;pc=pc t ":" $5 ","} /^ctxt /{cx=$2} /^intr /{ir=$2} /^procs_running /{pr=$2} /^procs_blocked /{pb=$2} END{sub(/,$/,"",pc);printf "percoreraw=\"%s\";cpuextra=\"%s %s %s %s\"",pc,cx,ir,pr,pb}' /proc/stat 2>/dev/null)`,
// MEMINFO: total free buf cached swapTotal swapFree active slab (all MiB)
`meminfo=$(awk '/^MemTotal:/{t=$2} /^MemFree:/{f=$2} /^Buffers:/{b=$2} /^Cached:/{c=$2} /^SReclaimable:/{s=$2} /^SwapTotal:/{st=$2} /^SwapFree:/{sf=$2} /^Active:/{ac=$2} /^Slab:/{sl=$2} END{printf "%d %d %d %d %d %d %d %d",t/1024,f/1024,b/1024,(c+s)/1024,st/1024,sf/1024,ac/1024,sl/1024}' /proc/meminfo 2>/dev/null)`,
// PSI: cpuSome10,cpuSome60,memSome10,memSome60,memFull10,ioSome10,ioSome60,ioFull10
`psi=$(if [ -r /proc/pressure/cpu ]; then awk 'function g(s,k,a){if(match(s,k"=[0-9.]+")){return substr(s,RSTART+length(k)+1,RLENGTH-length(k)-1)}return ""} FILENAME~/cpu$/&&/^some/{cs10=g($0,"avg10");cs60=g($0,"avg60")} FILENAME~/memory$/&&/^some/{ms10=g($0,"avg10");ms60=g($0,"avg60")} FILENAME~/memory$/&&/^full/{mf10=g($0,"avg10")} FILENAME~/io$/&&/^some/{is10=g($0,"avg10");is60=g($0,"avg60")} FILENAME~/io$/&&/^full/{if10=g($0,"avg10")} END{printf "%s,%s,%s,%s,%s,%s,%s,%s",cs10,cs60,ms10,ms60,mf10,is10,is60,if10}' /proc/pressure/cpu /proc/pressure/memory /proc/pressure/io 2>/dev/null; fi)`,
// NET: iface:rxB:txB:rxPkt:txPkt:rxErr:rxDrop:txErr:txDrop
`net=$(awk 'NR>2{gsub(/^[ \t]+/,"");split($0,a,":");n=a[1];if(n!="lo"&&n!~/^(veth|docker|br-)/){split(a[2],b);printf "%s:%s:%s:%s:%s:%s:%s:%s:%s,",n,b[1],b[9],b[2],b[10],b[3],b[4],b[11],b[12]}}' /proc/net/dev 2>/dev/null | sed 's/,$//')`,
`tcpretrans=$(awk '/^Tcp:/{if(h){print $13;exit}h=1}' /proc/net/snmp 2>/dev/null)`,
`fdnr=$(awk '{printf "%s:%s",$1,$3}' /proc/sys/fs/file-nr 2>/dev/null)`,
`users=$(who 2>/dev/null | wc -l | tr -d ' ')`,
`reboot=$([ -f /var/run/reboot-required ] && echo 1 || echo 0)`,
`hv=$(hostname 2>/dev/null || uname -n 2>/dev/null)`,
`osn=$(awk -F= '/^PRETTY_NAME=/{gsub(/"/,"",$2);print $2;exit}' /etc/os-release 2>/dev/null || uname -s 2>/dev/null)`,
`kn=$(uname -r 2>/dev/null)`,
`up=$(awk '{printf "%.0f",$1}' /proc/uptime 2>/dev/null)`,
`la=$(awk '{print $1" "$2" "$3}' /proc/loadavg 2>/dev/null)`,
DISK_IO_ASSIGNMENT,
PARTITION_IO_ASSIGNMENT,
THERMAL_ASSIGNMENT,
`echo "OSFAM:linux|CPURAW:$cpuraw|CPUEXTRA:$cpuextra|CORES:$cores|PERCORERAW:$percoreraw|MEMINFO:$meminfo|PSI:$psi|NET:$net|TCPRETRANS:$tcpretrans|DISKIO:$diskio|PARTITIONIO:$partitionio|DISKMOUNTS:$diskmounts|THERMALS:$thermals|FD:$fdnr|USERS:$users|REBOOT:$reboot|HOST:$hv|OS:$osn|KERNEL:$kn|UPTIME:$up|LOAD:$la"`,
].join('; ');
const macos = [
`cores=$(sysctl -n hw.logicalcpu 2>/dev/null || echo 1)`,
`psize=$(sysctl -n hw.pagesize 2>/dev/null || echo 4096)`,
`msize=$(sysctl -n hw.memsize 2>/dev/null || echo 0)`,
`cpupct=$(ps -A -o %cpu= 2>/dev/null | awk -v c="$cores" '{s+=$1} END{if(c<=0)c=1;s=s/c;if(s<0)s=0;if(s>100)s=100;printf "%.0f",s}')`,
`vmmem=$(vm_stat 2>/dev/null | awk -v ps="$psize" '/^Pages free:/{gsub(/[^0-9]/,"",$NF);f=$NF+0} /^Pages speculative:/{gsub(/[^0-9]/,"",$NF);sp=$NF+0} /^Pages inactive:/{gsub(/[^0-9]/,"",$NF);ia=$NF+0} /^Pages purgeable:/{gsub(/[^0-9]/,"",$NF);pg=$NF+0} END{printf "%d %d",int((f+sp)*ps/1048576),int((ia+pg)*ps/1048576)}')`,
`mt=$(echo "$msize" | awk '{printf "%d",$1/1048576}')`,
`mf=$(echo "$vmmem" | awk '{print $1}')`,
`mc=$(echo "$vmmem" | awk '{print $2}')`,
`sw=$(sysctl vm.swapusage 2>/dev/null | awk '{for(i=1;i<=NF;i++){if($i=="total"&&$(i+1)=="="){v=$(i+2);m=(v~/G/?1024:1);gsub(/[MmGg]/,"",v);st=v*m}if($i=="used"&&$(i+1)=="="){v=$(i+2);m=(v~/G/?1024:1);gsub(/[MmGg]/,"",v);su=v*m}}} END{printf "%.0f %.0f",st+0,(st-su>0?st-su:0)}')`,
`disks=$({ mount 2>/dev/null; printf "__NETCATTY_DF__\\n"; df -kP 2>/dev/null; } | awk '$0=="__NETCATTY_DF__"{d=1;next} !d{if(index($1,"/dev/disk")==1&&(index($0,"(apfs,")||index($0,"(apfs)"))){k=$1;sub(/s[0-9].*$/,"",k);cap[$1]="apfs:" k}next} $1=="Filesystem"{next} index($1,"/dev/")==1{m=$6;if(m=="/"||index(m,"/Volumes/")==1){t=$2/1048576;k=(($1 in cap)?cap[$1]:$1);if(k~/^apfs:/){u=($2-$4)/1048576;p=(t>0?int(u*100/t+0.5):0)}else{u=$3/1048576;p=$5;gsub(/%/,"",p)}printf "%s:%.6f:%.6f:%s:%s,",m,u,t,p,k}}' | sed 's/,$//')`,
`net=$(netstat -ibn 2>/dev/null | awk 'NR==1{for(i=1;i<=NF;i++){if($i=="Ibytes")ib=i;if($i=="Obytes")ob=i}next} ib&&ob&&$1~/^[[:alpha:]]/&&$1!~/^lo/&&$0~/<Link#/{n=$1;gsub(/[*]/,"",n);rx=$(ib)+0;tx=$(ob)+0;if(rx>0||tx>0)seen[n]=rx ":" tx} END{for(n in seen)printf "%s:%s,",n,seen[n]}' | sed 's/,$//')`,
`hv=$(hostname 2>/dev/null || uname -n 2>/dev/null)`,
`osn=$(printf "%s %s" "$(sw_vers -productName 2>/dev/null)" "$(sw_vers -productVersion 2>/dev/null)" | sed 's/[[:space:]]*$//')`,
`kn=$(uname -r 2>/dev/null)`,
`bs=$(sysctl -n kern.boottime 2>/dev/null | awk -F'[ ,]+' '{for(i=1;i<=NF;i++)if($i=="sec"){print $(i+2);exit}}')`,
`up=$(awk -v n="$(date +%s 2>/dev/null || echo 0)" -v b="$bs" 'BEGIN{if(n>0&&b>0)printf "%.0f",n-b}')`,
`la=$(sysctl -n vm.loadavg 2>/dev/null | tr -d '{}' | awk '{print $1" "$2" "$3}')`,
`users=$(who 2>/dev/null | wc -l | tr -d ' ')`,
`echo "OSFAM:macos|CPU:$cpupct|CORES:$cores|MEMINFO:$mt $mf 0 $mc $sw|DISKS:$disks|NET:$net|USERS:$users|HOST:$hv|OS:$osn|KERNEL:$kn|UPTIME:$up|LOAD:$la"`,
].join('; ');
const bsd = [
`cores=$(sysctl -n hw.ncpu 2>/dev/null || echo 1)`,
`cpupct=$(ps -axo %cpu= 2>/dev/null | awk -v c="$cores" '{s+=$1} END{if(c<=0)c=1;s=s/c;if(s<0)s=0;if(s>100)s=100;printf "%.0f",s}')`,
`mt=$(sysctl -n hw.physmem 2>/dev/null | awk '{printf "%d",$1/1048576}' || echo 0)`,
`psize=$(sysctl -n hw.pagesize 2>/dev/null || echo 4096)`,
`mf=$(awk -v p="$(sysctl -n vm.stats.vm.v_free_count 2>/dev/null || echo 0)" -v ps="$psize" 'BEGIN{printf "%d",p*ps/1048576}')`,
`mc=$(awk -v p="$(sysctl -n vm.stats.vm.v_inactive_count 2>/dev/null || echo 0)" -v ps="$psize" 'BEGIN{printf "%d",p*ps/1048576}')`,
`disks=$(df -kP 2>/dev/null | awk '$1!="Filesystem"&&$1!~/^(devfs|tmpfs|procfs|fdescfs)$/{t=$2/1048576;u=$3/1048576;p=$5;gsub(/%/,"",p);if(t>0)printf "%s:%.6f:%.6f:%s:%s,",$6,u,t,p,$1}' | sed 's/,$//')`,
`net=$(netstat -ibn 2>/dev/null | awk 'NR==1{for(i=1;i<=NF;i++){if($i=="Ibytes")ib=i;if($i=="Obytes")ob=i}next} ib&&ob&&$1!~/^lo/&&$0~/<Link#/{n=$1;gsub(/[*]/,"",n);seen[n]=($(ib)+0)":"($(ob)+0)} END{for(n in seen)printf "%s:%s,",n,seen[n]}' | sed 's/,$//')`,
`hv=$(hostname 2>/dev/null || uname -n 2>/dev/null)`,
`osn=$(uname -sr 2>/dev/null || echo BSD)`,
`kn=$(uname -r 2>/dev/null)`,
`bs=$(sysctl -n kern.boottime 2>/dev/null | awk -F'[ ,]+' '{for(i=1;i<=NF;i++)if($i=="sec"){print $(i+2);exit}}')`,
`up=$(awk -v n="$(date +%s 2>/dev/null || echo 0)" -v b="$bs" 'BEGIN{if(n>0&&b>0)printf "%.0f",n-b}')`,
`la=$(sysctl -n vm.loadavg 2>/dev/null | tr -d '{}' | awk '{print $1" "$2" "$3}')`,
`echo "OSFAM:freebsd|CPU:$cpupct|CORES:$cores|MEMINFO:$mt $mf 0 $mc 0 0|DISKS:$disks|NET:$net|HOST:$hv|OS:$osn|KERNEL:$kn|UPTIME:$up|LOAD:$la"`,
].join('; ');
return `ostype=$(uname -s 2>/dev/null || echo Unknown); if [ "$ostype" = "Linux" ]; then ${linux}; elif [ "$ostype" = "Darwin" ]; then ${macos}; elif [ "$ostype" = "FreeBSD" ] || [ "$ostype" = "OpenBSD" ] || [ "$ostype" = "NetBSD" ]; then ${bsd}; else echo "UNSUPPORTED_OS:$ostype"; fi`;
}
/**
* Separate Linux disk capacity + inode utilization command (kept distinct to stay under 8192 bytes).
*/
export function buildLinuxDiskCommand(): string {
const diskTable = `{ LC_ALL=C mount 2>/dev/null; printf "%s\\n" "__NETCATTY_DF__"; LC_ALL=C df -kPT 2>/dev/null || LC_ALL=C df -kP 2>/dev/null; }`;
const diskRoot = `{ LC_ALL=C mount 2>/dev/null; printf "%s\\n" "__NETCATTY_DF__"; LC_ALL=C df -kPT / 2>/dev/null || LC_ALL=C df -kP / 2>/dev/null; }`;
const inodesCmd = `inodes=$(LC_ALL=C df -iP 2>/dev/null | awk 'NR>1 && $2 ~ /^[0-9]+$/ && $2+0 > 0 {p=$5; gsub(/%/,"",p); if(p!~/^[0-9]+$/) p=int($3*100/$2+0.5); printf "%s:%s:%s:%s,", $6, $3, $2, p}' | sed 's/,$//')`;
return [
`disks=$( { ${diskTable}; } | ${LINUX_DISK_AWK} | sed 's/,$//' )`,
`[ -n "$disks" ] || disks=$( { ${diskRoot}; } | ${LINUX_DISK_AWK} | sed 's/,$//' )`,
inodesCmd,
`echo "DISKS:$disks|INODES:$inodes"`,
].join('; ');
}
export function buildGpuProbeCommand(): string {
return `if [ "$(uname -s 2>/dev/null)" = "Linux" ]; then ${GPU_ASSIGNMENT}; echo "GPU:$gpustat"; fi`;
}
export function buildWindowsStatsCommand(): string {
const ps = [
`$os=Get-CimInstance Win32_OperatingSystem`,
`$cs=Get-CimInstance Win32_ComputerSystem`,
`$cpu=(Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average`,
`$cores=[int]$cs.NumberOfLogicalProcessors`,
`$mt=[int]([math]::Round($os.TotalVisibleMemorySize/1024))`,
`$mf=[int]([math]::Round($os.FreePhysicalMemory/1024))`,
`$up=[int]((Get-Date)-$os.LastBootUpTime).TotalSeconds`,
`$disks=(Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object { $t=[math]::Round($_.Size/1GB,4); $u=[math]::Round(($_.Size-$_.FreeSpace)/1GB,4); $p=if($_.Size -gt 0){[int][math]::Round(($_.Size-$_.FreeSpace)*100/$_.Size)}else{0}; "$($_.DeviceID):$($u):$($t):$($p):$($_.FileSystem)" }) -join ','`,
`Write-Output ("OSFAM:windows|CPU:{0}|CORES:{1}|MEMINFO:{2} {3} 0 0 0 0|DISKS:{4}|HOST:{5}|OS:{6}|KERNEL:{7}|UPTIME:{8}" -f ([int]$cpu),$cores,$mt,$mf,$disks,$env:COMPUTERNAME,$os.Caption,$os.Version,$up)`,
].join('; ');
return `powershell -NoProfile -NonInteractive -Command "${ps.replace(/"/g, '\\"')}"`;
}
export function buildProcessesCommand(limit = 150): string {
const safeLimit = Math.max(20, Math.min(300, Math.trunc(limit)));
return [
`ostype=$(uname -s 2>/dev/null || echo "Linux")`,
`if [ "$ostype" = "Darwin" ]; then ps -axo pid=,user=,%cpu=,%mem=,rss=,state=,etime=,command= 2>/dev/null | sort -k3 -rn | head -n ${safeLimit};`,
`elif ps -eo pid=,user=,%cpu=,%mem=,rss=,stat=,etime=,args= --sort=-%cpu >/dev/null 2>&1; then ps -eo pid=,user=,%cpu=,%mem=,rss=,stat=,etime=,args= --sort=-%cpu 2>/dev/null | head -n ${safeLimit};`,
`else ps -eo pid=,user=,%cpu=,%mem=,rss=,stat=,etime=,args= 2>/dev/null | sort -k3 -rn | head -n ${safeLimit}; fi`,
].join(' ');
}
export function buildServicesAndContainersCommand(): string {
return [
`echo "__NC_SYSTEMD__"`,
`if command -v systemctl >/dev/null 2>&1; then LC_ALL=C systemctl list-units --type=service --all --no-pager --no-legend --plain 2>/dev/null | head -n 200; fi`,
`echo "__NC_DOCKER__"`,
`if command -v docker >/dev/null 2>&1; then docker ps -a --no-trunc --format '{{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.State}}\\t{{.Status}}\\t{{.Ports}}' 2>/dev/null | head -n 100; fi`,
`echo "__NC_PODMAN__"`,
`if command -v podman >/dev/null 2>&1; then podman ps -a --no-trunc --format '{{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.State}}\\t{{.Status}}\\t{{.Ports}}' 2>/dev/null | head -n 100; fi`,
].join('; ');
}
export function buildPortsCommand(): string {
return [
`echo "__NC_PORTS__"`,
`if command -v ss >/dev/null 2>&1; then LC_ALL=C ss -tulnpH 2>/dev/null || LC_ALL=C ss -tulnH 2>/dev/null;`,
`elif command -v netstat >/dev/null 2>&1; then LC_ALL=C netstat -tulnp 2>/dev/null || LC_ALL=C netstat -an 2>/dev/null | head -n 150;`,
`elif command -v lsof >/dev/null 2>&1; then LC_ALL=C lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null | head -n 150; fi`,
`echo "__NC_SOCKSUMMARY__"`,
`if command -v ss >/dev/null 2>&1; then LC_ALL=C ss -tanH 2>/dev/null | awk '{c[$1]++} END{for(k in c) printf "%s:%d\\n",k,c[k]}'; fi`,
].join('; ');
}
/**
* Active-tab System & Security Audit collector (open FDs, active logged-in users,
* recent SSH logins, failed auth count, pending reboot).
*/
export function buildSystemAuditCommand(): string {
return [
`echo "__NC_FD__"`,
`awk '{printf "%s:%s\\n",$1,$3}' /proc/sys/fs/file-nr 2>/dev/null || true`,
`echo "__NC_REBOOT__"`,
`[ -f /var/run/reboot-required ] && echo 1 || echo 0`,
`echo "__NC_WHO__"`,
`LC_ALL=C who 2>/dev/null | head -n 30 || true`,
`echo "__NC_LAST__"`,
`LC_ALL=C last -n 8 2>/dev/null | head -n 12 || true`,
`echo "__NC_FAILEDAUTH__"`,
`if command -v journalctl >/dev/null 2>&1; then journalctl -u ssh -u sshd --since "24 hours ago" --no-pager 2>/dev/null | grep -cE "Failed password|Invalid user|authentication failure" || true; else echo ""; fi`,
].join('; ');
}
const SAFE_UNIT_NAME = /^[a-zA-Z0-9@_.:-]{1,160}$/;
const SAFE_CONTAINER_ID = /^[a-zA-Z0-9_.-]{1,128}$/;
export function buildServiceLogsCommand(unit: string, lines = 120): string {
if (!SAFE_UNIT_NAME.test(unit)) {
throw new Error(`Invalid systemd unit name: ${unit}`);
}
const safeLines = Math.max(10, Math.min(500, Math.trunc(lines)));
return `LC_ALL=C journalctl -u '${unit}' -n ${safeLines} --no-pager --output=short-iso 2>&1`;
}
export function buildContainerLogsCommand(runtime: 'docker' | 'podman', id: string, lines = 120): string {
if (!SAFE_CONTAINER_ID.test(id)) {
throw new Error(`Invalid container identifier: ${id}`);
}
const safeLines = Math.max(10, Math.min(500, Math.trunc(lines)));
const bin = runtime === 'podman' ? 'podman' : 'docker';
return `${bin} logs --tail ${safeLines} --timestamps '${id}' 2>&1`;
}
export type SafeServiceAction = 'start' | 'stop' | 'restart' | 'reload';
const ALLOWED_SERVICE_ACTIONS = new Set<SafeServiceAction>(['start', 'stop', 'restart', 'reload']);
export function buildServiceActionCommand(unit: string, action: SafeServiceAction): string {
if (!SAFE_UNIT_NAME.test(unit)) {
throw new Error(`Invalid systemd unit name: ${unit}`);
}
if (!ALLOWED_SERVICE_ACTIONS.has(action)) {
throw new Error(`Unsupported systemd action: ${action}`);
}
return `systemctl ${action} '${unit}' 2>&1`;
}
export type SafeContainerAction = 'start' | 'stop' | 'restart';
const ALLOWED_CONTAINER_ACTIONS = new Set<SafeContainerAction>(['start', 'stop', 'restart']);
export function buildContainerActionCommand(
runtime: 'docker' | 'podman',
id: string,
action: SafeContainerAction,
): string {
if (!SAFE_CONTAINER_ID.test(id)) {
throw new Error(`Invalid container identifier: ${id}`);
}
if (!ALLOWED_CONTAINER_ACTIONS.has(action)) {
throw new Error(`Unsupported container action: ${action}`);
}
const bin = runtime === 'podman' ? 'podman' : 'docker';
return `${bin} ${action} '${id}' 2>&1`;
}
export type SafeProcessSignal = 'SIGTERM' | 'SIGKILL' | 'SIGHUP' | 'SIGINT';
const ALLOWED_SIGNALS = new Set<SafeProcessSignal>(['SIGTERM', 'SIGKILL', 'SIGHUP', 'SIGINT']);
export function buildProcessSignalCommand(pid: number, signal: SafeProcessSignal): string {
if (!Number.isSafeInteger(pid) || pid <= 1) {
throw new Error(`Refusing to signal invalid or init PID: ${pid}`);
}
if (!ALLOWED_SIGNALS.has(signal)) {
throw new Error(`Unsupported process signal: ${signal}`);
}
return `kill -s ${signal} ${pid}`;
}
@@ -1,237 +0,0 @@
import type { MonitorDiskRow } from './types';
// Exact parity with Netcatty domain/monitorDisks.ts and electron/bridges/sshBridge/monitorDiskIo.cjs,
// extended with IOPS, %util busy, and queue depth from /sys/block/*/stat (11-field Linux block stats).
const SYSTEM_MOUNTS = ['/', '/boot', '/etc', '/usr', '/var', '/home', '/opt', '/srv', '/tmp'];
const mountNames = new Intl.Collator('en', { numeric: true });
// Format per device: name:readSectors:writeSectors[:readsCompleted:writesCompleted:ioTicksMs:inFlight]
export const DISK_IO_ASSIGNMENT = String.raw`diskio=$(if [ -r /proc/uptime ]; then awk '{printf "%s;",$1}' /proc/uptime; for d in /sys/block/*; do [ -e "$d/device" ] && [ -r "$d/stat" ] || continue; awk -v path="$d" 'NF>=10 {n=split(path,a,"/");printf "%s:%s:%s:%s:%s:%s:%s,",a[n],$3,$7,$1,$5,$10,$9} NF>=7 && NF<10 {n=split(path,a,"/");printf "%s:%s:%s,",a[n],$3,$7}' "$d/stat"; done; fi)`;
export const PARTITION_IO_ASSIGNMENT = String.raw`partitionio=$(if [ -r /proc/uptime ]; then awk 'NR==1 {printf "%s;",$1;next} NF>=7 {n=split(FILENAME,a,"/");gsub(/:/,"-",a[n-1]);printf "%s:%s:%s,",a[n-1],$3,$7}' /proc/uptime /sys/dev/block/*/stat 2>/dev/null; fi); diskmounts=$(awk '{gsub(/:/,"-",$3);printf "%s:%s,",$5,$3}' /proc/self/mountinfo 2>/dev/null)`;
export interface DiskIoDeviceCounters {
readSectors: number;
writeSectors: number;
readsCompleted?: number;
writesCompleted?: number;
ioTicksMs?: number;
inFlight?: number;
}
export interface DiskIoSnapshot {
timestamp: number;
devices: Map<string, DiskIoDeviceCounters>;
}
export interface DiskIoRates {
diskReadSpeed: number | null;
diskWriteSpeed: number | null;
diskReadIops: number | null;
diskWriteIops: number | null;
diskUtilPercent: number | null;
diskQueueDepth: number | null;
}
export type MonitorDiskListRow =
| { kind: 'disk'; disk: MonitorDiskRow; alert: boolean }
| { kind: 'system'; count: number; expanded: boolean; alert: boolean };
export interface MonitorDiskListStats {
disks: readonly MonitorDiskRow[];
diskPercent?: number | null;
diskUsed?: number | null;
diskTotal?: number | null;
}
function mountPriority(mountPoint: string): number {
const rank = SYSTEM_MOUNTS.findIndex(
(path) => mountPoint === path || (path !== '/' && mountPoint.startsWith(`${path}/`)),
);
return rank < 0 ? SYSTEM_MOUNTS.length : rank;
}
export function isMonitorSystemDisk(mountPoint: string): boolean {
const priority = mountPriority(mountPoint);
return priority > 0 && priority < SYSTEM_MOUNTS.length;
}
export function monitorSystemDiskAlert(disk: MonitorDiskRow, threshold = 80): boolean {
return (
isMonitorSystemDisk(disk.mountPoint) &&
((typeof disk.percent === 'number' && Number.isFinite(disk.percent) && disk.percent > threshold) ||
(typeof disk.inodePercent === 'number' && Number.isFinite(disk.inodePercent) && disk.inodePercent > threshold))
);
}
export function sortMonitorDisks<T extends { mountPoint: string }>(disks: readonly T[]): T[] {
return [...disks].sort(
(a, b) => mountPriority(a.mountPoint) - mountPriority(b.mountPoint) || mountNames.compare(a.mountPoint, b.mountPoint),
);
}
export function buildMonitorDiskListLayout(
stats?: MonitorDiskListStats | null,
manuallyExpanded = false,
alertThreshold = 80,
) {
const disks = sortMonitorDisks(
stats?.disks.length
? stats.disks
: [
{
mountPoint: '/',
percent: stats?.diskPercent ?? null,
used: stats?.diskUsed ?? null,
total: stats?.diskTotal ?? null,
},
],
);
const system = disks.filter((disk) => isMonitorSystemDisk(disk.mountPoint));
const forcedExpanded = system.some((disk) => monitorSystemDiskAlert(disk, alertThreshold));
const expanded = forcedExpanded || manuallyExpanded;
const rows: MonitorDiskListRow[] = disks
.filter((disk) => !isMonitorSystemDisk(disk.mountPoint))
.map((disk) => ({
kind: 'disk',
disk,
alert: (disk.percent ?? 0) > alertThreshold || (disk.inodePercent ?? 0) > alertThreshold,
}));
if (system.length) {
rows.push({ kind: 'system', count: system.length, expanded, alert: forcedExpanded });
if (expanded) {
rows.push(
...system.map((disk) => ({
kind: 'disk' as const,
disk,
alert: monitorSystemDiskAlert(disk, alertThreshold),
})),
);
}
}
return { rows, expanded, forcedExpanded };
}
export function parseDiskIo(text: string | null | undefined): DiskIoSnapshot | null {
if (typeof text !== 'string') return null;
const [time, counters, ...extra] = text.trim().split(';');
const timestamp = Number(time);
if (!time || extra.length || !Number.isFinite(timestamp) || timestamp < 0 || !counters) return null;
const devices = new Map<string, DiskIoDeviceCounters>();
for (const entry of counters.replace(/,$/, '').split(',')) {
const fields = entry.split(':');
const [name, read, write, readsComp, writesComp, ioTicks, inFlight] = fields;
if (
(fields.length !== 3 && fields.length !== 7) ||
!/^[a-zA-Z0-9_.!-]+$/.test(name) ||
devices.has(name) ||
!/^\d+$/.test(read) ||
!/^\d+$/.test(write)
) {
return null;
}
const readSectors = Number(read);
const writeSectors = Number(write);
if (!Number.isSafeInteger(readSectors) || !Number.isSafeInteger(writeSectors)) return null;
const item: DiskIoDeviceCounters = { readSectors, writeSectors };
if (fields.length === 7) {
if (!/^\d+$/.test(readsComp) || !/^\d+$/.test(writesComp) || !/^\d+$/.test(ioTicks) || !/^\d+$/.test(inFlight)) {
return null;
}
item.readsCompleted = Number(readsComp);
item.writesCompleted = Number(writesComp);
item.ioTicksMs = Number(ioTicks);
item.inFlight = Number(inFlight);
}
devices.set(name, item);
}
return { timestamp, devices };
}
export function diskIoRates(
current: DiskIoSnapshot | null | undefined,
previous: DiskIoSnapshot | null | undefined,
): DiskIoRates {
const unavailable: DiskIoRates = {
diskReadSpeed: null,
diskWriteSpeed: null,
diskReadIops: null,
diskWriteIops: null,
diskUtilPercent: null,
diskQueueDepth: null,
};
if (!current || !previous || current.devices.size !== previous.devices.size) return unavailable;
const seconds = current.timestamp - previous.timestamp;
if (!(seconds > 0)) return unavailable;
let read = 0;
let write = 0;
let hasExtended = true;
let readOps = 0;
let writeOps = 0;
let maxUtil = 0;
let totalInFlight = 0;
for (const [name, counters] of current.devices) {
const before = previous.devices.get(name);
if (!before || counters.readSectors < before.readSectors || counters.writeSectors < before.writeSectors) {
return unavailable;
}
read += (counters.readSectors - before.readSectors) * 512;
write += (counters.writeSectors - before.writeSectors) * 512;
if (
counters.readsCompleted != null &&
before.readsCompleted != null &&
counters.writesCompleted != null &&
before.writesCompleted != null &&
counters.ioTicksMs != null &&
before.ioTicksMs != null &&
counters.readsCompleted >= before.readsCompleted &&
counters.writesCompleted >= before.writesCompleted &&
counters.ioTicksMs >= before.ioTicksMs
) {
readOps += counters.readsCompleted - before.readsCompleted;
writeOps += counters.writesCompleted - before.writesCompleted;
const devUtil = ((counters.ioTicksMs - before.ioTicksMs) / (seconds * 1000)) * 100;
if (devUtil > maxUtil) maxUtil = devUtil;
totalInFlight += counters.inFlight ?? 0;
} else {
hasExtended = false;
}
}
return {
diskReadSpeed: read / seconds,
diskWriteSpeed: write / seconds,
diskReadIops: hasExtended ? Number((readOps / seconds).toFixed(1)) : null,
diskWriteIops: hasExtended ? Number((writeOps / seconds).toFixed(1)) : null,
diskUtilPercent: hasExtended ? Number(Math.max(0, Math.min(100, maxUtil)).toFixed(1)) : null,
diskQueueDepth: hasExtended ? totalInFlight : null,
};
}
export function withPartitionIo(
disks: readonly MonitorDiskRow[],
mounts: string | null | undefined,
current: DiskIoSnapshot | null | undefined,
previous: DiskIoSnapshot | null | undefined,
): MonitorDiskRow[] {
const devices = new Map<string, string>();
for (const entry of (mounts || '').split(',')) {
const separator = entry.lastIndexOf(':');
if (separator < 0) continue;
const mount = entry
.slice(0, separator)
.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
devices.set(mount, entry.slice(separator + 1));
}
return disks.map((disk) => {
const name = devices.get(disk.mountPoint);
if (!name) return disk;
const sample = (snapshot: DiskIoSnapshot | null | undefined): DiskIoSnapshot | null =>
snapshot?.devices.has(name)
? { timestamp: snapshot.timestamp, devices: new Map([[name, snapshot.devices.get(name)!]]) }
: null;
const rates = diskIoRates(sample(current), sample(previous));
return rates.diskReadSpeed == null
? disk
: { ...disk, diskReadSpeed: rates.diskReadSpeed, diskWriteSpeed: rates.diskWriteSpeed };
});
}
@@ -1,140 +0,0 @@
/** Decimal byte-rate units, shared by disk I/O and network monitoring (exact Netcatty parity). */
export function formatMonitorRate(value: number | null | undefined): string {
if (value == null || !Number.isFinite(value) || value < 0) return '--';
if (value >= 1e9) return `${(value / 1e9).toFixed(1)} GB/s`;
if (value >= 1e6) return `${(value / 1e6).toFixed(1)} MB/s`;
return `${(value / 1e3).toFixed(1)} KB/s`;
}
export function formatPercent(value: number | null | undefined, digits = 1): string {
if (value == null || !Number.isFinite(value)) return '--';
return `${Math.max(0, Math.min(100, value)).toFixed(digits)}%`;
}
export function formatMemoryMiB(mib: number | null | undefined): string {
if (mib == null || !Number.isFinite(mib) || mib < 0) return '--';
if (mib >= 1024 * 1024) return `${(mib / (1024 * 1024)).toFixed(1)} TiB`;
if (mib >= 1024) return `${(mib / 1024).toFixed(1)} GiB`;
return `${Math.round(mib)} MiB`;
}
export function formatDiskGiB(gib: number | null | undefined): string {
if (gib == null || !Number.isFinite(gib) || gib < 0) return '--';
if (gib >= 1024) return `${(gib / 1024).toFixed(2)} TiB`;
if (gib >= 100) return `${gib.toFixed(0)} GiB`;
if (gib >= 10) return `${gib.toFixed(1)} GiB`;
return `${gib.toFixed(2)} GiB`;
}
export function formatRssKb(kb: number | null | undefined): string {
if (kb == null || !Number.isFinite(kb) || kb < 0) return '--';
if (kb >= 1024 * 1024) return `${(kb / (1024 * 1024)).toFixed(2)} GiB`;
if (kb >= 1024) return `${(kb / 1024).toFixed(1)} MiB`;
return `${Math.round(kb)} KiB`;
}
export function formatBytes(bytes: number | null | undefined): string {
if (bytes == null || !Number.isFinite(bytes) || bytes < 0) return '--';
if (bytes >= 1e12) return `${(bytes / 1e12).toFixed(2)} TB`;
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(2)} GB`;
if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(1)} MB`;
if (bytes >= 1e3) return `${(bytes / 1e3).toFixed(1)} KB`;
return `${Math.round(bytes)} B`;
}
export function formatUptime(seconds: number | null | undefined, locale = 'en'): string {
if (seconds == null || !Number.isFinite(seconds) || seconds < 0) return '--';
const total = Math.floor(seconds);
const days = Math.floor(total / 86400);
const hours = Math.floor((total % 86400) / 3600);
const mins = Math.floor((total % 3600) / 60);
const isZh = locale.toLowerCase().startsWith('zh');
if (days > 0) return isZh ? `${days}天 ${hours}小时` : `${days}d ${hours}h`;
if (hours > 0) return isZh ? `${hours}小时 ${mins}分` : `${hours}h ${mins}m`;
return isZh ? `${Math.max(1, mins)}分钟` : `${Math.max(1, mins)}m`;
}
export function formatLatency(ms: number | null | undefined): string {
if (ms == null || !Number.isFinite(ms) || ms < 0) return '--';
return `${Math.round(ms)} ms`;
}
export function formatLoadAverage(load: readonly number[] | null | undefined): string {
if (!load || load.length === 0) return '--';
return load.slice(0, 3).map((v) => v.toFixed(2)).join(' / ');
}
export function formatRelativeAge(timestampMs: number, nowMs = Date.now(), locale = 'en'): string {
if (!timestampMs || !Number.isFinite(timestampMs)) return '--';
const deltaSec = Math.max(0, Math.floor((nowMs - timestampMs) / 1000));
const isZh = locale.toLowerCase().startsWith('zh');
if (deltaSec < 5) return isZh ? '刚刚' : 'just now';
if (deltaSec < 60) return isZh ? `${deltaSec}秒前` : `${deltaSec}s ago`;
const mins = Math.floor(deltaSec / 60);
if (mins < 60) return isZh ? `${mins}分钟前` : `${mins}m ago`;
const hours = Math.floor(mins / 60);
return isZh ? `${hours}小时前` : `${hours}h ago`;
}
export function formatMemoryPercent(memUsed: number | null | undefined, memTotal: number | null | undefined): number | null {
if (memUsed == null || memTotal == null || !Number.isFinite(memUsed) || !Number.isFinite(memTotal) || memTotal <= 0) {
return null;
}
return Math.max(0, Math.min(100, (memUsed / memTotal) * 100));
}
export function formatCompactCount(value: number | null | undefined): string {
if (value == null || !Number.isFinite(value) || value < 0) return '--';
if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
return `${Math.round(value)}`;
}
export function formatIops(readIops: number | null | undefined, writeIops: number | null | undefined): string {
if (readIops == null && writeIops == null) return '--';
const r = readIops != null && Number.isFinite(readIops) ? Math.round(readIops) : 0;
const w = writeIops != null && Number.isFinite(writeIops) ? Math.round(writeIops) : 0;
return `${formatCompactCount(r)}/${formatCompactCount(w)} IOPS`;
}
export function formatMarkdownDiagnostics(input: {
title: string;
generatedAt: string;
hosts: Array<{
label: string;
hostname?: string;
status: string;
cpu?: number | null;
memPercent?: number | null;
diskPercent?: number | null;
load?: string;
latency?: string;
os?: string;
}>;
activeAlerts: Array<{ severity: string; message: string }>;
}): string {
const lines: string[] = [
`# Netcatty Monitor Diagnostics — ${input.title}`,
``,
`Generated: ${input.generatedAt}`,
``,
`## Fleet Summary`,
``,
`| Host | Status | CPU | Memory | Disk | Load | Latency | OS |`,
`| --- | --- | --- | --- | --- | --- | --- | --- |`,
];
for (const h of input.hosts) {
lines.push(
`| ${h.label}${h.hostname ? ` (${h.hostname})` : ''} | ${h.status} | ${formatPercent(h.cpu, 1)} | ${formatPercent(h.memPercent, 1)} | ${formatPercent(h.diskPercent, 0)} | ${h.load ?? '--'} | ${h.latency ?? '--'} | ${h.os ?? '--'} |`,
);
}
lines.push(``, `## Active Alerts (${input.activeAlerts.length})`, ``);
if (input.activeAlerts.length === 0) {
lines.push(`- None (all monitored hosts healthy)`);
} else {
for (const a of input.activeAlerts) {
lines.push(`- **[${a.severity.toUpperCase()}]** ${a.message}`);
}
}
return `${lines.join('\n')}\n`;
}
-120
View File
@@ -1,120 +0,0 @@
import type { MonitorGpuCard, MonitorThermalSensor } from './types';
// Exact parity with Netcatty electron/bridges/sshBridge/monitorGpuStats.cjs + extended temp/power/AMD support.
export const GPU_ASSIGNMENT = `gpustat=$(gpucsv=$(timeout -s KILL 2 nvidia-smi --query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw --format=csv,noheader,nounits 2>/dev/null) && [ -n "$gpucsv" ] && printf '%s\\n' "$gpucsv" | awk -F', *' 'NF >= 5 {idx=$1; hasExt=(NF>=7); pwr=(hasExt?$NF:"N/A"); temp=(hasExt?$(NF-1):"N/A"); total=(hasExt?$(NF-2):$NF); used=(hasExt?$(NF-3):$(NF-1)); util=(hasExt?$(NF-4):$(NF-2)); nameEnd=(hasExt?NF-5:NF-3); gsub(/^[ \\t"]+|[ \\t"]+$/, "", idx); gsub(/^[ \\t"]+|[ \\t"]+$/, "", util); gsub(/^[ \\t"]+|[ \\t"]+$/, "", used); gsub(/^[ \\t"]+|[ \\t"]+$/, "", total); gsub(/^[ \\t"]+|[ \\t"]+$/, "", temp); gsub(/^[ \\t"]+|[ \\t"]+$/, "", pwr); if (idx !~ /^[0-9]+$/) next; name=$2; for (i=3; i<=nameEnd; i++) name=name ", " $i; gsub(/^[ \\t"]+|[ \\t"]+$/, "", name); gsub(/\\t/, " ", name); gsub(/\\|/, "/", name); gsub(/ ;; /, " ", name); g++; if (util ~ /^[0-9]+(\\.[0-9]+)?$/) {n++; u+=util} if (used ~ /^[0-9]+(\\.[0-9]+)?$/) {mu+=used; uc++} if (total ~ /^[0-9]+(\\.[0-9]+)?$/) {mt+=total; tc++} if (name0=="") name0=name; utilOut=(util ~ /^[0-9]+(\\.[0-9]+)?$/) ? sprintf("%.0f", util) : "N/A"; usedOut=(used ~ /^[0-9]+(\\.[0-9]+)?$/) ? sprintf("%.0f", used) : "N/A"; totalOut=(total ~ /^[0-9]+(\\.[0-9]+)?$/) ? sprintf("%.0f", total) : "N/A"; tempOut=(temp ~ /^[0-9]+(\\.[0-9]+)?$/) ? sprintf("%.0f", temp) : "N/A"; pwrOut=(pwr ~ /^[0-9]+(\\.[0-9]+)?$/) ? sprintf("%.1f", pwr) : "N/A"; rec=idx "\\t" name "\\t" utilOut "\\t" usedOut "\\t" totalOut "\\t" tempOut "\\t" pwrOut; list=(list=="") ? rec : list " ;; " rec} END{if (n>0) {printf "%.0f %s %s %s", u/n, (uc==g ? sprintf("%.0f", mu) : "N/A"), (tc==g ? sprintf("%.0f", mt) : "N/A"), name0; if (list != "") printf " ;; %s", list}}' 2>/dev/null || for c in /sys/class/drm/card[0-9]*/device; do [ -r "$c/gpu_busy_percent" ] || continue; b=$(cat "$c/gpu_busy_percent" 2>/dev/null); vu=$(cat "$c/mem_info_vram_used" 2>/dev/null || echo 0); vt=$(cat "$c/mem_info_vram_total" 2>/dev/null || echo 0); idx=$(basename "$(dirname "$c")" | sed 's/card//'); um=$(awk -v v="$vu" 'BEGIN{printf "%.0f", v/1048576}'); tm=$(awk -v v="$vt" 'BEGIN{printf "%.0f", v/1048576}'); printf "%s %s %s AMD GPU ;; %s\\tAMD GPU %s\\t%s\\t%s\\t%s\\tN/A\\tN/A" "$b" "$um" "$tm" "$idx" "$idx" "$b" "$um" "$tm"; break; done)`;
export const THERMAL_ASSIGNMENT = String.raw`thermals=$(for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] || continue; t=$(cat "$z/temp" 2>/dev/null); lbl=$(cat "$z/type" 2>/dev/null || basename "$z"); printf "%s:%s," "$lbl" "$t"; done | sed 's/,$//')`;
export interface ParsedGpuStats {
gpu: number | null;
gpuName: string | null;
gpuMemUsed: number | null;
gpuMemTotal: number | null;
gpus: MonitorGpuCard[];
}
const GPU_LIST_MARK = ' ;; ';
export function emptyGpuStats(): ParsedGpuStats {
return {
gpu: null,
gpuName: null,
gpuMemUsed: null,
gpuMemTotal: null,
gpus: [],
};
}
function parseGpuNumber(value: string | null | undefined): number | null {
if (value == null) return null;
const trimmed = String(value).trim();
if (!/^[0-9]+(?:\.[0-9]+)?$/.test(trimmed)) return null;
const num = Number(trimmed);
return Number.isFinite(num) ? num : null;
}
export function parseGpuCard(record: string): MonitorGpuCard | null {
const fields = String(record || '').split('\t');
if (fields.length < 5) return null;
const indexRaw = parseGpuNumber(fields[0]);
if (indexRaw == null) return null;
const index = Math.trunc(indexRaw);
const hasExtended = fields.length >= 7;
const powerWatts = hasExtended ? parseGpuNumber(fields[fields.length - 1]) : null;
const temperatureC = hasExtended ? parseGpuNumber(fields[fields.length - 2]) : null;
const memoryTotal = parseGpuNumber(fields[hasExtended ? fields.length - 3 : fields.length - 1]);
const memoryUsed = parseGpuNumber(fields[hasExtended ? fields.length - 4 : fields.length - 2]);
const utilization = parseGpuNumber(fields[hasExtended ? fields.length - 5 : fields.length - 3]);
const nameEnd = hasExtended ? fields.length - 5 : fields.length - 3;
const name = fields.slice(1, nameEnd).join('\t').trim();
const vendor = /nvidia|geforce|rtx|gtx|tesla|quadro|a100|h100|l40/i.test(name)
? 'nvidia'
: /amd|radeon|instinct|mi\d+/i.test(name)
? 'amd'
: /intel|arc|iris/i.test(name)
? 'intel'
: 'unknown';
return {
index,
name,
vendor,
utilization: utilization == null ? null : Math.max(0, Math.min(100, Math.round(utilization))),
memoryUsed: memoryUsed == null ? null : Math.round(memoryUsed),
memoryTotal: memoryTotal == null ? null : Math.round(memoryTotal),
...(temperatureC != null ? { temperatureC: Math.round(temperatureC) } : {}),
...(powerWatts != null ? { powerWatts } : {}),
};
}
export function parseGpuStats(output: string | null | undefined): ParsedGpuStats {
const payload =
String(output || '')
.split('|')
.find((part) => part.startsWith('GPU:'))
?.slice(4)
.trim() ?? '';
if (!payload) return emptyGpuStats();
const markAt = payload.indexOf(GPU_LIST_MARK);
const summary = (markAt === -1 ? payload : payload.slice(0, markAt)).trim();
const list = markAt === -1 ? '' : payload.slice(markAt + GPU_LIST_MARK.length);
const raw = summary.split(/\s+/).filter(Boolean);
const utilization = parseGpuNumber(raw[0]);
if (utilization == null) return emptyGpuStats();
const gpus = list
? list
.split(GPU_LIST_MARK)
.map(parseGpuCard)
.filter((card): card is MonitorGpuCard => card !== null)
: [];
const memUsed = parseGpuNumber(raw[1]);
const memTotal = parseGpuNumber(raw[2]);
return {
gpu: Math.max(0, Math.min(100, Math.round(utilization))),
gpuName: raw.slice(3).join(' ') || null,
gpuMemUsed: memUsed == null ? null : Math.round(memUsed),
gpuMemTotal: memTotal == null ? null : Math.round(memTotal),
gpus,
};
}
export function parseThermalSensors(raw: string | null | undefined): MonitorThermalSensor[] {
if (!raw || !raw.trim()) return [];
const sensors: MonitorThermalSensor[] = [];
const seen = new Map<string, number>();
for (const entry of raw.split(',')) {
const idx = entry.lastIndexOf(':');
if (idx <= 0) continue;
const rawLabel = entry.slice(0, idx).trim();
const rawValue = Number(entry.slice(idx + 1).trim());
if (!rawLabel || !Number.isFinite(rawValue)) continue;
// Linux thermal_zone temp is in millidegrees Celsius when > 200.
const temperatureC = rawValue > 200 ? Number((rawValue / 1000).toFixed(1)) : Number(rawValue.toFixed(1));
if (temperatureC < -50 || temperatureC > 180) continue;
const count = (seen.get(rawLabel) ?? 0) + 1;
seen.set(rawLabel, count);
const id = count === 1 ? rawLabel : `${rawLabel}-${count}`;
const label = count === 1 ? rawLabel : `${rawLabel} #${count}`;
sensors.push({ id, label, temperatureC });
}
return sensors;
}
-447
View File
@@ -1,447 +0,0 @@
export type MonitorLocale = 'en' | 'zh-CN';
const EN = {
appTitle: 'Monitor',
appSubtitle: 'Agentless SSH fleet observability & operations',
fleetOverview: 'Fleet Overview',
panels: 'Panels',
newPanel: 'New Panel',
editPanel: 'Edit Panel',
duplicatePanel: 'Duplicate',
deletePanel: 'Delete Panel',
panelName: 'Panel Name',
panelDescription: 'Description',
selectHosts: 'Select Vault Hosts',
addHosts: 'Add Hosts',
removeHost: 'Remove Host',
startMonitoring: 'Start',
stopMonitoring: 'Pause',
stopAll: 'Stop All',
refreshNow: 'Refresh',
viewGrid: 'Cards',
viewTable: 'Table',
viewWallboard: 'Wallboard',
viewCompare: 'Compare',
compareSelectHint: 'Select 2–6 hosts to overlay CPU, Memory, Network, Disk I/O, and Latency curves side-by-side.',
compareNeedMore: 'Add at least 2 hosts to compare metrics side-by-side.',
customizeWidgets: 'Widgets',
widgetCpuBreakdown: 'CPU Breakdown',
widgetMemoryPsi: 'Memory & PSI',
widgetNetworkTcp: 'Network & TCP',
widgetDiskIoMounts: 'Disk I/O & Mounts',
widgetPerCore: 'Per-Core Matrix',
widgetGpuThermals: 'GPU & Thermals',
widgetSystemSecurity: 'System & Security',
cpuUser: 'User',
cpuSystem: 'System',
cpuCtxt: 'Ctx/s',
cpuIntr: 'Intr/s',
cpuProcs: 'Run/Blk',
memActive: 'Active',
memSlab: 'Slab',
psiPressure: 'Linux PSI Pressure',
psiCpu: 'CPU some',
psiMem: 'Mem some/full',
psiIo: 'I/O some/full',
netPps: 'Packets',
netDrops: 'Drops/Errs',
tcpRetrans: 'TCP Retrans',
diskIops: 'IOPS',
diskUtil: 'Util / QDepth',
inodesLabel: 'Inodes',
openFds: 'Open FDs',
activeUsersLabel: 'Logged-in Users',
rebootPending: 'Reboot Required',
auditTitle: 'System & Security Audit',
recentLogins: 'Recent SSH Logins',
failedAuth24h: 'Failed Auth (24h)',
copyDiagnostics: 'Copy Diagnostics',
exportMarkdown: 'MD',
procStateAll: 'All',
procStateRunning: 'Running',
procStateSleeping: 'Sleeping',
procStateZombie: 'Zombie',
procTopCpu: 'Top CPU',
procTopMem: 'Top Memory',
actionStart: 'Start',
actionStop: 'Stop',
actionRestart: 'Restart',
actionReload: 'Reload',
confirmOpTitle: 'Confirm Service / Container Action',
socketsSynRecv: 'SYN_RECV',
thresholdIowait: 'CPU IOwait (%)',
thresholdInode: 'Inode Usage (%)',
thresholdNetDrops: 'Net Drops / Poll',
thresholdConsecutive: 'Hysteresis (consecutive polls)',
incidentTimeline: 'Incident Timeline',
interval: 'Interval',
range: 'Window',
sortBy: 'Sort',
sortManual: 'Manual',
sortName: 'Name',
sortHealth: 'Health',
sortCpu: 'CPU %',
sortMemory: 'Memory %',
searchHosts: 'Search hosts, tags, groups, notes...',
allHosts: 'All',
pinnedOnly: 'Pinned',
alertsOnly: 'Alerts',
pinHost: 'Pin host',
unpinHost: 'Unpin host',
openTerminal: 'Terminal',
openSftp: 'SFTP',
openRemoteDesktop: 'Remote Desktop',
probeReachable: 'Reachable',
probeUnreachable: 'Unreachable',
probeBannerVerified: 'Banner Verified',
probeRttStats: 'TCP RTT (Min / Avg / Max)',
probeLatencyTrend: 'Reachability & TCP Latency',
inspectHost: 'Inspect',
retryHost: 'Retry',
backToFleet: 'Back to Fleet',
columns: 'Columns',
statusLive: 'Live',
statusStale: 'Stale',
statusQueued: 'Queued',
statusConnecting: 'Connecting',
statusOffline: 'Offline',
statusLogin: 'Auth Required',
statusError: 'Error',
statusUnsupported: 'Unsupported',
statusDisconnected: 'Disconnected',
statusIdle: 'Paused',
healthHealthy: 'Healthy',
healthWarning: 'Warning',
healthCritical: 'Critical',
healthOffline: 'Offline',
healthPending: 'Pending',
summaryTotal: 'Hosts',
summaryOnline: 'Online',
summaryWarnings: 'Warnings',
summaryCritical: 'Critical',
summaryAvgCpu: 'Avg CPU',
summaryAvgMem: 'Avg Mem',
tabOverview: 'Overview',
tabProcesses: 'Processes',
tabServices: 'Services & Containers',
tabNetwork: 'Network & Ports',
tabAlerts: 'Alerts & Rules',
metricCpu: 'CPU',
metricMemory: 'Memory',
metricSwap: 'Swap',
metricDisk: 'Disk',
metricDiskIo: 'Disk I/O',
metricNetwork: 'Network',
metricLatency: 'Latency',
metricLoad: 'Load Avg',
metricUptime: 'Uptime',
metricGpu: 'GPU',
metricThermals: 'Thermals',
cpuPerCore: 'Per-Core Utilization',
cpuIowait: 'IOwait',
cpuSteal: 'Steal',
memBuffers: 'Buffers',
memCached: 'Cached',
memFree: 'Free',
diskMounts: 'Disk Mounts & Usage',
systemDisks: 'System Mounts',
showSystemDisks: 'Show system mounts',
hideSystemDisks: 'Hide system mounts',
hostMetadata: 'Host Metadata',
metaHostname: 'Hostname',
metaOs: 'Operating System',
metaKernel: 'Kernel',
metaArch: 'Cores',
metaAddress: 'Address',
metaGroup: 'Group',
metaTags: 'Tags',
metaNotes: 'Notes',
processesTitle: 'Live Processes',
searchProcesses: 'Filter by PID, user, or command...',
processKillTerm: 'Terminate (SIGTERM)',
processKillForce: 'Force Kill (SIGKILL)',
processConfirmTitle: 'Confirm Process Signal',
processConfirmBody: 'Send signal to PID',
processCancel: 'Cancel',
processSendSignal: 'Send Signal',
servicesTitle: 'systemd Services',
containersTitle: 'Containers (Docker / Podman)',
searchServices: 'Filter services or containers...',
viewLogs: 'Logs',
closeLogs: 'Close Logs',
logsLoading: 'Loading logs...',
noServices: 'No systemd services detected on this host.',
noContainers: 'No Docker or Podman containers detected.',
portsTitle: 'Listening Ports & Sockets',
searchPorts: 'Filter by port, address, or process...',
socketsTotal: 'Total',
socketsEstablished: 'Established',
socketsListen: 'Listening',
socketsTimeWait: 'TIME_WAIT',
socketsCloseWait: 'CLOSE_WAIT',
alertsTitle: 'Alert Feed',
alertRulesTitle: 'Threshold Rules',
acknowledge: 'Ack',
acknowledgeAll: 'Ack All',
clearResolved: 'Clear Resolved',
noAlerts: 'No active or recent alerts. Fleet is healthy.',
saveThresholds: 'Save Thresholds',
resetDefaults: 'Reset Defaults',
thresholdWarn: 'Warning',
thresholdCrit: 'Critical',
thresholdOffline: 'Alert when host goes offline or errors',
emptyTitle: 'Monitor Your SSH Fleet',
emptyBody: 'Select saved hosts from your Netcatty Vault to monitor live CPU, memory, disks, GPU, processes, systemd services, containers, and listening ports — zero remote agents required.',
emptyAction: 'Select Vault Hosts',
emptyPanelTitle: 'No hosts in this panel',
emptyPanelBody: 'Add one or more Vault hosts to begin real-time SSH telemetry.',
save: 'Save',
cancel: 'Cancel',
close: 'Close',
moveUp: 'Move Up',
moveDown: 'Move Down',
copyCommand: 'Copy Command',
copied: 'Copied',
netRx: 'RX',
netTx: 'TX',
diskRead: 'Read',
diskWrite: 'Write',
updatedAt: 'Updated',
gpuVram: 'VRAM',
gpuTemp: 'Temp',
gpuPower: 'Power',
allStates: 'All States',
activeOnly: 'Active',
failedOnly: 'Failed',
loadingData: 'Collecting telemetry...',
execUnavailable: 'Host SSH execution capability is not enabled yet.',
} as const;
export type I18nKey = keyof typeof EN;
const ZH_CN: Record<I18nKey, string> = {
appTitle: '监控',
appSubtitle: '无 Agent SSH 服务器集群监控与运维工作台',
fleetOverview: '集群总览',
panels: '监控面板',
newPanel: '新建面板',
editPanel: '编辑面板',
duplicatePanel: '复制面板',
deletePanel: '删除面板',
panelName: '面板名称',
panelDescription: '描述',
selectHosts: '选择 Vault 主机',
addHosts: '添加主机',
removeHost: '移除主机',
startMonitoring: '开始监控',
stopMonitoring: '暂停监控',
stopAll: '全部停止',
refreshNow: '立即刷新',
viewGrid: '卡片',
viewTable: '表格',
viewWallboard: '大屏矩阵',
viewCompare: '多机对比',
compareSelectHint: '选择 2–6 台主机同屏叠加对比 CPU、内存、网络、磁盘 I/O 与延迟曲线。',
compareNeedMore: '请至少添加 2 台主机以进行多机指标对比。',
customizeWidgets: '定制组件',
widgetCpuBreakdown: 'CPU 细分',
widgetMemoryPsi: '内存与 PSI',
widgetNetworkTcp: '网络与 TCP',
widgetDiskIoMounts: '磁盘 I/O 与挂载',
widgetPerCore: '多核热力图',
widgetGpuThermals: 'GPU 与温度',
widgetSystemSecurity: '系统与安全',
cpuUser: '用户态',
cpuSystem: '内核态',
cpuCtxt: '上下文切换/s',
cpuIntr: '中断/s',
cpuProcs: '运行/阻塞',
memActive: '活跃内存',
memSlab: 'Slab',
psiPressure: 'Linux PSI 压力指标',
psiCpu: 'CPU some',
psiMem: '内存 some/full',
psiIo: 'I/O some/full',
netPps: '包速率',
netDrops: '丢包/错包',
tcpRetrans: 'TCP 重传',
diskIops: 'IOPS',
diskUtil: '繁忙度 / 队列',
inodesLabel: 'Inode',
openFds: '文件句柄 FD',
activeUsersLabel: '在线会话用户',
rebootPending: '待重启生效',
auditTitle: '系统与安全审计',
recentLogins: '近期 SSH 登录记录',
failedAuth24h: '24h 认证失败次数',
copyDiagnostics: '复制诊断摘要',
exportMarkdown: 'MD',
procStateAll: '全部',
procStateRunning: '运行中',
procStateSleeping: '休眠',
procStateZombie: '僵尸',
procTopCpu: 'CPU 占比最高',
procTopMem: '内存占比最高',
actionStart: '启动',
actionStop: '停止',
actionRestart: '重启',
actionReload: '重载',
confirmOpTitle: '确认服务 / 容器操作',
socketsSynRecv: 'SYN_RECV',
thresholdIowait: 'CPU IO 等待 (%)',
thresholdInode: 'Inode 占用 (%)',
thresholdNetDrops: '单次采样丢包数',
thresholdConsecutive: '防抖连续触发次数',
incidentTimeline: '告警事件时间线',
interval: '刷新间隔',
range: '时间窗口',
sortBy: '排序',
sortManual: '手动',
sortName: '名称',
sortHealth: '健康度',
sortCpu: 'CPU 占用',
sortMemory: '内存占用',
searchHosts: '搜索主机名、标签、分组、备注...',
allHosts: '全部',
pinnedOnly: '已置顶',
alertsOnly: '有告警',
pinHost: '置顶主机',
unpinHost: '取消置顶',
openTerminal: '终端',
openSftp: 'SFTP',
openRemoteDesktop: '远程桌面',
probeReachable: '可达',
probeUnreachable: '不可达',
probeBannerVerified: '协议握手已验证',
probeRttStats: 'TCP 延迟 (最小 / 平均 / 最大)',
probeLatencyTrend: '连通性与 TCP 延迟趋势',
inspectHost: '详情',
retryHost: '重试',
backToFleet: '返回集群',
columns: '显示列',
statusLive: '在线',
statusStale: '延迟',
statusQueued: '排队中',
statusConnecting: '连接中',
statusOffline: '离线',
statusLogin: '需认证',
statusError: '错误',
statusUnsupported: '不支持',
statusDisconnected: '已断开',
statusIdle: '已暂停',
healthHealthy: '健康',
healthWarning: '警告',
healthCritical: '严重',
healthOffline: '离线',
healthPending: '等待采样',
summaryTotal: '主机数',
summaryOnline: '在线',
summaryWarnings: '警告',
summaryCritical: '严重',
summaryAvgCpu: '平均 CPU',
summaryAvgMem: '平均内存',
tabOverview: '概览与图表',
tabProcesses: '进程管理',
tabServices: '服务与容器',
tabNetwork: '网络与端口',
tabAlerts: '告警与阈值',
metricCpu: 'CPU',
metricMemory: '内存',
metricSwap: '交换分区',
metricDisk: '磁盘',
metricDiskIo: '磁盘 I/O',
metricNetwork: '网络',
metricLatency: '延迟',
metricLoad: '负载',
metricUptime: '运行时长',
metricGpu: 'GPU',
metricThermals: '温度传感器',
cpuPerCore: '各核心占用',
cpuIowait: 'IO 等待',
cpuSteal: '虚拟化抢占',
memBuffers: '缓冲',
memCached: '缓存',
memFree: '空闲',
diskMounts: '磁盘挂载与使用率',
systemDisks: '系统挂载点',
showSystemDisks: '展开系统挂载点',
hideSystemDisks: '收起系统挂载点',
hostMetadata: '主机信息',
metaHostname: '主机名',
metaOs: '操作系统',
metaKernel: '内核版本',
metaArch: 'CPU 核心',
metaAddress: '地址',
metaGroup: '分组',
metaTags: '标签',
metaNotes: '备注',
processesTitle: '实时进程',
searchProcesses: '按 PID、用户或命令行筛选...',
processKillTerm: '终止 (SIGTERM)',
processKillForce: '强制结束 (SIGKILL)',
processConfirmTitle: '确认发送进程信号',
processConfirmBody: '确认向以下进程发送信号',
processCancel: '取消',
processSendSignal: '发送信号',
servicesTitle: 'systemd 系统服务',
containersTitle: '容器 (Docker / Podman)',
searchServices: '筛选服务或容器...',
viewLogs: '查看日志',
closeLogs: '关闭日志',
logsLoading: '正在加载日志...',
noServices: '当前主机未检测到 systemd 服务。',
noContainers: '当前主机未检测到 Docker 或 Podman 容器。',
portsTitle: '监听端口与连接统计',
searchPorts: '按端口、地址或进程名筛选...',
socketsTotal: '总连接',
socketsEstablished: '已建立',
socketsListen: '监听中',
socketsTimeWait: 'TIME_WAIT',
socketsCloseWait: 'CLOSE_WAIT',
alertsTitle: '告警动态',
alertRulesTitle: '阈值规则配置',
acknowledge: '确认',
acknowledgeAll: '全部确认',
clearResolved: '清除已恢复',
noAlerts: '暂无活动或近期告警,集群运行健康。',
saveThresholds: '保存阈值',
resetDefaults: '恢复默认',
thresholdWarn: '警告阈值',
thresholdCrit: '严重阈值',
thresholdOffline: '主机离线或采集异常时触发告警',
emptyTitle: '监控您的 SSH 服务器集群',
emptyBody: '从 Netcatty Vault 选择已保存的 SSH 主机,实时掌握 CPU、内存、磁盘、GPU、进程、systemd 服务、容器与监听端口 — 无需安装任何远端 Agent。',
emptyAction: '选择 Vault 主机',
emptyPanelTitle: '当前面板暂无主机',
emptyPanelBody: '添加一台或多台 Vault 主机以开始实时 SSH 监控。',
save: '保存',
cancel: '取消',
close: '关闭',
moveUp: '上移',
moveDown: '下移',
copyCommand: '复制命令',
copied: '已复制',
netRx: '下行',
netTx: '上行',
diskRead: '读取',
diskWrite: '写入',
updatedAt: '更新于',
gpuVram: '显存',
gpuTemp: '温度',
gpuPower: '功耗',
allStates: '全部状态',
activeOnly: '运行中',
failedOnly: '异常/失败',
loadingData: '正在采集数据...',
execUnavailable: '宿主 SSH 命令执行能力尚未就绪。',
};
export function resolveMonitorLocale(rawLocale?: string | null): MonitorLocale {
if (rawLocale && rawLocale.toLowerCase().startsWith('zh')) return 'zh-CN';
return 'en';
}
export function createTranslator(locale: MonitorLocale): (key: I18nKey) => string {
const dict = locale === 'zh-CN' ? ZH_CN : EN;
return (key: I18nKey) => dict[key] ?? EN[key];
}
@@ -1,121 +0,0 @@
import type { MonitorInterval, MonitorPanel, MonitorRangeMinutes, MonitorViewMode, OverviewWidgetKey } from './types';
export const MONITOR_INTERVALS: readonly MonitorInterval[] = [1, 2, 3, 5, 10, 30, 60];
export const MONITOR_RANGES: readonly MonitorRangeMinutes[] = [1, 5, 15, 30, 60];
export const DEFAULT_MONITOR_INTERVAL: MonitorInterval = 5;
export const ALL_OVERVIEW_WIDGETS: readonly OverviewWidgetKey[] = [
'cpuBreakdown',
'memoryPsi',
'networkTcp',
'diskIoMounts',
'perCore',
'gpuThermals',
'systemSecurity',
];
export function normalizeVisibleWidgets(raw: unknown): OverviewWidgetKey[] {
if (!Array.isArray(raw)) return [...ALL_OVERVIEW_WIDGETS];
const valid = raw.filter((k): k is OverviewWidgetKey =>
typeof k === 'string' && (ALL_OVERVIEW_WIDGETS as readonly string[]).includes(k),
);
return valid.length > 0 ? [...new Set(valid)] : [...ALL_OVERVIEW_WIDGETS];
}
function normalizeViewMode(value: unknown): MonitorViewMode {
if (value === 'charts' || value === 'list' || value === 'wallboard' || value === 'compare') return value;
return 'list';
}
function normalizeRange(value: unknown): MonitorRangeMinutes {
if (value === 1 || value === 5 || value === 15 || value === 30 || value === 60) return value;
return 30;
}
export function normalizeMonitorPanels(value: unknown): MonitorPanel[] {
if (!Array.isArray(value)) return [];
const ids = new Set<string>();
const panels = value.flatMap((raw): MonitorPanel[] => {
if (!raw || typeof raw !== 'object') return [];
const p = raw as Record<string, unknown>;
if (typeof p.id !== 'string' || !p.id || ids.has(p.id) || typeof p.name !== 'string' || !p.name.trim()) {
return [];
}
ids.add(p.id);
const sortVal =
p.sort === 'name' || p.sort === 'health' || p.sort === 'cpu' || p.sort === 'memory'
? p.sort
: 'manual';
const hostIds = Array.isArray(p.hostIds)
? [...new Set(p.hostIds.filter((id): id is string => typeof id === 'string' && !!id))]
: [];
const compareHostIds = Array.isArray(p.compareHostIds)
? [...new Set(p.compareHostIds.filter((id): id is string => typeof id === 'string' && hostIds.includes(id)))].slice(0, 6)
: undefined;
return [
{
id: p.id,
name: p.name.trim().slice(0, 120),
description: typeof p.description === 'string' ? p.description.slice(0, 1000) : '',
hostIds,
view: normalizeViewMode(p.view),
interval: MONITOR_INTERVALS.includes(p.interval as MonitorInterval)
? (p.interval as MonitorInterval)
: DEFAULT_MONITOR_INTERVAL,
range: normalizeRange(p.range),
sort: sortVal,
...(compareHostIds && compareHostIds.length > 0 ? { compareHostIds } : {}),
},
];
});
const reserved = new Set(panels.map((p) => p.name.toLowerCase()));
const seenNames = new Set<string>();
const namesById = new Map<string, string>();
for (const p of [...panels].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) {
const key = p.name.toLowerCase();
if (!seenNames.has(key)) {
seenNames.add(key);
continue;
}
let suffix = 2;
let name: string;
do {
const ending = ` (${suffix++})`;
name = p.name.slice(0, 120 - ending.length).trimEnd() + ending;
} while (reserved.has(name.toLowerCase()));
reserved.add(name.toLowerCase());
namesById.set(p.id, name);
}
return panels.map((p) => (namesById.has(p.id) ? { ...p, name: namesById.get(p.id)! } : p));
}
export function reorderMonitorHosts(hostIds: string[], from: string, to: string): string[] {
const fromIndex = hostIds.indexOf(from);
const toIndex = hostIds.indexOf(to);
if (fromIndex < 0 || toIndex < 0 || fromIndex === toIndex) return hostIds;
const next = [...hostIds];
next.splice(fromIndex, 1);
next.splice(toIndex, 0, from);
return next;
}
export function rebaseMonitorPanel(
latest: MonitorPanel[],
base: MonitorPanel | null,
next: MonitorPanel,
): MonitorPanel[] {
const current = latest.find((p) => p.id === next.id);
if (base && !current) throw new Error('monitor.deleted');
const merged = { ...(current ?? next) };
for (const field of Object.keys(next) as (keyof MonitorPanel)[]) {
if (!base || JSON.stringify(base[field]) !== JSON.stringify(next[field])) {
Object.assign(merged, { [field]: next[field] });
}
}
if (latest.some((p) => p.id !== merged.id && p.name.toLowerCase() === merged.name.trim().toLowerCase())) {
throw new Error('monitor.duplicateName');
}
return normalizeMonitorPanels(
current ? latest.map((p) => (p.id === next.id ? merged : p)) : [...latest, merged],
);
}
@@ -1,861 +0,0 @@
import { diskIoRates, parseDiskIo, withPartitionIo, type DiskIoSnapshot } from './disks';
import { parseGpuStats, parseThermalSensors } from './gpu';
import type {
ContainerRow,
MonitorDiskRow,
MonitorNetInterface,
MonitorOsFamily,
MonitorPsiMetrics,
MonitorStats,
MonitorTopProcess,
PortRow,
ProcessRow,
SocketSummary,
SystemAuditSnapshot,
SystemdServiceRow,
} from './types';
interface RawNetInterfaceSample {
name: string;
rxBytes: number;
txBytes: number;
rxPackets?: number;
txPackets?: number;
rxErrors?: number;
rxDrops?: number;
txErrors?: number;
txDrops?: number;
}
export interface TelemetryDeltaState {
prevCpu?: {
total: number;
idle: number;
iowait: number;
steal: number;
user: number;
system: number;
ctxt?: number;
intr?: number;
perCore: Array<{ total: number; idle: number }>;
timestamp: number;
};
prevNet?: {
interfaces: RawNetInterfaceSample[];
tcpRetransmits?: number | null;
timestamp: number;
};
prevDiskIo?: DiskIoSnapshot | null;
prevPartitionIo?: DiskIoSnapshot | null;
}
export interface PrimaryStatsParseResult {
ok: true;
stats: MonitorStats;
needsSeparateLinuxDisks: boolean;
nextDelta: TelemetryDeltaState;
}
export interface PrimaryStatsParseError {
ok: false;
unsupported?: boolean;
error: string;
}
export function parseDisksPayload(disksStr: string): MonitorDiskRow[] {
const disks: MonitorDiskRow[] = [];
const trimmed = disksStr.trim();
if (!trimmed) return disks;
for (const entry of trimmed.split(',')) {
const diskParts = entry.split(':');
if (diskParts.length < 4) continue;
let mountPoint = diskParts[0];
let offset = 1;
if (/^[A-Za-z]$/.test(mountPoint) && diskParts.length >= 5 && diskParts[1] === '') {
mountPoint = `${mountPoint}:`;
offset = 2;
}
const used = Number.parseFloat(diskParts[offset]);
const total = Number.parseFloat(diskParts[offset + 1]);
let percent = Number.parseInt(diskParts[offset + 2], 10);
if (Number.isNaN(percent) && Number.isFinite(used) && Number.isFinite(total) && total > 0) {
percent = Math.round((used / total) * 100);
}
if (!Number.isNaN(used) && !Number.isNaN(total) && !Number.isNaN(percent) && total > 0) {
const diskMetadata = diskParts.slice(offset + 3).join(':').trim();
let capacityKey = diskMetadata;
let filesystemType: string | undefined;
if (diskMetadata.startsWith('fs=')) {
const separator = diskMetadata.indexOf(':');
if (separator > 3) {
filesystemType = diskMetadata.slice(3, separator).trim();
capacityKey = diskMetadata.slice(separator + 1).trim();
}
}
disks.push({
mountPoint,
used,
total,
percent: Math.max(0, Math.min(100, percent)),
...(capacityKey ? { capacityKey } : {}),
...(filesystemType ? { filesystemType } : {}),
});
}
}
return disks;
}
export function parseInodesPayload(inodesStr: string): Map<string, { inodeUsed: number; inodeTotal: number; inodePercent: number }> {
const map = new Map<string, { inodeUsed: number; inodeTotal: number; inodePercent: number }>();
const trimmed = inodesStr.trim();
if (!trimmed) return map;
for (const entry of trimmed.split(',')) {
const parts = entry.split(':');
if (parts.length < 4) continue;
const mount = parts[0];
const used = Number.parseInt(parts[1], 10);
const total = Number.parseInt(parts[2], 10);
const pct = Number.parseInt(parts[3], 10);
if (mount && Number.isFinite(used) && Number.isFinite(total) && total > 0 && Number.isFinite(pct)) {
map.set(mount, { inodeUsed: used, inodeTotal: total, inodePercent: Math.max(0, Math.min(100, pct)) });
}
}
return map;
}
function parsePsiPayload(raw: string): MonitorPsiMetrics | null {
const trimmed = raw.trim();
if (!trimmed) return null;
const cols = trimmed.split(',');
if (cols.length < 8) return null;
const parseNum = (s: string) => {
const v = Number(s);
return s !== '' && Number.isFinite(v) && v >= 0 ? v : null;
};
const psi: MonitorPsiMetrics = {
cpuSome10: parseNum(cols[0]),
cpuSome60: parseNum(cols[1]),
memSome10: parseNum(cols[2]),
memSome60: parseNum(cols[3]),
memFull10: parseNum(cols[4]),
ioSome10: parseNum(cols[5]),
ioSome60: parseNum(cols[6]),
ioFull10: parseNum(cols[7]),
};
if (Object.values(psi).every((v) => v === null)) return null;
return psi;
}
export function parsePrimaryStatsOutput(
rawStdout: string,
prevDelta: TelemetryDeltaState = {},
options: { now?: number; latencyMs?: number | null; responseLatencyMs?: number | null; linuxDiskStdout?: string } = {},
): PrimaryStatsParseResult | PrimaryStatsParseError {
const now = options.now ?? Date.now();
let combined = String(rawStdout || '').trim().replace(/^NC_LATENCY_MARK\|?/, '');
if (options.linuxDiskStdout) {
const diskTrim = String(options.linuxDiskStdout).trim();
if (diskTrim) combined = `${combined}|${diskTrim}`;
}
if (!combined) {
return { ok: false, error: 'Empty telemetry response' };
}
if (combined.startsWith('UNSUPPORTED_OS:')) {
return {
ok: false,
unsupported: true,
error: `Server stats not supported on this OS (${combined.slice(15).trim() || 'Unknown'})`,
};
}
const parts = combined.split('|');
let osFamily: MonitorOsFamily = 'unknown';
let cpuDirect: number | null = null;
let cpuRawTotal: number | null = null;
let cpuRawIdle: number | null = null;
let cpuRawIowait = 0;
let cpuRawSteal = 0;
let cpuRawUser: number | null = null;
let cpuRawSystem: number | null = null;
let cpuRawCtxt: number | null = null;
let cpuRawIntr: number | null = null;
let procsRunning: number | null = null;
let procsBlocked: number | null = null;
let cpuPerCoreRaw: Array<{ total: number; idle: number }> = [];
let cpuCores: number | null = null;
let memTotal: number | null = null;
let memFree: number | null = null;
let memBuffers: number | null = null;
let memCached: number | null = null;
let memUsed: number | null = null;
let memActive: number | null = null;
let memSlab: number | null = null;
let swapTotal: number | null = null;
let swapUsed: number | null = null;
let psi: MonitorPsiMetrics | null = null;
const topProcesses: MonitorTopProcess[] = [];
let disks: MonitorDiskRow[] = [];
let inodesMap = new Map<string, { inodeUsed: number; inodeTotal: number; inodePercent: number }>();
let diskIo: DiskIoSnapshot | null = null;
let partitionIo: DiskIoSnapshot | null = null;
let diskMounts = '';
const networkInterfaces: RawNetInterfaceSample[] = [];
let tcpRetransmitsRaw: number | null = null;
let fdUsed: number | null = null;
let fdMax: number | null = null;
let activeUsers: number | null = null;
let rebootRequired = false;
let hostname = '';
let osName = '';
let kernelRelease = '';
let uptimeSeconds: number | null = null;
let loadAverage: number[] = [];
let gpu: number | null = null;
let gpuName: string | null = null;
let gpuMemUsed: number | null = null;
let gpuMemTotal: number | null = null;
let gpus: MonitorStats['gpus'] = [];
let thermals: MonitorStats['thermals'] = [];
let sawCpuRaw = false;
for (const part of parts) {
if (part.startsWith('OSFAM:')) {
const fam = part.slice(6).trim().toLowerCase();
if (fam === 'linux' || fam === 'macos' || fam === 'freebsd' || fam === 'openbsd' || fam === 'netbsd' || fam === 'windows') {
osFamily = fam;
}
} else if (part.startsWith('CPU:')) {
const val = Number.parseFloat(part.slice(4).trim());
if (Number.isFinite(val)) cpuDirect = Math.min(100, Math.max(0, Math.round(val)));
} else if (part.startsWith('PARTITIONIO:')) {
partitionIo = parseDiskIo(part.slice(12));
} else if (part.startsWith('DISKMOUNTS:')) {
diskMounts = part.slice(11);
} else if (part.startsWith('DISKIO:')) {
diskIo = parseDiskIo(part.slice(7));
} else if (part.startsWith('CPURAW:')) {
sawCpuRaw = true;
const rawParts = part.slice(7).trim().split(/\s+/);
if (rawParts.length >= 2) {
const t = Number.parseInt(rawParts[0], 10);
const i = Number.parseInt(rawParts[1], 10);
if (Number.isFinite(t) && Number.isFinite(i)) {
cpuRawTotal = t;
cpuRawIdle = i;
if (rawParts.length >= 3) cpuRawIowait = Number.parseInt(rawParts[2], 10) || 0;
if (rawParts.length >= 4) cpuRawSteal = Number.parseInt(rawParts[3], 10) || 0;
if (rawParts.length >= 6) {
const u = Number.parseInt(rawParts[4], 10);
const s = Number.parseInt(rawParts[5], 10);
if (Number.isFinite(u) && Number.isFinite(s)) {
cpuRawUser = u;
cpuRawSystem = s;
}
}
}
}
} else if (part.startsWith('CPUEXTRA:')) {
const extra = part.slice(9).trim().split(/\s+/);
if (extra.length >= 4) {
const cx = Number.parseInt(extra[0], 10);
const ir = Number.parseInt(extra[1], 10);
const pr = Number.parseInt(extra[2], 10);
const pb = Number.parseInt(extra[3], 10);
if (Number.isFinite(cx)) cpuRawCtxt = cx;
if (Number.isFinite(ir)) cpuRawIntr = ir;
if (Number.isFinite(pr)) procsRunning = pr;
if (Number.isFinite(pb)) procsBlocked = pb;
}
} else if (part.startsWith('CORES:')) {
const val = Number.parseInt(part.slice(6).trim(), 10);
if (Number.isFinite(val) && val > 0) cpuCores = val;
} else if (part.startsWith('PERCORERAW:')) {
const coreStr = part.slice(11).trim();
if (coreStr) {
cpuPerCoreRaw = coreStr
.split(',')
.map((v) => {
const coreParts = v.trim().split(':');
if (coreParts.length >= 2) {
const total = Number.parseInt(coreParts[0], 10);
const idle = Number.parseInt(coreParts[1], 10);
if (Number.isFinite(total) && Number.isFinite(idle)) return { total, idle };
}
return null;
})
.filter((v): v is { total: number; idle: number } => v !== null);
}
} else if (part.startsWith('MEMINFO:')) {
const memParts = part.slice(8).trim().split(/\s+/);
if (memParts.length >= 4) {
const total = Number.parseInt(memParts[0], 10);
const free = Number.parseInt(memParts[1], 10);
const buffers = Number.parseInt(memParts[2], 10);
const cached = Number.parseInt(memParts[3], 10);
if (Number.isFinite(total)) memTotal = total;
if (Number.isFinite(free)) memFree = free;
if (Number.isFinite(buffers)) memBuffers = buffers;
if (Number.isFinite(cached)) memCached = cached;
if (memTotal !== null && memFree !== null && memBuffers !== null && memCached !== null) {
memUsed = Math.max(0, memTotal - memFree - memBuffers - memCached);
}
if (memParts.length >= 6) {
const st = Number.parseInt(memParts[4], 10);
const sf = Number.parseInt(memParts[5], 10);
if (Number.isFinite(st)) swapTotal = st;
if (Number.isFinite(sf) && swapTotal !== null) {
swapUsed = Math.max(0, swapTotal - sf);
}
}
if (memParts.length >= 8) {
const ac = Number.parseInt(memParts[6], 10);
const sl = Number.parseInt(memParts[7], 10);
if (Number.isFinite(ac)) memActive = ac;
if (Number.isFinite(sl)) memSlab = sl;
}
}
} else if (part.startsWith('PSI:')) {
psi = parsePsiPayload(part.slice(4));
} else if (part.startsWith('PROCS:')) {
const procsStr = part.slice(6).trim();
if (procsStr) {
for (const entry of procsStr.split(',')) {
const procParts = entry.split(';');
if (procParts.length >= 3) {
const pid = procParts[0];
const memPercent = Number.parseFloat(procParts[1]);
const command = procParts.slice(2).join(';');
if (Number.isFinite(memPercent)) topProcesses.push({ pid, memPercent, command });
}
}
}
} else if (part.startsWith('DISKS:')) {
disks = parseDisksPayload(part.slice(6));
} else if (part.startsWith('INODES:')) {
inodesMap = parseInodesPayload(part.slice(7));
} else if (part.startsWith('NET:')) {
const netStr = part.slice(4).trim();
if (netStr) {
for (const entry of netStr.split(',')) {
const netParts = entry.split(':');
if (netParts.length >= 3) {
const name = netParts[0];
const rxBytes = Number.parseInt(netParts[1], 10);
const txBytes = Number.parseInt(netParts[2], 10);
if (Number.isFinite(rxBytes) && Number.isFinite(txBytes)) {
const sample: RawNetInterfaceSample = { name, rxBytes, txBytes };
if (netParts.length >= 9) {
sample.rxPackets = Number.parseInt(netParts[3], 10) || 0;
sample.txPackets = Number.parseInt(netParts[4], 10) || 0;
sample.rxErrors = Number.parseInt(netParts[5], 10) || 0;
sample.rxDrops = Number.parseInt(netParts[6], 10) || 0;
sample.txErrors = Number.parseInt(netParts[7], 10) || 0;
sample.txDrops = Number.parseInt(netParts[8], 10) || 0;
}
networkInterfaces.push(sample);
}
}
}
}
} else if (part.startsWith('TCPRETRANS:')) {
const val = Number.parseInt(part.slice(11).trim(), 10);
if (Number.isFinite(val) && val >= 0) tcpRetransmitsRaw = val;
} else if (part.startsWith('FD:')) {
const [u, m] = part.slice(3).trim().split(':');
const used = Number.parseInt(u, 10);
const max = Number.parseInt(m, 10);
if (Number.isFinite(used) && Number.isFinite(max) && max > 0) {
fdUsed = used;
fdMax = max;
}
} else if (part.startsWith('USERS:')) {
const val = Number.parseInt(part.slice(6).trim(), 10);
if (Number.isFinite(val) && val >= 0) activeUsers = val;
} else if (part.startsWith('REBOOT:')) {
rebootRequired = part.slice(7).trim() === '1';
} else if (part.startsWith('GPU:')) {
({ gpu, gpuName, gpuMemUsed, gpuMemTotal, gpus } = parseGpuStats(part));
} else if (part.startsWith('THERMALS:')) {
thermals = parseThermalSensors(part.slice(9));
} else if (part.startsWith('HOST:')) {
hostname = part.slice(5).trim();
} else if (part.startsWith('OS:')) {
osName = part.slice(3).trim();
} else if (part.startsWith('KERNEL:')) {
kernelRelease = part.slice(7).trim();
} else if (part.startsWith('UPTIME:')) {
const u = Number(part.slice(7).trim());
if (part.slice(7).trim() !== '' && Number.isFinite(u) && u >= 0) uptimeSeconds = u;
} else if (part.startsWith('LOAD:')) {
const loadText = part.slice(5).trim();
if (loadText) {
loadAverage = loadText
.split(/\s+/)
.map((v) => Number(v))
.filter((v) => Number.isFinite(v) && v >= 0)
.slice(0, 3);
}
}
}
if (osFamily === 'unknown' && sawCpuRaw) osFamily = 'linux';
const diskRates = diskIoRates(diskIo, prevDelta.prevDiskIo);
disks = withPartitionIo(disks, diskMounts, partitionIo, prevDelta.prevPartitionIo).map((disk) => {
const inode = inodesMap.get(disk.mountPoint);
return inode ? { ...disk, ...inode } : disk;
});
// Network rates (bytes/s, pps, errors/drops delta, TCP retransmits/s)
const prevNet = prevDelta.prevNet;
const timeDelta = prevNet && prevNet.timestamp > 0 ? (now - prevNet.timestamp) / 1000 : 0;
let netRxSpeed = 0;
let netTxSpeed = 0;
let netRxPps = 0;
let netTxPps = 0;
let netErrorsDelta = 0;
let netDropsDelta = 0;
const netInterfaces: MonitorNetInterface[] = [];
const networkReady = Boolean(prevNet && prevNet.timestamp > 0 && prevNet.interfaces.length > 0 && timeDelta > 0);
for (const iface of networkInterfaces) {
const prevIface = networkReady ? prevNet!.interfaces.find((p) => p.name === iface.name) : undefined;
const rxDelta = prevIface ? iface.rxBytes - prevIface.rxBytes : 0;
const txDelta = prevIface ? iface.txBytes - prevIface.txBytes : 0;
const rxSpeed = prevIface && rxDelta > 0 ? Math.round(rxDelta / timeDelta) : 0;
const txSpeed = prevIface && txDelta > 0 ? Math.round(txDelta / timeDelta) : 0;
netRxSpeed += rxSpeed;
netTxSpeed += txSpeed;
let rxPps = 0;
let txPps = 0;
if (prevIface && iface.rxPackets != null && prevIface.rxPackets != null && iface.rxPackets >= prevIface.rxPackets) {
rxPps = Math.round((iface.rxPackets - prevIface.rxPackets) / timeDelta);
netRxPps += rxPps;
}
if (prevIface && iface.txPackets != null && prevIface.txPackets != null && iface.txPackets >= prevIface.txPackets) {
txPps = Math.round((iface.txPackets - prevIface.txPackets) / timeDelta);
netTxPps += txPps;
}
if (prevIface && iface.rxErrors != null && prevIface.rxErrors != null && iface.rxErrors > prevIface.rxErrors) {
netErrorsDelta += iface.rxErrors - prevIface.rxErrors;
}
if (prevIface && iface.txErrors != null && prevIface.txErrors != null && iface.txErrors > prevIface.txErrors) {
netErrorsDelta += iface.txErrors - prevIface.txErrors;
}
if (prevIface && iface.rxDrops != null && prevIface.rxDrops != null && iface.rxDrops > prevIface.rxDrops) {
netDropsDelta += iface.rxDrops - prevIface.rxDrops;
}
if (prevIface && iface.txDrops != null && prevIface.txDrops != null && iface.txDrops > prevIface.txDrops) {
netDropsDelta += iface.txDrops - prevIface.txDrops;
}
netInterfaces.push({
...iface,
rxSpeed,
txSpeed,
rxPps,
txPps,
});
}
let tcpRetransmitsPerSec: number | null = null;
if (
networkReady &&
tcpRetransmitsRaw != null &&
prevNet?.tcpRetransmits != null &&
tcpRetransmitsRaw >= prevNet.tcpRetransmits
) {
tcpRetransmitsPerSec = Number(((tcpRetransmitsRaw - prevNet.tcpRetransmits) / timeDelta).toFixed(2));
}
// CPU delta + breakdown
const prevCpu = prevDelta.prevCpu;
let cpu: number | null = null;
let cpuUser: number | null = null;
let cpuSystem: number | null = null;
let cpuIdle: number | null = null;
let cpuIowait: number | null = null;
let cpuSteal: number | null = null;
let contextSwitchesPerSec: number | null = null;
let interruptsPerSec: number | null = null;
let cpuPerCore: number[] = [];
if (cpuRawTotal !== null && cpuRawIdle !== null && prevCpu && prevCpu.total > 0) {
const totalDelta = cpuRawTotal - prevCpu.total;
const idleDelta = cpuRawIdle - prevCpu.idle;
if (totalDelta > 0) {
cpu = Math.max(0, Math.min(100, Math.round(100 - (idleDelta / totalDelta) * 100)));
cpuIdle = Number(Math.max(0, Math.min(100, (idleDelta / totalDelta) * 100)).toFixed(1));
const iowaitDelta = cpuRawIowait - prevCpu.iowait;
const stealDelta = cpuRawSteal - prevCpu.steal;
if (iowaitDelta >= 0) cpuIowait = Number(Math.max(0, Math.min(100, (iowaitDelta / totalDelta) * 100)).toFixed(1));
if (stealDelta >= 0) cpuSteal = Number(Math.max(0, Math.min(100, (stealDelta / totalDelta) * 100)).toFixed(1));
if (cpuRawUser !== null && cpuRawSystem !== null && prevCpu.user >= 0 && prevCpu.system >= 0) {
const userDelta = cpuRawUser - prevCpu.user;
const sysDelta = cpuRawSystem - prevCpu.system;
if (userDelta >= 0) cpuUser = Number(Math.max(0, Math.min(100, (userDelta / totalDelta) * 100)).toFixed(1));
if (sysDelta >= 0) cpuSystem = Number(Math.max(0, Math.min(100, (sysDelta / totalDelta) * 100)).toFixed(1));
}
}
const cpuSec = (now - prevCpu.timestamp) / 1000;
if (cpuSec > 0) {
if (cpuRawCtxt != null && prevCpu.ctxt != null && cpuRawCtxt >= prevCpu.ctxt) {
contextSwitchesPerSec = Math.round((cpuRawCtxt - prevCpu.ctxt) / cpuSec);
}
if (cpuRawIntr != null && prevCpu.intr != null && cpuRawIntr >= prevCpu.intr) {
interruptsPerSec = Math.round((cpuRawIntr - prevCpu.intr) / cpuSec);
}
}
}
if (cpu === null && cpuDirect !== null) {
cpu = cpuDirect;
}
if (cpuPerCoreRaw.length > 0 && prevCpu && prevCpu.perCore.length > 0) {
cpuPerCore = cpuPerCoreRaw.map((core, index) => {
const prevCore = prevCpu.perCore[index];
if (prevCore) {
const totalDelta = core.total - prevCore.total;
const idleDelta = core.idle - prevCore.idle;
if (totalDelta > 0) {
return Math.max(0, Math.min(100, Math.round(100 - (idleDelta / totalDelta) * 100)));
}
}
return 0;
});
} else if (cpuPerCoreRaw.length > 0) {
cpuPerCore = cpuPerCoreRaw.map(() => 0);
}
if (cpu === null && memTotal === null && cpuCores === null) {
return { ok: false, error: 'Unable to parse server stats (unsupported OS or shell)' };
}
const rootDisk = disks.find((d) => d.mountPoint === '/') ?? disks[0];
const nextDelta: TelemetryDeltaState = {
prevCpu:
cpuRawTotal !== null && cpuRawIdle !== null
? {
total: cpuRawTotal,
idle: cpuRawIdle,
iowait: cpuRawIowait,
steal: cpuRawSteal,
user: cpuRawUser ?? -1,
system: cpuRawSystem ?? -1,
ctxt: cpuRawCtxt ?? undefined,
intr: cpuRawIntr ?? undefined,
perCore: cpuPerCoreRaw,
timestamp: now,
}
: prevDelta.prevCpu,
prevNet: {
interfaces: networkInterfaces,
tcpRetransmits: tcpRetransmitsRaw,
timestamp: now,
},
prevDiskIo: diskIo,
prevPartitionIo: partitionIo,
};
return {
ok: true,
needsSeparateLinuxDisks: sawCpuRaw && disks.length === 0,
nextDelta,
stats: {
osFamily,
cpu,
cpuUser,
cpuSystem,
cpuIdle,
cpuIowait,
cpuSteal,
cpuCores,
cpuPerCore,
contextSwitchesPerSec,
interruptsPerSec,
procsRunning,
procsBlocked,
gpu,
gpuName,
gpuMemUsed,
gpuMemTotal,
gpus,
thermals,
psi,
memTotal,
memUsed,
memFree,
memActive,
memSlab,
memBuffers,
memCached,
swapTotal,
swapUsed,
topProcesses,
diskPercent: rootDisk ? rootDisk.percent : null,
diskUsed: rootDisk ? rootDisk.used : null,
diskTotal: rootDisk ? rootDisk.total : null,
disks,
...diskRates,
networkReady,
netRxSpeed,
netTxSpeed,
netRxPps,
netTxPps,
netErrorsDelta,
netDropsDelta,
tcpRetransmitsPerSec,
fdUsed,
fdMax,
activeUsers,
rebootRequired,
latencyMs: options.latencyMs ?? null,
responseLatencyMs: options.responseLatencyMs ?? null,
netInterfaces,
hostname,
osName,
kernelRelease,
uptimeSeconds,
loadAverage,
},
};
}
export function parseProcessesOutput(stdout: string): ProcessRow[] {
const rows: ProcessRow[] = [];
for (const rawLine of String(stdout || '').split(/\r?\n/)) {
const line = rawLine.trim();
if (!line) continue;
const match = line.match(/^(\d+)\s+(\S+)\s+([0-9.]+)\s+([0-9.]+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(.+)$/);
if (!match) continue;
const pid = Number.parseInt(match[1], 10);
const cpuPercent = Number.parseFloat(match[3]);
const memPercent = Number.parseFloat(match[4]);
const rssKb = Number.parseInt(match[5], 10);
if (!Number.isSafeInteger(pid) || !Number.isFinite(cpuPercent) || !Number.isFinite(memPercent)) continue;
rows.push({
pid,
user: match[2],
cpuPercent,
memPercent,
rssKb: Number.isFinite(rssKb) ? rssKb : 0,
state: match[6],
elapsed: match[7],
command: match[8].trim(),
});
}
return rows;
}
export function parseServicesAndContainersOutput(stdout: string): {
services: SystemdServiceRow[];
containers: ContainerRow[];
} {
const services: SystemdServiceRow[] = [];
const containers: ContainerRow[] = [];
let section: 'none' | 'systemd' | 'docker' | 'podman' = 'none';
for (const rawLine of String(stdout || '').split(/\r?\n/)) {
const trimmed = rawLine.trim();
if (trimmed === '__NC_SYSTEMD__') {
section = 'systemd';
continue;
}
if (trimmed === '__NC_DOCKER__') {
section = 'docker';
continue;
}
if (trimmed === '__NC_PODMAN__') {
section = 'podman';
continue;
}
if (!trimmed) continue;
if (section === 'systemd') {
const m = trimmed.match(/^(\S+\.service)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)$/);
if (m) {
services.push({
unit: m[1],
loadState: m[2],
activeState: m[3],
subState: m[4],
description: m[5].trim(),
});
}
} else if (section === 'docker' || section === 'podman') {
const cols = rawLine.split('\t');
if (cols.length >= 5) {
const id = cols[0].trim();
if (!id) continue;
containers.push({
runtime: section,
id: id.slice(0, 12),
name: cols[1].trim(),
image: cols[2].trim(),
state: cols[3].trim(),
status: cols[4].trim(),
ports: (cols[5] ?? '').trim(),
});
}
}
}
return { services, containers };
}
function parseAddressPort(endpoint: string): { address: string; port: number | null } {
const clean = endpoint.trim();
const idx = clean.lastIndexOf(':');
if (idx < 0) return { address: clean, port: null };
const address = clean.slice(0, idx).replace(/^\[|\]$/g, '');
const portStr = clean.slice(idx + 1);
const port = /^\d+$/.test(portStr) ? Number.parseInt(portStr, 10) : null;
return { address, port };
}
export function parsePortsOutput(stdout: string): {
ports: PortRow[];
summary: SocketSummary;
} {
const ports: PortRow[] = [];
const summary: SocketSummary = {
total: 0,
established: 0,
listen: 0,
synRecv: 0,
timeWait: 0,
closeWait: 0,
other: 0,
};
let section: 'ports' | 'summary' = 'ports';
for (const rawLine of String(stdout || '').split(/\r?\n/)) {
const line = rawLine.trim();
if (!line) continue;
if (line === '__NC_PORTS__') {
section = 'ports';
continue;
}
if (line === '__NC_SOCKSUMMARY__') {
section = 'summary';
continue;
}
if (section === 'summary') {
const [stateKey, countRaw] = line.split(':');
const count = Number.parseInt(countRaw, 10);
if (!Number.isFinite(count) || count <= 0) continue;
summary.total += count;
const upper = stateKey.toUpperCase();
if (upper === 'ESTAB' || upper === 'ESTABLISHED') summary.established += count;
else if (upper === 'LISTEN') summary.listen += count;
else if (upper === 'SYN-RECV' || upper === 'SYN_RECV') summary.synRecv += count;
else if (upper === 'TIME-WAIT' || upper === 'TIME_WAIT') summary.timeWait += count;
else if (upper === 'CLOSE-WAIT' || upper === 'CLOSE_WAIT') summary.closeWait += count;
else summary.other += count;
continue;
}
const ssMatch = line.match(/^(tcp|udp|tcp6|udp6)\s+(\S+)\s+\d+\s+\d+\s+(\S+)\s+(\S+)(?:\s+(.*))?$/i);
if (ssMatch) {
const { address, port } = parseAddressPort(ssMatch[3]);
const extra = ssMatch[5] ?? '';
const procMatch = extra.match(/"([^"]+)",pid=(\d+)/);
ports.push({
protocol: ssMatch[1].toLowerCase(),
state: ssMatch[2].toUpperCase(),
localAddress: address,
port,
peerAddress: ssMatch[4],
process: procMatch ? procMatch[1] : '',
pid: procMatch ? Number.parseInt(procMatch[2], 10) : null,
});
continue;
}
const nsMatch = line.match(/^(tcp|udp|tcp6|udp6)\s+\d+\s+\d+\s+(\S+)\s+(\S+)\s+(\S+)?(?:\s+(\d+)\/(\S+))?$/i);
if (nsMatch) {
const { address, port } = parseAddressPort(nsMatch[2]);
ports.push({
protocol: nsMatch[1].toLowerCase(),
state: (nsMatch[4] && !nsMatch[4].includes('/') ? nsMatch[4] : 'LISTEN').toUpperCase(),
localAddress: address,
port,
peerAddress: nsMatch[3],
process: nsMatch[6] ?? '',
pid: nsMatch[5] ? Number.parseInt(nsMatch[5], 10) : null,
});
continue;
}
const lsofMatch = line.match(/^(\S+)\s+(\d+)\s+\S+\s+\S+\s+(IPv[46])\s+\S+\s+\S+\s+(TCP|UDP)\s+(\S+)\s+\(LISTEN\)$/);
if (lsofMatch) {
const { address, port } = parseAddressPort(lsofMatch[5]);
ports.push({
protocol: lsofMatch[4].toLowerCase() + (lsofMatch[3] === 'IPv6' ? '6' : ''),
state: 'LISTEN',
localAddress: address,
port,
peerAddress: '*',
process: lsofMatch[1],
pid: Number.parseInt(lsofMatch[2], 10),
});
}
}
if (summary.total === 0 && ports.length > 0) {
summary.listen = ports.filter((p) => p.state === 'LISTEN' || p.state === 'UNCONN').length;
summary.total = ports.length;
}
return { ports, summary };
}
export function parseSystemAuditOutput(stdout: string): SystemAuditSnapshot {
const result: SystemAuditSnapshot = {
fdUsed: null,
fdMax: null,
loggedInUsers: [],
recentLogins: [],
failedAuthCount: null,
rebootRequired: false,
};
let section: 'none' | 'fd' | 'reboot' | 'who' | 'last' | 'failed' = 'none';
for (const rawLine of String(stdout || '').split(/\r?\n/)) {
const line = rawLine.trim();
if (line === '__NC_FD__') { section = 'fd'; continue; }
if (line === '__NC_REBOOT__') { section = 'reboot'; continue; }
if (line === '__NC_WHO__') { section = 'who'; continue; }
if (line === '__NC_LAST__') { section = 'last'; continue; }
if (line === '__NC_FAILEDAUTH__') { section = 'failed'; continue; }
if (!line) continue;
if (section === 'fd') {
const [u, m] = line.split(':');
const used = Number.parseInt(u, 10);
const max = Number.parseInt(m, 10);
if (Number.isFinite(used) && Number.isFinite(max) && max > 0) {
result.fdUsed = used;
result.fdMax = max;
}
} else if (section === 'reboot') {
result.rebootRequired = line === '1';
} else if (section === 'who') {
const m = line.match(/^(\S+)\s+(\S+)\s+(\S+\s+\S+(?:\s+\S+)?)(?:\s+\(([^)]+)\))?/);
if (m) {
result.loggedInUsers.push({
user: m[1],
tty: m[2],
since: m[3],
from: m[4] ?? 'local',
});
}
} else if (section === 'last') {
if (!/^wtmp begins/i.test(line) && !/^reboot\s+/i.test(line)) {
result.recentLogins.push(line);
}
} else if (section === 'failed') {
const n = Number.parseInt(line, 10);
if (Number.isFinite(n) && n >= 0) result.failedAuthCount = n;
}
}
return result;
}
@@ -1,337 +0,0 @@
export type MonitorInterval = 1 | 2 | 3 | 5 | 10 | 30 | 60;
export type MonitorRangeMinutes = 1 | 5 | 15 | 30 | 60;
export type MonitorViewMode = 'charts' | 'list' | 'wallboard' | 'compare';
export type MonitorHostStatus =
| 'idle'
| 'queued'
| 'connecting'
| 'live'
| 'offline'
| 'login'
| 'error'
| 'unsupported'
| 'disconnected';
export type MonitorOsFamily = 'linux' | 'macos' | 'freebsd' | 'openbsd' | 'netbsd' | 'windows' | 'unknown';
export type OverviewWidgetKey =
| 'cpuBreakdown'
| 'memoryPsi'
| 'networkTcp'
| 'diskIoMounts'
| 'perCore'
| 'gpuThermals'
| 'systemSecurity';
export interface MonitorGpuCard {
index: number;
name: string;
vendor?: 'nvidia' | 'amd' | 'intel' | 'unknown';
utilization: number | null;
memoryUsed: number | null;
memoryTotal: number | null;
temperatureC?: number | null;
powerWatts?: number | null;
}
export interface MonitorThermalSensor {
id: string;
label: string;
temperatureC: number;
criticalC?: number | null;
}
export interface MonitorPsiMetrics {
cpuSome10: number | null;
cpuSome60: number | null;
memSome10: number | null;
memSome60: number | null;
memFull10: number | null;
ioSome10: number | null;
ioSome60: number | null;
ioFull10: number | null;
}
export interface MonitorDiskRow {
mountPoint: string;
used: number | null;
total: number | null;
percent: number | null;
inodeUsed?: number | null;
inodeTotal?: number | null;
inodePercent?: number | null;
capacityKey?: string;
filesystemType?: string;
diskReadSpeed?: number | null;
diskWriteSpeed?: number | null;
}
export interface MonitorNetInterface {
name: string;
rxBytes: number;
txBytes: number;
rxSpeed: number;
txSpeed: number;
rxPackets?: number;
txPackets?: number;
rxPps?: number;
txPps?: number;
rxErrors?: number;
txErrors?: number;
rxDrops?: number;
txDrops?: number;
}
export interface MonitorTopProcess {
pid: string;
memPercent: number;
command: string;
}
export interface MonitorStats {
osFamily: MonitorOsFamily;
cpu: number | null;
cpuUser?: number | null;
cpuSystem?: number | null;
cpuIdle?: number | null;
cpuIowait?: number | null;
cpuSteal?: number | null;
cpuCores: number | null;
cpuPerCore: number[];
contextSwitchesPerSec?: number | null;
interruptsPerSec?: number | null;
procsRunning?: number | null;
procsBlocked?: number | null;
gpu: number | null;
gpuName: string | null;
gpuMemUsed: number | null;
gpuMemTotal: number | null;
gpus: MonitorGpuCard[];
thermals: MonitorThermalSensor[];
psi?: MonitorPsiMetrics | null;
memTotal: number | null;
memUsed: number | null;
memFree: number | null;
memActive?: number | null;
memSlab?: number | null;
memBuffers: number | null;
memCached: number | null;
swapTotal: number | null;
swapUsed: number | null;
topProcesses: MonitorTopProcess[];
diskPercent: number | null;
diskUsed: number | null;
diskTotal: number | null;
disks: MonitorDiskRow[];
diskReadSpeed: number | null;
diskWriteSpeed: number | null;
diskReadIops?: number | null;
diskWriteIops?: number | null;
diskUtilPercent?: number | null;
diskQueueDepth?: number | null;
networkReady: boolean;
netRxSpeed: number;
netTxSpeed: number;
netRxPps?: number;
netTxPps?: number;
netErrorsDelta?: number;
netDropsDelta?: number;
tcpRetransmitsPerSec?: number | null;
fdUsed?: number | null;
fdMax?: number | null;
activeUsers?: number | null;
rebootRequired?: boolean;
latencyMs: number | null;
responseLatencyMs: number | null;
netInterfaces: MonitorNetInterface[];
hostname: string;
osName: string;
kernelRelease: string;
uptimeSeconds: number | null;
loadAverage: number[];
}
export interface MonitorPoint {
at: number;
cpu: number | null;
cpuUser?: number | null;
cpuSystem?: number | null;
cpuIowait?: number | null;
cpuSteal?: number | null;
memory: number | null;
swap?: number | null;
disk: number | null;
rx: number | null;
tx: number | null;
diskRead: number | null;
diskWrite: number | null;
diskIops?: number | null;
latencyMs: number | null;
}
export interface MonitorHostRef {
hostId: string;
label: string;
hostname?: string;
port?: number;
username?: string;
protocol?: string;
group?: string;
tags?: string[];
notes?: string;
os?: string;
hostBindingToken?: string;
}
export interface MonitorPanel {
id: string;
name: string;
description: string;
hostIds: string[];
view: MonitorViewMode;
interval: MonitorInterval;
range: MonitorRangeMinutes;
sort: 'manual' | 'name' | 'health' | 'cpu' | 'memory';
compareHostIds?: string[];
}
export interface ProcessRow {
pid: number;
user: string;
cpuPercent: number;
memPercent: number;
rssKb: number;
state: string;
elapsed: string;
command: string;
}
export interface SystemdServiceRow {
unit: string;
loadState: string;
activeState: string;
subState: string;
description: string;
}
export interface ContainerRow {
runtime: 'docker' | 'podman';
id: string;
name: string;
image: string;
state: string;
status: string;
ports: string;
}
export interface PortRow {
protocol: string;
state: string;
localAddress: string;
port: number | null;
peerAddress: string;
process: string;
pid: number | null;
}
export interface SocketSummary {
total: number;
established: number;
listen: number;
synRecv: number;
timeWait: number;
closeWait: number;
other: number;
}
export interface SystemAuditSnapshot {
fdUsed: number | null;
fdMax: number | null;
loggedInUsers: Array<{ user: string; tty: string; from: string; since: string }>;
recentLogins: string[];
failedAuthCount: number | null;
rebootRequired: boolean;
}
export type AlertMetric =
| 'cpu'
| 'cpuIowait'
| 'memory'
| 'swap'
| 'disk'
| 'inode'
| 'loadPerCore'
| 'netDrops'
| 'latencyMs'
| 'offline'
| 'failedServices'
| 'containerDown';
export type AlertSeverity = 'info' | 'warning' | 'critical';
export interface AlertThresholds {
cpuWarning: number;
cpuCritical: number;
iowaitWarning: number;
iowaitCritical: number;
memoryWarning: number;
memoryCritical: number;
swapWarning: number;
swapCritical: number;
diskWarning: number;
diskCritical: number;
inodeWarning: number;
inodeCritical: number;
loadPerCoreWarning: number;
loadPerCoreCritical: number;
netDropsWarning: number;
netDropsCritical: number;
latencyWarningMs: number;
latencyCriticalMs: number;
consecutivePolls: number;
alertOnOffline: boolean;
}
export interface AlertEvent {
id: string;
hostId: string;
hostLabel: string;
metric: AlertMetric;
severity: AlertSeverity;
value: number | null;
threshold: number | null;
message: string;
startedAt?: number;
at: number;
acknowledged: boolean;
resolvedAt?: number | null;
}
export interface HealthSummary {
score: number;
level: 'healthy' | 'warning' | 'critical' | 'offline' | 'pending';
badges: Array<{ metric: AlertMetric; severity: AlertSeverity; label: string }>;
}
export interface MonitorProbeResult {
reachable: boolean;
protocol: 'rdp' | 'vnc' | 'ssh';
port: number;
rttMs: number | null;
bannerVerified: boolean;
bannerDetail?: string;
error?: string;
checkedAt: number;
}
export interface HostRuntimeState {
hostId: string;
mode?: 'ssh' | 'probe';
status: MonitorHostStatus;
error?: string | null;
updatedAt: number;
stats: MonitorStats | null;
probe?: MonitorProbeResult | null;
points: MonitorPoint[];
lastCommandDurationMs?: number | null;
}
-26
View File
@@ -1,26 +0,0 @@
import React from 'react';
import { definePlugin } from '@netcatty/plugin-sdk';
import { registerHostReactView } from '@netcatty/plugin-sdk/host-react';
import css from './style.css';
import { MONITOR_WORKBENCH_VIEW_ID } from './services/hostBridge';
import { MonitorWorkbench } from './ui/MonitorWorkbench';
export default definePlugin({
activate(context) {
context.subscriptions.add(
registerHostReactView(
context.views,
MONITOR_WORKBENCH_VIEW_ID,
() => <MonitorWorkbench context={context} />,
css,
),
);
context.subscriptions.add({
dispose() {
if (typeof context.views.setBadge === 'function') {
void context.views.setBadge(MONITOR_WORKBENCH_VIEW_ID, null).catch(() => {});
}
},
});
},
});
@@ -1,276 +0,0 @@
import type { JsonValue, PluginContext, VaultHostMetadata } from '@netcatty/plugin-sdk';
import type { MonitorHostRef, MonitorProbeResult } from '../domain/types';
export interface HostProbeOptions {
hostBindingToken: string;
protocol?: 'rdp' | 'vnc' | 'ssh';
port?: number;
timeoutMs?: number;
}
export interface HostExecResult {
stdout: string;
stderr: string;
exitCode: number | null;
truncated?: boolean;
durationMs?: number;
latencyMs: number | null;
responseLatencyMs: number | null;
}
export interface HostExecOptions {
hostBindingToken: string;
command: string;
timeoutMs?: number;
maxOutputBytes?: number;
}
export interface ResolvedHostBinding {
hostBindingToken: string;
status: 'available' | 'missing' | 'revoked';
host?: MonitorHostRef;
}
export const MONITOR_WORKBENCH_VIEW_ID = 'com.binaricat.netcatty-monitor.workbench';
export interface ViewBadgePayload {
count: number;
tone: 'default' | 'info' | 'warning' | 'danger';
tooltip?: string;
}
export interface MonitorHostBridge {
readonly supportsHostExec: boolean;
readonly supportsHostProbe: boolean;
selectHosts(title: string): Promise<MonitorHostRef[]>;
resolveHostBindings(tokens: readonly string[]): Promise<ResolvedHostBinding[]>;
revokeHostBinding(token: string): Promise<boolean>;
execHostCommand(options: HostExecOptions): Promise<HostExecResult>;
probeHost(options: HostProbeOptions): Promise<MonitorProbeResult>;
openHostSession(host: MonitorHostRef, mode: 'terminal' | 'sftp' | 'remoteDesktop'): Promise<boolean>;
setViewBadge(badge: ViewBadgePayload | null): Promise<void>;
confirmAction(options: { title: string; message?: string; confirmLabel?: string; destructive?: boolean }): Promise<boolean | null>;
copyText(text: string, title: string): Promise<boolean>;
saveJsonSnapshot(defaultName: string, payload: unknown): Promise<boolean>;
saveMarkdownReport(defaultName: string, markdown: string): Promise<boolean>;
loadStorage<T extends JsonValue>(key: string): Promise<T | undefined>;
saveStorage(key: string, value: JsonValue): Promise<void>;
}
function mapVaultMetadata(token: string, meta: VaultHostMetadata | undefined): MonitorHostRef {
const label = meta?.label?.trim() || meta?.hostname?.trim() || token.slice(0, 12);
return {
hostId: token,
hostBindingToken: token,
label,
hostname: meta?.hostname,
port: meta?.port,
username: meta?.username,
protocol: meta?.protocol ?? 'ssh',
group: meta?.group,
tags: Array.isArray(meta?.tags) ? [...meta.tags] : [],
notes: meta?.notes,
os: meta?.os,
};
}
export function createMonitorHostBridge(context: PluginContext): MonitorHostBridge {
return {
get supportsHostExec() {
return typeof context.vault.execHostCommand === 'function';
},
get supportsHostProbe() {
return typeof context.vault.probeHost === 'function';
},
async selectHosts(title: string): Promise<MonitorHostRef[]> {
const res = await context.vault.selectHosts({
title,
durable: true,
});
if (res.cancelled) return [];
const hosts: MonitorHostRef[] = [];
for (const item of res.hosts) {
const token = item.hostBindingToken || item.target.handle;
if (!token) continue;
hosts.push(mapVaultMetadata(token, item.metadata));
}
return hosts;
},
async resolveHostBindings(tokens: readonly string[]): Promise<ResolvedHostBinding[]> {
const unique = [...new Set(tokens.filter((t) => typeof t === 'string' && t.length > 0))].slice(0, 100);
if (unique.length === 0 || typeof context.vault.resolveHostBindings !== 'function') return [];
try {
const res = await context.vault.resolveHostBindings({ hostBindingTokens: unique });
return res.hosts.map((item) => ({
hostBindingToken: item.hostBindingToken,
status: item.status,
host: item.status === 'available' ? mapVaultMetadata(item.hostBindingToken, item.metadata) : undefined,
}));
} catch (err) {
context.logger.warn('Failed to resolve host bindings', { error: String(err) });
return [];
}
},
async revokeHostBinding(token: string): Promise<boolean> {
if (!token || typeof context.vault.revokeHostBinding !== 'function') return false;
try {
const res = await context.vault.revokeHostBinding(token);
return Boolean(res.revoked);
} catch {
return false;
}
},
async execHostCommand(options: HostExecOptions): Promise<HostExecResult> {
const res = await context.vault.execHostCommand({
hostBindingToken: options.hostBindingToken,
command: options.command,
timeoutMs: options.timeoutMs ?? 10_000,
maxOutputBytes: options.maxOutputBytes ?? 256 * 1024,
});
return {
stdout: res.stdout,
stderr: res.stderr,
exitCode: res.exitCode,
truncated: res.truncated,
durationMs: res.durationMs,
latencyMs: typeof res.latencyMs === 'number' && Number.isFinite(res.latencyMs) ? res.latencyMs : null,
responseLatencyMs:
typeof res.responseLatencyMs === 'number' && Number.isFinite(res.responseLatencyMs)
? res.responseLatencyMs
: null,
};
},
async probeHost(options: HostProbeOptions): Promise<MonitorProbeResult> {
const res = await context.vault.probeHost({
hostBindingToken: options.hostBindingToken,
...(options.protocol ? { protocol: options.protocol } : {}),
...(typeof options.port === 'number' ? { port: options.port } : {}),
timeoutMs: options.timeoutMs ?? 5_000,
});
return {
reachable: Boolean(res.reachable),
protocol: res.protocol,
port: res.port,
rttMs: typeof res.rttMs === 'number' && Number.isFinite(res.rttMs) ? res.rttMs : null,
bannerVerified: Boolean(res.bannerVerified),
...(res.bannerDetail ? { bannerDetail: res.bannerDetail } : {}),
...(res.error ? { error: res.error } : {}),
checkedAt: res.checkedAt,
};
},
async openHostSession(host: MonitorHostRef, mode: 'terminal' | 'sftp' | 'remoteDesktop'): Promise<boolean> {
const token = host.hostBindingToken || host.hostId;
try {
const res = await context.vault.requestConnect({
hostBindingToken: token,
mode,
});
return !res.cancelled;
} catch (err) {
context.logger.warn('Failed to open host session', { mode, host: host.label, error: String(err) });
return false;
}
},
async setViewBadge(badge: ViewBadgePayload | null): Promise<void> {
if (typeof context.views.setBadge !== 'function') return;
try {
if (!badge || badge.count <= 0) {
await context.views.setBadge(MONITOR_WORKBENCH_VIEW_ID, null);
} else {
await context.views.setBadge({
viewId: MONITOR_WORKBENCH_VIEW_ID,
count: Math.min(999, Math.max(0, Math.trunc(badge.count))),
tone: badge.tone,
...(badge.tooltip ? { tooltip: badge.tooltip.slice(0, 160) } : {}),
});
}
} catch (err) {
context.logger.debug('View badge update unavailable', { error: String(err) });
}
},
async confirmAction(options: {
title: string;
message?: string;
confirmLabel?: string;
destructive?: boolean;
}): Promise<boolean | null> {
const uiAny = context.ui as unknown as {
confirm?: (params: {
title: string;
message?: string;
confirmLabel?: string;
destructive?: boolean;
}) => Promise<boolean>;
};
if (typeof uiAny.confirm !== 'function') return null;
try {
return Boolean(await uiAny.confirm(options));
} catch {
return null;
}
},
async copyText(text: string, title: string): Promise<boolean> {
try {
return await context.clipboard.writeText(text, title);
} catch {
return false;
}
},
async saveJsonSnapshot(defaultName: string, payload: unknown): Promise<boolean> {
try {
const res = await context.ui.saveFile({
title: 'Export Monitor Snapshot',
defaultName,
filters: [{ name: 'JSON', extensions: ['json'] }],
data: JSON.stringify(payload, null, 2),
encoding: 'utf8',
});
return !res.cancelled;
} catch {
return false;
}
},
async saveMarkdownReport(defaultName: string, markdown: string): Promise<boolean> {
try {
const res = await context.ui.saveFile({
title: 'Export Diagnostics Report (Markdown)',
defaultName,
filters: [{ name: 'Markdown', extensions: ['md'] }],
data: markdown,
encoding: 'utf8',
});
return !res.cancelled;
} catch {
return false;
}
},
async loadStorage<T extends JsonValue>(key: string): Promise<T | undefined> {
try {
return await context.storage.get<T>(key);
} catch {
return undefined;
}
},
async saveStorage(key: string, value: JsonValue): Promise<void> {
try {
await context.storage.set(key, value);
} catch (err) {
context.logger.warn('Failed to persist monitor storage key', { key, error: String(err) });
}
},
};
}
@@ -1,615 +0,0 @@
import { applyAlertHysteresis, evaluateHostHealth, mergeAlertFeed, DEFAULT_ALERT_THRESHOLDS } from '../domain/alerts';
import {
buildContainerActionCommand,
buildContainerLogsCommand,
buildGpuProbeCommand,
buildLinuxDiskCommand,
buildPortsCommand,
buildPrimaryStatsCommand,
buildProcessSignalCommand,
buildProcessesCommand,
buildServiceActionCommand,
buildServiceLogsCommand,
buildServicesAndContainersCommand,
buildSystemAuditCommand,
buildWindowsStatsCommand,
type SafeContainerAction,
type SafeProcessSignal,
type SafeServiceAction,
} from '../domain/collectors';
import { formatMemoryPercent } from '../domain/formatting';
import { parseGpuStats } from '../domain/gpu';
import {
parsePortsOutput,
parsePrimaryStatsOutput,
parseProcessesOutput,
parseServicesAndContainersOutput,
parseSystemAuditOutput,
type TelemetryDeltaState,
} from '../domain/parsers';
import type {
AlertEvent,
AlertThresholds,
ContainerRow,
HostRuntimeState,
MonitorHostRef,
MonitorInterval,
MonitorPoint,
PortRow,
ProcessRow,
SocketSummary,
SystemAuditSnapshot,
SystemdServiceRow,
} from '../domain/types';
import type { MonitorHostBridge } from './hostBridge';
const MAX_CONCURRENT_EXECS = 12;
const HISTORY_WINDOW_MS = 60 * 60 * 1000;
const HISTORY_MAX_POINTS = 1200;
const GPU_CADENCE_MS = 15_000;
const MIN_PROBE_INTERVAL_SEC = 5;
const IMMEDIATE_ALERT_METRICS = new Set(['offline'] as const);
export function isProbeProtocol(protocol?: string | null): protocol is 'rdp' | 'vnc' {
const p = String(protocol || '').toLowerCase();
return p === 'rdp' || p === 'vnc';
}
interface HostInternal {
host: MonitorHostRef;
state: HostRuntimeState;
delta: TelemetryDeltaState;
failures: number;
sampling: boolean;
timer: ReturnType<typeof setTimeout> | null;
lastGpuProbeAt: number;
cachedGpu: {
gpu: number | null;
gpuName: string | null;
gpuMemUsed: number | null;
gpuMemTotal: number | null;
gpus: NonNullable<HostRuntimeState['stats']>['gpus'];
} | null;
useWindowsFallback: boolean;
}
export interface MonitorEngineSnapshot {
running: boolean;
hosts: Record<string, HostRuntimeState>;
alerts: AlertEvent[];
thresholds: AlertThresholds;
}
export class MonitorEngine {
readonly #bridge: MonitorHostBridge;
readonly #entries = new Map<string, HostInternal>();
readonly #listeners = new Set<() => void>();
#running = false;
#disposed = false;
#intervalSec: MonitorInterval = 5;
#thresholds: AlertThresholds = { ...DEFAULT_ALERT_THRESHOLDS };
#alerts: AlertEvent[] = [];
readonly #alertStreaks = new Map<string, number>();
#activeExecs = 0;
readonly #waiters: Array<() => void> = [];
readonly #now: () => number;
constructor(bridge: MonitorHostBridge, options: { now?: () => number; thresholds?: AlertThresholds } = {}) {
this.#bridge = bridge;
this.#now = options.now ?? Date.now;
if (options.thresholds) this.#thresholds = { ...options.thresholds };
}
subscribe(listener: () => void): () => void {
this.#listeners.add(listener);
return () => this.#listeners.delete(listener);
}
#emit(): void {
for (const listener of this.#listeners) listener();
}
getSnapshot(): MonitorEngineSnapshot {
const hosts: Record<string, HostRuntimeState> = {};
for (const [id, entry] of this.#entries) {
hosts[id] = entry.state;
}
return {
running: this.#running,
hosts,
alerts: this.#alerts,
thresholds: this.#thresholds,
};
}
setThresholds(thresholds: AlertThresholds): void {
this.#thresholds = { ...thresholds };
for (const entry of this.#entries.values()) {
const { violations } = evaluateHostHealth(entry.state, this.#thresholds);
this.#alerts = mergeAlertFeed(this.#alerts, entry.host.hostId, entry.host.label, violations, this.#now());
}
this.#emit();
}
acknowledgeAlert(alertId: string): void {
this.#alerts = this.#alerts.map((a) => (a.id === alertId ? { ...a, acknowledged: true } : a));
this.#emit();
}
acknowledgeAllAlerts(): void {
this.#alerts = this.#alerts.map((a) => ({ ...a, acknowledged: true }));
this.#emit();
}
clearResolvedAlerts(): void {
this.#alerts = this.#alerts.filter((a) => !a.resolvedAt);
this.#emit();
}
setIntervalSeconds(interval: MonitorInterval): void {
if (this.#intervalSec === interval) return;
this.#intervalSec = interval;
if (this.#running) {
for (const entry of this.#entries.values()) {
this.#clearTimer(entry);
if (!entry.sampling && entry.state.status !== 'unsupported') {
this.#scheduleNext(entry, 50);
}
}
}
}
reconcileHosts(hosts: readonly MonitorHostRef[], options: { running: boolean; interval: MonitorInterval }): void {
this.#intervalSec = options.interval;
const nextIds = new Set(hosts.map((h) => h.hostId));
for (const [id, entry] of this.#entries) {
if (!nextIds.has(id)) {
this.#clearTimer(entry);
this.#entries.delete(id);
}
}
for (const host of hosts) {
const existing = this.#entries.get(host.hostId);
if (existing) {
existing.host = host;
} else {
const mode: 'ssh' | 'probe' = isProbeProtocol(host.protocol) ? 'probe' : 'ssh';
this.#entries.set(host.hostId, {
host,
state: {
hostId: host.hostId,
mode,
status: options.running ? 'queued' : 'idle',
error: null,
updatedAt: 0,
stats: null,
probe: null,
points: [],
},
delta: {},
failures: 0,
sampling: false,
timer: null,
lastGpuProbeAt: 0,
cachedGpu: null,
useWindowsFallback: false,
});
}
}
const wasRunning = this.#running;
this.#running = options.running;
if (!this.#running) {
for (const entry of this.#entries.values()) {
this.#clearTimer(entry);
if (entry.state.status === 'queued' || entry.state.status === 'connecting') {
entry.state = { ...entry.state, status: 'idle' };
}
}
} else {
for (const entry of this.#entries.values()) {
if (!entry.sampling && !entry.timer && entry.state.status !== 'unsupported') {
if (!wasRunning || entry.state.status === 'idle' || entry.state.status === 'queued') {
this.#scheduleNext(entry, 0);
}
}
}
}
this.#emit();
}
retryHost(hostId: string): void {
const entry = this.#entries.get(hostId);
if (!entry || this.#disposed) return;
this.#clearTimer(entry);
entry.failures = 0;
entry.useWindowsFallback = false;
entry.state = { ...entry.state, status: 'queued', error: null };
this.#emit();
void this.#collectHost(entry);
}
refreshAllNow(): void {
if (this.#disposed) return;
for (const entry of this.#entries.values()) {
this.#clearTimer(entry);
if (!entry.sampling && entry.state.status !== 'unsupported') {
void this.#collectHost(entry);
}
}
}
dispose(): void {
this.#disposed = true;
this.#running = false;
for (const entry of this.#entries.values()) {
this.#clearTimer(entry);
}
this.#entries.clear();
this.#listeners.clear();
}
#clearTimer(entry: HostInternal): void {
if (entry.timer) {
clearTimeout(entry.timer);
entry.timer = null;
}
}
#scheduleNext(entry: HostInternal, delayMs: number): void {
if (this.#disposed || !this.#running) return;
this.#clearTimer(entry);
entry.timer = setTimeout(() => {
entry.timer = null;
void this.#collectHost(entry);
}, delayMs);
(entry.timer as unknown as { unref?: () => void })?.unref?.();
}
async #acquireSlot(): Promise<void> {
if (this.#activeExecs < MAX_CONCURRENT_EXECS) {
this.#activeExecs += 1;
return;
}
await new Promise<void>((resolve) => {
this.#waiters.push(resolve);
});
}
#releaseSlot(): void {
const next = this.#waiters.shift();
if (next) {
next();
return;
}
this.#activeExecs = Math.max(0, this.#activeExecs - 1);
}
async #execBounded(host: MonitorHostRef, command: string, timeoutMs = 10_000, maxOutputBytes = 256 * 1024) {
await this.#acquireSlot();
try {
return await this.#bridge.execHostCommand({
hostBindingToken: host.hostBindingToken || host.hostId,
command,
timeoutMs,
maxOutputBytes,
});
} finally {
this.#releaseSlot();
}
}
async #collectHost(entry: HostInternal): Promise<void> {
if (this.#disposed || entry.sampling || !this.#entries.has(entry.host.hostId)) return;
if (isProbeProtocol(entry.host.protocol)) {
await this.#collectProbe(entry, entry.host.protocol);
return;
}
entry.sampling = true;
if (entry.state.status === 'idle' || entry.state.status === 'queued') {
entry.state = { ...entry.state, status: 'connecting', error: null };
this.#emit();
}
const startedAt = this.#now();
try {
const cmd = entry.useWindowsFallback ? buildWindowsStatsCommand() : buildPrimaryStatsCommand();
const primary = await this.#execBounded(entry.host, cmd, 10_000, 256 * 1024);
if (this.#disposed || !this.#entries.has(entry.host.hostId)) return;
let parsed = parsePrimaryStatsOutput(primary.stdout, entry.delta, {
now: this.#now(),
latencyMs: primary.latencyMs,
responseLatencyMs: primary.responseLatencyMs,
});
// Fallback to Windows OpenSSH PowerShell probe if uname failed or reported non-POSIX Windows
if (!parsed.ok && !entry.useWindowsFallback && (parsed.unsupported || /not supported|Unable to parse/i.test(parsed.error))) {
try {
const winRes = await this.#execBounded(entry.host, buildWindowsStatsCommand(), 10_000, 128 * 1024);
const winParsed = parsePrimaryStatsOutput(winRes.stdout, entry.delta, {
now: this.#now(),
latencyMs: winRes.latencyMs,
responseLatencyMs: winRes.responseLatencyMs,
});
if (winParsed.ok) {
entry.useWindowsFallback = true;
parsed = winParsed;
}
} catch {
// Keep original error
}
}
if (!parsed.ok) {
entry.failures += 1;
entry.state = {
...entry.state,
status: parsed.unsupported ? 'unsupported' : 'error',
error: parsed.error,
updatedAt: this.#now(),
};
} else {
// Fetch Linux disks in a dedicated Dropbear-safe exec when primary omitted them
if (parsed.needsSeparateLinuxDisks) {
try {
const diskRes = await this.#execBounded(entry.host, buildLinuxDiskCommand(), 10_000, 128 * 1024);
const merged = parsePrimaryStatsOutput(primary.stdout, entry.delta, {
now: this.#now(),
latencyMs: primary.latencyMs,
responseLatencyMs: primary.responseLatencyMs,
linuxDiskStdout: diskRes.stdout,
});
if (merged.ok) parsed = merged;
} catch {
// Keep primary stats even if disk probe failed
}
}
// Optional slower-cadence GPU probe on Linux
const now = this.#now();
if (parsed.stats.osFamily === 'linux' && now - entry.lastGpuProbeAt >= GPU_CADENCE_MS) {
entry.lastGpuProbeAt = now;
try {
const gpuRes = await this.#execBounded(entry.host, buildGpuProbeCommand(), 4_000, 64 * 1024);
entry.cachedGpu = parseGpuStats(gpuRes.stdout);
} catch {
// Non-fatal
}
}
const stats = entry.cachedGpu
? {
...parsed.stats,
...entry.cachedGpu,
}
: parsed.stats;
entry.delta = parsed.nextDelta;
entry.failures = 0;
const memPct = formatMemoryPercent(stats.memUsed, stats.memTotal);
const swapPct = formatMemoryPercent(stats.swapUsed, stats.swapTotal);
const totalIops =
stats.diskReadIops != null || stats.diskWriteIops != null
? Number(((stats.diskReadIops ?? 0) + (stats.diskWriteIops ?? 0)).toFixed(1))
: null;
const point: MonitorPoint = {
at: now,
cpu: stats.cpu,
cpuUser: stats.cpuUser ?? null,
cpuSystem: stats.cpuSystem ?? null,
cpuIowait: stats.cpuIowait ?? null,
cpuSteal: stats.cpuSteal ?? null,
memory: memPct == null ? null : Number(memPct.toFixed(1)),
swap: swapPct == null ? null : Number(swapPct.toFixed(1)),
disk: stats.diskPercent,
rx: stats.networkReady ? stats.netRxSpeed : null,
tx: stats.networkReady ? stats.netTxSpeed : null,
diskRead: stats.diskReadSpeed,
diskWrite: stats.diskWriteSpeed,
diskIops: totalIops,
latencyMs: stats.latencyMs ?? stats.responseLatencyMs,
};
const cutoff = now - HISTORY_WINDOW_MS;
const points = [...entry.state.points.filter((p) => p.at >= cutoff), point].slice(-HISTORY_MAX_POINTS);
entry.state = {
hostId: entry.host.hostId,
status: 'live',
error: null,
updatedAt: now,
stats,
points,
lastCommandDurationMs: Math.max(0, now - startedAt),
};
}
} catch (err) {
if (this.#disposed || !this.#entries.has(entry.host.hostId)) return;
const msg = err instanceof Error ? err.message : String(err);
entry.failures += 1;
const isAuth = /auth|permission|passphrase|login|unauthenticated/i.test(msg);
const isUnsupported = /unsupported|single-channel|bastion/i.test(msg);
entry.state = {
...entry.state,
status: isUnsupported ? 'unsupported' : isAuth ? 'login' : 'error',
error: msg,
updatedAt: this.#now(),
};
} finally {
entry.sampling = false;
const { violations } = evaluateHostHealth(entry.state, this.#thresholds);
const confirmed = applyAlertHysteresis(
this.#alertStreaks,
entry.host.hostId,
violations,
this.#thresholds.consecutivePolls,
{ immediateMetrics: IMMEDIATE_ALERT_METRICS },
);
this.#alerts = mergeAlertFeed(this.#alerts, entry.host.hostId, entry.host.label, confirmed, this.#now());
this.#emit();
if (!this.#disposed && this.#running && entry.state.status !== 'unsupported') {
const backoffFactor = entry.failures > 0 ? Math.min(6, 2 ** entry.failures) : 1;
const delayMs = this.#intervalSec * 1000 * backoffFactor;
this.#scheduleNext(entry, delayMs);
}
}
}
async #collectProbe(entry: HostInternal, protocol: 'rdp' | 'vnc'): Promise<void> {
if (this.#disposed || entry.sampling || !this.#entries.has(entry.host.hostId)) return;
entry.sampling = true;
if (entry.state.status === 'idle' || entry.state.status === 'queued') {
entry.state = { ...entry.state, mode: 'probe', status: 'connecting', error: null };
this.#emit();
}
const startedAt = this.#now();
try {
await this.#acquireSlot();
let probe;
try {
probe = await this.#bridge.probeHost({
hostBindingToken: entry.host.hostBindingToken || entry.host.hostId,
protocol,
...(typeof entry.host.port === 'number' ? { port: entry.host.port } : {}),
timeoutMs: 5_000,
});
} finally {
this.#releaseSlot();
}
if (this.#disposed || !this.#entries.has(entry.host.hostId)) return;
const now = probe.checkedAt || this.#now();
if (probe.reachable) {
entry.failures = 0;
} else {
entry.failures += 1;
}
const point: MonitorPoint = {
at: now,
cpu: null,
memory: null,
disk: null,
rx: null,
tx: null,
diskRead: null,
diskWrite: null,
latencyMs: probe.reachable ? probe.rttMs : null,
};
const cutoff = now - HISTORY_WINDOW_MS;
const points = [...entry.state.points.filter((p) => p.at >= cutoff), point].slice(-HISTORY_MAX_POINTS);
entry.state = {
hostId: entry.host.hostId,
mode: 'probe',
status: probe.reachable ? 'live' : 'offline',
error: probe.reachable ? null : (probe.error ?? 'Host unreachable'),
updatedAt: now,
stats: null,
probe,
points,
lastCommandDurationMs: Math.max(0, this.#now() - startedAt),
};
} catch (err) {
if (this.#disposed || !this.#entries.has(entry.host.hostId)) return;
const msg = err instanceof Error ? err.message : String(err);
entry.failures += 1;
entry.state = {
...entry.state,
mode: 'probe',
status: /unsupported/i.test(msg) ? 'unsupported' : 'offline',
error: msg,
updatedAt: this.#now(),
};
} finally {
entry.sampling = false;
const { violations } = evaluateHostHealth(entry.state, this.#thresholds);
const confirmed = applyAlertHysteresis(
this.#alertStreaks,
entry.host.hostId,
violations,
this.#thresholds.consecutivePolls,
{ immediateMetrics: IMMEDIATE_ALERT_METRICS },
);
this.#alerts = mergeAlertFeed(this.#alerts, entry.host.hostId, entry.host.label, confirmed, this.#now());
this.#emit();
if (!this.#disposed && this.#running && entry.state.status !== 'unsupported') {
const baseSec = Math.max(this.#intervalSec, MIN_PROBE_INTERVAL_SEC);
const backoffFactor = entry.failures > 0 ? Math.min(6, 2 ** entry.failures) : 1;
this.#scheduleNext(entry, baseSec * 1000 * backoffFactor);
}
}
}
// Active-tab-only operational probes (never polled for background fleet hosts)
async fetchProcesses(host: MonitorHostRef): Promise<ProcessRow[]> {
const res = await this.#execBounded(host, buildProcessesCommand(150), 10_000, 512 * 1024);
return parseProcessesOutput(res.stdout);
}
async sendProcessSignal(host: MonitorHostRef, pid: number, signal: SafeProcessSignal): Promise<void> {
const cmd = buildProcessSignalCommand(pid, signal);
const res = await this.#execBounded(host, cmd, 8_000, 16 * 1024);
if (res.exitCode && res.exitCode !== 0) {
throw new Error(res.stderr.trim() || `Signal ${signal} failed with exit code ${res.exitCode}`);
}
}
async fetchServicesAndContainers(host: MonitorHostRef): Promise<{
services: SystemdServiceRow[];
containers: ContainerRow[];
}> {
const res = await this.#execBounded(host, buildServicesAndContainersCommand(), 10_000, 512 * 1024);
return parseServicesAndContainersOutput(res.stdout);
}
async fetchServiceLogs(host: MonitorHostRef, unit: string, lines = 120): Promise<string> {
const res = await this.#execBounded(host, buildServiceLogsCommand(unit, lines), 10_000, 512 * 1024);
return res.stdout || res.stderr || '(no log output)';
}
async fetchContainerLogs(host: MonitorHostRef, runtime: 'docker' | 'podman', id: string, lines = 120): Promise<string> {
const res = await this.#execBounded(host, buildContainerLogsCommand(runtime, id, lines), 10_000, 512 * 1024);
return res.stdout || res.stderr || '(no log output)';
}
async fetchPorts(host: MonitorHostRef): Promise<{ ports: PortRow[]; summary: SocketSummary }> {
const res = await this.#execBounded(host, buildPortsCommand(), 10_000, 512 * 1024);
return parsePortsOutput(res.stdout);
}
async fetchSystemAudit(host: MonitorHostRef): Promise<SystemAuditSnapshot> {
const res = await this.#execBounded(host, buildSystemAuditCommand(), 10_000, 128 * 1024);
return parseSystemAuditOutput(res.stdout);
}
async runServiceAction(host: MonitorHostRef, unit: string, action: SafeServiceAction): Promise<string> {
const cmd = buildServiceActionCommand(unit, action);
const res = await this.#execBounded(host, cmd, 15_000, 32 * 1024);
if (res.exitCode && res.exitCode !== 0) {
throw new Error(res.stderr.trim() || res.stdout.trim() || `systemctl ${action} ${unit} exited with ${res.exitCode}`);
}
return res.stdout || `systemctl ${action} ${unit}: OK`;
}
async runContainerAction(
host: MonitorHostRef,
runtime: 'docker' | 'podman',
id: string,
action: SafeContainerAction,
): Promise<string> {
const cmd = buildContainerActionCommand(runtime, id, action);
const res = await this.#execBounded(host, cmd, 15_000, 32 * 1024);
if (res.exitCode && res.exitCode !== 0) {
throw new Error(res.stderr.trim() || res.stdout.trim() || `${runtime} ${action} ${id} exited with ${res.exitCode}`);
}
return res.stdout || `${runtime} ${action} ${id}: OK`;
}
}
export function isHostStateStale(state: HostRuntimeState | undefined, intervalSec: number, now = Date.now()): boolean {
if (!state || state.status !== 'live' || !state.updatedAt) return false;
return now - state.updatedAt > Math.max(5_000, intervalSec * 2_500);
}
File diff suppressed because it is too large. Load diff
@@ -1,286 +0,0 @@
import React, { useMemo } from 'react';
import {
PluginDataGrid,
PluginMetricChart,
type PluginDataGridColumn,
type PluginMetricChartColor,
} from '@netcatty/plugin-sdk/host-react';
import { evaluateHostHealth } from '../domain/alerts';
import {
formatIops,
formatLatency,
formatLoadAverage,
formatMemoryPercent,
formatMonitorRate,
formatPercent,
} from '../domain/formatting';
import type { I18nKey } from '../domain/i18n';
import type {
AlertThresholds,
HostRuntimeState,
MonitorHostRef,
MonitorInterval,
MonitorRangeMinutes,
} from '../domain/types';
const SERIES_COLORS: readonly PluginMetricChartColor[] = ['emerald', 'sky', 'amber', 'violet', 'rose', 'cyan'];
export interface CompareViewProps {
hosts: MonitorHostRef[];
selectedHostIds: string[];
runtimeHosts: Record<string, HostRuntimeState>;
interval: MonitorInterval;
range: MonitorRangeMinutes;
thresholds: AlertThresholds;
t: (key: I18nKey) => string;
onToggleCompareHost: (hostId: string) => void;
onInspectHost: (hostId: string) => void;
}
export function CompareView({
hosts,
selectedHostIds,
runtimeHosts,
interval,
range,
thresholds,
t,
onToggleCompareHost,
onInspectHost,
}: CompareViewProps) {
const now = Date.now();
const rangeMs = range * 60_000;
const intervalMs = interval * 1_000;
const effectiveSelected = useMemo(() => {
const valid = selectedHostIds.filter((id) => hosts.some((h) => h.hostId === id)).slice(0, 6);
if (valid.length >= 2) return valid;
return hosts.slice(0, Math.min(4, hosts.length)).map((h) => h.hostId);
}, [hosts, selectedHostIds]);
const comparedHosts = useMemo(
() =>
effectiveSelected
.map((id, idx) => {
const host = hosts.find((h) => h.hostId === id);
if (!host) return null;
return {
host,
state: runtimeHosts[id],
color: SERIES_COLORS[idx % SERIES_COLORS.length],
};
})
.filter((x): x is NonNullable<typeof x> => x !== null),
[effectiveSelected, hosts, runtimeHosts],
);
const columns = useMemo<PluginDataGridColumn[]>(
() => [
{ name: 'host', type: 'text', width: 180, sortable: true },
{ name: 'health', type: 'text', width: 88, sortable: true },
{ name: 'cpu', type: 'text', width: 95 },
{ name: 'iowait', type: 'text', width: 82 },
{ name: 'memory', type: 'text', width: 92 },
{ name: 'disk', type: 'text', width: 82 },
{ name: 'iops', type: 'text', width: 120 },
{ name: 'network', type: 'text', width: 145 },
{ name: 'load', type: 'text', width: 115 },
{ name: 'latency', type: 'text', width: 84 },
],
[],
);
const rows = useMemo(
() =>
comparedHosts.map(({ host, state }) => {
const s = state?.stats;
const { health } = evaluateHostHealth(state, thresholds);
const memPct = formatMemoryPercent(s?.memUsed, s?.memTotal);
return {
_hostId: host.hostId,
host: host.label,
health: `${health.score}/100`,
cpu: formatPercent(s?.cpu, 1),
iowait: s?.cpuIowait != null ? `${s.cpuIowait.toFixed(1)}%` : '--',
memory: formatPercent(memPct, 1),
disk: formatPercent(s?.diskPercent, 0),
iops: formatIops(s?.diskReadIops, s?.diskWriteIops),
network: s?.networkReady ? `↓${formatMonitorRate(s.netRxSpeed)} ↑${formatMonitorRate(s.netTxSpeed)}` : '--',
load: formatLoadAverage(s?.loadAverage),
latency: formatLatency(state?.mode === 'probe' ? state.probe?.rttMs : (s?.latencyMs ?? s?.responseLatencyMs)),
};
}),
[comparedHosts, thresholds],
);
if (hosts.length < 2) {
return (
<div className="nm-content">
<div className="nm-empty">
<h3 className="nm-empty-title">{t('viewCompare')}</h3>
<p className="nm-empty-body">{t('compareNeedMore')}</p>
</div>
</div>
);
}
return (
<div className="nm-content">
<div className="nm-panel-card-sub" style={{ marginBottom: 8 }}>
{t('compareSelectHint')}
</div>
{/* Host Selector Chips (2-6 hosts) */}
<div className="nm-compare-chips">
{hosts.map((h) => {
const active = effectiveSelected.includes(h.hostId);
return (
<button
key={h.hostId}
type="button"
className={`nm-chip ${active ? 'nm-chip-active' : ''}`}
onClick={() => onToggleCompareHost(h.hostId)}
>
<span>{active ? '✓' : '+'}</span>
<span>{h.label}</span>
</button>
);
})}
</div>
{/* Synchronized Multi-Host Overlay Charts */}
<div className="nm-chart-grid">
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">{t('metricCpu')} (%)</h3>
<span className="nm-panel-card-sub nm-mono">{comparedHosts.length} hosts</span>
</div>
<PluginMetricChart
variant="line"
height={165}
rangeMs={rangeMs}
intervalMs={intervalMs}
endAt={now}
min={0}
max={100}
showGrid
showAxes
showLegend
interactive
ariaLabel={`${t('viewCompare')} ${t('metricCpu')}`}
thresholds={[{ value: thresholds.cpuWarning, tone: 'warning' }, { value: thresholds.cpuCritical, tone: 'critical' }]}
series={comparedHosts.map(({ host, state, color }) => ({
id: host.hostId,
label: host.label,
color,
unit: '%',
points: (state?.points ?? []).map((p) => ({ at: p.at, value: p.cpu })),
}))}
/>
</section>
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">{t('metricMemory')} (%)</h3>
<span className="nm-panel-card-sub nm-mono">{comparedHosts.length} hosts</span>
</div>
<PluginMetricChart
variant="line"
height={165}
rangeMs={rangeMs}
intervalMs={intervalMs}
endAt={now}
min={0}
max={100}
showGrid
showAxes
showLegend
interactive
ariaLabel={`${t('viewCompare')} ${t('metricMemory')}`}
thresholds={[{ value: thresholds.memoryWarning, tone: 'warning' }, { value: thresholds.memoryCritical, tone: 'critical' }]}
series={comparedHosts.map(({ host, state, color }) => ({
id: host.hostId,
label: host.label,
color,
unit: '%',
points: (state?.points ?? []).map((p) => ({ at: p.at, value: p.memory })),
}))}
/>
</section>
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">{t('metricNetwork')} (RX + TX)</h3>
<span className="nm-panel-card-sub nm-mono">bytes/s</span>
</div>
<PluginMetricChart
variant="line"
height={165}
rangeMs={rangeMs}
intervalMs={intervalMs}
endAt={now}
min={0}
max="auto"
showGrid
showAxes
showLegend
interactive
ariaLabel={`${t('viewCompare')} ${t('metricNetwork')}`}
series={comparedHosts.map(({ host, state, color }) => ({
id: host.hostId,
label: host.label,
color,
unit: 'bytes/s',
points: (state?.points ?? []).map((p) => ({
at: p.at,
value: p.rx != null || p.tx != null ? (p.rx ?? 0) + (p.tx ?? 0) : null,
})),
}))}
/>
</section>
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">{t('metricDiskIo')} / {t('metricLatency')}</h3>
<span className="nm-panel-card-sub nm-mono">ms</span>
</div>
<PluginMetricChart
variant="line"
height={165}
rangeMs={rangeMs}
intervalMs={intervalMs}
endAt={now}
min={0}
max="auto"
showGrid
showAxes
showLegend
interactive
ariaLabel={`${t('viewCompare')} ${t('metricLatency')}`}
thresholds={[{ value: thresholds.latencyWarningMs, tone: 'warning' }]}
series={comparedHosts.map(({ host, state, color }) => ({
id: host.hostId,
label: host.label,
color,
unit: 'ms',
points: (state?.points ?? []).map((p) => ({ at: p.at, value: p.latencyMs })),
}))}
/>
</section>
</div>
{/* Side-by-Side KPI Matrix */}
<div className="nm-grid-wrap" style={{ minHeight: 180 }}>
<PluginDataGrid
columns={columns}
rows={rows}
onCellDoubleClick={({ rowIndex }) => {
const row = rows[rowIndex];
if (row?._hostId) onInspectHost(row._hostId);
}}
emptyMessage={t('compareNeedMore')}
/>
</div>
</div>
);
}
File diff suppressed because it is too large. Load diff
@@ -1,279 +0,0 @@
import React, { Suspense, lazy, useState } from 'react';
import { PluginPopover } from '@netcatty/plugin-sdk/host-react';
import { evaluateHostHealth } from '../domain/alerts';
import { formatLatency } from '../domain/formatting';
import type { I18nKey, MonitorLocale } from '../domain/i18n';
import { ALL_OVERVIEW_WIDGETS, MONITOR_RANGES } from '../domain/panels';
import type {
AlertEvent,
AlertThresholds,
HostRuntimeState,
MonitorHostRef,
MonitorInterval,
MonitorRangeMinutes,
OverviewWidgetKey,
} from '../domain/types';
import type { MonitorHostBridge } from '../services/hostBridge';
import type { MonitorEngine } from '../services/monitorEngine';
import { OverviewTab } from './tabs/OverviewTab';
const ProcessesTab = lazy(() => import('./tabs/ProcessesTab'));
const ServicesTab = lazy(() => import('./tabs/ServicesTab'));
const PortsTab = lazy(() => import('./tabs/PortsTab'));
const AlertsTab = lazy(() => import('./tabs/AlertsTab'));
export type HostDetailTab = 'overview' | 'processes' | 'services' | 'ports' | 'alerts';
const WIDGET_LABEL_KEY: Record<OverviewWidgetKey, I18nKey> = {
cpuBreakdown: 'widgetCpuBreakdown',
memoryPsi: 'widgetMemoryPsi',
networkTcp: 'widgetNetworkTcp',
diskIoMounts: 'widgetDiskIoMounts',
perCore: 'widgetPerCore',
gpuThermals: 'widgetGpuThermals',
systemSecurity: 'widgetSystemSecurity',
};
export interface HostWorkbenchProps {
host: MonitorHostRef;
state: HostRuntimeState | undefined;
interval: MonitorInterval;
range: MonitorRangeMinutes;
alerts: AlertEvent[];
thresholds: AlertThresholds;
visibleWidgets: readonly OverviewWidgetKey[];
engine: MonitorEngine;
bridge: MonitorHostBridge;
locale: MonitorLocale;
t: (key: I18nKey) => string;
onBack: () => void;
onChangeRange: (range: MonitorRangeMinutes) => void;
onToggleWidget: (widget: OverviewWidgetKey) => void;
onRetry: () => void;
onOpenSession: (mode: 'terminal' | 'sftp' | 'remoteDesktop') => void;
onExportSnapshot: (format: 'json' | 'md') => void;
onSaveThresholds: (next: AlertThresholds) => void;
onAckAlert: (id: string) => void;
onAckAll: () => void;
onClearResolved: () => void;
}
export default function HostWorkbench({
host,
state,
interval,
range,
alerts,
thresholds,
visibleWidgets,
engine,
bridge,
locale,
t,
onBack,
onChangeRange,
onToggleWidget,
onRetry,
onOpenSession,
onExportSnapshot,
onSaveThresholds,
onAckAlert,
onAckAll,
onClearResolved,
}: HostWorkbenchProps) {
const [activeTab, setActiveTab] = useState<HostDetailTab>('overview');
const [widgetsOpen, setWidgetsOpen] = useState(false);
const isProbe = state?.mode === 'probe' || host.protocol === 'rdp' || host.protocol === 'vnc';
const { health } = evaluateHostHealth(state, thresholds);
const hostAlerts = alerts.filter((a) => a.hostId === host.hostId && !a.resolvedAt);
const latency = isProbe ? state?.probe?.rttMs : (state?.stats?.latencyMs ?? state?.stats?.responseLatencyMs);
return (
<div className="nm-main">
{/* Host Inspector Header */}
<header className="nm-topbar">
<div className="nm-topbar-left">
<button type="button" className="nm-btn nm-btn-ghost" onClick={onBack}>
← {t('backToFleet')}
</button>
<div>
<h2 className="nm-page-title">
{host.label}
{host.hostname ? ` (${host.hostname})` : ''}
</h2>
<span className="nm-page-sub nm-mono">
{state?.stats?.osName || host.os || host.protocol || 'SSH'} · {formatLatency(latency)}
</span>
</div>
<span
className={`nm-badge ${
health.level === 'healthy'
? 'nm-badge-ok'
: health.level === 'warning'
? 'nm-badge-warn'
: health.level === 'critical' || health.level === 'offline'
? 'nm-badge-crit'
: ''
}`}
>
{health.score}/100
</span>
{state?.stats?.rebootRequired && <span className="nm-badge nm-badge-warn">{t('rebootPending')}</span>}
</div>
<div className="nm-topbar-right">
<select
className="nm-select"
aria-label={t('range')}
value={String(range)}
onChange={(e) => onChangeRange(Number(e.target.value) as MonitorRangeMinutes)}
>
{MONITOR_RANGES.map((m) => (
<option key={m} value={m}>
{m === 60 ? '1h' : `${m}m`}
</option>
))}
</select>
{!isProbe && activeTab === 'overview' && (
<>
<button
type="button"
id="nm-widgets-trigger"
className="nm-btn nm-btn-ghost"
onClick={() => setWidgetsOpen((v) => !v)}
>
{t('customizeWidgets')}
</button>
<PluginPopover anchor="nm-widgets-trigger" open={widgetsOpen} onClose={() => setWidgetsOpen(false)}>
<div className="nm-popover-menu">
{ALL_OVERVIEW_WIDGETS.map((w) => (
<label key={w} className="nm-checkbox-row">
<input
type="checkbox"
checked={visibleWidgets.includes(w)}
onChange={() => onToggleWidget(w)}
/>
<span>{t(WIDGET_LABEL_KEY[w])}</span>
</label>
))}
</div>
</PluginPopover>
</>
)}
<button type="button" className="nm-btn nm-btn-ghost" onClick={onRetry}>
{t('refreshNow')}
</button>
<button type="button" className="nm-btn nm-btn-ghost" onClick={() => onExportSnapshot('json')}>
JSON
</button>
<button type="button" className="nm-btn nm-btn-ghost" onClick={() => onExportSnapshot('md')}>
{t('exportMarkdown')}
</button>
{isProbe ? (
<button type="button" className="nm-btn nm-btn-primary" onClick={() => onOpenSession('remoteDesktop')}>
{t('openRemoteDesktop')}
</button>
) : (
<>
<button type="button" className="nm-btn nm-btn-ghost" onClick={() => onOpenSession('sftp')}>
{t('openSftp')}
</button>
<button type="button" className="nm-btn nm-btn-primary" onClick={() => onOpenSession('terminal')}>
{t('openTerminal')}
</button>
</>
)}
</div>
</header>
{/* Operational Tabs */}
<nav className="nm-tabs" role="tablist">
<button
type="button"
role="tab"
aria-selected={activeTab === 'overview'}
className={`nm-tab ${activeTab === 'overview' ? 'nm-tab-active' : ''}`}
onClick={() => setActiveTab('overview')}
>
{t('tabOverview')}
</button>
{!isProbe && (
<>
<button
type="button"
role="tab"
aria-selected={activeTab === 'processes'}
className={`nm-tab ${activeTab === 'processes' ? 'nm-tab-active' : ''}`}
onClick={() => setActiveTab('processes')}
>
{t('tabProcesses')}
</button>
<button
type="button"
role="tab"
aria-selected={activeTab === 'services'}
className={`nm-tab ${activeTab === 'services' ? 'nm-tab-active' : ''}`}
onClick={() => setActiveTab('services')}
>
{t('tabServices')}
</button>
<button
type="button"
role="tab"
aria-selected={activeTab === 'ports'}
className={`nm-tab ${activeTab === 'ports' ? 'nm-tab-active' : ''}`}
onClick={() => setActiveTab('ports')}
>
{t('tabNetwork')}
</button>
</>
)}
<button
type="button"
role="tab"
aria-selected={activeTab === 'alerts'}
className={`nm-tab ${activeTab === 'alerts' ? 'nm-tab-active' : ''}`}
onClick={() => setActiveTab('alerts')}
>
{t('tabAlerts')}
{hostAlerts.length > 0 && <span className="nm-badge nm-badge-crit">{hostAlerts.length}</span>}
</button>
</nav>
{/* Active Tab Content */}
{activeTab === 'overview' ? (
<OverviewTab
host={host}
state={state}
interval={interval}
range={range}
thresholds={thresholds}
visibleWidgets={visibleWidgets}
locale={locale}
t={t}
/>
) : (
<Suspense fallback={<div className="nm-content">{t('loadingData')}</div>}>
{activeTab === 'processes' && <ProcessesTab host={host} engine={engine} bridge={bridge} t={t} />}
{activeTab === 'services' && <ServicesTab host={host} engine={engine} bridge={bridge} t={t} />}
{activeTab === 'ports' && <PortsTab host={host} engine={engine} bridge={bridge} t={t} />}
{activeTab === 'alerts' && (
<AlertsTab
alerts={alerts}
thresholds={thresholds}
hostFilterId={host.hostId}
locale={locale}
t={t}
onSaveThresholds={onSaveThresholds}
onAckAlert={onAckAlert}
onAckAll={onAckAll}
onClearResolved={onClearResolved}
/>
)}
</Suspense>
)}
</div>
);
}
@@ -1,16 +0,0 @@
import React from 'react';
export type MonitorIconName = 'hosts' | 'online' | 'warnings' | 'critical' | 'cpu' | 'memory';
export function MonitorIcon({ name, className = 'nm-kpi-icon' }: { name: MonitorIconName; className?: string }) {
return (
<img
className={className}
src={`asset:assets/ui/${name}.svg`}
alt=""
width={15}
height={15}
aria-hidden="true"
/>
);
}
@@ -1,701 +0,0 @@
import React, { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { JsonValue, PluginContext } from '@netcatty/plugin-sdk';
import { PluginSplitPane, usePluginShortcuts } from '@netcatty/plugin-sdk/host-react';
import { computeAlertBadge, DEFAULT_ALERT_THRESHOLDS, normalizeAlertThresholds } from '../domain/alerts';
import { formatLatency, formatLoadAverage, formatMarkdownDiagnostics, formatMemoryPercent } from '../domain/formatting';
import { createTranslator, resolveMonitorLocale } from '../domain/i18n';
import {
ALL_OVERVIEW_WIDGETS,
DEFAULT_MONITOR_INTERVAL,
normalizeMonitorPanels,
normalizeVisibleWidgets,
reorderMonitorHosts,
} from '../domain/panels';
import type { AlertThresholds, MonitorHostRef, MonitorPanel, OverviewWidgetKey } from '../domain/types';
import { createMonitorHostBridge, type MonitorHostBridge } from '../services/hostBridge';
import { MonitorEngine, type MonitorEngineSnapshot } from '../services/monitorEngine';
import { FleetOverview } from './FleetOverview';
const HostWorkbench = lazy(() => import('./HostWorkbench'));
const AlertsTab = lazy(() => import('./tabs/AlertsTab'));
const STORAGE_PANELS = 'monitor:panels';
const STORAGE_HOSTS = 'monitor:hosts';
const STORAGE_PINNED = 'monitor:pinned';
const STORAGE_HIDDEN_COLS = 'monitor:hiddenCols';
const STORAGE_THRESHOLDS = 'monitor:thresholds';
const STORAGE_VISIBLE_WIDGETS = 'monitor:visibleWidgets';
function createDefaultPanel(locale: 'en' | 'zh-CN'): MonitorPanel {
return {
id: 'default-fleet',
name: locale === 'zh-CN' ? '默认集群' : 'Default Fleet',
description: '',
hostIds: [],
view: 'charts',
interval: DEFAULT_MONITOR_INTERVAL,
range: 15,
sort: 'manual',
};
}
export interface MonitorWorkbenchProps {
context: PluginContext;
bridgeOverride?: MonitorHostBridge;
}
export function MonitorWorkbench({ context, bridgeOverride }: MonitorWorkbenchProps) {
const [locale, setLocale] = useState(() => resolveMonitorLocale(context.environment?.locale));
const [theme, setTheme] = useState(() => context.environment?.theme ?? 'dark');
const t = useMemo(() => createTranslator(locale), [locale]);
const bridge = useMemo(() => bridgeOverride ?? createMonitorHostBridge(context), [context, bridgeOverride]);
const engineRef = useRef<MonitorEngine | null>(null);
if (!engineRef.current) {
engineRef.current = new MonitorEngine(bridge);
}
const engine = engineRef.current;
const [panels, setPanels] = useState<MonitorPanel[]>(() => [createDefaultPanel(resolveMonitorLocale(context.environment?.locale))]);
const [activePanelId, setActivePanelId] = useState<string>('default-fleet');
const [hostCatalog, setHostCatalog] = useState<Record<string, MonitorHostRef>>({});
const [pinnedHostIds, setPinnedHostIds] = useState<string[]>([]);
const [hiddenColumns, setHiddenColumns] = useState<string[]>([]);
const [visibleWidgets, setVisibleWidgets] = useState<OverviewWidgetKey[]>([...ALL_OVERVIEW_WIDGETS]);
const [thresholds, setThresholds] = useState<AlertThresholds>(DEFAULT_ALERT_THRESHOLDS);
const [running, setRunning] = useState<boolean>(true);
const [focusedHostId, setFocusedHostId] = useState<string | null>(null);
const [showGlobalAlerts, setShowGlobalAlerts] = useState(false);
const [hydrated, setHydrated] = useState(false);
const [panelModal, setPanelModal] = useState<{ mode: 'create' | 'edit'; id?: string; name: string; description: string } | null>(null);
const [engineSnap, setEngineSnap] = useState<MonitorEngineSnapshot>(() => engine.getSnapshot());
// Subscribe to host environment changes (locale & theme)
useEffect(() => {
const sub = context.environment?.onDidChange?.((env) => {
setLocale(resolveMonitorLocale(env.locale));
setTheme(env.theme);
});
return () => sub?.dispose();
}, [context.environment]);
// Sync active unacknowledged alerts to the Netcatty Vault sidebar badge (deduplicated)
const lastBadgeKeyRef = useRef<string | null>(null);
useEffect(() => {
const badge = computeAlertBadge(engineSnap.alerts, locale);
const key = badge ? `${badge.count}|${badge.tone}|${badge.tooltip}` : 'none';
if (lastBadgeKeyRef.current === key) return;
lastBadgeKeyRef.current = key;
void bridge.setViewBadge(badge);
}, [bridge, engineSnap.alerts, locale]);
useEffect(() => {
return () => {
lastBadgeKeyRef.current = null;
void bridge.setViewBadge(null);
};
}, [bridge]);
// Subscribe to MonitorEngine updates and clean up on unmount
useEffect(() => {
const unsub = engine.subscribe(() => {
setEngineSnap(engine.getSnapshot());
});
return () => {
unsub();
engine.dispose();
};
}, [engine]);
// Hydrate persisted state and refresh durable Vault host bindings
useEffect(() => {
let cancelled = false;
void (async () => {
const [rawPanels, rawHosts, rawPinned, rawHidden, rawThresholds, rawWidgets] = await Promise.all([
bridge.loadStorage<JsonValue>(STORAGE_PANELS),
bridge.loadStorage<JsonValue>(STORAGE_HOSTS),
bridge.loadStorage<JsonValue>(STORAGE_PINNED),
bridge.loadStorage<JsonValue>(STORAGE_HIDDEN_COLS),
bridge.loadStorage<JsonValue>(STORAGE_THRESHOLDS),
bridge.loadStorage<JsonValue>(STORAGE_VISIBLE_WIDGETS),
]);
if (cancelled) return;
const loadedPanels = normalizeMonitorPanels(rawPanels);
const effectivePanels = loadedPanels.length > 0 ? loadedPanels : [createDefaultPanel(locale)];
setPanels(effectivePanels);
setActivePanelId(effectivePanels[0].id);
const loadedCatalog: Record<string, MonitorHostRef> = {};
if (rawHosts && typeof rawHosts === 'object' && !Array.isArray(rawHosts)) {
for (const [id, raw] of Object.entries(rawHosts as Record<string, unknown>)) {
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
const h = raw as Record<string, unknown>;
loadedCatalog[id] = {
hostId: id,
hostBindingToken: typeof h.hostBindingToken === 'string' ? h.hostBindingToken : id,
label: typeof h.label === 'string' ? h.label : id.slice(0, 12),
hostname: typeof h.hostname === 'string' ? h.hostname : undefined,
port: typeof h.port === 'number' ? h.port : undefined,
username: typeof h.username === 'string' ? h.username : undefined,
protocol: typeof h.protocol === 'string' ? h.protocol : 'ssh',
group: typeof h.group === 'string' ? h.group : undefined,
tags: Array.isArray(h.tags) ? h.tags.filter((x): x is string => typeof x === 'string') : [],
notes: typeof h.notes === 'string' ? h.notes : undefined,
os: typeof h.os === 'string' ? h.os : undefined,
};
}
}
}
setHostCatalog(loadedCatalog);
if (Array.isArray(rawPinned)) {
setPinnedHostIds(rawPinned.filter((id): id is string => typeof id === 'string'));
}
if (Array.isArray(rawHidden)) {
setHiddenColumns(rawHidden.filter((col): col is string => typeof col === 'string'));
}
setVisibleWidgets(normalizeVisibleWidgets(rawWidgets));
const normThresholds = normalizeAlertThresholds(rawThresholds);
setThresholds(normThresholds);
engine.setThresholds(normThresholds);
setHydrated(true);
// Refresh host labels/tags/groups for all persisted durable bindings without showing a modal
const allTokens = [
...new Set(effectivePanels.flatMap((p) => p.hostIds).filter((id) => id.startsWith('hb_'))),
];
if (allTokens.length > 0) {
const resolved = await bridge.resolveHostBindings(allTokens);
if (cancelled) return;
if (resolved.length > 0) {
setHostCatalog((prev) => {
const next = { ...prev };
for (const item of resolved) {
if (item.status === 'available' && item.host) {
next[item.hostBindingToken] = item.host;
}
}
return next;
});
}
}
})();
return () => {
cancelled = true;
};
}, [bridge, engine]);
const activePanel = useMemo(
() => panels.find((p) => p.id === activePanelId) ?? panels[0],
[panels, activePanelId],
);
const activePanelHosts = useMemo<MonitorHostRef[]>(() => {
if (!activePanel) return [];
return activePanel.hostIds.map(
(id) =>
hostCatalog[id] ?? {
hostId: id,
hostBindingToken: id,
label: id.slice(0, 12),
},
);
}, [activePanel, hostCatalog]);
// Reconcile active panel hosts with MonitorEngine
useEffect(() => {
if (!hydrated || !activePanel) return;
engine.reconcileHosts(activePanelHosts, { running, interval: activePanel.interval });
}, [hydrated, engine, activePanelHosts, running, activePanel?.interval]);
const persistPanels = useCallback(
(next: MonitorPanel[]) => {
setPanels(next);
void bridge.saveStorage(STORAGE_PANELS, next as unknown as JsonValue);
},
[bridge],
);
const persistCatalog = useCallback(
(next: Record<string, MonitorHostRef>) => {
setHostCatalog(next);
void bridge.saveStorage(STORAGE_HOSTS, next as unknown as JsonValue);
},
[bridge],
);
const handleUpdatePanel = useCallback(
(patch: Partial<MonitorPanel>) => {
if (!activePanel) return;
const next = panels.map((p) => (p.id === activePanel.id ? { ...p, ...patch } : p));
persistPanels(next);
},
[activePanel, panels, persistPanels],
);
const handleAddHosts = useCallback(async () => {
if (!activePanel) return;
const selected = await bridge.selectHosts(t('selectHosts'));
if (selected.length === 0) return;
const nextCatalog = { ...hostCatalog };
const nextIds = [...activePanel.hostIds];
for (const h of selected) {
nextCatalog[h.hostId] = h;
if (!nextIds.includes(h.hostId)) nextIds.push(h.hostId);
}
persistCatalog(nextCatalog);
persistPanels(panels.map((p) => (p.id === activePanel.id ? { ...p, hostIds: nextIds } : p)));
setRunning(true);
}, [activePanel, bridge, hostCatalog, panels, persistCatalog, persistPanels, t]);
const handleRemoveHost = useCallback(
(hostId: string) => {
if (!activePanel) return;
const nextPanels = panels.map((p) =>
p.id === activePanel.id ? { ...p, hostIds: p.hostIds.filter((id) => id !== hostId) } : p,
);
persistPanels(nextPanels);
if (focusedHostId === hostId) setFocusedHostId(null);
const stillReferenced = nextPanels.some((p) => p.hostIds.includes(hostId));
if (!stillReferenced && hostId.startsWith('hb_')) {
void bridge.revokeHostBinding(hostId);
}
},
[activePanel, bridge, focusedHostId, panels, persistPanels],
);
const handleTogglePin = useCallback(
(hostId: string) => {
const next = pinnedHostIds.includes(hostId)
? pinnedHostIds.filter((id) => id !== hostId)
: [...pinnedHostIds, hostId];
setPinnedHostIds(next);
void bridge.saveStorage(STORAGE_PINNED, next as unknown as JsonValue);
},
[bridge, pinnedHostIds],
);
const handleReorderHost = useCallback(
(hostId: string, direction: 'up' | 'down') => {
if (!activePanel) return;
const idx = activePanel.hostIds.indexOf(hostId);
if (idx < 0) return;
const targetIdx = direction === 'up' ? idx - 1 : idx + 1;
if (targetIdx < 0 || targetIdx >= activePanel.hostIds.length) return;
const reordered = reorderMonitorHosts(activePanel.hostIds, hostId, activePanel.hostIds[targetIdx]);
persistPanels(panels.map((p) => (p.id === activePanel.id ? { ...p, hostIds: reordered } : p)));
},
[activePanel, panels, persistPanels],
);
const handleToggleColumn = useCallback(
(col: string) => {
const next = hiddenColumns.includes(col)
? hiddenColumns.filter((c) => c !== col)
: [...hiddenColumns, col];
setHiddenColumns(next);
void bridge.saveStorage(STORAGE_HIDDEN_COLS, next as unknown as JsonValue);
},
[bridge, hiddenColumns],
);
const handleToggleWidget = useCallback(
(widget: OverviewWidgetKey) => {
const exists = visibleWidgets.includes(widget);
const next = exists
? visibleWidgets.length > 1
? visibleWidgets.filter((w) => w !== widget)
: visibleWidgets
: [...visibleWidgets, widget];
setVisibleWidgets(next);
void bridge.saveStorage(STORAGE_VISIBLE_WIDGETS, next as unknown as JsonValue);
},
[bridge, visibleWidgets],
);
const handleSaveThresholds = useCallback(
(next: AlertThresholds) => {
const normalized = normalizeAlertThresholds(next);
setThresholds(normalized);
engine.setThresholds(normalized);
void bridge.saveStorage(STORAGE_THRESHOLDS, normalized as unknown as JsonValue);
},
[bridge, engine],
);
const handleSavePanelModal = useCallback(() => {
if (!panelModal || !panelModal.name.trim()) return;
if (panelModal.mode === 'create') {
const created: MonitorPanel = {
id: `panel-${Date.now()}`,
name: panelModal.name.trim().slice(0, 120),
description: panelModal.description.trim().slice(0, 1000),
hostIds: [],
view: 'charts',
interval: DEFAULT_MONITOR_INTERVAL,
range: 15,
sort: 'manual',
};
const next = normalizeMonitorPanels([...panels, created]);
persistPanels(next);
setActivePanelId(created.id);
setFocusedHostId(null);
setShowGlobalAlerts(false);
} else if (panelModal.id) {
const next = normalizeMonitorPanels(
panels.map((p) =>
p.id === panelModal.id
? {
...p,
name: panelModal.name.trim().slice(0, 120),
description: panelModal.description.trim().slice(0, 1000),
}
: p,
),
);
persistPanels(next);
}
setPanelModal(null);
}, [panelModal, panels, persistPanels]);
const handleDeletePanel = useCallback(
(panelId: string) => {
if (panels.length <= 1) return;
const next = panels.filter((p) => p.id !== panelId);
persistPanels(next);
if (activePanelId === panelId) {
setActivePanelId(next[0].id);
setFocusedHostId(null);
}
},
[activePanelId, panels, persistPanels],
);
const handleDuplicatePanel = useCallback(
(panel: MonitorPanel) => {
const dup: MonitorPanel = {
...panel,
id: `panel-${Date.now()}`,
name: `${panel.name} Copy`,
};
const next = normalizeMonitorPanels([...panels, dup]);
persistPanels(next);
setActivePanelId(dup.id);
},
[panels, persistPanels],
);
const handleExportSnapshot = useCallback(
(format: 'json' | 'md', hostId?: string) => {
const nowIso = new Date().toISOString();
const baseName = hostId
? `monitor-${(hostCatalog[hostId]?.label || 'host').replace(/[^a-zA-Z0-9_-]/g, '_')}`
: `monitor-${(activePanel?.name || 'fleet').replace(/[^a-zA-Z0-9_-]/g, '_')}`;
if (format === 'md') {
const targetHosts = hostId
? activePanelHosts.filter((h) => h.hostId === hostId)
: activePanelHosts;
const md = formatMarkdownDiagnostics({
title: hostId ? (hostCatalog[hostId]?.label || 'Host') : (activePanel?.name || 'Fleet'),
generatedAt: nowIso,
hosts: targetHosts.map((h) => {
const st = engineSnap.hosts[h.hostId];
const s = st?.stats;
return {
label: h.label,
hostname: h.hostname,
status: st?.status ?? 'idle',
cpu: s?.cpu ?? null,
memPercent: formatMemoryPercent(s?.memUsed, s?.memTotal),
diskPercent: s?.diskPercent ?? null,
load: formatLoadAverage(s?.loadAverage),
latency: formatLatency(st?.mode === 'probe' ? st.probe?.rttMs : (s?.latencyMs ?? s?.responseLatencyMs)),
os: s?.osName || h.os,
};
}),
activeAlerts: engineSnap.alerts
.filter((a) => !a.resolvedAt && (!hostId || a.hostId === hostId))
.map((a) => ({ severity: a.severity, message: a.message })),
});
void bridge.saveMarkdownReport(`${baseName}.md`, md);
return;
}
const payload = hostId
? {
exportedAt: nowIso,
host: hostCatalog[hostId],
runtime: engineSnap.hosts[hostId],
}
: {
exportedAt: nowIso,
panel: activePanel,
hosts: activePanelHosts.map((h) => ({ host: h, runtime: engineSnap.hosts[h.hostId] })),
alerts: engineSnap.alerts,
};
void bridge.saveJsonSnapshot(`${baseName}.json`, payload);
},
[activePanel, activePanelHosts, bridge, engineSnap, hostCatalog],
);
usePluginShortcuts((shortcut) => {
if (shortcut === 'escape') {
if (panelModal) setPanelModal(null);
else if (focusedHostId) setFocusedHostId(null);
else if (showGlobalAlerts) setShowGlobalAlerts(false);
}
});
const activeAlertsCount = useMemo(
() => engineSnap.alerts.filter((a) => !a.resolvedAt && !a.acknowledged).length,
[engineSnap.alerts],
);
const pinnedSet = useMemo(() => new Set(pinnedHostIds), [pinnedHostIds]);
const focusedHost = focusedHostId ? activePanelHosts.find((h) => h.hostId === focusedHostId) ?? hostCatalog[focusedHostId] ?? null : null;
const brandIconSrc =
theme.toLowerCase().includes('light') ? 'asset:assets/plugin-icon-light.png' : 'asset:assets/plugin-icon-dark.png';
return (
<div className="nm-root" data-monitor-workbench="true">
<PluginSplitPane className="nm-split" direction="horizontal" initialSize={224} minSize={180} maxSize={340} collapsible>
{/* Left Navigation & Panels Rail */}
<aside className="nm-sidebar">
<div className="nm-sidebar-header">
<div className="nm-brand">
<img className="nm-brand-icon" src={brandIconSrc} alt="Monitor" />
<span className="nm-brand-title">{t('appTitle')}</span>
</div>
<button
type="button"
className="nm-btn nm-btn-sm nm-btn-ghost"
title={t('newPanel')}
onClick={() => setPanelModal({ mode: 'create', name: '', description: '' })}
>
+
</button>
</div>
<div className="nm-sidebar-section">
<div className="nm-section-label">
<span>{t('panels')}</span>
<span>{panels.length}</span>
</div>
{panels.map((p) => {
const isSelected = !showGlobalAlerts && p.id === activePanel?.id;
return (
<button
key={p.id}
type="button"
className={`nm-panel-item ${isSelected ? 'nm-panel-item-active' : ''}`}
onClick={() => {
setActivePanelId(p.id);
setFocusedHostId(null);
setShowGlobalAlerts(false);
}}
>
<span className="nm-panel-name">{p.name}</span>
<span className="nm-count-pill nm-mono">{p.hostIds.length}</span>
</button>
);
})}
<div className="nm-section-label" style={{ marginTop: 10 }}>
<span>{t('tabAlerts')}</span>
</div>
<button
type="button"
className={`nm-panel-item ${showGlobalAlerts ? 'nm-panel-item-active' : ''}`}
onClick={() => {
setShowGlobalAlerts(true);
setFocusedHostId(null);
}}
>
<span className="nm-panel-name">{t('alertsTitle')}</span>
{activeAlertsCount > 0 ? (
<span className="nm-badge nm-badge-crit">{activeAlertsCount}</span>
) : (
<span className="nm-count-pill nm-mono">0</span>
)}
</button>
</div>
{activePanel && (
<div className="nm-sidebar-footer">
<button
type="button"
className="nm-btn nm-btn-ghost"
onClick={() =>
setPanelModal({
mode: 'edit',
id: activePanel.id,
name: activePanel.name,
description: activePanel.description,
})
}
>
{t('editPanel')}
</button>
<div style={{ display: 'flex', gap: 6 }}>
<button
type="button"
className="nm-btn nm-btn-sm nm-btn-ghost"
style={{ flex: 1 }}
onClick={() => handleDuplicatePanel(activePanel)}
>
{t('duplicatePanel')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm nm-btn-danger"
style={{ flex: 1 }}
disabled={panels.length <= 1}
onClick={() => handleDeletePanel(activePanel.id)}
>
{t('deletePanel')}
</button>
</div>
</div>
)}
</aside>
{/* Right Main Canvas */}
<main className="nm-main">
{!bridge.supportsHostExec && (
<div className="nm-inline-banner" style={{ margin: '10px 16px 0' }}>
<span>{t('execUnavailable')}</span>
</div>
)}
{showGlobalAlerts ? (
<>
<header className="nm-topbar">
<div className="nm-topbar-left">
<h1 className="nm-page-title">{t('tabAlerts')}</h1>
<span className="nm-page-sub">{t('appSubtitle')}</span>
</div>
</header>
<Suspense fallback={<div className="nm-content">{t('loadingData')}</div>}>
<AlertsTab
alerts={engineSnap.alerts}
thresholds={thresholds}
locale={locale}
t={t}
onSaveThresholds={handleSaveThresholds}
onAckAlert={(id) => engine.acknowledgeAlert(id)}
onAckAll={() => engine.acknowledgeAllAlerts()}
onClearResolved={() => engine.clearResolvedAlerts()}
/>
</Suspense>
</>
) : focusedHost && activePanel ? (
<Suspense fallback={<div className="nm-content">{t('loadingData')}</div>}>
<HostWorkbench
host={focusedHost}
state={engineSnap.hosts[focusedHost.hostId]}
interval={activePanel.interval}
range={activePanel.range}
alerts={engineSnap.alerts}
thresholds={thresholds}
visibleWidgets={visibleWidgets}
engine={engine}
bridge={bridge}
locale={locale}
t={t}
onBack={() => setFocusedHostId(null)}
onChangeRange={(r) => handleUpdatePanel({ range: r })}
onToggleWidget={handleToggleWidget}
onRetry={() => engine.retryHost(focusedHost.hostId)}
onOpenSession={(mode) => void bridge.openHostSession(focusedHost, mode)}
onExportSnapshot={(fmt) => handleExportSnapshot(fmt, focusedHost.hostId)}
onSaveThresholds={handleSaveThresholds}
onAckAlert={(id) => engine.acknowledgeAlert(id)}
onAckAll={() => engine.acknowledgeAllAlerts()}
onClearResolved={() => engine.clearResolvedAlerts()}
/>
</Suspense>
) : activePanel ? (
<>
<header className="nm-topbar">
<div className="nm-topbar-left">
<h1 className="nm-page-title">{activePanel.name}</h1>
{activePanel.description && <span className="nm-page-sub">{activePanel.description}</span>}
</div>
</header>
<FleetOverview
panel={activePanel}
hosts={activePanelHosts}
runtimeHosts={engineSnap.hosts}
pinnedHostIds={pinnedSet}
hiddenColumns={hiddenColumns}
thresholds={thresholds}
running={running}
locale={locale}
t={t}
onUpdatePanel={handleUpdatePanel}
onToggleRunning={() => setRunning((r) => !r)}
onRefreshNow={() => engine.refreshAllNow()}
onAddHosts={() => void handleAddHosts()}
onRemoveHost={handleRemoveHost}
onTogglePin={handleTogglePin}
onReorderHost={handleReorderHost}
onToggleColumn={handleToggleColumn}
onInspectHost={(id) => setFocusedHostId(id)}
onRetryHost={(id) => engine.retryHost(id)}
onOpenSession={(host, mode) => void bridge.openHostSession(host, mode)}
onExportSnapshot={(fmt) => handleExportSnapshot(fmt)}
/>
</>
) : null}
</main>
</PluginSplitPane>
{/* Panel Create / Edit Modal */}
{panelModal && (
<div className="nm-modal-backdrop">
<div className="nm-modal-card">
<h3 className="nm-panel-card-title">
{panelModal.mode === 'create' ? t('newPanel') : t('editPanel')}
</h3>
<label className="nm-field-label">
<span>{t('panelName')}</span>
<input
type="text"
className="nm-input"
maxLength={120}
value={panelModal.name}
onChange={(e) => setPanelModal((m) => (m ? { ...m, name: e.target.value } : null))}
/>
</label>
<label className="nm-field-label">
<span>{t('panelDescription')}</span>
<textarea
className="nm-textarea"
rows={3}
maxLength={1000}
value={panelModal.description}
onChange={(e) => setPanelModal((m) => (m ? { ...m, description: e.target.value } : null))}
/>
</label>
<div className="nm-modal-actions">
<button type="button" className="nm-btn" onClick={() => setPanelModal(null)}>
{t('cancel')}
</button>
<button
type="button"
className="nm-btn nm-btn-primary"
disabled={!panelModal.name.trim()}
onClick={handleSavePanelModal}
>
{t('save')}
</button>
</div>
</div>
</div>
)}
</div>
);
}
@@ -1,252 +0,0 @@
import React, { useState } from 'react';
import { DEFAULT_ALERT_THRESHOLDS } from '../../domain/alerts';
import { formatRelativeAge } from '../../domain/formatting';
import type { I18nKey, MonitorLocale } from '../../domain/i18n';
import type { AlertEvent, AlertThresholds } from '../../domain/types';
export interface AlertsTabProps {
alerts: AlertEvent[];
thresholds: AlertThresholds;
hostFilterId?: string | null;
locale: MonitorLocale;
t: (key: I18nKey) => string;
onSaveThresholds: (next: AlertThresholds) => void;
onAckAlert: (id: string) => void;
onAckAll: () => void;
onClearResolved: () => void;
}
export default function AlertsTab({
alerts,
thresholds,
hostFilterId,
locale,
t,
onSaveThresholds,
onAckAlert,
onAckAll,
onClearResolved,
}: AlertsTabProps) {
const [draft, setDraft] = useState<AlertThresholds>(thresholds);
const visibleAlerts = hostFilterId ? alerts.filter((a) => a.hostId === hostFilterId) : alerts;
const setNum = (key: keyof AlertThresholds, raw: string) => {
const val = Number(raw);
if (!Number.isFinite(val)) return;
setDraft((prev) => ({ ...prev, [key]: val }));
};
return (
<div className="nm-content">
{/* Incident Timeline */}
<section className="nm-panel-card" style={{ marginBottom: 14 }}>
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">
{t('incidentTimeline')} ({visibleAlerts.filter((a) => !a.resolvedAt).length})
</h3>
<div className="nm-toolbar-group">
<button type="button" className="nm-btn nm-btn-sm" onClick={onAckAll}>
{t('acknowledgeAll')}
</button>
<button type="button" className="nm-btn nm-btn-sm" onClick={onClearResolved}>
{t('clearResolved')}
</button>
</div>
</div>
{visibleAlerts.length === 0 ? (
<p className="nm-panel-card-sub">{t('noAlerts')}</p>
) : (
<div className="nm-disk-list">
{visibleAlerts.map((ev) => (
<div
key={ev.id}
className={`nm-alert-row ${ev.severity === 'critical' ? 'nm-alert-crit' : 'nm-alert-warn'} ${ev.resolvedAt ? 'nm-alert-resolved' : ''}`}
>
<div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span
className={`nm-badge ${
ev.severity === 'critical'
? 'nm-badge-crit'
: ev.severity === 'info'
? 'nm-badge-info'
: 'nm-badge-warn'
}`}
>
{ev.severity.toUpperCase()}
</span>
<strong>{ev.message}</strong>
{ev.resolvedAt && <span className="nm-badge nm-badge-ok">RESOLVED</span>}
</div>
<div className="nm-panel-card-sub nm-mono">
{formatRelativeAge(ev.at, Date.now(), locale)}
{ev.threshold != null ? ` · threshold ${ev.threshold}` : ''}
</div>
</div>
{!ev.acknowledged && !ev.resolvedAt && (
<button type="button" className="nm-btn nm-btn-sm" onClick={() => onAckAlert(ev.id)}>
{t('acknowledge')}
</button>
)}
</div>
))}
</div>
)}
</section>
{/* Threshold & Hysteresis Configuration */}
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">{t('alertRulesTitle')}</h3>
<div className="nm-toolbar-group">
<button
type="button"
className="nm-btn nm-btn-sm"
onClick={() => {
setDraft({ ...DEFAULT_ALERT_THRESHOLDS });
onSaveThresholds({ ...DEFAULT_ALERT_THRESHOLDS });
}}
>
{t('resetDefaults')}
</button>
<button type="button" className="nm-btn nm-btn-sm nm-btn-primary" onClick={() => onSaveThresholds(draft)}>
{t('saveThresholds')}
</button>
</div>
</div>
<div className="nm-threshold-grid">
<div className="nm-threshold-item">
<strong>{t('metricCpu')} (%)</strong>
<div className="nm-threshold-inputs">
<label className="nm-field-label">
<span>{t('thresholdWarn')}</span>
<input type="number" className="nm-input" min={10} max={100} value={draft.cpuWarning} onChange={(e) => setNum('cpuWarning', e.target.value)} />
</label>
<label className="nm-field-label">
<span>{t('thresholdCrit')}</span>
<input type="number" className="nm-input" min={10} max={100} value={draft.cpuCritical} onChange={(e) => setNum('cpuCritical', e.target.value)} />
</label>
</div>
</div>
<div className="nm-threshold-item">
<strong>{t('thresholdIowait')}</strong>
<div className="nm-threshold-inputs">
<label className="nm-field-label">
<span>{t('thresholdWarn')}</span>
<input type="number" className="nm-input" min={5} max={100} value={draft.iowaitWarning} onChange={(e) => setNum('iowaitWarning', e.target.value)} />
</label>
<label className="nm-field-label">
<span>{t('thresholdCrit')}</span>
<input type="number" className="nm-input" min={10} max={100} value={draft.iowaitCritical} onChange={(e) => setNum('iowaitCritical', e.target.value)} />
</label>
</div>
</div>
<div className="nm-threshold-item">
<strong>{t('metricMemory')} (%)</strong>
<div className="nm-threshold-inputs">
<label className="nm-field-label">
<span>{t('thresholdWarn')}</span>
<input type="number" className="nm-input" min={10} max={100} value={draft.memoryWarning} onChange={(e) => setNum('memoryWarning', e.target.value)} />
</label>
<label className="nm-field-label">
<span>{t('thresholdCrit')}</span>
<input type="number" className="nm-input" min={10} max={100} value={draft.memoryCritical} onChange={(e) => setNum('memoryCritical', e.target.value)} />
</label>
</div>
</div>
<div className="nm-threshold-item">
<strong>{t('metricDisk')} (%)</strong>
<div className="nm-threshold-inputs">
<label className="nm-field-label">
<span>{t('thresholdWarn')}</span>
<input type="number" className="nm-input" min={10} max={100} value={draft.diskWarning} onChange={(e) => setNum('diskWarning', e.target.value)} />
</label>
<label className="nm-field-label">
<span>{t('thresholdCrit')}</span>
<input type="number" className="nm-input" min={10} max={100} value={draft.diskCritical} onChange={(e) => setNum('diskCritical', e.target.value)} />
</label>
</div>
</div>
<div className="nm-threshold-item">
<strong>{t('thresholdInode')}</strong>
<div className="nm-threshold-inputs">
<label className="nm-field-label">
<span>{t('thresholdWarn')}</span>
<input type="number" className="nm-input" min={10} max={100} value={draft.inodeWarning} onChange={(e) => setNum('inodeWarning', e.target.value)} />
</label>
<label className="nm-field-label">
<span>{t('thresholdCrit')}</span>
<input type="number" className="nm-input" min={10} max={100} value={draft.inodeCritical} onChange={(e) => setNum('inodeCritical', e.target.value)} />
</label>
</div>
</div>
<div className="nm-threshold-item">
<strong>{t('metricLoad')} (× cores)</strong>
<div className="nm-threshold-inputs">
<label className="nm-field-label">
<span>{t('thresholdWarn')}</span>
<input type="number" step="0.1" className="nm-input" min={0.2} max={20} value={draft.loadPerCoreWarning} onChange={(e) => setNum('loadPerCoreWarning', e.target.value)} />
</label>
<label className="nm-field-label">
<span>{t('thresholdCrit')}</span>
<input type="number" step="0.1" className="nm-input" min={0.5} max={40} value={draft.loadPerCoreCritical} onChange={(e) => setNum('loadPerCoreCritical', e.target.value)} />
</label>
</div>
</div>
<div className="nm-threshold-item">
<strong>{t('thresholdNetDrops')}</strong>
<div className="nm-threshold-inputs">
<label className="nm-field-label">
<span>{t('thresholdWarn')}</span>
<input type="number" className="nm-input" min={1} max={100000} value={draft.netDropsWarning} onChange={(e) => setNum('netDropsWarning', e.target.value)} />
</label>
<label className="nm-field-label">
<span>{t('thresholdCrit')}</span>
<input type="number" className="nm-input" min={5} max={1000000} value={draft.netDropsCritical} onChange={(e) => setNum('netDropsCritical', e.target.value)} />
</label>
</div>
</div>
<div className="nm-threshold-item">
<strong>{t('metricLatency')} (ms)</strong>
<div className="nm-threshold-inputs">
<label className="nm-field-label">
<span>{t('thresholdWarn')}</span>
<input type="number" className="nm-input" min={20} max={5000} value={draft.latencyWarningMs} onChange={(e) => setNum('latencyWarningMs', e.target.value)} />
</label>
<label className="nm-field-label">
<span>{t('thresholdCrit')}</span>
<input type="number" className="nm-input" min={50} max={10000} value={draft.latencyCriticalMs} onChange={(e) => setNum('latencyCriticalMs', e.target.value)} />
</label>
</div>
</div>
<div className="nm-threshold-item">
<strong>{t('thresholdConsecutive')}</strong>
<label className="nm-field-label">
<span>1–10</span>
<input type="number" className="nm-input" min={1} max={10} value={draft.consecutivePolls} onChange={(e) => setNum('consecutivePolls', e.target.value)} />
</label>
</div>
</div>
<label className="nm-checkbox-row" style={{ marginTop: 6 }}>
<input
type="checkbox"
checked={draft.alertOnOffline}
onChange={(e) => setDraft((prev) => ({ ...prev, alertOnOffline: e.target.checked }))}
/>
<span>{t('thresholdOffline')}</span>
</label>
</section>
</div>
);
}
@@ -1,762 +0,0 @@
import React, { useMemo, useState } from 'react';
import { PluginMetricChart } from '@netcatty/plugin-sdk/host-react';
import { buildMonitorDiskListLayout } from '../../domain/disks';
import {
formatCompactCount,
formatDiskGiB,
formatIops,
formatLatency,
formatLoadAverage,
formatMemoryMiB,
formatMemoryPercent,
formatMonitorRate,
formatPercent,
formatUptime,
} from '../../domain/formatting';
import type { I18nKey, MonitorLocale } from '../../domain/i18n';
import { ALL_OVERVIEW_WIDGETS } from '../../domain/panels';
import type {
AlertThresholds,
HostRuntimeState,
MonitorHostRef,
MonitorInterval,
MonitorRangeMinutes,
OverviewWidgetKey,
} from '../../domain/types';
export interface OverviewTabProps {
host: MonitorHostRef;
state: HostRuntimeState | undefined;
interval: MonitorInterval;
range: MonitorRangeMinutes;
thresholds: AlertThresholds;
visibleWidgets?: readonly OverviewWidgetKey[];
locale: MonitorLocale;
t: (key: I18nKey) => string;
}
function coreHeatmapClass(val: number, warn: number, crit: number): string {
if (val >= crit) return 'nm-core-cell nm-core-cell-crit';
if (val >= warn) return 'nm-core-cell nm-core-cell-warn';
if (val >= 40) return 'nm-core-cell nm-core-cell-mid';
return 'nm-core-cell nm-core-cell-cool';
}
export function OverviewTab({
host,
state,
interval,
range,
thresholds,
visibleWidgets = ALL_OVERVIEW_WIDGETS,
locale,
t,
}: OverviewTabProps) {
const [showSystemDisks, setShowSystemDisks] = useState(false);
const stats = state?.stats;
const points = state?.points ?? [];
const now = Date.now();
const rangeMs = range * 60_000;
const intervalMs = interval * 1_000;
const isProbe = state?.mode === 'probe' || host.protocol === 'rdp' || host.protocol === 'vnc';
const show = (key: OverviewWidgetKey) => visibleWidgets.includes(key);
const rttSummary = useMemo(() => {
const values = points
.map((p) => p.latencyMs)
.filter((v): v is number => typeof v === 'number' && Number.isFinite(v) && v >= 0);
if (values.length === 0) return null;
const min = Math.round(Math.min(...values));
const max = Math.round(Math.max(...values));
const avg = Math.round(values.reduce((a, b) => a + b, 0) / values.length);
return { min, avg, max };
}, [points]);
if (isProbe) {
const probe = state?.probe;
return (
<div className="nm-content">
<div className="nm-chart-grid">
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<div>
<h3 className="nm-panel-card-title">{t('probeLatencyTrend')}</h3>
<span className="nm-panel-card-sub nm-mono">
{(probe?.protocol ?? host.protocol ?? 'rdp').toUpperCase()} :
{probe?.port ?? host.port ?? (host.protocol === 'vnc' ? 5900 : 3389)}
{probe?.bannerVerified ? ` · ${t('probeBannerVerified')}` : ''}
{probe?.bannerDetail ? ` (${probe.bannerDetail})` : ''}
</span>
</div>
<span className={`nm-badge ${probe?.reachable ? 'nm-badge-ok' : 'nm-badge-crit'}`}>
{probe?.reachable ? t('probeReachable') : t('probeUnreachable')} · {formatLatency(probe?.rttMs)}
</span>
</div>
<PluginMetricChart
variant="area"
height={170}
rangeMs={rangeMs}
intervalMs={Math.max(intervalMs, 5_000)}
endAt={now}
min={0}
max="auto"
showGrid
showAxes
interactive
ariaLabel={t('probeLatencyTrend')}
thresholds={[
{ value: thresholds.latencyWarningMs, tone: 'warning', label: `${thresholds.latencyWarningMs}ms` },
{ value: thresholds.latencyCriticalMs, tone: 'critical', label: `${thresholds.latencyCriticalMs}ms` },
]}
series={[
{
id: 'rtt',
label: t('metricLatency'),
color: 'sky',
unit: 'ms',
points: points.map((p) => ({ at: p.at, value: p.latencyMs })),
},
]}
/>
{rttSummary && (
<div className="nm-panel-card-sub nm-mono">
{t('probeRttStats')}: {rttSummary.min} ms / {rttSummary.avg} ms / {rttSummary.max} ms
</div>
)}
</section>
<section className="nm-panel-card">
<h3 className="nm-panel-card-title">{t('hostMetadata')}</h3>
<div className="nm-meta-grid">
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metaAddress')}</span>
<span className="nm-meta-val nm-mono">
{host.hostname || '--'}:{probe?.port ?? host.port ?? (host.protocol === 'vnc' ? 5900 : 3389)}
</span>
</div>
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metaOs')}</span>
<span className="nm-meta-val">{host.os || (probe?.protocol ?? host.protocol ?? 'RDP').toUpperCase()}</span>
</div>
{host.group && (
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metaGroup')}</span>
<span className="nm-meta-val">{host.group}</span>
</div>
)}
{host.tags && host.tags.length > 0 && (
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metaTags')}</span>
<div className="nm-badges-row">
{host.tags.map((tag) => (
<span key={tag} className="nm-badge">
{tag}
</span>
))}
</div>
</div>
)}
</div>
{host.notes && (
<div className="nm-meta-item" style={{ marginTop: 4 }}>
<span className="nm-meta-label">{t('metaNotes')}</span>
<span className="nm-panel-card-sub">{host.notes}</span>
</div>
)}
</section>
</div>
</div>
);
}
const memPct = formatMemoryPercent(stats?.memUsed, stats?.memTotal);
const swapPct = formatMemoryPercent(stats?.swapUsed, stats?.swapTotal);
const fdPct =
stats?.fdUsed != null && stats?.fdMax != null && stats.fdMax > 0
? Math.min(100, (stats.fdUsed / stats.fdMax) * 100)
: null;
const diskLayout = useMemo(
() => buildMonitorDiskListLayout(stats, showSystemDisks, thresholds.diskWarning),
[stats, showSystemDisks, thresholds.diskWarning],
);
const hasCpuBreakdown = points.some((p) => p.cpuUser != null || p.cpuSystem != null);
return (
<div className="nm-content">
{/* 4 Primary Real-Time Multi-Series Charts */}
<div className="nm-chart-grid">
{/* CPU Deep Breakdown Chart */}
{show('cpuBreakdown') && (
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<div>
<h3 className="nm-panel-card-title">{t('metricCpu')}</h3>
<span className="nm-panel-card-sub nm-mono">
{stats?.cpuCores ? `${stats.cpuCores}c` : '--'}
{stats?.cpuUser != null ? ` · ${t('cpuUser')} ${stats.cpuUser}%` : ''}
{stats?.cpuSystem != null ? ` · ${t('cpuSystem')} ${stats.cpuSystem}%` : ''}
{stats?.cpuIowait != null ? ` · ${t('cpuIowait')} ${stats.cpuIowait}%` : ''}
{stats?.cpuSteal != null ? ` · ${t('cpuSteal')} ${stats.cpuSteal}%` : ''}
</span>
</div>
<span className="nm-kpi-value nm-mono">{formatPercent(stats?.cpu, 1)}</span>
</div>
<PluginMetricChart
variant={hasCpuBreakdown ? 'line' : 'area'}
height={152}
rangeMs={rangeMs}
intervalMs={intervalMs}
endAt={now}
min={0}
max={100}
showGrid
showAxes
showLegend={hasCpuBreakdown}
interactive
ariaLabel={t('metricCpu')}
thresholds={[
{ value: thresholds.cpuWarning, tone: 'warning', label: `${thresholds.cpuWarning}%` },
{ value: thresholds.cpuCritical, tone: 'critical', label: `${thresholds.cpuCritical}%` },
]}
series={
hasCpuBreakdown
? [
{
id: 'cpu',
label: t('metricCpu'),
color: 'emerald',
unit: '%',
points: points.map((p) => ({ at: p.at, value: p.cpu })),
},
{
id: 'user',
label: t('cpuUser'),
color: 'sky',
unit: '%',
points: points.map((p) => ({ at: p.at, value: p.cpuUser ?? null })),
},
{
id: 'sys',
label: t('cpuSystem'),
color: 'violet',
unit: '%',
points: points.map((p) => ({ at: p.at, value: p.cpuSystem ?? null })),
},
{
id: 'iowait',
label: t('cpuIowait'),
color: 'amber',
unit: '%',
points: points.map((p) => ({ at: p.at, value: p.cpuIowait ?? null })),
},
{
id: 'steal',
label: t('cpuSteal'),
color: 'rose',
unit: '%',
points: points.map((p) => ({ at: p.at, value: p.cpuSteal ?? null })),
},
]
: [
{
id: 'cpu',
label: t('metricCpu'),
color: 'emerald',
unit: '%',
points: points.map((p) => ({ at: p.at, value: p.cpu })),
},
]
}
/>
{(stats?.contextSwitchesPerSec != null || stats?.procsRunning != null) && (
<div className="nm-micro-grid nm-mono">
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('cpuCtxt')}</span>
<span className="nm-micro-val">{formatCompactCount(stats?.contextSwitchesPerSec)}</span>
</div>
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('cpuIntr')}</span>
<span className="nm-micro-val">{formatCompactCount(stats?.interruptsPerSec)}</span>
</div>
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('cpuProcs')}</span>
<span className="nm-micro-val">
{stats?.procsRunning ?? '--'} / {stats?.procsBlocked ?? '--'}
</span>
</div>
</div>
)}
</section>
)}
{/* Memory, Swap & Linux PSI */}
{show('memoryPsi') && (
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<div>
<h3 className="nm-panel-card-title">{t('metricMemory')}</h3>
<span className="nm-panel-card-sub nm-mono">
{formatMemoryMiB(stats?.memUsed)} / {formatMemoryMiB(stats?.memTotal)}
{stats?.memCached != null ? ` · ${t('memCached')} ${formatMemoryMiB(stats.memCached)}` : ''}
{stats?.memSlab != null ? ` · ${t('memSlab')} ${formatMemoryMiB(stats.memSlab)}` : ''}
</span>
</div>
<span className="nm-kpi-value nm-mono">{formatPercent(memPct, 1)}</span>
</div>
<PluginMetricChart
variant="area"
height={152}
rangeMs={rangeMs}
intervalMs={intervalMs}
endAt={now}
min={0}
max={100}
showGrid
showAxes
showLegend={Boolean(stats?.swapTotal)}
interactive
ariaLabel={t('metricMemory')}
thresholds={[
{ value: thresholds.memoryWarning, tone: 'warning', label: `${thresholds.memoryWarning}%` },
{ value: thresholds.memoryCritical, tone: 'critical', label: `${thresholds.memoryCritical}%` },
]}
series={[
{
id: 'memory',
label: t('metricMemory'),
color: 'sky',
unit: '%',
points: points.map((p) => ({ at: p.at, value: p.memory })),
},
...(stats?.swapTotal
? [
{
id: 'swap',
label: `${t('metricSwap')} (${formatPercent(swapPct, 0)})`,
color: 'amber' as const,
unit: '%' as const,
points: points.map((p) => ({ at: p.at, value: p.swap ?? null })),
},
]
: []),
]}
/>
{stats?.psi && (
<div className="nm-micro-grid nm-mono">
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('psiCpu')}</span>
<span className="nm-micro-val">
{stats.psi.cpuSome10?.toFixed(1) ?? '--'}% / {stats.psi.cpuSome60?.toFixed(1) ?? '--'}%
</span>
</div>
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('psiMem')}</span>
<span className="nm-micro-val">
{stats.psi.memSome10?.toFixed(1) ?? '--'}% / {stats.psi.memFull10?.toFixed(1) ?? '--'}%
</span>
</div>
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('psiIo')}</span>
<span className="nm-micro-val">
{stats.psi.ioSome10?.toFixed(1) ?? '--'}% / {stats.psi.ioFull10?.toFixed(1) ?? '--'}%
</span>
</div>
</div>
)}
</section>
)}
{/* Network RX/TX & TCP Stack */}
{show('networkTcp') && (
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<div>
<h3 className="nm-panel-card-title">{t('metricNetwork')}</h3>
<span className="nm-panel-card-sub nm-mono">
{t('netRx')} {stats?.networkReady ? formatMonitorRate(stats.netRxSpeed) : '--'} ·{' '}
{t('netTx')} {stats?.networkReady ? formatMonitorRate(stats.netTxSpeed) : '--'}
</span>
</div>
<span className="nm-badge nm-badge-info nm-mono">
{formatLatency(stats?.latencyMs ?? stats?.responseLatencyMs)}
</span>
</div>
<PluginMetricChart
variant="line"
height={152}
rangeMs={rangeMs}
intervalMs={intervalMs}
endAt={now}
min={0}
max="auto"
showGrid
showAxes
showLegend
interactive
ariaLabel={t('metricNetwork')}
series={[
{
id: 'rx',
label: t('netRx'),
color: 'cyan',
unit: 'bytes/s',
points: points.map((p) => ({ at: p.at, value: p.rx })),
},
{
id: 'tx',
label: t('netTx'),
color: 'violet',
unit: 'bytes/s',
points: points.map((p) => ({ at: p.at, value: p.tx })),
},
]}
/>
{stats?.networkReady && (
<div className="nm-micro-grid nm-mono">
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('netPps')}</span>
<span className="nm-micro-val">
↓{formatCompactCount(stats.netRxPps)} ↑{formatCompactCount(stats.netTxPps)}/s
</span>
</div>
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('netDrops')}</span>
<span
className="nm-micro-val"
style={{
color:
(stats.netDropsDelta ?? 0) + (stats.netErrorsDelta ?? 0) > 0
? 'var(--plugin-warn)'
: undefined,
}}
>
{stats.netDropsDelta ?? 0} / {stats.netErrorsDelta ?? 0}
</span>
</div>
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('tcpRetrans')}</span>
<span className="nm-micro-val">
{stats.tcpRetransmitsPerSec != null ? `${stats.tcpRetransmitsPerSec}/s` : '--'}
</span>
</div>
</div>
)}
</section>
)}
{/* Disk I/O, IOPS, %Util & Queue Depth */}
{show('diskIoMounts') && (
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<div>
<h3 className="nm-panel-card-title">{t('metricDiskIo')}</h3>
<span className="nm-panel-card-sub nm-mono">
{t('diskRead')} {formatMonitorRate(stats?.diskReadSpeed)} ·{' '}
{t('diskWrite')} {formatMonitorRate(stats?.diskWriteSpeed)}
</span>
</div>
<span className="nm-badge nm-mono">{formatPercent(stats?.diskPercent, 0)} /</span>
</div>
<PluginMetricChart
variant="line"
height={152}
rangeMs={rangeMs}
intervalMs={intervalMs}
endAt={now}
min={0}
max="auto"
showGrid
showAxes
showLegend
interactive
ariaLabel={t('metricDiskIo')}
series={[
{
id: 'diskRead',
label: t('diskRead'),
color: 'emerald',
unit: 'bytes/s',
points: points.map((p) => ({ at: p.at, value: p.diskRead })),
},
{
id: 'diskWrite',
label: t('diskWrite'),
color: 'amber',
unit: 'bytes/s',
points: points.map((p) => ({ at: p.at, value: p.diskWrite })),
},
]}
/>
{(stats?.diskReadIops != null || stats?.diskUtilPercent != null) && (
<div className="nm-micro-grid nm-mono">
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('diskIops')}</span>
<span className="nm-micro-val">{formatIops(stats?.diskReadIops, stats?.diskWriteIops)}</span>
</div>
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('diskUtil')}</span>
<span className="nm-micro-val">
{formatPercent(stats?.diskUtilPercent, 0)} · Q={stats?.diskQueueDepth ?? 0}
</span>
</div>
</div>
)}
</section>
)}
</div>
{/* Per-Core CPU Heatmap Matrix */}
{show('perCore') && stats && stats.cpuPerCore.length > 0 && (
<section className="nm-panel-card" style={{ marginBottom: 14 }}>
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">{t('cpuPerCore')}</h3>
<span className="nm-panel-card-sub nm-mono">
{t('metricLoad')}: {formatLoadAverage(stats.loadAverage)}
</span>
</div>
<div className="nm-core-grid">
{stats.cpuPerCore.map((val, i) => (
<div key={i} className={coreHeatmapClass(val, thresholds.cpuWarning, thresholds.cpuCritical)}>
<div className="nm-core-top nm-mono">
<span>C{i}</span>
<strong>{val}%</strong>
</div>
<div className="nm-bar-track">
<div
className={
val >= thresholds.cpuCritical
? 'nm-bar-fill nm-bar-crit'
: val >= thresholds.cpuWarning
? 'nm-bar-fill nm-bar-warn'
: 'nm-bar-fill nm-bar-ok'
}
style={{ width: `${Math.max(0, Math.min(100, val))}%` }}
/>
</div>
</div>
))}
</div>
</section>
)}
{/* Disk Mounts + Inodes | System Security + GPU & Thermals */}
<div className="nm-two-col">
{show('diskIoMounts') && (
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">{t('diskMounts')}</h3>
<span className="nm-panel-card-sub nm-mono">{stats?.disks.length ?? 0} mounts</span>
</div>
<div className="nm-disk-list">
{diskLayout.rows.map((row, idx) => {
if (row.kind === 'system') {
return (
<button
key={`sys-${idx}`}
type="button"
className="nm-btn"
style={{ justifyContent: 'space-between', width: '100%' }}
disabled={diskLayout.forcedExpanded}
onClick={() => setShowSystemDisks((v) => !v)}
>
<span>
{t('systemDisks')} ({row.count}) {row.alert ? '!' : ''}
</span>
<span>{row.expanded ? t('hideSystemDisks') : t('showSystemDisks')}</span>
</button>
);
}
const pct = row.disk.percent ?? 0;
return (
<div key={row.disk.mountPoint} className={`nm-disk-row ${row.alert ? 'nm-disk-row-alert' : ''}`}>
<div className="nm-disk-head">
<span className="nm-disk-mount nm-mono">{row.disk.mountPoint}</span>
<span className="nm-mono">
{formatDiskGiB(row.disk.used)} / {formatDiskGiB(row.disk.total)} ({formatPercent(row.disk.percent, 0)})
</span>
</div>
<div className="nm-bar-track">
<div
className={
pct >= thresholds.diskCritical
? 'nm-bar-fill nm-bar-crit'
: pct >= thresholds.diskWarning
? 'nm-bar-fill nm-bar-warn'
: 'nm-bar-fill nm-bar-sky'
}
style={{ width: `${Math.max(0, Math.min(100, pct))}%` }}
/>
</div>
{(row.disk.filesystemType || row.disk.diskReadSpeed != null || row.disk.inodePercent != null) && (
<div className="nm-disk-meta nm-mono">
{row.disk.filesystemType && <span>{row.disk.filesystemType}</span>}
{row.disk.inodePercent != null && (
<span
style={{
color:
row.disk.inodePercent >= thresholds.inodeCritical
? 'var(--plugin-crit)'
: row.disk.inodePercent >= thresholds.inodeWarning
? 'var(--plugin-warn)'
: undefined,
}}
>
{t('inodesLabel')}: {row.disk.inodePercent}%
</span>
)}
{row.disk.diskReadSpeed != null && (
<span>
R: {formatMonitorRate(row.disk.diskReadSpeed)} · W: {formatMonitorRate(row.disk.diskWriteSpeed)}
</span>
)}
</div>
)}
</div>
);
})}
</div>
</section>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{show('systemSecurity') && (
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">{t('hostMetadata')}</h3>
{stats?.activeUsers != null && (
<span className="nm-badge nm-mono">
{t('activeUsersLabel')}: {stats.activeUsers}
</span>
)}
</div>
<div className="nm-meta-grid">
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metaHostname')}</span>
<span className="nm-meta-val nm-mono">{stats?.hostname || host.hostname || '--'}</span>
</div>
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metaAddress')}</span>
<span className="nm-meta-val nm-mono">
{host.username ? `${host.username}@` : ''}
{host.hostname || '--'}
{host.port ? `:${host.port}` : ''}
</span>
</div>
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metaOs')}</span>
<span className="nm-meta-val">{stats?.osName || host.os || '--'}</span>
</div>
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metaKernel')}</span>
<span className="nm-meta-val nm-mono">{stats?.kernelRelease || '--'}</span>
</div>
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metricUptime')}</span>
<span className="nm-meta-val nm-mono">{formatUptime(stats?.uptimeSeconds, locale)}</span>
</div>
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metricLoad')}</span>
<span className="nm-meta-val nm-mono">{formatLoadAverage(stats?.loadAverage)}</span>
</div>
</div>
{stats?.fdUsed != null && stats?.fdMax != null && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<div className="nm-disk-head nm-mono">
<span className="nm-meta-label">{t('openFds')}</span>
<span>
{formatCompactCount(stats.fdUsed)} / {formatCompactCount(stats.fdMax)} ({formatPercent(fdPct, 1)})
</span>
</div>
<div className="nm-bar-track">
<div
className={(fdPct ?? 0) >= 80 ? 'nm-bar-fill nm-bar-warn' : 'nm-bar-fill nm-bar-sky'}
style={{ width: `${Math.max(1, Math.min(100, fdPct ?? 0))}%` }}
/>
</div>
</div>
)}
{host.notes && (
<div className="nm-meta-item">
<span className="nm-meta-label">{t('metaNotes')}</span>
<span className="nm-panel-card-sub">{host.notes}</span>
</div>
)}
</section>
)}
{show('gpuThermals') &&
((stats?.gpus && stats.gpus.length > 0) || (stats?.thermals && stats.thermals.length > 0)) && (
<section className="nm-panel-card">
<h3 className="nm-panel-card-title">
{stats?.gpus.length ? t('metricGpu') : t('metricThermals')}
</h3>
{stats?.gpus.map((gpu) => {
const vramPct = formatMemoryPercent(gpu.memoryUsed, gpu.memoryTotal);
return (
<div key={gpu.index} className="nm-gpu-card">
<div className="nm-disk-head">
<span className="nm-disk-mount">
GPU {gpu.index} · {gpu.name}
</span>
<span className="nm-mono">{formatPercent(gpu.utilization, 0)}</span>
</div>
<div className="nm-bar-track">
<div
className="nm-bar-fill nm-bar-violet"
style={{ width: `${Math.max(0, Math.min(100, gpu.utilization ?? 0))}%` }}
/>
</div>
<div className="nm-disk-meta nm-mono">
<span>
{t('gpuVram')}: {formatMemoryMiB(gpu.memoryUsed)} / {formatMemoryMiB(gpu.memoryTotal)} ({formatPercent(vramPct, 0)})
</span>
{gpu.temperatureC != null && (
<span>
{t('gpuTemp')}: {gpu.temperatureC}°C
</span>
)}
{gpu.powerWatts != null && (
<span>
{t('gpuPower')}: {gpu.powerWatts.toFixed(1)}W
</span>
)}
</div>
</div>
);
})}
{stats?.thermals && stats.thermals.length > 0 && (
<div>
<div className="nm-meta-label" style={{ marginBottom: 6 }}>
{t('metricThermals')}
</div>
<div className="nm-thermal-grid">
{stats.thermals.map((sensor) => (
<span key={sensor.id} className="nm-thermal-chip nm-mono">
<span>{sensor.label}</span>
<strong
style={{
color:
sensor.temperatureC >= 85
? 'var(--plugin-crit)'
: sensor.temperatureC >= 70
? 'var(--plugin-warn)'
: 'var(--plugin-ok)',
}}
>
{sensor.temperatureC.toFixed(1)}°C
</strong>
</span>
))}
</div>
</div>
)}
</section>
)}
</div>
</div>
</div>
);
}
@@ -1,216 +0,0 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { PluginDataGrid, type PluginDataGridColumn } from '@netcatty/plugin-sdk/host-react';
import { formatCompactCount } from '../../domain/formatting';
import type { I18nKey } from '../../domain/i18n';
import type { MonitorHostRef, PortRow, SocketSummary, SystemAuditSnapshot } from '../../domain/types';
import type { MonitorHostBridge } from '../../services/hostBridge';
import type { MonitorEngine } from '../../services/monitorEngine';
export interface PortsTabProps {
host: MonitorHostRef;
engine: MonitorEngine;
bridge: MonitorHostBridge;
t: (key: I18nKey) => string;
}
export default function PortsTab({ host, engine, bridge, t }: PortsTabProps) {
const [ports, setPorts] = useState<PortRow[]>([]);
const [summary, setSummary] = useState<SocketSummary>({
total: 0,
established: 0,
listen: 0,
synRecv: 0,
timeWait: 0,
closeWait: 0,
other: 0,
});
const [audit, setAudit] = useState<SystemAuditSnapshot | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState('');
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const [portsData, auditData] = await Promise.all([
engine.fetchPorts(host),
engine.fetchSystemAudit(host).catch(() => null),
]);
setPorts(portsData.ports);
setSummary(portsData.summary);
setAudit(auditData);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
}, [engine, host]);
useEffect(() => {
void load();
}, [load]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return ports;
return ports.filter(
(p) =>
p.protocol.includes(q) ||
p.localAddress.toLowerCase().includes(q) ||
String(p.port ?? '').includes(q) ||
p.process.toLowerCase().includes(q),
);
}, [ports, query]);
const columns = useMemo<PluginDataGridColumn[]>(
() => [
{ name: 'protocol', type: 'text', width: 84, sortable: true },
{ name: 'state', type: 'text', width: 96, sortable: true },
{ name: 'port', type: 'number', width: 88, sortable: true },
{ name: 'localAddress', type: 'text', width: 200 },
{ name: 'peerAddress', type: 'text', width: 160 },
{ name: 'process', type: 'text', width: 170, sortable: true },
{ name: 'pid', type: 'number', width: 84, sortable: true },
],
[],
);
const handleCopyDiag = () => {
const lines = [
`Host: ${host.label} (${host.hostname ?? ''})`,
`Sockets: total=${summary.total} listen=${summary.listen} established=${summary.established} syn_recv=${summary.synRecv} time_wait=${summary.timeWait} close_wait=${summary.closeWait}`,
...(audit?.fdUsed != null && audit?.fdMax != null ? [`Open FDs: ${audit.fdUsed} / ${audit.fdMax}`] : []),
...(audit?.failedAuthCount != null ? [`Failed SSH Auth (24h): ${audit.failedAuthCount}`] : []),
`Listening Ports (${ports.length}):`,
...ports.slice(0, 30).map((p) => ` ${p.protocol} ${p.localAddress}:${p.port ?? '*'} ${p.process || ''}`),
];
void bridge.copyText(lines.join('\n'), `Copy Network & Audit Diagnostics (${host.label})`);
};
return (
<div className="nm-content-flush">
<div className="nm-kpi-strip" style={{ padding: '0 0 10px', borderBottom: 'none' }}>
<div className="nm-kpi-card">
<span className="nm-kpi-label">{t('socketsTotal')}</span>
<span className="nm-kpi-value nm-mono">{summary.total}</span>
</div>
<div className="nm-kpi-card">
<span className="nm-kpi-label">{t('socketsListen')}</span>
<span className="nm-kpi-value nm-mono" style={{ color: 'var(--plugin-ok)' }}>
{summary.listen}
</span>
</div>
<div className="nm-kpi-card">
<span className="nm-kpi-label">{t('socketsEstablished')}</span>
<span className="nm-kpi-value nm-mono" style={{ color: 'var(--plugin-sky)' }}>
{summary.established}
</span>
</div>
<div className="nm-kpi-card">
<span className="nm-kpi-label">{t('socketsSynRecv')}</span>
<span className="nm-kpi-value nm-mono" style={{ color: summary.synRecv > 50 ? 'var(--plugin-warn)' : undefined }}>
{summary.synRecv}
</span>
</div>
<div className="nm-kpi-card">
<span className="nm-kpi-label">{t('socketsTimeWait')}</span>
<span className="nm-kpi-value nm-mono">{summary.timeWait}</span>
</div>
<div className="nm-kpi-card">
<span className="nm-kpi-label">{t('socketsCloseWait')}</span>
<span className="nm-kpi-value nm-mono" style={{ color: summary.closeWait > 0 ? 'var(--plugin-warn)' : undefined }}>
{summary.closeWait}
</span>
</div>
</div>
<div className="nm-toolbar" style={{ padding: '0 0 8px', borderBottom: 'none' }}>
<input
type="search"
className="nm-input nm-search"
placeholder={t('searchPorts')}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<div className="nm-toolbar-group">
<button type="button" className="nm-btn" onClick={handleCopyDiag}>
{t('copyDiagnostics')}
</button>
<button type="button" className="nm-btn" onClick={() => void load()} disabled={loading}>
{t('refreshNow')}
</button>
</div>
</div>
{error && (
<div className="nm-inline-banner" style={{ borderColor: 'var(--plugin-crit)' }}>
<span>{error}</span>
</div>
)}
<div className="nm-grid-wrap">
<PluginDataGrid
columns={columns}
rows={filtered.map((p) => ({
protocol: p.protocol,
state: p.state,
port: p.port ?? '--',
localAddress: p.localAddress,
peerAddress: p.peerAddress,
process: p.process || '--',
pid: p.pid ?? '--',
}))}
loading={loading && ports.length === 0}
emptyMessage={t('loadingData')}
/>
</div>
{/* System & Security Audit Panel */}
{audit && (
<div className="nm-audit-grid">
<section className="nm-panel-card">
<div className="nm-panel-card-head">
<h3 className="nm-panel-card-title">{t('auditTitle')}</h3>
{audit.rebootRequired && <span className="nm-badge nm-badge-warn">{t('rebootPending')}</span>}
</div>
<div className="nm-micro-grid nm-mono">
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('openFds')}</span>
<span className="nm-micro-val">
{audit.fdUsed != null && audit.fdMax != null
? `${formatCompactCount(audit.fdUsed)} / ${formatCompactCount(audit.fdMax)}`
: '--'}
</span>
</div>
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('activeUsersLabel')}</span>
<span className="nm-micro-val">{audit.loggedInUsers.length}</span>
</div>
<div className="nm-micro-pill">
<span className="nm-micro-label">{t('failedAuth24h')}</span>
<span
className="nm-micro-val"
style={{ color: (audit.failedAuthCount ?? 0) >= 20 ? 'var(--plugin-warn)' : undefined }}
>
{audit.failedAuthCount ?? '--'}
</span>
</div>
</div>
</section>
<section className="nm-panel-card">
<h3 className="nm-panel-card-title">{t('recentLogins')}</h3>
<ul className="nm-audit-list nm-mono">
{audit.recentLogins.length === 0 ? (
<li>--</li>
) : (
audit.recentLogins.map((line, i) => <li key={i}>{line}</li>)
)}
</ul>
</section>
</div>
)}
</div>
);
}
@@ -1,288 +0,0 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { PluginDataGrid, type PluginDataGridColumn, type PluginDataGridSort } from '@netcatty/plugin-sdk/host-react';
import type { SafeProcessSignal } from '../../domain/collectors';
import { formatRssKb } from '../../domain/formatting';
import type { I18nKey } from '../../domain/i18n';
import type { MonitorHostRef, ProcessRow } from '../../domain/types';
import type { MonitorHostBridge } from '../../services/hostBridge';
import type { MonitorEngine } from '../../services/monitorEngine';
export interface ProcessesTabProps {
host: MonitorHostRef;
engine: MonitorEngine;
bridge: MonitorHostBridge;
t: (key: I18nKey) => string;
}
type ProcStateFilter = 'all' | 'running' | 'sleeping' | 'zombie';
function matchesProcState(state: string, filter: ProcStateFilter): boolean {
if (filter === 'all') return true;
const ch = state.charAt(0).toUpperCase();
if (filter === 'running') return ch === 'R';
if (filter === 'sleeping') return ch === 'S' || ch === 'D' || ch === 'I';
if (filter === 'zombie') return ch === 'Z';
return true;
}
export default function ProcessesTab({ host, engine, bridge, t }: ProcessesTabProps) {
const [rows, setRows] = useState<ProcessRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [stateFilter, setStateFilter] = useState<ProcStateFilter>('all');
const [sort, setSort] = useState<PluginDataGridSort | null>({ column: 'cpu', direction: 'desc' });
const [selectedIdx, setSelectedIdx] = useState<number | null>(null);
const [pendingSignal, setPendingSignal] = useState<{ proc: ProcessRow; signal: SafeProcessSignal } | null>(null);
const [signalBusy, setSignalBusy] = useState(false);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const next = await engine.fetchProcesses(host);
setRows(next);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
}, [engine, host]);
useEffect(() => {
void load();
const timer = setInterval(() => {
void load();
}, 6_000);
return () => clearInterval(timer);
}, [load]);
const topCpu = useMemo(() => [...rows].sort((a, b) => b.cpuPercent - a.cpuPercent).slice(0, 5), [rows]);
const topMem = useMemo(() => [...rows].sort((a, b) => b.memPercent - a.memPercent).slice(0, 5), [rows]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
const list = rows.filter((r) => {
if (!matchesProcState(r.state, stateFilter)) return false;
if (!q) return true;
return (
String(r.pid).includes(q) ||
r.user.toLowerCase().includes(q) ||
r.command.toLowerCase().includes(q)
);
});
if (sort) {
const dir = sort.direction === 'asc' ? 1 : -1;
list.sort((a, b) => {
switch (sort.column) {
case 'pid': return (a.pid - b.pid) * dir;
case 'user': return a.user.localeCompare(b.user) * dir;
case 'cpu': return (a.cpuPercent - b.cpuPercent) * dir;
case 'mem': return (a.memPercent - b.memPercent) * dir;
case 'rss': return (a.rssKb - b.rssKb) * dir;
case 'state': return a.state.localeCompare(b.state) * dir;
default: return a.command.localeCompare(b.command) * dir;
}
});
}
return list;
}, [rows, query, stateFilter, sort]);
const columns = useMemo<PluginDataGridColumn[]>(
() => [
{ name: 'pid', type: 'number', width: 78, sortable: true },
{ name: 'user', type: 'text', width: 105, sortable: true },
{ name: 'cpu', type: 'number', width: 78, sortable: true },
{ name: 'mem', type: 'number', width: 78, sortable: true },
{ name: 'rss', type: 'text', width: 92, sortable: true },
{ name: 'state', type: 'text', width: 68, sortable: true },
{ name: 'elapsed', type: 'text', width: 96 },
{ name: 'command', type: 'text', width: 420, sortable: true },
],
[],
);
const gridRows = useMemo(
() =>
filtered.map((p) => ({
pid: p.pid,
user: p.user,
cpu: `${p.cpuPercent.toFixed(1)}%`,
mem: `${p.memPercent.toFixed(1)}%`,
rss: formatRssKb(p.rssKb),
state: p.state,
elapsed: p.elapsed,
command: p.command,
})),
[filtered],
);
const selectedProc = selectedIdx != null ? filtered[selectedIdx] ?? null : null;
const confirmSignal = async () => {
if (!pendingSignal) return;
setSignalBusy(true);
try {
await engine.sendProcessSignal(host, pendingSignal.proc.pid, pendingSignal.signal);
setPendingSignal(null);
await load();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
setPendingSignal(null);
} finally {
setSignalBusy(false);
}
};
return (
<div className="nm-content-flush">
{/* Top-5 CPU & Memory Quick Summary Strip */}
{rows.length > 0 && (
<div className="nm-top-strip">
<div className="nm-top-box">
<div className="nm-micro-label">{t('procTopCpu')}</div>
{topCpu.map((p) => (
<div key={`cpu-${p.pid}`} className="nm-top-row nm-mono">
<span className="nm-top-cmd">
{p.pid} · {p.command}
</span>
<strong>{p.cpuPercent.toFixed(1)}%</strong>
</div>
))}
</div>
<div className="nm-top-box">
<div className="nm-micro-label">{t('procTopMem')}</div>
{topMem.map((p) => (
<div key={`mem-${p.pid}`} className="nm-top-row nm-mono">
<span className="nm-top-cmd">
{p.pid} · {p.command}
</span>
<strong>
{p.memPercent.toFixed(1)}% ({formatRssKb(p.rssKb)})
</strong>
</div>
))}
</div>
</div>
)}
<div className="nm-toolbar" style={{ padding: '0 0 8px', borderBottom: 'none' }}>
<div className="nm-toolbar-group">
<input
type="search"
className="nm-input nm-search"
placeholder={t('searchProcesses')}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<div className="nm-segmented">
{(['all', 'running', 'sleeping', 'zombie'] as const).map((st) => (
<button
key={st}
type="button"
className={`nm-seg-btn ${stateFilter === st ? 'nm-seg-btn-active' : ''}`}
onClick={() => setStateFilter(st)}
>
{t(
st === 'all'
? 'procStateAll'
: st === 'running'
? 'procStateRunning'
: st === 'sleeping'
? 'procStateSleeping'
: 'procStateZombie',
)}
</button>
))}
</div>
<span className="nm-badge nm-mono">{filtered.length}</span>
</div>
<button type="button" className="nm-btn" onClick={() => void load()} disabled={loading}>
{t('refreshNow')}
</button>
</div>
{error && (
<div className="nm-inline-banner" style={{ borderColor: 'var(--plugin-crit)' }}>
<span>{error}</span>
</div>
)}
{selectedProc && (
<div className="nm-action-bar">
<span className="nm-mono" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '52%' }}>
PID {selectedProc.pid} ({selectedProc.user}) — {selectedProc.command}
</span>
<div className="nm-toolbar-group">
<button
type="button"
className="nm-btn nm-btn-sm"
onClick={() => void bridge.copyText(selectedProc.command, 'Copy Process Command')}
>
{t('copyCommand')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm"
disabled={selectedProc.pid <= 1}
onClick={() => setPendingSignal({ proc: selectedProc, signal: 'SIGHUP' })}
>
SIGHUP
</button>
<button
type="button"
className="nm-btn nm-btn-sm"
disabled={selectedProc.pid <= 1}
onClick={() => setPendingSignal({ proc: selectedProc, signal: 'SIGTERM' })}
>
{t('processKillTerm')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm nm-btn-danger"
disabled={selectedProc.pid <= 1}
onClick={() => setPendingSignal({ proc: selectedProc, signal: 'SIGKILL' })}
>
{t('processKillForce')}
</button>
</div>
</div>
)}
<div className="nm-grid-wrap">
<PluginDataGrid
columns={columns}
rows={gridRows}
sort={sort}
loading={loading && rows.length === 0}
onSortChange={setSort}
onCellSelect={({ rowIndex }) => setSelectedIdx(rowIndex)}
emptyMessage={t('loadingData')}
/>
</div>
{pendingSignal && (
<div className="nm-modal-backdrop">
<div className="nm-modal-card">
<h3 className="nm-panel-card-title">{t('processConfirmTitle')}</h3>
<p className="nm-panel-card-sub">
{t('processConfirmBody')} <strong className="nm-mono">{pendingSignal.proc.pid}</strong> ({pendingSignal.signal})?
</p>
<pre className="nm-log-pre nm-mono" style={{ maxHeight: 90 }}>
{pendingSignal.proc.command}
</pre>
<div className="nm-modal-actions">
<button type="button" className="nm-btn" onClick={() => setPendingSignal(null)} disabled={signalBusy}>
{t('processCancel')}
</button>
<button type="button" className="nm-btn nm-btn-danger" onClick={() => void confirmSignal()} disabled={signalBusy}>
{t('processSendSignal')} ({pendingSignal.signal})
</button>
</div>
</div>
</div>
)}
</div>
);
}
@@ -1,433 +0,0 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { PluginDataGrid, type PluginDataGridColumn } from '@netcatty/plugin-sdk/host-react';
import type { SafeContainerAction, SafeServiceAction } from '../../domain/collectors';
import type { I18nKey } from '../../domain/i18n';
import type { ContainerRow, MonitorHostRef, SystemdServiceRow } from '../../domain/types';
import type { MonitorHostBridge } from '../../services/hostBridge';
import type { MonitorEngine } from '../../services/monitorEngine';
export interface ServicesTabProps {
host: MonitorHostRef;
engine: MonitorEngine;
bridge: MonitorHostBridge;
t: (key: I18nKey) => string;
}
type PendingOp =
| { kind: 'service'; unit: string; action: SafeServiceAction }
| { kind: 'container'; runtime: 'docker' | 'podman'; id: string; name: string; action: SafeContainerAction };
export default function ServicesTab({ host, engine, bridge, t }: ServicesTabProps) {
const [services, setServices] = useState<SystemdServiceRow[]>([]);
const [containers, setContainers] = useState<ContainerRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [subMode, setSubMode] = useState<'services' | 'containers'>('services');
const [stateFilter, setStateFilter] = useState<'all' | 'active' | 'failed'>('all');
const [query, setQuery] = useState('');
const [selectedIdx, setSelectedIdx] = useState<number | null>(null);
const [logTitle, setLogTitle] = useState<string | null>(null);
const [logText, setLogText] = useState('');
const [logLoading, setLogLoading] = useState(false);
const [pendingOp, setPendingOp] = useState<PendingOp | null>(null);
const [opBusy, setOpBusy] = useState(false);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data = await engine.fetchServicesAndContainers(host);
setServices(data.services);
setContainers(data.containers);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
}, [engine, host]);
useEffect(() => {
void load();
}, [load]);
const filteredServices = useMemo(() => {
const q = query.trim().toLowerCase();
return services.filter((s) => {
if (stateFilter === 'active' && s.activeState !== 'active') return false;
if (stateFilter === 'failed' && s.activeState !== 'failed') return false;
if (!q) return true;
return s.unit.toLowerCase().includes(q) || s.description.toLowerCase().includes(q);
});
}, [services, stateFilter, query]);
const filteredContainers = useMemo(() => {
const q = query.trim().toLowerCase();
return containers.filter((c) => {
if (stateFilter === 'active' && c.state !== 'running') return false;
if (stateFilter === 'failed' && c.state === 'running') return false;
if (!q) return true;
return (
c.name.toLowerCase().includes(q) ||
c.image.toLowerCase().includes(q) ||
c.id.toLowerCase().includes(q)
);
});
}, [containers, stateFilter, query]);
const serviceColumns = useMemo<PluginDataGridColumn[]>(
() => [
{ name: 'unit', type: 'text', width: 230, sortable: true },
{ name: 'active', type: 'text', width: 95, sortable: true },
{ name: 'sub', type: 'text', width: 95 },
{ name: 'load', type: 'text', width: 88 },
{ name: 'description', type: 'text', width: 340 },
],
[],
);
const containerColumns = useMemo<PluginDataGridColumn[]>(
() => [
{ name: 'runtime', type: 'text', width: 82 },
{ name: 'name', type: 'text', width: 175, sortable: true },
{ name: 'state', type: 'text', width: 95, sortable: true },
{ name: 'status', type: 'text', width: 165 },
{ name: 'image', type: 'text', width: 220 },
{ name: 'ports', type: 'text', width: 180 },
],
[],
);
const openLogs = async (
target: { kind: 'service'; unit: string } | { kind: 'container'; runtime: 'docker' | 'podman'; id: string; name: string },
) => {
setLogLoading(true);
setLogTitle(target.kind === 'service' ? target.unit : `${target.runtime}:${target.name}`);
setLogText(t('logsLoading'));
try {
const out =
target.kind === 'service'
? await engine.fetchServiceLogs(host, target.unit, 120)
: await engine.fetchContainerLogs(host, target.runtime, target.id, 120);
setLogText(out);
} catch (err) {
setLogText(err instanceof Error ? err.message : String(err));
} finally {
setLogLoading(false);
}
};
const executeOp = async (op: PendingOp) => {
setOpBusy(true);
setError(null);
setNotice(null);
try {
const msg =
op.kind === 'service'
? await engine.runServiceAction(host, op.unit, op.action)
: await engine.runContainerAction(host, op.runtime, op.id, op.action);
setNotice(msg);
setPendingOp(null);
await load();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
setPendingOp(null);
} finally {
setOpBusy(false);
}
};
const requestOp = async (op: PendingOp) => {
const targetLabel = op.kind === 'service' ? op.unit : `${op.runtime}:${op.name}`;
const hostConfirmed = await bridge.confirmAction({
title: t('confirmOpTitle'),
message: `${op.action.toUpperCase()} ${targetLabel} on ${host.label}?`,
confirmLabel: op.action.toUpperCase(),
destructive: op.action === 'stop',
});
if (hostConfirmed === true) {
await executeOp(op);
} else if (hostConfirmed === null) {
// Fallback to inline modal when host ui.confirm is not available
setPendingOp(op);
}
};
const selectedService = subMode === 'services' && selectedIdx != null ? filteredServices[selectedIdx] ?? null : null;
const selectedContainer = subMode === 'containers' && selectedIdx != null ? filteredContainers[selectedIdx] ?? null : null;
return (
<div className="nm-content-flush">
<div className="nm-toolbar" style={{ padding: '0 0 8px', borderBottom: 'none' }}>
<div className="nm-toolbar-group">
<div className="nm-segmented">
<button
type="button"
className={`nm-seg-btn ${subMode === 'services' ? 'nm-seg-btn-active' : ''}`}
onClick={() => {
setSubMode('services');
setSelectedIdx(null);
}}
>
{t('servicesTitle')} ({services.length})
</button>
<button
type="button"
className={`nm-seg-btn ${subMode === 'containers' ? 'nm-seg-btn-active' : ''}`}
onClick={() => {
setSubMode('containers');
setSelectedIdx(null);
}}
>
{t('containersTitle')} ({containers.length})
</button>
</div>
<input
type="search"
className="nm-input nm-search"
placeholder={t('searchServices')}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<select
className="nm-select"
value={stateFilter}
onChange={(e) => setStateFilter(e.target.value as 'all' | 'active' | 'failed')}
>
<option value="all">{t('allStates')}</option>
<option value="active">{t('activeOnly')}</option>
<option value="failed">{t('failedOnly')}</option>
</select>
</div>
<button type="button" className="nm-btn" onClick={() => void load()} disabled={loading}>
{t('refreshNow')}
</button>
</div>
{error && (
<div className="nm-inline-banner" style={{ borderColor: 'var(--plugin-crit)' }}>
<span>{error}</span>
</div>
)}
{notice && (
<div className="nm-inline-banner" style={{ borderColor: 'var(--plugin-ok)' }}>
<span className="nm-mono">{notice}</span>
</div>
)}
{selectedService && (
<div className="nm-action-bar">
<span className="nm-mono">
<strong>{selectedService.unit}</strong> · {selectedService.activeState}/{selectedService.subState}
</span>
<div className="nm-toolbar-group">
<button
type="button"
className="nm-btn nm-btn-sm"
disabled={opBusy}
onClick={() => void requestOp({ kind: 'service', unit: selectedService.unit, action: 'start' })}
>
{t('actionStart')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm"
disabled={opBusy}
onClick={() => void requestOp({ kind: 'service', unit: selectedService.unit, action: 'restart' })}
>
{t('actionRestart')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm"
disabled={opBusy}
onClick={() => void requestOp({ kind: 'service', unit: selectedService.unit, action: 'reload' })}
>
{t('actionReload')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm nm-btn-danger"
disabled={opBusy}
onClick={() => void requestOp({ kind: 'service', unit: selectedService.unit, action: 'stop' })}
>
{t('actionStop')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm nm-btn-primary"
onClick={() => void openLogs({ kind: 'service', unit: selectedService.unit })}
>
{t('viewLogs')} (journalctl)
</button>
</div>
</div>
)}
{selectedContainer && (
<div className="nm-action-bar">
<span className="nm-mono">
<strong>{selectedContainer.name}</strong> ({selectedContainer.id}) · {selectedContainer.state}
</span>
<div className="nm-toolbar-group">
<button
type="button"
className="nm-btn nm-btn-sm"
disabled={opBusy}
onClick={() =>
void requestOp({
kind: 'container',
runtime: selectedContainer.runtime,
id: selectedContainer.id,
name: selectedContainer.name,
action: 'start',
})
}
>
{t('actionStart')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm"
disabled={opBusy}
onClick={() =>
void requestOp({
kind: 'container',
runtime: selectedContainer.runtime,
id: selectedContainer.id,
name: selectedContainer.name,
action: 'restart',
})
}
>
{t('actionRestart')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm nm-btn-danger"
disabled={opBusy}
onClick={() =>
void requestOp({
kind: 'container',
runtime: selectedContainer.runtime,
id: selectedContainer.id,
name: selectedContainer.name,
action: 'stop',
})
}
>
{t('actionStop')}
</button>
<button
type="button"
className="nm-btn nm-btn-sm nm-btn-primary"
onClick={() =>
void openLogs({
kind: 'container',
runtime: selectedContainer.runtime,
id: selectedContainer.id,
name: selectedContainer.name,
})
}
>
{t('viewLogs')} ({selectedContainer.runtime} logs)
</button>
</div>
</div>
)}
<div className="nm-grid-wrap">
{subMode === 'services' ? (
<PluginDataGrid
columns={serviceColumns}
rows={filteredServices.map((s) => ({
unit: s.unit,
active: s.activeState,
sub: s.subState,
load: s.loadState,
description: s.description,
}))}
loading={loading && services.length === 0}
onCellSelect={({ rowIndex }) => setSelectedIdx(rowIndex)}
onCellDoubleClick={({ rowIndex }) => {
const svc = filteredServices[rowIndex];
if (svc) void openLogs({ kind: 'service', unit: svc.unit });
}}
emptyMessage={t('noServices')}
/>
) : (
<PluginDataGrid
columns={containerColumns}
rows={filteredContainers.map((c) => ({
runtime: c.runtime,
name: c.name,
state: c.state,
status: c.status,
image: c.image,
ports: c.ports || '--',
}))}
loading={loading && containers.length === 0}
onCellSelect={({ rowIndex }) => setSelectedIdx(rowIndex)}
onCellDoubleClick={({ rowIndex }) => {
const ctr = filteredContainers[rowIndex];
if (ctr) {
void openLogs({ kind: 'container', runtime: ctr.runtime, id: ctr.id, name: ctr.name });
}
}}
emptyMessage={t('noContainers')}
/>
)}
</div>
{logTitle && (
<div className="nm-log-panel">
<div className="nm-log-head">
<span className="nm-mono">{logTitle}</span>
<div className="nm-toolbar-group">
<button
type="button"
className="nm-btn nm-btn-sm"
disabled={logLoading}
onClick={() => void bridge.copyText(logText, `Copy Logs (${logTitle})`)}
>
{t('copyCommand')}
</button>
<button type="button" className="nm-btn nm-btn-sm" onClick={() => setLogTitle(null)}>
{t('closeLogs')}
</button>
</div>
</div>
<pre className="nm-log-pre nm-mono">{logText}</pre>
</div>
)}
{pendingOp && (
<div className="nm-modal-backdrop">
<div className="nm-modal-card">
<h3 className="nm-panel-card-title">{t('confirmOpTitle')}</h3>
<p className="nm-panel-card-sub">
<strong className="nm-mono">{pendingOp.action.toUpperCase()}</strong>{' '}
<span className="nm-mono">
{pendingOp.kind === 'service' ? pendingOp.unit : `${pendingOp.runtime}:${pendingOp.name}`}
</span>{' '}
({host.label})?
</p>
<div className="nm-modal-actions">
<button type="button" className="nm-btn" onClick={() => setPendingOp(null)} disabled={opBusy}>
{t('cancel')}
</button>
<button
type="button"
className={`nm-btn ${pendingOp.action === 'stop' ? 'nm-btn-danger' : 'nm-btn-primary'}`}
onClick={() => void executeOp(pendingOp)}
disabled={opBusy}
>
{pendingOp.action.toUpperCase()}
</button>
</div>
</div>
</div>
)}
</div>
);
}
@@ -1,222 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
applyAlertHysteresis,
computeAlertBadge,
DEFAULT_ALERT_THRESHOLDS,
evaluateHostHealth,
mergeAlertFeed,
} from '../src/domain/alerts.js';
import {
normalizeMonitorPanels,
normalizeVisibleWidgets,
rebaseMonitorPanel,
reorderMonitorHosts,
} from '../src/domain/panels.js';
import type { HostRuntimeState } from '../src/domain/types.js';
function makeLiveState(overrides: Partial<NonNullable<HostRuntimeState['stats']>> = {}): HostRuntimeState {
return {
hostId: 'hb_1',
status: 'live',
updatedAt: 1000,
points: [],
stats: {
osFamily: 'linux',
cpu: 25,
cpuCores: 4,
cpuPerCore: [25, 25, 25, 25],
gpu: null,
gpuName: null,
gpuMemUsed: null,
gpuMemTotal: null,
gpus: [],
thermals: [],
memTotal: 16384,
memUsed: 4096,
memFree: 8192,
memBuffers: 1024,
memCached: 3072,
swapTotal: 2048,
swapUsed: 0,
topProcesses: [],
diskPercent: 42,
diskUsed: 42,
diskTotal: 100,
disks: [{ mountPoint: '/', percent: 42, used: 42, total: 100 }],
diskReadSpeed: null,
diskWriteSpeed: null,
networkReady: true,
netRxSpeed: 1000,
netTxSpeed: 500,
latencyMs: 25,
responseLatencyMs: 30,
netInterfaces: [],
hostname: 'web-01',
osName: 'Ubuntu 24.04',
kernelRelease: '6.8.0',
uptimeSeconds: 7200,
loadAverage: [0.5, 0.4, 0.3],
...overrides,
},
};
}
test('evaluateHostHealth computes health score and violations across metrics', () => {
const healthy = evaluateHostHealth(makeLiveState(), DEFAULT_ALERT_THRESHOLDS);
assert.equal(healthy.health.level, 'healthy');
assert.equal(healthy.health.score, 100);
assert.equal(healthy.violations.length, 0);
const degraded = evaluateHostHealth(
makeLiveState({ cpu: 97, memUsed: 14500, latencyMs: 250 }),
DEFAULT_ALERT_THRESHOLDS,
);
assert.equal(degraded.health.level, 'critical');
assert.ok(degraded.health.score < 60);
assert.equal(degraded.violations.some((v) => v.metric === 'cpu' && v.severity === 'critical'), true);
assert.equal(degraded.violations.some((v) => v.metric === 'memory' && v.severity === 'warning'), true);
assert.equal(degraded.violations.some((v) => v.metric === 'latencyMs' && v.severity === 'warning'), true);
});
test('mergeAlertFeed deduplicates active alerts and auto-resolves cleared metrics', () => {
const { violations } = evaluateHostHealth(makeLiveState({ cpu: 96 }), DEFAULT_ALERT_THRESHOLDS);
let feed = mergeAlertFeed([], 'hb_1', 'web-01', violations, 10_000);
assert.equal(feed.length, 1);
assert.equal(feed[0].resolvedAt, null);
// Repeating violation updates in-place instead of duplicating
feed = mergeAlertFeed(feed, 'hb_1', 'web-01', violations, 15_000);
assert.equal(feed.length, 1);
assert.equal(feed[0].at, 15_000);
// Clearing violation marks alert resolved
feed = mergeAlertFeed(feed, 'hb_1', 'web-01', [], 20_000);
assert.equal(feed[0].resolvedAt, 20_000);
});
test('computeAlertBadge tracks warning/critical tones, ack/resolve clearing, clamping, and EN/zh-CN tooltips', () => {
assert.equal(computeAlertBadge([]), null);
const warnAlert = {
id: 'a1',
hostId: 'hb_1',
hostLabel: 'web-01',
metric: 'cpu' as const,
severity: 'warning' as const,
value: 84,
threshold: 80,
message: 'web-01: CPU 84%\nline2',
at: 1000,
acknowledged: false,
resolvedAt: null,
};
const warnBadge = computeAlertBadge([warnAlert], 'en');
assert.deepEqual(warnBadge, {
count: 1,
tone: 'warning',
tooltip: '1 active alert: web-01: CPU 84% line2',
});
const critAlert = {
...warnAlert,
id: 'a2',
metric: 'memory' as const,
severity: 'critical' as const,
message: 'web-01: MEM 97%',
};
const critBadgeEn = computeAlertBadge([critAlert, warnAlert], 'en');
assert.equal(critBadgeEn?.count, 2);
assert.equal(critBadgeEn?.tone, 'danger');
assert.match(critBadgeEn?.tooltip ?? '', /2 active alerts \(1 critical\)/);
const critBadgeZh = computeAlertBadge([critAlert, warnAlert], 'zh-CN');
assert.equal(critBadgeZh?.count, 2);
assert.equal(critBadgeZh?.tone, 'danger');
assert.match(critBadgeZh?.tooltip ?? '', /2 条告警(1 条严重)/);
// Acknowledged or resolved alerts do not contribute to the sidebar badge
assert.equal(
computeAlertBadge([
{ ...warnAlert, acknowledged: true },
{ ...critAlert, resolvedAt: 2000 },
]),
null,
);
});
test('panel normalization, dedupe, reorder, and rebase preserve Netcatty parity', () => {
const normalized = normalizeMonitorPanels([
{ id: 'b', name: 'Production', hostIds: ['h1', 'h1', 'h2'], interval: 5, range: 15, view: 'charts' },
{ id: 'a', name: 'Production', hostIds: ['h3'], interval: 99, range: 999 },
]);
assert.equal(normalized.length, 2);
assert.equal(normalized[0].name, 'Production (2)');
assert.deepEqual(normalized[0].hostIds, ['h1', 'h2']);
assert.equal(normalized[1].name, 'Production');
assert.equal(normalized[1].interval, 5);
assert.equal(normalized[1].range, 30);
assert.deepEqual(reorderMonitorHosts(['h1', 'h2', 'h3'], 'h3', 'h1'), ['h3', 'h1', 'h2']);
const updated = rebaseMonitorPanel(normalized, normalized[0], {
...normalized[0],
description: 'Updated',
});
assert.equal(updated[0].description, 'Updated');
// Commercial view modes (wallboard, compare) and 1m/60m ranges
const commercial = normalizeMonitorPanels([
{ id: 'noc', name: 'NOC', hostIds: ['h1', 'h2'], view: 'wallboard', interval: 2, range: 60 },
{ id: 'cmp', name: 'Compare', hostIds: ['h1', 'h2'], compareHostIds: ['h1', 'h2'], view: 'compare', interval: 1, range: 1 },
]);
assert.equal(commercial[0].view, 'wallboard');
assert.equal(commercial[0].range, 60);
assert.equal(commercial[1].view, 'compare');
assert.equal(commercial[1].range, 1);
assert.deepEqual(commercial[1].compareHostIds, ['h1', 'h2']);
assert.deepEqual(normalizeVisibleWidgets(['cpuBreakdown', 'invalid' as never, 'cpuBreakdown', 'gpuThermals']), [
'cpuBreakdown',
'gpuThermals',
]);
});
test('commercial alert rules (iowait, inode, netDrops) and hysteresis filter transient spikes', () => {
const { violations } = evaluateHostHealth(
makeLiveState({
cpuIowait: 42,
disks: [{ mountPoint: '/', percent: 42, used: 42, total: 100, inodePercent: 96 }],
netDropsDelta: 16,
}),
DEFAULT_ALERT_THRESHOLDS,
);
assert.equal(violations.some((v) => v.metric === 'cpuIowait' && v.severity === 'critical'), true);
assert.equal(violations.some((v) => v.metric === 'inode' && v.severity === 'critical'), true);
assert.equal(violations.some((v) => v.metric === 'netDrops' && v.severity === 'warning'), true);
const streaks = new Map<string, number>();
// Poll 1: suppressed when consecutivePolls = 2
const firstPass = applyAlertHysteresis(streaks, 'hb_1', violations, 2, { immediateMetrics: new Set(['offline']) });
assert.equal(firstPass.length, 0);
// Poll 2: consecutive breach passes hysteresis
const secondPass = applyAlertHysteresis(streaks, 'hb_1', violations, 2, { immediateMetrics: new Set(['offline']) });
assert.equal(secondPass.length, violations.length);
// Immediate metric (offline) bypasses hysteresis on poll 1
const offlinePass = applyAlertHysteresis(
streaks,
'hb_2',
[{ metric: 'offline', severity: 'critical', value: null, threshold: null, label: 'Host unreachable' }],
3,
{ immediateMetrics: new Set(['offline']) },
);
assert.equal(offlinePass.length, 1);
// Healthy poll resets streaks
const recovered = applyAlertHysteresis(streaks, 'hb_1', [], 2);
assert.equal(recovered.length, 0);
const spikeAgain = applyAlertHysteresis(streaks, 'hb_1', violations, 2);
assert.equal(spikeAgain.length, 0);
});
@@ -1,149 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
buildMonitorDiskListLayout,
diskIoRates,
isMonitorSystemDisk,
parseDiskIo,
sortMonitorDisks,
withPartitionIo,
} from '../src/domain/disks.js';
import { parseGpuStats, parseThermalSensors } from '../src/domain/gpu.js';
import {
formatCompactCount,
formatDiskGiB,
formatIops,
formatMarkdownDiagnostics,
formatMemoryMiB,
formatMonitorRate,
formatUptime,
} from '../src/domain/formatting.js';
test('disk grouping and system-disk auto-expand alert preserves Netcatty parity', () => {
assert.equal(isMonitorSystemDisk('/'), false);
assert.equal(isMonitorSystemDisk('/boot'), true);
assert.equal(isMonitorSystemDisk('/var/lib/docker'), true);
assert.equal(isMonitorSystemDisk('/data'), false);
const sorted = sortMonitorDisks([
{ mountPoint: '/data' },
{ mountPoint: '/var' },
{ mountPoint: '/' },
{ mountPoint: '/boot' },
]);
assert.deepEqual(
sorted.map((d) => d.mountPoint),
['/', '/boot', '/var', '/data'],
);
// Under 80%: collapsed by default
const collapsed = buildMonitorDiskListLayout({
disks: [
{ mountPoint: '/', percent: 50, used: 50, total: 100 },
{ mountPoint: '/boot', percent: 40, used: 0.4, total: 1 },
{ mountPoint: '/data', percent: 60, used: 600, total: 1000 },
],
});
assert.equal(collapsed.expanded, false);
assert.equal(collapsed.forcedExpanded, false);
assert.equal(collapsed.rows.length, 3); // '/', '/data', system header
// System disk > 80%: forced expanded
const alerted = buildMonitorDiskListLayout({
disks: [
{ mountPoint: '/', percent: 50, used: 50, total: 100 },
{ mountPoint: '/var', percent: 88, used: 44, total: 50 },
],
});
assert.equal(alerted.forcedExpanded, true);
assert.equal(alerted.expanded, true);
assert.equal(alerted.rows.some((r) => r.kind === 'disk' && r.disk.mountPoint === '/var' && r.alert), true);
});
test('disk I/O and partition I/O calculation', () => {
const prev = parseDiskIo('10.0;sda:1000:2000');
const curr = parseDiskIo('12.0;sda:1100:2200');
const rates = diskIoRates(curr, prev);
assert.equal(rates.diskReadSpeed, (100 * 512) / 2);
assert.equal(rates.diskWriteSpeed, (200 * 512) / 2);
const pPrev = parseDiskIo('10.0;8-1:500:500');
const pCurr = parseDiskIo('12.0;8-1:520:540');
const disks = withPartitionIo([{ mountPoint: '/mnt/my drive', percent: 30, used: 30, total: 100 }], '/mnt/my\\040drive:8-1,', pCurr, pPrev);
assert.equal(disks[0].diskReadSpeed, (20 * 512) / 2);
assert.equal(disks[0].diskWriteSpeed, (40 * 512) / 2);
});
test('GPU & thermal sensor parsing supports multi-GPU + temp + power + commas in product name', () => {
const output =
'GPU:55 12288 49152 NVIDIA RTX 4090, Founders ;; 0\tNVIDIA RTX 4090, Founders\t70\t8192\t24576\t64\t285.5 ;; 1\tNVIDIA RTX 4090, Founders\t40\t4096\t24576\t58\t190.2';
const parsed = parseGpuStats(output);
assert.equal(parsed.gpu, 55);
assert.equal(parsed.gpuMemUsed, 12288);
assert.equal(parsed.gpuMemTotal, 49152);
assert.equal(parsed.gpus.length, 2);
assert.equal(parsed.gpus[0].name, 'NVIDIA RTX 4090, Founders');
assert.equal(parsed.gpus[0].vendor, 'nvidia');
assert.equal(parsed.gpus[0].temperatureC, 64);
assert.equal(parsed.gpus[0].powerWatts, 285.5);
const thermals = parseThermalSensors('x86_pkg_temp:61200,nvme:41000,nvme:44000');
assert.equal(thermals.length, 3);
assert.equal(thermals[0].temperatureC, 61.2);
assert.equal(thermals[2].label, 'nvme #2');
});
test('formatting helpers match Netcatty conventions', () => {
assert.equal(formatMonitorRate(1500), '1.5 KB/s');
assert.equal(formatMonitorRate(2_500_000), '2.5 MB/s');
assert.equal(formatMonitorRate(3_200_000_000), '3.2 GB/s');
assert.equal(formatMonitorRate(null), '--');
assert.equal(formatMemoryMiB(16384), '16.0 GiB');
assert.equal(formatDiskGiB(1536), '1.50 TiB');
assert.equal(formatUptime(90061, 'en'), '1d 1h');
assert.equal(formatUptime(90061, 'zh-CN'), '1天 1小时');
assert.equal(formatCompactCount(42_500), '42.5k');
assert.equal(formatIops(1850, 420), '1.9k/420 IOPS');
const md = formatMarkdownDiagnostics({
title: 'Prod Fleet',
generatedAt: '2026-11-28T00:00:00Z',
hosts: [
{
label: 'web-01',
hostname: '10.0.0.1',
status: 'live',
cpu: 42,
memPercent: 60,
diskPercent: 55,
load: '0.80 / 0.70 / 0.60',
latency: '18 ms',
os: 'Ubuntu 24.04',
},
],
activeAlerts: [],
});
assert.match(md, /# Netcatty Monitor Diagnostics — Prod Fleet/);
assert.match(md, /\| web-01 \(10\.0\.0\.1\) \| live \| 42\.0% \| 60\.0% \| 55% \|/);
});
test('7-field disk I/O computes IOPS, %util, queue depth, and inode alert auto-expands system disks', () => {
const prev = parseDiskIo('10.0;nvme0n1:1000:2000:500:300:1000:1');
const curr = parseDiskIo('12.0;nvme0n1:1200:2400:900:500:2200:3');
const rates = diskIoRates(curr, prev);
assert.equal(rates.diskReadSpeed, (200 * 512) / 2);
assert.equal(rates.diskWriteSpeed, (400 * 512) / 2);
assert.equal(rates.diskReadIops, 200);
assert.equal(rates.diskWriteIops, 100);
assert.equal(rates.diskUtilPercent, 60);
assert.equal(rates.diskQueueDepth, 3);
const inodeAlert = buildMonitorDiskListLayout({
disks: [
{ mountPoint: '/', percent: 40, used: 40, total: 100, inodePercent: 20 },
{ mountPoint: '/var', percent: 30, used: 15, total: 50, inodePercent: 92 },
],
});
assert.equal(inodeAlert.forcedExpanded, true);
assert.equal(inodeAlert.rows.some((r) => r.kind === 'disk' && r.disk.mountPoint === '/var' && r.alert), true);
});
@@ -1,324 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { MonitorEngine } from '../src/services/monitorEngine.js';
import type { MonitorHostBridge } from '../src/services/hostBridge.js';
function createMockBridge(handler: (cmd: string) => { stdout: string; latencyMs?: number }): MonitorHostBridge {
return {
supportsHostExec: true,
supportsHostProbe: true,
async selectHosts() {
return [];
},
async resolveHostBindings() {
return [];
},
async revokeHostBinding() {
return true;
},
async execHostCommand({ command }) {
const res = handler(command);
return {
stdout: res.stdout,
stderr: '',
exitCode: 0,
latencyMs: res.latencyMs ?? 15,
responseLatencyMs: 20,
};
},
async probeHost({ protocol = 'rdp', port = 3389 }) {
return {
reachable: true,
protocol,
port,
rttMs: 28,
bannerVerified: true,
bannerDetail: 'RDP-TLS',
checkedAt: Date.now(),
};
},
async openHostSession() {
return true;
},
async setViewBadge() {},
async copyText() {
return true;
},
async confirmAction() {
return true;
},
async saveJsonSnapshot() {
return true;
},
async saveMarkdownReport() {
return true;
},
async loadStorage() {
return undefined;
},
async saveStorage() {},
};
}
test('MonitorEngine polls Linux host, fetches separate disks + GPU, records history & operational tabs', async () => {
let clock = 1_000_000;
let cpuTick = 0;
const bridge = createMockBridge((cmd) => {
if (cmd.includes('OSFAM:linux')) {
cpuTick += 1;
const total = 1000 + cpuTick * 200;
const idle = 500 + cpuTick * 100;
return {
stdout: `OSFAM:linux|CPURAW:${total} ${idle} 4 0|CORES:4|PERCORERAW:250:125,250:125|MEMINFO:8192 2048 256 1024 1024 1024|NET:eth0:${cpuTick * 10000}:${cpuTick * 5000}|DISKIO:${100 + cpuTick * 5};sda:100:200|PARTITIONIO:|DISKMOUNTS:|THERMALS:cpu:48000|HOST:node-1|OS:Debian 12|KERNEL:6.1.0|UPTIME:5000|LOAD:0.40 0.35 0.30`,
latencyMs: 18,
};
}
if (cmd.includes('DISKS:$disks')) {
return { stdout: 'DISKS:/:40.0:100.0:40:fs=ext4:/dev/sda1' };
}
if (cmd.includes('nvidia-smi')) {
return { stdout: 'GPU:62 4096 16384 NVIDIA L4 ;; 0\tNVIDIA L4\t62\t4096\t16384\t54\t70.0' };
}
if (cmd.includes('__NC_SYSTEMD__')) {
return { stdout: '__NC_SYSTEMD__\nsshd.service loaded active running OpenSSH\n__NC_DOCKER__\n__NC_PODMAN__' };
}
if (cmd.includes('__NC_PORTS__')) {
return { stdout: '__NC_PORTS__\ntcp LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=100,fd=3))\n__NC_SOCKSUMMARY__\nLISTEN:1' };
}
if (cmd.includes('ps -axo pid=')) {
return { stdout: ' 100 root 5.0 1.2 12000 Ss 10:00 /usr/sbin/sshd -D' };
}
return { stdout: '' };
});
const engine = new MonitorEngine(bridge, { now: () => clock });
const host = { hostId: 'hb_node1', hostBindingToken: 'hb_node1', label: 'Node 1', hostname: '10.0.0.10' };
engine.reconcileHosts([host], { running: true, interval: 60 });
await new Promise((r) => setTimeout(r, 40));
const snap1 = engine.getSnapshot();
assert.equal(snap1.hosts['hb_node1']?.status, 'live');
assert.equal(snap1.hosts['hb_node1']?.stats?.disks[0]?.mountPoint, '/');
assert.equal(snap1.hosts['hb_node1']?.stats?.gpu, 62);
assert.equal(snap1.hosts['hb_node1']?.points.length, 1);
// Trigger second sample after advancing clock
clock += 5000;
engine.refreshAllNow();
await new Promise((r) => setTimeout(r, 40));
const snap2 = engine.getSnapshot();
assert.equal(snap2.hosts['hb_node1']?.stats?.cpu, 50);
assert.equal(snap2.hosts['hb_node1']?.points.length, 2);
// Active-tab probes
const procs = await engine.fetchProcesses(host);
assert.equal(procs.length, 1);
assert.equal(procs[0].pid, 100);
const { services } = await engine.fetchServicesAndContainers(host);
assert.equal(services.length, 1);
assert.equal(services[0].unit, 'sshd.service');
const { ports, summary } = await engine.fetchPorts(host);
assert.equal(ports.length, 1);
assert.equal(summary.listen, 1);
engine.dispose();
});
test('MonitorEngine caps concurrent execs at 12 and handles stale detection + Windows fallback', async () => {
let inFlight = 0;
let peakInFlight = 0;
const bridge: MonitorHostBridge = {
supportsHostExec: true,
supportsHostProbe: true,
async selectHosts() { return []; },
async resolveHostBindings() { return []; },
async revokeHostBinding() { return true; },
async probeHost({ protocol = 'rdp', port = 3389 }) {
return { reachable: true, protocol, port, rttMs: 20, bannerVerified: true, checkedAt: Date.now() };
},
async execHostCommand({ command }) {
inFlight += 1;
peakInFlight = Math.max(peakInFlight, inFlight);
await new Promise((r) => setTimeout(r, 15));
inFlight -= 1;
if (command.includes('powershell')) {
return {
stdout: 'OSFAM:windows|CPU:28|CORES:4|MEMINFO:8192 4096 0 0 0 0|DISKS:C::50.0:200.0:25:NTFS|HOST:WIN-01|OS:Windows Server 2022|KERNEL:10.0|UPTIME:1200',
stderr: '',
exitCode: 0,
latencyMs: 12,
responseLatencyMs: 16,
};
}
return {
stdout: 'UNSUPPORTED_OS:MINGW64_NT',
stderr: '',
exitCode: 0,
latencyMs: 12,
responseLatencyMs: 16,
};
},
async openHostSession() { return true; },
async setViewBadge() {},
async copyText() { return true; },
async confirmAction() { return true; },
async saveJsonSnapshot() { return true; },
async saveMarkdownReport() { return true; },
async loadStorage() { return undefined; },
async saveStorage() {},
};
const engine = new MonitorEngine(bridge);
const hosts = Array.from({ length: 20 }, (_, i) => ({
hostId: `hb_win_${i}`,
hostBindingToken: `hb_win_${i}`,
label: `win-${i}`,
}));
try {
engine.reconcileHosts(hosts, { running: true, interval: 60 });
await new Promise((r) => setTimeout(r, 140));
assert.ok(peakInFlight <= 12, `Expected concurrency <= 12, observed ${peakInFlight}`);
const snap = engine.getSnapshot();
const liveCount = Object.values(snap.hosts).filter((h) => h.status === 'live' && h.stats?.osFamily === 'windows').length;
assert.equal(liveCount, 20);
} finally {
engine.dispose();
}
});
test('MonitorEngine probes standalone RDP/VNC hosts via vault.probeHost and records RTT history & offline alerts', async () => {
let probeOk = true;
const bridge: MonitorHostBridge = {
supportsHostExec: true,
supportsHostProbe: true,
async selectHosts() { return []; },
async resolveHostBindings() { return []; },
async revokeHostBinding() { return true; },
async execHostCommand() {
throw new Error('SSH exec should not be called for RDP probe hosts');
},
async probeHost({ protocol = 'rdp', port = 3389 }) {
return probeOk
? { reachable: true, protocol, port, rttMs: 32, bannerVerified: true, bannerDetail: 'RDP-NLA', checkedAt: Date.now() }
: { reachable: false, protocol, port, rttMs: null, bannerVerified: false, error: 'Connection refused', checkedAt: Date.now() };
},
async openHostSession() { return true; },
async setViewBadge() {},
async copyText() { return true; },
async confirmAction() { return true; },
async saveJsonSnapshot() { return true; },
async saveMarkdownReport() { return true; },
async loadStorage() { return undefined; },
async saveStorage() {},
};
const engine = new MonitorEngine(bridge);
const rdpHost = { hostId: 'hb_rdp_1', hostBindingToken: 'hb_rdp_1', label: 'Win Jump', hostname: '10.0.5.8', port: 3389, protocol: 'rdp' };
try {
engine.reconcileHosts([rdpHost], { running: true, interval: 60 });
await new Promise((r) => setTimeout(r, 40));
const snap1 = engine.getSnapshot();
assert.equal(snap1.hosts['hb_rdp_1']?.mode, 'probe');
assert.equal(snap1.hosts['hb_rdp_1']?.status, 'live');
assert.equal(snap1.hosts['hb_rdp_1']?.probe?.rttMs, 32);
assert.equal(snap1.hosts['hb_rdp_1']?.probe?.bannerVerified, true);
assert.equal(snap1.hosts['hb_rdp_1']?.points[0]?.latencyMs, 32);
assert.equal(snap1.alerts.filter((a) => !a.resolvedAt).length, 0);
probeOk = false;
engine.refreshAllNow();
await new Promise((r) => setTimeout(r, 40));
const snap2 = engine.getSnapshot();
assert.equal(snap2.hosts['hb_rdp_1']?.status, 'offline');
assert.equal(snap2.alerts.some((a) => a.hostId === 'hb_rdp_1' && a.metric === 'offline' && !a.resolvedAt), true);
} finally {
engine.dispose();
}
});
test('MonitorEngine enforces alert hysteresis and supports system audit + service/container actions', async () => {
let clock = 2_000_000;
let latency = 240; // breaches 180ms warning threshold
const executedCommands: string[] = [];
const bridge = createMockBridge((cmd) => {
executedCommands.push(cmd);
if (cmd.includes('OSFAM:linux')) {
return {
stdout:
'OSFAM:linux|CPURAW:1000 500 20 5 300 150|CPUEXTRA:5000 1000 2 0|CORES:4|PERCORERAW:250:125,250:125|MEMINFO:8192 2048 256 1024 1024 1024 2048 512|NET:eth0:10000:5000:100:50:0:0:0:0|TCPRETRANS:12|DISKIO:100;sda:100:200:50:80:400:1|PARTITIONIO:|DISKMOUNTS:|FD:1200:65536|USERS:2|REBOOT:1|THERMALS:|HOST:node-hyst|OS:Ubuntu 24.04|KERNEL:6.8.0|UPTIME:5000|LOAD:0.40 0.35 0.30',
latencyMs: latency,
};
}
if (cmd.includes('DISKS:$disks')) {
return { stdout: 'DISKS:/:40.0:100.0:40:fs=ext4:/dev/sda1|INODES:/:12000:100000:12' };
}
if (cmd.includes('__NC_FD__')) {
return {
stdout: [
'__NC_FD__',
'1200:65536',
'__NC_REBOOT__',
'1',
'__NC_WHO__',
'ops pts/0 2026-11-28 08:00 (10.0.0.5)',
'__NC_LAST__',
'ops pts/0 10.0.0.5 Sat Nov 28 08:00 still logged in',
'__NC_FAILEDAUTH__',
'4',
].join('\n'),
};
}
return { stdout: 'ok' };
});
const engine = new MonitorEngine(bridge, { now: () => clock });
const host = { hostId: 'hb_hyst', hostBindingToken: 'hb_hyst', label: 'Node Hyst', hostname: '10.0.0.99' };
try {
// Poll 1: single latency breach is suppressed by default consecutivePolls=2 hysteresis
engine.reconcileHosts([host], { running: true, interval: 60 });
await new Promise((r) => setTimeout(r, 40));
const snap1 = engine.getSnapshot();
assert.equal(snap1.hosts['hb_hyst']?.stats?.rebootRequired, true);
assert.equal(snap1.hosts['hb_hyst']?.stats?.disks[0]?.inodePercent, 12);
assert.equal(snap1.alerts.filter((a) => !a.resolvedAt).length, 0);
// Poll 2: consecutive breach fires the warning alert
clock += 5000;
engine.refreshAllNow();
await new Promise((r) => setTimeout(r, 40));
const snap2 = engine.getSnapshot();
assert.equal(snap2.alerts.some((a) => a.hostId === 'hb_hyst' && a.metric === 'latencyMs' && !a.resolvedAt), true);
// Poll 3: recovery resolves the alert
latency = 15;
clock += 5000;
engine.refreshAllNow();
await new Promise((r) => setTimeout(r, 40));
const snap3 = engine.getSnapshot();
assert.equal(snap3.alerts.filter((a) => !a.resolvedAt).length, 0);
// System audit + service/container lifecycle actions
const audit = await engine.fetchSystemAudit(host);
assert.equal(audit.fdUsed, 1200);
assert.equal(audit.fdMax, 65536);
assert.equal(audit.loggedInUsers.length, 1);
assert.equal(audit.failedAuthCount, 4);
assert.equal(audit.rebootRequired, true);
assert.equal(audit.recentLogins.length, 1);
await engine.runServiceAction(host, 'nginx.service', 'restart');
assert.ok(executedCommands.some((c) => c.includes("systemctl restart 'nginx.service'")));
await engine.runContainerAction(host, 'docker', 'a1b2c3d4e5f6', 'restart');
assert.ok(executedCommands.some((c) => c.includes("docker restart 'a1b2c3d4e5f6'")));
} finally {
engine.dispose();
}
});
@@ -1,243 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
buildContainerActionCommand,
buildContainerLogsCommand,
buildLinuxDiskCommand,
buildPortsCommand,
buildPrimaryStatsCommand,
buildProcessSignalCommand,
buildServiceActionCommand,
buildServiceLogsCommand,
buildSystemAuditCommand,
DROPBEAR_MAX_COMMAND_BYTES,
} from '../src/domain/collectors.js';
import {
parsePortsOutput,
parsePrimaryStatsOutput,
parseProcessesOutput,
parseServicesAndContainersOutput,
parseSystemAuditOutput,
} from '../src/domain/parsers.js';
const HOST_EXEC_MAX_BYTES = 8192;
test('collector commands stay well below Dropbear and host-exec 8192-byte limits', () => {
const primary = buildPrimaryStatsCommand();
const linuxDisk = buildLinuxDiskCommand();
const audit = buildSystemAuditCommand();
assert.ok(Buffer.byteLength(primary, 'utf8') < Math.min(DROPBEAR_MAX_COMMAND_BYTES, HOST_EXEC_MAX_BYTES), `primary=${Buffer.byteLength(primary, 'utf8')}`);
assert.ok(Buffer.byteLength(linuxDisk, 'utf8') < Math.min(DROPBEAR_MAX_COMMAND_BYTES, HOST_EXEC_MAX_BYTES), `disk=${Buffer.byteLength(linuxDisk, 'utf8')}`);
assert.ok(Buffer.byteLength(buildPortsCommand(), 'utf8') < HOST_EXEC_MAX_BYTES);
assert.ok(Buffer.byteLength(audit, 'utf8') < HOST_EXEC_MAX_BYTES);
});
test('command builders reject shell injection on unit/container/pid and build lifecycle actions', () => {
assert.throws(() => buildServiceLogsCommand('nginx; rm -rf /'));
assert.throws(() => buildServiceActionCommand('nginx && id', 'restart'));
assert.throws(() => buildContainerLogsCommand('docker', '$(whoami)'));
assert.throws(() => buildContainerActionCommand('docker', 'abc;rm', 'restart'));
assert.throws(() => buildProcessSignalCommand(1, 'SIGKILL'));
assert.throws(() => buildProcessSignalCommand(-5, 'SIGTERM'));
assert.equal(buildProcessSignalCommand(4242, 'SIGTERM'), 'kill -s SIGTERM 4242');
assert.match(buildServiceLogsCommand('nginx.service', 80), /journalctl -u 'nginx\.service' -n 80/);
assert.match(buildServiceActionCommand('nginx.service', 'reload'), /systemctl reload 'nginx\.service'/);
assert.match(buildContainerLogsCommand('podman', 'web_api-1', 50), /podman logs --tail 50 --timestamps 'web_api-1'/);
assert.equal(buildContainerActionCommand('docker', 'a1b2c3d4e5f6', 'restart'), "docker restart 'a1b2c3d4e5f6' 2>&1");
});
test('parsePrimaryStatsOutput computes Linux CPU/per-core/net/disk-IO deltas accurately', () => {
const sample1 =
'OSFAM:linux|CPURAW:1000 500 20 10|CORES:2|PERCORERAW:500:250,500:250|MEMINFO:16384 2048 512 4096 4096 3072|NET:eth0:100000:50000|DISKIO:100.0;nvme0n1:100:200|PARTITIONIO:100.0;259-1:100:200|DISKMOUNTS:/:259-1,|THERMALS:x86_pkg_temp:54500,acpitz:42000|HOST:prod-web-01|OS:Ubuntu 24.04.1 LTS|KERNEL:6.8.0-45-generic|UPTIME:86400|LOAD:0.84 0.72 0.65';
const diskStdout = 'DISKS:/:40.000000:100.000000:40:fs=ext4:/dev/nvme0n1p1,/var:12.000000:50.000000:24:fs=ext4:/dev/nvme0n1p2';
const r1 = parsePrimaryStatsOutput(sample1, {}, { now: 100_000, latencyMs: 24, linuxDiskStdout: diskStdout });
assert.equal(r1.ok, true);
if (!r1.ok) return;
assert.equal(r1.stats.osFamily, 'linux');
assert.equal(r1.stats.cpu, null); // First delta sample
assert.equal(r1.stats.cpuCores, 2);
assert.equal(r1.stats.memTotal, 16384);
assert.equal(r1.stats.memUsed, 16384 - 2048 - 512 - 4096);
assert.equal(r1.stats.swapTotal, 4096);
assert.equal(r1.stats.swapUsed, 1024);
assert.equal(r1.stats.networkReady, false);
assert.equal(r1.stats.thermals.length, 2);
assert.equal(r1.stats.thermals[0].temperatureC, 54.5);
assert.equal(r1.stats.disks.length, 2);
assert.equal(r1.stats.diskPercent, 40);
// 2 seconds later
const sample2 =
'OSFAM:linux|CPURAW:1200 550 30 14|CORES:2|PERCORERAW:600:270,600:280|MEMINFO:16384 2048 512 4096 4096 3072|NET:eth0:120000:60000|DISKIO:102.0;nvme0n1:140:280|PARTITIONIO:102.0;259-1:140:280|DISKMOUNTS:/:259-1,|THERMALS:x86_pkg_temp:56000|HOST:prod-web-01|OS:Ubuntu 24.04.1 LTS|KERNEL:6.8.0-45-generic|UPTIME:86402|LOAD:1.10 0.80 0.70';
const r2 = parsePrimaryStatsOutput(sample2, r1.nextDelta, { now: 102_000, latencyMs: 22, linuxDiskStdout: diskStdout });
assert.equal(r2.ok, true);
if (!r2.ok) return;
// totalDelta=200, idleDelta=50 -> 75% CPU, iowaitDelta=10 -> 5.0%, stealDelta=4 -> 2.0%
assert.equal(r2.stats.cpu, 75);
assert.equal(r2.stats.cpuIowait, 5);
assert.equal(r2.stats.cpuSteal, 2);
assert.deepEqual(r2.stats.cpuPerCore, [80, 70]);
assert.equal(r2.stats.networkReady, true);
assert.equal(r2.stats.netRxSpeed, 10_000);
assert.equal(r2.stats.netTxSpeed, 5_000);
assert.equal(r2.stats.diskReadSpeed, (40 * 512) / 2);
assert.equal(r2.stats.diskWriteSpeed, (80 * 512) / 2);
assert.equal(r2.stats.disks[0].diskReadSpeed, (40 * 512) / 2);
});
test('parsePrimaryStatsOutput handles macOS and Windows payloads', () => {
const mac =
'OSFAM:macos|CPU:32|CORES:10|MEMINFO:32768 4096 0 8192 2048 1536|DISKS:/:120.5:500.0:24:apfs:/dev/disk3|NET:en0:5000:2500|HOST:mac-studio|OS:macOS 15.2|KERNEL:24.2.0|UPTIME:12345|LOAD:1.25 1.10 0.95';
const macRes = parsePrimaryStatsOutput(mac, {}, { now: 10_000, latencyMs: 9 });
assert.equal(macRes.ok, true);
if (macRes.ok) {
assert.equal(macRes.stats.osFamily, 'macos');
assert.equal(macRes.stats.cpu, 32);
assert.equal(macRes.stats.disks[0].mountPoint, '/');
assert.equal(macRes.stats.swapUsed, 512);
}
const win =
'OSFAM:windows|CPU:44|CORES:8|MEMINFO:16384 6144 0 0 0 0|DISKS:C::82.4:256.0:32:NTFS|HOST:WIN-SRV01|OS:Windows Server 2022|KERNEL:10.0.20348|UPTIME:43200';
const winRes = parsePrimaryStatsOutput(win, {}, { now: 10_000 });
assert.equal(winRes.ok, true);
if (winRes.ok) {
assert.equal(winRes.stats.osFamily, 'windows');
assert.equal(winRes.stats.cpu, 44);
assert.equal(winRes.stats.disks[0].mountPoint, 'C:');
assert.equal(winRes.stats.disks[0].percent, 32);
}
});
test('parseProcessesOutput parses ps rows cleanly', () => {
const out = `
1234 root 42.5 3.2 128000 Ssl 02:14:09 /usr/bin/dockerd -H fd://
882 postgres 12.0 18.4 940120 Ss 3-01:22:10 postgres: writer process
`;
const rows = parseProcessesOutput(out);
assert.equal(rows.length, 2);
assert.equal(rows[0].pid, 1234);
assert.equal(rows[0].cpuPercent, 42.5);
assert.equal(rows[0].command, '/usr/bin/dockerd -H fd://');
assert.equal(rows[1].user, 'postgres');
});
test('parseServicesAndContainersOutput parses systemd + docker + podman', () => {
const out = [
'__NC_SYSTEMD__',
'nginx.service loaded active running A high performance web server',
'redis-server.service loaded failed failed Advanced key-value store',
'__NC_DOCKER__',
'a1b2c3d4e5f67890\tapi-gateway\tnginx:1.27\trunning\tUp 4 days\t0.0.0.0:443->443/tcp',
'__NC_PODMAN__',
'ff00112233445566\tworker-1\tghcr.io/app/worker:latest\texited\tExited (0) 2 hours ago\t',
].join('\n');
const { services, containers } = parseServicesAndContainersOutput(out);
assert.equal(services.length, 2);
assert.equal(services[1].activeState, 'failed');
assert.equal(containers.length, 2);
assert.equal(containers[0].runtime, 'docker');
assert.equal(containers[0].id, 'a1b2c3d4e5f6');
assert.equal(containers[1].runtime, 'podman');
});
test('parsePortsOutput parses ss, lsof, and socket summary', () => {
const out = [
'__NC_PORTS__',
'tcp LISTEN 0 4096 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=912,fd=3))',
'tcp LISTEN 0 511 [::]:443 [::]:* users:(("nginx",pid=1402,fd=7))',
'node 5501 chenqi 21u IPv4 0x123 0t0 TCP 127.0.0.1:5173 (LISTEN)',
'__NC_SOCKSUMMARY__',
'ESTAB:18',
'LISTEN:6',
'TIME-WAIT:4',
].join('\n');
const { ports, summary } = parsePortsOutput(out);
assert.equal(ports.length, 3);
assert.equal(ports[0].port, 22);
assert.equal(ports[0].process, 'sshd');
assert.equal(ports[1].localAddress, '::');
assert.equal(ports[2].port, 5173);
assert.equal(ports[2].process, 'node');
assert.equal(summary.established, 18);
assert.equal(summary.listen, 6);
assert.equal(summary.timeWait, 4);
assert.equal(summary.total, 28);
});
test('parsePrimaryStatsOutput parses commercial telemetry (CPU breakdown, PSI, Inodes, pps/drops, TCP retrans, FD/reboot)', () => {
const sample1 =
'OSFAM:linux|CPURAW:1000 500 20 10 350 120|CPUEXTRA:10000 4000 3 1|CORES:2|PERCORERAW:500:250,500:250|MEMINFO:16384 2048 512 4096 4096 3072 6144 1024|PSI:1.25,0.80,0.50,0.40,0.10,2.75,2.10,0.80|NET:eth0:100000:50000:1000:500:1:2:3:4|TCPRETRANS:100|DISKIO:100.0;nvme0n1:100:200:50:80:1000:2|PARTITIONIO:|DISKMOUNTS:|FD:4096:65536|USERS:3|REBOOT:1|THERMALS:|HOST:prod-db-01|OS:Ubuntu 24.04|KERNEL:6.8.0|UPTIME:86400|LOAD:1.20 1.00 0.90';
const diskStdout = 'DISKS:/:40.0:100.0:40:fs=ext4:/dev/nvme0n1p1|INODES:/:85000:100000:85';
const r1 = parsePrimaryStatsOutput(sample1, {}, { now: 100_000, latencyMs: 18, linuxDiskStdout: diskStdout });
assert.equal(r1.ok, true);
if (!r1.ok) return;
assert.equal(r1.stats.memActive, 6144);
assert.equal(r1.stats.memSlab, 1024);
assert.equal(r1.stats.psi?.cpuSome10, 1.25);
assert.equal(r1.stats.psi?.ioFull10, 0.8);
assert.equal(r1.stats.fdUsed, 4096);
assert.equal(r1.stats.fdMax, 65536);
assert.equal(r1.stats.activeUsers, 3);
assert.equal(r1.stats.rebootRequired, true);
assert.equal(r1.stats.disks[0].inodePercent, 85);
assert.equal(r1.stats.disks[0].inodeUsed, 85000);
// 2 seconds later
const sample2 =
'OSFAM:linux|CPURAW:1200 550 30 14 430 176|CPUEXTRA:16000 6000 5 2|CORES:2|PERCORERAW:600:270,600:280|MEMINFO:16384 2048 512 4096 4096 3072 6144 1024|PSI:2.00,1.10,0.40,0.30,0.10,3.50,2.50,1.00|NET:eth0:120000:60000:1400:700:2:5:4:9|TCPRETRANS:110|DISKIO:102.0;nvme0n1:140:280:250:180:1600:4|PARTITIONIO:|DISKMOUNTS:|FD:4200:65536|USERS:3|REBOOT:1|THERMALS:|HOST:prod-db-01|OS:Ubuntu 24.04|KERNEL:6.8.0|UPTIME:86402|LOAD:1.40 1.05 0.92';
const r2 = parsePrimaryStatsOutput(sample2, r1.nextDelta, { now: 102_000, latencyMs: 20, linuxDiskStdout: diskStdout });
assert.equal(r2.ok, true);
if (!r2.ok) return;
assert.equal(r2.stats.cpu, 75);
assert.equal(r2.stats.cpuUser, 40);
assert.equal(r2.stats.cpuSystem, 28);
assert.equal(r2.stats.cpuIowait, 5);
assert.equal(r2.stats.cpuSteal, 2);
assert.equal(r2.stats.cpuIdle, 25);
assert.equal(r2.stats.contextSwitchesPerSec, 3000);
assert.equal(r2.stats.interruptsPerSec, 1000);
assert.equal(r2.stats.procsRunning, 5);
assert.equal(r2.stats.procsBlocked, 2);
assert.equal(r2.stats.netRxPps, 200);
assert.equal(r2.stats.netTxPps, 100);
assert.equal(r2.stats.netErrorsDelta, 2);
assert.equal(r2.stats.netDropsDelta, 8);
assert.equal(r2.stats.tcpRetransmitsPerSec, 5);
assert.equal(r2.stats.diskReadIops, 100);
assert.equal(r2.stats.diskWriteIops, 50);
assert.equal(r2.stats.diskUtilPercent, 30);
assert.equal(r2.stats.diskQueueDepth, 4);
});
test('parseSystemAuditOutput and SYN-RECV socket summary parse cleanly', () => {
const audit = parseSystemAuditOutput(
[
'__NC_FD__',
'2048:131072',
'__NC_REBOOT__',
'1',
'__NC_WHO__',
'root pts/0 2026-11-28 09:00',
'ops pts/1 2026-11-28 09:15 (10.0.0.10)',
'__NC_LAST__',
'ops pts/1 10.0.0.10 Sat Nov 28 09:15 still logged in',
'wtmp begins Fri Nov 1 00:00:00 2026',
'__NC_FAILEDAUTH__',
'14',
].join('\n'),
);
assert.equal(audit.fdUsed, 2048);
assert.equal(audit.fdMax, 131072);
assert.equal(audit.loggedInUsers.length, 2);
assert.equal(audit.failedAuthCount, 14);
assert.equal(audit.rebootRequired, true);
assert.equal(audit.recentLogins.length, 1);
const { summary } = parsePortsOutput('__NC_PORTS__\n__NC_SOCKSUMMARY__\nESTAB:10\nSYN-RECV:3\nLISTEN:4');
assert.equal(summary.synRecv, 3);
assert.equal(summary.total, 17);
});
-4
View File
@@ -1,4 +0,0 @@
declare module 'react-dom/server' {
import type { ReactNode } from 'react';
export function renderToStaticMarkup(element: ReactNode): string;
}
-428
View File
@@ -1,428 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { DEFAULT_ALERT_THRESHOLDS } from '../src/domain/alerts.js';
import { createTranslator } from '../src/domain/i18n.js';
import type { HostRuntimeState, MonitorHostRef, MonitorPanel } from '../src/domain/types.js';
// Provide minimal DOM globals required by @remote-dom/core when importing host-react in Node SSR tests.
const g = globalThis as Record<string, unknown>;
for (const name of ['HTMLElement', 'Element', 'Node', 'MutationObserver', 'CustomEvent']) {
if (typeof g[name] === 'undefined') {
g[name] = class {};
}
}
const { FleetOverview } = await import('../src/ui/FleetOverview.js');
const { OverviewTab } = await import('../src/ui/tabs/OverviewTab.js');
const sampleHost: MonitorHostRef = {
hostId: 'hb_prod_1',
hostBindingToken: 'hb_prod_1',
label: 'prod-eu-01',
hostname: '10.0.1.24',
port: 22,
username: 'ops',
group: 'Production',
tags: ['web', 'eu'],
notes: 'Primary ingress node',
};
const sampleState: HostRuntimeState = {
hostId: 'hb_prod_1',
status: 'live',
updatedAt: Date.now(),
points: [
{ at: Date.now() - 10_000, cpu: 32, memory: 58, disk: 48, rx: 120_000, tx: 60_000, diskRead: 40_000, diskWrite: 20_000, latencyMs: 22 },
{ at: Date.now(), cpu: 41, memory: 61, disk: 48, rx: 140_000, tx: 75_000, diskRead: 50_000, diskWrite: 25_000, latencyMs: 19 },
],
stats: {
osFamily: 'linux',
cpu: 41,
cpuCores: 4,
cpuPerCore: [38, 44, 40, 42],
cpuIowait: 1.2,
cpuSteal: 0.1,
gpu: 55,
gpuName: 'NVIDIA L4',
gpuMemUsed: 4096,
gpuMemTotal: 24576,
gpus: [{ index: 0, name: 'NVIDIA L4', vendor: 'nvidia', utilization: 55, memoryUsed: 4096, memoryTotal: 24576, temperatureC: 58, powerWatts: 62.5 }],
thermals: [{ id: 'pkg', label: 'x86_pkg_temp', temperatureC: 54.0 }],
memTotal: 16384,
memUsed: 10000,
memFree: 2048,
memBuffers: 512,
memCached: 3824,
swapTotal: 2048,
swapUsed: 128,
topProcesses: [],
diskPercent: 48,
diskUsed: 96,
diskTotal: 200,
disks: [
{ mountPoint: '/', percent: 48, used: 96, total: 200, filesystemType: 'ext4', diskReadSpeed: 50_000, diskWriteSpeed: 25_000 },
{ mountPoint: '/boot', percent: 35, used: 0.35, total: 1, filesystemType: 'ext4' },
],
diskReadSpeed: 50_000,
diskWriteSpeed: 25_000,
networkReady: true,
netRxSpeed: 140_000,
netTxSpeed: 75_000,
latencyMs: 19,
responseLatencyMs: 24,
netInterfaces: [{ name: 'eth0', rxBytes: 1_000_000, txBytes: 500_000, rxSpeed: 140_000, txSpeed: 75_000 }],
hostname: 'prod-eu-01.internal',
osName: 'Ubuntu 24.04 LTS',
kernelRelease: '6.8.0-45-generic',
uptimeSeconds: 184_000,
loadAverage: [0.82, 0.75, 0.68],
},
};
const samplePanel: MonitorPanel = {
id: 'default',
name: 'Production',
description: '',
hostIds: ['hb_prod_1'],
view: 'charts',
interval: 5,
range: 15,
sort: 'manual',
};
test('FleetOverview renders zero inline <svg>/<canvas> and uses host-rendered PluginMetricChart', () => {
const html = renderToStaticMarkup(
<FleetOverview
panel={samplePanel}
hosts={[sampleHost]}
runtimeHosts={{ hb_prod_1: sampleState }}
pinnedHostIds={new Set(['hb_prod_1'])}
hiddenColumns={[]}
thresholds={DEFAULT_ALERT_THRESHOLDS}
running
locale="en"
t={createTranslator('en')}
onUpdatePanel={() => {}}
onToggleRunning={() => {}}
onRefreshNow={() => {}}
onAddHosts={() => {}}
onRemoveHost={() => {}}
onTogglePin={() => {}}
onReorderHost={() => {}}
onToggleColumn={() => {}}
onInspectHost={() => {}}
onRetryHost={() => {}}
onOpenSession={() => {}}
onExportSnapshot={() => {}}
/>,
);
assert.doesNotMatch(html, /<svg\b|<canvas\b/i, 'Plugin markup must never emit inline <svg> or <canvas>');
assert.match(html, /data-plugin-widget="metric-chart"/);
for (const icon of ['hosts', 'online', 'warnings', 'critical', 'cpu', 'memory']) {
assert.match(html, new RegExp(`asset:assets/ui/${icon}\\.svg`), `Expected KPI icon ${icon}.svg`);
}
assert.match(html, /prod-eu-01/);
assert.match(html, /41%/);
});
test('OverviewTab renders 4 metric-chart widgets, per-core bars, disk grouping, GPU, and bilingual zh-CN labels', () => {
const html = renderToStaticMarkup(
<OverviewTab
host={sampleHost}
state={sampleState}
interval={5}
range={15}
thresholds={DEFAULT_ALERT_THRESHOLDS}
locale="zh-CN"
t={createTranslator('zh-CN')}
/>,
);
assert.doesNotMatch(html, /<svg\b|<canvas\b/i);
const chartCount = (html.match(/data-plugin-widget="metric-chart"/g) ?? []).length;
assert.equal(chartCount, 4);
assert.match(html, /NVIDIA L4/);
assert.match(html, /x86_pkg_temp/);
assert.match(html, /系统挂载点/);
});
test('FleetOverview table mode uses PluginDataGrid and AlertsTab renders active alerts + thresholds', async () => {
const AlertsTab = (await import('../src/ui/tabs/AlertsTab.js')).default;
const tableHtml = renderToStaticMarkup(
<FleetOverview
panel={{ ...samplePanel, view: 'list' }}
hosts={[sampleHost]}
runtimeHosts={{ hb_prod_1: sampleState }}
pinnedHostIds={new Set()}
hiddenColumns={['tags']}
thresholds={DEFAULT_ALERT_THRESHOLDS}
running
locale="en"
t={createTranslator('en')}
onUpdatePanel={() => {}}
onToggleRunning={() => {}}
onRefreshNow={() => {}}
onAddHosts={() => {}}
onRemoveHost={() => {}}
onTogglePin={() => {}}
onReorderHost={() => {}}
onToggleColumn={() => {}}
onInspectHost={() => {}}
onRetryHost={() => {}}
onOpenSession={() => {}}
onExportSnapshot={() => {}}
/>,
);
assert.doesNotMatch(tableHtml, /<svg\b|<canvas\b/i);
assert.match(tableHtml, /data-plugin-widget="data-grid"/);
const alertsHtml = renderToStaticMarkup(
<AlertsTab
alerts={[
{
id: 'a1',
hostId: 'hb_prod_1',
hostLabel: 'prod-eu-01',
metric: 'cpu',
severity: 'critical',
value: 98,
threshold: 95,
message: 'prod-eu-01: CPU 98%',
at: Date.now(),
acknowledged: false,
resolvedAt: null,
},
]}
thresholds={DEFAULT_ALERT_THRESHOLDS}
locale="en"
t={createTranslator('en')}
onSaveThresholds={() => {}}
onAckAlert={() => {}}
onAckAll={() => {}}
onClearResolved={() => {}}
/>,
);
assert.doesNotMatch(alertsHtml, /<svg\b|<canvas\b/i);
assert.match(alertsHtml, /prod-eu-01: CPU 98%/);
assert.match(alertsHtml, /Save Thresholds/);
});
test('RDP/VNC probe host renders latency metric-chart and Remote Desktop action with zero inline svg', () => {
const rdpHost: MonitorHostRef = {
hostId: 'hb_rdp_1',
hostBindingToken: 'hb_rdp_1',
label: 'Windows Jumpbox',
hostname: '10.0.9.4',
port: 3389,
protocol: 'rdp',
};
const rdpState: HostRuntimeState = {
hostId: 'hb_rdp_1',
mode: 'probe',
status: 'live',
updatedAt: Date.now(),
stats: null,
probe: {
reachable: true,
protocol: 'rdp',
port: 3389,
rttMs: 26,
bannerVerified: true,
bannerDetail: 'RDP-NLA',
checkedAt: Date.now(),
},
points: [
{ at: Date.now() - 10_000, cpu: null, memory: null, disk: null, rx: null, tx: null, diskRead: null, diskWrite: null, latencyMs: 24 },
{ at: Date.now(), cpu: null, memory: null, disk: null, rx: null, tx: null, diskRead: null, diskWrite: null, latencyMs: 26 },
],
};
const fleetHtml = renderToStaticMarkup(
<FleetOverview
panel={{ ...samplePanel, hostIds: ['hb_rdp_1'], view: 'charts' }}
hosts={[rdpHost]}
runtimeHosts={{ hb_rdp_1: rdpState }}
pinnedHostIds={new Set()}
hiddenColumns={[]}
thresholds={DEFAULT_ALERT_THRESHOLDS}
running
locale="en"
t={createTranslator('en')}
onUpdatePanel={() => {}}
onToggleRunning={() => {}}
onRefreshNow={() => {}}
onAddHosts={() => {}}
onRemoveHost={() => {}}
onTogglePin={() => {}}
onReorderHost={() => {}}
onToggleColumn={() => {}}
onInspectHost={() => {}}
onRetryHost={() => {}}
onOpenSession={() => {}}
onExportSnapshot={() => {}}
/>,
);
assert.doesNotMatch(fleetHtml, /<svg\b|<canvas\b/i);
assert.match(fleetHtml, /data-plugin-widget="metric-chart"/);
assert.match(fleetHtml, /Remote Desktop/);
assert.match(fleetHtml, /Banner Verified/);
const detailHtml = renderToStaticMarkup(
<OverviewTab
host={rdpHost}
state={rdpState}
interval={5}
range={15}
thresholds={DEFAULT_ALERT_THRESHOLDS}
locale="en"
t={createTranslator('en')}
/>,
);
assert.doesNotMatch(detailHtml, /<svg\b|<canvas\b/i);
assert.match(detailHtml, /Reachability &amp; TCP Latency/);
assert.match(detailHtml, /24 ms \/ 25 ms \/ 26 ms/);
});
test('FleetOverview wallboard and compare modes render commercial widgets with zero inline svg', () => {
const secondHost: MonitorHostRef = {
...sampleHost,
hostId: 'hb_prod_2',
hostBindingToken: 'hb_prod_2',
label: 'prod-us-02',
hostname: '10.0.2.30',
};
const secondState: HostRuntimeState = {
...sampleState,
hostId: 'hb_prod_2',
};
const wallboardHtml = renderToStaticMarkup(
<FleetOverview
panel={{ ...samplePanel, hostIds: ['hb_prod_1', 'hb_prod_2'], view: 'wallboard' }}
hosts={[sampleHost, secondHost]}
runtimeHosts={{ hb_prod_1: sampleState, hb_prod_2: secondState }}
pinnedHostIds={new Set()}
hiddenColumns={[]}
thresholds={DEFAULT_ALERT_THRESHOLDS}
running
locale="en"
t={createTranslator('en')}
onUpdatePanel={() => {}}
onToggleRunning={() => {}}
onRefreshNow={() => {}}
onAddHosts={() => {}}
onRemoveHost={() => {}}
onTogglePin={() => {}}
onReorderHost={() => {}}
onToggleColumn={() => {}}
onInspectHost={() => {}}
onRetryHost={() => {}}
onOpenSession={() => {}}
onExportSnapshot={() => {}}
/>,
);
assert.doesNotMatch(wallboardHtml, /<svg\b|<canvas\b/i);
assert.match(wallboardHtml, /nm-wallboard-grid/);
assert.match(wallboardHtml, /prod-eu-01/);
assert.match(wallboardHtml, /prod-us-02/);
const compareHtml = renderToStaticMarkup(
<FleetOverview
panel={{
...samplePanel,
hostIds: ['hb_prod_1', 'hb_prod_2'],
compareHostIds: ['hb_prod_1', 'hb_prod_2'],
view: 'compare',
}}
hosts={[sampleHost, secondHost]}
runtimeHosts={{ hb_prod_1: sampleState, hb_prod_2: secondState }}
pinnedHostIds={new Set()}
hiddenColumns={[]}
thresholds={DEFAULT_ALERT_THRESHOLDS}
running
locale="en"
t={createTranslator('en')}
onUpdatePanel={() => {}}
onToggleRunning={() => {}}
onRefreshNow={() => {}}
onAddHosts={() => {}}
onRemoveHost={() => {}}
onTogglePin={() => {}}
onReorderHost={() => {}}
onToggleColumn={() => {}}
onInspectHost={() => {}}
onRetryHost={() => {}}
onOpenSession={() => {}}
onExportSnapshot={() => {}}
/>,
);
assert.doesNotMatch(compareHtml, /<svg\b|<canvas\b/i);
assert.equal((compareHtml.match(/data-plugin-widget="metric-chart"/g) ?? []).length, 4);
assert.match(compareHtml, /data-plugin-widget="data-grid"/);
assert.match(compareHtml, /Compare CPU/);
});
test('OverviewTab renders PSI, Inodes, Open FDs, and honors visibleWidgets filtering', () => {
const richState: HostRuntimeState = {
...sampleState,
stats: {
...sampleState.stats!,
cpuUser: 28.4,
cpuSystem: 11.3,
cpuIowait: 1.2,
cpuSteal: 0.1,
contextSwitchesPerSec: 18_400,
interruptsPerSec: 6_200,
procsRunning: 3,
procsBlocked: 0,
psi: { cpuSome10: 1.4, cpuSome60: 1.1, memSome10: 0.2, memSome60: 0.1, memFull10: 0.0, ioSome10: 2.1, ioSome60: 1.8, ioFull10: 0.4 },
diskReadIops: 420,
diskWriteIops: 180,
diskUtilPercent: 34,
diskQueueDepth: 2,
netRxPps: 1200,
netTxPps: 800,
tcpRetransmitsPerSec: 1.2,
fdUsed: 2048,
fdMax: 65536,
activeUsers: 2,
rebootRequired: true,
disks: [
{ mountPoint: '/', percent: 48, used: 96, total: 200, filesystemType: 'ext4', inodePercent: 31 },
],
},
};
const fullHtml = renderToStaticMarkup(
<OverviewTab
host={sampleHost}
state={richState}
interval={5}
range={15}
thresholds={DEFAULT_ALERT_THRESHOLDS}
locale="en"
t={createTranslator('en')}
/>,
);
assert.doesNotMatch(fullHtml, /<svg\b|<canvas\b/i);
assert.match(fullHtml, /CPU some/);
assert.match(fullHtml, /Inodes: 31%/);
assert.match(fullHtml, /Open FDs/);
assert.match(fullHtml, /NVIDIA L4/);
// Hide gpu + disks widgets via visibleWidgets
const filteredHtml = renderToStaticMarkup(
<OverviewTab
host={sampleHost}
state={richState}
interval={5}
range={15}
thresholds={DEFAULT_ALERT_THRESHOLDS}
visibleWidgets={['cpuBreakdown', 'memoryPsi']}
locale="en"
t={createTranslator('en')}
/>,
);
assert.equal((filteredHtml.match(/data-plugin-widget="metric-chart"/g) ?? []).length, 2);
assert.doesNotMatch(filteredHtml, /NVIDIA L4/);
});
-20
View File
@@ -1,20 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"types": ["node"]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"tests/**/*.ts",
"tests/**/*.tsx"
]
}
+43 -2
View File
@@ -529,8 +529,31 @@ test("node_modules packaging exclusions prune unused payloads while preserving l
"node_modules/foo/CHANGELOG.md",
"node_modules/foo/HISTORY.md",
"node_modules/@anthropic-ai/sdk/README.md",
"node_modules/bare-url/prebuilds/ios-arm64/bare-url.bare",
"node_modules/bare-fs/index.js",
"node_modules/bare-path/index.js",
"node_modules/bare-events/index.js",
"node_modules/bare-stream/index.js",
"node_modules/@anthropic-ai/claude-agent-sdk/assistant.mjs",
"node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs",
"node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js",
"node_modules/@anthropic-ai/claude-agent-sdk/extractFromBunfs.js",
"node_modules/@anthropic-ai/claude-agent-sdk/manifest.json",
"node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json",
"node_modules/node-pty/third_party/conpty/1.23.251008001/win10-x64/OpenConsole.exe",
"node_modules/node-pty/deps/winpty/src/include/winpty.h",
"node_modules/node-pty/src/unix/pty.cc",
"node_modules/node-pty/scripts/post-install.js",
"node_modules/node-pty/node-addon-api/napi.h",
"node_modules/node-pty/typings/node-pty.d.ts",
"node_modules/@serialport/bindings-cpp/src/serialport.cpp",
"node_modules/sqlite3/src/database.cc",
"node_modules/prebuild-install/index.js",
"node_modules/tar/index.js",
]) {
assert.equal(nmMac(path.join(root, dropped), stat), false, `expected excluded: ${dropped}`);
for (const [label, filter] of [["mac", nmMac], ["win", nmWin], ["linux", nmLinux]]) {
assert.equal(filter(path.join(root, dropped), stat), false, `expected excluded (${label}): ${dropped}`);
}
}
for (const kept of [
@@ -548,9 +571,20 @@ test("node_modules packaging exclusions prune unused payloads while preserving l
"node_modules/foo/NOTICE.md",
// @anthropic-ai/claude-agent-sdk declares "license": "SEE LICENSE IN README.md"
"node_modules/@anthropic-ai/claude-agent-sdk/README.md",
"node_modules/@anthropic-ai/claude-agent-sdk/LICENSE.md",
"node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs",
"node_modules/tar-stream/index.js",
"node_modules/node-pty/lib/index.js",
"node_modules/node-pty/build/Release/pty.node",
"node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
"node_modules/@serialport/bindings-cpp/dist/index.js",
"node_modules/@serialport/bindings-cpp/build/Release/bindings.node",
"node_modules/sqlite3/lib/sqlite3.js",
"node_modules/sqlite3/build/Release/node_sqlite3.node",
]) {
assert.equal(nmMac(path.join(root, kept), stat), true, `expected preserved: ${kept}`);
for (const [label, filter] of [["mac", nmMac], ["win", nmWin], ["linux", nmLinux]]) {
assert.equal(filter(path.join(root, kept), stat), true, `expected preserved (${label}): ${kept}`);
}
}
// Platform-scoped @vscode/windows-process-tree exclusion
@@ -591,6 +625,12 @@ test("app file exclusions prune dev schemas, test helpers/fixtures, svg sources,
"electron/bridges/cliDiscoveryTestIsolation.cjs",
"electron/bridges/sshBridge/serverStatsTestHelpers.cjs",
"electron/bridges/terminalBridge.moshConpty.integration.cjs",
"electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp",
"electron/preload.cjs",
"electron/preload/api.cjs",
"electron/entitlements.mac.plist",
"electron/launch.cjs",
"electron/plugins/distribution/README.md",
"dist/icon.svg",
"dist/tray-iconTemplate.svg",
]) {
@@ -599,6 +639,7 @@ test("app file exclusions prune dev schemas, test helpers/fixtures, svg sources,
assert.equal(macFilter(path.join(root, "dist/index.html"), stat), true);
assert.equal(macFilter(path.join(root, "electron/main.cjs"), stat), true);
assert.equal(macFilter(path.join(root, "electron/preload.bundle.cjs"), stat), true);
const macosVariantIcon = path.join(root, "dist/icons/variants/macos/icon.png");
assert.equal(macFilter(macosVariantIcon, stat), true);
+9 -2
View File
@@ -253,12 +253,19 @@ declare global {
},
): Promise<{ success: boolean; cwd?: string; error?: string; directoryState?: {
revision: number;
shellKind: 'powershell' | 'cmd' | 'git-bash';
pathFlavor: 'win32';
shellKind: 'powershell' | 'cmd' | 'git-bash' | 'wsl';
pathFlavor: 'win32' | 'posix';
provider: string;
cwd: string | null;
home: string | null;
} }>;
readWslSessionDirectory?(sessionId: string, operation: 'list' | 'realpath', path: string): Promise<{
success: boolean;
error?: 'unavailable' | 'readFailed' | 'accessDenied';
files?: Pick<import('../../domain/models').RemoteFile, 'name' | 'type' | 'linkTarget' | 'hidden'>[];
home?: string | null;
path?: string;
}>;
/**
* Get metadata about an already-connected SSH session — currently the
* SSH server identification string (the `software` part of the