Spaces:
Running

axeronis commited on
Commit
6d6f2a7
·
1 Parent(s): 82b97d4

fix: demo-chat page with localStorage persistence, pending_action confirmation, cache invalidation

Browse files
Files changed (1) hide show
  1. frontend/app/demo-chat/page.tsx +160 -7
frontend/app/demo-chat/page.tsx CHANGED
@@ -2,12 +2,13 @@
2
 
3
  import { useState, useRef, useEffect } from 'react'
4
  import { motion } from 'framer-motion'
5
- import { Send, Bot, User, Loader2, Sparkles, Wand2, ArrowLeft, Trash2, CheckCircle } from 'lucide-react'
6
  import { api } from '@/lib/api'
7
  import { useToast } from '@/contexts/ToastContext'
8
  import { cn } from '@/lib/utils'
9
  import Link from 'next/link'
10
  import { useAuth } from '@/contexts/AuthContext'
 
11
 
12
  interface DemoMessage {
13
  id: string
@@ -17,17 +18,67 @@ interface DemoMessage {
17
  changes?: any[]
18
  }
19
 
 
 
 
 
 
 
 
20
  export default function DemoChatPage() {
21
  const { user, isLoading: authLoading } = useAuth()
22
  const toast = useToast()
 
 
23
  const [messages, setMessages] = useState<DemoMessage[]>([])
24
  const [input, setInput] = useState('')
25
  const [isLoading, setIsLoading] = useState(false)
26
  const [isCorrectMode, setIsCorrectMode] = useState(false)
27
  const [corrections, setCorrections] = useState<string[]>([])
 
 
28
  const messagesEndRef = useRef<HTMLDivElement>(null)
29
  const inputRef = useRef<HTMLInputElement>(null)
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  useEffect(() => {
32
  messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
33
  }, [messages])
@@ -36,6 +87,51 @@ export default function DemoChatPage() {
36
  setTimeout(() => inputRef.current?.focus(), 300)
37
  }, [])
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  const handleSmartCorrection = async (correction: string) => {
40
  setIsLoading(true)
41
  try {
@@ -43,6 +139,10 @@ export default function DemoChatPage() {
43
  const data = response.data
44
 
45
  if (data.success && data.changes.length > 0) {
 
 
 
 
46
  setMessages(prev => [...prev, {
47
  id: crypto.randomUUID(),
48
  role: 'system',
@@ -74,6 +174,10 @@ export default function DemoChatPage() {
74
  }
75
  }
76
 
 
 
 
 
77
  const handleSend = async () => {
78
  if (!input.trim() || isLoading) return
79
 
@@ -112,6 +216,11 @@ export default function DemoChatPage() {
112
  content: response.data.response,
113
  timestamp: new Date()
114
  }])
 
 
 
 
 
115
  } catch (error: any) {
116
  toast.error('Ошибка генерации')
117
  setMessages(prev => [...prev, {
@@ -135,6 +244,9 @@ export default function DemoChatPage() {
135
  const clearChat = () => {
136
  setMessages([])
137
  setCorrections([])
 
 
 
138
  toast.info('Чат очищен')
139
  }
140
 
@@ -148,7 +260,7 @@ export default function DemoChatPage() {
148
 
149
  return (
150
  <div className="flex flex-col h-full bg-[#0a0a0f]">
151
- {/* Header - sticky at top */}
152
  <header className="flex-shrink-0 flex items-center justify-between px-3 py-2 border-b border-white/5 bg-[#0a0a0f] safe-area-top">
153
  <div className="flex items-center gap-2">
154
  <Link href="/settings/brain" className="p-2 text-white/40 hover:text-white rounded-lg">
@@ -163,12 +275,19 @@ export default function DemoChatPage() {
163
  </div>
164
  </div>
165
 
166
- <button onClick={clearChat} className="p-2 text-white/40 hover:text-white rounded-lg">
167
- <Trash2 className="w-4 h-4" />
168
- </button>
 
 
 
 
 
 
 
169
  </header>
170
 
171
- {/* Messages - scrollable middle area */}
172
  <div className="flex-1 overflow-y-auto">
173
  <div className="max-w-2xl mx-auto px-3 py-4 space-y-3">
174
  {messages.length === 0 ? (
@@ -276,7 +395,41 @@ export default function DemoChatPage() {
276
  </div>
277
  </div>
278
 
279
- {/* Input - fixed at bottom with safe area */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  <div className="flex-shrink-0 border-t border-white/5 bg-[#0a0a0f] px-3 py-2 pb-safe">
281
  <div className="max-w-2xl mx-auto">
282
  <div className={cn(
 
2
 
3
  import { useState, useRef, useEffect } from 'react'
4
  import { motion } from 'framer-motion'
5
+ import { Send, Bot, User, Loader2, Sparkles, Wand2, ArrowLeft, Trash2, CheckCircle, X } from 'lucide-react'
6
  import { api } from '@/lib/api'
7
  import { useToast } from '@/contexts/ToastContext'
8
  import { cn } from '@/lib/utils'
9
  import Link from 'next/link'
10
  import { useAuth } from '@/contexts/AuthContext'
11
+ import { useQueryClient } from '@tanstack/react-query'
12
 
13
  interface DemoMessage {
14
  id: string
 
18
  changes?: any[]
19
  }
20
 
21
+ interface PendingAction {
22
+ type: string
23
+ path: string
24
+ value: string
25
+ display_path: string
26
+ }
27
+
28
  export default function DemoChatPage() {
29
  const { user, isLoading: authLoading } = useAuth()
30
  const toast = useToast()
31
+ const queryClient = useQueryClient()
32
+
33
  const [messages, setMessages] = useState<DemoMessage[]>([])
34
  const [input, setInput] = useState('')
35
  const [isLoading, setIsLoading] = useState(false)
36
  const [isCorrectMode, setIsCorrectMode] = useState(false)
37
  const [corrections, setCorrections] = useState<string[]>([])
38
+ const [pendingAction, setPendingAction] = useState<PendingAction | null>(null)
39
+
40
  const messagesEndRef = useRef<HTMLDivElement>(null)
41
  const inputRef = useRef<HTMLInputElement>(null)
42
 
43
+ // =========================================================================
44
+ // LocalStorage Persistence
45
+ // =========================================================================
46
+
47
+ // Load from localStorage on mount
48
+ useEffect(() => {
49
+ try {
50
+ const savedMessages = localStorage.getItem('demoChatPage_messages')
51
+ const savedCorrections = localStorage.getItem('demoChatPage_corrections')
52
+
53
+ if (savedMessages) {
54
+ const parsed = JSON.parse(savedMessages)
55
+ setMessages(parsed.map((m: any) => ({
56
+ ...m,
57
+ timestamp: new Date(m.timestamp)
58
+ })))
59
+ }
60
+ if (savedCorrections) {
61
+ setCorrections(JSON.parse(savedCorrections))
62
+ }
63
+ } catch (e) {
64
+ console.error('Failed to load demo chat from localStorage:', e)
65
+ }
66
+ }, [])
67
+
68
+ // Save messages to localStorage
69
+ useEffect(() => {
70
+ if (messages.length > 0) {
71
+ localStorage.setItem('demoChatPage_messages', JSON.stringify(messages))
72
+ }
73
+ }, [messages])
74
+
75
+ // Save corrections to localStorage
76
+ useEffect(() => {
77
+ if (corrections.length > 0) {
78
+ localStorage.setItem('demoChatPage_corrections', JSON.stringify(corrections))
79
+ }
80
+ }, [corrections])
81
+
82
  useEffect(() => {
83
  messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
84
  }, [messages])
 
87
  setTimeout(() => inputRef.current?.focus(), 300)
88
  }, [])
89
 
90
+ // =========================================================================
91
+ // Confirmation Handlers
92
+ // =========================================================================
93
+
94
+ const confirmAction = async () => {
95
+ if (!pendingAction) return
96
+
97
+ try {
98
+ const response = await api.post('/api/v1/demo/confirm-action', {
99
+ action: pendingAction
100
+ })
101
+
102
+ if (response.data.success) {
103
+ toast.success(`✅ ${response.data.message}`)
104
+
105
+ // Invalidate cache so settings page shows new values
106
+ queryClient.invalidateQueries({ queryKey: ['tenant'] })
107
+ queryClient.invalidateQueries({ queryKey: ['ai-settings'] })
108
+
109
+ setMessages(prev => [...prev, {
110
+ id: crypto.randomUUID(),
111
+ role: 'system',
112
+ content: `✅ Настройка изменена!\n📍 ${pendingAction.display_path}\n→ "${pendingAction.value}"`,
113
+ timestamp: new Date()
114
+ }])
115
+ } else {
116
+ toast.error(response.data.message)
117
+ }
118
+ } catch (error) {
119
+ console.error('Confirm action error:', error)
120
+ toast.error('Ошибка применения настройки')
121
+ } finally {
122
+ setPendingAction(null)
123
+ }
124
+ }
125
+
126
+ const rejectAction = () => {
127
+ setPendingAction(null)
128
+ toast.info('Изменение отменено')
129
+ }
130
+
131
+ // =========================================================================
132
+ // Smart Correction
133
+ // =========================================================================
134
+
135
  const handleSmartCorrection = async (correction: string) => {
136
  setIsLoading(true)
137
  try {
 
139
  const data = response.data
140
 
141
  if (data.success && data.changes.length > 0) {
142
+ // Invalidate cache
143
+ queryClient.invalidateQueries({ queryKey: ['tenant'] })
144
+ queryClient.invalidateQueries({ queryKey: ['ai-settings'] })
145
+
146
  setMessages(prev => [...prev, {
147
  id: crypto.randomUUID(),
148
  role: 'system',
 
174
  }
175
  }
176
 
177
+ // =========================================================================
178
+ // Send Message
179
+ // =========================================================================
180
+
181
  const handleSend = async () => {
182
  if (!input.trim() || isLoading) return
183
 
 
216
  content: response.data.response,
217
  timestamp: new Date()
218
  }])
219
+
220
+ // Check for pending action that needs confirmation
221
+ if (response.data.pending_action) {
222
+ setPendingAction(response.data.pending_action)
223
+ }
224
  } catch (error: any) {
225
  toast.error('Ошибка генерации')
226
  setMessages(prev => [...prev, {
 
244
  const clearChat = () => {
245
  setMessages([])
246
  setCorrections([])
247
+ setPendingAction(null)
248
+ localStorage.removeItem('demoChatPage_messages')
249
+ localStorage.removeItem('demoChatPage_corrections')
250
  toast.info('Чат очищен')
251
  }
252
 
 
260
 
261
  return (
262
  <div className="flex flex-col h-full bg-[#0a0a0f]">
263
+ {/* Header */}
264
  <header className="flex-shrink-0 flex items-center justify-between px-3 py-2 border-b border-white/5 bg-[#0a0a0f] safe-area-top">
265
  <div className="flex items-center gap-2">
266
  <Link href="/settings/brain" className="p-2 text-white/40 hover:text-white rounded-lg">
 
275
  </div>
276
  </div>
277
 
278
+ <div className="flex items-center gap-2">
279
+ {corrections.length > 0 && (
280
+ <span className="px-2 py-1 bg-violet-500/20 text-violet-400 text-xs rounded-full">
281
+ {corrections.length} правок
282
+ </span>
283
+ )}
284
+ <button onClick={clearChat} className="p-2 text-white/40 hover:text-white rounded-lg">
285
+ <Trash2 className="w-4 h-4" />
286
+ </button>
287
+ </div>
288
  </header>
289
 
290
+ {/* Messages */}
291
  <div className="flex-1 overflow-y-auto">
292
  <div className="max-w-2xl mx-auto px-3 py-4 space-y-3">
293
  {messages.length === 0 ? (
 
395
  </div>
396
  </div>
397
 
398
+ {/* Pending Action Confirmation */}
399
+ {pendingAction && (
400
+ <div className="mx-3 mb-2 p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl">
401
+ <div className="flex items-start gap-3">
402
+ <div className="p-1.5 bg-amber-500/20 rounded-lg">
403
+ <Wand2 className="w-4 h-4 text-amber-400" />
404
+ </div>
405
+ <div className="flex-1 min-w-0">
406
+ <p className="text-sm font-medium text-amber-200">AI предлагает изменить настройку:</p>
407
+ <p className="text-xs text-amber-300/80 mt-1">
408
+ 📍 {pendingAction.display_path}
409
+ </p>
410
+ <p className="text-xs text-white/90 mt-1 bg-black/20 px-2 py-1 rounded font-mono truncate">
411
+ → {String(pendingAction.value).substring(0, 100)}{String(pendingAction.value).length > 100 ? '...' : ''}
412
+ </p>
413
+ <div className="flex gap-2 mt-3">
414
+ <button
415
+ onClick={confirmAction}
416
+ className="flex-1 px-3 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-medium rounded-lg transition-colors"
417
+ >
418
+ ✅ Применить
419
+ </button>
420
+ <button
421
+ onClick={rejectAction}
422
+ className="flex-1 px-3 py-1.5 bg-white/10 hover:bg-white/20 text-slate-300 text-xs font-medium rounded-lg transition-colors"
423
+ >
424
+ ❌ Отмена
425
+ </button>
426
+ </div>
427
+ </div>
428
+ </div>
429
+ </div>
430
+ )}
431
+
432
+ {/* Input */}
433
  <div className="flex-shrink-0 border-t border-white/5 bg-[#0a0a0f] px-3 py-2 pb-safe">
434
  <div className="max-w-2xl mx-auto">
435
  <div className={cn(