feat: smeta-web — веб-интерфейс ИИ-ассистента для сметчика
FastAPI + Claude Code CLI + vanilla JS чат. - JWT авторизация, SSE streaming - Загрузка файлов (Excel, Word, PDF, CSV, TXT) - Каждая вкладка — отдельная Claude-сессия - Системный промпт: русский язык, работа с файлами, уточняющие вопросы - Деплой: systemd + nginx + Let's Encrypt на smeta.kazin.ru Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
SMETA_USER=smeta
|
||||
SMETA_PASS=your-secure-password-here
|
||||
SESSION_SECRET=your-random-secret-here
|
||||
CLAUDE_BIN=/home/mcp-user/.npm-global/bin/claude
|
||||
DATA_DIR=/home/mcp-user/smeta-web-data
|
||||
PORT=8000
|
||||
@@ -0,0 +1,4 @@
|
||||
.env
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
@@ -0,0 +1,75 @@
|
||||
# smeta-web
|
||||
|
||||
Веб-интерфейс ИИ-ассистента для сметчика. Claude Code работает на сервере, пользователь общается через чат в браузере.
|
||||
|
||||
## Возможности
|
||||
|
||||
- Чат с Claude на русском языке
|
||||
- Загрузка файлов: Excel, Word, PDF, CSV, TXT (drag & drop)
|
||||
- Claude читает, анализирует и создаёт файлы
|
||||
- Предпросмотр и скачивание результатов
|
||||
- Каждая вкладка — отдельная сессия (можно открыть несколько)
|
||||
- JWT-авторизация
|
||||
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
Браузер → nginx (HTTPS, Let's Encrypt) → FastAPI (uvicorn) → Claude Code CLI (subprocess)
|
||||
```
|
||||
|
||||
- **Frontend**: vanilla HTML + JS, SSE для streaming
|
||||
- **Backend**: FastAPI, JWT auth
|
||||
- **AI**: Claude Code CLI (`claude -p --output-format stream-json --resume`)
|
||||
- **Прокси**: xray → VPN для доступа к Anthropic API
|
||||
|
||||
## Деплой
|
||||
|
||||
Сервер: `192.168.87.76` (`git.kazin.ru` / `smeta.kazin.ru`)
|
||||
SSH: `ssh server-mcp-user`
|
||||
|
||||
```
|
||||
/home/mcp-user/smeta-web/ # приложение
|
||||
/home/mcp-user/smeta-web-data/ # файлы пользователей
|
||||
```
|
||||
|
||||
### Systemd-сервисы
|
||||
|
||||
| Сервис | Назначение |
|
||||
|--------|-----------|
|
||||
| `smeta-web.service` | FastAPI (uvicorn на порту 8101) |
|
||||
| `xray.service` | VPN-прокси для Anthropic API |
|
||||
|
||||
### Nginx
|
||||
|
||||
```
|
||||
smeta.kazin.ru:443 → proxy_pass localhost:8101
|
||||
```
|
||||
|
||||
Сертификат: Let's Encrypt (автопродление через certbot).
|
||||
|
||||
### Конфигурация
|
||||
|
||||
`/home/mcp-user/smeta-web/.env`:
|
||||
|
||||
```env
|
||||
SMETA_USER=smeta # логин
|
||||
SMETA_PASS=... # пароль
|
||||
SESSION_SECRET=... # JWT секрет
|
||||
CLAUDE_BIN=~/.npm-global/bin/claude
|
||||
DATA_DIR=/home/mcp-user/smeta-web-data
|
||||
PORT=8101
|
||||
```
|
||||
|
||||
Для смены пароля: отредактировать `.env` → `sudo systemctl restart smeta-web`
|
||||
|
||||
### Инструкции для Claude
|
||||
|
||||
`claude_project_instructions.md` — системный промпт, который добавляется к каждому запросу через `--append-system-prompt-file`. Определяет поведение: русский язык, работа с файлами, уточняющие вопросы.
|
||||
|
||||
## Разработка
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
cp .env.example .env # заполнить
|
||||
python main.py
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
"""JWT authentication — single user from env vars."""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
from jose import jwt
|
||||
|
||||
SECRET = os.environ.get("SESSION_SECRET", "change-me-in-production")
|
||||
ALGORITHM = "HS256"
|
||||
TOKEN_EXPIRE = 86400 * 7 # 7 days
|
||||
|
||||
VALID_USER = os.environ.get("SMETA_USER", "smeta")
|
||||
VALID_PASS = os.environ.get("SMETA_PASS", "")
|
||||
|
||||
|
||||
def authenticate(username: str, password: str) -> str | None:
|
||||
"""Return JWT token if credentials are valid, else None."""
|
||||
if not VALID_PASS:
|
||||
return None # password must be set
|
||||
if username == VALID_USER and password == VALID_PASS:
|
||||
payload = {"sub": username, "exp": int(time.time()) + TOKEN_EXPIRE}
|
||||
return jwt.encode(payload, SECRET, algorithm=ALGORITHM)
|
||||
return None
|
||||
|
||||
|
||||
def verify_token(token: str) -> str | None:
|
||||
"""Return username if token is valid, else None."""
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET, algorithms=[ALGORITHM])
|
||||
return payload.get("sub")
|
||||
except Exception:
|
||||
return None
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Bridge between FastAPI and Claude Code CLI subprocess."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
CLAUDE_BIN = os.environ.get(
|
||||
"CLAUDE_BIN", os.path.expanduser("~/.npm-global/bin/claude")
|
||||
)
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "/tmp/smeta-web-data"))
|
||||
APP_DIR = Path(__file__).parent
|
||||
|
||||
# Session tracking: tab_id -> claude session_id
|
||||
_sessions: dict[str, str] = {}
|
||||
|
||||
|
||||
def get_work_dir(username: str, tab_id: str) -> Path:
|
||||
d = DATA_DIR / username / tab_id
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def get_session_id(tab_id: str) -> str | None:
|
||||
return _sessions.get(tab_id)
|
||||
|
||||
|
||||
def set_session_id(tab_id: str, sid: str):
|
||||
_sessions[tab_id] = sid
|
||||
|
||||
|
||||
def clear_session(tab_id: str):
|
||||
_sessions.pop(tab_id, None)
|
||||
|
||||
|
||||
async def stream_claude(
|
||||
message: str,
|
||||
username: str,
|
||||
tab_id: str = "default",
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Run claude CLI, yield SSE-formatted events."""
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
session_id = get_session_id(tab_id)
|
||||
|
||||
instructions = APP_DIR / "claude_project_instructions.md"
|
||||
|
||||
cmd = [
|
||||
CLAUDE_BIN, "-p", message,
|
||||
"--output-format", "stream-json",
|
||||
"--verbose",
|
||||
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
|
||||
]
|
||||
if instructions.exists():
|
||||
cmd.extend(["--append-system-prompt-file", str(instructions)])
|
||||
if session_id:
|
||||
cmd.extend(["--resume", session_id])
|
||||
|
||||
env = os.environ.copy()
|
||||
# Proxy for Anthropic API (xray on server)
|
||||
env.setdefault("HTTPS_PROXY", "http://127.0.0.1:10809")
|
||||
env.setdefault("HTTP_PROXY", "http://127.0.0.1:10809")
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=str(work_dir),
|
||||
env=env,
|
||||
)
|
||||
|
||||
try:
|
||||
async for raw_line in proc.stdout:
|
||||
line = raw_line.decode().strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
etype = event.get("type", "")
|
||||
|
||||
if etype == "assistant":
|
||||
# Extract text from content blocks
|
||||
msg = event.get("message", {})
|
||||
for block in msg.get("content", []):
|
||||
if block.get("type") == "text":
|
||||
text = block["text"]
|
||||
yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n"
|
||||
elif block.get("type") == "tool_use":
|
||||
name = block.get("name", "")
|
||||
inp = block.get("input", {})
|
||||
yield f"event: tool\ndata: {json.dumps({'tool': name, 'input': inp}, ensure_ascii=False)}\n\n"
|
||||
|
||||
elif etype == "result":
|
||||
sid = event.get("session_id", "")
|
||||
if sid:
|
||||
set_session_id(tab_id, sid)
|
||||
result_text = event.get("result", "")
|
||||
cost = event.get("total_cost_usd", 0)
|
||||
yield f"event: done\ndata: {json.dumps({'result': result_text, 'cost': cost}, ensure_ascii=False)}\n\n"
|
||||
|
||||
finally:
|
||||
if proc.returncode is None:
|
||||
proc.terminate()
|
||||
await proc.wait()
|
||||
|
||||
|
||||
def list_user_files(username: str, tab_id: str = "default") -> list[dict]:
|
||||
"""List files in user's work directory."""
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
files = []
|
||||
for f in sorted(work_dir.iterdir()):
|
||||
if f.is_file() and not f.name.startswith("."):
|
||||
files.append({
|
||||
"name": f.name,
|
||||
"size": f.stat().st_size,
|
||||
})
|
||||
return files
|
||||
@@ -0,0 +1,40 @@
|
||||
# Инструкции для ИИ-ассистента сметчика
|
||||
|
||||
## Язык
|
||||
- Отвечай ТОЛЬКО на русском языке
|
||||
- Технические термины можно на английском (Excel, Python, PDF)
|
||||
- Будь вежлив и профессионален
|
||||
|
||||
## Кто ты
|
||||
Ты — ИИ-ассистент для сметчика железнодорожного строительства. Пользователь — профессиональный сметчик, НЕ программист. Не используй технический жаргон. Объясняй просто.
|
||||
|
||||
## Что ты умеешь
|
||||
1. **Работа с файлами** — Excel (.xlsx, .xls), Word (.docx), PDF, CSV, TXT
|
||||
- Читать, анализировать, извлекать данные
|
||||
- Создавать новые файлы на основе запросов
|
||||
- Переносить данные между таблицами
|
||||
- Фильтровать, сортировать, считать суммы
|
||||
2. **Сметные вопросы** — ГЭСН, НР, СП, коэффициенты, нормативка
|
||||
3. **Общие вопросы** — расчёты, формулы, пояснения
|
||||
|
||||
## Как работать с файлами
|
||||
- Файлы пользователя лежат в текущей рабочей директории
|
||||
- Для работы с Excel используй Python + openpyxl (или pandas если нужно)
|
||||
- Для Word — python-docx
|
||||
- Для PDF — pymupdf (fitz)
|
||||
- ВСЕГДА показывай что получилось: первые строки таблицы, краткое описание результата
|
||||
- После создания файла — скажи пользователю что файл готов и он может его скачать
|
||||
|
||||
## Правила поведения
|
||||
1. **Уточняй** — если запрос неясен, задай уточняющий вопрос ПЕРЕД выполнением
|
||||
2. **Превью** — всегда показывай предпросмотр результата (первые 10-20 строк)
|
||||
3. **Подтверждение** — для разрушающих операций (удаление, перезапись) спрашивай подтверждение
|
||||
4. **Ошибки** — если что-то не получается, объясни простым языком и предложи альтернативу
|
||||
5. **Не выполняй** сетевых запросов, не устанавливай пакеты, не трогай системные файлы
|
||||
|
||||
## Автоматические приёмы (применяй сам, без запроса)
|
||||
- Перед работой с файлом — прочитай его структуру и покажи пользователю
|
||||
- Если данные грязные (пустые строки, лишние пробелы) — предупреди
|
||||
- При создании Excel — форматируй красиво (заголовки жирным, автоширина столбцов)
|
||||
- При больших таблицах — покажи итоги (кол-во строк, сумма, мин/макс если уместно)
|
||||
- Если вопрос по нормативке — дай ссылку на пункт нормативного документа
|
||||
@@ -0,0 +1,143 @@
|
||||
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from auth import authenticate, verify_token
|
||||
from claude_bridge import (
|
||||
clear_session,
|
||||
get_work_dir,
|
||||
list_user_files,
|
||||
stream_claude,
|
||||
)
|
||||
|
||||
app = FastAPI(title="smeta-web")
|
||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||
|
||||
MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB
|
||||
|
||||
|
||||
def _get_user(request: Request) -> str:
|
||||
"""Extract and verify user from Authorization header."""
|
||||
auth = request.headers.get("authorization", "")
|
||||
token = auth.removeprefix("Bearer ").strip()
|
||||
if not token:
|
||||
raise HTTPException(401, "No token")
|
||||
user = verify_token(token)
|
||||
if not user:
|
||||
raise HTTPException(401, "Invalid token")
|
||||
return user
|
||||
|
||||
|
||||
def _get_tab(request: Request, body: dict | None = None) -> str:
|
||||
"""Extract tab_id from request header or body."""
|
||||
if body and "tab_id" in body:
|
||||
return body["tab_id"]
|
||||
return request.headers.get("x-tab-id", "default")
|
||||
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def index():
|
||||
return Path("static/chat.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.post("/api/login")
|
||||
async def login(request: Request):
|
||||
body = await request.json()
|
||||
username = body.get("username", "")
|
||||
password = body.get("password", "")
|
||||
token = authenticate(username, password)
|
||||
if not token:
|
||||
raise HTTPException(401, "Wrong credentials")
|
||||
return {"token": token, "username": username}
|
||||
|
||||
|
||||
@app.post("/api/chat")
|
||||
async def chat(request: Request):
|
||||
user = _get_user(request)
|
||||
body = await request.json()
|
||||
message = body.get("message", "").strip()
|
||||
tab_id = _get_tab(request, body)
|
||||
if not message:
|
||||
raise HTTPException(400, "Empty message")
|
||||
|
||||
return StreamingResponse(
|
||||
stream_claude(message, user, tab_id),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/upload")
|
||||
async def upload(request: Request, file: UploadFile):
|
||||
user = _get_user(request)
|
||||
tab_id = request.headers.get("x-tab-id", "default")
|
||||
work_dir = get_work_dir(user, tab_id)
|
||||
|
||||
content = await file.read()
|
||||
if len(content) > MAX_UPLOAD_SIZE:
|
||||
raise HTTPException(413, f"File too large (max {MAX_UPLOAD_SIZE // 1024 // 1024}MB)")
|
||||
|
||||
safe_name = Path(file.filename).name
|
||||
if not safe_name or safe_name.startswith("."):
|
||||
raise HTTPException(400, "Invalid filename")
|
||||
dest = work_dir / safe_name
|
||||
dest.write_bytes(content)
|
||||
return {"filename": safe_name, "size": len(content)}
|
||||
|
||||
|
||||
@app.get("/api/files")
|
||||
async def files(request: Request):
|
||||
user = _get_user(request)
|
||||
tab_id = request.headers.get("x-tab-id", "default")
|
||||
return list_user_files(user, tab_id)
|
||||
|
||||
|
||||
@app.get("/api/files/{filename}")
|
||||
async def download_file(filename: str, request: Request):
|
||||
user = _get_user(request)
|
||||
tab_id = request.headers.get("x-tab-id", "default")
|
||||
safe_name = Path(filename).name
|
||||
fpath = get_work_dir(user, tab_id) / safe_name
|
||||
if not fpath.exists() or not fpath.is_file():
|
||||
raise HTTPException(404, "File not found")
|
||||
return FileResponse(fpath, filename=filename)
|
||||
|
||||
|
||||
@app.post("/api/reset")
|
||||
async def reset_session(request: Request):
|
||||
user = _get_user(request)
|
||||
body = await request.json()
|
||||
tab_id = _get_tab(request, body)
|
||||
clear_session(tab_id)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/clear-files")
|
||||
async def clear_files(request: Request):
|
||||
user = _get_user(request)
|
||||
body = await request.json()
|
||||
tab_id = _get_tab(request, body)
|
||||
work_dir = get_work_dir(user, tab_id)
|
||||
for f in work_dir.iterdir():
|
||||
if f.name.startswith("."):
|
||||
continue
|
||||
if f.is_file():
|
||||
f.unlink()
|
||||
elif f.is_dir():
|
||||
shutil.rmtree(f)
|
||||
clear_session(tab_id)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|
||||
@@ -0,0 +1,4 @@
|
||||
fastapi>=0.115
|
||||
uvicorn[standard]>=0.32
|
||||
python-jose[cryptography]>=3.3
|
||||
python-multipart>=0.0.12
|
||||
@@ -0,0 +1,345 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Сметный ИИ-ассистент</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f5f5f5; height: 100vh; display: flex; flex-direction: column; }
|
||||
|
||||
/* Login */
|
||||
#login-screen { display: flex; align-items: center; justify-content: center; height: 100vh; }
|
||||
#login-form { background: #fff; padding: 2rem; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,.1); width: 320px; }
|
||||
#login-form h2 { margin-bottom: 1rem; text-align: center; }
|
||||
#login-form input { width: 100%; padding: .6rem; margin-bottom: .8rem; border: 1px solid #ddd; border-radius: 6px; font-size: 1rem; }
|
||||
#login-form button { width: 100%; padding: .7rem; background: #2563eb; color: #fff; border: none; border-radius: 6px; font-size: 1rem; cursor: pointer; }
|
||||
#login-form button:hover { background: #1d4ed8; }
|
||||
#login-error { color: #dc2626; font-size: .85rem; margin-bottom: .5rem; display: none; }
|
||||
|
||||
/* Chat */
|
||||
#chat-screen { display: none; flex-direction: column; height: 100vh; }
|
||||
#header { background: #fff; padding: .6rem 1rem; border-bottom: 1px solid #e5e7eb; display: flex; align-items: center; justify-content: space-between; }
|
||||
#header h1 { font-size: 1.1rem; font-weight: 600; }
|
||||
.header-actions { display: flex; gap: .5rem; }
|
||||
.header-actions button { padding: .3rem .8rem; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer; font-size: .8rem; }
|
||||
.header-actions button:hover { background: #e5e7eb; }
|
||||
|
||||
#messages { flex: 1; overflow-y: auto; padding: 1rem; display: flex; flex-direction: column; gap: .6rem; }
|
||||
.msg { max-width: 80%; padding: .7rem 1rem; border-radius: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; font-size: .95rem; }
|
||||
.msg-user { align-self: flex-end; background: #2563eb; color: #fff; }
|
||||
.msg-ai { align-self: flex-start; background: #fff; border: 1px solid #e5e7eb; }
|
||||
.msg-tool { align-self: flex-start; background: #fef3c7; border: 1px solid #fcd34d; font-size: .8rem; font-family: monospace; }
|
||||
.msg-file { align-self: flex-start; background: #ecfdf5; border: 1px solid #6ee7b7; font-size: .85rem; }
|
||||
.msg-file a { color: #059669; text-decoration: underline; cursor: pointer; }
|
||||
.msg-error { align-self: center; background: #fef2f2; border: 1px solid #fca5a5; color: #dc2626; }
|
||||
.msg-system { align-self: center; background: #f0f9ff; border: 1px solid #93c5fd; font-size: .8rem; color: #1e40af; }
|
||||
.typing { align-self: flex-start; color: #9ca3af; font-style: italic; font-size: .85rem; }
|
||||
|
||||
/* Input */
|
||||
#input-area { background: #fff; border-top: 1px solid #e5e7eb; padding: .8rem 1rem; }
|
||||
#drop-zone { border: 2px dashed transparent; border-radius: 8px; transition: border-color .2s; padding: .3rem; }
|
||||
#drop-zone.dragover { border-color: #2563eb; background: #eff6ff; }
|
||||
#file-list { display: flex; gap: .3rem; flex-wrap: wrap; margin-bottom: .3rem; }
|
||||
.file-badge { background: #e0f2fe; padding: .2rem .5rem; border-radius: 4px; font-size: .75rem; display: flex; align-items: center; gap: .3rem; }
|
||||
.file-badge .remove { cursor: pointer; color: #dc2626; font-weight: bold; }
|
||||
#input-row { display: flex; gap: .5rem; }
|
||||
#msg-input { flex: 1; padding: .6rem; border: 1px solid #d1d5db; border-radius: 8px; font-size: 1rem; resize: none; min-height: 42px; max-height: 150px; font-family: inherit; }
|
||||
#send-btn { padding: .6rem 1.2rem; background: #2563eb; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem; white-space: nowrap; }
|
||||
#send-btn:disabled { background: #93c5fd; cursor: not-allowed; }
|
||||
#file-btn { padding: .6rem; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 8px; cursor: pointer; font-size: 1.1rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Login Screen -->
|
||||
<div id="login-screen">
|
||||
<form id="login-form" onsubmit="return doLogin(event)">
|
||||
<h2>Сметный ИИ</h2>
|
||||
<div id="login-error">Неверный логин или пароль</div>
|
||||
<input type="text" id="login-user" placeholder="Логин" autocomplete="username" required>
|
||||
<input type="password" id="login-pass" placeholder="Пароль" autocomplete="current-password" required>
|
||||
<button type="submit">Войти</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Chat Screen -->
|
||||
<div id="chat-screen">
|
||||
<div id="header">
|
||||
<h1>Сметный ИИ-ассистент</h1>
|
||||
<div class="header-actions">
|
||||
<button onclick="resetSession()">Новый диалог</button>
|
||||
<button onclick="listFiles()">Файлы</button>
|
||||
<button onclick="logout()">Выйти</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="messages"></div>
|
||||
|
||||
<div id="input-area">
|
||||
<div id="drop-zone">
|
||||
<div id="file-list"></div>
|
||||
<div id="input-row">
|
||||
<button id="file-btn" onclick="document.getElementById('file-input').click()" title="Прикрепить файл">📎</button>
|
||||
<textarea id="msg-input" placeholder="Напишите сообщение..." rows="1" onkeydown="handleKey(event)"></textarea>
|
||||
<button id="send-btn" onclick="sendMessage()">Отправить</button>
|
||||
</div>
|
||||
</div>
|
||||
<input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const API = '';
|
||||
let token = localStorage.getItem('token');
|
||||
let pendingFiles = [];
|
||||
let streaming = false;
|
||||
// Each tab gets its own session — allows multiple windows
|
||||
const tabId = sessionStorage.getItem('tabId') || crypto.randomUUID();
|
||||
sessionStorage.setItem('tabId', tabId);
|
||||
|
||||
// --- Init ---
|
||||
if (token) showChat(); else showLogin();
|
||||
|
||||
function showLogin() {
|
||||
document.getElementById('login-screen').style.display = 'flex';
|
||||
document.getElementById('chat-screen').style.display = 'none';
|
||||
}
|
||||
function showChat() {
|
||||
document.getElementById('login-screen').style.display = 'none';
|
||||
document.getElementById('chat-screen').style.display = 'flex';
|
||||
document.getElementById('msg-input').focus();
|
||||
}
|
||||
|
||||
// --- Auth ---
|
||||
async function doLogin(e) {
|
||||
e.preventDefault();
|
||||
const user = document.getElementById('login-user').value;
|
||||
const pass = document.getElementById('login-pass').value;
|
||||
try {
|
||||
const r = await fetch(API + '/api/login', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({username: user, password: pass})
|
||||
});
|
||||
if (!r.ok) throw new Error();
|
||||
const data = await r.json();
|
||||
token = data.token;
|
||||
localStorage.setItem('token', token);
|
||||
showChat();
|
||||
addMsg('system', 'Добро пожаловать! Напишите вопрос или прикрепите файл.');
|
||||
} catch {
|
||||
document.getElementById('login-error').style.display = 'block';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function logout() {
|
||||
token = null;
|
||||
localStorage.removeItem('token');
|
||||
showLogin();
|
||||
}
|
||||
function authHeaders() {
|
||||
return {'Authorization': 'Bearer ' + token, 'X-Tab-Id': tabId};
|
||||
}
|
||||
|
||||
// --- Messages ---
|
||||
const msgs = document.getElementById('messages');
|
||||
function addMsg(type, text) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'msg msg-' + type;
|
||||
div.textContent = text;
|
||||
msgs.appendChild(div);
|
||||
msgs.scrollTop = msgs.scrollHeight;
|
||||
return div;
|
||||
}
|
||||
function addTyping() {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'typing';
|
||||
div.id = 'typing-indicator';
|
||||
div.textContent = 'Claude думает...';
|
||||
msgs.appendChild(div);
|
||||
msgs.scrollTop = msgs.scrollHeight;
|
||||
return div;
|
||||
}
|
||||
function removeTyping() {
|
||||
const el = document.getElementById('typing-indicator');
|
||||
if (el) el.remove();
|
||||
}
|
||||
|
||||
// --- File Upload ---
|
||||
const dropZone = document.getElementById('drop-zone');
|
||||
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('dragover'); });
|
||||
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
|
||||
dropZone.addEventListener('drop', e => {
|
||||
e.preventDefault();
|
||||
dropZone.classList.remove('dragover');
|
||||
handleFiles(e.dataTransfer.files);
|
||||
});
|
||||
|
||||
function handleFiles(fileList) {
|
||||
for (const f of fileList) pendingFiles.push(f);
|
||||
renderFileList();
|
||||
}
|
||||
function renderFileList() {
|
||||
const fl = document.getElementById('file-list');
|
||||
fl.innerHTML = '';
|
||||
pendingFiles.forEach((f, i) => {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'file-badge';
|
||||
badge.innerHTML = f.name + ' <span class="remove" onclick="removeFile(' + i + ')">×</span>';
|
||||
fl.appendChild(badge);
|
||||
});
|
||||
}
|
||||
function removeFile(i) { pendingFiles.splice(i, 1); renderFileList(); }
|
||||
|
||||
async function uploadFiles() {
|
||||
const uploaded = [];
|
||||
for (const f of pendingFiles) {
|
||||
const fd = new FormData();
|
||||
fd.append('file', f);
|
||||
const r = await fetch(API + '/api/upload', {
|
||||
method: 'POST',
|
||||
headers: authHeaders(),
|
||||
body: fd,
|
||||
});
|
||||
if (r.ok) {
|
||||
const data = await r.json();
|
||||
uploaded.push(data.filename);
|
||||
}
|
||||
}
|
||||
pendingFiles = [];
|
||||
renderFileList();
|
||||
return uploaded;
|
||||
}
|
||||
|
||||
// --- Send Message ---
|
||||
function handleKey(e) {
|
||||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
if (streaming) return;
|
||||
const input = document.getElementById('msg-input');
|
||||
let text = input.value.trim();
|
||||
if (!text && pendingFiles.length === 0) return;
|
||||
|
||||
// Upload files first
|
||||
let uploaded = [];
|
||||
if (pendingFiles.length > 0) {
|
||||
uploaded = await uploadFiles();
|
||||
if (uploaded.length > 0) {
|
||||
const fileNote = 'Загружены файлы: ' + uploaded.join(', ');
|
||||
addMsg('file', fileNote);
|
||||
if (!text) text = 'Я загрузил файлы: ' + uploaded.join(', ') + '. Покажи их содержимое.';
|
||||
else text = 'Файлы в рабочей директории: ' + uploaded.join(', ') + '\n\n' + text;
|
||||
}
|
||||
}
|
||||
|
||||
addMsg('user', text);
|
||||
input.value = '';
|
||||
input.style.height = 'auto';
|
||||
|
||||
streaming = true;
|
||||
document.getElementById('send-btn').disabled = true;
|
||||
addTyping();
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/api/chat', {
|
||||
method: 'POST',
|
||||
headers: {...authHeaders(), 'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({message: text}),
|
||||
});
|
||||
|
||||
if (r.status === 401) { logout(); return; }
|
||||
if (!r.ok) { addMsg('error', 'Ошибка: ' + r.status); return; }
|
||||
|
||||
removeTyping();
|
||||
let aiDiv = null;
|
||||
let aiText = '';
|
||||
const reader = r.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, {stream: true});
|
||||
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop();
|
||||
|
||||
let eventType = '';
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event: ')) {
|
||||
eventType = line.slice(7);
|
||||
} else if (line.startsWith('data: ')) {
|
||||
const data = JSON.parse(line.slice(6));
|
||||
if (eventType === 'text') {
|
||||
if (!aiDiv) aiDiv = addMsg('ai', '');
|
||||
aiText += data.text;
|
||||
aiDiv.textContent = aiText;
|
||||
msgs.scrollTop = msgs.scrollHeight;
|
||||
} else if (eventType === 'tool') {
|
||||
addMsg('tool', '🔧 ' + data.tool + (data.input.command ? ': ' + data.input.command : data.input.file_path ? ': ' + data.input.file_path : ''));
|
||||
} else if (eventType === 'done') {
|
||||
if (!aiDiv && data.result) {
|
||||
aiDiv = addMsg('ai', data.result);
|
||||
}
|
||||
// cost info hidden from user
|
||||
}
|
||||
eventType = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!aiDiv && !aiText) addMsg('ai', '(пустой ответ)');
|
||||
|
||||
} catch (err) {
|
||||
removeTyping();
|
||||
addMsg('error', 'Ошибка соединения: ' + err.message);
|
||||
} finally {
|
||||
streaming = false;
|
||||
document.getElementById('send-btn').disabled = false;
|
||||
input.focus();
|
||||
}
|
||||
}
|
||||
|
||||
// --- Session ---
|
||||
async function resetSession() {
|
||||
await fetch(API + '/api/reset', {method: 'POST', headers: authHeaders()});
|
||||
msgs.innerHTML = '';
|
||||
addMsg('system', 'Новый диалог начат.');
|
||||
}
|
||||
|
||||
async function listFiles() {
|
||||
const r = await fetch(API + '/api/files', {headers: authHeaders()});
|
||||
if (!r.ok) return;
|
||||
const files = await r.json();
|
||||
if (files.length === 0) { addMsg('system', 'Файлов нет.'); return; }
|
||||
const list = files.map(f => {
|
||||
const kb = (f.size / 1024).toFixed(1);
|
||||
return f.name + ' (' + kb + ' KB)';
|
||||
}).join('\n');
|
||||
const div = addMsg('file', 'Файлы в рабочей директории:\n' + list);
|
||||
// Add download links
|
||||
files.forEach(f => {
|
||||
const a = document.createElement('a');
|
||||
a.textContent = ' [скачать ' + f.name + ']';
|
||||
a.href = API + '/api/files/' + encodeURIComponent(f.name);
|
||||
a.onclick = e => {
|
||||
e.preventDefault();
|
||||
fetch(a.href, {headers: authHeaders()})
|
||||
.then(r => r.blob())
|
||||
.then(b => { const u = URL.createObjectURL(b); const l = document.createElement('a'); l.href = u; l.download = f.name; l.click(); });
|
||||
};
|
||||
div.appendChild(a);
|
||||
});
|
||||
}
|
||||
|
||||
// Auto-resize textarea
|
||||
document.getElementById('msg-input').addEventListener('input', function() {
|
||||
this.style.height = 'auto';
|
||||
this.style.height = Math.min(this.scrollHeight, 150) + 'px';
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user