refactor: 清理未使用代码并添加未来功能标记
Some checks failed
CI / Rust Check (push) Has been cancelled
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled

style: 统一代码格式和注释风格

docs: 更新多个功能文档的完整度和状态

feat(runtime): 添加路径验证工具支持

fix(pipeline): 改进条件判断和变量解析逻辑

test(types): 为ID类型添加全面测试用例

chore: 更新依赖项和Cargo.lock文件

perf(mcp): 优化MCP协议传输和错误处理
This commit is contained in:
iven
2026-03-25 21:55:12 +08:00
parent aa6a9cbd84
commit bf6d81f9c6
109 changed files with 12271 additions and 815 deletions

View File

@@ -21,7 +21,6 @@ import {
Grid,
Volume2,
VolumeX,
Settings,
Download,
Share2,
} from 'lucide-react';
@@ -78,7 +77,7 @@ interface SceneRendererProps {
showNarration: boolean;
}
function SceneRenderer({ scene, isPlaying, showNarration }: SceneRendererProps) {
function SceneRenderer({ scene, showNarration }: SceneRendererProps) {
const renderContent = () => {
switch (scene.type) {
case 'title':
@@ -240,7 +239,7 @@ function OutlinePanel({
{section.title}
</p>
<div className="space-y-1">
{section.scenes.map((sceneId, sceneIndex) => {
{section.scenes.map((sceneId) => {
const globalIndex = scenes.findIndex(s => s.id === sceneId);
const isActive = globalIndex === currentIndex;
const scene = scenes.find(s => s.id === sceneId);
@@ -271,7 +270,6 @@ function OutlinePanel({
export function ClassroomPreviewer({
data,
onClose,
onExport,
}: ClassroomPreviewerProps) {
const [currentSceneIndex, setCurrentSceneIndex] = useState(0);
@@ -281,7 +279,7 @@ export function ClassroomPreviewer({
const [isFullscreen, setIsFullscreen] = useState(false);
const [viewMode, setViewMode] = useState<'slides' | 'grid'>('slides');
const { showToast } = useToast();
const { toast } = useToast();
const currentScene = data.scenes[currentSceneIndex];
const totalScenes = data.scenes.length;
@@ -310,12 +308,12 @@ export function ClassroomPreviewer({
nextScene();
} else {
setIsPlaying(false);
showToast('课堂播放完成', 'success');
toast('课堂播放完成', 'success');
}
}, duration);
return () => clearTimeout(timer);
}, [isPlaying, currentSceneIndex, currentScene, totalScenes, nextScene, showToast]);
}, [isPlaying, currentSceneIndex, currentScene, totalScenes, nextScene, toast]);
// Keyboard navigation
useEffect(() => {
@@ -352,7 +350,7 @@ export function ClassroomPreviewer({
if (onExport) {
onExport(format);
} else {
showToast(`导出 ${format.toUpperCase()} 功能开发中...`, 'info');
toast(`导出 ${format.toUpperCase()} 功能开发中...`, 'info');
}
};

View File

@@ -32,7 +32,7 @@ interface PipelineResultPreviewProps {
onClose?: () => void;
}
type PreviewMode = 'auto' | 'json' | 'markdown' | 'classroom';
type PreviewMode = 'auto' | 'json' | 'markdown' | 'classroom' | 'files';
// === Utility Functions ===
@@ -123,14 +123,14 @@ interface JsonPreviewProps {
function JsonPreview({ data }: JsonPreviewProps) {
const [copied, setCopied] = useState(false);
const { showToast } = useToast();
const { toast } = useToast();
const jsonString = JSON.stringify(data, null, 2);
const handleCopy = async () => {
await navigator.clipboard.writeText(jsonString);
setCopied(true);
showToast('已复制到剪贴板', 'success');
toast('已复制到剪贴板', 'success');
setTimeout(() => setCopied(false), 2000);
};
@@ -190,7 +190,6 @@ export function PipelineResultPreview({
onClose,
}: PipelineResultPreviewProps) {
const [mode, setMode] = useState<PreviewMode>('auto');
const { showToast } = useToast();
// Determine the best preview mode
const outputs = result.outputs as Record<string, unknown> | undefined;

View File

@@ -7,16 +7,13 @@
* Pipelines orchestrate Skills and Hands to accomplish complex tasks.
*/
import { useState, useEffect, useCallback } from 'react';
import { useState } from 'react';
import {
Play,
RefreshCw,
Search,
ChevronRight,
Loader2,
CheckCircle,
XCircle,
Clock,
Package,
Filter,
X,
@@ -26,7 +23,6 @@ import {
PipelineInfo,
PipelineRunResponse,
usePipelines,
usePipelineRun,
validateInputs,
getDefaultForType,
formatInputType,
@@ -378,7 +374,7 @@ export function PipelinesPanel() {
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState('');
const [selectedPipeline, setSelectedPipeline] = useState<PipelineInfo | null>(null);
const { showToast } = useToast();
const { toast } = useToast();
const { pipelines, loading, error, refresh } = usePipelines({
category: selectedCategory ?? undefined,
@@ -406,9 +402,9 @@ export function PipelinesPanel() {
const handleRunComplete = (result: PipelineRunResponse) => {
setSelectedPipeline(null);
if (result.status === 'completed') {
showToast('Pipeline 执行完成', 'success');
toast('Pipeline 执行完成', 'success');
} else {
showToast(`Pipeline 执行失败: ${result.error}`, 'error');
toast(`Pipeline 执行失败: ${result.error}`, 'error');
}
};

View File

@@ -1,21 +1,208 @@
import { useEffect } from 'react';
import { Radio, RefreshCw, MessageCircle, Settings2 } from 'lucide-react';
/**
* IMChannels - IM Channel Management UI
*
* Displays and manages IM channel configurations.
* Supports viewing, configuring, and adding new channels.
*/
import { useState, useEffect } from 'react';
import { Radio, RefreshCw, MessageCircle, Settings2, Plus, X, Check, AlertCircle, ExternalLink } from 'lucide-react';
import { useConnectionStore } from '../../store/connectionStore';
import { useConfigStore } from '../../store/configStore';
import { useConfigStore, type ChannelInfo } from '../../store/configStore';
import { useAgentStore } from '../../store/agentStore';
const CHANNEL_ICONS: Record<string, string> = {
feishu: '飞',
qqbot: 'QQ',
wechat: '微',
discord: 'D',
slack: 'S',
telegram: 'T',
};
const CHANNEL_CONFIG_FIELDS: Record<string, { key: string; label: string; type: string; placeholder: string; required: boolean }[]> = {
feishu: [
{ key: 'appId', label: 'App ID', type: 'text', placeholder: 'cli_xxx', required: true },
{ key: 'appSecret', label: 'App Secret', type: 'password', placeholder: '••••••••', required: true },
],
discord: [
{ key: 'botToken', label: 'Bot Token', type: 'password', placeholder: 'OTk2NzY4...', required: true },
{ key: 'guildId', label: 'Guild ID (可选)', type: 'text', placeholder: '123456789', required: false },
],
slack: [
{ key: 'botToken', label: 'Bot Token', type: 'password', placeholder: 'xoxb-...', required: true },
{ key: 'appToken', label: 'App Token', type: 'password', placeholder: 'xapp-...', required: false },
],
telegram: [
{ key: 'botToken', label: 'Bot Token', type: 'password', placeholder: '123456:ABC...', required: true },
],
qqbot: [
{ key: 'appId', label: 'App ID', type: 'text', placeholder: '1234567890', required: true },
{ key: 'token', label: 'Token', type: 'password', placeholder: '••••••••', required: true },
],
wechat: [
{ key: 'corpId', label: 'Corp ID', type: 'text', placeholder: 'wwxxx', required: true },
{ key: 'agentId', label: 'Agent ID', type: 'text', placeholder: '1000001', required: true },
{ key: 'secret', label: 'Secret', type: 'password', placeholder: '••••••••', required: true },
],
};
const KNOWN_CHANNELS = [
{ type: 'feishu', label: '飞书 (Feishu/Lark)', description: '企业即时通讯平台' },
{ type: 'discord', label: 'Discord', description: '游戏社区和语音聊天' },
{ type: 'slack', label: 'Slack', description: '团队协作平台' },
{ type: 'telegram', label: 'Telegram', description: '加密即时通讯' },
{ type: 'qqbot', label: 'QQ 机器人', description: '腾讯QQ官方机器人' },
{ type: 'wechat', label: '企业微信', description: '企业微信机器人' },
];
interface ChannelConfigModalProps {
channel: ChannelInfo | null;
channelType: string | null;
isOpen: boolean;
onClose: () => void;
onSave: (config: Record<string, string>) => Promise<void>;
isSaving: boolean;
}
function ChannelConfigModal({ channel, channelType, isOpen, onClose, onSave, isSaving }: ChannelConfigModalProps) {
const [config, setConfig] = useState<Record<string, string>>({});
const [error, setError] = useState<string | null>(null);
const fields = channelType ? CHANNEL_CONFIG_FIELDS[channelType] || [] : [];
useEffect(() => {
if (channel?.config) {
setConfig(channel.config as Record<string, string>);
} else {
setConfig({});
}
setError(null);
}, [channel, channelType]);
if (!isOpen || !channelType) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
// Validate required fields
for (const field of fields) {
if (field.required && !config[field.key]?.trim()) {
setError(`请填写 ${field.label}`);
return;
}
}
try {
await onSave(config);
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : '保存失败');
}
};
const channelInfo = KNOWN_CHANNELS.find(c => c.type === channelType);
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md mx-4">
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{channel ? `配置 ${channel.label}` : `添加 ${channelInfo?.label || channelType}`}
</h3>
<button
onClick={onClose}
className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
>
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-4 space-y-4">
{channelInfo && (
<p className="text-sm text-gray-500 dark:text-gray-400">
{channelInfo.description}
</p>
)}
{fields.length === 0 ? (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
<AlertCircle className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p> UI </p>
<p className="text-xs mt-1"> CLI </p>
</div>
) : (
fields.map((field) => (
<div key={field.key}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{field.label}
{field.required && <span className="text-red-500 ml-1">*</span>}
</label>
<input
type={field.type}
value={config[field.key] || ''}
onChange={(e) => setConfig({ ...config, [field.key]: e.target.value })}
placeholder={field.placeholder}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
))
)}
{error && (
<div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-600 dark:text-red-400">
{error}
</div>
)}
{fields.length > 0 && (
<div className="flex gap-3 pt-2">
<button
type="button"
onClick={onClose}
className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"
>
</button>
<button
type="submit"
disabled={isSaving}
className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2"
>
{isSaving ? (
<>
<RefreshCw className="w-4 h-4 animate-spin" />
...
</>
) : (
<>
<Check className="w-4 h-4" />
</>
)}
</button>
</div>
)}
</form>
</div>
</div>
);
}
export function IMChannels() {
const channels = useConfigStore((s) => s.channels);
const loadChannels = useConfigStore((s) => s.loadChannels);
const createChannel = useConfigStore((s) => s.createChannel);
const updateChannel = useConfigStore((s) => s.updateChannel);
const connectionState = useConnectionStore((s) => s.connectionState);
const loadPluginStatus = useAgentStore((s) => s.loadPluginStatus);
const [isModalOpen, setIsModalOpen] = useState(false);
const [selectedChannel, setSelectedChannel] = useState<ChannelInfo | null>(null);
const [newChannelType, setNewChannelType] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
const [showAddMenu, setShowAddMenu] = useState(false);
const connected = connectionState === 'connected';
const loading = connectionState === 'connecting' || connectionState === 'reconnecting' || connectionState === 'handshaking';
@@ -29,20 +216,47 @@ export function IMChannels() {
loadPluginStatus().then(() => loadChannels());
};
const knownChannels = [
{ id: 'feishu', type: 'feishu', label: '飞书 (Feishu)' },
{ id: 'qqbot', type: 'qqbot', label: 'QQ 机器人' },
{ id: 'wechat', type: 'wechat', label: '微信' },
];
const handleConfigure = (channel: ChannelInfo) => {
setSelectedChannel(channel);
setNewChannelType(channel.type);
setIsModalOpen(true);
};
const availableChannels = knownChannels.filter(
const handleAddChannel = (type: string) => {
setSelectedChannel(null);
setNewChannelType(type);
setIsModalOpen(true);
setShowAddMenu(false);
};
const handleSaveConfig = async (config: Record<string, string>) => {
setIsSaving(true);
try {
if (selectedChannel) {
await updateChannel(selectedChannel.id, { config });
} else if (newChannelType) {
const channelInfo = KNOWN_CHANNELS.find(c => c.type === newChannelType);
await createChannel({
type: newChannelType,
name: channelInfo?.label || newChannelType,
config,
enabled: true,
});
}
await loadChannels();
} finally {
setIsSaving(false);
}
};
const availableChannels = KNOWN_CHANNELS.filter(
(channel) => !channels.some((item) => item.type === channel.type)
);
return (
<div className="max-w-3xl">
<div className="flex justify-between items-center mb-6">
<h1 className="text-xl font-bold text-gray-900">IM </h1>
<h1 className="text-xl font-bold text-gray-900 dark:text-white">IM </h1>
<div className="flex gap-2">
<span className="text-xs text-gray-400 flex items-center">
{connected ? `${channels.length} 个已识别频道` : loading ? '连接中...' : '未连接 Gateway'}
@@ -58,12 +272,12 @@ export function IMChannels() {
</div>
{!connected ? (
<div className="bg-white rounded-xl border border-gray-200 h-64 flex flex-col items-center justify-center mb-6 shadow-sm text-gray-400">
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 h-64 flex flex-col items-center justify-center mb-6 shadow-sm text-gray-400">
<Radio className="w-8 h-8 mb-3 opacity-40" />
<span className="text-sm"> Gateway IM </span>
</div>
) : (
<div className="bg-white rounded-xl border border-gray-200 mb-6 shadow-sm divide-y divide-gray-100">
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 mb-6 shadow-sm divide-y divide-gray-100 dark:divide-gray-700">
{channels.length > 0 ? channels.map((channel) => (
<div key={channel.id} className="p-4 flex items-center gap-4">
<div className={`w-10 h-10 rounded-xl flex items-center justify-center text-white text-sm font-semibold ${
@@ -71,24 +285,30 @@ export function IMChannels() {
? 'bg-gradient-to-br from-blue-500 to-indigo-500'
: channel.status === 'error'
? 'bg-gradient-to-br from-red-500 to-rose-500'
: 'bg-gray-300'
: 'bg-gray-300 dark:bg-gray-600'
}`}>
{CHANNEL_ICONS[channel.type] || <MessageCircle className="w-4 h-4" />}
</div>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-900">{channel.label}</div>
<div className="text-sm font-medium text-gray-900 dark:text-white">{channel.label}</div>
<div className={`text-xs mt-1 ${
channel.status === 'active'
? 'text-green-600'
? 'text-green-600 dark:text-green-400'
: channel.status === 'error'
? 'text-red-500'
? 'text-red-500 dark:text-red-400'
: 'text-gray-400'
}`}>
{channel.status === 'active' ? '已连接' : channel.status === 'error' ? channel.error || '错误' : '未配置'}
{channel.accounts !== undefined && channel.accounts > 0 ? ` · ${channel.accounts} 个账号` : ''}
</div>
</div>
<div className="text-xs text-gray-400">{channel.type}</div>
<button
onClick={() => handleConfigure(channel)}
className="p-2 text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
title="配置"
>
<Settings2 className="w-4 h-4" />
</button>
</div>
)) : (
<div className="h-40 flex items-center justify-center text-sm text-gray-400">
@@ -98,23 +318,88 @@ export function IMChannels() {
</div>
)}
{/* Add Channel Section */}
{connected && availableChannels.length > 0 && (
<div className="mb-6">
<div className="flex items-center justify-between mb-3">
<div className="text-xs text-gray-500 dark:text-gray-400"></div>
<div className="relative">
<button
onClick={() => setShowAddMenu(!showAddMenu)}
className="text-xs text-white bg-blue-500 hover:bg-blue-600 px-3 py-1.5 rounded-lg flex items-center gap-1 transition-colors"
>
<Plus className="w-3 h-3" />
</button>
{showAddMenu && (
<div className="absolute right-0 mt-1 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-10">
{availableChannels.map((channel) => (
<button
key={channel.type}
onClick={() => handleAddChannel(channel.type)}
className="w-full px-4 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 first:rounded-t-lg last:rounded-b-lg flex items-center gap-2"
>
<span className="w-6 h-6 rounded bg-gray-100 dark:bg-gray-700 flex items-center justify-center text-xs">
{CHANNEL_ICONS[channel.type] || '?'}
</span>
<div>
<div className="font-medium text-gray-900 dark:text-white">{channel.label}</div>
<div className="text-xs text-gray-500">{channel.description}</div>
</div>
</button>
))}
</div>
)}
</div>
</div>
</div>
)}
{/* Planned Channels */}
<div>
<div className="text-xs text-gray-500 mb-3"></div>
<div className="text-xs text-gray-500 dark:text-gray-400 mb-3"></div>
<div className="flex flex-wrap gap-3">
{availableChannels.map((channel) => (
<span
key={channel.id}
className="text-xs text-gray-500 bg-gray-100 px-4 py-2 rounded-lg"
key={channel.type}
className="text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 px-4 py-2 rounded-lg"
>
{channel.label}
</span>
))}
<div className="text-xs text-gray-400 flex items-center gap-1">
<Settings2 className="w-3 h-3" />
channelaccountbinding Gateway
{availableChannels.length === 0 && (
<div className="text-xs text-green-600 dark:text-green-400 flex items-center gap-1">
<Check className="w-3 h-3" />
</div>
)}
</div>
</div>
{/* External Link Notice */}
<div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
<div className="flex items-start gap-2">
<ExternalLink className="w-4 h-4 text-blue-500 mt-0.5" />
<div className="text-xs text-blue-700 dark:text-blue-300">
<p className="font-medium mb-1"></p>
<p> Gateway </p>
<p className="mt-1">: <code className="bg-blue-100 dark:bg-blue-800 px-1 rounded">~/.openfang/openfang.toml</code></p>
</div>
</div>
</div>
{/* Config Modal */}
<ChannelConfigModal
channel={selectedChannel}
channelType={newChannelType}
isOpen={isModalOpen}
onClose={() => {
setIsModalOpen(false);
setSelectedChannel(null);
setNewChannelType(null);
}}
onSave={handleSaveConfig}
isSaving={isSaving}
/>
</div>
);
}

View File

@@ -0,0 +1,382 @@
/**
* SecureStorage - OS Keyring/Keychain Management UI
*
* Allows users to view, add, and delete securely stored credentials
* using the OS keyring (Windows DPAPI, macOS Keychain, Linux Secret Service).
*/
import { useState, useEffect } from 'react';
import {
Key,
Plus,
Trash2,
Eye,
EyeOff,
RefreshCw,
AlertCircle,
CheckCircle,
Shield,
ShieldOff,
} from 'lucide-react';
import { secureStorage, isSecureStorageAvailable } from '../../lib/secure-storage';
interface StoredKey {
key: string;
hasValue: boolean;
preview?: string;
}
// Known storage keys used by the application
const KNOWN_KEYS = [
{ key: 'zclaw_api_key', label: 'API Key', description: 'LLM API 密钥' },
{ key: 'zclaw_device_keys_private', label: 'Device Private Key', description: '设备私钥 (Ed25519)' },
{ key: 'zclaw_gateway_token', label: 'Gateway Token', description: 'Gateway 认证令牌' },
{ key: 'zclaw_feishu_secret', label: '飞书 Secret', description: '飞书应用密钥' },
{ key: 'zclaw_discord_token', label: 'Discord Token', description: 'Discord Bot Token' },
{ key: 'zclaw_slack_token', label: 'Slack Token', description: 'Slack Bot Token' },
{ key: 'zclaw_telegram_token', label: 'Telegram Token', description: 'Telegram Bot Token' },
];
export function SecureStorage() {
const [isAvailable, setIsAvailable] = useState<boolean | null>(null);
const [storedKeys, setStoredKeys] = useState<StoredKey[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [showAddForm, setShowAddForm] = useState(false);
const [newKey, setNewKey] = useState('');
const [newValue, setNewValue] = useState('');
const [showValue, setShowValue] = useState<Record<string, boolean>>({});
const [revealedValues, setRevealedValues] = useState<Record<string, string>>({});
const [isSaving, setIsSaving] = useState(false);
const [isDeleting, setIsDeleting] = useState<string | null>(null);
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
const loadStoredKeys = async () => {
setIsLoading(true);
try {
const available = await isSecureStorageAvailable();
setIsAvailable(available);
const keys: StoredKey[] = [];
for (const knownKey of KNOWN_KEYS) {
const value = await secureStorage.get(knownKey.key);
keys.push({
key: knownKey.key,
hasValue: !!value,
preview: value ? `${value.slice(0, 8)}${value.length > 8 ? '...' : ''}` : undefined,
});
}
setStoredKeys(keys);
} catch (error) {
console.error('Failed to load stored keys:', error);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadStoredKeys();
}, []);
const handleReveal = async (key: string) => {
if (revealedValues[key]) {
// Hide if already revealed
setRevealedValues((prev) => {
const next = { ...prev };
delete next[key];
return next;
});
setShowValue((prev) => ({ ...prev, [key]: false }));
} else {
// Reveal the value
const value = await secureStorage.get(key);
if (value) {
setRevealedValues((prev) => ({ ...prev, [key]: value }));
setShowValue((prev) => ({ ...prev, [key]: true }));
}
}
};
const handleAddKey = async () => {
if (!newKey.trim() || !newValue.trim()) {
setMessage({ type: 'error', text: '请填写密钥名称和值' });
return;
}
setIsSaving(true);
setMessage(null);
try {
await secureStorage.set(newKey.trim(), newValue.trim());
setMessage({ type: 'success', text: '密钥已保存' });
setNewKey('');
setNewValue('');
setShowAddForm(false);
await loadStoredKeys();
} catch (error) {
setMessage({ type: 'error', text: `保存失败: ${error instanceof Error ? error.message : '未知错误'}` });
} finally {
setIsSaving(false);
}
};
const handleDeleteKey = async (key: string) => {
if (!confirm(`确定要删除密钥 "${key}" 吗?此操作无法撤销。`)) {
return;
}
setIsDeleting(key);
setMessage(null);
try {
await secureStorage.delete(key);
setMessage({ type: 'success', text: '密钥已删除' });
setRevealedValues((prev) => {
const next = { ...prev };
delete next[key];
return next;
});
await loadStoredKeys();
} catch (error) {
setMessage({ type: 'error', text: `删除失败: ${error instanceof Error ? error.message : '未知错误'}` });
} finally {
setIsDeleting(null);
}
};
const getKeyLabel = (key: string) => {
const known = KNOWN_KEYS.find((k) => k.key === key);
return known ? known.label : key;
};
const getKeyDescription = (key: string) => {
const known = KNOWN_KEYS.find((k) => k.key === key);
return known?.description;
};
return (
<div className="max-w-3xl">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-xl font-bold text-gray-900 dark:text-white"></h1>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
使 (Keyring/Keychain)
</p>
</div>
<div className="flex gap-2 items-center">
{isAvailable !== null && (
<span className={`text-xs flex items-center gap-1 ${isAvailable ? 'text-green-600' : 'text-amber-600'}`}>
{isAvailable ? (
<>
<Shield className="w-3 h-3" /> Keyring
</>
) : (
<>
<ShieldOff className="w-3 h-3" /> 使
</>
)}
</span>
)}
<button
onClick={loadStoredKeys}
disabled={isLoading}
className="text-xs text-white bg-orange-500 hover:bg-orange-600 px-3 py-1.5 rounded-lg flex items-center gap-1 transition-colors disabled:opacity-50"
>
<RefreshCw className={`w-3 h-3 ${isLoading ? 'animate-spin' : ''}`} />
</button>
</div>
</div>
{/* Status Banner */}
{isAvailable === false && (
<div className="mb-6 p-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
<div className="flex items-start gap-2">
<AlertCircle className="w-4 h-4 text-amber-500 mt-0.5" />
<div className="text-xs text-amber-700 dark:text-amber-300">
<p className="font-medium">Keyring </p>
<p className="mt-1">
使 AES-GCM
Tauri
</p>
</div>
</div>
</div>
)}
{/* Message */}
{message && (
<div className={`mb-4 p-3 rounded-lg flex items-center gap-2 ${
message.type === 'success'
? 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300'
: 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300'
}`}>
{message.type === 'success' ? (
<CheckCircle className="w-4 h-4" />
) : (
<AlertCircle className="w-4 h-4" />
)}
{message.text}
</div>
)}
{/* Stored Keys List */}
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 mb-6 shadow-sm">
{isLoading ? (
<div className="h-40 flex items-center justify-center text-sm text-gray-400">
<RefreshCw className="w-4 h-4 animate-spin mr-2" />
...
</div>
) : storedKeys.length > 0 ? (
<div className="divide-y divide-gray-100 dark:divide-gray-700">
{storedKeys.map((item) => (
<div key={item.key} className="p-4">
<div className="flex items-center gap-4">
<div className={`w-10 h-10 rounded-xl flex items-center justify-center ${
item.hasValue
? 'bg-gradient-to-br from-green-500 to-emerald-500 text-white'
: 'bg-gray-200 dark:bg-gray-700 text-gray-400'
}`}>
<Key className="w-4 h-4" />
</div>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-900 dark:text-white">
{getKeyLabel(item.key)}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
{getKeyDescription(item.key) || item.key}
</div>
{item.hasValue && (
<div className="text-xs text-gray-400 dark:text-gray-500 mt-1 font-mono">
{showValue[item.key] ? (
<span className="break-all">{revealedValues[item.key]}</span>
) : (
<span>{item.preview}</span>
)}
</div>
)}
</div>
<div className="flex items-center gap-2">
{item.hasValue && (
<>
<button
onClick={() => handleReveal(item.key)}
className="p-2 text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
title={showValue[item.key] ? '隐藏' : '显示'}
>
{showValue[item.key] ? (
<EyeOff className="w-4 h-4" />
) : (
<Eye className="w-4 h-4" />
)}
</button>
<button
onClick={() => handleDeleteKey(item.key)}
disabled={isDeleting === item.key}
className="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
title="删除"
>
{isDeleting === item.key ? (
<RefreshCw className="w-4 h-4 animate-spin" />
) : (
<Trash2 className="w-4 h-4" />
)}
</button>
</>
)}
{!item.hasValue && (
<span className="text-xs text-gray-400 dark:text-gray-500 px-2"></span>
)}
</div>
</div>
</div>
))}
</div>
) : (
<div className="h-40 flex items-center justify-center text-sm text-gray-400">
</div>
)}
</div>
{/* Add New Key */}
<div className="mb-6">
{!showAddForm ? (
<button
onClick={() => setShowAddForm(true)}
className="w-full p-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl text-gray-500 dark:text-gray-400 hover:border-orange-400 hover:text-orange-500 transition-colors flex items-center justify-center gap-2"
>
<Plus className="w-4 h-4" />
<span className="text-sm"></span>
</button>
) : (
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 shadow-sm">
<h3 className="text-sm font-medium text-gray-900 dark:text-white mb-4"></h3>
<div className="space-y-3">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
</label>
<input
type="text"
value={newKey}
onChange={(e) => setNewKey(e.target.value)}
placeholder="例如: zclaw_custom_key"
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
</label>
<input
type="password"
value={newValue}
onChange={(e) => setNewValue(e.target.value)}
placeholder="输入密钥值"
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
<div className="flex gap-2 pt-2">
<button
onClick={() => {
setShowAddForm(false);
setNewKey('');
setNewValue('');
setMessage(null);
}}
className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 text-sm"
>
</button>
<button
onClick={handleAddKey}
disabled={isSaving || !newKey.trim() || !newValue.trim()}
className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2 text-sm"
>
{isSaving ? (
<>
<RefreshCw className="w-3 h-3 animate-spin" />
...
</>
) : (
<>
<CheckCircle className="w-3 h-3" />
</>
)}
</button>
</div>
</div>
</div>
)}
</div>
{/* Info Section */}
<div className="p-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700">
<h3 className="text-sm font-medium text-gray-900 dark:text-white mb-2"></h3>
<ul className="text-xs text-gray-500 dark:text-gray-400 space-y-1">
<li> Windows: 使用 DPAPI </li>
<li> macOS: 使用 Keychain </li>
<li> Linux: 使用 Secret Service API (gnome-keyring, kwallet )</li>
<li> 后备方案: AES-GCM localStorage</li>
</ul>
</div>
</div>
);
}

View File

@@ -16,6 +16,8 @@ import {
ClipboardList,
Clock,
Heart,
Key,
Database,
} from 'lucide-react';
import { silentErrorHandler } from '../../lib/error-utils';
import { General } from './General';
@@ -33,6 +35,8 @@ import { SecurityStatus } from '../SecurityStatus';
import { SecurityLayersPanel } from '../SecurityLayersPanel';
import { TaskList } from '../TaskList';
import { HeartbeatConfig } from '../HeartbeatConfig';
import { SecureStorage } from './SecureStorage';
import { VikingPanel } from '../VikingPanel';
interface SettingsLayoutProps {
onBack: () => void;
@@ -49,6 +53,8 @@ type SettingsPage =
| 'workspace'
| 'privacy'
| 'security'
| 'storage'
| 'viking'
| 'audit'
| 'tasks'
| 'heartbeat'
@@ -65,6 +71,8 @@ const menuItems: { id: SettingsPage; label: string; icon: React.ReactNode }[] =
{ id: 'im', label: 'IM 频道', icon: <MessageSquare className="w-4 h-4" /> },
{ id: 'workspace', label: '工作区', icon: <FolderOpen className="w-4 h-4" /> },
{ id: 'privacy', label: '数据与隐私', icon: <Shield className="w-4 h-4" /> },
{ id: 'storage', label: '安全存储', icon: <Key className="w-4 h-4" /> },
{ id: 'viking', label: '语义记忆', icon: <Database className="w-4 h-4" /> },
{ id: 'security', label: '安全状态', icon: <Shield className="w-4 h-4" /> },
{ id: 'audit', label: '审计日志', icon: <ClipboardList className="w-4 h-4" /> },
{ id: 'tasks', label: '定时任务', icon: <Clock className="w-4 h-4" /> },
@@ -88,6 +96,7 @@ export function SettingsLayout({ onBack }: SettingsLayoutProps) {
case 'im': return <IMChannels />;
case 'workspace': return <Workspace />;
case 'privacy': return <Privacy />;
case 'storage': return <SecureStorage />;
case 'security': return (
<div className="space-y-6">
<div>
@@ -121,6 +130,7 @@ export function SettingsLayout({ onBack }: SettingsLayoutProps) {
<HeartbeatConfig />
</div>
);
case 'viking': return <VikingPanel />;
case 'feedback': return <Feedback />;
case 'about': return <About />;
default: return <General />;

View File

@@ -0,0 +1,288 @@
/**
* VikingPanel - OpenViking Semantic Memory UI
*
* Provides interface for semantic search and knowledge base management.
* OpenViking is an optional sidecar for semantic memory operations.
*/
import { useState, useEffect } from 'react';
import {
Search,
RefreshCw,
AlertCircle,
CheckCircle,
FileText,
Server,
Play,
Square,
} from 'lucide-react';
import {
getVikingStatus,
findVikingResources,
getVikingServerStatus,
startVikingServer,
stopVikingServer,
} from '../lib/viking-client';
import type { VikingStatus, VikingFindResult } from '../lib/viking-client';
export function VikingPanel() {
const [status, setStatus] = useState<VikingStatus | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState<VikingFindResult[]>([]);
const [isSearching, setIsSearching] = useState(false);
const [serverRunning, setServerRunning] = useState(false);
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
const loadStatus = async () => {
setIsLoading(true);
try {
const vikingStatus = await getVikingStatus();
setStatus(vikingStatus);
const serverStatus = await getVikingServerStatus();
setServerRunning(serverStatus.running);
} catch (error) {
console.error('Failed to load Viking status:', error);
setStatus({ available: false, error: String(error) });
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadStatus();
}, []);
const handleSearch = async () => {
if (!searchQuery.trim()) return;
setIsSearching(true);
setMessage(null);
try {
const results = await findVikingResources(searchQuery, undefined, 10);
setSearchResults(results);
if (results.length === 0) {
setMessage({ type: 'error', text: '未找到匹配的资源' });
}
} catch (error) {
setMessage({
type: 'error',
text: `搜索失败: ${error instanceof Error ? error.message : '未知错误'}`,
});
} finally {
setIsSearching(false);
}
};
const handleServerToggle = async () => {
try {
if (serverRunning) {
await stopVikingServer();
setServerRunning(false);
setMessage({ type: 'success', text: '服务器已停止' });
} else {
await startVikingServer();
setServerRunning(true);
setMessage({ type: 'success', text: '服务器已启动' });
}
} catch (error) {
setMessage({
type: 'error',
text: `操作失败: ${error instanceof Error ? error.message : '未知错误'}`,
});
}
};
return (
<div className="max-w-4xl">
{/* Header */}
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-xl font-bold text-gray-900 dark:text-white"></h1>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
OpenViking
</p>
</div>
<div className="flex gap-2 items-center">
{status?.available && (
<span className="text-xs flex items-center gap-1 text-green-600">
<CheckCircle className="w-3 h-3" />
</span>
)}
<button
onClick={loadStatus}
disabled={isLoading}
className="text-xs text-white bg-orange-500 hover:bg-orange-600 px-3 py-1.5 rounded-lg flex items-center gap-1 transition-colors disabled:opacity-50"
>
<RefreshCw className={`w-3 h-3 ${isLoading ? 'animate-spin' : ''}`} />
</button>
</div>
</div>
{/* Status Banner */}
{!status?.available && (
<div className="mb-6 p-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
<div className="flex items-start gap-2">
<AlertCircle className="w-4 h-4 text-amber-500 mt-0.5" />
<div className="text-xs text-amber-700 dark:text-amber-300">
<p className="font-medium">OpenViking CLI </p>
<p className="mt-1">
OpenViking CLI {' '}
<code className="bg-amber-100 dark:bg-amber-800 px-1 rounded">ZCLAW_VIKING_BIN</code>
</p>
{status?.error && (
<p className="mt-1 text-amber-600 dark:text-amber-400 font-mono text-xs">
{status.error}
</p>
)}
</div>
</div>
</div>
)}
{/* Message */}
{message && (
<div
className={`mb-4 p-3 rounded-lg flex items-center gap-2 ${
message.type === 'success'
? 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300'
: 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300'
}`}
>
{message.type === 'success' ? (
<CheckCircle className="w-4 h-4" />
) : (
<AlertCircle className="w-4 h-4" />
)}
{message.text}
</div>
)}
{/* Server Control */}
{status?.available && (
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 mb-6 shadow-sm">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div
className={`w-10 h-10 rounded-xl flex items-center justify-center ${
serverRunning
? 'bg-gradient-to-br from-green-500 to-emerald-500 text-white'
: 'bg-gray-200 dark:bg-gray-700 text-gray-400'
}`}
>
<Server className="w-4 h-4" />
</div>
<div>
<div className="text-sm font-medium text-gray-900 dark:text-white">
Viking Server
</div>
<div className="text-xs text-gray-500 dark:text-gray-400">
{serverRunning ? '运行中' : '已停止'}
</div>
</div>
</div>
<button
onClick={handleServerToggle}
className={`px-4 py-2 rounded-lg flex items-center gap-2 text-sm transition-colors ${
serverRunning
? 'bg-red-100 text-red-600 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400'
: 'bg-green-100 text-green-600 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400'
}`}
>
{serverRunning ? (
<>
<Square className="w-4 h-4" />
</>
) : (
<>
<Play className="w-4 h-4" />
</>
)}
</button>
</div>
</div>
)}
{/* Search Box */}
{status?.available && (
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 mb-6 shadow-sm">
<h3 className="text-sm font-medium text-gray-900 dark:text-white mb-3"></h3>
<div className="flex gap-2">
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
placeholder="输入自然语言查询..."
className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
<button
onClick={handleSearch}
disabled={isSearching || !searchQuery.trim()}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2 text-sm"
>
{isSearching ? (
<RefreshCw className="w-4 h-4 animate-spin" />
) : (
<Search className="w-4 h-4" />
)}
</button>
</div>
</div>
)}
{/* Search Results */}
{searchResults.length > 0 && (
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm divide-y divide-gray-100 dark:divide-gray-700">
<div className="p-3 border-b border-gray-200 dark:border-gray-700">
<span className="text-xs text-gray-500">
{searchResults.length}
</span>
</div>
{searchResults.map((result, index) => (
<div key={`${result.uri}-${index}`} className="p-4">
<div className="flex items-start gap-3">
<div className="w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center flex-shrink-0">
<FileText className="w-4 h-4 text-blue-600 dark:text-blue-400" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-gray-900 dark:text-white truncate">
{result.uri}
</span>
<span className="text-xs text-gray-400 bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded">
{result.level}
</span>
<span className="text-xs text-blue-600 dark:text-blue-400">
{Math.round(result.score * 100)}%
</span>
</div>
{result.overview && (
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1 line-clamp-2">
{result.overview}
</p>
)}
<p className="text-xs text-gray-600 dark:text-gray-300 mt-2 line-clamp-3 font-mono">
{result.content}
</p>
</div>
</div>
</div>
))}
</div>
)}
{/* Info Section */}
<div className="mt-6 p-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700">
<h3 className="text-sm font-medium text-gray-900 dark:text-white mb-2"> OpenViking</h3>
<ul className="text-xs text-gray-500 dark:text-gray-400 space-y-1">
<li> </li>
<li> </li>
<li> </li>
<li> AI </li>
</ul>
</div>
</div>
);
}

View File

@@ -4,7 +4,7 @@
* Draggable palette of available node types.
*/
import React, { DragEvent } from 'react';
import { DragEvent } from 'react';
import type { NodePaletteItem, NodeCategory } from '../../lib/workflow-builder/types';
interface NodePaletteProps {

View File

@@ -4,7 +4,7 @@
* Panel for editing node properties.
*/
import React, { useState, useEffect } from 'react';
import { useState, useEffect } from 'react';
import type { WorkflowNodeData } from '../../lib/workflow-builder/types';
interface PropertyPanelProps {
@@ -16,7 +16,6 @@ interface PropertyPanelProps {
}
export function PropertyPanel({
nodeId,
nodeData,
onUpdate,
onDelete,

View File

@@ -5,7 +5,7 @@
* Pipeline DSL configurations.
*/
import React, { useCallback, useRef, useEffect } from 'react';
import { useCallback, useRef, useEffect } from 'react';
import {
ReactFlow,
Controls,
@@ -17,17 +17,17 @@ import {
useNodesState,
useEdgesState,
Node,
NodeChange,
EdgeChange,
Edge,
NodeTypes,
Panel,
ReactFlowProvider,
useReactFlow,
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';
import { useWorkflowBuilderStore, nodePaletteItems, paletteCategories } from '../../store/workflowBuilderStore';
import type { WorkflowNodeType, WorkflowNodeData } from '../../lib/workflow-builder/types';
import { validateCanvas } from '../../lib/workflow-builder/yaml-converter';
import { useWorkflowBuilderStore, paletteCategories } from '../../store/workflowBuilderStore';
import type { WorkflowNodeData, WorkflowNodeType } from '../../lib/workflow-builder/types';
// Import custom node components
import { InputNode } from './nodes/InputNode';
@@ -66,7 +66,7 @@ const nodeTypes: NodeTypes = {
export function WorkflowBuilderInternal() {
const reactFlowWrapper = useRef<HTMLDivElement>(null);
const { screenToFlowPosition, fitView } = useReactFlow();
const { screenToFlowPosition } = useReactFlow();
const {
canvas,
@@ -84,8 +84,8 @@ export function WorkflowBuilderInternal() {
} = useWorkflowBuilderStore();
// Local state for React Flow
const [nodes, setNodes, onNodesChange] = useNodesState([]);
const [edges, setEdges, onEdgesChange] = useEdgesState([]);
const [nodes, setNodes, onNodesChange] = useNodesState<Node<WorkflowNodeData>>([]);
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
// Sync canvas state with React Flow
useEffect(() => {
@@ -94,7 +94,7 @@ export function WorkflowBuilderInternal() {
id: n.id,
type: n.type,
position: n.position,
data: n.data,
data: n.data as WorkflowNodeData,
})));
setEdges(canvas.edges.map(e => ({
id: e.id,
@@ -111,7 +111,7 @@ export function WorkflowBuilderInternal() {
// Handle node changes (position, selection)
const handleNodesChange = useCallback(
(changes) => {
(changes: NodeChange<Node<WorkflowNodeData>>[]) => {
onNodesChange(changes);
// Sync position changes back to store
@@ -132,7 +132,7 @@ export function WorkflowBuilderInternal() {
// Handle edge changes
const handleEdgesChange = useCallback(
(changes) => {
(changes: EdgeChange[]) => {
onEdgesChange(changes);
},
[onEdgesChange]
@@ -235,7 +235,7 @@ export function WorkflowBuilderInternal() {
{/* Node Palette */}
<NodePalette
categories={paletteCategories}
onDragStart={(type) => {
onDragStart={() => {
setDragging(true);
}}
onDragEnd={() => {

View File

@@ -4,7 +4,7 @@
* Toolbar with actions for the workflow builder.
*/
import React, { useState } from 'react';
import { useState } from 'react';
import type { ValidationResult } from '../../lib/workflow-builder/types';
import { canvasToYaml } from '../../lib/workflow-builder/yaml-converter';
import { useWorkflowBuilderStore } from '../../store/workflowBuilderStore';

View File

@@ -4,11 +4,13 @@
* Node for conditional branching.
*/
import React, { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { Handle, Position, NodeProps, Node } from '@xyflow/react';
import type { ConditionNodeData } from '../../../lib/workflow-builder/types';
export const ConditionNode = memo(({ data, selected }: NodeProps<ConditionNodeData>) => {
type ConditionNodeType = Node<ConditionNodeData>;
export const ConditionNode = memo(({ data, selected }: NodeProps<ConditionNodeType>) => {
const branchCount = data.branches.length + (data.hasDefault ? 1 : 0);
return (
@@ -39,7 +41,7 @@ export const ConditionNode = memo(({ data, selected }: NodeProps<ConditionNodeDa
{/* Branches */}
<div className="space-y-1">
{data.branches.map((branch, index) => (
{data.branches.map((branch: { label?: string; when: string }, index: number) => (
<div key={index} className="flex items-center justify-between">
<div className="relative">
{/* Branch Output Handle */}

View File

@@ -4,11 +4,11 @@
* Node for exporting workflow results to various formats.
*/
import React, { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { Handle, Position, NodeProps, Node } from '@xyflow/react';
import type { ExportNodeData } from '../../../lib/workflow-builder/types';
export const ExportNode = memo(({ data, selected }: NodeProps<ExportNodeData>) => {
export const ExportNode = memo(({ data, selected }: NodeProps<Node<ExportNodeData>>) => {
const formatLabels: Record<string, string> = {
pptx: 'PowerPoint',
html: 'HTML',

View File

@@ -4,11 +4,13 @@
* Node for executing hand actions.
*/
import React, { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { Handle, Position, NodeProps, Node } from '@xyflow/react';
import type { HandNodeData } from '../../../lib/workflow-builder/types';
export const HandNode = memo(({ data, selected }: NodeProps<HandNodeData>) => {
type HandNodeType = Node<HandNodeData>;
export const HandNode = memo(({ data, selected }: NodeProps<HandNodeType>) => {
const hasHand = Boolean(data.handId);
const hasAction = Boolean(data.action);

View File

@@ -4,8 +4,8 @@
* Node for making HTTP requests.
*/
import React, { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { Handle, Position, NodeProps, Node } from '@xyflow/react';
import type { HttpNodeData } from '../../../lib/workflow-builder/types';
const methodColors: Record<string, string> = {
@@ -16,7 +16,7 @@ const methodColors: Record<string, string> = {
PATCH: 'bg-purple-100 text-purple-700',
};
export const HttpNode = memo(({ data, selected }: NodeProps<HttpNodeData>) => {
export const HttpNode = memo(({ data, selected }: NodeProps<Node<HttpNodeData>>) => {
const hasUrl = Boolean(data.url);
return (

View File

@@ -4,11 +4,11 @@
* Node for defining workflow input variables.
*/
import React, { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { Handle, Position, NodeProps, Node } from '@xyflow/react';
import type { InputNodeData } from '../../../lib/workflow-builder/types';
export const InputNode = memo(({ data, selected }: NodeProps<InputNodeData>) => {
export const InputNode = memo(({ data, selected }: NodeProps<Node<InputNodeData>>) => {
return (
<div
className={`

View File

@@ -4,11 +4,11 @@
* Node for LLM generation actions.
*/
import React, { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { Handle, Position, NodeProps, Node } from '@xyflow/react';
import type { LlmNodeData } from '../../../lib/workflow-builder/types';
export const LlmNode = memo(({ data, selected }: NodeProps<LlmNodeData>) => {
export const LlmNode = memo(({ data, selected }: NodeProps<Node<LlmNodeData>>) => {
const templatePreview = data.template.length > 50
? data.template.slice(0, 50) + '...'
: data.template || 'No template';

View File

@@ -4,11 +4,11 @@
* Node for executing skill orchestration graphs (DAGs).
*/
import React, { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { Handle, Position, NodeProps, Node } from '@xyflow/react';
import type { OrchestrationNodeData } from '../../../lib/workflow-builder/types';
export const OrchestrationNode = memo(({ data, selected }: NodeProps<OrchestrationNodeData>) => {
export const OrchestrationNode = memo(({ data, selected }: NodeProps<Node<OrchestrationNodeData>>) => {
const hasGraphId = Boolean(data.graphId);
const hasGraph = Boolean(data.graph);
const inputCount = Object.keys(data.inputMappings).length;

View File

@@ -4,11 +4,11 @@
* Node for parallel execution of steps.
*/
import React, { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { Handle, Position, NodeProps, Node } from '@xyflow/react';
import type { ParallelNodeData } from '../../../lib/workflow-builder/types';
export const ParallelNode = memo(({ data, selected }: NodeProps<ParallelNodeData>) => {
export const ParallelNode = memo(({ data, selected }: NodeProps<Node<ParallelNodeData>>) => {
return (
<div
className={`

View File

@@ -4,11 +4,11 @@
* Node for executing skills.
*/
import React, { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { Handle, Position, NodeProps, Node } from '@xyflow/react';
import type { SkillNodeData } from '../../../lib/workflow-builder/types';
export const SkillNode = memo(({ data, selected }: NodeProps<SkillNodeData>) => {
export const SkillNode = memo(({ data, selected }: NodeProps<Node<SkillNodeData>>) => {
const hasSkill = Boolean(data.skillId);
return (

View File

@@ -0,0 +1,340 @@
/**
* Workflow Recommendations Component
*
* Displays proactive workflow recommendations from the Adaptive Intelligence Mesh.
* Shows detected patterns and suggested workflows based on user behavior.
*/
import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useMeshStore } from '../store/meshStore';
import type { WorkflowRecommendation, BehaviorPattern, PatternTypeVariant } from '../lib/intelligence-client';
// === Main Component ===
export const WorkflowRecommendations: React.FC = () => {
const {
recommendations,
patterns,
isLoading,
error,
analyze,
acceptRecommendation,
dismissRecommendation,
} = useMeshStore();
const [selectedPattern, setSelectedPattern] = useState<string | null>(null);
useEffect(() => {
// Initial analysis
analyze();
}, [analyze]);
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500" />
<span className="ml-3 text-gray-400">Analyzing patterns...</span>
</div>
);
}
if (error) {
return (
<div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
<p className="text-red-400 text-sm">{error}</p>
</div>
);
}
return (
<div className="space-y-6">
{/* Recommendations Section */}
<section>
<h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<span className="text-2xl">💡</span>
Recommended Workflows
{recommendations.length > 0 && (
<span className="ml-2 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full">
{recommendations.length}
</span>
)}
</h3>
<AnimatePresence mode="popLayout">
{recommendations.length === 0 ? (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="p-6 bg-gray-800/30 rounded-lg border border-gray-700/50 text-center"
>
<p className="text-gray-400">No recommendations available yet.</p>
<p className="text-gray-500 text-sm mt-2">
Continue using the app to build up behavior patterns.
</p>
</motion.div>
) : (
<div className="space-y-3">
{recommendations.map((rec) => (
<RecommendationCard
key={rec.id}
recommendation={rec}
onAccept={() => acceptRecommendation(rec.id)}
onDismiss={() => dismissRecommendation(rec.id)}
/>
))}
</div>
)}
</AnimatePresence>
</section>
{/* Detected Patterns Section */}
<section>
<h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<span className="text-2xl">📊</span>
Detected Patterns
{patterns.length > 0 && (
<span className="ml-2 px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded-full">
{patterns.length}
</span>
)}
</h3>
{patterns.length === 0 ? (
<div className="p-6 bg-gray-800/30 rounded-lg border border-gray-700/50 text-center">
<p className="text-gray-400">No patterns detected yet.</p>
</div>
) : (
<div className="grid gap-3">
{patterns.map((pattern) => (
<PatternCard
key={pattern.id}
pattern={pattern}
isSelected={selectedPattern === pattern.id}
onClick={() =>
setSelectedPattern(
selectedPattern === pattern.id ? null : pattern.id
)
}
/>
))}
</div>
)}
</section>
</div>
);
};
// === Sub-Components ===
interface RecommendationCardProps {
recommendation: WorkflowRecommendation;
onAccept: () => void;
onDismiss: () => void;
}
const RecommendationCard: React.FC<RecommendationCardProps> = ({
recommendation,
onAccept,
onDismiss,
}) => {
const confidencePercent = Math.round(recommendation.confidence * 100);
const getConfidenceColor = (confidence: number) => {
if (confidence >= 0.8) return 'text-green-400';
if (confidence >= 0.6) return 'text-yellow-400';
return 'text-orange-400';
};
return (
<motion.div
layout
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95 }}
className="p-4 bg-gray-800/50 rounded-lg border border-gray-700/50 hover:border-blue-500/30 transition-colors"
>
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<h4 className="text-white font-medium truncate">
{recommendation.pipeline_id}
</h4>
<span
className={`text-xs font-mono ${getConfidenceColor(
recommendation.confidence
)}`}
>
{confidencePercent}%
</span>
</div>
<p className="text-gray-400 text-sm mb-3">{recommendation.reason}</p>
{/* Suggested Inputs */}
{Object.keys(recommendation.suggested_inputs).length > 0 && (
<div className="mb-3">
<p className="text-xs text-gray-500 mb-1">Suggested inputs:</p>
<div className="flex flex-wrap gap-1">
{Object.entries(recommendation.suggested_inputs).map(
([key, value]) => (
<span
key={key}
className="px-2 py-0.5 bg-gray-700/50 text-gray-300 text-xs rounded"
>
{key}: {String(value).slice(0, 20)}
</span>
)
)}
</div>
</div>
)}
{/* Matched Patterns */}
{recommendation.patterns_matched.length > 0 && (
<div className="text-xs text-gray-500">
Based on {recommendation.patterns_matched.length} pattern(s)
</div>
)}
</div>
{/* Actions */}
<div className="flex gap-2 shrink-0">
<button
onClick={onAccept}
className="px-3 py-1.5 bg-blue-500 hover:bg-blue-600 text-white text-sm rounded transition-colors"
>
Accept
</button>
<button
onClick={onDismiss}
className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-gray-300 text-sm rounded transition-colors"
>
Dismiss
</button>
</div>
</div>
{/* Confidence Bar */}
<div className="mt-3 h-1 bg-gray-700 rounded-full overflow-hidden">
<motion.div
initial={{ width: 0 }}
animate={{ width: `${confidencePercent}%` }}
className={`h-full ${
recommendation.confidence >= 0.8
? 'bg-green-500'
: recommendation.confidence >= 0.6
? 'bg-yellow-500'
: 'bg-orange-500'
}`}
/>
</div>
</motion.div>
);
};
interface PatternCardProps {
pattern: BehaviorPattern;
isSelected: boolean;
onClick: () => void;
}
const PatternCard: React.FC<PatternCardProps> = ({
pattern,
isSelected,
onClick,
}) => {
const getPatternTypeLabel = (type: PatternTypeVariant | string) => {
// Handle object format
const typeStr = typeof type === 'string' ? type : type.type;
switch (typeStr) {
case 'SkillCombination':
return { label: 'Skill Combo', icon: '⚡' };
case 'TemporalTrigger':
return { label: 'Time Trigger', icon: '⏰' };
case 'TaskPipelineMapping':
return { label: 'Task Mapping', icon: '🔄' };
case 'InputPattern':
return { label: 'Input Pattern', icon: '📝' };
default:
return { label: typeStr, icon: '📊' };
}
};
const { label, icon } = getPatternTypeLabel(pattern.pattern_type as PatternTypeVariant);
const confidencePercent = Math.round(pattern.confidence * 100);
return (
<motion.div
layout
onClick={onClick}
className={`p-3 rounded-lg border cursor-pointer transition-colors ${
isSelected
? 'bg-purple-500/10 border-purple-500/50'
: 'bg-gray-800/30 border-gray-700/50 hover:border-gray-600'
}`}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<span className="text-lg">{icon}</span>
<span className="text-white font-medium">{label}</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-400">
{pattern.frequency}x used
</span>
<span
className={`text-xs font-mono ${
pattern.confidence >= 0.6
? 'text-green-400'
: 'text-yellow-400'
}`}
>
{confidencePercent}%
</span>
</div>
</div>
<AnimatePresence>
{isSelected && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="mt-3 pt-3 border-t border-gray-700/50 overflow-hidden"
>
<div className="space-y-2 text-sm">
<div>
<span className="text-gray-500">ID:</span>{' '}
<span className="text-gray-300 font-mono text-xs">
{pattern.id}
</span>
</div>
<div>
<span className="text-gray-500">First seen:</span>{' '}
<span className="text-gray-300">
{new Date(pattern.first_occurrence).toLocaleDateString()}
</span>
</div>
<div>
<span className="text-gray-500">Last seen:</span>{' '}
<span className="text-gray-300">
{new Date(pattern.last_occurrence).toLocaleDateString()}
</span>
</div>
{pattern.context.intent && (
<div>
<span className="text-gray-500">Intent:</span>{' '}
<span className="text-gray-300">{pattern.context.intent}</span>
</div>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
);
};
export default WorkflowRecommendations;

View File

@@ -128,8 +128,142 @@ export type {
IdentityFiles,
IdentityChangeProposal,
IdentitySnapshot,
MemoryEntryForAnalysis,
} from './intelligence-backend';
// === Mesh Types ===
export interface BehaviorPattern {
id: string;
pattern_type: PatternTypeVariant;
frequency: number;
last_occurrence: string;
first_occurrence: string;
confidence: number;
context: PatternContext;
}
export function getPatternTypeString(patternType: PatternTypeVariant): string {
if (typeof patternType === 'string') {
return patternType;
}
return patternType.type;
}
export type PatternTypeVariant =
| { type: 'SkillCombination'; skill_ids: string[] }
| { type: 'TemporalTrigger'; hand_id: string; time_pattern: string }
| { type: 'TaskPipelineMapping'; task_type: string; pipeline_id: string }
| { type: 'InputPattern'; keywords: string[]; intent: string };
export interface PatternContext {
skill_ids?: string[];
recent_topics?: string[];
intent?: string;
time_of_day?: number;
day_of_week?: number;
}
export interface WorkflowRecommendation {
id: string;
pipeline_id: string;
confidence: number;
reason: string;
suggested_inputs: Record<string, unknown>;
patterns_matched: string[];
timestamp: string;
}
export interface MeshConfig {
enabled: boolean;
min_confidence: number;
max_recommendations: number;
analysis_window_hours: number;
}
export interface MeshAnalysisResult {
recommendations: WorkflowRecommendation[];
patterns_detected: number;
timestamp: string;
}
export type ActivityType =
| { type: 'skill_used'; skill_ids: string[] }
| { type: 'pipeline_executed'; task_type: string; pipeline_id: string }
| { type: 'input_received'; keywords: string[]; intent: string };
// === Persona Evolver Types ===
export type EvolutionChangeType =
| 'instruction_addition'
| 'instruction_refinement'
| 'trait_addition'
| 'style_adjustment'
| 'domain_expansion';
export type InsightCategory =
| 'communication_style'
| 'technical_expertise'
| 'task_efficiency'
| 'user_preference'
| 'knowledge_gap';
export type IdentityFileType = 'soul' | 'instructions';
export type ProposalStatus = 'pending' | 'approved' | 'rejected';
export interface EvolutionProposal {
id: string;
agent_id: string;
target_file: IdentityFileType;
change_type: EvolutionChangeType;
reason: string;
current_content: string;
proposed_content: string;
confidence: number;
evidence: string[];
status: ProposalStatus;
created_at: string;
}
export interface ProfileUpdate {
section: string;
previous: string;
updated: string;
source: string;
}
export interface EvolutionInsight {
category: InsightCategory;
observation: string;
recommendation: string;
confidence: number;
}
export interface EvolutionResult {
agent_id: string;
timestamp: string;
profile_updates: ProfileUpdate[];
proposals: EvolutionProposal[];
insights: EvolutionInsight[];
evolved: boolean;
}
export interface PersonaEvolverConfig {
auto_profile_update: boolean;
min_preferences_for_update: number;
min_conversations_for_evolution: number;
enable_instruction_refinement: boolean;
enable_soul_evolution: boolean;
max_proposals_per_cycle: number;
}
export interface PersonaEvolverState {
last_evolution: string | null;
total_evolutions: number;
pending_proposals: number;
profile_enrichment_score: number;
}
// === Type Conversion Utilities ===
/**

View File

@@ -753,36 +753,210 @@ export class KernelClient {
});
}
// === Triggers API (stubs for compatibility) ===
// === Triggers API ===
async listTriggers(): Promise<{ triggers?: { id: string; type: string; enabled: boolean }[] }> {
return { triggers: [] };
/**
* List all triggers
* Returns empty array on error for graceful degradation
*/
async listTriggers(): Promise<{
triggers?: Array<{
id: string;
name: string;
handId: string;
triggerType: string;
enabled: boolean;
createdAt: string;
modifiedAt: string;
description?: string;
tags: string[];
}>
}> {
try {
const triggers = await invoke<Array<{
id: string;
name: string;
handId: string;
triggerType: string;
enabled: boolean;
createdAt: string;
modifiedAt: string;
description?: string;
tags: string[];
}>>('trigger_list');
return { triggers };
} catch (error) {
this.log('error', `[TriggersAPI] listTriggers failed: ${this.formatError(error)}`);
return { triggers: [] };
}
}
async getTrigger(_id: string): Promise<{ id: string; type: string; enabled: boolean } | null> {
return null;
/**
* Get a single trigger by ID
* Returns null on error for graceful degradation
*/
async getTrigger(id: string): Promise<{
id: string;
name: string;
handId: string;
triggerType: string;
enabled: boolean;
createdAt: string;
modifiedAt: string;
description?: string;
tags: string[];
} | null> {
try {
return await invoke<{
id: string;
name: string;
handId: string;
triggerType: string;
enabled: boolean;
createdAt: string;
modifiedAt: string;
description?: string;
tags: string[];
} | null>('trigger_get', { id });
} catch (error) {
this.log('error', `[TriggersAPI] getTrigger(${id}) failed: ${this.formatError(error)}`);
return null;
}
}
async createTrigger(_trigger: { type: string; name?: string; enabled?: boolean; config?: Record<string, unknown>; handName?: string; workflowId?: string }): Promise<{ id?: string } | null> {
return null;
/**
* Create a new trigger
* Returns null on error for graceful degradation
*/
async createTrigger(trigger: {
id: string;
name: string;
handId: string;
triggerType: { type: string; cron?: string; pattern?: string; path?: string; secret?: string; events?: string[] };
enabled?: boolean;
description?: string;
tags?: string[];
}): Promise<{
id: string;
name: string;
handId: string;
triggerType: string;
enabled: boolean;
createdAt: string;
modifiedAt: string;
description?: string;
tags: string[];
} | null> {
try {
return await invoke<{
id: string;
name: string;
handId: string;
triggerType: string;
enabled: boolean;
createdAt: string;
modifiedAt: string;
description?: string;
tags: string[];
}>('trigger_create', { request: trigger });
} catch (error) {
this.log('error', `[TriggersAPI] createTrigger(${trigger.id}) failed: ${this.formatError(error)}`);
return null;
}
}
async updateTrigger(_id: string, _updates: { name?: string; enabled?: boolean; config?: Record<string, unknown>; handName?: string; workflowId?: string }): Promise<{ id: string }> {
throw new Error('Triggers not implemented');
/**
* Update an existing trigger
* Throws on error as this is a mutation operation that callers need to handle
*/
async updateTrigger(id: string, updates: {
name?: string;
enabled?: boolean;
handId?: string;
triggerType?: { type: string; cron?: string; pattern?: string; path?: string; secret?: string; events?: string[] };
}): Promise<{
id: string;
name: string;
handId: string;
triggerType: string;
enabled: boolean;
createdAt: string;
modifiedAt: string;
description?: string;
tags: string[];
}> {
try {
return await invoke<{
id: string;
name: string;
handId: string;
triggerType: string;
enabled: boolean;
createdAt: string;
modifiedAt: string;
description?: string;
tags: string[];
}>('trigger_update', { id, updates });
} catch (error) {
this.log('error', `[TriggersAPI] updateTrigger(${id}) failed: ${this.formatError(error)}`);
throw error;
}
}
async deleteTrigger(_id: string): Promise<{ status: string }> {
throw new Error('Triggers not implemented');
/**
* Delete a trigger
* Throws on error as this is a destructive operation that callers need to handle
*/
async deleteTrigger(id: string): Promise<void> {
try {
await invoke('trigger_delete', { id });
} catch (error) {
this.log('error', `[TriggersAPI] deleteTrigger(${id}) failed: ${this.formatError(error)}`);
throw error;
}
}
// === Approvals API (stubs for compatibility) ===
async listApprovals(_status?: string): Promise<{ approvals?: unknown[] }> {
return { approvals: [] };
/**
* Execute a trigger
* Throws on error as callers need to know if execution failed
*/
async executeTrigger(id: string, input?: Record<string, unknown>): Promise<Record<string, unknown>> {
try {
return await invoke<Record<string, unknown>>('trigger_execute', { id, input: input || {} });
} catch (error) {
this.log('error', `[TriggersAPI] executeTrigger(${id}) failed: ${this.formatError(error)}`);
throw error;
}
}
async respondToApproval(_approvalId: string, _approved: boolean, _reason?: string): Promise<{ status: string }> {
throw new Error('Approvals not implemented');
// === Approvals API ===
async listApprovals(_status?: string): Promise<{
approvals: Array<{
id: string;
handId: string;
status: string;
createdAt: string;
input: Record<string, unknown>;
}>
}> {
try {
const approvals = await invoke<Array<{
id: string;
handId: string;
status: string;
createdAt: string;
input: Record<string, unknown>;
}>>('approval_list');
return { approvals };
} catch (error) {
console.error('[kernel-client] listApprovals error:', error);
return { approvals: [] };
}
}
async respondToApproval(approvalId: string, approved: boolean, reason?: string): Promise<void> {
return invoke('approval_respond', { id: approvalId, approved, reason });
}
/**
@@ -871,6 +1045,16 @@ export class KernelClient {
private log(level: string, message: string): void {
this.onLog?.(level, message);
}
/**
* Format error for consistent logging
*/
private formatError(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
return String(error);
}
}
// === Singleton ===

View File

@@ -139,7 +139,6 @@ export class PipelineRecommender {
}
const recommendations: PipelineRecommendation[] = [];
const messageLower = message.toLowerCase();
for (const pattern of INTENT_PATTERNS) {
const matches = pattern.keywords

View File

@@ -0,0 +1,174 @@
/**
* OpenViking Client - Semantic Memory Operations
*
* Client for interacting with OpenViking CLI sidecar.
* Provides semantic search, resource management, and knowledge base operations.
*/
import { invoke } from '@tauri-apps/api/core';
// === Types ===
export interface VikingStatus {
available: boolean;
version?: string;
dataDir?: string;
error?: string;
}
export interface VikingResource {
uri: string;
name: string;
resourceType: string;
size?: number;
modifiedAt?: string;
}
export interface VikingFindResult {
uri: string;
score: number;
content: string;
level: string;
overview?: string;
}
export interface VikingGrepResult {
uri: string;
line: number;
content: string;
matchStart: number;
matchEnd: number;
}
export interface VikingAddResult {
uri: string;
status: string;
}
// === Client Functions ===
/**
* Check if OpenViking CLI is available
*/
export async function getVikingStatus(): Promise<VikingStatus> {
return invoke<VikingStatus>('viking_status');
}
/**
* Add a resource to OpenViking from file
*/
export async function addVikingResource(
uri: string,
content: string
): Promise<VikingAddResult> {
return invoke<VikingAddResult>('viking_add', { uri, content });
}
/**
* Add a resource with inline content
*/
export async function addVikingResourceInline(
uri: string,
content: string
): Promise<VikingAddResult> {
return invoke<VikingAddResult>('viking_add_inline', { uri, content });
}
/**
* Find resources by semantic search
*/
export async function findVikingResources(
query: string,
scope?: string,
limit?: number
): Promise<VikingFindResult[]> {
return invoke<VikingFindResult[]>('viking_find', { query, scope, limit });
}
/**
* Grep resources by pattern
*/
export async function grepVikingResources(
pattern: string,
uri?: string,
caseSensitive?: boolean,
limit?: number
): Promise<VikingGrepResult[]> {
return invoke<VikingGrepResult[]>('viking_grep', {
pattern,
uri,
caseSensitive,
limit,
});
}
/**
* List resources at a path
*/
export async function listVikingResources(path: string): Promise<VikingResource[]> {
return invoke<VikingResource[]>('viking_ls', { path });
}
/**
* Read resource content
*/
export async function readVikingResource(
uri: string,
level?: string
): Promise<string> {
return invoke<string>('viking_read', { uri, level });
}
/**
* Remove a resource
*/
export async function removeVikingResource(uri: string): Promise<void> {
return invoke<void>('viking_remove', { uri });
}
/**
* Get resource tree
*/
export async function getVikingTree(
path: string,
depth?: number
): Promise<Record<string, unknown>> {
return invoke<Record<string, unknown>>('viking_tree', { path, depth });
}
// === Server Functions ===
export interface VikingServerStatus {
running: boolean;
port?: number;
pid?: number;
error?: string;
}
/**
* Get Viking server status
*/
export async function getVikingServerStatus(): Promise<VikingServerStatus> {
return invoke<VikingServerStatus>('viking_server_status');
}
/**
* Start Viking server
*/
export async function startVikingServer(): Promise<void> {
return invoke<void>('viking_server_start');
}
/**
* Stop Viking server
*/
export async function stopVikingServer(): Promise<void> {
return invoke<void>('viking_server_stop');
}
/**
* Restart Viking server
*/
export async function restartVikingServer(): Promise<void> {
return invoke<void>('viking_server_restart');
}

View File

@@ -43,10 +43,13 @@ export interface WorkspaceInfo {
export interface ChannelInfo {
id: string;
type: string;
name: string;
label: string;
status: 'active' | 'inactive' | 'error';
enabled?: boolean;
accounts?: number;
error?: string;
config?: Record<string, string>;
}
export interface ScheduledTask {
@@ -292,12 +295,13 @@ export const useConfigStore = create<ConfigStateSlice & ConfigActionsSlice>((set
channels.push({
id: 'feishu',
type: 'feishu',
name: 'feishu',
label: '飞书 (Feishu)',
status: feishu?.configured ? 'active' : 'inactive',
accounts: feishu?.accounts || 0,
});
} catch {
channels.push({ id: 'feishu', type: 'feishu', label: '飞书 (Feishu)', status: 'inactive' });
channels.push({ id: 'feishu', type: 'feishu', name: 'feishu', label: '飞书 (Feishu)', status: 'inactive' });
}
set({ channels });

View File

@@ -0,0 +1,161 @@
/**
* Mesh Store - State management for Adaptive Intelligence Mesh
*
* Manages workflow recommendations and behavior patterns.
*/
import { create } from 'zustand';
import { invoke } from '@tauri-apps/api/core';
import type {
WorkflowRecommendation,
BehaviorPattern,
MeshConfig,
MeshAnalysisResult,
PatternContext,
ActivityType,
} from '../lib/intelligence-client';
// === Types ===
export interface MeshState {
// State
recommendations: WorkflowRecommendation[];
patterns: BehaviorPattern[];
config: MeshConfig;
isLoading: boolean;
error: string | null;
lastAnalysis: string | null;
// Actions
analyze: () => Promise<void>;
acceptRecommendation: (recommendationId: string) => Promise<void>;
dismissRecommendation: (recommendationId: string) => Promise<void>;
recordActivity: (activity: ActivityType, context: PatternContext) => Promise<void>;
getPatterns: () => Promise<void>;
updateConfig: (config: Partial<MeshConfig>) => Promise<void>;
decayPatterns: () => Promise<void>;
clearError: () => void;
}
// === Store ===
export const useMeshStore = create<MeshState>((set, get) => ({
// Initial state
recommendations: [],
patterns: [],
config: {
enabled: true,
min_confidence: 0.6,
max_recommendations: 5,
analysis_window_hours: 24,
},
isLoading: false,
error: null,
lastAnalysis: null,
// Actions
analyze: async () => {
set({ isLoading: true, error: null });
try {
const agentId = localStorage.getItem('currentAgentId') || 'default';
const result = await invoke<MeshAnalysisResult>('mesh_analyze', { agentId });
set({
recommendations: result.recommendations,
patterns: [], // Will be populated by getPatterns
lastAnalysis: result.timestamp,
isLoading: false,
});
// Also fetch patterns
await get().getPatterns();
} catch (err) {
set({
error: err instanceof Error ? err.message : String(err),
isLoading: false,
});
}
},
acceptRecommendation: async (recommendationId: string) => {
try {
const agentId = localStorage.getItem('currentAgentId') || 'default';
await invoke('mesh_accept_recommendation', { agentId, recommendationId });
// Remove from local state
set((state) => ({
recommendations: state.recommendations.filter((r) => r.id !== recommendationId),
}));
} catch (err) {
set({ error: err instanceof Error ? err.message : String(err) });
}
},
dismissRecommendation: async (recommendationId: string) => {
try {
const agentId = localStorage.getItem('currentAgentId') || 'default';
await invoke('mesh_dismiss_recommendation', { agentId, recommendationId });
// Remove from local state
set((state) => ({
recommendations: state.recommendations.filter((r) => r.id !== recommendationId),
}));
} catch (err) {
set({ error: err instanceof Error ? err.message : String(err) });
}
},
recordActivity: async (activity: ActivityType, context: PatternContext) => {
try {
const agentId = localStorage.getItem('currentAgentId') || 'default';
await invoke('mesh_record_activity', { agentId, activityType: activity, context });
} catch (err) {
console.error('Failed to record activity:', err);
}
},
getPatterns: async () => {
try {
const agentId = localStorage.getItem('currentAgentId') || 'default';
const patterns = await invoke<BehaviorPattern[]>('mesh_get_patterns', { agentId });
set({ patterns });
} catch (err) {
console.error('Failed to get patterns:', err);
}
},
updateConfig: async (config: Partial<MeshConfig>) => {
try {
const agentId = localStorage.getItem('currentAgentId') || 'default';
const newConfig = { ...get().config, ...config };
await invoke('mesh_update_config', { agentId, config: newConfig });
set({ config: newConfig });
} catch (err) {
set({ error: err instanceof Error ? err.message : String(err) });
}
},
decayPatterns: async () => {
try {
const agentId = localStorage.getItem('currentAgentId') || 'default';
await invoke('mesh_decay_patterns', { agentId });
// Refresh patterns after decay
await get().getPatterns();
} catch (err) {
console.error('Failed to decay patterns:', err);
}
},
clearError: () => set({ error: null }),
}));
// === Types for intelligence-client ===
export type {
WorkflowRecommendation,
BehaviorPattern,
MeshConfig,
MeshAnalysisResult,
PatternContext,
ActivityType,
};

View File

@@ -0,0 +1,195 @@
/**
* Persona Evolution Store
*
* Manages persona evolution state and proposals.
*/
import { create } from 'zustand';
import { invoke } from '@tauri-apps/api/core';
import type {
EvolutionResult,
EvolutionProposal,
PersonaEvolverConfig,
PersonaEvolverState,
MemoryEntryForAnalysis,
} from '../lib/intelligence-client';
export interface PersonaEvolutionStore {
// State
currentAgentId: string;
proposals: EvolutionProposal[];
history: EvolutionResult[];
isLoading: boolean;
error: string | null;
config: PersonaEvolverConfig | null;
state: PersonaEvolverState | null;
showProposalsPanel: boolean;
// Actions
setCurrentAgentId: (agentId: string) => void;
setShowProposalsPanel: (show: boolean) => void;
// Evolution Actions
runEvolution: (memories: MemoryEntryForAnalysis[]) => Promise<EvolutionResult | null>;
loadEvolutionHistory: (limit?: number) => Promise<void>;
loadEvolverState: () => Promise<void>;
loadEvolverConfig: () => Promise<void>;
updateConfig: (config: Partial<PersonaEvolverConfig>) => Promise<void>;
// Proposal Actions
getPendingProposals: () => EvolutionProposal[];
applyProposal: (proposal: EvolutionProposal) => Promise<boolean>;
dismissProposal: (proposalId: string) => void;
clearProposals: () => void;
}
export const usePersonaEvolutionStore = create<PersonaEvolutionStore>((set, get) => ({
// Initial State
currentAgentId: '',
proposals: [],
history: [],
isLoading: false,
error: null,
config: null,
state: null,
showProposalsPanel: false,
// Setters
setCurrentAgentId: (agentId: string) => set({ currentAgentId: agentId }),
setShowProposalsPanel: (show: boolean) => set({ showProposalsPanel: show }),
// Run evolution cycle for current agent
runEvolution: async (memories: MemoryEntryForAnalysis[]) => {
const { currentAgentId } = get();
if (!currentAgentId) {
set({ error: 'No agent selected' });
return null;
}
set({ isLoading: true, error: null });
try {
const result = await invoke<EvolutionResult>('persona_evolve', {
agentId: currentAgentId,
memories,
});
// Update state with results
set((state) => ({
history: [result, ...state.history].slice(0, 20),
proposals: [...result.proposals, ...state.proposals],
isLoading: false,
showProposalsPanel: result.proposals.length > 0,
}));
return result;
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
set({ error: errorMsg, isLoading: false });
return null;
}
},
// Load evolution history
loadEvolutionHistory: async (limit = 10) => {
set({ isLoading: true, error: null });
try {
const history = await invoke<EvolutionResult[]>('persona_evolution_history', {
limit,
});
set({ history, isLoading: false });
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
set({ error: errorMsg, isLoading: false });
}
},
// Load evolver state
loadEvolverState: async () => {
try {
const state = await invoke<PersonaEvolverState>('persona_evolver_state');
set({ state });
} catch (err) {
console.error('[PersonaStore] Failed to load evolver state:', err);
}
},
// Load evolver config
loadEvolverConfig: async () => {
try {
const config = await invoke<PersonaEvolverConfig>('persona_evolver_config');
set({ config });
} catch (err) {
console.error('[PersonaStore] Failed to load evolver config:', err);
}
},
// Update evolver config
updateConfig: async (newConfig: Partial<PersonaEvolverConfig>) => {
const { config } = get();
if (!config) return;
const updatedConfig = { ...config, ...newConfig };
try {
await invoke('persona_evolver_update_config', { config: updatedConfig });
set({ config: updatedConfig });
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
set({ error: errorMsg });
}
},
// Get pending proposals sorted by confidence
getPendingProposals: () => {
const { proposals } = get();
return proposals
.filter((p) => p.status === 'pending')
.sort((a, b) => b.confidence - a.confidence);
},
// Apply a proposal (approve)
applyProposal: async (proposal: EvolutionProposal) => {
set({ isLoading: true, error: null });
try {
await invoke('persona_apply_proposal', { proposal });
// Remove from pending list
set((state) => ({
proposals: state.proposals.filter((p) => p.id !== proposal.id),
isLoading: false,
}));
return true;
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
set({ error: errorMsg, isLoading: false });
return false;
}
},
// Dismiss a proposal (reject)
dismissProposal: (proposalId: string) => {
set((state) => ({
proposals: state.proposals.filter((p) => p.id !== proposalId),
}));
},
// Clear all proposals
clearProposals: () => set({ proposals: [] }),
}));
// Export convenience hooks
export const usePendingProposals = () =>
usePersonaEvolutionStore((state) => state.getPendingProposals());
export const useEvolutionHistory = () =>
usePersonaEvolutionStore((state) => state.history);
export const useEvolverConfig = () =>
usePersonaEvolutionStore((state) => state.config);
export const useEvolverState = () =>
usePersonaEvolutionStore((state) => state.state);