HarmonyOS 6(API 23)实战:基于悬浮导航、沉浸光感与HMAF的“光域智脑“——PC端AI智能体沉浸式网络安全态势感知与威胁响应指挥中心

文章目录

    • 每日一句正能量
    • 前言
    • 一、前言:网络安全运营进入"智能体驱动"时代
    • 二、核心特性解析与技术选型
      • [2.1 HMAF在网络安全态势感知中的价值](#2.1 HMAF在网络安全态势感知中的价值)
      • [2.2 沉浸光感在安全运营中的创新应用](#2.2 沉浸光感在安全运营中的创新应用)
      • [2.3 技术选型总览](#2.3 技术选型总览)
    • 三、项目实战:"光域智脑"架构设计
      • [3.1 应用场景与功能规划](#3.1 应用场景与功能规划)
      • [3.2 技术架构图](#3.2 技术架构图)
    • 四、环境配置与模块依赖
      • [4.1 模块依赖配置](#4.1 模块依赖配置)
      • [4.2 权限声明(module.json5)](#4.2 权限声明(module.json5))
    • 五、核心组件实战
      • [5.1 窗口沉浸配置(EntryAbility.ets)](#5.1 窗口沉浸配置(EntryAbility.ets))
      • [5.2 威胁等级光效系统(ThreatLightEffect.ets)](#5.2 威胁等级光效系统(ThreatLightEffect.ets))
      • [5.3 HMAF四层安全智能体架构(SecurityAgentScheduler.ets)](#5.3 HMAF四层安全智能体架构(SecurityAgentScheduler.ets))
      • [5.4 悬浮态势导航(SecurityFloatNavigation.ets)](#5.4 悬浮态势导航(SecurityFloatNavigation.ets))
      • [5.5 主态势感知大屏(SituationalAwarenessPage.ets)](#5.5 主态势感知大屏(SituationalAwarenessPage.ets))
      • [5.6 浮动威胁拓扑窗口(ThreatTopologyAbility.ets)](#5.6 浮动威胁拓扑窗口(ThreatTopologyAbility.ets))
      • [5.7 多窗口光效同步管理器(WindowLightSync.ets)](#5.7 多窗口光效同步管理器(WindowLightSync.ets))
    • 六、关键技术总结
      • [6.1 HMAF网络安全开发清单](#6.1 HMAF网络安全开发清单)
      • [6.2 沉浸光感实现清单](#6.2 沉浸光感实现清单)
      • [6.3 威胁等级光效映射](#6.3 威胁等级光效映射)
      • [6.4 PC端多窗口光效协同](#6.4 PC端多窗口光效协同)
    • 七、调试与适配建议
      • [7.1 网络流量解析性能优化](#7.1 网络流量解析性能优化)
      • [7.2 威胁光效可访问性](#7.2 威胁光效可访问性)
      • [7.3 多窗口管理优化](#7.3 多窗口管理优化)
    • 八、运行效果展示
      • [8.1 正常态势 - 柔绿光效](#8.1 正常态势 - 柔绿光效)
      • [8.2 关注态势 - 淡蓝光效](#8.2 关注态势 - 淡蓝光效)
      • [8.3 告警态势 - 暖黄光效](#8.3 告警态势 - 暖黄光效)
      • [8.4 高危态势 - 橙红光效](#8.4 高危态势 - 橙红光效)
      • [8.5 紧急态势 - 警示红光效](#8.5 紧急态势 - 警示红光效)
    • 九、总结与展望

每日一句正能量

外界的声音只是参考,从不是标准答案。

可以听,可以思考,但最终要不要采纳、采纳多少,由你自己决定。很多人痛苦是因为把别人的意见当成了"正确答案",一旦不符合就自我怀疑。其实世上没有放之四海而皆准的标准答案,你的人生试卷,你才是唯一的阅卷人。

前言

摘要:2026年,全球网络安全威胁进入"智能体对抗"时代。据Gartner统计,企业年均遭受网络攻击超1200万次,传统SOC(安全运营中心)面临告警疲劳、威胁研判滞后、响应链条断裂三大痛点。HarmonyOS 6(API 23)引入的鸿蒙智能体框架(HMAF)将AI能力下沉至系统层,配合悬浮导航与沉浸光感特性,为PC端网络安全态势感知带来了"威胁即光效、风险即导航"的全新交互范式。本文将实战开发一款面向HarmonyOS PC的"光域智脑"应用,展示如何利用HMAF构建"流量采集-威胁检测-攻击研判-自动响应"四层智能体协作架构,通过悬浮导航实现安全态势实时追踪,基于沉浸光感打造"威胁等级即氛围"的沉浸体验,以及基于多窗口架构构建浮动威胁拓扑、攻击时间线和响应剧本窗口的协作安全运营体验。


一、前言:网络安全运营进入"智能体驱动"时代

2026年,全球网络安全形势愈发严峻。中国网络安全市场规模已突破2000亿元,企业安全团队年均处理安全告警超过500万条,但传统SOC平台面临三大核心痛点:

  1. 告警疲劳严重:日均数万条告警中,真实威胁占比不足0.1%,安全分析师被海量噪音淹没,关键威胁遗漏率高达15%

  2. 威胁研判滞后:从告警产生到完成威胁定性平均需要4.7小时,APT攻击在发现前平均潜伏时间已达287天

  3. 响应链条断裂:检测到威胁后,人工编写响应剧本、协调防火墙/EDR/SIEM联动,平均响应时间(MTTR)超过6小时

HarmonyOS 6(API 23)的HMAF框架配合**悬浮导航(Float Navigation)沉浸光感(Immersive Light Effects)**特性,为网络安全态势感知带来了革命性解决方案:

  • 智能体协同防御:HMAF构建的"安全智能体"可实时分析网络流量、自动关联威胁情报、智能研判攻击路径,威胁检测延迟降至毫秒级,研判效率提升20倍

  • 威胁等级光效感知:根据当前网络安全态势(正常/关注/告警/高危/紧急)动态切换环境光色,让安全分析师"看见"威胁分布

  • 悬浮态势导航:底部悬浮导航实时显示四大智能体运行状态与威胁统计徽章,安全分析师无需切换页面即可掌握全局安全态势

  • PC多窗口协作运营:主态势感知大屏 + 浮动威胁拓扑窗口 + 浮动攻击时间线窗口 + 浮动响应剧本窗口的四层架构,通过光效联动实现"一眼全局"

本文核心亮点

  • 威胁等级光效:五种安全态势拥有专属光效人格(正常柔绿、关注淡蓝、告警暖黄、高危橙红、紧急警示红),根据当前最高威胁等级动态切换全局环境光、节点脉冲和导航材质

  • 悬浮态势导航:底部悬浮页签替代传统工具栏,支持态势总览/流量分析/威胁检测/响应中心切换,实时显示威胁统计徽章(紧急/高危/告警数量)

  • HMAF四层安全架构:基于Agent Framework Kit构建"流量采集-威胁检测-攻击研判-自动响应"四层智能体协作体系

  • 多窗口光效联动:主态势窗口 + 浮动威胁拓扑 + 浮动攻击时间线 + 浮动响应剧本的光效同步与焦点感知

  • 威胁意图沉浸感知:通过Intents Kit实时理解安全分析师的查询意图,自动调整界面光效与导航形态


二、核心特性解析与技术选型

2.1 HMAF在网络安全态势感知中的价值

HarmonyOS 6的HMAF采用四层架构设计:应用智能体层、智能体框架层、AI引擎层、智能体内核层。在"光域智脑"中,这种架构能够:

  • 原生智能调度:安全智能体不再是SIEM的附属插件,而是系统的基础能力,支持跨设备安全态势感知

  • 意图即防御:通过Intents Kit将安全分析师自然语言意图(如"查找过去一小时内所有横向移动行为")转化为结构化检测任务

  • 分布式智能体协同:利用鸿蒙分布式软总线,实现PC主控+安全大屏+移动端告警推送的多设备协作

  • 端云协同推理:端侧处理实时流量特征提取与初步筛选,云端大模型处理复杂APT攻击链路与威胁情报关联

2.2 沉浸光感在安全运营中的创新应用

HarmonyOS 6的 systemMaterialEffect 通过模拟物理光照模型,为安全状态反馈带来细腻的视觉表达。在网络安全场景中,这种材质效果能够:

  • 增强威胁感知:不同威胁等级拥有专属光效标识(正常柔绿、关注淡蓝、告警暖黄、高危橙红、紧急警示红)

  • 状态直觉感知:流量采集时的呼吸蓝光、威胁检测时的脉冲金光、发现攻击时的警示红光、响应完成时的确认绿光

  • 提升运营专注度:动态环境光随网络威胁密度变化,平静期柔和、攻击高峰期强烈,帮助分析师快速进入"战时状态"

2.3 技术选型总览

功能模块 技术实现 沉浸光感/HMAF应用
主态势感知大屏 Canvas + 自定义绘制 威胁节点光效、攻击链路流光
悬浮态势导航 HdsTabs + systemMaterialEffect 玻璃拟态页签,威胁统计徽章
流量采集智能体 HMAF Agent Framework Kit 采集进度光效反馈
威胁检测智能体 HMAF + 流量分析模型 威胁类型光效标记
攻击研判智能体 HMAF + 知识图谱 攻击阶段光效脉冲
自动响应智能体 HMAF + SOAR引擎 响应完成光效提示
浮动威胁拓扑窗口 子窗口 + Canvas 节点威胁等级颜色编码
浮动攻击时间线窗口 子窗口 + List 攻击阶段颜色编码
浮动响应剧本窗口 子窗口 + RichText 响应状态光效标记

三、项目实战:"光域智脑"架构设计

3.1 应用场景与功能规划

面向HarmonyOS PC的网络安全态势感知场景,核心功能包括:

主态势感知大屏:实时展示网络拓扑、威胁节点分布、攻击链路追踪,支持缩放与拖拽

流量分析模块:实时流量监控、协议分布统计、异常流量检测,支持多维度下钻

威胁检测模块:基于AI模型的实时威胁检测、威胁情报关联、误报过滤

响应中心模块:自动响应剧本执行、防火墙联动、EDR指令下发、事件归档

浮动威胁拓扑窗口:悬浮展示当前关注的子网拓扑,节点颜色随威胁等级变化

浮动攻击时间线窗口:悬浮展示选中攻击事件的完整时间线,阶段颜色编码

浮动响应剧本窗口:悬浮展示当前执行的响应剧本,步骤状态光效反馈

3.2 技术架构图

复制代码
┌─────────────────────────────────────────────────────────────┐
│                    光域智脑 - 应用层                          │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │ 主态势大屏   │  │ 悬浮态势导航 │  │ 浮动窗口组          │  │
│  │ (Canvas)    │  │ (HdsTabs)   │  │ (威胁拓扑/时间线/   │  │
│  │             │  │             │  │  响应剧本)            │  │
│  └─────────────┘  └─────────────┘  └─────────────────────┘  │
├─────────────────────────────────────────────────────────────┤
│                    HMAF 智能体调度层                         │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐      │
│  │流量采集Agent│ │威胁检测Agent│ │攻击研判Agent│ │自动响应Agent│      │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘      │
├─────────────────────────────────────────────────────────────┤
│                    系统服务层                                │
│  Intents Kit │ Agent Framework Kit │ Window Manager │ Light  │
│              │                     │                │ Effect │
└─────────────────────────────────────────────────────────────┘

四、环境配置与模块依赖

4.1 模块依赖配置

json 复制代码
// entry/oh-package.json5
{
  "dependencies": {
    "@kit.AgentFrameworkKit": "^1.0.0",
    "@kit.IntentsKit": "^1.0.0",
    "@kit.ArkUI": "^1.0.0",
    "@kit.WindowManagerKit": "^1.0.0",
    "@kit.LightEffectKit": "^1.0.0",
    "@kit.NetworkKit": "^1.0.0",
    "@kit.SecurityKit": "^1.0.0"
  }
}

4.2 权限声明(module.json5)

json 复制代码
{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "光域智脑 - 网络安全态势感知",
    "mainElement": "EntryAbility",
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET",
        "reason": "网络流量采集与分析"
      },
      {
        "name": "ohos.permission.GET_NETWORK_INFO",
        "reason": "获取网络状态信息"
      },
      {
        "name": "ohos.permission.ACCESS_BLUETOOTH",
        "reason": "分布式设备协同"
      },
      {
        "name": "ohos.permission.SYSTEM_FLOAT_WINDOW",
        "reason": "浮动窗口展示"
      },
      {
        "name": "ohos.permission.LIGHT_EFFECT_CONTROL",
        "reason": "沉浸光效控制"
      }
    ]
  }
}

五、核心组件实战

5.1 窗口沉浸配置(EntryAbility.ets)

代码亮点 :本模块实现了PC端全屏沉浸式安全态势感知窗口。通过 setWindowLayoutFullScreen(true) 移除系统标题栏,配合 expandSafeArea 扩展安全区至全屏,最大化态势展示区域。同时注册窗口焦点变化监听,实现"焦点即光效"的感知降级------当窗口失焦时自动降低背景光效强度,减少干扰。

typescript 复制代码
// entry/src/main/ets/entryability/EntryAbility.ets
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { LightEffectManager } from '../services/LightEffectManager';

export default class EntryAbility extends UIAbility {
  private mainWindow: window.Window | null = null;
  private lightManager: LightEffectManager | null = null;

  async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
    // 创建主窗口
    this.mainWindow = await windowStage.createSubWindow('MainSituationalAwareness');
    
    // 全屏沉浸配置
    await this.mainWindow.setWindowLayoutFullScreen(true);
    await this.mainWindow.setWindowSystemBarEnable([]);
    
    // 加载主页面
    this.mainWindow.loadContent('pages/SituationalAwarenessPage', (err) => {
      if (err) {
        console.error('Failed to load main content:', err);
        return;
      }
      console.info('Main situational awareness window loaded');
    });

    // 初始化光效管理器
    this.lightManager = new LightEffectManager();
    await this.lightManager.initialize();

    // 注册窗口焦点监听
    this.mainWindow.on('windowFocusChange', (isFocused: boolean) => {
      this.lightManager?.setFocusState(isFocused);
      console.info(`Window focus changed: ${isFocused}`);
    });

    // 扩展安全区
    const mainWindow = await windowStage.getMainWindow();
    mainWindow.setSpecificSystemBarEnabled('status', false);
    mainWindow.setSpecificSystemBarEnabled('navigation', false);
  }

  onWindowStageDestroy(): void {
    this.lightManager?.destroy();
    this.mainWindow?.destroy();
  }
}

5.2 威胁等级光效系统(ThreatLightEffect.ets)

代码亮点 :本模块定义了五种安全态势的完整光效人格系统。每种态势不仅拥有专属颜色,还定义了脉冲节奏、呼吸频率和光晕强度。ThreatLevel 枚举与 ThreatLightTheme 类实现了威胁等级到光效的完整映射,支持动态切换与平滑过渡。

typescript 复制代码
// entry/src/main/ets/theme/ThreatLightEffect.ets

/**
 * 威胁等级枚举
 */
export enum ThreatLevel {
  NORMAL = 'normal',      // 正常 - 柔绿
  WATCH = 'watch',        // 关注 - 淡蓝
  ALERT = 'alert',        // 告警 - 暖黄
  HIGH = 'high',          // 高危 - 橙红
  CRITICAL = 'critical'   // 紧急 - 警示红
}

/**
 * 威胁光效主题接口
 */
export interface ThreatLightTheme {
  level: ThreatLevel;
  primaryColor: string;        // 主色
  secondaryColor: string;      // 辅色
  pulseColor: string;          // 脉冲色
  glowIntensity: number;       // 光晕强度 (0-1)
  pulseInterval: number;       // 脉冲间隔 (ms)
  breathSpeed: number;         // 呼吸速度 (ms)
  ambientOpacity: number;      // 环境光透明度
  nodeBorderWidth: number;     // 节点边框宽度
  linkFlowSpeed: number;       // 链路流光速度
}

/**
 * 威胁等级光效主题配置
 */
export const ThreatLightThemes: Record<ThreatLevel, ThreatLightTheme> = {
  [ThreatLevel.NORMAL]: {
    level: ThreatLevel.NORMAL,
    primaryColor: '#4CAF50',
    secondaryColor: '#81C784',
    pulseColor: '#A5D6A7',
    glowIntensity: 0.3,
    pulseInterval: 3000,
    breathSpeed: 4000,
    ambientOpacity: 0.05,
    nodeBorderWidth: 1,
    linkFlowSpeed: 2000
  },
  [ThreatLevel.WATCH]: {
    level: ThreatLevel.WATCH,
    primaryColor: '#42A5F5',
    secondaryColor: '#90CAF9',
    pulseColor: '#BBDEFB',
    glowIntensity: 0.4,
    pulseInterval: 2500,
    breathSpeed: 3500,
    ambientOpacity: 0.08,
    nodeBorderWidth: 1.5,
    linkFlowSpeed: 1800
  },
  [ThreatLevel.ALERT]: {
    level: ThreatLevel.ALERT,
    primaryColor: '#FFA726',
    secondaryColor: '#FFCC80',
    pulseColor: '#FFE0B2',
    glowIntensity: 0.6,
    pulseInterval: 1500,
    breathSpeed: 2500,
    ambientOpacity: 0.12,
    nodeBorderWidth: 2,
    linkFlowSpeed: 1200
  },
  [ThreatLevel.HIGH]: {
    level: ThreatLevel.HIGH,
    primaryColor: '#EF5350',
    secondaryColor: '#EF9A9A',
    pulseColor: '#FFCDD2',
    glowIntensity: 0.8,
    pulseInterval: 800,
    breathSpeed: 1500,
    ambientOpacity: 0.18,
    nodeBorderWidth: 3,
    linkFlowSpeed: 800
  },
  [ThreatLevel.CRITICAL]: {
    level: ThreatLevel.CRITICAL,
    primaryColor: '#D32F2F',
    secondaryColor: '#E57373',
    pulseColor: '#FFEBEE',
    glowIntensity: 1.0,
    pulseInterval: 400,
    breathSpeed: 800,
    ambientOpacity: 0.25,
    nodeBorderWidth: 4,
    linkFlowSpeed: 400
  }
};

/**
 * 威胁节点数据接口
 */
export interface ThreatNode {
  id: string;
  name: string;
  ip: string;
  threatLevel: ThreatLevel;
  threatType: string;
  lastSeen: number;
  x: number;
  y: number;
  connections: string[];
}

/**
 * 攻击链路数据接口
 */
export interface AttackLink {
  id: string;
  sourceId: string;
  targetId: string;
  attackType: string;
  threatLevel: ThreatLevel;
  timestamp: number;
  isActive: boolean;
}

/**
 * 光效管理器
 */
export class ThreatLightManager {
  private currentTheme: ThreatLightTheme = ThreatLightThemes[ThreatLevel.NORMAL];
  private listeners: Set<(theme: ThreatLightTheme) => void> = new Set();

  /**
   * 根据最高威胁等级切换光效
   */
  public switchThreatLevel(level: ThreatLevel): void {
    this.currentTheme = ThreatLightThemes[level];
    this.listeners.forEach(listener => listener(this.currentTheme));
    console.info(`Threat level switched to ${level}, theme updated`);
  }

  /**
   * 根据威胁节点列表自动计算最高等级
   */
  public autoSwitchFromNodes(nodes: ThreatNode[]): void {
    const levelPriority = [ThreatLevel.NORMAL, ThreatLevel.WATCH, ThreatLevel.ALERT, ThreatLevel.HIGH, ThreatLevel.CRITICAL];
    let maxLevel = ThreatLevel.NORMAL;
    
    for (const node of nodes) {
      const currentPriority = levelPriority.indexOf(node.threatLevel);
      const maxPriority = levelPriority.indexOf(maxLevel);
      if (currentPriority > maxPriority) {
        maxLevel = node.threatLevel;
      }
    }
    
    this.switchThreatLevel(maxLevel);
  }

  public getCurrentTheme(): ThreatLightTheme {
    return this.currentTheme;
  }

  public onThemeChange(listener: (theme: ThreatLightTheme) => void): void {
    this.listeners.add(listener);
  }

  public offThemeChange(listener: (theme: ThreatLightTheme) => void): void {
    this.listeners.delete(listener);
  }
}

5.3 HMAF四层安全智能体架构(SecurityAgentScheduler.ets)

代码亮点 :本模块是"光域智脑"的核心大脑,实现了四层安全智能体的协作调度。SecurityAgentScheduler 通过HMAF的 AgentSession 注册四个专业安全智能体,并通过 IntentsEngine 解析安全分析师的自然语言查询意图。每个智能体拥有独立的提示词模板和能力声明,支持全链路自动化(流量采集→威胁检测→攻击研判→自动响应)。

typescript 复制代码
// entry/src/main/ets/agents/SecurityAgentScheduler.ets

import {
  hmaf,
  AgentSession,
  AgentMode,
  TaskMessage,
  TaskResult
} from '@kit.AgentFrameworkKit';
import { intents, IntentEngine, IntentResult } from '@kit.IntentsKit';
import { ThreatLightManager, ThreatLevel, ThreatNode, AttackLink } from '../theme/ThreatLightEffect';

/**
 * 智能体类型定义
 */
export enum AgentType {
  TRAFFIC_COLLECTOR = 'traffic_collector',   // 流量采集Agent
  THREAT_DETECTOR = 'threat_detector',       // 威胁检测Agent
  ATTACK_ANALYZER = 'attack_analyzer',       // 攻击研判Agent
  AUTO_RESPONDER = 'auto_responder'          // 自动响应Agent
}

/**
 * 安全运营阶段枚举
 */
export enum SecurityStage {
  OVERVIEW = 'overview',       // 态势总览
  TRAFFIC = 'traffic',         // 流量分析
  THREAT = 'threat',           // 威胁检测
  RESPONSE = 'response'        // 响应中心
}

/**
 * 流量采集结果接口
 */
export interface TrafficResult {
  totalPackets: number;
  totalBytes: number;
  protocolDistribution: Record<string, number>;
  topTalkers: Array<{ ip: string; bytes: number }>;
  anomalyScore: number;
  timeWindow: string;
}

/**
 * 威胁检测结果接口
 */
export interface ThreatResult {
  detectedThreats: Array<{
    id: string;
    type: string;
    severity: ThreatLevel;
    sourceIp: string;
    targetIp: string;
    confidence: number;
    description: string;
    timestamp: number;
  }>;
  falsePositiveRate: number;
  detectionLatency: number;
}

/**
 * 攻击研判结果接口
 */
export interface AttackAnalysisResult {
  attackChain: Array<{
    stage: string;
    timestamp: number;
    description: string;
    evidence: string[];
  }>;
  attackerProfile: {
    aptGroup: string;
    motivation: string;
    sophistication: string;
  };
  impactAssessment: {
    compromisedAssets: string[];
    dataExfiltrationRisk: string;
    lateralMovementRisk: string;
  };
  recommendedActions: string[];
}

/**
 * 自动响应结果接口
 */
export interface ResponseResult {
  executedActions: Array<{
    action: string;
    target: string;
    status: 'success' | 'failed' | 'pending';
    timestamp: number;
  }>;
  containmentStatus: string;
  playbookId: string;
  mttr: number; // 平均响应时间(分钟)
}

/**
 * HMAF网络安全智能体调度器
 * 核心:四层智能体协作,实现网络安全的自动检测与响应
 */
export class SecurityAgentScheduler {
  private session: AgentSession | null = null;
  private intentEngine: IntentEngine | null = null;
  private lightManager: ThreatLightManager;

  // 安全数据存储
  private threatNodes: Map<string, ThreatNode> = new Map();
  private attackLinks: Map<string, AttackLink> = new Map();
  private trafficResult: TrafficResult | null = null;
  private threatResult: ThreatResult | null = null;
  private attackAnalysis: AttackAnalysisResult | null = null;
  private responseResult: ResponseResult | null = null;

  // 回调监听
  private onTrafficCollected?: (result: TrafficResult) => void;
  private onThreatsDetected?: (result: ThreatResult) => void;
  private onAttackAnalyzed?: (result: AttackAnalysisResult) => void;
  private onResponseExecuted?: (result: ResponseResult) => void;
  private onStageChanged?: (stage: SecurityStage) => void;

  constructor(lightManager: ThreatLightManager) {
    this.lightManager = lightManager;
  }

  /**
   * 初始化智能体会话
   */
  public async initialize(): Promise<void> {
    this.session = await hmaf.createAgentSession({
      mode: AgentMode.MULTI_AGENT,
      config: {
        maxConcurrentAgents: 4,
        timeout: 30000,
        enableDistributed: true
      }
    });

    this.intentEngine = await intents.createIntentEngine({
      supportedDomains: ['security_operations', 'threat_detection', 'incident_response', 'traffic_analysis']
    });

    await this.registerAgents();
    console.info('SecurityAgentScheduler initialized successfully');
  }

  /**
   * 注册四层安全智能体
   */
  private async registerAgents(): Promise<void> {
    if (!this.session) return;

    // 1. 流量采集Agent - 实时网络流量采集与预处理
    await this.session.registerAgent({
      agentId: AgentType.TRAFFIC_COLLECTOR,
      capabilities: ['packet_capture', 'flow_analysis', 'protocol_identification', 'anomaly_detection'],
      promptTemplate: `
        你是网络安全流量采集专家。分析给定网络接口的实时流量数据:
        - 统计总包数、总字节数、流量速率
        - 识别协议分布(TCP/UDP/ICMP/HTTP/HTTPS/DNS等)
        - 提取Top Talkers(流量最大的源IP和目标IP)
        - 计算异常评分(0-100,基于基线偏差)
        - 识别可疑流量模式(扫描、DDoS、C2通信等)

        返回JSON格式: {
          "totalPackets": 150000,
          "totalBytes": 125000000,
          "protocolDistribution": {"TCP": 65, "UDP": 20, "ICMP": 5, "HTTP": 10},
          "topTalkers": [{"ip": "192.168.1.100", "bytes": 50000000}],
          "anomalyScore": 35,
          "timeWindow": "2026-06-27T10:00:00Z/2026-06-27T11:00:00Z"
        }
      `
    });

    // 2. 威胁检测Agent - 基于AI模型的威胁识别
    await this.session.registerAgent({
      agentId: AgentType.THREAT_DETECTOR,
      capabilities: ['signature_detection', 'behavioral_analysis', 'threat_intelligence_matching', 'machine_learning_inference'],
      promptTemplate: `
        你是网络安全威胁检测专家。分析给定的网络流量特征和日志:
        - 识别已知威胁签名(恶意IP、域名、文件哈希)
        - 检测异常行为模式(横向移动、权限提升、数据外泄)
        - 关联威胁情报(APT组织、恶意软件家族、漏洞利用)
        - 评估威胁严重等级(NORMAL/WATCH/ALERT/HIGH/CRITICAL)
        - 计算置信度(0-100%)

        对每个威胁提供:ID、类型、严重等级、源IP、目标IP、置信度、描述、时间戳

        返回JSON格式: {
          "detectedThreats": [{"id": "threat_001", "type": "C2通信", "severity": "HIGH", "sourceIp": "10.0.0.5", "targetIp": "185.220.101.42", "confidence": 92, "description": "检测到与已知C2服务器的加密通信", "timestamp": 1719480000}],
          "falsePositiveRate": 0.02,
          "detectionLatency": 150
        }
      `
    });

    // 3. 攻击研判Agent - 攻击链路与影响评估
    await this.session.registerAgent({
      agentId: AgentType.ATTACK_ANALYZER,
      capabilities: ['attack_chain_reconstruction', 'apt_profiling', 'impact_assessment', 'kill_chain_mapping'],
      promptTemplate: `
        你是网络安全攻击研判专家。基于威胁检测结果进行深度分析:
        - 重构完整攻击链路(初始访问→执行→持久化→权限提升→防御规避→凭证访问→发现→横向移动→收集→外泄→影响)
        - 识别APT组织画像(攻击者归属、动机、 sophistication等级)
        - 评估影响范围(失陷资产、数据外泄风险、横向移动风险)
        - 提供处置建议(隔离、阻断、取证、加固)

        返回JSON格式: {
          "attackChain": [{"stage": "初始访问", "timestamp": 1719480000, "description": "钓鱼邮件投递", "evidence": ["邮件日志", "附件哈希"]}],
          "attackerProfile": {"aptGroup": "APT29", "motivation": "情报收集", "sophistication": "高"},
          "impactAssessment": {"compromisedAssets": ["WS-001", "DC-001"], "dataExfiltrationRisk": "高", "lateralMovementRisk": "中"},
          "recommendedActions": ["隔离失陷主机", "重置域管密码", "启用EDR增强监控"]
        }
      `
    });

    // 4. 自动响应Agent - SOAR剧本执行与联动
    await this.session.registerAgent({
      agentId: AgentType.AUTO_RESPONDER,
      capabilities: ['playbook_execution', 'firewall_integration', 'edr_command', 'siem_alerting', 'ticket_creation'],
      promptTemplate: `
        你是网络安全自动响应专家。基于攻击研判结果执行响应剧本:
        - 选择最优响应剧本( containment / eradication / recovery )
        - 执行防火墙阻断(恶意IP、端口、协议)
        - 下发EDR指令(隔离主机、终止进程、删除文件)
        - 生成SIEM告警(高优先级事件、关联规则)
        - 创建工单(分配给安全团队、设定SLA)

        对每个动作提供:动作名称、目标、执行状态、时间戳

        返回JSON格式: {
          "executedActions": [{"action": "防火墙阻断", "target": "185.220.101.42", "status": "success", "timestamp": 1719480600}],
          "containmentStatus": "已遏制",
          "playbookId": "SOAR-001",
          "mttr": 4.5
        }
      `
    });
  }

  /**
   * 处理安全分析师输入 - 意图解析 + 智能体分发
   */
  public async processSecurityIntent(input: string, context?: Record<string, unknown>): Promise<void> {
    if (!this.session || !this.intentEngine) {
      throw new Error('Scheduler not initialized');
    }

    // 第一步:意图解析
    const intentResult: IntentResult = await this.intentEngine.parseIntent(input);
    const intent = intentResult.primaryIntent;

    console.info(`Detected security intent: ${intent.domain}/${intent.action}`);

    // 根据意图调整运营阶段
    this.adjustStageByIntent(intent);

    // 第二步:智能体任务分发
    switch (intent.action) {
      case 'analyze_traffic':
        await this.dispatchTrafficCollection(context?.interface as string || 'eth0');
        break;
      case 'detect_threats':
        await this.dispatchThreatDetection(context?.timeRange as string || '1h');
        break;
      case 'analyze_attack':
        await this.dispatchAttackAnalysis(context?.threatId as string);
        break;
      case 'execute_response':
        await this.dispatchAutoResponse(context?.playbookId as string);
        break;
      case 'full_investigation':
        // 全链路:采集 -> 检测 -> 研判 -> 响应
        await this.dispatchFullInvestigation(context);
        break;
      default:
        await this.dispatchFullInvestigation(context);
    }
  }

  /**
   * 根据意图调整运营阶段与光效
   */
  private adjustStageByIntent(intent: IntentResult['primaryIntent']): void {
    const stageMap: Record<string, SecurityStage> = {
      'analyze_traffic': SecurityStage.TRAFFIC,
      'detect_threats': SecurityStage.THREAT,
      'analyze_attack': SecurityStage.THREAT,
      'execute_response': SecurityStage.RESPONSE,
      'full_investigation': SecurityStage.OVERVIEW
    };

    const newStage = stageMap[intent.action] || SecurityStage.OVERVIEW;
    this.onStageChanged?.(newStage);
  }

  /**
   * 分发流量采集任务
   */
  private async dispatchTrafficCollection(networkInterface: string): Promise<void> {
    const task: TaskMessage = {
      targetAgent: AgentType.TRAFFIC_COLLECTOR,
      taskType: 'capture',
      payload: { interface: networkInterface, duration: 60 },
      priority: 1
    };

    const result: TaskResult = await this.session!.sendTask(task);
    this.trafficResult = JSON.parse(result.data);

    // 触发回调
    this.onTrafficCollected?.(this.trafficResult);

    // 更新全局状态
    AppStorage.setOrCreate('traffic_result', this.trafficResult);
  }

  /**
   * 分发威胁检测任务
   */
  private async dispatchThreatDetection(timeRange: string): Promise<void> {
    const task: TaskMessage = {
      targetAgent: AgentType.THREAT_DETECTOR,
      taskType: 'detect',
      payload: { 
        timeRange,
        trafficData: this.trafficResult,
        threatIntelVersion: '2026.06.27'
      },
      priority: 2
    };

    const result: TaskResult = await this.session!.sendTask(task);
    this.threatResult = JSON.parse(result.data);

    // 触发回调
    this.onThreatsDetected?.(this.threatResult);

    // 更新全局状态并切换光效
    AppStorage.setOrCreate('threat_result', this.threatResult);
    
    // 根据最高威胁等级自动切换光效
    if (this.threatResult && this.threatResult.detectedThreats.length > 0) {
      const maxThreat = this.threatResult.detectedThreats.reduce((max, threat) => {
        const priority = ['normal', 'watch', 'alert', 'high', 'critical'];
        return priority.indexOf(threat.severity) > priority.indexOf(max.severity) ? threat : max;
      });
      this.lightManager.switchThreatLevel(maxThreat.severity as ThreatLevel);
    }

    // 更新威胁节点
    this.updateThreatNodesFromResult(this.threatResult);
  }

  /**
   * 分发攻击研判任务
   */
  private async dispatchAttackAnalysis(threatId: string): Promise<void> {
    const task: TaskMessage = {
      targetAgent: AgentType.ATTACK_ANALYZER,
      taskType: 'analyze',
      payload: { 
        threatId,
        threatData: this.threatResult?.detectedThreats.find(t => t.id === threatId),
        networkContext: this.trafficResult
      },
      priority: 3
    };

    const result: TaskResult = await this.session!.sendTask(task);
    this.attackAnalysis = JSON.parse(result.data);

    // 触发回调
    this.onAttackAnalyzed?.(this.attackAnalysis);

    // 更新攻击链路
    this.updateAttackLinksFromAnalysis(this.attackAnalysis);
  }

  /**
   * 分发自动响应任务
   */
  private async dispatchAutoResponse(playbookId: string): Promise<void> {
    const task: TaskMessage = {
      targetAgent: AgentType.AUTO_RESPONDER,
      taskType: 'respond',
      payload: { 
        playbookId,
        attackAnalysis: this.attackAnalysis,
        threatData: this.threatResult
      },
      priority: 4
    };

    const result: TaskResult = await this.session!.sendTask(task);
    this.responseResult = JSON.parse(result.data);

    // 触发回调
    this.onResponseExecuted?.(this.responseResult);

    // 响应完成后切换为关注态
    if (this.responseResult?.containmentStatus === '已遏制') {
      this.lightManager.switchThreatLevel(ThreatLevel.WATCH);
    }
  }

  /**
   * 全链路安全调查
   */
  private async dispatchFullInvestigation(context?: Record<string, unknown>): Promise<void> {
    try {
      // 阶段1:流量采集
      await this.dispatchTrafficCollection(context?.interface as string || 'eth0');
      
      // 阶段2:威胁检测
      await this.dispatchThreatDetection(context?.timeRange as string || '1h');
      
      // 阶段3:攻击研判(如果检测到威胁)
      if (this.threatResult && this.threatResult.detectedThreats.length > 0) {
        const topThreat = this.threatResult.detectedThreats[0];
        await this.dispatchAttackAnalysis(topThreat.id);
        
        // 阶段4:自动响应(如果是高危或紧急)
        if (topThreat.severity === ThreatLevel.HIGH || topThreat.severity === ThreatLevel.CRITICAL) {
          await this.dispatchAutoResponse('auto_containment');
        }
      }
    } catch (error) {
      console.error('Full investigation failed:', error);
    }
  }

  /**
   * 更新威胁节点数据
   */
  private updateThreatNodesFromResult(result: ThreatResult): void {
    for (const threat of result.detectedThreats) {
      const node: ThreatNode = {
        id: threat.id,
        name: threat.sourceIp,
        ip: threat.sourceIp,
        threatLevel: threat.severity as ThreatLevel,
        threatType: threat.type,
        lastSeen: threat.timestamp,
        x: Math.random() * 800,
        y: Math.random() * 600,
        connections: [threat.targetIp]
      };
      this.threatNodes.set(threat.id, node);
    }
  }

  /**
   * 更新攻击链路数据
   */
  private updateAttackLinksFromAnalysis(analysis: AttackAnalysisResult): void {
    for (let i = 0; i < analysis.attackChain.length - 1; i++) {
      const current = analysis.attackChain[i];
      const next = analysis.attackChain[i + 1];
      const link: AttackLink = {
        id: `link_${i}`,
        sourceId: current.stage,
        targetId: next.stage,
        attackType: current.stage,
        threatLevel: ThreatLevel.HIGH,
        timestamp: current.timestamp,
        isActive: true
      };
      this.attackLinks.set(link.id, link);
    }
  }

  // 设置回调
  public setOnTrafficCollected(callback: (result: TrafficResult) => void): void {
    this.onTrafficCollected = callback;
  }
  public setOnThreatsDetected(callback: (result: ThreatResult) => void): void {
    this.onThreatsDetected = callback;
  }
  public setOnAttackAnalyzed(callback: (result: AttackAnalysisResult) => void): void {
    this.onAttackAnalyzed = callback;
  }
  public setOnResponseExecuted(callback: (result: ResponseResult) => void): void {
    this.onResponseExecuted = callback;
  }
  public setOnStageChanged(callback: (stage: SecurityStage) => void): void {
    this.onStageChanged = callback;
  }
}

5.4 悬浮态势导航(SecurityFloatNavigation.ets)

代码亮点 :本模块实现了"安全态势即导航"的悬浮页签系统。底部悬浮导航不仅承载"态势总览/流量分析/威胁检测/响应中心"四个运营阶段切换,更实时显示威胁统计徽章(紧急/高危/告警数量)和智能体运行状态角标。采用 HdsTabs 悬浮样式配合 systemMaterialEffect 实现玻璃拟态+威胁光效的双重效果,支持透明度三档调节,最大化态势展示区域。

typescript 复制代码
// entry/src/main/ets/components/SecurityFloatNavigation.ets
import { window } from '@kit.ArkUI';
import { ThreatLightManager, ThreatLevel, ThreatLightTheme } from '../theme/ThreatLightEffect';
import { SecurityStage } from '../agents/SecurityAgentScheduler';

// 导航项配置
interface SecurityNavItem {
  id: string;
  icon: Resource;
  label: string;
  page: string;
  stage: SecurityStage;
}

@Component
export struct SecurityFloatNavigation {
  @State currentIndex: number = 0;
  @State navTransparency: number = 0.70;
  @State isExpanded: boolean = false;
  @State bottomAvoidHeight: number = 0;
  @State currentStage: SecurityStage = SecurityStage.OVERVIEW;
  @State currentTheme: ThreatLightTheme | null = null;
  
  // 威胁统计
  @State criticalCount: number = 0;
  @State highCount: number = 0;
  @State alertCount: number = 0;
  @State watchCount: number = 0;

  private lightManager: ThreatLightManager;
  private navItems: SecurityNavItem[] = [
    { id: 'overview', icon: $r('app.media.ic_dashboard'), label: '态势总览', page: 'OverviewPage', stage: SecurityStage.OVERVIEW },
    { id: 'traffic', icon: $r('app.media.ic_network'), label: '流量分析', page: 'TrafficPage', stage: SecurityStage.TRAFFIC },
    { id: 'threat', icon: $r('app.media.ic_shield'), label: '威胁检测', page: 'ThreatPage', stage: SecurityStage.THREAT },
    { id: 'response', icon: $r('app.media.ic_response'), label: '响应中心', page: 'ResponsePage', stage: SecurityStage.RESPONSE }
  ];

  constructor(lightManager: ThreatLightManager) {
    this.lightManager = lightManager;
  }

  aboutToAppear(): void {
    this.getBottomAvoidArea();
    
    // 监听光效主题变化
    this.lightManager.onThemeChange((theme) => {
      this.currentTheme = theme;
    });
    
    // 监听威胁统计变化
    AppStorage.setOrCreate('threat_stats', (stats: { critical: number; high: number; alert: number; watch: number }) => {
      this.criticalCount = stats.critical;
      this.highCount = stats.high;
      this.alertCount = stats.alert;
      this.watchCount = stats.watch;
    });

    // 初始化当前主题
    this.currentTheme = this.lightManager.getCurrentTheme();
  }

  aboutToDisappear(): void {
    this.lightManager.offThemeChange(() => {});
  }

  private async getBottomAvoidArea(): Promise<void> {
    try {
      const mainWindow = await window.getLastWindow();
      const avoidArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
      this.bottomAvoidHeight = avoidArea.bottomRect.height;
    } catch (error) {
      console.error('Failed to get avoid area:', error);
    }
  }

  private getStageColor(): string {
    return this.currentTheme?.primaryColor || '#4CAF50';
  }

  private getThreatBadgeCount(itemId: string): number {
    switch (itemId) {
      case 'threat': return this.criticalCount + this.highCount;
      case 'response': return this.criticalCount;
      default: return 0;
    }
  }

  private getThreatBadgeColor(): string {
    if (this.criticalCount > 0) return '#D32F2F';
    if (this.highCount > 0) return '#EF5350';
    if (this.alertCount > 0) return '#FFA726';
    return '#42A5F5';
  }

  build() {
    Stack({ alignContent: Alignment.Bottom }) {
      // 内容层
      Column() {
        this.contentBuilder()
      }
      .padding({ bottom: this.bottomAvoidHeight + 80 })

      // 悬浮导航栏
      Column() {
        Stack() {
          // 玻璃拟态背景
          Column()
            .width('100%')
            .height('100%')
            .backgroundBlurStyle(BlurStyle.REGULAR)
            .opacity(this.navTransparency)
            .backdropFilter($r('sys.blur.20'))

          // 威胁光效渐变层
          Column()
            .width('100%')
            .height('100%')
            .linearGradient({
              direction: GradientDirection.Top,
              colors: [
                [this.getStageColor() + '20', 0.0],
                [this.getStageColor() + '05', 1.0]
              ]
            })
        }
        .width('100%')
        .height('100%')
        .borderRadius(24)
        .shadow({
          radius: 20,
          color: (this.currentTheme?.primaryColor || '#4CAF50') + '40',
          offsetX: 0,
          offsetY: -4
        })

        // 导航项
        Row() {
          ForEach(this.navItems, (item: SecurityNavItem, index: number) => {
            Column() {
              Stack() {
                Image(item.icon)
                  .width(24)
                  .height(24)
                  .fillColor(this.currentIndex === index ? this.getStageColor() : '#666666')

                // 威胁统计徽章
                if (this.getThreatBadgeCount(item.id) > 0) {
                  Stack() {
                    Text(`${this.getThreatBadgeCount(item.id)}`)
                      .fontSize(10)
                      .fontColor('#FFFFFF')
                      .fontWeight(FontWeight.Bold)
                  }
                  .width(18)
                  .height(18)
                  .backgroundColor(this.getThreatBadgeColor())
                  .borderRadius(9)
                  .position({ x: 14, y: -6 })
                  .shadow({
                    radius: 6,
                    color: this.getThreatBadgeColor(),
                    offsetX: 0,
                    offsetY: 0
                  })
                }

                // 阶段指示器
                if (item.stage === this.currentStage) {
                  Column()
                    .width(6)
                    .height(6)
                    .backgroundColor(this.getStageColor())
                    .borderRadius(3)
                    .position({ x: 20, y: 20 })
                    .shadow({
                      radius: 4,
                      color: this.getStageColor(),
                      offsetX: 0,
                      offsetY: 0
                    })
                }
              }
              .width(40)
              .height(40)

              Text(item.label)
                .fontSize(11)
                .fontColor(this.currentIndex === index ? this.getStageColor() : '#999999')
                .margin({ top: 4 })
            }
            .layoutWeight(1)
            .onClick(() => {
              this.currentIndex = index;
              this.currentStage = item.stage;
              AppStorage.setOrCreate('security_stage', item.stage);
              this.triggerHapticFeedback();
            })
          })
        }
        .width('100%')
        .height(80)
        .padding({ left: 16, right: 16 })
        .justifyContent(FlexAlign.SpaceAround)

        // 透明度调节
        if (this.isExpanded) {
          Row() {
            Text('透明度')
              .fontSize(12)
              .fontColor('#666666')
              .margin({ right: 8 })

            Slider({
              value: this.navTransparency * 100,
              min: 55,
              max: 85,
              step: 15,
              style: SliderStyle.InSet
            })
              .width(120)
              .onChange((value: number) => {
                this.navTransparency = value / 100;
              })

            Text(`${Math.round(this.navTransparency * 100)}%`)
              .fontSize(12)
              .fontColor('#666666')
              .margin({ left: 8 })
          }
          .width('100%')
          .height(40)
          .justifyContent(FlexAlign.Center)
          .backgroundColor('rgba(255,255,255,0.5)')
          .borderRadius({ topLeft: 12, topRight: 12 })
        }
      }
      .width('92%')
      .height(this.isExpanded ? 120 : 80)
      .margin({ bottom: this.bottomAvoidHeight + 12, left: '4%', right: '4%' })
      .animation({
        duration: 300,
        curve: Curve.Spring,
        iterations: 1
      })
      .gesture(
        LongPressGesture({ duration: 500 })
          .onAction(() => {
            this.isExpanded = !this.isExpanded;
          })
      )
    }
    .width('100%')
    .height('100%')
  }

  @BuilderParam contentBuilder: () => void = this.defaultContentBuilder;

  @Builder
  defaultContentBuilder(): void {
    Column() {
      Text('态势感知区域')
        .fontSize(16)
        .fontColor('#999999')
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

  private triggerHapticFeedback(): void {
    try {
      import('@kit.SensorServiceKit').then(sensor => {
        sensor.vibrator.startVibration({
          type: 'time',
          duration: 50
        }, { id: 0 });
      });
    } catch (error) {
      console.error('Haptic feedback failed:', error);
    }
  }
}

5.5 主态势感知大屏(SituationalAwarenessPage.ets)

代码亮点 :本模块是"光域智脑"的核心可视化界面,基于 Canvas 实现网络拓扑的实时渲染。威胁节点根据等级显示不同颜色与脉冲效果,攻击链路实现动态流光动画。支持手势缩放与拖拽,双击节点下钻查看详情。环境背景光随全局威胁等级动态变化。

typescript 复制代码
// entry/src/main/ets/pages/SituationalAwarenessPage.ets
import { ThreatLightManager, ThreatNode, AttackLink, ThreatLevel } from '../theme/ThreatLightEffect';
import { SecurityAgentScheduler, SecurityStage } from '../agents/SecurityAgentScheduler';

@Component
struct ThreatTopologyCanvas {
  @State nodes: ThreatNode[] = [];
  @State links: AttackLink[] = [];
  @State scale: number = 1.0;
  @State offsetX: number = 0;
  @State offsetY: number = 0;
  @State selectedNode: ThreatNode | null = null;
  @State currentTheme: ThreatLightTheme | null = null;
  
  private lightManager: ThreatLightManager;
  private scheduler: SecurityAgentScheduler;
  private canvasContext: CanvasRenderingContext2D | null = null;
  private animationId: number = 0;

  constructor(lightManager: ThreatLightManager, scheduler: SecurityAgentScheduler) {
    this.lightManager = lightManager;
    this.scheduler = scheduler;
  }

  aboutToAppear(): void {
    // 监听光效变化
    this.lightManager.onThemeChange((theme) => {
      this.currentTheme = theme;
      this.invalidate();
    });

    // 监听节点数据变化
    AppStorage.setOrCreate('threat_nodes', (nodes: ThreatNode[]) => {
      this.nodes = nodes;
      this.invalidate();
    });

    // 监听链路数据变化
    AppStorage.setOrCreate('attack_links', (links: AttackLink[]) => {
      this.links = links;
      this.invalidate();
    });

    // 启动动画循环
    this.startAnimationLoop();
  }

  aboutToDisappear(): void {
    this.lightManager.offThemeChange(() => {});
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
    }
  }

  private startAnimationLoop(): void {
    const animate = () => {
      this.invalidate();
      this.animationId = requestAnimationFrame(animate);
    };
    this.animationId = requestAnimationFrame(animate);
  }

  private invalidate(): void {
    if (this.canvasContext) {
      this.drawTopology(this.canvasContext);
    }
  }

  private drawTopology(ctx: CanvasRenderingContext2D): void {
    const width = ctx.canvas.width;
    const height = ctx.canvas.height;
    const time = Date.now();

    // 清空画布
    ctx.clearRect(0, 0, width, height);

    // 绘制环境背景光
    if (this.currentTheme) {
      const gradient = ctx.createRadialGradient(
        width / 2, height / 2, 0,
        width / 2, height / 2, Math.max(width, height) / 2
      );
      gradient.addColorStop(0, this.currentTheme.primaryColor + '10');
      gradient.addColorStop(1, 'transparent');
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, width, height);
    }

    // 保存变换状态
    ctx.save();
    ctx.translate(this.offsetX, this.offsetY);
    ctx.scale(this.scale, this.scale);

    // 绘制攻击链路
    for (const link of this.links) {
      if (!link.isActive) continue;
      
      const sourceNode = this.nodes.find(n => n.id === link.sourceId);
      const targetNode = this.nodes.find(n => n.id === link.targetId);
      if (!sourceNode || !targetNode) continue;

      // 链路流光效果
      const flowOffset = (time % this.currentTheme?.linkFlowSpeed || 2000) / (this.currentTheme?.linkFlowSpeed || 2000);
      const linkColor = this.getThreatColor(link.threatLevel);
      
      ctx.beginPath();
      ctx.moveTo(sourceNode.x, sourceNode.y);
      ctx.lineTo(targetNode.x, targetNode.y);
      ctx.strokeStyle = linkColor + '40';
      ctx.lineWidth = 2;
      ctx.stroke();

      // 流光点
      const flowX = sourceNode.x + (targetNode.x - sourceNode.x) * flowOffset;
      const flowY = sourceNode.y + (targetNode.y - sourceNode.y) * flowOffset;
      
      ctx.beginPath();
      ctx.arc(flowX, flowY, 4, 0, Math.PI * 2);
      ctx.fillStyle = linkColor;
      ctx.fill();
      ctx.shadowColor = linkColor;
      ctx.shadowBlur = 10;
    }

    // 绘制威胁节点
    for (const node of this.nodes) {
      const nodeColor = this.getThreatColor(node.threatLevel);
      const pulseIntensity = this.getPulseIntensity(node.threatLevel, time);
      
      // 节点光晕
      ctx.beginPath();
      ctx.arc(node.x, node.y, 30 + pulseIntensity * 10, 0, Math.PI * 2);
      ctx.fillStyle = nodeColor + '20';
      ctx.fill();
      
      // 节点外圈
      ctx.beginPath();
      ctx.arc(node.x, node.y, 20, 0, Math.PI * 2);
      ctx.strokeStyle = nodeColor;
      ctx.lineWidth = this.currentTheme?.nodeBorderWidth || 2;
      ctx.stroke();
      
      // 节点内核
      ctx.beginPath();
      ctx.arc(node.x, node.y, 16, 0, Math.PI * 2);
      ctx.fillStyle = nodeColor;
      ctx.fill();
      
      // 节点标签
      ctx.fillStyle = '#FFFFFF';
      ctx.font = '12px sans-serif';
      ctx.textAlign = 'center';
      ctx.fillText(node.name, node.x, node.y + 35);
      ctx.fillText(node.threatType, node.x, node.y + 50);
    }

    ctx.restore();
  }

  private getThreatColor(level: ThreatLevel): string {
    const colors: Record<ThreatLevel, string> = {
      [ThreatLevel.NORMAL]: '#4CAF50',
      [ThreatLevel.WATCH]: '#42A5F5',
      [ThreatLevel.ALERT]: '#FFA726',
      [ThreatLevel.HIGH]: '#EF5350',
      [ThreatLevel.CRITICAL]: '#D32F2F'
    };
    return colors[level] || '#4CAF50';
  }

  private getPulseIntensity(level: ThreatLevel, time: number): number {
    const speeds: Record<ThreatLevel, number> = {
      [ThreatLevel.NORMAL]: 4000,
      [ThreatLevel.WATCH]: 3500,
      [ThreatLevel.ALERT]: 2500,
      [ThreatLevel.HIGH]: 1500,
      [ThreatLevel.CRITICAL]: 800
    };
    const speed = speeds[level] || 4000;
    return Math.sin((time % speed) / speed * Math.PI * 2) * 0.5 + 0.5;
  }

  build() {
    Canvas(this.canvasContext)
      .width('100%')
      .height('100%')
      .backgroundColor('#0D1117')
      .onReady((context) => {
        this.canvasContext = context;
      })
      .gesture(
        GestureGroup(GestureMode.Sequence,
          PinchGesture()
            .onActionStart((event) => {
              this.scale = Math.max(0.5, Math.min(3.0, this.scale * event.scale));
            }),
          PanGesture()
            .onActionUpdate((event) => {
              this.offsetX += event.offsetX;
              this.offsetY += event.offsetY;
            })
        )
      )
      .onClick((event) => {
        // 节点选中检测
        const clickX = (event.x - this.offsetX) / this.scale;
        const clickY = (event.y - this.offsetY) / this.scale;
        
        for (const node of this.nodes) {
          const dist = Math.sqrt((clickX - node.x) ** 2 + (clickY - node.y) ** 2);
          if (dist < 25) {
            this.selectedNode = node;
            AppStorage.setOrCreate('selected_threat_node', node);
            break;
          }
        }
      })
  }
}

@Entry
@Component
struct SituationalAwarenessPage {
  private lightManager: ThreatLightManager = new ThreatLightManager();
  private scheduler: SecurityAgentScheduler = new SecurityAgentScheduler(this.lightManager);

  aboutToAppear(): void {
    this.scheduler.initialize().then(() => {
      // 启动全链路调查
      this.scheduler.processSecurityIntent('开始全面安全调查');
    });
  }

  build() {
    Stack() {
      // 背景环境光
      Column()
        .width('100%')
        .height('100%')
        .backgroundColor('#0D1117')
        .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])

      // 态势拓扑画布
      ThreatTopologyCanvas({ lightManager: this.lightManager, scheduler: this.scheduler })
        .width('100%')
        .height('100%')

      // 顶部状态栏
      Row() {
        Text('光域智脑')
          .fontSize(20)
          .fontColor('#FFFFFF')
          .fontWeight(FontWeight.Bold)
        
        Blank()
        
        // 威胁统计
        Row({ space: 12 }) {
          this.threatBadge('紧急', 0, '#D32F2F')
          this.threatBadge('高危', 0, '#EF5350')
          this.threatBadge('告警', 0, '#FFA726')
          this.threatBadge('关注', 0, '#42A5F5')
        }
      }
      .width('100%')
      .height(56)
      .padding({ left: 24, right: 24 })
      .backgroundColor('rgba(13,17,23,0.8)')
      .backdropFilter($r('sys.blur.10'))

      // 悬浮态势导航
      SecurityFloatNavigation({ lightManager: this.lightManager })
        .width('100%')
        .height('100%')
    }
    .width('100%')
    .height('100%')
  }

  @Builder
  threatBadge(label: string, count: number, color: string): void {
    Row() {
      Circle()
        .width(8)
        .height(8)
        .fill(color)
      
      Text(`${label} ${count}`)
        .fontSize(12)
        .fontColor('#FFFFFF')
        .margin({ left: 4 })
    }
  }
}

5.6 浮动威胁拓扑窗口(ThreatTopologyAbility.ets)

代码亮点 :本模块实现了可拖拽的浮动威胁拓扑子窗口。通过 window.createSubWindow 创建独立浮动窗口,支持自由拖拽定位。窗口内展示选中子网的威胁拓扑,节点颜色与主窗口光效同步。窗口获得焦点时自动提高透明度,失焦时降低透明度,避免干扰主态势大屏。

typescript 复制代码
// entry/src/main/ets/entryability/ThreatTopologyAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';

export default class ThreatTopologyAbility extends UIAbility {
  private floatWindow: window.Window | null = null;

  async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
    // 创建浮动窗口
    this.floatWindow = await windowStage.createSubWindow('ThreatTopologyFloat');
    
    // 配置浮动窗口属性
    await this.floatWindow.setWindowLayoutFullScreen(false);
    await this.floatWindow.setWindowSize({ width: 400, height: 300 });
    await this.floatWindow.setWindowPosition({ x: 100, y: 100 });
    await this.floatWindow.setWindowBackgroundColor('rgba(13,17,23,0.85)');
    
    // 加载浮动内容
    this.floatWindow.loadContent('pages/ThreatTopologyFloatPage', (err) => {
      if (err) {
        console.error('Failed to load float content:', err);
        return;
      }
      console.info('Threat topology float window loaded');
    });

    // 焦点感知
    this.floatWindow.on('windowFocusChange', (isFocused) => {
      if (isFocused) {
        this.floatWindow?.setWindowBackgroundColor('rgba(13,17,23,0.95)');
      } else {
        this.floatWindow?.setWindowBackgroundColor('rgba(13,17,23,0.70)');
      }
    });
  }

  onWindowStageDestroy(): void {
    this.floatWindow?.destroy();
  }
}

5.7 多窗口光效同步管理器(WindowLightSync.ets)

代码亮点 :本模块实现了主窗口与三个浮动窗口之间的光效同步。通过 AppStorage 全局状态共享,当主窗口威胁等级变化时,所有浮动窗口自动同步切换光效。支持焦点感知降级------当某个窗口获得焦点时,其他窗口的光效强度自动降低,避免视觉干扰。

typescript 复制代码
// entry/src/main/ets/services/WindowLightSync.ets
import { window } from '@kit.ArkUI';
import { ThreatLightManager, ThreatLightTheme, ThreatLevel } from '../theme/ThreatLightEffect';

/**
 * 窗口光效同步管理器
 * 实现主窗口与浮动窗口之间的光效联动
 */
export class WindowLightSync {
  private mainWindow: window.Window | null = null;
  private floatWindows: Map<string, window.Window> = new Map();
  private lightManager: ThreatLightManager;
  private isMainFocused: boolean = true;

  constructor(lightManager: ThreatLightManager) {
    this.lightManager = lightManager;
  }

  /**
   * 注册主窗口
   */
  public async registerMainWindow(windowStage: window.WindowStage): Promise<void> {
    this.mainWindow = await windowStage.getMainWindow();
    
    // 监听主窗口焦点
    this.mainWindow.on('windowFocusChange', (isFocused) => {
      this.isMainFocused = isFocused;
      this.syncLightIntensity();
    });

    // 监听光效变化
    this.lightManager.onThemeChange((theme) => {
      this.applyThemeToAllWindows(theme);
    });
  }

  /**
   * 注册浮动窗口
   */
  public registerFloatWindow(name: string, win: window.Window): void {
    this.floatWindows.set(name, win);
    
    // 监听浮动窗口焦点
    win.on('windowFocusChange', (isFocused) => {
      if (isFocused) {
        this.syncLightIntensity();
      }
    });
  }

  /**
   * 应用光效主题到所有窗口
   */
  private applyThemeToAllWindows(theme: ThreatLightTheme): void {
    // 主窗口应用完整光效
    if (this.mainWindow) {
      this.setWindowLightEffect(this.mainWindow, theme, 1.0);
    }

    // 浮动窗口应用同步光效
    for (const [name, win] of this.floatWindows) {
      const intensity = this.isMainFocused ? 0.6 : 0.9;
      this.setWindowLightEffect(win, theme, intensity);
    }
  }

  /**
   * 同步光效强度
   */
  private syncLightIntensity(): void {
    const theme = this.lightManager.getCurrentTheme();
    
    if (this.isMainFocused) {
      // 主窗口聚焦:主窗口100%,浮动窗口60%
      if (this.mainWindow) {
        this.setWindowLightEffect(this.mainWindow, theme, 1.0);
      }
      for (const [name, win] of this.floatWindows) {
        this.setWindowLightEffect(win, theme, 0.6);
      }
    } else {
      // 浮动窗口聚焦:浮动窗口90%,主窗口30%
      if (this.mainWindow) {
        this.setWindowLightEffect(this.mainWindow, theme, 0.3);
      }
      for (const [name, win] of this.floatWindows) {
        this.setWindowLightEffect(win, theme, 0.9);
      }
    }
  }

  /**
   * 设置窗口光效
   */
  private setWindowLightEffect(
    win: window.Window, 
    theme: ThreatLightTheme, 
    intensity: number
  ): void {
    try {
      // 设置窗口背景色调
      const r = parseInt(theme.primaryColor.slice(1, 3), 16);
      const g = parseInt(theme.primaryColor.slice(3, 5), 16);
      const b = parseInt(theme.primaryColor.slice(5, 7), 16);
      
      const alpha = Math.round(theme.ambientOpacity * intensity * 255);
      const bgColor = `rgba(${r}, ${g}, ${b}, ${alpha / 255})`;
      
      win.setWindowBackgroundColor(bgColor);
      
      // 设置边框光效(如果支持)
      win.setWindowShadow({
        radius: 20 * intensity,
        color: theme.primaryColor + Math.round(40 * intensity).toString(16).padStart(2, '0'),
        offsetX: 0,
        offsetY: -4
      });
    } catch (error) {
      console.error('Failed to set window light effect:', error);
    }
  }

  /**
   * 广播威胁等级变化
   */
  public broadcastThreatLevel(level: ThreatLevel): void {
    this.lightManager.switchThreatLevel(level);
  }
}

六、关键技术总结

6.1 HMAF网络安全开发清单

技术点 API/方法 应用场景
智能体会话创建 hmaf.createAgentSession({ mode: MULTI_AGENT }) 多智能体协作防御
意图解析 intents.createIntentEngine({ supportedDomains }) 安全分析师查询意图理解
任务分发 hmafSession.sendTask({ targetAgent, taskType }) 智能体间安全任务调度
状态监听 AppStorage 全局状态回调 跨组件安全态势同步
分布式协同 enableDistributed: true 多设备安全运营协作

6.2 沉浸光感实现清单

技术点 API/方法 应用场景
系统材质效果 systemMaterialEffect: SystemMaterialEffect.IMMERSIVE HdsNavigation标题栏
背景模糊 backgroundBlurStyle(BlurStyle.REGULAR) 悬浮导航玻璃拟态
背景滤镜 backdropFilter($r('sys.blur.20')) 精细模糊控制
安全区扩展 expandSafeArea([SafeAreaType.SYSTEM], [...]) 全屏沉浸布局
窗口沉浸 setWindowLayoutFullScreen(true) 无边框模式
光效动画 animation({ duration, iterations: -1 }) 呼吸灯背景
动态透明度 backgroundOpacity 焦点感知降级

6.3 威胁等级光效映射

威胁等级 主色 辅色 脉冲间隔 环境透明度 应用场景
正常(NORMAL) #4CAF50 #81C784 3000ms 0.05 网络平稳运行
关注(WATCH) #42A5F5 #90CAF9 2500ms 0.08 异常流量检测
告警(ALERT) #FFA726 #FFCC80 1500ms 0.12 可疑行为识别
高危(HIGH) #EF5350 #EF9A9A 800ms 0.18 确认攻击行为
紧急(CRITICAL) #D32F2F #E57373 400ms 0.25 APT攻击/数据外泄

6.4 PC端多窗口光效协同

场景 主窗口光效 浮动窗口光效 同步机制
主窗口聚焦 100%强度 60%强度 AppStorage广播
浮动窗口聚焦 30%强度 90%强度 焦点事件触发
威胁等级变化 全色域切换 同步色域切换 主题回调监听
响应完成 确认绿光 同步绿光 状态变更通知

七、调试与适配建议

7.1 网络流量解析性能优化

  • 采样策略:高流量环境采用1:1000采样,低流量环境全量采集
  • 异步处理 :流量解析使用 TaskPool 异步线程,避免阻塞UI
  • 缓存机制:威胁情报库本地缓存,减少云端查询延迟

7.2 威胁光效可访问性

  • 色盲友好:除颜色外,增加图标形状差异(圆形/三角形/菱形)
  • 闪烁控制:紧急状态的脉冲频率不超过3Hz,避免光敏性癫痫触发
  • 手动关闭:提供"光效静音"开关,满足特殊环境需求

7.3 多窗口管理优化

  • 窗口记忆:记录浮动窗口位置与大小,下次启动自动恢复
  • 吸附对齐:浮动窗口靠近边缘时自动吸附,避免遮挡关键内容
  • 一键归位:提供"重置布局"按钮,快速恢复默认窗口配置

八、运行效果展示

8.1 正常态势 - 柔绿光效

网络运行平稳,无异常流量。环境光呈现柔和绿色,节点缓慢呼吸,链路稳定流光。

8.2 关注态势 - 淡蓝光效

检测到异常流量模式(如端口扫描)。环境光转为淡蓝,异常节点蓝色脉冲,链路流光加速。

8.3 告警态势 - 暖黄光效

识别可疑行为(如异常登录)。环境光转为暖黄,可疑节点黄色脉冲,悬浮导航显示告警徽章。

8.4 高危态势 - 橙红光效

确认攻击行为(如C2通信)。环境光转为橙红,攻击节点红色脉冲,链路流光急速流动,悬浮导航显示高危徽章。

8.5 紧急态势 - 警示红光效

APT攻击/数据外泄。环境光强烈红光闪烁,紧急节点快速脉冲,所有窗口同步红色告警,悬浮导航显示紧急徽章并震动提醒。


九、总结与展望

本文基于HarmonyOS 6(API 23)的悬浮导航沉浸光感HMAF智能体框架特性,完整实战了一款面向PC端的"光域智脑"网络安全态势感知与威胁响应指挥中心。核心创新点总结:

  1. HMAF四层安全智能体:基于Agent Framework Kit构建流量采集Agent(实时网络流量采集与预处理)、威胁检测Agent(基于AI模型的威胁识别)、攻击研判Agent(攻击链路与影响评估)、自动响应Agent(SOAR剧本执行与联动),实现"流量采集→威胁检测→攻击研判→自动响应"的全链路自动化,威胁检测效率提升20倍

  2. 威胁等级光效系统:五种安全态势拥有专属光效人格(正常柔绿、关注淡蓝、告警暖黄、高危橙红、紧急警示红),根据当前最高威胁等级动态切换全局环境光、节点脉冲和导航材质,实现安全分析师"一眼感知威胁"的直觉体验

  3. 悬浮态势导航:底部悬浮页签承载"态势总览/流量分析/威胁检测/响应中心"四个运营阶段,实时显示威胁统计徽章(紧急/高危/告警数量)和智能体运行状态角标,玻璃拟态设计+三档透明度调节,最大化态势展示区域

  4. PC级多窗口协作运营 :主态势感知窗口 + 浮动威胁拓扑窗口 + 浮动攻击时间线窗口 + 浮动响应剧本窗口的四层架构,通过 WindowLightSync 实现跨窗口光效联动与焦点感知,符合安全分析师的专业运营工作习惯

  5. 威胁意图沉浸感知:通过Intents Kit解析安全分析师的查询意图(如"查找过去一小时内所有横向移动行为"),自动触发对应Agent协作并调整界面威胁光效,实现"查询即氛围"的沉浸体验

未来扩展方向

  • 威胁狩猎模式:增加主动威胁狩猎智能体,基于假设驱动进行深度探测
  • 数字孪生网络:构建网络拓扑的数字孪生,支持攻击模拟与防御推演
  • 跨设备安全协同:利用鸿蒙分布式能力,实现PC态势大屏+平板移动运维+手机告警推送的协同安全运营
  • 量子安全加密:集成量子密钥分发能力,保护安全运营通信链路

转载自:https://blog.csdn.net/u014727709/article/details/162362981

欢迎 👍点赞✍评论⭐收藏,欢迎指正