Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions frontend/src/app/components/ChatInterface.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
import React, { useRef, useEffect } from 'react';
import { Bot, Send, CheckCircle2, AlertCircle } from 'lucide-react';
import type { Message } from '../../types/chat';

interface ChatInterfaceProps {
messages: Message[];
inputState: string;
setInputState: (value: string) => void;
isTyping: boolean;
handleSendMessage: (e: React.FormEvent) => void;
"use client";

import React, { useEffect, useRef, useState } from "react";
Expand All @@ -20,6 +30,69 @@ export interface ChatInterfaceProps {

export function ChatInterface({
messages,
inputState,
setInputState,
isTyping,
handleSendMessage,
}: ChatInterfaceProps) {
const messagesEndRef = useRef<HTMLDivElement>(null);

// Auto scroll
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages, isTyping]);

return (
<div className="glass-panel">
<div className="chat-container">
<div className="chat-header">
<div className="agent-avatar">
<Bot size={28} />
</div>
<div>
<h2 style={{ margin: 0, fontSize: '1.25rem' }}>OpenClaw Agent</h2>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '0.85rem', color: 'var(--success)' }}>
<CheckCircle2 size={12} fill="var(--success)" color="var(--bg-card)" /> Online
</div>
</div>
</div>

<div className="chat-messages">
{messages.map((msg) => (
<div key={msg.id} className={`message ${msg.sender}`}>
{msg.proactive && (
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '0.75rem', color: 'var(--accent-primary)', marginBottom: '4px', fontWeight: 600, textTransform: 'uppercase' }}>
<AlertCircle size={12} /> Proactive Nudge
</div>
)}
<div className="message-bubble">{msg.text}</div>
</div>
))}
{isTyping && (
<div className="message agent">
<div className="typing-indicator">
<span></span><span></span><span></span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>

<form onSubmit={handleSendMessage} className="chat-input-container">
<input
type="text"
placeholder="Ask Smasage to adjust goals..."
value={inputState}
onChange={(e) => setInputState(e.target.value)}
/>
<button type="submit" className="send-button">
<Send size={18} />
</button>
</form>
</div>
</div>
);
}
isTyping,
onSendMessage,
placeholder = "Ask Smasage to adjust goals...",
Expand Down
53 changes: 53 additions & 0 deletions frontend/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
"use client"
import React, { useState } from 'react';
import { Target, Activity } from 'lucide-react';
import { PortfolioStats } from './components/PortfolioStats';
import { evaluateGoalStatus, getStatusColor, type GoalData } from '../utils/goalProjection';
import PortfolioChart from './PortfolioChart';
import { DashboardHeader } from './components/DashboardHeader';
import { ConnectWalletButton } from './components/ConnectWalletButton';
import { useWallet } from './components/WalletContext';
import { ErrorBoundary } from './components/ErrorBoundary';
import { useChat } from '../hooks/useChat';
import { ChatInterface } from './components/ChatInterface';

export default function Home() {
const { publicKey, setPublicKey } = useWallet();
const [showInstallModal, setShowInstallModal] = useState(false);
// Connect Wallet logic
const handleConnectWallet = async () => {
if (!window.freighterApi) {
setShowInstallModal(true);
return;
}
try {
const key = await window.freighterApi.getPublicKey();
setPublicKey(key);
} catch {
// Optionally handle rejection
}
};
"use client";
import React, { useState, useEffect, useMemo } from "react";
import { Activity } from "lucide-react";
Expand Down Expand Up @@ -73,6 +102,21 @@ export default function Home() {
};
}, [goalData]);

// Calculate goal status
const goalResult = evaluateGoalStatus(goalData);
const progress = goalResult.progressPercentage;
const goalStatus = goalResult.status;

const { messages, inputState, setInputState, isTyping, handleSendMessage, allocations, wsConnected } = useChat({
userId: 'user-demo-001',
goalData,
});

