summaryrefslogtreecommitdiff
path: root/frontend/src/components
diff options
context:
space:
mode:
Diffstat (limited to 'frontend/src/components')
-rw-r--r--frontend/src/components/LandingPage.tsx262
-rw-r--r--frontend/src/components/VNInterface.tsx28
-rw-r--r--frontend/src/components/document/index.ts14
-rw-r--r--frontend/src/components/document/nodes/StepLogFeed.tsx277
-rw-r--r--frontend/src/components/document/nodes/StepsDiagramComponent.tsx239
5 files changed, 170 insertions, 650 deletions
diff --git a/frontend/src/components/LandingPage.tsx b/frontend/src/components/LandingPage.tsx
index e7579b5..f126d6f 100644
--- a/frontend/src/components/LandingPage.tsx
+++ b/frontend/src/components/LandingPage.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react'
+import React, { useState, useEffect, useRef } from 'react'
import { LoadingScreen } from './LoadingScreen'
import { HeartLogo } from './HeartLogo'
@@ -9,7 +9,12 @@ interface LandingPageProps {
export function LandingPage({ onLogin }: LandingPageProps) {
const [loading, setLoading] = useState(false)
const [showLanding, setShowLanding] = useState(false)
+ const [isStandby, setIsStandby] = useState(true) // false = LIVE, true = STDBY
+ const [velocity, setVelocity] = useState(0)
+ const [energy, setEnergy] = useState(0)
+ const [ramped, setRamped] = useState(false)
const [pendingAction, setPendingAction] = useState<null | 'makimaRedirect'>(null)
+ const [activePanel, setActivePanel] = useState<null | 'mission' | 'makima'>(null)
// Fade-in landing page content after mount
useEffect(() => {
@@ -17,6 +22,62 @@ export function LandingPage({ onLogin }: LandingPageProps) {
return () => clearTimeout(timer)
}, [])
+ // Ramp up stats, then keep them fluctuating near max
+ useEffect(() => {
+ const VELOCITY_MAX = 603
+ const ENERGY_MAX = 32
+
+ let rampInterval: number | undefined
+ let fluctuateInterval: number | undefined
+
+ // Ramp-up for ~2 seconds
+ const rampDurationMs = 2000
+ const tickMs = 30
+ const vStep = VELOCITY_MAX / (rampDurationMs / tickMs)
+ const eStep = ENERGY_MAX / (rampDurationMs / tickMs)
+
+ rampInterval = window.setInterval(() => {
+ setVelocity((v) => {
+ const next = v + vStep
+ return next >= VELOCITY_MAX ? VELOCITY_MAX : next
+ })
+ setEnergy((e) => {
+ const next = e + eStep
+ return next >= ENERGY_MAX ? ENERGY_MAX : next
+ })
+ }, tickMs)
+
+ const stopRamp = window.setTimeout(() => {
+ if (rampInterval) window.clearInterval(rampInterval)
+ setVelocity(VELOCITY_MAX)
+ setEnergy(ENERGY_MAX)
+ setRamped(true)
+
+ // Fluctuate near the top
+ fluctuateInterval = window.setInterval(() => {
+ setVelocity((v) => {
+ const min = VELOCITY_MAX - 18
+ const max = VELOCITY_MAX
+ const delta = (Math.random() - 0.5) * 6 // ±3
+ const next = Math.max(min, Math.min(max, v + delta))
+ return next
+ })
+ setEnergy((e) => {
+ const min = ENERGY_MAX - 2
+ const max = ENERGY_MAX
+ const delta = (Math.random() - 0.5) * 0.25 // ±0.125
+ const next = Math.max(min, Math.min(max, e + delta))
+ return next
+ })
+ }, 220)
+ }, rampDurationMs + 60)
+
+ return () => {
+ if (rampInterval) window.clearInterval(rampInterval)
+ if (fluctuateInterval) window.clearInterval(fluctuateInterval)
+ }
+ }, [])
+
const handleLoadingComplete = () => {
if (pendingAction === 'makimaRedirect') {
window.location.assign('https://makima.jp')
@@ -30,129 +91,144 @@ export function LandingPage({ onLogin }: LandingPageProps) {
setLoading(true)
}
- const scrollTo = (id: string) => {
- document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' })
+ const handleMission = () => {
+ setActivePanel((mode) => (mode === 'mission' ? null : 'mission'))
+ }
+
+ const handleMakimaPanel = () => {
+ setActivePanel((mode) => (mode === 'makima' ? null : 'makima'))
}
return (
<div>
{loading && <LoadingScreen onComplete={handleLoadingComplete} />}
- {/* Professional floating header */}
{!loading && (
- <div className={`pro-header ${showLanding ? 'fade-in' : 'hidden'}`}>
- <div className="pro-header-content">
- <div className="pro-header-left">
+ <div className={`floating-header ${showLanding ? 'fade-in' : 'hidden'}`}>
+ <div className="header-content">
+ <div className="brand">
<img
src="/logo/crane-logo-transparent.png"
alt="Soryu"
- height={36}
- className="pro-crane-logo"
+ height={40}
+ className="brand-mark"
onError={(e) => {
const img = e.currentTarget as HTMLImageElement
img.onerror = null
img.src = '/logo/crane-logo.png'
}}
/>
- <span className="pro-company-name">SORYU</span>
</div>
-
- <div className="pro-header-center">
+ <div className="header-center">
<HeartLogo size="header-no-rays" className="header-heart" />
</div>
- <nav className="pro-header-nav">
- <button className="pro-nav-link" onClick={() => scrollTo('pro-mission')}>
- Mission
- </button>
- <button className="pro-nav-link" onClick={() => scrollTo('pro-makima')}>
- Makima
- </button>
- <button className="pro-nav-link pro-nav-login" onClick={handleLogin}>
- Login
- </button>
- </nav>
+ <div className="system-info">
+ <div className="info-item">
+ <span className="info-label">System:</span>
+ <span
+ className="info-value live-status clickable"
+ onClick={() => setIsStandby(!isStandby)}
+ title="Click to toggle between LIVE and STANDBY"
+ >
+ <span className={`status-dot ${isStandby ? 'standby' : 'live'}`}></span>
+ {isStandby ? 'STDBY' : 'LIVE'}
+ </span>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Version:</span>
+ <span className="info-value">v1.0.0</span>
+ </div>
+ </div>
</div>
</div>
)}
- {/* Main professional landing layout */}
- <div className={`pro-landing ${showLanding && !loading ? 'fade-in' : 'hidden'}`}>
-
- {/* Hero section */}
- <section className="pro-hero">
- <div className="pro-hero-inner">
- <div className="pro-hero-tagline-jp">そりゅう</div>
- <h1 className="pro-hero-headline">
- Real‑Time Systems for<br />Mission‑Critical Observability
- </h1>
- <p className="pro-hero-sub">
- Low‑latency streaming infrastructure that turns live data into reliable, secure insight.
- </p>
- <div className="pro-hero-cta">
- <button className="pro-btn-primary" onClick={() => scrollTo('pro-mission')}>
- Learn More
- </button>
- <button className="pro-btn-secondary" onClick={handleLogin}>
- <span className="pro-btn-icon">▶</span> Launch Makima
- </button>
- </div>
- </div>
- </section>
-
- {/* Content grid: Mission + Makima cards */}
- <section className="pro-content-grid">
- <div className="pro-card" id="pro-mission">
- <div className="pro-card-header">
- <h2 className="pro-card-title">Mission</h2>
- <div className="pro-card-accent" />
+ <div className={`modern-landing-page manga-style ${showLanding && !loading ? 'fade-in' : 'hidden'}`}>
+ {/* Background GIF fills the main body */}
+ <div className="background-only" aria-hidden="true">
+ <img src="/background-animation.gif" alt="" className="background-gif" />
+ </div>
+
+ {/* Minimal overlay: masthead, issue badge, and CTA */}
+ <div className={`taisho-cover ${activePanel ? 'mission-mode' : ''}`}>
+ <div className="cover-backdrop" aria-hidden="true" />
+ <div className="cover-content">
+ {/* Masthead + Issue badge (kept) */}
+ <div className="masthead">
+ <div className="masthead-vertical">
+ <span className="jp">そりゅう</span>
+ <span className="en">SORYU</span>
+ </div>
+ <div className="issue-badge"><span className="led-heart" aria-hidden="true"></span>かはいい Vol.01</div>
</div>
- <div className="pro-card-body">
- <h3 className="pro-card-subtitle">
- Building real‑time systems for mission-critical observability and surveillance
- </h3>
- <p className="pro-card-text">
- We deliver low‑latency streaming &amp; infrastructure that turns live data into
- reliable, secure insight. Target selection, monitoring and full end to end observability
- to make vital decisions where it matters most.
- </p>
+
+ {/* Hero area becomes Mission content when in mission mode */}
+ {activePanel === 'mission' ? (
+ <div className="mission-screen" role="region" aria-label="Mission">
+ <h1 className="mission-headline">Building real‑time systems for mission-critical observability and surveillance </h1>
+ <img src="/PC98Doukuusei.webp" alt="Mission montage" className="mission-image" />
+ <p className="mission-paragraph">
+ We deliver low‑latency streaming & infrastructure that turns live data into
+ reliable, secure insight. Target selection, monitoring and full end to end observability
+ to make vital decisions where it matters most.
+ </p>
+ </div>
+ ) : activePanel === 'makima' ? (
+ <div className="mission-screen makima-screen" role="region" aria-label="Makima">
+ <h1 className="mission-headline makima-headline">Mesh Orchestration Platform</h1>
+ <span className="makima-badge">Control System</span>
+ <img src="/logo/makima-logo.svg" alt="Makima mesh logo" className="mission-image makima-logo" />
+ <p className="mission-paragraph">
+ Makima is a control system for orchestrating distributed daemon meshes,
+ coordinating concurrent execution across distinct domains.
+ </p>
+ <p className="mission-paragraph">
+ Unified command interface for spawning, monitoring, and directing
+ worker daemons. Real-time task coordination with overlay management.
+ </p>
+ </div>
+ ) : (
+ <div className="hero" />
+ )}
+
+ {/* CTA row spanning full width: left Mission/MAKIMA, right Login */}
+ <div className="cta-area">
+ <div className="cta-left">
+ <button className="taisho-cta" onClick={handleMission}>
+ <span className="cta-text">{activePanel === 'mission' ? 'Close' : 'Mission'}</span>
+ </button>
+ <button className="taisho-cta" onClick={handleMakimaPanel}>
+ <span className="cta-text">{activePanel === 'makima' ? 'Close' : 'MAKIMA'}</span>
+ </button>
+ </div>
+ <div className="cta-right">
+ <button className="taisho-cta" onClick={handleLogin}>
+ <span className="cta-icon">▶</span>
+ <span className="cta-text">Login</span>
+ </button>
+ </div>
</div>
</div>
+ </div>
- <div className="pro-card" id="pro-makima">
- <div className="pro-card-header">
- <h2 className="pro-card-title">Makima</h2>
- <span className="pro-card-badge">Control System</span>
- <div className="pro-card-accent" />
- </div>
- <div className="pro-card-body">
- <img
- src="/logo/makima-logo.svg"
- alt="Makima mesh logo"
- className="pro-makima-logo"
- />
- <h3 className="pro-card-subtitle">Mesh Orchestration Platform</h3>
- <p className="pro-card-text">
- Makima is a control system for orchestrating distributed daemon meshes,
- coordinating concurrent execution across distinct domains.
- </p>
- <p className="pro-card-text">
- Unified command interface for spawning, monitoring, and directing
- worker daemons. Real-time task coordination with overlay management.
- </p>
+ {/* Bottom stats: Velocity + Energy only (hidden in mission mode) */}
+ {!activePanel && (
+ <div className="bottom-stats">
+ <div className="rf-stats">
+ <div className="rf-stat">
+ <span className="label">Velocity</span>
+ <span className="value">{Math.round(velocity)} km/h</span>
+ </div>
+ <div className="rf-stat">
+ <span className="label">Energy</span>
+ <span className="value">{energy.toFixed(1)} MJ</span>
+ </div>
</div>
</div>
- </section>
-
- {/* Footer */}
- <footer className="pro-footer">
- <div className="pro-footer-inner">
- <span className="pro-footer-brand">SORYU</span>
- <span className="pro-footer-sep">—</span>
- <span className="pro-footer-text">Real‑time systems &amp; infrastructure</span>
- </div>
- </footer>
+ )}
</div>
+ {/* MissionDrawer removed in favor of mission screen transformation */}
</div>
)
}
diff --git a/frontend/src/components/VNInterface.tsx b/frontend/src/components/VNInterface.tsx
index 0a77f39..318a9b9 100644
--- a/frontend/src/components/VNInterface.tsx
+++ b/frontend/src/components/VNInterface.tsx
@@ -9,11 +9,9 @@ import {
showSettingsModalStore,
isVisibleStore,
yenBalanceStore,
- documentEditorEnabledStore,
toggleStandby,
toggleShowChoices,
- updateTime,
- setDocumentEditorEnabled
+ updateTime
} from '../stores'
interface VNInterfaceProps {
@@ -28,7 +26,6 @@ export function VNInterface({ onLogout }: VNInterfaceProps) {
const showSettingsModal = useStore(showSettingsModalStore)
const isVisible = useStore(isVisibleStore)
const yenBalance = useStore(yenBalanceStore)
- const documentEditorEnabled = useStore(documentEditorEnabledStore)
// Fade in effect on mount
useEffect(() => {
@@ -116,14 +113,6 @@ export function VNInterface({ onLogout }: VNInterfaceProps) {
<span className="info-value">Contracts</span>
</Link>
</div>
- {documentEditorEnabled && (
- <div className="status-item">
- <Link to="/directives" style={{ color: '#66ccff', textDecoration: 'none', display: 'flex', alignItems: 'center', gap: '4px' }}>
- <span className="info-label">Edit:</span>
- <span className="info-value">Directives</span>
- </Link>
- </div>
- )}
</div>
</div>
</div>
@@ -209,21 +198,6 @@ export function VNInterface({ onLogout }: VNInterfaceProps) {
</div>
</div>
<div className="settings-section">
- <h3>Feature Flags</h3>
- <div className="setting-item">
- <label>
- <input
- type="checkbox"
- checked={documentEditorEnabled}
- onChange={(e) => setDocumentEditorEnabled(e.target.checked)}
- /> Document Editor (Directives)
- </label>
- <div style={{ fontSize: '0.8em', opacity: 0.7, marginTop: '4px' }}>
- Enable the directive document editor interface
- </div>
- </div>
- </div>
- <div className="settings-section">
<h3>Audio</h3>
<div className="setting-item">
<label>Master Volume</label>
diff --git a/frontend/src/components/document/index.ts b/frontend/src/components/document/index.ts
deleted file mode 100644
index 906c1dc..0000000
--- a/frontend/src/components/document/index.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export { default as DocumentLayout } from './DocumentLayout'
-export { default as DocumentEditor } from './DocumentEditor'
-export { DirectiveFileTree } from './DirectiveFileTree'
-export { default as DocumentSettings } from './DocumentSettings'
-
-// Lexical Nodes
-export { StepsDiagramNode, $createStepsDiagramNode, $isStepsDiagramNode } from './nodes/StepsDiagramNode'
-export { ContractBlockNode, $createContractBlockNode, $isContractBlockNode } from './nodes/ContractBlockNode'
-
-// Sub-components
-export { StepsDiagramComponent } from './nodes/StepsDiagramComponent'
-export { ContractBlockComponent } from './nodes/ContractBlockComponent'
-export { StepLogFeed } from './nodes/StepLogFeed'
-export { ContractLogFeed } from './nodes/ContractLogFeed'
diff --git a/frontend/src/components/document/nodes/StepLogFeed.tsx b/frontend/src/components/document/nodes/StepLogFeed.tsx
deleted file mode 100644
index 2f2f553..0000000
--- a/frontend/src/components/document/nodes/StepLogFeed.tsx
+++ /dev/null
@@ -1,277 +0,0 @@
-import React, { useEffect, useRef, useState, useCallback } from 'react';
-
-interface StepLogFeedProps {
- taskId: string;
- stepName: string;
- stepStatus: string;
- onCollapse: () => void;
-}
-
-interface LogEntry {
- timestamp: string;
- content: string;
- type: 'stdout' | 'stderr' | 'system' | 'user';
-}
-
-/**
- * Live log feed for an expanded step row.
- * Connects via WebSocket to stream task output and allows
- * sending messages (comments) and interrupting the task.
- */
-export function StepLogFeed({ taskId, stepName, stepStatus, onCollapse }: StepLogFeedProps) {
- const [logs, setLogs] = useState<LogEntry[]>([]);
- const [message, setMessage] = useState('');
- const [sending, setSending] = useState(false);
- const [connected, setConnected] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const logsEndRef = useRef<HTMLDivElement>(null);
- const wsRef = useRef<WebSocket | null>(null);
- const logContainerRef = useRef<HTMLDivElement>(null);
- const inputRef = useRef<HTMLInputElement>(null);
-
- const isActive = ['running', 'starting'].includes(stepStatus.toLowerCase());
-
- // Auto-scroll to bottom when new logs arrive
- useEffect(() => {
- logsEndRef.current?.scrollIntoView({ behavior: 'smooth' });
- }, [logs]);
-
- // Connect to WebSocket for live streaming
- useEffect(() => {
- if (!taskId) return;
-
- const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
- const wsUrl = `${protocol}//${window.location.host}/api/v1/mesh/tasks/subscribe`;
-
- let ws: WebSocket;
- let reconnectTimer: ReturnType<typeof setTimeout>;
- let shouldReconnect = true;
-
- function connect() {
- try {
- ws = new WebSocket(wsUrl);
- wsRef.current = ws;
-
- ws.addEventListener('open', () => {
- setConnected(true);
- setError(null);
- // Subscribe to this specific task
- ws.send(JSON.stringify({ type: 'subscribe', taskId }));
- });
-
- ws.addEventListener('message', (evt) => {
- try {
- const data = JSON.parse(evt.data);
- // Handle different message formats from the backend
- if (data.taskId === taskId || data.task_id === taskId) {
- const entry: LogEntry = {
- timestamp: data.timestamp || new Date().toISOString(),
- content: data.content || data.output || data.message || JSON.stringify(data),
- type: data.type || data.stream || 'stdout',
- };
- setLogs(prev => [...prev, entry]);
- }
- } catch {
- // Non-JSON message, treat as raw log
- setLogs(prev => [...prev, {
- timestamp: new Date().toISOString(),
- content: evt.data,
- type: 'stdout',
- }]);
- }
- });
-
- ws.addEventListener('close', () => {
- setConnected(false);
- wsRef.current = null;
- if (shouldReconnect && isActive) {
- reconnectTimer = setTimeout(connect, 3000);
- }
- });
-
- ws.addEventListener('error', () => {
- setConnected(false);
- setError('WebSocket connection failed');
- });
- } catch (err) {
- setError('Failed to connect to log stream');
- }
- }
-
- connect();
-
- return () => {
- shouldReconnect = false;
- clearTimeout(reconnectTimer);
- if (wsRef.current) {
- wsRef.current.close();
- wsRef.current = null;
- }
- };
- }, [taskId, isActive]);
-
- // Keyboard shortcut: Escape to collapse
- useEffect(() => {
- const handler = (e: KeyboardEvent) => {
- if (e.key === 'Escape') {
- onCollapse();
- }
- };
- document.addEventListener('keydown', handler);
- return () => document.removeEventListener('keydown', handler);
- }, [onCollapse]);
-
- // Send a message/comment to the task
- const handleSendMessage = useCallback(async () => {
- if (!message.trim() || !taskId || sending) return;
-
- setSending(true);
- try {
- const response = await fetch(`/api/v1/mesh/tasks/${taskId}/message`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ message: message.trim() }),
- });
-
- if (!response.ok) {
- const body = await response.json().catch(() => ({ message: response.statusText }));
- throw new Error(body.message || body.error || `HTTP ${response.status}`);
- }
-
- // Add as a user message in the log
- setLogs(prev => [...prev, {
- timestamp: new Date().toISOString(),
- content: message.trim(),
- type: 'user',
- }]);
- setMessage('');
- inputRef.current?.focus();
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to send message');
- } finally {
- setSending(false);
- }
- }, [message, taskId, sending]);
-
- const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- handleSendMessage();
- }
- // Prevent Escape from bubbling when input is focused
- if (e.key === 'Escape') {
- e.stopPropagation();
- inputRef.current?.blur();
- }
- }, [handleSendMessage]);
-
- // Interrupt the running task
- const handleInterrupt = useCallback(async () => {
- if (!taskId) return;
- try {
- // Send a special interrupt message
- const response = await fetch(`/api/v1/mesh/tasks/${taskId}/message`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ message: '/interrupt' }),
- });
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}`);
- }
- setLogs(prev => [...prev, {
- timestamp: new Date().toISOString(),
- content: 'Interrupt signal sent',
- type: 'system',
- }]);
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to interrupt');
- }
- }, [taskId]);
-
- const formatTimestamp = (ts: string) => {
- try {
- return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
- } catch {
- return '';
- }
- };
-
- return (
- <div className="step-log-feed">
- {/* Header */}
- <div className="step-log-feed-header">
- <div className="step-log-feed-header-left">
- <span className="step-log-feed-title">{stepName} - Logs</span>
- <span className={`step-log-feed-status ${connected ? 'connected' : 'disconnected'}`}>
- {connected ? 'Live' : 'Disconnected'}
- </span>
- </div>
- <div className="step-log-feed-header-right">
- {isActive && (
- <button
- className="step-log-feed-interrupt-btn"
- onClick={handleInterrupt}
- title="Interrupt this contract"
- >
- &#x23F9; Interrupt
- </button>
- )}
- <button
- className="step-log-feed-collapse-btn"
- onClick={onCollapse}
- title="Collapse (Esc)"
- >
- &#x2715;
- </button>
- </div>
- </div>
-
- {/* Log content */}
- <div className="step-log-feed-content" ref={logContainerRef}>
- {logs.length === 0 && !error && (
- <div className="step-log-feed-empty">
- {isActive
- ? 'Waiting for log output...'
- : 'No logs available for this step.'}
- </div>
- )}
-
- {error && (
- <div className="step-log-feed-error">{error}</div>
- )}
-
- {logs.map((entry, idx) => (
- <div key={idx} className={`step-log-entry step-log-entry--${entry.type}`}>
- <span className="step-log-entry-time">{formatTimestamp(entry.timestamp)}</span>
- <span className="step-log-entry-content">{entry.content}</span>
- </div>
- ))}
- <div ref={logsEndRef} />
- </div>
-
- {/* Message input (comment/interrupt controls) */}
- {isActive && (
- <div className="step-log-feed-input">
- <input
- ref={inputRef}
- type="text"
- className="step-log-feed-input-field"
- placeholder="Send a message to this contract..."
- value={message}
- onChange={(e) => setMessage(e.target.value)}
- onKeyDown={handleKeyDown}
- disabled={sending}
- />
- <button
- className="step-log-feed-send-btn"
- onClick={handleSendMessage}
- disabled={!message.trim() || sending}
- title="Send message (Enter)"
- >
- {sending ? '...' : '&#x27A4;'}
- </button>
- </div>
- )}
- </div>
- );
-}
diff --git a/frontend/src/components/document/nodes/StepsDiagramComponent.tsx b/frontend/src/components/document/nodes/StepsDiagramComponent.tsx
deleted file mode 100644
index ac1cb83..0000000
--- a/frontend/src/components/document/nodes/StepsDiagramComponent.tsx
+++ /dev/null
@@ -1,239 +0,0 @@
-import React, { useEffect, useState, useRef, useCallback } from 'react';
-import { getDirective, DirectiveStep, DirectiveWithSteps } from '../../../services/directiveApi';
-import { StepLogFeed } from './StepLogFeed';
-import './StepsDiagram.css';
-
-interface StepsDiagramComponentProps {
- directiveId: string;
- onExpandContract?: (step: DirectiveStep) => void;
-}
-
-type StepStatus = 'pending' | 'ready' | 'running' | 'completed' | 'failed' | 'skipped';
-
-const STATUS_LABELS: Record<string, string> = {
- pending: 'Queued',
- ready: 'Ready',
- running: 'Executing',
- completed: 'Fulfilled',
- failed: 'Failed',
- skipped: 'Skipped',
-};
-
-function formatTime(dateStr: string): string {
- if (!dateStr) return '';
- const d = new Date(dateStr);
- return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
-}
-
-interface StepCardProps {
- step: DirectiveStep;
- isExpanded: boolean;
- onToggleExpand: () => void;
- onCollapse: () => void;
-}
-
-function StepCard({ step, isExpanded, onToggleExpand, onCollapse }: StepCardProps) {
- const status = (step.status || 'pending').toLowerCase() as StepStatus;
- const hasTask = !!step.taskId || !!step.contractId;
- const canExpand = hasTask && ['running', 'completed', 'failed'].includes(status);
-
- return (
- <div className={`steps-diagram-card steps-diagram-card--${status} ${isExpanded ? 'steps-diagram-card--expanded' : ''}`}>
- <div
- className={`steps-diagram-card-header ${canExpand ? 'steps-diagram-card-header--clickable' : ''}`}
- onClick={canExpand ? onToggleExpand : undefined}
- role={canExpand ? 'button' : undefined}
- tabIndex={canExpand ? 0 : undefined}
- onKeyDown={canExpand ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onToggleExpand(); } } : undefined}
- >
- <span className="steps-diagram-card-name">{step.name}</span>
- <div className="steps-diagram-card-header-right">
- <span className={`steps-diagram-status-badge steps-diagram-status-badge--${status}`}>
- {STATUS_LABELS[status] || status}
- </span>
- {canExpand && (
- <span className={`steps-diagram-expand-icon ${isExpanded ? 'expanded' : ''}`}>
- &#x25B6;
- </span>
- )}
- </div>
- </div>
- {step.description && !isExpanded && (
- <p className="steps-diagram-card-desc">{step.description}</p>
- )}
- <div className="steps-diagram-card-footer">
- <span className="steps-diagram-card-index">#{step.orderIndex}</span>
- {status === 'running' && (
- <span className="steps-diagram-card-progress">In progress...</span>
- )}
- {status === 'completed' && step.completedAt && (
- <span className="steps-diagram-card-time">
- Completed {formatTime(step.completedAt)}
- </span>
- )}
- </div>
-
- {/* Expandable log feed */}
- {isExpanded && hasTask && (
- <StepLogFeed
- taskId={step.taskId || step.contractId}
- stepName={step.name}
- stepStatus={status}
- onCollapse={onCollapse}
- />
- )}
- </div>
- );
-}
-
-export function StepsDiagramComponent({ directiveId, onExpandContract }: StepsDiagramComponentProps) {
- const [steps, setSteps] = useState<DirectiveStep[]>([]);
- const [directiveStatus, setDirectiveStatus] = useState<string>('');
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [expandedStepId, setExpandedStepId] = useState<string | null>(null);
- const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
- const prevStepCountRef = useRef(0);
-
- const fetchSteps = useCallback(async () => {
- try {
- const data: DirectiveWithSteps = await getDirective(directiveId);
- setSteps(data.steps || []);
- setDirectiveStatus(data.status || '');
- setError(null);
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load contracts');
- } finally {
- setLoading(false);
- }
- }, [directiveId]);
-
- useEffect(() => {
- fetchSteps();
- intervalRef.current = setInterval(fetchSteps, 5000);
- return () => {
- if (intervalRef.current) clearInterval(intervalRef.current);
- };
- }, [fetchSteps]);
-
- // Track when new steps appear for animation
- useEffect(() => {
- prevStepCountRef.current = steps.length;
- }, [steps.length]);
-
- // Keyboard shortcut: Escape to collapse expanded step
- useEffect(() => {
- const handler = (e: KeyboardEvent) => {
- if (e.key === 'Escape' && expandedStepId) {
- setExpandedStepId(null);
- }
- };
- document.addEventListener('keydown', handler);
- return () => document.removeEventListener('keydown', handler);
- }, [expandedStepId]);
-
- const toggleExpand = useCallback((stepId: string) => {
- setExpandedStepId(prev => prev === stepId ? null : stepId);
- }, []);
-
- const collapseExpanded = useCallback(() => {
- setExpandedStepId(null);
- }, []);
-
- const completedCount = steps.filter(s => s.status?.toLowerCase() === 'completed').length;
- const totalCount = steps.length;
- const isActive = ['active', 'running', 'planning'].includes(directiveStatus.toLowerCase());
- const isBuilding = isActive && steps.length === 0;
-
- // Group steps by orderIndex
- const groupedSteps: Map<number, DirectiveStep[]> = new Map();
- const sortedSteps = [...steps].sort((a, b) => a.orderIndex - b.orderIndex);
- for (const step of sortedSteps) {
- const idx = step.orderIndex;
- if (!groupedSteps.has(idx)) groupedSteps.set(idx, []);
- groupedSteps.get(idx)!.push(step);
- }
- const orderGroups = Array.from(groupedSteps.entries()).sort((a, b) => a[0] - b[0]);
-
- if (loading) {
- return (
- <div className="steps-diagram" contentEditable={false}>
- <div className="steps-diagram-header">
- <span className="steps-diagram-header-title">Contract Steps</span>
- <span className="steps-diagram-header-author">Authored by Makima</span>
- </div>
- <div className="steps-diagram-loading">
- <div className="steps-diagram-spinner" />
- <span>Loading contracts...</span>
- </div>
- </div>
- );
- }
-
- if (error) {
- return (
- <div className="steps-diagram" contentEditable={false}>
- <div className="steps-diagram-header">
- <span className="steps-diagram-header-title">Contract Steps</span>
- <span className="steps-diagram-header-author">Authored by Makima</span>
- </div>
- <div className="steps-diagram-error">Failed to load contracts: {error}</div>
- </div>
- );
- }
-
- return (
- <div className={`steps-diagram ${expandedStepId ? 'steps-diagram--has-expanded' : ''}`} contentEditable={false}>
- <div className="steps-diagram-header">
- <div className="steps-diagram-header-left">
- <span className="steps-diagram-header-title">Contract Steps</span>
- {totalCount > 0 && (
- <span className="steps-diagram-header-count">
- {completedCount}/{totalCount} fulfilled
- </span>
- )}
- </div>
- <span className="steps-diagram-header-author">Authored by Makima</span>
- </div>
-
- {isBuilding && (
- <div className="steps-diagram-planning">
- <div className="steps-diagram-planning-dots">
- <span /><span /><span />
- </div>
- <span>Makima is drafting contracts...</span>
- </div>
- )}
-
- {totalCount === 0 && !isBuilding && (
- <div className="steps-diagram-empty">No contract steps defined yet.</div>
- )}
-
- {totalCount > 0 && (
- <div className="steps-diagram-dag">
- {orderGroups.map(([orderIndex, groupSteps], groupIdx) => (
- <React.Fragment key={orderIndex}>
- {groupIdx > 0 && (
- <div className="steps-diagram-arrow">
- <div className="steps-diagram-arrow-line" />
- <div className="steps-diagram-arrow-head" />
- </div>
- )}
- <div className="steps-diagram-group">
- {groupSteps.map((step) => (
- <StepCard
- key={step.id}
- step={step}
- isExpanded={expandedStepId === step.id}
- onToggleExpand={() => toggleExpand(step.id)}
- onCollapse={collapseExpanded}
- />
- ))}
- </div>
- </React.Fragment>
- ))}
- </div>
- )}
- </div>
- );
-}