This commit is contained in:
Mikan
2026-06-19 19:14:27 +03:00
parent 2167493887
commit 32575e217e
23 changed files with 1191 additions and 92 deletions

View File

@@ -1,7 +1,7 @@
"""Glossary + Triggers routes."""
"""Glossary + Triggers + public UI settings routes."""
from __future__ import annotations
from typing import List
from typing import Any, Dict, List
from uuid import UUID
from sqlalchemy import select
@@ -11,12 +11,37 @@ from fastapi import APIRouter, Depends, HTTPException
from app.db import get_db_dep
from app.deps import get_current_user
from app.models import DeferredTrigger, GlossaryEntry, Session, User, World
from app.models import DeferredTrigger, GlossaryEntry, Session, Setting, User, World
from app.schemas import GlossaryEntryOut, TriggerOut
router = APIRouter(prefix="/api", tags=["misc"])
# Public, unauthenticated UI settings (logo URL etc.) — used by the frontend
# on the login/register/home pages BEFORE the user is authenticated, so the
# branding (logo, eventually theme) shows up everywhere.
#
# Only a curated subset of settings is exposed here. Anything sensitive (api
# keys, internal URLs, admin tokens) MUST stay behind /api/admin/settings.
PUBLIC_SETTING_KEYS = ("ui.logo_url",)
_PUBLIC_DEFAULTS: Dict[str, Any] = {"ui.logo_url": "/logo.png"}
@router.get("/settings/public")
async def get_public_settings(db: AsyncSession = Depends(get_db_dep)):
"""Return UI settings that are safe to expose without authentication.
Used by the frontend to render the logo (and other public branding) on
every page, including login/register. The response shape is a flat
`{key: value}` dict.
"""
out: Dict[str, Any] = dict(_PUBLIC_DEFAULTS)
rows = await db.execute(select(Setting).where(Setting.key.in_(PUBLIC_SETTING_KEYS)))
for row in rows.scalars().all():
out[row.key] = row.value
return out
@router.get("/worlds/{world_id}/glossary", response_model=List[GlossaryEntryOut])
async def list_glossary(
world_id: UUID,

View File

@@ -14,7 +14,7 @@ from sse_starlette.sse import EventSourceResponse
from app.db import get_db_dep
from app.deps import get_current_user
from app.engine.orchestrator import run_iteration
from app.engine.orchestrator import generate_intro_scene, run_iteration
from app.models import Message, Session, User, World
from app.schemas import IterationRequest, MessageOut, SessionCreate, SessionOut
@@ -142,6 +142,35 @@ async def iterate_session(
return EventSourceResponse(event_generator())
@router.post("/{session_id}/intro")
async def intro_session(
session_id: UUID,
db: AsyncSession = Depends(get_db_dep),
user: User = Depends(get_current_user),
):
"""SSE stream that generates the opening cinematic scene for a new session."""
result = await db.execute(
select(Session).join(World, Session.world_id == World.id).where(Session.id == session_id)
)
session = result.scalars().first()
if not session:
raise HTTPException(status_code=404, detail="session_not_found")
w_result = await db.execute(select(World).where(World.id == session.world_id))
world = w_result.scalars().first()
if not world or (world.owner_id != user.id and not user.is_admin):
raise HTTPException(status_code=403, detail="forbidden")
async def event_generator():
try:
async for event in generate_intro_scene(db=db, user_id=user.id, session_id=session_id):
yield {"event": event["type"], "data": json.dumps(event.get("data", {}), ensure_ascii=False, default=str)}
except Exception as e:
yield {"event": "error", "data": json.dumps({"message": str(e)}, ensure_ascii=False)}
yield {"event": "done", "data": "{}"}
return EventSourceResponse(event_generator())
@router.delete("/{session_id}", status_code=204)
async def delete_session(
session_id: UUID,

View File

@@ -12,6 +12,7 @@ from fastapi import APIRouter, Depends, HTTPException
from app.db import get_db_dep
from app.deps import get_current_user
from app.engine.world_builder import commit_world_builder, continue_world_builder, start_world_builder
from app.engine.world_editor import edit_world_via_chat, reset_editor_dialogue
from app.models import User, World
from app.schemas import (
WorldBuilderCommit,
@@ -19,6 +20,8 @@ from app.schemas import (
WorldBuilderReply,
WorldBuilderStart,
WorldCreate,
WorldEditorChatReply,
WorldEditorChatRequest,
WorldOut,
WorldUpdate,
)
@@ -159,3 +162,56 @@ async def builder_commit(
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"builder_commit_failed: {e}")
# === World Editor (AI-assisted editing of an existing world) ===
@router.post("/{world_id}/chat", response_model=WorldEditorChatReply)
async def world_editor_chat(
world_id: UUID,
payload: WorldEditorChatRequest,
db: AsyncSession = Depends(get_db_dep),
user: User = Depends(get_current_user),
):
"""Chat with the AI to edit an existing world's definition.
Returns the AI's prose reply plus the proposed new definition. The
frontend must call PATCH /worlds/{id} to actually persist the change.
"""
result = await db.execute(select(World).where(World.id == world_id))
world = result.scalars().first()
if not world:
raise HTTPException(status_code=404, detail="world_not_found")
if world.owner_id != user.id and not user.is_admin:
raise HTTPException(status_code=403, detail="forbidden")
try:
ai_message, new_defn, changed = await edit_world_via_chat(
db=db, user=user, world=world, message=payload.message,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"world_editor_chat_failed: {e}")
return WorldEditorChatReply(
ai_message=ai_message,
definition=new_defn,
changed=changed,
)
@router.post("/{world_id}/chat/reset")
async def world_editor_chat_reset(
world_id: UUID,
db: AsyncSession = Depends(get_db_dep),
user: User = Depends(get_current_user),
):
"""Clear the cached editor dialogue for a world (start fresh)."""
result = await db.execute(select(World).where(World.id == world_id))
world = result.scalars().first()
if not world:
raise HTTPException(status_code=404, detail="world_not_found")
if world.owner_id != user.id and not user.is_admin:
raise HTTPException(status_code=403, detail="forbidden")
reset_editor_dialogue(world_id)
return {"ok": True}