Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions docs/superpowers/specs/2026-08-05-workflow-chain-view-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Maestro Workflow 체인 시각화 설계 (대시보드)

- 날짜: 2026-08-05
- 상태: 확정 (이메일 유스케이스 잔여 — 운영자가 이전 단계를 보고 결정)
- 범위: `workflow/src/` 하위만 (서버 무변경 — 기존 chain API 사용)

## 1. 동작

- **ChannelBoard 카드**: `parentRequestId`가 있는 요청에 "🔗 체인" 배지 표시.
- **DecisionSheet**: 선택한 요청이 체인에 속하면(App이 `chain` prop 전달)
상단에 컴팩트 타임라인 표시 — 체인의 각 요청을 순서대로
`subjectType · title · 상태(결정됨/대기)`로, 현재 요청은 강조.
체인 로드 실패 시 조용히 생략(기존 "체인 이전 요청: id" 라인 유지).
- **App**: 요청 선택 시 `parentRequestId`가 있으면 `fetchRequestChain`으로
체인을 불러 sheet에 전달. 없으면 즉시 열림(로딩 블로킹 없음 — 체인은
도착하는 대로 표시).

## 2. api.js

`fetchRequestChain(requestId)` → `GET /api/decision-requests/:id/chain`
(기존 토큰 상태 재사용 — 운영자/서버 토큰).

## 3. 테스트

- ChannelBoard: parentRequestId 카드에 배지, 없는 카드엔 없음.
- DecisionSheet: chain prop 타임라인 렌더(순서·현재 강조·상태 라벨).
- App: 체인 요청 선택 시 fetchRequestChain 호출 + sheet에 표시 (mock).

## 4. 비범위

레인 자체를 체인으로 묶는 보드 재배치, 서버 변경, 체인 내 결정 코멘트
전문 표시(타이틀·상태만).
70 changes: 70 additions & 0 deletions workflow/src/App.chain.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

const fetchPendingRequests = vi.fn();
const fetchRequestChain = vi.fn();
vi.mock('./lib/api.js', () => ({
WS_URL: 'ws://test',
fetchPendingRequests: (...args) => fetchPendingRequests(...args),
fetchHistory: vi.fn().mockResolvedValue([]),
decideRequest: vi.fn(),
fetchRequestChain: (...args) => fetchRequestChain(...args),
loadServerToken: vi.fn().mockReturnValue(''),
getServerToken: vi.fn().mockReturnValue(''),
setServerToken: vi.fn(),
}));

import App from './App.jsx';

class FakeWebSocket {
send() {}
close() {}
}

