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
69 changes: 69 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,65 @@ export interface ChatInterfaceProps {

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

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>
isTyping,
onSendMessage,
placeholder = "Ask Smasage to adjust goals...",
Expand Down
45 changes: 45 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,13 @@ export default function Home() {
};
}, [goalData]);

const { messages, inputState, setInputState, isTyping, handleSendMessage, allocations, wsConnected } = useChat({
userId: 'user-demo-001',
goalData,
});
const goalResult = evaluateGoalStatus(goalData);
const progress = goalResult.progressPercentage;
const goalStatus = goalResult.status;
// WebSocket notifications
const { registerGoal } = useNotifications({
userId: "user-demo-001",
Expand Down Expand Up @@ -233,6 +269,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
120 changes: 120 additions & 0 deletions frontend/src/hooks/useChat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { useState, useEffect, useCallback, useRef } 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 [wsConnected, setWsConnected] = useState(false);
const responseTimeout = useRef<number | null>(null);

const { registerGoal } = useNotifications({
userId,
onNotification: (notification) => {
if (notification.type === 'connected') {
setWsConnected(true);
} else 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]);

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

useEffect(() => {
if (wsConnected) {
registerGoal({
currentBalance: goalData.currentBalance,
targetAmount: goalData.targetAmount,
targetDate: goalData.targetDate,
expectedAPY: goalData.expectedAPY,
monthlyContribution: goalData.monthlyContribution,
});
}
}, [wsConnected, registerGoal, goalData]);

useEffect(() => {
return () => {
if (responseTimeout.current !== null) {
window.clearTimeout(responseTimeout.current);
}
};
}, []);

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);

responseTimeout.current = window.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]);

const parsedAllocations = parseAllocationsFromMessage(agentMsg.text);
if (parsedAllocations) {
setAllocations(parsedAllocations);
}
}, 1800);
},
[inputState]
);

return {
messages,
inputState,
setInputState,
isTyping,
handleSendMessage,
allocations,
wsConnected,
};
}
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