feat(rpg): Phase 1 — pixel art office + 페이지 5개 통합 + replan 마커

자기야 요청: 픽셀 RPG 스타일 (deskrpg/openclaw-office 분위기) 의 가상
사무실로 대시보드 메인 리뉴얼. 페이지 너무 많은 거 줄이고 office 를 메인
기능으로 승격. rails 페이지에 재기획 (replan) 시각적 표시 추가.

## Phase 1 (이번 세션) 범위

### Office RPG (Phaser 3 + procedural pixel art)
- frontend/components/office-rpg/ 신설
- spriteFactory.ts: 16x16 floor/wall/carpet/desk/chair 타일 + 16x24 자매
  캐릭터 sprite 4 명 (harang/narang/darang/erang) 자매별 색상. 모두 코드로
  procedural 생성 (외부 asset 0, 라이선스 문제 0)
- OfficeScene.ts: 16x12 tile layout (벽/바닥/4 책상/회의실/문). 자매 sprite
  가 각 책상에 idle (2-frame breathing), 클릭 가능
- PhaserHost.tsx: Next.js dynamic import (ssr:false), Phaser 4 namespace
  import. Camera zoom 3x 픽셀 perfect 렌더링
- OfficeRpg.tsx: React wrapper. 좌측 PhaserHost + 우측 SisterDetailPanel
  slide-in
- SisterDetailPanel.tsx: 자매 클릭 시 SisterAvatar 사진 + 역할 + 상태 표시

### 메인 페이지 리뉴얼 (1242 줄 → 50 줄)
- app/page.tsx 를 office-first 로 교체. 헤더 한 줄 + OfficeRpg + 최근
  파이프라인 strip
- ActivePipelineStrip.tsx 신설: 최근 8 개 파이프라인 카드, 5초 polling

### 페이지 19 → 5 통합
- 삭제: app/projects, app/sisters, app/activities, app/org, app/office,
  app/admin/*, app/rails/log, app/rails/escalations
- 유지: app/page (=office), app/rails (=파이프라인 + 통합 timeline),
  app/settings, app/login, app/register
- Sidebar 메뉴: 11 → 3 (사무실 / 레일 / 설정)

### Rails 페이지 — TransitionsTimeline + replan 마커
- TransitionsTimeline.tsx 신설: 파이프라인의 모든 state transitions 를
  세로 타임라인으로. 4초 polling. 통계 배지 (전이 수, review loop ×N,
  ↑ 재기획 ×N, 🚨 escalated)
- reviewing → planning 전이는 빨간 "↑ 재기획" 마커 + 빨간 도트
- escalated 전이는 노란 "🚨 escalated" 마커
- 일반 전이는 파란 도트

### 의존성
- + phaser 4.0.0

## 다음 phase 계획

Phase 2 (다음 세션):
- Walk animation (4 방향)
- Stage handoff: narang sprite 가 darang 책상으로 walk over
- Active pipeline 이 office 위 floating bubble 로
- 클릭으로 rails drawer

Phase 3 (그 후):
- 사용자 본인 아바타 (자기야 캐릭터)
- 회의실 인터랙션
- 채팅 통합

## 빌드 결과
build clean. 8 routes (/, /login, /rails, /register, /settings, /_not-found,
favicon, robots).
This commit is contained in:
2026-04-11 04:30:45 +09:00
parent 9addaba626
commit 9a17f65419
27 changed files with 1578 additions and 4264 deletions

View File

@@ -1,311 +0,0 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { PageTitle, BtnToggle } from '@/components/ui/base';
import { API_URL } from '@/lib/config';
// ─── Styled ───
const Header = styled.div`
display: flex;
justify-content: space-between;
align-items: flex-end;
border-bottom: 1px solid var(--border-color);
padding-bottom: var(--space-md);
margin-bottom: var(--space-md);
`;
const HeaderMeta = styled.div`
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
`;
const LogControls = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
gap: var(--space-lg);
margin-bottom: var(--space-md);
flex-wrap: wrap;
`;
const FilterGroup = styled.div`
display: flex;
gap: var(--space-md);
flex-wrap: wrap;
`;
const SearchBox = styled.div`
position: relative;
flex-grow: 1;
max-width: 300px;
`;
const SearchInput = styled.input`
width: 100%;
background: #1a1a1a;
border: 1px solid var(--border-color);
color: var(--text-primary);
padding: 8px 12px;
font-family: var(--font-mono);
font-size: 12px;
outline: none;
&:focus { border-color: var(--border-hover); }
&::placeholder { color: var(--text-secondary); }
`;
const LogContainer = styled.div`
border: 1px solid var(--border-color);
background: #0d0d0d;
font-family: var(--font-mono);
overflow-x: auto;
`;
const LogTable = styled.table`
width: 100%;
border-collapse: collapse;
`;
const Th = styled.th`
text-align: left;
padding: 10px 12px;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-secondary);
border-bottom: 1px solid var(--border-color);
white-space: nowrap;
`;
const Tr = styled.tr`
&:hover td { background: #1a1a1a; }
border-bottom: 1px solid #1a1a1a;
`;
const Td = styled.td`
padding: 10px 12px;
font-size: 12px;
color: var(--text-secondary);
vertical-align: top;
`;
const TdTime = styled(Td)`
white-space: nowrap;
font-size: 11px;
`;
const TdEvent = styled(Td)`
color: var(--text-primary);
`;
const Tag = styled.span<{ $type: string }>`
display: inline-block;
padding: 2px 6px;
font-size: 9px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
background: #1a1a1a;
border: 1px solid;
white-space: nowrap;
${({ $type }) => {
switch ($type) {
case 'SECURITY': return 'color: #ff5f5f; border-color: #ff5f5f44;';
case 'ORG': return 'color: #5fafff; border-color: #5fafff44;';
case 'BACKUP': return 'color: #5fff8a; border-color: #5fff8a44;';
default: return 'color: #888; border-color: #44444444;';
}
}}
`;
const BracketLabel = styled.span`
color: var(--text-primary);
font-weight: 600;
`;
const Pagination = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
padding: var(--space-md);
border-top: 1px solid var(--border-color);
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
`;
const PaginationBtns = styled.div`
display: flex;
gap: var(--space-sm);
`;
const PageBtn = styled.button<{ $active?: boolean }>`
background: ${({ $active }) => $active ? 'var(--text-primary)' : 'transparent'};
border: 1px solid var(--border-color);
color: ${({ $active }) => $active ? '#000' : 'var(--text-secondary)'};
padding: 4px 10px;
font-size: 11px;
cursor: pointer;
font-family: var(--font-mono);
transition: all 0.15s;
&:hover {
border-color: var(--border-hover);
color: ${({ $active }) => $active ? '#000' : 'var(--text-primary)'};
}
`;
// ─── Tag helpers ───
function getTagType(action: string): string {
if (/security|auth|key|guard|block/i.test(action)) return 'SECURITY';
if (/org|sister|node|role/i.test(action)) return 'ORG';
if (/backup|snapshot|save/i.test(action)) return 'BACKUP';
return 'SYSTEM';
}
function formatDetail(detail: string | null, action: string): React.ReactNode {
if (!detail) return action;
// bracket [텍스트] 하이라이트
const parts = detail.split(/(\[.*?\])/g);
return parts.map((part, i) =>
part.startsWith('[') ? <BracketLabel key={i}>{part}</BracketLabel> : part,
);
}
const PAGE_SIZE = 20;
const ALL_TYPES = ['ALL', 'SYSTEM', 'SECURITY', 'ORG', 'BACKUP'];
interface ActivityItem {
id: number;
action: string;
detail: string | null;
createdAt: string;
sister?: { name: string } | null;
project?: { name: string } | null;
}
export default function ActivitiesPage() {
const [items, setItems] = useState<ActivityItem[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(0);
const [filter, setFilter] = useState('ALL');
const [search, setSearch] = useState('');
useEffect(() => {
const load = async () => {
try {
const res = await fetch(`${API_URL}/api/activity?limit=200&offset=0`);
if (res.ok) {
const d = await res.json();
setItems(d.items ?? []);
setTotal(d.total ?? 0);
}
} catch { /* silent */ }
};
load();
const iv = setInterval(load, 30000);
return () => clearInterval(iv);
}, []);
const filtered = items.filter((item) => {
const tagType = getTagType(item.action);
if (filter !== 'ALL' && tagType !== filter) return false;
if (search) {
const q = search.toLowerCase();
const text = `${item.action} ${item.detail ?? ''} ${item.sister?.name ?? ''}`.toLowerCase();
if (!text.includes(q)) return false;
}
return true;
});
const totalPages = Math.ceil(filtered.length / PAGE_SIZE);
const paged = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
const runtimeStr = (() => {
return `SYS_LOG_V.4.2 // ENTRIES: ${total}`;
})();
return (
<>
<Header>
<PageTitle>
<span style={{ color: 'var(--text-secondary)', fontSize: '18px' }}>/ ACTIVITY LOG</span>
</PageTitle>
<HeaderMeta>{runtimeStr}</HeaderMeta>
</Header>
<LogControls>
<FilterGroup>
{ALL_TYPES.map((t) => (
<BtnToggle key={t} $active={filter === t} onClick={() => { setFilter(t); setPage(0); }}>
{t}
</BtnToggle>
))}
</FilterGroup>
<SearchBox>
<SearchInput
placeholder="SEARCH LOGS..."
value={search}
onChange={(e) => { setSearch(e.target.value); setPage(0); }}
/>
</SearchBox>
</LogControls>
<LogContainer>
<LogTable>
<thead>
<tr>
<Th>TIME</Th>
<Th>TYPE</Th>
<Th>EVENT</Th>
<Th>CODE</Th>
</tr>
</thead>
<tbody>
{paged.length === 0 ? (
<Tr>
<Td colSpan={4} style={{ textAlign: 'center', padding: 'var(--space-xl)', color: 'var(--text-secondary)' }}>
</Td>
</Tr>
) : (
paged.map((item) => {
const tagType = getTagType(item.action);
const code = `0x${item.id.toString(16).toUpperCase().padStart(3, '0')}`;
return (
<Tr key={item.id}>
<TdTime>
{new Date(item.createdAt).toLocaleString('ko-KR', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false,
})}
</TdTime>
<Td><Tag $type={tagType}>{tagType}</Tag></Td>
<TdEvent>{formatDetail(item.detail, item.action)}</TdEvent>
<Td style={{ fontFamily: 'var(--font-mono)', fontSize: '11px' }}>{code}</Td>
</Tr>
);
})
)}
</tbody>
</LogTable>
<Pagination>
<span>SHOWING {paged.length} / {filtered.length} ENTRIES</span>
<PaginationBtns>
<PageBtn onClick={() => setPage((p) => Math.max(0, p - 1))} disabled={page === 0}>PREV</PageBtn>
{Array.from({ length: Math.min(totalPages, 5) }, (_, i) => (
<PageBtn key={i} $active={page === i} onClick={() => setPage(i)}>{i + 1}</PageBtn>
))}
{totalPages > 5 && <span>...</span>}
<PageBtn onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))} disabled={page >= totalPages - 1}>NEXT</PageBtn>
</PaginationBtns>
</Pagination>
</LogContainer>
</>
);
}

View File

@@ -1,230 +0,0 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import BarChart from '@/components/admin/BarChart';
import { adminFetch } from '@/lib/adminFetch';
type Period = 'day' | 'week' | 'month';
interface CostData {
period: string;
since: string;
summary: {
totalTokens: number;
inputTokens: number;
outputTokens: number;
estimatedUsd: number;
recordCount: number;
};
bySister: Array<{ name: string; totalTokens: number; estimatedUsd: number }>;
byModel: Array<{ model: string; totalTokens: number; estimatedUsd: number; count: number }>;
timeline: Array<{ date: string; totalTokens: number; estimatedUsd: number }>;
}
const Controls = styled.div`
display: flex;
gap: 8px;
margin-bottom: 24px;
`;
const PeriodBtn = styled.button<{ $active: boolean }>`
padding: 6px 16px;
border-radius: 7px;
font-size: 13px;
font-weight: ${({ $active }) => $active ? '600' : '400'};
background: ${({ $active }) => $active ? 'rgba(88,166,255,0.15)' : 'transparent'};
border: 1px solid ${({ $active }) => $active ? 'rgba(88,166,255,0.4)' : 'var(--border-color)'};
color: ${({ $active }) => $active ? '#58A6FF' : 'var(--text-secondary)'};
cursor: pointer;
transition: all 0.15s;
&:hover { color: #58A6FF; border-color: rgba(88,166,255,0.3); }
`;
const SummaryGrid = styled.div`
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 14px;
margin-bottom: 28px;
`;
const SummaryCard = styled.div`
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 10px;
padding: 16px 18px;
`;
const SummaryLabel = styled.div`
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
margin-bottom: 6px;
`;
const SummaryValue = styled.div`
font-size: 20px;
font-weight: 700;
color: var(--text-primary);
`;
const SummaryUnit = styled.span`
font-size: 12px;
color: var(--text-secondary);
margin-left: 4px;
`;
const ChartsGrid = styled.div`
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-bottom: 28px;
@media (max-width: 900px) {
grid-template-columns: 1fr;
}
`;
const Card = styled.div`
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 20px 22px;
`;
const RecordBtn = styled.button`
padding: 8px 16px;
border-radius: 7px;
font-size: 12px;
font-weight: 600;
background: rgba(88,166,255,0.08);
border: 1px solid rgba(88,166,255,0.25);
color: #58A6FF;
cursor: pointer;
transition: background 0.15s;
&:hover { background: rgba(88,166,255,0.18); }
&:disabled { opacity: 0.5; cursor: not-allowed; }
`;
const EmptyNote = styled.div`
padding: 32px;
text-align: center;
color: var(--text-secondary);
font-size: 13px;
line-height: 1.6;
`;
function formatTokens(n: number): string {
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
return String(n);
}
export default function CostsPage() {
const [period, setPeriod] = useState<Period>('week');
const [data, setData] = useState<CostData | null>(null);
const [loading, setLoading] = useState(true);
const [recording, setRecording] = useState(false);
const load = async (p: Period) => {
setLoading(true);
try {
const res = await adminFetch(`/api/admin/costs?period=${p}`);
if (res.ok) setData(await res.json());
} catch {
// silent
} finally {
setLoading(false);
}
};
useEffect(() => { load(period); }, [period]);
const recordAll = async () => {
setRecording(true);
try {
await Promise.all(['harang', 'narang', 'darang', 'erang'].map((name) =>
adminFetch(`/api/admin/costs/record/${name}`, { method: 'POST' }),
));
await load(period);
} finally {
setRecording(false);
}
};
const sisterChartData = data?.bySister.map((s) => ({
label: { harang: '하랑이', narang: '나랑이', darang: '다랑이', erang: '이랑이' }[s.name] ?? s.name,
value: s.estimatedUsd,
})) ?? [];
const modelChartData = data?.byModel.map((m) => ({
label: m.model.split('/').pop() ?? m.model,
value: m.totalTokens,
})) ?? [];
const timelineChartData = data?.timeline.map((t) => ({
label: t.date.slice(5),
value: t.estimatedUsd,
})) ?? [];
return (
<>
<Controls>
{(['day', 'week', 'month'] as Period[]).map((p) => (
<PeriodBtn key={p} $active={period === p} onClick={() => setPeriod(p)}>
{p === 'day' ? '오늘' : p === 'week' ? '7일' : '30일'}
</PeriodBtn>
))}
<RecordBtn onClick={recordAll} disabled={recording} style={{ marginLeft: 'auto' }}>
{recording ? '수집 중...' : '📊 토큰 수집'}
</RecordBtn>
</Controls>
{loading ? (
<div style={{ color: 'var(--text-secondary)', fontSize: '14px' }}> ...</div>
) : !data || data.summary.recordCount === 0 ? (
<EmptyNote>
.<br />
&quot; &quot; .
</EmptyNote>
) : (
<>
<SummaryGrid>
<SummaryCard>
<SummaryLabel> </SummaryLabel>
<SummaryValue>{formatTokens(data.summary.totalTokens)}<SummaryUnit>tokens</SummaryUnit></SummaryValue>
</SummaryCard>
<SummaryCard>
<SummaryLabel> </SummaryLabel>
<SummaryValue>${data.summary.estimatedUsd.toFixed(4)}<SummaryUnit>USD</SummaryUnit></SummaryValue>
</SummaryCard>
<SummaryCard>
<SummaryLabel> </SummaryLabel>
<SummaryValue>{formatTokens(data.summary.inputTokens)}</SummaryValue>
</SummaryCard>
<SummaryCard>
<SummaryLabel> </SummaryLabel>
<SummaryValue>{formatTokens(data.summary.outputTokens)}</SummaryValue>
</SummaryCard>
</SummaryGrid>
<ChartsGrid>
<Card>
<BarChart data={sisterChartData} unit="$" title="자매별 비용 (USD)" />
</Card>
<Card>
<BarChart data={modelChartData} unit=" tok" title="모델별 토큰 사용량" />
</Card>
</ChartsGrid>
{timelineChartData.length > 0 && (
<Card>
<BarChart data={timelineChartData} unit="$" title="일별 비용 추이" />
</Card>
)}
</>
)}
</>
);
}

View File