return (
<ErrorBoundary fallbackMessage="The dashboard failed to load. Please try again.">
<>
<DashboardHeader wsConnected={wsConnected}>
<ConnectWalletButton onClick={handleConnectWallet} publicKey={publicKey || undefined} />
// WebSocket notifications
const { registerGoal } = useNotifications({
userId: "user-demo-001",
Expand Down Expand Up @@ -233,6 +277,15 @@ export default function Home() {
</div>
</div>

{/* Right Panel - Chat Agent */}
<ChatInterface
messages={messages}
inputState={inputState}
setInputState={setInputState}
isTyping={isTyping}
handleSendMessage={handleSendMessage}
/>
</main>
{/* Right Panel - Chat Agent */}
<div className="glass-panel">
<ChatInterface
Expand Down
97 changes: 97 additions & 0 deletions frontend/src/hooks/useChat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { useState, useEffect, useCallback } from 'react';
import { useNotifications } from './useNotifications';
import { parseAllocationsFromMessage, getDefaultAllocations } from '../utils/allocationParser';
import type { AssetAllocation } from '../utils/chartUtils';
import type { GoalData } from '../utils/goalProjection';
import type { Message } from '../types/chat';

interface UseChatOptions {
userId: string;
goalData: GoalData;
}

export function useChat({ userId, goalData }: UseChatOptions) {
const [messages, setMessages] = useState<Message[]>([
{ id: 1, sender: 'agent', text: "Welcome to Smasage! 👋 I'm OpenClaw, your personal AI savings assistant natively built on Stellar. What financial goal can we crush today?" }
]);
const [inputState, setInputState] = useState('');
const [isTyping, setIsTyping] = useState(false);
const [allocations, setAllocations] = useState<AssetAllocation[]>(getDefaultAllocations());

const { registerGoal, isConnected } = useNotifications({
userId,
onNotification: (notification) => {
if (notification.type === 'agent-message') {
const payload = notification.payload as { text: string; proactive?: boolean; timestamp?: string; };
const agentMsg: Message = {
id: Date.now(),
sender: 'agent',
text: payload.text,
proactive: payload.proactive,
timestamp: payload.timestamp,
};
setMessages(prev => [...prev, agentMsg]);

// Parse allocations if present
const parsedAllocations = parseAllocationsFromMessage(payload.text);
if (parsedAllocations) {
setAllocations(parsedAllocations);
}
}
},
onError: (error) => {
console.error('[Chat] WebSocket error:', error);
},
enabled: true,
});

// Register goal when connected
useEffect(() => {
if (isConnected) {
registerGoal({
currentBalance: goalData.currentBalance,
targetAmount: goalData.targetAmount,
targetDate: goalData.targetDate,
expectedAPY: goalData.expectedAPY,
monthlyContribution: goalData.monthlyContribution,
});
}
}, [isConnected, registerGoal, goalData]);

const handleSendMessage = useCallback((e: React.FormEvent) => {
e.preventDefault();
if (!inputState.trim()) return;

const userMsg: Message = { id: Date.now(), sender: 'user', text: inputState };
setMessages(prev => [...prev, userMsg]);
setInputState('');
setIsTyping(true);

// Mock agent response delay
setTimeout(() => {
setIsTyping(false);
const agentMsg: Message = {
id: Date.now() + 1,
sender: 'agent',
text: "That's a great goal. I'll allocate 60% to Stellar Blend for safe yield, and the rest to Soroswap XLM/USDC LP to accelerate returns. Does that sound good?"
};
setMessages(prev => [...prev, agentMsg]);

// Parse allocations from agent message
const parsedAllocations = parseAllocationsFromMessage(agentMsg.text);
if (parsedAllocations) {
setAllocations(parsedAllocations);
}
}, 1800);
}, [inputState]);

return {
messages,
inputState,
setInputState,
isTyping,
handleSendMessage,
allocations,
wsConnected: isConnected,
};
}
7 changes: 7 additions & 0 deletions frontend/src/types/chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface Message {
id: number;
sender: 'agent' | 'user';
text: string;
proactive?: boolean;
timestamp?: string;
}
Loading