-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathWorkflowPanel.jsx
More file actions
411 lines (366 loc) · 15.7 KB
/
WorkflowPanel.jsx
File metadata and controls
411 lines (366 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { websocket } from '../services/websocket';
import { boostAPI, workflowAPI } from '../services/api';
import './WorkflowPanel.css';
const AUTO_OPEN_DELAY_SECONDS = 600;
const formatNumber = (n) => n.toLocaleString();
const formatTime = (totalSeconds) => {
const h = Math.floor(totalSeconds / 3600);
const m = Math.floor((totalSeconds % 3600) / 60);
const s = Math.floor(totalSeconds % 60);
return `${String(h).padStart(2, '0')}h ${String(m).padStart(2, '0')}m ${String(s).padStart(2, '0')}s`;
};
export default function WorkflowPanel({ isRunning }) {
const [collapsed, setCollapsed] = useState(true);
const [mode, setMode] = useState('idle');
// Boost controls state
const [boostNextCount, setBoostNextCount] = useState(0);
const [boostNextInput, setBoostNextInput] = useState('');
const [isEditingBoostNext, setIsEditingBoostNext] = useState(false);
const [boostedCategories, setBoostedCategories] = useState([]);
const [availableCategories, setAvailableCategories] = useState([]);
const [boostEnabled, setBoostEnabled] = useState(false);
const [boostAlwaysPrefer, setBoostAlwaysPrefer] = useState(false);
// Token tracking & timer state
const [tokenStats, setTokenStats] = useState({ total_input: 0, total_output: 0, by_model: {}, elapsed_seconds: 0 });
const [showPerModel, setShowPerModel] = useState(false);
const [localElapsed, setLocalElapsed] = useState(0);
const lastSyncRef = useRef(Date.now());
const hasElapsedSyncRef = useRef(false);
const lastAutoOpenedHourRef = useRef(0);
// Auto-open: pop open exactly once, 10 minutes after user presses Start.
// No persistence. Resets every time isRunning goes true.
const hasPoppedThisSession = useRef(false);
const expandPanel = useCallback(() => {
setCollapsed(false);
localStorage.setItem('workflow_panel_collapsed', 'false');
}, []);
useEffect(() => {
if (isRunning) {
hasPoppedThisSession.current = false;
}
}, [isRunning]);
useEffect(() => {
if (!isRunning || hasPoppedThisSession.current) return;
if (localElapsed >= AUTO_OPEN_DELAY_SECONDS) {
expandPanel();
hasPoppedThisSession.current = true;
}
}, [isRunning, localElapsed, expandPanel]);
// Fetch boost status and categories
const fetchBoostStatus = useCallback(async () => {
try {
const statusResponse = await boostAPI.getStatus();
if (statusResponse.success && statusResponse.status) {
setBoostEnabled(statusResponse.status.enabled);
setBoostNextCount(statusResponse.status.boost_next_count || 0);
setBoostedCategories(statusResponse.status.boosted_categories || []);
setBoostAlwaysPrefer(statusResponse.status.boost_always_prefer || false);
}
const categoriesResponse = await boostAPI.getCategories('all');
if (categoriesResponse.success) {
setAvailableCategories(categoriesResponse.categories || []);
}
} catch (error) {
console.debug('Failed to fetch boost status:', error);
}
}, []);
useEffect(() => {
fetchBoostStatus();
const interval = setInterval(fetchBoostStatus, 5000);
return () => clearInterval(interval);
}, [fetchBoostStatus]);
useEffect(() => {
if (!isEditingBoostNext) {
setBoostNextInput(boostNextCount > 0 ? boostNextCount.toString() : '');
}
}, [boostNextCount, isEditingBoostNext]);
// Handle setting boost next count
const handleSetBoostNextCount = async () => {
const count = parseInt(boostNextInput, 10);
if (isNaN(count) || count < 0) {
return;
}
try {
await boostAPI.setNextCount(count);
setBoostNextCount(count);
setBoostNextInput(count > 0 ? count.toString() : '');
setIsEditingBoostNext(false);
} catch (error) {
console.error('Failed to set boost count:', error);
}
};
// Handle always-prefer toggle
const handleAlwaysPreferToggle = async () => {
try {
const newValue = !boostAlwaysPrefer;
await boostAPI.setAlwaysPrefer(newValue);
setBoostAlwaysPrefer(newValue);
} catch (error) {
console.error('Failed to toggle always-prefer boost:', error);
}
};
// Handle category toggle
const handleCategoryToggle = async (categoryId) => { try {
const response = await boostAPI.toggleCategory(categoryId);
if (response.success) {
setBoostedCategories(response.all_boosted_categories || []);
}
} catch (error) {
console.error('Failed to toggle category:', error);
}
};
// Token stats: initial fetch on mount and when isRunning changes
useEffect(() => {
hasElapsedSyncRef.current = false;
const fetchTokenStats = async () => {
try {
const resp = await workflowAPI.getTokenStats();
if (resp.success) {
hasElapsedSyncRef.current = true;
setTokenStats(resp);
setLocalElapsed(resp.elapsed_seconds || 0);
lastSyncRef.current = Date.now();
}
} catch { /* ignore */ }
};
fetchTokenStats();
}, [isRunning]);
// Token stats: listen for real-time WebSocket updates
useEffect(() => {
const handleTokenUpdate = (data) => {
hasElapsedSyncRef.current = true;
setTokenStats(data);
setLocalElapsed(data.elapsed_seconds || 0);
lastSyncRef.current = Date.now();
};
websocket.on('token_usage_updated', handleTokenUpdate);
return () => websocket.off('token_usage_updated', handleTokenUpdate);
}, []);
// Local 1-second timer tick for smooth elapsed display
useEffect(() => {
if (!isRunning) return;
const interval = setInterval(() => {
setLocalElapsed(prev => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, [isRunning]);
// Fetch current workflow mode when running
useEffect(() => {
if (!isRunning) {
setMode('idle');
return;
}
const fetchMode = async () => {
try {
const response = await workflowAPI.getPredictions();
if (response.success) {
setMode(response.mode || 'idle');
}
} catch (error) {
console.debug('Failed to fetch workflow mode:', error);
}
};
fetchMode();
const interval = setInterval(fetchMode, 5000);
return () => clearInterval(interval);
}, [isRunning]);
useEffect(() => {
if (!isRunning) {
return;
}
const handleBoostNextCountUpdated = (data) => {
setBoostNextCount(data.count || 0);
};
const handleCategoryBoostToggled = (data) => {
setBoostedCategories(data.all_categories || []);
};
const handleBoostEnabled = () => {
setBoostEnabled(true);
fetchBoostStatus();
};
const handleBoostDisabled = () => {
setBoostEnabled(false);
setBoostNextCount(0);
setBoostedCategories([]);
setBoostAlwaysPrefer(false);
};
const handleAlwaysPreferUpdated = (data) => {
setBoostAlwaysPrefer(data.enabled || false);
};
websocket.on('boost_next_count_updated', handleBoostNextCountUpdated);
websocket.on('category_boost_toggled', handleCategoryBoostToggled);
websocket.on('boost_enabled', handleBoostEnabled);
websocket.on('boost_disabled', handleBoostDisabled);
websocket.on('boost_always_prefer_updated', handleAlwaysPreferUpdated);
return () => {
websocket.off('boost_next_count_updated', handleBoostNextCountUpdated);
websocket.off('category_boost_toggled', handleCategoryBoostToggled);
websocket.off('boost_enabled', handleBoostEnabled);
websocket.off('boost_disabled', handleBoostDisabled);
websocket.off('boost_always_prefer_updated', handleAlwaysPreferUpdated);
};
}, [isRunning, fetchBoostStatus]);
const toggleCollapse = () => {
setCollapsed(prev => {
const next = !prev;
localStorage.setItem('workflow_panel_collapsed', next.toString());
return next;
});
};
// REMOVED: Conditional rendering that hid panel when no workflow running
// WorkflowPanel is now ETERNAL - always visible for boost controls
// User can access boost configuration at any time, not just during active research
return (
<div className={`workflow-panel ${collapsed ? 'collapsed' : ''}`}>
<div className="workflow-header">
<h3>MOTO Workflow</h3>
<button onClick={toggleCollapse} className="collapse-btn">
{collapsed ? '◀' : '▶'}
</button>
</div>
{!collapsed && (
<>
<div className="workflow-mode">
Mode: <span className="wf-mode-badge">{mode}</span>
</div>
{/* BOOST CONTROLS - ETERNAL (always visible, even when boost not enabled) */}
<div className="boost-controls">
{!boostEnabled && (
<div className="boost-disabled-notice">
Boost not enabled - Enable in API Boost button above. This is a great way to use your free, daily OpenRouter credits.
</div>
)}
<div className={`boost-section ${boostedCategories.length > 0 || boostAlwaysPrefer ? 'boost-mode-inactive' : ''}`}>
<label className="boost-label">Boost Next # of Tasks:</label>
<div className="boost-next-row">
<input
type="number"
min="0"
value={boostNextInput}
onChange={(e) => setBoostNextInput(e.target.value)}
onFocus={() => setIsEditingBoostNext(true)}
onBlur={() => setIsEditingBoostNext(false)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleSetBoostNextCount();
}
}}
placeholder="0"
className="boost-next-input"
disabled={!boostEnabled || boostedCategories.length > 0 || boostAlwaysPrefer}
title={boostedCategories.length > 0 ? 'Disable category boost first' : boostAlwaysPrefer ? 'Disable "always prefer" first' : 'Replace the remaining boosted-call count immediately'}
/>
<button
onClick={handleSetBoostNextCount}
className="boost-apply-btn"
disabled={!boostEnabled || boostNextInput.trim() === '' || boostedCategories.length > 0 || boostAlwaysPrefer}
title={boostedCategories.length > 0 ? 'Disable category boost first' : boostAlwaysPrefer ? 'Disable "always prefer" first' : 'Apply a new remaining count immediately'}
>
Apply
</button>
{boostNextCount > 0 && (
<span className="boost-count-badge">{boostNextCount} left</span>
)}
</div>
</div>
<div className={`boost-section boost-always-prefer-row ${boostNextCount > 0 || boostedCategories.length > 0 ? 'boost-mode-inactive' : ''}`}>
<label className="boost-always-prefer-label">
<input
type="checkbox"
checked={boostAlwaysPrefer}
onChange={handleAlwaysPreferToggle}
disabled={!boostEnabled || boostNextCount > 0 || boostedCategories.length > 0}
className="boost-always-prefer-checkbox"
/>
<span>Use boost as next API call when available</span>
</label>
{boostAlwaysPrefer && (
<div className="boost-always-prefer-hint">Boost attempted first every call — falls back on failure</div>
)}
</div>
{availableCategories.length > 0 && (
<>
<div className="boost-or-divider">— OR —</div>
<div className={`boost-section ${boostNextCount > 0 || boostAlwaysPrefer ? 'boost-mode-inactive' : ''}`}>
<label className="boost-label">Boost by Category:</label>
<div className="boost-categories">
{['Aggregator', 'Compiler', 'Autonomous', 'Proof Solver'].map(group => {
const groupCats = availableCategories.filter(cat => cat.group === group);
if (!groupCats.length) return null;
return (
<div key={group} className="boost-category-group">
<span className="boost-group-label">{group}</span>
<div className="boost-category-row">
{groupCats.map(cat => (
<button
key={cat.id}
className={`category-btn ${boostedCategories.includes(cat.id) ? 'active' : ''}`}
onClick={() => handleCategoryToggle(cat.id)}
disabled={!boostEnabled || boostNextCount > 0 || boostAlwaysPrefer}
title={boostNextCount > 0 ? 'Set Boost Next to 0 first' : boostAlwaysPrefer ? 'Disable "always prefer" first' : `Toggle boost for ${cat.label}`}
>
{cat.label}
</button>
))}
</div>
</div>
);
})}
</div>
</div>
</>
)}
</div>
{/* RESEARCH TIMER & TOKEN STATS */}
<div className="token-stats-section">
<div className="token-stats-heading">Token Usage</div>
<div className="research-timer">
<span className="timer-label">Elapsed</span>
<span className="timer-value">{formatTime(localElapsed)}</span>
</div>
<div className="token-totals">
<div className="token-row">
<span className="token-label">Input tokens</span>
<span className="token-value">{formatNumber(tokenStats.total_input)}</span>
</div>
<div className="token-row">
<span className="token-label">Output tokens</span>
<span className="token-value">{formatNumber(tokenStats.total_output)}</span>
</div>
<div className="token-row token-total-row">
<span className="token-label">Total tokens</span>
<span className="token-value">{formatNumber(tokenStats.total_input + tokenStats.total_output)}</span>
</div>
</div>
{Object.keys(tokenStats.by_model || {}).length > 0 && (
<div className="per-model-section">
<button
className="per-model-toggle"
onClick={() => setShowPerModel(prev => !prev)}
>
{showPerModel ? '▾' : '▸'} Per-model tokens ({Object.keys(tokenStats.by_model).length})
</button>
{showPerModel && (
<div className="per-model-list">
{Object.entries(tokenStats.by_model)
.sort((a, b) => (b[1].input + b[1].output) - (a[1].input + a[1].output))
.map(([modelId, usage]) => (
<div key={modelId} className="model-row">
<div className="model-name" title={modelId}>{modelId}</div>
<div className="model-tokens">
<span className="model-in">Input tokens: {formatNumber(usage.input)}</span>
<span className="model-out">Output tokens: {formatNumber(usage.output)}</span>
</div>
</div>
))}
</div>
)}
</div>
)}
</div>
</>
)}
</div>
);
}