@@ -1,209 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import CodeEditor from '@/components/admin/CodeEditor';
import { adminFetch } from '@/lib/adminFetch';
const SISTERS = ['harang', 'narang', 'darang', 'erang'];
const FILES = ['SOUL.md', 'AGENTS.md', 'TOOLS.md', 'PROTOCOL.md', 'HEARTBEAT.md'];
const DISPLAY_NAMES: Record<string, string> = {
harang: '하랑이', narang: '나랑이', darang: '다랑이', erang: '이랑이',
};
const Layout = styled.div`
display: grid;
grid-template-columns: 180px 1fr;
gap: 20px;
`;
const FileTree = styled.div`
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 10px;
overflow: hidden;
`;
const TreeSection = styled.div`
border-bottom: 1px solid var(--border-color);
padding: 6px;
&:last-child { border-bottom: none; }
`;
const TreeLabel = styled.div`
font-size: 11px;
font-weight: 700;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
padding: 6px 8px 4px;
`;
const TreeItem = styled.button<{ $active: boolean }>`
width: 100%;
text-align: left;
padding: 6px 10px;
font-size: 12px;
border: none;
border-radius: 5px;
cursor: pointer;
background: ${({ $active }) => $active ? 'rgba(88,166,255,0.12)' : 'transparent'};
color: ${({ $active }) => $active ? '#58A6FF' : 'var(--text-secondary)'};
transition: background 0.15s;
&:hover { background: rgba(240,246,252,0.06); color: var(--text-primary); }
`;
const EditorPane = styled.div`
display: flex;
flex-direction: column;
gap: 12px;
`;
const Toolbar = styled.div`
display: flex;
align-items: center;
gap: 10px;
`;
const PathLabel = styled.span`
font-size: 13px;
color: var(--text-secondary);
font-family: monospace;
flex: 1;
`;
const Btn = styled.button<{ $primary?: boolean; $danger?: boolean }>`
padding: 7px 16px;
border-radius: 7px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
border: 1px solid;
transition: all 0.15s;
disabled: ${({ disabled }) => disabled ? 'not-allowed' : 'pointer'};
${({ $primary }) =>
$primary &&
`background: rgba(88,166,255,0.12); border-color: rgba(88,166,255,0.4); color: #58A6FF;
&:hover { background: rgba(88,166,255,0.22); }`}
${({ $danger }) =>
$danger &&
`background: transparent; border-color: rgba(240,246,252,0.15); color: #8B949E;
&:hover { color: #E6EDF3; }`}
${({ $primary, $danger }) =>
!$primary && !$danger &&
`background: transparent; border-color: rgba(240,246,252,0.15); color: #8B949E;
&:hover { color: #E6EDF3; }`}
`;
const ResultMsg = styled.div<{ $success: boolean }>`
padding: 8px 12px;
border-radius: 6px;
font-size: 12px;
font-family: monospace;
background: ${({ $success }) => $success ? 'rgba(0,230,118,0.08)' : 'rgba(255,23,68,0.08)'};
color: ${({ $success }) => $success ? '#00FF00' : '#FF1744'};
border: 1px solid ${({ $success }) => $success ? 'rgba(0,230,118,0.3)' : 'rgba(255,23,68,0.3)'};
`;
export default function HarnessPage() {
const [selected, setSelected] = useState({ sister: 'narang', file: 'SOUL.md' });
const [content, setContent] = useState('');
const [saved, setSaved] = useState('');
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [result, setResult] = useState<{ success: boolean; msg: string } | null>(null);
useEffect(() => {
setContent('');
setSaved('');
setResult(null);
setLoading(true);
adminFetch(`/api/admin/harness/${selected.sister}/${selected.file}`)
.then((r) => r.json())
.then((d) => { setContent(d.content ?? ''); setSaved(d.content ?? ''); })
.catch(() => setContent('(로드 실패)'))
.finally(() => setLoading(false));
}, [selected.sister, selected.file]);
const handleSave = async () => {
setSaving(true);
setResult(null);
try {
const res = await adminFetch(`/api/admin/harness/${selected.sister}/${selected.file}`, {
method: 'PUT',
body: JSON.stringify({ content }),
});
if (res.status === 401) {
setResult({ success: false, msg: '인증 실패 — API Key 또는 JWT 토큰을 확인해' });
return;
}
if (!res.ok) {
const text = await res.text();
setResult({ success: false, msg: `서버 오류 ${res.status}: ${text.slice(0, 100)}` });
return;
}
const d = await res.json();
if (d.success) {
setSaved(content);
setResult({ success: true, msg: '저장 완료' });
} else {
setResult({ success: false, msg: d.error ?? '저장 실패' });
}
} catch (e) {
setResult({ success: false, msg: (e as Error).message });
} finally {
setSaving(false);
}
};
const isDirty = content !== saved;
return (
<Layout>
<FileTree>
{SISTERS.map((s) => (
<TreeSection key={s}>
<TreeLabel>{DISPLAY_NAMES[s] ?? s}</TreeLabel>
{FILES.map((f) => (
<TreeItem
key={f}
$active={selected.sister === s && selected.file === f}
onClick={() => setSelected({ sister: s, file: f })}
>
{f}
</TreeItem>
))}
</TreeSection>
))}
</FileTree>
<EditorPane>
<Toolbar>
<PathLabel>
~/.openclaw/workspace/{selected.file} ({DISPLAY_NAMES[selected.sister]})
</PathLabel>
{isDirty && (
<span style={{ fontSize: '11px', color: '#FF9800' }}> </span>
)}
<Btn onClick={() => { setContent(saved); setResult(null); }} $danger></Btn>
<Btn $primary onClick={handleSave} disabled={!isDirty || saving}>
{saving ? '저장 중...' : '💾 저장'}
</Btn>
</Toolbar>
{result && <ResultMsg $success={result.success}>{result.msg}</ResultMsg>}
{loading ? (
<div style={{ padding: '32px', textAlign: 'center', color: 'var(--text-secondary)', fontSize: '13px' }}>
...
</div>
) : (
<CodeEditor value={content} onChange={setContent} />
)}
</EditorPane>
</Layout>
);
}

View File

@@ -1,63 +0,0 @@
'use client';
import React from 'react';
import styled from 'styled-components';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
const ADMIN_TABS = [
{ href: '/admin', label: '자매 관리' },
{ href: '/admin/logs', label: '로그 뷰어' },
{ href: '/admin/costs', label: '비용 모니터' },
{ href: '/admin/repos', label: '저장소' },
];
const Wrapper = styled.div`
display: flex;
flex-direction: column;
gap: var(--space-lg);
`;
const AdminHeader = styled.div`
border-bottom: 1px solid var(--border-color);
padding-bottom: var(--space-md);
`;
const TabNav = styled.div`
display: flex;
gap: var(--space-lg);
flex-wrap: wrap;
`;
const TabLink = styled(Link)<{ $active: boolean }>`
font-size: 13px;
font-weight: 500;
color: ${({ $active }) => $active ? 'var(--text-primary)' : 'var(--text-secondary)'};
text-decoration: none;
padding: var(--space-sm) 0;
border-bottom: 1px solid ${({ $active }) => $active ? 'var(--text-primary)' : 'transparent'};
transition: color 0.15s, border-color 0.15s;
&:hover { color: var(--text-primary); }
`;
export default function AdminLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
return (
<Wrapper>
<AdminHeader>
<div style={{ fontSize: '28px', fontWeight: 600, letterSpacing: '-0.02em', marginBottom: 'var(--space-md)' }}>
</div>
<TabNav>
{ADMIN_TABS.map((tab) => (
<TabLink key={tab.href} href={tab.href} $active={pathname === tab.href}>
{tab.label}
</TabLink>
))}
</TabNav>
</AdminHeader>
{children}
</Wrapper>
);
}

View File

@@ -1,115 +0,0 @@
'use client';
import React, { useState, useCallback, useEffect } from 'react';
import styled from 'styled-components';
import LogTerminal from '@/components/admin/LogTerminal';
import { adminFetch } from '@/lib/adminFetch';
const SISTERS = [
{ value: 'harang', label: '하랑이' },
{ value: 'narang', label: '나랑이' },
{ value: 'darang', label: '다랑이' },
{ value: 'erang', label: '이랑이' },
];
const Controls = styled.div`
display: flex;
gap: 10px;
align-items: center;
margin-bottom: 16px;
`;
const Select = styled.select`
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 7px;
color: var(--text-primary);
padding: 8px 12px;
font-size: 13px;
cursor: pointer;
outline: none;
&:focus { border-color: #58A6FF; }
option { background: #1a1f2a; }
`;
const LinesInput = styled.input`
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 7px;
color: var(--text-primary);
padding: 8px 12px;
font-size: 13px;
width: 80px;
outline: none;
&:focus { border-color: #58A6FF; }
`;
const FetchBtn = styled.button`
padding: 8px 18px;
border-radius: 7px;
font-size: 13px;
font-weight: 600;
background: rgba(88,166,255,0.1);
border: 1px solid rgba(88,166,255,0.35);
color: #58A6FF;
cursor: pointer;
transition: background 0.15s;
&:hover { background: rgba(88,166,255,0.2); }
&:disabled { opacity: 0.5; cursor: not-allowed; }
`;
const Label = styled.span`
font-size: 12px;
color: var(--text-secondary);
`;
export default function LogsPage() {
const [sister, setSister] = useState('narang');
const [lines, setLines] = useState(100);
const [logLines, setLogLines] = useState<string[]>([]);
const [loading, setLoading] = useState(false);
const fetchLogs = useCallback(async () => {
setLoading(true);
try {
const res = await adminFetch(`/api/admin/logs/${sister}?lines=${lines}`);
const d = await res.json();
setLogLines(d.lines ?? []);
} catch {
setLogLines(['(로그 로드 실패)']);
} finally {
setLoading(false);
}
}, [sister, lines]);
// 마운트 시 자동 로드
useEffect(() => {
fetchLogs();
}, [fetchLogs]);
return (
<>
<Controls>
<Select value={sister} onChange={(e) => setSister(e.target.value)}>
{SISTERS.map((s) => (
<option key={s.value} value={s.value}>{s.label}</option>
))}
</Select>
<Label></Label>
<LinesInput
type="number"
value={lines}
onChange={(e) => setLines(parseInt(e.target.value, 10) || 100)}
min={10}
max={500}
/>
<Label></Label>
<FetchBtn onClick={fetchLogs} disabled={loading}>
{loading ? '로딩 중...' : '📋 로그 가져오기'}
</FetchBtn>
</Controls>
<LogTerminal lines={logLines} />
</>
);
}

View File

@@ -1,89 +0,0 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import StatusBadge from '@/components/common/StatusBadge';
import ConfirmModal from '@/components/admin/ConfirmModal';
import { API_URL } from '@/lib/config';
import { adminFetch } from '@/lib/adminFetch';
import { SISTER_DISPLAY_NAMES } from '@/lib/sisters';
import SisterAvatar from '@/components/common/SisterAvatar';
type Status = 'online' | 'offline' | 'working' | 'unknown';
interface ActionResult {
success: boolean;
output: string;
error: string | null;
}
interface SisterAdminItem {
id?: number;
name: string;
status: Status;
}
const Table = styled.div`display:flex;flex-direction:column;gap:8px;user-select:none;`;
const Row = styled.div`background:var(--bg-surface);border:1px solid var(--border-color);border-radius:10px;padding:16px 20px;display:flex;align-items:center;gap:16px;`;
const SisterInfo = styled.div`display:flex;align-items:center;gap:10px;flex:1;`;
const Name = styled.span`font-size:15px;font-weight:600;color:var(--text-primary);min-width:70px;`;
const Actions = styled.div`display:flex;gap:8px;`;
const ActionBtn = styled.button<{ $danger?: boolean }>`padding:6px 14px;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;border:1px solid;transition:all .15s;user-select:none;${({ $danger }) => $danger ? `background: rgba(255,23,68,0.08); border-color: rgba(255,23,68,0.3); color: #FF1744; &:hover { background: rgba(255,23,68,0.18); }` : `background: rgba(88,166,255,0.08); border-color: rgba(88,166,255,0.3); color: #58A6FF; &:hover { background: rgba(88,166,255,0.18); }`}`;
const ResultBanner = styled.div<{ $success: boolean }>`margin-top:8px;padding:8px 12px;background:${({ $success }) => $success ? 'rgba(0,230,118,0.08)' : 'rgba(255,23,68,0.08)'};border:1px solid ${({ $success }) => $success ? 'rgba(0,230,118,0.3)' : 'rgba(255,23,68,0.3)'};border-radius:6px;font-size:12px;color:${({ $success }) => $success ? '#00FF00' : '#FF1744'};font-family:monospace;white-space:pre-wrap;`;
export default function AdminSistersPage() {
const [sisters, setSisters] = useState<SisterAdminItem[]>([]);
const [modal, setModal] = useState<{ action: 'restart' | 'reset'; name: string } | null>(null);
const [results, setResults] = useState<Record<string, ActionResult>>({});
const [loading, setLoading] = useState<Record<string, boolean>>({});
useEffect(() => {
fetch(`${API_URL}/api/sisters`).then((r) => r.json()).then(setSisters).catch(() => {});
const iv = setInterval(() => { fetch(`${API_URL}/api/sisters`).then((r) => r.json()).then(setSisters).catch(() => {}); }, 15000);
return () => clearInterval(iv);
}, []);
const doAction = async (action: 'restart' | 'reset', name: string) => {
setModal(null);
setLoading((p) => ({ ...p, [`${action}:${name}`]: true }));
try {
const res = await adminFetch(`/api/admin/sisters/${name}/${action}`, { method: 'POST' });
const data: ActionResult = await res.json();
setResults((p) => ({ ...p, [`${action}:${name}`]: data }));
} catch (e) {
setResults((p) => ({ ...p, [`${action}:${name}`]: { success: false, output: '', error: (e as Error).message } }));
} finally {
setLoading((p) => ({ ...p, [`${action}:${name}`]: false }));
}
};
return (
<>
<Table>
{sisters.map((s) => {
const restartResult = results[`restart:${s.name}`];
const resetResult = results[`reset:${s.name}`];
return (
<div key={s.id}>
<Row>
<SisterInfo>
<SisterAvatar name={s.name} size={28} />
<Name>{SISTER_DISPLAY_NAMES[s.name] ?? s.name}</Name>
<StatusBadge status={s.status as Status} />
</SisterInfo>
<Actions>
<ActionBtn onClick={() => setModal({ action: 'restart', name: s.name })} disabled={loading[`restart:${s.name}`]}>{loading[`restart:${s.name}`] ? '...' : '재시작'}</ActionBtn>
<ActionBtn $danger onClick={() => setModal({ action: 'reset', name: s.name })} disabled={loading[`reset:${s.name}`]}>{loading[`reset:${s.name}`] ? '...' : '리셋'}</ActionBtn>
</Actions>
</Row>
{restartResult && <ResultBanner $success={restartResult.success}>: {restartResult.success ? '✅ 성공' : `${restartResult.error}`}{restartResult.output && `\n${restartResult.output}`}</ResultBanner>}
{resetResult && <ResultBanner $success={resetResult.success}>: {resetResult.success ? '✅ 성공' : `${resetResult.error}`}</ResultBanner>}
</div>
);
})}
</Table>
{modal && <ConfirmModal title={modal.action === 'restart' ? '게이트웨이 재시작' : '세션 리셋'} message={`${SISTER_DISPLAY_NAMES[modal.name] ?? modal.name}${modal.action === 'restart' ? 'OpenClaw Gateway를 재시작' : '메인 세션을 초기화'}하시겠어요?`} confirmLabel={modal.action === 'restart' ? '재시작' : '리셋'} danger={modal.action === 'reset'} onConfirm={() => doAction(modal.action, modal.name)} onCancel={() => setModal(null)} />}
</>
);
}

View File

@@ -1,111 +0,0 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
const Grid = styled.div`
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 16px;
`;
const Card = styled.a`
display: block;
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 10px;
padding: 18px 20px;
text-decoration: none;
transition: transform 0.15s, border-color 0.15s;
&:hover {
transform: translateY(-2px);
border-color: rgba(88,166,255,0.3);
}
`;
const RepoName = styled.div`
font-size: 14px;
font-weight: 700;
color: #58A6FF;
margin-bottom: 6px;
`;
const RepoDesc = styled.div`
font-size: 12px;
color: var(--text-secondary);
margin-bottom: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const Stats = styled.div`
display: flex;
gap: 14px;
`;
const Stat = styled.span`
font-size: 12px;
color: var(--text-secondary);
`;
const PRBadge = styled.span<{ $count: number }>`
font-size: 11px;
padding: 2px 8px;
border-radius: 4px;
font-weight: 600;
background: ${({ $count }) => $count > 0 ? 'rgba(88,166,255,0.12)' : 'rgba(139,148,158,0.08)'};
color: ${({ $count }) => $count > 0 ? '#58A6FF' : 'var(--text-secondary)'};
`;
const NoProjects = styled.div`
padding: 32px;
text-align: center;
color: var(--text-secondary);
font-size: 13px;
`;
interface RepoProjectItem {
id: number;
name: string;
description: string | null;
repoUrl: string;
openPRs: number;
sprintCount: number;
progress: number;
}
export default function ReposPage() {
const [projects, setProjects] = useState<RepoProjectItem[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(`${API_URL}/api/projects`)
.then((r) => r.json())
.then(setProjects)
.catch(() => {})
.finally(() => setLoading(false));
}, []);
if (loading) return <div style={{ color: 'var(--text-secondary)', fontSize: '14px' }}> ...</div>;
if (!projects.length) return <NoProjects> </NoProjects>;
return (
<Grid>
{projects.map((p) => (
<Card key={p.id} href={p.repoUrl} target="_blank" rel="noopener">
<RepoName>📁 {p.name}</RepoName>
{p.description && <RepoDesc>{p.description}</RepoDesc>}
<Stats>
<PRBadge $count={p.openPRs}>PR {p.openPRs}</PRBadge>
<Stat>Sprint {p.sprintCount}</Stat>
<Stat> {p.progress}%</Stat>
</Stats>
</Card>
))}
</Grid>
);
}

View File

@@ -1,246 +0,0 @@
'use client';
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
import {
useRailsSocket,
type RailsPipelineSummary,
type RailsSubTaskNode,
} from '@/lib/useRailsSocket';
import OfficeFloor from '@/components/office/OfficeFloor';
import SubTaskTree from '@/components/rails/SubTaskTree';
import SubTaskDetailDrawer from '@/components/rails/SubTaskDetailDrawer';
type SisterKey = 'harang' | 'narang' | 'darang' | 'erang';
const Page = styled.main`
display: flex;
flex-direction: column;
gap: 24px;
padding: 24px 32px;
max-width: 1600px;
margin: 0 auto;
width: 100%;
`;
const Header = styled.header`
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 24px;
flex-wrap: wrap;
`;
const TitleBlock = styled.div``;
const Title = styled.h1`
font-size: 28px;
font-weight: 700;
margin: 0 0 4px;
letter-spacing: -0.01em;
`;
const Subtitle = styled.p`
font-size: 13px;
color: var(--text-secondary);
margin: 0;
`;
const StatsBar = styled.div`
display: flex;
gap: 28px;
`;
const StatBlock = styled.div`
display: flex;
flex-direction: column;
gap: 2px;
`;
const StatNum = styled.span`
font-family: var(--font-mono);
font-size: 24px;
font-weight: 700;
`;
const StatLabel = styled.span`
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
`;
const TwoCol = styled.div`
display: grid;
grid-template-columns: 1fr minmax(360px, 460px);
gap: 24px;
@media (max-width: 1100px) {
grid-template-columns: 1fr;
}
`;
const Card = styled.section`
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 16px;
padding: 24px;
display: flex;
flex-direction: column;
gap: 16px;
`;
const CardTitle = styled.h2`
font-size: 13px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-secondary);
margin: 0;
`;
const Empty = styled.div`
padding: 60px 20px;
text-align: center;
color: var(--text-secondary);
font-size: 13px;
`;
export default function OfficePage() {
const [pipelines, setPipelines] = useState<RailsPipelineSummary[]>([]);
const [trees, setTrees] = useState<Map<string, RailsSubTaskNode[]>>(new Map());
const [selectedSister, setSelectedSister] = useState<SisterKey | null>(null);
const [detailNodeId, setDetailNodeId] = useState<string | null>(null);
const { connected } = useRailsSocket({
onPipelinesSnapshot: (next) => setPipelines(next),
onSubTasksUpdated: (pid, tree) => {
setTrees((prev) => {
const m = new Map(prev);
m.set(pid, tree);
return m;
});
},
});
// Initial fetch
useEffect(() => {
fetch(`${API_URL}/api/rails/pipelines`, { credentials: 'include' })
.then((r) => r.json())
.then(async (data: { pipelines: RailsPipelineSummary[] }) => {
setPipelines(data.pipelines);
const recent = data.pipelines.slice(0, 6);
const treeMap = new Map<string, RailsSubTaskNode[]>();
for (const p of recent) {
try {
const r = await fetch(
`${API_URL}/api/rails/pipelines/${p.id}/sub-tasks`,
{ credentials: 'include' },
);
const d = (await r.json()) as { tree: RailsSubTaskNode[] };
treeMap.set(p.id, d.tree);
} catch {
/* ignore */
}
}
setTrees(treeMap);
})
.catch(() => {
/* ignore */
});
}, []);
const stats = useMemo(() => {
const active = pipelines.filter(
(p) => !['done', 'aborted'].includes(p.currentState),
);
const escalated = pipelines.filter((p) => p.currentState === 'escalated');
return {
total: pipelines.length,
active: active.length,
escalated: escalated.length,
};
}, [pipelines]);
const selectedSubTree = useMemo(() => {
if (!selectedSister) return [];
const out: RailsSubTaskNode[] = [];
for (const tree of trees.values()) {
const filterMine = (nodes: RailsSubTaskNode[]): RailsSubTaskNode[] =>
nodes
.filter((n) => n.agentName === selectedSister)
.map((n) => ({ ...n, children: filterMine(n.children) }));
out.push(...filterMine(tree));
}
return out;
}, [selectedSister, trees]);
const handleSelectSister = useCallback((key: SisterKey | null) => {
setSelectedSister(key);
}, []);
return (
<Page>
<Header>
<TitleBlock>
<Title>Digital Office</Title>
<Subtitle>
4 {' '}
<span style={{ opacity: connected ? 1 : 0.4 }}>
{connected ? '· LIVE' : '· offline'}
</span>
</Subtitle>
</TitleBlock>
<StatsBar>
<StatBlock>
<StatNum>{stats.total}</StatNum>
<StatLabel>Total</StatLabel>
</StatBlock>
<StatBlock>
<StatNum style={{ color: '#22c55e' }}>{stats.active}</StatNum>
<StatLabel>Active</StatLabel>
</StatBlock>
<StatBlock>
<StatNum style={{ color: stats.escalated > 0 ? '#ef4444' : undefined }}>
{stats.escalated}
</StatNum>
<StatLabel>Escalated</StatLabel>
</StatBlock>
</StatsBar>
</Header>
<TwoCol>
<OfficeFloor
pipelines={pipelines}
treesByPipeline={trees}
selectedSister={selectedSister}
onSelectSister={handleSelectSister}
/>
<Card>
<CardTitle>
{selectedSister ? `${selectedSister} 작업` : '디테일'}
</CardTitle>
{selectedSister ? (
selectedSubTree.length > 0 ? (
<SubTaskTree tree={selectedSubTree} onSelectNode={setDetailNodeId} />
) : (
<Empty>{selectedSister} </Empty>
)
) : (
<Empty> </Empty>
)}
</Card>
</TwoCol>
{detailNodeId && (
<SubTaskDetailDrawer
subTaskId={detailNodeId}
onClose={() => setDetailNodeId(null)}
/>
)}
</Page>
);
}

View File

@@ -1,280 +0,0 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
// ─── Styled ───
const MainViewport = styled.div`
display: flex;
flex-direction: column;
gap: var(--space-xl);
min-height: 80vh;
`;
const HeaderInfo = styled.div`
display: flex;
gap: var(--space-xl);
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
border-bottom: 1px solid var(--border-color);
padding-bottom: var(--space-md);
span { color: var(--text-primary); }
`;
const TreeContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
overflow-x: auto;
padding: var(--space-xl) 0;
@media (max-width: 767px) {
align-items: flex-start;
}
`;
const NodeGroup = styled.div`
display: flex;
flex-direction: column;
align-items: center;
position: relative;
`;
const TerminalCard = styled.div<{ $level: 'high' | 'mid' | 'low' | 'none' }>`
border: 1px solid ${({ $level }) => ({
high: '#f43f5e',
mid: '#3b82f6',
low: '#10b981',
none: '#525252',
})[$level]};
border-left-width: 3px;
padding: var(--space-md) var(--space-lg);
background: var(--bg-main);
min-width: 200px;
max-width: 260px;
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
transition: border-color 0.2s, box-shadow 0.2s;
position: relative;
cursor: default;
&:hover {
box-shadow: 0 12px 36px rgba(0,0,0,0.7);
}
`;
const NodeLabel = styled.div`
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
margin-bottom: var(--space-sm);
span {
color: var(--text-secondary);
margin-right: var(--space-xs);
font-family: var(--font-mono);
font-size: 11px;
}
`;
const BadgeRow = styled.div`
display: flex;
gap: var(--space-xs);
flex-wrap: wrap;
`;
const Badge = styled.div`
background: #1a1a1a;
border: 1px solid var(--border-color);
padding: 2px 6px;
font-size: 9px;
font-family: var(--font-mono);
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--text-secondary);
b { color: var(--text-primary); font-weight: normal; }
`;
const TreeConnector = styled.div`
width: 1px;
height: 24px;
background: var(--border-color);
margin: 0 auto;
`;
const TreeBranch = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
const TreeChildren = styled.div`
display: flex;
gap: var(--space-xl);
align-items: flex-start;
position: relative;
&::before {
content: '';
position: absolute;
top: 0;
left: calc(var(--space-xl) / 2 + 100px);
right: calc(var(--space-xl) / 2 + 100px);
height: 1px;
background: var(--border-color);
}
@media (max-width: 767px) {
flex-direction: column;
gap: var(--space-lg);
&::before { display: none; }
}
`;
const PageFooter = styled.footer`
margin-top: auto;
width: 100%;
padding: var(--space-lg) 0;
display: flex;
justify-content: space-between;
border-top: 1px solid var(--border-color);
font-family: var(--font-mono);
color: var(--text-secondary);
font-size: 10px;
`;
type Level = 'high' | 'mid' | 'low' | 'none';
interface OrgData {
owner: { name: string; role: string };
sisters: Array<{
name: string;
role: string;
description?: string;
status?: string;
lxcId?: number;
}>;
pipeline: Array<{ from: string; to: string; label: string }>;
}
const LEVEL_MAP: Record<string, Level> = {
Orchestrator: 'high',
Generator: 'mid',
Evaluator: 'mid',
'Infra Manager': 'low',
};
const ROLE_TAG: Record<string, string> = {
Orchestrator: 'ORCH',
Generator: 'GEN',
Evaluator: 'EVAL',
'Infra Manager': 'INFRA',
};
const LXC_ID: Record<string, number> = {
harang: 104,
narang: 105,
darang: 106,
erang: 107,
};
export default function OrgPage() {
const [orgData, setOrgData] = useState<OrgData | null>(null);
const ts = new Date().toLocaleDateString('ko-KR').replace(/\. /g, '.').replace('.', '') + '_' +
new Date().toLocaleTimeString('ko-KR', { hour12: false, hour: '2-digit', minute: '2-digit' });
useEffect(() => {
fetch(`${API_URL}/api/org`)
.then((r) => r.json())
.then(setOrgData)
.catch(() => {});
}, []);
const sisters = orgData?.sisters ?? [];
return (
<MainViewport>
<HeaderInfo>
<div>SYS_TYPE: <span>CORE_ROOT_01</span></div>
<div>TIMESTAMP: <span style={{ color: 'var(--text-secondary)' }}>{ts}</span></div>
</HeaderInfo>
<TreeContainer>
<NodeGroup>
{/* HQ */}
<TerminalCard $level="high">
<NodeLabel><span>[HQ]</span> </NodeLabel>
<BadgeRow>
<Badge>MEM: <b>{sisters.length + 1}</b></Badge>
<Badge>S_ADMIN</Badge>
<Badge>LV_09</Badge>
</BadgeRow>
</TerminalCard>
<TreeConnector />
{/* 자매 레벨 */}
<TreeBranch>
<TreeChildren>
{/* 하랑이 (Orchestrator) */}
{sisters.filter((s) => s.role === 'Orchestrator').map((s) => (
<NodeGroup key={s.name}>
<TerminalCard $level={LEVEL_MAP[s.role] ?? 'none'}>
<NodeLabel>
<span>[{ROLE_TAG[s.role] ?? s.role}]</span>
{s.name === 'harang' ? '하랑이' : s.name}
</NodeLabel>
<BadgeRow>
<Badge>LXC: <b>{LXC_ID[s.name] ?? '---'}</b></Badge>
<Badge>{ROLE_TAG[s.role] ?? s.role}</Badge>
<Badge>{s.status === 'online' ? 'ACTIVE' : s.status === 'offline' ? 'STBY' : 'RUN'}</Badge>
</BadgeRow>
</TerminalCard>
<TreeConnector />
<TreeBranch>
<TreeChildren>
{/* 나랑/다랑/이랑 */}
{sisters.filter((s2) => s2.role !== 'Orchestrator').map((s2) => (
<NodeGroup key={s2.name}>
<TerminalCard $level={LEVEL_MAP[s2.role] ?? 'none'}>
<NodeLabel>
{s2.name === 'narang' ? '나랑이' : s2.name === 'darang' ? '다랑이' : '이랑이'}
</NodeLabel>
<BadgeRow>
<Badge>LXC: <b>{LXC_ID[s2.name] ?? '---'}</b></Badge>
<Badge>{ROLE_TAG[s2.role] ?? s2.role}</Badge>
<Badge>{s2.status === 'online' ? 'ON' : s2.status === 'offline' ? '--' : 'RUN'}</Badge>
</BadgeRow>
</TerminalCard>
</NodeGroup>
))}
</TreeChildren>
</TreeBranch>
</NodeGroup>
))}
{/* Orchestrator 없을 때 fallback */}
{sisters.filter((s) => s.role === 'Orchestrator').length === 0 && (
<NodeGroup>
<TerminalCard $level="none">
<NodeLabel> </NodeLabel>
<BadgeRow><Badge>N/A</Badge></BadgeRow>
</TerminalCard>
</NodeGroup>
)}
</TreeChildren>
</TreeBranch>
</NodeGroup>
</TreeContainer>
<PageFooter>
<div>TOTAL_NODES: {String(sisters.length + 1).padStart(2, '0')}</div>
<div>STATUS: SYNC_COMPLETE</div>
</PageFooter>
</MainViewport>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,266 +0,0 @@
'use client';
import React, { useEffect, useMemo, useState } from 'react';
import { useParams } from 'next/navigation';
import styled from 'styled-components';
import Link from 'next/link';
import { LabelMeta, PageTitle, SectionTitle, TechBar, TechBarFill, BtnToggle } from '@/components/ui/base';
import { API_URL } from '@/lib/config';
import SisterAvatar from '@/components/common/SisterAvatar';
interface TaskItem { id: number; taskId: string; title: string; assignee: string; status: string; }
interface SprintItem { id: number; number: number; name: string; status: string; progress: number; tasks: TaskItem[]; }
interface HistoryItem { label: string; kind: 'sprint' | 'hotfix'; summary?: string | null; description?: string | null; }
interface SisterState { name: string; status: string; }
interface CommitItem { sha?: string; html_url?: string; commit?: { message?: string; author?: { date?: string; name?: string } }; author?: { login?: string } | null; }
interface BranchItem { name?: string; protected?: boolean; commit?: { id?: string } }
interface PullItem { id?: number; number?: number; title?: string; html_url?: string; state?: string; merged?: boolean; user?: { login?: string }; created_at?: string; }
interface ProjectDetail {
id: number;
name: string;
repoUrl: string;
status: string;
phase: string;
currentSprint?: string | null;
latestQa: { label: string | null; status: 'passed' | 'failed' | 'unknown'; blockerCount: number; summary: string | null } | null;
deploy: { branch: string; status: string; latestDeployAt: string | null; redeployRequired: boolean; note: string };
}
const Breadcrumb = styled.div`font-family:var(--font-mono);font-size:11px;color:var(--text-secondary);margin-bottom:var(--space-md);a{color:var(--text-secondary);text-decoration:none;&:hover{color:var(--text-primary);}}`;
const PageTitleRow = styled.div`display:flex;justify-content:space-between;align-items:flex-start;gap:var(--space-lg);margin-bottom:var(--space-xl);flex-wrap:wrap;`;
const ProjectGrid = styled.div`display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:var(--space-xl);align-items:start;@media (max-width:1199px){display:flex;flex-direction:column;}`;
const Panel = styled.section<{ $column?: 'main' | 'side'; $mobileOrder?: number }>`border:1px solid var(--border-color);padding:var(--space-lg);background:var(--bg-surface);${({$column})=>$column==='side'?'grid-column:2;':'grid-column:1;'}@media (max-width:1199px){order:${({$mobileOrder=0})=>$mobileOrder};}`;
const FlowList = styled.div`display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:var(--space-sm);@media (max-width:767px){grid-template-columns:1fr;}`;
const FlowItem = styled.div<{ $active:boolean }>`border:1px solid ${({$active})=>$active?'var(--text-primary)':'var(--border-color)'};padding:var(--space-md);background:${({$active})=>$active?'#111':'transparent'};display:flex;flex-direction:column;gap:4px;`;
const LedgerList = styled.div`display:flex;flex-direction:column;gap:var(--space-md);`;
const LedgerItem = styled.div`display:flex;flex-direction:column;gap:8px;border-top:1px solid #1a1a1a;padding-top:var(--space-md);&:first-child{border-top:none;padding-top:0;}`;
const Meta = styled.div`font-size:11px;color:var(--text-secondary);font-family:var(--font-mono);`;
const NodeStack = styled.div`display:flex;flex-direction:column;gap:var(--space-sm);`;
const NodeMiniCard = styled.div`border:1px solid var(--border-color);padding:var(--space-sm) var(--space-md);display:flex;justify-content:space-between;align-items:center;gap:var(--space-md);`;
const NodeInfo = styled.div`display:flex;align-items:center;gap:var(--space-sm);`;
const NodeDot = styled.div<{ $status:string }>`width:8px;height:8px;border-radius:50%;background:${({$status})=>$status==='online'?'#00ff88':$status==='working'?'#5fafff':'#555'};`;
const Empty = styled.div`padding:var(--space-xl) 0;color:var(--text-secondary);font-size:13px;font-family:var(--font-mono);`;
const TabBar = styled.div`display:flex;gap:var(--space-sm);margin-bottom:var(--space-xl);flex-wrap:wrap;`;
const GitList = styled.div`display:flex;flex-direction:column;gap:var(--space-sm);`;
const GitItem = styled.a`border:1px solid var(--border-color);padding:12px var(--space-lg);text-decoration:none;color:var(--text-primary);display:flex;justify-content:space-between;gap:var(--space-md);align-items:center;`;
const GitPrimary = styled.div`display:flex;flex-direction:column;gap:4px;min-width:0;`;
const GitTitle = styled.div`font-size:13px;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;
const ROLE_LABEL: Record<string, string> = { harang: 'ORCHESTRATOR', narang: 'GENERATOR', darang: 'EVALUATOR', erang: 'INFRA' };
const ROLE_NAME: Record<string, string> = { harang: '하랑', narang: '나랑', darang: '다랑', erang: '이랑' };
function formatDate(value?: string | null): string {
if (!value) return '-';
return new Date(value).toLocaleString('ko-KR');
}
export default function ProjectDetailPage() {
const { id } = useParams<{ id: string }>();
const [project, setProject] = useState<ProjectDetail | null>(null);
const [tasks, setTasks] = useState<SprintItem[]>([]);
const [history, setHistory] = useState<HistoryItem[]>([]);
const [sisters, setSisters] = useState<SisterState[]>([]);
const [commits, setCommits] = useState<CommitItem[]>([]);
const [branches, setBranches] = useState<BranchItem[]>([]);
const [pulls, setPulls] = useState<PullItem[]>([]);
const [tab, setTab] = useState<'overview'|'commits'|'branches'|'prs'>('overview');
const [loading, setLoading] = useState(true);
useEffect(() => {
Promise.allSettled([
fetch(`${API_URL}/api/projects/${id}`),
fetch(`${API_URL}/api/projects/${id}/tasks`),
fetch(`${API_URL}/api/projects/${id}/history`),
fetch(`${API_URL}/api/sisters`),
]).then(async ([projectRes, tasksRes, historyRes, sistersRes]) => {
if (projectRes.status === 'fulfilled' && projectRes.value.ok) setProject(await projectRes.value.json());
if (tasksRes.status === 'fulfilled' && tasksRes.value.ok) setTasks(await tasksRes.value.json());
if (historyRes.status === 'fulfilled' && historyRes.value.ok) setHistory(await historyRes.value.json());
if (sistersRes.status === 'fulfilled' && sistersRes.value.ok) setSisters(await sistersRes.value.json());
}).finally(() => setLoading(false));
}, [id]);
useEffect(() => {
if (tab === 'commits' && commits.length === 0) fetch(`${API_URL}/api/projects/${id}/commits?limit=20`).then((r) => r.ok ? r.json() : []).then(setCommits).catch(() => {});
if (tab === 'branches' && branches.length === 0) fetch(`${API_URL}/api/projects/${id}/branches`).then((r) => r.ok ? r.json() : []).then(setBranches).catch(() => {});
if (tab === 'prs' && pulls.length === 0) fetch(`${API_URL}/api/projects/${id}/pulls?state=all`).then((r) => r.ok ? r.json() : []).then(setPulls).catch(() => {});
}, [tab, id, commits.length, branches.length, pulls.length]);
const allTasks = useMemo(() => tasks.flatMap((sprint) => sprint.tasks ?? []), [tasks]);
const assignedNodes = useMemo(() => {
const names = Array.from(new Set(allTasks.map((task) => task.assignee).filter(Boolean)));
return (names.length > 0 ? names : ['harang', 'narang', 'darang', 'erang']).map((name) => ({
name,
status: sisters.find((sister) => sister.name === name)?.status ?? 'offline',
}));
}, [allTasks, sisters]);
const hotfixes = history.filter((entry) => entry.kind === 'hotfix');
const currentSprintMeta = useMemo(() => {
if (project?.currentSprint) return project.currentSprint;
const activeSprint = tasks.find((sprint) => sprint.status === 'in_progress');
if (activeSprint) return activeSprint.name || String(activeSprint.number).padStart(2, '0');
const latestSprint = tasks.at(-1);
if (latestSprint?.status === 'done') return 'COMPLETED';
if (latestSprint) return latestSprint.name || String(latestSprint.number).padStart(2, '0');
return 'BACKLOG';
}, [project, tasks]);
if (loading) return <Empty>LOADING...</Empty>;
if (!project) return <Empty>PROJECT NOT FOUND</Empty>;
const flowStates = [
{ key: 'PLANNING', title: 'Planning', active: project.phase === 'PLANNING' },
{ key: 'IMPLEMENT', title: 'Implement', active: project.phase === 'IMPLEMENT' },
{ key: 'QA', title: 'QA', active: project.phase === 'QA' },
{ key: 'READY FOR DEPLOY', title: 'Merge to Main', active: project.phase === 'READY FOR DEPLOY' },
{ key: 'DEPLOYED', title: 'Redeploy', active: project.phase === 'DEPLOYED' },
];
return (
<>
<Breadcrumb><Link href="/projects">PROJECTS</Link> / P-{String(project.id).padStart(3, '0')} / {project.name}</Breadcrumb>
<PageTitleRow>
<PageTitle>
{project.name}
{project.repoUrl && <a href={project.repoUrl} target="_blank" rel="noopener" style={{ fontSize: '12px', color: '#5fafff', marginLeft: 'var(--space-md)', fontWeight: 400 }}> GITEA</a>}
</PageTitle>
<LabelMeta><span>STATUS:</span>{project.status?.toUpperCase()} / <span>SPRINT:</span>{currentSprintMeta} / <span>DEPLOY:</span>{project.deploy.status}</LabelMeta>
</PageTitleRow>
<TabBar>
<BtnToggle $active={tab === 'overview'} onClick={() => setTab('overview')}>Overview</BtnToggle>
<BtnToggle $active={tab === 'commits'} onClick={() => setTab('commits')}>Commits</BtnToggle>
<BtnToggle $active={tab === 'branches'} onClick={() => setTab('branches')}>Branches</BtnToggle>
<BtnToggle $active={tab === 'prs'} onClick={() => setTab('prs')}>Pull Requests</BtnToggle>
</TabBar>
{tab === 'overview' && (
<ProjectGrid>
<Panel $column="main" $mobileOrder={1}>
<SectionTitle><span>DELIVERY FLOW</span><LabelMeta>{project.phase}</LabelMeta></SectionTitle>
<FlowList>
{flowStates.map((item) => (
<FlowItem key={item.key} $active={item.active}>
<LabelMeta>{item.title}</LabelMeta>
<Meta>{item.key}</Meta>
</FlowItem>
))}
</FlowList>
</Panel>
<Panel $column="side" $mobileOrder={2}>
<SectionTitle><span>QA STATUS</span><LabelMeta>{project.latestQa?.status ?? 'unknown'}</LabelMeta></SectionTitle>
<Meta>{project.latestQa?.label ?? 'QA 문서 없음'}</Meta>
<div style={{ marginTop: 'var(--space-md)', fontSize: '13px', color: 'var(--text-primary)' }}>{project.latestQa?.summary ?? 'latest QA 없음'}</div>
<Meta style={{ marginTop: 'var(--space-md)' }}>{project.latestQa?.status === 'passed' ? 'QA PASSED' : project.latestQa?.status === 'failed' ? `QA FAILED · ${project.latestQa.blockerCount} BLOCKERS` : 'QA PENDING'}</Meta>
</Panel>
<Panel $column="side" $mobileOrder={3}>
<SectionTitle><span>DEPLOY STATUS</span><LabelMeta>{project.deploy.branch}</LabelMeta></SectionTitle>
<Meta>{project.deploy.status}</Meta>
<Meta style={{ marginTop: 'var(--space-sm)' }}>{project.deploy.note}</Meta>
<Meta style={{ marginTop: 'var(--space-sm)' }}>{project.deploy.latestDeployAt ? formatDate(project.deploy.latestDeployAt) : 'LAST DEPLOY UNKNOWN'}</Meta>
</Panel>
<Panel $column="main" $mobileOrder={4}>
<SectionTitle><span>SPRINT LEDGER</span><LabelMeta>{tasks.length} SPRINTS</LabelMeta></SectionTitle>
<LedgerList>
{tasks.map((sprint) => (
<LedgerItem key={sprint.id}>
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 'var(--space-md)', flexWrap: 'wrap' }}>
<div>
<div style={{ fontSize: '14px', fontWeight: 600, color: 'var(--text-primary)' }}>SPRINT {String(sprint.number).padStart(2, '0')} · {sprint.name}</div>
<Meta>{sprint.tasks?.length ?? 0} TASKS · {sprint.tasks?.filter((task) => task.status === 'done').length ?? 0} DONE</Meta>
</div>
<LabelMeta>{sprint.status}</LabelMeta>
</div>
<TechBar><TechBarFill $width={sprint.progress ?? 0} /></TechBar>
</LedgerItem>
))}
{tasks.length === 0 && <Empty>NO SPRINTS</Empty>}
</LedgerList>
</Panel>
<Panel $column="main" $mobileOrder={5}>
<SectionTitle><span>HOTFIX HISTORY</span><LabelMeta>{hotfixes.length} ITEMS</LabelMeta></SectionTitle>
<LedgerList>
{hotfixes.map((entry) => (
<LedgerItem key={entry.label}>
<div style={{ fontSize: '14px', fontWeight: 600, color: 'var(--text-primary)' }}>{entry.label}</div>
<Meta>{entry.summary ?? entry.description ?? 'hotfix summary 없음'}</Meta>
</LedgerItem>
))}
{hotfixes.length === 0 && <Empty>NO HOTFIX HISTORY</Empty>}
</LedgerList>
</Panel>
<Panel $column="side" $mobileOrder={6}>
<SectionTitle><span>ASSIGNED NODES</span><LabelMeta>LIVE STATUS</LabelMeta></SectionTitle>
<NodeStack>
{assignedNodes.map((node) => (
<NodeMiniCard key={node.name}>
<NodeInfo>
<SisterAvatar name={node.name} size={28} />
<div>
<div style={{ fontSize: '13px', color: 'var(--text-primary)', fontWeight: 600 }}>{ROLE_NAME[node.name] ?? node.name}</div>
<Meta>{ROLE_LABEL[node.name] ?? 'NODE'}</Meta>
</div>
</NodeInfo>
<NodeDot $status={node.status} />
</NodeMiniCard>
))}
</NodeStack>
</Panel>
</ProjectGrid>
)}
{tab === 'commits' && (
<GitList>
{commits.map((commit) => (
<GitItem key={commit.sha} href={commit.html_url ?? '#'} target="_blank" rel="noopener">
<GitPrimary>
<GitTitle>{commit.commit?.message?.split('\n')[0] ?? commit.sha ?? 'UNKNOWN COMMIT'}</GitTitle>
<Meta>{commit.commit?.author?.name ?? commit.author?.login ?? '-'}</Meta>
</GitPrimary>
<Meta>{commit.sha?.slice(0, 7) ?? '-'} · {formatDate(commit.commit?.author?.date)}</Meta>
</GitItem>
))}
{commits.length === 0 && <Empty>NO COMMITS</Empty>}
</GitList>
)}
{tab === 'branches' && (
<GitList>
{branches.map((branch) => (
<GitItem key={branch.name} href={project.repoUrl} target="_blank" rel="noopener">
<GitPrimary>
<GitTitle>{branch.name ?? 'UNKNOWN BRANCH'}</GitTitle>
<Meta>{branch.protected ? 'PROTECTED' : 'ACTIVE BRANCH'}</Meta>
</GitPrimary>
<Meta>{branch.commit?.id?.slice(0, 7) ?? '-'}</Meta>
</GitItem>
))}
{branches.length === 0 && <Empty>NO BRANCHES</Empty>}
</GitList>
)}
{tab === 'prs' && (
<GitList>
{pulls.map((pull) => (
<GitItem key={pull.id} href={pull.html_url ?? '#'} target="_blank" rel="noopener">
<GitPrimary>
<GitTitle>#{pull.number ?? '-'} {pull.title ?? 'UNKNOWN PR'}</GitTitle>
<Meta>{pull.user?.login ?? '-'} · {pull.merged ? 'MERGED' : pull.state?.toUpperCase() ?? 'UNKNOWN'}</Meta>
</GitPrimary>
<Meta>{formatDate(pull.created_at)}</Meta>
</GitItem>
))}
{pulls.length === 0 && <Empty>NO PULL REQUESTS</Empty>}
</GitList>
)}
</>
);
}

View File

@@ -1,113 +0,0 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import Link from 'next/link';
import { PageTitle, LabelMeta, TechBar, TechBarFill, Btn } from '@/components/ui/base';
import { API_URL } from '@/lib/config';
import { adminFetch } from '@/lib/adminFetch';
interface ProjectListItem {
id: number;
name: string;
description: string | null;
progress: number;
phase: string;
currentSprint: string | null;
latestHotfix: string | null;
latestQaLabel: string | null;
latestQaStatus: 'passed' | 'failed' | 'unknown';
blockerCount: number;
deployStatus: string;
updatedAt: string;
}
const ProjectList = styled.div`display:flex;flex-direction:column;gap:var(--space-md);`;
const ProjectRow = styled(Link)`display:grid;grid-template-columns:1.2fr 1fr 220px;gap:var(--space-lg);padding:var(--space-lg);border:1px solid var(--border-color);align-items:center;text-decoration:none;transition:border-color .15s, background .15s;&:hover{border-color:var(--border-hover);background:#111}@media (max-width:1199px){grid-template-columns:1fr;}`;
const Left = styled.div`display:flex;flex-direction:column;gap:6px;min-width:0;`;
const ProjectName = styled.div`font-size:15px;font-weight:600;color:var(--text-primary);`;
const ProjectDesc = styled.div`font-size:12px;color:var(--text-secondary);line-height:1.5;`;
const Middle = styled.div`display:flex;flex-direction:column;gap:10px;`;
const Right = styled.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;@media (max-width:1199px){align-items:flex-start;}`;
const Meta = styled.div`font-size:11px;color:var(--text-secondary);font-family:var(--font-mono);`;
const PhaseBadge = styled.div<{ $phase:string }>`font-size:11px;font-family:var(--font-mono);padding:4px 8px;border:1px solid ${({$phase})=>$phase==='DEPLOYED'?'#5fafff44':$phase==='READY FOR DEPLOY'?'#5fff8a44':$phase==='QA'?'#ffcc6644':'var(--border-color)'};color:${({$phase})=>$phase==='DEPLOYED'?'#5fafff':$phase==='READY FOR DEPLOY'?'#5fff8a':$phase==='QA'?'#ffcc66':'var(--text-primary)'};white-space:nowrap;`;
const EmptyState = styled.div`padding:var(--space-xl) 0;color:var(--text-secondary);font-size:13px;font-family:var(--font-mono);`;
function qaLabel(project: ProjectListItem): string {
if (project.latestQaStatus === 'passed') return 'QA PASSED';
if (project.latestQaStatus === 'failed') return `QA FAILED${project.blockerCount > 0 ? ` · ${project.blockerCount} BLOCKERS` : ''}`;
return 'QA PENDING';
}
export default function ProjectsPage() {
const [projects, setProjects] = useState<ProjectListItem[]>([]);
const [loading, setLoading] = useState(true);
const [syncing, setSyncing] = useState(false);
const [syncResult, setSyncResult] = useState<string | null>(null);
const loadProjects = () => {
setLoading(true);
fetch(`${API_URL}/api/projects`).then((r) => r.json()).then(setProjects).catch(() => {}).finally(() => setLoading(false));
};
const runSync = async (path: string, label: string) => {
setSyncing(true);
setSyncResult(null);
try {
const res = await adminFetch(path, { method: 'POST' });
const data = await res.json();
setSyncResult(`${label}: ${JSON.stringify(data)}`);
loadProjects();
} catch {
setSyncResult(`${label}: failed`);
} finally {
setSyncing(false);
}
};
useEffect(() => { loadProjects(); }, []);
return (
<>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 'var(--space-md)', flexWrap: 'wrap', marginBottom: 'var(--space-lg)' }}>
<PageTitle></PageTitle>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-md)', flexWrap: 'wrap' }}>
{syncResult && <span style={{ fontFamily: 'var(--font-mono)', fontSize: '11px', color: 'var(--text-secondary)' }}>{syncResult}</span>}
<LabelMeta>VOL: {String(projects.length).padStart(2, '0')}</LabelMeta>
<Btn onClick={() => runSync('/api/admin/gitea/sync', 'gitea sync')} disabled={syncing}>{syncing ? 'SYNCING...' : '↻ GITEA SYNC'}</Btn>
<Btn onClick={() => runSync('/api/projects/sync-all-sprints', 'sprint sync')} disabled={syncing}>{syncing ? '...' : '↻ SPRINT SYNC'}</Btn>
</div>
</div>
{loading ? <EmptyState>LOADING...</EmptyState> : projects.length === 0 ? <EmptyState>NO PROJECTS REGISTERED</EmptyState> : (
<ProjectList>
{projects.map((project) => (
<ProjectRow key={project.id} href={`/projects/${project.id}`}>
<Left>
<Meta>P-{String(project.id).padStart(3, '0')}</Meta>
<ProjectName>{project.name}</ProjectName>
<ProjectDesc>{project.description ?? '설명 없음'}</ProjectDesc>
</Left>
<Middle>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-sm)', flexWrap: 'wrap' }}>
<PhaseBadge $phase={project.phase}>{project.phase}</PhaseBadge>
<Meta>{project.currentSprint ? `SPRINT ${project.currentSprint}` : 'PLANNING BACKLOG'}</Meta>
{project.latestHotfix && <Meta>HOTFIX {project.latestHotfix}</Meta>}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-sm)' }}>
<TechBar style={{ flex: 1 }}><TechBarFill $width={project.progress ?? 0} /></TechBar>
<LabelMeta style={{ minWidth: 44, textAlign: 'right' }}>{project.progress ?? 0}%</LabelMeta>
</div>
</Middle>
<Right>
<Meta>{qaLabel(project)}</Meta>
<Meta>{project.deployStatus}</Meta>
<Meta>{new Date(project.updatedAt).toLocaleDateString('ko-KR')} UPDATED</Meta>
</Right>
</ProjectRow>
))}
</ProjectList>
)}
</>
);
}

View File

@@ -1,284 +0,0 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
interface Escalation {
id: string;
pipelineId: string;
reason: string;
errorCategory: string;
stage: string;
attempts: number;
contextSnapshot: string;
resolvedAt: string | null;
resolution: string | null;
createdAt: string;
}
const Page = styled.main`
display: flex;
flex-direction: column;
gap: 24px;
padding: 32px 36px;
max-width: 1400px;
margin: 0 auto;
width: 100%;
`;
const Header = styled.header`
display: flex;
justify-content: space-between;
align-items: flex-end;
flex-wrap: wrap;
gap: 16px;
`;
const Title = styled.h1`
font-size: 28px;
font-weight: 700;
margin: 0 0 4px;
letter-spacing: -0.01em;
`;
const Subtitle = styled.p`
font-size: 13px;
color: var(--text-secondary);
margin: 0;
`;
const Filters = styled.div`
display: flex;
gap: 8px;
`;
const FilterBtn = styled.button<{ $active: boolean }>`
padding: 8px 16px;
background: ${({ $active }) => ($active ? '#5fafff' : 'transparent')};
color: ${({ $active }) => ($active ? '#0a0a0a' : 'var(--text-primary)')};
border: 1px solid ${({ $active }) => ($active ? '#5fafff' : 'var(--border-color)')};
border-radius: 8px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
`;
const Cards = styled.div`
display: flex;
flex-direction: column;
gap: 12px;
`;
const Card = styled.div<{ $resolved: boolean }>`
background: var(--bg-input);
border: 1px solid ${({ $resolved }) => ($resolved ? 'var(--border-color)' : '#ef444460')};
border-left: 4px solid ${({ $resolved }) => ($resolved ? '#525252' : '#ef4444')};
border-radius: 12px;
padding: 20px 24px;
display: flex;
flex-direction: column;
gap: 12px;
`;
const CardHeader = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
`;
const Reason = styled.h3`
margin: 0;
font-size: 16px;
font-weight: 700;
flex: 1;
word-break: break-word;
`;
const Tags = styled.div`
display: flex;
gap: 8px;
flex-wrap: wrap;
`;
const Tag = styled.span<{ $color: string }>`
display: inline-block;
padding: 4px 12px;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
border-radius: 12px;
background: ${({ $color }) => $color}20;
color: ${({ $color }) => $color};
border: 1px solid ${({ $color }) => $color}60;
`;
const Meta = styled.div`
display: flex;
gap: 18px;
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
flex-wrap: wrap;
`;
const Snapshot = styled.details`
margin-top: 4px;
summary {
cursor: pointer;
font-size: 11px;
color: var(--text-secondary);
user-select: none;
}
pre {
margin: 8px 0 0;
background: var(--bg-surface);
border: 1px solid var(--border-color);
padding: 12px;
border-radius: 8px;
font-size: 11px;
overflow-x: auto;
}
`;
const Empty = styled.div`
padding: 60px 20px;
text-align: center;
color: var(--text-secondary);
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 12px;
`;
function categoryColor(c: string): string {
switch (c) {
case 'timeout':
return '#f97316';
case 'rate_limit':
return '#eab308';
case 'network':
return '#3b82f6';
case 'permission':
return '#ef4444';
case 'config':
return '#a855f7';
case 'invariant':
return '#ec4899';
default:
return '#6b7280';
}
}
function relTime(iso: string): string {
try {
const ms = Date.now() - new Date(iso).getTime();
const sec = Math.floor(ms / 1000);
if (sec < 60) return `${sec}s 전`;
if (sec < 3600) return `${Math.floor(sec / 60)}m 전`;
if (sec < 86400) return `${Math.floor(sec / 3600)}h 전`;
return `${Math.floor(sec / 86400)}d 전`;
} catch {
return iso;
}
}
export default function EscalationsPage() {
const [escalations, setEscalations] = useState<Escalation[]>([]);
const [filter, setFilter] = useState<'all' | 'unresolved' | 'resolved'>('all');
useEffect(() => {
const params = new URLSearchParams();
params.set('limit', '100');
if (filter === 'unresolved') params.set('resolved', 'false');
if (filter === 'resolved') params.set('resolved', 'true');
fetch(`${API_URL}/api/rails/escalations?${params.toString()}`, {
credentials: 'include',
})
.then((r) => r.json())
.then((data: { escalations: Escalation[] }) => setEscalations(data.escalations))
.catch(() => setEscalations([]));
}, [filter]);
return (
<Page>
<Header>
<div>
<Title>Escalations</Title>
<Subtitle>
</Subtitle>
</div>
<Filters>
<FilterBtn $active={filter === 'all'} onClick={() => setFilter('all')}>
</FilterBtn>
<FilterBtn
$active={filter === 'unresolved'}
onClick={() => setFilter('unresolved')}
>
</FilterBtn>
<FilterBtn
$active={filter === 'resolved'}
onClick={() => setFilter('resolved')}
>
</FilterBtn>
</Filters>
</Header>
{escalations.length === 0 ? (
<Empty>
{filter === 'unresolved' ? '미해결 에스컬레이션 없음 ✓' : '에스컬레이션 없음'}
</Empty>
) : (
<Cards>
{escalations.map((e) => (
<Card key={e.id} $resolved={!!e.resolvedAt}>
<CardHeader>
<Reason>{e.reason}</Reason>
<Tags>
<Tag $color={categoryColor(e.errorCategory)}>
{e.errorCategory}
</Tag>
{e.stage && <Tag $color="#6b7280">stage: {e.stage}</Tag>}
<Tag $color="#a855f7">attempts: {e.attempts}</Tag>
{e.resolvedAt ? (
<Tag $color="#22c55e">{e.resolution ?? 'resolved'}</Tag>
) : (
<Tag $color="#ef4444">unresolved</Tag>
)}
</Tags>
</CardHeader>
<Meta>
<span>id: {e.id}</span>
<span>pipeline: {e.pipelineId.slice(0, 12)}...</span>
<span>created: {relTime(e.createdAt)}</span>
{e.resolvedAt && <span>resolved: {relTime(e.resolvedAt)}</span>}
</Meta>
{e.contextSnapshot && (
<Snapshot>
<summary>Context snapshot</summary>
<pre>
{(() => {
try {
return JSON.stringify(JSON.parse(e.contextSnapshot), null, 2);
} catch {
return e.contextSnapshot;
}
})()}
</pre>
</Snapshot>
)}
</Card>
))}
</Cards>
)}
</Page>
);
}

View File

@@ -1,364 +0,0 @@
'use client';
import React, { useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
import { useRailsSocket } from '@/lib/useRailsSocket';
interface Transition {
id: number;
pipelineId: string;
fromState: string;
toState: string;
eventType: string;
timestamp: string;
}
const Page = styled.main`
display: flex;
flex-direction: column;
gap: 24px;
padding: 32px 36px;
max-width: 1600px;
margin: 0 auto;
width: 100%;
`;
const Header = styled.header`
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 24px;
flex-wrap: wrap;
`;
const Title = styled.h1`
font-size: 28px;
font-weight: 700;
margin: 0 0 4px;
letter-spacing: -0.01em;
`;
const Subtitle = styled.p`
font-size: 13px;
color: var(--text-secondary);
margin: 0;
`;
const Live = styled.span<{ $on: boolean }>`
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: ${({ $on }) => ($on ? '#22c55e' : 'var(--text-secondary)')};
&::before {
content: '';
width: 8px;
height: 8px;
border-radius: 50%;
background: ${({ $on }) => ($on ? '#22c55e' : '#525252')};
box-shadow: ${({ $on }) =>
$on ? '0 0 0 4px rgba(34, 197, 94, 0.15)' : 'none'};
}
`;
const Filters = styled.div`
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 14px 18px;
`;
const Input = styled.input`
padding: 8px 12px;
background: var(--bg-surface);
border: 1px solid var(--border-color);
color: var(--text-primary);
border-radius: 8px;
font-size: 13px;
font-family: var(--font-mono);
min-width: 280px;
`;
const Select = styled.select`
padding: 8px 12px;
background: var(--bg-surface);
border: 1px solid var(--border-color);
color: var(--text-primary);
border-radius: 8px;
font-size: 13px;
`;
const ClearBtn = styled.button`
padding: 8px 16px;
background: transparent;
color: var(--text-secondary);
border: 1px solid var(--border-color);
border-radius: 8px;
font-size: 12px;
cursor: pointer;
&:hover {
border-color: #5fafff;
color: var(--text-primary);
}
`;
const Counter = styled.div`
margin-left: auto;
font-size: 11px;
font-family: var(--font-mono);
color: var(--text-secondary);
`;
const LogTable = styled.div`
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 12px;
overflow: hidden;
`;
const Row = styled.div<{ $type: string }>`
display: grid;
grid-template-columns: 180px 90px 130px minmax(200px, 1fr) 130px;
gap: 16px;
padding: 12px 18px;
font-family: var(--font-mono);
font-size: 12px;
border-bottom: 1px solid var(--border-color);
align-items: center;
&:last-child {
border-bottom: none;
}
&:hover {
background: var(--bg-surface);
}
`;
const HeaderRow = styled(Row)`
background: var(--bg-surface);
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
font-size: 10px;
color: var(--text-secondary);
position: sticky;
top: 0;
z-index: 1;
`;
const Time = styled.span`
color: var(--text-secondary);
`;
const EventBadge = styled.span<{ $type: string }>`
display: inline-block;
padding: 3px 10px;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
border-radius: 12px;
color: #fff;
background: ${({ $type }) => eventColor($type)};
`;
const StateChip = styled.span<{ $state: string }>`
display: inline-block;
padding: 3px 10px;
font-size: 10px;
font-weight: 600;
border-radius: 12px;
background: ${({ $state }) => stateColor($state)}30;
color: ${({ $state }) => stateColor($state)};
border: 1px solid ${({ $state }) => stateColor($state)}60;
`;
const Arrow = styled.span`
color: var(--text-secondary);
margin: 0 6px;
`;
const PidChip = styled.button`
background: transparent;
border: 1px dashed var(--border-color);
color: var(--text-primary);
padding: 3px 8px;
border-radius: 6px;
font-family: var(--font-mono);
font-size: 11px;
cursor: pointer;
&:hover {
border-color: #5fafff;
border-style: solid;
}
`;
const Empty = styled.div`
padding: 60px 20px;
text-align: center;
color: var(--text-secondary);
`;
function eventColor(type: string): string {
switch (type) {
case 'REQUEST':
return '#8b5cf6';
case 'PLAN_READY':
case 'IMPL_DONE':
case 'APPROVE':
case 'DEPLOY_DONE':
return '#22c55e';
case 'REQUEST_CHANGES':
return '#f97316';
case 'ERROR':
case 'TIMEOUT':
return '#ef4444';
case 'ABORT':
return '#525252';
case 'RESUME':
case 'RETRY':
return '#5fafff';
default:
return '#6b7280';
}
}
function stateColor(state: string): string {
switch (state) {
case 'idle':
return '#6b7280';
case 'planning':
case 'implementing':
case 'reviewing':
case 'deploying':
return '#f97316';
case 'done':
return '#22c55e';
case 'escalated':
return '#ef4444';
case 'aborted':
return '#525252';
default:
return '#6b7280';
}
}
const EVENT_TYPES = [
'',
'REQUEST',
'PLAN_READY',
'IMPL_DONE',
'APPROVE',
'REQUEST_CHANGES',
'DEPLOY_DONE',
'ERROR',
'TIMEOUT',
'ABORT',
'RESUME',
];
export default function RailsLogPage() {
const [transitions, setTransitions] = useState<Transition[]>([]);
const [pipelineFilter, setPipelineFilter] = useState('');
const [eventFilter, setEventFilter] = useState('');
const [tick, setTick] = useState(0);
const { connected } = useRailsSocket({
onPipelineUpdated: () => setTick((n) => n + 1),
});
useEffect(() => {
const params = new URLSearchParams();
params.set('limit', '300');
if (pipelineFilter) params.set('pipelineId', pipelineFilter);
if (eventFilter) params.set('eventType', eventFilter);
fetch(`${API_URL}/api/rails/transitions?${params.toString()}`, {
credentials: 'include',
})
.then((r) => r.json())
.then((data: { transitions: Transition[] }) => setTransitions(data.transitions))
.catch(() => setTransitions([]));
}, [pipelineFilter, eventFilter, tick]);
const visible = useMemo(() => transitions, [transitions]);
return (
<Page>
<Header>
<div>
<Title>SIEM Log</Title>
<Subtitle>Rails state transitions </Subtitle>
</div>
<Live $on={connected}>{connected ? 'LIVE' : 'OFFLINE'}</Live>
</Header>
<Filters>
<Input
placeholder="pipeline id 필터 (ULID)"
value={pipelineFilter}
onChange={(e) => setPipelineFilter(e.target.value.trim())}
/>
<Select
value={eventFilter}
onChange={(e) => setEventFilter(e.target.value)}
>
{EVENT_TYPES.map((t) => (
<option key={t || 'all'} value={t}>
{t || '— all events —'}
</option>
))}
</Select>
{(pipelineFilter || eventFilter) && (
<ClearBtn
onClick={() => {
setPipelineFilter('');
setEventFilter('');
}}
>
</ClearBtn>
)}
<Counter>{visible.length} entries</Counter>
</Filters>
<LogTable>
<HeaderRow $type="">
<span>Timestamp</span>
<span>Event</span>
<span>Pipeline</span>
<span>Transition</span>
<span></span>
</HeaderRow>
{visible.length === 0 ? (
<Empty>No transitions matching the filters.</Empty>
) : (
visible.map((t) => (
<Row key={t.id} $type={t.eventType}>
<Time>{new Date(t.timestamp).toLocaleString('ko-KR')}</Time>
<EventBadge $type={t.eventType}>{t.eventType}</EventBadge>
<PidChip onClick={() => setPipelineFilter(t.pipelineId)}>
{t.pipelineId.slice(0, 12)}...
</PidChip>
<span>
<StateChip $state={t.fromState}>{t.fromState}</StateChip>
<Arrow></Arrow>
<StateChip $state={t.toState}>{t.toState}</StateChip>
</span>
<span />
</Row>
))
)}
</LogTable>
</Page>
);
}

View File

@@ -10,6 +10,7 @@ import {
} from '@/lib/useRailsSocket';
import SubTaskTree from '@/components/rails/SubTaskTree';
import SubTaskDetailDrawer from '@/components/rails/SubTaskDetailDrawer';
import TransitionsTimeline from '@/components/rails/TransitionsTimeline';
const Page = styled.main`
display: flex;
@@ -457,6 +458,8 @@ export default function RailsPage() {
) : (
<Empty> sub-task .</Empty>
)}
<TransitionsTimeline pipelineId={selected.id} />
</>
) : (
<Empty> .</Empty>

View File

@@ -1,218 +0,0 @@
'use client';
import React, { useEffect, useState, useCallback } from 'react';
import { useParams } from 'next/navigation';
import styled from 'styled-components';
import Link from 'next/link';
import { LabelMeta, TechBar, TechBarFill, Timeline, TimelineItem, TimeStamp, TimelineContent, Btn } from '@/components/ui/base';
import { API_URL } from '@/lib/config';
import SisterAvatar from '@/components/common/SisterAvatar';
import { SISTER_ROLES } from '@/lib/sisters';
import { adminFetch } from '@/lib/adminFetch';
import CodeEditor from '@/components/admin/CodeEditor';
import LogTerminal from '@/components/admin/LogTerminal';
const Breadcrumb = styled.div`font-family: var(--font-mono);font-size: 11px;color: var(--text-secondary);margin-bottom: var(--space-md);a { color: var(--text-secondary); text-decoration: none; &:hover { color: var(--text-primary); } }`;
const Hero = styled.section`display:grid;grid-template-columns:128px 1fr;gap:var(--space-xl);align-items:center;padding:var(--space-xl);border:1px solid var(--border-color);margin-bottom:var(--space-xl);@media (max-width:767px){grid-template-columns:1fr;justify-items:start;}`;
const HeroMeta = styled.div`display:flex;flex-direction:column;gap:var(--space-sm);`;
const HeroName = styled.div`font-size:36px;font-weight:700;letter-spacing:-0.03em;color:var(--text-primary);`;
const HeroRole = styled.div`font-size:14px;color:var(--text-secondary);font-family:var(--font-mono);`;
const HeroStatus = styled.div`display:flex;align-items:center;gap:var(--space-sm);margin-top:var(--space-sm);flex-wrap:wrap;`;
const StatusDot = styled.div<{ $on: boolean }>`width:10px;height:10px;border-radius:50%;background:${({$on})=>$on?'#FFF':'#555'};${({$on})=>$on&&`box-shadow:0 0 8px rgba(255,255,255,0.3);`}`;
const HeroStats = styled.div`display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:var(--space-md);margin-top:var(--space-lg);@media (max-width:767px){grid-template-columns:repeat(2,minmax(0,1fr));}`;
const StatCard = styled.div`border:1px solid var(--border-color);padding:var(--space-md);`;
const StatLabel = styled.div`font-size:10px;color:var(--text-secondary);font-family:var(--font-mono);margin-bottom:6px;`;
const StatValue = styled.div`font-size:18px;color:var(--text-primary);font-family:var(--font-mono);`;
const DetailGrid = styled.div`display:grid;grid-template-columns:320px 1fr;gap:var(--space-xxl);align-items:start;@media (max-width:1199px){grid-template-columns:1fr;gap:var(--space-xl);}`;
const MetaPanel = styled.div`display:flex;flex-direction:column;gap:var(--space-lg);`;
const MetaCard = styled.div`border:1px solid var(--border-color);padding:var(--space-lg);`;
const TabBar = styled.div`display:flex;gap:var(--space-lg);border-bottom:1px solid var(--border-color);margin-bottom:var(--space-lg);overflow:auto;`;
const TabBtn = styled.button<{ $active: boolean }>`font-size:13px;font-weight:500;color:${({$active})=>$active?'var(--text-primary)':'var(--text-secondary)'};background:transparent;border:none;border-bottom:1px solid ${({$active})=>$active?'var(--text-primary)':'transparent'};padding:var(--space-sm) 0;cursor:pointer;transition:color .15s,border-color .15s;white-space:nowrap;&:hover{color:var(--text-primary);}`;
const Toolbar = styled.div`display:flex;align-items:center;gap:10px;margin-bottom:12px;flex-wrap:wrap;`;
const Select = styled.select`background:var(--bg-surface);border:1px solid var(--border-color);border-radius:7px;color:var(--text-primary);padding:8px 12px;font-size:13px;cursor:pointer;outline:none;option{background:#1a1f2a;}`;
const LinesInput = styled.input`background:var(--bg-surface);border:1px solid var(--border-color);border-radius:7px;color:var(--text-primary);padding:8px 12px;font-size:13px;width:80px;outline:none;`;
const ResultMsg = styled.div<{ $success: boolean }>`padding:8px 12px;border-radius:6px;font-size:12px;font-family:monospace;background:${({$success})=>$success?'rgba(0,230,118,0.08)':'rgba(255,23,68,0.08)'};color:${({$success})=>$success?'#00FF00':'#FF1744'};border:1px solid ${({$success})=>$success?'rgba(0,230,118,0.3)':'rgba(255,23,68,0.3)'};margin-bottom:12px;`;
const SessionCard = styled.div`border:1px solid var(--border-color);padding:var(--space-md);margin-bottom:var(--space-sm);`;
const SISTER_DISPLAY: Record<string, string> = { harang: '하랑이', narang: '나랑이', darang: '다랑이', erang: '이랑이' };
const FILES = ['SOUL.md', 'AGENTS.md', 'TOOLS.md', 'PROTOCOL.md', 'HEARTBEAT.md'];
interface SisterInfo {
id?: number;
name: string;
status?: string;
lxcId?: string | number | null;
lastSeen?: string | null;
user?: string | null;
}
interface SystemInfo {
uptime?: string;
cpu?: number;
memory?: { used?: number; total?: number };
disk?: { used?: string; total?: string };
}
interface ConfigData {
description?: string | null;
}
interface ActivityItem {
id: number;
createdAt: string;
action?: string;
detail?: string | null;
}
interface ActivityResponse {
items?: ActivityItem[];
}
interface SessionItem {
id?: string | number;
title?: string;
label?: string;
status?: string;
}
interface SessionsResponse {
sessions?: SessionItem[];
items?: SessionItem[];
}
interface HarnessResponse {
content?: string;
}
interface SaveHarnessResponse {
success?: boolean;
error?: string;
}
interface LogResponse {
lines?: string[];
}
export default function SisterDetailPage() {
const { name } = useParams<{ name: string }>();
const [sisterInfo, setSisterInfo] = useState<SisterInfo | null>(null);
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
const [configData, setConfigData] = useState<ConfigData | null>(null);
const [activity, setActivity] = useState<ActivityItem[]>([]);
const [sessions, setSessions] = useState<SessionItem[]>([]);
const [tab, setTab] = useState('overview');
const [loading, setLoading] = useState(true);
const [logLines, setLogLines] = useState<string[]>([]);
const [logLoading, setLogLoading] = useState(false);
const [lines, setLines] = useState(100);
const [selectedFile, setSelectedFile] = useState('SOUL.md');
const [content, setContent] = useState('');
const [saved, setSaved] = useState('');
const [saveResult, setSaveResult] = useState<{ success: boolean; msg: string } | null>(null);
useEffect(() => {
Promise.allSettled([
fetch(`${API_URL}/api/sisters`),
fetch(`${API_URL}/api/sisters/${name}/config`),
fetch(`${API_URL}/api/sisters/${name}/activity`),
fetch(`${API_URL}/api/sisters/${name}/system`),
fetch(`${API_URL}/api/sisters/${name}/sessions`),
]).then(([sRes, cRes, aRes, syRes, ssRes]) => {
if (sRes.status === 'fulfilled' && sRes.value.ok) sRes.value.json().then((d: SisterInfo[]) => setSisterInfo(d.find((s) => s.name === name) ?? null));
if (cRes.status === 'fulfilled' && cRes.value.ok) cRes.value.json().then((data: ConfigData) => setConfigData(data));
if (aRes.status === 'fulfilled' && aRes.value.ok) aRes.value.json().then((d: ActivityResponse) => setActivity(d.items ?? []));
if (syRes.status === 'fulfilled' && syRes.value.ok) syRes.value.json().then((data: SystemInfo) => setSystemInfo(data));
if (ssRes.status === 'fulfilled' && ssRes.value.ok) ssRes.value.json().then((d: SessionsResponse) => setSessions(d.sessions ?? d.items ?? []));
}).finally(() => setLoading(false));
}, [name]);
const fetchLogs = useCallback(async () => {
setLogLoading(true);
try {
const res = await adminFetch(`/api/admin/logs/${name}?lines=${lines}`);
const d: LogResponse = await res.json();
setLogLines(d.lines ?? []);
} catch {
setLogLines(['(로그 로드 실패)']);
} finally {
setLogLoading(false);
}
}, [name, lines]);
useEffect(() => { if (tab === 'logs') fetchLogs(); }, [tab, fetchLogs]);
useEffect(() => {
if (tab !== 'harness') return;
setSaveResult(null);
adminFetch(`/api/admin/harness/${name}/${selectedFile}`)
.then((r) => r.json())
.then((d: HarnessResponse) => { setContent(d.content ?? ''); setSaved(d.content ?? ''); })
.catch(() => setContent('(로드 실패)'));
}, [tab, name, selectedFile]);
const handleSave = async () => {
setSaveResult(null);
try {
const res = await adminFetch(`/api/admin/harness/${name}/${selectedFile}`, { method: 'PUT', body: JSON.stringify({ content }) });
const d: SaveHarnessResponse = await res.json();
if (d.success) { setSaved(content); setSaveResult({ success: true, msg: '저장 완료' }); }
else setSaveResult({ success: false, msg: d.error ?? '저장 실패' });
} catch (e) {
setSaveResult({ success: false, msg: (e as Error).message });
}
};
const isActive = sisterInfo?.status === 'online' || sisterInfo?.status === 'working';
return (
<>
<Breadcrumb><Link href="/sisters"> </Link> / {SISTER_DISPLAY[name] ?? name}</Breadcrumb>
{loading ? <div style={{ color: 'var(--text-secondary)', fontSize: '13px', fontFamily: 'var(--font-mono)' }}>LOADING...</div> : <>
<Hero>
<SisterAvatar name={name} size={120} />
<HeroMeta>
<HeroName>{SISTER_DISPLAY[name] ?? name}</HeroName>
<HeroRole>{SISTER_ROLES[name] ?? 'UNKNOWN'}</HeroRole>
<HeroStatus>
<StatusDot $on={isActive} />
<LabelMeta>{isActive ? 'ACTIVE' : 'STANDBY'}</LabelMeta>
<LabelMeta><span>LXC:</span>{sisterInfo?.lxcId ?? '--'}</LabelMeta>
</HeroStatus>
<HeroStats>
<StatCard><StatLabel>UPTIME</StatLabel><StatValue>{systemInfo?.uptime ?? '--:--:--'}</StatValue></StatCard>
<StatCard><StatLabel>CPU</StatLabel><StatValue>{systemInfo?.cpu?.toFixed?.(1) ?? '0.0'}%</StatValue></StatCard>
<StatCard><StatLabel>MEM</StatLabel><StatValue>{systemInfo?.memory?.used ?? 0}/{systemInfo?.memory?.total ?? 0}MB</StatValue></StatCard>
<StatCard><StatLabel>DISK</StatLabel><StatValue>{systemInfo?.disk?.used ?? '0G'}/{systemInfo?.disk?.total ?? '0G'}</StatValue></StatCard>
</HeroStats>
</HeroMeta>
</Hero>
<DetailGrid>
<MetaPanel>
<MetaCard>
<LabelMeta style={{ marginBottom: 'var(--space-sm)', display: 'block' }}>SYSTEM SUMMARY</LabelMeta>
<div style={{ margin: 'var(--space-md) 0', fontFamily: 'var(--font-mono)', fontSize: '11px', color: 'var(--text-secondary)', lineHeight: 1.8 }}>
LAST_SEEN: {sisterInfo?.lastSeen ? new Date(sisterInfo.lastSeen).toLocaleString() : '--'}<br />
ROLE: {SISTER_ROLES[name] ?? '--'}<br />
STATUS: {String(sisterInfo?.status ?? 'unknown').toUpperCase()}<br />
HOST_USER: {sisterInfo?.user ?? '--'}
</div>
<TechBar><TechBarFill $width={isActive ? 100 : 0} /></TechBar>
</MetaCard>
{configData?.description && <MetaCard><LabelMeta style={{ marginBottom: 'var(--space-sm)', display: 'block' }}>DESC</LabelMeta><div style={{ fontSize: '12px', color: 'var(--text-secondary)', lineHeight: 1.6 }}>{configData.description}</div></MetaCard>}
</MetaPanel>
<div>
<TabBar>
{[{ id: 'overview', label: '개요' }, { id: 'sessions', label: '세션' }, { id: 'activity', label: '활동' }, { id: 'harness', label: '하네스' }, { id: 'logs', label: '로그' }].map((t) => <TabBtn key={t.id} $active={tab === t.id} onClick={() => setTab(t.id)}>{t.label}</TabBtn>)}
</TabBar>
{tab === 'overview' && <Timeline>{activity.slice(0, 8).map((item) => <TimelineItem key={item.id}><TimeStamp>{new Date(item.createdAt).toLocaleString('ko-KR', { hour12: false })}</TimeStamp><TimelineContent>{item.detail ?? item.action}</TimelineContent></TimelineItem>)}</Timeline>}
{tab === 'sessions' && <>{sessions.length === 0 ? <div style={{ color: 'var(--text-secondary)' }}> </div> : sessions.map((session, i: number) => <SessionCard key={session.id ?? i}><div style={{ color: 'var(--text-primary)', fontSize: '13px' }}>{session.title ?? session.label ?? session.id ?? 'session'}</div><div style={{ color: 'var(--text-secondary)', fontSize: '11px', fontFamily: 'var(--font-mono)' }}>{session.status ?? ''}</div></SessionCard>)}</>}
{tab === 'activity' && <Timeline>{activity.map((item) => <TimelineItem key={item.id}><TimeStamp>{new Date(item.createdAt).toLocaleString('ko-KR', { hour12: false })}</TimeStamp><TimelineContent>{item.detail ?? item.action}</TimelineContent></TimelineItem>)}</Timeline>}
{tab === 'harness' && <><Toolbar><Select value={selectedFile} onChange={(e) => setSelectedFile(e.target.value)}>{FILES.map((f) => <option key={f} value={f}>{f}</option>)}</Select><Btn onClick={() => { setContent(saved); setSaveResult(null); }}></Btn><Btn onClick={handleSave}></Btn></Toolbar>{saveResult && <ResultMsg $success={saveResult.success}>{saveResult.msg}</ResultMsg>}<CodeEditor value={content} onChange={setContent} /></>}
{tab === 'logs' && <><Toolbar><span style={{ color: 'var(--text-secondary)', fontSize: '12px' }}></span><LinesInput type="number" value={lines} onChange={(e) => setLines(parseInt(e.target.value, 10) || 100)} min={10} max={500} /><span style={{ color: 'var(--text-secondary)', fontSize: '12px' }}></span><Btn onClick={fetchLogs}>{logLoading ? '로딩 중...' : '로그 가져오기'}</Btn></Toolbar><LogTerminal lines={logLines} /></>}
</div>
</DetailGrid>
</>}
</>
);
}

View File

@@ -1,135 +0,0 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled, { keyframes } from 'styled-components';
import Link from 'next/link';
import { PageTitle, LabelMeta, BtnToggle } from '@/components/ui/base';
import { API_URL } from '@/lib/config';
import SisterAvatar from '@/components/common/SisterAvatar';
const pulse = keyframes`0%{opacity:.35}50%{opacity:.7}100%{opacity:.35}`;
const SISTER_ROLES: Record<string, string> = { harang: 'Primary', narang: 'Secondary', darang: 'Standby', erang: 'Sync' };
interface SisterListItem {
id?: number;
name: string;
status: string;
uptime?: string;
lastSeen?: string | null;
cpu?: number;
lxcId?: string | number | null;
currentTask?: string | null;
memory?: { used?: number; total?: number };
disk?: { used?: string; total?: string };
}
const NodeGrid = styled.section`display:flex;flex-direction:column;gap:var(--space-lg);`;
const NodeEntry = styled(Link)`display:grid;grid-template-columns:220px 1fr 180px;gap:0;border:1px solid var(--border-color);transition:border-color .2s, background .15s;text-decoration:none;&:hover{border-color:var(--border-hover);background:#111}@media (max-width:1199px){grid-template-columns:200px 1fr}@media (max-width:767px){grid-template-columns:1fr}`;
const NodeInfo = styled.div`border-right:1px solid var(--border-color);padding:var(--space-lg);display:flex;flex-direction:column;gap:var(--space-md);@media (max-width:767px){border-right:none;border-bottom:1px solid var(--border-color)}`;
const NodeName = styled.div`display:flex;align-items:center;gap:var(--space-sm);font-size:16px;font-weight:600;color:var(--text-primary);`;
const StatusIndicator = styled.div<{ $active: boolean }>`width:8px;height:8px;border-radius:50%;background:${({$active})=>$active?'#FFF':'#555'};flex-shrink:0;${({$active})=>$active&&`box-shadow:0 0 8px rgba(255,255,255,.3);`}`;
const MetaPair = styled.div`display:flex;flex-direction:column;gap:2px;`;
const MetaVal = styled.div`font-size:13px;color:var(--text-primary);font-family:var(--font-mono);`;
const NodeControls = styled.div`display:flex;gap:var(--space-sm);flex-wrap:wrap;`;
const CapacitySection = styled.div`border-right:1px solid var(--border-color);padding:var(--space-lg);display:flex;flex-direction:column;gap:var(--space-md);@media (max-width:1199px){border-right:none}@media (max-width:767px){border-bottom:1px solid var(--border-color)}`;
const BarWrap = styled.div`display:flex;flex-direction:column;gap:8px;`;
const BarRow = styled.div`display:flex;align-items:center;gap:8px;font-family:var(--font-mono);font-size:11px;color:var(--text-secondary);`;
const Bar = styled.div`flex:1;height:8px;background:#151515;border:1px solid #222;overflow:hidden;`;
const Fill = styled.div<{ $width:number }>`height:100%;width:${({$width})=>$width}%;background:var(--text-primary);min-width:${({$width})=>$width > 0 ? '2px' : '0'};`;
const OpsMeta = styled.div`padding:var(--space-lg);display:flex;flex-direction:column;gap:var(--space-sm);@media (max-width:1199px){display:none}`;
const MetaRow = styled.div`display:flex;justify-content:space-between;font-family:var(--font-mono);font-size:11px;color:var(--text-secondary);padding:2px 0;gap:var(--space-md);`;
const Skeleton = styled.div`height:120px;border:1px solid var(--border-color);background:#111;animation:${pulse} 1.4s ease-in-out infinite;`;
const ErrorBox = styled.div`padding:var(--space-lg);border:1px solid #5a2a2a;color:#ff9b9b;`;
function getNodeStatus(s: SisterListItem): boolean { return s.status === 'online' || s.status === 'working'; }
function getStatusBtns(s: SisterListItem): [string, string] { if (s.status === 'offline') return ['STANDBY', 'ACTIVATE']; return ['ACTIVE', 'REBOOT']; }
function diskPercent(disk?: SisterListItem['disk']): number {
if (!disk?.used || !disk?.total) return 0;
const parse = (v: string) => {
const m = String(v).match(/([0-9.]+)\s*([KMGTP]?)/i);
if (!m) return 0;
const n = parseFloat(m[1]);
const unit = (m[2] || 'G').toUpperCase();
const scale: Record<string, number> = { K: 1/1024/1024, M: 1/1024, G: 1, T: 1024, P: 1024*1024, '': 1 };
return n * (scale[unit] ?? 1);
};
const used = parse(disk.used);
const total = parse(disk.total);
if (!isFinite(used) || !isFinite(total) || total <= 0) return 0;
return Math.max(0, Math.min(100, (used / total) * 100));
}
export default function SistersPage() {
const [sisters, setSisters] = useState<SisterListItem[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let active = true;
const load = async () => {
try {
const base: SisterListItem[] = await fetch(`${API_URL}/api/sisters`).then((r) => r.ok ? r.json() : Promise.reject());
const withSystem = await Promise.all(base.map(async (s: SisterListItem) => {
try {
const system = await fetch(`${API_URL}/api/sisters/${s.name}/system`).then((r) => r.ok ? r.json() : null);
return { ...s, ...(system ?? {}) };
} catch {
return { ...s, uptime: '00:00:00', cpu: 0, memory: { used: 0, total: 0 }, disk: { used: '0G', total: '0G' } };
}
}));
if (active) { setSisters(withSystem); setError(null); }
} catch {
if (active) setError('데이터를 불러올 수 없습니다');
} finally {
if (active) setLoading(false);
}
};
load();
const iv = setInterval(load, 15000);
return () => { active = false; clearInterval(iv); };
}, []);
return (
<>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 'var(--space-lg)' }}>
<PageTitle> </PageTitle>
<LabelMeta><span>TOTAL NODES:</span> {String(sisters.length).padStart(2, '0')}</LabelMeta>
</div>
{error && <ErrorBox>{error}</ErrorBox>}
<NodeGrid>
{loading ? Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} />) : sisters.map((s) => {
const isActive = getNodeStatus(s);
const [btn1, btn2] = getStatusBtns(s);
return (
<NodeEntry key={s.id ?? s.name} href={`/sisters/${s.name}`}>
<NodeInfo>
<NodeName>
<StatusIndicator $active={isActive} />
<SisterAvatar name={s.name} size={28} />
{s.name === 'harang' ? '하랑' : s.name === 'narang' ? '나랑' : s.name === 'darang' ? '다랑' : '이랑'} ({SISTER_ROLES[s.name] ?? s.name})
</NodeName>
<MetaPair><LabelMeta>Uptime</LabelMeta><MetaVal>{s.uptime ?? '00:00:00'}</MetaVal></MetaPair>
<MetaPair><LabelMeta>Last Seen</LabelMeta><MetaVal>{s.lastSeen ? new Date(s.lastSeen).toLocaleString('ko-KR') : '—'}</MetaVal></MetaPair>
<NodeControls><BtnToggle>{btn1}</BtnToggle><BtnToggle>{btn2}</BtnToggle></NodeControls>
</NodeInfo>
<CapacitySection>
<BarWrap>
<BarRow><span>CPU</span><span>{s.cpu?.toFixed?.(1) ?? '0.0'}%</span><Bar><Fill $width={Math.max(0, Math.min(100, Number(s.cpu ?? 0)))} /></Bar></BarRow>
<BarRow><span>MEM</span><span>{s.memory?.used ?? 0}/{s.memory?.total ?? 0}MB</span><Bar><Fill $width={s.memory?.total ? Math.max(0, Math.min(100, (((s.memory.used ?? 0) / s.memory.total) * 100))) : 0} /></Bar></BarRow>
<BarRow><span>DSK</span><span>{s.disk?.used ?? '0G'}/{s.disk?.total ?? '0G'}</span><Bar><Fill $width={diskPercent(s.disk)} /></Bar></BarRow>
</BarWrap>
</CapacitySection>
<OpsMeta>
<MetaRow><span>STATUS</span><span>{String(s.status).toUpperCase()}</span></MetaRow>
<MetaRow><span>ROLE</span><span>{String(SISTER_ROLES[s.name] ?? s.name).toUpperCase()}</span></MetaRow>
<MetaRow><span>LXC ID</span><span>{s.lxcId ?? '--'}</span></MetaRow>
<MetaRow><span>LAST CHECK</span><span>{s.lastSeen ? 'just synced' : '--'}</span></MetaRow>
<MetaRow><span>CURRENT TASK</span><span>{s.currentTask ?? '-'}</span></MetaRow>
</OpsMeta>
</NodeEntry>
);
})}
</NodeGrid>
</>
);
}

