Compare commits

...

51 Commits

Author SHA1 Message Date
02476c001f feat(control): add live workboard v0 2026-06-19 14:41:43 +09:00
be0120bd0c feat(rpg): Phaser/픽셀아트 빼고 profile photo 기반 가상 사무실로 전환
자기야 피드백: "픽셀 아트 안 예쁘다, profile photo 로 바꿀 수 없나?
픽셀 아트 고집 안 해도 됨." → 16x28 픽셀로는 anime 일러스트 정체성 못
살리는 게 사실. Phaser 자체도 큰 의존성이라 깔끔하게 빼고 React+CSS+SVG
로 재작성.

## 변경

### 제거
- phaser 4.0.0 의존성 (~3MB)
- frontend/components/office-rpg/ 전체 (Phaser 통합 layer + procedural
  pixel sprite factory + Office scene)

### 신설
- frontend/components/office-room/OfficeRoom.tsx
  - 2x2 grid layout: 하랑/나랑 (위), 다랑/이랑 (아래)
  - 가운데 회의실 (시각 표시만, 향후 인터랙션용)
  - 각 자매 = 책상 SVG 위에 원형 portrait card
    - 72px portrait (실제 /api/sisters/{name}/avatar)
    - 자매 시그니처 색 border (harang=blue, narang=teal, darang=red, erang=violet)
    - hover 시 위로 살짝 떠오름
    - 활성 stage 일 때 PulseRing + StatusDot 펄스
  - 자매 사이 SVG flow arrow (plan → impl → review → deploy 방향)
    활성 stage 시 화살표 hi-lighted
  - 클릭 → 우측 SisterDetailPanel slide-in
- frontend/components/office-room/SisterDetailPanel.tsx
  - 기존 office-rpg 의 detail panel 을 재사용 (PortraitLg + 자매 시그니처
    accent + 역할 설명 + 백엔드 sister info)

### app/page.tsx
- OfficeRpg → OfficeRoom 으로 교체
- 4초 polling 으로 활성 파이프라인의 currentState 추적 →
  STATE_TO_STAGE 매핑 → 해당 자매 카드 자동 펄스
2026-04-11 05:01:40 +09:00
480db0c734 fix(rpg): 자매 sprite 를 실제 일러스트와 닮게 재작성
자기야 발견: 1차 sprite 색상이 실제 자매 일러스트와 거리가 멀었음. 4 자매
실제 avatar.png (각 LXC 의 ~/.openclaw/avatar.png) 를 직접 확인 후 시그니처
정정:

  하랑 — 흰/은 머리 + 흰 cat ears + 파란 리본 + 파란 눈 (이전: 빨강 — 틀림)
  나랑 — 검은 short bob + 검은 cat ears + 청록 보타이 + 청록 눈 (그나마 비슷)
  다랑 — 흰 머리 + 흰 cat ears + 빨간 chinese 옷 + 빨간 눈 (이전: 노랑 — 틀림)
  이랑 — 흰 long hair + 흰 cat ears + 흰 옷 + 파란 눈 + 파란 나비 (이전: 보라)

핵심 변경:
- spriteFactory.ts SISTER_PALETTES 전면 재작성: hair / hairShadow / outfit /
  outfit2 / eye / earInner 등 분리. 자매별로 정확한 시그니처 색상.
- 4 자매 모두 catgirl 이라 sprite 위쪽에 cat ears 추가 (행 0-2 에 cat ear
  outline + hair fill + earInner pink).
- CHAR_H 24 → 28 로 키워서 cat ears 와 더 긴 머리/몸 표현 공간 확보.
- 자매별 추가 디테일:
    darang  → 이마에 빨간 보석 점
    erang   → 머리 옆에 작은 파란 나비
    harang  → 머리 위에 파란 리본
    narang  → 옆머리 청록 헤어핀
- narang 만 short bob (옆 bangs 다른 자매보다 짧음). 나머지 3 명은 long hair.
- OfficeScene.ts: sprite 28px 으로 커졌으니 origin 을 (0.5, 1) 로 바꾸고
  발끝을 타일 바닥 위에 정렬해 일관된 standing height.

이전: sprite 가 식별 불가능한 색깔 박스. 이번: 4 자매 각각 일러스트 시그
니처 색 + cat ears + 머리스타일이 보임.
2026-04-11 04:37:37 +09:00
9a17f65419 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).
2026-04-11 04:30:45 +09:00
9addaba626 fix(rails): LLM 응답 텍스트 드래그/복사 가능하게 + drawer drag-select 보호
자기야 요청: 대시보드의 LLM 응답 본문을 드래그해서 복사하고 싶음.

수정:
- LlmOutput 에 user-select: text + cursor: text 를 명시. 부모 어딘가에서
  상속받을 가능성을 차단. ::selection 색상도 추가해 선택 영역이 가시적
- LlmOutput 내부의 button (더보기 토글) 만 user-select: none 로 예외 처리
- Backdrop click 핸들러 개선: 사용자가 drawer 내부에서 drag-select 시작
  하다가 mouseup 이 backdrop 위에서 끝나면 기존 코드는 drawer 를 닫아 버려
  selection 이 사라졌음. 이제 mousedown 도 backdrop 에서 시작했을 때만
  close 를 실행 (data-backdrop-down attr 로 추적)
2026-04-11 01:56:22 +09:00
837ab28d07 feat(rails): SubTaskDetailDrawer 컴팩트화 — collapsible 섹션 + 이벤트 필터
자기야 피드백: 드로어가 너무 길어서 보기 힘듦. LLM 응답 + 전체 이벤트 로그
+ 자식 노드 다 펼쳐져 있어서 하나 클릭하면 화면 한 페이지가 다 차버림.

수정:
- LLM 응답: 280 자 미리보기 + "더 보기 (+N chars)" 토글. 긴 마크다운이
  디폴트로 화면을 먹지 않음. 응답 길이를 헤더 옆 배지로 미리 표시
- 하위 노드: 디폴트 접힘. 헤더에 개수 배지, 클릭하면 펼침
- 이벤트 로그: 디폴트 접힘. 펼치면 두 칩 (milestones / all) 으로 필터링
  - milestones: spawned/completed/failed/escalated 만
  - all: started/progress/output 까지 전부
  대부분 디버깅엔 milestones 만 보면 충분
- 새 sub-task 클릭 시 expanded 상태 전부 리셋

새 styled components: CollapsibleHeader, ChevronIcon, SectionCount, ChipRow,
Chip, ShowMoreButton (재사용 가능)

대시보드 한 화면이 디폴트로 절반 이하로 줄어듦. 정보 손실 0 — 클릭으로
다 볼 수 있음.
2026-04-11 01:49:46 +09:00
13e95f4ace feat(rails): GIT_RAW_ALLOWED_HOSTS env 로 파일 프록시 allowlist 외부화
- 기존에는 git.nabomhalang.co.kr 한 곳만 하드코딩되어 있었음
- GIT_RAW_ALLOWED_HOSTS=comma,separated,hosts 로 여러 호스트 지원
- 기본값은 기존과 동일 (git.nabomhalang.co.kr) — 행동 변화 없음
- hanarang-rails v0.1.3 의 외부 배포 친화 패키지와 세트
2026-04-10 21:52:11 +09:00
9a99a8a33c feat(rails): MD 파일 클릭해서 뷰어 모달로 내용 보기
- backend: /api/rails/file-content 프록시 (Gitea host allowlist)
- frontend: FileViewerModal — 마크다운/코드 렌더링, front matter 파싱
- drawer: FileRow 클릭 핸들러 + 호버 효과
  - .md 로그는 resultJson에서 직접 표시
  - 추출된 코드 파일은 rawUrlBase로 백엔드 프록시 페치
2026-04-10 21:09:38 +09:00
548279c888 feat(drawer): artifacts section — files, code blocks, deploy URL 2026-04-10 20:35:12 +09:00
fb8f2f3b87 merge: LLM output markdown rendering 2026-04-10 19:37:22 +09:00
501c430ab2 feat(ui): parse LLM resultJson and render as markdown in detail drawer
- resultJson was showing as raw {"text":"..."} JSON string
- Now parses the JSON and renders the text via react-markdown
- Pretty rendering: headings, lists, code blocks, blockquotes, links
- Shows status dot + model name header
- Fallback to raw view when text field is empty
2026-04-10 19:37:15 +09:00
a7cb728602 feat(dashboard): SIEM log + escalations + office collaboration lines
B - SIEM 로그 + 경보:
- backend/rails: GET /api/rails/transitions (filter by pipelineId, eventType)
- backend/rails: GET /api/rails/escalations (filter by resolved)
- frontend/app/rails/log/page.tsx — 결정론적 이벤트 스트림
    필터: pipelineId / eventType / 초기화
    timestamp / event badge / pipeline pill / state transition / 클릭 → 필터링
    이벤트 타입별 색상 (REQUEST_CHANGES=주황, ERROR=빨강, 등)
- frontend/app/rails/escalations/page.tsx — 경보 카드 뷰
    탭: 전체 / 미해결 / 해결됨
    카드: reason, category 태그, attempts, stage, 시간
    context snapshot 펼침 (JSON pretty)
- sidebar: 로그 / 경보 메뉴 추가

C - Office collaboration lines:
- OfficeFloor 의 4자매 책상 위에 SVG overlay
- harang→narang→narang→darang→darang→erang 흐름선
- active stage 가 있으면 점선 애니메이션 (flowDash keyframe)
- 비활성 시 흐릿한 정적 점선
- 화살표 마커로 방향 표시
2026-04-10 18:28:07 +09:00
f8da7331ce feat(ui): 자매 프로필 사진 통합
- OfficeFloor: 4자매 책상에 SisterAvatar (60px gradient frame)
- SubTaskTree: 노드 row 에 작은 SisterAvatar (20px) 표시
- SubTaskDetailDrawer: 헤더에 큰 SisterAvatar (40px) + role badge 함께

이미 있는 백엔드 /api/sisters/:name/avatar 엔드포인트 재활용
(SSH 로 ~/.openclaw/avatar.png 가져오는 AvatarService)
2026-04-10 18:14:39 +09:00
5ec1287792 feat(rails): node detail drawer — click any sub-task to inspect
Backend:
- rails.service.ts: getSubTaskDetail(id) - calls rails GET /api/sub-tasks/:id
- rails.controller.ts: GET /api/rails/sub-tasks/:id

Frontend:
- components/rails/SubTaskDetailDrawer.tsx — slide-in drawer
    Header: role badge, title, close button (ESC)
    Body: state/agent/model/duration/complexity grid,
          description, error, result JSON
          children list
          event log timeline (color-coded by event type)
- components/rails/SubTaskTree.tsx: clickable Node, hover state, onSelectNode prop
- app/rails/page.tsx: detailNodeId state, drawer mount
- app/office/page.tsx: same drawer wired to its sub-tree

ESC key closes drawer. Backdrop click closes.
2026-04-10 17:59:16 +09:00
98ee03baa9 chore: gitignore .claude/state 2026-04-10 17:42:15 +09:00
d100ee7c42 feat(ui): redesign /rails + /office for breathing room and digital office feel
Office (full rewrite):
- frontend/components/office/OfficeFloor.tsx — 새로운 책상 그리드
  4 자매 책상 (2x2 grid), 자매당 카드 형태
  자매 아바타 (gradient), 역할 라벨, 작업 중 pulse 애니메이션
  worker pill chips (manager/principal/lead/junior 색상별)
  Stats: workers / active / done / fail
  십자 가이드 라인으로 office floor plan 분위기
- frontend/app/office/page.tsx — 867 → 220 줄 압축
  rails 데이터 직접 사용 (sisters API 의존성 제거)
  사이드 패널: 선택된 자매의 sub-task 트리

Rails (간격 + 가독성):
- frontend/app/rails/page.tsx — 카드 spacing 확대, 헤더 명료화
  Start 폼을 별도 카드로 분리 (한 줄 → enter 시 시작)
  파이프라인 카드 padding 18px, 클릭 영역 확장
  state badge 컬러 + 라운드, project name 큼지막
  rel time / id 메타는 mono font 로 separator
- frontend/components/rails/SubTaskTree.tsx — 노드 padding 12px,
  자식들 사이 dashed border + 16px 들여쓰기 ( 시각적 hierarchy)
  Title sans font 로 변경, complexity meta 별도 줄

Sidebar:
- 기존 작업 변경 없음 ('레일' 메뉴는 이전 커밋에서 추가됨)

검증: pnpm build (next 16 turbopack) ✓
2026-04-10 17:42:06 +09:00
8ad373f78e merge: rails integration into dashboard 2026-04-10 17:30:18 +09:00
80598e7b58 feat(rails): integrate hanarang-rails orchestrator into dashboard
Backend:
- src/rails/rails.service.ts — HTTP client for rails API (read-only)
- src/rails/rails.controller.ts — REST under /api/rails/* (JwtGuard 보호)
    GET /pipelines, /pipelines/:id, /pipelines/:id/sub-tasks, /health
    POST /pipelines/start, /pipelines/:id/abort
- src/rails/rails.scheduler.ts — 2초마다 rails poll → EventEmitter2 broadcast
- src/rails/rails.module.ts — module + DI
- events.gateway.ts — rails.* 이벤트 핸들러 3종 (Socket.IO 'rails:*')
- app.module.ts — RailsModule 등록

Frontend:
- lib/useRailsSocket.ts — Socket.IO 훅 (rails:pipelines / pipeline:updated / subtasks)
- components/rails/PipelineList.tsx — 좌측 파이프라인 카드 목록
- components/rails/SubTaskTree.tsx — 우측 계층 트리 뷰
    role 별 색상 (manager/principal/lead/junior)
    state 별 dot + running pulse 애니메이션
    duration / model 표시
- app/rails/page.tsx — 라이브 대시보드 페이지
    좌: 파이프라인 목록 + Start 폼
    우: 선택된 파이프라인의 sub-task 트리
- components/common/Sidebar.tsx — '레일' 메뉴 추가

기존 hanarang-dashboard 의 UX/테마 그대로 재사용 (CSS variables).
인증은 기존 JwtGuard 그대로 적용.

검증: backend nest build ✓ | frontend next build ✓ (turbopack)

다음: Dev 서버에 배포 + 첫 라이브 파이프라인 구동 확인.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 17:30:11 +09:00
bec8df64ec fix: ChatWorkspace loadRuntime() use cookie-based withSessionRequest 2026-04-09 10:08:02 +09:00
2d01f520c4 Merge PR: SPRINT-017 office mobile plan 2026-04-09 09:59:27 +09:00
622eac3a10 fix: SPRINT-017 review fixes
1. Desktop breakpoint 768px → 1280px+ (tablet keeps mobile flow)
2. Default context always rendered (shows working sister when none selected)
3. MobileSisterCard aria-pressed for accessibility
4. ChatWorkspace localStorage → cookie-based withSessionRequest
2026-04-09 09:51:12 +09:00
4434e75a12 feat: SPRINT-017 mobile-first office dashboard overhaul
- Mobile summary view with sister cards, focus, health, quick actions
- Compact card flow replaces OfficeScene on mobile (no shrink)
- ContextPanel absorbed inline on mobile
- PipelinePanel vertical stack on mobile
- ServerHealthPanel 2-col mobile, 1-col below 360px
- ChatWorkspace tab padding optimized for narrow screens
- Desktop 1280+ layout preserved as-is
- Breakpoints: 360 / 390 / 768 / 1280+
2026-04-09 09:40:22 +09:00
ba800ea8e3 docs: sharpen sprint 017 office mobile plan 2026-04-09 09:20:30 +09:00
c25e05f685 Merge PR #14: SPRINT-016 office dashboard hotfix 2026-04-09 08:59:16 +09:00
54535e7b5e fix: resolve 8 review/security issues (SPRINT-016 hotfix)
Security:
- JwtGuard + RoleGuard on all sisters endpoints
- Admin-only access for config/sessions/subagents/activity
- ThrottlerGuard on /auth/refresh
- HttpOnly SameSite cookies + CSRF (replaces localStorage)

Code Quality:
- Per-sister draft input (Record<SisterName, string>)
- crypto.randomUUID for optimistic message ids (dedupe ready)
- Polling disabled while WebSocket connected
- SVG keyboard accessibility (role/tabIndex/onKeyDown)
2026-04-09 08:51:28 +09:00
bc6904d348 docs: add sprint 017 office stabilization plan 2026-04-08 18:51:17 +09:00
fc0d831f57 merge: fix circular dependency Events↔Sisters↔Activity + restore WebSocket broadcast 2026-04-08 05:50:07 +00:00
58843db298 fix: wire activity.logged event to WebSocket broadcast
Add @OnEvent('activity.logged') listener in EventsGateway to bridge
EventEmitter2 → WebSocket activity:new broadcast. Restores real-time
activity push without reintroducing circular dependency.
2026-04-08 14:14:01 +09:00
d8f2818e59 fix: break circular dependency between Events↔Sisters↔Activity
- Replace EventsGateway direct dependency in ActivityService with EventEmitter2
- ActivityModule no longer imports EventsModule (cycle broken)
- Register EventEmitterModule in AppModule
- Update activity.service.spec.ts to provide EventEmitter2
- SistersModule safely imports ActivityModule without creating a cycle

Dependency graph after fix:
  EventsModule → SistersModule → ActivityModule (leaf, no back-edge)
2026-04-08 14:07:19 +09:00
88547e9464 fix: wire office dashboard to runtime state 2026-04-08 13:49:26 +09:00
bb36380c92 fix: wrap office pipeline keyframes with css helper 2026-04-07 05:09:05 +00:00
1ccc1e6830 docs: add sprint-016 release preflight 2026-04-07 13:56:45 +09:00
a9e1e677b0 feat: merge SPRINT-016 isometric office dashboard 2026-04-07 13:36:58 +09:00
658d5e7af7 docs: restore code-reviewer in sprint 016 spec 2026-04-07 13:01:44 +09:00
3bdd24a3a5 fix: restore 17 subagents in office dashboard 2026-04-07 12:57:43 +09:00
f920318138 fix: align office dashboard subagent count 2026-04-07 12:51:55 +09:00
a731ecee4b fix: stabilize office dashboard demo states and motion 2026-04-07 12:12:11 +09:00
6e0583efeb feat: implement SPRINT-016 isometric office dashboard
Build the 4자매 office dashboard with SVG scene, agent state
visualization, context panel, direct chat workspace, pipeline panel,
and server health panel.

- frontend/app/office/page.tsx: Main office page (sisters + ops data,
  WS live + polling fallback, selected agent state, chat toggle)
- frontend/components/office/OfficeScene.tsx: SVG 2D office floor plan
  with 4 fixed sister desks, 17 subagent nodes, handoff connector lines,
  conference room, and per-state animations (idle/thinking/tool_calling/
  speaking/error)
- frontend/components/office/ContextPanel.tsx: Right context panel
  showing selected sister or subagent detail, current task, subagent
  list, chat/detail links
- frontend/components/office/ChatWorkspace.tsx: Direct chat workspace
  with sister tabs, message timeline, streaming-ready layout; Gateway
  connection pending notice (honest fallback labeling)
- frontend/components/office/PipelinePanel.tsx: Bottom pipeline panel
  with sprint/workflow nodes and flow animations
- frontend/components/office/ServerHealthPanel.tsx: Server health grid
  for 4 sisters + Dev + Docker with live/snapshot/fallback labels
- frontend/components/common/Sidebar.tsx: Add /office nav item

Data labeling: sisters live via WS (snapshot fallback),
subagent states derived/fallback, pipeline snapshot, chat gateway-pending.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 11:49:23 +09:00
3ba765b430 docs: plan sprint-016 office dashboard 2026-04-07 11:29:59 +09:00
68c69f6dfa merge: hotfix-006 dashboard copy and live fidelity 2026-04-06 20:47:24 +09:00
441f590989 fix: correct dashboard freshness wiring 2026-04-06 20:45:41 +09:00
6596090677 fix: tighten dashboard copy and freshness labels 2026-04-06 20:40:59 +09:00
b47248b2be docs: plan hotfix-006 dashboard copy and live fidelity 2026-04-06 20:37:04 +09:00
768f9fdc20 merge: sprint-015 dashboard v3 redesign 2026-04-06 20:25:39 +09:00
a8ff05c96a fix: stabilize backend prisma and lint 2026-04-06 20:21:40 +09:00
90ab555915 fix: source dashboard ops from real logs 2026-04-06 20:04:20 +09:00
5b7e4ec50d feat: redesign dashboard v3 layout 2026-04-06 19:52:29 +09:00
1b3edd45f6 docs: plan sprint-015 dashboard v3 redesign 2026-04-06 19:44:31 +09:00
2aa8dc14b9 Merge remote-tracking branch 'origin/feature/structure-renewal-sync' 2026-04-06 12:33:04 +09:00
805f5ed5cb Revert "hotfix: fix dashboard mobile charts and project details"
This reverts commit cb5d940550.
2026-04-05 09:04:38 +09:00
cb5d940550 hotfix: fix dashboard mobile charts and project details
- Fix Sister load chart: change BarChart align-items to stretch with BarCol
  justify-content flex-end so percentage-height bars render correctly
- Fix Project progress chart: same BarChart fix, add mobile height (120px)
- Add responsive BarLabel with text truncation for mobile
- Show hotfix description/summary in project hotfix history (fallback to default)
- Add SisterAvatar to assigned nodes area (avatar + name together)
- Add mobile breakpoint for PhaseItem grid (70px label column on mobile)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 07:45:17 +09:00
115 changed files with 24677 additions and 2780 deletions

View File

@@ -0,0 +1 @@
1775818515

1
.gitignore vendored
View File

@@ -44,3 +44,4 @@ coverage/
# TypeScript
*.tsbuildinfo
.claude/state/

View File

@@ -4,6 +4,19 @@
- 4자매 운영 상태를 실시간으로 보여준다
- 프로젝트/Sprint/Hotfix/QA/Deploy 흐름을 시각화한다
- `main`이 항상 배포 가능 상태라는 원칙을 UI와 운영에 함께 반영한다
- 오피스 화면과 운영 패널이 분리되지 않고 하나의 관제 경험으로 이어지게 만든다
## 저장소 / Git 기준
- Repo: `hanarang-dashboard`
- Git URL: `https://git.nabomhalang.co.kr/hanarang/hanarang-dashboard`
- 기본 브랜치: `main`
- 현재 오피스 구현 기준 경로:
- `frontend/app/office/page.tsx`
- `frontend/components/office/OfficeScene.tsx`
- `frontend/components/office/ContextPanel.tsx`
- `frontend/components/office/ChatWorkspace.tsx`
- `frontend/components/office/PipelinePanel.tsx`
- `frontend/components/office/ServerHealthPanel.tsx`
## 현재 표준 구조
- 루트: `README.md`, `ARCHITECTURE.md`
@@ -15,24 +28,70 @@
- `deploy/`
- 장기 문서: `docs/`
## 활성 작업
- **SPRINT-014**: Hermes 전환 + 프로젝트 IA/파일 구조 리뉴얼
## 현재 상태
- **SPRINT-016**: `/office` 기본 화면과 핵심 컴포넌트가 `main`에 반영됨
- **다음 활성 작업**: **SPRINT-017** `/office` 모바일 화면 전면 개편
## 이번 Sprint 핵심 요구사항
1. OpenClaw → Hermes 전환 후 자매 상태가 전부 offline으로 보이는 문제 해결
2. 자매 프로필 사진 탐색 경로/fallback 재정비
3. 변경된 파일 구조에 맞춘 프로젝트 진행률 / Sprint / Hotfix UI 개편
4. 프로젝트를 네비게이션 두 번째 페이지로 고정
5. 다랑 QA 완료 후 `main`이 배포 상태가 되고, 이랑은 최신 `main`을 pull해서 재배포만 수행하도록 흐름 고정
## SPRINT-017 active scope
이번 Sprint는 안정화 전반이 아니라 **`/office` 모바일 정보 구조 재설계**에만 집중해.
### 이번에 반드시 해결할 것
1. `360px`, `390px` 첫 viewport에서 아래 4가지를 한 번에 읽히게 만든다.
- 4자매 상태
- current focus
- health summary
- quick actions
2. `mobile(<768)`에서는 데스크톱 씬 축소판을 금지하고, 모바일 전용 세로 흐름 IA로 바꾼다.
3. `PipelinePanel``ServerHealthPanel`을 가로 스크롤 없이 읽히는 카드 흐름으로 바꾼다.
4. `ChatWorkspace`를 모바일 direct chat 기준으로 다시 정리하고, `JWT 없음 / empty / error / runtime 확인 중` 상태를 즉시 읽히게 만든다.
5. `live / snapshot / fallback` 의미는 유지하되, 모바일에서 더 짧고 일관된 라벨로 통일한다.
### 이번에 하지 않을 것
- 새로운 백엔드 API 추가
- WebSocket 프로토콜 재설계
- 별도 모바일 앱 설계
- 3D/고해상도 오피스 씬 확장
- 데스크톱 전체 IA 재작성
## 현재 main 구현에서 확인된 모바일 문제
- `frontend/components/office/OfficeScene.tsx`
- `aspect-ratio: 800 / 460` 고정 씬이라 모바일에서 데스크톱 축소판처럼 보임
- `frontend/app/office/page.tsx`
- 모바일 전용 summary hero가 없고, `ChatArea``460px` 고정 높이에 의존함
- 선택 전에는 `ContextPanel`과 chat이 핵심 정보 대신 빈 상태에 가까움
- `frontend/components/office/ContextPanel.tsx`
- 선택 의존 구조라 첫 진입 시 상세 정보가 비어 있음
- `frontend/components/office/PipelinePanel.tsx`
- `overflow-x: auto` 기반이라 모바일에서 가로 스크롤 전제가 생김
- `frontend/components/office/ChatWorkspace.tsx`
- 모바일에서 direct chat 맥락이 탭, 타임라인, composer, 상태 패널로 분산되고 보조 정보가 숨겨짐
## breakpoint 기준
- **Mobile compact:** `360px`
- **Mobile default:** `390px`
- **Tablet:** `768px`
- **Desktop:** `1280px+`
## 이행 전략
- 코드에서는 구 구조와 신 구조를 일정 기간 동시 지원
- 문서는 신 구조를 기준으로 선반영
- 신규 QA 문서는 `.plans/qa/` 기준
- 신규 Hotfix 문서는 `.plans/hotfix/` 기준
- 문서는 실제 `main` 구현 경로를 근거로만 갱신한다
- SPRINT-017은 `mobile-first IA``상태 라벨 통일`까지만 잠근다
- 구현 작업은 `frontend/app/office/page.tsx``frontend/components/office/*` 범위 안에서 끝내는 걸 기본으로 한다
- QA는 `360 / 390 / 768 / 1280+` 실브라우저 확인을 기준으로 남긴다
## 문서 맵
- 구조 기준: `../ARCHITECTURE.md`
- 제품 PRD: `../docs/product-specs/openclaw-office-dashboard-prd.md`
- 디자인 인덱스: `./design/index.md`
- Sprint 계획: `./sprints/SPRINT-014.md`
- Sprint 016 비전: `./sprints/SPRINT-016.md`
- Sprint 017 실행 계획: `./sprints/SPRINT-017.md`
- 오피스 모바일 IA: `./design/ui/office-dashboard-design.md`
- 오피스 direct chat 모바일 기준: `./design/ui/office-chat-design.md`
- API / 실시간 모델 참고: `./design/api-design.md`
- 배포 플로우: `./deploy/main-release-flow.md`
## 교차 참조 규칙
- Sprint 문서는 관련 design 문서를 반드시 링크한다
- design 문서는 실제 Git 구현 경로와 breakpoint를 같이 적는다
- QA 문서는 `360 / 390 / 768 / 1280+` 결과를 나눠 기록한다
- `live / snapshot / fallback` 용어는 Sprint 문서와 UI 문서에서 동일하게 쓴다
- 여기까지가 SPRINT-017 기준 scope야.

View File

@@ -20,10 +20,13 @@
## PM2 설정
```
backend: pm2 start dist/main.js --name hanarang-api --env production
frontend: pm2 start npm --name hanarang-web -- start -- -p 3004
backend: pm2 start backend/dist/src/main.js --name hanarang-api --cwd /path/to/hanarang-dashboard --env production
frontend: pm2 start npm --name hanarang-web --cwd /path/to/hanarang-dashboard/frontend -- start -- -p 3004
```
- backend 엔트리포인트는 실제 Nest 빌드 산출물 기준 `backend/dist/src/main.js`를 사용해.
- repo 루트에서 실행하면 `--cwd`를 명시해서 PM2가 올바른 작업 디렉터리를 잡도록 해.
## SSH 키 배포
- Dev 서버(10.10.10.169)에서 4자매 서버로 SSH 접속할 수 있도록 키 배포 필요
- 이랑이가 SSH 키 생성 + 각 자매 서버에 authorized_keys 추가

View File

@@ -3,36 +3,137 @@
## 공통 규칙
- Base URL: `https://hanarang-api.nabomhalang.co.kr`
- 응답 형식: JSON
- 인증: MVP에서는 인증 없음 (내부망 전용). 추후 JWT 추가 가능.
- 에러 형식: `{ "statusCode": 400, "message": "...", "error": "Bad Request" }`
- WS Namespace: `/ws`
- 기본 에러 형식: `{ "statusCode": 400, "message": "...", "error": "Bad Request" }`
- SPRINT-017 기준으로 오피스 화면은 `REST snapshot + WebSocket push` 혼합 모델을 사용한다.
## Sisters (자매 상태)
## 인증 규칙
- 읽기 전용 상태 조회 API는 현재 공개 조회가 가능한 엔드포인트가 섞여 있어.
- direct chat (`POST /api/sisters/:name/chat`) 은 JWT 필수야.
- WebSocket 연결도 JWT 필수야. 토큰이 없거나 잘못되면 서버가 연결을 끊어.
- 그래서 `/office`**읽기와 쓰기의 권한 상태를 분리해서** 다뤄야 해.
| Method | Endpoint | 설명 |
|--------|----------|------|
| GET | `/api/sisters` | 4자매 상태 목록 (SSH로 실시간 조회) |
| GET | `/api/sisters/:name` | 자매 상세 (설정 + 상태) |
| GET | `/api/sisters/:name/config` | openclaw.json 내용 |
| GET | `/api/sisters/:name/sessions` | 최근 세션 목록 |
| GET | `/api/sisters/:name/subagents` | 서브에이전트 사용 현황 |
| POST | `/api/sisters/:name/restart` | Gateway 재시작 (관리자) |
| POST | `/api/sisters/:name/reset` | 세션 리셋 (관리자) |
## 오피스 대시보드 핵심 소스
- Git 구현 기준:
- `frontend/app/office/page.tsx`
- `backend/src/sisters/sisters.controller.ts`
- `backend/src/events/events.gateway.ts`
- `backend/src/events/events.scheduler.ts`
- 관련 Sprint: `../sprints/SPRINT-017.md`
- 관련 UI 문서:
- `./ui/office-dashboard-design.md`
- `./ui/office-chat-design.md`
### GET `/api/sisters`
## 상태 모델
### Data Mode
| mode | 의미 | UI 원칙 |
|---|---|---|
| `live` | WebSocket 또는 최신 runtime 기준으로 실시간성이 유지되는 상태 | 가장 신뢰도 높은 상태로 표시 |
| `snapshot` | REST polling 기준 최신 스냅샷 | live보다 약한 상태로 표시 |
| `fallback` | runtime 또는 status 조회 실패 시 보여주는 보정 데이터 | 추정치임을 숨기지 않음 |
### Agent State
| state | 의미 |
|---|---|
| `idle` | 대기 중 |
| `thinking` | 작업 준비 / 추론 중 |
| `tool_calling` | 외부 작업/도구 호출 중 |
| `speaking` | 응답 생성 또는 대화 중 |
| `error` | 연결 또는 런타임 이상 |
## Sisters (오피스 화면 기준)
| Method | Endpoint | 인증 | 설명 |
|--------|----------|------|------|
| GET | `/api/sisters` | 없음 | 4자매 상태 목록 |
| GET | `/api/sisters/runtime` | 없음 | 4자매 runtime 스냅샷 |
| GET | `/api/sisters/:name/runtime` | 없음 | 개별 자매 runtime |
| GET | `/api/sisters/:name/system` | 없음 | 개별 자매 시스템 정보 |
| GET | `/api/sisters/:name/avatar` | 없음 | 자매 아바타 이미지 |
| GET | `/api/sisters/:name/config` | 없음 | openclaw 설정 조회 |
| GET | `/api/sisters/:name/sessions` | 없음 | 최근 세션 목록 |
| GET | `/api/sisters/:name/subagents` | 없음 | 서브에이전트 목록/현황 |
| GET | `/api/sisters/:name/activity` | 없음 | 최근 활동 로그 |
| POST | `/api/sisters/:name/chat` | JWT 필요 | direct chat 전송 |
### GET `/api/sisters/runtime`
오피스 메인 화면의 상단 상태와 최근 메시지, 서브에이전트 상태를 구성하는 runtime source야.
예시 필드:
```json
// Response 200
[
{
"name": "harang",
"displayName": "하랑이",
"ip": "10.10.10.112",
"status": "online",
"lastSeen": "2026-04-04T01:45:00Z",
"role": "Orchestrator"
"gatewayConnected": true,
"mainState": "thinking",
"currentTask": "SPRINT-017 scope 잠금",
"activeSessionLabel": "main",
"activeSessionUpdatedAt": 1775640000000,
"controlSessionKey": "agent:harang:main",
"recentMessages": [
{
"id": "msg_1",
"role": "assistant",
"content": "scope 정리 중",
"ts": "2026-04-08T09:20:00Z"
}
],
"subagents": [
{
"name": "prd-writer",
"state": "tool_calling",
"updatedAt": 1775640000000,
"currentTask": "SPRINT-017 작성",
"sessionLabel": "main"
}
]
}
]
```
### POST `/api/sisters/:name/chat`
```json
// Request
{ "message": "SPRINT-017 scope 확인해" }
```
```json
// Response 200 example
{
"ok": true,
"queued": true,
"sessionKey": "agent:harang:main"
}
```
### Chat 실패 처리 원칙
- JWT 없음 → 입력창 비활성화 또는 전송 실패 이유 명시
- timeout → 전송은 재시도 가능 상태로 남김
- 최근 메시지 없음 → empty state 문구 사용
- tool 메시지와 assistant 메시지는 같은 bubble로 합치지 않음
## WebSocket
### 연결
- Namespace: `/ws`
- 인증 방식:
- `handshake.auth.token`
- 또는 `Authorization: Bearer <token>`
- 토큰 없음/검증 실패 시 disconnect
### 서버 이벤트
| Event | Payload | 설명 |
|---|---|---|
| `pong` | `{ ts }` | ping 응답 |
| `sisters:update` | `{ sisters, ts }` | 4자매 상태 push |
| `activity:new` | `{ item, ts }` | 새 활동 로그 push |
### 운영 규칙
- WS는 가장 강한 source야.
- WS가 끊겨도 마지막 성공 시각을 보존해 stale 여부를 판단해야 해.
- scheduler polling 값이 더 오래된 경우 live 값을 덮어쓰면 안 돼.
- SPRINT-017에서는 reconnect / stale / snapshot downgrade 규칙을 문서와 QA 기준으로 잠근다.
## Projects (프로젝트)
| Method | Endpoint | 설명 |
@@ -69,3 +170,9 @@
| Method | Endpoint | 설명 |
|--------|----------|------|
| GET | `/health` | 서버 상태 확인 |
## SPRINT-017 문서 기준 정리
- 오피스 화면은 읽기 API와 쓰기 API 권한을 분리해서 다룬다
- `live / snapshot / fallback`은 API 문서, UI 문서, QA 문서에서 같은 의미로 쓴다
- direct chat, WS disconnect, stale 상태는 정상 흐름만큼 중요하게 검증한다
- 여기까지가 API 기준 scope야.

View File

@@ -44,5 +44,5 @@ Backend가 SSH로 각 자매 서버에서 수집:
## 배포
- **Dev 서버:** 10.10.10.169
- **프로세스 관리:** PM2
- **FE:** pm2 start npm --name hanarang-web -- start (포트 3004)
- **BE:** pm2 start dist/main.js --name hanarang-api (포트 3005)
- **FE:** `pm2 start npm --name hanarang-web --cwd /path/to/hanarang-dashboard/frontend -- start -- -p 3004`
- **BE:** `pm2 start backend/dist/src/main.js --name hanarang-api --cwd /path/to/hanarang-dashboard` (포트 3005)

View File

@@ -8,6 +8,8 @@
## 페이지별 UI
- `ui/dashboard-design.md`
- `ui/office-dashboard-design.md`
- `ui/office-chat-design.md`
- `ui/projects-page-design.md`
- `ui/project-detail-design.md`
- `ui/sister-detail-design.md`
@@ -16,8 +18,23 @@
- `ui/settings-design.md`
- `ui/admin-design.md`
## Sprint 014에서 반드시 반영할 화면
- 대시보드 메인: Hermes 상태/프로젝트 요약/두 번째 네비 반영
- 프로젝트 목록: 프로젝트를 두 번째 페이지로 이동한 기준 재배치
- 프로젝트 상세: Sprint / Hotfix / QA / Deploy 분리 구조 반영
- 자매 페이지: Hermes 상태 판정과 아바타 fallback 반영
## 레퍼런스
- `references/07-master-dashboard-v3-reference.md`
## 현재 우선 문서
- Sprint 실행 기준: `../sprints/SPRINT-017.md`
- 제품 비전: `../../docs/product-specs/openclaw-office-dashboard-prd.md`
- 실행 개요: `../OVERVIEW.md`
## SPRINT-017에서 반드시 잠글 것
- 오피스 메인: Desktop / Tablet / Mobile 정보 우선순위
- 오피스 채팅: JWT 필요, 전송 실패, empty state 처리
- 운영 패널: active workflow / sprint / review loop / deploy gate / server health 상태 톤 통일
- 실시간 모델: `live / snapshot / fallback` 판정 규칙
- WS + polling reconciliation: stale / reconnect / downgrade 기준
## Git 기준 확인 경로
- `/office` entry: `frontend/app/office/page.tsx`
- scene: `frontend/components/office/OfficeScene.tsx`
- chat: `frontend/components/office/ChatWorkspace.tsx`
- ws gateway: `backend/src/events/events.gateway.ts`

View File

@@ -0,0 +1,33 @@
# Master Dashboard v3 Reference Notes
## 출처
자기야가 2026-04-06에 공유한 레퍼런스 시안.
## 핵심 인상
- 짙은 다크 배경 위에 운영 패널을 촘촘하게 배치
- 상단 global status bar + 중앙 sprint progress + 우측 runtime connection 구조
- 4자매 상태 카드를 1행에서 동시에 노출
- `ACTIVE PIPELINE`을 중심으로 4자매 협업 흐름을 시각화
- `ACTIVITY FEED` / `SPRINT METRICS` / `INFRASTRUCTURE OVERVIEW` / `MISTAKE LOG & HARNESS`를 한 화면에서 모두 판단 가능
## 채택 결정
- **채택:** 정보 구조, 섹션 구성, 운영 화면다운 밀도, Active Pipeline 개념
- **부분 채택:** 색 강조, pulse/flow 애니메이션, 상단 진행률 표현
- **비채택:** 과한 glow, glassmorphism 회귀, 장식 위주의 다이어그램화
## 제품 적용 원칙
- 하나랑 대시보드는 현행 미니멀 터미널 UI 톤을 유지
- 레퍼런스는 `레이아웃/정보 위계/흐름 표현` 위주로 번역 적용
- 비주얼 차용 비율은 대략 70% 이내로 제한
- 실데이터 기반 운영 화면으로 느껴져야 하며 mock showcase처럼 보이면 안 됨
## 특히 강한 섹션
1. Sister Status Cards
2. Active Pipeline
3. Activity Feed + Metrics 병렬 비교
4. Infra + Mistake Log 하단 운영 패널
## 구현 시 주의
- 실제 데이터 밀도에 비해 컴포넌트가 과장되면 안 됨
- 첫 스크롤 안에 가장 중요한 판단 정보가 모여야 함
- 모바일에서는 같은 구조를 억지로 축소하지 말고 세로 흐름으로 재배열

View File

@@ -1,31 +1,239 @@
# 대시보드 메인 (`/`) — Sprint 014 리뉴얼 포인트
# 대시보드 메인 (`/`) — Sprint 015 Master Dashboard v3
## 유지 요소
- 미니멀 터미널 UI
- 4자매 상태 카드
- 프로젝트 요약 + 활동 피드
- 모바일 하단 탭바
## 목적
대시보드 메인은 단순 요약 화면이 아니라, 자기야가 들어오자마자 `지금 4자매 파이프라인이 어디까지 와 있는지` 즉시 판단할 수 있는 대표 운영 화면이어야 해.
## 수정 포인트
### 1. 자매 상태 판정
- Hermes 런타임 기준 상태를 읽어야 함
- OpenClaw만 보는 하드코딩 제거
- 상태 카드가 전원 `OFFLINE`으로 고정되지 않게 실제 상태/uptime/cpu를 노출
이번 v3의 핵심은 **현행 미니멀 터미널 UI를 유지하면서, 더 강한 정보 구조와 흐름 시각화로 메인 화면을 재구성하는 것**이야.
### 2. 자매 아바타
- 실사/프로필 이미지가 있으면 사용
- 없으면 fallback SVG
- broken image 상태 금지
## 유지할 것
- 현재 제품의 미니멀 터미널 톤
- 짙은 배경 + 얇은 border + mono 보조 텍스트
- 4자매 중심 세계관/역할 구분
- 모바일 하단 탭바와 기존 페이지 동선
### 3. 프로젝트 요약 영역
- 프로젝트는 네비게이션 두 번째 페이지와 동일한 정보 구조를 축약해서 보여줌
- 단순 퍼센트만이 아니라 현재 phase가 드러나야 함
## 강하게 가져올 것
- 상단 global status bar 구조
- 4자매 카드 1행 배치
- `ACTIVE PIPELINE` 중심 운영 다이어그램
- `ACTIVITY FEED` + `SPRINT METRICS` 병렬 구조
- `INFRASTRUCTURE OVERVIEW` + `MISTAKE LOG & HARNESS` 하단 운영 패널 구조
### 4. 네비게이션 순서
- `대시 → 프로 → 활동 → 자매 → 조직 → 설정 → 관리`
- 모바일 하단 탭바도 같은 순서 유지
## 줄일 것
- 과한 glow
- 장식성 애니메이션 남발
- 의미 없이 많은 뱃지/배경 장식
- mock 대시보드처럼 보이는 가짜 숫자 강조
## 모바일 기준
- 2열 상태 카드 유지
- 프로젝트 요약은 phase 우선, 활동 피드는 그 아래
- 하단 탭에서 프로젝트가 두 번째 탭으로 보여야 함
---
## 전체 레이아웃
### 1. Top Global Status Bar
한 줄 또는 반응형 2단 구조.
#### 좌측
- 브랜드/제품명
- 현재 페이지 정체성 (`Master Dashboard`)
#### 중앙
- 현재 Sprint / Day / focus summary
- 진행률 bar 또는 current cycle 요약
#### 우측
- Discord/Runtime 연결 상태
- 알림 진입점
- operator/avatar 요약
#### UX 기준
- 상단에서 현재 운영 국면을 짧게 읽을 수 있어야 함
- 모바일에서는 좌/중/우를 무리하게 한 줄에 우겨넣지 말고 2단으로 자연스럽게 접기
---
### 2. Sister Status Cards Row
4자매 카드는 1행 핵심 상태 영역.
#### 공통 정보
- 이름
- 역할
- 상태 (`IDLE`, `WORKING`, `REVIEWING`, `OFFLINE`, `DEPLOYING` 등)
- CPU / RAM 또는 대응 리소스 지표
- 현재 작업 한 줄 요약
#### 역할별 색 기준
- Harang: amber
- Narang: sky
- Darang: pink
- Irang: violet
#### 상태 표현 규칙
- 색은 역할 + 현재 상태를 같이 전달해야 함
- working/reviewing처럼 active 상태일 때만 강한 강조
- idle은 조용하게
- offline은 회색/경고 계열로 분명히 구분
#### 카드 UX 기준
- 네 카드의 높이/구조는 최대한 동일
- 긴 텍스트는 1줄 또는 2줄 clamp
- CPU/RAM은 숫자와 bar를 함께 보여줘도 되지만 과장하지 말 것
- 아바타/아이콘은 보조 요소고, 상태 텍스트가 주인공이어야 함
---
### 3. `ACTIVE PIPELINE`
이번 v3의 대표 섹션.
#### 목적
User → Harang → Narang → Darang → Irang 흐름과, maker-checker loop, escalation 조건을 한눈에 보여준다.
#### 기본 노드
- User
- Harang (`Plan & Assign`)
- Narang (`Implement` or active task id)
- Darang (`Review / QA`)
- Irang (`Deploy / Idle`)
#### 보여줄 정보
- 현재 active task 또는 ticket id
- Narang ↔ Darang review loop
- escalation 조건 또는 누적 실패 횟수
- Irang이 아직 idle인지, redeploy 대기인지
#### 구현 기준
- SVG 기반 라인/화살표 허용
- active state가 있을 때만 제한적 pulse/flow
- 정적인 설명보다 실제 운영 상태가 우선
- loop / escalation은 읽히되 과하게 복잡하면 안 됨
#### 금지
- 예쁘기만 한 다이어그램
- 현재 상태를 읽을 수 없는 장식형 선/화살표
---
### 4. Middle Row — `ACTIVITY FEED` + `SPRINT METRICS`
운영 근거와 정량 판단을 나란히 배치한다.
#### A. Activity Feed
운영 이벤트 타임라인.
##### 우선 정보
- 시각
- 주체/대상 (예: Narang → Darang)
- 이벤트 타입 (`handoff`, `review_request`, `review_fail`, `deploy`, `hotfix` 등)
- 관련 task/sprint/hotfix id
- 실패/경고 시 짧은 원인
##### UX 기준
- 텍스트 로그가 아니라 읽히는 이벤트 카드여야 함
- event type 색은 통일감 있게 관리
- 필요하면 details/JSON 결과는 접어서 보여줌
#### B. Sprint Metrics
한 Sprint의 진행 체감치를 운영 지표로 압축.
##### 포함 후보
- total tasks
- done / in progress / review / planning 비중
- sister별 completed count
- avg iterations
- first-pass rate
- escalation count
##### UX 기준
- 차트는 보조, 숫자 읽기가 우선
- donut + mini bar + stat box 조합 허용
- `활동 피드와 같은 행에서 비교`했을 때 자연스러워야 함
---
### 5. Bottom Row — `INFRASTRUCTURE OVERVIEW` + `MISTAKE LOG & HARNESS`
운영 기반과 학습 자산을 하단에 둔다.
#### A. Infrastructure Overview
##### 목적
현재 시스템이 어디서 어떻게 돌아가는지 빠르게 파악.
##### 포함 요소
- gateway
- sisters runtime host/lxc/vm
- deploy access path
- health / load / uptime 요약
##### 표현 방식
- 단순 카드 나열보다 연결 관계가 보이는 가벼운 맵 구조 선호
- 다만 실제 데이터가 빈약하면 과장된 네트워크 다이어그램으로 만들지 말 것
#### B. Mistake Log & Harness
##### 목적
운영 중 쌓인 실수/규칙/학습 자산을 한 눈에 보여줌.
##### 포함 요소
- 최신 mistake/harness rule 몇 개
- 작성 시점
- 누가 추가했는지
- category (`DB Schema`, `Frontend`, `Deployment` 등)
- 필요하면 작은 trend visualization
##### UX 기준
- 단순 문서 링크가 아니라 운영 학습 보드처럼 보여야 함
- `View Full` 또는 상세 문서 링크는 보조로 유지
---
## 데스크톱 정보 순서
1. Top Global Status Bar
2. Sister Status Cards
3. Active Pipeline
4. Activity Feed / Sprint Metrics
5. Infrastructure Overview / Mistake Log & Harness
## 모바일 정보 순서
1. Top Status Summary
2. Sister Status Cards (2열 또는 1열)
3. Active Pipeline
4. Activity Feed
5. Sprint Metrics
6. Infrastructure Overview
7. Mistake Log & Harness
모바일에서는 복잡한 수평 관계보다 세로 읽기 흐름이 우선이야.
---
## 데이터 연결 원칙
- mock 텍스트/숫자로 고정하지 말고 실제 데이터가 들어올 자리를 먼저 설계할 것
- 값이 없을 때는 `No recent activity`, `No active deployment`, `No harness rules yet`처럼 조용한 empty state 제공
- offline / missing / unavailable 상태는 숨기지 말고 명확히 드러낼 것
- websocket 연결 상태와 데이터 freshness를 같은 의미로 쓰지 말 것
- 각 섹션은 가능하면 아래 source 중 하나로 구분할 것
- `runtime live`
- `event mirrored`
- `polling snapshot`
- `doc derived`
- `empty / unavailable`
- 추정/합성값이면 사실처럼 단정하지 말고 neutral wording 사용
## 카피 원칙
- 설명문보다 라벨형 문구 우선
- 첫 화면 문구는 짧고 건조해야 함
- `~만들었어`, `~정리했어`, `~읽히게` 같은 메타 설명 금지
- 보드/패널 body는 원문 요약 또는 상태 문구 위주로 짧게 유지
## 인터랙션 원칙
- hover 없어도 핵심 정보가 읽혀야 함
- 클릭 가능한 영역은 페이지 이동 또는 상세 패널 열기처럼 의미가 분명해야 함
- notification / details / expand는 보조 수단
## 스타일 원칙
- background는 현행 다크 톤 유지
- border 1px 중심
- 그림자/glow는 active state 강조용 최소치만 사용
- 하드한 터미널 감성과 현대적 운영 패널 느낌 사이 균형 유지
## 연결 페이지
- 프로젝트 페이지는 phase/QA/deploy 세부 판단용
- 활동 페이지는 장기 로그 열람용
- 자매 상세는 개별 runtime/세션 분석용
- 관리 페이지는 조작/재시작/관리용
즉, 홈은 모든 걸 다 보여주는 곳이 아니라 **지금 어디를 눌러야 하는지 판단시키는 운영 출발점**이어야 해.

View File

@@ -0,0 +1,150 @@
# 오피스 direct chat UI 기준 — SPRINT-017 모바일 개편
## 문서 목적
`ChatWorkspace.tsx`를 모바일 direct chat 기준으로 다시 정리하기 위한 문서야. 기준 Sprint는 `.plans/sprints/SPRINT-017.md`이고, 메인 IA와 first viewport 원칙은 `.plans/design/ui/office-dashboard-design.md`를 따른다.
## 기준 구현 파일
- `frontend/components/office/ChatWorkspace.tsx`
- `frontend/app/office/page.tsx`
- 연관 문서: `.plans/design/ui/office-dashboard-design.md`
## breakpoint 기준
- `360px`: minimum mobile compact
- `390px`: primary mobile baseline
- `768px`: tablet transition
- `1280px+`: desktop baseline
## 현재 main 구현에서 확인된 문제
- `page.tsx`에서 chat은 `ChatArea` 고정 높이(`520px`, 모바일 `460px`) 안에 들어가 세로 흐름을 끊는다.
- `ChatWorkspace.tsx`는 모바일에서도 데스크톱 구조의 흔적이 강하다.
- 자매 탭, 메시지, 보조 컨텍스트가 분리되어 있다.
- `SisterContext``1199px` 미만에서 숨겨져 모바일 보조 정보가 사라진다.
- `SendBtn`은 토큰이 없으면 disabled라서, `JWT 없음` 이유를 화면에서 놓치기 쉽다.
- empty 상태 문구는 있지만, `JWT 없음 / error / runtime 확인 중`이 같은 강도로 정리되어 있지 않다.
## 모바일 direct chat 원칙
1. **한 컬럼 흐름**
- mobile(` <768`)에서는 탭 → 상태 → 타임라인 → composer → 보조 정보 순서로 한 컬럼으로 간다.
2. **전송 가능 여부를 숨기지 않기**
- `JWT 없음`이면 입력 근처에서 바로 이유를 보여준다.
3. **상태는 상단에 짧게**
- runtime/source 상태는 header 또는 composer 상단에서 한 번에 읽히게 한다.
4. **메시지가 우선**
- 보조 컨텍스트보다 타임라인과 입력창이 우선이다.
5. **고정 높이 최소화**
- 460px 박스 안에 억지로 채우지 않는다.
## mobile layout
모바일 기본 순서는 아래야.
### 1. sister switcher
- 4자매 전환을 상단 compact tab 또는 segmented control로 둔다
- 이름과 active 상태만 짧게 보여준다
- role 전체 문구는 모바일에서 숨기거나 축약한다
### 2. runtime / source badge row
상단 배지 영역에서 아래를 보여준다.
- runtime 상태: `연결됨`, `확인 중`, `stale`, `error`
- source badge: `live`, `snapshot`, `fallback`
- 필요 시 현재 자매 상태(`thinking`, `tool_calling`, `speaking`, `idle`)
### 3. timeline
- 메시지 타임라인은 화면에서 가장 큰 비중을 차지한다
- `user / assistant / tool` 구분은 유지한다
- tool 메시지는 mono 또는 강조 배경 유지
- 버블 최대 폭은 모바일에서 너무 좁아지지 않게 조정한다
### 4. composer
- 입력창과 전송 버튼은 타임라인 바로 아래
- `Enter = 전송`, `Shift+Enter = 줄바꿈` 힌트는 짧게 유지
- 전송 불가 상태면 버튼만 막지 말고 이유를 붙인다
### 5. support state block
모바일에서는 숨기지 말고 composer 아래 또는 접이식 블록으로 둔다.
- current task
- active session label
- data source 설명 한 줄
## 상태 배지 규칙
### source badge
- `live`: runtime 연결 또는 최신 상태 반영 중
- `snapshot`: 마지막 조회 스냅샷 표시 중
- `fallback`: 기본값 또는 보조 데이터 기준
### runtime badge
- `연결됨`: gatewayConnected = true
- `확인 중`: 아직 runtime snapshot 수신 전
- `stale`: 최근 업데이트가 늦음
- `오류`: 전송 또는 조회 실패
### 배지 위치
- header 오른쪽 또는 바로 아래 1줄
- 모바일에서는 긴 설명 대신 짧은 라벨 + 보조 문구 1개만 둔다
## empty / error / JWT 없음 UX
### empty
조건:
- 메시지 없음
- 최근 runtime 메시지도 없음
표현:
- "아직 대화가 없어"
- 바로 보낼 수 있는 예시 액션 1개 또는 placeholder
- runtime 상태 보조 문구
### JWT 없음
조건:
- `localStorage` 토큰 없음
- 또는 인증이 풀려 전송 불가
표현:
- 입력 근처에 즉시 보이는 경고 문구
- 예: `로그인이 풀려서 지금은 전송할 수 없어. 다시 로그인해.`
- 전송 버튼 disabled만 두고 끝내지 않는다
### 전송 실패
조건:
- `/api/sisters/:name/chat` 실패
표현:
- 타임라인 내 실패 메시지 유지
- composer 근처에 `다시 시도` 또는 실패 이유 보조 문구
- 실패와 empty를 같은 문구로 합치지 않는다
### runtime 확인 중
조건:
- runtime snapshot 미수신 또는 gateway 미연결
표현:
- header 배지 또는 상태 줄에 표시
- 메시지 전송 가능 여부와 별개인지 함께 설명
## 메시지 규칙
- `user`: 우측 또는 구분되는 배경
- `assistant`: 기본 응답 버블
- `tool`: mono 스타일과 별도 톤 유지
- timestamp는 보조 정보로만 노출
- 모바일에서 버블 폭이 지나치게 좁아 읽기 어렵지 않게 한다
## mobile에서 숨기면 안 되는 정보
- active sister
- runtime/source 상태
- current task 또는 active session 중 하나
- JWT 없음 / 전송 실패 이유
## desktop / tablet 유지 규칙
### desktop (`1280px+`)
- 현재 3열 느낌을 유지해도 돼
- 다만 source/runtime 라벨과 상태 문구는 모바일 기준과 통일해
### tablet (`768px`)
- 좌측 자매 전환 + 중앙 타임라인 구조 유지 가능
- 우측 보조 패널이 사라져도 핵심 상태는 상단에서 읽혀야 해
## QA 체크 포인트
- `360px`, `390px`에서 탭, 타임라인, 입력창이 겹치지 않는지
- 입력창이 키보드 노출 시 잘리지 않는지
- `JWT 없음` 상태가 버튼 disabled 외에 문구로도 보이는지
- `empty`, `runtime 확인 중`, `전송 실패`가 서로 다른 문구로 보이는지
- `user / assistant / tool` 구분이 모바일에서도 유지되는지
- source badge와 runtime badge가 다른 의미로 명확히 읽히는지

View File

@@ -0,0 +1,207 @@
# 오피스 대시보드 UI 기준 — SPRINT-017 모바일 개편
## 문서 목적
`/office` 메인 화면의 모바일 IA와 우선순위를 잠그는 문서야. 기준 Sprint는 `.plans/sprints/SPRINT-017.md`이고, active scope는 `.plans/OVERVIEW.md`를 따른다.
## 기준 구현 파일
- `frontend/app/office/page.tsx`
- `frontend/components/office/OfficeScene.tsx`
- `frontend/components/office/ContextPanel.tsx`
- `frontend/components/office/PipelinePanel.tsx`
- `frontend/components/office/ServerHealthPanel.tsx`
- 관련 chat 문서: `.plans/design/ui/office-chat-design.md`
## breakpoint 기준
- `360px`: minimum mobile compact
- `390px`: primary mobile baseline
- `768px`: tablet transition
- `1280px+`: desktop baseline
## 현재 main 구현에서 바꿔야 하는 점
- `OfficeScene.tsx``800 / 460` 비율 SVG 씬을 전제로 해서 모바일에서 정보보다 축소 그림이 먼저 보인다.
- `page.tsx`는 모바일 전용 상단 summary가 없어서 첫 화면에서 핵심 운영 정보가 바로 안 잡힌다.
- `ContextPanel.tsx`는 선택 전 빈 상태라 모바일 첫 진입에 불리하다.
- `PipelinePanel.tsx``overflow-x: auto`가 들어가 있어 모바일에서 읽기보다 옆으로 밀게 된다.
- `ServerHealthPanel.tsx`는 카드 그리드는 있지만 상단 health summary 우선순위가 없다.
## 모바일 핵심 원칙
1. **데스크톱 축소판 금지**
- 모바일은 desktop scene을 줄이는 방식이 아니라 모바일 전용 정보 구조를 쓴다.
2. **첫 viewport 우선**
- `360px`, `390px` 첫 화면에서 운영자가 바로 판단할 정보만 먼저 보여준다.
3. **선택 전에도 정보가 보이게**
- 자매를 누르기 전에도 상태, focus, health, action이 읽혀야 한다.
4. **가로 스크롤 금지**
- mobile에서는 모든 핵심 블록이 세로 흐름 안에서 끝나야 한다.
5. **상태 의미 유지**
- `live / snapshot / fallback`은 유지하되, 짧고 일관된 라벨로 통일한다.
## mobile IA
모바일(` <768`) 기본 순서는 아래로 고정해.
### 1. summary hero
가장 위. 첫 진입 핵심 문장 1개와 source badge 1개를 보여준다.
**포함 정보**
- 현재 focus project 또는 active task
- data source badge (`live`, `snapshot`, `fallback`)
- 보조 문구 한 줄
**하지 않을 것**
- 긴 설명문
- 데스크톱용 메타 정보 여러 줄
### 2. compact sister status
4자매 상태를 2x2 또는 1열 compact card로 보여준다.
**각 카드 최소 정보**
- 자매 이름
- 상태색과 상태 라벨
- current task 또는 active session 한 줄
- runtime/source 힌트 한 줄
**행동**
- 탭 또는 카드 선택 가능
- 선택 시 인라인 상세가 펼쳐져도 첫 카드 밀도를 깨지 않게 유지
### 3. focus / health / quick action block
첫 viewport 안에 반드시 들어와야 하는 운영 블록이야.
**focus block**
- current focus
- sprint / deploy state 중 하나의 핵심 값
**health block**
- online count
- 문제 있는 sister/server 요약
- source badge
**quick action block**
- direct chat 진입
- 상세 보기 또는 관련 패널 점프
### 4. panel sections
첫 viewport 이후 순차 노출.
모바일 추천 순서:
1. direct chat
2. pipeline
3. health detail
4. context detail
이 순서는 "지금 말 걸기 → 지금 뭐가 막혔는지 보기 → 상세 맥락 보기" 흐름을 따른다.
## first viewport priority
`360px`, `390px`에서 아래 4개가 모두 한 번에 보여야 해.
1. 4자매 상태
2. current focus
3. health summary
4. quick actions
### 우선순위 이유
- 자매 상태가 먼저 안 보이면 운영 화면이 아니라 decorative scene이 된다.
- focus가 없으면 무엇을 관제 중인지 설명이 안 된다.
- health summary가 없으면 online/offline 판단이 늦어진다.
- quick actions가 없으면 direct chat 진입이 숨는다.
## compact sister status 설계
### desktop와 다르게 볼 것
- desktop(`1280px+`)은 scene 중심
- tablet(`768px`)은 scene 축소 유지 가능하되 summary 보강 필요
- mobile(` <768`)은 scene 대신 status card 중심
### 카드 규칙
- 카드 높이는 task 한 줄, 상태 한 줄 기준으로 짧게 유지
- 자매 4명을 한 화면 안에서 비교 가능해야 함
- 선택된 자매는 인라인 확장이나 하단 sheet로 상세를 보여줄 수 있음
- subagent 수나 role은 보조 정보로만 노출
## scene 대체 전략
### mobile에서 scene을 이렇게 바꿔
`OfficeScene.tsx` 모바일 분기는 아래 둘 중 하나를 기준으로 구현해.
#### 옵션 A. compact sister stack
- 세로 카드 4개
- 각 카드에서 상태, current task, quick action 제공
- 선택 시 아래에 context summary 노출
#### 옵션 B. selectable status cards
- 2x2 grid 또는 가로 2열 카드
- 선택 카드만 확장
- 확장 영역에서 subagent / recent context / chat action 제공
### 반드시 지킬 것
- `800x460` SVG를 그대로 줄여서 넣지 않는다
- 회의실/존 은유는 모바일에서 필수 요소가 아니다
- mobile에서 중요한 건 공간 은유보다 운영 정보의 순서다
## context 흡수 전략
`ContextPanel.tsx` 내용은 mobile에서 별도 우측 패널이 아니라 아래 중 하나로 흡수해.
- selected sister 카드 안 인라인 상세
- accordion section
- bottom sheet
### mobile 기본 상태
- 아무 것도 선택되지 않아도 default context summary가 있어야 한다
- 예: "현재 focus", "현재 제일 바쁜 자매", "바로 채팅할 자매"
## health block 기준
`ServerHealthPanel.tsx` 전체를 첫 화면에 다 넣지 말고, 상단에는 summary만 먼저 둬.
**상단 summary 최소 정보**
- `online x/y`
- 문제 상태 1건 요약 또는 `all clear`
- source badge (`live`, `snapshot`, `fallback`)
**상세 패널에서 보여줄 것**
- 자매/서버 카드 리스트
- detail 문구
- refreshed/generated 시각
## pipeline block 기준
`PipelinePanel.tsx` 전체를 모바일 첫 viewport에 다 넣지 않는다.
**상단 summary 최소 정보**
- active task
- focus
- review loop count 또는 deploy state
**상세 패널에서 보여줄 것**
- 세로 단계 카드
- node role / state / detail
- snapshot freshness
## source badge 규칙
모바일에서는 source 표현을 아래처럼 통일해.
- `live`: 현재 runtime 또는 ws 기반 최신 상태
- `snapshot`: polling 또는 마지막 스냅샷 기준 상태
- `fallback`: 문서/기본값/보조 데이터 기준 상태
### 라벨 톤
- 라벨은 짧게
- 설명은 보조 문구 한 줄
- 첫 화면과 하위 패널에서 같은 단어 사용
## 상태 문구 규칙
- `loading`: 불러오는 중
- `empty`: 아직 표시할 데이터 없음
- `error`: 가져오지 못함 또는 전송 실패
- `stale`: 최신 연결이 약해 마지막 확인값 표시 중
`empty``error`는 절대 같은 문구로 처리하지 않아.
## desktop / tablet 유지 규칙
### desktop (`1280px+`)
- 기존 scene + context panel + bottom panels 구조 유지
- 단, source badge와 상태 라벨은 새 기준으로 통일
### tablet (`768px`)
- 데스크톱 구조를 유지해도 되지만 summary 우선순위를 보강해야 함
- 첫 화면에서 핵심 정보가 씬 아래로 밀리면 안 됨
## QA 체크 포인트
- `360px`, `390px`에서 첫 viewport에 핵심 정보 4종이 모두 보이는지
- horizontal scroll이 없는지
- 선택 전에도 default context가 읽히는지
- sister 선택 후 상세 확인이 같은 세로 흐름 안에서 끝나는지
- `live / snapshot / fallback` 라벨이 첫 화면과 패널에서 같은지

View File

@@ -0,0 +1,44 @@
# HOTFIX-006 Narang Handoff
## repo / branch
- repo: `https://git.nabomhalang.co.kr/hanarang/hanarang-dashboard`
- branch: `feature/hotfix-006-dashboard-copy-live-fidelity`
## 읽을 문서
1. `.plans/hotfix/HOTFIX-006.md`
2. `.plans/design/ui/dashboard-design.md`
## 이번 수정 핵심
자기야 피드백은 명확해.
1. 문구가 너무 길고 쓸데없는 말이 많아
2. 실시간처럼 보이는데 실제론 아닌 부분이 있어
이 두 개를 바로 고쳐.
## 꼭 손볼 것
- 상단 headline / summary
- current focus 설명문
- operator meta
- pipeline node detail / fallback
- infra/meta card detail
- board 카드 body 문구
- `socket live`, `LIVE ON` 같은 라벨의 의미
## 절대 기준
- 설명문 쓰지 마
- UI 자기소개하지 마
- 실시간 아닌 걸 실시간처럼 포장하지 마
- source-of-truth 애매하면 neutral wording으로 낮춰
- 문구는 짧고 건조하게
## 구현 목표
- `ACTIVE PIPELINE`은 진짜 이벤트 기반이면 그렇게 보이고
- 아니면 `SNAPSHOT`, `DOC-DERIVED`, `NO ACTIVE HANDOFF`처럼 정직하게 보여
- `MISTAKE LOG & HARNESS`도 원문/출처/시각 중심으로 짧게 정리
- freshness 메타를 넣어서 stale 여부를 읽을 수 있게 해
## QA 전 체크
- 자기야가 봤을 때 `주구절절하다`는 느낌이 없어야 해
- `실시간인가? 아닌가?`가 헷갈리면 실패야
- build 통과는 기본

142
.plans/hotfix/HOTFIX-006.md Normal file
View File

@@ -0,0 +1,142 @@
# HOTFIX-006: 대시보드 문구 절제 + 실시간성 정합성 보정
## 목표
Master Dashboard v3에서 주구절절한 설명형 문구를 운영 대시보드다운 짧은 문장으로 정리하고, `실시간처럼 보이지만 실제로는 폴링/요약/문서 기반인 정보`를 정확한 source-of-truth 기준으로 다시 맞춘다.
## 왜 이걸 고치나
현재 메인 대시보드는 레이아웃은 좋아졌는데 두 가지 문제가 남아 있어.
1. **문구가 길다**
- 상단 Headline / Summary
- OperatorMeta
- pipeline/detail/fallback 문장
- harness/qa 보드 설명
이런 부분이 대시보드보다 설명문처럼 읽혀.
2. **실시간성 표현이 과하다**
- `socket live`는 웹소켓 연결 상태일 뿐, 모든 카드/보드가 실시간 원본 반영이라는 뜻은 아니야.
- `ACTIVE PIPELINE`, `MISTAKE LOG & HARNESS`, 일부 infra/meta는 최근 activity / QA 문서 / polling snapshot을 조합해 만든 값이 섞여 있어.
- 따라서 `실시간 반영`처럼 보이는 문구와 라벨은 정정해야 해.
## 범위
- 대시보드 메인(`/`) 문구 전반 절제
- source-of-truth 명시 정리
- 실시간 / 폴링 / 문서기반 / 추정치 상태 구분
- 필요 시 백엔드 dashboard ops 응답에 freshness/source 메타 추가
- 프론트에서 misleading wording 제거
## 태스크
### TASK-078: 대시보드 카피를 운영형 짧은 문구로 전면 정리
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `frontend/app/page.tsx`
- `frontend/components/dashboard/ActivePipeline.tsx`
- **설명:**
- 문장형 설명을 줄이고 짧은 운영 문구로 교체
- 섹션 제목/보조 문구/fallback/empty state를 모두 다시 본다
- **문구 기준:**
- 길게 설명하지 말 것
- 1문장보다 라벨형/상태형 표현 우선
- `~읽히게 만들었어`, `~정리했어` 같은 메타 설명 금지
- **완료 기준:**
- 첫 화면 문구가 대시보드 UI 문장처럼 짧고 건조함
- 자기소개/설계 설명 문장이 제거됨
### TASK-079: source-of-truth 기준표 정리
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `backend/src/dashboard/dashboard.service.ts`
- 필요 시 dashboard DTO/타입 정의
- `.plans/design/ui/dashboard-design.md`
- **설명:** 각 섹션 값이 어디서 왔는지 명확히 구분한다.
- **최소 구분:**
- runtime live
- websocket event mirrored
- polling snapshot
- repo/qa doc derived
- fallback/empty
- **완료 기준:**
- 주요 카드/보드/파이프라인 값에 원본 기준을 설명할 수 있음
- 합성값을 실시간 원본처럼 표시하지 않음
### TASK-080: `LIVE` 표현 정합성 보정
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `frontend/app/page.tsx`
- `frontend/lib/useSocket.ts`
- **설명:**
- 현재 `socket live`는 websocket 연결 상태만 뜻하므로 표현을 더 정확히 바꾼다.
- 예: `SOCKET ON`, `EVENT STREAM ON`, `SNAPSHOT`, `STALE`, `SYNCED 12s AGO` 같은 운영형 라벨로 정리
- **완료 기준:**
- websocket 연결 여부와 데이터 최신성이 혼동되지 않음
- LIVE ON/OFF 하나만 보고 전체가 실시간이라고 오해되지 않음
### TASK-081: `ACTIVE PIPELINE` 실데이터/추정치 경계 보정
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `backend/src/dashboard/dashboard.service.ts`
- `frontend/components/dashboard/ActivePipeline.tsx`
- **설명:**
- 노드 상태/active task/focus가 최근 activity 기반 추론이면 그 사실을 숨기지 말 것
- 명시적 handoff/event가 없으면 억지 문장 대신 짧은 neutral fallback 사용
- **완료 기준:**
- `ACTIVE PIPELINE`이 추정치를 확정 사실처럼 말하지 않음
- 이벤트 없음/불충분 상태가 자연스럽게 보임
### TASK-082: `MISTAKE LOG & HARNESS` / 보드 카드 원문성 보강
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `backend/src/dashboard/dashboard.service.ts`
- `frontend/app/page.tsx`
- **설명:**
- `관리자 harness 편집 로그에서 직접 가져온 기록이야.` 같은 설명형 body 제거
- 가능하면 원문 제목/원문 요약/출처/시각만 짧게 노출
- **완료 기준:**
- 보드 카드 문구가 덜 소설 같고 더 기록물처럼 읽힘
- source 라벨/시각이 더 명확함
### TASK-083: freshness 메타 추가 및 노출
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `backend/src/dashboard/dashboard.controller.ts`
- `backend/src/dashboard/dashboard.service.ts`
- `frontend/app/page.tsx`
- **설명:** dashboard ops 응답에 최소 freshness 메타를 추가한다.
- **예시:**
- generatedAt
- activityLatestAt
- sistersLatestAt
- qaDocLatestAt
- **완료 기준:**
- UI에서 `last sync`, `activity lag`, `runtime lag` 같은 판단이 가능함
- stale 상태를 눈치채기 쉬움
## 문구 톤 기준 예시
### 금지
- "지금 어디가 움직이고 있는지, 첫 화면에서 바로 읽히게 만들었어."
- "장식보다 handoff 판단이 먼저 읽히게 정리했어."
- "현재 오너 기준은 ... 최근 handoff와 phase를 같이 보고 있어."
- "관리자 harness 편집 로그에서 직접 가져온 기록이야."
### 권장
- `MASTER DASHBOARD`
- `CURRENT FOCUS`
- `SOCKET ON`
- `SNAPSHOT`
- `NO ACTIVE HANDOFF`
- `NO RECENT QA`
- `LAST EVENT 2m AGO`
- `DOC-DERIVED`
## 완료 기준
- 문구가 짧고 운영 대시보드답게 바뀜
- 실시간/폴링/문서유도 값이 구분됨
- misleading `live` 표현이 제거됨
- 자기야가 봤을 때 `실시간 아닌데 실시간처럼 보인다`는 느낌이 사라짐

View File

@@ -0,0 +1,93 @@
# SPRINT-016 Release Preflight
- 검증 대상 repo: `https://git.nabomhalang.co.kr/hanarang/hanarang-dashboard`
- 검증 대상 branch: `main`
- 검증 대상 commit: `a9e1e677b0f129cc2f45e4f2624020d9d4626159` (`feat: merge SPRINT-016 isometric office dashboard`)
- 기준 문서:
- `.plans/sprints/SPRINT-016.md`
- `.plans/design/ui/office-dashboard-design.md`
- `.plans/design/ui/office-chat-design.md`
- `docs/product-specs/openclaw-office-dashboard-prd.md`
- `.plans/deploy/deploy-plan.md`
- 검증자: 하랑
- 검증일시: `2026-04-07 13:55 KST`
- 결과: `✅ PASSED`
- 재검증 필요 여부: `아니야. 다만 배포 직전 운영 env / WS 프록시 확인은 필요해.`
## 1. 이번 문서 보강 이유
이번 `/office` 변경분은 코드 자체 preflight는 통과했는데, 배포 직전 확인 과정에서 아래 두 가지가 배포 게이트로 걸렸어.
1. PM2 backend 실행 경로 문서가 실제 산출물과 달랐어.
2. `/office` 변경에 대한 배포 전 검증 근거 문서가 `.plans/qa/`에 없었어.
그래서 이번 문서는 **다랑이의 별도 브라우저 QA 보고서 대체가 아니라**, 현재 `main` 기준 배포 판단에 필요한 **release preflight 근거**를 남기는 용도야.
## 2. 실행 결과
- [x] `frontend npm run lint` — 성공 (`0 errors`, `20 warnings`, 전부 기존 unused-var 경고)
- [x] `frontend npm run build` — 성공
- [x] `backend npm run build` — 성공
- [x] `backend npm test -- --runInBand` — 성공 (`9 suites`, `26 tests` passed)
- [x] `backend/dist/src/main.js` 실제 산출물 존재 확인
- [x] Next build 결과에 `/office` route 포함 확인
## 3. 확인한 핵심 근거
### 배포 문서/산출물 정합성
- 기존 문서의 backend PM2 경로 `dist/main.js`는 실제 빌드 결과와 달랐어.
- 실제 Nest 진입 파일은 `backend/dist/src/main.js`였고, 배포 문서와 아키텍처 문서를 이 기준으로 수정했어.
### `/office` 변경분 상태
- 오피스 대시보드 관련 파일이 `main`에 반영돼 있어.
- `frontend/app/office/page.tsx`
- `frontend/components/office/OfficeScene.tsx`
- `frontend/components/office/ContextPanel.tsx`
- `frontend/components/office/ChatWorkspace.tsx`
- `frontend/components/office/PipelinePanel.tsx`
- `frontend/components/office/ServerHealthPanel.tsx`
- Next production build 산출물에서 `/office`가 정적 라우트로 생성되는 것까지 확인했어.
### 코드 preflight
- frontend는 lint/build 모두 통과했어.
- backend는 build/test 모두 통과했어.
- 현재 `main` 헤드는 `a9e1e67`로 고정 확인했어.
## 4. 배포 전 운영 체크
이건 코드 blocker는 아니고, 이랑이가 배포 직전에 확인하면 돼.
- Dev 서버 env
- `DATABASE_URL`
- `JWT_SECRET`
- `SSH_KEY_PATH`
- `GITEA_BASE_URL`
- `GITEA_TOKEN`
- `CORS_ORIGINS`
- Frontend env
- `NEXT_PUBLIC_API_URL`
- 필요 시 `NEXT_PUBLIC_WS_URL`
- Nginx websocket 프록시 또는 WS URL 설정
## 5. 최종 판정
- **배포 문서 경로 오류 수정 완료**
- **`/office` 변경분 release preflight 근거 문서화 완료**
- **현재 기준 코드/빌드/테스트 blocker 없음**
## 6. 최종 JSON
```json
{
"type": "release_preflight",
"from": "harang",
"task_id": "SPRINT-016-RELEASE-PREFLIGHT",
"repo": "https://git.nabomhalang.co.kr/hanarang/hanarang-dashboard",
"branch": "main",
"commit": "a9e1e677b0f129cc2f45e4f2624020d9d4626159",
"passed": true,
"errors": [],
"notes": [
"PM2 backend entry corrected to backend/dist/src/main.js",
"frontend lint/build passed",
"backend build/test passed",
"office route present in production build output",
"deploy-time env and websocket proxy checks remain operational checks only"
],
"suggestion": "Safe to proceed with deploy after environment and websocket configuration checks."
}
```

View File

@@ -0,0 +1,547 @@
# 하나랑 대시보드 Rebuild From Scratch Implementation Plan
> **For Hermes:** 이 문서는 하랑이 planner role 산출물이다. 승인 전 구현/배포 금지. 승인 후 나랑이 builder 또는 Codex가 task 단위로 실행하고, 다랑이 reviewer가 spec/code quality를 검증한다.
**Goal:** 기존 하나랑 대시보드를 “자기야가 4자매가 작업하는 과정을 실시간으로 보는 서비스”로 처음부터 다시 설계하고 구현한다. 메인 화면의 핵심은 이랑이/하랑이/나랑이/다랑이가 PLAN → BUILD → REVIEW → DEPLOY 흐름에서 무엇을 하고 있는지 live timeline/board/scene으로 보여주는 것이다.
**Architecture:** 기존 `hanarang-dashboard` repo는 유지하되, 제품/정보구조/UI를 새로 잡는다. Frontend는 Next.js 16 + styled-components를 유지하고, Backend는 NestJS + Prisma/MariaDB + Socket.IO를 유지한다. 메인 서비스는 `4 Sisters Live Workboard`이며, v0는 mock event stream으로 “작업 과정이 보이는 화면”을 먼저 완성한다. v1에서 NestJS Socket.IO event stream과 workflow state API를 붙인다. 기존 코드는 삭제보다 `legacy` 보존/점진 교체를 우선한다.
**Tech Stack:** Next.js 16, React 19, styled-components, NestJS 11, Prisma 7, MariaDB, Socket.IO, Hermes role skills, Proxmox read-only API.
---
## 0. 배경
기존 대시보드는 다음 전제를 갖고 있었다.
- 하랑/나랑/다랑/이랑이 각각 독립 gateway로 상시 동작
- 4자매 서버 상태를 곧 agent 상태로 봄
- OpenClaw/Lobster workflow 흔적이 UI에 남아 있음
- 실시간 office/metaphor와 운영 패널이 섞여 있음
현재 운영 방향은 바뀌었다.
- 자기야의 기본 진입점은 이랑이 하나
- 하랑=planner, 나랑=builder, 다랑=reviewer는 role skill로 호출
- 하랑/나랑/다랑 gateway는 나중에 standby 전환 가능
- Proxmox 서버 상태와 role runnable 상태를 분리해서 봐야 함
- 하네스 엔지니어링 원칙: PLAN → 승인 → 구현 → QA → 배포 게이트
그래서 단순 리팩토링보다 “처음부터 다시 만드는” 수준의 IA/UI 재설계가 맞다.
---
## 1. 제품 방향
### 한 줄 정의
하나랑 대시보드는 자기야가 **4자매가 작업하는 과정을 실시간으로 보는 서비스**다. 단순 관제센터가 아니라, 하랑이의 기획, 나랑이의 구현, 다랑이의 리뷰, 이랑이의 인프라/배포 판단이 어떤 순서로 흘러가는지 메인 화면에서 바로 보여준다.
### 핵심 사용자
- 자기야: 최종 사용자/승인자
- 이랑이: 메인 비서, 오케스트레이터, 인프라 책임자
- 하랑이 role: planner
- 나랑이 role: builder
- 다랑이 role: reviewer
### 새 핵심 은유
기존 “정적인 관제 카드 모음”이 아니라 **4자매 작업실을 실시간으로 보는 화면**이 메인이다.
```text
4 Sisters Live Workboard
├─ Live Work Scene: 지금 누가 어떤 작업 중인지
├─ Workflow Timeline: PLAN → BUILD → REVIEW → DEPLOY 이벤트 흐름
├─ Active Task Focus: 현재 선택된 작업의 상세 상태
├─ Sister Activity Lanes: 하랑/나랑/다랑/이랑 역할별 lane
└─ Infra/Approval Side Panel: 막힌 이유, 승인 필요, 인프라 위험
```
이랑이는 여전히 단일 진입점이지만, 화면의 주인공은 “이랑이 혼자”가 아니라 **4자매가 함께 일하는 과정**이다. 하랑/나랑/다랑이 gateway로 상시 떠 있지 않아도, role execution/event log를 통해 작업 과정이 보여야 한다.
---
## 2. Scope
### 포함 — v0
- 메인 화면을 `4 Sisters Live Workboard`로 설계
- 하랑/나랑/다랑/이랑 activity lane
- PLAN → BUILD → REVIEW → DEPLOY live timeline
- 현재 작업 focus panel
- approval/blocker side panel
- mock event stream으로 실시간처럼 흐르는 UI
- 새 AppShell/Navigation
- 4자매 role status 카드
- Proxmox monitoring link/panel placeholder
- 프로젝트 list placeholder
- mobile-first layout
- mock/static data로 UI 완성
- 기존 route와 충돌하지 않는 방식으로 새 route 구성
### 포함 — v1
- Backend API 계약 연결
- role agent health endpoint 연결
- Proxmox v0 live inventory 연결
- project/workflow API 연결
- Socket.IO live update 일부 적용
### 포함 — v2
- 기존 legacy 화면 정리
- 인증/권한 흐름 재검토
- 실제 action gate UI
- deployment/QA report UI
### 제외 — 당장 하지 않음
- 기존 DB schema 삭제
- 기존 production deploy
- 하랑/나랑/다랑 gateway 중지
- Proxmox write action
- DB migration
- 도메인/Nginx 변경
---
## 3. Product IA
### Primary Navigation
1. **Live** — 4자매 작업 과정 실시간 메인 화면
2. **Harness** — PLAN/Build/Review/Deploy 흐름 상세
3. **Projects** — repo/project/sprint/task
4. **Infra** — Proxmox/server/service health
5. **Agents** — 이랑이 + 하랑/나랑/다랑 role health
6. **Settings** — 토큰/환경/연동 상태. secret 값 표시 금지
### Live 메인 화면
메인 화면은 대시보드의 핵심 서비스다.
상단:
- 현재 active workflow 이름
- live/snapshot/mock/fallback source badge
- 전체 phase: Planning / Building / Reviewing / Waiting Approval / Deploying
- pending approvals / blockers
중앙:
- **4 Sisters Live Workboard**
- 하랑 lane: 요구사항 정리, PLAN 작성, handoff
- 나랑 lane: 구현 task, test/build, diff 생성
- 다랑 lane: spec review, code review, QA 결과
- 이랑 lane: 인프라 확인, 배포 게이트, 위험 차단
- 각 lane에는 현재 상태, 마지막 이벤트, 진행 중 작업, 다음 handoff를 표시한다.
우측:
- Active Task Focus
- 지금 선택한 이벤트/작업 상세
- 관련 파일/plan/QA report 링크
- tool call 또는 verification command 상태
하단:
- Workflow Timeline
- event stream 형태
- PLAN_CREATED, BUILD_STARTED, TEST_PASSED, REVIEW_REQUESTED, QA_FAILED, APPROVAL_NEEDED 같은 이벤트
- Infra/Approval compact panel
### Harness 화면
Live 화면보다 상세한 작업 단위 board다.
- workflow list
- stage별 task cards
- approval gates
- QA report links
- build/test logs
### Agents 화면
agent 상태를 4축으로 표시한다.
| 항목 | 의미 |
|---|---|
| role | erang-main, harang-planner, narang-builder, darang-reviewer |
| mode | main, role-skill, profile, gateway |
| runnable | 현재 호출 가능한지 |
| gateway | active, standby, failed, unknown |
| server | LXC running 여부 |
### Infra 화면
처음엔 Proxmox monitoring PLAN과 연결한다.
- `/infra/proxmox`
- live-only v0
- DB 없음
- write action 없음
---
## 4. Design Principles
1. **운영 판단이 먼저**
- 예쁜 오피스보다 “지금 위험한가?”를 먼저 보여준다.
2. **상태의 출처를 숨기지 않음**
- live / snapshot / mock / fallback 구분.
3. **상시 gateway와 role runnable을 분리**
- gateway standby는 장애가 아니다.
4. **모바일 우선**
- 자기야 iPhone에서 빠르게 봐야 함.
5. **과한 애니메이션 금지**
- 상태 파악 방해 금지.
6. **하네스 원칙 내장**
- PLAN 승인 없이는 Build가 시작되지 않는 UI.
---
## 5. Repo Strategy
### 기본 전략
기존 repo 유지:
```text
/home/erang/hanarang-dashboard
```
새 구현은 기존 route를 바로 갈아엎지 않고, feature branch에서 새 구조를 만든다.
추천 branch:
```bash
git checkout -b feature/rebuild-control-center
```
### 파일 구조 제안
Frontend:
```text
frontend/app/(control)/page.tsx
frontend/app/(control)/harness/page.tsx
frontend/app/(control)/projects/page.tsx
frontend/app/(control)/infra/page.tsx
frontend/app/(control)/infra/proxmox/page.tsx
frontend/app/(control)/agents/page.tsx
frontend/app/(control)/settings/page.tsx
frontend/components/control/AppFrame.tsx
frontend/components/control/TopStatusBar.tsx
frontend/components/control/NavigationRail.tsx
frontend/components/control/StatusCard.tsx
frontend/components/control/SourceBadge.tsx
frontend/components/harness/HarnessBoard.tsx
frontend/components/harness/PipelineStageCard.tsx
frontend/components/harness/ApprovalQueue.tsx
frontend/components/agents/AgentRoleCard.tsx
frontend/components/agents/AgentRoleMap.tsx
frontend/components/infra/InfraSummaryPanel.tsx
frontend/components/infra/ProxmoxSummaryCard.tsx
frontend/lib/control/mock-data.ts
frontend/lib/control/types.ts
frontend/lib/control/api.ts
```
Backend v0/v1:
```text
backend/src/infra/agents/agent-role-health.controller.ts
backend/src/infra/agents/agent-role-health.service.ts
backend/src/infra/proxmox/*
backend/src/control/control.controller.ts
backend/src/control/control.service.ts
```
---
## 6. Tasks
### Task 1: 현재 구조 조사
**Objective:** 새 대시보드를 얹을 수 있는 실제 route/component/API 구조를 확인한다.
**Files:**
- Read: `frontend/app/**`
- Read: `frontend/components/**`
- Read: `frontend/AGENTS.md`
- Read: `backend/src/app.module.ts`
- Read: `backend/src/dashboard/**`
- Read: `backend/src/events/**`
**Commands:**
```bash
cd /home/erang/hanarang-dashboard
find frontend/app -maxdepth 4 -type f | sort
find frontend/components -maxdepth 3 -type f | sort
find backend/src -maxdepth 3 -type f | sort
```
**Verification:**
- Next.js route 구조 확인
- styled-components 사용 패턴 확인
- 기존 API/gateway 패턴 확인
---
### Task 2: 새 제품 스펙 작성
**Objective:** 기존 PRD를 새 운영 구조에 맞게 대체한다.
**Files:**
- Create: `.plans/rebuild-from-scratch/product-spec.md`
- Modify: `docs/product-specs/openclaw-office-dashboard-prd.md` 또는 새 파일 생성
**Acceptance criteria:**
- 이랑이 단일 진입점 명시
- 하랑/나랑/다랑 role agent 모델 명시
- gateway standby != down 명시
- Proxmox monitoring 연결 명시
**Verification:**
- 다랑이 review에서 scope ambiguity 없음
---
### Task 3: Design system 초안
**Objective:** 새 dashboard의 UI 토큰과 컴포넌트 원칙을 정한다.
**Files:**
- Create: `.plans/rebuild-from-scratch/design-system.md`
- Create: `frontend/components/control/README.md`
**Design tokens:**
- background: dark infra control center
- status colors: ok/warning/critical/standby/unknown
- density: desktop 3-column, mobile 1-column
- source badges: live/snapshot/mock/fallback
**Verification:**
- 모든 상태가 색상만이 아니라 text label도 가짐
---
### Task 4: Frontend live workboard skeleton
**Objective:** mock event stream만으로 4자매가 작업하는 과정이 메인 화면에서 실시간처럼 보이게 만든다.
**Files:**
- Create: `frontend/app/(control)/page.tsx`
- Create: `frontend/components/control/AppFrame.tsx`
- Create: `frontend/components/control/TopStatusBar.tsx`
- Create: `frontend/components/control/NavigationRail.tsx`
- Create: `frontend/components/live/LiveWorkboard.tsx`
- Create: `frontend/components/live/SisterActivityLane.tsx`
- Create: `frontend/components/live/WorkflowTimeline.tsx`
- Create: `frontend/components/live/ActiveTaskFocus.tsx`
- Create: `frontend/lib/control/types.ts`
- Create: `frontend/lib/control/mock-events.ts`
**Rules:**
- 기존 `frontend/app/page.tsx`를 바로 삭제하지 않는다.
- 새 route가 충돌하면 `/control` 아래에 먼저 만든다.
- mock data는 `source: 'mock'`을 반드시 표시한다.
- 메인 화면의 첫 impression은 “4자매가 일하고 있다”여야 한다. 인프라/프로젝트 카드는 보조 패널로 둔다.
**Verification:**
```bash
cd frontend
npm run lint
npm run build
```
---
### Task 5: Harness detail board UI
**Objective:** 메인 Live Workboard에서 선택한 workflow를 더 자세히 보는 상세 board를 만든다.
**Files:**
- Create: `frontend/components/harness/HarnessBoard.tsx`
- Create: `frontend/components/harness/PipelineStageCard.tsx`
- Create: `frontend/components/harness/ApprovalQueue.tsx`
**Acceptance criteria:**
- PLAN_REQUIRED, BUILDING, REVIEWING, WAITING_APPROVAL, DEPLOY_READY 상태 표시
- 각 단계에 responsible role 표시
- 승인 대기 항목이 명확함
- Live 화면의 event와 같은 workflow id로 연결됨
**Verification:**
- mock pipeline 3개 렌더링
- 모바일 1열 전환
---
### Task 6: Agent role map UI
**Objective:** 이랑이 중심 role agent 상태를 표시한다.
**Files:**
- Create: `frontend/components/agents/AgentRoleMap.tsx`
- Create: `frontend/components/agents/AgentRoleCard.tsx`
**Acceptance criteria:**
- erang-main = active main
- harang-planner/narang-builder/darang-reviewer = role-skill runnable
- gateway active/standby/failed와 runnable 분리
---
### Task 7: Infra summary placeholder
**Objective:** Proxmox monitoring v0와 연결될 홈 요약 영역을 만든다.
**Files:**
- Create: `frontend/components/infra/InfraSummaryPanel.tsx`
- Create: `frontend/components/infra/ProxmoxSummaryCard.tsx`
**Acceptance criteria:**
- live/snapshot/mock source badge
- critical 우선 정렬
- `/infra/proxmox`로 이동 link
---
### Task 8: Backend live workflow summary API
**Objective:** frontend mock event stream을 backend live/snapshot API 계약으로 전환할 수 있게 한다.
**Files:**
- Create: `backend/src/control/control.module.ts`
- Create: `backend/src/control/control.controller.ts`
- Create: `backend/src/control/control.service.ts`
- Create: `backend/src/control/workflow-events.gateway.ts`
- Modify: `backend/src/app.module.ts`
**Endpoints:**
```text
GET /control/summary
GET /control/workflows/active
WS /control/events
```
**Response:**
```ts
type ControlSummary = {
activeWorkflow: WorkflowSummary | null;
sisters: SisterActivityLaneState[];
events: WorkflowEvent[];
infra: InfraSummary;
approvals: ApprovalItem[];
source: 'live' | 'snapshot' | 'mock' | 'fallback';
updatedAt: string;
};
```
**Verification:**
```bash
cd backend
npm test -- control
npm run build
```
---
### Task 9: API client 연결
**Objective:** frontend가 `/control/summary`를 읽고 실패 시 fallback mock을 쓴다.
**Files:**
- Create: `frontend/lib/control/api.ts`
- Modify: `frontend/app/(control)/page.tsx`
**Acceptance criteria:**
- API 실패 시 fallback 표시
- fallback임을 UI에 명확히 표시
- loading/error/empty 상태 있음
---
### Task 10: QA 문서 작성
**Objective:** 다랑이가 검증할 QA checklist를 만든다.
**Files:**
- Create: `.plans/rebuild-from-scratch/qa-checklist.md`
**Checks:**
- iPhone viewport
- source badge 정확성
- gateway standby != down
- mock/fallback 구분
- PLAN approval gate 표시
- build/lint pass
---
## 7. Approval Gates
### Gate A — Rebuild plan approval
지금 단계. 자기야가 이 PLAN을 승인해야 구현 시작 가능.
### Gate B — Frontend v0 implementation
허용:
- frontend route/component 추가
- mock/static data
- no DB migration
- no deploy
### Gate C — Backend API v0
허용:
- read-only summary endpoint
- mock/fallback service
- no DB migration
### Gate D — Proxmox integration
별도 Proxmox monitoring PLAN과 연결.
### Gate E — Deploy
L3. 별도 승인 필요.
---
## 8. Rollback Plan
- feature branch에서 작업한다.
- 기존 `main`과 production route는 건드리지 않는다.
- 새 route가 문제면 branch 폐기 또는 route 제거.
- 배포 전까지 기존 사이트 영향 없음.
---
## 9. Open Questions
1. 이름을 계속 `하나랑 대시보드`로 둘지, `하나랑 Control Center`로 바꿀지
2. 첫 화면을 `/`로 교체할지, `/control`에서 먼저 검증할지
3. 기존 오피스/등축 UI를 완전히 버릴지, 나중에 `Agents` 화면의 보조 시각화로 남길지
4. 로그인/권한을 유지할지, 자기야 개인망 전용으로 단순화할지
## 10. 이랑이 추천
- 이름: `하나랑 Live Workboard` 또는 `하나랑 Control Center`
- 메인 서비스: 4자매 작업 과정 실시간 화면
- 구현 시작 route: `/control` 또는 `/live`
- 기존 `/`는 당장 유지
- v0는 mock event stream으로 “작업 과정이 보이는 화면”부터 완성
- 이후 backend `/control/summary`, `/control/events` 연결
- 마지막에 `/`를 새 live 화면으로 교체
이 방식이면 자기야가 원하는 “4자매가 일하는 걸 실시간으로 보는 메인 서비스”를 먼저 만들고, 인프라/프로젝트 관제는 그 옆에 붙일 수 있어.

View File

@@ -0,0 +1,57 @@
# Narang Builder Report — Live Workboard v0
## Scope Executed
- Plan: `.plans/rebuild-from-scratch/PLAN.md`
- Task: Frontend live workboard skeleton
- Scope: mock event stream 기반 4자매 작업 과정 메인 화면 구현
## Files Changed
- `frontend/app/page.tsx`
- 기존 사무실 메인 화면을 Live Workboard 메인 화면으로 교체
- `frontend/app/control/page.tsx`
- `/control` route에서도 같은 Live Workboard 확인 가능
- `frontend/components/common/Sidebar.tsx`
- nav에 `Live`, `Control` 항목 추가
- `frontend/components/live/LiveWorkboard.tsx`
- 메인 Live Workboard container
- phase strip, 4자매 lane, active focus, timeline, v0 scope note 구성
- `frontend/components/live/SisterActivityLane.tsx`
- 하랑/나랑/다랑/이랑 activity lane card
- `frontend/components/live/WorkflowTimeline.tsx`
- mock event stream timeline
- `frontend/components/live/ActiveTaskFocus.tsx`
- 선택 이벤트 상세와 approval/risk panel
- `frontend/lib/control/types.ts`
- Live Workboard 타입 정의
- `frontend/lib/control/mock-events.ts`
- v0 mock workflow/sister/event/approval data
## Verification
- `npm run lint -- components/live app/control app/page.tsx lib/control components/common/Sidebar.tsx`: PASS
- `npm run build`: PASS
- `curl -I http://localhost:3004/`: HTTP 200 during dev server smoke test
- Browser accessibility snapshot: `/`에 Live Workboard, 4자매 lane, Workflow Timeline, Active Task Focus 확인
## Known Existing Issues
- `npm run lint` 전체 실행은 기존 파일들의 React 19 lint rule 위반 때문에 FAIL.
- 새로 추가/수정한 Live Workboard 관련 파일만 대상으로 한 lint는 PASS.
- 기존 오류 위치 예시:
- `components/office-room/SisterDetailPanel.tsx`
- `components/rails/FileViewerModal.tsx`
- `components/rails/SubTaskDetailDrawer.tsx`
- `components/rails/TransitionsTimeline.tsx`
## Risks / Notes
- 현재 데이터는 `source: mock`으로 명확히 표시됨.
- 아직 real Socket.IO event stream은 연결하지 않음.
- production deploy는 수행하지 않음.
- DB/Prisma/Nginx/systemd 변경 없음.
## Ready for Darang Review
yes

View File

@@ -0,0 +1,59 @@
# Darang Review Report — Live Workboard v0
## Verdict
PASS WITH IMPORTANT NOTES
## Spec Compliance
- [x] 메인 화면의 핵심을 4자매 작업 과정 실시간 시각화로 변경했다.
- [x] 하랑/나랑/다랑/이랑 activity lane을 구현했다.
- [x] Workflow Timeline을 구현했다.
- [x] Active Task Focus를 구현했다.
- [x] Approval / Risk side panel을 구현했다.
- [x] `source: mock · v0`를 UI에 명확히 표시했다.
- [x] `/` 메인 화면과 `/control` route에서 Live Workboard를 볼 수 있다.
- [x] DB migration, 배포, 인프라 변경 없이 frontend v0 범위만 수행했다.
## Critical Issues
없음.
## Important Issues
1. 전체 `npm run lint`는 기존 legacy 파일 오류 때문에 실패한다.
- 새 파일/수정 파일 대상 lint는 PASS.
- build는 PASS.
2. 브라우저 vision 검증은 인증 상태 차이 때문에 로그인 화면을 보기도 했다.
- accessibility snapshot과 curl smoke에서는 `/` route가 정상 응답하고 Live Workboard 구조가 확인됐다.
- 실제 운영 계정 로그인 후 시각 QA가 한 번 더 필요하다.
## Minor Issues
- `/control``/`가 같은 화면을 보여준다. v1에서 `/control`을 상세 관제 route로 분리할지 결정 필요.
- mock event 자동 회전은 데모용이다. 실제 event stream 연결 시 선택 이벤트 유지 정책을 다시 정해야 한다.
## Verification Checked
- `npm run lint -- components/live app/control app/page.tsx lib/control components/common/Sidebar.tsx`: PASS
- `npm run build`: PASS
- `curl -I http://localhost:3004/`: PASS, HTTP 200
- browser snapshot: PASS, Live Workboard 주요 섹션 확인
## Deployment Risk
Low for local/frontend code.
이유:
- frontend-only 변경
- DB/인프라/배포 없음
- 기존 office 컴포넌트 삭제 없음
- production 반영은 아직 별도 승인 필요
## Required Fixes Before Proceeding
없음.
## Recommended Next Step
v1 전에 먼저 자기야가 화면 방향을 확인한다. 방향이 맞으면 다음 task는 backend event contract (`GET /control/summary`, `WS /control/events`) 설계/구현이다.

View File

@@ -0,0 +1,49 @@
# SPRINT-015 Narang Handoff
## repo / branch
- repo: `https://git.nabomhalang.co.kr/hanarang/hanarang-dashboard`
- branch: `feature/sprint-015-v3-redesign-plan`
## 읽을 문서
1. `.plans/sprints/SPRINT-015.md`
2. `.plans/design/ui/dashboard-design.md`
3. `.plans/design/index.md`
4. 기존 구현 참조가 필요하면 `.plans/sprints/SPRINT-014.md`
## 이번에 해야 하는 일
대시보드 메인(`/`)을 v3 정보 구조로 재설계해.
핵심은 이거야.
- 현행 미니멀 터미널 톤 유지
- 레퍼런스의 정보 구조 적극 채택
- `ACTIVE PIPELINE`을 대표 섹션으로 도입
- 4자매 상태 카드 / Activity Feed / Sprint Metrics / Infra / Mistake Log를 운영 화면답게 재배치
- 장식은 줄이고 실데이터 연결 가능한 구조로 구현
## 절대 기준
- glassmorphism으로 회귀하지 마
- styled-components 체계 유지
- fake mock 느낌 강한 장식 UI로 끝내지 마
- hover 없이도 핵심 정보 읽혀야 해
- 데스크톱 먼저 맞추고 모바일 세로 흐름까지 꼭 정리해
- 기존 페이지 동선 숨기지 마
## 구현 우선순위
1. 상단 Global Status Bar / Hero Summary
2. 4자매 상태 카드 v3
3. `ACTIVE PIPELINE`
4. `ACTIVITY FEED` / `SPRINT METRICS`
5. `INFRASTRUCTURE OVERVIEW` / `MISTAKE LOG & HARNESS`
6. 반응형/빈 상태/오프라인 상태 정리
## 확인 포인트
- 첫 화면 첫 스크롤 안에서 자매 상태 + 현재 파이프라인이 읽혀야 함
- 색은 상태 의미가 있을 때만 강하게 사용
- Activity / Metrics / Infra / Mistake가 각각 따로 노는 패널이 아니라 운영 맥락으로 이어져야 함
- `ACTIVE PIPELINE`은 예쁘기만 한 다이어그램이 아니라 현재 handoff / review loop / escalation을 보여줘야 함
## QA 전 필수
- `npm run build` 통과
- 반응형 확인
- 데이터 없을 때/길 때/오프라인일 때 레이아웃 확인
- 외부 URL 기준으로 실제 읽기 흐름 확인

View File

@@ -0,0 +1,180 @@
# SPRINT-015: Master Dashboard v3 정보 구조 리디자인
## 목표
기존 미니멀 터미널 UI를 유지하면서, 자기야가 제안한 레퍼런스의 강한 정보 구조를 흡수해 메인 대시보드를 `4자매 운영 관제의 대표 화면`으로 재정의한다.
## 핵심 방향
- glassmorphism으로 회귀하지 않음
- 현재 프로덕션의 미니멀 터미널 톤 유지
- 대신 레이아웃/정보 위계/운영 흐름 표현은 새 레퍼런스를 적극 반영
- 장식보다 운영 가독성을 우선
- 데스크톱 우선 설계 후 모바일 세로 흐름까지 함께 정리
## 디자인 원칙
1. **정보 구조 우선**
- 예쁜 카드보다 `지금 무엇이 진행 중인지`가 먼저 읽혀야 함
2. **운영 화면다운 밀도**
- 한 화면에서 자매 상태 / 현재 파이프라인 / 활동 / 지표 / 인프라를 함께 판단 가능해야 함
3. **현행 톤 유지**
- 배경, border, mono 보조 텍스트, 브라켓/터미널 감성은 유지
4. **애니메이션 절제**
- 상태 강조용 pulse/flow만 제한적으로 사용
- 불필요한 glow, 과한 색 번짐, 반복 뱃지는 줄임
5. **실데이터 우선**
- 예시 숫자가 아니라 실제 runtime/task/project/deploy 데이터를 붙일 수 있는 구조로 설계
## 범위
- 메인 대시보드(`/`) 레이아웃 v3 개편
- 상단 global status bar 재설계
- 4자매 상태 카드 재배치/요약 정보 재정의
- `ACTIVE PIPELINE` 섹션 신설
- `ACTIVITY FEED` / `SPRINT METRICS` 병렬 구조 재정렬
- `INFRASTRUCTURE OVERVIEW` / `MISTAKE LOG & HARNESS` 하단 운영 영역 재구성
- 기존 프로젝트/활동/자매/관리 페이지와 연결되는 진입 동선 재정리
## 제외 범위
- 이번 Sprint에서 새 도메인 기능 추가는 하지 않음
- 백엔드 데이터 모델을 대규모로 갈아엎지 않음
- 기존 페이지 전체를 동시 리디자인하지 않음
- chart 라이브러리 교체는 필요할 때만 제한적으로 수행
## 태스크
### TASK-070: 대시보드 v3 IA 확정 및 섹션 맵 정리
- **담당:** 하랑이 → 나랑이
- **상태:** pending
- **설명:** 레퍼런스를 현행 제품에 맞게 번역한 섹션 구조/우선순위를 확정한다.
- **산출물:**
- `.plans/design/ui/dashboard-design.md` 갱신
- 섹션별 데이터 소스 매핑 표
- **완료 기준:**
- 상단바 / 자매 카드 / Active Pipeline / Activity Feed / Metrics / Infra / Mistake Log의 역할이 문서로 명확함
### TASK-071: 상단 Global Status Bar + Hero Summary 개편
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `frontend/app/page.tsx`
- `frontend/components/**` 내 dashboard 공통 헤더/요약 관련 컴포넌트
- **설명:**
- 좌측 브랜드/페이지 아이덴티티
- 중앙 sprint/day 또는 현재 운영 focus
- 우측 연결 상태/알림/관리자 프로필 요약
구조를 재정의한다.
- **완료 기준:**
- 첫 화면 상단에서 현재 스프린트/연결 상태를 즉시 읽을 수 있음
- 모바일에서 세로 스택 또는 2단 구조로 무너지지 않음
### TASK-072: 4자매 상태 카드 v3 재설계
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `frontend/app/page.tsx`
- `frontend/components/sisters/**` 또는 대시보드 상태 카드 컴포넌트
- **설명:** 각 자매 카드에 아래 정보를 안정적으로 담는다.
- 이름 / 역할
- 현재 상태 (`IDLE`, `WORKING`, `REVIEWING`, `OFFLINE` 등)
- CPU / RAM 또는 대응 운영 지표
- 현재 작업 한 줄 요약
- **완료 기준:**
- 카드 4개가 한 세트로 읽힘
- 색상/강조는 자매별 역할과 상태를 동시에 표현함
- 아바타/아이콘/텍스트 길이 차이로 카드 높이가 깨지지 않음
### TASK-073: `ACTIVE PIPELINE` 시각화 도입
- **담당:** 나랑이
- **상태:** pending
- **의존성:** TASK-070
- **주요 파일:**
- `frontend/app/page.tsx`
- 새 공통 컴포넌트 생성 가능 (`frontend/components/dashboard/ActivePipeline.tsx` 등)
- **설명:**
- User → Harang → Narang → Darang → Irang 흐름을 운영 그래프로 표현
- maker-checker loop, escalation 조건, 현재 active task를 읽을 수 있게 구성
- **구현 메모:**
- SVG/HTML 혼합 구현 허용
- 애니메이션은 실제 active state가 있을 때만 제한적으로 사용
- 정적인 장식보다 상태 전달이 우선
- **완료 기준:**
- 현재 누가 받고/처리하고/검토 중인지 한눈에 보임
- 3회 실패 escalation 같은 운영 규칙이 과하지 않게 드러남
### TASK-074: `ACTIVITY FEED` / `SPRINT METRICS` 병렬 재배치
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `frontend/app/page.tsx`
- 기존 activity/task/metrics 컴포넌트
- **설명:** 활동 피드와 지표를 같은 행에서 비교하는 운영 레이아웃으로 정렬한다.
- **완료 기준:**
- 활동 피드는 이벤트 타입/주체/대상 task를 읽기 쉬움
- metrics는 total tasks, 완료율, 반복 횟수, first-pass rate, escalation 수를 빠르게 읽을 수 있음
- mock처럼 보이지 않도록 실제 데이터 연결 포인트가 드러남
### TASK-075: `INFRASTRUCTURE OVERVIEW` / `MISTAKE LOG & HARNESS` 하단 운영 영역 구성
- **담당:** 나랑이
- **상태:** pending
- **설명:** 인프라 상태 맵과 mistake/harness 규칙 영역을 하단 2열 운영 패널로 정리한다.
- **주요 파일:**
- `frontend/app/page.tsx`
- 관련 API 데이터를 읽는 서비스/타입
- **완료 기준:**
- Gateway / sisters infra / deploy access 흐름이 읽힘
- MISTAKE.md/하네스 규칙 로그는 운영 학습 자산처럼 보여야 함
- 모바일에서는 Infra → Mistake Log 순 세로 배치
### TASK-076: 현행 디자인 시스템과 v3 레이아웃 정합화
- **담당:** 나랑이
- **상태:** pending
- **의존성:** TASK-071 ~ TASK-075
- **설명:** 새 레이아웃이 기존 미니멀 터미널 UI와 충돌하지 않게 색/간격/타이포/테두리 규칙을 정리한다.
- **완료 기준:**
- 기존 프로젝트/활동/설정 페이지와 같은 제품군처럼 보임
- Tailwind 레퍼런스의 분위기를 가져오되 styled-components 기반 현행 톤과 충돌하지 않음
### TASK-077: 반응형/실데이터 QA 준비
- **담당:** 나랑이 → 다랑이
- **상태:** pending
- **의존성:** TASK-071 ~ TASK-076
- **설명:** 데스크톱/태블릿/모바일 반응형과 실데이터 연결 상태를 확인하고 QA 요청 준비를 마친다.
- **완료 기준:**
- Desktop / Tablet / Mobile 주요 breakpoints 확인
- 빈 상태 / 긴 텍스트 / offline 상태 / 데이터 없음 상태가 깨지지 않음
- QA 전달 시 스크린샷 또는 확인 포인트 포함
## 데이터 매핑 기준
| 섹션 | 우선 데이터 |
|---|---|
| Global Status Bar | current sprint, connection status, notifications, current operator |
| Sister Cards | runtime status, role, usage metrics, current work summary |
| Active Pipeline | latest handoff, active implementation, active review, escalation count |
| Activity Feed | latest activities/log events/task transitions |
| Sprint Metrics | total tasks, completion, review loops, first-pass rate, escalations |
| Infrastructure Overview | gateway/node/server/process summary |
| Mistake Log & Harness | latest MISTAKE/Harness rules or derived operational lessons |
## UX 규칙
- 정보 순서는 `지금 상태 → 흐름 → 근거 이벤트 → 정량 지표 → 인프라/학습 자산`
- 카드 하나하나보다 섹션 간 관계가 더 중요함
- hover가 없어도 중요한 정보는 보여야 함
- 색은 상태 의미가 있을 때만 강하게 쓴다
- `Working`, `Reviewing`, `Ready for Deploy` 같은 운영 단어는 전체 제품에서 같은 표현을 유지한다
## 구현 제약
- styled-components 구조 유지
- 기존 공통 토큰/색 변수 최대한 재사용
- 새 레이아웃 때문에 기존 페이지 진입 동선이 숨지면 안 됨
- 과한 애니메이션/지속적인 repaint 유발 구현 지양
- fake 숫자 하드코딩으로 끝내지 말고 실데이터 연결 지점을 남길 것
## 검증 기준
- 홈 화면 진입 시 `하나랑 대시보드가 무엇을 운영하는지` 즉시 이해됨
- 4자매 상태와 현재 파이프라인이 첫 스크롤 안에서 읽힘
- 활동/지표/인프라/학습 로그가 운영자 관점에서 자연스럽게 이어짐
- 데스크톱/모바일 모두 정보 손실 없이 읽힘
- 현행 미니멀 터미널 UI와 충돌하지 않음
## 참고
- 레퍼런스는 `정보 구조`를 강하게 채택
- 비주얼은 현재 제품 톤을 유지한 상태로 70%만 차용
- `ACTIVE PIPELINE`은 이번 v3 리디자인의 대표 섹션으로 취급

View File

@@ -0,0 +1,218 @@
# SPRINT-016: 4자매 Isometric Office Dashboard 재기획
## 목표
기존 하나랑 대시보드를 `운영 패널 중심 UI`에서 한 단계 확장해, 4자매 메인 에이전트와 17개 서브에이전트가 실제로 협업하는 흐름을 **2D 등축 투영 오피스**로 시각화하는 차세대 관제 화면으로 재기획한다.
핵심은 이거야.
- 4자매의 고정 좌석과 역할이 한눈에 보여야 해
- 서브에이전트가 어떤 워크플로우 안에서 움직이는지 보여야 해
- 단순 예쁜 씬이 아니라 실시간 상태/협업/채팅/서버 헬스를 같이 판단할 수 있어야 해
- OpenClaw Gateway WebSocket을 기준으로 실제 상태를 반영해야 해
## 참고 레퍼런스
- 참고 프로젝트: `https://github.com/WW-AI-Lab/openclaw-office`
- 채택 포인트:
- 2D 등축 투영 오피스
- 고정 좌석 + 동적 이동
- 상태 애니메이션 / 연결선 / 회의실 은유
- Chat 작업공간과 관리 패널 결합
- 그대로 복제하지 않고, 하나랑 4자매 구조와 Lobster/Discord handoff 흐름에 맞게 번역한다.
## 운영 구조
### 메인 에이전트 (고정 데스크 / 독립 OpenClaw 인스턴스)
- 하랑이 (Planning)
- 나랑이 (Dev)
- 다랑이 (QA)
- 이랑이 (Infra)
### 서브에이전트
- 하랑이: `planner`, `task-tracker`, `prd-writer`
- 나랑이: `worker`, `db-designer`, `test-writer`, `refactorer`
- 다랑이: `reviewer`, `code-reviewer`, `qa-tester`, `security-auditor`, `ux-reviewer`
- 이랑이: `deploy-manager`, `db-manager`, `nginx-manager`, `monitoring`, `dns-manager`
총 21개 에이전트 (main 4 + sub 17)
## 파이프라인 모델
### 자매 내부
- Lobster 워크플로우 기반 순차 실행
- 예:
- `plan-sprint.lobster`
- `implement-sprint.lobster`
- `review-sprint.lobster`
- `deploy-check.lobster`
### 자매 간
- Discord 멘션 기반 자연어 핸드오프
- `자기야 → 하랑이 → 나랑이 → 다랑이 → 이랑이`
- 실패 시 `다랑이 → 나랑이` 되돌림 루프 지원
## 제품 목표
1. 4자매와 서브에이전트 협업 구조를 직관적으로 보여준다
2. OpenClaw Gateway WebSocket 기반 실시간 상태 모니터링을 제공한다
3. 자매 선택 직접 채팅과 운영 관제를 한 제품 안에 통합한다
4. Lobster 워크플로우 / 스프린트 / QA / 배포 흐름을 하나의 모델로 묶는다
5. 서버 헬스와 에이전트 헬스를 같은 맥락에서 본다
## 범위
- 메인 오피스 대시보드 (`/` 또는 신규 workspace landing)
- 에이전트 상태 시각화
- 회의실/협업 연결선/동적 이동 규칙
- 자매 선택 직접 채팅 인터페이스
- 파이프라인 현황 패널
- 서버 상태 패널
- 모바일/태블릿 대응 전략
- 데이터 소스 / WebSocket 이벤트 / 폴링 보정 전략 문서화
## 제외 범위
- 이번 Sprint에서 실제 Gateway 프로토콜을 새로 정의하지 않음
- 3D 전환 안 함
- 음성/영상 통화 기능 없음
- 에이전트 생성/삭제 전체 관리 콘솔을 이번 Sprint 핵심으로 두지 않음
## 정보 구조
### 1. Office Scene
- 4자매 고정 좌석
- 각 자매 주변에 자기 서브에이전트 풀 배치
- 상태에 따라 idle / thinking / tool_calling / speaking / error 시각화
- 회의실 / 작업대 / 대기 구역 / 인프라 구역 구분
### 2. Agent Detail Layer
- 선택한 자매/서브에이전트 상세
- 현재 세션 / 최근 메시지 / tool call / 리소스 지표
- 최근 handoff / 현재 워크플로우 단계
### 3. Chat Workspace
- 자매 선택 direct chat
- 최근 대화 히스토리
- 작업 지시 / 응답 / 툴 호출 상태 확인
### 4. Pipeline Panel
- 현재 Sprint
- active Lobster workflow
- cycle / retry / review loop
- handoff 상태
- deploy gate / approval 상태
### 5. Server Health Panel
- 4자매 서버 헬스
- Dev 서버
- Docker/infra 상태
- heartbeat / websocket / reconnect 상태
## 디자인 원칙
1. **은유는 강하게, 판단은 더 강하게**
- 오피스는 분위기용이 아니라 상태 판단용이야.
2. **실시간 우선, 추정은 정직하게**
- live / snapshot / doc-derived / fallback 구분 유지
3. **고정 좌석 + 동적 이동**
- 메인 자매는 늘 같은 자리에 있어야 함
- 서브에이전트만 워크플로우에 따라 이동/연결
4. **4자매 중심성 유지**
- 21개 전체를 보여도 중심은 언제나 하랑/나랑/다랑/이랑이야
5. **운영 패널과 오피스 뷰 결합**
- 보기 좋은 씬만 있고 운영 판단이 안 되면 실패
## 기술 방향
- Frontend: 기존 Next.js + styled-components 유지
- Backend: 기존 Nest.js + Prisma 유지
- 실시간: OpenClaw Gateway WebSocket 중심
- 보조 동기화: low-frequency polling snapshot 허용
- 렌더링: SVG + CSS animation 또는 canvas-lite 검토 가능
- 상태 저장: 기존 구조 유지하되 office scene 전용 store 계층 검토
## 데이터 소스 기준
| 대상 | 우선 소스 |
|---|---|
| 메인 에이전트 상태 | 4자매 Gateway WebSocket |
| 서브에이전트 상태 | 각 자매 runtime/agent event + workflow 상태 |
| 협업 연결선 | handoff / workflow transition / event stream |
| 채팅 인터페이스 | session/chat API |
| 파이프라인 현황 | Lobster workflow state + activity log |
| 서버 헬스 | admin/system/health 계열 API |
## 태스크
### TASK-091: 제품 PRD 및 IA 재정의
- **담당:** 하랑이
- **상태:** pending
- **산출물:**
- `docs/product-specs/openclaw-office-dashboard-prd.md`
- `.plans/OVERVIEW.md` 갱신
- **완료 기준:**
- 오피스 대시보드 비전/핵심 사용자/핵심 흐름/핵심 화면이 문서화됨
### TASK-092: 오피스 씬 레이아웃 설계
- **담당:** 하랑이 → 나랑이
- **상태:** pending
- **산출물:**
- `.plans/design/ui/office-dashboard-design.md`
- **완료 기준:**
- 4자매 좌석 / 서브에이전트 위치 / 회의실 / 인프라 구역 구조가 정의됨
### TASK-093: 채팅 워크스페이스 설계
- **담당:** 하랑이 → 나랑이
- **상태:** pending
- **산출물:**
- `.plans/design/ui/office-chat-design.md`
- **완료 기준:**
- 자매 선택 direct chat 구조와 패널 관계가 정의됨
### TASK-094: Gateway/WebSocket 실시간 모델 정의
- **담당:** 나랑이
- **상태:** pending
- **주요 범위:**
- 4개 Gateway 연결 전략
- presence / health / workflow / agent event 정리
- reconnect / reconciliation 규칙
- **완료 기준:**
- live / snapshot / fallback 구분이 문서와 코드 양쪽에서 유지됨
### TASK-095: 메인 오피스 씬 구현
- **담당:** 나랑이
- **상태:** pending
- **완료 기준:**
- 4자매 고정 좌석과 서브에이전트 동적 이동이 구현됨
- 상태별 시각 표현이 동작함
### TASK-096: 협업 시각화 + 회의실 이동 구현
- **담당:** 나랑이
- **상태:** pending
- **완료 기준:**
- handoff 연결선
- 회의실 이동 상태
- review/deploy loop 표현이 동작함
### TASK-097: 직접 채팅 인터페이스 구현
- **담당:** 나랑이
- **상태:** pending
- **완료 기준:**
- 자매 선택 direct chat 가능
- 최근 대화/응답/상태가 확인됨
### TASK-098: 서버 헬스 패널 구현
- **담당:** 나랑이
- **상태:** pending
- **완료 기준:**
- 4자매 + Dev + Docker 서버 상태가 함께 보임
### TASK-099: QA / 모바일 / 실브라우저 검증
- **담당:** 다랑이
- **상태:** pending
- **완료 기준:**
- Desktop / Tablet / Mobile 실브라우저 기준 확인
- live/snapshot 구분 검증
- 성능/가독성/blocker 확인
## 권장 구현 순서
1. PRD / IA / 오피스 씬 문서화
2. Gateway 실시간 모델 정리
3. 메인 오피스 씬 구현
4. 연결선 / 회의실 / 채팅 / 패널 구현
5. QA + 모바일 검증
## 완료 기준
- 4자매와 서브에이전트 구조가 오피스 화면에서 한눈에 보임
- 실시간 상태와 파이프라인이 실제 운영 흐름과 맞음
- 채팅/헬스/파이프라인이 오피스 뷰와 분리되지 않고 자연스럽게 이어짐
- 문서, 설계, 구현 기준이 `.plans/`에 정리됨

View File

@@ -0,0 +1,212 @@
# SPRINT-017: `/office` 모바일 화면 전면 개편
## 목표
`/office`를 데스크톱 축소판이 아니라 **모바일 전용 운영 화면**으로 다시 정리해. 이번 Sprint의 성공 기준은 단순 반응형이 아니야. `360px`, `390px` 첫 화면에서 운영자가 바로 읽어야 할 정보가 세로 흐름으로 보이고, direct chat, pipeline, health, context가 모바일 기준으로 다시 배치되어야 해.
## 이번 Sprint의 한 줄 정의
`main`에 이미 있는 `/office` 구현을 기준으로, **새 API 없이** `frontend/app/office/page.tsx``frontend/components/office/*`의 모바일 IA와 상태 표현을 다시 잠근다.
## 배경
현재 `main` 구현은 데스크톱 기준 구조가 먼저 잡혀 있어.
### 현재 구현에서 확인된 문제
1. `frontend/components/office/OfficeScene.tsx`
- `aspect-ratio: 800 / 460` 고정 씬이라 `mobile(<768)`에서 데스크톱 축소판처럼 보인다.
2. `frontend/app/office/page.tsx`
- 헤더 아래에 모바일 전용 summary hero가 없다.
- `ChatArea``520px`, 모바일에서 `460px` 고정 높이라 세로 흐름을 끊는다.
- 핵심 정보가 `OfficeScene`, `ContextPanel`, 하단 패널로 흩어져 첫 viewport 우선순위가 없다.
3. `frontend/components/office/ContextPanel.tsx`
- 선택 전에는 "에이전트를 선택하면 상세 정보가 표시됩니다"만 보여서 첫 진입 정보가 비어 있다.
4. `frontend/components/office/PipelinePanel.tsx`
- `overflow-x: auto``min-width` 카드에 기대고 있어 모바일에서 가로 스크롤이 전제된다.
5. `frontend/components/office/ChatWorkspace.tsx`
- direct chat이 모바일 세로 흐름보다 데스크톱 3열 구조에 가깝다.
- `JWT 없음`, `runtime 확인 중`, `empty`, `전송 실패`가 모바일에서 즉시 읽히는 구조가 아니다.
## 참고 문서
- 실행 개요: `.plans/OVERVIEW.md`
- 이전 Sprint: `.plans/sprints/SPRINT-016.md`
- 오피스 모바일 IA: `.plans/design/ui/office-dashboard-design.md`
- 오피스 direct chat 모바일 기준: `.plans/design/ui/office-chat-design.md`
- API 참고: `.plans/design/api-design.md`
- 제품 PRD: `docs/product-specs/openclaw-office-dashboard-prd.md`
## 기준 구현 경로
- `frontend/app/office/page.tsx`
- `frontend/components/office/OfficeScene.tsx`
- `frontend/components/office/ContextPanel.tsx`
- `frontend/components/office/ChatWorkspace.tsx`
- `frontend/components/office/PipelinePanel.tsx`
- `frontend/components/office/ServerHealthPanel.tsx`
## breakpoint 기준
- **360px:** 최소 지원 모바일 폭, 첫 viewport 가독성 기준
- **390px:** 기본 모바일 기준 폭
- **768px:** tablet 전환 시작점
- **1280px+:** desktop 기존 구조 유지 기준
## Sprint 범위
### 포함
- `mobile(<768)` 전용 상단 summary view-model 정의
- 첫 viewport 정보 우선순위 재설계
- compact sister status 블록 도입
- focus / health / quick action 블록 도입
- 모바일에서 office scene을 compact sister stack 또는 selectable status cards로 대체
- direct chat 모바일 1열 레이아웃 재정의
- pipeline / health 패널의 모바일 카드 흐름 재정의
- `live / snapshot / fallback``loading / empty / error / stale` 표현 통일
- `360 / 390 / 768 / 1280+` QA 기준 작성
### 제외
- 신규 백엔드 API
- WebSocket reconnect 정책 재설계
- 새 도메인 데이터 모델 추가
- 별도 모바일 앱
- 데스크톱 오피스 씬 컨셉 리뉴얼
## mobile first success criteria
### 첫 viewport 필수 정보 (`360px`, `390px`)
첫 화면 안에서 아래가 모두 보여야 해.
1. 4자매 상태 요약
2. current focus
3. health summary
4. quick actions
### 금지 사항
- 가로 스크롤
- 데스크톱 씬 축소판 유지
- 선택 전 빈 상태로 시작하는 context 구조
- 채팅 타임라인/입력창 잘림
### 유지 사항
- `live / snapshot / fallback` 의미 자체는 바꾸지 않는다
- desktop(`1280px+`)에서는 기존 scene + side panel 구조를 기능적으로 유지한다
- 기존 fetch 결과만 재조합하고 새 API는 추가하지 않는다
## 실행 계획
### T1. scope와 mobile IA 잠금
**대상 문서**
- `.plans/OVERVIEW.md`
- `.plans/sprints/SPRINT-017.md`
- `.plans/design/ui/office-dashboard-design.md`
- `.plans/design/ui/office-chat-design.md`
**done when**
- 첫 viewport 필수 정보가 문서에 명시된다
- 금지 사항과 유지 사항이 문서에 명시된다
- 실제 구현 파일 경로가 교차 참조된다
### T2. 모바일 상단 summary view-model 정의
**대상 파일**
- `frontend/app/office/page.tsx`
**작업**
- 기존 sisters / ops / server 데이터를 재조합해 모바일 summary에 필요한 값을 만든다
- 선택 전에도 빈 화면이 아니라 기본 summary 콘텐츠가 먼저 보이게 한다
**done when**
- sister status 집계가 계산된다
- current focus가 상단에서 바로 보인다
- health summary와 quick action 대상이 함께 계산된다
### T3. `/office` 레이아웃을 mobile-first 세로 스택으로 재배치
**대상 파일**
- `frontend/app/office/page.tsx`
**작업**
- 모바일에서는 `summary hero → compact sister status → focus/health/action block → panel sections` 순서로 재구성한다
- desktop(`1280px+`)에서만 기존 scene + context + bottom panels 구조를 유지한다
**done when**
- `360px`, `390px` 첫 viewport에서 핵심 정보 4종이 읽힌다
- 페이지 전체에 가로 스크롤이 없다
- desktop 구조가 기능적으로 유지된다
### T4. scene / context 모바일 대체
**대상 파일**
- `frontend/components/office/OfficeScene.tsx`
- `frontend/components/office/ContextPanel.tsx`
**작업**
- 모바일에서는 `800x460` 씬을 그대로 축소하지 않는다
- compact sister stack 또는 selectable status cards로 바꾼다
- context는 별도 우측 패널이 아니라 인라인 상세, accordion, sheet 중 하나로 흡수한다
**done when**
- 선택 없이도 기본 context가 보인다
- sister 선택과 상세 확인이 세로 흐름 안에서 끝난다
- 모바일에서 scene은 상징이 아니라 정보 전달 수단이 된다
### T5. direct chat 모바일 1열 재정렬
**대상 파일**
- `frontend/components/office/ChatWorkspace.tsx`
**작업**
- 자매 전환, runtime badge, 타임라인, composer, 보조 상태를 한 컬럼 흐름으로 재배치한다
- 고정 높이 의존을 줄인다
- `JWT 없음`, `empty`, `전송 실패`, `runtime 확인 중` 상태를 상단 또는 입력 근처에서 즉시 읽히게 한다
**done when**
- `360px`, `390px`에서 메시지, 입력창, 상태 라벨이 겹치지 않는다
- send disabled 이유가 숨겨지지 않는다
- `user / assistant / tool` 메시지 구분이 유지된다
### T6. pipeline / health 모바일 카드화
**대상 파일**
- `frontend/components/office/PipelinePanel.tsx`
- `frontend/components/office/ServerHealthPanel.tsx`
**작업**
- pipeline은 가로 노드열 대신 세로 단계 카드로 재배치한다
- health는 summary 우선, 상세는 확장 또는 후순위 카드로 정리한다
**done when**
- 모바일에서 가로 스크롤이 없다
- active task, focus, review loop, deploy state가 1~2스크린 안에 파악된다
- online count와 source badge가 유지된다
### T7. 상태 라벨 통일
**대상 파일**
- `frontend/app/office/page.tsx`
- `frontend/components/office/OfficeScene.tsx`
- `frontend/components/office/ChatWorkspace.tsx`
- `frontend/components/office/PipelinePanel.tsx`
- `frontend/components/office/ServerHealthPanel.tsx`
**작업**
- `live / snapshot / fallback` 라벨을 모바일 기준으로 짧게 통일한다
- `loading / empty / error / stale` 표현을 패널 간 같은 톤으로 맞춘다
**done when**
- source 의미가 첫 화면과 각 패널에서 같은 단어로 보인다
- `empty``error`가 다른 문구로 표현된다
- `fallback` 의미가 사라지지 않는다
### T8. breakpoint QA
**산출물**
- `.plans/qa/SPRINT-017-review-1.md` 이상
**작업**
- `360 / 390 / 768 / 1280+` 실브라우저 체크
- 첫 viewport 정보 충족 여부와 horizontal scroll 부재 확인
**done when**
- breakpoint별 결과가 분리 기록된다
- blocker / warning / follow-up이 분리된다
- direct chat, pipeline, health, context 재배치 검증이 남는다
## 완료 기준
- `360px`, `390px` 첫 화면에서 4자매 상태, current focus, health summary, quick actions를 모두 읽을 수 있다
- `mobile(<768)`에서 데스크톱 축소판이 사라진다
- `ContextPanel` 선택 의존 구조가 모바일 기본 흐름 안으로 흡수된다
- `PipelinePanel``ServerHealthPanel`이 가로 스크롤 없이 읽힌다
- `ChatWorkspace`가 모바일 direct chat로 동작하고, `JWT 없음 / empty / error / runtime 확인 중` 상태가 즉시 읽힌다
- `live / snapshot / fallback` 의미가 유지된 채 문구가 통일된다
## 핸드오프 메모
- 하랑이는 scope와 우선순위를 잠근다
- 나랑이는 `page.tsx``office/*` 모바일 IA를 구현한다
- 다랑이는 `360 / 390 / 768 / 1280+` 기준으로 실브라우저 QA를 남긴다
- 이번 Sprint는 "안정화 전체"가 아니라 **모바일 운영 화면 재구성**까지로 좁게 끝낸다

View File

@@ -0,0 +1 @@
1 1775809467

View File

@@ -12,6 +12,7 @@
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1",
"@nestjs/event-emitter": "^3.0.1",
"@nestjs/jwt": "^11.0.2",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.0.1",
@@ -2294,6 +2295,19 @@
}
}
},
"node_modules/@nestjs/event-emitter": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@nestjs/event-emitter/-/event-emitter-3.0.1.tgz",
"integrity": "sha512-0Ln/x+7xkU6AJFOcQI9tIhUMXVF7D5itiaQGOyJbXtlAfAIt8gzDdJm+Im7cFzKoWkiW5nCXCPh6GSvdQd/3Dw==",
"license": "MIT",
"dependencies": {
"eventemitter2": "6.4.9"
},
"peerDependencies": {
"@nestjs/common": "^10.0.0 || ^11.0.0",
"@nestjs/core": "^10.0.0 || ^11.0.0"
}
},
"node_modules/@nestjs/jwt": {
"version": "11.0.2",
"resolved": "https://registry.npmjs.org/@nestjs/jwt/-/jwt-11.0.2.tgz",
@@ -6204,6 +6218,12 @@
"node": ">= 0.6"
}
},
"node_modules/eventemitter2": {
"version": "6.4.9",
"resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-6.4.9.tgz",
"integrity": "sha512-JEPTiaOt9f04oa6NOkc4aH+nVp5I3wEjpHbIPqfgCdD5v5bUzy7xQqwcVO2aDQgOWhI28da57HksMrzK9HlRxg==",
"license": "MIT"
},
"node_modules/events": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",

View File

@@ -6,6 +6,9 @@
"private": true,
"license": "UNLICENSED",
"scripts": {
"prisma:generate": "prisma generate",
"prebuild": "npm run prisma:generate",
"pretest": "npm run prisma:generate",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
@@ -24,6 +27,7 @@
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1",
"@nestjs/event-emitter": "^3.0.1",
"@nestjs/jwt": "^11.0.2",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.0.1",

7705
backend/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -6,10 +6,7 @@ export class ActivityController {
constructor(private readonly activityService: ActivityService) {}
@Get('activity')
getFeed(
@Query('limit') limit?: string,
@Query('offset') offset?: string,
) {
getFeed(@Query('limit') limit?: string, @Query('offset') offset?: string) {
return this.activityService.getFeed(
limit ? parseInt(limit, 10) : 50,
offset ? parseInt(offset, 10) : 0,

View File

@@ -2,10 +2,9 @@ import { Module } from '@nestjs/common';
import { ActivityController } from './activity.controller';
import { ActivityService } from './activity.service';
import { PrismaModule } from '../prisma/prisma.module';
import { EventsModule } from '../events/events.module';
@Module({
imports: [PrismaModule, EventsModule],
imports: [PrismaModule],
controllers: [ActivityController],
providers: [ActivityService],
exports: [ActivityService],

View File

@@ -1,4 +1,5 @@
import { Test, TestingModule } from '@nestjs/testing';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { ActivityService } from './activity.service';
import { PrismaService } from '../prisma/prisma.service';
@@ -7,7 +8,9 @@ describe('ActivityService', () => {
const mockPrisma = {
activityLog: {
create: jest.fn().mockResolvedValue({ id: 1, action: 'test', createdAt: new Date() }),
create: jest
.fn()
.mockResolvedValue({ id: 1, action: 'test', createdAt: new Date() }),
findMany: jest.fn().mockResolvedValue([]),
count: jest.fn().mockResolvedValue(0),
},
@@ -18,6 +21,7 @@ describe('ActivityService', () => {
providers: [
ActivityService,
{ provide: PrismaService, useValue: mockPrisma },
EventEmitter2,
],
}).compile();

View File

@@ -1,6 +1,6 @@
import { Injectable, Optional } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { PrismaService } from '../prisma/prisma.service';
import { EventsGateway } from '../events/events.gateway';
export interface LogActivityDto {
sisterId?: number;
@@ -15,7 +15,11 @@ function sanitizeActivityDetail(detail?: string | null): string | undefined {
const raw = detail.trim();
// 내부 stderr/명령문 직접 노출 금지
if (/stderr:/i.test(raw) || /command not found/i.test(raw) || /bash:\s*line/i.test(raw)) {
if (
/stderr:/i.test(raw) ||
/command not found/i.test(raw) ||
/bash:\s*line/i.test(raw)
) {
return '내부 작업 중 오류가 발생했어. 자세한 시스템 로그는 관리자 로그에서 확인할 수 있어.';
}
@@ -30,7 +34,7 @@ function sanitizeActivityDetail(detail?: string | null): string | undefined {
export class ActivityService {
constructor(
private readonly prisma: PrismaService,
@Optional() private readonly events?: EventsGateway,
private readonly eventEmitter: EventEmitter2,
) {}
async log(dto: LogActivityDto) {
@@ -45,9 +49,7 @@ export class ActivityService {
},
});
if (this.events) {
this.events.broadcastActivity(record);
}
this.eventEmitter.emit('activity.logged', record);
return record;
}
@@ -66,7 +68,10 @@ export class ActivityService {
this.prisma.activityLog.count(),
]);
return {
items: items.map((item) => ({ ...item, detail: sanitizeActivityDetail(item.detail) })),
items: items.map((item) => ({
...item,
detail: sanitizeActivityDetail(item.detail),
})),
total,
limit,
offset,
@@ -87,7 +92,10 @@ export class ActivityService {
this.prisma.activityLog.count({ where: { projectId } }),
]);
return {
items: items.map((item) => ({ ...item, detail: sanitizeActivityDetail(item.detail) })),
items: items.map((item) => ({
...item,
detail: sanitizeActivityDetail(item.detail),
})),
total,
limit,
offset,

View File

@@ -10,9 +10,16 @@ describe('AdminService', () => {
let service: AdminService;
const mockSister = {
id: 2, name: 'narang', ip: '10.10.10.216', user: 'narang',
lxcId: 105, status: 'online', lastSeen: new Date(),
sshKeyPath: null, createdAt: new Date(), updatedAt: new Date(),
id: 2,
name: 'narang',
ip: '10.10.10.216',
user: 'narang',
lxcId: 105,
status: 'online',
lastSeen: new Date(),
sshKeyPath: null,
createdAt: new Date(),
updatedAt: new Date(),
};
const mockPrisma = {
@@ -30,7 +37,9 @@ describe('AdminService', () => {
{ provide: ActivityService, useValue: mockActivity },
{
provide: ConfigService,
useValue: { get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa') },
useValue: {
get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa'),
},
},
],
}).compile();
@@ -41,7 +50,11 @@ describe('AdminService', () => {
});
it('restartSister: SSH 성공 시 success=true', async () => {
mockSsh.executeCommand.mockResolvedValue({ stdout: 'RESTART_OK', stderr: '', code: 0 });
mockSsh.executeCommand.mockResolvedValue({
stdout: 'RESTART_OK',
stderr: '',
code: 0,
});
const result = await service.restartSister('narang');

View File

@@ -5,7 +5,13 @@ import { SshService } from '../sisters/ssh.service';
import { ActivityService } from '../activity/activity.service';
import { SisterName } from '../common/sister-name.pipe';
const ALLOWED_HARNESS_FILES = ['AGENTS.md', 'SOUL.md', 'PROTOCOL.md', 'TOOLS.md', 'HEARTBEAT.md'] as const;
const ALLOWED_HARNESS_FILES = [
'AGENTS.md',
'SOUL.md',
'PROTOCOL.md',
'TOOLS.md',
'HEARTBEAT.md',
] as const;
type HarnessFile = (typeof ALLOWED_HARNESS_FILES)[number];
@Injectable()
@@ -36,7 +42,9 @@ export class AdminService {
await this.activity.log({
sisterId: sister.id,
action: 'gateway_restart',
detail: success ? 'Gateway restart successful' : `stderr: ${result.stderr}`,
detail: success
? 'Gateway restart successful'
: `stderr: ${result.stderr}`,
});
return { success, output: result.stdout, error: result.stderr || null };
@@ -68,7 +76,9 @@ export class AdminService {
await this.activity.log({
sisterId: sister.id,
action: 'session_reset',
detail: success ? 'Session reset successful' : `stderr: ${result.stderr}`,
detail: success
? 'Session reset successful'
: `stderr: ${result.stderr}`,
});
return { success, output: result.stdout, error: result.stderr || null };
@@ -102,7 +112,7 @@ export class AdminService {
const keyPath = this.getKeyPath();
// 내용에서 위험한 셸 escape + null byte 방지
const escaped = content.replace(/\x00/g, '').replace(/'/g, "'\\''");
const escaped = content.split('\0').join('').replace(/'/g, "'\\''");
try {
const result = await this.ssh.executeCommand(
@@ -162,7 +172,9 @@ export class AdminService {
}
private async getSister(name: SisterName) {
const sister = await this.prisma.sisterConfig.findUnique({ where: { name } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name },
});
if (!sister) throw new Error(`Sister ${name} not found`);
return sister;
}

View File

@@ -1,5 +1,6 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { ThrottlerModule } from '@nestjs/throttler';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@@ -17,10 +18,13 @@ import { EventsModule } from './events/events.module';
import { CostsModule } from './costs/costs.module';
import { GiteaSyncModule } from './gitea-sync/gitea-sync.module';
import { SettingsModule } from './settings/settings.module';
import { DashboardModule } from './dashboard/dashboard.module';
import { RailsModule } from './rails/rails.module';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
EventEmitterModule.forRoot(),
ThrottlerModule.forRoot([{ ttl: 60000, limit: 100 }]),
PrismaModule,
SistersModule,
@@ -36,6 +40,8 @@ import { SettingsModule } from './settings/settings.module';
CostsModule,
GiteaSyncModule,
SettingsModule,
DashboardModule,
RailsModule,
],
controllers: [AppController],
providers: [AppService],

View File

@@ -0,0 +1,128 @@
import { randomBytes, timingSafeEqual } from 'crypto';
import type { CookieOptions, Request, Response } from 'express';
export const ACCESS_TOKEN_COOKIE = 'hanarang_access_token';
export const REFRESH_TOKEN_COOKIE = 'hanarang_refresh_token';
export const CSRF_TOKEN_COOKIE = 'hanarang_csrf_token';
const ACCESS_TOKEN_MAX_AGE_MS = 15 * 60 * 1000;
const REFRESH_TOKEN_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
function isHttpsRequest(req?: Request): boolean {
const forwardedProto = req?.headers['x-forwarded-proto'];
const protocol = Array.isArray(forwardedProto)
? forwardedProto[0]
: forwardedProto;
return (
process.env.NODE_ENV === 'production' ||
req?.secure === true ||
protocol === 'https'
);
}
function baseCookieOptions(req?: Request): CookieOptions {
return {
path: '/',
secure: isHttpsRequest(req),
};
}
export function parseCookieHeader(
header?: string | string[],
): Record<string, string> {
const raw = Array.isArray(header) ? header.join(';') : header;
if (!raw) return {};
return raw
.split(';')
.map((part) => part.trim())
.filter((part) => part.length > 0)
.reduce<Record<string, string>>((cookies, part) => {
const eqIndex = part.indexOf('=');
if (eqIndex === -1) return cookies;
const key = decodeURIComponent(part.slice(0, eqIndex).trim());
const value = decodeURIComponent(part.slice(eqIndex + 1).trim());
cookies[key] = value;
return cookies;
}, {});
}
export function getCookieValue(
req: Pick<Request, 'headers'>,
name: string,
): string | undefined {
return parseCookieHeader(req.headers.cookie)[name];
}
export function generateCsrfToken(): string {
return randomBytes(32).toString('hex');
}
export function hasValidCsrfToken(req: Request): boolean {
const cookieToken = getCookieValue(req, CSRF_TOKEN_COOKIE);
const headerToken = req.headers['x-csrf-token'];
const requestToken = Array.isArray(headerToken) ? headerToken[0] : headerToken;
if (!cookieToken || !requestToken) return false;
const cookieBuffer = Buffer.from(cookieToken);
const requestBuffer = Buffer.from(requestToken);
if (cookieBuffer.length !== requestBuffer.length) return false;
try {
return timingSafeEqual(cookieBuffer, requestBuffer);
} catch {
return false;
}
}
export function setAuthCookies(
res: Response,
req: Request,
tokens: { accessToken: string; refreshToken: string },
csrfToken = generateCsrfToken(),
) {
res.cookie(ACCESS_TOKEN_COOKIE, tokens.accessToken, {
...baseCookieOptions(req),
httpOnly: true,
sameSite: 'lax',
maxAge: ACCESS_TOKEN_MAX_AGE_MS,
});
res.cookie(REFRESH_TOKEN_COOKIE, tokens.refreshToken, {
...baseCookieOptions(req),
httpOnly: true,
sameSite: 'strict',
maxAge: REFRESH_TOKEN_MAX_AGE_MS,
});
res.cookie(CSRF_TOKEN_COOKIE, csrfToken, {
...baseCookieOptions(req),
httpOnly: false,
sameSite: 'strict',
maxAge: REFRESH_TOKEN_MAX_AGE_MS,
});
return csrfToken;
}
export function clearAuthCookies(res: Response, req?: Request) {
res.clearCookie(ACCESS_TOKEN_COOKIE, {
...baseCookieOptions(req),
httpOnly: true,
sameSite: 'lax',
});
res.clearCookie(REFRESH_TOKEN_COOKIE, {
...baseCookieOptions(req),
httpOnly: true,
sameSite: 'strict',
});
res.clearCookie(CSRF_TOKEN_COOKIE, {
...baseCookieOptions(req),
httpOnly: false,
sameSite: 'strict',
});
}

View File

@@ -1,37 +1,96 @@
import {
Controller,
Post,
Get,
BadRequestException,
Body,
Headers,
Controller,
Get,
HttpCode,
Post,
Req,
Res,
UnauthorizedException,
UseGuards,
Request,
BadRequestException,
} from '@nestjs/common';
import { AuthService, LoginDto } from './auth.service';
import { JwtGuard } from './jwt.guard';
import type {
Request as ExpressRequest,
Response as ExpressResponse,
} from 'express';
import { Throttle, ThrottlerGuard } from '@nestjs/throttler';
import { AuthService, LoginDto } from './auth.service';
import {
getCookieValue,
hasValidCsrfToken,
setAuthCookies,
clearAuthCookies,
REFRESH_TOKEN_COOKIE,
} from './auth-cookies';
import { JwtGuard } from './jwt.guard';
interface AuthenticatedRequest extends ExpressRequest {
user: { userId: number };
}
@Controller('api/auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@HttpCode(200)
@UseGuards(ThrottlerGuard)
@Throttle({ default: { limit: 5, ttl: 60000 } })
@Post('login')
login(@Body() dto: LoginDto) {
return this.authService.login(dto);
async login(
@Body() dto: LoginDto,
@Req() req: ExpressRequest,
@Res({ passthrough: true }) res: ExpressResponse,
) {
const tokens = await this.authService.login(dto);
setAuthCookies(res, req, tokens);
return {
username: tokens.username,
role: tokens.role,
};
}
@HttpCode(200)
@UseGuards(ThrottlerGuard)
@Throttle({ default: { limit: 3, ttl: 60000 } })
@Post('refresh')
refresh(@Headers('x-refresh-token') token: string) {
async refresh(
@Req() req: ExpressRequest,
@Res({ passthrough: true }) res: ExpressResponse,
) {
const cookieToken = getCookieValue(req, REFRESH_TOKEN_COOKIE);
const headerToken = req.headers['x-refresh-token'];
const token = cookieToken ?? (Array.isArray(headerToken) ? headerToken[0] : headerToken);
if (!token) throw new BadRequestException('Refresh token required');
return this.authService.refresh(token);
if (cookieToken && !hasValidCsrfToken(req)) {
throw new UnauthorizedException('Invalid CSRF token');
}
const tokens = await this.authService.refresh(token);
setAuthCookies(res, req, tokens);
return {
username: tokens.username,
role: tokens.role,
};
}
@HttpCode(200)
@Post('logout')
logout(
@Req() req: ExpressRequest,
@Res({ passthrough: true }) res: ExpressResponse,
) {
clearAuthCookies(res, req);
return { ok: true };
}
@UseGuards(JwtGuard)
@Get('me')
getMe(@Request() req: any) {
getMe(@Request() req: AuthenticatedRequest) {
return this.authService.getMe(req.user.userId);
}
}

View File

@@ -6,10 +6,12 @@ import * as bcrypt from 'bcrypt';
import { IsString, IsNotEmpty } from 'class-validator';
export class LoginDto {
@IsString() @IsNotEmpty()
@IsString()
@IsNotEmpty()
username!: string;
@IsString() @IsNotEmpty()
@IsString()
@IsNotEmpty()
password!: string;
}
@@ -22,7 +24,9 @@ export class AuthService {
) {}
async login(dto: LoginDto) {
const user = await this.prisma.user.findUnique({ where: { username: dto.username } });
const user = await this.prisma.user.findUnique({
where: { username: dto.username },
});
if (!user) throw new UnauthorizedException('Invalid credentials');
const ok = await bcrypt.compare(dto.password, user.password);
@@ -33,11 +37,16 @@ export class AuthService {
async refresh(refreshToken: string) {
try {
const payload = this.jwt.verify<{ sub: number; username: string; role: string }>(
refreshToken,
{ secret: this.config.get<string>('JWT_SECRET') + '_refresh' },
);
const user = await this.prisma.user.findUnique({ where: { id: payload.sub } });
const payload = this.jwt.verify<{
sub: number;
username: string;
role: string;
}>(refreshToken, {
secret: this.config.get<string>('JWT_SECRET') + '_refresh',
});
const user = await this.prisma.user.findUnique({
where: { id: payload.sub },
});
if (!user) throw new UnauthorizedException();
return this.signTokens(user.id, user.username, user.role);
} catch {
@@ -60,7 +69,10 @@ export class AuthService {
const payload = { sub: userId, username, role };
const accessToken = this.jwt.sign(payload, { secret, expiresIn: '15m' });
const refreshToken = this.jwt.sign(payload, { secret: secret + '_refresh', expiresIn: '7d' });
const refreshToken = this.jwt.sign(payload, {
secret: secret + '_refresh',
expiresIn: '7d',
});
return { accessToken, refreshToken, username, role };
}

View File

@@ -1,7 +1,9 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import type { Request } from 'express';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ACCESS_TOKEN_COOKIE, getCookieValue } from './auth-cookies';
export interface JwtPayload {
sub: number;
@@ -9,13 +11,21 @@ export interface JwtPayload {
role: string;
}
function cookieTokenExtractor(req?: Request): string | null {
if (!req) return null;
return getCookieValue(req, ACCESS_TOKEN_COOKIE) ?? null;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(config: ConfigService) {
const secret = config.get<string>('JWT_SECRET');
if (!secret) throw new Error('JWT_SECRET not set');
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
jwtFromRequest: ExtractJwt.fromExtractors([
cookieTokenExtractor,
ExtractJwt.fromAuthHeaderAsBearerToken(),
]),
ignoreExpiration: false,
secretOrKey: secret,
});
@@ -23,6 +33,10 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
validate(payload: JwtPayload) {
if (!payload?.sub) throw new UnauthorizedException();
return { userId: payload.sub, username: payload.username, role: payload.role };
return {
userId: payload.sub,
username: payload.username,
role: payload.role,
};
}
}

View File

@@ -1,28 +1,46 @@
import { Injectable, CanActivate, ExecutionContext, ForbiddenException, SetMetadata } from '@nestjs/common';
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
SetMetadata,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request as ExpressRequest } from 'express';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
interface RoleUser {
role: string;
}
interface RequestWithUser extends ExpressRequest {
user?: RoleUser;
}
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles || requiredRoles.length === 0) return true;
const request = context.switchToHttp().getRequest();
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
if (!user) throw new ForbiddenException('Authentication required');
const hasRole = requiredRoles.includes(user.role);
if (!hasRole) throw new ForbiddenException(`Role '${user.role}' not authorized. Required: ${requiredRoles.join(', ')}`);
if (!hasRole)
throw new ForbiddenException(
`Role '${user.role}' not authorized. Required: ${requiredRoles.join(', ')}`,
);
return true;
}

View File

@@ -14,7 +14,9 @@ export class CostsController {
@Get()
getCosts(@Query('period') period?: string) {
const validPeriods: CostPeriod[] = ['day', 'week', 'month'];
const p = validPeriods.includes(period as CostPeriod) ? (period as CostPeriod) : 'week';
const p = validPeriods.includes(period as CostPeriod)
? (period as CostPeriod)
: 'week';
return this.costsService.getCosts(p);
}

View File

@@ -14,8 +14,6 @@ const MODEL_PRICING: Record<string, { input: number; output: number }> = {
default: { input: 3.0, output: 15.0 },
};
const SISTER_NAMES: SisterName[] = ['harang', 'narang', 'darang', 'erang'];
export type CostPeriod = 'day' | 'week' | 'month';
@Injectable()
@@ -38,14 +36,23 @@ export class CostsService {
this.getTimeline(since, period),
]);
return { period, since: since.toISOString(), summary, bySister, byModel, timeline };
return {
period,
since: since.toISOString(),
summary,
bySister,
byModel,
timeline,
};
}
async recordCosts(sisterName: SisterName) {
const keyPath = this.config.get<string>('SSH_KEY_PATH');
if (!keyPath) return;
const sister = await this.prisma.sisterConfig.findUnique({ where: { name: sisterName } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name: sisterName },
});
if (!sister) return;
try {
@@ -99,7 +106,12 @@ export class CostsService {
private async getSummary(since: Date) {
const result = await this.prisma.costLog.aggregate({
where: { recordedAt: { gte: since } },
_sum: { inputTokens: true, outputTokens: true, totalTokens: true, estimatedUsd: true },
_sum: {
inputTokens: true,
outputTokens: true,
totalTokens: true,
estimatedUsd: true,
},
_count: true,
});
@@ -145,14 +157,23 @@ export class CostsService {
}
private async getTimeline(since: Date, period: CostPeriod) {
void period;
const logs = await this.prisma.costLog.findMany({
where: { recordedAt: { gte: since } },
orderBy: { recordedAt: 'asc' },
select: { sisterName: true, totalTokens: true, estimatedUsd: true, recordedAt: true },
select: {
sisterName: true,
totalTokens: true,
estimatedUsd: true,
recordedAt: true,
},
});
// 날짜별 집계
const grouped: Record<string, { date: string; totalTokens: number; estimatedUsd: number }> = {};
const grouped: Record<
string,
{ date: string; totalTokens: number; estimatedUsd: number }
> = {};
for (const log of logs) {
const dateKey = log.recordedAt.toISOString().slice(0, 10);
@@ -172,9 +193,12 @@ export class CostsService {
private getSince(period: CostPeriod): Date {
const now = new Date();
switch (period) {
case 'day': return new Date(now.getTime() - 24 * 60 * 60 * 1000);
case 'week': return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
case 'month': return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
case 'day':
return new Date(now.getTime() - 24 * 60 * 60 * 1000);
case 'week':
return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
case 'month':
return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
}
}
}

View File

@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { DashboardService } from './dashboard.service';
@Controller('api/dashboard')
export class DashboardController {
constructor(private readonly dashboardService: DashboardService) {}
@Get('ops')
getOpsBoard(): Promise<any> {
return this.dashboardService.getOpsBoard();
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { DashboardController } from './dashboard.controller';
import { DashboardService } from './dashboard.service';
import { PrismaModule } from '../prisma/prisma.module';
import { ProjectsModule } from '../projects/projects.module';
import { GiteaModule } from '../gitea/gitea.module';
@Module({
imports: [PrismaModule, ProjectsModule, GiteaModule],
controllers: [DashboardController],
providers: [DashboardService],
exports: [DashboardService],
})
export class DashboardModule {}

View File

@@ -0,0 +1,335 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { ProjectsService } from '../projects/projects.service';
import { GiteaService } from '../gitea/gitea.service';
interface ActivityRecord {
id: number;
action: string;
detail: string | null;
createdAt: Date;
sister: { name: string } | null;
project: { name: string } | null;
}
interface OpsBoardItem {
id: string;
title: string;
body: string;
tone: 'default' | 'warn' | 'ok' | 'active';
author: string;
time: string;
category: string;
source: string;
}
interface FreshnessMeta {
generatedAt: string;
activityLatestAt: string | null;
sistersLatestAt: string | null;
qaDocLatestAt: string | null;
}
const QA_PATH_CANDIDATES = ['.plans/qa/', '.qa/'];
const SISTER_ROLES: Record<string, string> = {
harang: 'Plan & Assign',
narang: 'Implement',
darang: 'Review / QA',
erang: 'Deploy / Infra',
};
function toneFromText(text: string): 'default' | 'warn' | 'ok' | 'active' {
const normalized = text.toLowerCase();
if (/(fail|error|blocker|offline|invalid|drift)/.test(normalized))
return 'warn';
if (/(passed|deploy|merged|restart_ok|write_ok|successful)/.test(normalized))
return 'ok';
if (/(review|qa|handoff|sync|update)/.test(normalized)) return 'active';
return 'default';
}
function nodeStateFromEvidence(params: {
sisterStatus?: string;
activity?: ActivityRecord | null;
name: string;
}): 'idle' | 'active' | 'review' | 'blocked' | 'ready' {
const { sisterStatus, activity, name } = params;
const text =
`${activity?.action ?? ''} ${activity?.detail ?? ''}`.toLowerCase();
if (name !== 'user' && sisterStatus === 'offline') return 'blocked';
if (/(review|qa)/.test(text)) return 'review';
if (
name === 'erang' &&
/(deploy|merged|ready for deploy|deployed)/.test(text)
)
return 'ready';
if (sisterStatus === 'working') return 'active';
if (activity) return 'ready';
return 'idle';
}
function sanitizeSummary(text?: string | null) {
const raw = text?.trim();
if (!raw) return null;
if (/stderr:/i.test(raw) || /command not found/i.test(raw) || /bash:\s*line/i.test(raw)) {
return '내부 작업 중 오류가 발생했어. 자세한 시스템 로그는 관리자 로그에서 확인해.';
}
if (/^ssh failed/i.test(raw) || /ssh connection failed/i.test(raw)) {
return '원격 노드 연결에 실패했어.';
}
return raw;
}
function summarizeActivity(
activity?: ActivityRecord | null,
fallback = 'NO EVENT',
) {
return sanitizeSummary(activity?.detail) || activity?.action?.replace(/_/g, ' ') || fallback;
}
function parseQaSummary(content: string): string {
const lines = content.split(/\r?\n/).map((line) => line.trim());
const taskLine = lines.find((line) => /^###\s+/.test(line));
if (taskLine) return taskLine.replace(/^###\s+/, '').trim();
const bullet = lines.find((line) => /^-\s+/.test(line));
if (bullet) return bullet.replace(/^-\s+/, '').trim();
return (
lines.find((line) => line.length > 0 && !line.startsWith('#')) ?? 'QA note'
);
}
function inferQaAuthor(path: string, content: string): string {
if (/darang/i.test(path) || /다랑/i.test(content)) return '다랑이';
if (/harang/i.test(path) || /하랑/i.test(content)) return '하랑이';
return 'QA Doc';
}
function extractRepoName(repoUrl: string): string {
return repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
}
@Injectable()
export class DashboardService {
constructor(
private readonly prisma: PrismaService,
private readonly projectsService: ProjectsService,
private readonly gitea: GiteaService,
) {}
async getOpsBoard() {
const [projects, sisters, rawActivities] = await Promise.all([
this.projectsService.getProjects(),
this.prisma.sisterConfig.findMany({ orderBy: { id: 'asc' } }),
this.prisma.activityLog.findMany({
orderBy: { createdAt: 'desc' },
take: 40,
include: {
sister: { select: { name: true } },
project: { select: { name: true } },
},
}),
]);
const activities = rawActivities as ActivityRecord[];
const latestProjectActivity =
activities.find((item) => item.project?.name) ?? null;
const latestBySister = new Map<string, ActivityRecord>();
for (const item of activities) {
if (item.sister?.name && !latestBySister.has(item.sister.name)) {
latestBySister.set(item.sister.name, item);
}
}
const focusProject = latestProjectActivity?.project?.name
? (projects.find(
(project) => project.name === latestProjectActivity.project?.name,
) ?? null)
: (projects.find((project) =>
['IMPLEMENT', 'QA', 'READY FOR DEPLOY'].includes(project.phase),
) ?? null);
const reviewLoopCount = activities.filter((item) =>
/(review|qa)/i.test(`${item.action} ${item.detail ?? ''}`),
).length;
const escalationCount = projects.filter(
(project) => (project.blockerCount ?? 0) > 0,
).length;
const nodes = [
{
id: 'user',
label: 'User',
role: 'Request / Approval',
state: nodeStateFromEvidence({
name: 'user',
activity: latestProjectActivity,
}),
detail: latestProjectActivity
? `${latestProjectActivity.project?.name ?? 'project'} · ${summarizeActivity(latestProjectActivity, 'NO EVENT')}`
: 'NO ACTIVE HANDOFF',
},
...sisters.map((sister) => {
const activity = latestBySister.get(sister.name) ?? null;
return {
id: sister.name,
label:
sister.name === 'erang'
? 'Irang'
: `${sister.name.slice(0, 1).toUpperCase()}${sister.name.slice(1)}`,
role: SISTER_ROLES[sister.name] ?? 'Unknown',
state: nodeStateFromEvidence({
name: sister.name,
sisterStatus: sister.status,
activity,
}),
detail: activity
? summarizeActivity(activity)
: sister.status === 'offline'
? 'RUNTIME OFFLINE'
: sister.lastSeen
? 'SNAPSHOT ONLY'
: 'NO EVENT',
};
}),
];
const harnessItems = activities
.filter((item) => item.action === 'harness_updated')
.slice(0, 4)
.map(
(item) =>
({
id: `harness-${item.id}`,
title: item.detail ?? 'HARNESS UPDATED',
body: item.detail ?? 'HARNESS UPDATED',
tone: toneFromText(`${item.action} ${item.detail ?? ''}`),
author: item.sister?.name
? this.toDisplayName(item.sister.name)
: 'System',
time: item.createdAt.toISOString(),
category: 'harness',
source: `activity:${item.action}`,
}) satisfies OpsBoardItem,
);
const qaItems = await this.getLatestQaBoardItems(
projects.map((project) => ({
name: project.name,
repoName: extractRepoName(project.repoUrl),
updatedAt: project.updatedAt,
})),
);
const board = [...harnessItems, ...qaItems]
.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime())
.slice(0, 6);
const freshness: FreshnessMeta = {
generatedAt: new Date().toISOString(),
activityLatestAt: activities[0]?.createdAt?.toISOString() ?? null,
sistersLatestAt:
sisters
.map((sister) => sister.lastSeen)
.filter((value): value is Date => value instanceof Date)
.sort((a, b) => b.getTime() - a.getTime())[0]
?.toISOString() ?? null,
qaDocLatestAt:
board
.filter((item) => item.category === 'DOC-DERIVED')
.map((item) => item.time)
.sort((a, b) => new Date(b).getTime() - new Date(a).getTime())[0] ??
null,
};
return {
focusProject: focusProject
? {
name: focusProject.name,
ownerSister: focusProject.ownerSister ?? null,
phase: focusProject.phase,
currentSprint: focusProject.currentSprint ?? null,
progress: focusProject.progress ?? 0,
deployStatus: focusProject.deployStatus,
}
: null,
pipeline: {
activeTask: focusProject
? `${focusProject.name} · ${focusProject.currentSprint ?? focusProject.phase}`
: 'NO ACTIVE PIPELINE',
focus: latestProjectActivity
? summarizeActivity(latestProjectActivity, 'NO EVENT')
: 'SNAPSHOT / NO ACTIVE HANDOFF',
reviewLoopCount,
escalationCount,
deployState: focusProject?.deployStatus ?? 'STANDBY',
nodes,
},
board,
freshness,
};
}
private async getLatestQaBoardItems(
projects: { name: string; repoName: string; updatedAt: string }[],
) {
const docs = await Promise.all(
projects.map(async (project) => {
if (!project.repoName) return [] as OpsBoardItem[];
const pathGroups = await Promise.all(
QA_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(project.repoName, path),
),
);
const qaFiles = Array.from(
new Set(
pathGroups
.flat()
.filter((path) =>
/(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path),
),
),
);
const latestPath = qaFiles.sort().at(-1);
if (!latestPath) return [] as OpsBoardItem[];
const content = await this.gitea.getRawFile(
project.repoName,
latestPath,
);
if (!content) return [] as OpsBoardItem[];
const summary = parseQaSummary(content);
const label =
latestPath.split('/').pop()?.replace(/\.md$/i, '') ?? latestPath;
const tone = toneFromText(content);
return [
{
id: `qa-${project.repoName}-${label}`,
title: label,
body: summary,
tone,
author: inferQaAuthor(latestPath, content),
time: project.updatedAt,
category: 'DOC-DERIVED',
source: `${project.repoName}:${latestPath}`,
} satisfies OpsBoardItem,
];
}),
);
return docs.flat();
}
private toDisplayName(name: string) {
if (name === 'harang') return '하랑이';
if (name === 'narang') return '나랑이';
if (name === 'darang') return '다랑이';
if (name === 'erang') return '이랑이';
return name;
}
}

View File

@@ -10,6 +10,18 @@ import { Server, Socket } from 'socket.io';
import { Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { OnEvent } from '@nestjs/event-emitter';
import { ACCESS_TOKEN_COOKIE, parseCookieHeader } from '../auth/auth-cookies';
interface SocketUserPayload {
username?: string;
role?: string;
sub?: number;
}
interface SocketWithUser extends Socket {
user?: SocketUserPayload;
}
@WebSocketGateway({
cors: {
@@ -37,11 +49,19 @@ export class EventsGateway
this.logger.log('WebSocket Gateway initialized');
}
handleConnection(client: Socket) {
handleConnection(client: SocketWithUser) {
// JWT 인증 필수 — 토큰 없거나 유효하지 않으면 disconnect
const authHeader = client.handshake.headers.authorization;
const tokenFromHeader = Array.isArray(authHeader)
? authHeader[0]?.replace('Bearer ', '')
: authHeader?.replace('Bearer ', '');
const tokenFromCookie = parseCookieHeader(client.handshake.headers.cookie)[
ACCESS_TOKEN_COOKIE
];
const token =
(client.handshake.auth?.token as string) ??
(client.handshake.headers.authorization as string)?.replace('Bearer ', '');
(client.handshake.auth?.token as string | undefined) ??
tokenFromHeader ??
tokenFromCookie;
if (!token) {
this.logger.debug(`WS rejected (no token): ${client.id}`);
@@ -56,9 +76,13 @@ export class EventsGateway
}
try {
const payload = this.jwtService.verify(token, { secret });
(client as any).user = payload;
this.logger.debug(`WS client connected: ${client.id} (${payload.username})`);
const payload = this.jwtService.verify<SocketUserPayload>(token, {
secret,
});
client.user = payload;
this.logger.debug(
`WS client connected: ${client.id} (${payload.username ?? 'unknown'})`,
);
} catch {
this.logger.debug(`WS rejected (invalid token): ${client.id}`);
client.disconnect();
@@ -84,6 +108,39 @@ export class EventsGateway
this.server.emit('activity:new', { item, ts: Date.now() });
}
/** EventEmitter2에서 activity.logged 수신 → WebSocket 브로드캐스트 */
@OnEvent('activity.logged')
handleActivityLogged(record: unknown) {
this.broadcastActivity(record);
}
// ── Rails orchestrator events ──────────────────────────────────────
@OnEvent('rails.pipelines.snapshot')
handleRailsPipelinesSnapshot(payload: { pipelines: unknown[] }) {
this.server.emit('rails:pipelines', {
pipelines: payload.pipelines,
ts: Date.now(),
});
}
@OnEvent('rails.pipeline.updated')
handleRailsPipelineUpdated(payload: { pipeline: unknown }) {
this.server.emit('rails:pipeline:updated', {
pipeline: payload.pipeline,
ts: Date.now(),
});
}
@OnEvent('rails.subtasks.updated')
handleRailsSubTasksUpdated(payload: { pipelineId: string; tree: unknown }) {
this.server.emit('rails:subtasks', {
pipelineId: payload.pipelineId,
tree: payload.tree,
ts: Date.now(),
});
}
/** 연결된 클라이언트 수 */
getClientCount(): number {
return this.server?.sockets?.sockets?.size ?? 0;

View File

@@ -13,7 +13,11 @@ import { SistersModule } from '../sisters/sisters.module';
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: (() => { const s = config.get<string>('JWT_SECRET'); if (!s) throw new Error('JWT_SECRET is not configured'); return s; })(),
secret: (() => {
const s = config.get<string>('JWT_SECRET');
if (!s) throw new Error('JWT_SECRET is not configured');
return s;
})(),
}),
}),
],

View File

@@ -1,4 +1,9 @@
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import {
Injectable,
Logger,
OnModuleInit,
OnModuleDestroy,
} from '@nestjs/common';
import { SistersService } from '../sisters/sisters.service';
import { EventsGateway } from './events.gateway';
@@ -6,7 +11,10 @@ import { EventsGateway } from './events.gateway';
export class EventsScheduler implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(EventsScheduler.name);
private timer: NodeJS.Timeout | null = null;
private readonly INTERVAL_MS = parseInt(process.env.WS_POLL_INTERVAL_MS ?? '30000', 10);
private readonly INTERVAL_MS = parseInt(
process.env.WS_POLL_INTERVAL_MS ?? '30000',
10,
);
constructor(
private readonly sistersService: SistersService,
@@ -14,8 +22,12 @@ export class EventsScheduler implements OnModuleInit, OnModuleDestroy {
) {}
onModuleInit() {
this.timer = setInterval(() => this.tick(), this.INTERVAL_MS);
this.logger.log(`WebSocket scheduler started (interval: ${this.INTERVAL_MS}ms)`);
this.timer = setInterval(() => {
void this.tick();
}, this.INTERVAL_MS);
this.logger.log(
`WebSocket scheduler started (interval: ${this.INTERVAL_MS}ms)`,
);
}
onModuleDestroy() {

View File

@@ -14,13 +14,17 @@ export class SistersScheduler {
start() {
if (this.timer) return;
this.timer = setInterval(async () => {
try {
const sisters = await this.sistersService.getAllSistersStatus();
this.eventsGateway.broadcastSisterStatus(sisters);
} catch {
this.logger.warn('Failed to broadcast sisters update');
}
this.timer = setInterval(() => {
void this.broadcast();
}, 30000);
}
private async broadcast() {
try {
const sisters = await this.sistersService.getAllSistersStatus();
this.eventsGateway.broadcastSisterStatus(sisters);
} catch {
this.logger.warn('Failed to broadcast sisters update');
}
}
}

View File

@@ -8,7 +8,13 @@ import { AuthModule } from '../auth/auth.module';
import { ProjectsModule } from '../projects/projects.module';
@Module({
imports: [PrismaModule, GiteaModule, ActivityModule, AuthModule, ProjectsModule],
imports: [
PrismaModule,
GiteaModule,
ActivityModule,
AuthModule,
ProjectsModule,
],
controllers: [GiteaSyncController],
providers: [GiteaSyncService],
exports: [GiteaSyncService],

View File

@@ -1,5 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../prisma/prisma.service';
import { GiteaService } from '../gitea/gitea.service';
import { ActivityService } from '../activity/activity.service';
@@ -17,7 +16,11 @@ export class GiteaSyncService {
private readonly sprintSync: SprintSyncService,
) {}
async syncRepos(): Promise<{ synced: number; created: number; updated: number }> {
async syncRepos(): Promise<{
synced: number;
created: number;
updated: number;
}> {
const repos = await this.gitea.getOrgRepos();
if (!repos.length) {
@@ -71,11 +74,14 @@ export class GiteaSyncService {
});
}
this.logger.log(`Gitea sync: ${repos.length} repos, ${created} new, ${updated} updated`);
this.logger.log(
`Gitea sync: ${repos.length} repos, ${created} new, ${updated} updated`,
);
// Sprint 동기화도 함께 수행
await this.sprintSync.syncAllProjectSprints().catch((e) => {
this.logger.warn(`Sprint sync failed: ${e.message}`);
await this.sprintSync.syncAllProjectSprints().catch((e: unknown) => {
const message = e instanceof Error ? e.message : String(e);
this.logger.warn(`Sprint sync failed: ${message}`);
});
return { synced: repos.length, created, updated };

View File

@@ -45,7 +45,7 @@ export interface GiteaBranch {
@Injectable()
export class GiteaService {
private readonly logger = new Logger(GiteaService.name);
private readonly client: AxiosInstance;
private readonly client: AxiosInstance | null;
private readonly org: string;
constructor(private readonly config: ConfigService) {
@@ -54,8 +54,10 @@ export class GiteaService {
this.org = config.get<string>('GITEA_ORG') ?? 'hanarang';
if (!baseURL || !token) {
this.logger.warn('GITEA_BASE_URL or GITEA_TOKEN not set — Gitea features disabled');
this.client = null as any;
this.logger.warn(
'GITEA_BASE_URL or GITEA_TOKEN not set — Gitea features disabled',
);
this.client = null;
return;
}
@@ -66,27 +68,30 @@ export class GiteaService {
});
}
private isAvailable(): boolean {
return this.client !== null;
}
async getOrgRepos(): Promise<GiteaRepo[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaRepo[]>(`/orgs/${this.org}/repos`, {
params: { limit: 50 },
});
const { data } = await client.get<GiteaRepo[]>(
`/orgs/${this.org}/repos`,
{
params: { limit: 50 },
},
);
return data;
} catch (error) {
} catch {
this.logger.warn('Failed to fetch Gitea repos');
return [];
}
}
async getRepo(repoName: string): Promise<GiteaRepo | null> {
if (!this.isAvailable()) return null;
const client = this.client;
if (!client) return null;
try {
const { data } = await this.client.get<GiteaRepo>(`/repos/${this.org}/${repoName}`);
const { data } = await client.get<GiteaRepo>(
`/repos/${this.org}/${repoName}`,
);
return data;
} catch {
return null;
@@ -94,9 +99,10 @@ export class GiteaService {
}
async getOpenPRs(repoName: string): Promise<GiteaPR[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaPR[]>(
const { data } = await client.get<GiteaPR[]>(
`/repos/${this.org}/${repoName}/pulls`,
{ params: { state: 'open', limit: 20 } },
);
@@ -107,9 +113,10 @@ export class GiteaService {
}
async getCommits(repoName: string, limit = 20): Promise<GiteaCommit[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaCommit[]>(
const { data } = await client.get<GiteaCommit[]>(
`/repos/${this.org}/${repoName}/commits`,
{ params: { limit } },
);
@@ -121,9 +128,10 @@ export class GiteaService {
}
async getBranches(repoName: string): Promise<GiteaBranch[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaBranch[]>(
const { data } = await client.get<GiteaBranch[]>(
`/repos/${this.org}/${repoName}/branches`,
{ params: { limit: 50 } },
);
@@ -133,10 +141,14 @@ export class GiteaService {
}
}
async getPulls(repoName: string, state: 'open' | 'closed' | 'all' = 'open'): Promise<GiteaPR[]> {
if (!this.isAvailable()) return [];
async getPulls(
repoName: string,
state: 'open' | 'closed' | 'all' = 'open',
): Promise<GiteaPR[]> {
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaPR[]>(
const { data } = await client.get<GiteaPR[]>(
`/repos/${this.org}/${repoName}/pulls`,
{ params: { state, limit: 30, type: 'pulls' } },
);
@@ -147,22 +159,27 @@ export class GiteaService {
}
async getRepoTree(repoName: string, treePath: string): Promise<string[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<{ tree: { path: string; type: string }[] }>(
`/repos/${this.org}/${repoName}/git/trees/HEAD`,
{ params: { recursive: true } },
);
return (data.tree ?? []).filter((e) => e.path.startsWith(treePath) && e.type === 'blob').map((e) => e.path);
const { data } = await client.get<{
tree: { path: string; type: string }[];
}>(`/repos/${this.org}/${repoName}/git/trees/HEAD`, {
params: { recursive: true },
});
return (data.tree ?? [])
.filter((e) => e.path.startsWith(treePath) && e.type === 'blob')
.map((e) => e.path);
} catch {
return [];
}
}
async getRawFile(repoName: string, filePath: string): Promise<string | null> {
if (!this.isAvailable()) return null;
const client = this.client;
if (!client) return null;
try {
const { data } = await this.client.get<string>(
const { data } = await client.get<string>(
`/repos/${this.org}/${repoName}/raw/${filePath}`,
{ params: { ref: 'main' }, responseType: 'text' },
);

View File

@@ -1,20 +1,64 @@
import { NestFactory } from '@nestjs/core';
import { Logger, ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
import type { NextFunction, Request, Response } from 'express';
import helmet from 'helmet';
import { AppModule } from './app.module';
import {
ACCESS_TOKEN_COOKIE,
REFRESH_TOKEN_COOKIE,
getCookieValue,
hasValidCsrfToken,
} from './auth/auth-cookies';
function getAllowedOrigins() {
return (process.env.CORS_ORIGINS ?? 'http://localhost:3004')
.split(',')
.map((origin) => origin.trim())
.filter((origin): origin is string => origin.length > 0);
}
function shouldBypassCsrf(req: Request): boolean {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method.toUpperCase())) {
return true;
}
if (req.path === '/api/auth/login') {
return true;
}
const hasAuthorizationHeader = Boolean(req.headers.authorization);
if (hasAuthorizationHeader) {
return true;
}
const hasAuthCookie = Boolean(
getCookieValue(req, ACCESS_TOKEN_COOKIE) ||
getCookieValue(req, REFRESH_TOKEN_COOKIE),
);
return !hasAuthCookie;
}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(helmet());
app.use((req: Request, res: Response, next: NextFunction) => {
if (shouldBypassCsrf(req) || hasValidCsrfToken(req)) {
next();
return;
}
const allowedOrigins = (process.env.CORS_ORIGINS ?? 'http://localhost:3004')
.split(',')
.map((o) => o.trim())
.filter(Boolean);
res.status(403).json({ message: 'Invalid CSRF token' });
});
const allowedOrigins = getAllowedOrigins();
app.enableCors({
origin: (origin, callback) => {
origin: (
origin: string | undefined,
callback: (err: Error | null, allow?: boolean) => void,
) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
@@ -22,13 +66,26 @@ async function bootstrap() {
}
},
methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: [
'Content-Type',
'Authorization',
'X-CSRF-Token',
'X-Refresh-Token',
],
credentials: true,
});
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
const port = process.env.BACKEND_PORT ?? 3005;
const port = Number(process.env.BACKEND_PORT ?? 3005);
await app.listen(port);
Logger.log(`🚀 Backend running on port ${port}`, 'Bootstrap');
}
bootstrap();
void bootstrap();

View File

@@ -4,7 +4,10 @@ import { PrismaClient } from '@prisma/client';
import { PrismaMariaDb } from '@prisma/adapter-mariadb';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
constructor(config: ConfigService) {
const dbUrl = config.get<string>('DATABASE_URL');
if (!dbUrl) {

View File

@@ -1,4 +1,12 @@
import { Controller, Get, Param, Query, ParseIntPipe, UseGuards, Post } from '@nestjs/common';
import {
Controller,
Get,
Param,
Query,
ParseIntPipe,
UseGuards,
Post,
} from '@nestjs/common';
import { ProjectsService } from './projects.service';
import { SprintSyncService } from './sprint-sync.service';
import { JwtGuard } from '../auth/jwt.guard';

View File

@@ -3,7 +3,12 @@ import { PrismaService } from '../prisma/prisma.service';
import { GiteaService } from '../gitea/gitea.service';
type QaStatus = 'passed' | 'failed' | 'unknown';
type ProjectPhase = 'PLANNING' | 'IMPLEMENT' | 'QA' | 'READY FOR DEPLOY' | 'DEPLOYED';
type ProjectPhase =
| 'PLANNING'
| 'IMPLEMENT'
| 'QA'
| 'READY FOR DEPLOY'
| 'DEPLOYED';
export interface RepoDocumentMeta {
path: string;
@@ -36,7 +41,10 @@ function normalizeRepoName(repoUrl: string): string {
return repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
}
function extractDocOrder(path: string, kind: 'sprint' | 'hotfix' | 'qa'): number {
function extractDocOrder(
path: string,
kind: 'sprint' | 'hotfix' | 'qa',
): number {
const name = path.split('/').pop() ?? '';
if (kind === 'hotfix') {
const hotfix = name.match(/HOTFIX-(\d+)/i);
@@ -81,7 +89,8 @@ function parseTaskSummary(content: string): string | null {
function parseQaStatus(content: string): QaStatus {
if (/passed\s*[:=]\s*true/i.test(content)) return 'passed';
if (/passed\s*[:=]\s*false/i.test(content)) return 'failed';
if (/\bPASSED\b/i.test(content) && !/\bFAILED\b/i.test(content)) return 'passed';
if (/\bPASSED\b/i.test(content) && !/\bFAILED\b/i.test(content))
return 'passed';
if (/\bFAILED\b/i.test(content)) return 'failed';
return 'unknown';
}
@@ -89,19 +98,27 @@ function parseQaStatus(content: string): QaStatus {
function parseBlockerCount(content: string): number {
const jsonMatch = content.match(/"errors"\s*:\s*\[(.*?)\]/is);
if (jsonMatch) {
const items = jsonMatch[1].split(',').map((item) => item.trim()).filter(Boolean);
const items = jsonMatch[1]
.split(',')
.map((item) => item.trim())
.filter(Boolean);
if (items.length > 0) return items.length;
}
const errorLines = content
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => /^[-*]\s+/.test(line) && /(error|blocker|실패|문제)/i.test(line));
.filter(
(line) =>
/^[-*]\s+/.test(line) && /(error|blocker|실패|문제)/i.test(line),
);
return errorLines.length;
}
function isRepoDocumentMeta(value: RepoDocumentMeta | null): value is RepoDocumentMeta {
function isRepoDocumentMeta(
value: RepoDocumentMeta | null,
): value is RepoDocumentMeta {
return value !== null;
}
@@ -141,11 +158,12 @@ function buildProjectMeta(params: {
phase = 'IMPLEMENT';
}
const deployStatus = phase === 'DEPLOYED'
? 'DEPLOYED ON MAIN'
: phase === 'READY FOR DEPLOY'
? 'READY FOR DEPLOY'
: 'REDEPLOY REQUIRED';
const deployStatus =
phase === 'DEPLOYED'
? 'DEPLOYED ON MAIN'
: phase === 'READY FOR DEPLOY'
? 'READY FOR DEPLOY'
: 'REDEPLOY REQUIRED';
return {
phase,
@@ -177,17 +195,30 @@ export class ProjectsService {
const [repoMetaMap, repoDocsMap] = await Promise.all([
this.getRepoMetaMap(),
this.getRepoDocumentMap(dbProjects.map((project) => normalizeRepoName(project.repoUrl))),
this.getRepoDocumentMap(
dbProjects.map((project) => normalizeRepoName(project.repoUrl)),
),
]);
return dbProjects.map((project) => {
const totalSprints = project.sprints.length;
const doneSprints = project.sprints.filter((sprint) => sprint.status === 'done').length;
const inProgressSprint = project.sprints.find((sprint) => sprint.status === 'in_progress');
const ownerSister = project.sprints.flatMap((sprint) => sprint.tasks).find((task) => task.assignee)?.assignee ?? 'narang';
const progress = totalSprints > 0 ? Math.round((doneSprints / totalSprints) * 100) : 0;
const doneSprints = project.sprints.filter(
(sprint) => sprint.status === 'done',
).length;
const inProgressSprint = project.sprints.find(
(sprint) => sprint.status === 'in_progress',
);
const ownerSister =
project.sprints
.flatMap((sprint) => sprint.tasks)
.find((task) => task.assignee)?.assignee ?? 'narang';
const progress =
totalSprints > 0 ? Math.round((doneSprints / totalSprints) * 100) : 0;
const repoMeta = repoMetaMap[project.giteaId];
const docs = repoDocsMap.get(normalizeRepoName(project.repoUrl)) ?? { hotfixes: [], qas: [] };
const docs = repoDocsMap.get(normalizeRepoName(project.repoUrl)) ?? {
hotfixes: [],
qas: [],
};
const latestHotfix = docs.hotfixes.at(-1) ?? null;
const latestQa = docs.qas.at(-1) ?? null;
const meta = buildProjectMeta({
@@ -213,7 +244,11 @@ export class ProjectsService {
totalSprints,
doneSprints,
sprintCount: totalSprints,
currentSprint: inProgressSprint?.name ?? (doneSprints === totalSprints && totalSprints > 0 ? 'COMPLETED' : null),
currentSprint:
inProgressSprint?.name ??
(doneSprints === totalSprints && totalSprints > 0
? 'COMPLETED'
: null),
ownerSister,
openPRs: repoMeta?.openPRs ?? 0,
updatedAt: repoMeta?.updatedAt ?? project.updatedAt.toISOString(),
@@ -253,8 +288,12 @@ export class ProjectsService {
]);
const totalSprints = project.sprints.length;
const doneSprints = project.sprints.filter((sprint) => sprint.status === 'done').length;
const activeSprint = project.sprints.find((sprint) => sprint.status === 'in_progress');
const doneSprints = project.sprints.filter(
(sprint) => sprint.status === 'done',
).length;
const activeSprint = project.sprints.find(
(sprint) => sprint.status === 'in_progress',
);
const meta = buildProjectMeta({
totalSprints,
doneSprints,
@@ -276,7 +315,8 @@ export class ProjectsService {
label: docs.qas.at(-1)?.label ?? null,
status: docs.qas.at(-1)?.qaStatus ?? 'unknown',
blockerCount: docs.qas.at(-1)?.blockerCount ?? 0,
summary: docs.qas.at(-1)?.summary ?? docs.qas.at(-1)?.description ?? null,
summary:
docs.qas.at(-1)?.summary ?? docs.qas.at(-1)?.description ?? null,
}
: null,
deploy: {
@@ -310,17 +350,23 @@ export class ProjectsService {
const repoName = normalizeRepoName(project.repoUrl);
const docs = await this.collectRepoDocuments(repoName);
return [...docs.sprints, ...docs.hotfixes].filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order);
return [...docs.sprints, ...docs.hotfixes]
.filter(isRepoDocumentMeta)
.sort((a, b) => a.order - b.order);
}
private async getProjectMeta(id: number) {
const project = await this.prisma.project.findUnique({ where: { id }, select: { id: true, repoUrl: true } });
const project = await this.prisma.project.findUnique({
where: { id },
select: { id: true, repoUrl: true },
});
if (!project) throw new NotFoundException(`Project ${id} not found`);
return project;
}
private async getRepoMetaMap() {
const repoMetaMap: Record<number, { openPRs: number; updatedAt: string }> = {};
const repoMetaMap: Record<number, { openPRs: number; updatedAt: string }> =
{};
try {
const repos = await this.gitea.getOrgRepos();
for (const repo of repos) {
@@ -337,35 +383,80 @@ export class ProjectsService {
private async getRepoDocumentMap(repoNames: string[]) {
const uniqueRepoNames = Array.from(new Set(repoNames.filter(Boolean)));
const entries = await Promise.all(uniqueRepoNames.map(async (repoName) => [repoName, await this.collectRepoDocuments(repoName)] as const));
const entries = await Promise.all(
uniqueRepoNames.map(
async (repoName) =>
[repoName, await this.collectRepoDocuments(repoName)] as const,
),
);
return new Map(entries);
}
private async collectRepoDocuments(repoName: string) {
const [sprintPaths, hotfixPathGroups, qaPathGroups] = await Promise.all([
this.gitea.getRepoTree(repoName, SPRINT_PATH),
Promise.all(HOTFIX_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(QA_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(
HOTFIX_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
Promise.all(
QA_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
]);
const sprintFiles = sprintPaths.filter((path) => /SPRINT-\d+\.md$/i.test(path));
const hotfixFiles = Array.from(new Set(hotfixPathGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path))));
const qaFiles = Array.from(new Set(qaPathGroups.flat().filter((path) => /(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path))));
const sprintFiles = sprintPaths.filter((path) =>
/SPRINT-\d+\.md$/i.test(path),
);
const hotfixFiles = Array.from(
new Set(
hotfixPathGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path)),
),
);
const qaFiles = Array.from(
new Set(
qaPathGroups
.flat()
.filter((path) =>
/(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path),
),
),
);
const [sprints, hotfixes, qas] = await Promise.all([
Promise.all(sprintFiles.map((path) => this.readRepoDocument(repoName, path, 'sprint'))),
Promise.all(hotfixFiles.map((path) => this.readRepoDocument(repoName, path, 'hotfix'))),
Promise.all(qaFiles.map((path) => this.readRepoDocument(repoName, path, 'qa'))),
Promise.all(
sprintFiles.map((path) =>
this.readRepoDocument(repoName, path, 'sprint'),
),
),
Promise.all(
hotfixFiles.map((path) =>
this.readRepoDocument(repoName, path, 'hotfix'),
),
),
Promise.all(
qaFiles.map((path) => this.readRepoDocument(repoName, path, 'qa')),
),
]);
return {
sprints: sprints.filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order),
hotfixes: hotfixes.filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order),
sprints: sprints
.filter(isRepoDocumentMeta)
.sort((a, b) => a.order - b.order),
hotfixes: hotfixes
.filter(isRepoDocumentMeta)
.sort((a, b) => a.order - b.order),
qas: qas.filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order),
};
}
private async readRepoDocument(repoName: string, path: string, kind: 'sprint' | 'hotfix' | 'qa'): Promise<RepoDocumentMeta | null> {
private async readRepoDocument(
repoName: string,
path: string,
kind: 'sprint' | 'hotfix' | 'qa',
): Promise<RepoDocumentMeta | null> {
const content = await this.gitea.getRawFile(repoName, path);
if (!content) return null;

View File

@@ -6,6 +6,15 @@ import { GiteaService } from '../gitea/gitea.service';
describe('SprintSyncService', () => {
let service: SprintSyncService;
type TaskWriteArgs = {
data: {
taskId?: string;
assignee: string;
status: string;
};
where?: { id: number };
};
const mockPrisma = {
project: { findUnique: jest.fn(), findMany: jest.fn() },
sprint: { findFirst: jest.fn(), create: jest.fn(), update: jest.fn() },
@@ -29,8 +38,13 @@ describe('SprintSyncService', () => {
service = module.get<SprintSyncService>(SprintSyncService);
jest.clearAllMocks();
mockPrisma.project.findUnique.mockResolvedValue({ id: 1, repoUrl: 'https://gitea.example.com/hanarang/project-alpha' });
mockPrisma.project.findMany.mockResolvedValue([{ id: 1, repoUrl: 'https://gitea.example.com/hanarang/project-alpha' }]);
mockPrisma.project.findUnique.mockResolvedValue({
id: 1,
repoUrl: 'https://gitea.example.com/hanarang/project-alpha',
});
mockPrisma.project.findMany.mockResolvedValue([
{ id: 1, repoUrl: 'https://gitea.example.com/hanarang/project-alpha' },
]);
mockPrisma.sprint.findFirst.mockResolvedValue(null);
mockPrisma.sprint.create.mockResolvedValue({ id: 101, status: 'pending' });
mockPrisma.sprint.update.mockResolvedValue({ id: 101, status: 'pending' });
@@ -38,65 +52,107 @@ describe('SprintSyncService', () => {
mockPrisma.task.create.mockResolvedValue({});
mockPrisma.task.update.mockResolvedValue({});
mockGitea.getRepoTree.mockImplementation(async (_repoName: string, path: string) => {
if (path === '.plans/sprints/') return ['.plans/sprints/SPRINT-005.md', '.plans/sprints/HOTFIX-001.md'];
if (path === '.plans/qa/') return ['.plans/qa/SPRINT-005-review-darang.md'];
if (path === '.qa/') return [];
if (path === '.plans/hotfix/') return ['.plans/hotfix/HOTFIX-001.md'];
return [];
});
mockGitea.getRepoTree.mockImplementation(
(_repoName: string, path: string) => {
if (path === '.plans/sprints/') {
return [
'.plans/sprints/SPRINT-005.md',
'.plans/sprints/HOTFIX-001.md',
];
}
if (path === '.plans/qa/') {
return ['.plans/qa/SPRINT-005-review-darang.md'];
}
if (path === '.qa/') return [];
if (path === '.plans/hotfix/') return ['.plans/hotfix/HOTFIX-001.md'];
return [];
},
);
});
it('담당 라인을 읽어 assignee를 저장한다', async () => {
mockGitea.getRawFile.mockImplementation(async (_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 이랑이\n- **설명:** deploy\n\n### TASK-020: QA 자동화\n- **담당:** darang\n- **설명:** qa\n`;
}
if (path.includes('review')) return 'passed: true';
return '# HOTFIX-001: sample';
});
mockGitea.getRawFile.mockImplementation(
(_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 이랑이\n- **설명:** deploy\n\n### TASK-020: QA 자동화\n- **담당:** darang\n- **설명:** qa\n`;
}
if (path.includes('review')) return 'passed: true';
return '# HOTFIX-001: sample';
},
);
await service.syncProjectSprints(1);
expect(mockPrisma.task.create).toHaveBeenNthCalledWith(1, expect.objectContaining({
data: expect.objectContaining({ taskId: 'TASK-019', assignee: 'erang', status: 'done' }),
}));
expect(mockPrisma.task.create).toHaveBeenNthCalledWith(2, expect.objectContaining({
data: expect.objectContaining({ taskId: 'TASK-020', assignee: 'darang', status: 'done' }),
}));
const createCalls = mockPrisma.task.create.mock.calls as Array<
[TaskWriteArgs]
>;
expect(createCalls[0]?.[0]).toMatchObject({
data: {
taskId: 'TASK-019',
assignee: 'erang',
status: 'done',
},
});
expect(createCalls[1]?.[0]).toMatchObject({
data: {
taskId: 'TASK-020',
assignee: 'darang',
status: 'done',
},
});
});
it('기존 task도 assignee를 갱신한다', async () => {
mockPrisma.task.findFirst.mockResolvedValue({ id: 500, assignee: 'narang', status: 'pending' });
mockGitea.getRawFile.mockImplementation(async (_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 하랑이\n`;
}
if (path.includes('review')) return 'passed: false';
return '# HOTFIX-001: sample';
mockPrisma.task.findFirst.mockResolvedValue({
id: 500,
assignee: 'narang',
status: 'pending',
});
mockGitea.getRawFile.mockImplementation(
(_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 하랑이\n`;
}
if (path.includes('review')) return 'passed: false';
return '# HOTFIX-001: sample';
},
);
await service.syncProjectSprints(1);
expect(mockPrisma.task.update).toHaveBeenCalledWith(expect.objectContaining({
const updateCalls = mockPrisma.task.update.mock.calls as Array<
[TaskWriteArgs]
>;
expect(updateCalls[0]?.[0]).toMatchObject({
where: { id: 500 },
data: expect.objectContaining({ assignee: 'harang' }),
}));
data: { assignee: 'harang' },
});
});
it('담당 라인이 없으면 narang fallback', async () => {
mockGitea.getRawFile.mockImplementation(async (_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- 설명만 있음\n`;
}
if (path.includes('review')) return 'FAILED';
return '# HOTFIX-001: sample';
});
mockGitea.getRawFile.mockImplementation(
(_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- 설명만 있음\n`;
}
if (path.includes('review')) return 'FAILED';
return '# HOTFIX-001: sample';
},
);
await service.syncProjectSprints(1);
expect(mockPrisma.task.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ assignee: 'narang', status: 'pending' }),
}));
const createCalls = mockPrisma.task.create.mock.calls as Array<
[TaskWriteArgs]
>;
expect(createCalls[0]?.[0]).toMatchObject({
data: {
assignee: 'narang',
status: 'pending',
},
});
});
});

View File

@@ -13,46 +13,64 @@ const QA_PATH_CANDIDATES = ['.plans/qa/', '.qa/'];
const HOTFIX_PATH_CANDIDATES = ['.plans/hotfix/', '.plans/sprints/'];
const SISTER_NAME_MAP: Record<string, string> = {
harang: 'harang',
'하랑': 'harang',
'하랑이': 'harang',
: 'harang',
: 'harang',
narang: 'narang',
'나랑': 'narang',
'나랑이': 'narang',
: 'narang',
: 'narang',
darang: 'darang',
'다랑': 'darang',
'다랑이': 'darang',
: 'darang',
: 'darang',
erang: 'erang',
'이랑': 'erang',
'이랑이': 'erang',
: 'erang',
: 'erang',
};
function parseSprintName(content: string, filename: string, number: number): string {
const headingMatch = content.match(/^#\s+(?:SPRINT-\d+|Sprint\s+\d+)[:\s—\-]+(.+)/m);
function parseSprintName(
content: string,
filename: string,
number: number,
): string {
const headingMatch = content.match(
/^#\s+(?:SPRINT-\d+|Sprint\s+\d+)[:\s—-]+(.+)/m,
);
if (headingMatch) return headingMatch[1].trim();
return filename.replace('.md', '') || `SPRINT-${String(number).padStart(3, '0')}`;
return (
filename.replace('.md', '') || `SPRINT-${String(number).padStart(3, '0')}`
);
}
function parseTaskAssignee(taskLines: string[]): string {
for (const rawLine of taskLines) {
const line = rawLine.trim();
const match = line.match(/^-\s*(?:\*\*)?(?:담당|assignee)\s*:(?:\*\*)?\s*(.+)$/i);
const match = line.match(
/^-\s*(?:\*\*)?(?:담당|assignee)\s*:(?:\*\*)?\s*(.+)$/i,
);
if (!match) continue;
const assignee = match[1]
.trim()
.replace(/[()\[\],]/g, ' ')
.replace(/[()[\],]/g, ' ')
.split(/\s+/)
.find((token) => SISTER_NAME_MAP[token.toLowerCase()] ?? SISTER_NAME_MAP[token]);
.find(
(token) =>
SISTER_NAME_MAP[token.toLowerCase()] ?? SISTER_NAME_MAP[token],
);
if (assignee) {
return SISTER_NAME_MAP[assignee.toLowerCase()] ?? SISTER_NAME_MAP[assignee];
return (
SISTER_NAME_MAP[assignee.toLowerCase()] ?? SISTER_NAME_MAP[assignee]
);
}
}
return 'narang';
}
function parseTasks(content: string, sprintStatus: 'pending' | 'done'): ParsedTask[] {
function parseTasks(
content: string,
sprintStatus: 'pending' | 'done',
): ParsedTask[] {
const lines = content.split(/\r?\n/);
const tasks: ParsedTask[] = [];
const seen = new Set<string>();
@@ -66,7 +84,9 @@ function parseTasks(content: string, sprintStatus: 'pending' | 'done'): ParsedTa
if (match) status = sprintStatus;
if (!match) {
match = line.match(/^-\s*\[([ xX])\]\s*(TASK-\d+[A-Z]?)\s*[:\-]?\s*(.+)$/i);
match = line.match(
/^-\s*\[([ xX])\]\s*(TASK-\d+[A-Z]?)\s*[:-]?\s*(.+)$/i,
);
if (match) status = /x/i.test(match[1]) ? 'done' : 'pending';
}
@@ -89,7 +109,11 @@ function parseTasks(content: string, sprintStatus: 'pending' | 'done'): ParsedTa
const taskBlock: string[] = [];
for (let lookahead = index + 1; lookahead < lines.length; lookahead += 1) {
const nextLine = lines[lookahead].trim();
if (/^#{2,6}\s+TASK-\d+[A-Z]?\s*:/i.test(nextLine) || /^-\s*\[?[ xX]?\]?\s*TASK-\d+[A-Z]?\s*[:\-]?/i.test(nextLine) || /^TASK-\d+[A-Z]?\s*:/i.test(nextLine)) {
if (
/^#{2,6}\s+TASK-\d+[A-Z]?\s*:/i.test(nextLine) ||
/^-\s*\[?[ xX]?\]?\s*TASK-\d+[A-Z]?\s*[:-]?/i.test(nextLine) ||
/^TASK-\d+[A-Z]?\s*:/i.test(nextLine)
) {
break;
}
if (/^##\s+/.test(nextLine) && !/^##\s+목표/.test(nextLine)) {
@@ -126,8 +150,12 @@ export class SprintSyncService {
private readonly gitea: GiteaService,
) {}
async syncProjectSprints(projectId: number): Promise<{ synced: number; created: number; updated: number }> {
const project = await this.prisma.project.findUnique({ where: { id: projectId } });
async syncProjectSprints(
projectId: number,
): Promise<{ synced: number; created: number; updated: number }> {
const project = await this.prisma.project.findUnique({
where: { id: projectId },
});
if (!project) return { synced: 0, created: 0, updated: 0 };
const repoName = project.repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
@@ -135,11 +163,14 @@ export class SprintSyncService {
}
async syncAllProjectSprints(): Promise<{ projects: number; synced: number }> {
const projects = await this.prisma.project.findMany({ select: { id: true, repoUrl: true } });
const projects = await this.prisma.project.findMany({
select: { id: true, repoUrl: true },
});
let totalSynced = 0;
for (const project of projects) {
const repoName = project.repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
const repoName =
project.repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
const result = await this.syncRepo(project.id, repoName);
totalSynced += result.synced;
}
@@ -147,16 +178,39 @@ export class SprintSyncService {
return { projects: projects.length, synced: totalSynced };
}
private async syncRepo(projectId: number, repoName: string): Promise<{ synced: number; created: number; updated: number }> {
private async syncRepo(
projectId: number,
repoName: string,
): Promise<{ synced: number; created: number; updated: number }> {
const [sprintFilePaths, qaGroups, hotfixGroups] = await Promise.all([
this.gitea.getRepoTree(repoName, '.plans/sprints/'),
Promise.all(QA_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(HOTFIX_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(
QA_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
Promise.all(
HOTFIX_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
]);
const sprintFiles = sprintFilePaths.filter((path) => /SPRINT-\d+\.md$/i.test(path));
const qaFiles = Array.from(new Set(qaGroups.flat().filter((path) => /SPRINT-\d+.*(?:review|qa).*\.md$/i.test(path))));
const hotfixFiles = Array.from(new Set(hotfixGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path))));
const sprintFiles = sprintFilePaths.filter((path) =>
/SPRINT-\d+\.md$/i.test(path),
);
const qaFiles = Array.from(
new Set(
qaGroups
.flat()
.filter((path) => /SPRINT-\d+.*(?:review|qa).*\.md$/i.test(path)),
),
);
const hotfixFiles = Array.from(
new Set(
hotfixGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path)),
),
);
if (!sprintFiles.length) {
this.logger.warn(`No sprint files found in ${repoName}/.plans/sprints/`);
@@ -186,14 +240,20 @@ export class SprintSyncService {
const number = parseInt(numberMatch[1], 10);
const name = parseSprintName(content, filename, number);
const status: 'pending' | 'done' = passedMap.get(number) ? 'done' : 'pending';
const status: 'pending' | 'done' = passedMap.get(number)
? 'done'
: 'pending';
const parsedTasks = parseTasks(content, status);
const existingSprint = await this.prisma.sprint.findFirst({ where: { projectId, number } });
const existingSprint = await this.prisma.sprint.findFirst({
where: { projectId, number },
});
let sprintId = existingSprint?.id ?? 0;
if (!existingSprint) {
const createdSprint = await this.prisma.sprint.create({ data: { projectId, number, name, status } });
const createdSprint = await this.prisma.sprint.create({
data: { projectId, number, name, status },
});
sprintId = createdSprint.id;
created += 1;
} else {
@@ -209,7 +269,9 @@ export class SprintSyncService {
}
for (const task of parsedTasks) {
const existingTask = await this.prisma.task.findFirst({ where: { sprintId, taskId: task.taskId } });
const existingTask = await this.prisma.task.findFirst({
where: { sprintId, taskId: task.taskId },
});
if (!existingTask) {
await this.prisma.task.create({
data: {
@@ -233,7 +295,9 @@ export class SprintSyncService {
}
}
this.logger.log(`${repoName}: ${sprintFiles.length} sprints, ${hotfixFiles.length} hotfix docs, ${passedMap.size} QA passed → ${created} created, ${updated} updated`);
this.logger.log(
`${repoName}: ${sprintFiles.length} sprints, ${hotfixFiles.length} hotfix docs, ${passedMap.size} QA passed → ${created} created, ${updated} updated`,
);
return { synced: sprintFiles.length, created, updated };
}
}

View File

@@ -0,0 +1,117 @@
import {
Body,
Controller,
Get,
HttpException,
HttpStatus,
Param,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { RailsService } from './rails.service';
import { JwtGuard } from '../auth/jwt.guard';
@Controller('api/rails')
@UseGuards(JwtGuard)
export class RailsController {
constructor(private readonly rails: RailsService) {}
@Get('health')
health() {
return this.rails.health();
}
@Get('pipelines')
async listPipelines(@Query('limit') limit?: string) {
const n = limit ? parseInt(limit, 10) : 20;
const pipelines = await this.rails.listPipelines(Number.isFinite(n) ? n : 20);
return { pipelines };
}
@Get('pipelines/:id')
async pipelineDetail(@Param('id') id: string) {
const detail = await this.rails.getPipeline(id);
if (!detail) {
throw new HttpException('pipeline not found', HttpStatus.NOT_FOUND);
}
return detail;
}
@Get('pipelines/:id/sub-tasks')
async subTaskTree(@Param('id') id: string) {
const tree = await this.rails.getSubTaskTree(id);
return { pipelineId: id, tree };
}
@Get('sub-tasks/:id')
async subTaskDetail(@Param('id') id: string) {
const detail = await this.rails.getSubTaskDetail(id);
if (!detail) {
throw new HttpException('sub-task not found', HttpStatus.NOT_FOUND);
}
return detail;
}
@Get('file-content')
async fileContent(@Query('url') url?: string) {
if (!url) {
throw new HttpException('url required', HttpStatus.BAD_REQUEST);
}
const content = await this.rails.fetchFileContent(url);
if (content === null) {
throw new HttpException('file not found or not allowed', HttpStatus.NOT_FOUND);
}
return { url, content };
}
@Get('transitions')
async transitions(
@Query('pipelineId') pipelineId?: string,
@Query('eventType') eventType?: string,
@Query('limit') limit?: string,
) {
const opts: { pipelineId?: string; eventType?: string; limit?: number } = {};
if (pipelineId) opts.pipelineId = pipelineId;
if (eventType) opts.eventType = eventType;
if (limit) opts.limit = parseInt(limit, 10);
const transitions = await this.rails.listTransitions(opts);
return { transitions };
}
@Get('escalations')
async escalations(
@Query('pipelineId') pipelineId?: string,
@Query('resolved') resolved?: string,
@Query('limit') limit?: string,
) {
const opts: { pipelineId?: string; resolved?: boolean; limit?: number } = {};
if (pipelineId) opts.pipelineId = pipelineId;
if (resolved === 'true') opts.resolved = true;
else if (resolved === 'false') opts.resolved = false;
if (limit) opts.limit = parseInt(limit, 10);
const escalations = await this.rails.listEscalations(opts);
return { escalations };
}
@Post('pipelines/start')
async start(
@Body() body: { project: string; requirements: string },
) {
if (!body?.project || typeof body.project !== 'string') {
throw new HttpException('project required', HttpStatus.BAD_REQUEST);
}
return this.rails.startPipeline({
project: body.project,
requirements: body.requirements ?? '',
});
}
@Post('pipelines/:id/abort')
async abort(
@Param('id') id: string,
@Body() body: { reason?: string },
) {
return this.rails.abortPipeline(id, body?.reason ?? 'aborted via dashboard');
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { RailsService } from './rails.service';
import { RailsController } from './rails.controller';
import { RailsScheduler } from './rails.scheduler';
import { AuthModule } from '../auth/auth.module';
@Module({
imports: [ConfigModule, AuthModule],
controllers: [RailsController],
providers: [RailsService, RailsScheduler],
exports: [RailsService],
})
export class RailsModule {}

View File

@@ -0,0 +1,84 @@
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { RailsService, type RailsPipelineSummary } from './rails.service';
/**
* Polls rails every N seconds for active pipelines and emits events
* that the EventsGateway broadcasts over Socket.IO.
*
* Events emitted (via EventEmitter2):
* rails.pipeline.updated — single pipeline changed state
* rails.pipelines.snapshot — full list snapshot
* rails.subtasks.updated — sub-task tree for an active pipeline
*/
@Injectable()
export class RailsScheduler implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(RailsScheduler.name);
private readonly intervalMs = 2000;
private timer: NodeJS.Timeout | null = null;
private lastSnapshot = new Map<string, string>(); // id → state
private activePipelines = new Set<string>();
constructor(
private readonly rails: RailsService,
private readonly emitter: EventEmitter2,
) {}
onModuleInit(): void {
this.logger.log(`Rails poller starting (interval ${this.intervalMs}ms)`);
this.start();
}
onModuleDestroy(): void {
if (this.timer) clearInterval(this.timer);
}
private start(): void {
this.timer = setInterval(() => {
this.tick().catch((err) => {
this.logger.warn(`poll error: ${(err as Error).message}`);
});
}, this.intervalMs);
}
private async tick(): Promise<void> {
const pipelines = await this.rails.listPipelines(50);
// Detect changes
const changed: RailsPipelineSummary[] = [];
for (const p of pipelines) {
const last = this.lastSnapshot.get(p.id);
if (last !== p.currentState) {
changed.push(p);
this.lastSnapshot.set(p.id, p.currentState);
}
// Track active (non-terminal)
if (!['done', 'aborted'].includes(p.currentState)) {
this.activePipelines.add(p.id);
} else {
this.activePipelines.delete(p.id);
}
}
// Emit full snapshot every tick (cheap, dashboards love fresh data)
this.emitter.emit('rails.pipelines.snapshot', { pipelines });
// Emit per-pipeline updates for changed ones
for (const p of changed) {
this.emitter.emit('rails.pipeline.updated', { pipeline: p });
}
// Fetch sub-task trees for active pipelines (throttled)
for (const id of this.activePipelines) {
try {
const tree = await this.rails.getSubTaskTree(id);
this.emitter.emit('rails.subtasks.updated', {
pipelineId: id,
tree,
});
} catch {
// ignore transient errors
}
}
}
}

View File

@@ -0,0 +1,208 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
export interface RailsPipelineSummary {
id: string;
projectName: string;
currentState: string;
createdAt: string;
updatedAt: string;
}
export interface RailsSubTaskNode {
id: string;
parentId: string | null;
role: string;
agentName: string;
title: string;
state: string;
complexityScore: number | null;
complexityTier: string | null;
model: string;
startedAt: string | null;
completedAt: string | null;
createdAt: string;
children: RailsSubTaskNode[];
}
export interface RailsPipelineDetail {
state: string;
context: Record<string, unknown>;
transitions: Array<{
fromState: string;
toState: string;
eventType: string;
timestamp: string;
}>;
}
/**
* Thin HTTP client that reads from hanarang-rails orchestrator API.
* The dashboard is a read-only consumer — it never writes to rails DB directly.
*/
@Injectable()
export class RailsService {
private readonly logger = new Logger(RailsService.name);
private readonly baseUrl: string;
constructor(private readonly config: ConfigService) {
this.baseUrl = this.config.get<string>('RAILS_API_URL') ?? 'http://127.0.0.1:18800';
}
async listPipelines(limit = 20): Promise<RailsPipelineSummary[]> {
const data = await this.fetchJson<{ pipelines: RailsPipelineSummary[] }>(
`/pipelines?limit=${limit}`,
);
return data.pipelines ?? [];
}
async getPipeline(id: string): Promise<RailsPipelineDetail | null> {
try {
return await this.fetchJson<RailsPipelineDetail>(`/pipelines/${id}`);
} catch (err) {
this.logger.warn(`pipeline ${id} fetch failed: ${(err as Error).message}`);
return null;
}
}
async getSubTaskTree(pipelineId: string): Promise<RailsSubTaskNode[]> {
const data = await this.fetchJson<{ tree: RailsSubTaskNode[] }>(
`/api/pipelines/${pipelineId}/sub-tasks`,
);
return data.tree ?? [];
}
async getSubTaskDetail(id: string): Promise<unknown | null> {
try {
return await this.fetchJson(`/api/sub-tasks/${id}`);
} catch {
return null;
}
}
async listTransitions(opts: {
pipelineId?: string;
eventType?: string;
limit?: number;
}): Promise<unknown[]> {
const params = new URLSearchParams();
if (opts.pipelineId) params.set('pipelineId', opts.pipelineId);
if (opts.eventType) params.set('eventType', opts.eventType);
params.set('limit', String(opts.limit ?? 100));
const data = await this.fetchJson<{ transitions: unknown[] }>(
`/api/transitions?${params.toString()}`,
);
return data.transitions ?? [];
}
/**
* Fetch raw file content from a Git host. Restricted to an allowlist
* of hosts for SSRF safety.
*
* Allowlist is configured via env var GIT_RAW_ALLOWED_HOSTS — comma
* separated. Defaults to the hanarang-internal Gitea instance.
*/
async fetchFileContent(rawUrl: string): Promise<string | null> {
const allowedHosts = (
this.config.get<string>('GIT_RAW_ALLOWED_HOSTS') ??
'git.nabomhalang.co.kr'
)
.split(',')
.map((h) => h.trim())
.filter(Boolean);
let parsed: URL;
try {
parsed = new URL(rawUrl);
} catch {
return null;
}
if (!allowedHosts.includes(parsed.host)) return null;
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8000);
const res = await fetch(rawUrl, { signal: controller.signal });
clearTimeout(timer);
if (!res.ok) return null;
return await res.text();
} catch {
return null;
}
}
async listEscalations(opts: {
pipelineId?: string;
resolved?: boolean;
limit?: number;
}): Promise<unknown[]> {
const params = new URLSearchParams();
if (opts.pipelineId) params.set('pipelineId', opts.pipelineId);
if (opts.resolved !== undefined) params.set('resolved', String(opts.resolved));
params.set('limit', String(opts.limit ?? 50));
const data = await this.fetchJson<{ escalations: unknown[] }>(
`/api/escalations?${params.toString()}`,
);
return data.escalations ?? [];
}
async startPipeline(input: {
project: string;
requirements: string;
}): Promise<{ pipelineId: string; finalState: string; transitions: number }> {
return this.postJson('/pipelines/start', input);
}
async abortPipeline(id: string, reason: string): Promise<{ id: string; state: string }> {
return this.postJson(`/pipelines/${id}/abort`, { reason });
}
async health(): Promise<{ ok: boolean; service?: string }> {
try {
return await this.fetchJson('/health');
} catch {
return { ok: false };
}
}
private async fetchJson<T>(path: string): Promise<T> {
const url = `${this.baseUrl}${path}`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8000);
try {
const res = await fetch(url, { signal: controller.signal });
clearTimeout(timer);
if (!res.ok) {
const text = await res.text();
throw new Error(`rails GET ${path}${res.status}: ${text.slice(0, 200)}`);
}
return (await res.json()) as T;
} catch (err) {
clearTimeout(timer);
throw err;
}
}
private async postJson<T>(path: string, body: unknown): Promise<T> {
const url = `${this.baseUrl}${path}`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 600_000);
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
signal: controller.signal,
});
clearTimeout(timer);
if (!res.ok) {
const text = await res.text();
throw new Error(`rails POST ${path}${res.status}: ${text.slice(0, 200)}`);
}
return (await res.json()) as T;
} catch (err) {
clearTimeout(timer);
throw err;
}
}
}

View File

@@ -24,7 +24,9 @@ export class SettingsService {
) {}
async getAll() {
const rows = await this.prisma.systemSettings.findMany({ orderBy: { key: 'asc' } });
const rows = await this.prisma.systemSettings.findMany({
orderBy: { key: 'asc' },
});
const merged = { ...DEFAULT_SETTINGS };
for (const row of rows) merged[row.key] = row.value;
return merged;
@@ -33,7 +35,9 @@ export class SettingsService {
async saveAll(payload: Record<string, string>) {
// DEFAULT_SETTINGS에 있는 키만 허용
const allowed = Object.keys(DEFAULT_SETTINGS);
const entries = Object.entries(payload).filter(([key]) => allowed.includes(key));
const entries = Object.entries(payload).filter(([key]) =>
allowed.includes(key),
);
await this.prisma.$transaction(
entries.map(([key, value]) =>
this.prisma.systemSettings.upsert({

View File

@@ -9,9 +9,16 @@ describe('SisterDetailService', () => {
let service: SisterDetailService;
const mockSister = {
id: 2, name: 'narang', ip: '10.10.10.216', user: 'narang',
lxcId: 105, status: 'online', lastSeen: new Date(),
sshKeyPath: null, createdAt: new Date(), updatedAt: new Date(),
id: 2,
name: 'narang',
ip: '10.10.10.216',
user: 'narang',
lxcId: 105,
status: 'online',
lastSeen: new Date(),
sshKeyPath: null,
createdAt: new Date(),
updatedAt: new Date(),
};
const mockPrisma = {
@@ -35,7 +42,9 @@ describe('SisterDetailService', () => {
{ provide: PrismaService, useValue: mockPrisma },
{
provide: ConfigService,
useValue: { get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa') },
useValue: {
get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa'),
},
},
],
}).compile();
@@ -58,7 +67,9 @@ describe('SisterDetailService', () => {
it('getSisterConfig: sister 없으면 NotFoundException', async () => {
mockPrisma.sisterConfig.findUnique.mockResolvedValue(null);
await expect(service.getSisterConfig('narang')).rejects.toThrow(NotFoundException);
await expect(service.getSisterConfig('narang')).rejects.toThrow(
NotFoundException,
);
});
it('getSisterSessions: SSH 실패 시 빈 배열', async () => {

View File

@@ -1,10 +1,9 @@
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../prisma/prisma.service';
import { SshService } from './ssh.service';
import { ConfigService } from '@nestjs/config';
const SISTER_NAMES = ['harang', 'narang', 'darang', 'erang'] as const;
type SisterName = (typeof SISTER_NAMES)[number];
type SisterName = 'harang' | 'narang' | 'darang' | 'erang';
const SISTER_ROLES: Record<SisterName, string> = {
harang: 'Orchestrator',
@@ -14,12 +13,22 @@ const SISTER_ROLES: Record<SisterName, string> = {
};
const SISTER_DESCRIPTIONS: Record<SisterName, string> = {
harang: '기획과 오케스트레이션. 스프린트를 설계하고 자매들에게 작업을 배분한다.',
harang:
'기획과 오케스트레이션. 스프린트를 설계하고 자매들에게 작업을 배분한다.',
narang: '코드 생성과 개발. 스프린트를 구현하고 PR을 만든다.',
darang: '품질 검증. 코드 리뷰와 보안 감사를 수행한다.',
erang: '인프라와 배포. 서버 관리, merge, 프로덕션 배포를 담당한다.',
};
function summarizeText(value?: string | null, maxLength = 120): string | null {
if (!value) return null;
const compact = value.replace(/\s+/g, ' ').trim();
if (!compact) return null;
if (compact.length <= maxLength) return compact;
return `${compact.slice(0, maxLength - 1)}`;
}
@Injectable()
export class SisterDetailService {
private readonly logger = new Logger(SisterDetailService.name);
@@ -39,21 +48,36 @@ export class SisterDetailService {
sister.ip,
sister.user,
sshKeyPath,
'WORKSPACE=~/.hermes/workspace; [ -d "$WORKSPACE" ] || WORKSPACE=~/.openclaw/workspace; cat "$WORKSPACE"/SOUL.md 2>/dev/null | head -60; echo "---AGENTS---"; cat "$WORKSPACE"/AGENTS.md 2>/dev/null | head -40',
'WORKSPACE=~/.hermes/workspace; [ -d "$WORKSPACE" ] || WORKSPACE=~/.openclaw/workspace; for FILE in SOUL.md AGENTS.md; do if [ -f "$WORKSPACE/$FILE" ]; then printf "%s|present|%s\n" "$FILE" "$(wc -l < "$WORKSPACE/$FILE" 2>/dev/null || echo 0)"; else printf "%s|missing|0\n" "$FILE"; fi; done',
);
const files = result.stdout
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const [file, status, lineCount] = line.split('|');
return {
file,
status,
lineCount: Number.parseInt(lineCount ?? '0', 10) || 0,
};
});
return {
name,
role: SISTER_ROLES[name],
description: SISTER_DESCRIPTIONS[name],
raw: result.stdout || '(설정 파일 없음)',
files,
summary: `${files.filter((file) => file.status === 'present').length}/${files.length} protected config files detected`,
};
} catch {
return {
name,
role: SISTER_ROLES[name],
description: SISTER_DESCRIPTIONS[name],
raw: '(SSH 연결 불가)',
files: [],
summary: '(SSH 연결 불가)',
};
}
}
@@ -67,20 +91,37 @@ export class SisterDetailService {
sister.ip,
sister.user,
sshKeyPath,
'SESSION_DIR=~/.hermes/sessions; [ -d "$SESSION_DIR" ] || SESSION_DIR=~/.openclaw/sessions; ls -lt "$SESSION_DIR"/ 2>/dev/null | head -20 || echo ""',
'SESSION_DIR=~/.hermes/agents/main/sessions; [ -d "$SESSION_DIR" ] || SESSION_DIR=~/.openclaw/agents/main/sessions; ls -lt "$SESSION_DIR"/ 2>/dev/null | head -20 || echo ""',
);
const lines = result.stdout.split('\n').filter((l) => l && !l.startsWith('total'));
return lines.map((line) => {
const parts = line.trim().split(/\s+/);
return {
name: parts[parts.length - 1] ?? '',
modified: parts.slice(5, 8).join(' '),
size: parts[4] ?? '0',
};
}).filter((s) => s.name && s.name !== '');
const sessions = result.stdout
.split('\n')
.filter((line) => line && !line.startsWith('total'))
.map((line) => {
const parts = line.trim().split(/\s+/);
const label = parts[parts.length - 1] ?? '';
const modified = parts.slice(5, 8).join(' ');
const size = parts[4] ?? '0';
return {
id: label,
label,
status: [modified, size !== '0' ? `${size}B` : null]
.filter((part): part is string => Boolean(part))
.join(' · '),
};
})
.filter((session) => session.label.length > 0);
return {
sessions,
total: sessions.length,
};
} catch {
return [];
return {
sessions: [],
total: 0,
};
}
}
@@ -96,10 +137,25 @@ export class SisterDetailService {
'AGENT_DIR=~/.hermes/workspace/agents; [ -d "$AGENT_DIR" ] || AGENT_DIR=~/.openclaw/workspace/agents; ls "$AGENT_DIR"/ 2>/dev/null || echo ""',
);
const agents = result.stdout.split('\n').filter((l) => l.trim().endsWith('.md'));
return agents.map((a) => ({ name: a.trim().replace('.md', ''), file: a.trim() }));
const items = result.stdout
.split('\n')
.map((line) => line.trim())
.filter((line) => line.endsWith('.md'))
.map((file) => ({
id: file.replace('.md', ''),
label: file.replace('.md', ''),
file,
}));
return {
items,
total: items.length,
};
} catch {
return [];
return {
items: [],
total: 0,
};
}
}
@@ -113,7 +169,16 @@ export class SisterDetailService {
}),
this.prisma.activityLog.count({ where: { sisterId: sister.id } }),
]);
return { items: logs, total };
return {
items: logs.map((log) => ({
id: log.id,
action: log.action,
detail: summarizeText(log.detail),
createdAt: log.createdAt,
})),
total,
};
}
async getOrgData() {
@@ -140,14 +205,16 @@ export class SisterDetailService {
}
private async getSisterRecord(name: SisterName) {
const sister = await this.prisma.sisterConfig.findUnique({ where: { name } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name },
});
if (!sister) throw new NotFoundException(`Sister ${name} not found`);
return sister;
}
private getKeyPath(): string {
const p = this.config.get<string>('SSH_KEY_PATH');
if (!p) throw new Error('SSH_KEY_PATH is not set');
return p;
const path = this.config.get<string>('SSH_KEY_PATH');
if (!path) throw new Error('SSH_KEY_PATH is not set');
return path;
}
}

View File

@@ -1,12 +1,24 @@
import { Controller, Get, Param, Res } from '@nestjs/common';
import {
Body,
Controller,
Get,
Param,
Post,
Res,
UseGuards,
} from '@nestjs/common';
import type { Response } from 'express';
import { SistersService } from './sisters.service';
import { SisterDetailService } from './sister-detail.service';
import { JwtGuard } from '../auth/jwt.guard';
import { RoleGuard, Roles } from '../auth/role.guard';
import { SisterNamePipe } from '../common/sister-name.pipe';
import type { SisterName } from '../common/sister-name.pipe';
import { AvatarService } from './avatar.service';
import { SisterDetailService } from './sister-detail.service';
import { SistersService } from './sisters.service';
@Controller('api/sisters')
@UseGuards(JwtGuard, RoleGuard)
@Roles('admin', 'viewer')
export class SistersController {
constructor(
private readonly sistersService: SistersService,
@@ -14,14 +26,51 @@ export class SistersController {
private readonly avatarService: AvatarService,
) {}
@Get('runtime')
async getSistersRuntime() {
return this.sistersService.getAllSistersRuntime();
}
@Get()
async getSistersStatus() {
return this.sistersService.getAllSistersStatus();
const sisters = await this.sistersService.getAllSistersStatus();
return sisters.map(({ id, name, lxcId, role, status, lastSeen, currentTask }) => ({
id,
name,
lxcId,
role,
status,
lastSeen,
currentTask,
}));
}
@Get(':name/runtime')
async getSisterRuntime(@Param('name', SisterNamePipe) name: SisterName) {
return this.sistersService.getSisterRuntime(name);
}
@UseGuards(JwtGuard)
@Post(':name/chat')
async chatWithSister(
@Param('name', SisterNamePipe) name: SisterName,
@Body('message') message: string,
) {
return this.sistersService.sendChatMessage(name, message);
}
@Get(':name/system')
async getSystemInfo(@Param('name', SisterNamePipe) name: SisterName) {
return this.sistersService.getSystemInfo(name as SisterName);
const system = await this.sistersService.getSystemInfo(name);
if (!system) return null;
return {
uptime: system.uptime,
cpu: system.cpu,
memory: system.memory,
disk: system.disk,
};
}
@Get(':name/avatar')
@@ -29,34 +78,38 @@ export class SistersController {
@Param('name', SisterNamePipe) name: SisterName,
@Res() res: Response,
) {
const sister = await this.sistersService.findByName(name as SisterName);
const sister = await this.sistersService.findByName(name);
if (!sister) {
return res.status(404).json({ message: 'Sister not found' });
}
const avatar = await this.avatarService.getAvatar(sister);
res.setHeader('Content-Type', avatar.contentType);
res.setHeader('Cache-Control', 'public, max-age=300');
res.setHeader('Cache-Control', 'private, max-age=300');
return res.send(avatar.data);
}
@Roles('admin')
@Get(':name/config')
async getSisterConfig(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterConfig(name as SisterName);
return this.sisterDetail.getSisterConfig(name);
}
@Roles('admin')
@Get(':name/sessions')
async getSisterSessions(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterSessions(name as SisterName);
return this.sisterDetail.getSisterSessions(name);
}
@Roles('admin')
@Get(':name/subagents')
async getSisterSubagents(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterSubagents(name as SisterName);
return this.sisterDetail.getSisterSubagents(name);
}
@Roles('admin')
@Get(':name/activity')
async getSisterActivity(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterActivityLog(name as SisterName);
return this.sisterDetail.getSisterActivityLog(name);
}
}

View File

@@ -1,16 +1,17 @@
import { Module } from '@nestjs/common';
import { SistersController } from './sisters.controller';
import { SistersService } from './sisters.service';
import { SisterDetailService } from './sister-detail.service';
import { SshService } from './ssh.service';
import { PrismaModule } from '../prisma/prisma.module';
import { ConfigModule } from '@nestjs/config';
import { SisterDetailService } from './sister-detail.service';
import { AvatarService } from './avatar.service';
import { ActivityModule } from '../activity/activity.module';
import { AuthModule } from '../auth/auth.module';
@Module({
imports: [PrismaModule, ConfigModule],
imports: [PrismaModule, ActivityModule, AuthModule],
controllers: [SistersController],
providers: [SistersService, SisterDetailService, SshService, AvatarService],
exports: [SistersService, SisterDetailService, SshService, AvatarService],
providers: [SistersService, SshService, SisterDetailService, AvatarService],
exports: [SistersService, SshService, SisterDetailService, AvatarService],
})
export class SistersModule {}

View File

@@ -7,13 +7,56 @@ import { ConfigService } from '@nestjs/config';
describe('SistersService', () => {
let service: SistersService;
let sshService: jest.Mocked<SshService>;
let prismaService: jest.Mocked<PrismaService>;
const mockSisters = [
{ id: 1, name: 'harang', ip: '10.10.10.112', user: 'harang', lxcId: 104, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{ id: 2, name: 'narang', ip: '10.10.10.216', user: 'narang', lxcId: 105, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{ id: 3, name: 'darang', ip: '10.10.10.136', user: 'darang', lxcId: 106, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{ id: 4, name: 'erang', ip: '10.10.10.163', user: 'erang', lxcId: 107, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{
id: 1,
name: 'harang',
ip: '10.10.10.112',
user: 'harang',
lxcId: 104,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: 2,
name: 'narang',
ip: '10.10.10.216',
user: 'narang',
lxcId: 105,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: 3,
name: 'darang',
ip: '10.10.10.136',
user: 'darang',
lxcId: 106,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: 4,
name: 'erang',
ip: '10.10.10.163',
user: 'erang',
lxcId: 107,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
];
beforeEach(async () => {
@@ -35,22 +78,28 @@ describe('SistersService', () => {
{ provide: PrismaService, useValue: mockPrisma },
{
provide: ConfigService,
useValue: { get: jest.fn().mockImplementation((key: string) => {
if (key === 'SSH_KEY_PATH') return '/home/narang/.ssh/id_rsa';
if (key === 'DATABASE_URL') return 'mysql://test:test@localhost:3306/test';
return undefined;
}) },
useValue: {
get: jest.fn().mockImplementation((key: string) => {
if (key === 'SSH_KEY_PATH') return '/home/narang/.ssh/id_rsa';
if (key === 'DATABASE_URL')
return 'mysql://test:test@localhost:3306/test';
return undefined;
}),
},
},
],
}).compile();
service = module.get<SistersService>(SistersService);
sshService = module.get(SshService);
prismaService = module.get(PrismaService);
});
it('SSH 성공 시 online 상태 반환', async () => {
sshService.executeCommand.mockResolvedValue({ stdout: 'active', stderr: '', code: 0 });
sshService.executeCommand.mockResolvedValue({
stdout: 'active',
stderr: '',
code: 0,
});
const result = await service.getAllSistersStatus();
@@ -58,11 +107,13 @@ describe('SistersService', () => {
expect(result[0].status).toBe('online');
expect(result[0].name).toBe('harang');
expect(result[0].role).toBe('Orchestrator');
expect((result[0] as any).ip).toBeUndefined(); // IP 노출 제거 확인
expect(result[0]).not.toHaveProperty('ip'); // IP 노출 제거 확인
});
it('SSH 실패 시 offline graceful fallback', async () => {
sshService.executeCommand.mockRejectedValue(new Error('Connection refused'));
sshService.executeCommand.mockRejectedValue(
new Error('Connection refused'),
);
const result = await service.getAllSistersStatus();
@@ -73,13 +124,13 @@ describe('SistersService', () => {
it('일부 SSH 실패 시 실패한 자매만 offline', async () => {
sshService.executeCommand
.mockResolvedValueOnce({ stdout: 'active', stderr: '', code: 0 }) // harang
.mockRejectedValueOnce(new Error('timeout')) // narang
.mockRejectedValueOnce(new Error('timeout')) // narang
.mockResolvedValueOnce({ stdout: 'inactive', stderr: '', code: 1 }) // darang
.mockRejectedValueOnce(new Error('timeout')); // erang
.mockRejectedValueOnce(new Error('timeout')); // erang
const result = await service.getAllSistersStatus();
expect(result[0].status).toBe('online'); // harang
expect(result[0].status).toBe('online'); // harang
expect(result[1].status).toBe('offline'); // narang (SSH 실패)
expect(result[2].status).toBe('offline'); // darang (inactive)
expect(result[3].status).toBe('offline'); // erang (SSH 실패)

View File

@@ -1,9 +1,48 @@
import { Injectable, Logger, Optional } from '@nestjs/common';
import {
BadRequestException,
Injectable,
Logger,
Optional,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { SshService } from './ssh.service';
import { ConfigService } from '@nestjs/config';
import { ActivityService } from '../activity/activity.service';
export type RuntimeState =
| 'idle'
| 'thinking'
| 'tool_calling'
| 'speaking'
| 'error';
export interface RuntimeMessage {
id: string;
role: 'user' | 'assistant' | 'tool';
content: string;
ts: string | null;
}
export interface RuntimeSubagent {
name: string;
state: RuntimeState;
updatedAt: number | null;
currentTask: string | null;
sessionLabel: string | null;
}
export interface SisterRuntimeSnapshot {
name: string;
gatewayConnected: boolean;
mainState: RuntimeState;
currentTask: string | null;
activeSessionLabel: string | null;
activeSessionUpdatedAt: number | null;
controlSessionKey: string | null;
recentMessages: RuntimeMessage[];
subagents: RuntimeSubagent[];
}
export interface SisterStatus {
id: number;
name: string;
@@ -13,6 +52,28 @@ export interface SisterStatus {
status: 'online' | 'offline' | 'working' | 'unknown';
lastSeen: Date | null;
currentTask: string | null;
liveState: RuntimeState;
activeSessionLabel: string | null;
gatewayConnected: boolean;
subagents: RuntimeSubagent[];
}
interface RuntimeProbeResult {
gatewayConnected?: boolean;
mainState?: RuntimeState;
currentTask?: string | null;
activeSessionLabel?: string | null;
activeSessionUpdatedAt?: number | null;
controlSessionKey?: string | null;
recentMessages?: RuntimeMessage[];
subagents?: RuntimeSubagent[];
}
interface ChatSendResult {
ok: boolean;
status: string;
reply: string;
raw?: string;
}
const SISTER_ROLES: Record<string, string> = {
@@ -22,6 +83,17 @@ const SISTER_ROLES: Record<string, string> = {
erang: 'Infra Manager',
};
function runtimeStateToStatus(
state: RuntimeState,
connected: boolean,
): 'online' | 'offline' | 'working' {
if (!connected || state === 'error') return 'offline';
if (state === 'thinking' || state === 'tool_calling' || state === 'speaking') {
return 'working';
}
return 'online';
}
@Injectable()
export class SistersService {
private readonly logger = new Logger(SistersService.name);
@@ -34,7 +106,7 @@ export class SistersService {
) {}
async getAllSistersStatus(): Promise<SisterStatus[]> {
const sisters = await this.prisma.sisterConfig.findMany();
const sisters = await this.prisma.sisterConfig.findMany({ orderBy: { id: 'asc' } });
const sshKeyPath = this.config.get<string>('SSH_KEY_PATH');
if (!sshKeyPath) {
throw new Error('SSH_KEY_PATH is not set. Check your .env file.');
@@ -49,34 +121,138 @@ export class SistersService {
return result.value;
}
const sister = sisters[index];
return {
id: sister.id,
name: sister.name,
user: sister.user,
lxcId: sister.lxcId,
role: SISTER_ROLES[sister.name] ?? 'Unknown',
status: 'offline' as const,
lastSeen: sister.lastSeen,
currentTask: null,
};
return this.buildOfflineStatus(sister);
});
}
async getAllSistersRuntime(): Promise<SisterRuntimeSnapshot[]> {
const sisters = await this.prisma.sisterConfig.findMany({ orderBy: { id: 'asc' } });
const sshKeyPath = this.config.get<string>('SSH_KEY_PATH');
if (!sshKeyPath) {
throw new Error('SSH_KEY_PATH is not set. Check your .env file.');
}
const results = await Promise.allSettled(
sisters.map(async (sister) => {
const runtime = await this.probeRuntime(sister, sshKeyPath, true);
return this.withRuntimeName(sister.name, runtime);
}),
);
return results.map((result, index) => {
if (result.status === 'fulfilled') return result.value;
return this.buildRuntimeFallback(sisters[index].name);
});
}
async getSisterRuntime(name: string): Promise<SisterRuntimeSnapshot> {
const sister = await this.findByName(name);
if (!sister) throw new Error(`Sister ${name} not found`);
const sshKeyPath = this.config.get<string>('SSH_KEY_PATH');
if (!sshKeyPath) {
throw new Error('SSH_KEY_PATH is not set. Check your .env file.');
}
try {
const runtime = await this.probeRuntime(sister, sshKeyPath, true);
return this.withRuntimeName(sister.name, runtime);
} catch {
return this.buildRuntimeFallback(sister.name);
}
}
async sendChatMessage(name: string, message: string) {
const trimmed = message.trim();
if (!trimmed) {
throw new BadRequestException('message is required');
}
const sister = await this.findByName(name);
if (!sister) throw new Error(`Sister ${name} not found`);
const sshKeyPath = this.config.get<string>('SSH_KEY_PATH');
if (!sshKeyPath) {
throw new Error('SSH_KEY_PATH is not set. Check your .env file.');
}
const sendResult = await this.ssh.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
this.buildAgentSendCommand(trimmed),
);
const parsed = this.parseRemoteJson<ChatSendResult>(sendResult.stdout);
if (!parsed?.ok) {
throw new Error(parsed?.raw || 'Failed to send message to sister runtime');
}
const runtime = await this.getSisterRuntime(name).catch(() =>
this.buildRuntimeFallback(name),
);
return {
ok: true,
reply: parsed.reply,
status: parsed.status,
runtime,
};
}
async findByName(name: string) {
return this.prisma.sisterConfig.findUnique({ where: { name } });
}
async getSystemInfo(name: string) {
const sister = await this.prisma.sisterConfig.findUnique({ where: { name } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name },
});
if (!sister) return null;
const sshKeyPath = this.config.get<string>('SSH_KEY_PATH');
if (!sshKeyPath) return null;
const [uptimeRes, cpuRes, memRes, diskRes] = await Promise.all([
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, 'cat /proc/uptime 2>/dev/null || echo "0 0"').catch(() => ({ stdout: '0 0', stderr: '', code: 0 })),
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, "top -bn1 | grep Cpu || echo '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id'").catch(() => ({ stdout: '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id', stderr: '', code: 0 })),
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, 'free -m | grep Mem || echo "Mem: 0 0 0 0 0 0"').catch(() => ({ stdout: 'Mem: 0 0 0 0 0 0', stderr: '', code: 0 })),
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, "df -h / | tail -1 || echo '/dev/root 0G 0G 0G 0% /'").catch(() => ({ stdout: '/dev/root 0G 0G 0G 0% /', stderr: '', code: 0 })),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
'cat /proc/uptime 2>/dev/null || echo "0 0"',
)
.catch(() => ({ stdout: '0 0', stderr: '', code: 0 })),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
"top -bn1 | grep Cpu || echo '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id'",
)
.catch(() => ({
stdout: '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id',
stderr: '',
code: 0,
})),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
'free -m | grep Mem || echo "Mem: 0 0 0 0 0 0"',
)
.catch(() => ({ stdout: 'Mem: 0 0 0 0 0 0', stderr: '', code: 0 })),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
"df -h / | tail -1 || echo '/dev/root 0G 0G 0G 0% /'",
)
.catch(() => ({
stdout: '/dev/root 0G 0G 0G 0% /',
stderr: '',
code: 0,
})),
]);
return {
@@ -88,33 +264,39 @@ export class SistersService {
}
private async checkSisterStatus(
sister: { id: number; name: string; ip: string; user: string; lxcId: number; lastSeen: Date | null; status: string },
sister: {
id: number;
name: string;
ip: string;
user: string;
lxcId: number;
lastSeen: Date | null;
status: string;
},
sshKeyPath: string,
): Promise<SisterStatus> {
try {
const result = await this.ssh.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
'if systemctl --user is-active hermes-agent >/dev/null 2>&1; then echo active; elif systemctl --user is-active hermes-gateway >/dev/null 2>&1; then echo active; elif pgrep -f "hermes.*gateway|hermes.*agent" >/dev/null 2>&1; then echo active; elif systemctl --user is-active openclaw-gateway >/dev/null 2>&1; then echo active; else echo inactive; fi',
);
const isActive = result.stdout.trim() === 'active';
const status: 'online' | 'offline' = isActive ? 'online' : 'offline';
const runtime = await this.probeRuntime(sister, sshKeyPath, false);
const gatewayConnected = Boolean(runtime.gatewayConnected);
const liveState = runtime.mainState ?? (gatewayConnected ? 'idle' : 'error');
const status = runtimeStateToStatus(liveState, gatewayConnected);
const prevStatus = sister.status;
const now = new Date();
const lastSeen = gatewayConnected ? now : sister.lastSeen;
await this.prisma.sisterConfig.update({
where: { id: sister.id },
data: { lastSeen: isActive ? now : sister.lastSeen, status },
data: { lastSeen, status },
});
if (prevStatus !== status && this.activity) {
await this.activity.log({
sisterId: sister.id,
action: 'status_changed',
detail: `[${sister.name}] status: ${prevStatus}${status}`,
}).catch(() => {});
await this.activity
.log({
sisterId: sister.id,
action: 'status_changed',
detail: `[${sister.name}] status: ${prevStatus}${status}`,
})
.catch(() => {});
}
return {
@@ -124,22 +306,448 @@ export class SistersService {
lxcId: sister.lxcId,
role: SISTER_ROLES[sister.name] ?? 'Unknown',
status,
lastSeen: isActive ? now : sister.lastSeen,
currentTask: null,
lastSeen,
currentTask: runtime.currentTask ?? null,
liveState,
activeSessionLabel: runtime.activeSessionLabel ?? null,
gatewayConnected,
subagents: runtime.subagents ?? [],
};
} catch {
this.logger.warn(`Failed to check status for ${sister.name}`);
return this.buildOfflineStatus(sister);
}
}
private async probeRuntime(
sister: { name: string; ip: string; user: string },
sshKeyPath: string,
includeMessages: boolean,
): Promise<RuntimeProbeResult> {
const result = await this.ssh.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
this.buildRuntimeProbeCommand(includeMessages),
);
const parsed = this.parseRemoteJson<RuntimeProbeResult>(result.stdout);
if (parsed) {
return parsed;
}
const legacy = this.parseLegacyRuntimeResult(result.stdout);
if (legacy) {
return legacy;
}
throw new Error(`Runtime probe returned invalid JSON for ${sister.name}`);
}
private withRuntimeName(
name: string,
runtime: RuntimeProbeResult,
): SisterRuntimeSnapshot {
return {
name,
gatewayConnected: Boolean(runtime.gatewayConnected),
mainState: runtime.mainState ?? 'error',
currentTask: runtime.currentTask ?? null,
activeSessionLabel: runtime.activeSessionLabel ?? null,
activeSessionUpdatedAt: runtime.activeSessionUpdatedAt ?? null,
controlSessionKey: runtime.controlSessionKey ?? null,
recentMessages: runtime.recentMessages ?? [],
subagents: runtime.subagents ?? [],
};
}
private buildOfflineStatus(sister: {
id: number;
name: string;
user: string;
lxcId: number;
lastSeen: Date | null;
}): SisterStatus {
return {
id: sister.id,
name: sister.name,
user: sister.user,
lxcId: sister.lxcId,
role: SISTER_ROLES[sister.name] ?? 'Unknown',
status: 'offline',
lastSeen: sister.lastSeen,
currentTask: null,
liveState: 'error',
activeSessionLabel: null,
gatewayConnected: false,
subagents: [],
};
}
private buildRuntimeFallback(name: string): SisterRuntimeSnapshot {
return {
name,
gatewayConnected: false,
mainState: 'error',
currentTask: null,
activeSessionLabel: null,
activeSessionUpdatedAt: null,
controlSessionKey: null,
recentMessages: [],
subagents: [],
};
}
private parseRemoteJson<T>(stdout: string): T | null {
const trimmed = stdout.trim();
const start = trimmed.indexOf('{');
const end = trimmed.lastIndexOf('}');
if (start === -1 || end === -1 || end <= start) return null;
try {
return JSON.parse(trimmed.slice(start, end + 1)) as T;
} catch {
return null;
}
}
private parseLegacyRuntimeResult(stdout: string): RuntimeProbeResult | null {
const trimmed = stdout.trim();
if (trimmed === 'active') {
return {
id: sister.id,
name: sister.name,
user: sister.user,
lxcId: sister.lxcId,
role: SISTER_ROLES[sister.name] ?? 'Unknown',
status: 'offline',
lastSeen: sister.lastSeen,
gatewayConnected: true,
mainState: 'idle',
currentTask: null,
activeSessionLabel: null,
activeSessionUpdatedAt: null,
controlSessionKey: null,
recentMessages: [],
subagents: [],
};
}
if (trimmed === 'inactive') {
return {
gatewayConnected: false,
mainState: 'error',
currentTask: null,
activeSessionLabel: null,
activeSessionUpdatedAt: null,
controlSessionKey: null,
recentMessages: [],
subagents: [],
};
}
return null;
}
private buildRuntimeProbeCommand(includeMessages: boolean): string {
return `
GATEWAY_CONNECTED=0
if systemctl --user is-active hermes-agent >/dev/null 2>&1; then GATEWAY_CONNECTED=1; \
elif systemctl --user is-active hermes-gateway >/dev/null 2>&1; then GATEWAY_CONNECTED=1; \
elif pgrep -f "hermes.*gateway|hermes.*agent" >/dev/null 2>&1; then GATEWAY_CONNECTED=1; \
elif systemctl --user is-active openclaw-gateway >/dev/null 2>&1; then GATEWAY_CONNECTED=1; \
elif pgrep -f "openclaw.*gateway|openclaw.*agent" >/dev/null 2>&1; then GATEWAY_CONNECTED=1; fi
export GATEWAY_CONNECTED
if command -v python3 >/dev/null 2>&1; then
python3 - <<'PY'
import json
import os
from pathlib import Path
INCLUDE_MESSAGES = ${includeMessages ? 'True' : 'False'}
MESSAGE_LIMIT = ${includeMessages ? '12' : '0'}
def pick_base():
for name in ('.hermes', '.openclaw'):
candidate = Path.home() / name
if candidate.exists():
return candidate
return None
def load_json(path: Path):
if not path.exists():
return {}
try:
return json.loads(path.read_text(errors='ignore'))
except Exception:
return {}
def normalize_role(role):
if role in ('user', 'assistant'):
return role
if role in ('tool', 'toolResult'):
return 'tool'
return None
def extract_text(content):
if isinstance(content, str):
return content.strip()
parts = []
if isinstance(content, list):
for item in content:
if not isinstance(item, dict):
continue
item_type = item.get('type')
text = item.get('text') or item.get('input') or item.get('content') or ''
if item_type in ('text', 'input_text', 'output_text') and text:
parts.append(str(text).strip())
elif item_type == 'tool_call':
tool_name = item.get('name') or item.get('toolName') or 'tool'
parts.append(f'[{tool_name}]')
return ' '.join(part for part in parts if part).strip()
def compact(text, limit=160):
normalized = ' '.join((text or '').split())
if not normalized:
return ''
if normalized.startswith('A new session was started via /new or /reset.'):
return ''
if len(normalized) <= limit:
return normalized
return normalized[: limit - 1] + '…'
def read_recent_messages(session_file, limit):
if not session_file or limit <= 0:
return []
path = Path(session_file)
if not path.exists():
return []
out = []
try:
lines = path.read_text(errors='ignore').splitlines()
except Exception:
return []
for line in reversed(lines):
try:
payload = json.loads(line)
except Exception:
continue
if payload.get('type') != 'message':
continue
message = payload.get('message') or {}
role = normalize_role(message.get('role'))
if not role:
continue
content = compact(extract_text(message.get('content')))
if not content:
continue
out.append(
{
'id': str(payload.get('id') or ''),
'role': role,
'content': content,
'ts': payload.get('timestamp') or message.get('timestamp'),
}
)
if len(out) >= limit:
break
out.reverse()
return out
def pick_session(index, prefer_key=None):
if not isinstance(index, dict) or not index:
return None, None
if prefer_key and prefer_key in index:
return prefer_key, index.get(prefer_key)
items = sorted(index.items(), key=lambda item: item[1].get('updatedAt') or 0, reverse=True)
return items[0]
def get_label(entry):
if not isinstance(entry, dict):
return None
return entry.get('displayName') or (entry.get('origin') or {}).get('label') or entry.get('lastTo')
def latest_user_text(messages):
for item in reversed(messages):
if item.get('role') == 'user':
return item.get('content')
return None
def age_minutes(updated_at):
if not updated_at:
return 10 ** 9
return max(0, (int(__import__('time').time() * 1000) - int(updated_at)) // 60000)
def state_from(entry, messages, connected):
if not connected:
return 'error'
if not isinstance(entry, dict):
return 'idle'
status = entry.get('status') or ''
last_role = messages[-1]['role'] if messages else None
age_min = age_minutes(entry.get('updatedAt'))
if status == 'running':
if last_role == 'tool':
return 'tool_calling'
if last_role == 'assistant':
return 'speaking'
return 'thinking'
if age_min <= 2:
if last_role == 'assistant':
return 'speaking'
if last_role == 'tool':
return 'tool_calling'
if last_role == 'user':
return 'thinking'
if age_min <= 15 and last_role == 'assistant':
return 'speaking'
return 'idle'
payload = {
'gatewayConnected': os.environ.get('GATEWAY_CONNECTED') == '1',
'mainState': 'error',
'currentTask': None,
'activeSessionLabel': None,
'activeSessionUpdatedAt': None,
'controlSessionKey': None,
'recentMessages': [],
'subagents': [],
}
base = pick_base()
if not base:
print(json.dumps(payload, ensure_ascii=False))
raise SystemExit
agents_root = base / 'agents'
main_index = load_json(agents_root / 'main' / 'sessions' / 'sessions.json')
active_key, active_entry = pick_session(main_index)
control_key, control_entry = pick_session(main_index, 'agent:main:main')
active_messages = read_recent_messages((active_entry or {}).get('sessionFile'), 8)
control_messages = read_recent_messages(
(control_entry or active_entry or {}).get('sessionFile'),
MESSAGE_LIMIT if INCLUDE_MESSAGES else 0,
)
payload['mainState'] = state_from(active_entry, active_messages, payload['gatewayConnected'])
payload['currentTask'] = latest_user_text(active_messages) or get_label(active_entry)
payload['activeSessionLabel'] = get_label(active_entry)
payload['activeSessionUpdatedAt'] = (active_entry or {}).get('updatedAt')
payload['controlSessionKey'] = control_key or active_key
payload['recentMessages'] = control_messages
subagent_names = set()
workspace_agents = base / 'workspace' / 'agents'
if workspace_agents.exists():
subagent_names.update(path.stem for path in workspace_agents.glob('*.md'))
if agents_root.exists():
subagent_names.update(
path.name for path in agents_root.iterdir() if path.is_dir() and path.name != 'main'
)
for subagent in sorted(subagent_names):
sub_index = load_json(agents_root / subagent / 'sessions' / 'sessions.json')
_, sub_entry = pick_session(sub_index)
sub_messages = read_recent_messages((sub_entry or {}).get('sessionFile'), 4)
payload['subagents'].append(
{
'name': subagent,
'state': state_from(sub_entry, sub_messages, payload['gatewayConnected']),
'updatedAt': (sub_entry or {}).get('updatedAt'),
'currentTask': latest_user_text(sub_messages) or get_label(sub_entry),
'sessionLabel': get_label(sub_entry),
}
)
print(json.dumps(payload, ensure_ascii=False))
PY
else
printf '%s' '{"gatewayConnected":false,"mainState":"error","currentTask":null,"activeSessionLabel":null,"activeSessionUpdatedAt":null,"controlSessionKey":null,"recentMessages":[],"subagents":[]}'
fi`.trim();
}
private buildAgentSendCommand(message: string): string {
const messageB64 = Buffer.from(message, 'utf8').toString('base64');
return `
export MSG_B64='${messageB64}'
if command -v python3 >/dev/null 2>&1 && command -v openclaw >/dev/null 2>&1; then
python3 - <<'PY'
import base64
import json
import os
import subprocess
message = base64.b64decode(os.environ['MSG_B64']).decode('utf-8')
proc = subprocess.run(
[
'openclaw',
'agent',
'--agent',
'main',
'--message',
message,
'--json',
'--timeout',
'120',
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
out = proc.stdout or ''
start = out.find('{')
end = out.rfind('}')
payload = {}
if start != -1 and end != -1 and end > start:
try:
payload = json.loads(out[start : end + 1])
except Exception:
payload = {}
result = payload.get('result') if isinstance(payload.get('result'), dict) else {}
payloads = result.get('payloads') if isinstance(result.get('payloads'), list) else []
texts = []
for item in payloads:
if not isinstance(item, dict):
continue
text = item.get('text') or item.get('message') or item.get('content')
if isinstance(text, str) and text.strip():
texts.append(text.strip())
reply = '\n\n'.join(texts).strip()
if not reply and proc.returncode == 0:
reply = str(payload.get('summary') or '응답 완료').strip()
print(
json.dumps(
{
'ok': proc.returncode == 0,
'status': payload.get('status') or ('completed' if proc.returncode == 0 else 'failed'),
'reply': reply,
'raw': out[-4000:],
},
ensure_ascii=False,
)
)
PY
else
printf '%s' '{"ok":false,"status":"failed","reply":"","raw":"openclaw runtime unavailable"}'
fi`.trim();
}
private parseUptime(stdout: string) {

View File

@@ -1,4 +1,12 @@
import { Controller, Get, Post, Patch, Param, Body, ParseIntPipe } from '@nestjs/common';
import {
Controller,
Get,
Post,
Patch,
Param,
Body,
ParseIntPipe,
} from '@nestjs/common';
import { TasksService, CreateSprintDto, UpdateTaskDto } from './tasks.service';
@Controller('api')

View File

@@ -8,15 +8,27 @@ describe('TasksService', () => {
let service: TasksService;
const mockTask = {
id: 1, taskId: 'TASK-001', title: 'Test', assignee: 'narang',
status: 'pending', iteration: 0, sprintId: 1,
createdAt: new Date(), updatedAt: new Date(),
id: 1,
taskId: 'TASK-001',
title: 'Test',
assignee: 'narang',
status: 'pending',
iteration: 0,
sprintId: 1,
createdAt: new Date(),
updatedAt: new Date(),
};
const mockSprint = {
id: 1, projectId: 1, number: 1, name: 'Sprint 001',
status: 'in_progress', startedAt: null, completedAt: null,
createdAt: new Date(), updatedAt: new Date(),
id: 1,
projectId: 1,
number: 1,
name: 'Sprint 001',
status: 'in_progress',
startedAt: null,
completedAt: null,
createdAt: new Date(),
updatedAt: new Date(),
tasks: [mockTask],
};
@@ -57,7 +69,9 @@ describe('TasksService', () => {
it('getTaskLedger: sprint + task + progress 반환', async () => {
mockPrisma.project.findUnique.mockResolvedValue({
id: 1,
sprints: [{ ...mockSprint, tasks: [{ ...mockTask, status: 'done' }, mockTask] }],
sprints: [
{ ...mockSprint, tasks: [{ ...mockTask, status: 'done' }, mockTask] },
],
});
const result = await service.getTaskLedger(1);
@@ -67,8 +81,15 @@ describe('TasksService', () => {
});
it('updateTask: 상태 변경 시 ActivityLog 기록', async () => {
mockPrisma.task.findUnique.mockResolvedValue({ ...mockTask, status: 'in_progress' });
mockPrisma.task.update.mockResolvedValue({ ...mockTask, status: 'done', sprintId: 1 });
mockPrisma.task.findUnique.mockResolvedValue({
...mockTask,
status: 'in_progress',
});
mockPrisma.task.update.mockResolvedValue({
...mockTask,
status: 'done',
sprintId: 1,
});
await service.updateTask(1, { status: 'done' });

View File

@@ -13,7 +13,15 @@ export class CreateSprintDto {
name!: string;
}
const VALID_STATUSES = ['pending', 'in_progress', 'review', 'done', 'failed', 'blocked', 'escalated'] as const;
const VALID_STATUSES = [
'pending',
'in_progress',
'review',
'done',
'failed',
'blocked',
'escalated',
] as const;
export class UpdateTaskDto {
@IsOptional()
@@ -58,14 +66,21 @@ export class TasksService {
startedAt: sprint.startedAt,
completedAt: sprint.completedAt,
tasks: sprint.tasks,
progress: sprint.tasks.length > 0
? Math.round(sprint.tasks.filter((t) => t.status === 'done').length / sprint.tasks.length * 100)
: 0,
progress:
sprint.tasks.length > 0
? Math.round(
(sprint.tasks.filter((t) => t.status === 'done').length /
sprint.tasks.length) *
100,
)
: 0,
}));
}
async createSprint(projectId: number, dto: CreateSprintDto) {
const project = await this.prisma.project.findUnique({ where: { id: projectId } });
const project = await this.prisma.project.findUnique({
where: { id: projectId },
});
if (!project) throw new NotFoundException(`Project ${projectId} not found`);
const sprint = await this.prisma.sprint.create({
@@ -90,9 +105,10 @@ export class TasksService {
where: { id: taskId },
data: {
...dto,
iteration: dto.status && dto.status !== prevStatus && prevStatus !== 'pending'
? { increment: 1 }
: undefined,
iteration:
dto.status && dto.status !== prevStatus && prevStatus !== 'pending'
? { increment: 1 }
: undefined,
},
});

View File

@@ -0,0 +1,115 @@
# 하나랑 오피스 대시보드 PRD
## 제품명
하나랑 오피스 대시보드
## 한 줄 정의
OpenClaw 4자매와 서브에이전트 협업을 2D 등축 투영 오피스로 시각화하고, 채팅/파이프라인/서버 헬스를 함께 운영하는 멀티에이전트 관제 프론트엔드.
## 배경
기존 하나랑 대시보드는 운영 정보는 잘 보여주지만, 4자매와 서브에이전트가 실제로 어떻게 협업하는지 한눈에 느끼기엔 한계가 있어.
자기야가 원하는 건 단순 상태 카드가 아니라:
- 누가 자기 자리에서 대기 중인지
- 누가 회의실로 이동했는지
- 어떤 서브에이전트가 어떤 워크플로우에서 일하고 있는지
- 지금 QA 루프인지 배포 직전인지
`오피스`라는 직관적인 은유로 읽는 화면이야.
## 제품 목표
1. 4자매 메인 에이전트와 17개 서브에이전트, 총 21개 에이전트를 하나의 세계관 안에서 시각화한다.
2. 4자매 독립 Gateway WebSocket을 통해 실시간 상태를 반영한다.
3. Lobster 워크플로우와 Discord handoff를 자연스럽게 한 화면에 묶는다.
4. 직접 채팅, 파이프라인 현황, 서버 헬스까지 운영 도구를 통합한다.
## 핵심 사용자
- 자기야: 전체 파이프라인 운영 책임자
- 하랑이: Planning / handoff orchestration
- 나랑이: 구현 상태 추적
- 다랑이: QA 루프 / blocker 판단
- 이랑이: 배포 / 인프라 점검
## 핵심 시나리오
### 시나리오 1: 현재 누가 일하고 있는지 한눈에 보기
자기야가 메인 화면에 들어오면, 하랑/나랑/다랑/이랑 좌석과 주변 서브에이전트 상태를 보고 즉시 현재 국면을 판단한다.
### 시나리오 2: 구현 → QA → 배포 흐름 확인
나랑이 쪽 서브에이전트가 활발히 움직이다가, 다랑이 회의실로 연결선이 넘어가고, 승인되면 이랑이 인프라 영역으로 흐름이 넘어가는 걸 본다.
### 시나리오 3: 특정 자매와 직접 대화
자기야가 하랑이나 나랑이를 선택해서 direct chat을 열고 작업을 지시한다.
### 시나리오 4: 서버/헬스 이상 감지
대시보드 한쪽 패널에서 Gateway 연결, Dev 서버, Docker 상태 이상을 바로 감지한다.
## 기능 요구사항
### 필수
1. 4자매 Gateway WebSocket 연결
2. 2D 등축 투영 오피스 메인 화면
3. 메인 에이전트 4명 고정 좌석
4. 서브에이전트 동적 이동/상태 표시
5. 상태: `idle`, `thinking`, `tool_calling`, `speaking`, `error`
6. 협업 연결선 / 회의실 이동 시각화
7. 자매 선택 직접 채팅 인터페이스
8. Lobster 워크플로우 / 스프린트 / 사이클 패널
9. 서버 상태 패널 (4자매 + Dev + Docker)
### 중요
10. live / snapshot / fallback 구분
11. 실브라우저/모바일 대응
12. 기존 하나랑 대시보드 운영 패널과의 연속성 유지
## 정보 구조
### 메인 오피스 화면
- 좌측 또는 중앙: 오피스 씬
- 우측: 선택 에이전트 detail / chat / workflow
- 하단 또는 보조 패널: 서버 헬스 / 최근 handoff / sprint state
### 오피스 씬 요소
- 하랑이 데스크
- 나랑이 데스크
- 다랑이 데스크
- 이랑이 데스크
- 회의실
- 임시 작업석
- 인프라/서버 존
- 서브에이전트 이동 경로
### 채팅
- 자매 선택 탭
- 메시지 히스토리
- 입력창
- tool call 상태 / streaming 표시
### 운영 패널
- active workflow
- current sprint
- review loop
- deploy gate
- server health
## 데이터 소스
- 4자매 Gateway WebSocket
- activity log
- workflow state
- session/chat API
- admin/system/health API
## 기술 원칙
- 기존 Next.js + styled-components 유지
- Backend는 기존 Nest.js + Prisma 유지
- WebSocket은 OpenClaw Gateway 기준
- 필요 시 polling reconciliation 허용
- fake 데이터 하드코딩 금지
## 비기능 요구사항
- 첫 화면에서 현재 협업 구조 이해 가능
- 과한 애니메이션 금지
- 모바일에서도 핵심 흐름 유지
- 데이터 소스 구분이 명확해야 함
## 성공 기준
- 자기야가 메인 화면만 보고 현재 상태를 설명할 수 있음
- 4자매/서브에이전트 구조가 카드보다 더 직관적으로 읽힘
- 채팅/워크플로우/서버 패널이 따로 놀지 않음
- live / snapshot / fallback 구분이 사용자에게 정직하게 보임

View File

@@ -0,0 +1 @@
1775809622

View File

@@ -0,0 +1 @@
1 1775809627

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

@@ -0,0 +1,7 @@
'use client';
import LiveWorkboard from '@/components/live/LiveWorkboard';
export default function ControlPage() {
return <LiveWorkboard />;
}

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>
);
}

View File

@@ -1,153 +1,7 @@
'use client';
import React, { useEffect, useState, useCallback } from 'react';
import styled, { keyframes } from 'styled-components';
import Link from 'next/link';
import { PageHeader, PageTitle, Card, BracketValue, LabelMeta, TechBar, TechBarFill, SectionTitle, Timeline, TimelineItem, TimeStamp, TimelineContent } from '@/components/ui/base';
import { API_URL, POLL_INTERVAL_MS } from '@/lib/config';
import { useSocket } from '@/lib/useSocket';
import SisterAvatar from '@/components/common/SisterAvatar';
import LiveWorkboard from '@/components/live/LiveWorkboard';
interface SisterItem { id?: number; name: string; status: string; cpu?: number; uptime?: string; }
interface ProjectItem { id: number; name: string; description: string | null; phase: string; progress: number; deployStatus: string; ownerSister?: string; }
interface ActivityItem { id: number; createdAt: string; detail?: string; action?: string; sister?: { name: string } | null; }
const pulse = keyframes`0%{opacity:.35}50%{opacity:.7}100%{opacity:.35}`;
const StatusGrid = styled.section`display:grid;grid-template-columns:repeat(4,1fr);gap:var(--space-lg);@media (min-width:768px) and (max-width:1199px){grid-template-columns:repeat(2,1fr)}@media (max-width:767px){grid-template-columns:repeat(2,1fr);gap:var(--space-md)}`;
const DataColumns = styled.div`display:grid;grid-template-columns:1.5fr 1fr;gap:var(--space-xxl);align-items:start;@media (max-width:1199px){grid-template-columns:1fr;gap:var(--space-xl);}`;
const ChartGrid = styled.section`display:grid;grid-template-columns:1fr 1fr;gap:var(--space-xl);margin-bottom:var(--space-xxl);@media (max-width:1199px){grid-template-columns:1fr;}`;
const ChartCard = styled.div`border:1px solid var(--border-color);padding:var(--space-lg);min-width:0;overflow:hidden;`;
const ProjectList = styled.div`display:flex;flex-direction:column;`;
const ProjectRow = styled(Link)`display:grid;grid-template-columns:40px 1fr auto;gap:var(--space-md);padding:var(--space-md) 0;border-bottom:1px solid #222;align-items:center;text-decoration:none;transition:opacity .15s;&:last-child{border-bottom:none}&:hover{opacity:.8}`;
const ProjectDetails = styled.div`display:flex;flex-direction:column;gap:2px;min-width:0;`;
const ProjectName = styled.div`font-size:15px;font-weight:500;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;
const ProjectDesc = styled.div`font-size:13px;color:var(--text-secondary);line-height:1.4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;
const WsIndicator = styled.span<{ $on:boolean }>`font-size:11px;font-family:var(--font-mono);color:${({$on})=>$on?'var(--text-secondary)':'#333'};margin-left:var(--space-md);`;
const SkeletonCard = styled.div`height:142px;border:1px solid var(--border-color);background:#111;animation:${pulse} 1.4s ease-in-out infinite;`;
const SkeletonLine = styled.div`height:14px;background:#111;animation:${pulse} 1.4s ease-in-out infinite;margin:10px 0;`;
const ErrorBox = styled.div`padding:var(--space-md);border:1px solid #5a2a2a;color:#ff9b9b;font-size:13px;margin-bottom:var(--space-lg);`;
const BarChart = styled.div`display:flex;align-items:stretch;gap:10px;height:160px;margin-top:var(--space-lg);min-width:0;overflow-x:auto;overflow-y:hidden;padding-bottom:var(--space-xs);-webkit-overflow-scrolling:touch;scrollbar-width:thin;@media (max-width:767px){gap:8px;height:140px;scrollbar-width:none;&::-webkit-scrollbar{display:none;}}`;
const BarCol = styled.div`display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:8px;flex:0 0 52px;min-width:52px;height:100%;@media (max-width:767px){flex-basis:48px;min-width:48px;}`;
const Bar = styled.div<{ $height:number }>`width:100%;max-width:48px;height:${({$height})=>$height}%;background:var(--text-primary);min-height:${({$height})=>$height > 0 ? '6px' : '0'};`;
const BarLabel = styled.div`font-size:11px;color:var(--text-secondary);font-family:var(--font-mono);max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;
const SISTER_SHORT: Record<string, string> = { harang: '하랑', narang: '나랑', darang: '다랑', erang: '이랑' };
function sisterBracketValue(sister: SisterItem): string {
if (sister.status === 'online') return '[ON]';
if (sister.status === 'working') return '[RUN]';
if (sister.status === 'offline') return '[--]';
return '[??]';
}
function sisterBarWidth(sister: SisterItem): number {
if (typeof sister.cpu === 'number') return Math.max(0, Math.min(100, sister.cpu));
if (sister.status === 'online') return 100;
if (sister.status === 'working') return 84;
if (sister.status === 'offline') return 0;
return 12;
}
function sisterSubLabel(sister: SisterItem): string {
return sister.uptime ? `Hermes ${sister.uptime}` : sister.status;
}
function formatTimestamp(iso: string): string {
const date = new Date(iso);
return `${date.toLocaleTimeString('ko-KR', { hour12: false })} GMT+9`;
}
export default function DashboardPage() {
const [sisters, setSisters] = useState<SisterItem[]>([]);
const [projects, setProjects] = useState<ProjectItem[]>([]);
const [activityItems, setActivityItems] = useState<ActivityItem[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const handleSistersUpdate = useCallback((items: SisterItem[]) => setSisters(items), []);
const handleActivityNew = useCallback((item: ActivityItem) => setActivityItems((prev) => [item, ...prev].slice(0, 10)), []);
const { connected } = useSocket({ onSistersUpdate: handleSistersUpdate, onActivityNew: handleActivityNew });
useEffect(() => {
let active = true;
const fetchAll = async () => {
try {
const [sRes, pRes, aRes] = await Promise.allSettled([
fetch(`${API_URL}/api/sisters`),
fetch(`${API_URL}/api/projects`),
fetch(`${API_URL}/api/activity?limit=8`),
]);
if (!active) return;
if (sRes.status === 'fulfilled' && sRes.value.ok) setSisters(await sRes.value.json());
if (pRes.status === 'fulfilled' && pRes.value.ok) setProjects(await pRes.value.json());
if (aRes.status === 'fulfilled' && aRes.value.ok) setActivityItems((await aRes.value.json()).items ?? []);
setError(null);
} catch {
if (active) setError('데이터를 불러올 수 없습니다');
} finally {
if (active) setLoading(false);
}
};
fetchAll();
const iv = setInterval(fetchAll, POLL_INTERVAL_MS);
return () => { active = false; clearInterval(iv); };
}, []);
return (
<>
<PageHeader><PageTitle> <WsIndicator $on={connected}> {connected ? 'LIVE' : 'POLL'}</WsIndicator></PageTitle></PageHeader>
{error && <ErrorBox>{error}</ErrorBox>}
<StatusGrid>
{loading ? Array.from({ length: 4 }).map((_, index) => <SkeletonCard key={index} />) : sisters.map((sister) => (
<Card key={sister.id ?? sister.name} as={Link} href={`/sisters/${sister.name}`} style={{ textDecoration: 'none' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<LabelMeta><span>SYS:</span>{SISTER_SHORT[sister.name] ?? sister.name}</LabelMeta>
<SisterAvatar name={sister.name} size={24} />
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-xs)' }}>
<BracketValue $dimmed={sister.status === 'offline'}>{sisterBracketValue(sister)}</BracketValue>
<LabelMeta>{sisterSubLabel(sister)}</LabelMeta>
</div>
<TechBar><TechBarFill $width={sisterBarWidth(sister)} /></TechBar>
</Card>
))}
</StatusGrid>
<ChartGrid>
<ChartCard>
<SectionTitle><span>HERMES NODE LOAD</span><LabelMeta>CPU %</LabelMeta></SectionTitle>
<BarChart>{(sisters.length > 0 ? sisters : [{ name: 'harang', status: 'offline' }, { name: 'narang', status: 'offline' }, { name: 'darang', status: 'offline' }, { name: 'erang', status: 'offline' }]).map((sister) => <BarCol key={sister.name}><Bar $height={Math.max(4, Number(sister.cpu ?? 0))} /><BarLabel>{SISTER_SHORT[sister.name] ?? sister.name}</BarLabel></BarCol>)}</BarChart>
</ChartCard>
<ChartCard>
<SectionTitle><span>PROJECT PHASE</span><LabelMeta>TOP {projects.length}</LabelMeta></SectionTitle>
<BarChart>{(projects.length > 0 ? projects.slice(0, 6) : [{ id: 0, name: 'EMPTY', phase: 'PLANNING', progress: 0, deployStatus: 'REDEPLOY REQUIRED', description: null }]).map((project) => <BarCol key={project.id}><Bar $height={Math.max(4, Number(project.progress ?? 0))} /><BarLabel>{project.phase.slice(0, 6)}</BarLabel></BarCol>)}</BarChart>
</ChartCard>
</ChartGrid>
<DataColumns>
<section>
<SectionTitle><span>ONGOING PROJECTS</span><LabelMeta>PROJECT = 2ND NAV</LabelMeta></SectionTitle>
<ProjectList>
{loading ? Array.from({ length: 4 }).map((_, index) => <SkeletonLine key={index} />) : projects.length === 0 ? <div style={{ color: 'var(--text-secondary)', fontSize: '13px', padding: 'var(--space-md) 0' }}> </div> : projects.map((project) => (
<ProjectRow key={project.id} href={`/projects/${project.id}`}>
<SisterAvatar name={project.ownerSister ?? 'narang'} size={32} />
<ProjectDetails>
<ProjectName>{project.name}</ProjectName>
<ProjectDesc>{project.phase} · {project.deployStatus}</ProjectDesc>
</ProjectDetails>
<LabelMeta>{project.progress ?? 0}%</LabelMeta>
</ProjectRow>
))}
</ProjectList>
</section>
<section>
<SectionTitle><span>ACTIVITY FEED</span><LabelMeta>{connected ? 'LIVE' : 'FEED'}</LabelMeta></SectionTitle>
<Timeline>
{loading ? Array.from({ length: 5 }).map((_, index) => <SkeletonLine key={index} />) : activityItems.length === 0 ? <div style={{ color: 'var(--text-secondary)', fontSize: '13px', paddingLeft: 'var(--space-lg)' }}> </div> : activityItems.map((item) => (
<TimelineItem key={item.id}><TimeStamp>{formatTimestamp(item.createdAt)}</TimeStamp><TimelineContent>{item.sister && <strong>{item.sister.name} </strong>}{item.detail ?? item.action}</TimelineContent></TimelineItem>
))}
</Timeline>
</section>
</DataColumns>
</>
);
export default function HomePage() {
return <LiveWorkboard />;
}

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>
)}
</>
);
}

478
frontend/app/rails/page.tsx Normal file
View File

@@ -0,0 +1,478 @@
'use client';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
import {
useRailsSocket,
type RailsPipelineSummary,
type RailsSubTaskNode,
} 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;
flex-direction: column;
gap: 28px;
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 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 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 StartCard = styled.section`
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 16px;
padding: 24px 28px;
display: flex;
flex-direction: column;
gap: 16px;
`;
const StartLabel = styled.div`
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-secondary);
`;
const StartRow = styled.div`
display: grid;
grid-template-columns: minmax(180px, 240px) 1fr auto;
gap: 12px;
@media (max-width: 700px) {
grid-template-columns: 1fr;
}
`;
const Input = styled.input`
padding: 12px 16px;
background: var(--bg-surface);
border: 1px solid var(--border-color);
color: var(--text-primary);
border-radius: 10px;
font-size: 14px;
font-family: var(--font-sans);
&::placeholder {
color: var(--text-secondary);
}
&:focus {
outline: none;
border-color: #5fafff;
box-shadow: 0 0 0 3px rgba(95, 175, 255, 0.15);
}
`;
const StartButton = styled.button`
padding: 12px 28px;
background: #5fafff;
color: #0a0a0a;
border: none;
border-radius: 10px;
font-weight: 700;
font-size: 14px;
cursor: pointer;
transition: opacity 0.15s;
&:hover {
opacity: 0.85;
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
}
`;
const Layout = styled.div`
display: grid;
grid-template-columns: minmax(360px, 440px) 1fr;
gap: 24px;
@media (max-width: 1100px) {
grid-template-columns: 1fr;
}
`;
const Pane = styled.section`
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 16px;
padding: 24px 28px;
display: flex;
flex-direction: column;
gap: 18px;
min-height: 420px;
`;
const PaneHeader = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
padding-bottom: 14px;
border-bottom: 1px solid var(--border-color);
`;
const PaneTitle = styled.h2`
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-secondary);
margin: 0;
`;
const Counter = styled.span`
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
`;
const PipelineList = styled.div`
display: flex;
flex-direction: column;
gap: 12px;
`;
const PipelineCard = styled.button<{ $selected: boolean; $state: string }>`
display: flex;
flex-direction: column;
gap: 8px;
padding: 18px 20px;
background: ${({ $selected }) =>
$selected ? 'var(--bg-surface)' : 'transparent'};
border: 1px solid ${({ $selected }) =>
$selected ? '#5fafff' : 'var(--border-color)'};
border-radius: 12px;
cursor: pointer;
text-align: left;
color: var(--text-primary);
transition: all 0.15s;
&:hover {
border-color: #5fafff;
background: var(--bg-surface);
}
`;
const CardTop = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
`;
const ProjectName = styled.span`
font-size: 15px;
font-weight: 700;
letter-spacing: -0.01em;
`;
const StateBadge = styled.span<{ $state: string }>`
padding: 4px 12px;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
border-radius: 20px;
color: #fff;
background: ${({ $state }) => stateBg($state)};
letter-spacing: 0.04em;
flex-shrink: 0;
`;
const CardMeta = styled.div`
display: flex;
gap: 12px;
font-size: 11px;
color: var(--text-secondary);
font-family: var(--font-mono);
`;
const Empty = styled.div`
padding: 60px 20px;
text-align: center;
color: var(--text-secondary);
font-size: 13px;
`;
const DetailHeader = styled.div`
display: flex;
flex-direction: column;
gap: 8px;
padding-bottom: 18px;
border-bottom: 1px solid var(--border-color);
`;
const DetailTitle = styled.h3`
font-size: 22px;
font-weight: 700;
margin: 0;
letter-spacing: -0.01em;
`;
const DetailMeta = styled.div`
display: flex;
gap: 18px;
font-size: 12px;
color: var(--text-secondary);
font-family: var(--font-mono);
`;
function stateBg(state: string): string {
switch (state) {
case 'done':
return '#22c55e';
case 'escalated':
return '#ef4444';
case 'aborted':
return '#525252';
case 'planning':
case 'implementing':
case 'reviewing':
case 'deploying':
return '#f97316';
default:
return '#525252';
}
}
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 RailsPage() {
const [pipelines, setPipelines] = useState<RailsPipelineSummary[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [tree, setTree] = useState<RailsSubTaskNode[]>([]);
const [projectInput, setProjectInput] = useState('');
const [reqInput, setReqInput] = useState('');
const [starting, setStarting] = useState(false);
const [detailNodeId, setDetailNodeId] = useState<string | null>(null);
const { connected } = useRailsSocket({
onPipelinesSnapshot: (next) => {
setPipelines(next);
setSelectedId((prev) => prev ?? (next[0]?.id ?? null));
},
onSubTasksUpdated: (pipelineId, nextTree) => {
setSelectedId((prev) => {
if (pipelineId === prev) setTree(nextTree);
return prev;
});
},
});
useEffect(() => {
fetch(`${API_URL}/api/rails/pipelines`, { credentials: 'include' })
.then((r) => r.json())
.then((data: { pipelines: RailsPipelineSummary[] }) => {
setPipelines(data.pipelines);
if (data.pipelines.length > 0) setSelectedId(data.pipelines[0]!.id);
})
.catch(() => undefined);
}, []);
useEffect(() => {
if (!selectedId) return;
fetch(`${API_URL}/api/rails/pipelines/${selectedId}/sub-tasks`, {
credentials: 'include',
})
.then((r) => r.json())
.then((data: { tree: RailsSubTaskNode[] }) => setTree(data.tree))
.catch(() => setTree([]));
}, [selectedId]);
const handleStart = useCallback(async () => {
if (!projectInput.trim()) return;
setStarting(true);
try {
const res = await fetch(`${API_URL}/api/rails/pipelines/start`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
project: projectInput.trim(),
requirements: reqInput.trim(),
}),
});
if (res.ok) {
const data = (await res.json()) as { pipelineId: string };
setSelectedId(data.pipelineId);
setProjectInput('');
setReqInput('');
}
} finally {
setStarting(false);
}
}, [projectInput, reqInput]);
const selected = useMemo(
() => pipelines.find((p) => p.id === selectedId) ?? null,
[pipelines, selectedId],
);
return (
<Page>
<Header>
<TitleBlock>
<Title>Rails Orchestrator</Title>
<Subtitle> 4 </Subtitle>
</TitleBlock>
<Live $on={connected}>{connected ? 'LIVE' : 'OFFLINE'}</Live>
</Header>
<StartCard>
<StartLabel> </StartLabel>
<StartRow>
<Input
placeholder="프로젝트 이름"
value={projectInput}
onChange={(e) => setProjectInput(e.target.value)}
/>
<Input
placeholder="요구사항 (예: TODO 앱 MVP, 로그인 추가)"
value={reqInput}
onChange={(e) => setReqInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void handleStart();
}}
/>
<StartButton
disabled={starting || !projectInput.trim()}
onClick={handleStart}
>
{starting ? '시작 중...' : 'Start'}
</StartButton>
</StartRow>
</StartCard>
<Layout>
<Pane>
<PaneHeader>
<PaneTitle>Pipelines</PaneTitle>
<Counter>{pipelines.length}</Counter>
</PaneHeader>
{pipelines.length === 0 ? (
<Empty> . .</Empty>
) : (
<PipelineList>
{pipelines.map((p) => (
<PipelineCard
key={p.id}
$selected={p.id === selectedId}
$state={p.currentState}
onClick={() => setSelectedId(p.id)}
>
<CardTop>
<ProjectName>{p.projectName}</ProjectName>
<StateBadge $state={p.currentState}>
{p.currentState}
</StateBadge>
</CardTop>
<CardMeta>
<span>{p.id.slice(0, 12)}</span>
<span>·</span>
<span>{relTime(p.updatedAt)}</span>
</CardMeta>
</PipelineCard>
))}
</PipelineList>
)}
</Pane>
<Pane>
{selected ? (
<>
<DetailHeader>
<PaneTitle>Pipeline Detail</PaneTitle>
<DetailTitle>{selected.projectName}</DetailTitle>
<DetailMeta>
<span>{selected.id}</span>
<span>state: {selected.currentState}</span>
<span>{new Date(selected.createdAt).toLocaleString('ko-KR')}</span>
</DetailMeta>
</DetailHeader>
{tree.length > 0 ? (
<SubTaskTree tree={tree} onSelectNode={setDetailNodeId} />
) : (
<Empty> sub-task .</Empty>
)}
<TransitionsTimeline pipelineId={selected.id} />
</>
) : (
<Empty> .</Empty>
)}
</Pane>
</Layout>
{detailNodeId && (
<SubTaskDetailDrawer
subTaskId={detailNodeId}
onClose={() => setDetailNodeId(null)}
/>
)}
</Page>
);
}

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,13 +7,10 @@ import { usePathname } from 'next/navigation';
import { useAuth } from '@/lib/AuthContext';
const NAV_ITEMS = [
{ href: '/', label: '대시' },
{ href: '/projects', label: '프로' },
{ href: '/activities', label: '활동' },
{ href: '/sisters', label: '자매' },
{ href: '/org', label: '조직' },
{ href: '/settings', label: '설정' },
{ href: '/admin', label: '관리' },
{ href: '/', label: '🟠 Live' },
{ href: '/control', label: '🧭 Control' },
{ href: '/rails', label: '🚦 레일' },
{ href: '/settings', label: '⚙️ 설정' },
];
const SidebarWrapper = styled.aside`

View File

@@ -46,10 +46,10 @@ interface SisterAvatarProps {
}
export default function SisterAvatar({ name, size = 32, className, style }: SisterAvatarProps) {
const [failed, setFailed] = useState(false);
const [failedFor, setFailedFor] = useState<string | null>(null);
const initial = SISTER_INITIALS[name] ?? name.slice(0, 1).toUpperCase();
if (failed) {
if (failedFor === name) {
return <Fallback $size={size} className={className} style={style}>{initial}</Fallback>;
}
@@ -60,7 +60,7 @@ export default function SisterAvatar({ name, size = 32, className, style }: Sist
alt={name}
className={className}
style={style}
onError={() => setFailed(true)}
onError={() => setFailedFor(name)}
/>
);
}

View File

@@ -0,0 +1,295 @@
'use client';
import React from 'react';
import styled, { keyframes } from 'styled-components';
export interface PipelineNode {
id: string;
label: string;
role: string;
state: 'idle' | 'active' | 'review' | 'blocked' | 'ready';
detail: string;
}
interface ActivePipelineProps {
activeTask: string;
focus: string;
reviewLoopCount: number;
escalationCount: number;
deployState: string;
nodes: PipelineNode[];
}
const flow = keyframes`
0% { transform: translateX(0); opacity: 0.15; }
40% { opacity: 0.8; }
100% { transform: translateX(20px); opacity: 0; }
`;
const PipelineCard = styled.section`
border: 1px solid var(--border-color);
background: var(--bg-surface);
padding: var(--space-lg);
display: flex;
flex-direction: column;
gap: var(--space-lg);
`;
const Header = styled.div`
display: flex;
justify-content: space-between;
gap: var(--space-md);
align-items: flex-start;
flex-wrap: wrap;
`;
const Eyebrow = styled.div`
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const Title = styled.h2`
font-size: 24px;
font-weight: 600;
color: var(--text-primary);
letter-spacing: -0.02em;
margin-top: 6px;
`;
const Summary = styled.p`
font-size: 13px;
color: var(--text-secondary);
line-height: 1.6;
max-width: 780px;
text-transform: uppercase;
`;
const HeaderStats = styled.div`
display: grid;
grid-template-columns: repeat(3, minmax(110px, 1fr));
gap: var(--space-sm);
@media (max-width: 767px) {
width: 100%;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
`;
const StatBox = styled.div`
border: 1px solid var(--border-color);
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
`;
const StatLabel = styled.span`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const StatValue = styled.span`
font-size: 15px;
color: var(--text-primary);
font-weight: 600;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const FlowMap = styled.div`
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 14px;
align-items: stretch;
@media (max-width: 1199px) {
grid-template-columns: 1fr;
}
`;
const NodeWrap = styled.div`
display: flex;
align-items: center;
gap: 10px;
@media (max-width: 1199px) {
flex-direction: column;
align-items: stretch;
}
`;
const Connector = styled.div<{ $active?: boolean }>`
flex: 1;
min-width: 36px;
height: 1px;
background: ${({ $active }) => ($active ? 'rgba(245,245,245,0.45)' : 'var(--border-color)')};
position: relative;
overflow: hidden;
&::after {
content: '';
position: absolute;
top: -2px;
left: -18px;
width: 18px;
height: 5px;
background: ${({ $active }) => ($active ? 'rgba(245,245,245,0.85)' : 'transparent')};
animation: ${({ $active }) => ($active ? flow : 'none')} 1.6s linear infinite;
}
@media (max-width: 1199px) {
width: 1px;
height: 24px;
min-width: 1px;
margin: 0 auto;
&::after {
top: -8px;
left: -2px;
width: 5px;
height: 10px;
animation: none;
}
}
`;
const stateBorder: Record<PipelineNode['state'], string> = {
idle: 'var(--border-color)',
active: '#6fc3ff',
review: '#ff7ac6',
blocked: '#ff8d7a',
ready: '#8dffb2',
};
const stateText: Record<PipelineNode['state'], string> = {
idle: 'IDLE',
active: 'ACTIVE',
review: 'REVIEW',
blocked: 'BLOCKED',
ready: 'READY',
};
const NodeCard = styled.div<{ $state: PipelineNode['state'] }>`
border: 1px solid ${({ $state }) => stateBorder[$state]};
padding: 14px;
display: flex;
flex-direction: column;
gap: 10px;
min-height: 148px;
background: linear-gradient(180deg, rgba(255,255,255,0.015) 0%, rgba(255,255,255,0) 100%);
`;
const NodeTop = styled.div`
display: flex;
justify-content: space-between;
gap: var(--space-sm);
align-items: flex-start;
`;
const NodeLabel = styled.div`
display: flex;
flex-direction: column;
gap: 4px;
`;
const NodeName = styled.div`
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
`;
const NodeRole = styled.div`
font-size: 12px;
color: var(--text-secondary);
`;
const StateBadge = styled.span<{ $state: PipelineNode['state'] }>`
font-family: var(--font-mono);
font-size: 10px;
color: ${({ $state }) => stateBorder[$state]};
border: 1px solid ${({ $state }) => stateBorder[$state]};
padding: 4px 6px;
text-transform: uppercase;
letter-spacing: 0.08em;
white-space: nowrap;
`;
const NodeDetail = styled.div`
font-size: 13px;
line-height: 1.6;
color: var(--text-primary);
`;
const NodeHint = styled.div`
margin-top: auto;
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
export default function ActivePipeline({
activeTask,
focus,
reviewLoopCount,
escalationCount,
deployState,
nodes,
}: ActivePipelineProps) {
return (
<PipelineCard>
<Header>
<div>
<Eyebrow>Active pipeline / snapshot</Eyebrow>
<Title>{activeTask}</Title>
<Summary>{focus}</Summary>
</div>
<HeaderStats>
<StatBox>
<StatLabel>review loop</StatLabel>
<StatValue>{reviewLoopCount}x</StatValue>
</StatBox>
<StatBox>
<StatLabel>escalations</StatLabel>
<StatValue>{escalationCount}</StatValue>
</StatBox>
<StatBox>
<StatLabel>deploy state</StatLabel>
<StatValue>{deployState}</StatValue>
</StatBox>
</HeaderStats>
</Header>
<FlowMap>
{nodes.map((node, index) => {
const connectorActive = node.state === 'active' || node.state === 'review' || node.state === 'ready';
return (
<NodeWrap key={node.id}>
<NodeCard $state={node.state}>
<NodeTop>
<NodeLabel>
<NodeName>{node.label}</NodeName>
<NodeRole>{node.role}</NodeRole>
</NodeLabel>
<StateBadge $state={node.state}>{stateText[node.state]}</StateBadge>
</NodeTop>
<NodeDetail>{node.detail}</NodeDetail>
<NodeHint>snapshot {String(index + 1).padStart(2, '0')}</NodeHint>
</NodeCard>
{index < nodes.length - 1 && <Connector $active={connectorActive} />}
</NodeWrap>
);
})}
</FlowMap>
</PipelineCard>
);
}

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,136 @@
'use client';
import styled from 'styled-components';
import type { ApprovalItem, WorkflowEvent } from '@/lib/control/types';
const Panel = styled.aside`
display: grid;
gap: 14px;
`;
const Card = styled.section`
border: 1px solid var(--border-color);
border-radius: 22px;
padding: 18px;
background: linear-gradient(180deg, rgba(255,255,255,0.045), rgba(255,255,255,0.018));
`;
const Title = styled.h2`
margin: 0 0 12px;
font-size: 15px;
`;
const Eyebrow = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
margin-bottom: 6px;
`;
const EventTitle = styled.h3`
margin: 0;
font-size: 20px;
line-height: 1.2;
`;
const Detail = styled.p`
margin: 12px 0 0;
color: var(--text-secondary);
font-size: 13px;
`;
const MetaGrid = styled.div`
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 16px;
`;
const Meta = styled.div`
border: 1px solid rgba(255,255,255,0.08);
border-radius: 14px;
padding: 10px;
background: rgba(0,0,0,0.18);
`;
const MetaValue = styled.div`
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-primary);
overflow-wrap: anywhere;
`;
const ApprovalList = styled.div`
display: grid;
gap: 8px;
`;
const ApprovalRow = styled.div<{ $status: ApprovalItem['status'] }>`
display: grid;
grid-template-columns: 42px 1fr auto;
gap: 8px;
align-items: center;
border: 1px solid ${({ $status }) => {
if ($status === 'blocked') return 'rgba(255, 112, 112, 0.42)';
if ($status === 'waiting') return 'rgba(255, 204, 102, 0.38)';
return 'rgba(139, 211, 255, 0.28)';
}};
border-radius: 14px;
padding: 10px;
background: rgba(0,0,0,0.14);
font-size: 12px;
`;
const Risk = styled.span`
font-family: var(--font-mono);
color: var(--text-secondary);
`;
const Status = styled.span`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
`;
export default function ActiveTaskFocus({
selectedEvent,
approvals,
}: {
selectedEvent: WorkflowEvent;
approvals: ApprovalItem[];
}) {
return (
<Panel>
<Card>
<Title>Active Task Focus</Title>
<Eyebrow>{selectedEvent.sister} · {selectedEvent.type}</Eyebrow>
<EventTitle>{selectedEvent.title}</EventTitle>
<Detail>{selectedEvent.detail}</Detail>
<MetaGrid>
<Meta>
<Eyebrow>workflow</Eyebrow>
<MetaValue>{selectedEvent.workflowId}</MetaValue>
</Meta>
<Meta>
<Eyebrow>source</Eyebrow>
<MetaValue>{selectedEvent.source}</MetaValue>
</Meta>
</MetaGrid>
</Card>
<Card>
<Title>Approval / Risk</Title>
<ApprovalList>
{approvals.map((item) => (
<ApprovalRow key={item.id} $status={item.status}>
<Risk>{item.risk}</Risk>
<span>{item.title}</span>
<Status>{item.status}</Status>
</ApprovalRow>
))}
</ApprovalList>
</Card>
</Panel>
);
}

View File

@@ -0,0 +1,223 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import SisterActivityLane from './SisterActivityLane';
import WorkflowTimeline from './WorkflowTimeline';
import ActiveTaskFocus from './ActiveTaskFocus';
import { mockLiveWorkboard, rotateEvents } from '@/lib/control/mock-events';
const Root = styled.div`
display: flex;
flex-direction: column;
gap: var(--space-lg);
`;
const Hero = styled.header`
border: 1px solid rgba(255,255,255,0.12);
border-radius: 28px;
padding: 24px;
background:
radial-gradient(circle at 16% 18%, rgba(255,143,112,0.18), transparent 34%),
radial-gradient(circle at 82% 12%, rgba(139,211,255,0.16), transparent 28%),
linear-gradient(135deg, rgba(255,255,255,0.075), rgba(255,255,255,0.02));
`;
const HeroTop = styled.div`
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
@media (max-width: 767px) {
flex-direction: column;
}
`;
const TitleBlock = styled.div`
display: grid;
gap: 8px;
`;
const Label = styled.div`
font-family: var(--font-mono);
color: var(--text-secondary);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const Title = styled.h1`
margin: 0;
font-size: clamp(30px, 5vw, 58px);
line-height: 0.95;
letter-spacing: -0.055em;
`;
const Summary = styled.p`
margin: 0;
max-width: 760px;
color: var(--text-secondary);
font-size: 14px;
`;
const SourceBadge = styled.div`
display: inline-flex;
align-items: center;
gap: 8px;
border: 1px solid rgba(255, 204, 102, 0.35);
border-radius: 999px;
padding: 8px 12px;
color: #ffcc66;
font-family: var(--font-mono);
font-size: 11px;
white-space: nowrap;
`;
const Dot = styled.span`
width: 7px;
height: 7px;
border-radius: 50%;
background: #ffcc66;
box-shadow: 0 0 18px rgba(255, 204, 102, 0.95);
`;
const PhaseGrid = styled.div`
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 8px;
margin-top: 22px;
@media (max-width: 767px) {
grid-template-columns: 1fr;
}
`;
const PhaseCell = styled.div<{ $active: boolean }>`
border: 1px solid ${({ $active }) => ($active ? 'rgba(255,255,255,0.36)' : 'rgba(255,255,255,0.09)')};
border-radius: 14px;
padding: 10px;
color: ${({ $active }) => ($active ? 'var(--text-primary)' : 'var(--text-secondary)')};
background: ${({ $active }) => ($active ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.16)')};
font-family: var(--font-mono);
font-size: 11px;
`;
const MainGrid = styled.div`
display: grid;
grid-template-columns: minmax(0, 1fr) 360px;
gap: var(--space-lg);
@media (max-width: 1100px) {
grid-template-columns: 1fr;
}
`;
const LanesGrid = styled.section`
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-md);
@media (max-width: 900px) {
grid-template-columns: 1fr;
}
`;
const BottomGrid = styled.div`
display: grid;
grid-template-columns: minmax(0, 1.35fr) minmax(280px, 0.65fr);
gap: var(--space-lg);
@media (max-width: 1100px) {
grid-template-columns: 1fr;
}
`;
const NoteCard = styled.section`
border: 1px solid var(--border-color);
border-radius: 22px;
padding: 18px;
background: rgba(255,255,255,0.025);
`;
const NoteTitle = styled.h2`
margin: 0 0 8px;
font-size: 15px;
`;
const NoteText = styled.p`
margin: 0;
color: var(--text-secondary);
font-size: 13px;
`;
const phases = [
['planning', 'PLAN'],
['building', 'BUILD'],
['reviewing', 'REVIEW'],
['waiting_approval', 'APPROVAL'],
['deploying', 'DEPLOY'],
] as const;
export default function LiveWorkboard() {
const [tick, setTick] = useState(0);
const [selectedId, setSelectedId] = useState(mockLiveWorkboard.events[0]?.id ?? '');
const events = useMemo(() => rotateEvents(mockLiveWorkboard.events, tick), [tick]);
const selected = events.find((event) => event.id === selectedId) ?? events[0];
useEffect(() => {
const timer = window.setInterval(() => {
setTick((value) => value + 1);
}, 4200);
return () => window.clearInterval(timer);
}, []);
return (
<Root>
<Hero>
<HeroTop>
<TitleBlock>
<Label>4 Sisters Live Workboard</Label>
<Title> 4 </Title>
<Summary>{mockLiveWorkboard.workflow.summary}</Summary>
</TitleBlock>
<SourceBadge aria-label="data source mock">
<Dot /> source: {mockLiveWorkboard.source} · v0
</SourceBadge>
</HeroTop>
<PhaseGrid>
{phases.map(([phase, label]) => (
<PhaseCell key={phase} $active={mockLiveWorkboard.workflow.phase === phase}>
{label}
</PhaseCell>
))}
</PhaseGrid>
</Hero>
<MainGrid>
<LanesGrid>
{mockLiveWorkboard.sisters.map((lane) => (
<SisterActivityLane key={lane.id} lane={lane} />
))}
</LanesGrid>
<ActiveTaskFocus selectedEvent={selected} approvals={mockLiveWorkboard.approvals} />
</MainGrid>
<BottomGrid>
<WorkflowTimeline
events={events}
selectedId={selected.id}
onSelect={(event) => setSelectedId(event.id)}
/>
<NoteCard>
<NoteTitle>v0 </NoteTitle>
<NoteText>
mock event stream이야. 4 . Socket.IO live event와 `/control/summary` .
</NoteText>
</NoteCard>
</BottomGrid>
</Root>
);
}

View File

@@ -0,0 +1,149 @@
'use client';
import styled, { keyframes } from 'styled-components';
import type { SisterLaneState } from '@/lib/control/types';
const pulse = keyframes`
0%, 100% { box-shadow: 0 0 0 rgba(255, 255, 255, 0); }
50% { box-shadow: 0 0 24px rgba(255, 255, 255, 0.08); }
`;
const LaneCard = styled.article<{ $color: string; $active: boolean }>`
position: relative;
min-height: 258px;
border: 1px solid color-mix(in srgb, ${({ $color }) => $color} 42%, var(--border-color));
border-radius: 22px;
padding: 18px;
overflow: hidden;
background:
radial-gradient(circle at top right, color-mix(in srgb, ${({ $color }) => $color} 18%, transparent), transparent 34%),
linear-gradient(180deg, rgba(255,255,255,0.045), rgba(255,255,255,0.015));
animation: ${({ $active }) => ($active ? pulse : 'none')} 2.8s ease-in-out infinite;
`;
const TopRow = styled.div`
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 18px;
`;
const Identity = styled.div`
display: flex;
flex-direction: column;
gap: 4px;
`;
const Name = styled.h3`
margin: 0;
font-size: 18px;
letter-spacing: -0.02em;
`;
const Role = styled.span`
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
`;
const StatusPill = styled.span<{ $color: string }>`
border: 1px solid color-mix(in srgb, ${({ $color }) => $color} 56%, var(--border-color));
color: ${({ $color }) => $color};
border-radius: 999px;
padding: 5px 9px;
font-family: var(--font-mono);
font-size: 10px;
background: rgba(0, 0, 0, 0.22);
`;
const TaskBlock = styled.div`
display: grid;
gap: 12px;
`;
const Label = styled.div`
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-secondary);
font-family: var(--font-mono);
margin-bottom: 4px;
`;
const Body = styled.p`
margin: 0;
font-size: 14px;
color: var(--text-primary);
`;
const Muted = styled.p`
margin: 0;
font-size: 12px;
color: var(--text-secondary);
`;
const ProgressTrack = styled.div`
height: 7px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
overflow: hidden;
margin-top: 16px;
`;
const ProgressFill = styled.div<{ $progress: number; $color: string }>`
width: ${({ $progress }) => $progress}%;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, ${({ $color }) => $color}, color-mix(in srgb, ${({ $color }) => $color} 54%, white));
`;
const MetaRow = styled.div`
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 10px;
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
`;
export default function SisterActivityLane({ lane }: { lane: SisterLaneState }) {
const active = lane.status === 'working' || lane.status === 'thinking' || lane.status === 'reviewing';
return (
<LaneCard $color={lane.color} $active={active}>
<TopRow>
<Identity>
<Name>{lane.name}</Name>
<Role>{lane.role} · {lane.mode}</Role>
</Identity>
<StatusPill $color={lane.color}>{lane.status}</StatusPill>
</TopRow>
<TaskBlock>
<div>
<Label>Current task</Label>
<Body>{lane.currentTask}</Body>
</div>
<div>
<Label>Last event</Label>
<Muted>{lane.lastEvent}</Muted>
</div>
<div>
<Label>Next handoff</Label>
<Muted>{lane.nextHandoff}</Muted>
</div>
</TaskBlock>
<ProgressTrack aria-label={`${lane.name} progress`}>
<ProgressFill $progress={lane.progress} $color={lane.color} />
</ProgressTrack>
<MetaRow>
<span>{lane.phase}</span>
<span>{lane.progress}%</span>
</MetaRow>
</LaneCard>
);
}

View File

@@ -0,0 +1,123 @@
'use client';
import styled from 'styled-components';
import type { WorkflowEvent } from '@/lib/control/types';
const TimelineRoot = styled.section`
border: 1px solid var(--border-color);
border-radius: 22px;
background: rgba(255, 255, 255, 0.025);
padding: 18px;
`;
const Header = styled.div`
display: flex;
justify-content: space-between;
gap: 12px;
align-items: center;
margin-bottom: 14px;
`;
const Title = styled.h2`
font-size: 15px;
margin: 0;
`;
const LiveBadge = styled.span`
font-family: var(--font-mono);
font-size: 10px;
color: #ffcc66;
border: 1px solid rgba(255, 204, 102, 0.35);
border-radius: 999px;
padding: 4px 8px;
`;
const EventList = styled.ol`
list-style: none;
display: grid;
gap: 10px;
`;
const EventItem = styled.li<{ $selected: boolean }>`
display: grid;
grid-template-columns: 54px 1fr;
gap: 12px;
padding: 12px;
border-radius: 16px;
border: 1px solid ${({ $selected }) => ($selected ? 'rgba(255,255,255,0.34)' : 'rgba(255,255,255,0.08)')};
background: ${({ $selected }) => ($selected ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.16)')};
cursor: pointer;
transition: border-color .15s ease, background .15s ease;
&:hover {
border-color: rgba(255,255,255,0.26);
}
`;
const EventTime = styled.div`
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
`;
const EventBody = styled.div`
min-width: 0;
`;
const EventTitle = styled.div`
display: flex;
justify-content: space-between;
gap: 8px;
font-size: 13px;
font-weight: 700;
`;
const EventDetail = styled.p`
margin: 5px 0 0;
color: var(--text-secondary);
font-size: 12px;
`;
const TypeBadge = styled.span`
flex-shrink: 0;
font-family: var(--font-mono);
font-size: 9px;
color: var(--text-secondary);
`;
export default function WorkflowTimeline({
events,
selectedId,
onSelect,
}: {
events: WorkflowEvent[];
selectedId: string;
onSelect: (event: WorkflowEvent) => void;
}) {
return (
<TimelineRoot>
<Header>
<Title>Workflow Timeline</Title>
<LiveBadge>mock stream</LiveBadge>
</Header>
<EventList>
{events.map((event) => (
<EventItem
key={event.id}
$selected={event.id === selectedId}
onClick={() => onSelect(event)}
>
<EventTime>{event.at}</EventTime>
<EventBody>
<EventTitle>
<span>{event.title}</span>
<TypeBadge>{event.type}</TypeBadge>
</EventTitle>
<EventDetail>{event.detail}</EventDetail>
</EventBody>
</EventItem>
))}
</EventList>
</TimelineRoot>
);
}

View File

@@ -0,0 +1,452 @@
'use client';
import React, { useState, useMemo } from 'react';
import styled, { keyframes } from 'styled-components';
import { API_URL } from '@/lib/config';
import SisterDetailPanel from './SisterDetailPanel';
/**
* Photo-first virtual office.
*
* Pixel art proved too low-resolution to capture the actual sister
* illustrations. Instead the office is a stylized CSS/SVG room and each
* sister is a circular portrait of her real avatar (served by the
* backend at /api/sisters/{name}/avatar) sitting at her desk.
*
* The layout is a simple 2x2 grid:
*
* 하랑 (plan) 나랑 (implement)
* ┌────────┐
* │ 회의실 │
* └────────┘
* 다랑 (review) 이랑 (deploy)
*
* Each sister card has:
* - circular portrait
* - korean name + role
* - status dot
* - active stage = glowing pulse ring
* - clickable → opens detail panel
*/
interface Sister {
key: string;
nameKR: string;
role: string;
stage: 'plan' | 'implement' | 'review' | 'deploy';
accent: string; // sister-specific accent color (matches the actual illustration)
}
const SISTERS: Sister[] = [
{ key: 'harang', nameKR: '하랑이', role: '기획', stage: 'plan', accent: '#5fafff' },
{ key: 'narang', nameKR: '나랑이', role: '구현', stage: 'implement', accent: '#37c4d4' },
{ key: 'darang', nameKR: '다랑이', role: '검토', stage: 'review', accent: '#e84848' },
{ key: 'erang', nameKR: '이랑이', role: '배포', stage: 'deploy', accent: '#9b8df0' },
];
interface OfficeRoomProps {
/** Currently active stage from any running pipeline (highlights one sister). */
activeStage?: 'plan' | 'implement' | 'review' | 'deploy' | null;
}
export default function OfficeRoom({ activeStage }: OfficeRoomProps) {
const [selected, setSelected] = useState<string | null>(null);
const handleClick = (key: string) => {
setSelected((prev) => (prev === key ? null : key));
};
return (
<Layout>
<RoomCard>
<RoomHeader>
<RoomTitle>🏢 </RoomTitle>
<RoomSub>4 SISTERS · LIVE</RoomSub>
</RoomHeader>
<Floor>
<RoomDecor />
{SISTERS.map((s, idx) => (
<DeskWrap key={s.key} $position={idx}>
<DeskBack />
<SisterCard
$accent={s.accent}
$active={activeStage === s.stage}
$selected={selected === s.key}
onClick={() => handleClick(s.key)}
>
{activeStage === s.stage && <PulseRing $accent={s.accent} />}
<Portrait
src={`${API_URL}/api/sisters/${s.key}/avatar`}
alt={s.nameKR}
$accent={s.accent}
/>
<NameRow>
<SisterName>{s.nameKR}</SisterName>
<RoleTag $accent={s.accent}>{s.role}</RoleTag>
</NameRow>
<StatusDot $active={activeStage === s.stage} $accent={s.accent} />
</SisterCard>
</DeskWrap>
))}
<MeetingRoom>
<MeetingLabel></MeetingLabel>
</MeetingRoom>
{/* Stage flow arrows (top→right→bottom→left, plan→impl→review→deploy) */}
<FlowSvg viewBox="0 0 100 100" preserveAspectRatio="none">
<defs>
<marker
id="arrow"
viewBox="0 0 10 10"
refX="6"
refY="5"
markerWidth="6"
markerHeight="6"
orient="auto"
>
<path d="M0,0 L10,5 L0,10 z" fill="#5fafff" opacity="0.55" />
</marker>
</defs>
{/* harang → narang (top horizontal) */}
<line
x1="35" y1="22" x2="65" y2="22"
stroke="#5fafff" strokeWidth="0.4" strokeDasharray="1.5 1.5"
markerEnd="url(#arrow)" opacity={activeStage === 'plan' || activeStage === 'implement' ? 0.85 : 0.25}
/>
{/* narang → darang (right vertical → cross to bottom-right? we draw a curve) */}
<line
x1="78" y1="35" x2="78" y2="65"
stroke="#5fafff" strokeWidth="0.4" strokeDasharray="1.5 1.5"
markerEnd="url(#arrow)" opacity={activeStage === 'implement' || activeStage === 'review' ? 0.85 : 0.25}
/>
{/* darang → erang? Actually deploy is below right; review→deploy is bottom horizontal reversed. Use bottom row left direction */}
<line
x1="65" y1="78" x2="35" y2="78"
stroke="#5fafff" strokeWidth="0.4" strokeDasharray="1.5 1.5"
markerEnd="url(#arrow)" opacity={activeStage === 'review' || activeStage === 'deploy' ? 0.85 : 0.25}
/>
{/* erang → harang? Pipeline ends at deploy. Skip return arrow. */}
</FlowSvg>
</Floor>
<Hint> · {activeStage ? `현재 ${activeStage} 단계 진행 중` : 'idle'}</Hint>
</RoomCard>
<PanelCol>
{selected ? (
<SisterDetailPanel
name={selected}
onClose={() => setSelected(null)}
/>
) : (
<PanelEmpty>
👀 <br />
</PanelEmpty>
)}
</PanelCol>
</Layout>
);
}
// ───────────────────────── styled ─────────────────────────
const pulse = keyframes`
0%, 100% { transform: scale(1); opacity: 0.6; }
50% { transform: scale(1.15); opacity: 0.0; }
`;
const dotPulse = keyframes`
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
`;
const Layout = styled.div`
display: grid;
grid-template-columns: minmax(0, 1fr) 320px;
gap: 16px;
width: 100%;
@media (max-width: 1024px) {
grid-template-columns: 1fr;
}
`;
const RoomCard = styled.section`
position: relative;
background: linear-gradient(160deg, #1a1f2e 0%, #0e1118 100%);
border: 1px solid var(--border-color);
border-radius: 18px;
overflow: hidden;
display: flex;
flex-direction: column;
min-height: 620px;
`;
const RoomHeader = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 18px 24px;
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
`;
const RoomTitle = styled.h2`
margin: 0;
font-size: 16px;
font-weight: 700;
color: var(--text-primary);
`;
const RoomSub = styled.span`
font-family: var(--font-mono);
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--text-secondary);
`;
const Floor = styled.div`
position: relative;
flex: 1;
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 0;
padding: 36px;
min-height: 520px;
`;
/**
* Background decoration: subtle isometric grid lines + carpet circle.
* Pure CSS — no images.
*/
const RoomDecor = styled.div`
position: absolute;
inset: 16px;
pointer-events: none;
background-image:
linear-gradient(rgba(255, 255, 255, 0.04) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.04) 1px, transparent 1px);
background-size: 32px 32px;
border: 1px dashed rgba(255, 255, 255, 0.06);
border-radius: 12px;
&::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
transform: translate(-50%, -50%);
background: radial-gradient(circle, rgba(95, 175, 255, 0.05) 0%, transparent 70%);
border-radius: 50%;
}
`;
const FlowSvg = styled.svg`
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
`;
const DeskWrap = styled.div<{ $position: number }>`
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 2;
gap: 8px;
${({ $position }) => {
switch ($position) {
case 0: return 'justify-self: start; align-self: start; padding-top: 12px;';
case 1: return 'justify-self: end; align-self: start; padding-top: 12px;';
case 2: return 'justify-self: start; align-self: end; padding-bottom: 12px;';
case 3: return 'justify-self: end; align-self: end; padding-bottom: 12px;';
default: return '';
}
}}
`;
/** Simple "desk" silhouette under the sister card. */
const DeskBack = styled.div`
position: absolute;
bottom: -2px;
left: 50%;
transform: translateX(-50%);
width: 130px;
height: 24px;
background: linear-gradient(180deg, #4a3520 0%, #2a1d10 100%);
border-radius: 4px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
z-index: -1;
&::before {
content: '';
position: absolute;
top: -8px;
left: 50%;
transform: translateX(-50%);
width: 40px;
height: 8px;
background: #1a3654;
border: 1px solid #0a1a2c;
border-radius: 2px 2px 0 0;
}
`;
interface SisterCardProps {
$accent: string;
$active: boolean;
$selected: boolean;
}
const SisterCard = styled.button<SisterCardProps>`
position: relative;
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
padding: 10px 14px 12px;
background: ${({ $selected }) =>
$selected ? 'rgba(255, 255, 255, 0.08)' : 'rgba(255, 255, 255, 0.04)'};
border: 1px solid
${({ $accent, $selected }) => ($selected ? $accent : 'rgba(255, 255, 255, 0.1)')};
border-radius: 12px;
cursor: pointer;
font-family: inherit;
transition: transform 0.15s ease, border-color 0.15s ease, background 0.15s ease;
&:hover {
transform: translateY(-2px);
border-color: ${({ $accent }) => $accent};
background: rgba(255, 255, 255, 0.08);
}
`;
const PulseRing = styled.span<{ $accent: string }>`
position: absolute;
top: 6px;
left: 50%;
transform: translateX(-50%);
width: 80px;
height: 80px;
border-radius: 50%;
border: 2px solid ${({ $accent }) => $accent};
animation: ${pulse} 1.6s ease-out infinite;
pointer-events: none;
`;
const Portrait = styled.img<{ $accent: string }>`
width: 72px;
height: 72px;
border-radius: 50%;
border: 3px solid ${({ $accent }) => $accent};
background: #111;
object-fit: cover;
box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.4),
0 4px 16px rgba(0, 0, 0, 0.5);
`;
const NameRow = styled.div`
display: flex;
align-items: center;
gap: 8px;
`;
const SisterName = styled.span`
font-size: 13px;
font-weight: 700;
color: var(--text-primary);
`;
const RoleTag = styled.span<{ $accent: string }>`
font-family: var(--font-mono);
font-size: 9px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
padding: 2px 7px;
border-radius: 8px;
color: ${({ $accent }) => $accent};
border: 1px solid ${({ $accent }) => $accent};
background: rgba(0, 0, 0, 0.3);
`;
const StatusDot = styled.span<{ $active: boolean; $accent: string }>`
position: absolute;
top: 8px;
right: 8px;
width: 8px;
height: 8px;
border-radius: 50%;
background: ${({ $active, $accent }) => ($active ? $accent : '#3a3a44')};
box-shadow: ${({ $active, $accent }) =>
$active ? `0 0 8px ${$accent}` : 'none'};
animation: ${({ $active }) => ($active ? dotPulse : 'none')} 1.6s ease-in-out
infinite;
`;
const MeetingRoom = styled.div`
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 110px;
height: 70px;
background: linear-gradient(180deg, rgba(95, 175, 255, 0.08) 0%, rgba(95, 175, 255, 0.02) 100%);
border: 1px solid rgba(95, 175, 255, 0.25);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
z-index: 1;
pointer-events: none;
`;
const MeetingLabel = styled.span`
font-family: var(--font-mono);
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: rgba(95, 175, 255, 0.7);
`;
const Hint = styled.div`
text-align: center;
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
padding: 12px 20px;
border-top: 1px solid rgba(255, 255, 255, 0.06);
`;
const PanelCol = styled.aside`
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 18px;
padding: 20px;
display: flex;
flex-direction: column;
gap: 14px;
min-height: 620px;
`;
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.7;
`;

View File

@@ -0,0 +1,231 @@
'use client';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
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_DESC: Record<string, string> = {
harang:
'프로젝트 요구사항에서 MVP 범위와 통과 기준을 결정한다. rails 파이프라인의 첫 단계.',
narang:
'하랑이의 기획을 받아 코드/파일을 직접 생성하고 git push 까지 진행한다.',
darang:
'narang 의 구현물을 review. APPROVE / REQUEST_CHANGES / ABORT 중 하나를 결정.',
erang:
'darang 통과 후 산출물을 배포 검증한다. 마지막 단계, DEPLOY_DONE / DEPLOY_FAILED.',
};
const SISTER_ACCENT: Record<string, string> = {
harang: '#5fafff',
narang: '#37c4d4',
darang: '#e84848',
erang: '#9b8df0',
};
const Header = styled.div`
display: flex;
align-items: center;
gap: 14px;
`;
const PortraitLg = styled.img<{ $accent: string }>`
width: 64px;
height: 64px;
border-radius: 50%;
border: 3px solid ${({ $accent }) => $accent};
background: #111;
object-fit: cover;
flex-shrink: 0;
`;
const NameRow = styled.div`
flex: 1;
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
`;
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;
flex-shrink: 0;
&: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';
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);
setInfo(null);
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]);
const accent = SISTER_ACCENT[name] ?? '#5fafff';
return (
<>
<Header>
<PortraitLg
src={`${API_URL}/api/sisters/${name}/avatar`}
alt={name}
$accent={accent}
/>
<NameRow>
<NameKR>{SISTER_KOREAN[name] ?? name}</NameKR>
<RoleLabel>{SISTER_ROLE[name] ?? 'unknown'}</RoleLabel>
</NameRow>
<CloseBtn onClick={onClose}></CloseBtn>
</Header>
<Section>
<SectionLabel></SectionLabel>
<SectionBody>{SISTER_DESC[name] ?? '—'}</SectionBody>
</Section>
<Section>
<SectionLabel></SectionLabel>
<SectionBody>
<StatusDot $status={info?.status ?? 'unknown'} />
{loading ? '확인 중...' : 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,647 @@
'use client';
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import styled, { keyframes } from 'styled-components';
import SisterAvatar from '@/components/common/SisterAvatar';
import { API_URL } from '@/lib/config';
import { withSessionRequest } from '@/lib/csrf';
import type { SisterName, AgentState } from './OfficeScene';
interface RuntimeMessage {
id: string;
role: 'user' | 'assistant' | 'tool';
content: string;
ts: string | null;
}
interface RuntimeSnapshot {
name: SisterName;
gatewayConnected: boolean;
mainState: AgentState;
currentTask: string | null;
activeSessionLabel: string | null;
recentMessages: RuntimeMessage[];
}
interface ChatMessage {
id: string;
role: 'user' | 'assistant' | 'tool';
content: string;
toolName?: string;
ts: string;
}
interface ChatWorkspaceProps {
initialSister: SisterName;
onClose: () => void;
}
const SISTER_DISPLAY: Record<SisterName, string> = {
harang: '하랑이',
narang: '나랑이',
darang: '다랑이',
erang: '이랑이',
};
const SISTER_ROLES: Record<SisterName, string> = {
harang: 'Planning & Orchestration',
narang: 'Development & Implementation',
darang: 'QA & Review',
erang: 'Infra & Deploy',
};
const SISTER_ORDER: SisterName[] = ['harang', 'narang', 'darang', 'erang'];
const fadeIn = keyframes`
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
`;
const Workspace = styled.div`
display: flex;
height: 100%;
border: 1px solid var(--border-color);
background: var(--bg-surface);
overflow: hidden;
@media (max-width: 767px) {
flex-direction: column;
}
`;
const SisterTabs = styled.nav`
width: 200px;
flex-shrink: 0;
border-right: 1px solid var(--border-color);
display: flex;
flex-direction: column;
padding: var(--space-md) 0;
@media (max-width: 767px) {
width: 100%;
flex-direction: row;
padding: 0;
overflow-x: auto;
border-right: none;
border-bottom: 1px solid var(--border-color);
}
`;
const SisterTabHeader = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 0 var(--space-md) var(--space-md);
@media (max-width: 767px) {
display: none;
}
`;
const SisterTab = styled.button<{ $active: boolean }>`
display: flex;
align-items: center;
gap: var(--space-sm);
padding: var(--space-sm) var(--space-md);
background: ${({ $active }) => ($active ? 'rgba(255,255,255,0.04)' : 'transparent')};
border: none;
border-left: 2px solid ${({ $active }) => ($active ? 'var(--text-primary)' : 'transparent')};
color: ${({ $active }) => ($active ? 'var(--text-primary)' : 'var(--text-secondary)')};
cursor: pointer;
text-align: left;
width: 100%;
transition: all 0.15s;
font-family: inherit;
&:hover {
color: var(--text-primary);
background: rgba(255,255,255,0.03);
}
@media (max-width: 767px) {
border-left: none;
border-bottom: 2px solid ${({ $active }) => ($active ? 'var(--text-primary)' : 'transparent')};
white-space: nowrap;
flex-shrink: 0;
padding: var(--space-xs) var(--space-sm);
gap: 4px;
}
`;
const TabMeta = styled.div`
display: flex;
flex-direction: column;
gap: 2px;
`;
const TabName = styled.div`
font-size: 13px;
font-weight: 600;
`;
const TabRole = styled.div`
font-size: 10px;
color: var(--text-secondary);
@media (max-width: 767px) {
display: none;
}
`;
const MessageArea = styled.div`
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
`;
const MessageHeader = styled.div`
padding: var(--space-md) var(--space-lg);
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
gap: var(--space-md);
flex-shrink: 0;
`;
const HeaderMeta = styled.div`
flex: 1;
`;
const HeaderName = styled.div`
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
`;
const HeaderRole = styled.div`
font-size: 11px;
color: var(--text-secondary);
`;
const HeaderBadge = styled.div<{ $ok: boolean }>`
font-family: var(--font-mono);
font-size: 10px;
color: ${({ $ok }) => ($ok ? '#00BFA5' : 'var(--text-secondary)')};
border: 1px solid currentColor;
padding: 2px var(--space-sm);
text-transform: uppercase;
letter-spacing: 0.06em;
`;
const Timeline = styled.div`
flex: 1;
overflow-y: auto;
padding: var(--space-lg);
display: flex;
flex-direction: column;
gap: var(--space-md);
`;
const MessageBubble = styled.div<{ $role: ChatMessage['role'] }>`
display: flex;
flex-direction: column;
gap: 4px;
align-items: ${({ $role }) => ($role === 'user' ? 'flex-end' : 'flex-start')};
animation: ${fadeIn} 0.2s ease;
`;
const BubbleContent = styled.div<{ $role: ChatMessage['role'] }>`
max-width: 75%;
padding: var(--space-sm) var(--space-md);
font-size: 13px;
line-height: 1.6;
color: var(--text-primary);
background: ${({ $role }) =>
$role === 'user'
? 'rgba(255,255,255,0.06)'
: $role === 'tool'
? 'rgba(255, 152, 0, 0.06)'
: 'rgba(255,255,255,0.02)'};
border: 1px solid ${({ $role }) =>
$role === 'user'
? 'rgba(255,255,255,0.12)'
: $role === 'tool'
? 'rgba(255,152,0,0.2)'
: 'rgba(255,255,255,0.06)'};
font-family: ${({ $role }) => ($role === 'tool' ? 'var(--font-mono)' : 'inherit')};
`;
const BubbleMeta = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
opacity: 0.6;
`;
const EmptyTimeline = styled.div`
flex: 1;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: var(--space-md);
color: var(--text-secondary);
font-size: 13px;
text-align: center;
`;
const RuntimeNotice = styled.div`
border: 1px solid var(--border-color);
padding: var(--space-md);
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
line-height: 1.7;
max-width: 320px;
text-align: center;
`;
const InputArea = styled.div`
padding: var(--space-md) var(--space-lg);
border-top: 1px solid var(--border-color);
display: flex;
gap: var(--space-sm);
align-items: flex-end;
flex-shrink: 0;
`;
const MessageInput = styled.textarea`
flex: 1;
background: var(--bg-input, #1a1a1a);
border: 1px solid var(--border-color);
color: var(--text-primary);
font-family: inherit;
font-size: 13px;
padding: var(--space-sm) var(--space-md);
resize: none;
min-height: 40px;
max-height: 120px;
line-height: 1.5;
&:focus {
outline: none;
border-color: var(--border-hover);
}
&::placeholder {
color: var(--text-secondary);
opacity: 0.5;
}
`;
const SendBtn = styled.button`
border: 1px solid var(--border-color);
background: transparent;
color: var(--text-secondary);
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: var(--space-sm) var(--space-md);
cursor: pointer;
font-family: var(--font-mono);
transition: all 0.15s;
white-space: nowrap;
align-self: flex-end;
&:hover:not(:disabled) {
border-color: var(--border-hover);
color: var(--text-primary);
}
&:disabled {
opacity: 0.3;
cursor: not-allowed;
}
`;
const InputMeta = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
opacity: 0.6;
text-transform: uppercase;
letter-spacing: 0.06em;
text-align: center;
`;
const SisterContext = styled.aside`
width: 220px;
flex-shrink: 0;
border-left: 1px solid var(--border-color);
padding: var(--space-lg);
display: flex;
flex-direction: column;
gap: var(--space-lg);
overflow-y: auto;
@media (max-width: 1199px) {
display: none;
}
`;
const ContextSection = styled.div`
display: flex;
flex-direction: column;
gap: var(--space-sm);
`;
const CtxLabel = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
border-bottom: 1px solid var(--border-color);
padding-bottom: 4px;
`;
const CtxValue = styled.div`
font-size: 12px;
color: var(--text-primary);
line-height: 1.5;
`;
const CtxMono = styled.div`
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
`;
const CloseBtn = styled.button`
border: 1px solid var(--border-color);
background: transparent;
color: var(--text-secondary);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: var(--space-xs) var(--space-sm);
cursor: pointer;
font-family: var(--font-mono);
&:hover {
border-color: var(--border-hover);
color: var(--text-primary);
}
`;
function formatTs(ts: string): string {
const date = new Date(ts);
const diff = Date.now() - date.getTime();
const min = Math.floor(diff / 60000);
if (min < 1) return '방금';
if (min < 60) return `${min}분 전`;
const hr = Math.floor(min / 60);
if (hr < 24) return `${hr}시간 전`;
return `${Math.floor(hr / 24)}일 전`;
}
function runtimeStateLabel(state: AgentState): string {
if (state === 'thinking') return 'thinking';
if (state === 'tool_calling') return 'tool_calling';
if (state === 'speaking') return 'speaking';
if (state === 'error') return 'error';
return 'idle';
}
// Fix #4: Remove localStorage token — use cookie-based auth via withSessionRequest
// Token is handled by HttpOnly cookies + CSRF, no client-side access needed
function mergeMessages(prev: ChatMessage[], incoming: ChatMessage[]) {
const map = new Map<string, ChatMessage>();
[...prev, ...incoming].forEach((item) => {
map.set(item.id, item);
});
return Array.from(map.values()).sort((a, b) => new Date(a.ts).getTime() - new Date(b.ts).getTime());
}
function mapRuntimeMessages(items: RuntimeMessage[]): ChatMessage[] {
return items.map((item, index) => ({
id: item.id || `${item.role}-${item.ts ?? 'none'}-${index}`,
role: item.role,
content: item.content,
ts: item.ts ?? new Date().toISOString(),
}));
}
export default function ChatWorkspace({ initialSister, onClose }: ChatWorkspaceProps) {
const [activeSister, setActiveSister] = useState<SisterName>(initialSister);
const [allMessages, setAllMessages] = useState<Partial<Record<SisterName, ChatMessage[]>>>({});
const [runtimeBySister, setRuntimeBySister] = useState<Partial<Record<SisterName, RuntimeSnapshot>>>({});
// Per-sister draft — prevents input leaking across tabs
const [drafts, setDrafts] = useState<Partial<Record<SisterName, string>>>({});
const input = drafts[activeSister] ?? '';
const [sending, setSending] = useState(false);
const timelineRef = useRef<HTMLDivElement>(null);
const messages = useMemo(() => allMessages[activeSister] ?? [], [allMessages, activeSister]);
const runtime = runtimeBySister[activeSister] ?? null;
// Cookie-based auth always available (no token check needed)
useEffect(() => {
setActiveSister(initialSister);
}, [initialSister]);
useEffect(() => {
if (timelineRef.current) {
timelineRef.current.scrollTop = timelineRef.current.scrollHeight;
}
}, [messages]);
const setMessages = useCallback((sister: SisterName, updater: (prev: ChatMessage[]) => ChatMessage[]) => {
setAllMessages((prev) => ({
...prev,
[sister]: updater(prev[sister] ?? []),
}));
}, []);
const loadRuntime = useCallback(async (sister: SisterName) => {
try {
const res = await fetch(`${API_URL}/api/sisters/${sister}/runtime`, withSessionRequest());
if (!res.ok) return;
const data = (await res.json()) as RuntimeSnapshot;
setRuntimeBySister((prev) => ({ ...prev, [sister]: data }));
const runtimeMessages = mapRuntimeMessages(data.recentMessages ?? []);
if (runtimeMessages.length > 0) {
setMessages(sister, (prev) => mergeMessages(prev, runtimeMessages));
}
} catch {
// ignore runtime refresh failures
}
}, [setMessages]);
useEffect(() => {
void loadRuntime(activeSister);
const interval = setInterval(() => {
void loadRuntime(activeSister);
}, 8000);
return () => clearInterval(interval);
}, [activeSister, loadRuntime]);
const handleSend = useCallback(async () => {
const text = input.trim();
if (!text || sending) return;
// Cookie-based auth — no token check needed
const userMessage: ChatMessage = {
id: `user-${crypto.randomUUID()}`,
role: 'user',
content: text,
ts: new Date().toISOString(),
};
setMessages(activeSister, (prev) => mergeMessages(prev, [userMessage]));
setDrafts((prev) => ({ ...prev, [activeSister]: '' }));
setSending(true);
try {
const res = await fetch(`${API_URL}/api/sisters/${activeSister}/chat`, withSessionRequest({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: text }),
}, { csrf: true }));
const data = await res.json();
if (!res.ok) {
throw new Error(data?.message || '채팅 전송 실패');
}
if (data?.runtime) {
setRuntimeBySister((prev) => ({ ...prev, [activeSister]: data.runtime as RuntimeSnapshot }));
}
const reply = String(data?.reply || '').trim();
if (reply) {
setMessages(activeSister, (prev) => mergeMessages(prev, [{
id: `assistant-${crypto.randomUUID()}`,
role: 'assistant',
content: reply,
ts: new Date().toISOString(),
}]));
}
void loadRuntime(activeSister);
} catch (error) {
const message = error instanceof Error ? error.message : '채팅 전송 중 오류가 발생했어.';
setMessages(activeSister, (prev) => mergeMessages(prev, [{
id: `error-${crypto.randomUUID()}`,
role: 'assistant',
content: `전송 실패: ${message}`,
ts: new Date().toISOString(),
}]));
} finally {
setSending(false);
}
}, [activeSister, input, loadRuntime, sending, setMessages]);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
void handleSend();
}
};
return (
<Workspace>
<SisterTabs>
<SisterTabHeader>direct chat</SisterTabHeader>
{SISTER_ORDER.map((name) => (
<SisterTab key={name} $active={activeSister === name} onClick={() => setActiveSister(name)}>
<SisterAvatar name={name} size={22} />
<TabMeta>
<TabName>{SISTER_DISPLAY[name]}</TabName>
<TabRole>{SISTER_ROLES[name].split(' ')[0]}</TabRole>
</TabMeta>
</SisterTab>
))}
</SisterTabs>
<MessageArea>
<MessageHeader>
<SisterAvatar name={activeSister} size={28} />
<HeaderMeta>
<HeaderName>{SISTER_DISPLAY[activeSister]}</HeaderName>
<HeaderRole>{SISTER_ROLES[activeSister]}</HeaderRole>
</HeaderMeta>
<HeaderBadge $ok={Boolean(runtime?.gatewayConnected)}>
{runtime?.gatewayConnected ? 'Runtime 연결됨' : 'Runtime 확인 중'}
</HeaderBadge>
<CloseBtn onClick={onClose}> </CloseBtn>
</MessageHeader>
<Timeline ref={timelineRef}>
{messages.length === 0 ? (
<EmptyTimeline>
<SisterAvatar name={activeSister} size={32} />
<div>{SISTER_DISPLAY[activeSister]} .</div>
<RuntimeNotice>
{runtime?.gatewayConnected
? '직접 채팅이 자매 runtime으로 연결돼 있어. 입력하면 바로 전달돼.'
: 'runtime 상태를 확인 중이야. 연결이 느려도 메시지는 다시 시도할 수 있어.'}
</RuntimeNotice>
</EmptyTimeline>
) : (
messages.map((msg) => (
<MessageBubble key={msg.id} $role={msg.role}>
<BubbleContent $role={msg.role}>{msg.content}</BubbleContent>
<BubbleMeta>{formatTs(msg.ts)}</BubbleMeta>
</MessageBubble>
))
)}
</Timeline>
<InputMeta>
shift+enter = · enter = · runtime: {runtime ? runtimeStateLabel(runtime.mainState) : 'loading'}
</InputMeta>
<InputArea>
<MessageInput
placeholder={`${SISTER_DISPLAY[activeSister]}에게 지시해...`}
value={input}
onChange={(e) => setDrafts((prev) => ({ ...prev, [activeSister]: e.target.value }))}
onKeyDown={handleKeyDown}
rows={1}
/>
<SendBtn onClick={() => void handleSend()} disabled={!input.trim() || sending}>
{sending ? '전송 중' : '전송'}
</SendBtn>
</InputArea>
</MessageArea>
<SisterContext>
<ContextSection>
<CtxLabel>agent</CtxLabel>
<CtxValue>{SISTER_DISPLAY[activeSister]}</CtxValue>
<CtxMono>{SISTER_ROLES[activeSister]}</CtxMono>
</ContextSection>
<ContextSection>
<CtxLabel> </CtxLabel>
<CtxValue>{runtime?.gatewayConnected ? 'Runtime 연결됨' : 'Runtime 확인 중'}</CtxValue>
<CtxMono>{runtime ? runtimeStateLabel(runtime.mainState) : 'loading'}</CtxMono>
</ContextSection>
<ContextSection>
<CtxLabel>data source</CtxLabel>
<CtxMono>
control: ssh openclaw agent
<br />
activity: runtime session snapshot
</CtxMono>
</ContextSection>
<ContextSection>
<CtxLabel>current task</CtxLabel>
<CtxValue>{runtime?.currentTask ?? runtime?.activeSessionLabel ?? '작업 정보 없음'}</CtxValue>
</ContextSection>
</SisterContext>
</Workspace>
);
}

View File

@@ -0,0 +1,422 @@
'use client';
import React from 'react';
import styled from 'styled-components';
import Link from 'next/link';
import SisterAvatar from '@/components/common/SisterAvatar';
import type { SisterNode, SubAgent, SisterName, AgentState, SelectedAgent } from './OfficeScene';
interface ContextPanelProps {
selected: SelectedAgent | null;
sisters: SisterNode[];
onOpenChat: (sisterName: SisterName) => void;
onClear: () => void;
}
const Panel = styled.aside`
width: 300px;
flex-shrink: 0;
border-left: 1px solid var(--border-color);
background: var(--bg-surface);
display: flex;
flex-direction: column;
overflow-y: auto;
@media (max-width: 1199px) {
width: 260px;
}
@media (max-width: 767px) {
width: 100%;
border-left: none;
border-top: 1px solid var(--border-color);
max-height: 260px;
}
`;
const PanelHeader = styled.div`
padding: var(--space-md) var(--space-lg);
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
`;
const PanelTitle = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const ClearBtn = styled.button`
background: none;
border: none;
color: var(--text-secondary);
font-size: 12px;
cursor: pointer;
padding: 0;
line-height: 1;
&:hover {
color: var(--text-primary);
}
`;
const PanelBody = styled.div`
flex: 1;
overflow-y: auto;
padding: var(--space-lg);
display: flex;
flex-direction: column;
gap: var(--space-lg);
`;
const EmptyState = styled.div`
color: var(--text-secondary);
font-size: 13px;
line-height: 1.6;
text-align: center;
padding: var(--space-xl) 0;
`;
const AgentHeader = styled.div`
display: flex;
align-items: flex-start;
gap: var(--space-md);
`;
const AgentAvatarWrap = styled.div`
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
`;
const AgentMeta = styled.div`
display: flex;
flex-direction: column;
gap: 4px;
`;
const AgentName = styled.div`
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
`;
const AgentRole = styled.div`
font-size: 12px;
color: var(--text-secondary);
`;
const AgentType = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
`;
const StateRow = styled.div`
display: flex;
align-items: center;
gap: var(--space-sm);
`;
const StateDot = styled.span<{ $state: AgentState }>`
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
background: ${({ $state }) => {
const colors: Record<AgentState, string> = {
idle: '#444',
thinking: '#2979FF',
tool_calling: '#FF9800',
speaking: '#00BFA5',
error: '#FF1744',
};
return colors[$state];
}};
`;
const StateLabel = styled.span<{ $state: AgentState }>`
font-family: var(--font-mono);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: ${({ $state }) => {
const colors: Record<AgentState, string> = {
idle: 'var(--text-secondary)',
thinking: '#2979FF',
tool_calling: '#FF9800',
speaking: '#00BFA5',
error: '#FF1744',
};
return colors[$state];
}};
`;
const Section = styled.div`
display: flex;
flex-direction: column;
gap: var(--space-sm);
`;
const SectionLabel = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
border-bottom: 1px solid var(--border-color);
padding-bottom: 4px;
`;
const SectionValue = styled.div`
font-size: 12px;
color: var(--text-primary);
line-height: 1.5;
`;
const CurrentTaskBox = styled.div`
font-size: 12px;
color: #58A6FF;
padding: var(--space-sm) var(--space-md);
background: rgba(88, 166, 255, 0.06);
border-left: 2px solid #58A6FF;
line-height: 1.5;
`;
const SubagentGrid = styled.div`
display: flex;
flex-direction: column;
gap: 4px;
`;
const SubagentRow = styled.div`
display: flex;
align-items: center;
gap: var(--space-sm);
font-size: 12px;
color: var(--text-primary);
`;
const SubDot = styled.span<{ $state: AgentState }>`
width: 6px;
height: 6px;
border-radius: 50%;
flex-shrink: 0;
background: ${({ $state }) => {
const colors: Record<AgentState, string> = {
idle: '#444',
thinking: '#2979FF',
tool_calling: '#FF9800',
speaking: '#00BFA5',
error: '#FF1744',
};
return colors[$state];
}};
`;
const SubName = styled.span`
color: var(--text-secondary);
font-size: 11px;
font-family: var(--font-mono);
`;
const ActionRow = styled.div`
display: flex;
gap: var(--space-sm);
flex-wrap: wrap;
`;
const ActionBtn = styled.button`
border: 1px solid var(--border-color);
background: transparent;
color: var(--text-secondary);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: var(--space-xs) var(--space-sm);
cursor: pointer;
font-family: var(--font-mono);
transition: all 0.15s;
&:hover {
border-color: var(--border-hover);
color: var(--text-primary);
}
`;
const ActionLink = styled(Link)`
border: 1px solid var(--border-color);
background: transparent;
color: var(--text-secondary);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: var(--space-xs) var(--space-sm);
text-decoration: none;
font-family: var(--font-mono);
transition: all 0.15s;
display: inline-block;
&:hover {
border-color: var(--border-hover);
color: var(--text-primary);
}
`;
const FallbackNote = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
opacity: 0.7;
text-transform: uppercase;
letter-spacing: 0.06em;
`;
const SISTER_DISPLAY: Record<SisterName, string> = {
harang: '하랑이',
narang: '나랑이',
darang: '다랑이',
erang: '이랑이',
};
function SisterDetail({ sister, onOpenChat }: { sister: SisterNode; onOpenChat: (name: SisterName) => void }) {
const hasLiveSubagentState = sister.subagents.some((item) => item.sessionLabel || item.currentTask || item.updatedAt);
return (
<>
<AgentHeader>
<AgentAvatarWrap>
<SisterAvatar name={sister.name} size={40} />
</AgentAvatarWrap>
<AgentMeta>
<AgentName>{SISTER_DISPLAY[sister.name]}</AgentName>
<AgentRole>{sister.role}</AgentRole>
<AgentType>main agent</AgentType>
</AgentMeta>
</AgentHeader>
<StateRow>
<StateDot $state={sister.state} />
<StateLabel $state={sister.state}>{sister.state}</StateLabel>
</StateRow>
{(sister.currentTask || sister.activeSessionLabel) && (
<Section>
<SectionLabel>current task</SectionLabel>
<CurrentTaskBox>{sister.currentTask ?? sister.activeSessionLabel ?? '작업 정보 없음'}</CurrentTaskBox>
</Section>
)}
<Section>
<SectionLabel>subagents ({sister.subagents.length})</SectionLabel>
<SubagentGrid>
{sister.subagents.map((sub) => (
<SubagentRow key={sub.id}>
<SubDot $state={sub.state} />
<span>{sub.label}</span>
<SubName>· {sub.state}</SubName>
</SubagentRow>
))}
</SubagentGrid>
<FallbackNote>{hasLiveSubagentState ? 'subagent state: live runtime' : 'subagent state: fallback'}</FallbackNote>
</Section>
<ActionRow>
<ActionBtn onClick={() => onOpenChat(sister.name)}></ActionBtn>
<ActionLink href={`/sisters/${sister.name}`}></ActionLink>
</ActionRow>
</>
);
}
function SubagentDetail({
sub,
sister,
onOpenChat,
}: {
sub: SubAgent;
sister: SisterNode;
onOpenChat: (name: SisterName) => void;
}) {
const liveNote = sub.sessionLabel || sub.currentTask || sub.updatedAt;
return (
<>
<AgentHeader>
<AgentAvatarWrap>
<SisterAvatar name={sister.name} size={40} />
</AgentAvatarWrap>
<AgentMeta>
<AgentName>{sub.label}</AgentName>
<AgentRole>{sub.name}</AgentRole>
<AgentType>subagent · {SISTER_DISPLAY[sister.name]} </AgentType>
</AgentMeta>
</AgentHeader>
<StateRow>
<StateDot $state={sub.state} />
<StateLabel $state={sub.state}>{sub.state}</StateLabel>
</StateRow>
<Section>
<SectionLabel>parent</SectionLabel>
<SectionValue>{SISTER_DISPLAY[sister.name]} · {sister.role}</SectionValue>
</Section>
{(sub.currentTask || sub.sessionLabel) && (
<Section>
<SectionLabel>current task</SectionLabel>
<CurrentTaskBox>{sub.currentTask ?? sub.sessionLabel ?? '작업 정보 없음'}</CurrentTaskBox>
</Section>
)}
<FallbackNote>{liveNote ? 'subagent state: live runtime' : 'subagent state: fallback · no direct api'}</FallbackNote>
<ActionRow>
<ActionBtn onClick={() => onOpenChat(sister.name)}>{SISTER_DISPLAY[sister.name]} </ActionBtn>
<ActionLink href={`/sisters/${sister.name}`}> </ActionLink>
</ActionRow>
</>
);
}
export default function ContextPanel({ selected, sisters, onOpenChat, onClear }: ContextPanelProps) {
const getSister = (name: SisterName) => sisters.find((s) => s.name === name);
let content: React.ReactNode = (
<EmptyState>
<br />
.
</EmptyState>
);
if (selected?.type === 'sister') {
const sister = getSister(selected.name);
if (sister) content = <SisterDetail sister={sister} onOpenChat={onOpenChat} />;
} else if (selected?.type === 'subagent') {
const sister = getSister(selected.sister);
const sub = sister?.subagents.find((item) => item.id === selected.id);
if (sister && sub) content = <SubagentDetail sub={sub} sister={sister} onOpenChat={onOpenChat} />;
}
return (
<Panel>
<PanelHeader>
<PanelTitle>context panel</PanelTitle>
{selected && <ClearBtn onClick={onClear}></ClearBtn>}
</PanelHeader>
<PanelBody>{content}</PanelBody>
</Panel>
);
}

View File

@@ -0,0 +1,427 @@
'use client';
import React, { useMemo } from 'react';
import styled, { keyframes, css } from 'styled-components';
import type { RailsSubTaskNode, RailsPipelineSummary } from '@/lib/useRailsSocket';
import SisterAvatar from '@/components/common/SisterAvatar';
const SISTERS = [
{ key: 'harang', label: '하랑', role: 'Planner', color: '#3b82f6', accent: '#60a5fa', x: 0, y: 0 },
{ key: 'narang', label: '나랑', role: 'Generator', color: '#22c55e', accent: '#4ade80', x: 1, y: 0 },
{ key: 'darang', label: '다랑', role: 'Evaluator', color: '#f43f5e', accent: '#fb7185', x: 0, y: 1 },
{ key: 'erang', label: '이랑', role: 'Infra', color: '#f97316', accent: '#fb923c', x: 1, y: 1 },
] as const;
type SisterKey = (typeof SISTERS)[number]['key'];
interface OfficeFloorProps {
pipelines: RailsPipelineSummary[];
treesByPipeline: Map<string, RailsSubTaskNode[]>;
selectedSister: SisterKey | null;
onSelectSister: (key: SisterKey | null) => void;
}
interface SisterStats {
total: number;
running: number;
done: number;
failed: number;
models: Set<string>;
}
const Wrap = styled.div`
display: flex;
flex-direction: column;
gap: 16px;
`;
const Floor = styled.div`
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(2, 1fr);
gap: 24px;
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 16px;
padding: 28px;
min-height: 540px;
position: relative;
`;
const Overlay = styled.svg`
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 0;
`;
const flowDash = keyframes`
to { stroke-dashoffset: -8; }
`;
const FlowLine = styled.line<{ $flowing: boolean }>`
stroke: ${({ $flowing }) =>
$flowing ? '#5fafff' : 'rgba(95, 175, 255, 0.15)'};
stroke-width: 0.4;
stroke-dasharray: ${({ $flowing }) => ($flowing ? '1.6 1.2' : '0.6 0.6')};
animation: ${({ $flowing }) =>
$flowing
? css`
${flowDash} 1.2s linear infinite
`
: 'none'};
`;
const pulse = keyframes`
0%, 100% { box-shadow: 0 0 0 0 rgba(255, 165, 0, 0.4); }
50% { box-shadow: 0 0 0 8px rgba(255, 165, 0, 0); }
`;
const blink = keyframes`
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
`;
const Desk = styled.button<{ $color: string; $active: boolean; $running: boolean; $selected: boolean }>`
position: relative;
z-index: 1;
background: ${({ $color }) => `${$color}10`};
border: 1.5px solid ${({ $color, $selected }) => ($selected ? $color : `${$color}50`)};
border-radius: 12px;
padding: 24px;
display: flex;
flex-direction: column;
gap: 14px;
cursor: pointer;
transition: all 0.2s ease;
min-height: 220px;
text-align: left;
color: var(--text-primary);
animation: ${({ $running }) => ($running ? pulse : 'none')} 1.6s ease-in-out infinite;
&:hover {
transform: translateY(-2px);
border-color: ${({ $color }) => $color};
}
`;
const DeskHead = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
`;
const SisterBadge = styled.div<{ $color: string }>`
display: flex;
align-items: center;
gap: 12px;
`;
const AvatarFrame = styled.div<{ $color: string; $running: boolean }>`
width: 60px;
height: 60px;
border-radius: 50%;
padding: 3px;
background: linear-gradient(135deg, ${({ $color }) => $color}, ${({ $color }) => `${$color}60`});
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
box-shadow: ${({ $color, $running }) =>
$running ? `0 4px 16px ${$color}60` : `0 2px 8px ${$color}30`};
`;
const NameBlock = styled.div`
display: flex;
flex-direction: column;
`;
const Name = styled.span`
font-size: 18px;
font-weight: 700;
`;
const Role = styled.span`
font-size: 11px;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
`;
const StatusDot = styled.div<{ $running: boolean }>`
width: 10px;
height: 10px;
border-radius: 50%;
background: ${({ $running }) => ($running ? '#22c55e' : '#525252')};
flex-shrink: 0;
${({ $running }) =>
$running &&
`
box-shadow: 0 0 0 4px rgba(34, 197, 94, 0.2);
animation: ${blink} 1.4s ease-in-out infinite;
`}
`;
const Stats = styled.div`
display: flex;
gap: 18px;
padding-top: 12px;
border-top: 1px dashed var(--border-color);
`;
const Stat = styled.div`
display: flex;
flex-direction: column;
gap: 2px;
`;
const StatNum = styled.span`
font-family: var(--font-mono);
font-size: 20px;
font-weight: 700;
`;
const StatLabel = styled.span`
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
`;
const Workers = styled.div`
display: flex;
flex-wrap: wrap;
gap: 6px;
min-height: 28px;
`;
const Worker = styled.div<{ $role: string; $state: string }>`
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 8px;
border-radius: 12px;
font-size: 10px;
font-weight: 600;
background: ${({ $role }) => roleColor($role)}20;
border: 1px solid ${({ $role }) => roleColor($role)}60;
color: ${({ $role }) => roleColor($role)};
${({ $state }) =>
$state === 'running' &&
`animation: ${blink} 1.2s ease-in-out infinite;`}
`;
const Empty = styled.span`
font-size: 11px;
color: var(--text-secondary);
font-style: italic;
`;
function roleColor(role: string): string {
switch (role) {
case 'manager':
return '#8b5cf6';
case 'principal':
return '#3b82f6';
case 'lead':
return '#f97316';
case 'junior':
return '#22c55e';
default:
return '#6b7280';
}
}
function flattenWorkers(tree: RailsSubTaskNode[]): RailsSubTaskNode[] {
const out: RailsSubTaskNode[] = [];
const walk = (nodes: RailsSubTaskNode[]) => {
for (const n of nodes) {
out.push(n);
if (n.children?.length) walk(n.children);
}
};
walk(tree);
return out;
}
function statsFor(workers: RailsSubTaskNode[]): SisterStats {
const stats: SisterStats = {
total: workers.length,
running: 0,
done: 0,
failed: 0,
models: new Set(),
};
for (const w of workers) {
if (w.state === 'running' || w.state === 'queued') stats.running += 1;
else if (w.state === 'done') stats.done += 1;
else if (w.state === 'failed' || w.state === 'escalated') stats.failed += 1;
if (w.model) stats.models.add(w.model);
}
return stats;
}
export default function OfficeFloor({
pipelines,
treesByPipeline,
selectedSister,
onSelectSister,
}: OfficeFloorProps) {
// Aggregate workers per sister across active pipelines
const workersBySister = useMemo(() => {
const map = new Map<SisterKey, RailsSubTaskNode[]>();
for (const sister of SISTERS) map.set(sister.key, []);
const activePipelines = pipelines.filter(
(p) => !['done', 'aborted'].includes(p.currentState),
);
const sourcePipelines = activePipelines.length > 0 ? activePipelines : pipelines.slice(0, 4);
for (const pipeline of sourcePipelines) {
const tree = treesByPipeline.get(pipeline.id) ?? [];
const flat = flattenWorkers(tree);
for (const node of flat) {
const sisterKey = node.agentName as SisterKey;
const target = map.get(sisterKey);
if (target) target.push(node);
}
}
return map;
}, [pipelines, treesByPipeline]);
// Determine which stages are currently running for animation
const activeStages = useMemo(() => {
const set = new Set<string>();
for (const sister of SISTERS) {
const stats = statsFor(workersBySister.get(sister.key) ?? []);
if (stats.running > 0) set.add(sister.key);
}
return set;
}, [workersBySister]);
// SVG flow lines: harang→narang→darang→erang following the pipeline order
// Coordinates are normalized 0-100 (viewBox 100x100)
const POS: Record<string, { x: number; y: number }> = {
harang: { x: 25, y: 25 },
narang: { x: 75, y: 25 },
darang: { x: 25, y: 75 },
erang: { x: 75, y: 75 },
};
// Order: plan→implement→review→deploy
const FLOW: Array<[keyof typeof POS, keyof typeof POS]> = [
['harang', 'narang'],
['narang', 'darang'],
['darang', 'erang'],
];
return (
<Wrap>
<Floor>
<Overlay viewBox="0 0 100 100" preserveAspectRatio="none">
<defs>
<marker
id="arrowhead"
markerWidth="10"
markerHeight="10"
refX="9"
refY="5"
orient="auto"
>
<polygon points="0 0, 10 5, 0 10" fill="#5fafff" />
</marker>
</defs>
{FLOW.map(([from, to]) => {
const fromActive = activeStages.has(from);
const toActive = activeStages.has(to);
const flowing = fromActive || toActive;
const a = POS[from]!;
const b = POS[to]!;
return (
<FlowLine
key={`${from}-${to}`}
x1={a.x}
y1={a.y}
x2={b.x}
y2={b.y}
$flowing={flowing}
markerEnd="url(#arrowhead)"
/>
);
})}
</Overlay>
{SISTERS.map((sister) => {
const workers = workersBySister.get(sister.key) ?? [];
const stats = statsFor(workers);
const running = stats.running > 0;
const isSelected = selectedSister === sister.key;
return (
<Desk
key={sister.key}
$color={sister.color}
$active={stats.total > 0}
$running={running}
$selected={isSelected}
onClick={() => onSelectSister(isSelected ? null : sister.key)}
>
<DeskHead>
<SisterBadge $color={sister.color}>
<AvatarFrame $color={sister.color} $running={running}>
<SisterAvatar name={sister.key} size={54} />
</AvatarFrame>
<NameBlock>
<Name>{sister.label}</Name>
<Role>{sister.role}</Role>
</NameBlock>
</SisterBadge>
<StatusDot $running={running} />
</DeskHead>
<Workers>
{workers.length === 0 ? (
<Empty> </Empty>
) : (
workers.slice(0, 12).map((w) => (
<Worker key={w.id} $role={w.role} $state={w.state}>
{w.role}
</Worker>
))
)}
{workers.length > 12 && (
<Worker $role="" $state="">
+{workers.length - 12}
</Worker>
)}
</Workers>
<Stats>
<Stat>
<StatNum>{stats.total}</StatNum>
<StatLabel>workers</StatLabel>
</Stat>
<Stat>
<StatNum style={{ color: '#22c55e' }}>{stats.running}</StatNum>
<StatLabel>active</StatLabel>
</Stat>
<Stat>
<StatNum>{stats.done}</StatNum>
<StatLabel>done</StatLabel>
</Stat>
{stats.failed > 0 && (
<Stat>
<StatNum style={{ color: '#ef4444' }}>{stats.failed}</StatNum>
<StatLabel>fail</StatLabel>
</Stat>
)}
</Stats>
</Desk>
);
})}
</Floor>
</Wrap>
);
}

Some files were not shown because too many files have changed in this diff Show More