forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAIChat.tsx
More file actions
226 lines (206 loc) · 7.59 KB
/
Copy pathAIChat.tsx
File metadata and controls
226 lines (206 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import React, { useState, useRef, useEffect } from 'react';
import { Send, Terminal, Layers, RefreshCw, Copy, Check, Plus } from 'lucide-react';
import { appStore, useAppStore } from '@/lib/store';
import { DEFAULT_MOVE_CALL } from '@/lib/constants';
import { apiService, AiChatMessage, AiToolCall } from '@/services/api';
import { RequestType } from '../types';
import { Avatar } from '../components/ui/Avatar';
interface Message extends AiChatMessage {
toolCall?: AiToolCall | null;
}
const INITIAL_MESSAGE: Message = {
role: 'model',
text: 'Sui AI Console ready.'
};
export const AIChat: React.FC = () => {
const { pendingAiPrompt } = useAppStore();
const [messages, setMessages] = useState<Message[]>([
INITIAL_MESSAGE
]);
const [input, setInput] = useState('');
const [isTyping, setIsTyping] = useState(false);
const [copiedId, setCopiedId] = useState<number | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const pendingPromptRef = useRef<string | null>(null);
const handleSendRef = useRef<(msg: string) => Promise<void>>(null!);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [messages, isTyping]);
useEffect(() => {
if (pendingAiPrompt && !pendingPromptRef.current) {
pendingPromptRef.current = pendingAiPrompt;
appStore.setPendingAiPrompt(null);
void handleSendRef.current(pendingAiPrompt);
}
}, [pendingAiPrompt]);
const handleCopy = (text: string, index: number) => {
navigator.clipboard.writeText(text);
setCopiedId(index);
setTimeout(() => setCopiedId(null), 2000);
};
const normalizeToolArgs = (
toolCall: AiToolCall
) => toolCall.args || {};
const resolveToolCallLabel = (
toolCall: AiToolCall
) => {
const args = normalizeToolArgs(toolCall);
return typeof args.name === 'string' && args.name.trim()
? args.name
: toolCall.name;
};
const handleSend = async (userMessage: string) => {
const trimmedMessage = userMessage.trim();
if (!trimmedMessage || isTyping) return;
setInput('');
const nextHistory: Message[] = [
...messages,
{ role: 'user', text: trimmedMessage }
];
setMessages(prev => [
...prev,
{ role: 'user', text: trimmedMessage }
]);
setIsTyping(true);
try {
const response = await apiService.sendAiChat(
nextHistory.map(({ role, text }) => ({
role,
text
}))
);
setMessages(prev => [
...prev,
{
role: response.role,
text: response.text,
toolCall:
response.toolCall ?? null
}
]);
} catch (error) {
const errorMessage =
error instanceof Error &&
error.message.trim()
? error.message
: 'AI Service Unavailable.';
setMessages(prev => [
...prev,
{
role: 'model',
text: `Error: ${errorMessage}`
}
]);
} finally {
setIsTyping(false);
}
};
useEffect(() => {
handleSendRef.current = handleSend;
});
const executeToolCall = (
toolCall: AiToolCall
) => {
const args = normalizeToolArgs(
toolCall
);
if (toolCall.name === 'create_rpc_request') {
appStore.openTab('rpc', {
id: `rpc-gen-${Date.now()}`,
name:
typeof args.name === 'string' &&
args.name.trim()
? args.name
: 'Generated Request',
type: RequestType.RPC,
rpcParams: {
method:
typeof args.method === 'string'
? args.method
: '',
params: Array.isArray(args.params)
? args.params
: []
},
moveParams: {
...DEFAULT_MOVE_CALL
}
});
}
if (toolCall.name === 'create_ptb') {
appStore.openTab('ptb', {
id: `ptb-gen-${Date.now()}`,
name:
typeof args.name === 'string' &&
args.name.trim()
? args.name
: 'Generated PTB',
type: RequestType.TRANSACTION,
rpcParams: {
method: '',
params: []
},
moveParams: {
...DEFAULT_MOVE_CALL
},
description:
typeof args.description === 'string'
? args.description
: undefined
});
}
};
return (
<div className="flex flex-col h-full bg-near-black font-sans">
<div className="px-4 py-2 border-b border-white/5 bg-dark-indigo-glow flex justify-between items-center shrink-0">
<span className="font-bold text-slate-400 text-xs">AI Console</span>
<button onClick={() => setMessages([INITIAL_MESSAGE])} aria-label="Clear chat history" title="Clear chat history" className="p-1 text-slate-500 hover:text-white"><RefreshCw size={14}/></button>
</div>
<div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-4 custom-scrollbar">
{messages.map((m, i) => (
<div key={i} className={`flex gap-3 ${m.role === 'user' ? 'flex-row-reverse' : ''}`}>
<Avatar
size="xs"
type={m.role === 'model' ? 'bot' : 'user'}
seed={m.role === 'model' ? 'sui-ai' : 'txio-user'}
/>
<div className={`max-w-[90%] space-y-2`}>
<div className={`p-3 rounded text-xs font-mono whitespace-pre-wrap relative group ${m.role === 'user' ? 'bg-slate-800 text-slate-200' : 'bg-near-black border border-white/5 text-slate-300'}`}>
{m.text}
{m.role === 'model' && (
<button onClick={() => handleCopy(m.text, i)} aria-label="Copy response" title="Copy response" className="absolute right-2 top-2 opacity-0 group-hover:opacity-100 text-slate-500 hover:text-white">
{copiedId === i ? <Check size={12}/> : <Copy size={12}/>}
</button>
)}
</div>
{m.toolCall && (
<div className="bg-dark-indigo-glow border border-white/5 p-2 rounded flex items-center justify-between">
<div className="text-xs text-electric-violet font-mono flex items-center gap-2">
{m.toolCall.name === 'create_rpc_request' ? <Terminal size={12}/> : <Layers size={12}/>}
{resolveToolCallLabel(m.toolCall)}
</div>
<button onClick={() => executeToolCall(m.toolCall!)} aria-label="Apply suggested action" title="Apply suggested action" className="p-1 bg-sui-700 text-white rounded hover:bg-electric-violet"><Plus size={12}/></button>
</div>
)}
</div>
</div>
))}
{isTyping && <div className="text-xs text-slate-600 italic px-10">Processing...</div>}
</div>
<div className="p-3 border-t border-white/5 bg-dark-indigo-glow">
<form onSubmit={(e) => { e.preventDefault(); handleSend(input); }} className="relative">
<input
className="w-full bg-near-black border border-white/10 rounded p-2 pr-10 text-xs text-white font-mono focus:border-electric-violet outline-none"
placeholder="Enter prompt..."
value={input}
onChange={(e) => setInput(e.target.value)}
disabled={isTyping}
/>
<button type="submit" disabled={!input.trim()} className="absolute right-2 top-1.5 text-slate-500 hover:text-white"><Send size={14}/></button>
</form>
</div>
</div>
);
};