Compare commits

...

29 Commits

Author SHA1 Message Date
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
56 changed files with 19922 additions and 189 deletions

View File

@@ -0,0 +1 @@
1775812935

1
.gitignore vendored
View File

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

View File

@@ -4,6 +4,19 @@
- 4자매 운영 상태를 실시간으로 보여준다 - 4자매 운영 상태를 실시간으로 보여준다
- 프로젝트/Sprint/Hotfix/QA/Deploy 흐름을 시각화한다 - 프로젝트/Sprint/Hotfix/QA/Deploy 흐름을 시각화한다
- `main`이 항상 배포 가능 상태라는 원칙을 UI와 운영에 함께 반영한다 - `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` - 루트: `README.md`, `ARCHITECTURE.md`
@@ -15,28 +28,70 @@
- `deploy/` - `deploy/`
- 장기 문서: `docs/` - 장기 문서: `docs/`
## 활성 작업 ## 현재 상태
- **SPRINT-015**: Master Dashboard v3 정보 구조 리디자인 - **SPRINT-016**: `/office` 기본 화면과 핵심 컴포넌트가 `main`에 반영됨
- **HOTFIX-006**: 대시보드 문구 절제 + 실시간성 정합성 보정 - **다음 활성 작업**: **SPRINT-017** `/office` 모바일 화면 전면 개편
## 이번 Sprint 핵심 요구사항 ## SPRINT-017 active scope
1. 메인 대시보드를 4자매 운영 관제의 대표 화면으로 재정의 이번 Sprint는 안정화 전반이 아니라 **`/office` 모바일 정보 구조 재설계**에만 집중해.
2. 현행 미니멀 터미널 UI를 유지한 채 레퍼런스의 강한 정보 구조를 흡수
3. 상단 global status bar / 4자매 상태 카드 / `ACTIVE PIPELINE` 중심 구조 도입 ### 이번에 반드시 해결할 것
4. `ACTIVITY FEED`, `SPRINT METRICS`, `INFRASTRUCTURE OVERVIEW`, `MISTAKE LOG & HARNESS`를 운영 문맥으로 재배치 1. `360px`, `390px` 첫 viewport에서 아래 4가지를 한 번에 읽히게 만든다.
5. 데스크톱 우선 설계 후 모바일 세로 흐름까지 함께 정리 - 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+`
## 이행 전략 ## 이행 전략
- 코드에서는 구 구조와 신 구조를 일정 기간 동시 지원 - 문서는 실제 `main` 구현 경로를 근거로만 갱신한다
- 문서는 신 구조를 기준으로 선반영 - SPRINT-017은 `mobile-first IA``상태 라벨 통일`까지만 잠근다
- 신규 QA 문서는 `.plans/qa/` 기준 - 구현 작업은 `frontend/app/office/page.tsx``frontend/components/office/*` 범위 안에서 끝내는 걸 기본으로 한다
- 신규 Hotfix 문서는 `.plans/hotfix/` 기준 - QA는 `360 / 390 / 768 / 1280+` 실브라우저 확인을 기준으로 남긴다
## 문서 맵 ## 문서 맵
- 구조 기준: `../ARCHITECTURE.md` - 구조 기준: `../ARCHITECTURE.md`
- 제품 PRD: `../docs/product-specs/openclaw-office-dashboard-prd.md`
- 디자인 인덱스: `./design/index.md` - 디자인 인덱스: `./design/index.md`
- Sprint 계획: `./sprints/SPRINT-015.md` - Sprint 016 비전: `./sprints/SPRINT-016.md`
- Sprint handoff: `./sprints/SPRINT-015-NARANG-HANDOFF.md` - Sprint 017 실행 계획: `./sprints/SPRINT-017.md`
- Hotfix 계획: `./hotfix/HOTFIX-006.md` - 오피스 모바일 IA: `./design/ui/office-dashboard-design.md`
- Hotfix handoff: `./hotfix/HOTFIX-006-NARANG-HANDOFF.md` - 오피스 direct chat 모바일 기준: `./design/ui/office-chat-design.md`
- API / 실시간 모델 참고: `./design/api-design.md`
- 배포 플로우: `./deploy/main-release-flow.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 설정 ## PM2 설정
``` ```
backend: pm2 start dist/main.js --name hanarang-api --env production 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 -- start -- -p 3004 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 키 배포 ## SSH 키 배포
- Dev 서버(10.10.10.169)에서 4자매 서버로 SSH 접속할 수 있도록 키 배포 필요 - Dev 서버(10.10.10.169)에서 4자매 서버로 SSH 접속할 수 있도록 키 배포 필요
- 이랑이가 SSH 키 생성 + 각 자매 서버에 authorized_keys 추가 - 이랑이가 SSH 키 생성 + 각 자매 서버에 authorized_keys 추가

View File

@@ -3,36 +3,137 @@
## 공통 규칙 ## 공통 규칙
- Base URL: `https://hanarang-api.nabomhalang.co.kr` - Base URL: `https://hanarang-api.nabomhalang.co.kr`
- 응답 형식: JSON - 응답 형식: JSON
- 인증: MVP에서는 인증 없음 (내부망 전용). 추후 JWT 추가 가능. - WS Namespace: `/ws`
- 에러 형식: `{ "statusCode": 400, "message": "...", "error": "Bad Request" }` - 기본 에러 형식: `{ "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 | 설명 | ## 오피스 대시보드 핵심 소스
|--------|----------|------| - Git 구현 기준:
| GET | `/api/sisters` | 4자매 상태 목록 (SSH로 실시간 조회) | - `frontend/app/office/page.tsx`
| GET | `/api/sisters/:name` | 자매 상세 (설정 + 상태) | - `backend/src/sisters/sisters.controller.ts`
| GET | `/api/sisters/:name/config` | openclaw.json 내용 | - `backend/src/events/events.gateway.ts`
| GET | `/api/sisters/:name/sessions` | 최근 세션 목록 | - `backend/src/events/events.scheduler.ts`
| GET | `/api/sisters/:name/subagents` | 서브에이전트 사용 현황 | - 관련 Sprint: `../sprints/SPRINT-017.md`
| POST | `/api/sisters/:name/restart` | Gateway 재시작 (관리자) | - 관련 UI 문서:
| POST | `/api/sisters/:name/reset` | 세션 리셋 (관리자) | - `./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 ```json
// Response 200
[ [
{ {
"name": "harang", "name": "harang",
"displayName": "하랑이", "gatewayConnected": true,
"ip": "10.10.10.112", "mainState": "thinking",
"status": "online", "currentTask": "SPRINT-017 scope 잠금",
"lastSeen": "2026-04-04T01:45:00Z", "activeSessionLabel": "main",
"role": "Orchestrator" "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 (프로젝트) ## Projects (프로젝트)
| Method | Endpoint | 설명 | | Method | Endpoint | 설명 |
@@ -69,3 +170,9 @@
| Method | Endpoint | 설명 | | Method | Endpoint | 설명 |
|--------|----------|------| |--------|----------|------|
| GET | `/health` | 서버 상태 확인 | | 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 - **Dev 서버:** 10.10.10.169
- **프로세스 관리:** PM2 - **프로세스 관리:** PM2
- **FE:** pm2 start npm --name hanarang-web -- start (포트 3004) - **FE:** `pm2 start npm --name hanarang-web --cwd /path/to/hanarang-dashboard/frontend -- start -- -p 3004`
- **BE:** pm2 start dist/main.js --name hanarang-api (포트 3005) - **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
- `ui/dashboard-design.md` - `ui/dashboard-design.md`
- `ui/office-dashboard-design.md`
- `ui/office-chat-design.md`
- `ui/projects-page-design.md` - `ui/projects-page-design.md`
- `ui/project-detail-design.md` - `ui/project-detail-design.md`
- `ui/sister-detail-design.md` - `ui/sister-detail-design.md`
@@ -19,8 +21,20 @@
## 레퍼런스 ## 레퍼런스
- `references/07-master-dashboard-v3-reference.md` - `references/07-master-dashboard-v3-reference.md`
## Sprint 015에서 반드시 반영할 화면 ## 현재 우선 문서
- 대시보드 메인: Master Dashboard v3 구조 반영 - Sprint 실행 기준: `../sprints/SPRINT-017.md`
- 핵심 섹션: Global Status Bar / 4자매 상태 카드 / `ACTIVE PIPELINE` - 제품 비전: `../../docs/product-specs/openclaw-office-dashboard-prd.md`
- 운영 패널: `ACTIVITY FEED`, `SPRINT METRICS`, `INFRASTRUCTURE OVERVIEW`, `MISTAKE LOG & HARNESS` - 실행 개요: `../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,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,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,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/common": "^11.0.1",
"@nestjs/config": "^4.0.3", "@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1", "@nestjs/core": "^11.0.1",
"@nestjs/event-emitter": "^3.0.1",
"@nestjs/jwt": "^11.0.2", "@nestjs/jwt": "^11.0.2",
"@nestjs/passport": "^11.0.5", "@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.0.1", "@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": { "node_modules/@nestjs/jwt": {
"version": "11.0.2", "version": "11.0.2",
"resolved": "https://registry.npmjs.org/@nestjs/jwt/-/jwt-11.0.2.tgz", "resolved": "https://registry.npmjs.org/@nestjs/jwt/-/jwt-11.0.2.tgz",
@@ -6204,6 +6218,12 @@
"node": ">= 0.6" "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": { "node_modules/events": {
"version": "3.3.0", "version": "3.3.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",

View File

@@ -27,6 +27,7 @@
"@nestjs/common": "^11.0.1", "@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.3", "@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1", "@nestjs/core": "^11.0.1",
"@nestjs/event-emitter": "^3.0.1",
"@nestjs/jwt": "^11.0.2", "@nestjs/jwt": "^11.0.2",
"@nestjs/passport": "^11.0.5", "@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.0.1", "@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

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

View File

@@ -1,4 +1,5 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from '@nestjs/testing';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { ActivityService } from './activity.service'; import { ActivityService } from './activity.service';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
@@ -20,6 +21,7 @@ describe('ActivityService', () => {
providers: [ providers: [
ActivityService, ActivityService,
{ provide: PrismaService, useValue: mockPrisma }, { provide: PrismaService, useValue: mockPrisma },
EventEmitter2,
], ],
}).compile(); }).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 { PrismaService } from '../prisma/prisma.service';
import { EventsGateway } from '../events/events.gateway';
export interface LogActivityDto { export interface LogActivityDto {
sisterId?: number; sisterId?: number;
@@ -34,7 +34,7 @@ function sanitizeActivityDetail(detail?: string | null): string | undefined {
export class ActivityService { export class ActivityService {
constructor( constructor(
private readonly prisma: PrismaService, private readonly prisma: PrismaService,
@Optional() private readonly events?: EventsGateway, private readonly eventEmitter: EventEmitter2,
) {} ) {}
async log(dto: LogActivityDto) { async log(dto: LogActivityDto) {
@@ -49,9 +49,7 @@ export class ActivityService {
}, },
}); });
if (this.events) { this.eventEmitter.emit('activity.logged', record);
this.events.broadcastActivity(record);
}
return record; return record;
} }

View File

@@ -1,5 +1,6 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { ThrottlerModule } from '@nestjs/throttler'; import { ThrottlerModule } from '@nestjs/throttler';
import { AppController } from './app.controller'; import { AppController } from './app.controller';
import { AppService } from './app.service'; import { AppService } from './app.service';
@@ -18,10 +19,12 @@ import { CostsModule } from './costs/costs.module';
import { GiteaSyncModule } from './gitea-sync/gitea-sync.module'; import { GiteaSyncModule } from './gitea-sync/gitea-sync.module';
import { SettingsModule } from './settings/settings.module'; import { SettingsModule } from './settings/settings.module';
import { DashboardModule } from './dashboard/dashboard.module'; import { DashboardModule } from './dashboard/dashboard.module';
import { RailsModule } from './rails/rails.module';
@Module({ @Module({
imports: [ imports: [
ConfigModule.forRoot({ isGlobal: true }), ConfigModule.forRoot({ isGlobal: true }),
EventEmitterModule.forRoot(),
ThrottlerModule.forRoot([{ ttl: 60000, limit: 100 }]), ThrottlerModule.forRoot([{ ttl: 60000, limit: 100 }]),
PrismaModule, PrismaModule,
SistersModule, SistersModule,
@@ -38,6 +41,7 @@ import { DashboardModule } from './dashboard/dashboard.module';
GiteaSyncModule, GiteaSyncModule,
SettingsModule, SettingsModule,
DashboardModule, DashboardModule,
RailsModule,
], ],
controllers: [AppController], controllers: [AppController],
providers: [AppService], 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,17 +1,30 @@
import { import {
Controller, BadRequestException,
Post,
Get,
Body, Body,
Headers, Controller,
Get,
HttpCode,
Post,
Req,
Res,
UnauthorizedException,
UseGuards, UseGuards,
Request, Request,
BadRequestException,
} from '@nestjs/common'; } from '@nestjs/common';
import type { Request as ExpressRequest } from 'express'; import type {
import { AuthService, LoginDto } from './auth.service'; Request as ExpressRequest,
import { JwtGuard } from './jwt.guard'; Response as ExpressResponse,
} from 'express';
import { Throttle, ThrottlerGuard } from '@nestjs/throttler'; 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 { interface AuthenticatedRequest extends ExpressRequest {
user: { userId: number }; user: { userId: number };
@@ -21,17 +34,58 @@ interface AuthenticatedRequest extends ExpressRequest {
export class AuthController { export class AuthController {
constructor(private readonly authService: AuthService) {} constructor(private readonly authService: AuthService) {}
@HttpCode(200)
@UseGuards(ThrottlerGuard) @UseGuards(ThrottlerGuard)
@Throttle({ default: { limit: 5, ttl: 60000 } }) @Throttle({ default: { limit: 5, ttl: 60000 } })
@Post('login') @Post('login')
login(@Body() dto: LoginDto) { async login(
return this.authService.login(dto); @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') @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'); 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) @UseGuards(JwtGuard)

View File

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

View File

@@ -69,13 +69,23 @@ function nodeStateFromEvidence(params: {
return 'idle'; 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( function summarizeActivity(
activity?: ActivityRecord | null, activity?: ActivityRecord | null,
fallback = 'NO EVENT', fallback = 'NO EVENT',
) { ) {
return ( return sanitizeSummary(activity?.detail) || activity?.action?.replace(/_/g, ' ') || fallback;
activity?.detail?.trim() || activity?.action?.replace(/_/g, ' ') || fallback
);
} }
function parseQaSummary(content: string): string { function parseQaSummary(content: string): string {

View File

@@ -10,6 +10,8 @@ import { Server, Socket } from 'socket.io';
import { Logger } from '@nestjs/common'; import { Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { OnEvent } from '@nestjs/event-emitter';
import { ACCESS_TOKEN_COOKIE, parseCookieHeader } from '../auth/auth-cookies';
interface SocketUserPayload { interface SocketUserPayload {
username?: string; username?: string;
@@ -49,12 +51,17 @@ export class EventsGateway
handleConnection(client: SocketWithUser) { handleConnection(client: SocketWithUser) {
// JWT 인증 필수 — 토큰 없거나 유효하지 않으면 disconnect // 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 = const token =
(client.handshake.auth?.token as string) ?? (client.handshake.auth?.token as string | undefined) ??
(client.handshake.headers.authorization as string)?.replace( tokenFromHeader ??
'Bearer ', tokenFromCookie;
'',
);
if (!token) { if (!token) {
this.logger.debug(`WS rejected (no token): ${client.id}`); this.logger.debug(`WS rejected (no token): ${client.id}`);
@@ -101,6 +108,39 @@ export class EventsGateway
this.server.emit('activity:new', { item, ts: Date.now() }); 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 { getClientCount(): number {
return this.server?.sockets?.sockets?.size ?? 0; return this.server?.sockets?.sockets?.size ?? 0;

View File

@@ -1,7 +1,14 @@
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import { Logger, ValidationPipe } from '@nestjs/common'; import { Logger, ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module'; import type { NextFunction, Request, Response } from 'express';
import helmet from 'helmet'; import helmet from 'helmet';
import { AppModule } from './app.module';
import {
ACCESS_TOKEN_COOKIE,
REFRESH_TOKEN_COOKIE,
getCookieValue,
hasValidCsrfToken,
} from './auth/auth-cookies';
function getAllowedOrigins() { function getAllowedOrigins() {
return (process.env.CORS_ORIGINS ?? 'http://localhost:3004') return (process.env.CORS_ORIGINS ?? 'http://localhost:3004')
@@ -10,10 +17,40 @@ function getAllowedOrigins() {
.filter((origin): origin is string => origin.length > 0); .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() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
app.use(helmet()); app.use(helmet());
app.use((req: Request, res: Response, next: NextFunction) => {
if (shouldBypassCsrf(req) || hasValidCsrfToken(req)) {
next();
return;
}
res.status(403).json({ message: 'Invalid CSRF token' });
});
const allowedOrigins = getAllowedOrigins(); const allowedOrigins = getAllowedOrigins();
@@ -29,6 +66,12 @@ async function bootstrap() {
} }
}, },
methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'], methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: [
'Content-Type',
'Authorization',
'X-CSRF-Token',
'X-Refresh-Token',
],
credentials: true, credentials: true,
}); });

View File

@@ -0,0 +1,105 @@
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('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,172 @@
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 ?? [];
}
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

@@ -1,7 +1,7 @@
import { Injectable, Logger, NotFoundException } from '@nestjs/common'; import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { SshService } from './ssh.service'; import { SshService } from './ssh.service';
import { ConfigService } from '@nestjs/config';
type SisterName = 'harang' | 'narang' | 'darang' | 'erang'; type SisterName = 'harang' | 'narang' | 'darang' | 'erang';
@@ -20,6 +20,15 @@ const SISTER_DESCRIPTIONS: Record<SisterName, string> = {
erang: '인프라와 배포. 서버 관리, merge, 프로덕션 배포를 담당한다.', 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() @Injectable()
export class SisterDetailService { export class SisterDetailService {
private readonly logger = new Logger(SisterDetailService.name); private readonly logger = new Logger(SisterDetailService.name);
@@ -39,21 +48,36 @@ export class SisterDetailService {
sister.ip, sister.ip,
sister.user, sister.user,
sshKeyPath, 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 { return {
name, name,
role: SISTER_ROLES[name], role: SISTER_ROLES[name],
description: SISTER_DESCRIPTIONS[name], description: SISTER_DESCRIPTIONS[name],
raw: result.stdout || '(설정 파일 없음)', files,
summary: `${files.filter((file) => file.status === 'present').length}/${files.length} protected config files detected`,
}; };
} catch { } catch {
return { return {
name, name,
role: SISTER_ROLES[name], role: SISTER_ROLES[name],
description: SISTER_DESCRIPTIONS[name], description: SISTER_DESCRIPTIONS[name],
raw: '(SSH 연결 불가)', files: [],
summary: '(SSH 연결 불가)',
}; };
} }
} }
@@ -67,24 +91,37 @@ export class SisterDetailService {
sister.ip, sister.ip,
sister.user, sister.user,
sshKeyPath, 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 const sessions = result.stdout
.split('\n') .split('\n')
.filter((l) => l && !l.startsWith('total')); .filter((line) => line && !line.startsWith('total'))
return lines
.map((line) => { .map((line) => {
const parts = line.trim().split(/\s+/); 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 { return {
name: parts[parts.length - 1] ?? '', id: label,
modified: parts.slice(5, 8).join(' '), label,
size: parts[4] ?? '0', status: [modified, size !== '0' ? `${size}B` : null]
.filter((part): part is string => Boolean(part))
.join(' · '),
}; };
}) })
.filter((s) => s.name && s.name !== ''); .filter((session) => session.label.length > 0);
return {
sessions,
total: sessions.length,
};
} catch { } catch {
return []; return {
sessions: [],
total: 0,
};
} }
} }
@@ -100,15 +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 ""', 'AGENT_DIR=~/.hermes/workspace/agents; [ -d "$AGENT_DIR" ] || AGENT_DIR=~/.openclaw/workspace/agents; ls "$AGENT_DIR"/ 2>/dev/null || echo ""',
); );
const agents = result.stdout const items = result.stdout
.split('\n') .split('\n')
.filter((l) => l.trim().endsWith('.md')); .map((line) => line.trim())
return agents.map((a) => ({ .filter((line) => line.endsWith('.md'))
name: a.trim().replace('.md', ''), .map((file) => ({
file: a.trim(), id: file.replace('.md', ''),
label: file.replace('.md', ''),
file,
})); }));
return {
items,
total: items.length,
};
} catch { } catch {
return []; return {
items: [],
total: 0,
};
} }
} }
@@ -122,7 +169,16 @@ export class SisterDetailService {
}), }),
this.prisma.activityLog.count({ where: { sisterId: sister.id } }), 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() { async getOrgData() {
@@ -157,8 +213,8 @@ export class SisterDetailService {
} }
private getKeyPath(): string { private getKeyPath(): string {
const p = this.config.get<string>('SSH_KEY_PATH'); const path = this.config.get<string>('SSH_KEY_PATH');
if (!p) throw new Error('SSH_KEY_PATH is not set'); if (!path) throw new Error('SSH_KEY_PATH is not set');
return p; 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 type { Response } from 'express';
import { SistersService } from './sisters.service'; import { JwtGuard } from '../auth/jwt.guard';
import { SisterDetailService } from './sister-detail.service'; import { RoleGuard, Roles } from '../auth/role.guard';
import { SisterNamePipe } from '../common/sister-name.pipe'; import { SisterNamePipe } from '../common/sister-name.pipe';
import type { SisterName } from '../common/sister-name.pipe'; import type { SisterName } from '../common/sister-name.pipe';
import { AvatarService } from './avatar.service'; import { AvatarService } from './avatar.service';
import { SisterDetailService } from './sister-detail.service';
import { SistersService } from './sisters.service';
@Controller('api/sisters') @Controller('api/sisters')
@UseGuards(JwtGuard, RoleGuard)
@Roles('admin', 'viewer')
export class SistersController { export class SistersController {
constructor( constructor(
private readonly sistersService: SistersService, private readonly sistersService: SistersService,
@@ -14,14 +26,51 @@ export class SistersController {
private readonly avatarService: AvatarService, private readonly avatarService: AvatarService,
) {} ) {}
@Get('runtime')
async getSistersRuntime() {
return this.sistersService.getAllSistersRuntime();
}
@Get() @Get()
async getSistersStatus() { 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') @Get(':name/system')
async getSystemInfo(@Param('name', SisterNamePipe) name: SisterName) { async getSystemInfo(@Param('name', SisterNamePipe) name: SisterName) {
return this.sistersService.getSystemInfo(name); 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') @Get(':name/avatar')
@@ -36,25 +85,29 @@ export class SistersController {
const avatar = await this.avatarService.getAvatar(sister); const avatar = await this.avatarService.getAvatar(sister);
res.setHeader('Content-Type', avatar.contentType); 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); return res.send(avatar.data);
} }
@Roles('admin')
@Get(':name/config') @Get(':name/config')
async getSisterConfig(@Param('name', SisterNamePipe) name: SisterName) { async getSisterConfig(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterConfig(name); return this.sisterDetail.getSisterConfig(name);
} }
@Roles('admin')
@Get(':name/sessions') @Get(':name/sessions')
async getSisterSessions(@Param('name', SisterNamePipe) name: SisterName) { async getSisterSessions(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterSessions(name); return this.sisterDetail.getSisterSessions(name);
} }
@Roles('admin')
@Get(':name/subagents') @Get(':name/subagents')
async getSisterSubagents(@Param('name', SisterNamePipe) name: SisterName) { async getSisterSubagents(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterSubagents(name); return this.sisterDetail.getSisterSubagents(name);
} }
@Roles('admin')
@Get(':name/activity') @Get(':name/activity')
async getSisterActivity(@Param('name', SisterNamePipe) name: SisterName) { async getSisterActivity(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterActivityLog(name); return this.sisterDetail.getSisterActivityLog(name);

View File

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

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 { PrismaService } from '../prisma/prisma.service';
import { SshService } from './ssh.service'; import { SshService } from './ssh.service';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { ActivityService } from '../activity/activity.service'; 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 { export interface SisterStatus {
id: number; id: number;
name: string; name: string;
@@ -13,6 +52,28 @@ export interface SisterStatus {
status: 'online' | 'offline' | 'working' | 'unknown'; status: 'online' | 'offline' | 'working' | 'unknown';
lastSeen: Date | null; lastSeen: Date | null;
currentTask: string | 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> = { const SISTER_ROLES: Record<string, string> = {
@@ -22,6 +83,17 @@ const SISTER_ROLES: Record<string, string> = {
erang: 'Infra Manager', 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() @Injectable()
export class SistersService { export class SistersService {
private readonly logger = new Logger(SistersService.name); private readonly logger = new Logger(SistersService.name);
@@ -34,7 +106,7 @@ export class SistersService {
) {} ) {}
async getAllSistersStatus(): Promise<SisterStatus[]> { 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'); const sshKeyPath = this.config.get<string>('SSH_KEY_PATH');
if (!sshKeyPath) { if (!sshKeyPath) {
throw new Error('SSH_KEY_PATH is not set. Check your .env file.'); throw new Error('SSH_KEY_PATH is not set. Check your .env file.');
@@ -49,19 +121,85 @@ export class SistersService {
return result.value; return result.value;
} }
const sister = sisters[index]; const sister = sisters[index];
return { return this.buildOfflineStatus(sister);
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,
};
}); });
} }
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) { async findByName(name: string) {
return this.prisma.sisterConfig.findUnique({ where: { name } }); return this.prisma.sisterConfig.findUnique({ where: { name } });
} }
@@ -138,21 +276,17 @@ export class SistersService {
sshKeyPath: string, sshKeyPath: string,
): Promise<SisterStatus> { ): Promise<SisterStatus> {
try { try {
const result = await this.ssh.executeCommand( const runtime = await this.probeRuntime(sister, sshKeyPath, false);
sister.ip, const gatewayConnected = Boolean(runtime.gatewayConnected);
sister.user, const liveState = runtime.mainState ?? (gatewayConnected ? 'idle' : 'error');
sshKeyPath, const status = runtimeStateToStatus(liveState, gatewayConnected);
'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 prevStatus = sister.status; const prevStatus = sister.status;
const now = new Date(); const now = new Date();
const lastSeen = gatewayConnected ? now : sister.lastSeen;
await this.prisma.sisterConfig.update({ await this.prisma.sisterConfig.update({
where: { id: sister.id }, where: { id: sister.id },
data: { lastSeen: isActive ? now : sister.lastSeen, status }, data: { lastSeen, status },
}); });
if (prevStatus !== status && this.activity) { if (prevStatus !== status && this.activity) {
@@ -172,11 +306,68 @@ export class SistersService {
lxcId: sister.lxcId, lxcId: sister.lxcId,
role: SISTER_ROLES[sister.name] ?? 'Unknown', role: SISTER_ROLES[sister.name] ?? 'Unknown',
status, status,
lastSeen: isActive ? now : sister.lastSeen, lastSeen,
currentTask: null, currentTask: runtime.currentTask ?? null,
liveState,
activeSessionLabel: runtime.activeSessionLabel ?? null,
gatewayConnected,
subagents: runtime.subagents ?? [],
}; };
} catch { } catch {
this.logger.warn(`Failed to check status for ${sister.name}`); 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 { return {
id: sister.id, id: sister.id,
name: sister.name, name: sister.name,
@@ -186,8 +377,377 @@ export class SistersService {
status: 'offline', status: 'offline',
lastSeen: sister.lastSeen, lastSeen: sister.lastSeen,
currentTask: null, 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 {
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) { private parseUptime(stdout: string) {

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

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

View File

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

View File

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

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

@@ -0,0 +1,475 @@
'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';
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>
)}
</>
) : (
<Empty> .</Empty>
)}
</Pane>
</Layout>
{detailNodeId && (
<SubTaskDetailDrawer
subTaskId={detailNodeId}
onClose={() => setDetailNodeId(null)}
/>
)}
</Page>
);
}

View File

@@ -8,6 +8,10 @@ import { useAuth } from '@/lib/AuthContext';
const NAV_ITEMS = [ const NAV_ITEMS = [
{ href: '/', label: '대시' }, { href: '/', label: '대시' },
{ href: '/rails', label: '레일' },
{ href: '/rails/log', label: '로그' },
{ href: '/rails/escalations', label: '경보' },
{ href: '/office', label: '오피스' },
{ href: '/projects', label: '프로' }, { href: '/projects', label: '프로' },
{ href: '/activities', label: '활동' }, { href: '/activities', label: '활동' },
{ href: '/sisters', label: '자매' }, { href: '/sisters', label: '자매' },

View File

@@ -46,10 +46,10 @@ interface SisterAvatarProps {
} }
export default function SisterAvatar({ name, size = 32, className, style }: 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(); 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>; 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} alt={name}
className={className} className={className}
style={style} style={style}
onError={() => setFailed(true)} onError={() => setFailedFor(name)}
/> />
); );
} }

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

View File

@@ -0,0 +1,496 @@
'use client';
import React, { useCallback } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
export type AgentState = 'idle' | 'thinking' | 'tool_calling' | 'speaking' | 'error';
export type SisterName = 'harang' | 'narang' | 'darang' | 'erang';
export interface SubAgent {
id: string;
name: string;
label: string;
sister: SisterName;
state: AgentState;
currentTask?: string | null;
updatedAt?: number | null;
sessionLabel?: string | null;
}
export interface SisterNode {
name: SisterName;
displayName: string;
role: string;
state: AgentState;
currentTask: string | null;
activeSessionLabel?: string | null;
subagents: SubAgent[];
}
export type SelectedAgent =
| { type: 'sister'; name: SisterName }
| { type: 'subagent'; id: string; sister: SisterName };
interface OfficeSceneProps {
sisters: SisterNode[];
selected: SelectedAgent | null;
onSelectSister: (name: SisterName) => void;
onSelectSubagent: (id: string, sister: SisterName) => void;
dataMode: 'live' | 'snapshot' | 'fallback';
subagentMode: 'live' | 'fallback';
}
const SceneWrapper = styled.div`
position: relative;
width: 100%;
aspect-ratio: 800 / 460;
max-height: 60vh;
border: 1px solid var(--border-color);
background: var(--bg-surface);
overflow: hidden;
user-select: none;
`;
const FreshnessLabel = styled.div`
position: absolute;
top: 8px;
right: 12px;
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
pointer-events: none;
`;
const WsDot = styled.span<{ $connected: boolean }>`
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
background: ${({ $connected }) => ($connected ? '#00FF00' : '#666')};
margin-right: 5px;
vertical-align: middle;
`;
const VB_W = 800;
const VB_H = 460;
type Point = [number, number];
const ZONES = {
harang: [5, 5, 345, 200] as const,
darang: [450, 5, 345, 200] as const,
narang: [5, 260, 345, 195] as const,
erang: [450, 260, 345, 195] as const,
};
const SISTER_POS: Record<SisterName, [number, number]> = {
harang: [75, 105],
darang: [725, 105],
narang: [75, 358],
erang: [725, 358],
};
const CONF = { cx: 400, cy: 232, rx: 55, ry: 30 };
const SUBAGENT_POSITIONS: Record<SisterName, Point[]> = {
harang: [[175, 65], [270, 65], [220, 160]],
darang: [[460, 65], [560, 65], [660, 65], [460, 160], [560, 160]],
narang: [[175, 295], [270, 295], [175, 395], [270, 395]],
erang: [[460, 295], [555, 295], [650, 295], [460, 395], [555, 395]],
};
const SUBAGENT_TARGETS: Record<SisterName, Point[]> = {
harang: [[295, 112], [338, 148], [365, 190]],
darang: [[505, 94], [560, 112], [462, 148], [438, 188], [520, 196]],
narang: [[292, 332], [330, 302], [362, 276], [344, 374]],
erang: [[618, 322], [664, 298], [702, 286], [610, 388], [664, 380]],
};
const ZONE_COLORS: Record<SisterName, string> = {
harang: 'rgba(41, 121, 255, 0.06)',
narang: 'rgba(0, 191, 165, 0.06)',
darang: 'rgba(255, 64, 129, 0.06)',
erang: 'rgba(255, 109, 0, 0.06)',
};
const ZONE_BORDER: Record<SisterName, string> = {
harang: 'rgba(41, 121, 255, 0.25)',
narang: 'rgba(0, 191, 165, 0.25)',
darang: 'rgba(255, 64, 129, 0.25)',
erang: 'rgba(255, 109, 0, 0.25)',
};
const STATE_COLORS: Record<AgentState, string> = {
idle: '#444444',
thinking: '#2979FF',
tool_calling: '#FF9800',
speaking: '#00BFA5',
error: '#FF1744',
};
const STATE_PROGRESS: Record<AgentState, number> = {
idle: 0,
error: 0,
thinking: 0.48,
tool_calling: 0.88,
speaking: 0.66,
};
function lerpPoint(from: Point, to: Point, progress: number): Point {
return [
from[0] + (to[0] - from[0]) * progress,
from[1] + (to[1] - from[1]) * progress,
];
}
function getSubagentPosition(sister: SisterName, index: number, state: AgentState): Point {
const from = SUBAGENT_POSITIONS[sister][index] ?? SUBAGENT_POSITIONS[sister][0];
const to = SUBAGENT_TARGETS[sister][index] ?? from;
return lerpPoint(from, to, STATE_PROGRESS[state]);
}
function getSubagentMotion(state: AgentState, index: number): { dx: number; dy: number; dur: string } | null {
const phase = index % 2 === 0 ? 1 : -1;
if (state === 'thinking') return { dx: 5 * phase, dy: -6, dur: '3.6s' };
if (state === 'tool_calling') return { dx: 10 * phase, dy: -14, dur: '2s' };
if (state === 'speaking') return { dx: 6 * phase, dy: -4, dur: '2.8s' };
return null;
}
function SisterCircle({
cx,
cy,
r,
state,
name,
selected,
onClick,
}: {
cx: number;
cy: number;
r: number;
state: AgentState;
name: SisterName;
selected: boolean;
onClick: () => void;
}) {
const color = STATE_COLORS[state];
const clipId = `avatar-clip-${name}`;
return (
<g
role="button"
tabIndex={0}
aria-label={`${name} — state: ${state}`}
onClick={onClick}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick(); } }}
style={{ cursor: 'pointer', outline: 'none' }}
>
{selected && (
<circle
cx={cx}
cy={cy}
r={r + 8}
fill="none"
stroke="var(--text-primary)"
strokeWidth={1}
strokeDasharray="4 3"
opacity={0.6}
/>
)}
<circle
cx={cx}
cy={cy}
r={r + 4}
fill="none"
stroke={color}
strokeWidth={state === 'error' ? 2.5 : 1.5}
opacity={state === 'idle' ? 0.4 : 1}
>
{state === 'thinking' && (
<animate attributeName="opacity" values="0.45;1;0.45" dur="1.8s" repeatCount="indefinite" />
)}
{state === 'tool_calling' && (
<animate attributeName="stroke-opacity" values="1;0.2;1" dur="0.9s" repeatCount="indefinite" />
)}
</circle>
<circle cx={cx} cy={cy} r={r} fill="#1e1e1e" stroke={color} strokeWidth={1} />
<defs>
<clipPath id={clipId}>
<circle cx={cx} cy={cy} r={r - 2} />
</clipPath>
</defs>
<image
href={`${API_URL}/api/sisters/${name}/avatar`}
x={cx - r + 2}
y={cy - r + 2}
width={(r - 2) * 2}
height={(r - 2) * 2}
preserveAspectRatio="xMidYMid slice"
clipPath={`url(#${clipId})`}
/>
<text
x={cx}
y={cy + r + 16}
textAnchor="middle"
fontSize={9}
fontFamily="var(--font-mono)"
fill={color}
style={{ textTransform: 'uppercase', letterSpacing: '0.06em', userSelect: 'none', pointerEvents: 'none' }}
>
{state}
</text>
</g>
);
}
function SubagentCircle({
cx,
cy,
r,
state,
label,
selected,
motion,
motionBegin,
onClick,
}: {
cx: number;
cy: number;
r: number;
state: AgentState;
label: string;
selected: boolean;
motion: { dx: number; dy: number; dur: string } | null;
motionBegin: string;
onClick: () => void;
}) {
const color = STATE_COLORS[state];
return (
<g
role="button"
tabIndex={0}
aria-label={`subagent ${label} — state: ${state}`}
onClick={onClick}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick(); } }}
style={{ cursor: 'pointer', outline: 'none' }}
>
{motion && (
<animateTransform
attributeName="transform"
type="translate"
values={`0 0; ${motion.dx} ${motion.dy}; 0 0`}
dur={motion.dur}
begin={motionBegin}
repeatCount="indefinite"
/>
)}
{selected && (
<circle cx={cx} cy={cy} r={r + 5} fill="none" stroke="var(--text-primary)" strokeWidth={1} opacity={0.5} />
)}
<circle cx={cx} cy={cy} r={r + 2} fill="none" stroke={color} strokeWidth={1} opacity={state === 'idle' ? 0.3 : 0.8}>
{state === 'thinking' && (
<animate attributeName="opacity" values="0.35;0.95;0.35" dur="2s" repeatCount="indefinite" />
)}
</circle>
<circle cx={cx} cy={cy} r={r} fill="#1a1a1a" stroke={color} strokeWidth={0.8} />
<text
x={cx}
y={cy + 4}
textAnchor="middle"
fontSize={8}
fontFamily="var(--font-mono)"
fill={color}
opacity={0.9}
style={{ userSelect: 'none', pointerEvents: 'none' }}
>
{label.length > 8 ? `${label.slice(0, 7)}` : label}
</text>
</g>
);
}
function ConnectorLine({ x1, y1, x2, y2, active }: { x1: number; y1: number; x2: number; y2: number; active: boolean }) {
return (
<line
x1={x1}
y1={y1}
x2={x2}
y2={y2}
stroke={active ? 'rgba(245,245,245,0.35)' : 'rgba(255,255,255,0.08)'}
strokeWidth={active ? 1.5 : 1}
strokeDasharray={active ? '6 4' : '3 4'}
strokeDashoffset={active ? 40 : 0}
>
{active && <animate attributeName="stroke-dashoffset" values="40;0" dur="1.4s" repeatCount="indefinite" />}
</line>
);
}
function PathConnector({ d, active }: { d: string; active: boolean }) {
return (
<path
d={d}
fill="none"
stroke={active ? 'rgba(245,245,245,0.3)' : 'rgba(255,255,255,0.06)'}
strokeWidth={active ? 1.5 : 1}
strokeDasharray={active ? '6 4' : '3 4'}
strokeDashoffset={active ? 40 : 0}
>
{active && <animate attributeName="stroke-dashoffset" values="40;0" dur="1.8s" repeatCount="indefinite" />}
</path>
);
}
const SISTER_ORDER: SisterName[] = ['harang', 'narang', 'darang', 'erang'];
export default function OfficeScene({
sisters,
selected,
onSelectSister,
onSelectSubagent,
dataMode,
subagentMode,
}: OfficeSceneProps) {
const getSister = useCallback(
(name: SisterName) => sisters.find((s) => s.name === name),
[sisters],
);
const isActive = useCallback(
(name: SisterName) => {
const sister = getSister(name);
return sister?.state === 'thinking' || sister?.state === 'tool_calling' || sister?.state === 'speaking';
},
[getSister],
);
const isSisterSelected = (name: SisterName) => selected?.type === 'sister' && selected.name === name;
const isSubSelected = (id: string) => selected?.type === 'subagent' && selected.id === id;
const harangActive = isActive('harang');
const narangActive = isActive('narang');
const darangActive = isActive('darang');
const erangActive = isActive('erang');
return (
<SceneWrapper>
<FreshnessLabel>
<WsDot $connected={dataMode === 'live'} />
{dataMode === 'live' ? 'live · ws' : dataMode === 'snapshot' ? 'snapshot · poll' : 'fallback · doc-derived'}
{subagentMode === 'live' ? ' · subagents: live · runtime' : ' · subagents: fallback'}
</FreshnessLabel>
<svg viewBox={`0 0 ${VB_W} ${VB_H}`} width="100%" height="100%" style={{ display: 'block' }}>
{SISTER_ORDER.map((name) => {
const [zx, zy, zw, zh] = ZONES[name];
return (
<rect
key={`zone-${name}`}
x={zx}
y={zy}
width={zw}
height={zh}
rx={4}
fill={ZONE_COLORS[name]}
stroke={ZONE_BORDER[name]}
strokeWidth={1}
/>
);
})}
<rect x={358} y={5} width={84} height={450} rx={2} fill="#111111" stroke="rgba(255,255,255,0.04)" strokeWidth={1} />
<rect x={5} y={205} width={790} height={50} rx={2} fill="#111111" stroke="rgba(255,255,255,0.04)" strokeWidth={1} />
<ellipse cx={CONF.cx} cy={CONF.cy} rx={CONF.rx} ry={CONF.ry} fill="#1a1a1a" stroke="rgba(255,255,255,0.15)" strokeWidth={1} />
<text x={CONF.cx} y={CONF.cy + 4} textAnchor="middle" fontSize={9} fontFamily="var(--font-mono)" fill="rgba(255,255,255,0.4)">
</text>
<ConnectorLine x1={SISTER_POS.harang[0]} y1={SISTER_POS.harang[1] + 30} x2={SISTER_POS.narang[0]} y2={SISTER_POS.narang[1] - 30} active={harangActive || narangActive} />
<ConnectorLine x1={SISTER_POS.darang[0]} y1={SISTER_POS.darang[1] + 30} x2={SISTER_POS.erang[0]} y2={SISTER_POS.erang[1] - 30} active={darangActive || erangActive} />
<ConnectorLine x1={SISTER_POS.harang[0] + 30} y1={SISTER_POS.harang[1]} x2={SISTER_POS.darang[0] - 30} y2={SISTER_POS.darang[1]} active={harangActive || darangActive} />
<ConnectorLine x1={SISTER_POS.narang[0] + 30} y1={SISTER_POS.narang[1]} x2={SISTER_POS.erang[0] - 30} y2={SISTER_POS.erang[1]} active={narangActive || erangActive} />
<PathConnector d={`M${SISTER_POS.narang[0] + 20},${SISTER_POS.narang[1] - 20} Q${CONF.cx},${CONF.cy} ${SISTER_POS.darang[0] - 20},${SISTER_POS.darang[1] + 20}`} active={narangActive && darangActive} />
{([
['harang', 18, 22, '하랑이 · Planning'] as const,
['darang', 463, 22, '다랑이 · QA'] as const,
['narang', 18, 272, '나랑이 · Dev'] as const,
['erang', 463, 272, '이랑이 · Infra'] as const,
] as const).map(([name, lx, ly, text]) => (
<text key={`label-${name}`} x={lx} y={ly} fontSize={10} fontFamily="var(--font-mono)" fill={ZONE_BORDER[name]}>
{text}
</text>
))}
{SISTER_ORDER.map((name) => {
const sister = getSister(name);
const state: AgentState = sister?.state ?? 'idle';
const [cx, cy] = SISTER_POS[name];
return (
<SisterCircle
key={`sister-${name}`}
cx={cx}
cy={cy}
r={28}
state={state}
name={name}
selected={isSisterSelected(name)}
onClick={() => onSelectSister(name)}
/>
);
})}
{SISTER_ORDER.map((sisterName) => {
const sister = getSister(sisterName);
const subagents = sister?.subagents ?? [];
return subagents.map((sub, i) => {
const pos = getSubagentPosition(sisterName, i, sub.state);
const motion = getSubagentMotion(sub.state, i);
return (
<SubagentCircle
key={sub.id}
cx={pos[0]}
cy={pos[1]}
r={14}
state={sub.state}
label={sub.name}
selected={isSubSelected(sub.id)}
motion={motion}
motionBegin={`${i * 0.22}s`}
onClick={() => onSelectSubagent(sub.id, sisterName)}
/>
);
});
})}
{SISTER_ORDER.map((sisterName) => {
const sister = getSister(sisterName);
const subagents = sister?.subagents ?? [];
const [sx, sy] = SISTER_POS[sisterName];
return subagents.map((sub, i) => {
const pos = getSubagentPosition(sisterName, i, sub.state);
const active = sub.state !== 'idle' && sub.state !== 'error';
return (
<line
key={`conn-${sub.id}`}
x1={sx}
y1={sy}
x2={pos[0]}
y2={pos[1]}
stroke={active ? ZONE_BORDER[sisterName] : 'rgba(255,255,255,0.05)'}
strokeWidth={active ? 0.8 : 0.5}
strokeDasharray="2 3"
/>
);
});
})}
</svg>
</SceneWrapper>
);
}

View File

@@ -0,0 +1,275 @@
'use client';
import React from 'react';
import styled, { css, keyframes } from 'styled-components';
import type { PipelineNode } from '@/components/dashboard/ActivePipeline';
// ─── Types ───────────────────────────────────────────────────────────────────
interface PipelinePanelProps {
activeTask: string;
focus: string;
reviewLoopCount: number;
escalationCount: number;
deployState: string;
nodes: PipelineNode[];
freshness: string;
}
// ─── Animations ──────────────────────────────────────────────────────────────
const flowAnim = keyframes`
0% { transform: translateX(-100%); opacity: 0; }
40% { opacity: 0.8; }
100% { transform: translateX(100%); opacity: 0; }
`;
// ─── Styled Components ────────────────────────────────────────────────────────
const Panel = styled.section`
border: 1px solid var(--border-color);
background: var(--bg-surface);
display: flex;
flex-direction: column;
gap: var(--space-md);
padding: var(--space-lg);
`;
const PanelHeader = styled.div`
display: flex;
align-items: baseline;
gap: var(--space-lg);
justify-content: space-between;
flex-wrap: wrap;
`;
const TitleGroup = styled.div`
display: flex;
flex-direction: column;
gap: 4px;
`;
const Eyebrow = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const Title = styled.h3`
font-size: 15px;
font-weight: 600;
color: var(--text-primary);
letter-spacing: -0.01em;
margin: 0;
`;
const Focus = styled.div`
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.04em;
max-width: 500px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@media (max-width: 767px) {
max-width: 100%;
white-space: normal;
}
`;
const Stats = styled.div`
display: flex;
gap: var(--space-md);
flex-wrap: wrap;
`;
const Stat = styled.div`
display: flex;
flex-direction: column;
gap: 2px;
min-width: 80px;
`;
const StatLabel = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
`;
const StatValue = styled.div`
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
`;
const NodeRow = styled.div`
display: flex;
gap: var(--space-sm);
align-items: stretch;
overflow-x: auto;
scrollbar-width: thin;
scrollbar-color: var(--border-color) transparent;
@media (max-width: 767px) {
flex-direction: column;
overflow-x: visible;
}
`;
const stateColors: Record<PipelineNode['state'], string> = {
idle: 'var(--border-color)',
active: '#6fc3ff',
review: '#ff7ac6',
blocked: '#ff8d7a',
ready: '#8dffb2',
};
const NodeCard = styled.div<{ $state: PipelineNode['state'] }>`
border: 1px solid ${({ $state }) => stateColors[$state]};
padding: var(--space-sm) var(--space-md);
min-width: 140px;
flex-shrink: 0;
display: flex;
flex-direction: column;
gap: 4px;
@media (max-width: 767px) {
min-width: 0;
}
`;
const NodeName = styled.div`
font-size: 13px;
font-weight: 600;
color: var(--text-primary);
`;
const NodeRole = styled.div`
font-size: 10px;
color: var(--text-secondary);
`;
const NodeState = styled.div<{ $state: PipelineNode['state'] }>`
font-family: var(--font-mono);
font-size: 10px;
color: ${({ $state }) => stateColors[$state]};
text-transform: uppercase;
letter-spacing: 0.06em;
`;
const NodeDetail = styled.div`
font-size: 11px;
color: var(--text-secondary);
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
`;
const Connector = styled.div<{ $active: boolean }>`
width: 24px;
flex-shrink: 0;
height: 1px;
background: ${({ $active }) => $active ? 'rgba(245,245,245,0.4)' : 'var(--border-color)'};
position: relative;
overflow: hidden;
align-self: center;
&::after {
content: '';
position: absolute;
top: -2px;
left: 0;
width: 100%;
height: 5px;
background: ${({ $active }) => $active ? 'rgba(245,245,245,0.8)' : 'transparent'};
animation: ${({ $active }) => $active ? css`${flowAnim} 1.6s linear infinite` : 'none'};
}
@media (max-width: 767px) {
width: 1px;
height: 16px;
align-self: flex-start;
margin-left: var(--space-lg);
}
`;
const FreshnessNote = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
opacity: 0.6;
text-transform: uppercase;
letter-spacing: 0.06em;
`;
// ─── Component ────────────────────────────────────────────────────────────────
export default function PipelinePanel({
activeTask,
focus,
reviewLoopCount,
escalationCount,
deployState,
nodes,
freshness,
}: PipelinePanelProps) {
return (
<Panel>
<PanelHeader>
<TitleGroup>
<Eyebrow>pipeline panel · snapshot</Eyebrow>
<Title>{activeTask}</Title>
<Focus>{focus}</Focus>
</TitleGroup>
<Stats>
<Stat>
<StatLabel>review loop</StatLabel>
<StatValue>{reviewLoopCount}x</StatValue>
</Stat>
<Stat>
<StatLabel>escalations</StatLabel>
<StatValue>{escalationCount}</StatValue>
</Stat>
<Stat>
<StatLabel>deploy state</StatLabel>
<StatValue>{deployState}</StatValue>
</Stat>
</Stats>
</PanelHeader>
{nodes.length > 0 ? (
<NodeRow>
{nodes.map((node, i) => {
const active = node.state === 'active' || node.state === 'review' || node.state === 'ready';
return (
<React.Fragment key={node.id}>
<NodeCard $state={node.state}>
<NodeName>{node.label}</NodeName>
<NodeRole>{node.role}</NodeRole>
<NodeState $state={node.state}>{node.state}</NodeState>
<NodeDetail>{node.detail}</NodeDetail>
</NodeCard>
{i < nodes.length - 1 && <Connector $active={active} />}
</React.Fragment>
);
})}
</NodeRow>
) : (
<NodeRole style={{ color: 'var(--text-secondary)', fontSize: '12px' }}>
</NodeRole>
)}
<FreshnessNote>snapshot · {freshness}</FreshnessNote>
</Panel>
);
}

View File

@@ -0,0 +1,189 @@
'use client';
import React from 'react';
import styled from 'styled-components';
// ─── Types ───────────────────────────────────────────────────────────────────
export interface ServerEntry {
id: string;
label: string;
type: 'sister' | 'dev' | 'docker';
status: 'online' | 'offline' | 'working' | 'unknown';
detail?: string | null;
source: 'live' | 'snapshot' | 'fallback';
}
interface ServerHealthPanelProps {
servers: ServerEntry[];
dataMode: 'live' | 'snapshot' | 'fallback';
generatedAt: string;
}
// ─── Styled Components ────────────────────────────────────────────────────────
const Panel = styled.section`
border: 1px solid var(--border-color);
background: var(--bg-surface);
padding: var(--space-lg);
display: flex;
flex-direction: column;
gap: var(--space-md);
`;
const PanelHeader = styled.div`
display: flex;
align-items: center;
gap: var(--space-md);
justify-content: space-between;
`;
const Eyebrow = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const WsDot = styled.span<{ $connected: boolean }>`
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
background: ${({ $connected }) => ($connected ? '#00FF00' : '#555')};
margin-right: 4px;
vertical-align: middle;
`;
const FreshnessNote = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
opacity: 0.5;
text-transform: uppercase;
letter-spacing: 0.06em;
`;
const Grid = styled.div`
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: var(--space-sm);
@media (max-width: 767px) {
grid-template-columns: repeat(2, 1fr);
}
@media (max-width: 359px) {
grid-template-columns: 1fr;
}
`;
const statusColors: Record<ServerEntry['status'], string> = {
online: '#00FF00',
offline: '#FF1744',
working: '#2979FF',
unknown: '#555555',
};
const ServerCard = styled.div<{ $status: ServerEntry['status'] }>`
border: 1px solid var(--border-color);
border-left: 2px solid ${({ $status }) => statusColors[$status]};
padding: var(--space-sm) var(--space-md);
display: flex;
flex-direction: column;
gap: 4px;
`;
const CardLabel = styled.div`
font-size: 12px;
font-weight: 600;
color: var(--text-primary);
display: flex;
align-items: center;
gap: 6px;
`;
const StatusDot = styled.span<{ $status: ServerEntry['status'] }>`
width: 6px;
height: 6px;
border-radius: 50%;
flex-shrink: 0;
background: ${({ $status }) => statusColors[$status]};
`;
const CardStatus = styled.div<{ $status: ServerEntry['status'] }>`
font-family: var(--font-mono);
font-size: 10px;
color: ${({ $status }) => statusColors[$status]};
text-transform: uppercase;
letter-spacing: 0.06em;
`;
const CardDetail = styled.div`
font-size: 11px;
color: var(--text-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
const SourceBadge = styled.span`
font-family: var(--font-mono);
font-size: 9px;
color: var(--text-secondary);
opacity: 0.5;
text-transform: uppercase;
letter-spacing: 0.06em;
`;
// ─── Component ────────────────────────────────────────────────────────────────
function formatGeneratedAt(ts: string): string {
try {
const date = new Date(ts);
const diff = Date.now() - date.getTime();
const sec = Math.floor(diff / 1000);
if (sec < 60) return `${sec}s ago`;
const min = Math.floor(sec / 60);
if (min < 60) return `${min}m ago`;
return `${Math.floor(min / 60)}h ago`;
} catch {
return ts;
}
}
export default function ServerHealthPanel({
servers,
dataMode,
generatedAt,
}: ServerHealthPanelProps) {
const onlineCount = servers.filter((s) => s.status === 'online' || s.status === 'working').length;
return (
<Panel>
<PanelHeader>
<Eyebrow>
<WsDot $connected={dataMode === 'live'} />
server health · {dataMode}
{' · '}{onlineCount}/{servers.length} online
</Eyebrow>
<FreshnessNote>refreshed {formatGeneratedAt(generatedAt)}</FreshnessNote>
</PanelHeader>
<Grid>
{servers.map((server) => (
<ServerCard key={server.id} $status={server.status}>
<CardLabel>
<StatusDot $status={server.status} />
{server.label}
</CardLabel>
<CardStatus $status={server.status}>{server.status}</CardStatus>
{server.detail && <CardDetail>{server.detail}</CardDetail>}
<SourceBadge>{server.source}</SourceBadge>
</ServerCard>
))}
</Grid>
</Panel>
);
}

View File

@@ -0,0 +1,118 @@
'use client';
import React from 'react';
import styled from 'styled-components';
import type { RailsPipelineSummary } from '@/lib/useRailsSocket';
const Wrap = styled.div`
display: flex;
flex-direction: column;
gap: 8px;
`;
const Card = styled.button<{ $active: boolean }>`
display: flex;
align-items: center;
gap: 12px;
padding: 12px 14px;
background: ${({ $active }) =>
$active ? 'var(--bg-input)' : 'var(--bg-surface)'};
border: 1px solid ${({ $active }) =>
$active ? '#5fafff' : 'var(--border-color)'};
border-radius: 8px;
color: var(--text-primary);
cursor: pointer;
text-align: left;
transition: all 0.15s;
&:hover {
border-color: #5fafff;
}
`;
const StateBadge = styled.span<{ $state: string }>`
display: inline-block;
padding: 2px 10px;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
border-radius: 12px;
color: #fff;
background: ${({ $state }) => {
switch ($state) {
case 'done':
return '#22c55e';
case 'escalated':
return '#ef4444';
case 'aborted':
return '#6b7280';
case 'planning':
case 'implementing':
case 'reviewing':
case 'deploying':
return '#f97316';
default:
return '#6b7280';
}
}};
`;
const Id = styled.span`
font-family: var(--font-mono, monospace);
font-size: 11px;
opacity: 0.6;
`;
const Name = styled.span`
font-weight: 600;
flex: 1;
`;
const Time = styled.span`
font-size: 11px;
opacity: 0.6;
`;
interface Props {
pipelines: RailsPipelineSummary[];
selectedId: string | null;
onSelect: (id: string) => void;
}
export default function PipelineList({ pipelines, selectedId, onSelect }: Props) {
if (pipelines.length === 0) {
return <Wrap>No pipelines yet.</Wrap>;
}
return (
<Wrap>
{pipelines.map((p) => (
<Card
key={p.id}
$active={p.id === selectedId}
onClick={() => onSelect(p.id)}
>
<Id>{p.id.slice(0, 8)}</Id>
<Name>{p.projectName}</Name>
<StateBadge $state={p.currentState}>{p.currentState}</StateBadge>
<Time>{formatTime(p.updatedAt)}</Time>
</Card>
))}
</Wrap>
);
}
function formatTime(iso: string): string {
try {
const d = new Date(iso);
const now = Date.now();
const diffMs = now - d.getTime();
const sec = Math.floor(diffMs / 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;
}
}

View File

@@ -0,0 +1,634 @@
'use client';
import React, { useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import ReactMarkdown from 'react-markdown';
import { API_URL } from '@/lib/config';
import SisterAvatar from '@/components/common/SisterAvatar';
const SISTER_NAMES = new Set(['harang', 'narang', 'darang', 'erang']);
function parseResult(
raw: string | null,
): { text: string; ok: boolean; extra?: Record<string, unknown> } | null {
if (!raw) return null;
try {
const parsed = JSON.parse(raw) as Record<string, unknown>;
if (typeof parsed === 'object' && parsed !== null) {
const text = typeof parsed.text === 'string' ? parsed.text : '';
const ok = parsed.ok !== false;
const { text: _t, ok: _o, ...rest } = parsed as {
text?: unknown;
ok?: unknown;
} & Record<string, unknown>;
void _t;
void _o;
return { text, ok, extra: Object.keys(rest).length > 0 ? rest : undefined };
}
} catch {
return { text: raw, ok: true };
}
return null;
}
interface SubTaskEvent {
id: number;
eventType: string;
payload: unknown;
timestamp: string;
}
interface ParentLink {
id: string;
role: string;
title: string;
}
interface ChildSummary {
id: string;
role: string;
agentName: string;
title: string;
state: string;
model: string;
startedAt: string | null;
completedAt: string | null;
}
interface SubTaskDetail {
id: string;
pipelineId: string;
parentId: string | null;
role: string;
agentName: string;
title: string;
description: string;
state: string;
complexityScore: number | null;
complexityTier: string | null;
model: string;
resultJson: string | null;
errorReason: string | null;
startedAt: string | null;
completedAt: string | null;
createdAt: string;
parents: ParentLink[];
childrenList: ChildSummary[];
events: SubTaskEvent[];
}
const Backdrop = styled.div`
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.55);
z-index: 50;
display: flex;
justify-content: flex-end;
`;
const Drawer = styled.div`
width: min(640px, 95vw);
height: 100%;
background: var(--bg-main);
border-left: 1px solid var(--border-color);
overflow-y: auto;
display: flex;
flex-direction: column;
`;
const Header = styled.div`
position: sticky;
top: 0;
background: var(--bg-main);
padding: 24px 28px 18px;
border-bottom: 1px solid var(--border-color);
display: flex;
flex-direction: column;
gap: 10px;
z-index: 1;
`;
const TopRow = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
`;
const RoleBadge = styled.span<{ $role: string }>`
padding: 4px 12px;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
border-radius: 14px;
color: #fff;
background: ${({ $role }) => roleColor($role)};
`;
const Close = styled.button`
background: transparent;
border: 1px solid var(--border-color);
color: var(--text-primary);
padding: 6px 14px;
border-radius: 8px;
cursor: pointer;
font-size: 12px;
&:hover {
border-color: #5fafff;
}
`;
const Title = styled.h2`
font-size: 20px;
font-weight: 700;
margin: 0;
letter-spacing: -0.01em;
word-break: break-word;
`;
const Breadcrumb = styled.div`
display: flex;
gap: 6px;
font-size: 11px;
color: var(--text-secondary);
font-family: var(--font-mono);
flex-wrap: wrap;
`;
const Body = styled.div`
padding: 24px 28px;
display: flex;
flex-direction: column;
gap: 24px;
`;
const Section = styled.section`
display: flex;
flex-direction: column;
gap: 10px;
`;
const SectionLabel = styled.h3`
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-secondary);
margin: 0;
`;
const Grid = styled.div`
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 12px;
`;
const Field = styled.div`
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 10px;
padding: 12px 14px;
display: flex;
flex-direction: column;
gap: 4px;
`;
const FieldLabel = styled.span`
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-secondary);
`;
const FieldValue = styled.span`
font-size: 13px;
font-weight: 500;
font-family: var(--font-mono);
word-break: break-all;
`;
const StateBadge = styled.span<{ $state: string }>`
display: inline-block;
padding: 3px 10px;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
border-radius: 12px;
color: #fff;
background: ${({ $state }) => stateColor($state)};
`;
const Description = styled.p`
font-size: 13px;
line-height: 1.6;
color: var(--text-primary);
background: var(--bg-input);
padding: 14px 16px;
border-radius: 10px;
margin: 0;
white-space: pre-wrap;
word-break: break-word;
`;
const LlmOutput = styled.div<{ $ok: boolean }>`
background: var(--bg-input);
border: 1px solid ${({ $ok }) => ($ok ? 'var(--border-color)' : '#ef444460')};
border-left: 4px solid ${({ $ok }) => ($ok ? '#5fafff' : '#ef4444')};
padding: 18px 22px;
border-radius: 10px;
font-size: 13px;
line-height: 1.75;
color: var(--text-primary);
& > *:first-child { margin-top: 0; }
& > *:last-child { margin-bottom: 0; }
h1, h2, h3, h4, h5, h6 {
font-size: 14px;
font-weight: 700;
margin: 14px 0 6px;
color: var(--text-primary);
}
p { margin: 10px 0; }
ul, ol {
margin: 10px 0;
padding-left: 22px;
}
li { margin: 4px 0; }
code {
background: var(--bg-surface);
padding: 1px 6px;
border-radius: 4px;
font-size: 12px;
font-family: var(--font-mono);
color: #5fafff;
}
pre {
background: var(--bg-surface);
border: 1px solid var(--border-color);
padding: 12px 14px;
border-radius: 8px;
overflow-x: auto;
margin: 10px 0;
code {
background: transparent;
padding: 0;
color: inherit;
}
}
blockquote {
border-left: 3px solid var(--border-color);
padding-left: 12px;
margin: 10px 0;
color: var(--text-secondary);
}
a {
color: #5fafff;
text-decoration: none;
&:hover { text-decoration: underline; }
}
strong { font-weight: 700; }
`;
const OutputHeader = styled.div`
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 8px;
`;
const OutputStatusDot = styled.span<{ $ok: boolean }>`
width: 8px;
height: 8px;
border-radius: 50%;
background: ${({ $ok }) => ($ok ? '#22c55e' : '#ef4444')};
`;
const ChildList = styled.div`
display: flex;
flex-direction: column;
gap: 8px;
`;
const ChildCard = styled.div`
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 10px;
font-size: 12px;
`;
const ChildTitle = styled.span`
flex: 1;
font-size: 12px;
`;
const Events = styled.ol`
display: flex;
flex-direction: column;
gap: 8px;
list-style: none;
padding: 0;
margin: 0;
`;
const EventRow = styled.li`
display: flex;
gap: 12px;
padding: 10px 14px;
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 10px;
font-family: var(--font-mono);
font-size: 11px;
`;
const EventType = styled.span<{ $type: string }>`
font-weight: 700;
text-transform: uppercase;
color: ${({ $type }) => eventColor($type)};
flex-shrink: 0;
width: 90px;
`;
const EventTime = styled.span`
color: var(--text-secondary);
flex-shrink: 0;
`;
const EventPayload = styled.pre`
margin: 0;
font-size: 11px;
white-space: pre-wrap;
word-break: break-all;
flex: 1;
color: var(--text-primary);
opacity: 0.8;
`;
const Loading = styled.div`
padding: 60px 20px;
text-align: center;
color: var(--text-secondary);
`;
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 stateColor(state: string): string {
switch (state) {
case 'done':
return '#22c55e';
case 'running':
return '#f97316';
case 'failed':
case 'escalated':
return '#ef4444';
case 'queued':
return '#6b7280';
default:
return '#525252';
}
}
function eventColor(type: string): string {
switch (type) {
case 'spawned':
return '#8b5cf6';
case 'started':
return '#f97316';
case 'progress':
case 'output':
return '#5fafff';
case 'completed':
return '#22c55e';
case 'failed':
case 'escalated':
return '#ef4444';
default:
return '#6b7280';
}
}
function duration(start: string | null, end: string | null): string {
if (!start) return '—';
const s = new Date(start).getTime();
const e = end ? new Date(end).getTime() : Date.now();
const ms = e - s;
if (ms < 1000) return `${ms}ms`;
if (ms < 60_000) return `${(ms / 1000).toFixed(2)}s`;
return `${Math.floor(ms / 60000)}m ${Math.floor((ms % 60000) / 1000)}s`;
}
interface Props {
subTaskId: string;
onClose: () => void;
}
export default function SubTaskDetailDrawer({ subTaskId, onClose }: Props) {
const [detail, setDetail] = useState<SubTaskDetail | null>(null);
const [loading, setLoading] = useState(true);
const llmResult = useMemo(
() => (detail ? parseResult(detail.resultJson) : null),
[detail],
);
useEffect(() => {
setLoading(true);
fetch(`${API_URL}/api/rails/sub-tasks/${subTaskId}`, {
credentials: 'include',
})
.then((r) => r.json())
.then((data: SubTaskDetail) => {
setDetail(data);
setLoading(false);
})
.catch(() => setLoading(false));
}, [subTaskId]);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [onClose]);
return (
<Backdrop onClick={onClose}>
<Drawer onClick={(e) => e.stopPropagation()}>
{loading || !detail ? (
<Loading> ...</Loading>
) : (
<>
<Header>
<TopRow>
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
{SISTER_NAMES.has(detail.agentName) && (
<SisterAvatar name={detail.agentName} size={40} />
)}
<RoleBadge $role={detail.role}>{detail.role}</RoleBadge>
</div>
<Close onClick={onClose}> ESC</Close>
</TopRow>
<Title>{detail.title}</Title>
{detail.parents.length > 0 && (
<Breadcrumb>
{detail.parents.map((p, i) => (
<React.Fragment key={p.id}>
<span>{p.role}</span>
<span></span>
{i === detail.parents.length - 1 && <span></span>}
</React.Fragment>
))}
</Breadcrumb>
)}
</Header>
<Body>
<Section>
<SectionLabel> / </SectionLabel>
<Grid>
<Field>
<FieldLabel>State</FieldLabel>
<FieldValue>
<StateBadge $state={detail.state}>{detail.state}</StateBadge>
</FieldValue>
</Field>
<Field>
<FieldLabel>Agent</FieldLabel>
<FieldValue>{detail.agentName}</FieldValue>
</Field>
<Field>
<FieldLabel>Model</FieldLabel>
<FieldValue>{detail.model || '—'}</FieldValue>
</Field>
<Field>
<FieldLabel>Duration</FieldLabel>
<FieldValue>
{duration(detail.startedAt, detail.completedAt)}
</FieldValue>
</Field>
{detail.complexityTier && (
<Field>
<FieldLabel>Complexity</FieldLabel>
<FieldValue>
{detail.complexityTier} ({detail.complexityScore})
</FieldValue>
</Field>
)}
<Field>
<FieldLabel>ID</FieldLabel>
<FieldValue>{detail.id.slice(0, 16)}...</FieldValue>
</Field>
</Grid>
</Section>
{detail.description && (
<Section>
<SectionLabel></SectionLabel>
<Description>{detail.description}</Description>
</Section>
)}
{detail.errorReason && (
<Section>
<SectionLabel></SectionLabel>
<Description>{detail.errorReason}</Description>
</Section>
)}
{llmResult && llmResult.text && (
<Section>
<SectionLabel>LLM </SectionLabel>
<LlmOutput $ok={llmResult.ok}>
<OutputHeader>
<OutputStatusDot $ok={llmResult.ok} />
<span style={{ fontSize: 11, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
{llmResult.ok ? 'success' : 'failed'} · {detail.model || 'default'}
</span>
</OutputHeader>
<ReactMarkdown>{llmResult.text}</ReactMarkdown>
</LlmOutput>
</Section>
)}
{llmResult && !llmResult.text && detail.resultJson && (
<Section>
<SectionLabel> ( )</SectionLabel>
<Description>{detail.resultJson}</Description>
</Section>
)}
{detail.childrenList.length > 0 && (
<Section>
<SectionLabel>
({detail.childrenList.length})
</SectionLabel>
<ChildList>
{detail.childrenList.map((c) => (
<ChildCard key={c.id}>
<RoleBadge $role={c.role}>{c.role}</RoleBadge>
<ChildTitle>{c.title}</ChildTitle>
<StateBadge $state={c.state}>{c.state}</StateBadge>
<span style={{ fontSize: 10, opacity: 0.6 }}>
{duration(c.startedAt, c.completedAt)}
</span>
</ChildCard>
))}
</ChildList>
</Section>
)}
<Section>
<SectionLabel> ({detail.events.length})</SectionLabel>
<Events>
{detail.events.map((ev) => (
<EventRow key={ev.id}>
<EventType $type={ev.eventType}>{ev.eventType}</EventType>
<EventTime>
{new Date(ev.timestamp).toLocaleTimeString('ko-KR')}
</EventTime>
<EventPayload>
{typeof ev.payload === 'string'
? ev.payload
: JSON.stringify(ev.payload)}
</EventPayload>
</EventRow>
))}
</Events>
</Section>
</Body>
</>
)}
</Drawer>
</Backdrop>
);
}

View File

@@ -0,0 +1,207 @@
'use client';
import React from 'react';
import styled from 'styled-components';
import type { RailsSubTaskNode } from '@/lib/useRailsSocket';
import SisterAvatar from '@/components/common/SisterAvatar';
const SISTER_NAMES = new Set(['harang', 'narang', 'darang', 'erang']);
const Wrap = styled.div`
font-family: var(--font-sans);
font-size: 13px;
line-height: 1.6;
display: flex;
flex-direction: column;
gap: 8px;
`;
const Node = styled.button<{ $state: string }>`
padding: 12px 16px;
border-left: 3px solid ${({ $state }) => stateColor($state)};
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 8px;
display: flex;
flex-direction: column;
gap: 6px;
cursor: pointer;
text-align: left;
color: var(--text-primary);
font-family: var(--font-sans);
width: 100%;
transition: all 0.15s;
&:hover {
background: var(--bg-input);
border-color: #5fafff;
}
`;
const RoleBadge = styled.span<{ $role: string }>`
display: inline-block;
padding: 3px 10px;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
border-radius: 12px;
color: #fff;
margin-right: 10px;
background: ${({ $role }) => roleColor($role)};
`;
const StateDot = styled.span<{ $state: string }>`
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 12px;
background: ${({ $state }) => stateColor($state)};
flex-shrink: 0;
animation: ${({ $state }) => ($state === 'running' ? 'pulse 1.2s infinite' : 'none')};
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
`;
const Model = styled.span`
font-size: 11px;
opacity: 0.55;
margin-left: 12px;
font-family: var(--font-mono);
`;
const Duration = styled.span`
font-size: 11px;
opacity: 0.55;
margin-left: auto;
font-family: var(--font-mono);
`;
const Title = styled.span`
font-size: 13px;
font-weight: 500;
`;
const Meta = styled.span`
font-size: 11px;
opacity: 0.55;
margin-left: 22px;
font-family: var(--font-mono);
`;
const Row = styled.div`
display: flex;
align-items: center;
gap: 4px;
`;
const Children = styled.div`
margin-left: 28px;
margin-top: 4px;
display: flex;
flex-direction: column;
gap: 8px;
border-left: 1px dashed var(--border-color);
padding-left: 16px;
`;
function stateColor(state: string): string {
switch (state) {
case 'done':
return '#22c55e';
case 'running':
return '#f97316';
case 'failed':
return '#ef4444';
case 'escalated':
return '#ef4444';
case 'queued':
return '#6b7280';
default:
return '#333333';
}
}
function roleColor(role: string): string {
switch (role) {
case 'manager':
return '#8b5cf6';
case 'principal':
return '#3b82f6';
case 'lead':
return '#f97316';
case 'junior':
return '#6b7280';
default:
return '#6b7280';
}
}
function duration(startedAt: string | null, completedAt: string | null): string {
if (!startedAt) return '—';
const start = new Date(startedAt).getTime();
const end = completedAt ? new Date(completedAt).getTime() : Date.now();
const ms = end - start;
if (ms < 1000) return `${ms}ms`;
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
return `${Math.floor(ms / 60000)}m ${Math.floor((ms % 60000) / 1000)}s`;
}
function NodeRow({
node,
onSelect,
}: {
node: RailsSubTaskNode;
onSelect?: (id: string) => void;
}) {
return (
<>
<Node $state={node.state} onClick={() => onSelect?.(node.id)}>
<Row>
<StateDot $state={node.state} />
{SISTER_NAMES.has(node.agentName) && (
<SisterAvatar name={node.agentName} size={20} style={{ marginRight: 8 }} />
)}
<RoleBadge $role={node.role}>{node.role}</RoleBadge>
<Title>{node.title.slice(0, 100)}</Title>
<Model>{node.model || '—'}</Model>
<Duration>{duration(node.startedAt, node.completedAt)}</Duration>
</Row>
{node.complexityTier && (
<Meta>
complexity: {node.complexityTier} ({node.complexityScore})
</Meta>
)}
</Node>
{node.children.length > 0 && (
<Children>
{node.children.map((c) => (
<NodeRow key={c.id} node={c} onSelect={onSelect} />
))}
</Children>
)}
</>
);
}
interface Props {
tree: RailsSubTaskNode[];
onSelectNode?: (id: string) => void;
}
export default function SubTaskTree({ tree, onSelectNode }: Props) {
if (tree.length === 0) {
return <Wrap>No sub-tasks yet.</Wrap>;
}
return (
<Wrap>
{tree.map((node) => (
<NodeRow key={node.id} node={node} onSelect={onSelectNode} />
))}
</Wrap>
);
}

View File

@@ -3,6 +3,7 @@
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'; import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { API_URL } from './config'; import { API_URL } from './config';
import { withSessionRequest } from './csrf';
interface AuthUser { interface AuthUser {
userId: number; userId: number;
@@ -31,38 +32,20 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const loadUser = useCallback(async () => { const loadUser = useCallback(async () => {
const token = localStorage.getItem('hanarang_access_token');
if (!token) { setLoading(false); return; }
try { try {
const res = await fetch(`${API_URL}/api/auth/me`, { const res = await fetch(`${API_URL}/api/auth/me`, withSessionRequest());
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setUser({ userId: data.id, username: data.username, role: data.role }); setUser({ userId: data.id, username: data.username, role: data.role });
} else if (res.status === 401) { } else if (res.status === 401) {
// access token 만료 → refresh 시도 // access token expired → try refresh via cookie
const refreshToken = localStorage.getItem('hanarang_refresh_token');
if (refreshToken) {
try { try {
const rRes = await fetch(`${API_URL}/api/auth/refresh`, { const rRes = await fetch(`${API_URL}/api/auth/refresh`, withSessionRequest({ method: 'POST' }, { csrf: true }));
method: 'POST',
headers: { 'x-refresh-token': refreshToken },
});
if (rRes.ok) { if (rRes.ok) {
const d = await rRes.json(); const d = await rRes.json();
localStorage.setItem('hanarang_access_token', d.accessToken);
if (d.refreshToken) localStorage.setItem('hanarang_refresh_token', d.refreshToken);
setUser({ userId: 0, username: d.username, role: d.role }); setUser({ userId: 0, username: d.username, role: d.role });
} else {
localStorage.removeItem('hanarang_access_token');
localStorage.removeItem('hanarang_refresh_token');
} }
} catch { /* silent */ } } catch { /* silent */ }
} else {
localStorage.removeItem('hanarang_access_token');
}
} }
} catch { } catch {
// silent // silent
@@ -74,11 +57,11 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
useEffect(() => { loadUser(); }, [loadUser]); useEffect(() => { loadUser(); }, [loadUser]);
const login = async (username: string, password: string) => { const login = async (username: string, password: string) => {
const res = await fetch(`${API_URL}/api/auth/login`, { const res = await fetch(`${API_URL}/api/auth/login`, withSessionRequest({
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }), body: JSON.stringify({ username, password }),
}); }, { csrf: true }));
if (!res.ok) { if (!res.ok) {
const d = await res.json(); const d = await res.json();
@@ -86,27 +69,23 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
} }
const d = await res.json(); const d = await res.json();
localStorage.setItem('hanarang_access_token', d.accessToken); // Tokens are set as HttpOnly cookies by the server
if (d.refreshToken) { setUser({ userId: 0, username: d.username, role: d.role });
localStorage.setItem('hanarang_refresh_token', d.refreshToken);
} // Fetch actual userId from /me
// me API로 실제 userId 가져오기
try { try {
const meRes = await fetch(`${API_URL}/api/auth/me`, { const meRes = await fetch(`${API_URL}/api/auth/me`, withSessionRequest());
headers: { Authorization: `Bearer ${d.accessToken}` },
});
if (meRes.ok) { if (meRes.ok) {
const me = await meRes.json(); const me = await meRes.json();
setUser({ userId: me.id, username: me.username, role: me.role }); setUser({ userId: me.id, username: me.username, role: me.role });
return;
} }
} catch { /* fallback */ } } catch { /* fallback — already set basic info */ }
setUser({ userId: 0, username: d.username, role: d.role });
}; };
const logout = () => { const logout = async () => {
localStorage.removeItem('hanarang_access_token'); try {
localStorage.removeItem('hanarang_refresh_token'); await fetch(`${API_URL}/api/auth/logout`, withSessionRequest({ method: 'POST' }, { csrf: true }));
} catch { /* silent */ }
setUser(null); setUser(null);
}; };

