Compare commits

..

1 Commits

Author SHA1 Message Date
90968810ff 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:21:28 +09:00
43 changed files with 767 additions and 15692 deletions

View File

@@ -1 +0,0 @@
1775809670

View File

@@ -4,19 +4,6 @@
- 4자매 운영 상태를 실시간으로 보여준다
- 프로젝트/Sprint/Hotfix/QA/Deploy 흐름을 시각화한다
- `main`이 항상 배포 가능 상태라는 원칙을 UI와 운영에 함께 반영한다
- 오피스 화면과 운영 패널이 분리되지 않고 하나의 관제 경험으로 이어지게 만든다
## 저장소 / Git 기준
- Repo: `hanarang-dashboard`
- Git URL: `https://git.nabomhalang.co.kr/hanarang/hanarang-dashboard`
- 기본 브랜치: `main`
- 현재 오피스 구현 기준 경로:
- `frontend/app/office/page.tsx`
- `frontend/components/office/OfficeScene.tsx`
- `frontend/components/office/ContextPanel.tsx`
- `frontend/components/office/ChatWorkspace.tsx`
- `frontend/components/office/PipelinePanel.tsx`
- `frontend/components/office/ServerHealthPanel.tsx`
## 현재 표준 구조
- 루트: `README.md`, `ARCHITECTURE.md`
@@ -28,70 +15,25 @@
- `deploy/`
- 장기 문서: `docs/`
## 현재 상태
- **SPRINT-016**: `/office` 기본 화면과 핵심 컴포넌트가 `main`에 반영됨
- **다음 활성 작업**: **SPRINT-017** `/office` 모바일 화면 전면 개편
## 활성 작업
- **SPRINT-016**: 4자매 Isometric Office Dashboard 재기획
## SPRINT-017 active scope
이번 Sprint는 안정화 전반이 아니라 **`/office` 모바일 정보 구조 재설계**에만 집중해.
### 이번에 반드시 해결할 것
1. `360px`, `390px` 첫 viewport에서 아래 4가지를 한 번에 읽히게 만든다.
- 4자매 상태
- current focus
- health summary
- quick actions
2. `mobile(<768)`에서는 데스크톱 씬 축소판을 금지하고, 모바일 전용 세로 흐름 IA로 바꾼다.
3. `PipelinePanel``ServerHealthPanel`을 가로 스크롤 없이 읽히는 카드 흐름으로 바꾼다.
4. `ChatWorkspace`를 모바일 direct chat 기준으로 다시 정리하고, `JWT 없음 / empty / error / runtime 확인 중` 상태를 즉시 읽히게 만든다.
5. `live / snapshot / fallback` 의미는 유지하되, 모바일에서 더 짧고 일관된 라벨로 통일한다.
### 이번에 하지 않을 것
- 새로운 백엔드 API 추가
- WebSocket 프로토콜 재설계
- 별도 모바일 앱 설계
- 3D/고해상도 오피스 씬 확장
- 데스크톱 전체 IA 재작성
## 현재 main 구현에서 확인된 모바일 문제
- `frontend/components/office/OfficeScene.tsx`
- `aspect-ratio: 800 / 460` 고정 씬이라 모바일에서 데스크톱 축소판처럼 보임
- `frontend/app/office/page.tsx`
- 모바일 전용 summary hero가 없고, `ChatArea``460px` 고정 높이에 의존함
- 선택 전에는 `ContextPanel`과 chat이 핵심 정보 대신 빈 상태에 가까움
- `frontend/components/office/ContextPanel.tsx`
- 선택 의존 구조라 첫 진입 시 상세 정보가 비어 있음
- `frontend/components/office/PipelinePanel.tsx`
- `overflow-x: auto` 기반이라 모바일에서 가로 스크롤 전제가 생김
- `frontend/components/office/ChatWorkspace.tsx`
- 모바일에서 direct chat 맥락이 탭, 타임라인, composer, 상태 패널로 분산되고 보조 정보가 숨겨짐
## breakpoint 기준
- **Mobile compact:** `360px`
- **Mobile default:** `390px`
- **Tablet:** `768px`
- **Desktop:** `1280px+`
## 이번 Sprint 핵심 요구사항
1. 4자매와 17개 서브에이전트, 총 21개 에이전트를 오피스 은유로 재설계
2. 4자매 독립 Gateway WebSocket 기준 실시간 상태 모델 정리
3. 고정 좌석 4자매 + 동적 이동 서브에이전트 + 회의실/연결선 구조 정의
4. direct chat / workflow panel / server health를 오피스 화면과 통합
5. PRD와 `.plans/` 구조를 새 제품 방향 기준으로 정리
## 이행 전략
- 문서는 실제 `main` 구현 경로를 근거로만 갱신한다
- SPRINT-017은 `mobile-first IA``상태 라벨 통일`까지만 잠근다
- 구현 작업은 `frontend/app/office/page.tsx``frontend/components/office/*` 범위 안에서 끝내는 걸 기본으로 한다
- QA는 `360 / 390 / 768 / 1280+` 실브라우저 확인을 기준으로 남긴다
- 코드에서는 구 구조와 신 구조를 일정 기간 동시 지원
- 문서는 신 구조를 기준으로 선반영
- 신규 QA 문서는 `.plans/qa/` 기준
- 신규 Hotfix 문서는 `.plans/hotfix/` 기준
## 문서 맵
- 구조 기준: `../ARCHITECTURE.md`
- 제품 PRD: `../docs/product-specs/openclaw-office-dashboard-prd.md`
- 디자인 인덱스: `./design/index.md`
- Sprint 016 비전: `./sprints/SPRINT-016.md`
- Sprint 017 실행 계획: `./sprints/SPRINT-017.md`
- 오피스 모바일 IA: `./design/ui/office-dashboard-design.md`
- 오피스 direct chat 모바일 기준: `./design/ui/office-chat-design.md`
- API / 실시간 모델 참고: `./design/api-design.md`
- Sprint 계획: `./sprints/SPRINT-016.md`
- PRD: `../docs/product-specs/openclaw-office-dashboard-prd.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,13 +20,10 @@
## PM2 설정
```
backend: pm2 start backend/dist/src/main.js --name hanarang-api --cwd /path/to/hanarang-dashboard --env production
frontend: pm2 start npm --name hanarang-web --cwd /path/to/hanarang-dashboard/frontend -- start -- -p 3004
backend: pm2 start dist/main.js --name hanarang-api --env production
frontend: pm2 start npm --name hanarang-web -- start -- -p 3004
```
- backend 엔트리포인트는 실제 Nest 빌드 산출물 기준 `backend/dist/src/main.js`를 사용해.
- repo 루트에서 실행하면 `--cwd`를 명시해서 PM2가 올바른 작업 디렉터리를 잡도록 해.
## SSH 키 배포
- Dev 서버(10.10.10.169)에서 4자매 서버로 SSH 접속할 수 있도록 키 배포 필요
- 이랑이가 SSH 키 생성 + 각 자매 서버에 authorized_keys 추가

View File

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

View File

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

View File

@@ -21,20 +21,8 @@
## 레퍼런스
- `references/07-master-dashboard-v3-reference.md`
## 현재 우선 문서
- Sprint 실행 기준: `../sprints/SPRINT-017.md`
- 제품 비전: `../../docs/product-specs/openclaw-office-dashboard-prd.md`
- 실행 개요: `../OVERVIEW.md`
## SPRINT-017에서 반드시 잠글 것
- 오피스 메인: Desktop / Tablet / Mobile 정보 우선순위
- 오피스 채팅: JWT 필요, 전송 실패, empty state 처리
- 운영 패널: active workflow / sprint / review loop / deploy gate / server health 상태 톤 통일
- 실시간 모델: `live / snapshot / fallback` 판정 규칙
- WS + polling reconciliation: stale / reconnect / downgrade 기준
## Git 기준 확인 경로
- `/office` entry: `frontend/app/office/page.tsx`
- scene: `frontend/components/office/OfficeScene.tsx`
- chat: `frontend/components/office/ChatWorkspace.tsx`
- ws gateway: `backend/src/events/events.gateway.ts`
## Sprint 016에서 반드시 반영할 화면
- 오피스 메인: 4자매 고정 좌석 + 서브에이전트 동적 이동
- 오피스 채팅: 자매 선택 direct chat + 현재 상태 결합
- 운영 패널: active workflow / sprint / review loop / deploy gate / server health
- 모바일: 오피스 씬 단순화 + 세로 흐름 재배치

View File

@@ -1,150 +1,30 @@
# 오피스 direct chat UI 기준 — SPRINT-017 모바일 개편
# 오피스 채팅 워크스페이스 — Sprint 016
## 문서 목적
`ChatWorkspace.tsx`를 모바일 direct chat 기준으로 다시 정리하기 위한 문서야. 기준 Sprint는 `.plans/sprints/SPRINT-017.md`이고, 메인 IA와 first viewport 원칙은 `.plans/design/ui/office-dashboard-design.md`를 따른다.
## 목적
자기야가 4자매 중 한 명을 선택해 직접 대화하고, 현재 작업 맥락과 tool 상태를 함께 보는 운영 채팅 인터페이스.
## 기준 구현 파일
- `frontend/components/office/ChatWorkspace.tsx`
- `frontend/app/office/page.tsx`
- 연관 문서: `.plans/design/ui/office-dashboard-design.md`
## 구조
### 좌측
- 자매 선택 탭
- 최근 대화 상대
- unread / active 상태
## breakpoint 기준
- `360px`: minimum mobile compact
- `390px`: primary mobile baseline
- `768px`: tablet transition
- `1280px+`: desktop baseline
### 중앙
- 메시지 타임라인
- streaming 응답
- tool call 상태 삽입
- retry / stop / resend 액션
## 현재 main 구현에서 확인된 문제
- `page.tsx`에서 chat은 `ChatArea` 고정 높이(`520px`, 모바일 `460px`) 안에 들어가 세로 흐름을 끊는다.
- `ChatWorkspace.tsx`는 모바일에서도 데스크톱 구조의 흔적이 강하다.
- 자매 탭, 메시지, 보조 컨텍스트가 분리되어 있다.
- `SisterContext``1199px` 미만에서 숨겨져 모바일 보조 정보가 사라진다.
- `SendBtn`은 토큰이 없으면 disabled라서, `JWT 없음` 이유를 화면에서 놓치기 쉽다.
- empty 상태 문구는 있지만, `JWT 없음 / error / runtime 확인 중`이 같은 강도로 정리되어 있지 않다.
### 우측
- 선택 자매 상태
- current workflow
- 최근 handoff
- 관련 서브에이전트
## 모바일 direct chat 원
1. **한 컬럼 흐름**
- mobile(` <768`)에서는 탭 → 상태 → 타임라인 → composer → 보조 정보 순서로 한 컬럼으로 간다.
2. **전송 가능 여부를 숨기지 않기**
- `JWT 없음`이면 입력 근처에서 바로 이유를 보여준다.
3. **상태는 상단에 짧게**
- runtime/source 상태는 header 또는 composer 상단에서 한 번에 읽히게 한다.
4. **메시지가 우선**
- 보조 컨텍스트보다 타임라인과 입력창이 우선이다.
5. **고정 높이 최소화**
- 460px 박스 안에 억지로 채우지 않는다.
## UX 규
- 채팅은 메신저가 아니라 운영 명령 패널처럼 보여야 함
- 현재 자매 상태와 대화가 분리되지 않아야 함
- tool calling / speaking 상태는 대화 흐름 안에서 보여야 함
## 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

@@ -1,207 +1,63 @@
# 오피스 대시보드 UI 기준 — SPRINT-017 모바일 개편
# 오피스 대시보드 메인 (`/office` 또는 `/`) — Sprint 016
## 문서 목적
`/office` 메인 화면의 모바일 IA와 우선순위를 잠그는 문서야. 기준 Sprint는 `.plans/sprints/SPRINT-017.md`이고, active scope는 `.plans/OVERVIEW.md`를 따른다.
## 목적
4자매와 서브에이전트 협업을 `고정 좌석 + 동적 이동 + 운영 패널` 구조로 보여주는 대표 화면.
## 기준 구현 파일
- `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`
## 핵심 은유
- 메인 자매 = 고정 좌석
- 서브에이전트 = 이동 가능한 팀원
- 회의실 = 협업/리뷰/핸드오프 문맥
- 인프라 존 = 배포/서버/헬스
- 연결선 = handoff / workflow transition
## breakpoint 기준
- `360px`: minimum mobile compact
- `390px`: primary mobile baseline
- `768px`: tablet transition
- `1280px+`: desktop baseline
## 전체 레이아웃
### 1. Office Scene
화면 중심. 가장 큰 영역.
## 현재 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`은 유지하되, 짧고 일관된 라벨로 통일한다.
#### 서브에이전트 배치
- 기본은 자기 자매 주변 대기
- active workflow 시 작업석/회의실/인프라 존으로 이동
- 상태에 따라 아이콘/색/테두리/말풍선 변화
## 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**
### 2. Right Context Panel
- 선택 에이전트 detail
- 현재 세션/상태
- 최근 이벤트
- direct chat 진입
- 상세 보기 또는 관련 패널 점프
### 4. panel sections
첫 viewport 이후 순차 노출.
### 3. Bottom Ops Panel
- current sprint
- active workflow
- review loop
- deploy gate
- server health summary
모바일 추천 순서:
1. direct chat
2. pipeline
3. health detail
4. context detail
## 상태 표현
- `idle`: 조용한 점등
- `thinking`: 약한 pulse
- `tool_calling`: 도구 아이콘/점멸
- `speaking`: 말풍선 또는 stream 표시
- `error`: 적색 경고
이 순서는 "지금 말 걸기 → 지금 뭐가 막혔는지 보기 → 상세 맥락 보기" 흐름을 따른다.
## 연결 규칙
- 자매 간 핸드오프는 굵은 주 연결선
- 서브에이전트 내부 협업은 얇은 보조선
- review loop는 다랑이 회의실 중심으로 표시
- deploy path는 이랑이 인프라 존으로 흐름 표시
## first viewport priority
`360px`, `390px`에서 아래 4개가 모두 한 번에 보여야 해.
1. 4자매 상태
2. current focus
3. health summary
4. quick actions
## UX 규칙
- 중심은 언제나 4자매
- 21개 에이전트를 다 보여도 난잡하면 안 됨
- 선택 전에도 전체 상태는 읽혀야 함
- 선택 후에만 상세 정보 밀도 증가
### 우선순위 이유
- 자매 상태가 먼저 안 보이면 운영 화면이 아니라 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

