forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTerminalPanel.tsx
More file actions
718 lines (661 loc) · 29.2 KB
/
Copy pathTerminalPanel.tsx
File metadata and controls
718 lines (661 loc) · 29.2 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
import React, { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Terminal, X, Filter, Trash2, Command, Square, Copy, Check, Sparkles } from 'lucide-react';
import { useAppStore, appStore } from '@/lib/store';
import { apiService, CommandExecutionResponse } from '@/services/api';
const POLL_INTERVAL_MS = 500;
const TERMINAL_HEIGHT_STORAGE_KEY = 'txio_terminal_height';
const DEFAULT_TERMINAL_HEIGHT = 256;
const MIN_TERMINAL_HEIGHT = 120;
const MAX_TERMINAL_HEIGHT_INSET = 120; // px of viewport to leave above the terminal
const getInitialTerminalHeight = (): number => {
if (typeof window === 'undefined') return DEFAULT_TERMINAL_HEIGHT;
const stored = window.localStorage.getItem(TERMINAL_HEIGHT_STORAGE_KEY);
if (!stored) return DEFAULT_TERMINAL_HEIGHT;
const parsed = Number.parseInt(stored, 10);
if (!Number.isFinite(parsed) || parsed < MIN_TERMINAL_HEIGHT) return DEFAULT_TERMINAL_HEIGHT;
const maxHeight = Math.max(
MIN_TERMINAL_HEIGHT,
window.innerHeight - MAX_TERMINAL_HEIGHT_INSET
);
return Math.min(parsed, maxHeight);
};
export const TerminalPanel: React.FC = () => {
const { activityLogs, isTerminalOpen } = useAppStore();
const [input, setInput] = useState('');
const [isExecuting, setIsExecuting] = useState(false);
const [pendingCommand, setPendingCommand] = useState<string | null>(null);
const [pendingExecutionId, setPendingExecutionId] = useState<string | null>(null);
const [isCancelling, setIsCancelling] = useState(false);
const [showErrorsOnly, setShowErrorsOnly] = useState(false);
const [terminalHeight, setTerminalHeight] = useState<number>(getInitialTerminalHeight);
const [isDragging, setIsDragging] = useState(false);
const [copiedLogId, setCopiedLogId] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const executionIdRef = useRef<string | null>(null);
const isMountedRef = useRef(true);
const dragStartRef = useRef<{ startY: number; startHeight: number } | null>(null);
const handleResizeStart = (e: React.PointerEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
dragStartRef.current = { startY: e.clientY, startHeight: terminalHeight };
setIsDragging(true);
e.currentTarget.setPointerCapture(e.pointerId);
};
const handleResizeMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!dragStartRef.current) return;
const delta = dragStartRef.current.startY - e.clientY;
const maxHeight = Math.max(MIN_TERMINAL_HEIGHT, window.innerHeight - MAX_TERMINAL_HEIGHT_INSET);
const next = Math.max(
MIN_TERMINAL_HEIGHT,
Math.min(dragStartRef.current.startHeight + delta, maxHeight),
);
setTerminalHeight(next);
};
const handleResizeEnd = (e: React.PointerEvent<HTMLDivElement>) => {
if (!dragStartRef.current) return;
dragStartRef.current = null;
setIsDragging(false);
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(e.pointerId);
}
try {
window.localStorage.setItem(TERMINAL_HEIGHT_STORAGE_KEY, String(terminalHeight));
} catch {
// ignore quota errors
}
};
const focusInput = () => {
if (!isExecuting) {
inputRef.current?.focus();
}
};
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [activityLogs, showErrorsOnly]);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
if (executionIdRef.current) {
void apiService
.cancelCommandExecution(
executionIdRef.current
)
.catch(() => undefined);
}
};
}, []);
const visibleLogs = (showErrorsOnly
? activityLogs.filter(
(log) => log.type === 'error'
)
: activityLogs
)
.slice()
// The store prepends new logs, but the terminal should still read top-to-bottom.
.reverse();
const clearLogs = () => {
appStore.clearActivityLogs();
appStore.showToast('Terminal cleared', 'info');
};
const copyToClipboard = async (text: string, logId?: string) => {
try {
await navigator.clipboard.writeText(text);
if (logId) {
setCopiedLogId(logId);
setTimeout(() => setCopiedLogId(null), 1500);
}
appStore.showToast('Copied to clipboard', 'success');
} catch {
appStore.showToast('Failed to copy', 'error');
}
};
const copyAllLogs = () => {
const text = visibleLogs
.map((log) => {
const ts = new Date(log.timestamp).toLocaleTimeString();
return `[${ts}] ${log.type} ${log.userName} → ${log.action}`;
})
.join('\n');
void copyToClipboard(text);
};
const sleep = (ms: number) =>
new Promise((resolve) => {
setTimeout(resolve, ms);
});
const resetExecutionState = () => {
executionIdRef.current = null;
if (isMountedRef.current) {
setPendingExecutionId(null);
setPendingCommand(null);
setIsExecuting(false);
setIsCancelling(false);
}
};
const firstMeaningfulOutput = (
...values: Array<
string | null | undefined
>
) => {
for (const value of values) {
if (
typeof value ===
'string' &&
value.trim()
) {
return value;
}
}
return null;
};
const pushExecutionResult = (
result: CommandExecutionResponse
) => {
const primaryOutput =
firstMeaningfulOutput(
result.output,
result.stderr,
result.stdout
) ||
(result.state ===
'cancelled'
? `Command cancelled: ${result.command}`
: result.state ===
'timed_out'
? `Command timed out: ${result.command}`
: result.state ===
'error'
? 'Command failed.'
: 'Command completed without output.');
const logType =
result.state === 'success' ||
result.state === 'cancelled'
? 'system'
: 'error';
const summaryBits: string[] = [];
if (
typeof result.durationMs ===
'number'
) {
summaryBits.push(
`${result.durationMs}ms`
);
}
if (
typeof result.exitCode ===
'number'
) {
summaryBits.push(
`exit ${result.exitCode}`
);
}
appStore.pushLog(
primaryOutput,
'cli',
logType
);
if (summaryBits.length > 0) {
appStore.pushLog(
`${result.state.replace('_', ' ')} · ${summaryBits.join(' · ')}`,
'cli',
logType
);
}
if (
result.state === 'success' &&
result.command
.toLowerCase()
.includes('deploy')
) {
appStore.showToast(
'Package deployed',
'success'
);
}
};
const pollExecution = async (
executionId: string
) => {
let failedPolls = 0;
while (
isMountedRef.current &&
executionIdRef.current ===
executionId
) {
try {
const result =
await apiService.getCommandExecution(
executionId
);
failedPolls = 0;
if (
result.state ===
'running'
) {
await sleep(
POLL_INTERVAL_MS
);
continue;
}
pushExecutionResult(
result
);
resetExecutionState();
return;
} catch (error) {
failedPolls += 1;
if (failedPolls >= 3) {
const message =
error instanceof Error &&
error.message.trim()
? error.message
: 'Unable to refresh command status.';
appStore.pushLog(
`Error: ${message}`,
'cli',
'error'
);
resetExecutionState();
return;
}
await sleep(
POLL_INTERVAL_MS
);
}
}
};
const executeCommand = async (
command: string
) => {
setIsExecuting(true);
setIsCancelling(false);
setPendingCommand(command);
appStore.pushLog(
`Running ${command}...`,
'cli',
'system'
);
try {
const started =
await apiService.startCommandExecution(
command
);
executionIdRef.current =
started.executionId;
setPendingExecutionId(
started.executionId
);
if (
started.state !== 'running'
) {
pushExecutionResult(
started
);
resetExecutionState();
return;
}
await pollExecution(
started.executionId
);
} catch (error) {
const message =
error instanceof Error &&
error.message.trim()
? error.message
: 'Command failed.';
const wasCancelled =
message ===
'Request cancelled.';
appStore.pushLog(
wasCancelled
? `Command cancelled: ${command}`
: `Error: ${message}`,
'cli',
wasCancelled
? 'system'
: 'error'
);
} finally {
if (
executionIdRef.current === null
) {
resetExecutionState();
}
}
};
const cancelExecution = async () => {
if (
!pendingExecutionId ||
isCancelling
) {
return;
}
setIsCancelling(true);
try {
await apiService.cancelCommandExecution(
pendingExecutionId
);
} catch (error) {
const message =
error instanceof Error &&
error.message.trim()
? error.message
: 'Unable to cancel the running command.';
appStore.pushLog(
`Error: ${message}`,
'cli',
'error'
);
setIsCancelling(false);
}
};
const handleCommand = (
e: React.FormEvent
) => {
e.preventDefault();
const trimmedInput =
input.trim();
if (
!trimmedInput ||
isExecuting
) {
return;
}
const normalizedCommand =
trimmedInput.toLowerCase();
appStore.pushLog(
`➜ ${trimmedInput}`,
'cli',
'system'
);
if (normalizedCommand === 'clear') {
clearLogs();
} else if (
normalizedCommand === 'help'
) {
appStore.pushLog(
'Available commands: help, clear, txio <args>, cargo <args>',
'cli',
'system'
);
appStore.pushLog(
"Only 'txio' and 'cargo' are forwarded to the backend terminal.",
'cli',
'system'
);
} else {
void executeCommand(
trimmedInput
);
}
setInput('');
};
return (
<AnimatePresence>
{isTerminalOpen && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: terminalHeight, opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={
isDragging
? { type: 'tween', duration: 0 }
: { type: 'spring', damping: 25, stiffness: 200 }
}
onClick={focusInput}
className="bg-slate-50 dark:bg-near-black border-t border-slate-200 dark:border-white/[0.06] flex flex-col font-mono text-xs shadow-2xl relative z-40 overflow-hidden text-left"
>
{/* Resize handle */}
<div
onPointerDown={handleResizeStart}
onPointerMove={handleResizeMove}
onPointerUp={handleResizeEnd}
onPointerCancel={handleResizeEnd}
onClick={(e) => e.stopPropagation()}
role="separator"
tabIndex={0}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') e.stopPropagation(); }}
aria-orientation="horizontal"
aria-label="Resize terminal"
className={`shrink-0 h-1.5 cursor-row-resize flex items-center justify-center group transition-colors ${
isDragging ? 'bg-electric-violet/40' : 'hover:bg-electric-violet/20'
}`}
>
<div
className={`h-0.5 rounded-full transition-all duration-200 ${
isDragging
? 'w-20 bg-electric-violet'
: 'w-10 bg-white/[0.08] group-hover:w-16 group-hover:bg-electric-violet/60'
}`}
/>
</div>
{/* Terminal Header */}
<div className="flex items-center justify-between px-3 py-1.5 border-b border-slate-200 dark:border-white/[0.06] bg-white dark:bg-dark-indigo-glow select-none">
<div className="flex items-center gap-2.5 font-sans">
<div className="flex items-center gap-1.5 text-slate-600 dark:text-slate-300">
<Terminal size={12} className="text-electric-violet" />
<span className="text-[11px] font-medium tracking-tight">Terminal</span>
</div>
<div className="h-3 w-px bg-white/[0.08]"></div>
<span className="text-[11px] text-slate-500 font-mono">bash</span>
<div className="h-3 w-px bg-white/[0.08]"></div>
<div className={`flex items-center gap-1.5 text-[11px] font-medium ${
isCancelling
? 'text-amber-300'
: isExecuting
? 'text-amber-400'
: 'text-emerald-400/80'
}`}>
<span className={`h-1.5 w-1.5 rounded-full ${
isCancelling
? 'bg-amber-300 animate-pulse'
: isExecuting
? 'bg-amber-400 animate-pulse'
: 'bg-emerald-400/70'
}`}></span>
<span>
{isCancelling
? 'stopping'
: isExecuting
? 'running'
: 'idle'}
</span>
</div>
</div>
<div className="flex items-center gap-1">
<button
onClick={(e) => {
e.stopPropagation();
copyAllLogs();
}}
className="p-1.5 rounded-md text-slate-500 hover:text-slate-200 hover:bg-white/[0.05] transition-colors"
title="Copy all output"
>
<Copy size={13} />
</button>
<button
onClick={(e) => {
e.stopPropagation();
setShowErrorsOnly((current) => !current);
}}
className={`p-1.5 rounded-md transition-colors ${
showErrorsOnly
? 'text-electric-violet bg-electric-violet/[0.08]'
: 'text-slate-500 hover:text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-white/[0.05]'
}`}
title={showErrorsOnly ? 'Show all logs' : 'Show only errors'}
>
<Filter size={13} />
</button>
<button
onClick={(e) => {
e.stopPropagation();
clearLogs();
}}
className="p-1.5 rounded-md text-slate-500 hover:text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-white/[0.05] transition-colors"
title="Clear console"
>
<Trash2 size={13} />
</button>
{isExecuting && (
<button
onClick={(e) => {
e.stopPropagation();
void cancelExecution();
}}
disabled={isCancelling}
className="p-1.5 rounded-md text-amber-400 hover:text-amber-300 hover:bg-amber-400/10 transition-colors"
title={`Cancel ${pendingCommand || 'command'}`}
>
<Square size={11} fill="currentColor" />
</button>
)}
<button
onClick={(e) => {
e.stopPropagation();
appStore.toggleTerminal();
}}
className="p-1.5 rounded-md text-slate-500 hover:text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-white/[0.05] transition-colors"
aria-label="Close terminal"
>
<X size={13} />
</button>
</div>
</div>
{/* Terminal Output */}
<div
ref={scrollRef}
className="flex-1 overflow-y-auto p-4 space-y-1.5 custom-scrollbar bg-slate-50 dark:bg-near-black"
>
{visibleLogs.map((log) => {
const isMultiline = log.action.includes('\n');
const typeBadge = (
<span className={`shrink-0 px-1.5 rounded-[2px] font-bold text-[9px] uppercase ${
log.type === 'request' ? 'text-emerald-400 bg-emerald-400/5' :
log.type === 'team' ? 'text-blue-400 bg-blue-400/5' :
log.type === 'error' ? 'text-red-400 bg-red-400/5' :
'text-soft-purple bg-soft-purple/5'
}`}>
{log.type}
</span>
);
const timestamp = (
<span className="text-slate-600 shrink-0">[{new Date(log.timestamp).toLocaleTimeString()}]</span>
);
if (isMultiline) {
return (
<motion.div
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
key={log.id}
className="flex flex-col gap-1 group"
>
<div className="flex items-center gap-3">
{timestamp}
{typeBadge}
<span className="text-slate-500 font-bold">{log.userName}</span>
{log.target && <span className="text-electric-violet/60 italic text-[10px]">({log.target})</span>}
<div className="ml-auto flex items-center gap-1 shrink-0">
{log.type === 'error' && (
<button
onClick={(e) => {
e.stopPropagation();
appStore.setPendingAiPrompt(`Explain this terminal error:\n\n${log.action}`);
appStore.openTab('ai_chat');
}}
className="p-1 rounded text-slate-600 hover:text-electric-violet opacity-0 group-hover:opacity-100 transition-opacity"
title="Ask AI to explain this error"
>
<Sparkles size={12} />
</button>
)}
<button
onClick={(e) => {
e.stopPropagation();
void copyToClipboard(log.action, log.id);
}}
className="opacity-0 group-hover:opacity-100 p-1 rounded text-slate-500 hover:text-slate-200 hover:bg-white/[0.05] transition-all"
title="Copy output"
>
{copiedLogId === log.id ? <Check size={11} className="text-emerald-400" /> : <Copy size={11} />}
</button>
</div>
</div>
<pre className="text-slate-800 dark:text-white/90 whitespace-pre-wrap break-words ml-4 border-l border-slate-200 dark:border-white/5 pl-3">
{log.action}
</pre>
</motion.div>
);
}
return (
<motion.div
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
key={log.id}
className="flex gap-3 group"
>
{timestamp}
{typeBadge}
<span className="text-slate-600 dark:text-slate-300 flex-1">
<span className="text-slate-500 font-bold">{log.userName}</span>
<span className="mx-2 text-slate-600">→</span>
<span className="text-slate-800 dark:text-white/90 whitespace-pre-wrap break-words">{log.action}</span>
{log.target && <span className="ml-2 text-electric-violet/60 italic">({log.target})</span>}
</span>
{log.type === 'error' && (
<button
onClick={(e) => {
e.stopPropagation();
appStore.setPendingAiPrompt(`Explain this terminal error:\n\n${log.action}`);
appStore.openTab('ai_chat');
}}
className="shrink-0 p-1 rounded text-slate-600 hover:text-electric-violet opacity-0 group-hover:opacity-100 transition-opacity"
title="Ask AI to explain this error"
>
<Sparkles size={12} />
</button>
)}
<button
onClick={(e) => {
e.stopPropagation();
void copyToClipboard(log.action, log.id);
}}
className="opacity-0 group-hover:opacity-100 p-1 rounded text-slate-500 hover:text-slate-200 hover:bg-white/[0.05] transition-all shrink-0"
title="Copy output"
>
{copiedLogId === log.id ? <Check size={11} className="text-emerald-400" /> : <Copy size={11} />}
</button>
</motion.div>
);
})}
{/* Prompt */}
<div className="flex items-center gap-2 pt-2">
<span className="text-electric-violet font-bold">➜</span>
<span className="text-soft-purple font-bold">~</span>
<form onSubmit={handleCommand} className="flex-1">
<input
ref={inputRef}
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
disabled={isExecuting}
className="w-full bg-transparent border-none outline-none text-slate-900 dark:text-white caret-electric-violet"
autoFocus
placeholder={isExecuting && pendingCommand
? `${isCancelling ? 'Stopping' : 'Running'} ${pendingCommand}...`
: "Type 'help' for available commands..."}
/>
</form>
</div>
</div>
{/* Subtle bottom glow */}
<div className="absolute bottom-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-electric-violet/30 to-transparent"></div>
</motion.div>
)}
</AnimatePresence>
);
};