Spaces:
Running

axeronis commited on
Commit
b470ffe
·
1 Parent(s): 95fcbcb

fix: optimize AI toggle (optimistic UI, silent refresh, removed clunky page reloads)

Browse files
frontend/app/chats/page.tsx CHANGED
@@ -267,6 +267,7 @@ function ChatsContent() {
267
  isAnalyzing={selectedLead.processing_status === 'analyzing'}
268
  onRefresh={handleRefresh}
269
  onLeadRefresh={handleRefreshLeadOnly}
 
270
  onTakeover={() => { }}
271
  onBack={() => {
272
  // Clear selection to return to list on mobile
 
267
  isAnalyzing={selectedLead.processing_status === 'analyzing'}
268
  onRefresh={handleRefresh}
269
  onLeadRefresh={handleRefreshLeadOnly}
270
+ onConversationUpdate={(data) => setConversation(data)}
271
  onTakeover={() => { }}
272
  onBack={() => {
273
  // Clear selection to return to list on mobile
frontend/components/ChatWindow.tsx CHANGED
@@ -32,7 +32,8 @@ interface ChatWindowProps {
32
  isLoading?: boolean
33
  isAnalyzing?: boolean
34
  onRefresh?: () => void
35
- onLeadRefresh?: () => void // Refresh only lead data, not messages
 
36
  onTakeover?: () => void
37
  onBack?: () => void
38
  onToggleLeadsList?: () => void
@@ -76,6 +77,7 @@ export function ChatWindow({
76
  isAnalyzing,
77
  onRefresh,
78
  onLeadRefresh,
 
79
  onTakeover,
80
  onBack,
81
  onToggleLeadsList,
@@ -88,6 +90,7 @@ export function ChatWindow({
88
  const [realtimeMessages, setRealtimeMessages] = useState<Message[]>([])
89
  const [isMobileDrawerOpen, setIsMobileDrawerOpen] = useState(false)
90
  const [isTogglingAI, setIsTogglingAI] = useState(false)
 
91
  const [isBookingModalOpen, setIsBookingModalOpen] = useState(false)
92
  const [isTraining, setIsTraining] = useState(false)
93
  const [isTrainConfirmOpen, setIsTrainConfirmOpen] = useState(false)
@@ -95,8 +98,13 @@ export function ChatWindow({
95
 
96
  const messagesEndRef = useRef<HTMLDivElement>(null)
97
 
 
 
 
 
 
98
  // Computed values
99
- const isAIActive = !conversation?.human_takeover
100
  const allMessages = [...messages, ...optimisticMessages, ...realtimeMessages]
101
  .filter((msg, index, self) => index === self.findIndex((t) => t.id === msg.id))
102
  .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime())
@@ -187,29 +195,31 @@ export function ChatWindow({
187
 
188
  const handleToggleAI = async () => {
189
  if (!leadId || isTogglingAI) return
190
- setIsTogglingAI(true)
191
- try {
192
- const newIsAIActive = !!conversation?.human_takeover
193
- const token = localStorage.getItem('auth_token')
194
- if (!token) throw new Error('Не авторизован')
195
 
196
- const response = await fetch(
197
- `${process.env.NEXT_PUBLIC_API_URL}/api/v1/leads/${leadId}/toggle-ai`,
198
- {
199
- method: 'POST',
200
- headers: {
201
- 'Authorization': `Bearer ${token}`,
202
- 'Content-Type': 'application/json'
203
- },
204
- body: JSON.stringify({ is_ai_active: newIsAIActive })
205
- }
206
- )
207
 
208
- if (!response.ok) throw new Error('Failed to toggle AI')
209
- if (onRefresh) onRefresh()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  } catch (error) {
211
  console.error('Error toggling AI:', error)
212
- alert('Ошибка переключения режима AI')
 
 
213
  } finally {
214
  setIsTogglingAI(false)
215
  }
 
32
  isLoading?: boolean
33
  isAnalyzing?: boolean
34
  onRefresh?: () => void
35
+ onLeadRefresh?: () => void
36
+ onConversationUpdate?: (data: any) => void // New prop for silent updates
37
  onTakeover?: () => void
38
  onBack?: () => void
39
  onToggleLeadsList?: () => void
 
77
  isAnalyzing,
78
  onRefresh,
79
  onLeadRefresh,
80
+ onConversationUpdate,
81
  onTakeover,
82
  onBack,
83
  onToggleLeadsList,
 
90
  const [realtimeMessages, setRealtimeMessages] = useState<Message[]>([])
91
  const [isMobileDrawerOpen, setIsMobileDrawerOpen] = useState(false)
92
  const [isTogglingAI, setIsTogglingAI] = useState(false)
93
+ const [localAIActive, setLocalAIActive] = useState<boolean>(!conversation?.human_takeover)
94
  const [isBookingModalOpen, setIsBookingModalOpen] = useState(false)
95
  const [isTraining, setIsTraining] = useState(false)
96
  const [isTrainConfirmOpen, setIsTrainConfirmOpen] = useState(false)
 
98
 
99
  const messagesEndRef = useRef<HTMLDivElement>(null)
100
 
101
+ // Sync local state with prop
102
+ useEffect(() => {
103
+ setLocalAIActive(!conversation?.human_takeover)
104
+ }, [conversation?.human_takeover])
105
+
106
  // Computed values
107
+ const isAIActive = localAIActive
108
  const allMessages = [...messages, ...optimisticMessages, ...realtimeMessages]
109
  .filter((msg, index, self) => index === self.findIndex((t) => t.id === msg.id))
110
  .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime())
 
195
 
196
  const handleToggleAI = async () => {
197
  if (!leadId || isTogglingAI) return
 
 
 
 
 
198
 
199
+ const prevValue = localAIActive
200
+ const newValue = !prevValue
 
 
 
 
 
 
 
 
 
201
 
202
+ // 1. Optimistic Update
203
+ setLocalAIActive(newValue)
204
+ setIsTogglingAI(true)
205
+
206
+ try {
207
+ const result = await leadsApi.toggleAI(leadId, newValue)
208
+
209
+ // 2. Silent refresh of lead data & conversation state
210
+ if (onLeadRefresh) onLeadRefresh()
211
+ if (onConversationUpdate) {
212
+ // Update parent state with actual values from server
213
+ onConversationUpdate({
214
+ ...conversation,
215
+ human_takeover: result.human_takeover
216
+ })
217
+ }
218
  } catch (error) {
219
  console.error('Error toggling AI:', error)
220
+ // 3. Rollback on failure
221
+ setLocalAIActive(prevValue)
222
+ toast.error('Ошибка переключения режима AI')
223
  } finally {
224
  setIsTogglingAI(false)
225
  }
frontend/components/ChatWindow/ChatHeader.tsx CHANGED
@@ -121,21 +121,23 @@ export function ChatHeader({
121
  "relative w-12 h-6 rounded-full transition-all duration-300 flex-shrink-0",
122
  isAIActive
123
  ? "bg-gradient-to-r from-indigo-500 to-purple-600"
124
- : "bg-zinc-700"
 
125
  )}
126
  title={isAIActive ? 'AI Активен' : 'AI Отключен'}
127
  >
128
- {isTogglingAI ? (
129
- <div className="absolute inset-0 flex items-center justify-center">
130
- <Loader2 className="w-3 h-3 animate-spin text-white" />
131
- </div>
132
- ) : (
133
- <motion.div
134
- animate={{ x: isAIActive ? 26 : 4 }}
135
- transition={{ type: "spring", stiffness: 500, damping: 30 }}
136
- className="absolute top-1 w-4 h-4 bg-white rounded-full shadow-lg"
137
- />
138
- )}
 
139
  </button>
140
  </div>
141
 
 
121
  "relative w-12 h-6 rounded-full transition-all duration-300 flex-shrink-0",
122
  isAIActive
123
  ? "bg-gradient-to-r from-indigo-500 to-purple-600"
124
+ : "bg-zinc-700",
125
+ isTogglingAI && "opacity-80 cursor-wait"
126
  )}
127
  title={isAIActive ? 'AI Активен' : 'AI Отключен'}
128
  >
129
+ <motion.div
130
+ animate={{
131
+ x: isAIActive ? 26 : 4,
132
+ scale: isTogglingAI ? 0.8 : 1
133
+ }}
134
+ transition={{ type: "spring", stiffness: 500, damping: 30 }}
135
+ className="absolute top-1 w-4 h-4 bg-white rounded-full shadow-lg flex items-center justify-center overflow-hidden"
136
+ >
137
+ {isTogglingAI && (
138
+ <Loader2 className="w-2.5 h-2.5 animate-spin text-indigo-500" />
139
+ )}
140
+ </motion.div>
141
  </button>
142
  </div>
143