文章目录
-
- 每日一句正能量
- 前言
- 一、前言: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 智能体状态光效系统(AgentLightEffect.ets)](#5.2 智能体状态光效系统(AgentLightEffect.ets))
- [5.3 HMAF智能体调度器(AgentScheduler.ets)](#5.3 HMAF智能体调度器(AgentScheduler.ets))
- [5.4 悬浮智能体导航(AgentFloatNavigation.ets)](#5.4 悬浮智能体导航(AgentFloatNavigation.ets))
- [5.5 智能体对话页面(ChatPage.ets)](#5.5 智能体对话页面(ChatPage.ets))
- [5.6 浮动工具面板窗口(ToolPanelWindow.ets)](#5.6 浮动工具面板窗口(ToolPanelWindow.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 6(API 23)引入的鸿蒙智能体框架(HMAF)将AI能力从应用层下沉至系统层,配合悬浮导航与沉浸光感特性,为AI智能体应用开发开辟了全新范式。本文将实战开发一款面向HarmonyOS PC的"灵犀智脑"应用,展示如何利用HMAF构建多智能体协作工作流,通过悬浮导航实现智能体状态切换,基于沉浸光感打造"意图即氛围"的交互体验,以及基于多窗口架构构建浮动智能体对话、工具面板和知识库窗口的协作编排体验。
一、前言:AI智能体时代的交互范式革新
2026年,AI Agent(智能体)已成为技术领域最火热的方向。HarmonyOS 6开发者Beta版引入了全新的鸿蒙智能体框架(Harmony Intelligent Agent Framework,HMAF),这一框架的核心在于将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将用户自然语言意图转化为结构化任务,自动分发给合适的智能体
- 分布式智能体协同:利用鸿蒙分布式软总线,实现PC主控+手机传感器+平板显示的多设备智能体协作
- 端云协同推理:端侧MindSpore Lite处理隐私敏感任务,云端大模型处理复杂推理任务
2.2 沉浸光感在智能体交互中的创新应用
HarmonyOS 6的systemMaterialEffect通过模拟物理光照模型,为智能体状态反馈带来细腻的视觉表达。在AI智能体场景中,这种材质效果能够:
- 增强智能体人格化:不同智能体拥有专属光效人格(调度器冷峻蓝、执行器活力橙、验证器严谨绿)
- 状态直觉感知:思考时的呼吸蓝光、执行时的脉冲金光、异常时的警示红光,用户无需阅读文字即可感知智能体状态
- 提升沉浸专注度:动态环境光随任务复杂度变化,简单任务柔和、复杂任务强烈,帮助用户保持专注
2.3 悬浮导航的智能体适配
与传统工具类应用不同,AI智能体平台需要处理:
- 高频智能体切换:用户常在多个智能体间快速跳转查看状态
- 状态信息密度平衡:既要保证导航可见,又不能遮挡对话内容
- 实时状态徽章:智能体运行状态需要实时徽章提示(小红点、数字角标、脉冲光效)
HarmonyOS 6的悬浮页签支持**强(85%)、平衡(70%)、弱(55%)**三档透明度自定义,结合PC端的自由窗口能力,可以实现"需要时出现,专注时隐退"的智能导航体验。
三、项目实战:"灵犀智脑"架构设计
3.1 应用场景与功能规划
面向HarmonyOS PC的AI智能体编排场景,核心功能包括:
| 功能模块 | 技术实现 | 沉浸光感/HMAF应用 |
|---|---|---|
| 主对话窗口 | List + ChatBubble |
智能体人格光效、思考呼吸灯 |
| 悬浮智能体导航 | HdsTabs + systemMaterialEffect |
玻璃拟态页签,状态徽章光效 |
| 智能体调度器 | HMAF Agent Framework Kit | 调度决策光效反馈 |
| 智能体执行器 | HMAF + Function Calling | 执行进度光效脉冲 |
| 智能体验证器 | HMAF + 规则引擎 | 验证结果光效标记 |
| 浮动工具面板 | 子窗口 + HdsNavigation |
工具主题色光效同步 |
| 浮动知识库窗口 | 子窗口 + Grid |
知识热度光效 |
| 浮动日志窗口 | 子窗口 + List |
日志级别颜色编码 |
3.2 技术架构图
┌─────────────────────────────────────────────────────────────┐
│ 灵犀智脑 - 应用层 │
├─────────────┬─────────────┬─────────────┬─────────────────────┤
│ 调度器智能体 │ 执行器智能体 │ 验证器智能体 │ 知识库管理器 │
│ (Scheduler) │ (Executor) │ (Validator) │ (KnowledgeBase) │
├─────────────┴─────────────┴─────────────┴─────────────────────┤
│ HMAF - 智能体框架层 │
│ Agent Framework Kit + Intents Kit + NLU Kit │
├─────────────────────────────────────────────────────────────┤
│ AI系统底座 - 能力层 │
│ MindSpore Lite(端侧) │ 鸿蒙大模型4.0(云端) │ 分布式软总线 │
├─────────────────────────────────────────────────────────────┤
│ ArkUI - 表现层 │
│ 悬浮导航 │ 沉浸光感 │ 多窗口管理 │ 安全区扩展 │ 动画系统 │
└─────────────────────────────────────────────────────────────┘
四、环境配置与模块依赖
4.1 模块依赖配置
在oh-package.json5中添加HMAF及相关Kit依赖:
json
{
"name": "lingxi_brain",
"version": "1.0.0",
"description": "AI Agent Workflow Orchestration 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"
}
}
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.MICROPHONE",
"reason": "$string:microphone_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 智能体状态光效系统(AgentLightEffect.ets)
代码亮点 :这是本应用的核心创新组件。它将HMAF智能体运行状态映射为动态光效------待机时柔和呼吸、思考时快速脉冲、执行时进度流光、完成时确认闪光、异常时警示闪烁。每个智能体拥有专属人格色彩(调度器冷峻蓝、执行器活力橙、验证器严谨绿),通过AppStorage全局状态实现跨组件光效同步。
typescript
// entry/src/main/ets/components/AgentLightEffect.ets
import { hmaf } from '@kit.HMAFramework';
// 智能体状态枚举
export enum AgentState {
IDLE = 'idle', // 待机
THINKING = 'thinking', // 思考中
EXECUTING = 'executing', // 执行中
COMPLETED = 'completed', // 已完成
ERROR = 'error' // 异常
}
// 智能体人格色彩
export enum AgentPersonality {
SCHEDULER = { color: '#4A90D9', name: '调度器', icon: $r('app.media.ic_scheduler') },
EXECUTOR = { color: '#F5A623', name: '执行器', icon: $r('app.media.ic_executor') },
VALIDATOR = { color: '#2ECC71', name: '验证器', icon: $r('app.media.ic_validator') }
}
// 光效配置
interface LightEffectConfig {
baseColor: string;
pulseSpeed: number; // 脉冲周期(ms)
pulseIntensity: number; // 脉冲强度(0-1)
glowRadius: number; // 光晕半径
particleCount: number; // 粒子数量
}
@Component
export struct AgentLightEffect {
@State agentState: AgentState = AgentState.IDLE;
@State agentType: AgentPersonality = AgentPersonality.SCHEDULER;
@State lightIntensity: number = 0.4;
@State pulsePhase: number = 0;
@State particlePositions: Array<{x: number, y: number, size: number, opacity: number}> = [];
private pulseTimer: number = -1;
private particleTimer: number = -1;
aboutToAppear(): void {
this.startPulseAnimation();
this.startParticleAnimation();
// 监听全局智能体状态变化
AppStorage.setOrCreate('agent_state_change', (state: AgentState, type: AgentPersonality) => {
this.agentState = state;
this.agentType = type;
this.updateLightEffect();
});
}
aboutToDisappear(): void {
clearInterval(this.pulseTimer);
clearInterval(this.particleTimer);
}
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.getStateConfig().pulseIntensity;
const variation = Math.sin(this.pulsePhase) * 0.3;
return Math.max(0.1, Math.min(1.0, baseIntensity + variation));
}
private startParticleAnimation(): void {
this.particleTimer = setInterval(() => {
if (this.agentState === AgentState.EXECUTING) {
this.updateParticles();
}
}, 100);
}
private updateParticles(): void {
const newParticles: Array<{x: number, y: number, size: number, opacity: number}> = [];
for (let i = 0; i < this.getStateConfig().particleCount; i++) {
newParticles.push({
x: Math.random() * 100,
y: Math.random() * 100,
size: Math.random() * 4 + 2,
opacity: Math.random() * this.lightIntensity
});
}
this.particlePositions = newParticles;
}
private getStateConfig(): LightEffectConfig {
const configs: Record<<AgentState, LightEffectConfig> = {
[AgentState.IDLE]: {
baseColor: this.agentType.color,
pulseSpeed: 4000,
pulseIntensity: 0.4,
glowRadius: 80,
particleCount: 0
},
[AgentState.THINKING]: {
baseColor: this.agentType.color,
pulseSpeed: 1500,
pulseIntensity: 0.7,
glowRadius: 120,
particleCount: 5
},
[AgentState.EXECUTING]: {
baseColor: this.agentType.color,
pulseSpeed: 800,
pulseIntensity: 0.9,
glowRadius: 150,
particleCount: 15
},
[AgentState.COMPLETED]: {
baseColor: '#2ECC71',
pulseSpeed: 2000,
pulseIntensity: 0.6,
glowRadius: 100,
particleCount: 8
},
[AgentState.ERROR]: {
baseColor: '#FF4444',
pulseSpeed: 500,
pulseIntensity: 1.0,
glowRadius: 120,
particleCount: 0
}
};
return configs[this.agentState] || configs[AgentState.IDLE];
}
private updateLightEffect(): void {
const config = this.getStateConfig();
AppStorage.setOrCreate('current_agent_color', config.baseColor);
AppStorage.setOrCreate('current_agent_pulse', config.pulseSpeed);
AppStorage.setOrCreate('current_agent_intensity', config.pulseIntensity);
}
build() {
Stack() {
// 主光晕层
Column()
.width(400)
.height(400)
.backgroundColor(this.getStateConfig().baseColor)
.blur(this.getStateConfig().glowRadius)
.opacity(this.lightIntensity)
.position({ x: '50%', y: '30%' })
.anchor('50%')
.animation({
duration: this.getStateConfig().pulseSpeed,
curve: Curve.EaseInOut,
iterations: -1,
playMode: PlayMode.Alternate
})
// 粒子层(执行状态时显示)
if (this.agentState === AgentState.EXECUTING) {
ForEach(this.particlePositions, (particle: {x: number, y: number, size: number, opacity: number}, index: number) => {
Column()
.width(particle.size)
.height(particle.size)
.backgroundColor(this.getStateConfig().baseColor)
.borderRadius(particle.size / 2)
.opacity(particle.opacity)
.position({
x: `${particle.x}%`,
y: `${particle.y}%`
})
.animation({
duration: 1000,
curve: Curve.Linear,
iterations: -1
})
})
}
// 状态指示器环
Column()
.width(200)
.height(200)
.backgroundColor('transparent')
.border({
width: 3,
color: this.getStateConfig().baseColor,
style: BorderStyle.Solid
})
.borderRadius(100)
.opacity(this.lightIntensity * 0.5)
.animation({
duration: this.getStateConfig().pulseSpeed,
curve: Curve.EaseInOut,
iterations: -1,
playMode: PlayMode.Alternate
})
}
.width('100%')
.height('100%')
}
}
5.3 HMAF智能体调度器(AgentScheduler.ets)
代码亮点:基于HMAF Agent Framework Kit构建核心调度逻辑,实现"意图理解→任务分解→智能体分配→结果验证"的完整工作流。调度器通过Intents Kit解析用户自然语言意图,自动创建执行器和验证器智能体实例,并实时监控各智能体状态。
typescript
// entry/src/main/ets/services/AgentScheduler.ets
import { hmaf } from '@kit.HMAFramework';
import { intents } from '@kit.IntentsKit';
import { nlu } from '@kit.NLUKit';
// 任务定义
interface AgentTask {
id: string;
intent: string;
parameters: Record<string, string>;
assignedAgent: string;
priority: number;
deadline: number;
}
// 智能体实例
interface AgentInstance {
id: string;
type: 'scheduler' | 'executor' | 'validator';
status: 'idle' | 'busy' | 'error';
currentTask: AgentTask | null;
capability: string[];
}
export class AgentScheduler {
private static instance: AgentScheduler;
private agents: Map<string, AgentInstance> = new Map();
private taskQueue: AgentTask[] = [];
private hmafSession: hmaf.AgentSession | null = null;
private intentEngine: intents.IntentEngine | null = null;
private constructor() {}
static getInstance(): AgentScheduler {
if (!AgentScheduler.instance) {
AgentScheduler.instance = new AgentScheduler();
}
return AgentScheduler.instance;
}
async initialize(): Promise<void> {
try {
// 初始化HMAF会话
this.hmafSession = await hmaf.createAgentSession({
mode: hmaf.AgentMode.MULTI_AGENT,
maxConcurrentAgents: 5,
enableDistributed: true
});
// 初始化意图引擎
this.intentEngine = await intents.createIntentEngine({
supportedDomains: ['productivity', 'coding', 'research', 'analysis'],
language: 'zh-CN'
});
// 注册默认智能体
await this.registerDefaultAgents();
console.info('AgentScheduler initialized successfully');
} catch (error) {
console.error('Failed to initialize AgentScheduler:', error);
throw error;
}
}
private async registerDefaultAgents(): Promise<void> {
// 注册调度器自身
this.agents.set('scheduler-1', {
id: 'scheduler-1',
type: 'scheduler',
status: 'idle',
currentTask: null,
capability: ['task_decomposition', 'agent_coordination', 'conflict_resolution']
});
// 注册执行器智能体
this.agents.set('executor-1', {
id: 'executor-1',
type: 'executor',
status: 'idle',
currentTask: null,
capability: ['code_generation', 'data_analysis', 'document_processing', 'web_search']
});
this.agents.set('executor-2', {
id: 'executor-2',
type: 'executor',
status: 'idle',
currentTask: null,
capability: ['image_generation', 'video_editing', 'audio_processing']
});
// 注册验证器智能体
this.agents.set('validator-1', {
id: 'validator-1',
type: 'validator',
status: 'idle',
currentTask: null,
capability: ['code_review', 'fact_checking', 'quality_assurance', 'security_audit']
});
}
// 处理用户意图
async processUserIntent(userInput: string): Promise<string> {
try {
// 更新调度器状态为思考中
this.updateAgentState('scheduler-1', 'thinking');
// 解析用户意图
const parsedIntent = await this.intentEngine?.parseIntent(userInput);
if (!parsedIntent) {
throw new Error('Failed to parse user intent');
}
// 任务分解
const subTasks = await this.decomposeTask(parsedIntent);
// 分配任务给执行器
const executionResults = await this.dispatchTasks(subTasks);
// 验证结果
const validatedResults = await this.validateResults(executionResults);
// 更新调度器状态为完成
this.updateAgentState('scheduler-1', 'idle');
return this.formatResponse(validatedResults);
} catch (error) {
this.updateAgentState('scheduler-1', 'error');
console.error('Error processing user intent:', error);
return `执行异常:${error.message}`;
}
}
private async decomposeTask(intent: intents.ParsedIntent): Promise<<AgentTask[]> {
const tasks: AgentTask[] = [];
const taskId = `task-${Date.now()}`;
// 根据意图类型分解任务
switch (intent.domain) {
case 'coding':
tasks.push({
id: `${taskId}-1`,
intent: 'code_analysis',
parameters: { code: intent.parameters.code || '' },
assignedAgent: 'executor-1',
priority: 1,
deadline: Date.now() + 30000
});
tasks.push({
id: `${taskId}-2`,
intent: 'code_generation',
parameters: { requirements: intent.parameters.requirements || '' },
assignedAgent: 'executor-1',
priority: 2,
deadline: Date.now() + 60000
});
tasks.push({
id: `${taskId}-3`,
intent: 'code_review',
parameters: { generatedCode: '' },
assignedAgent: 'validator-1',
priority: 3,
deadline: Date.now() + 90000
});
break;
case 'research':
tasks.push({
id: `${taskId}-1`,
intent: 'web_search',
parameters: { query: intent.parameters.query || '' },
assignedAgent: 'executor-1',
priority: 1,
deadline: Date.now() + 20000
});
tasks.push({
id: `${taskId}-2`,
intent: 'data_analysis',
parameters: { searchResults: '' },
assignedAgent: 'executor-1',
priority: 2,
deadline: Date.now() + 40000
});
tasks.push({
id: `${taskId}-3`,
intent: 'fact_checking',
parameters: { analysisResult: '' },
assignedAgent: 'validator-1',
priority: 3,
deadline: Date.now() + 60000
});
break;
default:
tasks.push({
id: `${taskId}-1`,
intent: intent.action,
parameters: intent.parameters,
assignedAgent: 'executor-1',
priority: 1,
deadline: Date.now() + 30000
});
}
return tasks;
}
private async dispatchTasks(tasks: AgentTask[]): Promise<<Record<string, unknown>[]> {
const results: Record<string, unknown>[] = [];
for (const task of tasks) {
const agent = this.findAvailableAgent(task.assignedAgent);
if (!agent) {
console.warn(`No available agent for task ${task.id}`);
continue;
}
// 更新执行器状态
this.updateAgentState(agent.id, 'busy');
// 通过HMAF发送任务
const result = await this.hmafSession?.sendTask({
targetAgent: agent.id,
taskType: task.intent,
parameters: task.parameters,
timeout: task.deadline - Date.now()
});
results.push({
taskId: task.id,
agentId: agent.id,
result: result,
timestamp: Date.now()
});
// 更新执行器状态
this.updateAgentState(agent.id, 'idle');
}
return results;
}
private async validateResults(results: Record<string, unknown>[]): Promise<<Record<string, unknown>[]> {
const validator = this.agents.get('validator-1');
if (!validator || validator.status === 'busy') {
return results; // 无可用验证器,直接返回
}
this.updateAgentState('validator-1', 'busy');
const validatedResults: Record<string, unknown>[] = [];
for (const result of results) {
const validation = await this.hmafSession?.sendTask({
targetAgent: 'validator-1',
taskType: 'quality_assurance',
parameters: { input: JSON.stringify(result) },
timeout: 15000
});
validatedResults.push({
...result,
validation: validation,
isValid: validation?.score > 0.8
});
}
this.updateAgentState('validator-1', 'idle');
return validatedResults;
}
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' | 'busy' | 'error';
// 触发全局状态更新,驱动光效变化
AppStorage.setOrCreate('agent_state_update', {
agentId: agentId,
state: state,
timestamp: Date.now()
});
}
}
private formatResponse(results: Record<string, unknown>[]): string {
let response = '## 智能体协作结果\n\n';
for (const result of results) {
const taskId = result.taskId as string;
const agentId = result.agentId as string;
const isValid = result.isValid as boolean;
response += `### ${taskId}\n`;
response += `- **执行智能体**: ${agentId}\n`;
response += `- **验证结果**: ${isValid ? '✅ 通过' : '⚠️ 需复核'}\n`;
response += `- **输出**: ${JSON.stringify(result.result, null, 2)}\n\n`;
}
return response;
}
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?.intent || null
}));
}
}
5.4 悬浮智能体导航(AgentFloatNavigation.ets)
代码亮点:底部悬浮导航栏不仅承载页面切换功能,更重要的是实时显示各智能体运行状态。每个导航项配备状态徽章------待机时柔和光点、思考时呼吸脉冲、执行时旋转进度、异常时警示闪烁。支持长按展开透明度调节面板。
typescript
// entry/src/main/ets/components/AgentFloatNavigation.ets
import { window } from '@kit.ArkUI';
import { AgentState, AgentPersonality } from './AgentLightEffect';
// 导航项配置
interface AgentNavItem {
id: string;
icon: Resource;
label: string;
page: string;
agentType?: AgentPersonality;
}
@Component
export struct AgentFloatNavigation {
@State currentIndex: number = 0;
@State navTransparency: number = 0.70;
@State isExpanded: boolean = false;
@State bottomAvoidHeight: number = 0;
@State agentStates: Map<string, AgentState> = new Map([
['scheduler-1', AgentState.IDLE],
['executor-1', AgentState.IDLE],
['executor-2', AgentState.IDLE],
['validator-1', AgentState.IDLE]
]);
private navItems: AgentNavItem[] = [
{ id: 'chat', icon: $r('app.media.ic_chat'), label: '对话', page: 'ChatPage' },
{ id: 'workflow', icon: $r('app.media.ic_workflow'), label: '工作流', page: 'WorkflowPage', agentType: AgentPersonality.SCHEDULER },
{ id: 'tools', icon: $r('app.media.ic_tools'), label: '工具', page: 'ToolsPage', agentType: AgentPersonality.EXECUTOR },
{ id: 'knowledge', icon: $r('app.media.ic_knowledge'), label: '知识库', page: 'KnowledgePage', agentType: AgentPersonality.VALIDATOR },
{ id: 'settings', icon: $r('app.media.ic_settings'), label: '设置', page: 'SettingsPage' }
];
aboutToAppear(): void {
this.getBottomAvoidArea();
// 监听智能体状态变化
AppStorage.setOrCreate('agent_state_update', (update: {agentId: string, state: string}) => {
this.agentStates.set(update.agentId, update.state as AgentState);
});
}
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: AgentNavItem): AgentState {
if (!item.agentType) return AgentState.IDLE;
const agentId = item.id === 'workflow' ? 'scheduler-1' :
item.id === 'tools' ? 'executor-1' :
item.id === 'knowledge' ? 'validator-1' : '';
return this.agentStates.get(agentId) || AgentState.IDLE;
}
private getStateBadgeColor(state: AgentState): string {
const colors: Record<<AgentState, string> = {
[AgentState.IDLE]: '#888888',
[AgentState.THINKING]: '#4A90D9',
[AgentState.EXECUTING]: '#F5A623',
[AgentState.COMPLETED]: '#2ECC71',
[AgentState.ERROR]: '#FF4444'
};
return colors[state] || '#888888';
}
private getStateBadgeAnimation(state: AgentState): object {
switch (state) {
case AgentState.THINKING:
return {
duration: 1500,
curve: Curve.EaseInOut,
iterations: -1,
playMode: PlayMode.Alternate
};
case AgentState.EXECUTING:
return {
duration: 1000,
curve: Curve.Linear,
iterations: -1
};
case AgentState.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: AgentNavItem, index: number) => {
Column() {
Stack() {
Image(item.icon)
.width(24)
.height(24)
.fillColor(this.currentIndex === index ? this.getStateBadgeColor(this.getAgentStateForNavItem(item)) : '#666666')
// 智能体状态徽章
if (item.agentType && this.getAgentStateForNavItem(item) !== AgentState.IDLE) {
Column()
.width(10)
.height(10)
.backgroundColor(this.getStateBadgeColor(this.getAgentStateForNavItem(item)))
.borderRadius(5)
.position({ x: 18, y: -4 })
.shadow({
radius: 6,
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 ? this.getStateBadgeColor(this.getAgentStateForNavItem(item)) : '#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 智能体对话页面(ChatPage.ets)
代码亮点:实现具有智能体人格光效的对话页面。用户输入意图后,调度器智能体自动分解任务、分配执行器、验证结果,整个过程通过光效实时反馈。对话气泡根据智能体类型显示对应色彩边框。
typescript
// entry/src/main/ets/pages/ChatPage.ets
import { AgentScheduler } from '../services/AgentScheduler';
import { AgentPersonality, AgentState } from '../components/AgentLightEffect';
import { AgentFloatNavigation } from '../components/AgentFloatNavigation';
interface ChatMessage {
id: string;
role: 'user' | 'scheduler' | 'executor' | 'validator' | 'system';
content: string;
timestamp: number;
agentType?: AgentPersonality;
state?: AgentState;
}
@Entry
@Component
struct ChatPage {
@State messages: ChatMessage[] = [];
@State inputText: string = '';
@State isProcessing: boolean = false;
@State currentAgentState: AgentState = AgentState.IDLE;
@State currentAgentType: AgentPersonality = AgentPersonality.SCHEDULER;
@State topAvoidHeight: number = 0;
@State lightColor: string = '#4A90D9';
@State lightIntensity: number = 0.4;
private scheduler: AgentScheduler = AgentScheduler.getInstance();
private messageId: number = 0;
private listScroller: ListScroller = new ListScroller();
aboutToAppear(): void {
this.getTopAvoidArea();
this.initializeScheduler();
// 监听光效状态变化
AppStorage.setOrCreate('current_agent_color', (color: string) => {
this.lightColor = color;
});
AppStorage.setOrCreate('current_agent_intensity', (intensity: number) => {
this.lightIntensity = intensity;
});
}
private async initializeScheduler(): Promise<void> {
await this.scheduler.initialize();
this.addSystemMessage('灵犀智脑已就绪。请输入您的任务意图,我将自动调度智能体协作完成。');
}
private async getTopAvoidArea(): Promise<void> {
try {
const mainWindow = await window.getLastWindow();
const avoidArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_STATUS);
this.topAvoidHeight = avoidArea.topRect.height;
} catch (error) {
console.error('Failed to get top avoid area:', error);
}
}
private addSystemMessage(content: string): void {
this.messages.push({
id: `msg-${++this.messageId}`,
role: 'system',
content: content,
timestamp: Date.now()
});
this.scrollToBottom();
}
private addUserMessage(content: string): void {
this.messages.push({
id: `msg-${++this.messageId}`,
role: 'user',
content: content,
timestamp: Date.now()
});
this.scrollToBottom();
}
private addAgentMessage(role: 'scheduler' | 'executor' | 'validator', content: string, agentType: AgentPersonality): void {
this.messages.push({
id: `msg-${++this.messageId}`,
role: role,
content: content,
timestamp: Date.now(),
agentType: agentType,
state: AgentState.COMPLETED
});
this.scrollToBottom();
}
private scrollToBottom(): void {
setTimeout(() => {
this.listScroller.scrollToIndex(this.messages.length - 1);
}, 100);
}
private async sendMessage(): Promise<void> {
if (!this.inputText.trim() || this.isProcessing) return;
const userInput = this.inputText.trim();
this.inputText = '';
this.addUserMessage(userInput);
this.isProcessing = true;
// 更新状态为思考中
this.currentAgentState = AgentState.THINKING;
this.currentAgentType = AgentPersonality.SCHEDULER;
try {
// 调度器处理意图
const response = await this.scheduler.processUserIntent(userInput);
// 添加调度器消息
this.addAgentMessage('scheduler', '🎯 **调度器**:已解析意图并分解任务', AgentPersonality.SCHEDULER);
// 获取各智能体状态并添加执行记录
const agentStatus = this.scheduler.getAgentStatus();
for (const agent of agentStatus) {
if (agent.status === 'busy' || agent.task) {
const agentType = agent.type === 'scheduler' ? AgentPersonality.SCHEDULER :
agent.type === 'executor' ? AgentPersonality.EXECUTOR :
AgentPersonality.VALIDATOR;
this.addAgentMessage(
agent.type as 'scheduler' | 'executor' | 'validator',
`⚡ **${agent.type === 'scheduler' ? '调度器' : agent.type === 'executor' ? '执行器' : '验证器'}** (${agent.id}):正在执行 [${agent.task}]`,
agentType
);
}
}
// 添加最终结果
this.addAgentMessage('scheduler', response, AgentPersonality.SCHEDULER);
} catch (error) {
this.addSystemMessage(`❌ 执行异常:${error.message}`);
this.currentAgentState = AgentState.ERROR;
} finally {
this.isProcessing = false;
this.currentAgentState = AgentState.IDLE;
}
}
private getMessageColor(role: string, agentType?: AgentPersonality): string {
if (role === 'user') return '#4A90D9';
if (role === 'system') return '#888888';
return agentType?.color || '#666666';
}
private getMessageIcon(role: string, agentType?: AgentPersonality): string {
if (role === 'user') return '👤';
if (role === 'system') return '🔔';
return agentType?.name === '调度器' ? '🎯' :
agentType?.name === '执行器' ? '⚡' :
agentType?.name === '验证器' ? '✅' : '🤖';
}
build() {
AgentFloatNavigation({
contentBuilder: () => {
this.chatContentBuilder()
}
})
}
@Builder
chatContentBuilder(): void {
Stack() {
// 动态沉浸光效背景
Column() {
Column()
.width(300)
.height(300)
.backgroundColor(this.lightColor)
.blur(100)
.opacity(this.lightIntensity)
.position({ x: '50%', y: 200 })
.anchor('50%')
.animation({
duration: this.currentAgentState === AgentState.THINKING ? 1500 :
this.currentAgentState === AgentState.EXECUTING ? 800 : 4000,
curve: Curve.EaseInOut,
iterations: -1,
playMode: PlayMode.Alternate
})
}
.width('100%')
.height('100%')
.backgroundColor('#0f0f23')
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
// 内容层
Column() {
// 顶部避让
Column().width('100%').height(this.topAvoidHeight)
// 标题栏
Row() {
Text('🧠 灵犀智脑')
.fontSize(20)
.fontColor('#FFFFFF')
.fontWeight(FontWeight.Bold)
Row() {
// 智能体状态指示器
Column()
.width(8)
.height(8)
.backgroundColor(
this.currentAgentState === AgentState.IDLE ? '#888888' :
this.currentAgentState === AgentState.THINKING ? '#4A90D9' :
this.currentAgentState === AgentState.EXECUTING ? '#F5A623' :
this.currentAgentState === AgentState.ERROR ? '#FF4444' : '#2ECC71'
)
.borderRadius(4)
.animation({
duration: this.currentAgentState === AgentState.THINKING ? 1000 : 500,
curve: Curve.EaseInOut,
iterations: -1,
playMode: PlayMode.Alternate
})
Text(
this.currentAgentState === AgentState.IDLE ? '待机中' :
this.currentAgentState === AgentState.THINKING ? '思考中...' :
this.currentAgentState === AgentState.EXECUTING ? '执行中...' :
this.currentAgentState === AgentState.ERROR ? '异常' : '完成'
)
.fontSize(12)
.fontColor('rgba(255,255,255,0.7)')
.margin({ left: 8 })
}
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
.padding(16)
// 消息列表
List({ scroller: this.listScroller }) {
ForEach(this.messages, (msg: ChatMessage) => {
ListItem() {
Column() {
Row() {
Text(`${this.getMessageIcon(msg.role, msg.agentType)} ${msg.role === 'user' ? '我' : msg.agentType?.name || '系统'}`)
.fontSize(12)
.fontColor(this.getMessageColor(msg.role, msg.agentType))
.fontWeight(FontWeight.Medium)
Text(new Date(msg.timestamp).toLocaleTimeString())
.fontSize(10)
.fontColor('rgba(255,255,255,0.4)')
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
Text(msg.content)
.fontSize(14)
.fontColor(msg.role === 'user' ? '#FFFFFF' : 'rgba(255,255,255,0.9)')
.margin({ top: 8 })
.lineHeight(20)
}
.width('100%')
.padding(12)
.backgroundColor(
msg.role === 'user' ? 'rgba(74,144,217,0.15)' :
msg.role === 'system' ? 'rgba(136,136,136,0.1)' :
'rgba(255,255,255,0.05)'
)
.borderRadius(12)
.border({
width: 1,
color: msg.agentType ? `${msg.agentType.color}30` : 'transparent',
style: BorderStyle.Solid
})
.margin({ bottom: 8 })
}
})
}
.width('100%')
.layoutWeight(1)
.padding({ left: 16, right: 16 })
// 输入区域
Column() {
Row() {
TextInput({ placeholder: '输入任务意图,例如:帮我分析这段代码并优化...', text: $$this.inputText })
.width('80%')
.height(48)
.backgroundColor('rgba(255,255,255,0.1)')
.fontColor('#FFFFFF')
.placeholderColor('rgba(255,255,255,0.4)')
.borderRadius(24)
Button() {
Image(this.isProcessing ? $r('app.media.ic_loading') : $r('app.media.ic_send'))
.width(24)
.height(24)
.fillColor('#FFFFFF')
}
.type(ButtonType.Circle)
.backgroundColor(this.isProcessing ? '#888888' : this.lightColor)
.width(48)
.height(48)
.enabled(!this.isProcessing)
.onClick(() => {
this.sendMessage();
})
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
}
.width('100%')
.padding(16)
.backgroundColor('rgba(0,0,0,0.3)')
.backdropFilter($r('sys.blur.20'))
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
5.6 浮动工具面板窗口(ToolPanelWindow.ets)
代码亮点 :实现可拖拽的浮动工具面板,支持代码编辑器、数据分析图表、网页预览等工具。窗口激活时边缘发光增强,失活时自动降低光效强度,通过WindowManager与主窗口光效联动。
typescript
// entry/src/main/ets/windows/ToolPanelWindow.ets
import { window } from '@kit.ArkUI';
@Component
export struct ToolPanelWindow {
@State isActive: boolean = false;
@State currentTool: string = 'code';
@State windowLightColor: string = '#F5A623';
@State lightIntensity: number = 0.6;
private mainWindow: window.Window | null = null;
aboutToAppear(): void {
this.setupWindow();
// 监听主窗口光效变化
AppStorage.setOrCreate('current_agent_color', (color: string) => {
this.windowLightColor = color;
});
}
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(400, 600);
// 监听窗口焦点变化
this.mainWindow.on('windowFocusChange', (isFocused: boolean) => {
this.isActive = isFocused;
this.lightIntensity = isFocused ? 0.8 : 0.3;
});
} catch (error) {
console.error('Failed to setup tool panel window:', error);
}
}
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)
Row() {
Button() {
Text('代码')
.fontSize(12)
.fontColor(this.currentTool === 'code' ? '#FFFFFF' : '#888888')
}
.type(ButtonType.Capsule)
.backgroundColor(this.currentTool === 'code' ? this.windowLightColor : 'rgba(255,255,255,0.1)')
.height(28)
.onClick(() => { this.currentTool = 'code'; })
Button() {
Text('图表')
.fontSize(12)
.fontColor(this.currentTool === 'chart' ? '#FFFFFF' : '#888888')
}
.type(ButtonType.Capsule)
.backgroundColor(this.currentTool === 'chart' ? this.windowLightColor : 'rgba(255,255,255,0.1)')
.height(28)
.margin({ left: 8 })
.onClick(() => { this.currentTool = 'chart'; })
Button() {
Text('预览')
.fontSize(12)
.fontColor(this.currentTool === 'preview' ? '#FFFFFF' : '#888888')
}
.type(ButtonType.Capsule)
.backgroundColor(this.currentTool === 'preview' ? this.windowLightColor : 'rgba(255,255,255,0.1)')
.height(28)
.margin({ left: 8 })
.onClick(() => { this.currentTool = 'preview'; })
}
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
.padding(16)
// 工具内容区
if (this.currentTool === 'code') {
this.buildCodeEditor()
} else if (this.currentTool === 'chart') {
this.buildChartView()
} else {
this.buildPreviewView()
}
}
.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
})
}
@Builder
buildCodeEditor(): void {
Column() {
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)
}
@Builder
buildChartView(): void {
Column() {
Text('📊 数据分析图表')
.fontSize(16)
.fontColor('#FFFFFF')
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
.width('100%')
.layoutWeight(1)
.padding(16)
}
@Builder
buildPreviewView(): void {
Column() {
Text('🌐 网页预览')
.fontSize(16)
.fontColor('#FFFFFF')
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
.width('100%')
.layoutWeight(1)
.padding(16)
}
}
5.7 多窗口光效同步管理器(WindowLightSync.ets)
代码亮点:管理主窗口与浮动工具窗口、知识库窗口、日志窗口之间的光效联动。当智能体状态变化时,所有窗口同步切换主题色;当窗口焦点变化时,自动调整光效强度,形成层次分明的视觉体验。
typescript
// entry/src/main/ets/managers/WindowLightSync.ets
import { window } from '@kit.ArkUI';
// 窗口类型
export enum WindowType {
MAIN = 'main',
TOOL_PANEL = 'tool_panel',
KNOWLEDGE_BASE = 'knowledge_base',
LOG_VIEWER = 'log_viewer'
}
// 光效主题
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: '#F5A623',
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);
}
}
}
// 根据智能体状态更新主题
updateThemeByAgentState(state: string, agentType: string): void {
const themes: Record<string, LightTheme> = {
'scheduler_idle': {
primaryColor: '#4A90D9',
secondaryColor: '#6BB6FF',
intensity: 0.4,
pulseSpeed: 4000,
glowRadius: 80
},
'scheduler_thinking': {
primaryColor: '#4A90D9',
secondaryColor: '#8EC5FF',
intensity: 0.7,
pulseSpeed: 1500,
glowRadius: 120
},
'executor_executing': {
primaryColor: '#F5A623',
secondaryColor: '#FFD93D',
intensity: 0.9,
pulseSpeed: 800,
glowRadius: 150
},
'validator_validating': {
primaryColor: '#2ECC71',
secondaryColor: '#7EE8A0',
intensity: 0.6,
pulseSpeed: 2000,
glowRadius: 100
},
'error': {
primaryColor: '#FF4444',
secondaryColor: '#FF8888',
intensity: 1.0,
pulseSpeed: 500,
glowRadius: 120
}
};
const themeKey = `${agentType}_${state}`;
const theme = themes[themeKey] || themes['scheduler_idle'];
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 { ChatPage } from './ChatPage';
import { WindowLightSync, WindowType } from '../managers/WindowLightSync';
import { ToolPanelWindow } from '../windows/ToolPanelWindow';
@Entry
@Component
struct Index {
private lightSync: WindowLightSync = WindowLightSync.getInstance();
aboutToAppear(): void {
this.initializeWindows();
}
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.TOOL_PANEL,
400, 600,
100, 100
);
}
} catch (error) {
console.error('Failed to initialize windows:', error);
}
}
build() {
ChatPage()
}
}
六、关键技术总结
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 智能体状态光效映射
| 智能体状态 | 光效颜色 | 脉冲速度 | 光晕半径 | 视觉语义 |
|---|---|---|---|---|
| 待机 | 人格专属色 | 4000ms | 80px | 柔和呼吸,平静等待 |
| 思考中 | 人格专属色+亮 | 1500ms | 120px | 快速脉冲,活跃思考 |
| 执行中 | 人格专属色+饱和 | 800ms | 150px | 急促流光,全力执行 |
| 已完成 | 绿色 | 2000ms | 100px | 确认闪光,任务达成 |
| 异常 | 红色 | 500ms | 120px | 警示闪烁,需要关注 |
6.4 PC端多窗口光效协同
- 主窗口:全屏沉浸,智能体人格光效延伸至所有安全区边缘
- 浮动工具窗口:置顶、圆角、阴影,激活时边缘发光增强
- 光效同步 :通过
WindowLightSync管理器实现跨窗口主题色联动 - 焦点感知:窗口激活时边缘发光增强,失活时自动降低光效强度
- 智能体人格一致性:同一智能体在所有窗口中保持相同色彩标识
七、调试与适配建议
- HMAF会话管理:多智能体并发时注意会话资源释放,避免内存泄漏
- 光效功耗优化:夜间模式降低光效刷新率,延长OLED屏幕寿命
- 意图识别校准:不同行业领域需训练专用意图模型,提升解析准确率
- 分布式设备测试:测试跨设备智能体协作时的网络延迟与状态同步
- 无障碍支持:为视障用户提供语音播报智能体状态,光效切换时播放提示音
- 隐私保护:敏感任务数据本地处理,仅上传脱敏后的意图描述
八、总结与展望
本文基于HarmonyOS 6(API 23)的悬浮导航 、沉浸光感 与HMAF智能体框架特性,完整实战了一款面向PC端的"灵犀智脑"AI智能体工作流编排平台。核心创新点总结:
-
HMAF多智能体协作架构:基于Agent Framework Kit构建"调度器-执行器-验证器"三层智能体协作体系,实现意图理解→任务分解→智能体分配→结果验证的完整工作流
-
智能体状态光效系统:每个智能体拥有专属人格色彩(调度器冷峻蓝、执行器活力橙、验证器严谨绿),根据运行状态动态切换脉冲节奏与光晕强度,实现"状态直觉感知"
-
悬浮智能体导航:底部悬浮页签不仅承载页面切换,更实时显示各智能体运行状态徽章(呼吸脉冲、旋转进度、警示闪烁),玻璃拟态设计+三档透明度调节
-
PC级多窗口智能体协作 :主对话窗口 + 浮动工具面板 + 浮动知识库 + 浮动日志窗口的四层架构,通过
WindowLightSync实现跨窗口光效联动与焦点感知 -
意图感知沉浸体验:通过Intents Kit实时理解用户意图,自动调整界面光效与导航形态,实现"意图即氛围"的自然交互
未来扩展方向:
- 接入分布式软总线4.0,实现PC主控+手机传感器+平板显示的多设备智能体协同
- AI智能体市场:支持第三方开发者发布自定义智能体,通过光效标识区分能力类型
- 数字孪生集成:接入IoT设备数据,智能体自动感知物理世界状态并调整工作流
- VR/AR融合:支持VR头显接入,实现完全沉浸式的3D智能体交互空间
- 长期记忆进化:基于用户历史交互数据,智能体逐步学习用户偏好,光效个性化适配
转载自:https://blog.csdn.net/u014727709/article/details/161144634
欢迎 👍点赞✍评论⭐收藏,欢迎指正