@@ -1,93 +0,0 @@
# 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

@@ -1,212 +0,0 @@
# 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

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

View File

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

View File

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

7705
backend/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -1,5 +1,4 @@
import { Test, TestingModule } from '@nestjs/testing';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { ActivityService } from './activity.service';
import { PrismaService } from '../prisma/prisma.service';
@@ -21,7 +20,6 @@ describe('ActivityService', () => {
providers: [
ActivityService,
{ provide: PrismaService, useValue: mockPrisma },
EventEmitter2,
],
}).compile();

View File

@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Injectable, Optional } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { EventsGateway } from '../events/events.gateway';
export interface LogActivityDto {
sisterId?: number;
@@ -34,7 +34,7 @@ function sanitizeActivityDetail(detail?: string | null): string | undefined {
export class ActivityService {
constructor(
private readonly prisma: PrismaService,
private readonly eventEmitter: EventEmitter2,
@Optional() private readonly events?: EventsGateway,
) {}
async log(dto: LogActivityDto) {
@@ -49,7 +49,9 @@ export class ActivityService {
},
});
this.eventEmitter.emit('activity.logged', record);
if (this.events) {
this.events.broadcastActivity(record);
}
return record;
}

View File

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

View File

@@ -69,23 +69,13 @@ function nodeStateFromEvidence(params: {
return 'idle';
}
function sanitizeSummary(text?: string | null) {
const raw = text?.trim();
if (!raw) return null;
if (/stderr:/i.test(raw) || /command not found/i.test(raw) || /bash:\s*line/i.test(raw)) {
return '내부 작업 중 오류가 발생했어. 자세한 시스템 로그는 관리자 로그에서 확인해.';
}
if (/^ssh failed/i.test(raw) || /ssh connection failed/i.test(raw)) {
return '원격 노드 연결에 실패했어.';
}
return raw;
}
function summarizeActivity(
activity?: ActivityRecord | null,
fallback = 'NO EVENT',
) {
return sanitizeSummary(activity?.detail) || activity?.action?.replace(/_/g, ' ') || fallback;
return (
activity?.detail?.trim() || activity?.action?.replace(/_/g, ' ') || fallback
);
}
function parseQaSummary(content: string): string {

View File

@@ -10,7 +10,6 @@ import { Server, Socket } from 'socket.io';
import { Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { OnEvent } from '@nestjs/event-emitter';
import { ACCESS_TOKEN_COOKIE, parseCookieHeader } from '../auth/auth-cookies';
interface SocketUserPayload {
@@ -108,39 +107,6 @@ export class EventsGateway
this.server.emit('activity:new', { item, ts: Date.now() });
}
/** EventEmitter2에서 activity.logged 수신 → WebSocket 브로드캐스트 */
@OnEvent('activity.logged')
handleActivityLogged(record: unknown) {
this.broadcastActivity(record);
}
// ── Rails orchestrator events ──────────────────────────────────────
@OnEvent('rails.pipelines.snapshot')
handleRailsPipelinesSnapshot(payload: { pipelines: unknown[] }) {
this.server.emit('rails:pipelines', {
pipelines: payload.pipelines,
ts: Date.now(),
});
}
@OnEvent('rails.pipeline.updated')
handleRailsPipelineUpdated(payload: { pipeline: unknown }) {
this.server.emit('rails:pipeline:updated', {
pipeline: payload.pipeline,
ts: Date.now(),
});
}
@OnEvent('rails.subtasks.updated')
handleRailsSubTasksUpdated(payload: { pipelineId: string; tree: unknown }) {
this.server.emit('rails:subtasks', {
pipelineId: payload.pipelineId,
tree: payload.tree,
ts: Date.now(),
});
}
/** 연결된 클라이언트 수 */
getClientCount(): number {
return this.server?.sockets?.sockets?.size ?? 0;

View File

@@ -1,67 +0,0 @@
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 };
}
@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

@@ -1,14 +0,0 @@
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

@@ -1,84 +0,0 @@
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

@@ -1,134 +0,0 @@
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 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

@@ -91,7 +91,7 @@ export class SisterDetailService {
sister.ip,
sister.user,
sshKeyPath,
'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 ""',
'SESSION_DIR=~/.hermes/sessions; [ -d "$SESSION_DIR" ] || SESSION_DIR=~/.openclaw/sessions; ls -lt "$SESSION_DIR"/ 2>/dev/null | head -20 || echo ""',
);
const sessions = result.stdout

View File

@@ -1,12 +1,4 @@
import {
Body,
Controller,
Get,
Param,
Post,
Res,
UseGuards,
} from '@nestjs/common';
import { Controller, Get, Param, Res, UseGuards } from '@nestjs/common';
import type { Response } from 'express';
import { JwtGuard } from '../auth/jwt.guard';
import { RoleGuard, Roles } from '../auth/role.guard';
@@ -26,11 +18,6 @@ export class SistersController {
private readonly avatarService: AvatarService,
) {}
@Get('runtime')
async getSistersRuntime() {
return this.sistersService.getAllSistersRuntime();
}
@Get()
async getSistersStatus() {
const sisters = await this.sistersService.getAllSistersStatus();
@@ -46,20 +33,6 @@ export class SistersController {
}));
}
@Get(':name/runtime')
async getSisterRuntime(@Param('name', SisterNamePipe) name: SisterName) {
return this.sistersService.getSisterRuntime(name);
}
@UseGuards(JwtGuard)
@Post(':name/chat')
async chatWithSister(
@Param('name', SisterNamePipe) name: SisterName,
@Body('message') message: string,
) {
return this.sistersService.sendChatMessage(name, message);
}
@Get(':name/system')
async getSystemInfo(@Param('name', SisterNamePipe) name: SisterName) {
const system = await this.sistersService.getSystemInfo(name);

View File

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

View File

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

View File

@@ -1 +0,0 @@
1775809622

View File

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

View File

@@ -1,10 +1,9 @@
'use client';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import { API_URL, POLL_INTERVAL_MS } from '@/lib/config';
import { useSocket } from '@/lib/useSocket';
import SisterAvatar from '@/components/common/SisterAvatar';
import OfficeScene, {
type AgentState,
type SisterName,
@@ -18,44 +17,17 @@ import PipelinePanel from '@/components/office/PipelinePanel';
import ServerHealthPanel, { type ServerEntry } from '@/components/office/ServerHealthPanel';
import type { PipelineNode } from '@/components/dashboard/ActivePipeline';
interface RuntimeSubagentItem {
name: string;
state: AgentState;
updatedAt: number | null;
currentTask: string | null;
sessionLabel: string | null;
}
interface SisterRuntimeItem {
name: SisterName;
gatewayConnected: boolean;
mainState: AgentState;
currentTask: string | null;
activeSessionLabel: string | null;
activeSessionUpdatedAt: number | null;
controlSessionKey: string | null;
recentMessages: Array<{
id: string;
role: 'user' | 'assistant' | 'tool';
content: string;
ts: string | null;
}>;
subagents: RuntimeSubagentItem[];
}
// ─── Types ───────────────────────────────────────────────────────────────────
interface SisterApiItem {
id?: number;
name: SisterName;
name: string;
status: 'online' | 'offline' | 'working' | 'unknown';
role?: string;
currentTask?: string | null;
lastSeen?: string | null;
cpu?: number;
memory?: { used?: number; total?: number };
liveState?: AgentState;
activeSessionLabel?: string | null;
gatewayConnected?: boolean;
subagents?: RuntimeSubagentItem[];
}
interface DashboardOpsData {
@@ -83,31 +55,33 @@ interface DashboardOpsData {
};
}
// ─── Static subagent definitions ─────────────────────────────────────────────
const SUBAGENT_DEFS: Record<SisterName, { id: string; name: string; label: string }[]> = {
harang: [
{ id: 'harang-planner', name: 'planner', label: 'planner' },
{ id: 'harang-planner', name: 'planner', label: 'planner' },
{ id: 'harang-task-tracker', name: 'task-tracker', label: 'task-tracker' },
{ id: 'harang-prd-writer', name: 'prd-writer', label: 'prd-writer' },
{ id: 'harang-prd-writer', name: 'prd-writer', label: 'prd-writer' },
],
narang: [
{ id: 'narang-worker', name: 'worker', label: 'worker' },
{ id: 'narang-db-designer', name: 'db-designer', label: 'db-designer' },
{ id: 'narang-test-writer', name: 'test-writer', label: 'test-writer' },
{ id: 'narang-refactorer', name: 'refactorer', label: 'refactorer' },
{ id: 'narang-worker', name: 'worker', label: 'worker' },
{ id: 'narang-db-designer', name: 'db-designer', label: 'db-designer' },
{ id: 'narang-test-writer', name: 'test-writer', label: 'test-writer' },
{ id: 'narang-refactorer', name: 'refactorer', label: 'refactorer' },
],
darang: [
{ id: 'darang-reviewer', name: 'reviewer', label: 'reviewer' },
{ id: 'darang-code-reviewer', name: 'code-reviewer', label: 'code-reviewer' },
{ id: 'darang-qa-tester', name: 'qa-tester', label: 'qa-tester' },
{ id: 'darang-security-auditor', name: 'security-auditor', label: 'security-auditor' },
{ id: 'darang-ux-reviewer', name: 'ux-reviewer', label: 'ux-reviewer' },
{ id: 'darang-reviewer', name: 'reviewer', label: 'reviewer' },
{ id: 'darang-code-reviewer', name: 'code-reviewer', label: 'code-rvw' },
{ id: 'darang-qa-tester', name: 'qa-tester', label: 'qa-tester' },
{ id: 'darang-security-auditor', name: 'security-auditor', label: 'security' },
{ id: 'darang-ux-reviewer', name: 'ux-reviewer', label: 'ux-reviewer' },
],
erang: [
{ id: 'erang-deploy-manager', name: 'deploy-manager', label: 'deploy-manager' },
{ id: 'erang-db-manager', name: 'db-manager', label: 'db-manager' },
{ id: 'erang-nginx-manager', name: 'nginx-manager', label: 'nginx-manager' },
{ id: 'erang-monitoring', name: 'monitoring', label: 'monitoring' },
{ id: 'erang-dns-manager', name: 'dns-manager', label: 'dns-manager' },
{ id: 'erang-deploy-manager', name: 'deploy-manager', label: 'deploy' },
{ id: 'erang-db-manager', name: 'db-manager', label: 'db-mgr' },
{ id: 'erang-nginx-manager', name: 'nginx-manager', label: 'nginx' },
{ id: 'erang-monitoring', name: 'monitoring', label: 'monitor' },
{ id: 'erang-dns-manager', name: 'dns-manager', label: 'dns' },
],
};
@@ -115,26 +89,48 @@ const SISTER_DISPLAY: Record<SisterName, string> = {
harang: '하랑이',
narang: '나랑이',
darang: '다랑이',
erang: '이랑이',
erang: '이랑이',
};
const SISTER_ROLES: Record<SisterName, string> = {
harang: 'Planning & Orchestration',
narang: 'Development',
darang: 'QA & Review',
erang: 'Infra & Deploy',
erang: 'Infra & Deploy',
};
const SISTER_ORDER: SisterName[] = ['harang', 'narang', 'darang', 'erang'];
const SUBAGENT_COUNT = Object.values(SUBAGENT_DEFS).reduce((total, defs) => total + defs.length, 0);
const FALLBACK_SISTERS: SisterApiItem[] = [
{ name: 'harang', status: 'working', role: SISTER_ROLES.harang, currentTask: 'runtime snapshot 확인 중' },
{ name: 'narang', status: 'working', role: SISTER_ROLES.narang, currentTask: '개발 세션 상태 동기화 중' },
{ name: 'darang', status: 'online', role: SISTER_ROLES.darang, currentTask: '검증 상태 확인 중' },
{ name: 'erang', status: 'online', role: SISTER_ROLES.erang, currentTask: '배포 런타임 확인 중' },
{
name: 'harang',
status: 'working',
role: SISTER_ROLES.harang,
currentTask: 'SPRINT-016 scope lock',
},
{
name: 'narang',
status: 'working',
role: SISTER_ROLES.narang,
currentTask: 'Office scene dynamic movement',
},
{
name: 'darang',
status: 'online',
role: SISTER_ROLES.darang,
currentTask: 'Review loop standby',
},
{
name: 'erang',
status: 'online',
role: SISTER_ROLES.erang,
currentTask: 'Gateway health watch',
},
];
// ─── Helpers ──────────────────────────────────────────────────────────────────
function statusToAgentState(status: SisterApiItem['status'], hasTask: boolean): AgentState {
if (status === 'offline') return 'error';
if (status === 'working') return hasTask ? 'tool_calling' : 'thinking';
@@ -143,77 +139,34 @@ function statusToAgentState(status: SisterApiItem['status'], hasTask: boolean):
}
function derivedSubagentState(parentState: AgentState, index: number): AgentState {
if (parentState === 'error') return 'idle';
// Derive subagent state from parent with some variety
if (parentState === 'error') return 'idle'; // subagents idle when parent is offline
if (parentState === 'tool_calling' && index === 0) return 'thinking';
if (parentState === 'speaking' && index <= 1) return 'thinking';
return 'idle';
}
function normalizeSubagentState(state?: AgentState): AgentState {
if (state === 'thinking' || state === 'tool_calling' || state === 'speaking' || state === 'error') {
return state;
}
return 'idle';
}
function mergeSisterData(
statuses: SisterApiItem[],
runtime: SisterRuntimeItem[],
previous: SisterApiItem[] = [],
): SisterApiItem[] {
const previousMap = new Map(previous.map((item) => [item.name, item]));
const statusMap = new Map(statuses.map((item) => [item.name, item]));
const runtimeMap = new Map(runtime.map((item) => [item.name, item]));
return SISTER_ORDER.map((name) => {
const prev = previousMap.get(name);
const status = statusMap.get(name) ?? prev ?? FALLBACK_SISTERS.find((item) => item.name === name)!;
const live = runtimeMap.get(name);
return {
...prev,
...status,
name,
role: status.role ?? prev?.role ?? SISTER_ROLES[name],
currentTask: live?.currentTask ?? status.currentTask ?? prev?.currentTask ?? null,
liveState: live?.mainState ?? prev?.liveState,
activeSessionLabel: live?.activeSessionLabel ?? prev?.activeSessionLabel ?? null,
gatewayConnected: live?.gatewayConnected ?? prev?.gatewayConnected ?? false,
subagents: live?.subagents ?? prev?.subagents ?? [],
};
});
}
function buildSisterNodes(sisters: SisterApiItem[]): SisterNode[] {
return SISTER_ORDER.map((name) => {
const item = sisters.find((s) => s.name === name);
const fallbackState = statusToAgentState(item?.status ?? 'unknown', Boolean(item?.currentTask));
const state = item?.gatewayConnected ? item.liveState ?? fallbackState : fallbackState;
const apiItem = sisters.find((s) => s.name === name);
const status = apiItem?.status ?? 'unknown';
const hasTask = Boolean(apiItem?.currentTask);
const parentState = statusToAgentState(status, hasTask);
const runtimeSubagents = item?.subagents ?? [];
const runtimeMap = new Map(runtimeSubagents.map((sub) => [sub.name, sub]));
const subagents: SubAgent[] = SUBAGENT_DEFS[name].map((def, index) => {
const runtime = runtimeMap.get(def.name);
return {
id: def.id,
name: def.name,
label: def.label,
sister: name,
state: runtime ? normalizeSubagentState(runtime.state) : derivedSubagentState(state, index),
currentTask: runtime?.currentTask ?? null,
updatedAt: runtime?.updatedAt ?? null,
sessionLabel: runtime?.sessionLabel ?? null,
};
});
const subDefs = SUBAGENT_DEFS[name];
const subagents: SubAgent[] = subDefs.map((def, i) => ({
...def,
sister: name,
state: derivedSubagentState(parentState, i),
}));
return {
name,
displayName: SISTER_DISPLAY[name],
role: item?.role ?? SISTER_ROLES[name],
state,
currentTask: item?.currentTask ?? null,
activeSessionLabel: item?.activeSessionLabel ?? null,
role: apiItem?.role ?? SISTER_ROLES[name],
emoji: name === 'harang' || name === 'narang' ? '🦊' : name === 'darang' ? '🐱' : '🐺',
state: parentState,
currentTask: apiItem?.currentTask ?? null,
subagents,
};
});
@@ -221,20 +174,35 @@ function buildSisterNodes(sisters: SisterApiItem[]): SisterNode[] {
function buildServerEntries(sisters: SisterApiItem[], sisterSource: 'live' | 'snapshot' | 'fallback'): ServerEntry[] {
const sisterEntries: ServerEntry[] = SISTER_ORDER.map((name) => {
const sister = sisters.find((item) => item.name === name);
const s = sisters.find((x) => x.name === name);
return {
id: `server-${name}`,
label: SISTER_DISPLAY[name],
type: 'sister' as const,
status: sister?.status ?? 'unknown',
detail: sister?.currentTask ?? sister?.activeSessionLabel ?? null,
source: sister ? sisterSource : 'fallback',
status: s?.status ?? 'unknown',
detail: s?.currentTask ?? null,
source: s ? sisterSource : 'fallback',
};
});
// Dev server and Docker are fallback (no direct API yet)
const extraEntries: ServerEntry[] = [
{ id: 'server-dev', label: 'Dev Server', type: 'dev', status: 'unknown', detail: null, source: 'fallback' },
{ id: 'server-docker', label: 'Docker / Infra', type: 'docker', status: 'unknown', detail: null, source: 'fallback' },
{
id: 'server-dev',
label: 'Dev Server',
type: 'dev',
status: 'unknown',
detail: null,
source: 'fallback',
},
{
id: 'server-docker',
label: 'Docker / Infra',
type: 'docker',
status: 'unknown',
detail: null,
source: 'fallback',
},
];
return [...sisterEntries, ...extraEntries];
@@ -248,6 +216,8 @@ function formatGeneratedAt(ts: string): string {
}
}
// ─── Styled Components ────────────────────────────────────────────────────────
const Shell = styled.div`
display: flex;
flex-direction: column;
@@ -275,10 +245,6 @@ const PageMeta = styled.div`
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
@media (max-width: 1279px) {
display: none;
}
`;
const FreshnessBar = styled.div`
@@ -286,11 +252,6 @@ const FreshnessBar = styled.div`
gap: var(--space-md);
flex-wrap: wrap;
margin-left: auto;
@media (max-width: 1279px) {
margin-left: 0;
width: 100%;
}
`;
const FreshnessBadge = styled.span<{ $type: 'live' | 'snapshot' | 'fallback' }>`
@@ -298,21 +259,23 @@ const FreshnessBadge = styled.span<{ $type: 'live' | 'snapshot' | 'fallback' }>`
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: ${({ $type }) => ($type === 'live' ? '#00BFA5' : $type === 'snapshot' ? '#FF9800' : '#777')};
color: ${({ $type }) =>
$type === 'live' ? '#00BFA5'
: $type === 'snapshot' ? '#FF9800'
: '#555'};
border: 1px solid currentColor;
padding: 2px 6px;
opacity: 0.8;
`;
/* ─── Desktop layout (≥1280px): scene + context side-by-side ─── */
const DesktopMain = styled.div`
const MainArea = styled.div`
display: flex;
gap: 0;
min-height: 0;
flex: 1;
@media (max-width: 1279px) {
display: none;
@media (max-width: 767px) {
flex-direction: column;
}
`;
@@ -328,8 +291,8 @@ const ChatArea = styled.div`
height: 520px;
flex-shrink: 0;
@media (max-width: 1279px) {
height: 400px;
@media (max-width: 767px) {
height: 460px;
}
`;
@@ -337,10 +300,6 @@ const BottomPanels = styled.div`
display: flex;
flex-direction: column;
gap: var(--space-lg);
@media (max-width: 1279px) {
display: none;
}
`;
const LoadingOverlay = styled.div`
@@ -355,290 +314,76 @@ const LoadingOverlay = styled.div`
letter-spacing: 0.08em;
`;
/* ─── Mobile layout (<1280px) ─── */
const MobileFlow = styled.div`
display: none;
flex-direction: column;
gap: var(--space-lg);
@media (max-width: 1279px) {
display: flex;
}
`;
const MobileSisterGrid = styled.div`
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--space-sm);
@media (max-width: 359px) {
grid-template-columns: 1fr;
}
`;
const STATE_CARD_COLORS: Record<AgentState, string> = {
idle: '#444',
thinking: '#2979FF',
tool_calling: '#FF9800',
speaking: '#00BFA5',
error: '#FF1744',
};
const MobileSisterCard = styled.button<{ $state: AgentState; $selected: boolean }>`
display: flex;
align-items: center;
gap: var(--space-sm);
padding: var(--space-sm) var(--space-md);
border: 1px solid ${({ $state }) => STATE_CARD_COLORS[$state]};
background: ${({ $selected }) => ($selected ? 'rgba(255,255,255,0.04)' : 'var(--bg-surface)')};
cursor: pointer;
text-align: left;
font-family: inherit;
color: var(--text-primary);
outline: ${({ $selected }) => ($selected ? '1px solid var(--text-primary)' : 'none')};
outline-offset: -1px;
`;
const MobileCardMeta = styled.div`
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
flex: 1;
`;
const MobileCardName = styled.div`
font-size: 13px;
font-weight: 600;
white-space: nowrap;
`;
const MobileCardState = styled.div<{ $state: AgentState }>`
font-family: var(--font-mono);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: ${({ $state }) => STATE_CARD_COLORS[$state]};
`;
const MobileCardTask = styled.div`
font-size: 11px;
color: var(--text-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
const MobileFocusSection = styled.div`
border: 1px solid var(--border-color);
background: var(--bg-surface);
padding: var(--space-md) var(--space-lg);
display: flex;
flex-direction: column;
gap: var(--space-sm);
`;
const MobileSectionEyebrow = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const MobileFocusTitle = styled.div`
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
`;
const MobileFocusDetail = styled.div`
font-size: 12px;
color: var(--text-secondary);
`;
const MobileHealthRow = styled.div`
display: flex;
gap: var(--space-sm);
flex-wrap: wrap;
`;
const MobileHealthChip = styled.div<{ $ok: boolean }>`
font-family: var(--font-mono);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.06em;
padding: 2px 8px;
border: 1px solid ${({ $ok }) => ($ok ? '#00BFA5' : '#555')};
color: ${({ $ok }) => ($ok ? '#00BFA5' : '#777')};
`;
const MobileQuickActions = styled.div`
display: flex;
gap: var(--space-sm);
flex-wrap: wrap;
`;
const MobileActionBtn = 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);
}
`;
const MobileContextInline = styled.div`
border: 1px solid var(--border-color);
background: var(--bg-surface);
padding: var(--space-md) var(--space-lg);
display: flex;
flex-direction: column;
gap: var(--space-md);
`;
const MobileContextHeader = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
`;
const MobileContextTitle = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const MobileCloseBtn = 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 MobileSelectedSummary = styled.div`
display: flex;
align-items: center;
gap: var(--space-sm);
`;
const MobileSelectedMeta = styled.div`
display: flex;
flex-direction: column;
gap: 2px;
`;
const MobileSelectedName = styled.div`
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
`;
const MobileSelectedRole = styled.div`
font-size: 11px;
color: var(--text-secondary);
`;
const MobileTaskBox = 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 MobileChatArea = styled.div`
height: 400px;
flex-shrink: 0;
@media (max-width: 389px) {
height: 360px;
}
`;
// ─── Main Component ───────────────────────────────────────────────────────────
export default function OfficePage() {
const [sisters, setSisters] = useState<SisterApiItem[]>([]);
const [opsData, setOpsData] = useState<DashboardOpsData | null>(null);
const [loading, setLoading] = useState(true);
const [selected, setSelected] = useState<SelectedAgent | null>(null);
const [chatSister, setChatSister] = useState<SisterName | null>(null);
// Live WebSocket connection
const { connected } = useSocket<SisterApiItem>({
onSistersUpdate: (updated) => {
setSisters((prev) => mergeSisterData(updated, [], prev));
onSistersUpdate: (updatedSisters) => {
setSisters(updatedSisters);
},
});
const fetchAll = useCallback(async () => {
const [sistersRes, opsRes, runtimeRes] = await Promise.allSettled([
fetch(`${API_URL}/api/sisters`).then((r) => r.json()),
fetch(`${API_URL}/api/dashboard/ops`).then((r) => r.json()),
fetch(`${API_URL}/api/sisters/runtime`).then((r) => r.json()),
]);
setSisters((prev) => {
const base = sistersRes.status === 'fulfilled' && Array.isArray(sistersRes.value) ? sistersRes.value as SisterApiItem[] : prev;
const runtime = runtimeRes.status === 'fulfilled' && Array.isArray(runtimeRes.value) ? runtimeRes.value as SisterRuntimeItem[] : [];
return mergeSisterData(base, runtime, prev);
});
if (opsRes.status === 'fulfilled') {
setOpsData(opsRes.value as DashboardOpsData);
}
}, []);
// Initial data fetch
useEffect(() => {
const boot = async () => {
const fetchAll = async () => {
try {
await fetchAll();
const [sistersRes, opsRes] = await Promise.allSettled([
fetch(`${API_URL}/api/sisters`).then((r) => r.json()),
fetch(`${API_URL}/api/dashboard/ops`).then((r) => r.json()),
]);
if (sistersRes.status === 'fulfilled') {
setSisters(Array.isArray(sistersRes.value) ? sistersRes.value : []);
}
if (opsRes.status === 'fulfilled') {
setOpsData(opsRes.value);
}
} finally {
setLoading(false);
}
};
void boot();
void fetchAll();
// Polling fallback — only when socket is disconnected
// Fix #3: Polling only when socket is not connected
// Socket handles live updates; polling is a disconnected fallback
return () => {};
}, [fetchAll]);
}, []);
// Polling fallback — only when socket is disconnected
useEffect(() => {
if (connected) return; // socket is live, no polling needed
const interval = setInterval(() => {
void fetchAll();
fetch(`${API_URL}/api/sisters`)
.then((r) => r.json())
.then((data: SisterApiItem[]) => {
if (Array.isArray(data)) setSisters(data);
})
.catch(() => {/* ignore polling errors */});
}, POLL_INTERVAL_MS);
return () => clearInterval(interval);
}, [connected, fetchAll]);
}, [connected]);
const hasSisterSnapshot = sisters.length > 0;
const sisterDataMode: 'live' | 'snapshot' | 'fallback' = connected ? 'live' : hasSisterSnapshot ? 'snapshot' : 'fallback';
const sisterDataMode: 'live' | 'snapshot' | 'fallback' = connected
? 'live'
: hasSisterSnapshot
? 'snapshot'
: 'fallback';
const effectiveSisters = hasSisterSnapshot ? sisters : FALLBACK_SISTERS;
const sisterNodes = useMemo(() => buildSisterNodes(effectiveSisters), [effectiveSisters]);
const serverEntries = useMemo(() => buildServerEntries(effectiveSisters, sisterDataMode), [effectiveSisters, sisterDataMode]);
const subagentMode: 'live' | 'fallback' = useMemo(() => {
return effectiveSisters.some((item) => (item.subagents?.length ?? 0) > 0) ? 'live' : 'fallback';
}, [effectiveSisters]);
const sisterNodes = buildSisterNodes(effectiveSisters);
const serverEntries = buildServerEntries(effectiveSisters, sisterDataMode);
const handleSelectSister = useCallback((name: SisterName) => {
setSelected({ type: 'sister', name });
@@ -654,9 +399,17 @@ export default function OfficePage() {
setChatSister(sisterName);
}, []);
const handleCloseChat = useCallback(() => {
setChatSister(null);
}, []);
const handleClearSelection = useCallback(() => {
setSelected(null);
}, []);
const pipeline = opsData?.pipeline ?? {
activeTask: 'SPRINT-016',
focus: 'Office runtime sync',
focus: 'Isometric Office Dashboard',
reviewLoopCount: 0,
escalationCount: 0,
deployState: '—',
@@ -670,23 +423,6 @@ export default function OfficePage() {
qaDocLatestAt: null,
};
const selectedSisterNode = useMemo(() => {
if (!selected) return null;
if (selected.type === 'sister') return sisterNodes.find((s) => s.name === selected.name) ?? null;
if (selected.type === 'subagent') return sisterNodes.find((s) => s.name === selected.sister) ?? null;
return null;
}, [selected, sisterNodes]);
const selectedSubagent = useMemo(() => {
if (selected?.type !== 'subagent') return null;
return selectedSisterNode?.subagents.find((sub) => sub.id === selected.id) ?? null;
}, [selected, selectedSisterNode]);
const onlineCount = useMemo(
() => effectiveSisters.filter((s) => s.status === 'online' || s.status === 'working').length,
[effectiveSisters],
);
if (loading) {
return <LoadingOverlay> ...</LoadingOverlay>;
}
@@ -700,15 +436,16 @@ export default function OfficePage() {
<FreshnessBadge $type={sisterDataMode}>
: {sisterDataMode === 'live' ? 'live · ws' : sisterDataMode === 'snapshot' ? 'snapshot · poll' : 'fallback · doc'}
</FreshnessBadge>
<FreshnessBadge $type={subagentMode === 'live' ? 'live' : 'fallback'}>
: {subagentMode === 'live' ? 'live · runtime' : 'fallback'}
<FreshnessBadge $type="fallback">
서브에이전트: fallback
</FreshnessBadge>
<FreshnessBadge $type="snapshot">
pipeline: snapshot
</FreshnessBadge>
<FreshnessBadge $type="snapshot">pipeline: snapshot</FreshnessBadge>
</FreshnessBar>
</PageHeader>
{/* ─── Desktop layout (≥1280px) ─── */}
<DesktopMain>
<MainArea>
<SceneColumn>
<OfficeScene
sisters={sisterNodes}
@@ -716,12 +453,14 @@ export default function OfficePage() {
onSelectSister={handleSelectSister}
onSelectSubagent={handleSelectSubagent}
dataMode={sisterDataMode}
subagentMode={subagentMode}
/>
{chatSister && (
<ChatArea>
<ChatWorkspace initialSister={chatSister} onClose={() => setChatSister(null)} />
<ChatWorkspace
initialSister={chatSister}
onClose={handleCloseChat}
/>
</ChatArea>
)}
</SceneColumn>
@@ -730,122 +469,10 @@ export default function OfficePage() {
selected={selected}
sisters={sisterNodes}
onOpenChat={handleOpenChat}
onClear={() => setSelected(null)}
onClear={handleClearSelection}
/>
</DesktopMain>
</MainArea>
{/* ─── Mobile layout (<1280px) ─── */}
<MobileFlow>
{/* 1. Sister status cards */}
<MobileSisterGrid>
{sisterNodes.map((sister) => {
const isSelected = selected?.type === 'sister' && selected.name === sister.name;
return (
<MobileSisterCard
key={sister.name}
$state={sister.state}
$selected={isSelected}
aria-pressed={isSelected}
onClick={() => handleSelectSister(sister.name)}
>
<SisterAvatar name={sister.name} size={32} />
<MobileCardMeta>
<MobileCardName>{sister.displayName}</MobileCardName>
<MobileCardState $state={sister.state}>{sister.state}</MobileCardState>
{sister.currentTask && <MobileCardTask>{sister.currentTask}</MobileCardTask>}
</MobileCardMeta>
</MobileSisterCard>
);
})}
</MobileSisterGrid>
{/* 2. Current focus + health summary */}
<MobileFocusSection>
<MobileSectionEyebrow>current focus</MobileSectionEyebrow>
<MobileFocusTitle>{pipeline.activeTask}</MobileFocusTitle>
<MobileFocusDetail>{pipeline.focus}</MobileFocusDetail>
<MobileHealthRow>
<MobileHealthChip $ok={sisterDataMode === 'live'}>
ws: {sisterDataMode === 'live' ? 'connected' : 'disconnected'}
</MobileHealthChip>
<MobileHealthChip $ok={onlineCount >= 3}>
{onlineCount}/{SISTER_ORDER.length} online
</MobileHealthChip>
<MobileHealthChip $ok={pipeline.deployState !== 'blocked'}>
deploy: {pipeline.deployState}
</MobileHealthChip>
</MobileHealthRow>
</MobileFocusSection>
{/* 3. Quick actions */}
<MobileQuickActions>
{SISTER_ORDER.map((name) => (
<MobileActionBtn key={name} onClick={() => handleOpenChat(name)}>
{SISTER_DISPLAY[name]}
</MobileActionBtn>
))}
</MobileQuickActions>
{/* 4. Inline context — always show default, expand on selection */}
<MobileContextInline>
<MobileContextHeader>
<MobileContextTitle>
{selected && selectedSisterNode
? `${selected.type === 'sister' ? selectedSisterNode.displayName : selectedSubagent?.label ?? ''} · context`
: '현재 포커스'}
</MobileContextTitle>
{selected && <MobileCloseBtn onClick={() => setSelected(null)}></MobileCloseBtn>}
</MobileContextHeader>
<MobileSelectedSummary>
<SisterAvatar name={(selectedSisterNode ?? sisterNodes[0])?.name ?? 'harang'} size={28} />
<MobileSelectedMeta>
<MobileSelectedName>
{selected && selectedSisterNode
? (selected.type === 'sister' ? selectedSisterNode.displayName : selectedSubagent?.label)
: sisterNodes.find((s) => s.state === 'tool_calling' || s.state === 'thinking')?.displayName ?? sisterNodes[0]?.displayName ?? '—'}
</MobileSelectedName>
<MobileSelectedRole>
{selectedSisterNode?.role ?? sisterNodes[0]?.role ?? ''}
</MobileSelectedRole>
</MobileSelectedMeta>
</MobileSelectedSummary>
{((selectedSisterNode?.currentTask ?? sisterNodes.find((s) => s.state === 'tool_calling' || s.state === 'thinking')?.currentTask)) && (
<MobileTaskBox>
{selectedSisterNode?.currentTask ?? sisterNodes.find((s) => s.state === 'tool_calling' || s.state === 'thinking')?.currentTask ?? ''}
</MobileTaskBox>
)}
<MobileQuickActions>
<MobileActionBtn onClick={() => handleOpenChat((selectedSisterNode ?? sisterNodes[0])?.name ?? 'harang')}></MobileActionBtn>
</MobileQuickActions>
</MobileContextInline>
{/* 5. Chat (if open) */}
{chatSister && (
<MobileChatArea>
<ChatWorkspace initialSister={chatSister} onClose={() => setChatSister(null)} />
</MobileChatArea>
)}
{/* 6. Pipeline panel */}
<PipelinePanel
activeTask={pipeline.activeTask}
focus={pipeline.focus}
reviewLoopCount={pipeline.reviewLoopCount}
escalationCount={pipeline.escalationCount}
deployState={pipeline.deployState}
nodes={pipeline.nodes}
freshness={`generated ${formatGeneratedAt(freshness.generatedAt)}`}
/>
{/* 7. Server health */}
<ServerHealthPanel
servers={serverEntries}
dataMode={sisterDataMode}
generatedAt={freshness.generatedAt}
/>
</MobileFlow>
{/* ─── Desktop bottom panels ─── */}
<BottomPanels>
<PipelinePanel
activeTask={pipeline.activeTask}

View File

@@ -1,243 +0,0 @@
'use client';
import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
import {
useRailsSocket,
type RailsPipelineSummary,
type RailsSubTaskNode,
} from '@/lib/useRailsSocket';
import PipelineList from '@/components/rails/PipelineList';
import SubTaskTree from '@/components/rails/SubTaskTree';
import { LabelMeta } from '@/components/ui/base';
const Layout = styled.div`
display: grid;
grid-template-columns: minmax(320px, 380px) 1fr;
gap: 16px;
padding: 16px;
min-height: calc(100vh - 120px);
@media (max-width: 900px) {
grid-template-columns: 1fr;
}
`;
const Pane = styled.section`
background: var(--bg-input);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 16px;
overflow: auto;
`;
const PaneHeader = styled.header`
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
`;
const Dot = styled.span<{ $connected: boolean }>`
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 6px;
background: ${({ $connected }) => ($connected ? '#22c55e' : '#6b7280')};
`;
const StartBar = styled.div`
display: flex;
gap: 8px;
margin-bottom: 12px;
`;
const Input = styled.input`
flex: 1;
padding: 8px 12px;
background: var(--bg-surface);
border: 1px solid var(--border-color);
color: var(--text-primary);
border-radius: 8px;
font-size: 13px;
&:focus {
outline: none;
border-color: #5fafff;
}
`;
const Button = styled.button`
padding: 8px 16px;
background: #5fafff;
color: #fff;
border: none;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
&:hover {
opacity: 0.9;
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
`;
const DetailHeader = styled.div`
padding: 8px 0 12px;
border-bottom: 1px solid var(--border-color);
margin-bottom: 12px;
`;
const Meta = styled.div`
display: flex;
gap: 16px;
font-size: 12px;
opacity: 0.7;
margin-top: 4px;
`;
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 { connected } = useRailsSocket({
onPipelinesSnapshot: (next) => {
setPipelines(next);
if (!selectedId && next.length > 0) {
setSelectedId(next[0]!.id);
}
},
onSubTasksUpdated: (pipelineId, nextTree) => {
if (pipelineId === selectedId) {
setTree(nextTree);
}
},
});
// Initial fetch
useEffect(() => {
fetch(`${API_URL}/api/rails/pipelines`, { credentials: 'include' })
.then((r) => r.json())
.then((data: { pipelines: RailsPipelineSummary[] }) => {
setPipelines(data.pipelines);
if (!selectedId && data.pipelines.length > 0) {
setSelectedId(data.pipelines[0]!.id);
}
})
.catch(() => {
/* ignore */
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// When selection changes, fetch tree once
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 = pipelines.find((p) => p.id === selectedId) ?? null;
return (
<Layout>
<Pane>
<PaneHeader>
<LabelMeta>
<Dot $connected={connected} />
PIPELINES
</LabelMeta>
<span style={{ fontSize: 11, opacity: 0.6 }}>
{pipelines.length} total
</span>
</PaneHeader>
<StartBar>
<Input
placeholder="project"
value={projectInput}
onChange={(e) => setProjectInput(e.target.value)}
/>
</StartBar>
<StartBar>
<Input
placeholder="requirements..."
value={reqInput}
onChange={(e) => setReqInput(e.target.value)}
/>
<Button disabled={starting || !projectInput} onClick={handleStart}>
Start
</Button>
</StartBar>
<PipelineList
pipelines={pipelines}
selectedId={selectedId}
onSelect={setSelectedId}
/>
</Pane>
<Pane>
{selected ? (
<>
<DetailHeader>
<LabelMeta>PIPELINE DETAIL</LabelMeta>
<div style={{ fontWeight: 700, fontSize: 18, marginTop: 4 }}>
{selected.projectName}
</div>
<Meta>
<span>id: {selected.id}</span>
<span>state: {selected.currentState}</span>
<span>created: {new Date(selected.createdAt).toLocaleString()}</span>
</Meta>
</DetailHeader>
<SubTaskTree tree={tree} />
</>
) : (
<div style={{ opacity: 0.6, padding: 40, textAlign: 'center' }}>
Select a pipeline to view its sub-task tree.
</div>
)}
</Pane>
</Layout>
);
}

View File

@@ -8,7 +8,6 @@ import { useAuth } from '@/lib/AuthContext';
const NAV_ITEMS = [
{ href: '/', label: '대시' },
{ href: '/rails', label: '레일' },
{ href: '/office', label: '오피스' },
{ href: '/projects', label: '프로' },
{ href: '/activities', label: '활동' },

View File

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

View File

@@ -2,26 +2,9 @@
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';
import type { SisterName } 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[];
}
// ─── Types ───────────────────────────────────────────────────────────────────
interface ChatMessage {
id: string;
@@ -36,27 +19,40 @@ interface ChatWorkspaceProps {
onClose: () => void;
}
// ─── Static data ──────────────────────────────────────────────────────────────
const SISTER_DISPLAY: Record<SisterName, string> = {
harang: '하랑이',
narang: '나랑이',
darang: '다랑이',
erang: '이랑이',
erang: '이랑이',
};
const SISTER_EMOJIS: 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',
erang: 'Infra & Deploy',
};
const SISTER_ORDER: SisterName[] = ['harang', 'narang', 'darang', 'erang'];
// ─── Animations ──────────────────────────────────────────────────────────────
const fadeIn = keyframes`
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
to { opacity: 1; transform: translateY(0); }
`;
// ─── Styled Components ────────────────────────────────────────────────────────
const Workspace = styled.div`
display: flex;
height: 100%;
@@ -69,6 +65,7 @@ const Workspace = styled.div`
}
`;
// Left sidebar - sister tabs
const SisterTabs = styled.nav`
width: 200px;
flex-shrink: 0;
@@ -125,11 +122,14 @@ const SisterTab = styled.button<{ $active: boolean }>`
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 TabEmoji = styled.span`
font-size: 16px;
line-height: 1;
`;
const TabMeta = styled.div`
display: flex;
flex-direction: column;
@@ -150,6 +150,7 @@ const TabRole = styled.div`
}
`;
// Center - message timeline
const MessageArea = styled.div`
flex: 1;
display: flex;
@@ -166,6 +167,10 @@ const MessageHeader = styled.div`
flex-shrink: 0;
`;
const HeaderEmoji = styled.span`
font-size: 20px;
`;
const HeaderMeta = styled.div`
flex: 1;
`;
@@ -181,11 +186,11 @@ const HeaderRole = styled.div`
color: var(--text-secondary);
`;
const HeaderBadge = styled.div<{ $ok: boolean }>`
const HeaderBadge = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: ${({ $ok }) => ($ok ? '#00BFA5' : 'var(--text-secondary)')};
border: 1px solid currentColor;
color: var(--text-secondary);
border: 1px solid var(--border-color);
padding: 2px var(--space-sm);
text-transform: uppercase;
letter-spacing: 0.06em;
@@ -204,7 +209,7 @@ const MessageBubble = styled.div<{ $role: ChatMessage['role'] }>`
display: flex;
flex-direction: column;
gap: 4px;
align-items: ${({ $role }) => ($role === 'user' ? 'flex-end' : 'flex-start')};
align-items: ${({ $role }) => $role === 'user' ? 'flex-end' : 'flex-start'};
animation: ${fadeIn} 0.2s ease;
`;
@@ -218,15 +223,15 @@ const BubbleContent = styled.div<{ $role: ChatMessage['role'] }>`
$role === 'user'
? 'rgba(255,255,255,0.06)'
: $role === 'tool'
? 'rgba(255, 152, 0, 0.06)'
: 'rgba(255,255,255,0.02)'};
? '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')};
? '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`
@@ -236,6 +241,16 @@ const BubbleMeta = styled.div`
opacity: 0.6;
`;
const ToolCallBadge = styled.div`
display: flex;
align-items: center;
gap: 4px;
font-family: var(--font-mono);
font-size: 10px;
color: #FF9800;
margin-bottom: 2px;
`;
const EmptyTimeline = styled.div`
flex: 1;
display: flex;
@@ -248,7 +263,7 @@ const EmptyTimeline = styled.div`
text-align: center;
`;
const RuntimeNotice = styled.div`
const GatewayNotice = styled.div`
border: 1px solid var(--border-color);
padding: var(--space-md);
font-family: var(--font-mono);
@@ -257,10 +272,11 @@ const RuntimeNotice = styled.div`
text-transform: uppercase;
letter-spacing: 0.06em;
line-height: 1.7;
max-width: 320px;
max-width: 280px;
text-align: center;
`;
// Input area
const InputArea = styled.div`
padding: var(--space-md) var(--space-lg);
border-top: 1px solid var(--border-color);
@@ -282,6 +298,7 @@ const MessageInput = styled.textarea`
min-height: 40px;
max-height: 120px;
line-height: 1.5;
transition: border-color 0.15s;
&:focus {
outline: none;
@@ -324,12 +341,13 @@ const InputMeta = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
opacity: 0.6;
opacity: 0.5;
text-transform: uppercase;
letter-spacing: 0.06em;
text-align: center;
`;
// Right - sister context
const SisterContext = styled.aside`
width: 220px;
flex-shrink: 0;
@@ -373,6 +391,7 @@ const CtxMono = styled.div`
color: var(--text-secondary);
`;
// Close button
const CloseBtn = styled.button`
border: 1px solid var(--border-color);
background: transparent;
@@ -384,6 +403,7 @@ const CloseBtn = styled.button`
padding: var(--space-xs) var(--space-sm);
cursor: pointer;
font-family: var(--font-mono);
transition: all 0.15s;
&:hover {
border-color: var(--border-hover);
@@ -391,6 +411,8 @@ const CloseBtn = styled.button`
}
`;
// ─── Helpers ──────────────────────────────────────────────────────────────────
function formatTs(ts: string): string {
const date = new Date(ts);
const diff = Date.now() - date.getTime();
@@ -402,159 +424,84 @@ function formatTs(ts: string): string {
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(),
}));
}
// ─── Component ────────────────────────────────────────────────────────────────
export default function ChatWorkspace({ initialSister, onClose }: ChatWorkspaceProps) {
const [activeSister, setActiveSister] = useState<SisterName>(initialSister);
// Per-sister message maps avoid setState-in-effect for clearing on switch
const [allMessages, setAllMessages] = useState<Partial<Record<SisterName, ChatMessage[]>>>({});
const [runtimeBySister, setRuntimeBySister] = useState<Partial<Record<SisterName, RuntimeSnapshot>>>({});
// Per-sister draft — prevents input leaking across tabs
// Fix #2: 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]);
const setMessages = useCallback(
(updater: (prev: ChatMessage[]) => ChatMessage[]) => {
setAllMessages((prev) => ({
...prev,
[activeSister]: updater(prev[activeSister] ?? []),
}));
},
[activeSister],
);
// Scroll to bottom on new messages
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 () => {
// Fix #1: Use crypto.randomUUID for optimistic ids; reconcile with server id later
// Fix #2: Clear only the active sister's draft
const handleSend = useCallback(() => {
const text = input.trim();
if (!text || sending) return;
if (!text) return;
// Cookie-based auth — no token check needed
const userMessage: ChatMessage = {
id: `user-${crypto.randomUUID()}`,
const optimisticId = `opt-${crypto.randomUUID()}`;
const userMsg: ChatMessage = {
id: optimisticId,
role: 'user',
content: text,
ts: new Date().toISOString(),
};
setMessages(activeSister, (prev) => mergeMessages(prev, [userMessage]));
setMessages((prev) => [...prev, userMsg]);
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()}`,
// Gateway connection pending — show system notice
setTimeout(() => {
const sysMsg: ChatMessage = {
id: `sys-${crypto.randomUUID()}`,
role: 'assistant',
content: `전송 실패: ${message}`,
content: `[Gateway 연결 대기] ${SISTER_DISPLAY[activeSister]} OpenClaw Gateway가 아직 연결되지 않았습니다. 직접 채팅 기능은 Gateway WebSocket 연결 후 활성화됩니다.`,
ts: new Date().toISOString(),
}]));
} finally {
setSending(false);
}
}, [activeSister, input, loadRuntime, sending, setMessages]);
};
setMessages((prev) => [...prev, sysMsg]);
}, 400);
}, [activeSister, input, setMessages]);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
void handleSend();
handleSend();
}
};
return (
<Workspace>
{/* Left: sister tabs */}
<SisterTabs>
<SisterTabHeader>direct chat</SisterTabHeader>
{SISTER_ORDER.map((name) => (
<SisterTab key={name} $active={activeSister === name} onClick={() => setActiveSister(name)}>
<SisterAvatar name={name} size={22} />
<SisterTab
key={name}
$active={activeSister === name}
onClick={() => setActiveSister(name)}
>
<TabEmoji>{SISTER_EMOJIS[name]}</TabEmoji>
<TabMeta>
<TabName>{SISTER_DISPLAY[name]}</TabName>
<TabRole>{SISTER_ROLES[name].split(' ')[0]}</TabRole>
@@ -563,33 +510,35 @@ export default function ChatWorkspace({ initialSister, onClose }: ChatWorkspaceP
))}
</SisterTabs>
{/* Center: message timeline */}
<MessageArea>
<MessageHeader>
<SisterAvatar name={activeSister} size={28} />
<HeaderEmoji>{SISTER_EMOJIS[activeSister]}</HeaderEmoji>
<HeaderMeta>
<HeaderName>{SISTER_DISPLAY[activeSister]}</HeaderName>
<HeaderRole>{SISTER_ROLES[activeSister]}</HeaderRole>
</HeaderMeta>
<HeaderBadge $ok={Boolean(runtime?.gatewayConnected)}>
{runtime?.gatewayConnected ? 'Runtime 연결됨' : 'Runtime 확인 중'}
</HeaderBadge>
<HeaderBadge>Gateway </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>
<div>{SISTER_EMOJIS[activeSister]}</div>
<div>{SISTER_DISPLAY[activeSister]} .</div>
<GatewayNotice>
openclaw gateway <br />
<br />
gateway
</GatewayNotice>
</EmptyTimeline>
) : (
messages.map((msg) => (
<MessageBubble key={msg.id} $role={msg.role}>
{msg.role === 'tool' && (
<ToolCallBadge>🔧 tool · {msg.toolName}</ToolCallBadge>
)}
<BubbleContent $role={msg.role}>{msg.content}</BubbleContent>
<BubbleMeta>{formatTs(msg.ts)}</BubbleMeta>
</MessageBubble>
@@ -598,48 +547,61 @@ export default function ChatWorkspace({ initialSister, onClose }: ChatWorkspaceP
</Timeline>
<InputMeta>
shift+enter = · enter = · runtime: {runtime ? runtimeStateLabel(runtime.mainState) : 'loading'}
shift+enter = · enter = · gateway: 연결
</InputMeta>
<InputArea>
<MessageInput
placeholder={`${SISTER_DISPLAY[activeSister]}에게 지시...`}
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 onClick={handleSend} disabled={!input.trim()}>
</SendBtn>
</InputArea>
</MessageArea>
{/* Right: sister context */}
<SisterContext>
<ContextSection>
<CtxLabel>agent</CtxLabel>
<CtxValue>{SISTER_DISPLAY[activeSister]}</CtxValue>
<CtxValue>
{SISTER_EMOJIS[activeSister]} {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>
<CtxValue>Gateway </CtxValue>
<CtxMono>openclaw websocket</CtxMono>
</ContextSection>
<ContextSection>
<CtxLabel>data source</CtxLabel>
<CtxMono>
control: ssh openclaw agent
<br />
activity: runtime session snapshot
live: ws (pending)<br />
fallback: ui-only
</CtxMono>
</ContextSection>
<ContextSection>
<CtxLabel>current task</CtxLabel>
<CtxValue>{runtime?.currentTask ?? runtime?.activeSessionLabel ?? '작업 정보 없음'}</CtxValue>
<CtxLabel></CtxLabel>
<CtxValue>
<a
href={`/sisters/${activeSister}`}
style={{
color: 'var(--text-secondary)',
textDecoration: 'none',
fontSize: '12px',
}}
>
</a>
</CtxValue>
</ContextSection>
</SisterContext>
</Workspace>

View File

@@ -3,9 +3,10 @@
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';
// ─── Types ───────────────────────────────────────────────────────────────────
interface ContextPanelProps {
selected: SelectedAgent | null;
sisters: SisterNode[];
@@ -13,6 +14,8 @@ interface ContextPanelProps {
onClear: () => void;
}
// ─── Styled Components ────────────────────────────────────────────────────────
const Panel = styled.aside`
width: 300px;
flex-shrink: 0;
@@ -30,7 +33,7 @@ const Panel = styled.aside`
width: 100%;
border-left: none;
border-top: 1px solid var(--border-color);
max-height: 260px;
max-height: 220px;
}
`;
@@ -88,11 +91,10 @@ const AgentHeader = styled.div`
gap: var(--space-md);
`;
const AgentAvatarWrap = styled.div`
const AgentEmoji = styled.div`
font-size: 28px;
line-height: 1;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
`;
const AgentMeta = styled.div`
@@ -277,27 +279,40 @@ const FallbackNote = styled.div`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
opacity: 0.7;
opacity: 0.5;
text-transform: uppercase;
letter-spacing: 0.06em;
`;
// ─── Sister display data ──────────────────────────────────────────────────────
const SISTER_EMOJIS: Record<SisterName, string> = {
harang: '🦊',
narang: '🦊',
darang: '🐱',
erang: '🐺',
};
const SISTER_DISPLAY: Record<SisterName, string> = {
harang: '하랑이',
narang: '나랑이',
darang: '다랑이',
erang: '이랑이',
erang: '이랑이',
};
function SisterDetail({ sister, onOpenChat }: { sister: SisterNode; onOpenChat: (name: SisterName) => void }) {
const hasLiveSubagentState = sister.subagents.some((item) => item.sessionLabel || item.currentTask || item.updatedAt);
// ─── Component ────────────────────────────────────────────────────────────────
function SisterDetail({
sister,
onOpenChat,
}: {
sister: SisterNode;
onOpenChat: (name: SisterName) => void;
}) {
return (
<>
<AgentHeader>
<AgentAvatarWrap>
<SisterAvatar name={sister.name} size={40} />
</AgentAvatarWrap>
<AgentEmoji>{SISTER_EMOJIS[sister.name]}</AgentEmoji>
<AgentMeta>
<AgentName>{SISTER_DISPLAY[sister.name]}</AgentName>
<AgentRole>{sister.role}</AgentRole>
@@ -310,10 +325,10 @@ function SisterDetail({ sister, onOpenChat }: { sister: SisterNode; onOpenChat:
<StateLabel $state={sister.state}>{sister.state}</StateLabel>
</StateRow>
{(sister.currentTask || sister.activeSessionLabel) && (
{sister.currentTask && (
<Section>
<SectionLabel>current task</SectionLabel>
<CurrentTaskBox>{sister.currentTask ?? sister.activeSessionLabel ?? '작업 정보 없음'}</CurrentTaskBox>
<CurrentTaskBox>{sister.currentTask}</CurrentTaskBox>
</Section>
)}
@@ -328,12 +343,16 @@ function SisterDetail({ sister, onOpenChat }: { sister: SisterNode; onOpenChat:
</SubagentRow>
))}
</SubagentGrid>
<FallbackNote>{hasLiveSubagentState ? 'subagent state: live runtime' : 'subagent state: fallback'}</FallbackNote>
<FallbackNote>subagent state: fallback</FallbackNote>
</Section>
<ActionRow>
<ActionBtn onClick={() => onOpenChat(sister.name)}></ActionBtn>
<ActionLink href={`/sisters/${sister.name}`}></ActionLink>
<ActionBtn onClick={() => onOpenChat(sister.name)}>
</ActionBtn>
<ActionLink href={`/sisters/${sister.name}`}>
</ActionLink>
</ActionRow>
</>
);
@@ -348,14 +367,10 @@ function SubagentDetail({
sister: SisterNode;
onOpenChat: (name: SisterName) => void;
}) {
const liveNote = sub.sessionLabel || sub.currentTask || sub.updatedAt;
return (
<>
<AgentHeader>
<AgentAvatarWrap>
<SisterAvatar name={sister.name} size={40} />
</AgentAvatarWrap>
<AgentEmoji>🤖</AgentEmoji>
<AgentMeta>
<AgentName>{sub.label}</AgentName>
<AgentRole>{sub.name}</AgentRole>
@@ -370,44 +385,62 @@ function SubagentDetail({
<Section>
<SectionLabel>parent</SectionLabel>
<SectionValue>{SISTER_DISPLAY[sister.name]} · {sister.role}</SectionValue>
<SectionValue>
{SISTER_EMOJIS[sister.name]} {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>
<FallbackNote>subagent state: fallback · no direct api</FallbackNote>
<ActionRow>
<ActionBtn onClick={() => onOpenChat(sister.name)}>{SISTER_DISPLAY[sister.name]} </ActionBtn>
<ActionLink href={`/sisters/${sister.name}`}> </ActionLink>
<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) {
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 />
<br />
.
</EmptyState>
);
if (selected?.type === 'sister') {
const sister = getSister(selected.name);
if (sister) content = <SisterDetail sister={sister} onOpenChat={onOpenChat} />;
const sisterData = getSister(selected.name);
if (sisterData) {
content = (
<SisterDetail
sister={sisterData}
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} />;
const sisterData = getSister(selected.sister);
const subData = sisterData?.subagents.find((s) => s.id === selected.id);
if (sisterData && subData) {
content = (
<SubagentDetail
sub={subData}
sister={sisterData}
onOpenChat={onOpenChat}
/>
);
}
}
return (

View File

@@ -2,7 +2,8 @@
import React, { useCallback } from 'react';
import styled from 'styled-components';
import { API_URL } from '@/lib/config';
// ─── Types ───────────────────────────────────────────────────────────────────
export type AgentState = 'idle' | 'thinking' | 'tool_calling' | 'speaking' | 'error';
export type SisterName = 'harang' | 'narang' | 'darang' | 'erang';
@@ -13,18 +14,15 @@ export interface SubAgent {
label: string;
sister: SisterName;
state: AgentState;
currentTask?: string | null;
updatedAt?: number | null;
sessionLabel?: string | null;
}
export interface SisterNode {
name: SisterName;
displayName: string;
role: string;
emoji: string;
state: AgentState;
currentTask: string | null;
activeSessionLabel?: string | null;
subagents: SubAgent[];
}
@@ -38,9 +36,10 @@ interface OfficeSceneProps {
onSelectSister: (name: SisterName) => void;
onSelectSubagent: (id: string, sister: SisterName) => void;
dataMode: 'live' | 'snapshot' | 'fallback';
subagentMode: 'live' | 'fallback';
}
// ─── Styled wrappers ──────────────────────────────────────────────────────────
const SceneWrapper = styled.div`
position: relative;
width: 100%;
@@ -74,60 +73,68 @@ const WsDot = styled.span<{ $connected: boolean }>`
vertical-align: middle;
`;
// ─── SVG constants ────────────────────────────────────────────────────────────
const VB_W = 800;
const VB_H = 460;
type Point = [number, number];
// Zone rects [x, y, w, h]
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,
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,
};
// Sister desk center positions
const SISTER_POS: Record<SisterName, [number, number]> = {
harang: [75, 105],
harang: [75, 105],
darang: [725, 105],
narang: [75, 358],
erang: [725, 358],
narang: [75, 358],
erang: [725, 358],
};
// Conference room
const CONF = { cx: 400, cy: 232, rx: 55, ry: 30 };
// Subagent grid positions (cx, cy) per sister
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]],
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]],
erang: [[618, 322], [664, 298], [702, 286], [610, 388], [664, 380]],
};
// Zone accent colors
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)',
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)',
erang: 'rgba(255, 109, 0, 0.25)',
};
// State ring colors
const STATE_COLORS: Record<AgentState, string> = {
idle: '#444444',
thinking: '#2979FF',
tool_calling: '#FF9800',
speaking: '#00BFA5',
error: '#FF1744',
idle: '#444444',
thinking: '#2979FF',
tool_calling:'#FF9800',
speaking: '#00BFA5',
error: '#FF1744',
};
const STATE_PROGRESS: Record<AgentState, number> = {
@@ -154,46 +161,44 @@ function getSubagentPosition(sister: SisterName, index: number, state: AgentStat
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' };
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;
}
// ─── Helper: AgentCircle (rendered as SVG group) ──────────────────────────────
function SisterCircle({
cx,
cy,
r,
state,
name,
selected,
onClick,
cx, cy, r, state, emoji, selected, onClick,
}: {
cx: number;
cy: number;
r: number;
state: AgentState;
name: SisterName;
selected: boolean;
cx: number; cy: number; r: number;
state: AgentState; emoji: string; 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}`}
aria-label={`${emoji} sister — state: ${state}`}
onClick={onClick}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick(); } }}
style={{ cursor: 'pointer', outline: 'none' }}
>
{/* Outer selection ring */}
{selected && (
<circle
cx={cx}
cy={cy}
r={r + 8}
cx={cx} cy={cy} r={r + 8}
fill="none"
stroke="var(--text-primary)"
strokeWidth={1}
@@ -201,40 +206,45 @@ function SisterCircle({
opacity={0.6}
/>
)}
{/* State ring */}
<circle
cx={cx}
cy={cy}
r={r + 4}
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" />
<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" />
<animate
attributeName="stroke-opacity"
values="1;0.2;1"
dur="0.9s"
repeatCount="indefinite"
/>
)}
</circle>
{/* Body */}
<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})`}
/>
{/* Emoji */}
<text
x={cx}
y={cy + r + 16}
x={cx} y={cy + 7}
textAnchor="middle"
fontSize={r * 0.9}
style={{ userSelect: 'none', pointerEvents: 'none' }}
>
{emoji}
</text>
{/* State label below */}
<text
x={cx} y={cy + r + 16}
textAnchor="middle"
fontSize={9}
fontFamily="var(--font-mono)"
@@ -248,28 +258,15 @@ function SisterCircle({
}
function SubagentCircle({
cx,
cy,
r,
state,
label,
selected,
motion,
motionBegin,
onClick,
cx, cy, r, state, label, selected, motion, motionBegin, onClick,
}: {
cx: number;
cy: number;
r: number;
state: AgentState;
label: string;
selected: boolean;
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"
@@ -292,15 +289,23 @@ function SubagentCircle({
{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}>
<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" />
<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}
x={cx} y={cy + 4}
textAnchor="middle"
fontSize={8}
fontFamily="var(--font-mono)"
@@ -308,30 +313,42 @@ function SubagentCircle({
opacity={0.9}
style={{ userSelect: 'none', pointerEvents: 'none' }}
>
{label.length > 8 ? `${label.slice(0, 7)}` : label}
{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 }) {
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}
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" />}
{active && (
<animate
attributeName="stroke-dashoffset"
values="40;0"
dur="1.4s"
repeatCount="indefinite"
/>
)}
</line>
);
}
function PathConnector({ d, active }: { d: string; active: boolean }) {
function PathConnector({
d, active,
}: {
d: string; active: boolean;
}) {
return (
<path
d={d}
@@ -341,11 +358,27 @@ function PathConnector({ d, active }: { d: string; active: boolean }) {
strokeDasharray={active ? '6 4' : '3 4'}
strokeDashoffset={active ? 40 : 0}
>
{active && <animate attributeName="stroke-dashoffset" values="40;0" dur="1.8s" repeatCount="indefinite" />}
{active && (
<animate
attributeName="stroke-dashoffset"
values="40;0"
dur="1.8s"
repeatCount="indefinite"
/>
)}
</path>
);
}
// ─── Main Component ───────────────────────────────────────────────────────────
const SISTER_EMOJIS: Record<SisterName, string> = {
harang: '🦊',
narang: '🦊',
darang: '🐱',
erang: '🐺',
};
const SISTER_ORDER: SisterName[] = ['harang', 'narang', 'darang', 'erang'];
export default function OfficeScene({
@@ -354,7 +387,6 @@ export default function OfficeScene({
onSelectSister,
onSelectSubagent,
dataMode,
subagentMode,
}: OfficeSceneProps) {
const getSister = useCallback(
(name: SisterName) => sisters.find((s) => s.name === name),
@@ -363,101 +395,161 @@ export default function OfficeScene({
const isActive = useCallback(
(name: SisterName) => {
const sister = getSister(name);
return sister?.state === 'thinking' || sister?.state === 'tool_calling' || sister?.state === 'speaking';
const s = getSister(name);
return s?.state === 'thinking' || s?.state === 'tool_calling' || s?.state === 'speaking';
},
[getSister],
);
const isSisterSelected = (name: SisterName) => selected?.type === 'sister' && selected.name === name;
const isSubSelected = (id: string) => selected?.type === 'subagent' && selected.id === id;
const isSisterSelected = (name: SisterName) =>
selected?.type === 'sister' && selected.name === name;
const isSubSelected = (id: string) =>
selected?.type === 'subagent' && selected.id === id;
// Derive active handoff lines from sister states
const harangActive = isActive('harang');
const narangActive = isActive('narang');
const darangActive = isActive('darang');
const erangActive = isActive('erang');
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'}
{' · subagents: fallback'}
</FreshnessLabel>
<svg viewBox={`0 0 ${VB_W} ${VB_H}`} width="100%" height="100%" style={{ display: 'block' }}>
<svg
viewBox={`0 0 ${VB_W} ${VB_H}`}
width="100%"
height="100%"
style={{ display: 'block' }}
>
{/* ── Zone backgrounds ── */}
{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}
/>
<g key={`zone-${name}`}>
<rect
x={zx} y={zy} width={zw} height={zh}
rx={4}
fill={ZONE_COLORS[name]}
stroke={ZONE_BORDER[name]}
strokeWidth={1}
/>
</g>
);
})}
{/* ── Center corridor (vertical) ── */}
<rect x={358} y={5} width={84} height={450} rx={2} fill="#111111" stroke="rgba(255,255,255,0.04)" strokeWidth={1} />
{/* ── Center corridor (horizontal) ── */}
<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)">
{/* ── Conference room ── */}
<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)"
style={{ textTransform: 'uppercase', letterSpacing: '0.08em' }}
>
</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} />
{/* ── Connectors ── */}
{/* harang ↔ narang (left vertical through corridor) */}
<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}
/>
{/* darang ↔ erang (right vertical through corridor) */}
<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}
/>
{/* harang ↔ darang (through conference, horizontal top) */}
<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}
/>
{/* narang ↔ erang (horizontal bottom) */}
<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}
/>
{/* narang → darang (review path through conference, curved) */}
<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}
/>
{/* ── Zone labels ── */}
{([
['harang', 18, 22, '하랑이 · Planning'] as const,
['darang', 463, 22, '다랑이 · QA'] as const,
['narang', 18, 272, '나랑이 · Dev'] as const,
['erang', 463, 272, '이랑이 · Infra'] as const,
['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
key={`label-${name}`}
x={lx} y={ly}
fontSize={10}
fontFamily="var(--font-mono)"
fill={ZONE_BORDER[name]}
style={{ textTransform: 'uppercase', letterSpacing: '0.08em' }}
>
{text}
</text>
))}
{/* ── Sister nodes ── */}
{SISTER_ORDER.map((name) => {
const sister = getSister(name);
const state: AgentState = sister?.state ?? 'idle';
const sisterData = getSister(name);
const state: AgentState = sisterData?.state ?? 'idle';
const [cx, cy] = SISTER_POS[name];
return (
<SisterCircle
key={`sister-${name}`}
cx={cx}
cy={cy}
r={28}
cx={cx} cy={cy} r={28}
state={state}
name={name}
emoji={SISTER_EMOJIS[name]}
selected={isSisterSelected(name)}
onClick={() => onSelectSister(name)}
/>
);
})}
{/* ── Subagent nodes ── */}
{SISTER_ORDER.map((sisterName) => {
const sister = getSister(sisterName);
const subagents = sister?.subagents ?? [];
const sisterData = getSister(sisterName);
const subagents = sisterData?.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}
cx={pos[0]} cy={pos[1]} r={14}
state={sub.state}
label={sub.name}
selected={isSubSelected(sub.id)}
@@ -469,9 +561,10 @@ export default function OfficeScene({
});
})}
{/* ── Subagent → Sister connector lines (thin) ── */}
{SISTER_ORDER.map((sisterName) => {
const sister = getSister(sisterName);
const subagents = sister?.subagents ?? [];
const sisterData = getSister(sisterName);
const subagents = sisterData?.subagents ?? [];
const [sx, sy] = SISTER_POS[sisterName];
return subagents.map((sub, i) => {
const pos = getSubagentPosition(sisterName, i, sub.state);
@@ -479,10 +572,8 @@ export default function OfficeScene({
return (
<line
key={`conn-${sub.id}`}
x1={sx}
y1={sy}
x2={pos[0]}
y2={pos[1]}
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"

View File

@@ -1,7 +1,7 @@
'use client';
import React from 'react';
import styled, { css, keyframes } from 'styled-components';
import styled, { keyframes } from 'styled-components';
import type { PipelineNode } from '@/components/dashboard/ActivePipeline';
// ─── Types ───────────────────────────────────────────────────────────────────
@@ -74,11 +74,6 @@ const Focus = styled.div`
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@media (max-width: 767px) {
max-width: 100%;
white-space: normal;
}
`;
const Stats = styled.div`
@@ -115,11 +110,6 @@ const NodeRow = styled.div`
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> = {
@@ -138,10 +128,6 @@ const NodeCard = styled.div<{ $state: PipelineNode['state'] }>`
display: flex;
flex-direction: column;
gap: 4px;
@media (max-width: 767px) {
min-width: 0;
}
`;
const NodeName = styled.div`
@@ -191,14 +177,7 @@ const Connector = styled.div<{ $active: boolean }>`
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);
animation: ${({ $active }) => $active ? `${flowAnim} 1.6s linear infinite` : 'none'};
}
`;

View File

@@ -73,10 +73,6 @@ const Grid = styled.div`
@media (max-width: 767px) {
grid-template-columns: repeat(2, 1fr);
}
@media (max-width: 359px) {
grid-template-columns: 1fr;
}
`;
const statusColors: Record<ServerEntry['status'], string> = {

View File

@@ -1,118 +0,0 @@
'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

@@ -1,156 +0,0 @@
'use client';
import React from 'react';
import styled from 'styled-components';
import type { RailsSubTaskNode } from '@/lib/useRailsSocket';
const Wrap = styled.div`
font-family: var(--font-mono, monospace);
font-size: 13px;
line-height: 1.6;
`;
const Node = styled.div<{ $state: string }>`
padding: 4px 8px;
border-left: 3px solid ${({ $state }) => stateColor($state)};
margin: 2px 0;
background: var(--bg-surface);
border-radius: 4px;
`;
const RoleBadge = styled.span<{ $role: string }>`
display: inline-block;
padding: 1px 8px;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
border-radius: 10px;
color: #fff;
margin-right: 8px;
background: ${({ $role }) => roleColor($role)};
`;
const StateDot = styled.span<{ $state: string }>`
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 8px;
background: ${({ $state }) => stateColor($state)};
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: 10px;
opacity: 0.6;
margin-left: 8px;
`;
const Duration = styled.span`
font-size: 10px;
opacity: 0.6;
margin-left: auto;
`;
const Row = styled.div`
display: flex;
align-items: center;
`;
const Children = styled.div`
margin-left: 24px;
`;
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 }: { node: RailsSubTaskNode }) {
return (
<>
<Node $state={node.state}>
<Row>
<StateDot $state={node.state} />
<RoleBadge $role={node.role}>{node.role}</RoleBadge>
<span>{node.title.slice(0, 80)}</span>
<Model>{node.model || '—'}</Model>
<Duration>{duration(node.startedAt, node.completedAt)}</Duration>
</Row>
{node.complexityTier && (
<Row>
<span style={{ marginLeft: 22, fontSize: 10, opacity: 0.6 }}>
complexity: {node.complexityTier} ({node.complexityScore})
</span>
</Row>
)}
</Node>
{node.children.length > 0 && (
<Children>
{node.children.map((c) => (
<NodeRow key={c.id} node={c} />
))}
</Children>
)}
</>
);
}
interface Props {
tree: RailsSubTaskNode[];
}
export default function SubTaskTree({ tree }: Props) {
if (tree.length === 0) {
return <Wrap>No sub-tasks yet.</Wrap>;
}
return (
<Wrap>
{tree.map((node) => (
<NodeRow key={node.id} node={node} />
))}
</Wrap>
);
}

View File

@@ -1,93 +0,0 @@
'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

File diff suppressed because it is too large Load Diff