feat(chat): write API keys to OpenClaw and embed Control UI for chat
Part 1: API Key Integration - Create electron/utils/openclaw-auth.ts to write keys to ~/.openclaw/agents/main/agent/auth-profiles.json - Update provider:save and provider:setApiKey IPC handlers to persist keys to OpenClaw auth-profiles alongside ClawX storage - Save API key to OpenClaw on successful validation in Setup wizard - Pass provider API keys as environment variables when starting the Gateway process (ANTHROPIC_API_KEY, OPENROUTER_API_KEY, etc.) Part 2: Embed OpenClaw Control UI for Chat - Replace custom Chat UI with <webview> embedding the Gateway's built-in Control UI at http://127.0.0.1:{port}/?token={token} - Add gateway:getControlUiUrl IPC handler to provide tokenized URL - Enable webviewTag in Electron BrowserWindow preferences - Override X-Frame-Options/CSP headers to allow webview embedding - Suppress noisy control-ui token_mismatch stderr messages - Add loading/error states for the embedded webview This fixes the "No API key found for provider" error and replaces the buggy custom chat implementation with OpenClaw's battle-tested Control UI.
This commit is contained in:
@@ -15,6 +15,8 @@ import {
|
||||
isOpenClawInstalled
|
||||
} from '../utils/paths';
|
||||
import { getSetting } from '../utils/store';
|
||||
import { getApiKey } from '../utils/secure-storage';
|
||||
import { getProviderEnvVar } from '../utils/openclaw-auth';
|
||||
import { GatewayEventType, JsonRpcNotification, isNotification, isResponse } from './protocol';
|
||||
|
||||
/**
|
||||
@@ -370,6 +372,24 @@ export class GatewayManager extends EventEmitter {
|
||||
console.log(`Spawning Gateway: ${command} ${args.join(' ')}`);
|
||||
console.log(`Working directory: ${openclawDir}`);
|
||||
|
||||
// Load provider API keys from secure storage to pass as environment variables
|
||||
const providerEnv: Record<string, string> = {};
|
||||
const providerTypes = ['anthropic', 'openai', 'google', 'openrouter'];
|
||||
for (const providerType of providerTypes) {
|
||||
try {
|
||||
const key = await getApiKey(providerType);
|
||||
if (key) {
|
||||
const envVar = getProviderEnvVar(providerType);
|
||||
if (envVar) {
|
||||
providerEnv[envVar] = key;
|
||||
console.log(`Loaded API key for ${providerType} -> ${envVar}`);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(`Failed to load API key for ${providerType}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.process = spawn(command, args, {
|
||||
cwd: openclawDir,
|
||||
@@ -378,6 +398,8 @@ export class GatewayManager extends EventEmitter {
|
||||
shell: process.platform === 'win32', // Use shell on Windows for pnpm
|
||||
env: {
|
||||
...process.env,
|
||||
// Provider API keys
|
||||
...providerEnv,
|
||||
// Skip channel auto-connect during startup for faster boot
|
||||
OPENCLAW_SKIP_CHANNELS: '1',
|
||||
CLAWDBOT_SKIP_CHANNELS: '1',
|
||||
@@ -407,9 +429,18 @@ export class GatewayManager extends EventEmitter {
|
||||
console.log('Gateway:', data.toString());
|
||||
});
|
||||
|
||||
// Log stderr
|
||||
// Log stderr (filter out noisy control-ui token_mismatch messages)
|
||||
this.process.stderr?.on('data', (data) => {
|
||||
console.error('Gateway error:', data.toString());
|
||||
const msg = data.toString();
|
||||
// Suppress the constant Control UI token_mismatch noise
|
||||
// These come from the browser-based Control UI auto-polling with no token
|
||||
if (msg.includes('openclaw-control-ui') && msg.includes('token_mismatch')) {
|
||||
return;
|
||||
}
|
||||
if (msg.includes('closed before connect') && msg.includes('token mismatch')) {
|
||||
return;
|
||||
}
|
||||
console.error('Gateway error:', msg);
|
||||
});
|
||||
|
||||
// Store PID
|
||||
@@ -516,7 +547,7 @@ export class GatewayManager extends EventEmitter {
|
||||
}, 10000);
|
||||
|
||||
this.pendingRequests.set(connectId, {
|
||||
resolve: (result) => {
|
||||
resolve: (_result) => {
|
||||
clearTimeout(connectTimeout);
|
||||
handshakeComplete = true;
|
||||
console.log('WebSocket handshake complete, gateway connected');
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Electron Main Process Entry
|
||||
* Manages window creation, system tray, and IPC handlers
|
||||
*/
|
||||
import { app, BrowserWindow, ipcMain, shell } from 'electron';
|
||||
import { app, BrowserWindow, ipcMain, session, shell } from 'electron';
|
||||
import { join } from 'path';
|
||||
import { GatewayManager } from '../gateway/manager';
|
||||
import { registerIpcHandlers } from './ipc-handlers';
|
||||
@@ -32,6 +32,7 @@ function createWindow(): BrowserWindow {
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
sandbox: false,
|
||||
webviewTag: true, // Enable <webview> for embedding OpenClaw Control UI
|
||||
},
|
||||
titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default',
|
||||
trafficLightPosition: { x: 16, y: 16 },
|
||||
@@ -74,6 +75,28 @@ async function initialize(): Promise<void> {
|
||||
// Create system tray
|
||||
createTray(mainWindow);
|
||||
|
||||
// Override security headers for the OpenClaw Control UI webview
|
||||
// The Control UI sets X-Frame-Options: DENY and CSP frame-ancestors 'none'
|
||||
// which prevents embedding in an Electron webview
|
||||
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
|
||||
const headers = { ...details.responseHeaders };
|
||||
// Remove X-Frame-Options to allow embedding in webview
|
||||
delete headers['X-Frame-Options'];
|
||||
delete headers['x-frame-options'];
|
||||
// Remove restrictive CSP frame-ancestors
|
||||
if (headers['Content-Security-Policy']) {
|
||||
headers['Content-Security-Policy'] = headers['Content-Security-Policy'].map(
|
||||
(csp) => csp.replace(/frame-ancestors\s+'none'/g, "frame-ancestors 'self' *")
|
||||
);
|
||||
}
|
||||
if (headers['content-security-policy']) {
|
||||
headers['content-security-policy'] = headers['content-security-policy'].map(
|
||||
(csp) => csp.replace(/frame-ancestors\s+'none'/g, "frame-ancestors 'self' *")
|
||||
);
|
||||
}
|
||||
callback({ responseHeaders: headers });
|
||||
});
|
||||
|
||||
// Register IPC handlers
|
||||
registerIpcHandlers(gatewayManager, mainWindow);
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
type ProviderConfig,
|
||||
} from '../utils/secure-storage';
|
||||
import { getOpenClawStatus } from '../utils/paths';
|
||||
import { getSetting } from '../utils/store';
|
||||
import { saveProviderKeyToOpenClaw } from '../utils/openclaw-auth';
|
||||
|
||||
/**
|
||||
* Register all IPC handlers
|
||||
@@ -104,6 +106,20 @@ function registerGatewayHandlers(
|
||||
}
|
||||
});
|
||||
|
||||
// Get the Control UI URL with token for embedding
|
||||
ipcMain.handle('gateway:getControlUiUrl', async () => {
|
||||
try {
|
||||
const status = gatewayManager.getStatus();
|
||||
const token = await getSetting('gatewayToken');
|
||||
const port = status.port || 18789;
|
||||
// Pass token as query param - Control UI will store it in localStorage
|
||||
const url = `http://127.0.0.1:${port}/?token=${encodeURIComponent(token)}`;
|
||||
return { success: true, url, port, token };
|
||||
} catch (error) {
|
||||
return { success: false, error: String(error) };
|
||||
}
|
||||
});
|
||||
|
||||
// Health check
|
||||
ipcMain.handle('gateway:health', async () => {
|
||||
try {
|
||||
@@ -203,6 +219,13 @@ function registerProviderHandlers(): void {
|
||||
// Store the API key if provided
|
||||
if (apiKey) {
|
||||
await storeApiKey(config.id, apiKey);
|
||||
|
||||
// Also write to OpenClaw auth-profiles.json so the gateway can use it
|
||||
try {
|
||||
saveProviderKeyToOpenClaw(config.type, apiKey);
|
||||
} catch (err) {
|
||||
console.warn('Failed to save key to OpenClaw auth-profiles:', err);
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
@@ -225,6 +248,17 @@ function registerProviderHandlers(): void {
|
||||
ipcMain.handle('provider:setApiKey', async (_, providerId: string, apiKey: string) => {
|
||||
try {
|
||||
await storeApiKey(providerId, apiKey);
|
||||
|
||||
// Also write to OpenClaw auth-profiles.json
|
||||
// Resolve provider type from stored config, or use providerId as type
|
||||
const provider = await getProvider(providerId);
|
||||
const providerType = provider?.type || providerId;
|
||||
try {
|
||||
saveProviderKeyToOpenClaw(providerType, apiKey);
|
||||
} catch (err) {
|
||||
console.warn('Failed to save key to OpenClaw auth-profiles:', err);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: String(error) };
|
||||
|
||||
@@ -22,6 +22,7 @@ const electronAPI = {
|
||||
'gateway:restart',
|
||||
'gateway:rpc',
|
||||
'gateway:health',
|
||||
'gateway:getControlUiUrl',
|
||||
// OpenClaw
|
||||
'openclaw:status',
|
||||
'openclaw:isReady',
|
||||
|
||||
163
electron/utils/openclaw-auth.ts
Normal file
163
electron/utils/openclaw-auth.ts
Normal file
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* OpenClaw Auth Profiles Utility
|
||||
* Writes API keys to ~/.openclaw/agents/main/agent/auth-profiles.json
|
||||
* so the OpenClaw Gateway can load them for AI provider calls.
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { homedir } from 'os';
|
||||
|
||||
const AUTH_STORE_VERSION = 1;
|
||||
const AUTH_PROFILE_FILENAME = 'auth-profiles.json';
|
||||
|
||||
/**
|
||||
* Auth profile entry for an API key
|
||||
*/
|
||||
interface AuthProfileEntry {
|
||||
type: 'api_key';
|
||||
provider: string;
|
||||
key: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auth profiles store format
|
||||
*/
|
||||
interface AuthProfilesStore {
|
||||
version: number;
|
||||
profiles: Record<string, AuthProfileEntry>;
|
||||
order?: Record<string, string[]>;
|
||||
lastGood?: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider type to environment variable name mapping
|
||||
*/
|
||||
const PROVIDER_ENV_VARS: Record<string, string> = {
|
||||
anthropic: 'ANTHROPIC_API_KEY',
|
||||
openai: 'OPENAI_API_KEY',
|
||||
google: 'GEMINI_API_KEY',
|
||||
openrouter: 'OPENROUTER_API_KEY',
|
||||
groq: 'GROQ_API_KEY',
|
||||
deepgram: 'DEEPGRAM_API_KEY',
|
||||
cerebras: 'CEREBRAS_API_KEY',
|
||||
xai: 'XAI_API_KEY',
|
||||
mistral: 'MISTRAL_API_KEY',
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the path to the auth-profiles.json for a given agent
|
||||
*/
|
||||
function getAuthProfilesPath(agentId = 'main'): string {
|
||||
return join(homedir(), '.openclaw', 'agents', agentId, 'agent', AUTH_PROFILE_FILENAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read existing auth profiles store, or create an empty one
|
||||
*/
|
||||
function readAuthProfiles(agentId = 'main'): AuthProfilesStore {
|
||||
const filePath = getAuthProfilesPath(agentId);
|
||||
|
||||
try {
|
||||
if (existsSync(filePath)) {
|
||||
const raw = readFileSync(filePath, 'utf-8');
|
||||
const data = JSON.parse(raw) as AuthProfilesStore;
|
||||
// Validate basic structure
|
||||
if (data.version && data.profiles && typeof data.profiles === 'object') {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to read auth-profiles.json, creating fresh store:', error);
|
||||
}
|
||||
|
||||
return {
|
||||
version: AUTH_STORE_VERSION,
|
||||
profiles: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Write auth profiles store to disk
|
||||
*/
|
||||
function writeAuthProfiles(store: AuthProfilesStore, agentId = 'main'): void {
|
||||
const filePath = getAuthProfilesPath(agentId);
|
||||
const dir = join(filePath, '..');
|
||||
|
||||
// Ensure directory exists
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
writeFileSync(filePath, JSON.stringify(store, null, 2), 'utf-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a provider API key to OpenClaw's auth-profiles.json
|
||||
* This writes the key in the format OpenClaw expects so the gateway
|
||||
* can use it for AI provider calls.
|
||||
*
|
||||
* @param provider - Provider type (e.g., 'anthropic', 'openrouter', 'openai', 'google')
|
||||
* @param apiKey - The API key to store
|
||||
* @param agentId - Agent ID (defaults to 'main')
|
||||
*/
|
||||
export function saveProviderKeyToOpenClaw(
|
||||
provider: string,
|
||||
apiKey: string,
|
||||
agentId = 'main'
|
||||
): void {
|
||||
const store = readAuthProfiles(agentId);
|
||||
|
||||
// Profile ID follows OpenClaw convention: <provider>:default
|
||||
const profileId = `${provider}:default`;
|
||||
|
||||
// Upsert the profile entry
|
||||
store.profiles[profileId] = {
|
||||
type: 'api_key',
|
||||
provider,
|
||||
key: apiKey,
|
||||
};
|
||||
|
||||
// Update order to include this profile
|
||||
if (!store.order) {
|
||||
store.order = {};
|
||||
}
|
||||
if (!store.order[provider]) {
|
||||
store.order[provider] = [];
|
||||
}
|
||||
if (!store.order[provider].includes(profileId)) {
|
||||
store.order[provider].push(profileId);
|
||||
}
|
||||
|
||||
// Set as last good
|
||||
if (!store.lastGood) {
|
||||
store.lastGood = {};
|
||||
}
|
||||
store.lastGood[provider] = profileId;
|
||||
|
||||
writeAuthProfiles(store, agentId);
|
||||
console.log(`Saved API key for provider "${provider}" to OpenClaw auth-profiles (agent: ${agentId})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the environment variable name for a provider type
|
||||
*/
|
||||
export function getProviderEnvVar(provider: string): string | undefined {
|
||||
return PROVIDER_ENV_VARS[provider];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build environment variables object with all stored API keys
|
||||
* for passing to the Gateway process
|
||||
*/
|
||||
export function buildProviderEnvVars(providers: Array<{ type: string; apiKey: string }>): Record<string, string> {
|
||||
const env: Record<string, string> = {};
|
||||
|
||||
for (const { type, apiKey } of providers) {
|
||||
const envVar = PROVIDER_ENV_VARS[type];
|
||||
if (envVar && apiKey) {
|
||||
env[envVar] = apiKey;
|
||||
}
|
||||
}
|
||||
|
||||
return env;
|
||||
}
|
||||
@@ -1,399 +1,164 @@
|
||||
/**
|
||||
* Chat Page
|
||||
* Conversation interface with AI
|
||||
* Embeds OpenClaw's Control UI for chat functionality.
|
||||
* The Control UI handles all chat protocol details (sessions, streaming, etc.)
|
||||
* and is served by the Gateway at http://127.0.0.1:{port}/
|
||||
*/
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import {
|
||||
Send,
|
||||
Trash2,
|
||||
Bot,
|
||||
User,
|
||||
Copy,
|
||||
Check,
|
||||
RefreshCw,
|
||||
AlertCircle,
|
||||
Sparkles,
|
||||
MessageSquare,
|
||||
} from 'lucide-react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import { AlertCircle, RefreshCw, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { useChatStore } from '@/stores/chat';
|
||||
import { useGatewayStore } from '@/stores/gateway';
|
||||
import { LoadingSpinner } from '@/components/common/LoadingSpinner';
|
||||
import { cn, formatRelativeTime } from '@/lib/utils';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
// Message component with markdown support
|
||||
interface ChatMessageProps {
|
||||
message: {
|
||||
id: string;
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
timestamp: string;
|
||||
toolCalls?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
arguments: Record<string, unknown>;
|
||||
result?: unknown;
|
||||
status: 'pending' | 'running' | 'completed' | 'error';
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
function ChatMessage({ message }: ChatMessageProps) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const isUser = message.role === 'user';
|
||||
|
||||
const copyContent = useCallback(() => {
|
||||
navigator.clipboard.writeText(message.content);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}, [message.content]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex gap-3 group',
|
||||
isUser ? 'flex-row-reverse' : 'flex-row'
|
||||
)}
|
||||
>
|
||||
{/* Avatar */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-8 w-8 shrink-0 items-center justify-center rounded-full',
|
||||
isUser
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-gradient-to-br from-indigo-500 to-purple-600 text-white'
|
||||
)}
|
||||
>
|
||||
{isUser ? (
|
||||
<User className="h-4 w-4" />
|
||||
) : (
|
||||
<Sparkles className="h-4 w-4" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Message Content */}
|
||||
<div
|
||||
className={cn(
|
||||
'relative max-w-[80%] rounded-2xl px-4 py-3',
|
||||
isUser
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-muted'
|
||||
)}
|
||||
>
|
||||
{isUser ? (
|
||||
<p className="whitespace-pre-wrap">{message.content}</p>
|
||||
) : (
|
||||
<div className="prose prose-sm dark:prose-invert max-w-none">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
components={{
|
||||
// Custom code block styling
|
||||
code({ className, children, ...props }) {
|
||||
const match = /language-(\w+)/.exec(className || '');
|
||||
const isInline = !match && !className;
|
||||
|
||||
if (isInline) {
|
||||
return (
|
||||
<code className="bg-background/50 px-1.5 py-0.5 rounded text-sm font-mono" {...props}>
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative group/code">
|
||||
{match && (
|
||||
<div className="absolute right-2 top-2 flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground opacity-60">
|
||||
{match[1]}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 opacity-0 group-hover/code:opacity-100 transition-opacity"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(String(children));
|
||||
toast.success('Code copied!');
|
||||
}}
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<pre className="bg-background/50 rounded-lg p-4 overflow-x-auto">
|
||||
<code className={cn('text-sm font-mono', className)} {...props}>
|
||||
{children}
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
// Custom link styling
|
||||
a({ href, children }) {
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
},
|
||||
}}
|
||||
>
|
||||
{message.content}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Timestamp and actions */}
|
||||
<div className={cn(
|
||||
'flex items-center gap-2 mt-2',
|
||||
isUser ? 'justify-end' : 'justify-between'
|
||||
)}>
|
||||
<p
|
||||
className={cn(
|
||||
'text-xs',
|
||||
isUser
|
||||
? 'text-primary-foreground/70'
|
||||
: 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{formatRelativeTime(message.timestamp)}
|
||||
</p>
|
||||
|
||||
{!isUser && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
onClick={copyContent}
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tool Calls */}
|
||||
{message.toolCalls && message.toolCalls.length > 0 && (
|
||||
<div className="mt-3 space-y-2 border-t pt-2">
|
||||
<p className="text-xs font-medium text-muted-foreground">Tools Used:</p>
|
||||
{message.toolCalls.map((tool) => (
|
||||
<Card key={tool.id} className="bg-background/50">
|
||||
<CardContent className="p-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-xs font-medium">{tool.name}</p>
|
||||
<span className={cn(
|
||||
'text-xs px-1.5 py-0.5 rounded',
|
||||
tool.status === 'completed' && 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
|
||||
tool.status === 'running' && 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
|
||||
tool.status === 'error' && 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
|
||||
tool.status === 'pending' && 'bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400'
|
||||
)}>
|
||||
{tool.status}
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Typing indicator component
|
||||
function TypingIndicator() {
|
||||
return (
|
||||
<div className="flex gap-3">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 text-white">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
</div>
|
||||
<div className="bg-muted rounded-2xl px-4 py-3">
|
||||
<div className="flex gap-1">
|
||||
<span className="w-2 h-2 bg-muted-foreground/50 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} />
|
||||
<span className="w-2 h-2 bg-muted-foreground/50 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
|
||||
<span className="w-2 h-2 bg-muted-foreground/50 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Welcome screen component
|
||||
function WelcomeScreen() {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center text-center p-8">
|
||||
<div className="w-20 h-20 rounded-2xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center mb-6">
|
||||
<Bot className="h-10 w-10 text-white" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold mb-2">Welcome to ClawX Chat</h2>
|
||||
<p className="text-muted-foreground mb-8 max-w-md">
|
||||
I'm your AI assistant, ready to help with tasks, answer questions, and more.
|
||||
Start by typing a message below.
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4 max-w-lg w-full">
|
||||
{[
|
||||
{ icon: MessageSquare, title: 'Ask Questions', desc: 'Get answers on any topic' },
|
||||
{ icon: Sparkles, title: 'Creative Tasks', desc: 'Writing, brainstorming, ideas' },
|
||||
].map((item, i) => (
|
||||
<Card key={i} className="text-left">
|
||||
<CardContent className="p-4">
|
||||
<item.icon className="h-6 w-6 text-primary mb-2" />
|
||||
<h3 className="font-medium">{item.title}</h3>
|
||||
<p className="text-sm text-muted-foreground">{item.desc}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// Custom CSS to inject into the Control UI to match ClawX theme
|
||||
const CUSTOM_CSS = `
|
||||
/* Hide the Control UI header/nav that we don't need */
|
||||
.gateway-header, [data-testid="gateway-header"] {
|
||||
display: none !important;
|
||||
}
|
||||
/* Remove top padding that the header would occupy */
|
||||
body, #root {
|
||||
background: transparent !important;
|
||||
}
|
||||
/* Ensure the chat area fills the frame */
|
||||
.chat-container, [data-testid="chat-container"] {
|
||||
height: 100vh !important;
|
||||
max-height: 100vh !important;
|
||||
}
|
||||
`;
|
||||
|
||||
export function Chat() {
|
||||
const { messages, loading, sending, error, fetchHistory, sendMessage, clearHistory } = useChatStore();
|
||||
const gatewayStatus = useGatewayStore((state) => state.status);
|
||||
const [input, setInput] = useState('');
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const [controlUiUrl, setControlUiUrl] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const webviewRef = useRef<HTMLWebViewElement>(null);
|
||||
|
||||
const isGatewayRunning = gatewayStatus.state === 'running';
|
||||
|
||||
// Fetch history on mount
|
||||
// Fetch Control UI URL when gateway is running
|
||||
useEffect(() => {
|
||||
if (isGatewayRunning) {
|
||||
fetchHistory();
|
||||
if (!isGatewayRunning) {
|
||||
setControlUiUrl(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
}, [fetchHistory, isGatewayRunning]);
|
||||
|
||||
// Auto-scroll to bottom on new messages
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
}, [messages, sending]);
|
||||
|
||||
// Auto-resize textarea
|
||||
useEffect(() => {
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto';
|
||||
textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 200)}px`;
|
||||
}
|
||||
}, [input]);
|
||||
|
||||
// Handle send message
|
||||
const handleSend = useCallback(async () => {
|
||||
if (!input.trim() || sending || !isGatewayRunning) return;
|
||||
|
||||
const content = input.trim();
|
||||
setInput('');
|
||||
await sendMessage(content);
|
||||
}, [input, sending, isGatewayRunning, sendMessage]);
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
window.electron.ipcRenderer.invoke('gateway:getControlUiUrl')
|
||||
.then((result: unknown) => {
|
||||
const r = result as { success: boolean; url?: string; error?: string };
|
||||
if (r.success && r.url) {
|
||||
setControlUiUrl(r.url);
|
||||
} else {
|
||||
setError(r.error || 'Failed to get Control UI URL');
|
||||
}
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
setError(String(err));
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false);
|
||||
});
|
||||
}, [isGatewayRunning]);
|
||||
|
||||
// Handle key press
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
// Inject custom CSS when webview loads
|
||||
const handleWebviewReady = useCallback(() => {
|
||||
const webview = webviewRef.current as unknown as HTMLElement & {
|
||||
addEventListener: (event: string, cb: (e: unknown) => void) => void;
|
||||
insertCSS: (css: string) => Promise<string>;
|
||||
reload: () => void;
|
||||
};
|
||||
if (!webview) return;
|
||||
|
||||
webview.addEventListener('dom-ready', () => {
|
||||
// Inject custom CSS to match ClawX theme
|
||||
webview.insertCSS(CUSTOM_CSS).catch((err: unknown) => {
|
||||
console.warn('Failed to inject CSS:', err);
|
||||
});
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
webview.addEventListener('did-fail-load', (event: unknown) => {
|
||||
const e = event as { errorCode: number; errorDescription: string };
|
||||
if (e.errorCode !== -3) { // -3 is ERR_ABORTED, ignore it
|
||||
setError(`Failed to load: ${e.errorDescription}`);
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Set up webview event listeners
|
||||
useEffect(() => {
|
||||
if (controlUiUrl && webviewRef.current) {
|
||||
handleWebviewReady();
|
||||
}
|
||||
}, [handleSend]);
|
||||
}, [controlUiUrl, handleWebviewReady]);
|
||||
|
||||
return (
|
||||
<div className="flex h-[calc(100vh-8rem)] flex-col">
|
||||
{/* Gateway Warning */}
|
||||
{!isGatewayRunning && (
|
||||
<div className="bg-yellow-50 dark:bg-yellow-900/20 border-b border-yellow-200 dark:border-yellow-800 px-4 py-3 flex items-center gap-3">
|
||||
<AlertCircle className="h-5 w-5 text-yellow-600 dark:text-yellow-400" />
|
||||
<span className="text-sm text-yellow-700 dark:text-yellow-300">
|
||||
Gateway is not running. Chat functionality is unavailable.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Messages Area */}
|
||||
<div className="flex-1 overflow-auto p-4 space-y-4">
|
||||
{loading ? (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<LoadingSpinner size="lg" />
|
||||
</div>
|
||||
) : messages.length === 0 ? (
|
||||
<WelcomeScreen />
|
||||
) : (
|
||||
<>
|
||||
{messages.map((message) => (
|
||||
<ChatMessage key={message.id} message={message} />
|
||||
))}
|
||||
{sending && <TypingIndicator />}
|
||||
<div ref={messagesEndRef} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="px-4 py-2 bg-red-50 dark:bg-red-900/20 border-t border-red-200 dark:border-red-800">
|
||||
<p className="text-sm text-red-600 dark:text-red-400 flex items-center gap-2">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Input Area */}
|
||||
<div className="border-t p-4 bg-background">
|
||||
<div className="flex items-end gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={clearHistory}
|
||||
disabled={messages.length === 0}
|
||||
title="Clear history"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<div className="flex-1 relative">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={isGatewayRunning ? "Type a message... (Shift+Enter for new line)" : "Gateway not connected..."}
|
||||
disabled={sending || !isGatewayRunning}
|
||||
className="min-h-[44px] max-h-[200px] resize-none pr-12"
|
||||
rows={1}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
disabled={!input.trim() || sending || !isGatewayRunning}
|
||||
size="icon"
|
||||
className="shrink-0"
|
||||
>
|
||||
{sending ? (
|
||||
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground mt-2 text-center">
|
||||
Press Enter to send, Shift+Enter for new line
|
||||
const handleReload = useCallback(() => {
|
||||
const webview = webviewRef.current as unknown as HTMLElement & { reload: () => void };
|
||||
if (webview) {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
webview.reload();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Gateway not running state
|
||||
if (!isGatewayRunning) {
|
||||
return (
|
||||
<div className="flex h-[calc(100vh-8rem)] flex-col items-center justify-center text-center p-8">
|
||||
<AlertCircle className="h-12 w-12 text-yellow-500 mb-4" />
|
||||
<h2 className="text-xl font-semibold mb-2">Gateway Not Running</h2>
|
||||
<p className="text-muted-foreground max-w-md">
|
||||
The OpenClaw Gateway needs to be running to use chat.
|
||||
It will start automatically, or you can start it from Settings.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-[calc(100vh-4rem)] flex-col relative">
|
||||
{/* Loading overlay */}
|
||||
{loading && (
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/80">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground">Loading chat...</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error state */}
|
||||
{error && (
|
||||
<div className="absolute inset-0 z-10 flex flex-col items-center justify-center bg-background p-8 text-center">
|
||||
<AlertCircle className="h-12 w-12 text-red-500 mb-4" />
|
||||
<h2 className="text-xl font-semibold mb-2">Connection Error</h2>
|
||||
<p className="text-muted-foreground max-w-md mb-4">{error}</p>
|
||||
<Button onClick={handleReload} variant="outline">
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Embedded Control UI */}
|
||||
{controlUiUrl && (
|
||||
<webview
|
||||
ref={webviewRef as unknown as React.RefObject<HTMLElement>}
|
||||
src={controlUiUrl}
|
||||
className="flex-1 w-full h-full border-0"
|
||||
// @ts-expect-error webview attributes not in React types
|
||||
allowpopups="true"
|
||||
style={{
|
||||
display: error ? 'none' : 'flex',
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -551,7 +551,24 @@ function ProviderContent({
|
||||
setKeyValid(result.valid);
|
||||
|
||||
if (result.valid) {
|
||||
toast.success('API key validated successfully');
|
||||
// Save the API key to both ClawX secure storage and OpenClaw auth-profiles
|
||||
try {
|
||||
await window.electron.ipcRenderer.invoke(
|
||||
'provider:save',
|
||||
{
|
||||
id: selectedProvider,
|
||||
name: selectedProviderData?.name || selectedProvider,
|
||||
type: selectedProvider,
|
||||
enabled: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
apiKey
|
||||
);
|
||||
} catch (saveErr) {
|
||||
console.warn('Failed to persist API key:', saveErr);
|
||||
}
|
||||
toast.success('API key validated and saved');
|
||||
} else {
|
||||
toast.error(result.error || 'Invalid API key');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user