46
frontend/lib/csrf.ts Normal file
View File

@@ -0,0 +1,46 @@
export const CSRF_COOKIE_NAME = 'hanarang_csrf_token';
export function getCookieValue(name: string): string {
if (typeof document === 'undefined') return '';
const match = document.cookie
.split('; ')
.find((item) => item.startsWith(`${encodeURIComponent(name)}=`));
if (!match) return '';
return decodeURIComponent(match.split('=').slice(1).join('='));
}
export function getCsrfToken(): string {
return getCookieValue(CSRF_COOKIE_NAME);
}
export function needsCsrf(method?: string): boolean {
const normalized = (method ?? 'GET').toUpperCase();
return !['GET', 'HEAD', 'OPTIONS'].includes(normalized);
}
export function withCsrfHeaders(headers?: HeadersInit): Headers {
const nextHeaders = new Headers(headers);
const csrfToken = getCsrfToken();
if (csrfToken) {
nextHeaders.set('x-csrf-token', csrfToken);
}
return nextHeaders;
}
export function withSessionRequest(
init: RequestInit = {},
options: { csrf?: boolean } = {},
): RequestInit {
const useCsrf = options.csrf ?? needsCsrf(init.method);
return {
...init,
credentials: 'include',
headers: useCsrf ? withCsrfHeaders(init.headers) : new Headers(init.headers),
};
}