describe('App 체인 시각화', () => {
beforeEach(() => {
vi.stubGlobal('WebSocket', FakeWebSocket);
fetchPendingRequests.mockReset();
fetchRequestChain.mockReset();
});

it('체인 요청 선택 시 체인을 불러 시트에 타임라인으로 보여준다', async () => {
const reply = {
requestId: 'dcr_2',
parentRequestId: 'dcr_1',
subjectType: 'email-reply',
actorId: 'agent_mail',
subject: { title: '답장 초안 v1', summary: '', payload: {} },
};
fetchPendingRequests.mockResolvedValue([reply]);
fetchRequestChain.mockResolvedValue([
{ requestId: 'dcr_1', subjectType: 'email-triage', status: 'decided', subject: { title: '메일 분류' } },
{ ...reply, status: 'pending_decision' },
]);

const user = userEvent.setup();
render(<App />);
await user.click(await screen.findByText('답장 초안 v1'));

expect(fetchRequestChain).toHaveBeenCalledWith('dcr_2');
const timeline = await screen.findByLabelText('결정 체인');
expect(timeline.textContent).toContain('메일 분류');
});

it('체인 없는 요청은 체인 조회를 하지 않는다', async () => {
fetchPendingRequests.mockResolvedValue([{
requestId: 'dcr_solo',
subjectType: 'spend',
actorId: 'agent_a',
subject: { title: '단독 요청', summary: '', payload: {} },
}]);

const user = userEvent.setup();
render(<App />);
await user.click(await screen.findByText('단독 요청'));

expect(fetchRequestChain).not.toHaveBeenCalled();
expect(screen.queryByLabelText('결정 체인')).not.toBeInTheDocument();
});
});
21 changes: 19 additions & 2 deletions workflow/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
decideRequest,
fetchHistory,
fetchPendingRequests,
fetchRequestChain,
getServerToken,
loadServerToken,
setServerToken,
Expand All @@ -19,6 +20,7 @@ const MAX_RECONNECT_DELAY_MS = 15000;
export default function App() {
const [requests, setRequests] = useState([]);
const [selected, setSelected] = useState(null);
const [selectedChain, setSelectedChain] = useState(null);
const [connected, setConnected] = useState(false);
const [showHistory, setShowHistory] = useState(false);
const [history, setHistory] = useState([]);
Expand Down Expand Up @@ -106,17 +108,32 @@ export default function App() {
{showHistory ? (
<HistoryPanel entries={history} />
) : (
<ChannelBoard requests={requests} onSelect={setSelected} />
<ChannelBoard
requests={requests}
onSelect={(request) => {
setSelected(request);
setSelectedChain(null);
if (request.parentRequestId) {
// 체인 로드는 논블로킹 — 도착하는 대로 시트에 타임라인 표시 (스펙 2026-08-05 §1)
fetchRequestChain(request.requestId).then(setSelectedChain).catch(() => {});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Ignore stale chain responses

When an operator selects a chained request and then quickly selects another request before the first /chain call resolves, this promise still writes into the shared selectedChain state. Since DecisionSheet renders any non-null chain, the newly selected sheet can briefly or permanently show the previous request's timeline, including for a solo request if its own selection does not start a new fetch. Guard the response against the currently selected requestId or cancel/ignore it after selection changes.

Useful? React with 👍 / 👎.

}
}}
/>
)}
{selected ? (
<DecisionSheet
request={selected}
onClose={() => setSelected(null)}
chain={selectedChain}
onClose={() => {
setSelected(null);
setSelectedChain(null);
}}
onDecide={(decision, comment) => {
decideRequest(selected.requestId, { decision, comment })
.catch(() => {})
.finally(() => {
setSelected(null);
setSelectedChain(null);
reload();
});
}}
Expand Down
3 changes: 3 additions & 0 deletions workflow/src/components/ChannelBoard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export default function ChannelBoard({ requests, channelCount = 4, onSelect }) {
<span className="mr-2 rounded bg-indigo-600/70 px-1.5 py-0.5 text-[10px] uppercase">
{request.subjectType}
</span>
{request.parentRequestId ? (
<span className="rounded bg-slate-700 px-1.5 py-0.5 text-[10px] text-indigo-300">🔗 체인</span>
) : null}
<span className="block mt-1 text-sm font-medium">{request.subject.title}</span>
<span className="block text-xs text-slate-400">{request.actorId}</span>
</button>
Expand Down
16 changes: 16 additions & 0 deletions workflow/src/components/ChannelBoard.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,19 @@ describe('ChannelBoard', () => {
expect(onSelect).toHaveBeenCalledWith(requests[1]);
});
});

it('체인에 속한 요청 카드에 체인 배지를 표시한다', () => {
render(
<ChannelBoard
requests={[
{ requestId: 'dcr_1', subjectType: 'email-triage', actorId: 'agent_mail', subject: { title: '분류', payload: {} } },
{ requestId: 'dcr_2', parentRequestId: 'dcr_1', subjectType: 'email-reply', actorId: 'agent_mail', subject: { title: '답장', payload: {} } },
]}
onSelect={() => {}}
/>,
);
const notes = screen.getAllByTestId('decision-note');
expect(notes.some((note) => note.textContent.includes('체인'))).toBe(true);
const rootNote = notes.find((note) => note.textContent.includes('분류'));
expect(rootNote.textContent.includes('체인')).toBe(false);
});
16 changes: 14 additions & 2 deletions workflow/src/components/DecisionSheet.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const SECONDARY_ACTIONS = [
];

// 결정 시트: 상세 표시 + 승인/반려. 반려는 사유 칩 + 자유 입력 (본체 터치 반려 시트 패턴 계승).
export default function DecisionSheet({ request, onDecide, onClose }) {
export default function DecisionSheet({ request, onDecide, onClose, chain = null }) {
const [rejecting, setRejecting] = useState(false);
const [reason, setReason] = useState('');
const highlight = formatPresetHighlight(request.subjectType, request.subject.payload);
Expand Down Expand Up @@ -42,7 +42,19 @@ export default function DecisionSheet({ request, onDecide, onClose }) {
{JSON.stringify(request.subject.payload, null, 2)}
</pre>
<div className="mt-2 text-xs text-slate-500">요청자: {request.actorId}</div>
{request.parentRequestId ? (
{chain && chain.length > 1 ? (
<ol className="mt-3 space-y-1 rounded-lg bg-slate-800/60 p-2 text-xs" aria-label="결정 체인">
{chain.map((item) => {
const isCurrent = item.requestId === request.requestId;
return (
<li key={item.requestId} className={isCurrent ? 'font-semibold text-indigo-300' : 'text-slate-400'}>
{item.subjectType} · {item.subject?.title} · {item.status === 'pending_decision' ? '대기' : '결정됨'}
{isCurrent ? ' ← 현재' : ''}
</li>
);
})}
</ol>
) : request.parentRequestId ? (
<div className="mt-1 text-xs text-indigo-300">체인 이전 요청: {request.parentRequestId}</div>
) : null}

Expand Down
25 changes: 25 additions & 0 deletions workflow/src/components/DecisionSheet.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,31 @@ describe('DecisionSheet', () => {
expect(onDecide).toHaveBeenCalledWith('revise', '');
});

it('chain prop이 있으면 타임라인을 렌더하고 현재 요청을 강조한다', () => {
render(
<DecisionSheet
request={{
requestId: 'dcr_2',
parentRequestId: 'dcr_1',
subjectType: 'email-reply',
actorId: 'agent_mail',
subject: { title: '답장 초안 v1', summary: '', payload: {} },
}}
chain={[
{ requestId: 'dcr_1', subjectType: 'email-triage', status: 'decided', subject: { title: '메일 분류' } },
{ requestId: 'dcr_2', subjectType: 'email-reply', status: 'pending_decision', subject: { title: '답장 초안 v1' } },
]}
onDecide={() => {}}
onClose={() => {}}
/>,
);
const timeline = screen.getByLabelText('결정 체인');
expect(timeline.textContent).toContain('메일 분류');
expect(timeline.textContent).toContain('결정됨');
expect(timeline.textContent).toContain('대기');
expect(timeline.textContent).toContain('← 현재');
});

it('parentRequestId가 있으면 체인 이전 요청을 표시한다', () => {
render(
<DecisionSheet
Expand Down
6 changes: 6 additions & 0 deletions workflow/src/lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ export function decideRequest(requestId, { decision, comment = '' }) {
});
}

// 체인 시각화 (스펙 2026-08-05): 선택 요청의 결정 체인 전체 조회 (운영자/서버 토큰)
export async function fetchRequestChain(requestId) {
const body = await requestJson(`/api/decision-requests/${encodeURIComponent(requestId)}/chain`);
return body.items || [];
}

export async function fetchHistory(limit = 40) {
const body = await requestJson(`/api/history?limit=${limit}`);
return body.items || [];
Expand Down
Loading