mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
956 lines
34 KiB
Python
956 lines
34 KiB
Python
"""Chat router: CRUD for chats + model aggregation."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
from pathlib import Path
|
|
from typing import List, Optional
|
|
|
|
from fastapi import APIRouter, HTTPException, Query, Request
|
|
from pydantic import BaseModel
|
|
|
|
from cptr.models import Chat, ChatMessage, Config
|
|
from cptr.utils.config import check_access, now_ms, _get_jwt_secret
|
|
from cptr.utils.crypto import decrypt_key
|
|
from cptr.utils.workspace import ensure_cptr_gitignored
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
router = APIRouter(prefix="/api/chats", tags=["chats"])
|
|
|
|
COOKIE_NAME = "cptr_session"
|
|
|
|
|
|
def _get_user(request: Request) -> str:
|
|
"""Extract user_id from cookie, raise 401 if not authenticated."""
|
|
token = request.cookies.get(COOKIE_NAME)
|
|
client_host = request.client.host if request.client else "127.0.0.1"
|
|
auth = check_access(client_host=client_host, jwt_token=token)
|
|
if not auth or not auth.user_id:
|
|
raise HTTPException(401, "authentication required")
|
|
return auth.user_id
|
|
|
|
|
|
# ── List chats for a workspace ──────────────────────────────
|
|
|
|
|
|
@router.get("")
|
|
async def list_chats(
|
|
request: Request,
|
|
workspace: str = Query(..., description="Workspace root path"),
|
|
limit: int = Query(50, ge=1, le=200, description="Max chats to return"),
|
|
offset: int = Query(0, ge=0, description="Number of chats to skip"),
|
|
sort_by: str = Query("updated_at", description="Sort field: 'title' or 'updated_at'"),
|
|
sort_dir: str = Query("desc", description="Sort direction: 'asc' or 'desc'"),
|
|
):
|
|
"""List chats for a workspace by scanning .cptr/chats/ for JSON files.
|
|
|
|
Returns chat metadata with relative folder paths for sidebar display.
|
|
Supports pagination via limit/offset and sorting via sort_by/sort_dir.
|
|
"""
|
|
user_id = _get_user(request)
|
|
chats_dir = Path(workspace) / ".cptr" / "chats"
|
|
|
|
if not chats_dir.exists():
|
|
return {"chats": [], "total": 0, "has_more": False}
|
|
|
|
# Scan filesystem for chat JSON files in a thread
|
|
def _scan_chat_files() -> list[dict]:
|
|
entries = []
|
|
for json_file in chats_dir.rglob("*.json"):
|
|
chat_id = json_file.stem
|
|
rel_folder = str(json_file.parent.relative_to(chats_dir))
|
|
if rel_folder == ".":
|
|
rel_folder = ""
|
|
entries.append({"id": chat_id, "folder": rel_folder})
|
|
return entries
|
|
|
|
chat_entries = await asyncio.to_thread(_scan_chat_files)
|
|
|
|
if not chat_entries:
|
|
return {"chats": [], "total": 0, "has_more": False}
|
|
|
|
# Batch-fetch from DB
|
|
chat_ids = [e["id"] for e in chat_entries]
|
|
chats = await Chat.get_by_ids(chat_ids)
|
|
chat_map = {c.id: c for c in chats}
|
|
|
|
# Detect which chats have a running task (in-memory check, no DB hit)
|
|
from cptr.utils.chat_task import get_active_chat_ids
|
|
|
|
active_ids = get_active_chat_ids()
|
|
|
|
# Build response: only include chats owned by this user
|
|
result = []
|
|
for entry in chat_entries:
|
|
chat = chat_map.get(entry["id"])
|
|
if chat and chat.user_id == user_id:
|
|
result.append(
|
|
{
|
|
"id": chat.id,
|
|
"title": chat.title,
|
|
"summary": chat.summary,
|
|
"folder": entry["folder"],
|
|
"meta": chat.meta,
|
|
"current_message_id": chat.current_message_id,
|
|
"created_at": chat.created_at,
|
|
"updated_at": chat.updated_at,
|
|
"is_active": chat.id in active_ids,
|
|
}
|
|
)
|
|
|
|
# Sort by requested field
|
|
sort_field = sort_by if sort_by in ("title", "updated_at") else "updated_at"
|
|
reverse = sort_dir != "asc"
|
|
result.sort(key=lambda c: c[sort_field] or "", reverse=reverse)
|
|
total = len(result)
|
|
page = result[offset : offset + limit]
|
|
return {"chats": page, "total": total, "has_more": offset + limit < total}
|
|
|
|
|
|
# ── Models aggregation ──────────────────────────────────────
|
|
# NOTE: Must be declared before /{chat_id} to avoid 'models' being treated as a chat_id.
|
|
|
|
|
|
async def _get_connections() -> list[dict]:
|
|
return await Config.get("chat.connections") or []
|
|
|
|
|
|
# ── Model cache (app.state) ─────────────────────────────────
|
|
|
|
|
|
async def _get_connection_models(conn: dict, app_state) -> list[str]:
|
|
"""Get models for a connection: from stored data, cache, or auto-discover."""
|
|
stored = conn.get("data", {}).get("models")
|
|
if stored:
|
|
return stored
|
|
|
|
conn_id = conn.get("id", "")
|
|
cache = getattr(app_state, "MODELS", None)
|
|
if cache is None:
|
|
cache = {}
|
|
app_state.MODELS = cache
|
|
|
|
if conn_id in cache:
|
|
return cache[conn_id]
|
|
|
|
models = await _fetch_provider_models(conn)
|
|
cache[conn_id] = models
|
|
return models
|
|
|
|
|
|
def invalidate_model_cache(app_state):
|
|
"""Clear cached models. Call after connection create/update/delete."""
|
|
app_state.MODELS = {}
|
|
|
|
|
|
@router.get("/models")
|
|
async def get_models(request: Request):
|
|
"""Aggregate available models across all connections.
|
|
|
|
If a connection has data.models set, use those.
|
|
Otherwise, call the provider's /models endpoint to discover available models.
|
|
"""
|
|
_get_user(request)
|
|
connections = [c for c in await _get_connections() if c.get("enabled", True)]
|
|
models = []
|
|
|
|
for conn in connections:
|
|
model_ids = await _get_connection_models(conn, request.app.state)
|
|
|
|
prefix = (conn.get("prefix_id") or "").strip()
|
|
|
|
for model_id in model_ids or []:
|
|
prefixed_id = f"{prefix}/{model_id}" if prefix else model_id
|
|
models.append(
|
|
{
|
|
"id": prefixed_id,
|
|
"name": model_id,
|
|
"provider": conn.get("provider", ""),
|
|
"connection_id": conn["id"],
|
|
}
|
|
)
|
|
|
|
default_model = await Config.get("chat.default_model")
|
|
|
|
# Filter out inactive models
|
|
chat_models_config = await Config.get("chat.models") or {}
|
|
inactive = {k for k, v in chat_models_config.items() if v.get("is_active") is False}
|
|
if inactive:
|
|
models = [m for m in models if m["id"] not in inactive]
|
|
|
|
return {"models": models, "default": default_model}
|
|
|
|
|
|
async def _fetch_provider_models(conn: dict) -> list[str]:
|
|
"""Discover models from a provider's /models endpoint."""
|
|
import httpx
|
|
|
|
from cptr.utils.ai import _openrouter_headers
|
|
|
|
secret = _get_jwt_secret()
|
|
api_key = decrypt_key(conn.get("api_key", ""), secret) if conn.get("api_key") else None
|
|
provider = conn.get("provider", "")
|
|
base_url = conn.get("base_url")
|
|
|
|
try:
|
|
if provider == "anthropic":
|
|
url = (base_url or "https://api.anthropic.com/v1") + "/models"
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.get(
|
|
url,
|
|
headers={
|
|
"x-api-key": api_key or "",
|
|
"anthropic-version": "2023-06-01",
|
|
**_openrouter_headers(url),
|
|
},
|
|
)
|
|
if r.status_code == 200:
|
|
data = r.json()
|
|
models = [m["id"] for m in data.get("data", [])]
|
|
log.info("Auto-discovered %d models from %s", len(models), url)
|
|
return models
|
|
else:
|
|
log.warning(
|
|
"Model auto-discovery failed for %s: HTTP %d",
|
|
url,
|
|
r.status_code,
|
|
)
|
|
|
|
elif provider == "openai":
|
|
url = (base_url or "https://api.openai.com/v1") + "/models"
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.get(
|
|
url,
|
|
headers={
|
|
"Authorization": f"Bearer {api_key or ''}",
|
|
**_openrouter_headers(url),
|
|
},
|
|
)
|
|
if r.status_code == 200:
|
|
data = r.json()
|
|
models = [m["id"] for m in data.get("data", [])]
|
|
log.info("Auto-discovered %d models from %s", len(models), url)
|
|
return models
|
|
else:
|
|
log.warning(
|
|
"Model auto-discovery failed for %s: HTTP %d",
|
|
url,
|
|
r.status_code,
|
|
)
|
|
|
|
else:
|
|
log.warning("Unknown provider '%s', skipping model auto-discovery", provider)
|
|
|
|
except Exception:
|
|
log.exception("Model auto-discovery error for connection %s", conn.get("id", "?"))
|
|
|
|
return []
|
|
|
|
|
|
# ── Get a chat with all messages ────────────────────────────
|
|
|
|
|
|
@router.get("/{chat_id}")
|
|
async def get_chat(
|
|
chat_id: str,
|
|
request: Request,
|
|
model_id: str | None = Query(None, description="Model used for system prompt context"),
|
|
):
|
|
"""Get chat metadata + all messages."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
|
|
messages = await ChatMessage.get_all_by_chat(chat_id)
|
|
context_usage = await _get_chat_context_usage(chat, model_id)
|
|
return {
|
|
"chat": {
|
|
"id": chat.id,
|
|
"title": chat.title,
|
|
"summary": chat.summary,
|
|
"meta": chat.meta,
|
|
"current_message_id": chat.current_message_id,
|
|
"created_at": chat.created_at,
|
|
"updated_at": chat.updated_at,
|
|
},
|
|
"messages": [_message_dict(m) for m in messages],
|
|
"context_usage": context_usage,
|
|
}
|
|
|
|
|
|
def _message_dict(m) -> dict:
|
|
"""Serialize a ChatMessage, overlaying live state if task is running."""
|
|
from cptr.utils.chat_task import get_live_state
|
|
|
|
d = {
|
|
"id": m.id,
|
|
"parent_id": m.parent_id,
|
|
"role": m.role,
|
|
"content": m.content,
|
|
"model": m.model,
|
|
"done": m.done,
|
|
"output": m.output,
|
|
"usage": m.usage,
|
|
"meta": m.meta,
|
|
"created_at": m.created_at,
|
|
}
|
|
live = get_live_state(m.id)
|
|
if live:
|
|
d["content"] = live["content"]
|
|
d["output"] = live["output"]
|
|
d["done"] = False
|
|
return d
|
|
|
|
|
|
async def _get_context_leaf_message_id(chat) -> str | None:
|
|
if chat.current_message_id:
|
|
return chat.current_message_id
|
|
messages = await ChatMessage.get_all_by_chat(chat.id)
|
|
return messages[-1].id if messages else None
|
|
|
|
|
|
async def _get_chat_context_usage(chat, model_id: str | None = None) -> dict | None:
|
|
message_id = await _get_context_leaf_message_id(chat)
|
|
if not message_id:
|
|
return None
|
|
|
|
from cptr.utils.chat_task import _load_message_history, _load_system_prompt
|
|
from cptr.utils.context import (
|
|
build_context_usage,
|
|
estimate_context_usage,
|
|
estimate_messages_tokens,
|
|
load_compact_token_threshold,
|
|
)
|
|
|
|
messages, existing_summary = await _load_message_history(chat.id, message_id)
|
|
workspace = (chat.meta or {}).get("workspace", "")
|
|
model = model_id or await _infer_chat_model(chat.id)
|
|
compact_token_threshold = await load_compact_token_threshold(model)
|
|
system = await _load_system_prompt(workspace, model or "", user_id=chat.user_id)
|
|
if existing_summary:
|
|
system += f"\n\n[CONVERSATION SUMMARY]\n{existing_summary}"
|
|
|
|
usage_checkpoint = await _get_latest_usage_checkpoint(chat.id, message_id)
|
|
if usage_checkpoint:
|
|
trailing_messages, usage = usage_checkpoint
|
|
tokens = usage.get("input_tokens")
|
|
if isinstance(tokens, int) and tokens > 0:
|
|
tokens += usage.get("output_tokens", 0)
|
|
if trailing_messages:
|
|
tokens += estimate_messages_tokens(
|
|
[{"role": m.role, "content": m.content or ""} for m in trailing_messages]
|
|
)
|
|
return build_context_usage(
|
|
tokens, threshold=compact_token_threshold, source="estimated"
|
|
)
|
|
|
|
return estimate_context_usage(messages, system, threshold=compact_token_threshold)
|
|
|
|
|
|
async def _infer_chat_model(chat_id: str) -> str:
|
|
messages = await ChatMessage.get_all_by_chat(chat_id)
|
|
for message in reversed(messages):
|
|
if message.model:
|
|
return message.model
|
|
return await Config.get("chat.default_model") or ""
|
|
|
|
|
|
async def _get_latest_usage_checkpoint(
|
|
chat_id: str, message_id: str
|
|
) -> tuple[list[ChatMessage], dict] | None:
|
|
all_msgs = await ChatMessage.get_all_by_chat(chat_id)
|
|
msg_map = {m.id: m for m in all_msgs}
|
|
chain = []
|
|
cur = msg_map.get(message_id)
|
|
while cur:
|
|
chain.append(cur)
|
|
cur = msg_map.get(cur.parent_id) if cur.parent_id else None
|
|
chain.reverse()
|
|
|
|
for index in range(len(chain) - 1, -1, -1):
|
|
message = chain[index]
|
|
if message.chat_summary:
|
|
return None
|
|
usage = message.usage or {}
|
|
if message.role == "assistant" and usage.get("input_tokens"):
|
|
return chain[index + 1 :], usage
|
|
return None
|
|
|
|
|
|
# ── Delete a chat ───────────────────────────────────────────
|
|
|
|
|
|
@router.delete("/{chat_id}")
|
|
async def delete_chat(chat_id: str, request: Request):
|
|
"""Delete a chat and all its messages."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
|
|
# Remove .cptr/chats/{id}.json marker
|
|
workspace = chat.meta.get("workspace", "") if chat.meta else ""
|
|
if workspace:
|
|
marker = Path(workspace) / ".cptr" / "chats" / f"{chat_id}.json"
|
|
await asyncio.to_thread(marker.unlink, True) # missing_ok=True
|
|
|
|
await Chat.delete(chat_id)
|
|
return {"ok": True}
|
|
|
|
|
|
# ── Send a message ──────────────────────────────────────────
|
|
|
|
|
|
class SendMessageRequest(BaseModel):
|
|
content: str = ""
|
|
model_id: str
|
|
workspace: str
|
|
chat_id: Optional[str] = None
|
|
parent_id: Optional[str] = None
|
|
regeneration_prompt: Optional[str] = None
|
|
files: List[dict] = []
|
|
params: dict = {}
|
|
|
|
|
|
class CompactRequest(BaseModel):
|
|
model_id: str
|
|
|
|
|
|
@router.post("")
|
|
async def send_message(body: SendMessageRequest, request: Request):
|
|
"""Send a message. Omit chat_id to create a new chat.
|
|
Returns: { chat_id, message_id, queued? }
|
|
"""
|
|
user_id = _get_user(request)
|
|
|
|
# Create or fetch chat
|
|
if body.chat_id:
|
|
chat = await Chat.get_by_id(body.chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
# Sync params into chat meta
|
|
if chat.meta is None:
|
|
chat.meta = {}
|
|
if chat.meta.get("params") != body.params or chat.meta.get("last_model") != body.model_id:
|
|
chat.meta["params"] = body.params
|
|
chat.meta["last_model"] = body.model_id
|
|
await Chat.update_meta(chat.id, chat.meta)
|
|
else:
|
|
title = body.content[:50].strip() or "New Chat"
|
|
chat = await Chat.create(
|
|
user_id=user_id,
|
|
title=title,
|
|
meta={
|
|
"workspace": body.workspace,
|
|
"params": body.params,
|
|
"last_model": body.model_id,
|
|
},
|
|
created_at=now_ms(),
|
|
)
|
|
# Ensure .cptr/chats/ dir exists
|
|
chats_dir = Path(body.workspace) / ".cptr" / "chats"
|
|
await asyncio.to_thread(lambda: chats_dir.mkdir(parents=True, exist_ok=True))
|
|
|
|
# Auto-add .cptr to .gitignore if this is a git repo
|
|
await asyncio.to_thread(ensure_cptr_gitignored, body.workspace)
|
|
|
|
# Resolve connection for model
|
|
connection, bare_model = await _resolve_connection(body.model_id, request.app.state)
|
|
|
|
from cptr.utils.chat_task import (
|
|
get_pending_input_lock,
|
|
process_pending_chat_inputs,
|
|
start_task,
|
|
)
|
|
|
|
queued_msg = None
|
|
user_msg = None
|
|
assistant_msg = None
|
|
async with get_pending_input_lock(chat.id):
|
|
# Queue only follow-ups attached to their own unfinished assistant branch.
|
|
# Other branches in the same chat are independent and can run concurrently.
|
|
parent_msg = await ChatMessage.get_by_id(body.parent_id) if body.parent_id else None
|
|
if body.chat_id and _should_queue_for_parent(parent_msg):
|
|
queued_meta = {"queued": True}
|
|
if body.files:
|
|
queued_meta["files"] = body.files
|
|
queued_msg = await ChatMessage.create(
|
|
chat_id=chat.id,
|
|
role="user",
|
|
content=body.content,
|
|
parent_id=body.parent_id,
|
|
model=body.model_id,
|
|
meta=queued_meta,
|
|
created_at=now_ms(),
|
|
)
|
|
else:
|
|
if parent_msg and parent_msg.role == "user":
|
|
# Regeneration: create assistant as sibling of existing response.
|
|
assistant_parent = body.parent_id
|
|
else:
|
|
user_meta = {"files": body.files} if body.files else None
|
|
user_msg = await ChatMessage.create(
|
|
chat_id=chat.id,
|
|
role="user",
|
|
content=body.content,
|
|
parent_id=body.parent_id,
|
|
meta=user_meta,
|
|
created_at=now_ms(),
|
|
)
|
|
assistant_parent = user_msg.id
|
|
|
|
assistant_msg = await ChatMessage.create(
|
|
chat_id=chat.id,
|
|
role="assistant",
|
|
content="",
|
|
parent_id=assistant_parent,
|
|
model=body.model_id,
|
|
done=False,
|
|
created_at=now_ms(),
|
|
)
|
|
|
|
# Update chat pointer to new leaf while still holding the input lock.
|
|
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
|
|
|
|
if queued_msg:
|
|
workspace = (chat.meta or {}).get("workspace", body.workspace)
|
|
await process_pending_chat_inputs(chat.id, user_id, workspace)
|
|
return {"chat_id": chat.id, "message_id": queued_msg.id, "queued": True}
|
|
|
|
if not assistant_msg:
|
|
raise HTTPException(500, "failed to create assistant message")
|
|
|
|
# Export JSON immediately so list_chats discovers it right away
|
|
from cptr.utils.chat_export import export_chat_to_file
|
|
|
|
await export_chat_to_file(chat.id)
|
|
|
|
start_task(
|
|
message_id=assistant_msg.id,
|
|
chat_id=chat.id,
|
|
user_id=user_id,
|
|
connection=connection,
|
|
workspace=body.workspace,
|
|
model=bare_model,
|
|
regeneration_prompt=body.regeneration_prompt,
|
|
)
|
|
|
|
# Return the created messages so the frontend can append them
|
|
# directly — no separate GET needed, no client-side construction.
|
|
resp: dict = {
|
|
"chat_id": chat.id,
|
|
"message_id": assistant_msg.id,
|
|
"assistant_message": _message_dict(assistant_msg),
|
|
}
|
|
if parent_msg is None or parent_msg.role != "user":
|
|
resp["user_message"] = _message_dict(user_msg)
|
|
return resp
|
|
|
|
|
|
# ── Manual context compaction ───────────────────────────────
|
|
|
|
|
|
@router.post("/{chat_id}/compact")
|
|
async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
|
|
"""Summarize older active-branch messages and store a compaction checkpoint."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
if await _chat_has_active_generation(chat_id):
|
|
raise HTTPException(409, "wait for the current response to finish before compacting")
|
|
|
|
message_id = await _get_context_leaf_message_id(chat)
|
|
if not message_id:
|
|
return {"ok": True, "compacted": False, "reason": "empty", "context_usage": None}
|
|
current_msg = await ChatMessage.get_by_id(message_id)
|
|
if not current_msg or not current_msg.parent_id:
|
|
usage = await _get_chat_context_usage(chat, body.model_id)
|
|
return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage}
|
|
|
|
connection, bare_model = await _resolve_connection(body.model_id, request.app.state)
|
|
|
|
from cptr.utils.chat_task import _load_message_history
|
|
from cptr.utils.summarize import summarize_messages
|
|
|
|
messages, existing_summary = await _load_message_history(chat_id, current_msg.parent_id)
|
|
if not messages:
|
|
usage = await _get_chat_context_usage(chat, body.model_id)
|
|
return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage}
|
|
|
|
provider = connection["provider"]
|
|
api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret())
|
|
from cptr.utils.chat_task import _default_base_url
|
|
|
|
base_url = connection.get("base_url") or _default_base_url(provider)
|
|
api_type = connection.get("api_type", "chat_completions")
|
|
|
|
summary = await summarize_messages(
|
|
messages,
|
|
existing_summary,
|
|
provider,
|
|
base_url,
|
|
api_key,
|
|
bare_model,
|
|
api_type=api_type,
|
|
)
|
|
await ChatMessage.update(message_id, chat_summary=summary)
|
|
|
|
from cptr.utils.chat_export import export_chat_to_file
|
|
|
|
await export_chat_to_file(chat_id)
|
|
usage = await _get_chat_context_usage(chat, body.model_id)
|
|
return {
|
|
"ok": True,
|
|
"compacted": True,
|
|
"dropped_messages": len(messages),
|
|
"kept_messages": 1,
|
|
"summary_chars": len(summary),
|
|
"context_usage": usage,
|
|
}
|
|
|
|
|
|
# ── Approve / reject a pending tool call ────────────────────
|
|
|
|
|
|
class ApproveRequest(BaseModel):
|
|
call_id: str
|
|
approved: bool = True
|
|
|
|
|
|
@router.post("/{chat_id}/messages/{message_id}/approve")
|
|
async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, request: Request):
|
|
"""Execute or reject a pending tool call, then continue."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
|
|
msg = await ChatMessage.get_by_id(message_id)
|
|
if not msg or msg.chat_id != chat_id:
|
|
raise HTTPException(404, "message not found")
|
|
|
|
# Find pending tool call
|
|
output = msg.output or []
|
|
call = None
|
|
for item in output:
|
|
if (
|
|
item.get("type") == "function_call"
|
|
and item.get("call_id") == body.call_id
|
|
and item.get("status") == "pending"
|
|
):
|
|
call = item
|
|
break
|
|
|
|
if not call:
|
|
raise HTTPException(400, "no pending tool call with that call_id")
|
|
|
|
if body.approved:
|
|
# Execute the tool
|
|
from cptr.utils.tools import execute_tool
|
|
|
|
model_id = msg.model or ""
|
|
result = await execute_tool(
|
|
call["name"],
|
|
call.get("arguments", {}),
|
|
{"workspace": chat.meta.get("workspace", ""), "user_id": user_id, "model_id": model_id},
|
|
)
|
|
call["status"] = "completed"
|
|
output.append(
|
|
{
|
|
"type": "function_call_output",
|
|
"call_id": body.call_id,
|
|
"output": result,
|
|
}
|
|
)
|
|
|
|
# Emit artifact card if the tool produced an artifact
|
|
from cptr.utils.chat_task import build_artifact_item, build_image_item
|
|
|
|
artifact_item = build_artifact_item(call["name"], call.get("arguments", {}), result)
|
|
if artifact_item:
|
|
output.append(artifact_item)
|
|
from cptr.socket.main import emit_to_user
|
|
|
|
await emit_to_user(
|
|
user_id,
|
|
{"chat_id": chat_id, "message_id": message_id, "output": artifact_item},
|
|
)
|
|
|
|
image_item = build_image_item(call["name"], result)
|
|
if image_item:
|
|
output.append(image_item)
|
|
from cptr.socket.main import emit_to_user
|
|
|
|
await emit_to_user(
|
|
user_id,
|
|
{"chat_id": chat_id, "message_id": message_id, "output": image_item},
|
|
)
|
|
|
|
await ChatMessage.update(message_id, output=output, done=False)
|
|
|
|
# Resolve connection and continue
|
|
connection, bare_model = await _resolve_connection(model_id, request.app.state)
|
|
workspace = chat.meta.get("workspace", "") if chat.meta else ""
|
|
|
|
from cptr.utils.chat_task import start_task
|
|
|
|
start_task(
|
|
message_id=message_id,
|
|
chat_id=chat_id,
|
|
user_id=user_id,
|
|
connection=connection,
|
|
workspace=workspace,
|
|
model=bare_model,
|
|
)
|
|
else:
|
|
call["status"] = "rejected"
|
|
await ChatMessage.update(message_id, output=output, done=True)
|
|
# Process pending inputs since this chat is now idle.
|
|
from cptr.utils.chat_task import process_pending_chat_inputs
|
|
|
|
workspace = chat.meta.get("workspace", "") if chat.meta else ""
|
|
await process_pending_chat_inputs(chat_id, user_id, workspace)
|
|
|
|
return {"ok": True}
|
|
|
|
|
|
# ── Cancel a running task ───────────────────────────────────
|
|
|
|
|
|
@router.post("/{chat_id}/messages/{message_id}/cancel")
|
|
async def cancel_task_endpoint(chat_id: str, message_id: str, request: Request):
|
|
"""Cancel running task, preserve partial output."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
|
|
from cptr.utils.chat_task import cancel_task
|
|
|
|
found = await cancel_task(message_id)
|
|
|
|
if not found:
|
|
# Task already exited (e.g., waiting for tool approval) but message
|
|
# may still be marked done=False, force-finalize it.
|
|
msg = await ChatMessage.get_by_id(message_id)
|
|
if msg and not msg.done:
|
|
output = msg.output or []
|
|
for item in output:
|
|
if item.get("type") == "function_call" and item.get("status") == "pending":
|
|
item["status"] = "rejected"
|
|
await ChatMessage.update(message_id, output=output, done=True)
|
|
|
|
# Process pending inputs since this chat may now be idle.
|
|
from cptr.utils.chat_task import process_pending_chat_inputs
|
|
|
|
workspace = chat.meta.get("workspace", "") if chat.meta else ""
|
|
await process_pending_chat_inputs(chat_id, user_id, workspace)
|
|
|
|
return {"ok": True}
|
|
|
|
|
|
# ── Update current branch pointer ──────────────────────────
|
|
|
|
|
|
class UpdateCurrentRequest(BaseModel):
|
|
message_id: str
|
|
|
|
|
|
@router.post("/{chat_id}/current")
|
|
async def update_current(chat_id: str, body: UpdateCurrentRequest, request: Request):
|
|
"""Set current_message_id (the active branch leaf)."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
await Chat.update_current_message(chat_id, body.message_id, now_ms())
|
|
return {"ok": True}
|
|
|
|
|
|
# ── Update message content / output ────────────────────────
|
|
|
|
|
|
class UpdateMessageRequest(BaseModel):
|
|
content: Optional[str] = None
|
|
output: Optional[list] = None
|
|
|
|
|
|
@router.patch("/{chat_id}/messages/{message_id}")
|
|
async def update_message(
|
|
chat_id: str, message_id: str, body: UpdateMessageRequest, request: Request
|
|
):
|
|
"""Edit a message's content or output in-place."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
|
|
updates = {}
|
|
if body.content is not None:
|
|
updates["content"] = body.content
|
|
if body.output is not None:
|
|
updates["output"] = body.output
|
|
if updates:
|
|
await ChatMessage.update(message_id, **updates)
|
|
return {"ok": True}
|
|
|
|
|
|
# ── Create message directly (no task) ──────────────────────
|
|
|
|
|
|
class CreateMessageRequest(BaseModel):
|
|
parent_id: Optional[str] = None
|
|
role: str
|
|
content: str
|
|
output: Optional[list] = None
|
|
|
|
|
|
@router.post("/{chat_id}/messages")
|
|
async def create_message_endpoint(chat_id: str, body: CreateMessageRequest, request: Request):
|
|
"""Create a message without starting a task (for Save As Copy)."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
|
|
msg = await ChatMessage.create(
|
|
chat_id=chat_id,
|
|
role=body.role,
|
|
content=body.content,
|
|
parent_id=body.parent_id,
|
|
output=body.output,
|
|
done=True,
|
|
created_at=now_ms(),
|
|
)
|
|
await Chat.update_current_message(chat_id, msg.id, now_ms())
|
|
return {"ok": True, "message_id": msg.id}
|
|
|
|
|
|
async def _chat_has_active_generation(chat_id: str) -> bool:
|
|
"""Check if any assistant message in this chat has done=False."""
|
|
messages = await ChatMessage.get_all_by_chat(chat_id)
|
|
return any(m.role == "assistant" and not m.done for m in messages)
|
|
|
|
|
|
def _should_queue_for_parent(parent_msg: ChatMessage | None) -> bool:
|
|
return bool(parent_msg and parent_msg.role == "assistant" and not parent_msg.done)
|
|
|
|
|
|
# ── Queue management ───────────────────────────────────────
|
|
|
|
|
|
@router.post("/{chat_id}/queue/{message_id}/send")
|
|
async def queue_send_now(chat_id: str, message_id: str, request: Request):
|
|
"""Dequeue one message and send it immediately on its stored branch."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
|
|
msg = await ChatMessage.get_by_id(message_id)
|
|
if not msg or msg.chat_id != chat_id:
|
|
raise HTTPException(404, "message not found")
|
|
if not (msg.meta and msg.meta.get("queued")):
|
|
raise HTTPException(400, "message is not queued")
|
|
|
|
from cptr.utils.chat_task import cancel_task, get_pending_input_lock, start_task
|
|
|
|
async with get_pending_input_lock(chat_id):
|
|
all_msgs = await ChatMessage.get_all_by_chat(chat_id)
|
|
parent_msg = next((m for m in all_msgs if m.id == msg.parent_id), None)
|
|
if parent_msg and parent_msg.role == "assistant" and not parent_msg.done:
|
|
await cancel_task(parent_msg.id)
|
|
await ChatMessage.update(parent_msg.id, done=True)
|
|
parent_msg.done = True
|
|
|
|
# Clear queued flag on this message
|
|
meta = dict(msg.meta or {})
|
|
meta.pop("queued", None)
|
|
await ChatMessage.update(message_id, meta=meta or None)
|
|
|
|
# Resolve connection and start task
|
|
model_id = msg.model or (chat.meta or {}).get("last_model", "")
|
|
if not model_id:
|
|
model_id = next((m.model for m in reversed(all_msgs) if m.model), "")
|
|
connection, bare_model = await _resolve_connection(model_id, request.app.state)
|
|
workspace = (chat.meta or {}).get("workspace", "")
|
|
meta_for_model = dict(chat.meta or {})
|
|
if meta_for_model.get("last_model") != model_id:
|
|
meta_for_model["last_model"] = model_id
|
|
await Chat.update_meta(chat.id, meta_for_model, now_ms())
|
|
|
|
assistant_msg = await ChatMessage.create(
|
|
chat_id=chat_id,
|
|
role="assistant",
|
|
content="",
|
|
parent_id=message_id,
|
|
model=model_id,
|
|
done=False,
|
|
created_at=now_ms(),
|
|
)
|
|
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
|
|
|
|
start_task(
|
|
message_id=assistant_msg.id,
|
|
chat_id=chat_id,
|
|
user_id=user_id,
|
|
connection=connection,
|
|
workspace=workspace,
|
|
model=bare_model,
|
|
)
|
|
return {"ok": True, "chat_id": chat_id, "message_id": assistant_msg.id}
|
|
|
|
|
|
@router.delete("/{chat_id}/queue/{message_id}")
|
|
async def queue_delete(chat_id: str, message_id: str, request: Request):
|
|
"""Remove a queued message."""
|
|
user_id = _get_user(request)
|
|
chat = await Chat.get_by_id(chat_id)
|
|
if not chat or chat.user_id != user_id:
|
|
raise HTTPException(404, "chat not found")
|
|
|
|
msg = await ChatMessage.get_by_id(message_id)
|
|
if not msg or msg.chat_id != chat_id:
|
|
raise HTTPException(404, "message not found")
|
|
if not (msg.meta and msg.meta.get("queued")):
|
|
raise HTTPException(400, "message is not queued")
|
|
|
|
await ChatMessage.delete(message_id)
|
|
return {"ok": True}
|
|
|
|
|
|
async def _resolve_connection(model_id: str, app_state=None) -> tuple[dict, str]:
|
|
"""Find connection for model.
|
|
'openrouter/gpt-4o' → connection with prefix_id='openrouter', bare model='gpt-4o'
|
|
'claude-sonnet-4-20250514' → scan all connections for match
|
|
Raises 400 if not found.
|
|
"""
|
|
connections = [c for c in await _get_connections() if c.get("enabled", True)]
|
|
if not connections:
|
|
raise HTTPException(400, "no connections configured")
|
|
|
|
# Try prefix match first
|
|
if "/" in model_id:
|
|
prefix, bare = model_id.split("/", 1)
|
|
for conn in connections:
|
|
if (conn.get("prefix_id") or "").strip() == prefix:
|
|
return conn, bare
|
|
|
|
# Scan all connections using cache
|
|
for conn in connections:
|
|
if app_state:
|
|
model_ids = await _get_connection_models(conn, app_state)
|
|
else:
|
|
model_ids = conn.get("data", {}).get("models") or await _fetch_provider_models(conn)
|
|
prefix = (conn.get("prefix_id") or "").strip()
|
|
for mid in model_ids:
|
|
prefixed = f"{prefix}/{mid}" if prefix else mid
|
|
if prefixed == model_id or mid == model_id:
|
|
return conn, mid
|
|
|
|
raise HTTPException(400, f"no connection found for model: {model_id}")
|