HarmonyOS 6(API 23)实战:基于悬浮导航、沉浸光感与HMAF的“代码哨兵“——AI智能体代码安全审计平台

文章目录

    • 每日一句正能量
    • 前言
    • 一、前言: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 风险等级光效系统(RiskLightEffect.ets)](#5.2 风险等级光效系统(RiskLightEffect.ets))
      • [5.3 HMAF四层审计智能体架构(AuditAgentScheduler.ets)](#5.3 HMAF四层审计智能体架构(AuditAgentScheduler.ets))
      • [5.4 悬浮审计导航(AuditFloatNavigation.ets)](#5.4 悬浮审计导航(AuditFloatNavigation.ets))
      • [5.5 代码编辑器与风险高亮(CodeEditor.ets)](#5.5 代码编辑器与风险高亮(CodeEditor.ets))
      • [5.6 浮动漏洞详情窗口(VulnDetailWindow.ets)](#5.6 浮动漏洞详情窗口(VulnDetailWindow.ets))
      • [5.7 多窗口光效同步管理器(WindowLightSync.ets)](#5.7 多窗口光效同步管理器(WindowLightSync.ets))
      • [5.8 主页面集成(Index.ets)](#5.8 主页面集成(Index.ets))
    • 六、关键技术总结
      • [6.1 HMAF智能体审计开发清单](#6.1 HMAF智能体审计开发清单)
      • [6.2 沉浸光感实现清单](#6.2 沉浸光感实现清单)
      • [6.3 风险等级光效映射](#6.3 风险等级光效映射)
      • [6.4 PC端多窗口光效协同](#6.4 PC端多窗口光效协同)
    • 七、调试与适配建议
    • 八、总结与展望

每日一句正能量

保持一份克制与警醒,避免沉溺于安逸和享受,才能让自己持续成长。

克制是对即时满足的主动约束,警醒是对舒适区陷阱的持续觉察。真正的成长往往伴随不适感,因此需要刻意避免滑入懒散。

前言

摘要:随着HarmonyOS生态快速扩张,应用安全问题日益凸显。HarmonyOS 6(API 23)引入的鸿蒙智能体框架(HMAF)为自动化代码安全审计提供了全新可能。本文将实战开发一款面向HarmonyOS PC的"代码哨兵"应用,展示如何利用HMAF构建"漏洞挖掘-风险评级-修复建议-合规验证"四层智能体协作架构,通过悬浮导航实现审计任务状态实时追踪,基于沉浸光感打造"风险即氛围"的安全感知体验,以及基于多窗口架构构建浮动漏洞详情、风险热力图和修复方案窗口的协作审计体验。


一、前言:AI智能体时代的代码安全革新

2026年,AI代码审计智能体已成为网络安全领域最火热的方向。恒脑AI代码审计智能体在2026年1月的第六届"天府杯"国际网络安全大赛上,作为全球首位AI选手参赛,与顶尖黑客同台竞技并斩获漏洞防护赛前三名,充分证明了AI智能体在安全审计领域的巨大潜力。

传统代码审计工具往往采用固定的报告界面和扫描按钮,开发者需要手动上传代码、等待扫描、阅读报告、再手动修复问题。而在HarmonyOS 6的PC大屏环境下,这种被动式审计模式显得低效且缺乏安全感知。HMAF配合**悬浮导航(Float Navigation)沉浸光感(Immersive Light Effects)**特性,为AI智能体代码审计带来了"风险即氛围、漏洞即导航"的全新可能。

本文核心亮点

  • 风险等级光效:根据当前审计风险等级(信息/低危/中危/高危/严重)动态切换环境光色与脉冲节奏
  • 悬浮审计导航:底部悬浮页签替代传统工具栏,支持审计任务实时徽章提示,漏洞数量动态角标
  • HMAF四层审计架构:基于Agent Framework Kit构建"漏洞挖掘-风险评级-修复建议-合规验证"四层智能体协作架构
  • 多窗口审计协作:主代码窗口 + 浮动漏洞详情面板 + 浮动风险热力图 + 浮动修复方案窗口的光效联动
  • 实时漏洞感知:通过Intents Kit实时理解代码上下文,自动调整界面光效与导航形态

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

2.1 HMAF在代码安全审计中的价值

HarmonyOS 6的HMAF采用三层架构设计:底层是统一的AI系统底座,中间层是意图理解和任务编排引擎,上层是开放的智能体交互协议。 在"代码哨兵"中,这种架构能够:

  • 原生智能调度:智能体不再是应用的附属品,而是系统的基础能力,支持跨项目审计任务编排
  • 意图即审计:通过Intents Kit将开发者自然语言意图(如"扫描这段代码的SQL注入风险")转化为结构化审计任务
  • 分布式审计协同:利用鸿蒙分布式软总线,实现PC主控+手机预览+平板代码审查的多设备审计协作
  • 端云协同推理:端侧MindSpore Lite处理隐私敏感代码审计,云端大模型处理复杂漏洞模式识别

2.2 沉浸光感在安全审计中的创新应用

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

  • 增强风险感知:不同风险等级拥有专属光效标识(信息蓝、低危绿、中危黄、高危橙、严重红)
  • 状态直觉感知:扫描时的呼吸蓝光、发现漏洞时的脉冲金光、高危漏洞时的警示红光,开发者无需阅读报告即可感知安全状态
  • 提升审计专注度:动态环境光随代码复杂度变化,简单代码柔和、复杂代码强烈,帮助开发者保持专注

2.3 悬浮导航的审计适配

与传统开发工具不同,AI代码审计平台需要处理:

  • 高频审计任务切换:开发者常在多个审计任务间快速跳转查看状态
  • 漏洞信息密度平衡:既要保证导航可见,又不能遮挡代码内容
  • 实时漏洞徽章:审计任务运行状态需要实时徽章提示(漏洞数量角标、风险等级脉冲)

HarmonyOS 6的悬浮页签支持**强(85%)、平衡(70%)、弱(55%)**三档透明度自定义,结合PC端的自由窗口能力,可以实现"需要时出现,专注时隐退"的智能导航体验。


三、项目实战:"代码哨兵"架构设计

3.1 应用场景与功能规划

面向HarmonyOS PC的AI智能体代码安全审计场景,核心功能包括:

功能模块 技术实现 沉浸光感/HMAF应用
主代码窗口 TextArea + SyntaxHighlighter 风险行高亮光效、漏洞标记呼吸灯
悬浮审计导航 HdsTabs + systemMaterialEffect 玻璃拟态页签,漏洞数量徽章
漏洞挖掘智能体 HMAF Agent Framework Kit 扫描进度光效反馈
风险评级智能体 HMAF + 规则引擎 风险等级光效标记
修复建议智能体 HMAF + 代码生成 修复方案光效提示
合规验证智能体 HMAF + 合规规则库 合规状态光效标记
浮动漏洞详情面板 子窗口 + HdsNavigation 风险主题色光效同步
浮动风险热力图窗口 子窗口 + Canvas 风险密度光效
浮动修复方案窗口 子窗口 + List 修复优先级颜色编码

3.2 技术架构图

复制代码
┌─────────────────────────────────────────────────────────────┐
│                    代码哨兵 - 应用层                          │
├─────────────┬─────────────┬─────────────┬─────────────────────┤
│  漏洞挖掘智能体 │  风险评级智能体 │  修复建议智能体 │    合规验证智能体      │
│  (Miner)     │  (Rater)     │  (Fixer)     │   (Compliance)      │
├─────────────┴─────────────┴─────────────┴─────────────────────┤
│                  HMAF - 智能体框架层                          │
│         Agent Framework Kit + Intents Kit + NLU Kit          │
├─────────────────────────────────────────────────────────────┤
│                  AI系统底座 - 能力层                          │
│    MindSpore Lite(端侧) │ 鸿蒙大模型4.0(云端) │ 分布式软总线    │
├─────────────────────────────────────────────────────────────┤
│                  ArkUI - 表现层                              │
│    悬浮导航 │ 沉浸光感 │ 多窗口管理 │ 安全区扩展 │ 动画系统    │
└─────────────────────────────────────────────────────────────┘

四、环境配置与模块依赖

4.1 模块依赖配置

oh-package.json5中添加HMAF及相关Kit依赖:

json 复制代码
{
  "name": "code_sentry",
  "version": "1.0.0",
  "description": "AI Agent Code Security Audit Platform",
  "dependencies": {
    "@ohos/hmaframework": "^6.0.0",
    "@ohos/intentskit": "^6.0.0",
    "@ohos/nlukit": "^6.0.0",
    "@ohos/mindsporelite": "^6.0.0",
    "@ohos/aiengine": "^6.0.0",
    "@ohos/hds": "^6.0.0",
    "@ohos/securityauditkit": "^6.0.0"
  }
}

4.2 权限声明(module.json5)

json 复制代码
{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "$string:module_desc",
    "mainElement": "EntryAbility",
    "deviceTypes": ["phone", "tablet", "2in1"],
    "pages": "$profile:main_pages",
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "description": "$string:EntryAbility_desc",
        "icon": "$media:layered_image",
        "label": "$string:EntryAbility_label",
        "startWindowIcon": "$media:startIcon",
        "startWindowBackground": "$color:start_window_background",
        "exported": true,
        "skills": [
          {
            "entities": ["entity.system.home"],
            "actions": ["action.system.home"]
          }
        ]
      }
    ],
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET",
        "reason": "$string:internet_permission"
      },
      {
        "name": "ohos.permission.SYSTEM_FLOAT_WINDOW",
        "reason": "$string:float_window_permission",
        "usedScene": {
          "abilities": ["EntryAbility"],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.DISTRIBUTED_DATASYNC",
        "reason": "$string:distributed_permission"
      },
      {
        "name": "ohos.permission.AI_ENGINE_ACCESS",
        "reason": "$string:ai_engine_permission"
      },
      {
        "name": "ohos.permission.READ_FILE",
        "reason": "$string:read_file_permission"
      },
      {
        "name": "ohos.permission.WRITE_FILE",
        "reason": "$string:write_file_permission"
      }
    ]
  }
}

五、核心组件实战

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

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

export default class EntryAbility extends UIAbility {
  private windowStage: window.WindowStage | null = null;

  onWindowStageCreate(windowStage: window.WindowStage): void {
    this.windowStage = windowStage;
    windowStage.loadContent('pages/Index', (err) => {
      if (err.code) {
        console.error('Failed to load content:', JSON.stringify(err));
        return;
      }
      console.info('Succeeded in loading content.');
      this.setupImmersiveWindow(windowStage);
    });
  }

  private async setupImmersiveWindow(windowStage: window.WindowStage): Promise<void> {
    try {
      const mainWindow = windowStage.getMainWindowSync();
      await mainWindow.setWindowLayoutFullScreen(true);
      await mainWindow.setWindowBackgroundColor('#00000000');
      await mainWindow.setWindowSystemBarProperties({
        statusBarColor: '#00000000',
        navigationBarColor: '#00000000',
        statusBarContentColor: '#FFFFFF',
        navigationBarContentColor: '#FFFFFF'
      });
      await mainWindow.setWindowAvoidAreaOption({
        type: window.AvoidAreaType.TYPE_SYSTEM,
        enabled: true
      });
      console.info('Immersive window setup completed');
    } catch (error) {
      console.error('Failed to setup immersive window:', (error as BusinessError).message);
    }
  }

  onWindowStageDestroy(): void {
    this.windowStage = null;
  }
}

代码亮点 :通过setWindowLayoutFullScreen(true)实现内容延伸至非安全区,配合setWindowAvoidAreaOption启用HarmonyOS 6新增的安全区避让机制,确保悬浮导航不会遮挡代码内容。

5.2 风险等级光效系统(RiskLightEffect.ets)

代码亮点 :这是本应用的核心创新组件。它将代码审计风险等级映射为动态光效------信息级柔和蓝、低危级平静绿、中危级警示黄、高危级脉冲橙、严重级闪烁红。每个风险等级拥有专属脉冲节奏与光晕强度,通过AppStorage全局状态实现跨组件光效同步。

typescript 复制代码
// entry/src/main/ets/components/RiskLightEffect.ets
import { hmaf } from '@kit.HMAFramework';

// 风险等级枚举
export enum RiskLevel {
  INFO = 'info',         // 信息
  LOW = 'low',           // 低危
  MEDIUM = 'medium',     // 中危
  HIGH = 'high',         // 高危
  CRITICAL = 'critical'  // 严重
}

// 风险等级色彩配置
export const RiskColors: Record<RiskLevel, string> = {
  [RiskLevel.INFO]: '#4A90D9',      // 信息蓝
  [RiskLevel.LOW]: '#2ECC71',       // 低危绿
  [RiskLevel.MEDIUM]: '#F5A623',    // 中危黄
  [RiskLevel.HIGH]: '#FF6B6B',      // 高危橙
  [RiskLevel.CRITICAL]: '#FF0000'   // 严重红
};

// 光效配置
interface LightEffectConfig {
  baseColor: string;
  pulseSpeed: number;      // 脉冲周期(ms)
  pulseIntensity: number;  // 脉冲强度(0-1)
  glowRadius: number;      // 光晕半径
  alertMode: boolean;      // 是否启用警示模式
}

@Component
export struct RiskLightEffect {
  @State currentRisk: RiskLevel = RiskLevel.INFO;
  @State lightIntensity: number = 0.4;
  @State pulsePhase: number = 0;
  @State alertFlash: boolean = false;

  private pulseTimer: number = -1;
  private alertTimer: number = -1;

  aboutToAppear(): void {
    this.startPulseAnimation();
    // 监听全局风险等级变化
    AppStorage.setOrCreate('risk_level_change', (level: RiskLevel) => {
      this.currentRisk = level;
      this.updateLightEffect();
    });
  }

  aboutToDisappear(): void {
    clearInterval(this.pulseTimer);
    clearInterval(this.alertTimer);
  }

  private startPulseAnimation(): void {
    this.pulseTimer = setInterval(() => {
      this.pulsePhase = (this.pulsePhase + 0.05) % (Math.PI * 2);
      this.lightIntensity = this.calculatePulseIntensity();
    }, 50);
  }

  private calculatePulseIntensity(): number {
    const baseIntensity = this.getRiskConfig().pulseIntensity;
    const variation = Math.sin(this.pulsePhase) * 0.3;
    return Math.max(0.1, Math.min(1.0, baseIntensity + variation));
  }

  private getRiskConfig(): LightEffectConfig {
    const configs: Record<RiskLevel, LightEffectConfig> = {
      [RiskLevel.INFO]: {
        baseColor: RiskColors[RiskLevel.INFO],
        pulseSpeed: 4000,
        pulseIntensity: 0.4,
        glowRadius: 80,
        alertMode: false
      },
      [RiskLevel.LOW]: {
        baseColor: RiskColors[RiskLevel.LOW],
        pulseSpeed: 3000,
        pulseIntensity: 0.5,
        glowRadius: 100,
        alertMode: false
      },
      [RiskLevel.MEDIUM]: {
        baseColor: RiskColors[RiskLevel.MEDIUM],
        pulseSpeed: 2000,
        pulseIntensity: 0.7,
        glowRadius: 120,
        alertMode: false
      },
      [RiskLevel.HIGH]: {
        baseColor: RiskColors[RiskLevel.HIGH],
        pulseSpeed: 1000,
        pulseIntensity: 0.9,
        glowRadius: 150,
        alertMode: true
      },
      [RiskLevel.CRITICAL]: {
        baseColor: RiskColors[RiskLevel.CRITICAL],
        pulseSpeed: 500,
        pulseIntensity: 1.0,
        glowRadius: 200,
        alertMode: true
      }
    };
    return configs[this.currentRisk] || configs[RiskLevel.INFO];
  }

  private updateLightEffect(): void {
    const config = this.getRiskConfig();
    AppStorage.setOrCreate('current_risk_color', config.baseColor);
    AppStorage.setOrCreate('current_risk_pulse', config.pulseSpeed);
    AppStorage.setOrCreate('current_risk_intensity', config.pulseIntensity);
    
    // 高危/严重级别启用警示闪烁
    if (config.alertMode) {
      this.startAlertFlash();
    } else {
      clearInterval(this.alertTimer);
      this.alertFlash = false;
    }
  }

  private startAlertFlash(): void {
    this.alertTimer = setInterval(() => {
      this.alertFlash = !this.alertFlash;
    }, this.getRiskConfig().pulseSpeed / 2);
  }

  build() {
    Stack() {
      // 主光晕层
      Column()
        .width(400)
        .height(400)
        .backgroundColor(this.getRiskConfig().baseColor)
        .blur(this.getRiskConfig().glowRadius)
        .opacity(this.alertFlash ? this.lightIntensity * 1.5 : this.lightIntensity)
        .position({ x: '50%', y: '30%' })
        .anchor('50%')
        .animation({
          duration: this.getRiskConfig().pulseSpeed,
          curve: Curve.EaseInOut,
          iterations: -1,
          playMode: PlayMode.Alternate
        })

      // 警示闪烁层(高危/严重)
      if (this.getRiskConfig().alertMode) {
        Column()
          .width('100%')
          .height('100%')
          .backgroundColor(this.alertFlash ? 'rgba(255,0,0,0.1)' : 'transparent')
          .animation({
            duration: this.getRiskConfig().pulseSpeed / 2,
            curve: Curve.Step,
            iterations: -1
          })
      }

      // 风险指示器环
      Column()
        .width(200)
        .height(200)
        .backgroundColor('transparent')
        .border({
          width: 3,
          color: this.getRiskConfig().baseColor,
          style: BorderStyle.Solid
        })
        .borderRadius(100)
        .opacity(this.lightIntensity * 0.5)
        .animation({
          duration: this.getRiskConfig().pulseSpeed,
          curve: Curve.EaseInOut,
          iterations: -1,
          playMode: PlayMode.Alternate
        })
    }
    .width('100%')
    .height('100%')
  }
}

5.3 HMAF四层审计智能体架构(AuditAgentScheduler.ets)

代码亮点:基于HMAF Agent Framework Kit构建核心审计调度逻辑,实现"漏洞挖掘→风险评级→修复建议→合规验证"的完整审计工作流。调度器通过Intents Kit解析开发者自然语言意图,自动创建四层智能体实例,并实时监控各智能体状态。

typescript 复制代码
// entry/src/main/ets/services/AuditAgentScheduler.ets
import { hmaf } from '@kit.HMAFramework';
import { intents } from '@kit.IntentsKit';
import { nlu } from '@kit.NLUKit';

// 审计任务定义
interface AuditTask {
  id: string;
  taskType: 'vuln_scan' | 'risk_rate' | 'fix_suggest' | 'compliance_check';
  targetCode: string;
  filePath: string;
  priority: number;
  deadline: number;
}

// 智能体实例
interface AgentInstance {
  id: string;
  type: 'miner' | 'rater' | 'fixer' | 'compliance';
  status: 'idle' | 'scanning' | 'analyzing' | 'completed' | 'error';
  currentTask: AuditTask | null;
  capability: string[];
}

// 漏洞发现
interface Vulnerability {
  id: string;
  type: string;
  severity: RiskLevel;
  lineNumber: number;
  codeSnippet: string;
  description: string;
  cweId: string;
  cvssScore: number;
}

export class AuditAgentScheduler {
  private static instance: AuditAgentScheduler;
  private agents: Map<string, AgentInstance> = new Map();
  private taskQueue: AuditTask[] = [];
  private hmafSession: hmaf.AgentSession | null = null;
  private intentEngine: intents.IntentEngine | null = null;
  private vulnerabilities: Vulnerability[] = [];

  private constructor() {}

  static getInstance(): AuditAgentScheduler {
    if (!AuditAgentScheduler.instance) {
      AuditAgentScheduler.instance = new AuditAgentScheduler();
    }
    return AuditAgentScheduler.instance;
  }

  async initialize(): Promise<void> {
    try {
      // 初始化HMAF会话
      this.hmafSession = await hmaf.createAgentSession({
        mode: hmaf.AgentMode.MULTI_AGENT,
        maxConcurrentAgents: 8,
        enableDistributed: true
      });

      // 初始化意图引擎
      this.intentEngine = await intents.createIntentEngine({
        supportedDomains: ['security_audit', 'code_review', 'vulnerability_scan'],
        language: 'zh-CN'
      });

      // 注册四层审计智能体
      await this.registerAuditAgents();

      console.info('AuditAgentScheduler initialized successfully');
    } catch (error) {
      console.error('Failed to initialize AuditAgentScheduler:', error);
      throw error;
    }
  }

  private async registerAuditAgents(): Promise<void> {
    // 注册漏洞挖掘智能体
    this.agents.set('miner-1', {
      id: 'miner-1',
      type: 'miner',
      status: 'idle',
      currentTask: null,
      capability: ['sql_injection', 'xss', 'buffer_overflow', 'path_traversal', 'command_injection']
    });

    this.agents.set('miner-2', {
      id: 'miner-2',
      type: 'miner',
      status: 'idle',
      currentTask: null,
      capability: ['crypto_weakness', 'auth_bypass', 'session_hijack', 'csrf', 'ssrf']
    });

    // 注册风险评级智能体
    this.agents.set('rater-1', {
      id: 'rater-1',
      type: 'rater',
      status: 'idle',
      currentTask: null,
      capability: ['cvss_scoring', 'risk_matrix', 'impact_analysis', 'exploitability_assessment']
    });

    // 注册修复建议智能体
    this.agents.set('fixer-1', {
      id: 'fixer-1',
      type: 'fixer',
      status: 'idle',
      currentTask: null,
      capability: ['code_patch', 'secure_coding', 'refactoring', 'dependency_update']
    });

    // 注册合规验证智能体
    this.agents.set('compliance-1', {
      id: 'compliance-1',
      type: 'compliance',
      status: 'idle',
      currentTask: null,
      capability: ['owasp_top10', 'cwe_mapping', 'gdpr_check', 'privacy_compliance']
    });
  }

  // 处理开发者审计意图
  async processAuditIntent(userInput: string, codeContext: string): Promise<string> {
    try {
      // 更新状态为扫描中
      this.updateAgentState('miner-1', 'scanning');

      // 解析开发者意图
      const parsedIntent = await this.intentEngine?.parseIntent(userInput);
      if (!parsedIntent) {
        throw new Error('Failed to parse audit intent');
      }

      // 创建审计任务链
      const auditChain = await this.createAuditChain(parsedIntent, codeContext);
      
      // 执行漏洞挖掘
      const foundVulns = await this.executeVulnMining(auditChain);

      // 执行风险评级
      const ratedVulns = await this.executeRiskRating(foundVulns);

      // 执行修复建议
      const fixSuggestions = await this.executeFixSuggestions(ratedVulns);

      // 执行合规验证
      const complianceResult = await this.executeComplianceCheck(ratedVulns);

      // 更新状态为完成
      this.updateAgentState('miner-1', 'idle');

      return this.formatAuditReport(ratedVulns, fixSuggestions, complianceResult);
    } catch (error) {
      this.updateAgentState('miner-1', 'error');
      console.error('Error processing audit intent:', error);
      return `审计异常:${error.message}`;
    }
  }

  private async createAuditChain(intent: intents.ParsedIntent, code: string): Promise<<AuditTask[]> {
    const tasks: AuditTask[] = [];
    const taskId = `audit-${Date.now()}`;

    // 根据意图类型创建审计链
    switch (intent.domain) {
      case 'security_audit':
        tasks.push({
          id: `${taskId}-1`,
          taskType: 'vuln_scan',
          targetCode: code,
          filePath: intent.parameters.filePath || 'unknown',
          priority: 1,
          deadline: Date.now() + 30000
        });
        tasks.push({
          id: `${taskId}-2`,
          taskType: 'risk_rate',
          targetCode: code,
          filePath: intent.parameters.filePath || 'unknown',
          priority: 2,
          deadline: Date.now() + 60000
        });
        tasks.push({
          id: `${taskId}-3`,
          taskType: 'fix_suggest',
          targetCode: code,
          filePath: intent.parameters.filePath || 'unknown',
          priority: 3,
          deadline: Date.now() + 90000
        });
        tasks.push({
          id: `${taskId}-4`,
          taskType: 'compliance_check',
          targetCode: code,
          filePath: intent.parameters.filePath || 'unknown',
          priority: 4,
          deadline: Date.now() + 120000
        });
        break;

      default:
        tasks.push({
          id: `${taskId}-1`,
          taskType: 'vuln_scan',
          targetCode: code,
          filePath: 'unknown',
          priority: 1,
          deadline: Date.now() + 30000
        });
    }

    return tasks;
  }

  private async executeVulnMining(tasks: AuditTask[]): Promise<Vulnerability[]> {
    const foundVulns: Vulnerability[] = [];

    for (const task of tasks.filter(t => t.taskType === 'vuln_scan')) {
      const agent = this.findAvailableAgent('miner');
      if (!agent) continue;

      this.updateAgentState(agent.id, 'scanning');

      // 通过HMAF执行漏洞扫描
      const scanResult = await this.hmafSession?.sendTask({
        targetAgent: agent.id,
        taskType: 'vulnerability_scan',
        parameters: {
          code: task.targetCode,
          filePath: task.filePath,
          scanTypes: agent.capability
        },
        timeout: task.deadline - Date.now()
      });

      if (scanResult?.vulnerabilities) {
        foundVulns.push(...scanResult.vulnerabilities);
      }

      this.updateAgentState(agent.id, 'idle');
    }

    this.vulnerabilities = foundVulns;
    return foundVulns;
  }

  private async executeRiskRating(vulns: Vulnerability[]): Promise<Vulnerability[]> {
    const agent = this.findAvailableAgent('rater');
    if (!agent) return vulns;

    this.updateAgentState(agent.id, 'analyzing');

    const ratedVulns: Vulnerability[] = [];
    for (const vuln of vulns) {
      const rating = await this.hmafSession?.sendTask({
        targetAgent: agent.id,
        taskType: 'risk_rating',
        parameters: {
          vulnerability: JSON.stringify(vuln),
          context: vuln.codeSnippet
        },
        timeout: 15000
      });

      ratedVulns.push({
        ...vuln,
        severity: rating?.severity || vuln.severity,
        cvssScore: rating?.cvssScore || vuln.cvssScore
      });
    }

    this.updateAgentState(agent.id, 'idle');
    return ratedVulns;
  }

  private async executeFixSuggestions(vulns: Vulnerability[]): Promise<<Record<string, string>> {
    const agent = this.findAvailableAgent('fixer');
    if (!agent) return {};

    this.updateAgentState(agent.id, 'analyzing');

    const fixes: Record<string, string> = {};
    for (const vuln of vulns) {
      const fix = await this.hmafSession?.sendTask({
        targetAgent: agent.id,
        taskType: 'fix_suggestion',
        parameters: {
          vulnerability: JSON.stringify(vuln),
          language: 'arkts'
        },
        timeout: 20000
      });

      fixes[vuln.id] = fix?.suggestion || '暂无修复建议';
    }

    this.updateAgentState(agent.id, 'idle');
    return fixes;
  }

  private async executeComplianceCheck(vulns: Vulnerability[]): Promise<<Record<string, boolean>> {
    const agent = this.findAvailableAgent('compliance');
    if (!agent) return {};

    this.updateAgentState(agent.id, 'analyzing');

    const compliance: Record<string, boolean> = {};
    for (const vuln of vulns) {
      const check = await this.hmafSession?.sendTask({
        targetAgent: agent.id,
        taskType: 'compliance_check',
        parameters: {
          cweId: vuln.cweId,
          standard: 'OWASP_TOP10_2026'
        },
        timeout: 10000
      });

      compliance[vuln.id] = check?.compliant || false;
    }

    this.updateAgentState(agent.id, 'idle');
    return compliance;
  }

  private findAvailableAgent(type: string): AgentInstance | null {
    for (const [id, agent] of this.agents.entries()) {
      if (agent.type === type && agent.status === 'idle') {
        return agent;
      }
    }
    return null;
  }

  private updateAgentState(agentId: string, state: string): void {
    const agent = this.agents.get(agentId);
    if (agent) {
      agent.status = state as 'idle' | 'scanning' | 'analyzing' | 'completed' | 'error';
      
      // 触发全局状态更新,驱动光效变化
      AppStorage.setOrCreate('agent_state_update', {
        agentId: agentId,
        state: state,
        timestamp: Date.now()
      });

      // 根据风险等级更新全局光效
      if (state === 'scanning') {
        AppStorage.setOrCreate('risk_level_change', RiskLevel.MEDIUM);
      }
    }
  }

  private formatAuditReport(vulns: Vulnerability[], fixes: Record<string, string>, compliance: Record<string, boolean>): string {
    let report = '## 🔒 代码安全审计报告\n\n';
    
    const criticalCount = vulns.filter(v => v.severity === RiskLevel.CRITICAL).length;
    const highCount = vulns.filter(v => v.severity === RiskLevel.HIGH).length;
    const mediumCount = vulns.filter(v => v.severity === RiskLevel.MEDIUM).length;
    const lowCount = vulns.filter(v => v.severity === RiskLevel.LOW).length;
    const infoCount = vulns.filter(v => v.severity === RiskLevel.INFO).length;

    report += `### 风险统计\n`;
    report += `- 🔴 严重: ${criticalCount}\n`;
    report += `- 🟠 高危: ${highCount}\n`;
    report += `- 🟡 中危: ${mediumCount}\n`;
    report += `- 🟢 低危: ${lowCount}\n`;
    report += `- 🔵 信息: ${infoCount}\n\n`;

    report += `### 漏洞详情\n`;
    for (const vuln of vulns) {
      report += `#### ${vuln.id} - ${vuln.type}\n`;
      report += `- **风险等级**: ${vuln.severity}\n`;
      report += `- **CVSS评分**: ${vuln.cvssScore}\n`;
      report += `- **CWE编号**: ${vuln.cweId}\n`;
      report += `- **代码位置**: 第${vuln.lineNumber}行\n`;
      report += `- **代码片段**: \n\`\`\`arkts\n${vuln.codeSnippet}\n\`\`\`\n`;
      report += `- **描述**: ${vuln.description}\n`;
      report += `- **修复建议**: ${fixes[vuln.id] || '暂无'}\n`;
      report += `- **合规状态**: ${compliance[vuln.id] ? '✅ 合规' : '❌ 不合规'}\n\n`;
    }

    return report;
  }

  getVulnerabilityCount(): Record<RiskLevel, number> {
    const counts: Record<RiskLevel, number> = {
      [RiskLevel.INFO]: 0,
      [RiskLevel.LOW]: 0,
      [RiskLevel.MEDIUM]: 0,
      [RiskLevel.HIGH]: 0,
      [RiskLevel.CRITICAL]: 0
    };

    for (const vuln of this.vulnerabilities) {
      counts[vuln.severity]++;
    }

    return counts;
  }

  getAgentStatus(): Array<{id: string, type: string, status: string, task: string | null}> {
    return Array.from(this.agents.values()).map(agent => ({
      id: agent.id,
      type: agent.type,
      status: agent.status,
      task: agent.currentTask?.taskType || null
    }));
  }
}

5.4 悬浮审计导航(AuditFloatNavigation.ets)

代码亮点:底部悬浮导航栏不仅承载页面切换功能,更重要的是实时显示审计任务状态和漏洞数量。每个导航项配备风险徽章------信息级蓝色光点、低危级绿色光点、中危级黄色脉冲、高危级橙色脉冲、严重级红色闪烁。支持长按展开透明度调节面板。

typescript 复制代码
// entry/src/main/ets/components/AuditFloatNavigation.ets
import { window } from '@kit.ArkUI';
import { RiskLevel, RiskColors } from './RiskLightEffect';

// 导航项配置
interface AuditNavItem {
  id: string;
  icon: Resource;
  label: string;
  page: string;
  agentType?: 'miner' | 'rater' | 'fixer' | 'compliance';
}

@Component
export struct AuditFloatNavigation {
  @State currentIndex: number = 0;
  @State navTransparency: number = 0.70;
  @State isExpanded: boolean = false;
  @State bottomAvoidHeight: number = 0;
  @State agentStates: Map<string, string> = new Map([
    ['miner-1', 'idle'],
    ['miner-2', 'idle'],
    ['rater-1', 'idle'],
    ['fixer-1', 'idle'],
    ['compliance-1', 'idle']
  ]);
  @State vulnCounts: Record<RiskLevel, number> = {
    [RiskLevel.INFO]: 0,
    [RiskLevel.LOW]: 0,
    [RiskLevel.MEDIUM]: 0,
    [RiskLevel.HIGH]: 0,
    [RiskLevel.CRITICAL]: 0
  };

  private navItems: AuditNavItem[] = [
    { id: 'code', icon: $r('app.media.ic_code'), label: '代码', page: 'CodePage' },
    { id: 'vulns', icon: $r('app.media.ic_vuln'), label: '漏洞', page: 'VulnPage', agentType: 'miner' },
    { id: 'risk', icon: $r('app.media.ic_risk'), label: '风险', page: 'RiskPage', agentType: 'rater' },
    { id: 'fixes', icon: $r('app.media.ic_fix'), label: '修复', page: 'FixPage', agentType: 'fixer' },
    { id: 'compliance', icon: $r('app.media.ic_compliance'), label: '合规', page: 'CompliancePage', agentType: 'compliance' }
  ];

  aboutToAppear(): void {
    this.getBottomAvoidArea();
    // 监听智能体状态变化
    AppStorage.setOrCreate('agent_state_update', (update: {agentId: string, state: string}) => {
      this.agentStates.set(update.agentId, update.state);
    });
    // 监听漏洞数量变化
    AppStorage.setOrCreate('vuln_count_update', (counts: Record<RiskLevel, number>) => {
      this.vulnCounts = counts;
    });
  }

  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 getAgentStateForNavItem(item: AuditNavItem): string {
    if (!item.agentType) return 'idle';
    
    const agentId = item.id === 'vulns' ? 'miner-1' :
                   item.id === 'risk' ? 'rater-1' :
                   item.id === 'fixes' ? 'fixer-1' :
                   item.id === 'compliance' ? 'compliance-1' : '';
    return this.agentStates.get(agentId) || 'idle';
  }

  private getTotalVulnCount(): number {
    return Object.values(this.vulnCounts).reduce((a, b) => a + b, 0);
  }

  private getHighestRiskLevel(): RiskLevel {
    if (this.vulnCounts[RiskLevel.CRITICAL] > 0) return RiskLevel.CRITICAL;
    if (this.vulnCounts[RiskLevel.HIGH] > 0) return RiskLevel.HIGH;
    if (this.vulnCounts[RiskLevel.MEDIUM] > 0) return RiskLevel.MEDIUM;
    if (this.vulnCounts[RiskLevel.LOW] > 0) return RiskLevel.LOW;
    return RiskLevel.INFO;
  }

  private getStateBadgeColor(state: string): string {
    const colors: Record<string, string> = {
      'idle': '#888888',
      'scanning': '#4A90D9',
      'analyzing': '#F5A623',
      'completed': '#2ECC71',
      'error': '#FF4444'
    };
    return colors[state] || '#888888';
  }

  private getStateBadgeAnimation(state: string): object {
    switch (state) {
      case 'scanning':
        return {
          duration: 1500,
          curve: Curve.EaseInOut,
          iterations: -1,
          playMode: PlayMode.Alternate
        };
      case 'analyzing':
        return {
          duration: 1000,
          curve: Curve.Linear,
          iterations: -1
        };
      case 'error':
        return {
          duration: 500,
          curve: Curve.EaseInOut,
          iterations: -1,
          playMode: PlayMode.Alternate
        };
      default:
        return { duration: 0 };
    }
  }

  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: [
                ['rgba(255,255,255,0.15)', 0.0],
                ['rgba(255,255,255,0.05)', 1.0]
              ]
            })
        }
        .width('100%')
        .height('100%')
        .borderRadius(24)
        .shadow({
          radius: 20,
          color: 'rgba(0,0,0,0.2)',
          offsetX: 0,
          offsetY: -4
        })

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

                // 漏洞数量徽章
                if (item.id === 'vulns' && this.getTotalVulnCount() > 0) {
                  Column() {
                    Text(`${this.getTotalVulnCount()}`)
                      .fontSize(10)
                      .fontColor('#FFFFFF')
                  }
                  .width(18)
                  .height(18)
                  .backgroundColor(RiskColors[this.getHighestRiskLevel()])
                  .borderRadius(9)
                  .position({ x: 16, y: -8 })
                  .shadow({
                    radius: 6,
                    color: RiskColors[this.getHighestRiskLevel()],
                    offsetX: 0,
                    offsetY: 0
                  })
                }

                // 智能体状态徽章
                if (item.agentType && this.getAgentStateForNavItem(item) !== 'idle') {
                  Column()
                    .width(8)
                    .height(8)
                    .backgroundColor(this.getStateBadgeColor(this.getAgentStateForNavItem(item)))
                    .borderRadius(4)
                    .position({ x: 20, y: -4 })
                    .shadow({
                      radius: 4,
                      color: this.getStateBadgeColor(this.getAgentStateForNavItem(item)),
                      offsetX: 0,
                      offsetY: 0
                    })
                    .animation(this.getStateBadgeAnimation(this.getAgentStateForNavItem(item)))
                }
              }
              .width(40)
              .height(40)

              Text(item.label)
                .fontSize(11)
                .fontColor(this.currentIndex === index ? RiskColors[this.getHighestRiskLevel()] : '#999999')
                .margin({ top: 4 })
            }
            .layoutWeight(1)
            .onClick(() => {
              this.currentIndex = index;
              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 代码编辑器与风险高亮(CodeEditor.ets)

代码亮点:实现具有风险高亮功能的代码编辑器。根据审计结果,在代码行号旁显示风险标记,高危行背景脉冲闪烁,中危行背景柔和呼吸,低危行背景轻微变色。

typescript 复制代码
// entry/src/main/ets/components/CodeEditor.ets
import { RiskLevel, RiskColors } from './RiskLightEffect';

interface CodeLine {
  lineNumber: number;
  content: string;
  riskLevel: RiskLevel | null;
  vulnId: string | null;
}

@Component
export struct CodeEditor {
  @State codeLines: CodeLine[] = [];
  @State selectedLine: number = -1;
  @State currentRiskColor: string = '#4A90D9';
  @State currentRiskIntensity: number = 0.4;

  aboutToAppear(): void {
    // 监听风险等级变化
    AppStorage.setOrCreate('current_risk_color', (color: string) => {
      this.currentRiskColor = color;
    });
    AppStorage.setOrCreate('current_risk_intensity', (intensity: number) => {
      this.currentRiskIntensity = intensity;
    });
  }

  private getLineBackground(line: CodeLine): string {
    if (!line.riskLevel) return 'transparent';
    
    const color = RiskColors[line.riskLevel];
    const opacity = line.riskLevel === RiskLevel.CRITICAL ? 0.3 :
                   line.riskLevel === RiskLevel.HIGH ? 0.2 :
                   line.riskLevel === RiskLevel.MEDIUM ? 0.15 :
                   line.riskLevel === RiskLevel.LOW ? 0.1 : 0.05;
    
    return `${color}${Math.round(opacity * 255).toString(16).padStart(2, '0')}`;
  }

  private getLineBorderColor(line: CodeLine): string {
    if (!line.riskLevel) return 'transparent';
    return RiskColors[line.riskLevel];
  }

  private getLineAnimation(line: CodeLine): object {
    if (line.riskLevel === RiskLevel.CRITICAL) {
      return {
        duration: 500,
        curve: Curve.EaseInOut,
        iterations: -1,
        playMode: PlayMode.Alternate
      };
    }
    if (line.riskLevel === RiskLevel.HIGH) {
      return {
        duration: 1500,
        curve: Curve.EaseInOut,
        iterations: -1,
        playMode: PlayMode.Alternate
      };
    }
    return { duration: 0 };
  }

  build() {
    List() {
      ForEach(this.codeLines, (line: CodeLine) => {
        ListItem() {
          Row() {
            // 行号
            Text(`${line.lineNumber}`)
              .fontSize(12)
              .fontColor('#666666')
              .width(50)
              .textAlign(TextAlign.End)
              .padding({ right: 12 })

            // 风险标记
            if (line.riskLevel) {
              Column()
                .width(6)
                .height(6)
                .backgroundColor(RiskColors[line.riskLevel])
                .borderRadius(3)
                .margin({ right: 8 })
                .shadow({
                  radius: 4,
                  color: RiskColors[line.riskLevel],
                  offsetX: 0,
                  offsetY: 0
                })
                .animation(this.getLineAnimation(line))
            } else {
              Column()
                .width(6)
                .height(6)
                .margin({ right: 8 })
            }

            // 代码内容
            Text(line.content)
              .fontSize(14)
              .fontColor('#FFFFFF')
              .fontFamily('monospace')
              .lineHeight(20)
              .layoutWeight(1)

            // 漏洞ID(如果有)
            if (line.vulnId) {
              Text(line.vulnId)
                .fontSize(10)
                .fontColor(RiskColors[line.riskLevel || RiskLevel.INFO])
                .backgroundColor('rgba(0,0,0,0.3)')
                .borderRadius(4)
                .padding({ left: 6, right: 6, top: 2, bottom: 2 })
                .margin({ left: 8 })
            }
          }
          .width('100%')
          .height(32)
          .padding({ left: 16, right: 16 })
          .backgroundColor(this.getLineBackground(line))
          .border({
            width: { left: 2 },
            color: this.getLineBorderColor(line)
          })
          .animation(this.getLineAnimation(line))
          .onClick(() => {
            this.selectedLine = line.lineNumber;
            if (line.vulnId) {
              AppStorage.setOrCreate('selected_vuln_id', line.vulnId);
            }
          })
        }
      })
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#0f0f23')
  }
}

5.6 浮动漏洞详情窗口(VulnDetailWindow.ets)

代码亮点 :实现可拖拽的浮动漏洞详情面板,支持漏洞信息展示、修复方案预览、风险趋势图。窗口激活时边缘发光增强,失活时自动降低光效强度,通过WindowManager与主窗口光效联动。

typescript 复制代码
// entry/src/main/ets/windows/VulnDetailWindow.ets
import { window } from '@kit.ArkUI';
import { RiskLevel, RiskColors } from '../components/RiskLightEffect';

@Component
export struct VulnDetailWindow {
  @State isActive: boolean = false;
  @State currentVuln: {id: string, type: string, severity: RiskLevel, description: string} | null = null;
  @State windowLightColor: string = '#4A90D9';
  @State lightIntensity: number = 0.6;

  private mainWindow: window.Window | null = null;

  aboutToAppear(): void {
    this.setupWindow();
    // 监听主窗口光效变化
    AppStorage.setOrCreate('current_risk_color', (color: string) => {
      this.windowLightColor = color;
    });
    // 监听选中漏洞变化
    AppStorage.setOrCreate('selected_vuln_id', (vulnId: string) => {
      this.loadVulnDetail(vulnId);
    });
  }

  private async setupWindow(): Promise<void> {
    try {
      this.mainWindow = await window.getLastWindow();
      await this.mainWindow.setWindowBackgroundColor('#00000000');
      
      // 设置窗口为浮动样式
      await this.mainWindow.setWindowDecorVisible(false);
      await this.mainWindow.resize(450, 700);
      
      // 监听窗口焦点变化
      this.mainWindow.on('windowFocusChange', (isFocused: boolean) => {
        this.isActive = isFocused;
        this.lightIntensity = isFocused ? 0.8 : 0.3;
      });
    } catch (error) {
      console.error('Failed to setup vuln detail window:', error);
    }
  }

  private loadVulnDetail(vulnId: string): void {
    // 从全局状态加载漏洞详情
    const vulnDetail = AppStorage.get<<Record<string, unknown>>(`vuln_${vulnId}`);
    if (vulnDetail) {
      this.currentVuln = {
        id: vulnId,
        type: vulnDetail.type as string,
        severity: vulnDetail.severity as RiskLevel,
        description: vulnDetail.description as string
      };
    }
  }

  build() {
    Stack() {
      // 窗口边框光效
      Column()
        .width('100%')
        .height('100%')
        .backgroundColor('transparent')
        .border({
          width: 2,
          color: `${this.windowLightColor}${this.isActive ? 'FF' : '40'}`,
          style: BorderStyle.Solid
        })
        .borderRadius(16)
        .animation({
          duration: 300,
          curve: Curve.EaseInOut
        })

      // 内容层
      Column() {
        // 标题栏
        Row() {
          Text('🔍 漏洞详情')
            .fontSize(16)
            .fontColor('#FFFFFF')
            .fontWeight(FontWeight.Bold)

          if (this.currentVuln) {
            Text(this.currentVuln.severity)
              .fontSize(12)
              .fontColor('#FFFFFF')
              .backgroundColor(RiskColors[this.currentVuln.severity])
              .borderRadius(8)
              .padding({ left: 8, right: 8, top: 4, bottom: 4 })
          }
        }
        .width('100%')
        .justifyContent(FlexAlign.SpaceBetween)
        .padding(16)

        // 漏洞信息
        if (this.currentVuln) {
          Column() {
            Text(`漏洞ID: ${this.currentVuln.id}`)
              .fontSize(14)
              .fontColor('#FFFFFF')
              .margin({ bottom: 8 })

            Text(`类型: ${this.currentVuln.type}`)
              .fontSize(14)
              .fontColor('#AAAAAA')
              .margin({ bottom: 8 })

            Text(`描述: ${this.currentVuln.description}`)
              .fontSize(13)
              .fontColor('#CCCCCC')
              .lineHeight(20)
          }
          .width('100%')
          .padding(16)
          .backgroundColor('rgba(255,255,255,0.05)')
          .borderRadius(12)
          .margin({ bottom: 16 })
        }

        // 修复方案
        Column() {
          Text('🔧 修复方案')
            .fontSize(16)
            .fontColor('#FFFFFF')
            .fontWeight(FontWeight.Bold)
            .margin({ bottom: 12 })

          Text('// 修复后的安全代码示例')
            .fontSize(13)
            .fontColor('rgba(255,255,255,0.6)')
            .fontFamily('monospace')
            .lineHeight(20)
            .width('100%')
            .height('100%')
            .padding(16)
            .backgroundColor('rgba(0,0,0,0.3)')
            .borderRadius(8)
        }
        .width('100%')
        .layoutWeight(1)
        .padding(16)
      }
      .width('100%')
      .height('100%')
      .padding(2) // 为边框光效留出空间
    }
    .width('100%')
    .height('100%')
    .backgroundColor('rgba(15,15,35,0.95)')
    .borderRadius(16)
    .shadow({
      radius: 30,
      color: `${this.windowLightColor}${this.isActive ? '40' : '15'}`,
      offsetX: 0,
      offsetY: 0
    })
    .animation({
      duration: 300,
      curve: Curve.EaseInOut
    })
  }
}

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

代码亮点:管理主窗口与浮动漏洞详情窗口、风险热力图窗口、修复方案窗口之间的光效联动。当风险等级变化时,所有窗口同步切换主题色;当窗口焦点变化时,自动调整光效强度,形成层次分明的视觉体验。

typescript 复制代码
// entry/src/main/ets/managers/WindowLightSync.ets
import { window } from '@kit.ArkUI';
import { RiskLevel, RiskColors } from '../components/RiskLightEffect';

// 窗口类型
export enum WindowType {
  MAIN = 'main',
  VULN_DETAIL = 'vuln_detail',
  RISK_HEATMAP = 'risk_heatmap',
  FIX_PREVIEW = 'fix_preview'
}

// 光效主题
export interface LightTheme {
  primaryColor: string;
  secondaryColor: string;
  intensity: number;
  pulseSpeed: number;
  glowRadius: number;
}

export class WindowLightSync {
  private static instance: WindowLightSync;
  private windows: Map<<WindowType, window.Window> = new Map();
  private currentTheme: LightTheme = {
    primaryColor: '#4A90D9',
    secondaryColor: '#6BB6FF',
    intensity: 0.6,
    pulseSpeed: 2000,
    glowRadius: 100
  };
  private focusWindow: WindowType = WindowType.MAIN;

  private constructor() {}

  static getInstance(): WindowLightSync {
    if (!WindowLightSync.instance) {
      WindowLightSync.instance = new WindowLightSync();
    }
    return WindowLightSync.instance;
  }

  registerWindow(type: WindowType, win: window.Window): void {
    this.windows.set(type, win);
    
    // 监听窗口焦点
    win.on('windowFocusChange', (isFocused: boolean) => {
      if (isFocused) {
        this.focusWindow = type;
        this.updateFocusLightEffect();
      }
    });
  }

  // 同步所有窗口光效
  async syncLightEffect(theme: LightTheme): Promise<void> {
    this.currentTheme = theme;
    
    for (const [type, win] of this.windows.entries()) {
      try {
        const isFocused = type === this.focusWindow;
        const intensity = isFocused ? theme.intensity : theme.intensity * 0.4;
        
        // 设置窗口背景光效
        await win.setWindowBackgroundColor(`#00000000`);
        
        // 同步到AppStorage供各窗口组件读取
        AppStorage.setOrCreate(`window_${type}_color`, theme.primaryColor);
        AppStorage.setOrCreate(`window_${type}_intensity`, intensity);
        AppStorage.setOrCreate(`window_${type}_focused`, isFocused);
        
      } catch (error) {
        console.error(`Failed to sync light effect for ${type}:`, error);
      }
    }
  }

  // 根据风险等级更新主题
  updateThemeByRiskLevel(level: RiskLevel): void {
    const themes: Record<RiskLevel, LightTheme> = {
      [RiskLevel.INFO]: {
        primaryColor: RiskColors[RiskLevel.INFO],
        secondaryColor: '#6BB6FF',
        intensity: 0.4,
        pulseSpeed: 4000,
        glowRadius: 80
      },
      [RiskLevel.LOW]: {
        primaryColor: RiskColors[RiskLevel.LOW],
        secondaryColor: '#7EE8A0',
        intensity: 0.5,
        pulseSpeed: 3000,
        glowRadius: 100
      },
      [RiskLevel.MEDIUM]: {
        primaryColor: RiskColors[RiskLevel.MEDIUM],
        secondaryColor: '#FFD93D',
        intensity: 0.7,
        pulseSpeed: 2000,
        glowRadius: 120
      },
      [RiskLevel.HIGH]: {
        primaryColor: RiskColors[RiskLevel.HIGH],
        secondaryColor: '#FF8888',
        intensity: 0.9,
        pulseSpeed: 1000,
        glowRadius: 150
      },
      [RiskLevel.CRITICAL]: {
        primaryColor: RiskColors[RiskLevel.CRITICAL],
        secondaryColor: '#FF4444',
        intensity: 1.0,
        pulseSpeed: 500,
        glowRadius: 200
      }
    };

    const theme = themes[level] || themes[RiskLevel.INFO];
    this.syncLightEffect(theme);
  }

  private updateFocusLightEffect(): void {
    // 重新应用当前主题,根据新的焦点窗口调整强度
    this.syncLightEffect(this.currentTheme);
  }

  // 创建浮动窗口
  async createFloatWindow(type: WindowType, width: number, height: number, x: number, y: number): Promise<<window.Window> {
    try {
      const floatWindow = await window.createWindow({
        name: type,
        windowType: window.WindowType.TYPE_FLOAT,
        ctx: getContext()
      });

      await floatWindow.moveWindowTo(x, y);
      await floatWindow.resize(width, height);
      await floatWindow.setWindowBackgroundColor('#00000000');
      await floatWindow.showWindow();

      this.registerWindow(type, floatWindow);
      return floatWindow;
    } catch (error) {
      console.error(`Failed to create float window ${type}:`, error);
      throw error;
    }
  }
}

5.8 主页面集成(Index.ets)

typescript 复制代码
// entry/src/main/ets/pages/Index.ets
import { CodeEditor } from '../components/CodeEditor';
import { AuditAgentScheduler } from '../services/AuditAgentScheduler';
import { WindowLightSync, WindowType } from '../managers/WindowLightSync';
import { VulnDetailWindow } from '../windows/VulnDetailWindow';

@Entry
@Component
struct Index {
  private scheduler: AuditAgentScheduler = AuditAgentScheduler.getInstance();
  private lightSync: WindowLightSync = WindowLightSync.getInstance();

  aboutToAppear(): void {
    this.initializeWindows();
    this.initializeScheduler();
  }

  private async initializeScheduler(): Promise<void> {
    await this.scheduler.initialize();
  }

  private async initializeWindows(): Promise<void> {
    try {
      const mainWindow = await window.getLastWindow();
      this.lightSync.registerWindow(WindowType.MAIN, mainWindow);

      // 创建浮动漏洞详情窗口(PC端特有)
      if (deviceInfo.deviceType === '2in1' || deviceInfo.deviceType === 'tablet') {
        await this.lightSync.createFloatWindow(
          WindowType.VULN_DETAIL,
          450, 700,
          100, 100
        );
      }
    } catch (error) {
      console.error('Failed to initialize windows:', error);
    }
  }

  build() {
    Stack() {
      // 动态环境光背景
      Column() {
        Column()
          .width(400)
          .height(400)
          .backgroundColor(AppStorage.get<string>('current_risk_color') || '#4A90D9')
          .blur(150)
          .opacity(AppStorage.get<number>('current_risk_intensity') || 0.4)
          .position({ x: '50%', y: '30%' })
          .anchor('50%')
          .animation({
            duration: 3000,
            curve: Curve.EaseInOut,
            iterations: -1,
            playMode: PlayMode.Alternate
          })
      }
      .width('100%')
      .height('100%')
      .backgroundColor('#0a0a0f')

      // 内容层
      Column() {
        // 代码编辑器
        CodeEditor()
          .layoutWeight(1)
      }
      .width('100%')
      .height('100%')
    }
    .width('100%')
    .height('100%')
  }
}

六、关键技术总结

6.1 HMAF智能体审计开发清单

技术点 API/方法 应用场景
智能体会话创建 hmaf.createAgentSession({ mode: MULTI_AGENT }) 多智能体协作审计
意图解析 intents.createIntentEngine({ supportedDomains }) 开发者审计意图理解
任务分发 hmafSession.sendTask({ targetAgent, taskType }) 智能体间审计任务调度
状态监听 AppStorage全局状态回调 跨组件审计状态同步
分布式协同 enableDistributed: true 多设备审计协作
端侧推理 MindSpore Lite 隐私敏感代码本地审计

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 风险等级光效映射

风险等级 光效颜色 脉冲速度 光晕半径 视觉语义
信息 #4A90D9 4000ms 80px 柔和呼吸,提示信息
低危 #2ECC71 3000ms 100px 平静脉冲,轻微关注
中危 #F5A623 2000ms 120px 警示脉冲,需要处理
高危 #FF6B6B 1000ms 150px 急促流光,紧急处理
严重 #FF0000 500ms 200px 警示闪烁,立即处理

6.4 PC端多窗口光效协同

  • 主窗口:全屏沉浸,风险等级光效延伸至所有安全区边缘
  • 浮动漏洞详情窗口:置顶、圆角、阴影,激活时边缘发光增强
  • 光效同步 :通过WindowLightSync管理器实现跨窗口主题色联动
  • 焦点感知:窗口激活时边缘发光增强,失活时自动降低光效强度
  • 风险等级一致性:同一风险等级在所有窗口中保持相同色彩标识

七、调试与适配建议

  1. HMAF会话管理:多智能体并发时注意会话资源释放,避免内存泄漏
  2. 光效功耗优化:夜间模式降低光效刷新率,延长OLED屏幕寿命
  3. 意图识别校准:不同审计场景需训练专用意图模型,提升解析准确率
  4. 分布式设备测试:测试跨设备审计协作时的网络延迟与状态同步
  5. 无障碍支持:为视障开发者提供语音播报审计结果,光效切换时播放提示音
  6. 隐私保护:敏感代码审计本地处理,仅上传脱敏后的审计日志

八、总结与展望

本文基于HarmonyOS 6(API 23)的悬浮导航沉浸光感HMAF智能体框架特性,完整实战了一款面向PC端的"代码哨兵"AI智能体代码安全审计平台。核心创新点总结:

  1. HMAF四层审计架构:基于Agent Framework Kit构建"漏洞挖掘-风险评级-修复建议-合规验证"四层智能体协作体系,实现意图理解→漏洞扫描→风险评级→修复建议→合规验证的完整审计工作流

  2. 风险等级光效系统:每个风险等级拥有专属光效标识(信息蓝、低危绿、中危黄、高危橙、严重红),根据审计结果动态切换脉冲节奏与光晕强度,实现"风险直觉感知"

  3. 悬浮审计导航:底部悬浮页签不仅承载页面切换,更实时显示审计任务状态徽章(扫描脉冲、分析进度、漏洞数量角标),玻璃拟态设计+三档透明度调节

  4. PC级多窗口审计协作 :主代码窗口 + 浮动漏洞详情面板 + 浮动风险热力图 + 浮动修复方案窗口的四层架构,通过WindowLightSync实现跨窗口光效联动与焦点感知

  5. 实时漏洞感知:通过Intents Kit实时理解代码上下文,自动调整界面光效与导航形态,实现"风险即氛围"的自然交互

未来扩展方向

  • 接入分布式软总线4.0,实现PC主控+手机预览+平板代码审查的多设备审计协同
  • AI智能体审计市场:支持第三方开发者发布自定义审计智能体,通过光效标识区分审计能力类型
  • 数字孪生集成:接入IoT设备数据,智能体自动感知物理世界安全状态并调整审计策略
  • VR/AR融合:支持VR头显接入,实现完全沉浸式的3D代码安全审计空间
  • 长期记忆进化:基于开发者历史审计数据,智能体逐步学习开发者偏好,光效个性化适配

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

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

相关推荐
云安全助手1 小时前
谁能定义云安全AI时代?——具有“安全原生”的聚合与防护平台
人工智能·ai·claude
梅西库里RNG2 小时前
AI学习纪要——基础篇
人工智能·学习
梦想的颜色2 小时前
2026最新Claude Code 规范文件 CLAUDE.md 全面解析与超全模板
人工智能·小程序
多年小白2 小时前
芯片/半导体/CPO光模块 深度分析报告
人工智能·深度学习·microsoft·ai
wujian83112 小时前
AI表格怎么导出word
人工智能·ai·word·豆包·deepseek·ai导出鸭
初心未改HD2 小时前
深度学习之损失函数详解
人工智能·深度学习
ze^02 小时前
Day01 Web应用&架构搭建&域名源码&站库分离&MVC模型&解析受限&对应路径
安全·web安全·架构·mvc·安全架构
Asize2 小时前
重生之我在 Vibe Coding 时代当程序员:第一课,Prompt Engineering
人工智能
Aaron15882 小时前
RFSOC+VU13P/VU9P+GPU多通道同步一体化解决方案
人工智能·嵌入式硬件·算法·matlab·fpga开发·硬件架构·基带工程