View File

@@ -0,0 +1,93 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { io, Socket } from 'socket.io-client';
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[];
}
interface UseRailsSocketOptions {
onPipelinesSnapshot?: (pipelines: RailsPipelineSummary[]) => void;
onPipelineUpdated?: (pipeline: RailsPipelineSummary) => void;
onSubTasksUpdated?: (pipelineId: string, tree: RailsSubTaskNode[]) => void;
}
/**
* Listens to rails.* events emitted by the backend EventsGateway.
* Piggybacks on the existing /ws namespace — no new socket connection.
*/
export function useRailsSocket(options: UseRailsSocketOptions = {}) {
const socketRef = useRef<Socket | null>(null);
const [connected, setConnected] = useState(false);
useEffect(() => {
const wsUrl = process.env.NEXT_PUBLIC_WS_URL ?? window.location.origin;
const token =
typeof window !== 'undefined'
? localStorage.getItem('hanarang_access_token') ?? ''
: '';
const socket = io(`${wsUrl}/ws`, {
path: '/socket.io',
transports: ['websocket', 'polling'],
reconnectionAttempts: 5,
reconnectionDelay: 3000,
auth: { token },
});
socket.on('connect', () => setConnected(true));
socket.on('disconnect', () => setConnected(false));
if (options.onPipelinesSnapshot) {
socket.on('rails:pipelines', (payload: { pipelines: RailsPipelineSummary[] }) => {
options.onPipelinesSnapshot?.(payload.pipelines);
});
}
if (options.onPipelineUpdated) {
socket.on('rails:pipeline:updated', (payload: { pipeline: RailsPipelineSummary }) => {
options.onPipelineUpdated?.(payload.pipeline);
});
}
if (options.onSubTasksUpdated) {
socket.on(
'rails:subtasks',
(payload: { pipelineId: string; tree: RailsSubTaskNode[] }) => {
options.onSubTasksUpdated?.(payload.pipelineId, payload.tree);
},
);
}
socketRef.current = socket;
return () => {
socket.disconnect();
socketRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { connected, socket: socketRef.current };
}

4589
frontend/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff