Spaces:
Running
Running
axeronis commited on
Commit ·
795384e
1
Parent(s): f8877e5
feat: systematic settings confirmation with UI buttons (not prompt-based)
Browse files- backend/app/api/demo.py +73 -12
- frontend/components/DemoChat.tsx +84 -0
backend/app/api/demo.py
CHANGED
|
@@ -30,6 +30,8 @@ class DemoChatRequest(BaseModel):
|
|
| 30 |
|
| 31 |
class DemoChatResponse(BaseModel):
|
| 32 |
response: str
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
@router.post("/chat", response_model=DemoChatResponse)
|
|
@@ -44,7 +46,8 @@ async def demo_chat(
|
|
| 44 |
Does NOT save to database - purely for testing AI behavior.
|
| 45 |
"""
|
| 46 |
try:
|
| 47 |
-
from app.services.ai_core.settings_assistant import parse_ai_action, execute_setting_change, remove_action_from_response
|
|
|
|
| 48 |
from google import genai
|
| 49 |
import re
|
| 50 |
|
|
@@ -95,23 +98,25 @@ async def demo_chat(
|
|
| 95 |
|
| 96 |
|
| 97 |
# ========================================================================
|
| 98 |
-
# SMART SETTINGS ASSISTANT: Parse
|
|
|
|
| 99 |
# ========================================================================
|
|
|
|
| 100 |
if "__AI_ACTION__" in ai_response:
|
| 101 |
action = parse_ai_action(ai_response)
|
| 102 |
if action:
|
| 103 |
-
logger.info(f"🔧 Demo chat detected AI action: {action}")
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
logger.warning(f"⚠️ Failed to execute action: {result.get('message')}")
|
| 112 |
|
| 113 |
# Remove the action block from visible response
|
| 114 |
ai_response = remove_action_from_response(ai_response)
|
|
|
|
| 115 |
|
| 116 |
# Don't remove [SEND_VOICE] - let frontend handle it for demo
|
| 117 |
# Just log what features were triggered
|
|
@@ -177,7 +182,8 @@ async def demo_chat(
|
|
| 177 |
|
| 178 |
logger.info(f"🎮 Demo chat FULL response generated for tenant {tenant.id}")
|
| 179 |
|
| 180 |
-
return DemoChatResponse(response=ai_response.strip())
|
|
|
|
| 181 |
|
| 182 |
|
| 183 |
except Exception as e:
|
|
@@ -185,8 +191,63 @@ async def demo_chat(
|
|
| 185 |
raise HTTPException(status_code=500, detail=str(e))
|
| 186 |
|
| 187 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
class SmartCorrectionRequest(BaseModel):
|
|
|
|
| 190 |
correction: str
|
| 191 |
last_ai_response: Optional[str] = None # What AI said that was wrong
|
| 192 |
|
|
|
|
| 30 |
|
| 31 |
class DemoChatResponse(BaseModel):
|
| 32 |
response: str
|
| 33 |
+
pending_action: Optional[dict] = None # Action waiting for user confirmation
|
| 34 |
+
|
| 35 |
|
| 36 |
|
| 37 |
@router.post("/chat", response_model=DemoChatResponse)
|
|
|
|
| 46 |
Does NOT save to database - purely for testing AI behavior.
|
| 47 |
"""
|
| 48 |
try:
|
| 49 |
+
from app.services.ai_core.settings_assistant import parse_ai_action, execute_setting_change, remove_action_from_response, get_setting_display_name
|
| 50 |
+
|
| 51 |
from google import genai
|
| 52 |
import re
|
| 53 |
|
|
|
|
| 98 |
|
| 99 |
|
| 100 |
# ========================================================================
|
| 101 |
+
# SMART SETTINGS ASSISTANT: Parse __AI_ACTION__ but DON'T execute yet
|
| 102 |
+
# Return as pending_action for frontend confirmation
|
| 103 |
# ========================================================================
|
| 104 |
+
pending_action = None
|
| 105 |
if "__AI_ACTION__" in ai_response:
|
| 106 |
action = parse_ai_action(ai_response)
|
| 107 |
if action:
|
| 108 |
+
logger.info(f"🔧 Demo chat detected AI action (pending confirmation): {action}")
|
| 109 |
+
# DON'T execute - return for user confirmation
|
| 110 |
+
pending_action = {
|
| 111 |
+
"type": action.get("type"),
|
| 112 |
+
"path": action.get("path"),
|
| 113 |
+
"value": action.get("value"),
|
| 114 |
+
"display_path": get_setting_display_name(action.get("path", ""))
|
| 115 |
+
}
|
|
|
|
| 116 |
|
| 117 |
# Remove the action block from visible response
|
| 118 |
ai_response = remove_action_from_response(ai_response)
|
| 119 |
+
|
| 120 |
|
| 121 |
# Don't remove [SEND_VOICE] - let frontend handle it for demo
|
| 122 |
# Just log what features were triggered
|
|
|
|
| 182 |
|
| 183 |
logger.info(f"🎮 Demo chat FULL response generated for tenant {tenant.id}")
|
| 184 |
|
| 185 |
+
return DemoChatResponse(response=ai_response.strip(), pending_action=pending_action)
|
| 186 |
+
|
| 187 |
|
| 188 |
|
| 189 |
except Exception as e:
|
|
|
|
| 191 |
raise HTTPException(status_code=500, detail=str(e))
|
| 192 |
|
| 193 |
|
| 194 |
+
# ============================================================================
|
| 195 |
+
# CONFIRM ACTION ENDPOINT - Execute pending settings change
|
| 196 |
+
# ============================================================================
|
| 197 |
+
|
| 198 |
+
class ConfirmActionRequest(BaseModel):
|
| 199 |
+
action: dict # The pending_action from chat response
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class ConfirmActionResponse(BaseModel):
|
| 203 |
+
success: bool
|
| 204 |
+
message: str
|
| 205 |
+
changed_path: Optional[str] = None
|
| 206 |
+
old_value: Optional[str] = None
|
| 207 |
+
new_value: Optional[str] = None
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
@router.post("/confirm-action", response_model=ConfirmActionResponse)
|
| 211 |
+
async def confirm_action(
|
| 212 |
+
request: ConfirmActionRequest,
|
| 213 |
+
current_user: User = Depends(get_current_user),
|
| 214 |
+
session = Depends(get_async_session)
|
| 215 |
+
):
|
| 216 |
+
"""
|
| 217 |
+
Execute a pending settings change after user confirmation.
|
| 218 |
+
Called when user clicks "Apply" button in the confirmation UI.
|
| 219 |
+
"""
|
| 220 |
+
try:
|
| 221 |
+
from app.services.ai_core.settings_assistant import execute_setting_change
|
| 222 |
+
|
| 223 |
+
tenant = await session.get(Tenant, current_user.tenant_id)
|
| 224 |
+
if not tenant:
|
| 225 |
+
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 226 |
+
|
| 227 |
+
result = await execute_setting_change(session, tenant, request.action)
|
| 228 |
+
|
| 229 |
+
if result.get("success"):
|
| 230 |
+
logger.info(f"✅ Action confirmed and executed: {request.action.get('path')} = {request.action.get('value')}")
|
| 231 |
+
return ConfirmActionResponse(
|
| 232 |
+
success=True,
|
| 233 |
+
message="Настройка успешно изменена",
|
| 234 |
+
changed_path=result.get("changed_path"),
|
| 235 |
+
old_value=str(result.get("old_value", "")),
|
| 236 |
+
new_value=str(result.get("new_value", ""))
|
| 237 |
+
)
|
| 238 |
+
else:
|
| 239 |
+
return ConfirmActionResponse(
|
| 240 |
+
success=False,
|
| 241 |
+
message=result.get("message", "Ошибка при изменении настройки")
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
except Exception as e:
|
| 245 |
+
logger.error(f"❌ Confirm action error: {e}")
|
| 246 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 247 |
+
|
| 248 |
|
| 249 |
class SmartCorrectionRequest(BaseModel):
|
| 250 |
+
|
| 251 |
correction: str
|
| 252 |
last_ai_response: Optional[str] = None # What AI said that was wrong
|
| 253 |
|
frontend/components/DemoChat.tsx
CHANGED
|
@@ -119,9 +119,16 @@ export function DemoChat({ isOpen, onClose }: DemoChatProps) {
|
|
| 119 |
const [input, setInput] = useState('')
|
| 120 |
const [isLoading, setIsLoading] = useState(false)
|
| 121 |
const [corrections, setCorrections] = useState<string[]>([])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
const messagesEndRef = useRef<HTMLDivElement>(null)
|
| 123 |
const inputRef = useRef<HTMLInputElement>(null)
|
| 124 |
|
|
|
|
| 125 |
// Load from localStorage on mount
|
| 126 |
useEffect(() => {
|
| 127 |
try {
|
|
@@ -217,6 +224,12 @@ export function DemoChat({ isOpen, onClose }: DemoChatProps) {
|
|
| 217 |
timestamp: new Date()
|
| 218 |
}
|
| 219 |
setMessages(prev => [...prev, aiMessage])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
} catch (error) {
|
| 221 |
console.error('Demo chat error:', error)
|
| 222 |
toast.error('Ошибка генерации ответа')
|
|
@@ -243,11 +256,47 @@ export function DemoChat({ isOpen, onClose }: DemoChatProps) {
|
|
| 243 |
const clearChat = () => {
|
| 244 |
setMessages([])
|
| 245 |
setCorrections([])
|
|
|
|
| 246 |
localStorage.removeItem('demoChat_messages')
|
| 247 |
localStorage.removeItem('demoChat_corrections')
|
| 248 |
toast.info('Чат очищен')
|
| 249 |
}
|
| 250 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
return (
|
| 252 |
<AnimatePresence>
|
| 253 |
{isOpen && (
|
|
@@ -396,7 +445,42 @@ export function DemoChat({ isOpen, onClose }: DemoChatProps) {
|
|
| 396 |
<div ref={messagesEndRef} />
|
| 397 |
</div>
|
| 398 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
{/* Input */}
|
|
|
|
| 400 |
<div className="p-4 border-t border-white/10">
|
| 401 |
<div className="flex items-center gap-2">
|
| 402 |
<input
|
|
|
|
| 119 |
const [input, setInput] = useState('')
|
| 120 |
const [isLoading, setIsLoading] = useState(false)
|
| 121 |
const [corrections, setCorrections] = useState<string[]>([])
|
| 122 |
+
const [pendingAction, setPendingAction] = useState<{
|
| 123 |
+
type: string
|
| 124 |
+
path: string
|
| 125 |
+
value: string
|
| 126 |
+
display_path: string
|
| 127 |
+
} | null>(null)
|
| 128 |
const messagesEndRef = useRef<HTMLDivElement>(null)
|
| 129 |
const inputRef = useRef<HTMLInputElement>(null)
|
| 130 |
|
| 131 |
+
|
| 132 |
// Load from localStorage on mount
|
| 133 |
useEffect(() => {
|
| 134 |
try {
|
|
|
|
| 224 |
timestamp: new Date()
|
| 225 |
}
|
| 226 |
setMessages(prev => [...prev, aiMessage])
|
| 227 |
+
|
| 228 |
+
// Check for pending action that needs user confirmation
|
| 229 |
+
if (response.data.pending_action) {
|
| 230 |
+
setPendingAction(response.data.pending_action)
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
} catch (error) {
|
| 234 |
console.error('Demo chat error:', error)
|
| 235 |
toast.error('Ошибка генерации ответа')
|
|
|
|
| 256 |
const clearChat = () => {
|
| 257 |
setMessages([])
|
| 258 |
setCorrections([])
|
| 259 |
+
setPendingAction(null)
|
| 260 |
localStorage.removeItem('demoChat_messages')
|
| 261 |
localStorage.removeItem('demoChat_corrections')
|
| 262 |
toast.info('Чат очищен')
|
| 263 |
}
|
| 264 |
|
| 265 |
+
// Confirm pending settings change
|
| 266 |
+
const confirmAction = async () => {
|
| 267 |
+
if (!pendingAction) return
|
| 268 |
+
|
| 269 |
+
try {
|
| 270 |
+
const response = await api.post('/api/v1/demo/confirm-action', {
|
| 271 |
+
action: pendingAction
|
| 272 |
+
})
|
| 273 |
+
|
| 274 |
+
if (response.data.success) {
|
| 275 |
+
toast.success(`✅ ${response.data.message}`)
|
| 276 |
+
// Add confirmation message to chat
|
| 277 |
+
setMessages(prev => [...prev, {
|
| 278 |
+
id: crypto.randomUUID(),
|
| 279 |
+
role: 'ai',
|
| 280 |
+
content: `✅ Настройка изменена!\n📍 ${pendingAction.display_path}\n→ "${pendingAction.value}"`,
|
| 281 |
+
timestamp: new Date()
|
| 282 |
+
}])
|
| 283 |
+
} else {
|
| 284 |
+
toast.error(response.data.message)
|
| 285 |
+
}
|
| 286 |
+
} catch (error) {
|
| 287 |
+
console.error('Confirm action error:', error)
|
| 288 |
+
toast.error('Ошибка применения настройки')
|
| 289 |
+
} finally {
|
| 290 |
+
setPendingAction(null)
|
| 291 |
+
}
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
// Reject pending action
|
| 295 |
+
const rejectAction = () => {
|
| 296 |
+
setPendingAction(null)
|
| 297 |
+
toast.info('Изменение отменено')
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
return (
|
| 301 |
<AnimatePresence>
|
| 302 |
{isOpen && (
|
|
|
|
| 445 |
<div ref={messagesEndRef} />
|
| 446 |
</div>
|
| 447 |
|
| 448 |
+
{/* Pending Action Confirmation UI */}
|
| 449 |
+
{pendingAction && (
|
| 450 |
+
<div className="mx-4 mb-2 p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl">
|
| 451 |
+
<div className="flex items-start gap-3">
|
| 452 |
+
<div className="p-1.5 bg-amber-500/20 rounded-lg">
|
| 453 |
+
<Wand2 className="w-4 h-4 text-amber-400" />
|
| 454 |
+
</div>
|
| 455 |
+
<div className="flex-1 min-w-0">
|
| 456 |
+
<p className="text-sm font-medium text-amber-200">AI предлагает изменить настройку:</p>
|
| 457 |
+
<p className="text-xs text-amber-300/80 mt-1">
|
| 458 |
+
📍 {pendingAction.display_path}
|
| 459 |
+
</p>
|
| 460 |
+
<p className="text-xs text-white/90 mt-1 bg-black/20 px-2 py-1 rounded font-mono truncate">
|
| 461 |
+
→ {String(pendingAction.value).substring(0, 100)}{String(pendingAction.value).length > 100 ? '...' : ''}
|
| 462 |
+
</p>
|
| 463 |
+
<div className="flex gap-2 mt-3">
|
| 464 |
+
<button
|
| 465 |
+
onClick={confirmAction}
|
| 466 |
+
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 flex items-center justify-center gap-1"
|
| 467 |
+
>
|
| 468 |
+
✅ Применить
|
| 469 |
+
</button>
|
| 470 |
+
<button
|
| 471 |
+
onClick={rejectAction}
|
| 472 |
+
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 flex items-center justify-center gap-1"
|
| 473 |
+
>
|
| 474 |
+
❌ Отмена
|
| 475 |
+
</button>
|
| 476 |
+
</div>
|
| 477 |
+
</div>
|
| 478 |
+
</div>
|
| 479 |
+
</div>
|
| 480 |
+
)}
|
| 481 |
+
|
| 482 |
{/* Input */}
|
| 483 |
+
|
| 484 |
<div className="p-4 border-t border-white/10">
|
| 485 |
<div className="flex items-center gap-2">
|
| 486 |
<input
|