feat: City Rooms routing implementation

Backend:
- GET /api/v1/city/rooms - list all city rooms
- GET /api/v1/city/rooms/{slug} - get room by slug with host agents

Frontend:
- Updated /city/[slug] page with host agents section
- Added breadcrumb navigation
- Updated API client to fetch room by slug
- Added rewrite for /api/city/rooms/:slug

Task doc: TASK_PHASE_CITY_ROOMS_ROUTING_v1.md
This commit is contained in:
Apple
2025-11-30 10:54:39 -08:00
parent 36394cff55
commit 85fdcdf0be
5 changed files with 440 additions and 14 deletions

View File

@@ -36,6 +36,11 @@ const nextConfig: NextConfig = {
source: '/api/public/:path*',
destination: `${internalApiUrl}/public/:path*`,
},
// City Rooms API (specific slug endpoint) -> /api/v1/city/rooms
{
source: '/api/city/rooms/:slug',
destination: `${internalApiUrl}/api/v1/city/rooms/:slug`,
},
// City API -> /city
{
source: '/api/city/:path*',

View File

@@ -1,5 +1,5 @@
import Link from 'next/link'
import { ArrowLeft, Users, FileText, Clock, MessageCircle } from 'lucide-react'
import { ArrowLeft, Users, FileText, Clock, MessageCircle, Home, Bot } from 'lucide-react'
import { api, CityRoom } from '@/lib/api'
import { formatDate } from '@/lib/utils'
import { notFound } from 'next/navigation'
@@ -8,13 +8,28 @@ import { CityChatWidget } from '@/components/city/CityChatWidget'
// Force dynamic rendering - don't prerender at build time
export const dynamic = 'force-dynamic'
interface HostAgent {
id: string
display_name: string
avatar_url?: string
kind?: string
role: string
}
interface CityRoomDetail extends CityRoom {
host_agents?: HostAgent[]
chat_available?: boolean
scope?: string
room_role?: string
}
interface PageProps {
params: Promise<{ slug: string }>
}
async function getRoom(slug: string): Promise<CityRoom | null> {
async function getRoom(slug: string): Promise<CityRoomDetail | null> {
try {
return await api.getCityRoom(slug)
return await api.getCityRoom(slug) as CityRoomDetail
} catch (error) {
console.error('Failed to fetch room:', error)
return null
@@ -34,13 +49,18 @@ export default async function RoomPage({ params }: PageProps) {
{/* Header */}
<div className="px-4 py-6 border-b border-white/5">
<div className="max-w-6xl mx-auto">
<Link
href="/city"
className="inline-flex items-center gap-2 text-slate-400 hover:text-white transition-colors mb-4"
>
<ArrowLeft className="w-4 h-4" />
Назад до кімнат
</Link>
{/* Breadcrumb */}
<nav className="flex items-center gap-2 text-sm mb-4">
<Link href="/" className="text-slate-400 hover:text-white transition-colors">
<Home className="w-4 h-4" />
</Link>
<span className="text-slate-600">/</span>
<Link href="/city" className="text-slate-400 hover:text-white transition-colors">
City
</Link>
<span className="text-slate-600">/</span>
<span className="text-cyan-400">{room.name}</span>
</nav>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
@@ -94,6 +114,51 @@ export default async function RoomPage({ params }: PageProps) {
{/* Sidebar */}
<div className="space-y-6">
{/* Host Agents */}
{room.host_agents && room.host_agents.length > 0 && (
<div className="glass-panel p-6">
<h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<Bot className="w-5 h-5 text-violet-400" />
Агенти кімнати
</h3>
<div className="space-y-3">
{room.host_agents.map((agent) => (
<Link
key={agent.id}
href={`/agents/${agent.id}`}
className="flex items-center gap-3 p-3 rounded-lg bg-slate-800/50 hover:bg-slate-800 transition-colors group"
>
<div className="relative">
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-violet-500/30 to-purple-600/30 flex items-center justify-center overflow-hidden">
{agent.avatar_url ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={agent.avatar_url}
alt={agent.display_name}
className="w-full h-full object-cover"
/>
) : (
<Bot className="w-5 h-5 text-violet-400" />
)}
</div>
{/* Presence indicator */}
<span className="absolute bottom-0 right-0 w-3 h-3 rounded-full bg-gray-500 ring-2 ring-slate-900" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-white truncate group-hover:text-violet-400 transition-colors">
{agent.display_name}
</p>
<p className="text-xs text-slate-400 capitalize">
{agent.role} {agent.kind || 'agent'}
</p>
</div>
</Link>
))}
</div>
</div>
)}
{/* Room Info */}
<div className="glass-panel p-6">
<h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
@@ -102,8 +167,9 @@ export default async function RoomPage({ params }: PageProps) {
</h3>
<div className="space-y-4">
<InfoRow label="ID" value={room.id} />
<InfoRow label="Тип" value={room.scope || 'city'} />
<InfoRow label="Slug" value={room.slug} />
{room.room_role && <InfoRow label="Роль" value={room.room_role} />}
<InfoRow
label="Створено"
value={formatDate(room.created_at)}
@@ -122,7 +188,7 @@ export default async function RoomPage({ params }: PageProps) {
Учасники онлайн
</h3>
{room.members_online > 0 ? (
{room.members_online && room.members_online > 0 ? (
<div className="flex flex-wrap gap-2">
{Array.from({ length: Math.min(room.members_online, 8) }).map((_, i) => (
<div

View File

@@ -145,8 +145,16 @@ class ApiClient {
}
async getCityRoom(slug: string): Promise<CityRoom | null> {
const rooms = await this.getCityRooms()
return rooms.find(r => r.slug === slug) || null
try {
// Server-side: call backend directly, client-side: use proxy
const endpoint = typeof window === 'undefined'
? `/api/v1/city/rooms/${slug}`
: `/api/city/rooms/${slug}`
return await this.fetch<CityRoom>(endpoint)
} catch (error) {
console.error(`Failed to fetch city room ${slug}:`, error)
return null
}
}
// Second Me

View File

@@ -0,0 +1,272 @@
# TASK_PHASE_CITY_ROOMS_ROUTING_v1
Version: 1.0
Status: Ready
Priority: High (City Layer UX + Matrix Rooms)
---
# 1. МЕТА
Зробити так, щоб **кожна City Room** була доступною за URL:
- `/city` — огляд усіх кімнат
- `/city/{slug}` — сторінка конкретної кімнати
Сторінка кімнати має:
- завантажувати дані кімнати з backend (room meta + matrix_room_id),
- показувати присутніх агентів,
- інтегрувати чат (Matrix room),
- показувати presence агентів.
---
# 2. ВИХІДНІ ДАНІ
Вже є:
- Таблиця `rooms` з city-кімнатами (scope = 'city', 8+ кімнат).
- Поле `slug` або еквівалент (наприклад `city-general`, `city-welcome` тощо).
- `matrix_room_id` заповнене (Matrix sync завершений).
- Matrix Gateway та Chat API:
- `GET /api/v1/chat/rooms/{room_id}/messages`
- `POST /api/v1/chat/rooms/{room_id}/messages`
- Presence Layer:
- `GET /api/v1/agents/{agent_id}/presence`
- Frontend:
- базовий Chat Widget
- компонент PresenceDot
- карта /city вже існує (огляд кімнат).
---
# 3. SCOPE
1. Frontend routing для `/city/{slug}` (Next.js, App Router).
2. API-обгортка для завантаження City Room.
3. Сторінка кімнати:
- назва, опис, тип кімнати;
- список ключових агентів (host/moderators);
- presence-індикатори;
- чат-виджет, прив'язаний до room_id / matrix_room_id.
4. Обробка помилок:
- 404, якщо кімната не існує;
- fallback UI, якщо Matrix тимчасово недоступний.
---
# 4. МОДУЛЬ 1 — BACKEND (CITY-SERVICE) API (якщо ще немає)
Перевірити/додати в city-service:
## 4.1. GET /api/v1/city/rooms
Список всіх city-кімнат.
Вихід:
```json
[
{
"id": "uuid",
"slug": "city-general",
"name": "General",
"description": "Головна кімната міста",
"scope": "city",
"matrix_room_id": "!room:matrix.daarion.city",
"host_agents": ["agent_id_1", "agent_id_2"]
},
...
]
```
## 4.2. GET /api/v1/city/rooms/{slug}
Конкретна кімната за slug.
Вихід:
```json
{
"id": "uuid",
"slug": "city-general",
"name": "General",
"description": "Головна кімната міста",
"scope": "city",
"matrix_room_id": "!room:matrix.daarion.city",
"host_agents": [
{
"id": "agent_id_1",
"name": "DARIO",
"role": "host"
}
]
}
```
Якщо кімнати немає → 404.
---
# 5. МОДУЛЬ 2 — FRONTEND API КЛІЄНТ
В `apps/web/src/lib/api/city.ts` (або створити новий):
```ts
export async function getCityRooms(): Promise<CityRoomSummary[]> { ... }
export async function getCityRoomBySlug(slug: string): Promise<CityRoomDetail> { ... }
```
Де `CityRoomDetail` містить як мінімум:
- id
- slug
- name
- description
- matrixRoomId
- hostAgents[]
---
# 6. МОДУЛЬ 3 — ROUTING: `/city/{slug}`
У `apps/web/src/app/city/[slug]/page.tsx`:
1. Прочитати `params.slug`.
2. Викликати `getCityRoomBySlug(slug)`.
3. Якщо 404 → показати `notFound()` (Next.js).
4. Якщо інша помилка → показати error boundary / fallback.
---
# 7. МОДУЛЬ 4 — UI СТОРІНКИ КІМНАТИ
Макет сторінки `/city/{slug}`:
## 7.1. Верхня частина (header)
- Назва кімнати (`room.name`)
- Підназва / опис (`room.description`)
- Badge: `City Room`
- Breadcrumb: `City / {room.name}`
## 7.2. Блок "Host Agents"
Карточка(и) головних агентів кімнати:
- аватар
- ім'я
- роль (host/moderator)
- PresenceDot (online/away/offline)
- посилання "Перейти в кабінет агента"
Дані брати з `host_agents`.
## 7.3. Блок "Room Info" (опціонально)
- список тегів (public / governance / help / etc.)
- кількість учасників (якщо є)
## 7.4. Блок "Chat"
Використати Chat Widget, але прив'язати не до Agent/Node/MicroDAO, а до ROOM:
- якщо вже є універсальний `<AgentChatWidget>` з режимами entityType, можна:
- додати `entityType="room"`
- `entityId = room.id`
- якщо ні — створити `CityRoomChatWidget`, який:
- бере `room.id``/api/v1/chat/rooms/{room.id}/messages`
- дозволяє надсилати повідомлення в кімнату
Для неавторизованих:
- "Увійдіть, щоб писати у міську кімнату".
---
# 8. МОДУЛЬ 5 — ІНТЕГРАЦІЯ З /city
На сторінці `/city`:
- у списку/мапі кімнат:
- додати посилання на `/city/{slug}`.
- клік по кімнаті → відкриває `/city/{slug}`.
---
# 9. ОБРОБКА ПОМИЛОК
1. Якщо `/api/v1/city/rooms/{slug}` повертає 404:
- Next.js `notFound()` → стандартна 404-сторінка.
2. Якщо помилка backend (500):
- показати повідомлення "Кімната тимчасово недоступна".
3. Якщо немає `matrix_room_id`:
- показати банер "Matrix ще синхронізується, чат скоро з'явиться".
---
# 10. SMOKE-ТЕСТИ
Після завершення:
1. `/city`:
- список/мапа містить 8+ кімнат.
2. `/city/general`:
- сторінка відкривається;
- видно назву, опис;
- видно host-агентів (наприклад, DARIO/DARIA);
- видно presence.
3. `/city/welcome`, `/city/leadership-hall`, `/city/builders`, `/city/security`, `/city/announcements`:
- усі відкриваються без 404.
4. Chat:
- у кімнаті `/city/general` можливо:
- побачити історію повідомлень;
- відправити нове повідомлення (як авторизований користувач).
---
# 11. FINISH-АРТЕФАКТ
Після виконання Cursor створює:
`docs/debug/city_rooms_routing_report_<DATE>.md`
Зі змістом:
- список slug'ів city-кімнат;
- приклади успішних HTTP-викликів:
- `GET /api/v1/city/rooms`
- `GET /api/v1/city/rooms/{slug}`
- скріншот або опис перевірки `/city/{slug}`;
- підтвердження роботи чату в принаймні одній кімнаті.
---
# 12. PROMPT ДЛЯ CURSOR
```text
Виконай TASK_PHASE_CITY_ROOMS_ROUTING_v1.md.
Фокус:
1) Backend: /api/v1/city/rooms, /api/v1/city/rooms/{slug} (якщо ще немає)
2) Frontend: Next.js routing /city/[slug]
3) UI: сторінка кімнати (host agents, presence, chat)
4) Інтеграція з існуючими чат/Matrix/PRESENCE шарами
Після завершення створи:
docs/debug/city_rooms_routing_report_<DATE>.md
```
---
**Target Date**: Immediate
**Priority**: High
**Dependencies**: Matrix integration complete, Chat API working

View File

@@ -1048,6 +1048,81 @@ async def create_city_room(payload: CityRoomCreate):
raise HTTPException(status_code=500, detail="Failed to create city room")
@api_router.get("/city/rooms")
async def get_city_rooms_api():
"""
Отримати список всіх City Rooms для API.
"""
try:
rooms = await repo_city.get_all_rooms(limit=100, offset=0)
result = []
for room in rooms:
result.append({
"id": room.get("id"),
"slug": room.get("slug"),
"name": room.get("name"),
"description": room.get("description"),
"scope": room.get("owner_type", "city"),
"matrix_room_id": room.get("matrix_room_id"),
"is_public": room.get("is_public", True),
"room_role": room.get("room_role"),
})
return result
except Exception as e:
logger.error(f"Failed to get city rooms: {e}")
raise HTTPException(status_code=500, detail="Failed to get city rooms")
@api_router.get("/city/rooms/{slug}")
async def get_city_room_by_slug(slug: str):
"""
Отримати деталі City Room за slug.
"""
try:
room = await repo_city.get_room_by_slug(slug)
if not room:
raise HTTPException(status_code=404, detail=f"Room not found: {slug}")
# Get host agents for this room (public agents assigned to city rooms)
host_agents = []
try:
# Get DARIO and DARIA as default hosts for city rooms
default_hosts = ["dario", "daria", "daarwizz"]
for agent_id in default_hosts:
agent = await repo_city.get_agent_by_id(agent_id)
if agent:
host_agents.append({
"id": agent.get("id"),
"display_name": agent.get("display_name"),
"avatar_url": agent.get("avatar_url"),
"kind": agent.get("kind"),
"role": "host"
})
except Exception as e:
logger.warning(f"Failed to get host agents for room {slug}: {e}")
return {
"id": room.get("id"),
"slug": room.get("slug"),
"name": room.get("name"),
"description": room.get("description"),
"scope": room.get("owner_type", "city"),
"matrix_room_id": room.get("matrix_room_id"),
"matrix_room_alias": room.get("matrix_room_alias"),
"is_public": room.get("is_public", True),
"room_role": room.get("room_role"),
"host_agents": host_agents,
"chat_available": room.get("matrix_room_id") is not None
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to get city room by slug {slug}: {e}")
raise HTTPException(status_code=500, detail="Failed to get city room")
@router.get("/rooms/{room_id}", response_model=CityRoomDetail)
async def get_city_room(room_id: str):
"""