Skip to content

Commit ca76087

Browse files
committed
feat: unify ai chat context to just platform
1 parent 016516d commit ca76087

3 files changed

Lines changed: 54 additions & 76 deletions

File tree

src/App.tsx

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,10 @@ function AppContent() {
5151
const { isAuthenticated } = useAuth();
5252
const isAuthRoute = ['/login', '/signup', '/verify', '/auth/verify'].includes(location.pathname);
5353

54-
// Determine application context based on route
55-
const appContext = location.pathname.startsWith('/credit') ? 'credit-app' :
56-
location.pathname.startsWith('/idr') ? 'idr' :
57-
'platform';
58-
5954
// Gather comprehensive chat context data - ONLY if authenticated
6055
// This prevents unnecessary API calls and hook issues on login/signup pages
6156
const chatContextData = useChatContext({
62-
context: appContext,
57+
context: 'platform', // Unified platform context
6358
location: location.pathname,
6459
maxItems: {
6560
positions: isAuthenticated ? 10000 : 0,
@@ -73,7 +68,6 @@ function AppContent() {
7368
pathname: location.pathname,
7469
isAuthenticated,
7570
isAuthRoute,
76-
appContext,
7771
});
7872

7973
return (
@@ -207,7 +201,6 @@ function AppContent() {
207201
<Toaster />
208202
{isAuthenticated && (
209203
<ChatWidget
210-
context={appContext}
211204
authToken={localStorage.getItem('arda_token') || undefined}
212205
contextData={chatContextData}
213206
/>

src/shared/components/ui/chat-widget.tsx

Lines changed: 37 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import { cn } from './utils';
88
import { useChatAgentHealth } from '../../hooks/useChatAgentHealth';
99
import { API_PATHS } from '../../config/api-routes';
1010

11-
// Context types for different apps
12-
export type ChatContext = 'platform' | 'credit-app' | 'idr';
11+
// Context type - unified platform
12+
export type ChatContext = 'platform';
1313

1414
interface Message {
1515
role: 'user' | 'assistant' | 'system';
@@ -42,10 +42,6 @@ export interface ContextData {
4242
}
4343

4444
export interface ChatWidgetProps {
45-
/**
46-
* The application context - determines suggested questions and welcome message
47-
*/
48-
context: ChatContext;
4945
/**
5046
* Optional auth token for API calls
5147
*/
@@ -60,45 +56,39 @@ export interface ChatWidgetProps {
6056
*/
6157
onMessageSent?: (message: string) => void;
6258
/**
63-
* Optional custom suggested questions (overrides context-based suggestions)
59+
* Optional custom suggested questions (overrides default suggestions)
6460
*/
6561
customSuggestedQuestions?: SuggestedQuestion[];
6662
}
6763

68-
// Context-specific suggested questions
69-
const SUGGESTED_QUESTIONS: Record<ChatContext, SuggestedQuestion[]> = {
70-
platform: [
71-
{ text: 'How do I create a new company?', category: 'Getting Started' },
72-
{ text: 'How do I invite team members?', category: 'Team Management' },
73-
{ text: 'What is the difference between originator and investor roles?', category: 'Roles' },
74-
{ text: 'How do I switch between Credit App and IDR?', category: 'Navigation' },
75-
],
76-
'credit-app': [
77-
{ text: 'What is my current portfolio performance?', category: 'Portfolio' },
78-
{ text: 'Show me available investment deals', category: 'Deals' },
79-
{ text: 'What are my recent trades and orders?', category: 'Trading' },
80-
{ text: 'Analyze my risk exposure', category: 'Risk' },
81-
{ text: 'What is my Net Asset Value?', category: 'NAV' },
82-
{ text: 'Show payment and cash flow information', category: 'Payments' },
83-
],
84-
idr: [
85-
{ text: 'What documents need my review?', category: 'Documents' },
86-
{ text: 'Show me recent document changes', category: 'Changes' },
87-
{ text: 'What are my pending action items?', category: 'Actions' },
88-
{ text: 'Show document negotiation status', category: 'Negotiations' },
89-
{ text: 'Summarize AI-detected risks', category: 'Risk Analysis' },
90-
],
91-
};
92-
93-
// Context-specific welcome messages
94-
const WELCOME_MESSAGES: Record<ChatContext, string> = {
95-
platform: 'Hello! I\'m Ari, your ARDA Platform assistant. I can help you with:\n\n• Company setup and management\n• Team member invitations\n• Navigation between applications\n• Account settings\n\nWhat would you like to know?',
96-
'credit-app': 'Hello! I\'m Ari, your AI assistant for the ARDA Credit Platform. I can help you with:\n\n• Portfolio analysis & performance\n• Orders, trades & settlements\n• Investment opportunities\n• Risk & exposure metrics\n• Market insights\n\nTry asking me about your portfolio, recent trades, or available deals!',
97-
idr: 'Hello! I\'m Ari, your AI assistant for the Interactive Data Room. I can help you with:\n\n• Document review and analysis\n• Change detection and summaries\n• Action item tracking\n• Negotiation status updates\n• Risk assessments\n\nWhat documents or insights would you like to explore?',
98-
};
64+
// Suggested questions for the unified platform
65+
const SUGGESTED_QUESTIONS: SuggestedQuestion[] = [
66+
{ text: 'What is my current portfolio performance?', category: 'Portfolio' },
67+
{ text: 'Show me available loan deals', category: 'Deals' },
68+
{ text: 'Analyze my risk exposure', category: 'Risk Analysis' },
69+
{ text: 'What documents need my review?', category: 'Documents' },
70+
{ text: 'Track covenant compliance', category: 'Compliance' },
71+
{ text: 'Check for double-pledged collateral', category: 'Risk Analysis' },
72+
{ text: 'Show market insights and analytics', category: 'Analytics' },
73+
{ text: 'What are my pending action items?', category: 'Actions' },
74+
];
75+
76+
// Welcome message for the unified platform
77+
const WELCOME_MESSAGE = 'Hello! I\'m Ari, your ARDA Platform assistant. I can help you with:\n\n• Loan portfolio management and analytics\n• Deal uploads and tracking\n• Document review and analysis\n• Covenant compliance monitoring\n• Double-pledged collateral detection\n• Market insights and risk assessment\n\nWhat would you like to explore?';
78+
79+
// System prompt describing the platform's capabilities
80+
const SYSTEM_PROMPT = `You are Ari, an AI assistant for the ARDA Platform - a comprehensive loan repository and portfolio management system.
81+
82+
The ARDA Platform enables financial institutions to:
83+
- Upload and manage loan deals to the platform
84+
- Access detailed metrics and analytics on loan portfolios
85+
- View broader market information and analysis
86+
- Track covenant compliance across loans
87+
- Identify and monitor potential double-pledged collateral issues
88+
89+
When answering questions, focus on helping users understand and utilize these core features. Be specific about loan management workflows, portfolio analytics, and risk monitoring capabilities.`;
9990

10091
export function ChatWidget({
101-
context,
10292
authToken,
10393
contextData,
10494
onMessageSent,
@@ -108,7 +98,7 @@ export function ChatWidget({
10898
const [messages, setMessages] = useState<Message[]>([
10999
{
110100
role: 'assistant',
111-
content: WELCOME_MESSAGES[context],
101+
content: WELCOME_MESSAGE,
112102
timestamp: new Date(),
113103
},
114104
]);
@@ -120,7 +110,7 @@ export function ChatWidget({
120110
const [progressMessage, setProgressMessage] = useState('');
121111
const messagesEndRef = useRef<HTMLDivElement>(null);
122112

123-
const suggestedQuestions = customSuggestedQuestions || SUGGESTED_QUESTIONS[context];
113+
const suggestedQuestions = customSuggestedQuestions || SUGGESTED_QUESTIONS;
124114

125115
// Use predefined streaming endpoint (proxied by Vite)
126116
const streamEndpoint = API_PATHS.CHAT_STREAM;
@@ -144,8 +134,8 @@ export function ChatWidget({
144134

145135
// Prepare the request payload
146136
const requestPayload = {
147-
message: userMessage,
148-
context,
137+
message: `${SYSTEM_PROMPT}\n\nUser: ${userMessage}`, // Prepend system prompt
138+
context: 'platform', // Unified platform context
149139
contextData,
150140
conversationHistory: messages.map(m => ({
151141
role: m.role,
@@ -158,9 +148,10 @@ export function ChatWidget({
158148
console.log('[ChatWidget API Request] Sending to chat agent:', {
159149
endpoint: streamEndpoint,
160150
hasAuthToken: !!authToken,
151+
hasSystemPrompt: true, // System prompt is prepended to message
161152
payload: {
162-
message: userMessage,
163-
context,
153+
message: userMessage, // Log original message without system prompt for clarity
154+
context: 'platform', // Unified platform context
164155
contextDataSummary: {
165156
hasUser: !!contextData?.user,
166157
userId: contextData?.user?.id,
@@ -510,7 +501,7 @@ export function ChatWidget({
510501

511502
{/* Context Info */}
512503
<div className="text-xs text-muted-foreground pt-2 border-t">
513-
<p><strong>Context:</strong> {context === 'credit-app' ? 'Credit Platform' : context === 'idr' ? 'Data Room' : 'Platform'}</p>
504+
<p><strong>Context:</strong> ARDA Platform</p>
514505
</div>
515506
</div>
516507
)}

src/shared/hooks/useChatContext.ts

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
/**
22
* Central Chat Context Hook
3-
* Aggregates context data from different sources based on application context
3+
* Aggregates comprehensive context data for the unified ARDA Platform
44
*
55
* AUTOMATIC CONTEXT UPDATES:
6-
* - Credit App: Updates automatically when CompanyProvider context changes (company selection)
7-
* - IDR: Updates automatically when documents/deals change via localStorage or providers
8-
* - Platform: Updates automatically when user authentication state changes
6+
* - Portfolio data: Updates automatically when CompanyProvider context changes
7+
* - Documents/Deals: Updates automatically when documents/deals change via localStorage or providers
8+
* - User data: Updates automatically when user authentication state changes
99
*
1010
* PERFORMANCE OPTIMIZATIONS:
1111
* - All collectors use useMemo for efficient recomputation
@@ -16,7 +16,7 @@
1616
* USAGE:
1717
* ```typescript
1818
* const contextData = useChatContext({
19-
* context: 'credit-app',
19+
* context: 'platform',
2020
* location: location.pathname,
2121
* maxItems: { positions: 10, deals: 10, documents: 10, activities: 5 }
2222
* });
@@ -37,7 +37,7 @@ import { usePlatformContext } from './usePlatformContext';
3737

3838
/**
3939
* Main hook for gathering all chat context data
40-
* Automatically selects the appropriate context collector based on app context
40+
* Merges data from all collectors for comprehensive unified platform context
4141
*/
4242
export function useChatContext(options: ChatContextOptions): ChatContextData {
4343
const { context, location, includeFullData = false, maxItems, useCachedData = true } = options;
@@ -48,29 +48,23 @@ export function useChatContext(options: ChatContextOptions): ChatContextData {
4848
const idrData = useIDRContext({ location, maxItems });
4949
const platformData = usePlatformContext({ location });
5050

51-
// Combine and memoize context data
51+
// Combine and memoize context data - merge all data for unified platform
5252
const contextData = useMemo<ChatContextData>(() => {
5353
const baseContext: ChatContextData = {
5454
currentPage: location,
5555
contextTimestamp: new Date(),
5656
contextVersion: '1.0',
5757
};
5858

59-
// Select the appropriate context data based on current context
60-
if (context === 'credit-app') {
61-
return { ...baseContext, ...creditAppData };
62-
}
63-
64-
if (context === 'idr') {
65-
return { ...baseContext, ...idrData };
66-
}
67-
68-
if (context === 'platform') {
69-
return { ...baseContext, ...platformData };
70-
}
71-
72-
return baseContext;
73-
}, [location, context, creditAppData, idrData, platformData]);
59+
// Merge all context data together for the unified platform
60+
// This provides comprehensive context including portfolio, deals, and documents
61+
return {
62+
...baseContext,
63+
...platformData,
64+
...creditAppData,
65+
...idrData,
66+
};
67+
}, [location, creditAppData, idrData, platformData]);
7468

7569
return contextData;
7670
}

0 commit comments

Comments
 (0)