-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevboxActionsMenu.tsx
More file actions
1596 lines (1505 loc) · 50.1 KB
/
Copy pathDevboxActionsMenu.tsx
File metadata and controls
1596 lines (1505 loc) · 50.1 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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React from "react";
import { Box, Text, useInput } from "ink";
import TextInput from "ink-text-input";
import figures from "figures";
import { Header } from "./Header.js";
import { SpinnerComponent } from "./Spinner.js";
import { ErrorMessage } from "./ErrorMessage.js";
import { SuccessMessage } from "./SuccessMessage.js";
import { Breadcrumb } from "./Breadcrumb.js";
import { NavigationTips } from "./NavigationTips.js";
import { ConfirmationPrompt } from "./ConfirmationPrompt.js";
import { colors } from "../utils/theme.js";
import { useViewportHeight } from "../hooks/useViewportHeight.js";
import { useNavigation } from "../store/navigationStore.js";
import { useExitOnCtrlC } from "../hooks/useExitOnCtrlC.js";
import {
suspendDevbox,
resumeDevbox,
shutdownDevbox,
uploadFile,
createSnapshot as createDevboxSnapshot,
createTunnel,
createSSHKey,
} from "../services/devboxService.js";
import { StreamingLogsViewer } from "./StreamingLogsViewer.js";
import { DevboxView } from "@runloop/api-client/resources/devboxes.mjs";
type Operation =
| "exec"
| "upload"
| "snapshot"
| "ssh"
| "logs"
| "tunnel"
| "suspend"
| "resume"
| "delete"
| null;
interface DevboxActionsMenuProps {
devbox: DevboxView;
onBack: () => void;
breadcrumbItems?: Array<{ label: string; active?: boolean }>;
initialOperation?: string; // Operation to execute immediately
initialOperationIndex?: number; // Index of the operation to select
skipOperationsMenu?: boolean; // Skip showing operations menu and execute immediately
}
export const DevboxActionsMenu = ({
devbox,
onBack,
breadcrumbItems = [
{ label: "Devboxes" },
{ label: devbox.name || devbox.id, active: true },
],
initialOperation,
initialOperationIndex = 0,
skipOperationsMenu = false,
}: DevboxActionsMenuProps) => {
const { navigate, currentScreen, params } = useNavigation();
const [loading, setLoading] = React.useState(false);
const [selectedOperation, setSelectedOperation] = React.useState(
initialOperationIndex,
);
const [executingOperation, setExecutingOperation] = React.useState<Operation>(
(initialOperation as Operation) || null,
);
const [operationInput, setOperationInput] = React.useState("");
const [operationResult, setOperationResult] = React.useState<string | null>(
null,
);
const [operationError, setOperationError] = React.useState<Error | null>(
null,
);
const [execScroll, setExecScroll] = React.useState(0);
const [copyStatus, setCopyStatus] = React.useState<string | null>(null);
const [showDeleteConfirm, setShowDeleteConfirm] = React.useState(false);
// Snapshot form state
const [snapshotFormMode, setSnapshotFormMode] = React.useState(false);
const [snapshotName, setSnapshotName] = React.useState("");
const [snapshotCommitMessage, setSnapshotCommitMessage] = React.useState("");
const [snapshotMetadata, setSnapshotMetadata] = React.useState<
Record<string, string>
>({});
const [snapshotFormField, setSnapshotFormField] = React.useState<
"name" | "commit_message" | "metadata" | "create"
>("name");
const [inSnapshotMetadataSection, setInSnapshotMetadataSection] =
React.useState(false);
const [snapshotMetadataKey, setSnapshotMetadataKey] = React.useState("");
const [snapshotMetadataValue, setSnapshotMetadataValue] = React.useState("");
const [snapshotMetadataInputMode, setSnapshotMetadataInputMode] =
React.useState<"key" | "value" | null>(null);
const [selectedSnapshotMetadataIndex, setSelectedSnapshotMetadataIndex] =
React.useState(0);
// Calculate viewport for exec output:
// - Breadcrumb (3 lines + marginBottom): 4 lines
// - Command header (border + 2 content + border + marginBottom): 5 lines
// - Output box borders: 2 lines
// - Stats bar (marginTop + content): 2 lines
// - Help bar (marginTop + content): 2 lines
// - Safety buffer: 1 line
// Total: 16 lines
const execViewport = useViewportHeight({ overhead: 16, minHeight: 10 });
// CRITICAL: Aggressive memory cleanup to prevent heap exhaustion
React.useEffect(() => {
// Clear large data immediately when results are shown to free memory faster
if (operationResult || operationError) {
const timer = setTimeout(() => {
// After 100ms, if user hasn't acted, start aggressive cleanup
// This helps with memory without disrupting UX
}, 100);
return () => clearTimeout(timer);
}
}, [operationResult, operationError]);
// Cleanup on unmount
React.useEffect(() => {
return () => {
// Aggressively null out all large data structures
setOperationResult(null);
setOperationError(null);
setOperationInput("");
setLoading(false);
};
}, []);
const allOperations = [
{
key: "logs",
label: "View Logs",
color: colors.info,
icon: figures.info,
shortcut: "l",
},
{
key: "exec",
label: "Execute Command",
color: colors.success,
icon: figures.play,
shortcut: "e",
},
{
key: "upload",
label: "Upload File",
color: colors.success,
icon: figures.arrowUp,
shortcut: "u",
},
{
key: "snapshot",
label: "Create Snapshot",
color: colors.warning,
icon: figures.circleFilled,
shortcut: "n",
},
{
key: "ssh",
label: "SSH onto the box",
color: colors.primary,
icon: figures.arrowRight,
shortcut: "s",
},
{
key: "tunnel",
label: "Open Tunnel",
color: colors.secondary,
icon: figures.pointerSmall,
shortcut: "t",
},
{
key: "suspend",
label: "Suspend Devbox",
color: colors.warning,
icon: figures.squareSmallFilled,
shortcut: "p",
},
{
key: "resume",
label: "Resume Devbox",
color: colors.success,
icon: figures.play,
shortcut: "r",
},
{
key: "delete",
label: "Shutdown Devbox",
color: colors.error,
icon: figures.cross,
shortcut: "d",
},
];
// Filter operations based on devbox status
const hasTunnel = !!(devbox?.tunnel && devbox.tunnel.tunnel_key);
const operations = devbox
? allOperations
.filter((op) => {
const status = devbox.status;
// When suspended: logs and resume
if (status === "suspended") {
return op.key === "resume" || op.key === "logs";
}
// When not running (shutdown, failure, etc): only logs
if (
status !== "running" &&
status !== "provisioning" &&
status !== "initializing"
) {
return op.key === "logs";
}
// When running: everything except resume
if (status === "running") {
return op.key !== "resume";
}
// Default for transitional states (provisioning, initializing)
return op.key === "logs" || op.key === "delete";
})
.map((op) => {
// Dynamic tunnel label based on whether tunnel is active
if (op.key === "tunnel") {
return hasTunnel
? {
...op,
label: "Tunnel (Active)",
color: colors.success,
icon: figures.tick,
}
: op;
}
return op;
})
: allOperations;
// Auto-execute operations that don't need input (except delete which needs confirmation)
React.useEffect(() => {
const autoExecuteOps = ["ssh", "logs", "suspend", "resume"];
if (
executingOperation &&
autoExecuteOps.includes(executingOperation) &&
!loading &&
devbox
) {
executeOperation();
}
// Show confirmation for delete
if (
executingOperation === "delete" &&
!loading &&
devbox &&
!showDeleteConfirm
) {
setShowDeleteConfirm(true);
}
// Show snapshot form
if (
executingOperation === "snapshot" &&
!loading &&
devbox &&
!snapshotFormMode &&
!operationResult &&
!operationError
) {
setSnapshotFormMode(true);
setSnapshotFormField("name");
}
}, [executingOperation]);
// Handle Ctrl+C to exit
useExitOnCtrlC();
useInput((input, key) => {
// Handle snapshot metadata section input
if (snapshotFormMode && inSnapshotMetadataSection) {
const metadataKeys = Object.keys(snapshotMetadata);
const maxIndex = metadataKeys.length + 1;
// Handle input mode (typing key or value)
if (snapshotMetadataInputMode) {
if (
snapshotMetadataInputMode === "key" &&
key.return &&
snapshotMetadataKey.trim()
) {
setSnapshotMetadataInputMode("value");
return;
} else if (snapshotMetadataInputMode === "value" && key.return) {
if (snapshotMetadataKey.trim() && snapshotMetadataValue.trim()) {
setSnapshotMetadata({
...snapshotMetadata,
[snapshotMetadataKey.trim()]: snapshotMetadataValue.trim(),
});
}
setSnapshotMetadataKey("");
setSnapshotMetadataValue("");
setSnapshotMetadataInputMode(null);
setSelectedSnapshotMetadataIndex(0);
return;
} else if (key.escape) {
setSnapshotMetadataKey("");
setSnapshotMetadataValue("");
setSnapshotMetadataInputMode(null);
return;
} else if (key.tab) {
setSnapshotMetadataInputMode(
snapshotMetadataInputMode === "key" ? "value" : "key",
);
return;
}
return;
}
// Navigation mode in metadata section
if (key.upArrow && selectedSnapshotMetadataIndex > 0) {
setSelectedSnapshotMetadataIndex(selectedSnapshotMetadataIndex - 1);
} else if (key.downArrow && selectedSnapshotMetadataIndex < maxIndex) {
setSelectedSnapshotMetadataIndex(selectedSnapshotMetadataIndex + 1);
} else if (key.return) {
if (selectedSnapshotMetadataIndex === 0) {
setSnapshotMetadataKey("");
setSnapshotMetadataValue("");
setSnapshotMetadataInputMode("key");
} else if (selectedSnapshotMetadataIndex === maxIndex) {
setInSnapshotMetadataSection(false);
setSelectedSnapshotMetadataIndex(0);
setSnapshotMetadataKey("");
setSnapshotMetadataValue("");
setSnapshotMetadataInputMode(null);
} else if (
selectedSnapshotMetadataIndex >= 1 &&
selectedSnapshotMetadataIndex <= metadataKeys.length
) {
const keyToEdit = metadataKeys[selectedSnapshotMetadataIndex - 1];
setSnapshotMetadataKey(keyToEdit || "");
setSnapshotMetadataValue(snapshotMetadata[keyToEdit] || "");
const newMetadata = { ...snapshotMetadata };
delete newMetadata[keyToEdit];
setSnapshotMetadata(newMetadata);
setSnapshotMetadataInputMode("key");
}
} else if (
(input === "d" || key.delete) &&
selectedSnapshotMetadataIndex >= 1 &&
selectedSnapshotMetadataIndex <= metadataKeys.length
) {
const keyToDelete = metadataKeys[selectedSnapshotMetadataIndex - 1];
const newMetadata = { ...snapshotMetadata };
delete newMetadata[keyToDelete];
setSnapshotMetadata(newMetadata);
const newLength = Object.keys(newMetadata).length;
if (selectedSnapshotMetadataIndex > newLength) {
setSelectedSnapshotMetadataIndex(Math.max(0, newLength));
}
} else if (key.escape || input === "q") {
setInSnapshotMetadataSection(false);
setSelectedSnapshotMetadataIndex(0);
setSnapshotMetadataKey("");
setSnapshotMetadataValue("");
setSnapshotMetadataInputMode(null);
}
return;
}
// Handle snapshot form mode (main form navigation)
if (snapshotFormMode && !inSnapshotMetadataSection) {
const snapshotFields = [
"name",
"commit_message",
"metadata",
"create",
] as const;
const currentFieldIndex = snapshotFields.indexOf(snapshotFormField);
if (input === "q" || key.escape) {
// Cancel snapshot form
setSnapshotFormMode(false);
setSnapshotName("");
setSnapshotCommitMessage("");
setSnapshotMetadata({});
setSnapshotFormField("name");
setExecutingOperation(null);
if (skipOperationsMenu) {
onBack();
}
return;
}
// Navigate between fields (only when not actively editing text fields)
if (
snapshotFormField !== "name" &&
snapshotFormField !== "commit_message"
) {
if (key.upArrow && currentFieldIndex > 0) {
setSnapshotFormField(snapshotFields[currentFieldIndex - 1]);
return;
}
if (key.downArrow && currentFieldIndex < snapshotFields.length - 1) {
setSnapshotFormField(snapshotFields[currentFieldIndex + 1]);
return;
}
}
// Handle Enter key
if (key.return) {
if (snapshotFormField === "name") {
// Move to commit_message field
setSnapshotFormField("commit_message");
} else if (snapshotFormField === "commit_message") {
// Move to metadata field
setSnapshotFormField("metadata");
} else if (snapshotFormField === "metadata") {
// Enter metadata section
setInSnapshotMetadataSection(true);
setSelectedSnapshotMetadataIndex(0);
} else if (snapshotFormField === "create") {
// Execute snapshot creation
executeOperation();
}
return;
}
// Tab navigation (when not in text input fields)
if (
key.tab &&
snapshotFormField !== "name" &&
snapshotFormField !== "commit_message"
) {
const nextIndex = key.shift
? Math.max(0, currentFieldIndex - 1)
: Math.min(snapshotFields.length - 1, currentFieldIndex + 1);
setSnapshotFormField(snapshotFields[nextIndex]);
return;
}
return;
}
// Handle operation input mode (for exec, upload, tunnel)
if (
executingOperation &&
!operationResult &&
!operationError &&
!snapshotFormMode
) {
if (key.return && operationInput.trim()) {
// For exec, navigate to dedicated exec screen
if (executingOperation === "exec") {
navigate("devbox-exec", {
devboxId: devbox.id,
devboxName: devbox.name || devbox.id,
execCommand: operationInput,
});
} else {
executeOperation();
}
} else if (input === "q" || key.escape) {
setExecutingOperation(null);
setOperationInput("");
}
return;
}
// Handle operation result display
if (operationResult || operationError) {
if (input === "q" || key.escape || key.return) {
// Clear large data structures immediately to prevent memory leaks
setOperationResult(null);
setOperationError(null);
setOperationInput("");
setExecScroll(0);
setCopyStatus(null);
// If skipOperationsMenu is true, go back to parent instead of operations menu
if (skipOperationsMenu) {
setExecutingOperation(null);
onBack();
} else {
setExecutingOperation(null);
}
} else if (
input === "o" &&
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "tunnel"
) {
// Open tunnel URL in browser
const tunnelUrl = (operationResult as any).__tunnelUrl;
if (tunnelUrl) {
const openBrowser = async () => {
const { exec } = await import("child_process");
const platform = process.platform;
let openCommand: string;
if (platform === "darwin") {
openCommand = `open "${tunnelUrl}"`;
} else if (platform === "win32") {
openCommand = `start "${tunnelUrl}"`;
} else {
openCommand = `xdg-open "${tunnelUrl}"`;
}
exec(openCommand, (error) => {
if (error) {
setCopyStatus("Could not open browser");
setTimeout(() => setCopyStatus(null), 2000);
} else {
setCopyStatus("Opened in browser!");
setTimeout(() => setCopyStatus(null), 2000);
}
});
};
openBrowser();
}
} else if (
(key.upArrow || input === "k") &&
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "exec"
) {
setExecScroll(Math.max(0, execScroll - 1));
} else if (
(key.downArrow || input === "j") &&
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "exec"
) {
setExecScroll(execScroll + 1);
} else if (
key.pageUp &&
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "exec"
) {
setExecScroll(Math.max(0, execScroll - 10));
} else if (
key.pageDown &&
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "exec"
) {
setExecScroll(execScroll + 10);
} else if (
input === "g" &&
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "exec"
) {
setExecScroll(0);
} else if (
input === "G" &&
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "exec"
) {
const lines = [
...((operationResult as any).stdout || "").split("\n"),
...((operationResult as any).stderr || "").split("\n"),
];
const maxScroll = Math.max(
0,
lines.length - execViewport.viewportHeight,
);
setExecScroll(maxScroll);
} else if (
input === "c" &&
!key.ctrl && // Ignore if Ctrl+C for quit
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "exec"
) {
// Copy exec output to clipboard
const output =
((operationResult as any).stdout || "") +
((operationResult as any).stderr || "");
const copyToClipboard = async (text: string) => {
const { spawn } = await import("child_process");
const platform = process.platform;
let command: string;
let args: string[];
if (platform === "darwin") {
command = "pbcopy";
args = [];
} else if (platform === "win32") {
command = "clip";
args = [];
} else {
command = "xclip";
args = ["-selection", "clipboard"];
}
const proc = spawn(command, args);
proc.stdin.write(text);
proc.stdin.end();
proc.on("exit", (code) => {
if (code === 0) {
setCopyStatus("Copied to clipboard!");
setTimeout(() => setCopyStatus(null), 2000);
} else {
setCopyStatus("Failed to copy");
setTimeout(() => setCopyStatus(null), 2000);
}
});
proc.on("error", () => {
setCopyStatus("Copy not supported");
setTimeout(() => setCopyStatus(null), 2000);
});
};
copyToClipboard(output);
}
return;
}
// Operations selection mode
if (input === "q" || key.escape) {
// Clear all state before going back to free memory
setOperationResult(null);
setOperationError(null);
setOperationInput("");
setExecutingOperation(null);
setSelectedOperation(0);
setLoading(false);
onBack();
} else if (key.upArrow && selectedOperation > 0) {
setSelectedOperation(selectedOperation - 1);
} else if (key.downArrow && selectedOperation < operations.length - 1) {
setSelectedOperation(selectedOperation + 1);
} else if (key.return) {
const op = operations[selectedOperation].key as Operation;
setExecutingOperation(op);
} else if (input) {
// Check if input matches any operation shortcut
const matchedOp = operations.find((op) => op.shortcut === input);
if (matchedOp) {
setExecutingOperation(matchedOp.key as Operation);
}
}
});
const executeOperation = async () => {
try {
setLoading(true);
switch (executingOperation) {
// Note: "exec" is now handled by ExecViewer component directly
case "upload":
// Use service layer
const filename = operationInput.split("/").pop() || "file";
await uploadFile(devbox.id, operationInput, filename);
setOperationResult(`File ${filename} uploaded successfully`);
break;
case "snapshot":
// Use service layer with form data
const snapshotOptions: {
name?: string;
metadata?: Record<string, string>;
commit_message?: string;
} = {};
if (snapshotName.trim()) {
snapshotOptions.name = snapshotName.trim();
} else {
snapshotOptions.name = `snapshot-${Date.now()}`;
}
if (snapshotCommitMessage.trim()) {
snapshotOptions.commit_message = snapshotCommitMessage.trim();
}
if (Object.keys(snapshotMetadata).length > 0) {
snapshotOptions.metadata = snapshotMetadata;
}
const snapshot = await createDevboxSnapshot(
devbox.id,
snapshotOptions,
);
setOperationResult(`Snapshot created: ${snapshot.id}`);
// Reset snapshot form state
setSnapshotFormMode(false);
setSnapshotName("");
setSnapshotCommitMessage("");
setSnapshotMetadata({});
setSnapshotFormField("name");
break;
case "ssh":
// Use service layer
const sshKey = await createSSHKey(devbox.id);
const fsModule = await import("fs");
const pathModule = await import("path");
const osModule = await import("os");
const sshDir = pathModule.join(
osModule.homedir(),
".runloop",
"ssh_keys",
);
fsModule.mkdirSync(sshDir, { recursive: true });
const keyPath = pathModule.join(sshDir, `${devbox.id}.pem`);
fsModule.writeFileSync(keyPath, sshKey.ssh_private_key, {
mode: 0o600,
});
const sshUser =
devbox.launch_parameters?.user_parameters?.username || "user";
const env = process.env.RUNLOOP_ENV?.toLowerCase();
const sshHost = env === "dev" ? "ssh.runloop.pro" : "ssh.runloop.ai";
// macOS openssl doesn't support -verify_quiet, use compatible flags
// servername should be %h (target hostname) - SSH will replace %h with the actual hostname from the SSH command
// This matches the reference implementation where servername is the target hostname
const proxyCommand = `openssl s_client -quiet -servername %h -connect ${sshHost}:443 2>/dev/null`;
// Navigate to SSH session screen
navigate("ssh-session", {
keyPath,
proxyCommand,
sshUser,
url: sshKey.url,
devboxId: devbox.id,
devboxName: devbox.name || devbox.id,
returnScreen: currentScreen,
returnParams: params,
});
break;
case "logs":
// Set flag to show streaming logs viewer
const logsResult: any = {
__customRender: "logs",
};
setOperationResult(logsResult);
break;
case "tunnel":
// Use service layer
const port = parseInt(operationInput);
if (isNaN(port) || port < 1 || port > 65535) {
setOperationError(
new Error(
"Invalid port number. Please enter a port between 1 and 65535.",
),
);
} else {
const tunnel = await createTunnel(devbox.id, port);
// Store tunnel result with custom render type to enable "open in browser"
const tunnelResult: any = {
__customRender: "tunnel",
__tunnelUrl: tunnel.url,
__port: port,
};
setOperationResult(tunnelResult);
}
break;
case "suspend":
// Use service layer
await suspendDevbox(devbox.id);
setOperationResult(`Devbox ${devbox.id} suspended successfully`);
break;
case "resume":
// Use service layer
await resumeDevbox(devbox.id);
setOperationResult(`Devbox ${devbox.id} resumed successfully`);
break;
case "delete":
// Use service layer
await shutdownDevbox(devbox.id);
setOperationResult(`Devbox ${devbox.id} shut down successfully`);
break;
}
} catch (err) {
setOperationError(err as Error);
} finally {
setLoading(false);
}
};
const operationLabel =
operations.find((o) => o.key === executingOperation)?.label || "Operation";
// Show delete confirmation
if (showDeleteConfirm) {
return (
<ConfirmationPrompt
title="Shutdown Devbox"
message={`Are you sure you want to shutdown "${devbox.name || devbox.id}"?`}
details="The devbox will be terminated and all unsaved data will be lost."
breadcrumbItems={[
...breadcrumbItems.slice(0, -1),
{ label: devbox.name || devbox.id },
{ label: "Shutdown", active: true },
]}
confirmLabel="Yes, shutdown"
onConfirm={() => {
setShowDeleteConfirm(false);
executeOperation();
}}
onCancel={() => {
setShowDeleteConfirm(false);
setExecutingOperation(null);
onBack();
}}
/>
);
}
// Operation result display
if (operationResult || operationError) {
// Check for custom exec rendering
if (
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "exec"
) {
const command = (operationResult as any).command || "";
const stdout = (operationResult as any).stdout || "";
const stderr = (operationResult as any).stderr || "";
const exitCode = (operationResult as any).exitCode;
const stdoutLines = stdout ? stdout.split("\n") : [];
const stderrLines = stderr ? stderr.split("\n") : [];
const allLines = [...stdoutLines, ...stderrLines].filter(
(line) => line !== "",
);
const viewportHeight = execViewport.viewportHeight;
const maxScroll = Math.max(0, allLines.length - viewportHeight);
const actualScroll = Math.min(execScroll, maxScroll);
const visibleLines = allLines.slice(
actualScroll,
actualScroll + viewportHeight,
);
const hasMore = actualScroll + viewportHeight < allLines.length;
const hasLess = actualScroll > 0;
const exitCodeColor = exitCode === 0 ? colors.success : colors.error;
return (
<>
<Breadcrumb
items={[
...breadcrumbItems,
{ label: "Execute Command", active: true },
]}
/>
{/* Command header */}
<Box
flexDirection="column"
borderStyle="round"
borderColor={colors.primary}
paddingX={1}
marginBottom={1}
>
<Box>
<Text color={colors.primary} bold>
{figures.play} Command:
</Text>
<Text> </Text>
<Text color={colors.text}>
{command.length > 500
? command.substring(0, 500) + "..."
: command}
</Text>
</Box>
<Box>
<Text color={colors.textDim} dimColor>
Exit Code:{" "}
</Text>
<Text color={exitCodeColor} bold>
{exitCode}
</Text>
</Box>
</Box>
{/* Output display */}
<Box
flexDirection="column"
borderStyle="round"
borderColor={colors.border}
paddingX={1}
>
{allLines.length === 0 && (
<Text color={colors.textDim} dimColor>
No output
</Text>
)}
{visibleLines.map((line: string, index: number) => {
const actualIndex = actualScroll + index;
const isStderr = actualIndex >= stdoutLines.length;
const lineColor = isStderr ? colors.error : colors.text;
return (
<Box key={index}>
<Text color={lineColor}>{line}</Text>
</Box>
);
})}
</Box>
{/* Statistics bar */}
<Box marginTop={1} paddingX={1}>
<Text color={colors.primary} bold>
{figures.hamburger} {allLines.length}
</Text>
<Text color={colors.textDim} dimColor>
{" "}
lines
</Text>
{allLines.length > 0 && (
<>
<Text color={colors.textDim} dimColor>
{" "}
•{" "}
</Text>
<Text color={colors.textDim} dimColor>
Viewing {actualScroll + 1}-
{Math.min(actualScroll + viewportHeight, allLines.length)} of{" "}
{allLines.length}
</Text>
{hasLess && (
<Text color={colors.primary}> {figures.arrowUp}</Text>
)}
{hasMore && (
<Text color={colors.primary}> {figures.arrowDown}</Text>
)}
</>
)}
{stdout && (
<>
<Text color={colors.textDim} dimColor>
{" "}
•{" "}
</Text>
<Text color={colors.success} dimColor>
stdout: {stdoutLines.length} lines
</Text>
</>
)}
{stderr && (
<>
<Text color={colors.textDim} dimColor>
{" "}
•{" "}
</Text>
<Text color={colors.error} dimColor>
stderr: {stderrLines.length} lines
</Text>
</>
)}
{copyStatus && (
<>
<Text color={colors.textDim} dimColor>
{" "}
•{" "}
</Text>
<Text color={colors.success} bold>
{copyStatus}
</Text>
</>
)}
</Box>
{/* Help bar */}
<NavigationTips
showArrows
tips={[
{ key: "g", label: "Top" },
{ key: "G", label: "Bottom" },
{ key: "c", label: "Copy" },
{ key: "Enter/q/esc", label: "Back" },
]}
/>
</>
);
}
// Check for custom logs rendering - use streaming logs viewer
if (
operationResult &&
typeof operationResult === "object" &&
(operationResult as any).__customRender === "logs"
) {
return (
<StreamingLogsViewer
devboxId={devbox.id}