feat: полноценный мультипользовательский режим (users, JWT, изолированные задачи)
This commit is contained in:
+44
-43
@@ -18,21 +18,39 @@ from .schemas import TOOLS_SCHEMA
|
||||
OLLAMA_URL = "http://192.168.11.3:11434/api/chat"
|
||||
MODEL_NAME = "qwen2.5:14b"
|
||||
|
||||
def process_chat_message(user_message: str, chat_history: List[Dict[str, Any]] = None) -> Tuple[str, List[Dict[str, Any]]]:
|
||||
def process_chat_message(user_id: int, user_message: str, chat_history: List[Dict[str, Any]] = None) -> Tuple[str, List[Dict[str, Any]]]:
|
||||
if chat_history is None:
|
||||
chat_history = []
|
||||
|
||||
current_now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||
user_lower = user_message.lower().strip()
|
||||
|
||||
if any(phrase in user_lower for phrase in ["системный промпт", "покажи промпт", "промпт системы", "промпт из базы"]):
|
||||
prompt_text = db_get_active_system_prompt()
|
||||
formatted_text = f"⚙️ Актуальный системный промпт ИИ (из базы SQLite):\n\n{prompt_text}"
|
||||
# Быстрый прямой ответ для списка задач текущего пользователя
|
||||
if any(phrase in user_lower for phrase in ["все задачи", "покажи задачи", "список задач", "реестр задач"]):
|
||||
tasks = db_get_tasks(user_id)
|
||||
if not tasks:
|
||||
formatted_text = "Ваш список задач пуст."
|
||||
else:
|
||||
def get_task_num(t):
|
||||
tid = str(t.get("task_id", ""))
|
||||
try:
|
||||
return int(tid.upper().replace("TASK-", "").strip())
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
tasks_sorted = sorted(tasks, key=get_task_num, reverse=True)
|
||||
lines = [f"📋 Ваш реестр задач ({len(tasks_sorted)}):\n"]
|
||||
for t in tasks_sorted:
|
||||
tid = t.get('task_id', '')
|
||||
title = t.get('title', 'Без названия')
|
||||
lines.append(f"• {tid}: {title}")
|
||||
formatted_text = "\n".join(lines)
|
||||
|
||||
return formatted_text, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": formatted_text}]
|
||||
|
||||
if any(phrase in user_lower for phrase in ["базу знаний", "база знаний", "покажи правила", "инструкции ии"]):
|
||||
rules = db_get_rules()
|
||||
formatted_text = "🧠 База знаний ИИ (ai_knowledge_base):\n\n" + "\n\n".join([f"• {r.get('id')}. {r.get('rule_text')}" for r in rules]) if rules else "База знаний пуста."
|
||||
if any(phrase in user_lower for phrase in ["системный промпт", "покажи промпт", "промпт системы"]):
|
||||
prompt_text = db_get_active_system_prompt()
|
||||
formatted_text = f"⚙️ Актуальный системный промпт ИИ:\n\n{prompt_text}"
|
||||
return formatted_text, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": formatted_text}]
|
||||
|
||||
dynamic_prompt_text = db_get_active_system_prompt()
|
||||
@@ -64,64 +82,47 @@ def process_chat_message(user_message: str, chat_history: List[Dict[str, Any]] =
|
||||
tool_calls = msg.get("tool_calls", [])
|
||||
content_str = msg.get("content", "").strip().replace("**", "")
|
||||
|
||||
if not tool_calls and "name" in content_str and "db_" in content_str:
|
||||
try:
|
||||
start_idx = content_str.find("{")
|
||||
end_idx = content_str.rfind("}") + 1
|
||||
if start_idx != -1 and end_idx != -1:
|
||||
parsed = json.loads(content_str[start_idx:end_idx])
|
||||
if "name" in parsed:
|
||||
tool_calls = [{"function": parsed}]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if tool_calls:
|
||||
for tool in tool_calls:
|
||||
fn_name = tool["function"]["name"]
|
||||
fn_args = tool["function"].get("arguments", {})
|
||||
|
||||
if fn_name == "db_get_tasks":
|
||||
tasks = db_get_tasks()
|
||||
tasks = db_get_tasks(user_id)
|
||||
if not tasks:
|
||||
formatted_text = "Список задач пуст."
|
||||
formatted_text = "Ваш список задач пуст."
|
||||
else:
|
||||
tasks_sorted = sorted(tasks, key=lambda x: x.get('task_id', ''), reverse=True)
|
||||
formatted_text = f"📋 Реестр задач SCUD Orion AI (Всего: {len(tasks_sorted)}):\n\n"
|
||||
def get_task_num(t):
|
||||
tid = str(t.get("task_id", ""))
|
||||
try:
|
||||
return int(tid.upper().replace("TASK-", "").strip())
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
tasks_sorted = sorted(tasks, key=get_task_num, reverse=True)
|
||||
lines = [f"📋 Ваш реестр задач ({len(tasks_sorted)}):\n"]
|
||||
for t in tasks_sorted:
|
||||
due = f" (до {t['due_date']})" if t.get('due_date') else ""
|
||||
formatted_text += f"• {t.get('task_id')} — {t.get('title')}\n"
|
||||
formatted_text += f" - Приоритет: {t.get('priority') or 'MEDIUM'} | Статус: {t.get('status') or 'BACKLOG'} | Модуль: {t.get('module') or 'general'}{due}\n\n"
|
||||
return formatted_text, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": formatted_text}]
|
||||
tid = t.get('task_id', '')
|
||||
title = t.get('title', 'Без названия')
|
||||
lines.append(f"• {tid}: {title}")
|
||||
formatted_text = "\n".join(lines)
|
||||
|
||||
elif fn_name == "db_get_rules":
|
||||
rules = db_get_rules()
|
||||
formatted_text = "🧠 База знаний ИИ (ai_knowledge_base):\n\n" + "\n\n".join([f"• {r.get('id')}. {r.get('rule_text')}" for r in rules]) if rules else "База знаний пуста."
|
||||
return formatted_text, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": formatted_text}]
|
||||
|
||||
elif fn_name == "db_get_system_prompt":
|
||||
prompt_text = db_get_active_system_prompt()
|
||||
formatted_text = f"⚙️ Актуальный системный промпт ИИ (из базы SQLite):\n\n{prompt_text}"
|
||||
return formatted_text, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": formatted_text}]
|
||||
|
||||
elif fn_name == "db_add_system_prompt":
|
||||
res = db_add_system_prompt(name=fn_args.get("name", "main_agent"), prompt_text=fn_args.get("prompt_text", ""))
|
||||
formatted_text = res.get("message", "Промпт обновлен.")
|
||||
return formatted_text, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": formatted_text}]
|
||||
|
||||
elif fn_name == "db_add_task":
|
||||
res = db_add_task(module=fn_args.get("module", "general"), title=fn_args.get("title"), priority=fn_args.get("priority", "MEDIUM"), due_date=fn_args.get("due_date"))
|
||||
res = db_add_task(user_id=user_id, module=fn_args.get("module", "general"), title=fn_args.get("title"), priority=fn_args.get("priority", "MEDIUM"), due_date=fn_args.get("due_date"))
|
||||
formatted_text = f"[✓] Задача {res.get('task_id', 'TASK')} успешно создана!" if "status" in res else f"❌ Ошибка: {res.get('error')}"
|
||||
return formatted_text, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": formatted_text}]
|
||||
|
||||
elif fn_name == "db_update_task_status":
|
||||
res = db_update_task_status(task_id=fn_args.get("task_id"), status=fn_args.get("status"), due_date=fn_args.get("due_date"))
|
||||
res = db_update_task_status(user_id=user_id, task_id=fn_args.get("task_id"), status=fn_args.get("status"), due_date=fn_args.get("due_date"))
|
||||
formatted_text = f"[✓] Статус задачи {fn_args.get('task_id')} обновлен!" if "status" in res else f"❌ Ошибка: {res.get('error')}"
|
||||
return formatted_text, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": formatted_text}]
|
||||
|
||||
elif fn_name == "db_delete_task":
|
||||
task_id_to_del = fn_args.get("task_id", "").upper()
|
||||
res = db_delete_task(task_id=task_id_to_del)
|
||||
formatted_text = f"[✓] Задача {task_id_to_del} успешно удалена из базы!" if "status" in res else f"❌ Ошибка: {res.get('error')}"
|
||||
res = db_delete_task(user_id=user_id, task_id=task_id_to_del)
|
||||
formatted_text = f"[✓] Задача {task_id_to_del} успешно удалена из вашей базы!" if "status" in res else f"❌ Ошибка: {res.get('error')}"
|
||||
return formatted_text, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": formatted_text}]
|
||||
|
||||
return content_str, chat_history + [{"role": "user", "content": user_message}, {"role": "assistant", "content": content_str}]
|
||||
|
||||
+86
-105
@@ -1,129 +1,110 @@
|
||||
import sqlite3
|
||||
from typing import List, Dict, Any
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
DB_NAME = "/home/puh/scud_orion_ai_v2/data/scud_orion_ai.db"
|
||||
DB_PATH = "/home/puh/scud_context_api/scud_orion_ai.db"
|
||||
|
||||
def db_get_active_system_prompt() -> str:
|
||||
try:
|
||||
conn = sqlite3.connect(DB_NAME)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT prompt_text FROM system_prompts WHERE name = 'main_agent' AND is_active = 1 LIMIT 1")
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
if row and row[0]:
|
||||
return row[0].replace("**", "")
|
||||
except Exception as e:
|
||||
print(f"Ошибка чтения системного промпта из БД: {e}")
|
||||
def get_db_connection():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
return "Ты — интеллектуальный ИИ-ассистент и архитектурный координатор проекта SCUD Orion AI."
|
||||
# === ЗАДАЧИ С ФИЛЬТРАЦИЕЙ ПО USER_ID ===
|
||||
|
||||
def db_add_system_prompt(name: str = "main_agent", prompt_text: str = "") -> dict:
|
||||
clean_text = prompt_text.replace("**", "")
|
||||
conn = sqlite3.connect(DB_NAME)
|
||||
def db_get_tasks(user_id: int) -> List[Dict[str, Any]]:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
INSERT INTO system_prompts (name, prompt_text, is_active)
|
||||
VALUES (?, ?, 1)
|
||||
ON CONFLICT(name) DO UPDATE SET prompt_text=excluded.prompt_text, updated_at=CURRENT_TIMESTAMP
|
||||
""", (name, clean_text))
|
||||
SELECT id, task_id, module, title, priority, status, due_date, created_at
|
||||
FROM tasks
|
||||
WHERE user_id = ?
|
||||
ORDER BY id DESC
|
||||
""", (user_id,))
|
||||
rows = cursor.fetchall()
|
||||
conn.close()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def db_add_task(user_id: int, module: str, title: str, priority: str = "MEDIUM", due_date: Optional[str] = None) -> Dict[str, Any]:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("SELECT MAX(id) FROM tasks")
|
||||
max_id = cursor.fetchone()[0] or 0
|
||||
new_task_id = f"TASK-{(max_id + 1):02d}"
|
||||
|
||||
cursor.execute("""
|
||||
INSERT INTO tasks (task_id, module, title, priority, status, due_date, user_id)
|
||||
VALUES (?, ?, ?, ?, 'BACKLOG', ?, ?)
|
||||
""", (new_task_id, module, title, priority.upper(), due_date, user_id))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {"status": "success", "message": f"Системный промпт '{name}' успешно обновлен в базе!"}
|
||||
return {"status": "success", "task_id": new_task_id, "message": f"Задача {new_task_id} создана"}
|
||||
|
||||
def db_get_tasks(status: str = None) -> list:
|
||||
conn = sqlite3.connect(DB_NAME)
|
||||
conn.row_factory = sqlite3.Row
|
||||
def db_update_task_status(user_id: int, task_id: str, status: str, due_date: Optional[str] = None) -> Dict[str, Any]:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
if status:
|
||||
cursor.execute("SELECT * FROM tasks WHERE status = ? ORDER BY task_id ASC", (status.upper(),))
|
||||
else:
|
||||
cursor.execute("SELECT * FROM tasks ORDER BY task_id ASC")
|
||||
rows = [dict(r) for r in cursor.fetchall()]
|
||||
conn.close()
|
||||
return rows
|
||||
|
||||
def db_update_task_status(task_id: str, status: str = None, due_date: str = None) -> dict:
|
||||
conn = sqlite3.connect(DB_NAME)
|
||||
cursor = conn.cursor()
|
||||
updates = []
|
||||
params = []
|
||||
|
||||
if status:
|
||||
status_upper = status.upper()
|
||||
updates.append("status = ?")
|
||||
params.append(status_upper)
|
||||
if status_upper == "COMPLETED":
|
||||
updates.append("completed_at = CURRENT_TIMESTAMP")
|
||||
else:
|
||||
updates.append("completed_at = NULL")
|
||||
|
||||
|
||||
task_id_upper = task_id.upper().strip()
|
||||
|
||||
if due_date:
|
||||
updates.append("due_date = ?")
|
||||
params.append(due_date)
|
||||
|
||||
if not updates:
|
||||
conn.close()
|
||||
return {"error": "Не указаны параметры для обновления"}
|
||||
|
||||
params.append(task_id.upper())
|
||||
query = f"UPDATE tasks SET {', '.join(updates)} WHERE task_id = ?"
|
||||
cursor.execute(query, tuple(params))
|
||||
cursor.execute("""
|
||||
UPDATE tasks
|
||||
SET status = ?, due_date = ?
|
||||
WHERE UPPER(task_id) = ? AND user_id = ?
|
||||
""", (status.upper(), due_date, task_id_upper, user_id))
|
||||
else:
|
||||
cursor.execute("""
|
||||
UPDATE tasks
|
||||
SET status = ?
|
||||
WHERE UPPER(task_id) = ? AND user_id = ?
|
||||
""", (status.upper(), task_id_upper, user_id))
|
||||
|
||||
if cursor.rowcount == 0:
|
||||
conn.close()
|
||||
return {"error": f"Задача {task_id} не найдена"}
|
||||
return {"error": f"Задача {task_id_upper} не найдена или принадлежит другому пользователю"}
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {"status": "success", "message": f"Задача {task_id} обновлена"}
|
||||
return {"status": "success", "message": f"Статус {task_id_upper} обновлен"}
|
||||
|
||||
def db_delete_task(task_id: str) -> dict:
|
||||
conn = sqlite3.connect(DB_NAME)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM tasks WHERE task_id = ?", (task_id.upper(),))
|
||||
deleted_count = cursor.rowcount
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
if deleted_count == 0:
|
||||
return {"error": f"Задача {task_id} не найдена"}
|
||||
return {"status": "success", "message": f"Задача {task_id} удалена"}
|
||||
|
||||
def db_add_task(module: str = "general", title: str = "", priority: str = "MEDIUM", due_date: str = None, task_id: str = None) -> dict:
|
||||
conn = sqlite3.connect(DB_NAME)
|
||||
def db_delete_task(user_id: int, task_id: str) -> Dict[str, Any]:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
task_id_upper = task_id.upper().strip()
|
||||
|
||||
if not task_id:
|
||||
cursor.execute("SELECT task_id FROM tasks WHERE task_id LIKE 'TASK-%'")
|
||||
rows = cursor.fetchall()
|
||||
max_num = 0
|
||||
for r in rows:
|
||||
try:
|
||||
num = int(r[0].replace("TASK-", ""))
|
||||
if num > max_num:
|
||||
max_num = num
|
||||
except ValueError:
|
||||
pass
|
||||
task_id = f"TASK-{max_num + 1:02d}"
|
||||
|
||||
try:
|
||||
cursor.execute(
|
||||
"INSERT INTO tasks (task_id, module, title, status, priority, due_date) VALUES (?, ?, ?, 'BACKLOG', ?, ?)",
|
||||
(task_id.upper(), module, title, priority.upper(), due_date)
|
||||
)
|
||||
conn.commit()
|
||||
res = {"status": "success", "message": f"Задача {task_id} создана", "task_id": task_id}
|
||||
except sqlite3.IntegrityError:
|
||||
res = {"error": f"Задача с ID {task_id} уже существует"}
|
||||
finally:
|
||||
cursor.execute("DELETE FROM tasks WHERE UPPER(task_id) = ? AND user_id = ?", (task_id_upper, user_id))
|
||||
|
||||
if cursor.rowcount == 0:
|
||||
conn.close()
|
||||
return res
|
||||
return {"error": f"Задача {task_id_upper} не найдена или принадлежит другому пользователю"}
|
||||
|
||||
def db_get_rules() -> list:
|
||||
conn = sqlite3.connect(DB_NAME)
|
||||
conn.row_factory = sqlite3.Row
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id, rule_text, added_by FROM ai_knowledge_base ORDER BY id")
|
||||
rows = [dict(r) for r in cursor.fetchall()]
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return rows
|
||||
return {"status": "success", "message": f"Задача {task_id_upper} удалена"}
|
||||
|
||||
# === ОБЩИЕ СИСТЕМНЫЕ РЕСУРСЫ ===
|
||||
|
||||
def db_get_active_system_prompt() -> str:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT prompt_text FROM system_prompts WHERE is_active = 1 ORDER BY id DESC LIMIT 1")
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
return row["prompt_text"] if row else "Ты — ИИ-ассистент SCUD Orion AI."
|
||||
|
||||
def db_add_system_prompt(name: str, prompt_text: str) -> Dict[str, Any]:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("UPDATE system_prompts SET is_active = 0")
|
||||
cursor.execute("INSERT INTO system_prompts (name, prompt_text, is_active) VALUES (?, ?, 1)", (name, prompt_text))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {"status": "success", "message": "Системный промпт обновлен"}
|
||||
|
||||
def db_get_rules() -> List[Dict[str, Any]]:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id, rule_text FROM ai_knowledge_base ORDER BY id ASC")
|
||||
rows = cursor.fetchall()
|
||||
conn.close()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
+29
-14
@@ -10,24 +10,30 @@
|
||||
</head>
|
||||
<body class="bg-slate-100 text-slate-800 h-[100dvh] w-full flex flex-col font-sans overflow-hidden">
|
||||
|
||||
<!-- Окно авторизации c гостевым входом -->
|
||||
<!-- Окно авторизации / Регистрации -->
|
||||
<div id="auth-modal" class="fixed inset-0 bg-slate-900/80 backdrop-blur-md z-50 flex items-center justify-center p-4">
|
||||
<div class="bg-white rounded-2xl p-6 sm:p-8 max-w-md w-full shadow-2xl border border-slate-200">
|
||||
<div class="flex items-center space-x-3 mb-6">
|
||||
<div class="bg-indigo-600 text-white p-3 rounded-xl">
|
||||
<i class="fa-solid fa-lock text-xl"></i>
|
||||
<i class="fa-solid fa-user-shield text-xl"></i>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-lg font-bold text-slate-900">SCUD Orion AI</h2>
|
||||
<p class="text-xs text-slate-500">Авторизация в системе</p>
|
||||
<p id="auth-title" class="text-xs text-slate-500">Авторизация в системе</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form id="auth-form" onsubmit="handleLogin(event)" class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-slate-700 uppercase tracking-wider mb-2">API Token</label>
|
||||
<input type="password" id="auth-token-input" placeholder="Введите API токен..."
|
||||
class="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-3 text-sm text-slate-900 focus:outline-none focus:border-indigo-600 focus:bg-white transition">
|
||||
<label class="block text-xs font-semibold text-slate-700 uppercase tracking-wider mb-1">Имя пользователя</label>
|
||||
<input type="text" id="auth-username-input" placeholder="Введите логин..." required
|
||||
class="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-900 focus:outline-none focus:border-indigo-600 focus:bg-white transition">
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-slate-700 uppercase tracking-wider mb-1">Пароль</label>
|
||||
<input type="password" id="auth-password-input" placeholder="Введите пароль..." required
|
||||
class="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-900 focus:outline-none focus:border-indigo-600 focus:bg-white transition">
|
||||
</div>
|
||||
|
||||
<div id="auth-error" class="hidden text-xs text-red-600 font-medium bg-red-50 p-3 rounded-xl border border-red-200">
|
||||
@@ -36,16 +42,22 @@
|
||||
|
||||
<button type="submit" id="auth-btn" class="w-full bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white font-semibold py-3 rounded-xl text-sm transition shadow-md flex items-center justify-center gap-2">
|
||||
<i class="fa-solid fa-right-to-bracket"></i>
|
||||
<span>Войти с токеном</span>
|
||||
<span id="auth-submit-text">Войти в систему</span>
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="relative my-5">
|
||||
<div class="mt-3 text-center">
|
||||
<button type="button" id="auth-toggle-btn" onclick="toggleAuthMode()" class="text-xs text-indigo-600 hover:underline font-medium">
|
||||
Создать новый аккаунт
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="relative my-4">
|
||||
<div class="absolute inset-0 flex items-center"><div class="w-full border-t border-slate-200"></div></div>
|
||||
<div class="relative flex justify-center text-xs uppercase"><span class="bg-white px-2 text-slate-400 font-medium">Или</span></div>
|
||||
</div>
|
||||
|
||||
<button onclick="enableGuestMode()" class="w-full bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold py-3 rounded-xl text-sm transition border border-slate-300 flex items-center justify-center gap-2">
|
||||
<button onclick="enableGuestMode()" class="w-full bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold py-2.5 rounded-xl text-xs transition border border-slate-300 flex items-center justify-center gap-2">
|
||||
<i class="fa-solid fa-user-ninja"></i>
|
||||
<span>Войти как гость (Локальный ИИ)</span>
|
||||
</button>
|
||||
@@ -66,7 +78,11 @@
|
||||
|
||||
<div class="flex items-center space-x-2">
|
||||
<span id="guest-badge" class="hidden text-[10px] text-amber-700 font-semibold bg-amber-50 px-2 py-0.5 rounded-full border border-amber-200">
|
||||
Гостевой режим
|
||||
Гость
|
||||
</span>
|
||||
|
||||
<span id="username-badge" class="hidden text-xs text-indigo-700 font-bold bg-indigo-50 px-2.5 py-1 rounded-full border border-indigo-200">
|
||||
Admin
|
||||
</span>
|
||||
|
||||
<button id="tasks-drawer-btn" onclick="toggleDrawer()" class="bg-indigo-600 active:bg-indigo-700 text-white px-3 py-1.5 rounded-xl text-xs font-semibold flex items-center gap-1.5 shadow-sm">
|
||||
@@ -88,7 +104,7 @@
|
||||
<i class="fa-solid fa-robot mr-1"></i> ИИ-Ассистент
|
||||
</p>
|
||||
<p class="text-slate-800 text-xs sm:text-sm leading-relaxed">
|
||||
Привет! Задавайте вопросы нейросети прямо в чат.
|
||||
Привет! У каждого пользователя свое изолированное пространство задач. Вы можете задавать вопросы нейросети или ставить персональные задачи.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -115,7 +131,7 @@
|
||||
<aside id="task-drawer" class="fixed right-0 top-0 h-full w-full sm:w-[420px] bg-white border-l border-slate-200 shadow-2xl transform translate-x-full transition-transform duration-300 ease-in-out z-50 flex flex-col">
|
||||
<div class="p-3.5 border-b border-slate-200 flex justify-between items-center bg-slate-50 shrink-0">
|
||||
<h2 class="font-bold text-slate-800 flex items-center gap-2 text-sm">
|
||||
<i class="fa-solid fa-list-check text-indigo-600"></i> Реестр задач
|
||||
<i class="fa-solid fa-list-check text-indigo-600"></i> Мой реестр задач
|
||||
</h2>
|
||||
<div class="flex items-center gap-3">
|
||||
<button onclick="loadTasks()" class="text-xs text-slate-500 hover:text-indigo-600 transition p-1" title="Обновить">
|
||||
@@ -135,11 +151,10 @@
|
||||
</div>
|
||||
|
||||
<div id="tasks-container" class="flex-1 overflow-y-auto p-3.5 space-y-3 bg-slate-50/50 pb-8">
|
||||
<div class="text-center text-slate-400 py-8 text-xs">Загрузка задач...</div>
|
||||
<div class="text-center text-slate-400 py-8 text-xs">Загрузка ваших задач...</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Порядок подключения модулей JS -->
|
||||
<script src="/static/js/auth.js"></script>
|
||||
<script src="/static/js/tasks.js"></script>
|
||||
<script src="/static/js/chat.js"></script>
|
||||
|
||||
+4
-9
@@ -3,6 +3,7 @@ const SESSION_ID = "web_session_main";
|
||||
const STORAGE_KEY = 'scud_chat_input_history';
|
||||
|
||||
let API_TOKEN = localStorage.getItem(AUTH_TOKEN_KEY) || "";
|
||||
let CURRENT_USERNAME = localStorage.getItem('scud_username') || "";
|
||||
let IS_GUEST = localStorage.getItem('scud_is_guest') === 'true';
|
||||
let currentFilter = 'ALL';
|
||||
let allTasks = [];
|
||||
@@ -57,15 +58,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
} else if (API_TOKEN) {
|
||||
verifyToken(API_TOKEN).then(isValid => {
|
||||
if (isValid) {
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
loadTasks();
|
||||
} else {
|
||||
showAuthModal();
|
||||
}
|
||||
});
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
loadTasks();
|
||||
} else {
|
||||
showAuthModal();
|
||||
}
|
||||
|
||||
+67
-23
@@ -1,3 +1,5 @@
|
||||
let authMode = 'login'; // 'login' или 'register'
|
||||
|
||||
function showAuthModal() {
|
||||
document.getElementById('auth-modal').classList.remove('hidden');
|
||||
}
|
||||
@@ -6,37 +8,71 @@ function hideAuthModal() {
|
||||
document.getElementById('auth-modal').classList.add('hidden');
|
||||
}
|
||||
|
||||
async function verifyToken(token) {
|
||||
try {
|
||||
const res = await fetch('/api/v1/tasks', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
return res.status === 200;
|
||||
} catch (err) {
|
||||
return false;
|
||||
function setAuthMode(mode) {
|
||||
authMode = mode;
|
||||
const titleEl = document.getElementById('auth-title');
|
||||
const submitBtnText = document.getElementById('auth-submit-text');
|
||||
const toggleBtn = document.getElementById('auth-toggle-btn');
|
||||
const errorEl = document.getElementById('auth-error');
|
||||
|
||||
errorEl.classList.add('hidden');
|
||||
|
||||
if (mode === 'register') {
|
||||
titleEl.innerText = "Регистрация нового пользователя";
|
||||
submitBtnText.innerText = "Зарегистрироваться";
|
||||
toggleBtn.innerText = "Уже есть аккаунт? Войти";
|
||||
} else {
|
||||
titleEl.innerText = "Авторизация в системе";
|
||||
submitBtnText.innerText = "Войти в систему";
|
||||
toggleBtn.innerText = "Создать новый аккаунт";
|
||||
}
|
||||
}
|
||||
|
||||
function toggleAuthMode() {
|
||||
setAuthMode(authMode === 'login' ? 'register' : 'login');
|
||||
}
|
||||
|
||||
async function handleLogin(e) {
|
||||
e.preventDefault();
|
||||
const tokenInput = document.getElementById('auth-token-input');
|
||||
const usernameInput = document.getElementById('auth-username-input');
|
||||
const passwordInput = document.getElementById('auth-password-input');
|
||||
const errorEl = document.getElementById('auth-error');
|
||||
const token = tokenInput.value.trim();
|
||||
|
||||
if (!token) return;
|
||||
const username = usernameInput.value.trim();
|
||||
const password = passwordInput.value;
|
||||
|
||||
if (!username || !password) return;
|
||||
|
||||
errorEl.classList.add('hidden');
|
||||
const isValid = await verifyToken(token);
|
||||
const endpoint = authMode === 'register' ? '/api/v1/auth/register' : '/api/v1/auth/login';
|
||||
|
||||
if (isValid) {
|
||||
API_TOKEN = token;
|
||||
IS_GUEST = false;
|
||||
localStorage.setItem(AUTH_TOKEN_KEY, token);
|
||||
localStorage.removeItem('scud_is_guest');
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
loadTasks();
|
||||
} else {
|
||||
try {
|
||||
const res = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (res.status === 200) {
|
||||
API_TOKEN = data.token;
|
||||
CURRENT_USERNAME = data.username;
|
||||
IS_GUEST = false;
|
||||
|
||||
localStorage.setItem(AUTH_TOKEN_KEY, data.token);
|
||||
localStorage.setItem('scud_username', data.username);
|
||||
localStorage.removeItem('scud_is_guest');
|
||||
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
loadTasks();
|
||||
} else {
|
||||
errorEl.innerText = data.detail || "Ошибка авторизации";
|
||||
errorEl.classList.remove('hidden');
|
||||
}
|
||||
} catch (err) {
|
||||
errorEl.innerText = "Ошибка соединения с сервером";
|
||||
errorEl.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
@@ -44,6 +80,7 @@ async function handleLogin(e) {
|
||||
function enableGuestMode() {
|
||||
IS_GUEST = true;
|
||||
API_TOKEN = "";
|
||||
CURRENT_USERNAME = "Гость";
|
||||
localStorage.setItem('scud_is_guest', 'true');
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
@@ -51,22 +88,29 @@ function enableGuestMode() {
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem(AUTH_TOKEN_KEY);
|
||||
localStorage.removeItem('scud_username');
|
||||
localStorage.removeItem('scud_is_guest');
|
||||
API_TOKEN = "";
|
||||
CURRENT_USERNAME = "";
|
||||
IS_GUEST = false;
|
||||
document.getElementById('auth-token-input').value = "";
|
||||
showAuthModal();
|
||||
}
|
||||
|
||||
function updateUIState() {
|
||||
const tasksBtn = document.getElementById('tasks-drawer-btn');
|
||||
const guestBadge = document.getElementById('guest-badge');
|
||||
|
||||
const usernameBadge = document.getElementById('username-badge');
|
||||
|
||||
if (IS_GUEST) {
|
||||
if (tasksBtn) tasksBtn.classList.add('hidden');
|
||||
if (guestBadge) guestBadge.classList.remove('hidden');
|
||||
if (usernameBadge) usernameBadge.classList.add('hidden');
|
||||
} else {
|
||||
if (tasksBtn) tasksBtn.classList.remove('hidden');
|
||||
if (guestBadge) guestBadge.classList.add('hidden');
|
||||
if (usernameBadge) {
|
||||
usernameBadge.innerText = CURRENT_USERNAME || 'User';
|
||||
usernameBadge.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Executable
+350
@@ -0,0 +1,350 @@
|
||||
cd /home/puh/scud_context_api
|
||||
|
||||
# 1. Создаем необходимые директории для CSS и JS
|
||||
mkdir -p static/css static/js
|
||||
|
||||
# 2. Выносим CSS в static/css/styles.css
|
||||
cat << 'EOF' > static/css/styles.css
|
||||
/* Плавное (градиентное) исчезновение текста сверху при скролле */
|
||||
.fade-scroll-top {
|
||||
mask-image: linear-gradient(to bottom, transparent 0%, black 14px);
|
||||
-webkit-mask-image: linear-gradient(to bottom, transparent 0%, black 14px);
|
||||
}
|
||||
|
||||
/* Скрытие стандартного скроллбара */
|
||||
.no-scrollbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.no-scrollbar {
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
EOF
|
||||
|
||||
# 3. Выносим JavaScript в static/js/app.js
|
||||
cat << 'EOF' > static/js/app.js
|
||||
const API_TOKEN = "scud_secret_token_2026";
|
||||
const SESSION_ID = "web_session_main";
|
||||
const STORAGE_KEY = 'scud_chat_input_history';
|
||||
|
||||
let currentFilter = 'ALL';
|
||||
let allTasks = [];
|
||||
|
||||
// === ИСТОРИЯ КОМАНД (LOCALSTORAGE + СТРЕЛКИ ВВЕРХ/ВНИЗ) ===
|
||||
let inputHistory = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
|
||||
let historyIndex = -1;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const userInputEl = document.getElementById('user-input');
|
||||
|
||||
if (userInputEl) {
|
||||
// Динамическое расширение высоты поля до 4 строк (~96px)
|
||||
userInputEl.addEventListener('input', function() {
|
||||
this.style.height = 'auto';
|
||||
this.style.height = Math.min(this.scrollHeight, 96) + 'px';
|
||||
});
|
||||
|
||||
userInputEl.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
document.getElementById('chat-form').requestSubmit();
|
||||
}
|
||||
else if (e.key === 'ArrowUp') {
|
||||
if (inputHistory.length > 0 && historyIndex < inputHistory.length - 1) {
|
||||
e.preventDefault();
|
||||
if (historyIndex === -1) {
|
||||
this.dataset.draft = this.value;
|
||||
}
|
||||
historyIndex++;
|
||||
this.value = inputHistory[inputHistory.length - 1 - historyIndex];
|
||||
this.dispatchEvent(new Event('input'));
|
||||
setTimeout(() => this.setSelectionRange(this.value.length, this.value.length), 0);
|
||||
}
|
||||
}
|
||||
else if (e.key === 'ArrowDown') {
|
||||
if (historyIndex !== -1) {
|
||||
e.preventDefault();
|
||||
if (historyIndex > 0) {
|
||||
historyIndex--;
|
||||
this.value = inputHistory[inputHistory.length - 1 - historyIndex];
|
||||
} else {
|
||||
historyIndex = -1;
|
||||
this.value = this.dataset.draft || '';
|
||||
}
|
||||
this.dispatchEvent(new Event('input'));
|
||||
setTimeout(() => this.setSelectionRange(this.value.length, this.value.length), 0);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
loadTasks();
|
||||
});
|
||||
|
||||
function toggleDrawer() {
|
||||
const drawer = document.getElementById('task-drawer');
|
||||
const backdrop = document.getElementById('drawer-backdrop');
|
||||
const isHidden = drawer.classList.contains('translate-x-full');
|
||||
if (isHidden) {
|
||||
drawer.classList.remove('translate-x-full');
|
||||
backdrop.classList.remove('hidden');
|
||||
} else {
|
||||
drawer.classList.add('translate-x-full');
|
||||
backdrop.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function setFilter(status) {
|
||||
currentFilter = status;
|
||||
['ALL', 'IN_PROGRESS', 'BACKLOG', 'COMPLETED'].forEach(f => {
|
||||
const btn = document.getElementById(`filter-${f}`);
|
||||
if (f === status) {
|
||||
btn.className = "px-3 py-1.5 rounded-t-lg border-b-2 border-indigo-600 text-indigo-600 font-bold";
|
||||
} else {
|
||||
btn.className = "px-3 py-1.5 rounded-t-lg border-b-2 border-transparent hover:text-slate-700";
|
||||
}
|
||||
});
|
||||
renderTasks();
|
||||
}
|
||||
|
||||
async function loadTasks() {
|
||||
try {
|
||||
const res = await fetch('/api/v1/tasks', {
|
||||
headers: { 'Authorization': `Bearer ${API_TOKEN}` }
|
||||
});
|
||||
allTasks = await res.json();
|
||||
document.getElementById('task-count-badge').innerText = allTasks.length;
|
||||
renderTasks();
|
||||
} catch (err) {
|
||||
document.getElementById('tasks-container').innerHTML = `<div class="text-red-500 text-xs py-4 text-center">Ошибка загрузки задач</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderTasks() {
|
||||
const container = document.getElementById('tasks-container');
|
||||
const filtered = allTasks.filter(t => currentFilter === 'ALL' || t.status === currentFilter);
|
||||
|
||||
if (filtered.length === 0) {
|
||||
container.innerHTML = `<div class="text-slate-400 text-xs py-8 text-center">Нет задач с выбранным фильтром</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = filtered.map(t => {
|
||||
let statusBadge = 'bg-slate-100 text-slate-600 border-slate-200';
|
||||
let cardBg = 'bg-white';
|
||||
if (t.status === 'COMPLETED') {
|
||||
statusBadge = 'bg-emerald-50 text-emerald-700 border-emerald-300 font-semibold';
|
||||
cardBg = 'bg-emerald-50/20';
|
||||
} else if (t.status === 'IN_PROGRESS') {
|
||||
statusBadge = 'bg-amber-50 text-amber-700 border-amber-300 font-bold';
|
||||
cardBg = 'bg-amber-50/20 border-amber-200';
|
||||
}
|
||||
|
||||
let priorityBadge = 'text-slate-500 bg-slate-100 border-slate-200';
|
||||
if (t.priority === 'HIGH') priorityBadge = 'text-red-700 bg-red-50 border-red-200 font-bold';
|
||||
|
||||
let dueDateHtml = '';
|
||||
if (t.due_date) {
|
||||
dueDateHtml = `
|
||||
<div class="mt-2 text-[11px] text-amber-800 bg-amber-50 border border-amber-200 px-2 py-0.5 rounded-md flex items-center gap-1.5 w-fit font-medium">
|
||||
<i class="fa-solid fa-clock text-amber-600"></i>
|
||||
<span>Срок: ${t.due_date}</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="${cardBg} border border-slate-200 rounded-xl p-3.5 shadow-sm hover:shadow-md transition">
|
||||
<div class="flex justify-between items-center mb-1.5">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="font-mono text-xs font-bold text-slate-900 bg-slate-100 px-2 py-0.5 rounded border border-slate-200">${t.task_id}</span>
|
||||
<span class="text-[10px] uppercase px-1.5 py-0.5 rounded border ${priorityBadge}">${t.priority || 'HIGH'}</span>
|
||||
</div>
|
||||
<span class="text-[10px] uppercase px-2 py-0.5 rounded border ${statusBadge}">${t.status}</span>
|
||||
</div>
|
||||
|
||||
<h3 class="text-xs font-semibold text-slate-800 mb-1 leading-snug">${t.title}</h3>
|
||||
|
||||
<div class="text-[10px] text-slate-400 font-mono flex items-center gap-1">
|
||||
<i class="fa-solid fa-folder-closed text-slate-300"></i>
|
||||
<span>${t.module}</span>
|
||||
</div>
|
||||
|
||||
${dueDateHtml}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function sendMessage(e) {
|
||||
e.preventDefault();
|
||||
const input = document.getElementById('user-input');
|
||||
const chatWindow = document.getElementById('chat-window');
|
||||
const sendBtn = document.getElementById('send-btn');
|
||||
const text = input.value.trim();
|
||||
|
||||
if (!text) return;
|
||||
|
||||
if (inputHistory[inputHistory.length - 1] !== text) {
|
||||
inputHistory.push(text);
|
||||
if (inputHistory.length > 50) inputHistory.shift();
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(inputHistory));
|
||||
}
|
||||
historyIndex = -1;
|
||||
|
||||
chatWindow.innerHTML += `
|
||||
<div class="flex justify-end">
|
||||
<div class="bg-indigo-600 text-white rounded-xl px-4 py-2.5 max-w-2xl text-sm shadow-sm">
|
||||
${text}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
input.value = '';
|
||||
input.style.height = 'auto';
|
||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||
|
||||
sendBtn.disabled = true;
|
||||
sendBtn.classList.add('opacity-50');
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/chat', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${API_TOKEN}`
|
||||
},
|
||||
body: JSON.stringify({ session_id: SESSION_ID, message: text })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
chatWindow.innerHTML += `
|
||||
<div class="bg-white border border-slate-200 rounded-xl p-4 max-w-2xl shadow-sm">
|
||||
<p class="text-xs font-bold text-indigo-600 uppercase tracking-wider mb-1"><i class="fa-solid fa-robot mr-1"></i> ИИ-Ассистент</p>
|
||||
<p class="text-slate-700 text-sm whitespace-pre-wrap leading-relaxed">${data.reply}</p>
|
||||
</div>
|
||||
`;
|
||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||
loadTasks();
|
||||
|
||||
} catch (err) {
|
||||
chatWindow.innerHTML += `
|
||||
<div class="bg-red-50 border border-red-200 rounded-xl p-4 max-w-2xl text-red-700 text-sm">
|
||||
Ошибка связи с сервером API.
|
||||
</div>
|
||||
`;
|
||||
} finally {
|
||||
sendBtn.disabled = false;
|
||||
sendBtn.classList.remove('opacity-50');
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
# 4. Обновляем чистый static/index.html
|
||||
cat << 'EOF' > static/index.html
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>SCUD Orion AI — Context Manager</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<link rel="stylesheet" href="/static/css/styles.css">
|
||||
</head>
|
||||
<body class="bg-slate-50 text-slate-800 h-screen flex flex-col font-sans">
|
||||
|
||||
<!-- Хедер -->
|
||||
<header class="bg-white border-b border-slate-200 px-6 py-3 flex justify-between items-center shadow-sm">
|
||||
<div class="flex items-center space-x-3">
|
||||
<div class="bg-indigo-600 text-white p-2 rounded-lg">
|
||||
<i class="fa-solid fa-brain text-lg"></i>
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="text-base font-bold leading-none text-slate-900">SCUD Orion AI</h1>
|
||||
<span class="text-xs text-slate-500">Context & Task Manager</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center space-x-4">
|
||||
<span class="flex items-center text-xs text-emerald-600 font-medium bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200">
|
||||
<span class="h-2 w-2 rounded-full bg-emerald-500 mr-1.5"></span> API Online
|
||||
</span>
|
||||
<button onclick="toggleDrawer()" class="bg-indigo-50 hover:bg-indigo-100 text-indigo-700 px-3.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-2 transition border border-indigo-200">
|
||||
<i class="fa-solid fa-list-check text-indigo-600"></i>
|
||||
<span>Реестр задач</span>
|
||||
<span id="task-count-badge" class="bg-indigo-600 text-white text-[10px] px-1.5 py-0.2 rounded-full">0</span>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Основная зона чата -->
|
||||
<main class="flex-1 flex flex-col max-w-4xl w-full mx-auto bg-white my-4 rounded-xl border border-slate-200 shadow-sm overflow-hidden">
|
||||
<div id="chat-window" class="flex-1 p-6 overflow-y-auto space-y-4 bg-slate-50/50">
|
||||
<div class="bg-white border border-slate-200 rounded-xl p-4 max-w-2xl shadow-sm">
|
||||
<p class="text-xs font-bold text-indigo-600 uppercase tracking-wider mb-1">
|
||||
<i class="fa-solid fa-robot mr-1"></i> ИИ-Ассистент
|
||||
</p>
|
||||
<p class="text-slate-700 text-sm leading-relaxed">
|
||||
Привет! Я подключен к вашей базе задач и системным промптам. Вы можете писать команды прямо в чат или управлять задачами через панель справа.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Поле ввода -->
|
||||
<div class="p-4 bg-white border-t border-slate-200">
|
||||
<form id="chat-form" onsubmit="sendMessage(event)" class="flex items-end gap-2">
|
||||
<div class="flex-1 bg-slate-50 border border-slate-300 rounded-lg p-1 focus-within:border-indigo-600 focus-within:bg-white transition">
|
||||
<textarea id="user-input" rows="1" autocomplete="off" autocorrect="off" spellcheck="false"
|
||||
placeholder="Команда или вопрос (Shift+Enter — новая строка, ↑/↓ — история)..."
|
||||
class="w-full bg-transparent text-slate-800 px-3 py-1.5 text-sm focus:outline-none resize-none overflow-y-auto max-h-[96px] leading-relaxed fade-scroll-top no-scrollbar"></textarea>
|
||||
</div>
|
||||
<button type="submit" id="send-btn" class="bg-indigo-600 hover:bg-indigo-700 text-white font-medium px-5 h-[42px] rounded-lg text-sm transition flex items-center gap-2 shrink-0">
|
||||
<span>Отправить</span>
|
||||
<i class="fa-solid fa-paper-plane text-xs"></i>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Выезжающая панель (Drawer) -->
|
||||
<div id="drawer-backdrop" onclick="toggleDrawer()" class="fixed inset-0 bg-slate-900/30 backdrop-blur-sm hidden transition-opacity z-40"></div>
|
||||
|
||||
<aside id="task-drawer" class="fixed right-0 top-0 h-full w-[420px] bg-white border-l border-slate-200 shadow-2xl transform translate-x-full transition-transform duration-300 ease-in-out z-50 flex flex-col">
|
||||
<div class="p-4 border-b border-slate-200 flex justify-between items-center bg-slate-50">
|
||||
<h2 class="font-bold text-slate-800 flex items-center gap-2 text-sm">
|
||||
<i class="fa-solid fa-list-check text-indigo-600"></i> Реестр задач
|
||||
</h2>
|
||||
<div class="flex items-center gap-2">
|
||||
<button onclick="loadTasks()" class="text-xs text-slate-500 hover:text-indigo-600 transition p-1" title="Обновить">
|
||||
<i class="fa-solid fa-rotate-right"></i>
|
||||
</button>
|
||||
<button onclick="toggleDrawer()" class="text-slate-400 hover:text-slate-700 transition p-1">
|
||||
<i class="fa-solid fa-xmark text-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Фильтры задач -->
|
||||
<div class="flex border-b border-slate-200 bg-white px-2 pt-2 text-xs font-medium text-slate-500 gap-1">
|
||||
<button onclick="setFilter('ALL')" id="filter-ALL" class="px-3 py-1.5 rounded-t-lg border-b-2 border-indigo-600 text-indigo-600 font-bold">Все</button>
|
||||
<button onclick="setFilter('IN_PROGRESS')" id="filter-IN_PROGRESS" class="px-3 py-1.5 rounded-t-lg border-b-2 border-transparent hover:text-slate-700">В работе</button>
|
||||
<button onclick="setFilter('BACKLOG')" id="filter-BACKLOG" class="px-3 py-1.5 rounded-t-lg border-b-2 border-transparent hover:text-slate-700">Бэклог</button>
|
||||
<button onclick="setFilter('COMPLETED')" id="filter-COMPLETED" class="px-3 py-1.5 rounded-t-lg border-b-2 border-transparent hover:text-slate-700">Завершено</button>
|
||||
</div>
|
||||
|
||||
<div id="tasks-container" class="flex-1 overflow-y-auto p-4 space-y-3 bg-slate-50/50">
|
||||
<div class="text-center text-slate-400 py-8 text-xs">Загрузка задач...</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<script src="/static/js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
EOF
|
||||
|
||||
# 5. Фиксируем изменения фронтенда в Git
|
||||
git add static/
|
||||
git commit -m "refactor: декомпозиция фронтенда index.html (вынос static/css/styles.css и static/js/app.js)"
|
||||
git push origin feature/llm-refactoring
|
||||
+1
-1
@@ -2,4 +2,4 @@ home = /usr/bin
|
||||
include-system-site-packages = true
|
||||
version = 3.12.3
|
||||
executable = /usr/bin/python3.12
|
||||
command = /usr/bin/python3 -m venv --system-site-packages /home/puh/scud_context_api/venv
|
||||
command = /home/puh/scud_orion_ai_v2/venv/bin/python3 -m venv --system-site-packages /home/puh/scud_context_api/venv
|
||||
|
||||
Reference in New Issue
Block a user