View File

@@ -7,17 +7,9 @@ import { usePathname } from 'next/navigation';
import { useAuth } from '@/lib/AuthContext';
const NAV_ITEMS = [
{ href: '/', label: '대시' },
{ href: '/rails', label: '레일' },
{ href: '/rails/log', label: '로그' },
{ href: '/rails/escalations', label: '경보' },
{ href: '/office', label: '오피스' },
{ href: '/projects', label: '프로' },
{ href: '/activities', label: '활동' },
{ href: '/sisters', label: '자매' },
{ href: '/org', label: '조직' },
{ href: '/settings', label: '설정' },
{ href: '/admin', label: '관리' },
{ href: '/', label: '🏢 사무실' },
{ href: '/rails', label: '🚦 레일' },
{ href: '/settings', label: '⚙️ 설정' },
];
const SidebarWrapper = styled.aside`

View File

@@ -0,0 +1,188 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import Link from 'next/link';
import { API_URL } from '@/lib/config';
interface Pipeline {
id: string;
projectName: string;
currentState: string;
createdAt: string;
}
const Wrapper = styled.section`
display: flex;
flex-direction: column;
gap: 12px;
`;
const Header = styled.div`
display: flex;
align-items: baseline;
justify-content: space-between;
`;
const Title = styled.h2`
font-size: 14px;
font-weight: 700;
margin: 0;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-secondary);
`;
const ViewAll = styled(Link)`
font-size: 11px;
font-family: var(--font-mono);
color: var(--text-secondary);
text-decoration: none;
&:hover {
color: #5fafff;
}
`;
const Strip = styled.div`
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 10px;
`;
const Card = styled(Link)`
display: flex;
flex-direction: column;
gap: 6px;
padding: 12px 14px;
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 10px;
text-decoration: none;
color: inherit;
transition: border-color 0.15s;
&:hover {
border-color: #5fafff;
}
`;
const CardTop = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
`;
const ProjectName = styled.span`
font-size: 13px;
font-weight: 600;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const StateBadge = styled.span<{ $state: string }>`
font-size: 9px;
font-weight: 700;
text-transform: uppercase;
padding: 2px 8px;
border-radius: 10px;
color: #fff;
background: ${({ $state }) => {
switch ($state) {
case 'done':
return '#22c55e';
case 'planning':
return '#8b5cf6';
case 'implementing':
return '#3b82f6';
case 'reviewing':
return '#f59e0b';
case 'deploying':
return '#0ea5e9';
case 'escalated':
case 'failed':
return '#ef4444';
default:
return '#6b7280';
}
}};
`;
const PipelineId = styled.span`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
`;
const Empty = styled.div`
padding: 24px;
text-align: center;
font-size: 12px;
color: var(--text-secondary);
font-family: var(--font-mono);
background: var(--bg-input);
border: 1px dashed var(--border-color);
border-radius: 10px;
`;
export default function ActivePipelineStrip() {
const [pipelines, setPipelines] = useState<Pipeline[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
const load = async () => {
try {
const res = await fetch(`${API_URL}/api/rails/pipelines?limit=8`, {
credentials: 'include',
});
if (!res.ok) {
if (!cancelled) setLoading(false);
return;
}
const data = (await res.json()) as { pipelines?: Pipeline[] };
if (!cancelled) {
setPipelines(data.pipelines ?? []);
setLoading(false);
}
} catch {
if (!cancelled) setLoading(false);
}
};
void load();
const t = setInterval(load, 5000);
return () => {
cancelled = true;
clearInterval(t);
};
}, []);
return (
<Wrapper>
<Header>
<Title> </Title>
<ViewAll href="/rails"> </ViewAll>
</Header>
{loading && pipelines.length === 0 ? (
<Empty> ...</Empty>
) : pipelines.length === 0 ? (
<Empty> </Empty>
) : (
<Strip>
{pipelines.map((p) => (
<Card key={p.id} href={`/rails?pipelineId=${p.id}`}>
<CardTop>
<ProjectName>{p.projectName}</ProjectName>
<StateBadge $state={p.currentState}>{p.currentState}</StateBadge>
</CardTop>
<PipelineId>{p.id.slice(0, 12)}</PipelineId>
</Card>
))}
</Strip>
)}
</Wrapper>
);
}

View File

@@ -0,0 +1,143 @@
'use client';
import React, { useEffect, useRef, useState, useCallback } from 'react';
import dynamic from 'next/dynamic';
import styled from 'styled-components';
import SisterDetailPanel from './SisterDetailPanel';
/**
* Phaser is a heavy WebGL library that touches `window` on import. We must
* dynamic-import it client-side only to keep Next.js SSR happy.
*/
const PhaserHostInner = dynamic(() => import('./PhaserHost'), {
ssr: false,
loading: () => <LoadingHost> ...</LoadingHost>,
});
const Wrapper = styled.div`
position: relative;
display: grid;
grid-template-columns: minmax(0, 1fr) 320px;
gap: 16px;
width: 100%;
min-height: 600px;
@media (max-width: 1024px) {
grid-template-columns: 1fr;
}
`;
const SceneCard = styled.div`
position: relative;
background: #0b0b14;
border: 1px solid var(--border-color);
border-radius: 14px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
min-height: 600px;
image-rendering: pixelated;
`;
const Header = styled.div`
position: absolute;
top: 12px;
left: 16px;
right: 16px;
display: flex;
justify-content: space-between;
align-items: center;
z-index: 10;
pointer-events: none;
`;
const HeaderLabel = styled.span`
font-family: var(--font-mono);
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-secondary);
background: rgba(0, 0, 0, 0.45);
padding: 4px 10px;
border-radius: 12px;
border: 1px solid var(--border-color);
`;
const Hint = styled.div`
position: absolute;
bottom: 12px;
left: 16px;
right: 16px;
text-align: center;
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
opacity: 0.7;
pointer-events: none;
z-index: 10;
`;
const LoadingHost = styled.div`
font-family: var(--font-mono);
font-size: 12px;
color: var(--text-secondary);
`;
const PanelHost = styled.aside`
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 14px;
padding: 18px;
display: flex;
flex-direction: column;
gap: 16px;
min-height: 600px;
`;
const PanelEmpty = styled.div`
flex: 1;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
font-size: 12px;
color: var(--text-secondary);
font-family: var(--font-mono);
line-height: 1.6;
`;
export default function OfficeRpg() {
const [selectedSister, setSelectedSister] = useState<string | null>(null);
const handleSisterClick = useCallback((name: string) => {
setSelectedSister((prev) => (prev === name ? null : name));
}, []);
return (
<Wrapper>
<SceneCard>
<Header>
<HeaderLabel>🏢 </HeaderLabel>
<HeaderLabel>4 SISTERS · LIVE</HeaderLabel>
</Header>
<PhaserHostInner onSisterClick={handleSisterClick} />
<Hint> </Hint>
</SceneCard>
<PanelHost>
{selectedSister ? (
<SisterDetailPanel
name={selectedSister}
onClose={() => setSelectedSister(null)}
/>
) : (
<PanelEmpty>
👀 <br />
</PanelEmpty>
)}
</PanelHost>
</Wrapper>
);
}

View File

@@ -0,0 +1,173 @@
import * as Phaser from 'phaser';
import {
TILE_SIZE,
CHAR_W,
CHAR_H,
SISTER_PALETTES,
registerAllTextures,
} from './spriteFactory';
/**
* 16x12 tile office layout, encoded as a string. Each character is one
* tile. Total scene size = 256 x 192 px (then upscaled by camera zoom).
*
* Legend:
* # : wall
* . : floor (wood)
* , : carpet
* D : desk
* c : chair (decorative — sister sprite stands in front)
* _ : empty / outside (rendered black)
* 1 : harang spawn
* 2 : narang spawn
* 3 : darang spawn
* 4 : erang spawn
*/
const LAYOUT = [
'################',
'#..............#',
'#..D..D..D..D..#',
'#..1..2..3..4..#',
'#..............#',
'#,,,,,,,,,,,,,,#',
'#,,,,,,,,,,,,,,#',
'#..............#',
'#####......#####',
'#............,,#',
'#............,,#',
'################',
];
export const OFFICE_W_TILES = LAYOUT[0]!.length;
export const OFFICE_H_TILES = LAYOUT.length;
export const SISTER_KEYS: Array<keyof typeof SISTER_PALETTES> = [
'harang',
'narang',
'darang',
'erang',
];
export interface OfficeSceneEvents {
onSisterClick?: (sister: string) => void;
}
interface SisterStateMap {
[name: string]: 'idle' | 'working' | 'speaking' | 'error';
}
export class OfficeScene extends Phaser.Scene {
private sisterSprites = new Map<string, Phaser.GameObjects.Sprite>();
private statusBubbles = new Map<string, Phaser.GameObjects.Text>();
private events_: OfficeSceneEvents = {};
private currentStates: SisterStateMap = {};
constructor() {
super({ key: 'OfficeScene' });
}
init(data: OfficeSceneEvents): void {
this.events_ = data ?? {};
}
/** Public setter so React can update the click handler post-mount. */
setEvents(events: OfficeSceneEvents): void {
this.events_ = events;
}
preload(): void {
registerAllTextures(this);
}
create(): void {
// ── Tilemap render ──────────────────────────────────────────
const tileWorld = (col: number, row: number): { x: number; y: number } => ({
x: col * TILE_SIZE + TILE_SIZE / 2,
y: row * TILE_SIZE + TILE_SIZE / 2,
});
for (let row = 0; row < OFFICE_H_TILES; row++) {
const line = LAYOUT[row]!;
for (let col = 0; col < OFFICE_W_TILES; col++) {
const ch = line[col]!;
const { x, y } = tileWorld(col, row);
// Background — almost everything has floor or carpet under it
let baseTexture = '';
if (ch === ',') baseTexture = 'tile-carpet';
else if (ch === '#') baseTexture = 'tile-wall';
else if (ch === '_') baseTexture = '';
else baseTexture = 'tile-floor';
if (baseTexture) {
this.add.image(x, y, baseTexture).setOrigin(0.5, 0.5);
}
// Furniture overlays
if (ch === 'D') {
this.add.image(x, y, 'tile-desk').setOrigin(0.5, 0.5);
}
if (ch === 'c') {
this.add.image(x, y, 'tile-chair').setOrigin(0.5, 0.5);
}
// Sister spawn
if (ch >= '1' && ch <= '4') {
const idx = parseInt(ch, 10) - 1;
const name = SISTER_KEYS[idx]!;
const sprite = this.add
.sprite(x, y - 4, `sister-${name}`, 0)
.setOrigin(0.5, 0.5);
sprite.setInteractive({ useHandCursor: true });
sprite.on('pointerdown', () => {
this.events_.onSisterClick?.(name);
});
sprite.play(`sister-${name}-idle`);
this.sisterSprites.set(name, sprite);
// Status bubble (small floating tag above the sprite)
const bubble = this.add
.text(x, y - CHAR_H, '', {
fontFamily: 'monospace',
fontSize: '6px',
color: '#ffffff',
backgroundColor: '#000000aa',
padding: { x: 2, y: 1 },
})
.setOrigin(0.5, 1)
.setVisible(false);
this.statusBubbles.set(name, bubble);
}
}
}
// Camera zoom — scale up so 256x192 fills the host element nicely
this.cameras.main.setZoom(3);
this.cameras.main.centerOn(
(OFFICE_W_TILES * TILE_SIZE) / 2,
(OFFICE_H_TILES * TILE_SIZE) / 2,
);
// Hard-pixel rendering at zoom
this.cameras.main.setRoundPixels(true);
}
/** Called from React when sister state changes externally. */
setSisterState(name: string, state: 'idle' | 'working' | 'speaking' | 'error'): void {
if (this.currentStates[name] === state) return;
this.currentStates[name] = state;
const bubble = this.statusBubbles.get(name);
if (!bubble) return;
const map: Record<typeof state, string> = {
idle: '',
working: '⚙️',
speaking: '💬',
error: '⚠️',
};
const label = map[state];
if (label) {
bubble.setText(label).setVisible(true);
} else {
bubble.setVisible(false);
}
}
}

View File

@@ -0,0 +1,84 @@
'use client';
import React, { useEffect, useRef } from 'react';
import * as Phaser from 'phaser';
import styled from 'styled-components';
import { OfficeScene, OFFICE_W_TILES, OFFICE_H_TILES } from './OfficeScene';
import { TILE_SIZE } from './spriteFactory';
const Mount = styled.div`
width: 100%;
max-width: 100%;
display: flex;
justify-content: center;
align-items: center;
/* Crucial: pixel art must NOT be smoothed by the browser. */
& canvas {
image-rendering: pixelated;
image-rendering: -moz-crisp-edges;
image-rendering: crisp-edges;
}
`;
interface Props {
onSisterClick?: (sister: string) => void;
}
export default function PhaserHost({ onSisterClick }: Props) {
const containerRef = useRef<HTMLDivElement | null>(null);
const gameRef = useRef<Phaser.Game | null>(null);
useEffect(() => {
if (!containerRef.current) return;
if (gameRef.current) return;
const baseW = OFFICE_W_TILES * TILE_SIZE;
const baseH = OFFICE_H_TILES * TILE_SIZE;
// Camera zoom inside the scene = 3x. So our actual canvas needs
// baseW*3 x baseH*3 pixels.
const zoom = 3;
const game = new Phaser.Game({
type: Phaser.AUTO,
width: baseW * zoom,
height: baseH * zoom,
parent: containerRef.current,
backgroundColor: '#0b0b14',
pixelArt: true,
roundPixels: true,
antialias: false,
scene: [OfficeScene],
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
},
});
// Pass the click handler to the scene once it's started
game.scene.start('OfficeScene', { onSisterClick });
gameRef.current = game;
return () => {
game.destroy(true);
gameRef.current = null;
};
// intentionally only mount once — re-mounting Phaser is expensive and
// we route click events through a ref instead
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Forward updated click handler to the running scene without restart
useEffect(() => {
const game = gameRef.current;
if (!game) return;
const scene = game.scene.getScene('OfficeScene') as unknown as
| OfficeScene
| undefined;
if (scene && typeof scene.setEvents === 'function') {
scene.setEvents({ onSisterClick });
}
}, [onSisterClick]);
return <Mount ref={containerRef} />;
}

View File

@@ -0,0 +1,211 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import SisterAvatar from '@/components/common/SisterAvatar';
import { API_URL } from '@/lib/config';
interface SisterDetailPanelProps {
name: string;
onClose: () => void;
}
interface SisterInfo {
name: string;
status?: 'online' | 'offline' | 'working' | 'unknown';
role?: string;
currentTask?: string | null;
lastSeen?: string | null;
uptime?: string;
cpu?: number;
memory?: { used?: number; total?: number };
}
const SISTER_KOREAN: Record<string, string> = {
harang: '하랑이',
narang: '나랑이',
darang: '다랑이',
erang: '이랑이',
};
const SISTER_ROLE: Record<string, string> = {
harang: '기획 (Planner)',
narang: '구현 (Developer)',
darang: '검토 (QA)',
erang: '배포 (Infra)',
};
const SISTER_DESCRIPTION: Record<string, string> = {
harang:
'프로젝트 요구사항을 받아서 MVP 범위와 통과 기준을 결정한다. rails 파이프라인의 첫 단계.',
narang:
'하랑이의 기획을 받아서 실제 코드/파일을 생성한다. junior 가 코드 블록을 쓰고 git push 까지.',
darang:
'narang 의 구현물을 review. APPROVE / REQUEST_CHANGES / ABORT 중 하나를 결정.',
erang:
'darang 이 통과시킨 산출물을 배포 검증한다. 마지막 단계, DEPLOY_DONE / DEPLOY_FAILED.',
};
const Header = styled.div`
display: flex;
align-items: center;
gap: 14px;
`;
const NameRow = styled.div`
flex: 1;
display: flex;
flex-direction: column;
gap: 2px;
`;
const NameKR = styled.h2`
font-size: 18px;
font-weight: 700;
margin: 0;
color: var(--text-primary);
`;
const RoleLabel = styled.span`
font-size: 11px;
font-family: var(--font-mono);
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-secondary);
`;
const CloseBtn = styled.button`
background: transparent;
border: 1px solid var(--border-color);
color: var(--text-secondary);
font-size: 11px;
padding: 4px 10px;
border-radius: 8px;
cursor: pointer;
&:hover {
color: var(--text-primary);
border-color: var(--text-primary);
}
`;
const Section = styled.section`
display: flex;
flex-direction: column;
gap: 6px;
`;
const SectionLabel = styled.div`
font-size: 10px;
font-family: var(--font-mono);
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-secondary);
`;
const SectionBody = styled.div`
font-size: 13px;
line-height: 1.55;
color: var(--text-primary);
`;
const StatusDot = styled.span<{ $status: string }>`
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 8px;
background: ${({ $status }) => {
switch ($status) {
case 'online':
case 'working':
return '#22c55e';
case 'offline':
return '#6b7280';
case 'unknown':
default:
return '#f59e0b';
}
}};
`;
export default function SisterDetailPanel({
name,
onClose,
}: SisterDetailPanelProps) {
const [info, setInfo] = useState<SisterInfo | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
setLoading(true);
fetch(`${API_URL}/api/sisters/${name}`, { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((data: SisterInfo | null) => {
if (cancelled) return;
setInfo(data);
setLoading(false);
})
.catch(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [name]);
return (
<>
<Header>
<SisterAvatar name={name} size={56} />
<NameRow>
<NameKR>{SISTER_KOREAN[name] ?? name}</NameKR>
<RoleLabel>{SISTER_ROLE[name] ?? 'unknown'}</RoleLabel>
</NameRow>
<CloseBtn onClick={onClose}></CloseBtn>
</Header>
<Section>
<SectionLabel></SectionLabel>
<SectionBody>{SISTER_DESCRIPTION[name] ?? '—'}</SectionBody>
</Section>
<Section>
<SectionLabel></SectionLabel>
<SectionBody>
<StatusDot $status={info?.status ?? 'unknown'} />
{loading
? '확인 중...'
: info?.status
? info.status
: '상태 정보 없음'}
</SectionBody>
</Section>
{info?.currentTask && (
<Section>
<SectionLabel> </SectionLabel>
<SectionBody>{info.currentTask}</SectionBody>
</Section>
)}
{info?.uptime && (
<Section>
<SectionLabel></SectionLabel>
<SectionBody style={{ fontFamily: 'var(--font-mono)' }}>
{info.uptime}
</SectionBody>
</Section>
)}
{typeof info?.cpu === 'number' && (
<Section>
<SectionLabel>CPU</SectionLabel>
<SectionBody style={{ fontFamily: 'var(--font-mono)' }}>
{info.cpu.toFixed(1)}%
</SectionBody>
</Section>
)}
</>
);
}

View File

@@ -0,0 +1,371 @@
import type * as Phaser from 'phaser';
/**
* Procedural pixel art sprite factory.
*
* Why procedural: pre-baked sprite sheets would mean shipping art assets,
* downloading from external sources, and committing copyrighted-by-others
* material. Drawing every pixel in code keeps the dashboard self-contained
* and lets us match the 4-sister color identity exactly.
*
* Style: 1-bit-ish pixel art with 2-3 colors per sprite, 16px tiles, 16x24
* characters. Inspired by GBC Pokemon, deskrpg, openclaw-office.
*/
export const TILE_SIZE = 16;
export const CHAR_W = 16;
export const CHAR_H = 24;
export interface SisterPalette {
hair: number;
outfit: number;
outfit2: number;
skin: number;
outline: number;
}
export const SISTER_PALETTES: Record<string, SisterPalette> = {
harang: {
// 따뜻한 빨강 (planner / 부장 vibe)
hair: 0x6b2424,
outfit: 0xd84444,
outfit2: 0x9c2828,
skin: 0xf4cfa1,
outline: 0x1a0808,
},
narang: {
// 차가운 청록 (developer / 손에 코드)
hair: 0x1f3a4a,
outfit: 0x37b8c7,
outfit2: 0x1d6f7c,
skin: 0xf4cfa1,
outline: 0x081a1f,
},
darang: {
// 노랑 (qa / 검사관)
hair: 0x4a3a18,
outfit: 0xeac34a,
outfit2: 0xa07020,
skin: 0xf4cfa1,
outline: 0x1f1808,
},
erang: {
// 보라 (infra / 시스템)
hair: 0x2c1a3e,
outfit: 0x9858d8,
outfit2: 0x5c2c8a,
skin: 0xf4cfa1,
outline: 0x10081f,
},
};
/**
* Helper: write a 2D pixel grid into a Phaser Graphics object so it can be
* generated as a texture. Each cell of `grid` is a hex color or -1 for
* transparent.
*
* The grid is row-major: grid[y][x].
*/
function paintGrid(
g: Phaser.GameObjects.Graphics,
grid: number[][],
pixelSize = 1,
): void {
for (let y = 0; y < grid.length; y++) {
const row = grid[y]!;
for (let x = 0; x < row.length; x++) {
const c = row[x]!;
if (c < 0) continue;
g.fillStyle(c, 1);
g.fillRect(x * pixelSize, y * pixelSize, pixelSize, pixelSize);
}
}
}
/**
* Generate a simple character sprite (16x24) for one sister, looking down,
* 2 frames of idle (slight bob).
*
* Layout (16x24, frame 0):
* row 0-1 : empty
* row 2-7 : hair / head
* row 8-9 : face row
* row 10-15 : body / outfit
* row 16-19 : legs
* row 20-23 : feet / shadow base
*/
function makeSisterFrame(
scene: Phaser.Scene,
pal: SisterPalette,
frameIdx: 0 | 1,
): number[][] {
const _ = -1; // transparent
const O = pal.outline;
const H = pal.hair;
const S = pal.skin;
const C = pal.outfit;
const C2 = pal.outfit2;
const F = 0x000000;
// Subtle vertical bob: frame 1 shifts the entire body 1px down by adding
// an extra blank row at the top and dropping the last row. This is the
// simplest "breathing" idle.
const offset = frameIdx === 1 ? 1 : 0;
const totalH = CHAR_H;
// Build a base grid (16x22 for the actual character — leaves 2 rows for
// shadow / breathing slack)
const grid: number[][] = Array.from({ length: totalH }, () =>
Array.from({ length: CHAR_W }, () => _),
);
function row(y: number, cells: number[]): void {
if (y >= 0 && y < totalH) {
for (let x = 0; x < CHAR_W && x < cells.length; x++) {
grid[y]![x] = cells[x]!;
}
}
}
void scene; // not used directly here — Phaser texture is created separately
void F;
// Apply offset
const r = (n: number) => n + offset;
// hair top (5 rows of hair, row 1-5)
row(r(1), [_, _, _, _, O, O, O, O, O, O, O, O, _, _, _, _]);
row(r(2), [_, _, _, O, H, H, H, H, H, H, H, H, O, _, _, _]);
row(r(3), [_, _, O, H, H, H, H, H, H, H, H, H, H, O, _, _]);
row(r(4), [_, _, O, H, H, H, H, H, H, H, H, H, H, O, _, _]);
row(r(5), [_, _, O, H, H, S, S, S, S, S, S, H, H, O, _, _]);
// face (eyes/mouth)
row(r(6), [_, _, O, H, S, S, O, S, S, O, S, S, H, O, _, _]);
row(r(7), [_, _, O, H, S, S, S, S, S, S, S, S, H, O, _, _]);
row(r(8), [_, _, O, H, S, S, S, O, O, S, S, S, H, O, _, _]);
row(r(9), [_, _, _, O, S, S, S, S, S, S, S, S, O, _, _, _]);
// neck
row(r(10), [_, _, _, _, O, S, S, S, S, S, S, O, _, _, _, _]);
// outfit upper
row(r(11), [_, _, O, C, C, C, C, C, C, C, C, C, C, O, _, _]);
row(r(12), [_, O, C, C, C, C2, C2, C2, C2, C2, C2, C, C, C, O, _]);
row(r(13), [_, O, C, C, C, C2, C2, C2, C2, C2, C2, C, C, C, O, _]);
row(r(14), [_, O, C, C, C, C, C, C, C, C, C, C, C, C, O, _]);
row(r(15), [_, O, C, C, C, C, C, C, C, C, C, C, C, C, O, _]);
// arms
row(r(16), [_, O, C, S, S, C2, C2, C2, C2, C2, C2, S, S, C, O, _]);
row(r(17), [_, O, S, S, S, C2, C2, C2, C2, C2, C2, S, S, S, O, _]);
// belt
row(r(18), [_, _, O, C2, C2, C2, C2, C2, C2, C2, C2, C2, C2, O, _, _]);
// legs
row(r(19), [_, _, _, O, C2, C2, _, _, _, _, C2, C2, O, _, _, _]);
row(r(20), [_, _, _, O, C2, C2, _, _, _, _, C2, C2, O, _, _, _]);
row(r(21), [_, _, _, O, F, F, _, _, _, _, F, F, O, _, _, _]);
row(r(22), [_, _, _, _, O, O, _, _, _, _, O, O, _, _, _, _]);
return grid;
}
/**
* Generate a tile texture (16x16) representing a wood floor plank.
*/
function makeFloorTile(): number[][] {
const _ = 0xc4955a;
const D = 0x8a6438;
const L = 0xd6ab78;
const grid: number[][] = Array.from({ length: TILE_SIZE }, () =>
Array.from({ length: TILE_SIZE }, () => _),
);
// horizontal plank lines
for (let x = 0; x < TILE_SIZE; x++) {
grid[3]![x] = D;
grid[10]![x] = D;
}
// light highlights
for (let x = 0; x < TILE_SIZE; x++) {
if ((x + 1) % 4 === 0) {
grid[1]![x] = L;
grid[7]![x] = L;
grid[14]![x] = L;
}
}
return grid;
}
function makeWallTile(): number[][] {
const _ = 0x5a5266;
const D = 0x3a3445;
const L = 0x726a82;
const grid: number[][] = Array.from({ length: TILE_SIZE }, () =>
Array.from({ length: TILE_SIZE }, () => _),
);
// brick pattern
for (let y = 0; y < TILE_SIZE; y++) {
grid[y]![TILE_SIZE - 1] = D;
}
for (let x = 0; x < TILE_SIZE; x++) {
grid[TILE_SIZE - 1]![x] = D;
grid[0]![x] = L;
}
// brick seam every 4 rows
for (let x = 0; x < TILE_SIZE; x++) {
grid[7]![x] = D;
grid[15]![x] = D;
}
// staggered vertical seams
for (let y = 0; y < 7; y++) grid[y]![7] = D;
for (let y = 8; y < 16; y++) grid[y]![3] = D;
for (let y = 8; y < 16; y++) grid[y]![11] = D;
return grid;
}
function makeCarpetTile(): number[][] {
const _ = 0x4a2828;
const A = 0x6c3838;
const B = 0x2c1818;
const grid: number[][] = Array.from({ length: TILE_SIZE }, () =>
Array.from({ length: TILE_SIZE }, () => _),
);
for (let y = 0; y < TILE_SIZE; y++) {
for (let x = 0; x < TILE_SIZE; x++) {
if ((x + y) % 4 === 0) grid[y]![x] = A;
if ((x + y * 3) % 7 === 0) grid[y]![x] = B;
}
}
return grid;
}
function makeDeskTile(): number[][] {
// 32x16 desk drawn into a 16x16 cell — top half table, bottom half legs
const T = 0x6b4628;
const D = 0x3a2614;
const L = 0x8a5e36;
const _ = -1;
const grid: number[][] = Array.from({ length: TILE_SIZE }, () =>
Array.from({ length: TILE_SIZE }, () => _),
);
// tabletop
for (let x = 0; x < TILE_SIZE; x++) {
grid[2]![x] = D;
grid[3]![x] = T;
grid[4]![x] = T;
grid[5]![x] = L;
grid[6]![x] = D;
}
// monitor (small screen on top, lighter)
for (let y = 7; y < 11; y++) {
for (let x = 5; x < 11; x++) grid[y]![x] = 0x1a3a5a;
}
for (let x = 5; x < 11; x++) grid[11]![x] = 0x6e6e7c;
// legs (bottom)
for (let y = 12; y < TILE_SIZE; y++) {
grid[y]![1] = D;
grid[y]![14] = D;
}
return grid;
}
function makeChairTile(): number[][] {
const _ = -1;
const C = 0x2c1f3f;
const D = 0x16101f;
const grid: number[][] = Array.from({ length: TILE_SIZE }, () =>
Array.from({ length: TILE_SIZE }, () => _),
);
// backrest
for (let y = 2; y < 8; y++) {
for (let x = 5; x < 11; x++) grid[y]![x] = C;
}
for (let y = 2; y < 8; y++) {
grid[y]![5] = D;
grid[y]![10] = D;
}
// seat
for (let x = 4; x < 12; x++) {
grid[8]![x] = D;
grid[9]![x] = C;
}
// legs
grid[10]![5] = D;
grid[10]![10] = D;
grid[11]![5] = D;
grid[11]![10] = D;
return grid;
}
/**
* Render a grid into a Phaser texture and register it under `key`.
*/
export function registerGridTexture(
scene: Phaser.Scene,
key: string,
grid: number[][],
): void {
if (scene.textures.exists(key)) return;
const w = grid[0]?.length ?? TILE_SIZE;
const h = grid.length;
const g = scene.add.graphics({ x: 0, y: 0 });
paintGrid(g, grid, 1);
g.generateTexture(key, w, h);
g.destroy();
}
/**
* Build a 2-frame spritesheet texture for one sister.
* The two frames are stacked vertically into one image.
*/
export function registerSisterTexture(
scene: Phaser.Scene,
sister: keyof typeof SISTER_PALETTES,
): void {
const key = `sister-${sister}`;
if (scene.textures.exists(key)) return;
const pal = SISTER_PALETTES[sister];
const f0 = makeSisterFrame(scene, pal, 0);
const f1 = makeSisterFrame(scene, pal, 1);
// stack vertically
const combined: number[][] = [...f0, ...f1];
const g = scene.add.graphics({ x: 0, y: 0 });
paintGrid(g, combined, 1);
g.generateTexture(key, CHAR_W, CHAR_H * 2);
g.destroy();
// register as a spritesheet so we can play it as an animation
if (!scene.anims.exists(`${key}-idle`)) {
// We didn't actually create proper frames via spritesheet — instead,
// create a manual animation by swapping textures using `addKey`. Since
// Phaser anims need spritesheet/atlas frames, we re-register the
// texture as a spritesheet:
scene.textures.remove(key);
const g2 = scene.add.graphics({ x: 0, y: 0 });
paintGrid(g2, combined, 1);
g2.generateTexture(key, CHAR_W, CHAR_H * 2);
g2.destroy();
// Configure the texture frames manually
const tex = scene.textures.get(key);
tex.add(0, 0, 0, 0, CHAR_W, CHAR_H);
tex.add(1, 0, 0, CHAR_H, CHAR_W, CHAR_H);
scene.anims.create({
key: `${key}-idle`,
frames: [
{ key, frame: 0 },
{ key, frame: 1 },
],
frameRate: 2,
repeat: -1,
});
}
}
export function registerAllTextures(scene: Phaser.Scene): void {
registerGridTexture(scene, 'tile-floor', makeFloorTile());
registerGridTexture(scene, 'tile-wall', makeWallTile());
registerGridTexture(scene, 'tile-carpet', makeCarpetTile());
registerGridTexture(scene, 'tile-desk', makeDeskTile());
registerGridTexture(scene, 'tile-chair', makeChairTile());
for (const name of Object.keys(SISTER_PALETTES) as Array<
keyof typeof SISTER_PALETTES
>) {
registerSisterTexture(scene, name);
}
}

View File

@@ -0,0 +1,360 @@
'use client';
import React, { useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
interface Transition {
id: number;
pipelineId: string;
fromState: string;
toState: string;
eventType: string;
timestamp: string;
}
interface Props {
pipelineId: string | null;
}
const Wrapper = styled.section`
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 14px;
padding: 20px 22px;
display: flex;
flex-direction: column;
gap: 16px;
`;
const Header = styled.div`
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
`;
const Title = styled.h3`
font-size: 13px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-secondary);
margin: 0;
`;
const Stats = styled.div`
display: flex;
gap: 8px;
flex-wrap: wrap;
`;
const Stat = styled.span<{ $variant?: 'replan' | 'review' | 'normal' }>`
font-size: 10px;
font-family: var(--font-mono);
font-weight: 700;
text-transform: uppercase;
padding: 3px 10px;
border-radius: 10px;
background: ${({ $variant }) => {
switch ($variant) {
case 'replan':
return 'rgba(239, 68, 68, 0.18)';
case 'review':
return 'rgba(245, 158, 11, 0.18)';
default:
return 'var(--bg-main)';
}
}};
color: ${({ $variant }) => {
switch ($variant) {
case 'replan':
return '#fca5a5';
case 'review':
return '#fcd34d';
default:
return 'var(--text-primary)';
}
}};
border: 1px solid
${({ $variant }) => {
switch ($variant) {
case 'replan':
return 'rgba(239, 68, 68, 0.5)';
case 'review':
return 'rgba(245, 158, 11, 0.5)';
default:
return 'var(--border-color)';
}
}};
`;
const Track = styled.ol`
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 6px;
position: relative;
&::before {
content: '';
position: absolute;
left: 8px;
top: 8px;
bottom: 8px;
width: 1px;
background: var(--border-color);
}
`;
const Row = styled.li<{ $variant?: 'replan' | 'normal' | 'escalation' }>`
display: flex;
align-items: center;
gap: 12px;
font-family: var(--font-mono);
font-size: 11px;
position: relative;
padding-left: 24px;
&::before {
content: '';
position: absolute;
left: 5px;
top: 50%;
transform: translateY(-50%);
width: 7px;
height: 7px;
border-radius: 50%;
background: ${({ $variant }) => {
switch ($variant) {
case 'replan':
return '#ef4444';
case 'escalation':
return '#f59e0b';
default:
return '#5fafff';
}
}};
box-shadow: 0 0 0 2px var(--bg-input);
}
`;
const Time = styled.span`
color: var(--text-secondary);
white-space: nowrap;
flex-shrink: 0;
width: 64px;
`;
const Arrow = styled.span<{ $variant?: 'replan' | 'normal' | 'escalation' }>`
display: inline-flex;
align-items: center;
gap: 6px;
flex: 1;
color: ${({ $variant }) => {
switch ($variant) {
case 'replan':
return '#fca5a5';
case 'escalation':
return '#fcd34d';
default:
return 'var(--text-primary)';
}
}};
`;
const StateBadge = styled.span<{ $state: string }>`
padding: 1px 7px;
border-radius: 8px;
background: ${({ $state }) => stateColor($state)};
color: #fff;
font-size: 9px;
text-transform: uppercase;
font-weight: 700;
`;
const ReplanMarker = styled.span`
display: inline-flex;
align-items: center;
gap: 4px;
margin-left: 8px;
padding: 1px 7px;
border-radius: 8px;
background: rgba(239, 68, 68, 0.18);
color: #fca5a5;
font-size: 9px;
font-weight: 700;
text-transform: uppercase;
border: 1px solid rgba(239, 68, 68, 0.5);
`;
const Empty = styled.div`
padding: 18px;
text-align: center;
font-size: 12px;
color: var(--text-secondary);
font-family: var(--font-mono);
`;
function stateColor(state: string): string {
switch (state) {
case 'idle':
return '#6b7280';
case 'planning':
return '#8b5cf6';
case 'implementing':
return '#3b82f6';
case 'reviewing':
return '#f59e0b';
case 'deploying':
return '#0ea5e9';
case 'done':
return '#22c55e';
case 'escalated':
case 'failed':
case 'aborted':
return '#ef4444';
case 'retrying':
return '#a855f7';
default:
return '#525252';
}
}
function shortTime(iso: string): string {
try {
const d = new Date(iso);
return d.toLocaleTimeString('ko-KR', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
});
} catch {
return iso;
}
}
function classifyTransition(
t: Transition,
): 'replan' | 'normal' | 'escalation' {
if (t.fromState === 'reviewing' && t.toState === 'planning') return 'replan';
if (t.toState === 'escalated') return 'escalation';
return 'normal';
}
export default function TransitionsTimeline({ pipelineId }: Props) {
const [transitions, setTransitions] = useState<Transition[]>([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!pipelineId) {
setTransitions([]);
return;
}
let cancelled = false;
const load = async () => {
setLoading(true);
try {
const res = await fetch(
`${API_URL}/api/rails/transitions?pipelineId=${pipelineId}&limit=200`,
{ credentials: 'include' },
);
if (!res.ok) {
if (!cancelled) setLoading(false);
return;
}
const data = (await res.json()) as { transitions?: Transition[] };
if (!cancelled) {
// API returns DESC by timestamp — reverse to chronological
const rows = (data.transitions ?? []).slice().reverse();
setTransitions(rows);
setLoading(false);
}
} catch {
if (!cancelled) setLoading(false);
}
};
void load();
const t = setInterval(load, 4000);
return () => {
cancelled = true;
clearInterval(t);
};
}, [pipelineId]);
const stats = useMemo(() => {
const replans = transitions.filter(
(t) => t.fromState === 'reviewing' && t.toState === 'planning',
).length;
const reviewLoops = transitions.filter(
(t) => t.fromState === 'reviewing' && t.toState === 'implementing',
).length;
const escalations = transitions.filter(
(t) => t.toState === 'escalated',
).length;
return { replans, reviewLoops, escalations, total: transitions.length };
}, [transitions]);
if (!pipelineId) {
return (
<Wrapper>
<Header>
<Title> </Title>
</Header>
<Empty> </Empty>
</Wrapper>
);
}
return (
<Wrapper>
<Header>
<Title> </Title>
<Stats>
<Stat> {stats.total}</Stat>
{stats.reviewLoops > 0 && (
<Stat $variant="review">review loop ×{stats.reviewLoops}</Stat>
)}
{stats.replans > 0 && (
<Stat $variant="replan"> ×{stats.replans}</Stat>
)}
{stats.escalations > 0 && (
<Stat $variant="replan">🚨 escalated</Stat>
)}
</Stats>
</Header>
{loading && transitions.length === 0 ? (
<Empty> ...</Empty>
) : transitions.length === 0 ? (
<Empty> </Empty>
) : (
<Track>
{transitions.map((t) => {
const variant = classifyTransition(t);
return (
<Row key={t.id} $variant={variant}>
<Time>{shortTime(t.timestamp)}</Time>
<Arrow $variant={variant}>
<StateBadge $state={t.fromState}>{t.fromState}</StateBadge>
<StateBadge $state={t.toState}>{t.toState}</StateBadge>
<span style={{ color: 'var(--text-secondary)' }}>
[{t.eventType}]
</span>
{variant === 'replan' && <ReplanMarker> </ReplanMarker>}
{variant === 'escalation' && (
<ReplanMarker>🚨 escalated</ReplanMarker>
)}
</Arrow>
</Row>
);
})}
</Track>
)}
</Wrapper>
);
}

View File

@@ -10,6 +10,7 @@
},
"dependencies": {
"next": "16.2.2",
"phaser": "^4.0.0",
"react": "19.2.4",
"react-dom": "19.2.4",
"react-markdown": "^10.1.0",

View File

@@ -11,6 +11,9 @@ importers:
next:
specifier: 16.2.2
version: 16.2.2(@babel/core@7.29.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
phaser:
specifier: ^4.0.0
version: 4.0.0
react:
specifier: 19.2.4
version: 19.2.4
@@ -1092,6 +1095,9 @@ packages:
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
engines: {node: '>=0.10.0'}
eventemitter3@5.0.4:
resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}
extend@3.0.2:
resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}
@@ -1684,6 +1690,9 @@ packages:
path-parse@1.0.7:
resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}
phaser@4.0.0:
resolution: {integrity: sha512-f9oYpu3/UymB5JJDZRqOsNQm5FkMMC7u8eL8yQuqGAa54wTbgE2QbTOn70vgvlOVuYeQcw2mOQ52PpJHBSBkfQ==}
picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -3066,7 +3075,7 @@ snapshots:
eslint: 9.39.4
eslint-import-resolver-node: 0.3.10
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4))(eslint@9.39.4)
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4)
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4))(eslint@9.39.4))(eslint@9.39.4)
eslint-plugin-jsx-a11y: 6.10.2(eslint@9.39.4)
eslint-plugin-react: 7.37.5(eslint@9.39.4)
eslint-plugin-react-hooks: 7.0.1(eslint@9.39.4)
@@ -3099,7 +3108,7 @@ snapshots:
tinyglobby: 0.2.16
unrs-resolver: 1.11.1
optionalDependencies:
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4)
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4))(eslint@9.39.4))(eslint@9.39.4)
transitivePeerDependencies:
- supports-color
@@ -3114,7 +3123,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4):
eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.58.1(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4))(eslint@9.39.4))(eslint@9.39.4):
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -3265,6 +3274,8 @@ snapshots:
esutils@2.0.3: {}
eventemitter3@5.0.4: {}
extend@3.0.2: {}
fast-deep-equal@3.1.3: {}
@@ -4019,6 +4030,10 @@ snapshots:
path-parse@1.0.7: {}
phaser@4.0.0:
dependencies:
eventemitter3: 5.0.4
picocolors@1.1.1: {}
picomatch@2.3.2: {}