@mindstudio-ai/local-model-tunnel 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2596 @@
1
+ import {
2
+ TunnelRunner,
3
+ deleteLocalInterfacePath,
4
+ detectAllProviderStatuses,
5
+ discoverAllModelsWithParameters,
6
+ getApiBaseUrl,
7
+ getApiKey,
8
+ getConfigPath,
9
+ getEditorSessions,
10
+ getEnvironment,
11
+ getLocalInterfacePath,
12
+ getLocalInterfacesDir,
13
+ getSyncedModels,
14
+ getUserId,
15
+ pollDeviceAuth,
16
+ requestDeviceAuth,
17
+ requestEvents,
18
+ setApiKey,
19
+ setLocalInterfacePath,
20
+ setUserId,
21
+ syncModels,
22
+ verifyApiKey
23
+ } from "./chunk-44NXQXRB.js";
24
+
25
+ // src/tui/index.tsx
26
+ import { render } from "ink";
27
+ import { execFileSync, execSync as execSync2 } from "child_process";
28
+
29
+ // src/tui/App.tsx
30
+ import { useEffect as useEffect15, useCallback as useCallback10, useState as useState15, useRef as useRef9 } from "react";
31
+ import { Box as Box10, useApp, useStdout as useStdout7 } from "ink";
32
+
33
+ // src/tui/components/Header.tsx
34
+ import os from "os";
35
+ import { Box, Text } from "ink";
36
+ import { createRequire } from "module";
37
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
38
+ var require2 = createRequire(import.meta.url);
39
+ var pkg = require2("../package.json");
40
+ var LogoString = ` .=+-. :++.
41
+ *@@@@@+ :%@@@@%:
42
+ .%@@@@@@#..@@@@@@@=
43
+ .*@@@@@@@--@@@@@@@#.**.
44
+ *@@@@@@@.-@@@@@@@@.#@@*
45
+ .#@@@@@@@-.@@@@@@@* #@@@@%.
46
+ =@@@@@@@-.@@@@@@@#.-@@@@@@+
47
+ :@@@@@@: +@@@@@#. .@@@@@@:
48
+ .++: .-*-. .++:`;
49
+ var getConnectionDisplay = (status) => {
50
+ switch (status) {
51
+ case "connected":
52
+ return { color: "green", text: "Connected to Cloud" };
53
+ case "connecting":
54
+ return { color: "yellow", text: "Connecting..." };
55
+ case "not_authenticated":
56
+ return { color: "yellow", text: "Not Authenticated" };
57
+ case "disconnected":
58
+ return { color: "red", text: "Disconnected" };
59
+ default:
60
+ return { color: "red", text: "Error" };
61
+ }
62
+ };
63
+ function Header({
64
+ connection,
65
+ environment,
66
+ configPath,
67
+ connectionError,
68
+ compact
69
+ }) {
70
+ const { color: connectionColor, text: connectionText } = getConnectionDisplay(connection);
71
+ return /* @__PURE__ */ jsxs(
72
+ Box,
73
+ {
74
+ flexDirection: "row",
75
+ alignItems: "center",
76
+ borderStyle: "round",
77
+ borderColor: "cyan",
78
+ paddingX: 1,
79
+ paddingY: 1,
80
+ width: "100%",
81
+ children: [
82
+ !compact && /* @__PURE__ */ jsx(Box, { paddingLeft: 3, children: /* @__PURE__ */ jsx(Text, { color: "cyan", children: LogoString }) }),
83
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: compact ? 0 : 4, children: [
84
+ /* @__PURE__ */ jsxs(Box, { children: [
85
+ /* @__PURE__ */ jsx(Text, { bold: true, color: "white", children: "MindStudio Local Tunnel" }),
86
+ compact && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
87
+ " v",
88
+ pkg.version
89
+ ] }),
90
+ environment !== "prod" && /* @__PURE__ */ jsxs(Fragment, { children: [
91
+ /* @__PURE__ */ jsx(Text, { children: " " }),
92
+ /* @__PURE__ */ jsx(Text, { color: "yellow", bold: true, children: "[LOCAL]" })
93
+ ] })
94
+ ] }),
95
+ !compact && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
96
+ "v",
97
+ pkg.version
98
+ ] }),
99
+ /* @__PURE__ */ jsxs(Text, { color: connectionColor, children: [
100
+ "\u25CF ",
101
+ connectionText
102
+ ] }),
103
+ connectionError && /* @__PURE__ */ jsx(Text, { color: "red", children: connectionError }),
104
+ /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
105
+ "Config: ",
106
+ configPath.replace(os.homedir(), "~")
107
+ ] })
108
+ ] })
109
+ ]
110
+ }
111
+ );
112
+ }
113
+
114
+ // src/tui/components/NavigationMenu.tsx
115
+ import { useState, useEffect } from "react";
116
+ import { Box as Box2, Text as Text2, useInput, useStdout } from "ink";
117
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
118
+ function NavigationMenu({ items, onSelect, title }) {
119
+ const { stdout } = useStdout();
120
+ const compact = (stdout?.rows ?? 24) < 40;
121
+ const getDefaultIndex = () => {
122
+ const firstIdx = items.findIndex((i) => !i.disabled && !i.isSeparator);
123
+ return firstIdx >= 0 ? firstIdx : 0;
124
+ };
125
+ const [selectedIndex, setSelectedIndex] = useState(getDefaultIndex);
126
+ useEffect(() => {
127
+ setSelectedIndex(getDefaultIndex());
128
+ }, [items]);
129
+ const selectableItems = items.filter((i) => !i.isSeparator);
130
+ const findNextEnabled = (from, direction) => {
131
+ let idx = from;
132
+ for (let i = 0; i < items.length; i++) {
133
+ idx = (idx + direction + items.length) % items.length;
134
+ if (!items[idx].disabled && !items[idx].isSeparator) return idx;
135
+ }
136
+ return from;
137
+ };
138
+ useInput((input, key) => {
139
+ if (input === "q" || key.escape) {
140
+ const backItem = items.find((i) => i.id === "back");
141
+ if (backItem) {
142
+ onSelect("back");
143
+ } else if (input === "q") {
144
+ onSelect("quit");
145
+ }
146
+ return;
147
+ }
148
+ if (key.upArrow || compact && key.leftArrow) {
149
+ setSelectedIndex((prev) => findNextEnabled(prev, -1));
150
+ } else if (key.downArrow || compact && key.rightArrow) {
151
+ setSelectedIndex((prev) => findNextEnabled(prev, 1));
152
+ } else if (key.return) {
153
+ const item = items[selectedIndex];
154
+ if (item && !item.disabled) {
155
+ onSelect(item.id);
156
+ }
157
+ }
158
+ });
159
+ const hasBack = items.some((i) => i.id === "back");
160
+ if (compact) {
161
+ const selectedItem = items[selectedIndex];
162
+ return /* @__PURE__ */ jsx2(Box2, { flexDirection: "column", paddingX: 1, borderStyle: "single", borderTop: true, borderBottom: false, borderLeft: false, borderRight: false, borderColor: "gray", children: /* @__PURE__ */ jsx2(Box2, { height: 1, overflow: "hidden", gap: 1, children: items.map((item, index) => {
163
+ if (item.isSeparator) return null;
164
+ const isSelected = index === selectedIndex;
165
+ return /* @__PURE__ */ jsx2(
166
+ Text2,
167
+ {
168
+ color: item.disabled ? "gray" : isSelected ? "cyan" : "white",
169
+ bold: isSelected,
170
+ wrap: "truncate-end",
171
+ children: isSelected ? `\u276F ${item.label}` : ` ${item.label}`
172
+ },
173
+ item.id
174
+ );
175
+ }) }) });
176
+ }
177
+ const separatorExtraLines = items.filter((item, idx) => item.isSeparator && idx > 0).length;
178
+ const menuHeight = items.length + 4 + separatorExtraLines;
179
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", paddingX: 1, marginBottom: 1, borderStyle: "single", borderTop: true, borderBottom: false, borderLeft: false, borderRight: false, borderColor: "gray", children: [
180
+ /* @__PURE__ */ jsx2(Box2, { marginTop: 1, children: /* @__PURE__ */ jsx2(Text2, { color: "gray", children: title ?? "Actions" }) }),
181
+ /* @__PURE__ */ jsx2(Box2, { flexDirection: "column", children: items.map((item, index) => {
182
+ if (item.isSeparator) {
183
+ return /* @__PURE__ */ jsx2(Box2, { marginTop: index > 0 ? 1 : 0, children: item.label ? /* @__PURE__ */ jsx2(Text2, { bold: true, color: item.color ?? "gray", wrap: "truncate-end", children: item.label }) : null }, item.id);
184
+ }
185
+ const isSelected = index === selectedIndex;
186
+ const prefix = isSelected ? "\u276F" : " ";
187
+ if (item.disabled) {
188
+ return /* @__PURE__ */ jsx2(Box2, { height: 1, overflow: "hidden", children: /* @__PURE__ */ jsxs2(Text2, { color: "gray", wrap: "truncate-end", children: [
189
+ prefix,
190
+ " ",
191
+ item.label,
192
+ item.disabledReason ? ` (${item.disabledReason})` : ""
193
+ ] }) }, item.id);
194
+ }
195
+ return /* @__PURE__ */ jsxs2(Box2, { height: 1, overflow: "hidden", children: [
196
+ /* @__PURE__ */ jsxs2(Text2, { color: isSelected ? "cyan" : "white", bold: isSelected, wrap: "truncate-end", children: [
197
+ prefix,
198
+ " ",
199
+ item.label
200
+ ] }),
201
+ isSelected && /* @__PURE__ */ jsxs2(Text2, { color: "gray", wrap: "truncate-end", children: [
202
+ " - ",
203
+ item.description
204
+ ] })
205
+ ] }, item.id);
206
+ }) }),
207
+ /* @__PURE__ */ jsx2(Box2, { marginTop: 1, height: 1, children: /* @__PURE__ */ jsx2(Text2, { color: "gray", wrap: "truncate-end", children: hasBack ? "Up/Down Navigate \u2022 Enter Select \u2022 q/Esc Back" : "Up/Down Navigate \u2022 Enter Select \u2022 q Quit" }) })
208
+ ] });
209
+ }
210
+
211
+ // src/tui/hooks/useConnection.ts
212
+ import { useState as useState2, useEffect as useEffect2, useCallback } from "react";
213
+ function useConnection() {
214
+ const [status, setStatus] = useState2("connecting");
215
+ const [error, setError] = useState2(null);
216
+ const environment = getEnvironment();
217
+ const connect = useCallback(async () => {
218
+ setStatus("connecting");
219
+ setError(null);
220
+ const apiKey = getApiKey();
221
+ const userId = getUserId();
222
+ if (!apiKey || !userId) {
223
+ setStatus("not_authenticated");
224
+ return;
225
+ }
226
+ try {
227
+ const isValid = await verifyApiKey();
228
+ if (isValid) {
229
+ setStatus("connected");
230
+ } else {
231
+ setStatus("not_authenticated");
232
+ }
233
+ } catch (err) {
234
+ setStatus("error");
235
+ setError(err instanceof Error ? err.message : "Connection failed");
236
+ }
237
+ }, []);
238
+ useEffect2(() => {
239
+ connect();
240
+ }, [connect]);
241
+ return {
242
+ status,
243
+ environment,
244
+ error,
245
+ retry: connect
246
+ };
247
+ }
248
+
249
+ // src/tui/models/hooks/useSetupProviders.ts
250
+ import { useState as useState3, useEffect as useEffect3, useCallback as useCallback2, useRef } from "react";
251
+ function useSetupProviders() {
252
+ const [providers, setProviders] = useState3([]);
253
+ const [loading, setLoading] = useState3(true);
254
+ const [refreshing, setRefreshing] = useState3(false);
255
+ const initialLoadDone = useRef(false);
256
+ const refresh = useCallback2(async () => {
257
+ if (!initialLoadDone.current) {
258
+ setLoading(true);
259
+ } else {
260
+ setRefreshing(true);
261
+ }
262
+ const statuses = await detectAllProviderStatuses();
263
+ setProviders(statuses);
264
+ initialLoadDone.current = true;
265
+ setLoading(false);
266
+ setRefreshing(false);
267
+ }, []);
268
+ useEffect3(() => {
269
+ refresh();
270
+ }, [refresh]);
271
+ return { providers, loading, refreshing, refresh };
272
+ }
273
+
274
+ // src/tui/models/hooks/useModels.ts
275
+ import { useState as useState4, useEffect as useEffect4, useCallback as useCallback3, useRef as useRef2 } from "react";
276
+ function useModels() {
277
+ const [models, setModels] = useState4([]);
278
+ const [warnings, setWarnings] = useState4([]);
279
+ const [loading, setLoading] = useState4(true);
280
+ const [refreshing, setRefreshing] = useState4(false);
281
+ const initialLoadDone = useRef2(false);
282
+ const refresh = useCallback3(async () => {
283
+ if (!initialLoadDone.current) {
284
+ setLoading(true);
285
+ } else {
286
+ setRefreshing(true);
287
+ }
288
+ try {
289
+ const discoveredModels = await discoverAllModelsWithParameters();
290
+ setModels(discoveredModels.filter((m) => !m.statusHint));
291
+ setWarnings(discoveredModels.filter((m) => !!m.statusHint));
292
+ initialLoadDone.current = true;
293
+ return discoveredModels;
294
+ } catch {
295
+ return [];
296
+ } finally {
297
+ setLoading(false);
298
+ setRefreshing(false);
299
+ }
300
+ }, []);
301
+ useEffect4(() => {
302
+ refresh();
303
+ }, [refresh]);
304
+ return {
305
+ models,
306
+ warnings,
307
+ loading,
308
+ refreshing,
309
+ refresh
310
+ };
311
+ }
312
+
313
+ // src/tui/models/hooks/useRequests.ts
314
+ import { useState as useState5, useEffect as useEffect5, useCallback as useCallback4, useRef as useRef3 } from "react";
315
+ function useRequests(maxHistory = 50) {
316
+ const [requests, setRequests] = useState5([]);
317
+ const requestsRef = useRef3(/* @__PURE__ */ new Map());
318
+ useEffect5(() => {
319
+ const interval = setInterval(() => {
320
+ setRequests((prev) => {
321
+ const hasActive = prev.some((r) => r.status === "processing");
322
+ return hasActive ? [...prev] : prev;
323
+ });
324
+ }, 1e3);
325
+ return () => clearInterval(interval);
326
+ }, []);
327
+ useEffect5(() => {
328
+ const unsubStart = requestEvents.onStart((event) => {
329
+ const entry = {
330
+ id: event.id,
331
+ modelId: event.modelId,
332
+ requestType: event.requestType,
333
+ status: "processing",
334
+ startTime: event.timestamp
335
+ };
336
+ requestsRef.current.set(event.id, entry);
337
+ setRequests((prev) => [...prev, entry].slice(-maxHistory));
338
+ });
339
+ const unsubProgress = requestEvents.onProgress((event) => {
340
+ const existing = requestsRef.current.get(event.id);
341
+ if (existing && existing.status === "processing") {
342
+ const updated = {
343
+ ...existing,
344
+ ...event.content !== void 0 && { content: event.content },
345
+ ...event.step !== void 0 && { step: event.step },
346
+ ...event.totalSteps !== void 0 && { totalSteps: event.totalSteps }
347
+ };
348
+ requestsRef.current.set(event.id, updated);
349
+ setRequests(
350
+ (prev) => prev.map((r) => r.id === event.id ? updated : r)
351
+ );
352
+ }
353
+ });
354
+ const unsubComplete = requestEvents.onComplete((event) => {
355
+ const existing = requestsRef.current.get(event.id);
356
+ if (existing) {
357
+ const updated = {
358
+ ...existing,
359
+ status: event.success ? "completed" : "failed",
360
+ endTime: Date.now(),
361
+ duration: event.duration,
362
+ result: event.result,
363
+ error: event.error
364
+ };
365
+ requestsRef.current.set(event.id, updated);
366
+ setRequests(
367
+ (prev) => prev.map((r) => r.id === event.id ? updated : r)
368
+ );
369
+ }
370
+ });
371
+ return () => {
372
+ unsubStart();
373
+ unsubProgress();
374
+ unsubComplete();
375
+ };
376
+ }, [maxHistory]);
377
+ const activeCount = requests.filter((r) => r.status === "processing").length;
378
+ const clear = useCallback4(() => {
379
+ requestsRef.current.clear();
380
+ setRequests([]);
381
+ }, []);
382
+ return {
383
+ requests,
384
+ activeCount,
385
+ clear
386
+ };
387
+ }
388
+
389
+ // src/tui/models/hooks/useRegisteredModels.ts
390
+ import { useState as useState6, useEffect as useEffect6, useCallback as useCallback5 } from "react";
391
+ function useSyncedModels(connectionStatus) {
392
+ const [syncedNames, setSyncedNames] = useState6(
393
+ /* @__PURE__ */ new Set()
394
+ );
395
+ const [syncedModels, setSyncedModels] = useState6([]);
396
+ const refresh = useCallback5(async () => {
397
+ if (connectionStatus !== "connected") {
398
+ setSyncedNames(/* @__PURE__ */ new Set());
399
+ setSyncedModels([]);
400
+ return;
401
+ }
402
+ try {
403
+ const models = await getSyncedModels();
404
+ setSyncedNames(new Set(models.map((m) => m.name)));
405
+ setSyncedModels(models);
406
+ } catch {
407
+ }
408
+ }, [connectionStatus]);
409
+ useEffect6(() => {
410
+ refresh();
411
+ }, [refresh]);
412
+ return {
413
+ syncedNames,
414
+ syncedModels,
415
+ refresh
416
+ };
417
+ }
418
+
419
+ // src/tui/models/pages/DashboardPage.tsx
420
+ import { useMemo } from "react";
421
+ import { Box as Box4, Text as Text4, useStdout as useStdout3 } from "ink";
422
+ import Spinner2 from "ink-spinner";
423
+
424
+ // src/tui/models/components/RequestLog.tsx
425
+ import { Box as Box3, Text as Text3, useStdout as useStdout2 } from "ink";
426
+ import Spinner from "ink-spinner";
427
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
428
+ function formatTime(timestamp) {
429
+ const date = new Date(timestamp);
430
+ return date.toLocaleTimeString("en-US", {
431
+ hour12: false,
432
+ hour: "2-digit",
433
+ minute: "2-digit",
434
+ second: "2-digit"
435
+ });
436
+ }
437
+ function formatDuration(ms) {
438
+ if (ms < 1e3) return `${ms}ms`;
439
+ return `${(ms / 1e3).toFixed(1)}s`;
440
+ }
441
+ function getRequestTypeLabel(type) {
442
+ switch (type) {
443
+ case "llm_chat":
444
+ return { label: "text", color: "gray" };
445
+ case "image_generation":
446
+ return { label: "image", color: "gray" };
447
+ case "video_generation":
448
+ return { label: "video", color: "gray" };
449
+ default:
450
+ return { label: type, color: "gray" };
451
+ }
452
+ }
453
+ function snippetLine(content, maxWidth) {
454
+ const flat = content.replace(/\s+/g, " ").trim();
455
+ if (flat.length <= maxWidth) return flat;
456
+ return "\u2026" + flat.slice(-(maxWidth - 1));
457
+ }
458
+ function RequestItem({ request, width }) {
459
+ const time = formatTime(request.startTime);
460
+ const typeLabel = getRequestTypeLabel(request.requestType);
461
+ const snippetIndent = " ";
462
+ const snippetWidth = width - snippetIndent.length - 2;
463
+ if (request.status === "processing") {
464
+ const elapsed = Date.now() - request.startTime;
465
+ const snippet = request.content && request.requestType === "llm_chat" ? snippetLine(request.content, snippetWidth) : null;
466
+ const stepProgress = request.step !== void 0 && request.totalSteps ? `Step ${request.step}/${request.totalSteps}` : null;
467
+ return /* @__PURE__ */ jsxs3(Box3, { flexDirection: "column", children: [
468
+ /* @__PURE__ */ jsxs3(Box3, { children: [
469
+ /* @__PURE__ */ jsx3(Text3, { color: "cyan", children: /* @__PURE__ */ jsx3(Spinner, { type: "dots" }) }),
470
+ /* @__PURE__ */ jsxs3(Text3, { color: "gray", children: [
471
+ " ",
472
+ time,
473
+ " "
474
+ ] }),
475
+ /* @__PURE__ */ jsx3(Text3, { color: "white", children: request.modelId }),
476
+ /* @__PURE__ */ jsx3(Text3, { color: "gray", children: " " }),
477
+ /* @__PURE__ */ jsx3(Text3, { color: typeLabel.color, children: typeLabel.label }),
478
+ /* @__PURE__ */ jsxs3(Text3, { color: "gray", children: [
479
+ " ",
480
+ formatDuration(elapsed),
481
+ "..."
482
+ ] })
483
+ ] }),
484
+ snippet && /* @__PURE__ */ jsxs3(Text3, { color: "gray", wrap: "truncate-end", children: [
485
+ snippetIndent,
486
+ snippet
487
+ ] }),
488
+ stepProgress && /* @__PURE__ */ jsxs3(Text3, { color: "gray", children: [
489
+ snippetIndent,
490
+ stepProgress
491
+ ] })
492
+ ] });
493
+ }
494
+ if (request.status === "completed") {
495
+ const duration = request.duration ? formatDuration(request.duration) : "";
496
+ let resultInfo = "";
497
+ if (request.result?.chars) {
498
+ resultInfo = ` \xB7 ${request.result.chars} chars`;
499
+ } else if (request.result?.imageSize) {
500
+ resultInfo = ` \xB7 ${Math.round(request.result.imageSize / 1024)}KB`;
501
+ } else if (request.result?.videoSize) {
502
+ resultInfo = ` \xB7 ${Math.round(request.result.videoSize / 1024 / 1024)}MB`;
503
+ }
504
+ const snippet = request.content && request.requestType === "llm_chat" ? snippetLine(request.content, snippetWidth) : null;
505
+ return /* @__PURE__ */ jsxs3(Box3, { flexDirection: "column", children: [
506
+ /* @__PURE__ */ jsxs3(Box3, { children: [
507
+ /* @__PURE__ */ jsx3(Text3, { color: "green", children: "\u2713" }),
508
+ /* @__PURE__ */ jsxs3(Text3, { color: "gray", children: [
509
+ " ",
510
+ time,
511
+ " "
512
+ ] }),
513
+ /* @__PURE__ */ jsx3(Text3, { color: "white", children: request.modelId }),
514
+ /* @__PURE__ */ jsx3(Text3, { color: "gray", children: " " }),
515
+ /* @__PURE__ */ jsx3(Text3, { color: typeLabel.color, children: typeLabel.label }),
516
+ /* @__PURE__ */ jsxs3(Text3, { color: "gray", children: [
517
+ " ",
518
+ duration,
519
+ resultInfo
520
+ ] })
521
+ ] }),
522
+ snippet && /* @__PURE__ */ jsxs3(Text3, { color: "gray", wrap: "truncate-end", children: [
523
+ snippetIndent,
524
+ snippet
525
+ ] })
526
+ ] });
527
+ }
528
+ return /* @__PURE__ */ jsx3(Box3, { flexDirection: "column", children: /* @__PURE__ */ jsxs3(Box3, { children: [
529
+ /* @__PURE__ */ jsx3(Text3, { color: "red", children: "\u25CF" }),
530
+ /* @__PURE__ */ jsxs3(Text3, { color: "gray", children: [
531
+ " ",
532
+ time,
533
+ " "
534
+ ] }),
535
+ /* @__PURE__ */ jsx3(Text3, { color: "white", children: request.modelId }),
536
+ /* @__PURE__ */ jsx3(Text3, { color: "gray", children: " " }),
537
+ /* @__PURE__ */ jsx3(Text3, { color: typeLabel.color, children: typeLabel.label }),
538
+ /* @__PURE__ */ jsxs3(Text3, { color: "red", children: [
539
+ " ",
540
+ request.error || "Failed"
541
+ ] })
542
+ ] }) });
543
+ }
544
+ function RequestLog({ requests, maxVisible = 8, hasModels = true }) {
545
+ const { stdout } = useStdout2();
546
+ const width = stdout?.columns ?? 80;
547
+ const activeRequests = requests.filter((r) => r.status === "processing");
548
+ const completedRequests = requests.filter((r) => r.status !== "processing");
549
+ const itemLines = (r) => {
550
+ if (r.requestType === "llm_chat" && r.content) return 2;
551
+ if (r.status === "processing" && r.step !== void 0) return 2;
552
+ return 1;
553
+ };
554
+ let completedToShow = [];
555
+ let linesUsed = activeRequests.reduce((sum, r) => sum + itemLines(r), 0);
556
+ for (let i = completedRequests.length - 1; i >= 0 && linesUsed < maxVisible; i--) {
557
+ const r = completedRequests[i];
558
+ const lines = itemLines(r);
559
+ if (linesUsed + lines <= maxVisible) {
560
+ completedToShow.unshift(r);
561
+ linesUsed += lines;
562
+ } else {
563
+ break;
564
+ }
565
+ }
566
+ const visibleRequests = [...completedToShow, ...activeRequests];
567
+ return /* @__PURE__ */ jsxs3(
568
+ Box3,
569
+ {
570
+ flexDirection: "column",
571
+ flexGrow: 1,
572
+ width: "100%",
573
+ paddingX: 1,
574
+ marginTop: 1,
575
+ children: [
576
+ /* @__PURE__ */ jsxs3(Box3, { children: [
577
+ /* @__PURE__ */ jsx3(Text3, { bold: true, underline: true, color: "white", children: "Generation Requests" }),
578
+ activeRequests.length > 0 && /* @__PURE__ */ jsxs3(Text3, { color: "cyan", children: [
579
+ " (",
580
+ activeRequests.length,
581
+ " active)"
582
+ ] })
583
+ ] }),
584
+ requests.length === 0 ? /* @__PURE__ */ jsx3(Box3, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ jsx3(Text3, { color: "gray", children: hasModels ? "Tunnel is live \u2014 requests will appear here when models are used in MindStudio" : "Start a model to begin receiving generation requests." }) }) : /* @__PURE__ */ jsx3(Box3, { flexDirection: "column", marginTop: 1, children: visibleRequests.map((request) => /* @__PURE__ */ jsx3(RequestItem, { request, width }, request.id)) })
585
+ ]
586
+ }
587
+ );
588
+ }
589
+
590
+ // src/tui/models/pages/DashboardPage.tsx
591
+ import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
592
+ function getWorkflowCount(model) {
593
+ const param = model.parameters?.find((p) => p.type === "comfyWorkflow");
594
+ if (!param) return null;
595
+ return param.comfyWorkflowOptions.availableWorkflows.length;
596
+ }
597
+ function getCapabilityLabel(capability) {
598
+ switch (capability) {
599
+ case "text":
600
+ return { label: "Text Generation", color: "gray" };
601
+ case "image":
602
+ return { label: "Image Generation", color: "gray" };
603
+ case "video":
604
+ return { label: "Video Generation", color: "gray" };
605
+ default:
606
+ return { label: capability, color: "gray" };
607
+ }
608
+ }
609
+ function DashboardPage({
610
+ requests,
611
+ models,
612
+ modelWarnings = [],
613
+ providers,
614
+ providersLoading,
615
+ syncedNames,
616
+ modelsLoading,
617
+ syncStatus = "idle",
618
+ onNavigate
619
+ }) {
620
+ const { stdout } = useStdout3();
621
+ const installedProviders = providers.filter(({ status }) => status.installed);
622
+ const provNameWidth = Math.max(
623
+ ...installedProviders.map((p) => p.provider.displayName.length),
624
+ 8
625
+ );
626
+ const provStatusWidth = "Local Server Running".length;
627
+ const allModelNames = new Set(models.map((m) => m.name));
628
+ const unavailableSynced = [...syncedNames].filter(
629
+ (name) => !allModelNames.has(name)
630
+ );
631
+ const syncDescription = syncStatus === "syncing" ? "Syncing..." : syncStatus === "synced" ? "\u2713 Synced" : "Re-detect providers and sync models to MindStudio";
632
+ const menuItems = useMemo(() => {
633
+ return [
634
+ {
635
+ id: "interfaces",
636
+ label: "Connect to IDE",
637
+ description: "Connect your local editor to a MindStudio interface or script"
638
+ },
639
+ {
640
+ id: "refresh",
641
+ label: "Sync Models",
642
+ description: syncDescription
643
+ },
644
+ {
645
+ id: "setup",
646
+ label: "Manage Providers",
647
+ description: "Manage local AI providers"
648
+ },
649
+ {
650
+ id: "auth",
651
+ label: "Re-authenticate",
652
+ description: "Re-authenticate with MindStudio"
653
+ },
654
+ {
655
+ id: "quit",
656
+ label: "Exit",
657
+ description: "Quit the application"
658
+ }
659
+ ];
660
+ }, [syncDescription]);
661
+ const termHeight = (stdout?.rows ?? 24) - 4;
662
+ const compactHeader = (stdout?.rows ?? 24) <= 45 || (stdout?.columns ?? 80) <= 90;
663
+ const headerLines = compactHeader ? 7 : 14;
664
+ const providerContentLines = providersLoading ? 1 : installedProviders.length === 0 ? 2 : installedProviders.length;
665
+ const providersLines = 3 + providerContentLines;
666
+ const modelContentLines = modelsLoading ? 1 : models.length === 0 && unavailableSynced.length === 0 && modelWarnings.length === 0 ? 2 : models.length + modelWarnings.length + (unavailableSynced.length > 0 ? 1 + unavailableSynced.length : 0);
667
+ const modelsLines = 3 + modelContentLines;
668
+ const requestLogOverhead = 3;
669
+ const compactMenu = termHeight + 4 < 40;
670
+ const menuLines = compactMenu ? 2 : menuItems.length + 6;
671
+ const usedLines = headerLines + providersLines + modelsLines + requestLogOverhead + menuLines;
672
+ const maxVisible = Math.max(3, termHeight - usedLines);
673
+ return /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", flexGrow: 1, children: [
674
+ /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
675
+ /* @__PURE__ */ jsx4(Text4, { bold: true, color: "white", underline: true, children: "Providers" }),
676
+ providersLoading ? /* @__PURE__ */ jsxs4(Box4, { marginTop: 1, children: [
677
+ /* @__PURE__ */ jsx4(Text4, { color: "cyan", children: /* @__PURE__ */ jsx4(Spinner2, { type: "dots" }) }),
678
+ /* @__PURE__ */ jsx4(Text4, { children: " Detecting providers..." })
679
+ ] }) : installedProviders.length === 0 ? /* @__PURE__ */ jsxs4(Box4, { marginTop: 1, flexDirection: "column", children: [
680
+ /* @__PURE__ */ jsx4(Text4, { color: "yellow", children: "No providers installed." }),
681
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: 'Use "Manage Providers" below to install one.' })
682
+ ] }) : /* @__PURE__ */ jsx4(Box4, { flexDirection: "column", marginTop: 1, children: installedProviders.map(({ provider, status }) => {
683
+ const url = provider.baseUrl;
684
+ const statusColor = status.running ? "green" : "yellow";
685
+ const statusText = status.running ? "Local Server Running" : "Installed (not running)";
686
+ return /* @__PURE__ */ jsxs4(Box4, { children: [
687
+ /* @__PURE__ */ jsx4(Text4, { color: "white", children: provider.displayName.padEnd(provNameWidth + 2) }),
688
+ /* @__PURE__ */ jsx4(Text4, { color: statusColor, children: statusText.padEnd(provStatusWidth + 2) }),
689
+ status.running && /* @__PURE__ */ jsx4(Text4, { color: "gray", children: url })
690
+ ] }, provider.name);
691
+ }) })
692
+ ] }),
693
+ /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
694
+ /* @__PURE__ */ jsx4(Text4, { bold: true, color: "white", underline: true, children: "Models" }),
695
+ modelsLoading ? /* @__PURE__ */ jsxs4(Box4, { marginTop: 1, children: [
696
+ /* @__PURE__ */ jsx4(Text4, { color: "cyan", children: /* @__PURE__ */ jsx4(Spinner2, { type: "dots" }) }),
697
+ /* @__PURE__ */ jsx4(Text4, { children: " Discovering models..." })
698
+ ] }) : models.length === 0 && unavailableSynced.length === 0 && modelWarnings.length === 0 ? /* @__PURE__ */ jsxs4(Box4, { marginTop: 1, flexDirection: "column", children: [
699
+ /* @__PURE__ */ jsx4(Text4, { color: "yellow", children: "No models found." }),
700
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: "Download models using your provider (e.g., ollama pull llama3.2)" })
701
+ ] }) : /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", marginTop: 1, children: [
702
+ models.map((model) => {
703
+ const cap = getCapabilityLabel(model.capability);
704
+ const isSynced = syncedNames.has(model.name);
705
+ const displayProvider = providers.find((p) => p.provider.name === model.provider)?.provider.displayName ?? model.provider;
706
+ const workflowCount = getWorkflowCount(model);
707
+ const workflowSuffix = workflowCount !== null ? ` (${workflowCount} workflow${workflowCount !== 1 ? "s" : ""}, ${isSynced ? workflowCount : 0} synced)` : "";
708
+ return /* @__PURE__ */ jsxs4(Box4, { children: [
709
+ /* @__PURE__ */ jsx4(Text4, { color: isSynced ? "green" : "gray", children: isSynced ? "\u25CF" : "\u25CB" }),
710
+ /* @__PURE__ */ jsx4(Text4, { color: "white", children: ` ${model.name}` }),
711
+ workflowSuffix && /* @__PURE__ */ jsx4(Text4, { color: "gray", children: workflowSuffix }),
712
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: " - " }),
713
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: displayProvider }),
714
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: " - " }),
715
+ /* @__PURE__ */ jsx4(Text4, { color: cap.color, children: cap.label })
716
+ ] }, `${model.provider}:${model.name}`);
717
+ }),
718
+ modelWarnings.map((warning) => {
719
+ const displayProvider = providers.find((p) => p.provider.name === warning.provider)?.provider.displayName ?? warning.provider;
720
+ return /* @__PURE__ */ jsxs4(Box4, { children: [
721
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: "\u25CB" }),
722
+ /* @__PURE__ */ jsx4(Text4, { color: "white", children: ` ${warning.name}` }),
723
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: " - " }),
724
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: displayProvider }),
725
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: " - " }),
726
+ /* @__PURE__ */ jsx4(Text4, { color: "yellow", children: warning.statusHint })
727
+ ] }, `${warning.provider}:${warning.name}`);
728
+ }),
729
+ unavailableSynced.length > 0 && /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", marginTop: models.length > 0 ? 1 : 0, children: [
730
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: "Synced but provider not running:" }),
731
+ unavailableSynced.map((name) => /* @__PURE__ */ jsxs4(Box4, { children: [
732
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: "\u25CB" }),
733
+ /* @__PURE__ */ jsx4(Text4, { color: "gray", children: ` ${name}` })
734
+ ] }, name))
735
+ ] })
736
+ ] })
737
+ ] }),
738
+ /* @__PURE__ */ jsx4(
739
+ RequestLog,
740
+ {
741
+ requests,
742
+ maxVisible,
743
+ hasModels: models.length > 0
744
+ }
745
+ ),
746
+ /* @__PURE__ */ jsx4(NavigationMenu, { items: menuItems, onSelect: onNavigate })
747
+ ] });
748
+ }
749
+
750
+ // src/tui/models/pages/SetupPage.tsx
751
+ import { useState as useState7, useMemo as useMemo3, useEffect as useEffect7 } from "react";
752
+ import { Box as Box5, Text as Text6, useInput as useInput2, useStdout as useStdout5 } from "ink";
753
+ import Spinner3 from "ink-spinner";
754
+
755
+ // src/tui/components/MarkdownText.tsx
756
+ import { useMemo as useMemo2 } from "react";
757
+ import { Text as Text5, useStdout as useStdout4 } from "ink";
758
+ import chalk from "chalk";
759
+ import { marked } from "marked";
760
+ import { markedTerminal } from "marked-terminal";
761
+ import { jsx as jsx5 } from "react/jsx-runtime";
762
+ var codeStyle = chalk.cyan;
763
+ var identity = (s) => s;
764
+ function renderMarkdown(content, width) {
765
+ marked.use(
766
+ markedTerminal({
767
+ width,
768
+ codespan: codeStyle,
769
+ link: identity,
770
+ href: identity
771
+ })
772
+ );
773
+ marked.use({
774
+ renderer: {
775
+ code({ text }) {
776
+ const lines = text.trim().split("\n").map((l) => " " + codeStyle(l)).join("\n");
777
+ return lines + "\n\n";
778
+ },
779
+ link({ href, text }) {
780
+ if (text && text !== href) {
781
+ return `${text} (${href})`;
782
+ }
783
+ return href;
784
+ }
785
+ }
786
+ });
787
+ return marked.parse(content).trimEnd();
788
+ }
789
+
790
+ // src/tui/models/pages/SetupPage.tsx
791
+ import { Fragment as Fragment2, jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
792
+ function ProviderDetailView({
793
+ provider,
794
+ onBack
795
+ }) {
796
+ const [scrollOffset, setScrollOffset] = useState7(0);
797
+ const { stdout } = useStdout5();
798
+ const termHeight = (stdout?.rows ?? 24) - 4;
799
+ const headerHeight = 14;
800
+ const footerLines = 6;
801
+ const contentPadding = 2;
802
+ const viewHeight = termHeight - headerHeight - footerLines - contentPadding;
803
+ const contentWidth = (stdout?.columns ?? 80) - 4;
804
+ const renderedLines = useMemo3(() => {
805
+ const rendered = renderMarkdown(provider.readme, contentWidth);
806
+ return rendered.split("\n");
807
+ }, [provider.readme, contentWidth]);
808
+ const maxScroll = Math.max(0, renderedLines.length - viewHeight);
809
+ useInput2((input, key) => {
810
+ if (input === "q" || key.escape || key.return) {
811
+ onBack();
812
+ return;
813
+ }
814
+ if (key.upArrow) {
815
+ setScrollOffset((prev) => Math.max(0, prev - 1));
816
+ } else if (key.downArrow) {
817
+ setScrollOffset((prev) => Math.min(maxScroll, prev + 1));
818
+ }
819
+ });
820
+ const visibleContent = renderedLines.slice(scrollOffset, scrollOffset + viewHeight).join("\n");
821
+ const scrollbar = useMemo3(() => {
822
+ if (maxScroll === 0) return null;
823
+ const thumbSize = Math.max(
824
+ 1,
825
+ Math.round(viewHeight / renderedLines.length * viewHeight)
826
+ );
827
+ const thumbPos = Math.round(
828
+ scrollOffset / maxScroll * (viewHeight - thumbSize)
829
+ );
830
+ return Array.from(
831
+ { length: viewHeight },
832
+ (_, i) => i >= thumbPos && i < thumbPos + thumbSize
833
+ );
834
+ }, [scrollOffset, maxScroll, viewHeight, renderedLines.length]);
835
+ return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", children: [
836
+ /* @__PURE__ */ jsxs5(Box5, { height: viewHeight, children: [
837
+ /* @__PURE__ */ jsx6(
838
+ Box5,
839
+ {
840
+ flexDirection: "column",
841
+ paddingX: 1,
842
+ paddingY: 1,
843
+ flexGrow: 1,
844
+ overflow: "hidden",
845
+ children: /* @__PURE__ */ jsx6(Text6, { children: visibleContent })
846
+ }
847
+ ),
848
+ scrollbar && /* @__PURE__ */ jsx6(Box5, { flexDirection: "column", children: scrollbar.map((isThumb, i) => /* @__PURE__ */ jsx6(
849
+ Text6,
850
+ {
851
+ color: isThumb ? "cyan" : "gray",
852
+ dimColor: !isThumb,
853
+ children: isThumb ? "\u2503" : "\u2502"
854
+ },
855
+ i
856
+ )) })
857
+ ] }),
858
+ /* @__PURE__ */ jsxs5(
859
+ Box5,
860
+ {
861
+ flexDirection: "column",
862
+ paddingX: 1,
863
+ borderStyle: "single",
864
+ borderTop: true,
865
+ borderBottom: false,
866
+ borderLeft: false,
867
+ borderRight: false,
868
+ borderColor: "gray",
869
+ children: [
870
+ /* @__PURE__ */ jsx6(Box5, { marginTop: 1, children: /* @__PURE__ */ jsx6(Text6, { color: "gray", children: "Actions" }) }),
871
+ /* @__PURE__ */ jsxs5(Box5, { children: [
872
+ /* @__PURE__ */ jsxs5(Text6, { color: "cyan", bold: true, children: [
873
+ "\u276F",
874
+ " Back"
875
+ ] }),
876
+ /* @__PURE__ */ jsx6(Text6, { color: "gray", children: " - Return to providers" })
877
+ ] }),
878
+ /* @__PURE__ */ jsx6(Box5, { marginTop: 1, height: 1, children: /* @__PURE__ */ jsxs5(Text6, { color: "gray", wrap: "truncate-end", children: [
879
+ "Up/Down Scroll ",
880
+ "\u2022",
881
+ " Enter/q/Esc Back",
882
+ maxScroll > 0 && ` \u2022 ${Math.round(scrollOffset / maxScroll * 100)}%`
883
+ ] }) })
884
+ ]
885
+ }
886
+ )
887
+ ] });
888
+ }
889
+ function SetupPage({ onBack }) {
890
+ const { providers, loading } = useSetupProviders();
891
+ const [selectedProvider, setSelectedProvider] = useState7(null);
892
+ const running = useMemo3(
893
+ () => providers.filter((p) => p.status.running),
894
+ [providers]
895
+ );
896
+ const installed = useMemo3(
897
+ () => providers.filter((p) => p.status.installed && !p.status.running),
898
+ [providers]
899
+ );
900
+ const notInstalled = useMemo3(
901
+ () => providers.filter((p) => !p.status.installed),
902
+ [providers]
903
+ );
904
+ const allProviders = useMemo3(
905
+ () => [...running, ...installed, ...notInstalled],
906
+ [running, installed, notInstalled]
907
+ );
908
+ const totalItems = allProviders.length + 1;
909
+ const backIndex = allProviders.length;
910
+ const [cursorIndex, setCursorIndex] = useState7(0);
911
+ useEffect7(() => {
912
+ setCursorIndex(0);
913
+ }, [allProviders.length]);
914
+ useInput2((input, key) => {
915
+ if (selectedProvider) return;
916
+ if (input === "q" || key.escape) {
917
+ onBack();
918
+ return;
919
+ }
920
+ if (key.upArrow) {
921
+ setCursorIndex((prev) => Math.max(0, prev - 1));
922
+ } else if (key.downArrow) {
923
+ setCursorIndex((prev) => Math.min(totalItems - 1, prev + 1));
924
+ } else if (key.return) {
925
+ if (cursorIndex === backIndex) {
926
+ onBack();
927
+ } else if (allProviders[cursorIndex]) {
928
+ setSelectedProvider(allProviders[cursorIndex].provider.name);
929
+ }
930
+ }
931
+ });
932
+ if (selectedProvider) {
933
+ const found = providers.find((p) => p.provider.name === selectedProvider);
934
+ if (found) {
935
+ return /* @__PURE__ */ jsx6(
936
+ ProviderDetailView,
937
+ {
938
+ provider: found.provider,
939
+ onBack: () => setSelectedProvider(null)
940
+ }
941
+ );
942
+ }
943
+ }
944
+ return /* @__PURE__ */ jsx6(Box5, { flexDirection: "column", flexGrow: 1, children: /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
945
+ /* @__PURE__ */ jsx6(Text6, { bold: true, color: "white", underline: true, children: "Manage Providers" }),
946
+ /* @__PURE__ */ jsx6(Text6, { color: "gray", children: "Select a provider to view its setup guide." }),
947
+ loading ? /* @__PURE__ */ jsxs5(Box5, { marginTop: 1, children: [
948
+ /* @__PURE__ */ jsx6(Text6, { color: "cyan", children: /* @__PURE__ */ jsx6(Spinner3, { type: "dots" }) }),
949
+ /* @__PURE__ */ jsx6(Text6, { children: " Detecting providers..." })
950
+ ] }) : /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", marginTop: 1, children: [
951
+ running.length > 0 && /* @__PURE__ */ jsxs5(Fragment2, { children: [
952
+ /* @__PURE__ */ jsx6(Text6, { bold: true, color: "green", children: "Running" }),
953
+ running.map(({ provider }, i) => {
954
+ const index = i;
955
+ const isSelected = index === cursorIndex;
956
+ return /* @__PURE__ */ jsxs5(
957
+ Box5,
958
+ {
959
+ flexDirection: "column",
960
+ marginTop: i > 0 ? 1 : 0,
961
+ children: [
962
+ /* @__PURE__ */ jsx6(Box5, { children: /* @__PURE__ */ jsxs5(
963
+ Text6,
964
+ {
965
+ color: isSelected ? "cyan" : "white",
966
+ bold: isSelected,
967
+ children: [
968
+ isSelected ? "\u276F" : " ",
969
+ " ",
970
+ "\u25CF",
971
+ " ",
972
+ provider.displayName
973
+ ]
974
+ }
975
+ ) }),
976
+ /* @__PURE__ */ jsxs5(Text6, { color: "gray", wrap: "wrap", children: [
977
+ " ",
978
+ provider.description
979
+ ] })
980
+ ]
981
+ },
982
+ provider.name
983
+ );
984
+ })
985
+ ] }),
986
+ installed.length > 0 && /* @__PURE__ */ jsxs5(
987
+ Box5,
988
+ {
989
+ flexDirection: "column",
990
+ marginTop: running.length > 0 ? 1 : 0,
991
+ children: [
992
+ /* @__PURE__ */ jsx6(Text6, { bold: true, color: "yellow", children: "Installed" }),
993
+ installed.map(({ provider, status }, i) => {
994
+ const index = running.length + i;
995
+ const isSelected = index === cursorIndex;
996
+ return /* @__PURE__ */ jsxs5(
997
+ Box5,
998
+ {
999
+ flexDirection: "column",
1000
+ marginTop: i > 0 ? 1 : 0,
1001
+ children: [
1002
+ /* @__PURE__ */ jsx6(Box5, { children: /* @__PURE__ */ jsxs5(
1003
+ Text6,
1004
+ {
1005
+ color: isSelected ? "cyan" : "white",
1006
+ bold: isSelected,
1007
+ children: [
1008
+ isSelected ? "\u276F" : " ",
1009
+ " ",
1010
+ "\u25CB",
1011
+ " ",
1012
+ provider.displayName
1013
+ ]
1014
+ }
1015
+ ) }),
1016
+ /* @__PURE__ */ jsxs5(Text6, { color: "gray", wrap: "wrap", children: [
1017
+ " ",
1018
+ provider.description
1019
+ ] })
1020
+ ]
1021
+ },
1022
+ provider.name
1023
+ );
1024
+ })
1025
+ ]
1026
+ }
1027
+ ),
1028
+ notInstalled.length > 0 && /* @__PURE__ */ jsxs5(
1029
+ Box5,
1030
+ {
1031
+ flexDirection: "column",
1032
+ marginTop: running.length > 0 || installed.length > 0 ? 1 : 0,
1033
+ children: [
1034
+ /* @__PURE__ */ jsx6(Text6, { bold: true, color: "gray", children: "Not Installed" }),
1035
+ notInstalled.map(({ provider }, i) => {
1036
+ const index = running.length + installed.length + i;
1037
+ const isSelected = index === cursorIndex;
1038
+ return /* @__PURE__ */ jsxs5(
1039
+ Box5,
1040
+ {
1041
+ flexDirection: "column",
1042
+ marginTop: i > 0 ? 1 : 0,
1043
+ children: [
1044
+ /* @__PURE__ */ jsx6(Box5, { children: /* @__PURE__ */ jsxs5(
1045
+ Text6,
1046
+ {
1047
+ color: isSelected ? "cyan" : "white",
1048
+ bold: isSelected,
1049
+ children: [
1050
+ isSelected ? "\u276F" : " ",
1051
+ " ",
1052
+ provider.displayName
1053
+ ]
1054
+ }
1055
+ ) }),
1056
+ /* @__PURE__ */ jsxs5(Text6, { color: "gray", wrap: "wrap", children: [
1057
+ " ",
1058
+ provider.description
1059
+ ] })
1060
+ ]
1061
+ },
1062
+ provider.name
1063
+ );
1064
+ })
1065
+ ]
1066
+ }
1067
+ ),
1068
+ /* @__PURE__ */ jsx6(Box5, { marginTop: 1, children: /* @__PURE__ */ jsxs5(
1069
+ Text6,
1070
+ {
1071
+ color: cursorIndex === backIndex ? "cyan" : "white",
1072
+ bold: cursorIndex === backIndex,
1073
+ children: [
1074
+ cursorIndex === backIndex ? "\u276F" : " ",
1075
+ " Back"
1076
+ ]
1077
+ }
1078
+ ) })
1079
+ ] }),
1080
+ /* @__PURE__ */ jsx6(Box5, { marginTop: 1, children: /* @__PURE__ */ jsxs5(Text6, { color: "gray", children: [
1081
+ "Up/Down Navigate ",
1082
+ "\u2022",
1083
+ " Enter Select ",
1084
+ "\u2022",
1085
+ " q/Esc Back"
1086
+ ] }) })
1087
+ ] }) });
1088
+ }
1089
+
1090
+ // src/tui/interfaces/pages/InterfacesPage.tsx
1091
+ import { useState as useState12, useMemo as useMemo5, useEffect as useEffect12, useRef as useRef7 } from "react";
1092
+ import { Box as Box8, Text as Text9, useInput as useInput5 } from "ink";
1093
+ import Spinner5 from "ink-spinner";
1094
+
1095
+ // src/tui/interfaces/hooks/useEditorSessions.ts
1096
+ import { useState as useState8, useEffect as useEffect8, useCallback as useCallback6, useRef as useRef4 } from "react";
1097
+ function useEditorSessions() {
1098
+ const [sessions, setSessions] = useState8([]);
1099
+ const [loading, setLoading] = useState8(true);
1100
+ const [error, setError] = useState8(null);
1101
+ const [refreshStatus, setRefreshStatus] = useState8("idle");
1102
+ const initialLoadDone = useRef4(false);
1103
+ const timerRef = useRef4();
1104
+ const refresh = useCallback6(async () => {
1105
+ if (!initialLoadDone.current) {
1106
+ setLoading(true);
1107
+ } else {
1108
+ setRefreshStatus("refreshing");
1109
+ }
1110
+ setError(null);
1111
+ try {
1112
+ const data = await getEditorSessions();
1113
+ setSessions(data);
1114
+ initialLoadDone.current = true;
1115
+ setRefreshStatus("refreshed");
1116
+ clearTimeout(timerRef.current);
1117
+ timerRef.current = setTimeout(() => setRefreshStatus("idle"), 1500);
1118
+ } catch (err) {
1119
+ setError(err instanceof Error ? err.message : "Failed to fetch sessions");
1120
+ setRefreshStatus("idle");
1121
+ } finally {
1122
+ setLoading(false);
1123
+ }
1124
+ }, []);
1125
+ useEffect8(() => {
1126
+ refresh();
1127
+ }, [refresh]);
1128
+ useEffect8(() => {
1129
+ return () => clearTimeout(timerRef.current);
1130
+ }, []);
1131
+ return { sessions, loading, error, refreshStatus, refresh };
1132
+ }
1133
+
1134
+ // src/tui/interfaces/hooks/useLocalInterface.ts
1135
+ import { useState as useState9, useCallback as useCallback7, useRef as useRef5, useEffect as useEffect9 } from "react";
1136
+ import { spawn } from "child_process";
1137
+ import crypto from "crypto";
1138
+ import fs from "fs";
1139
+ import path from "path";
1140
+ var INTERFACE_SCAFFOLD_REPO = "https://github.com/mindstudio-ai/spa-bundle-scaffold";
1141
+ var SCRIPT_SCAFFOLD_REPO = "https://github.com/mindstudio-ai/script-scaffold";
1142
+ var MAX_OUTPUT_LINES = 500;
1143
+ function useLocalInterface({
1144
+ mode,
1145
+ appId,
1146
+ stepId,
1147
+ workflowId,
1148
+ sessionId
1149
+ }) {
1150
+ const key = `${appId}:${stepId}`;
1151
+ const [hasLocalCopy, setHasLocalCopy] = useState9(() => {
1152
+ const existing = getLocalInterfacePath(key);
1153
+ if (!existing) return false;
1154
+ try {
1155
+ return fs.existsSync(existing);
1156
+ } catch {
1157
+ return false;
1158
+ }
1159
+ });
1160
+ const [phase, setPhase] = useState9("idle");
1161
+ const [outputLines, setOutputLines] = useState9([]);
1162
+ const [errorMessage, setErrorMessage] = useState9(null);
1163
+ const processRef = useRef5(null);
1164
+ const mountedRef = useRef5(true);
1165
+ const stoppedRef = useRef5(false);
1166
+ useEffect9(() => {
1167
+ mountedRef.current = true;
1168
+ return () => {
1169
+ mountedRef.current = false;
1170
+ if (processRef.current) {
1171
+ processRef.current.kill("SIGTERM");
1172
+ processRef.current = null;
1173
+ }
1174
+ };
1175
+ }, []);
1176
+ const appendOutput = useCallback7((line) => {
1177
+ if (!mountedRef.current) return;
1178
+ setOutputLines((prev) => {
1179
+ const next = [...prev, line];
1180
+ return next.length > MAX_OUTPUT_LINES ? next.slice(next.length - MAX_OUTPUT_LINES) : next;
1181
+ });
1182
+ }, []);
1183
+ const runCommand = useCallback7(
1184
+ (command, args, options = {}) => {
1185
+ return new Promise((resolve, reject) => {
1186
+ const fullCommand = [command, ...args].join(" ");
1187
+ const proc = spawn(fullCommand, [], {
1188
+ cwd: options.cwd,
1189
+ shell: true,
1190
+ env: { ...process.env, FORCE_COLOR: "1", ...options.env }
1191
+ });
1192
+ processRef.current = proc;
1193
+ const handleData = (data) => {
1194
+ const lines = data.toString().split("\n");
1195
+ for (const line of lines) {
1196
+ if (line.length > 0) {
1197
+ appendOutput(line);
1198
+ }
1199
+ }
1200
+ };
1201
+ proc.stdout?.on("data", handleData);
1202
+ proc.stderr?.on("data", handleData);
1203
+ proc.on("close", (code) => {
1204
+ processRef.current = null;
1205
+ resolve(code ?? 0);
1206
+ });
1207
+ proc.on("error", (err) => {
1208
+ processRef.current = null;
1209
+ reject(err);
1210
+ });
1211
+ });
1212
+ },
1213
+ [appendOutput]
1214
+ );
1215
+ const getScaffoldRepo = () => mode === "script" ? SCRIPT_SCAFFOLD_REPO : INTERFACE_SCAFFOLD_REPO;
1216
+ const getDirPrefix = () => mode === "script" ? "script" : "interface";
1217
+ const getDevLocalArgs = () => {
1218
+ const env = {};
1219
+ if (getEnvironment() === "local") {
1220
+ env.MINDSTUDIO_API_URL = getApiBaseUrl();
1221
+ }
1222
+ if (mode === "script") {
1223
+ env.MINDSTUDIO_API_KEY = getApiKey() ?? "";
1224
+ return {
1225
+ args: ["run", "dev:local", "--", "--app", appId, "--workflow", workflowId, "--step", stepId],
1226
+ env
1227
+ };
1228
+ }
1229
+ return {
1230
+ args: ["run", "dev:local", "--", sessionId ?? ""],
1231
+ env
1232
+ };
1233
+ };
1234
+ const start = useCallback7(() => {
1235
+ setErrorMessage(null);
1236
+ setOutputLines([]);
1237
+ stoppedRef.current = false;
1238
+ const run = async () => {
1239
+ const localPath = getLocalInterfacePath(key);
1240
+ const dirExists = localPath && fs.existsSync(localPath);
1241
+ try {
1242
+ if (!dirExists) {
1243
+ setPhase("cloning");
1244
+ const interfacesDir = getLocalInterfacesDir();
1245
+ fs.mkdirSync(interfacesDir, { recursive: true });
1246
+ const shortId = crypto.randomBytes(4).toString("hex");
1247
+ const dirName = `${getDirPrefix()}-${shortId}`;
1248
+ const targetDir = path.join(interfacesDir, dirName);
1249
+ appendOutput(`Cloning scaffold into ${targetDir}...`);
1250
+ const cloneCode = await runCommand("git", [
1251
+ "clone",
1252
+ "--depth",
1253
+ "1",
1254
+ getScaffoldRepo(),
1255
+ targetDir
1256
+ ]);
1257
+ if (!mountedRef.current) return;
1258
+ if (cloneCode !== 0) {
1259
+ throw new Error(`git clone failed with exit code ${cloneCode}`);
1260
+ }
1261
+ setPhase("installing");
1262
+ appendOutput("Installing dependencies...");
1263
+ const installCode = await runCommand("npm", ["install"], {
1264
+ cwd: targetDir
1265
+ });
1266
+ if (!mountedRef.current) return;
1267
+ if (installCode !== 0) {
1268
+ throw new Error(`npm install failed with exit code ${installCode}`);
1269
+ }
1270
+ setLocalInterfacePath(key, targetDir);
1271
+ setHasLocalCopy(true);
1272
+ setPhase("running");
1273
+ const { args, env } = getDevLocalArgs();
1274
+ appendOutput("Starting local dev server...");
1275
+ await runCommand("npm", args, { cwd: targetDir, env });
1276
+ if (mountedRef.current) {
1277
+ setPhase("idle");
1278
+ setOutputLines([]);
1279
+ }
1280
+ } else {
1281
+ setPhase("running");
1282
+ const { args, env } = getDevLocalArgs();
1283
+ appendOutput("Starting local dev server...");
1284
+ await runCommand("npm", args, { cwd: localPath, env });
1285
+ if (mountedRef.current) {
1286
+ setPhase("idle");
1287
+ setOutputLines([]);
1288
+ }
1289
+ }
1290
+ } catch (err) {
1291
+ if (mountedRef.current) {
1292
+ setPhase("error");
1293
+ setErrorMessage(
1294
+ err instanceof Error ? err.message : "Unknown error"
1295
+ );
1296
+ }
1297
+ }
1298
+ };
1299
+ run();
1300
+ }, [key, mode, appId, stepId, workflowId, sessionId, appendOutput, runCommand]);
1301
+ const stop = useCallback7(() => {
1302
+ stoppedRef.current = true;
1303
+ if (processRef.current) {
1304
+ processRef.current.kill("SIGTERM");
1305
+ const proc = processRef.current;
1306
+ setTimeout(() => {
1307
+ if (proc && !proc.killed) {
1308
+ proc.kill("SIGKILL");
1309
+ }
1310
+ }, 2e3);
1311
+ processRef.current = null;
1312
+ }
1313
+ setPhase("idle");
1314
+ }, []);
1315
+ const deleteLocalCopy = useCallback7(() => {
1316
+ const localPath = getLocalInterfacePath(key);
1317
+ if (!localPath) return;
1318
+ setPhase("deleting");
1319
+ setOutputLines([]);
1320
+ appendOutput(`Deleting ${localPath}...`);
1321
+ try {
1322
+ fs.rmSync(localPath, { recursive: true, force: true });
1323
+ deleteLocalInterfacePath(key);
1324
+ setHasLocalCopy(false);
1325
+ appendOutput("Deleted successfully.");
1326
+ } catch (err) {
1327
+ setErrorMessage(
1328
+ err instanceof Error ? err.message : "Failed to delete"
1329
+ );
1330
+ }
1331
+ setPhase("idle");
1332
+ }, [key, appendOutput]);
1333
+ return {
1334
+ phase,
1335
+ hasLocalCopy,
1336
+ localPath: getLocalInterfacePath(key),
1337
+ outputLines,
1338
+ errorMessage,
1339
+ start,
1340
+ stop,
1341
+ deleteLocalCopy
1342
+ };
1343
+ }
1344
+
1345
+ // src/tui/interfaces/pages/InterfaceSessionView.tsx
1346
+ import { useState as useState10, useEffect as useEffect10 } from "react";
1347
+ import { Box as Box6, Text as Text7, useInput as useInput3 } from "ink";
1348
+ import os2 from "os";
1349
+ import open from "open";
1350
+ import { Fragment as Fragment3, jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
1351
+ function InterfaceSessionView({
1352
+ item,
1353
+ onStart,
1354
+ onDelete,
1355
+ onBack,
1356
+ hasLocalCopy,
1357
+ localPath
1358
+ }) {
1359
+ const menuItems = [
1360
+ { id: "start", label: "Start Locally" }
1361
+ ];
1362
+ if (hasLocalCopy) {
1363
+ menuItems.push({ id: "reveal", label: "Open Folder" });
1364
+ menuItems.push({ id: "delete", label: "Delete Local Copy" });
1365
+ }
1366
+ menuItems.push({ id: "back", label: "Back" });
1367
+ const [cursorIndex, setCursorIndex] = useState10(0);
1368
+ useEffect10(() => {
1369
+ setCursorIndex(0);
1370
+ }, [hasLocalCopy]);
1371
+ useInput3((input, key) => {
1372
+ if (input === "q" || key.escape) {
1373
+ onBack();
1374
+ return;
1375
+ }
1376
+ if (key.upArrow) {
1377
+ setCursorIndex((prev) => Math.max(0, prev - 1));
1378
+ } else if (key.downArrow) {
1379
+ setCursorIndex((prev) => Math.min(menuItems.length - 1, prev + 1));
1380
+ } else if (key.return) {
1381
+ const selected = menuItems[cursorIndex];
1382
+ if (!selected) return;
1383
+ switch (selected.id) {
1384
+ case "start":
1385
+ onStart();
1386
+ break;
1387
+ case "reveal":
1388
+ if (localPath) {
1389
+ open(localPath);
1390
+ }
1391
+ break;
1392
+ case "delete":
1393
+ onDelete();
1394
+ break;
1395
+ case "back":
1396
+ onBack();
1397
+ break;
1398
+ }
1399
+ }
1400
+ });
1401
+ const name = `${item.step.workflowName} - ${item.step.displayName}`;
1402
+ const displayPath = localPath?.replace(os2.homedir(), "~");
1403
+ let sessionInfo = null;
1404
+ if (item.kind === "interface") {
1405
+ const hotUpdateDomain = item.step.spaEditorSession?.hotUpdateDomain ?? "";
1406
+ sessionInfo = hotUpdateDomain.replace(/^https?:\/\//, "").split(".")[0] || null;
1407
+ }
1408
+ return /* @__PURE__ */ jsx7(Box6, { flexDirection: "column", flexGrow: 1, children: /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
1409
+ /* @__PURE__ */ jsx7(Text7, { bold: true, color: "white", underline: true, children: name }),
1410
+ /* @__PURE__ */ jsxs6(Box6, { marginTop: 1, flexDirection: "column", children: [
1411
+ sessionInfo && /* @__PURE__ */ jsxs6(Text7, { color: "gray", children: [
1412
+ "Session: ",
1413
+ sessionInfo
1414
+ ] }),
1415
+ hasLocalCopy && localPath ? /* @__PURE__ */ jsxs6(Fragment3, { children: [
1416
+ /* @__PURE__ */ jsx7(Text7, { color: "green", children: "Local copy exists" }),
1417
+ /* @__PURE__ */ jsxs6(Text7, { color: "gray", children: [
1418
+ "Path: ",
1419
+ displayPath
1420
+ ] })
1421
+ ] }) : /* @__PURE__ */ jsx7(Text7, { color: "yellow", children: 'No local copy. "Start Locally" will clone the scaffold and install dependencies.' })
1422
+ ] }),
1423
+ /* @__PURE__ */ jsx7(Box6, { marginTop: 1, flexDirection: "column", children: menuItems.map((menuItem, i) => {
1424
+ const isSelected = i === cursorIndex;
1425
+ return /* @__PURE__ */ jsxs6(
1426
+ Text7,
1427
+ {
1428
+ color: isSelected ? "cyan" : "white",
1429
+ bold: isSelected,
1430
+ children: [
1431
+ isSelected ? "\u276F" : " ",
1432
+ " ",
1433
+ menuItem.label
1434
+ ]
1435
+ },
1436
+ menuItem.id
1437
+ );
1438
+ }) }),
1439
+ /* @__PURE__ */ jsx7(Box6, { marginTop: 1, children: /* @__PURE__ */ jsxs6(Text7, { color: "gray", children: [
1440
+ "Up/Down Navigate ",
1441
+ "\u2022",
1442
+ " Enter Select ",
1443
+ "\u2022",
1444
+ " q/Esc Back"
1445
+ ] }) })
1446
+ ] }) });
1447
+ }
1448
+
1449
+ // src/tui/interfaces/pages/InterfaceRunningView.tsx
1450
+ import { useState as useState11, useMemo as useMemo4, useRef as useRef6, useEffect as useEffect11 } from "react";
1451
+ import { Box as Box7, Text as Text8, useInput as useInput4, useStdout as useStdout6 } from "ink";
1452
+ import { execSync } from "child_process";
1453
+ import os3 from "os";
1454
+ import open2 from "open";
1455
+ import Spinner4 from "ink-spinner";
1456
+ import { jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
1457
+ function copyToClipboard(text) {
1458
+ try {
1459
+ if (process.platform === "darwin") {
1460
+ execSync("pbcopy", { input: text });
1461
+ } else if (process.platform === "win32") {
1462
+ execSync("clip", { input: text });
1463
+ } else {
1464
+ execSync("xclip -selection clipboard", { input: text });
1465
+ }
1466
+ return true;
1467
+ } catch {
1468
+ return false;
1469
+ }
1470
+ }
1471
+ function getPhaseLabel(phase) {
1472
+ switch (phase) {
1473
+ case "cloning":
1474
+ return { text: "Cloning scaffold...", color: "cyan", showSpinner: true };
1475
+ case "installing":
1476
+ return { text: "Installing dependencies...", color: "cyan", showSpinner: true };
1477
+ case "running":
1478
+ return { text: "Dev server running", color: "green", showSpinner: true };
1479
+ case "error":
1480
+ return { text: "Error", color: "red", showSpinner: false };
1481
+ case "deleting":
1482
+ return { text: "Deleting local copy...", color: "yellow", showSpinner: true };
1483
+ default:
1484
+ return { text: "Idle", color: "gray", showSpinner: false };
1485
+ }
1486
+ }
1487
+ function InterfaceRunningView({
1488
+ name,
1489
+ phase,
1490
+ outputLines,
1491
+ errorMessage,
1492
+ localPath,
1493
+ onStop,
1494
+ onBack
1495
+ }) {
1496
+ const { stdout } = useStdout6();
1497
+ const termHeight = (stdout?.rows ?? 24) - 4;
1498
+ const isActive = phase === "cloning" || phase === "installing" || phase === "running" || phase === "deleting";
1499
+ const displayPath = localPath?.replace(os3.homedir(), "~");
1500
+ const menuItems = useMemo4(() => {
1501
+ const items = [];
1502
+ if (isActive && displayPath) {
1503
+ items.push({ id: "claude", label: "Copy Claude Code Command", copyValue: `cd ${displayPath} && claude` });
1504
+ items.push({ id: "codex", label: "Copy Codex Command", copyValue: `cd ${displayPath} && codex` });
1505
+ items.push({ id: "reveal", label: "Open Folder" });
1506
+ }
1507
+ items.push({ id: "action", label: isActive ? "Stop" : "Back" });
1508
+ return items;
1509
+ }, [isActive, displayPath]);
1510
+ const [cursorIndex, setCursorIndex] = useState11(0);
1511
+ const [copiedId, setCopiedId] = useState11(null);
1512
+ const copiedTimerRef = useRef6();
1513
+ useEffect11(() => {
1514
+ return () => clearTimeout(copiedTimerRef.current);
1515
+ }, []);
1516
+ const headerHeight = 14;
1517
+ const menuHeight = menuItems.length;
1518
+ const chromeLines = 7 + menuHeight;
1519
+ const logHeight = Math.max(3, termHeight - headerHeight - chromeLines);
1520
+ const maxScroll = Math.max(0, outputLines.length - logHeight);
1521
+ const effectiveOffset = maxScroll;
1522
+ const copyItem = (item) => {
1523
+ if (!item.copyValue) return;
1524
+ const success = copyToClipboard(item.copyValue);
1525
+ if (success) {
1526
+ setCopiedId(item.id);
1527
+ clearTimeout(copiedTimerRef.current);
1528
+ copiedTimerRef.current = setTimeout(() => setCopiedId(null), 2e3);
1529
+ }
1530
+ };
1531
+ useInput4((input, key) => {
1532
+ if (key.upArrow) {
1533
+ setCursorIndex((prev) => Math.max(0, prev - 1));
1534
+ } else if (key.downArrow) {
1535
+ setCursorIndex((prev) => Math.min(menuItems.length - 1, prev + 1));
1536
+ } else if (key.return) {
1537
+ const item = menuItems[cursorIndex];
1538
+ if (!item) return;
1539
+ if (item.copyValue) {
1540
+ copyItem(item);
1541
+ } else if (item.id === "reveal" && localPath) {
1542
+ open2(localPath);
1543
+ } else if (isActive) {
1544
+ onStop();
1545
+ } else {
1546
+ onBack();
1547
+ }
1548
+ } else if (input === "q" || key.escape) {
1549
+ if (isActive) {
1550
+ onStop();
1551
+ } else {
1552
+ onBack();
1553
+ }
1554
+ }
1555
+ });
1556
+ const visibleLines = outputLines.slice(
1557
+ effectiveOffset,
1558
+ effectiveOffset + logHeight
1559
+ );
1560
+ const phaseInfo = getPhaseLabel(phase);
1561
+ return /* @__PURE__ */ jsx8(Box7, { flexDirection: "column", flexGrow: 1, children: /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
1562
+ /* @__PURE__ */ jsx8(Text8, { bold: true, color: "white", underline: true, children: name }),
1563
+ /* @__PURE__ */ jsxs7(Box7, { marginTop: 1, children: [
1564
+ phaseInfo.showSpinner && /* @__PURE__ */ jsxs7(Text8, { color: phaseInfo.color, children: [
1565
+ /* @__PURE__ */ jsx8(Spinner4, { type: "dots" }),
1566
+ " "
1567
+ ] }),
1568
+ /* @__PURE__ */ jsx8(Text8, { color: phaseInfo.color, children: phaseInfo.text })
1569
+ ] }),
1570
+ errorMessage && /* @__PURE__ */ jsx8(Box7, { marginTop: 1, children: /* @__PURE__ */ jsx8(Text8, { color: "red", children: errorMessage }) }),
1571
+ /* @__PURE__ */ jsx8(Box7, { marginTop: 1, height: logHeight, children: /* @__PURE__ */ jsx8(Box7, { flexDirection: "column", flexGrow: 1, overflow: "hidden", children: visibleLines.map((line, i) => /* @__PURE__ */ jsx8(Text8, { wrap: "truncate-end", color: "gray", children: line }, effectiveOffset + i)) }) }),
1572
+ /* @__PURE__ */ jsx8(Box7, { marginTop: 1, flexDirection: "column", children: menuItems.map((item, i) => {
1573
+ const isSelected = i === cursorIndex;
1574
+ const isCopied = copiedId === item.id;
1575
+ return /* @__PURE__ */ jsxs7(Box7, { children: [
1576
+ /* @__PURE__ */ jsxs7(Text8, { color: isSelected ? "cyan" : "white", bold: isSelected, children: [
1577
+ isSelected ? "\u276F" : " ",
1578
+ " ",
1579
+ item.label
1580
+ ] }),
1581
+ isCopied && /* @__PURE__ */ jsxs7(Text8, { color: "green", children: [
1582
+ " ",
1583
+ "\u2713",
1584
+ " Copied!"
1585
+ ] })
1586
+ ] }, item.id);
1587
+ }) }),
1588
+ /* @__PURE__ */ jsx8(Box7, { marginTop: 1, height: 1, children: /* @__PURE__ */ jsxs7(Text8, { color: "gray", wrap: "truncate-end", children: [
1589
+ "Up/Down Navigate ",
1590
+ "\u2022",
1591
+ " Enter Select ",
1592
+ "\u2022",
1593
+ " q/Esc ",
1594
+ isActive ? "Stop" : "Back"
1595
+ ] }) })
1596
+ ] }) });
1597
+ }
1598
+
1599
+ // src/tui/interfaces/pages/InterfacesPage.tsx
1600
+ import { Fragment as Fragment4, jsx as jsx9, jsxs as jsxs8 } from "react/jsx-runtime";
1601
+ function getSessionStatus(item) {
1602
+ if (item.kind === "script") return "running";
1603
+ const status = item.step.spaEditorSession?.status;
1604
+ if (status === "running" || status === "compiling") return status;
1605
+ if (status === "starting") return "starting";
1606
+ return "stopped";
1607
+ }
1608
+ function isItemSelectable(item) {
1609
+ const status = getSessionStatus(item);
1610
+ return status === "running" || status === "compiling";
1611
+ }
1612
+ function getStatusLabel(status) {
1613
+ switch (status) {
1614
+ case "running":
1615
+ case "compiling":
1616
+ return { text: "Online", color: "green" };
1617
+ case "starting":
1618
+ return { text: "Starting", color: "yellow" };
1619
+ case "stopped":
1620
+ return { text: "Offline", color: "gray" };
1621
+ }
1622
+ }
1623
+ function getRefreshSuffix(status) {
1624
+ switch (status) {
1625
+ case "refreshing":
1626
+ return "Refreshing...";
1627
+ case "refreshed":
1628
+ return "\u2713 Refreshed";
1629
+ case "idle":
1630
+ return null;
1631
+ }
1632
+ }
1633
+ function formatCount(interfaces, scripts) {
1634
+ const parts = [];
1635
+ if (interfaces > 0) {
1636
+ parts.push(`${interfaces} Interface${interfaces !== 1 ? "s" : ""}`);
1637
+ }
1638
+ if (scripts > 0) {
1639
+ parts.push(`${scripts} Script${scripts !== 1 ? "s" : ""}`);
1640
+ }
1641
+ return parts.join(", ");
1642
+ }
1643
+ function OfflineView({
1644
+ item,
1645
+ onBack
1646
+ }) {
1647
+ useInput5((input, key) => {
1648
+ if (input === "q" || key.escape || key.return) {
1649
+ onBack();
1650
+ }
1651
+ });
1652
+ const name = item.kind === "interface" ? `${item.step.workflowName} - ${item.step.displayName}` : `${item.step.workflowName} - ${item.step.displayName}`;
1653
+ return /* @__PURE__ */ jsx9(Box8, { flexDirection: "column", flexGrow: 1, children: /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
1654
+ /* @__PURE__ */ jsx9(Text9, { bold: true, color: "white", underline: true, children: name }),
1655
+ /* @__PURE__ */ jsxs8(Box8, { marginTop: 1, flexDirection: "column", children: [
1656
+ /* @__PURE__ */ jsx9(Text9, { color: "yellow", children: "This interface is offline." }),
1657
+ /* @__PURE__ */ jsx9(Text9, { color: "gray", children: "Start the interface designer in MindStudio to connect to it." })
1658
+ ] }),
1659
+ /* @__PURE__ */ jsx9(Box8, { marginTop: 1, children: /* @__PURE__ */ jsxs8(Text9, { color: "cyan", bold: true, children: [
1660
+ "\u276F",
1661
+ " Back"
1662
+ ] }) }),
1663
+ /* @__PURE__ */ jsx9(Box8, { marginTop: 1, children: /* @__PURE__ */ jsx9(Text9, { color: "gray", children: "Enter/q/Esc Back" }) })
1664
+ ] }) });
1665
+ }
1666
+ function AgentListView({
1667
+ sessions,
1668
+ onBack,
1669
+ onSelectAgent,
1670
+ onRefresh,
1671
+ refreshStatus
1672
+ }) {
1673
+ const refreshIndex = sessions.length;
1674
+ const backIndex = sessions.length + 1;
1675
+ const totalItems = sessions.length + 2;
1676
+ const [cursorIndex, setCursorIndex] = useState12(0);
1677
+ useEffect12(() => {
1678
+ setCursorIndex(sessions.length > 0 ? 0 : backIndex);
1679
+ }, [sessions.length, backIndex]);
1680
+ useInput5((input, key) => {
1681
+ if (input === "q" || key.escape) {
1682
+ onBack();
1683
+ return;
1684
+ }
1685
+ if (key.upArrow) {
1686
+ setCursorIndex((prev) => Math.max(0, prev - 1));
1687
+ } else if (key.downArrow) {
1688
+ setCursorIndex((prev) => Math.min(totalItems - 1, prev + 1));
1689
+ } else if (key.return) {
1690
+ if (cursorIndex === backIndex) {
1691
+ onBack();
1692
+ } else if (cursorIndex === refreshIndex) {
1693
+ onRefresh();
1694
+ } else if (sessions[cursorIndex]) {
1695
+ onSelectAgent(sessions[cursorIndex].appId);
1696
+ }
1697
+ }
1698
+ });
1699
+ return /* @__PURE__ */ jsx9(Box8, { flexDirection: "column", flexGrow: 1, children: /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
1700
+ /* @__PURE__ */ jsx9(Text9, { bold: true, color: "white", underline: true, children: "Choose an Agent" }),
1701
+ sessions.length === 0 ? /* @__PURE__ */ jsxs8(Box8, { marginTop: 1, flexDirection: "column", children: [
1702
+ /* @__PURE__ */ jsx9(Text9, { color: "yellow", children: "No active editor sessions." }),
1703
+ /* @__PURE__ */ jsx9(Text9, { color: "gray", children: "Open an app in MindStudio's editor to see sessions here." })
1704
+ ] }) : /* @__PURE__ */ jsx9(Box8, { flexDirection: "column", marginTop: 1, children: sessions.map((session, i) => {
1705
+ const isSelected = i === cursorIndex;
1706
+ const stats = formatCount(
1707
+ session.customInterfaceSteps.length,
1708
+ session.scriptSteps.length
1709
+ );
1710
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginTop: i > 0 ? 1 : 0, children: [
1711
+ /* @__PURE__ */ jsxs8(Box8, { children: [
1712
+ /* @__PURE__ */ jsxs8(Text9, { color: isSelected ? "cyan" : "white", bold: isSelected, children: [
1713
+ isSelected ? "\u276F" : " ",
1714
+ " ",
1715
+ session.appName
1716
+ ] }),
1717
+ isSelected && /* @__PURE__ */ jsx9(Text9, { color: "gray", children: " - Connect to this Agent" })
1718
+ ] }),
1719
+ /* @__PURE__ */ jsxs8(Text9, { color: "gray", children: [
1720
+ " ",
1721
+ "https://app.mindstudio.ai/agents/",
1722
+ session.appId,
1723
+ "/edit"
1724
+ ] }),
1725
+ /* @__PURE__ */ jsxs8(Text9, { color: "gray", children: [
1726
+ " ",
1727
+ stats
1728
+ ] })
1729
+ ] }, session.appId);
1730
+ }) }),
1731
+ /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginTop: 1, children: [
1732
+ /* @__PURE__ */ jsxs8(Box8, { children: [
1733
+ /* @__PURE__ */ jsxs8(
1734
+ Text9,
1735
+ {
1736
+ color: cursorIndex === refreshIndex ? "cyan" : "white",
1737
+ bold: cursorIndex === refreshIndex,
1738
+ children: [
1739
+ cursorIndex === refreshIndex ? "\u276F" : " ",
1740
+ " Refresh"
1741
+ ]
1742
+ }
1743
+ ),
1744
+ getRefreshSuffix(refreshStatus) && /* @__PURE__ */ jsxs8(Text9, { color: "gray", children: [
1745
+ " ",
1746
+ getRefreshSuffix(refreshStatus)
1747
+ ] })
1748
+ ] }),
1749
+ /* @__PURE__ */ jsxs8(
1750
+ Text9,
1751
+ {
1752
+ color: cursorIndex === backIndex ? "cyan" : "white",
1753
+ bold: cursorIndex === backIndex,
1754
+ children: [
1755
+ cursorIndex === backIndex ? "\u276F" : " ",
1756
+ " Back"
1757
+ ]
1758
+ }
1759
+ )
1760
+ ] }),
1761
+ /* @__PURE__ */ jsx9(Box8, { marginTop: 1, children: /* @__PURE__ */ jsxs8(Text9, { color: "gray", children: [
1762
+ "Up/Down Navigate ",
1763
+ "\u2022",
1764
+ " Enter Select ",
1765
+ "\u2022",
1766
+ " q/Esc Back"
1767
+ ] }) })
1768
+ ] }) });
1769
+ }
1770
+ function AgentDetailView({
1771
+ session,
1772
+ onBack,
1773
+ onSelect,
1774
+ onRefresh,
1775
+ refreshStatus
1776
+ }) {
1777
+ const [offlineItem, setOfflineItem] = useState12(null);
1778
+ useEffect12(() => {
1779
+ onRefresh();
1780
+ }, []);
1781
+ const interfaces = useMemo5(
1782
+ () => session.customInterfaceSteps.map((step) => ({
1783
+ kind: "interface",
1784
+ appId: session.appId,
1785
+ appName: session.appName,
1786
+ step
1787
+ })),
1788
+ [session]
1789
+ );
1790
+ const scripts = useMemo5(
1791
+ () => session.scriptSteps.map((step) => ({
1792
+ kind: "script",
1793
+ appId: session.appId,
1794
+ appName: session.appName,
1795
+ step
1796
+ })),
1797
+ [session]
1798
+ );
1799
+ const allItems = useMemo5(
1800
+ () => [...interfaces, ...scripts],
1801
+ [interfaces, scripts]
1802
+ );
1803
+ const refreshIndex = allItems.length;
1804
+ const backIndex = allItems.length + 1;
1805
+ const totalItems = allItems.length + 2;
1806
+ const [cursorIndex, setCursorIndex] = useState12(0);
1807
+ useEffect12(() => {
1808
+ setCursorIndex(0);
1809
+ }, [allItems.length]);
1810
+ useInput5((input, key) => {
1811
+ if (offlineItem) return;
1812
+ if (input === "q" || key.escape) {
1813
+ onBack();
1814
+ return;
1815
+ }
1816
+ if (key.upArrow) {
1817
+ setCursorIndex((prev) => Math.max(0, prev - 1));
1818
+ } else if (key.downArrow) {
1819
+ setCursorIndex((prev) => Math.min(totalItems - 1, prev + 1));
1820
+ } else if (key.return) {
1821
+ if (cursorIndex === backIndex) {
1822
+ onBack();
1823
+ } else if (cursorIndex === refreshIndex) {
1824
+ onRefresh();
1825
+ } else {
1826
+ const item = allItems[cursorIndex];
1827
+ if (item) {
1828
+ if (isItemSelectable(item)) {
1829
+ onSelect(item);
1830
+ } else {
1831
+ setOfflineItem(item);
1832
+ }
1833
+ }
1834
+ }
1835
+ }
1836
+ });
1837
+ if (offlineItem) {
1838
+ return /* @__PURE__ */ jsx9(OfflineView, { item: offlineItem, onBack: () => setOfflineItem(null) });
1839
+ }
1840
+ const scriptsOffset = interfaces.length;
1841
+ return /* @__PURE__ */ jsx9(Box8, { flexDirection: "column", flexGrow: 1, children: /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
1842
+ /* @__PURE__ */ jsx9(Text9, { bold: true, color: "white", underline: true, children: session.appName }),
1843
+ /* @__PURE__ */ jsx9(Text9, { color: "gray", children: "Select an interface or script to connect your local editor." }),
1844
+ /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginTop: 1, children: [
1845
+ interfaces.length > 0 && /* @__PURE__ */ jsxs8(Fragment4, { children: [
1846
+ /* @__PURE__ */ jsx9(Text9, { bold: true, color: "white", underline: true, children: "Interfaces" }),
1847
+ /* @__PURE__ */ jsx9(Box8, { flexDirection: "column", marginTop: 1, children: interfaces.map((item, i) => {
1848
+ const isSelected = i === cursorIndex;
1849
+ const status = getSessionStatus(item);
1850
+ const statusLabel = getStatusLabel(status);
1851
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginTop: i > 0 ? 1 : 0, children: [
1852
+ /* @__PURE__ */ jsxs8(Text9, { color: isSelected ? "cyan" : "white", bold: isSelected, children: [
1853
+ isSelected ? "\u276F" : " ",
1854
+ " ",
1855
+ item.step.workflowName,
1856
+ " - ",
1857
+ item.step.displayName
1858
+ ] }),
1859
+ /* @__PURE__ */ jsx9(Box8, { children: /* @__PURE__ */ jsxs8(Text9, { color: statusLabel.color, children: [
1860
+ " ",
1861
+ statusLabel.text
1862
+ ] }) })
1863
+ ] }, `${item.step.workflowId}:${item.step.stepId}`);
1864
+ }) })
1865
+ ] }),
1866
+ scripts.length > 0 && /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginTop: interfaces.length > 0 ? 1 : 0, children: [
1867
+ /* @__PURE__ */ jsx9(Text9, { bold: true, color: "white", underline: true, children: "Scripts" }),
1868
+ /* @__PURE__ */ jsx9(Box8, { flexDirection: "column", marginTop: 1, children: scripts.map((item, i) => {
1869
+ const index = scriptsOffset + i;
1870
+ const isSelected = index === cursorIndex;
1871
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginTop: i > 0 ? 1 : 0, children: [
1872
+ /* @__PURE__ */ jsxs8(Text9, { color: isSelected ? "cyan" : "white", bold: isSelected, children: [
1873
+ isSelected ? "\u276F" : " ",
1874
+ " ",
1875
+ item.step.workflowName,
1876
+ " - ",
1877
+ item.step.displayName
1878
+ ] }),
1879
+ /* @__PURE__ */ jsxs8(Text9, { color: "gray", children: [
1880
+ " ",
1881
+ item.step.entryFile
1882
+ ] })
1883
+ ] }, `${item.step.workflowId}:${item.step.stepId}`);
1884
+ }) })
1885
+ ] }),
1886
+ /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginTop: 1, children: [
1887
+ /* @__PURE__ */ jsxs8(Box8, { children: [
1888
+ /* @__PURE__ */ jsxs8(
1889
+ Text9,
1890
+ {
1891
+ color: cursorIndex === refreshIndex ? "cyan" : "white",
1892
+ bold: cursorIndex === refreshIndex,
1893
+ children: [
1894
+ cursorIndex === refreshIndex ? "\u276F" : " ",
1895
+ " Refresh"
1896
+ ]
1897
+ }
1898
+ ),
1899
+ getRefreshSuffix(refreshStatus) && /* @__PURE__ */ jsxs8(Text9, { color: "gray", children: [
1900
+ " ",
1901
+ getRefreshSuffix(refreshStatus)
1902
+ ] })
1903
+ ] }),
1904
+ /* @__PURE__ */ jsxs8(
1905
+ Text9,
1906
+ {
1907
+ color: cursorIndex === backIndex ? "cyan" : "white",
1908
+ bold: cursorIndex === backIndex,
1909
+ children: [
1910
+ cursorIndex === backIndex ? "\u276F" : " ",
1911
+ " Back"
1912
+ ]
1913
+ }
1914
+ )
1915
+ ] })
1916
+ ] }),
1917
+ /* @__PURE__ */ jsx9(Box8, { marginTop: 1, children: /* @__PURE__ */ jsxs8(Text9, { color: "gray", children: [
1918
+ "Up/Down Navigate ",
1919
+ "\u2022",
1920
+ " Enter Select ",
1921
+ "\u2022",
1922
+ " q/Esc Back"
1923
+ ] }) })
1924
+ ] }) });
1925
+ }
1926
+ function LocalDevView({
1927
+ item,
1928
+ onBack
1929
+ }) {
1930
+ const mode = item.kind === "script" ? "script" : "interface";
1931
+ let sessionId = "";
1932
+ if (item.kind === "interface") {
1933
+ const hotUpdateDomain = item.step.spaEditorSession?.hotUpdateDomain ?? "";
1934
+ sessionId = hotUpdateDomain.replace(/^https?:\/\//, "").split(".")[0] || "";
1935
+ }
1936
+ const {
1937
+ phase,
1938
+ hasLocalCopy,
1939
+ localPath,
1940
+ outputLines,
1941
+ errorMessage,
1942
+ start,
1943
+ stop,
1944
+ deleteLocalCopy
1945
+ } = useLocalInterface({
1946
+ mode,
1947
+ appId: item.appId,
1948
+ stepId: item.step.stepId,
1949
+ workflowId: item.step.workflowId,
1950
+ sessionId
1951
+ });
1952
+ const name = `${item.step.workflowName} - ${item.step.displayName}`;
1953
+ const isActive = phase === "cloning" || phase === "installing" || phase === "running" || phase === "deleting";
1954
+ const wasActiveRef = useRef7(false);
1955
+ useEffect12(() => {
1956
+ if (isActive) {
1957
+ wasActiveRef.current = true;
1958
+ } else if (wasActiveRef.current && phase === "idle") {
1959
+ wasActiveRef.current = false;
1960
+ onBack();
1961
+ }
1962
+ }, [phase, isActive, onBack]);
1963
+ if (isActive || phase === "error") {
1964
+ return /* @__PURE__ */ jsx9(
1965
+ InterfaceRunningView,
1966
+ {
1967
+ name,
1968
+ phase,
1969
+ outputLines,
1970
+ errorMessage,
1971
+ localPath,
1972
+ onStop: stop,
1973
+ onBack
1974
+ }
1975
+ );
1976
+ }
1977
+ return /* @__PURE__ */ jsx9(
1978
+ InterfaceSessionView,
1979
+ {
1980
+ item,
1981
+ onStart: start,
1982
+ onDelete: deleteLocalCopy,
1983
+ onBack,
1984
+ hasLocalCopy,
1985
+ localPath
1986
+ }
1987
+ );
1988
+ }
1989
+ function InterfacesPage({ onBack }) {
1990
+ const { sessions, loading, error, refreshStatus, refresh } = useEditorSessions();
1991
+ const [selectedAppId, setSelectedAppId] = useState12(null);
1992
+ const [selectedItem, setSelectedItem] = useState12(null);
1993
+ if (loading) {
1994
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", flexGrow: 1, paddingX: 1, marginTop: 1, children: [
1995
+ /* @__PURE__ */ jsx9(Text9, { bold: true, color: "white", underline: true, children: "Choose an Agent" }),
1996
+ /* @__PURE__ */ jsxs8(Box8, { marginTop: 1, children: [
1997
+ /* @__PURE__ */ jsx9(Text9, { color: "cyan", children: /* @__PURE__ */ jsx9(Spinner5, { type: "dots" }) }),
1998
+ /* @__PURE__ */ jsx9(Text9, { children: " Loading editor sessions..." })
1999
+ ] })
2000
+ ] });
2001
+ }
2002
+ if (error) {
2003
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", flexGrow: 1, paddingX: 1, marginTop: 1, children: [
2004
+ /* @__PURE__ */ jsx9(Text9, { bold: true, color: "white", underline: true, children: "Choose an Agent" }),
2005
+ /* @__PURE__ */ jsx9(Box8, { marginTop: 1, children: /* @__PURE__ */ jsx9(Text9, { color: "red", children: error }) })
2006
+ ] });
2007
+ }
2008
+ if (selectedItem) {
2009
+ return /* @__PURE__ */ jsx9(
2010
+ LocalDevView,
2011
+ {
2012
+ item: selectedItem,
2013
+ onBack: () => setSelectedItem(null)
2014
+ }
2015
+ );
2016
+ }
2017
+ if (selectedAppId) {
2018
+ const session = sessions.find((s) => s.appId === selectedAppId);
2019
+ if (session) {
2020
+ return /* @__PURE__ */ jsx9(
2021
+ AgentDetailView,
2022
+ {
2023
+ session,
2024
+ onBack: () => setSelectedAppId(null),
2025
+ onSelect: (item) => {
2026
+ setSelectedItem(item);
2027
+ },
2028
+ onRefresh: refresh,
2029
+ refreshStatus
2030
+ }
2031
+ );
2032
+ }
2033
+ }
2034
+ return /* @__PURE__ */ jsx9(
2035
+ AgentListView,
2036
+ {
2037
+ sessions,
2038
+ onBack,
2039
+ onSelectAgent: setSelectedAppId,
2040
+ onRefresh: refresh,
2041
+ refreshStatus
2042
+ }
2043
+ );
2044
+ }
2045
+
2046
+ // src/tui/pages/OnboardingPage.tsx
2047
+ import { useEffect as useEffect14, useCallback as useCallback9, useState as useState14, useMemo as useMemo6 } from "react";
2048
+ import { Box as Box9, Text as Text10, useInput as useInput6 } from "ink";
2049
+ import Spinner6 from "ink-spinner";
2050
+ import chalk2 from "chalk";
2051
+
2052
+ // src/tui/hooks/useAuth.ts
2053
+ import { useState as useState13, useCallback as useCallback8, useRef as useRef8, useEffect as useEffect13 } from "react";
2054
+ import open3 from "open";
2055
+ var POLL_INTERVAL = 2e3;
2056
+ var MAX_ATTEMPTS = 30;
2057
+ function useAuth() {
2058
+ const [status, setStatus] = useState13("idle");
2059
+ const [authUrl, setAuthUrl] = useState13(null);
2060
+ const [timeRemaining, setTimeRemaining] = useState13(0);
2061
+ const cancelledRef = useRef8(false);
2062
+ const timerRef = useRef8(null);
2063
+ useEffect13(() => {
2064
+ return () => {
2065
+ cancelledRef.current = true;
2066
+ if (timerRef.current) clearInterval(timerRef.current);
2067
+ };
2068
+ }, []);
2069
+ const cancel = useCallback8(() => {
2070
+ cancelledRef.current = true;
2071
+ if (timerRef.current) {
2072
+ clearInterval(timerRef.current);
2073
+ timerRef.current = null;
2074
+ }
2075
+ setStatus("idle");
2076
+ setAuthUrl(null);
2077
+ setTimeRemaining(0);
2078
+ }, []);
2079
+ const startAuth = useCallback8(() => {
2080
+ cancelledRef.current = false;
2081
+ const run = async () => {
2082
+ try {
2083
+ const { url, token } = await requestDeviceAuth();
2084
+ if (cancelledRef.current) return;
2085
+ setAuthUrl(url);
2086
+ setStatus("waiting");
2087
+ const totalTime = MAX_ATTEMPTS * POLL_INTERVAL / 1e3;
2088
+ setTimeRemaining(totalTime);
2089
+ timerRef.current = setInterval(() => {
2090
+ setTimeRemaining((prev) => {
2091
+ const next = prev - 1;
2092
+ if (next <= 0 && timerRef.current) {
2093
+ clearInterval(timerRef.current);
2094
+ timerRef.current = null;
2095
+ }
2096
+ return Math.max(0, next);
2097
+ });
2098
+ }, 1e3);
2099
+ await open3(url);
2100
+ for (let i = 0; i < MAX_ATTEMPTS; i++) {
2101
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL));
2102
+ if (cancelledRef.current) return;
2103
+ const result = await pollDeviceAuth(token);
2104
+ if (result.status === "completed" && result.apiKey) {
2105
+ if (timerRef.current) clearInterval(timerRef.current);
2106
+ setApiKey(result.apiKey);
2107
+ if (result.userId) {
2108
+ setUserId(result.userId);
2109
+ }
2110
+ setStatus("success");
2111
+ return;
2112
+ }
2113
+ if (result.status === "expired") {
2114
+ if (timerRef.current) clearInterval(timerRef.current);
2115
+ setStatus("expired");
2116
+ return;
2117
+ }
2118
+ }
2119
+ if (!cancelledRef.current) {
2120
+ setStatus("timeout");
2121
+ }
2122
+ } catch {
2123
+ if (!cancelledRef.current) {
2124
+ setStatus("expired");
2125
+ }
2126
+ }
2127
+ };
2128
+ run();
2129
+ }, []);
2130
+ return {
2131
+ status,
2132
+ authUrl,
2133
+ timeRemaining,
2134
+ startAuth,
2135
+ cancel
2136
+ };
2137
+ }
2138
+
2139
+ // src/tui/pages/OnboardingPage.tsx
2140
+ import { Fragment as Fragment5, jsx as jsx10, jsxs as jsxs9 } from "react/jsx-runtime";
2141
+ var SHIMMER_SPEED = 35;
2142
+ function useShimmerLogo() {
2143
+ const [frame, setFrame] = useState14(0);
2144
+ const lines = useMemo6(() => LogoString.split("\n"), []);
2145
+ const totalChars = useMemo6(() => {
2146
+ let count = 0;
2147
+ for (const line of lines) {
2148
+ for (const ch of line) {
2149
+ if (ch !== " " && ch !== " ") count++;
2150
+ }
2151
+ }
2152
+ return count;
2153
+ }, [lines]);
2154
+ const cycleLength = totalChars + 40;
2155
+ useEffect14(() => {
2156
+ const interval = setInterval(() => {
2157
+ setFrame((f) => (f + 1) % cycleLength);
2158
+ }, SHIMMER_SPEED);
2159
+ return () => clearInterval(interval);
2160
+ }, [cycleLength]);
2161
+ return useMemo6(() => {
2162
+ const sweepPos = frame;
2163
+ const holdEnd = totalChars + 20;
2164
+ let charIdx = 0;
2165
+ return lines.map((line) => {
2166
+ let result = "";
2167
+ for (let i = 0; i < line.length; i++) {
2168
+ const ch = line[i];
2169
+ if (ch === " " || ch === " ") {
2170
+ result += ch;
2171
+ continue;
2172
+ }
2173
+ let brightness;
2174
+ if (sweepPos <= totalChars) {
2175
+ const lag = charIdx;
2176
+ const t = sweepPos - lag;
2177
+ brightness = t <= 0 ? 0.1 : Math.min(1, t / 8);
2178
+ } else if (sweepPos <= holdEnd) {
2179
+ brightness = 1;
2180
+ } else {
2181
+ const fadeProgress = (sweepPos - holdEnd) / (cycleLength - holdEnd);
2182
+ brightness = Math.max(0.1, 1 - fadeProgress);
2183
+ }
2184
+ if (brightness >= 0.9) {
2185
+ result += chalk2.cyanBright.bold(ch);
2186
+ } else if (brightness >= 0.6) {
2187
+ result += chalk2.cyan(ch);
2188
+ } else if (brightness >= 0.3) {
2189
+ result += chalk2.rgb(0, 100, 120)(ch);
2190
+ } else {
2191
+ result += chalk2.rgb(0, 50, 60)(ch);
2192
+ }
2193
+ charIdx++;
2194
+ }
2195
+ return result;
2196
+ }).join("\n");
2197
+ }, [frame, lines, totalChars, cycleLength]);
2198
+ }
2199
+ function OnboardingPage({ onComplete }) {
2200
+ const {
2201
+ status: authStatus,
2202
+ authUrl,
2203
+ timeRemaining,
2204
+ startAuth,
2205
+ cancel: cancelAuth
2206
+ } = useAuth();
2207
+ const shimmerLogo = useShimmerLogo();
2208
+ useEffect14(() => {
2209
+ if (authStatus === "success") {
2210
+ const timer = setTimeout(() => onComplete(), 1500);
2211
+ return () => clearTimeout(timer);
2212
+ }
2213
+ }, [authStatus, onComplete]);
2214
+ useEffect14(() => {
2215
+ return () => cancelAuth();
2216
+ }, []);
2217
+ const handleAction = useCallback9(() => {
2218
+ cancelAuth();
2219
+ startAuth();
2220
+ }, [cancelAuth, startAuth]);
2221
+ const canAct = authStatus === "idle" || authStatus === "expired" || authStatus === "timeout";
2222
+ useInput6((_input, key) => {
2223
+ if (canAct && !key.ctrl) {
2224
+ handleAction();
2225
+ }
2226
+ });
2227
+ return /* @__PURE__ */ jsxs9(Box9, { flexDirection: "column", flexGrow: 1, children: [
2228
+ /* @__PURE__ */ jsx10(Box9, { flexGrow: 1 }),
2229
+ /* @__PURE__ */ jsxs9(Box9, { flexDirection: "column", alignItems: "center", children: [
2230
+ /* @__PURE__ */ jsx10(Text10, { children: shimmerLogo }),
2231
+ /* @__PURE__ */ jsx10(Box9, { flexDirection: "column", alignItems: "center", marginTop: 2, children: /* @__PURE__ */ jsx10(Text10, { bold: true, color: "white", children: "MindStudio Local Tunnel" }) }),
2232
+ /* @__PURE__ */ jsxs9(Box9, { flexDirection: "column", alignItems: "center", children: [
2233
+ authStatus === "idle" && /* @__PURE__ */ jsxs9(Fragment5, { children: [
2234
+ /* @__PURE__ */ jsx10(Text10, { color: "gray", children: "Connect your MindStudio account to get started." }),
2235
+ /* @__PURE__ */ jsx10(Box9, { marginTop: 1, children: /* @__PURE__ */ jsx10(Text10, { color: "cyan", bold: true, children: "Press any key to Connect Account" }) })
2236
+ ] }),
2237
+ (authStatus === "expired" || authStatus === "timeout") && /* @__PURE__ */ jsxs9(Fragment5, { children: [
2238
+ /* @__PURE__ */ jsx10(Text10, { color: "red", children: authStatus === "expired" ? "Authorization expired." : "Authorization timed out." }),
2239
+ /* @__PURE__ */ jsx10(Box9, { marginTop: 1, children: /* @__PURE__ */ jsx10(Text10, { color: "cyan", bold: true, children: "Press any key to Try Again" }) })
2240
+ ] }),
2241
+ authStatus === "waiting" && /* @__PURE__ */ jsxs9(Fragment5, { children: [
2242
+ /* @__PURE__ */ jsxs9(Box9, { children: [
2243
+ /* @__PURE__ */ jsx10(Text10, { color: "cyan", children: /* @__PURE__ */ jsx10(Spinner6, { type: "dots" }) }),
2244
+ /* @__PURE__ */ jsxs9(Text10, { children: [
2245
+ " ",
2246
+ "Waiting for browser authorization... (",
2247
+ timeRemaining,
2248
+ "s remaining)"
2249
+ ] })
2250
+ ] }),
2251
+ authUrl && /* @__PURE__ */ jsxs9(Box9, { flexDirection: "column", alignItems: "center", marginTop: 1, children: [
2252
+ /* @__PURE__ */ jsx10(Text10, { color: "gray", children: "If browser didn't open, visit:" }),
2253
+ /* @__PURE__ */ jsx10(Text10, { color: "cyan", children: authUrl })
2254
+ ] })
2255
+ ] }),
2256
+ authStatus === "success" && /* @__PURE__ */ jsxs9(Text10, { color: "green", children: [
2257
+ "\u2713",
2258
+ " Authenticated!"
2259
+ ] })
2260
+ ] })
2261
+ ] }),
2262
+ /* @__PURE__ */ jsx10(Box9, { flexGrow: 1 })
2263
+ ] });
2264
+ }
2265
+
2266
+ // src/tui/App.tsx
2267
+ import { Fragment as Fragment6, jsx as jsx11, jsxs as jsxs10 } from "react/jsx-runtime";
2268
+ var MODEL_TYPE_MAP = {
2269
+ text: "llm_chat",
2270
+ image: "image_generation",
2271
+ video: "video_generation"
2272
+ };
2273
+ function App({ runner }) {
2274
+ const { exit } = useApp();
2275
+ const { stdout } = useStdout7();
2276
+ const {
2277
+ status: connectionStatus,
2278
+ environment,
2279
+ error: connectionError,
2280
+ retry: retryConnection
2281
+ } = useConnection();
2282
+ const {
2283
+ providers,
2284
+ loading: providersLoading,
2285
+ refresh: refreshProviders
2286
+ } = useSetupProviders();
2287
+ const {
2288
+ models,
2289
+ warnings: modelWarnings,
2290
+ loading: modelsLoading,
2291
+ refresh: refreshModels
2292
+ } = useModels();
2293
+ const { requests } = useRequests();
2294
+ const {
2295
+ syncedNames,
2296
+ syncedModels,
2297
+ refresh: refreshSynced
2298
+ } = useSyncedModels(connectionStatus);
2299
+ const shouldOnboard = getApiKey() === void 0 || getUserId() === void 0;
2300
+ const [page, setPage] = useState15(
2301
+ shouldOnboard ? "onboarding" : "dashboard"
2302
+ );
2303
+ const [syncStatus, setSyncStatus] = useState15(
2304
+ "idle"
2305
+ );
2306
+ const syncTimerRef = useRef9();
2307
+ const lastSyncPayloadRef = useRef9("");
2308
+ useEffect15(() => {
2309
+ if (connectionStatus === "not_authenticated") {
2310
+ setPage("onboarding");
2311
+ }
2312
+ }, [connectionStatus]);
2313
+ useEffect15(() => {
2314
+ if (page === "dashboard") {
2315
+ refreshAll();
2316
+ }
2317
+ }, [page]);
2318
+ useEffect15(() => {
2319
+ if (connectionStatus === "connected" && syncedModels.length > 0) {
2320
+ runner.start(syncedModels);
2321
+ }
2322
+ }, [connectionStatus, syncedModels, runner]);
2323
+ useEffect15(() => () => runner.stop(), [runner]);
2324
+ const refreshAll = useCallback10(
2325
+ async (silent = false) => {
2326
+ if (!silent) setSyncStatus("syncing");
2327
+ const [discoveredModels] = await Promise.all([
2328
+ refreshModels(),
2329
+ refreshProviders()
2330
+ ]);
2331
+ const modelsToSync = discoveredModels.filter((m) => !m.statusHint).map((m) => ({
2332
+ name: m.name,
2333
+ provider: m.provider,
2334
+ type: MODEL_TYPE_MAP[m.capability] || "llm_chat",
2335
+ parameters: m.parameters
2336
+ }));
2337
+ const payload = JSON.stringify(modelsToSync);
2338
+ if (payload !== lastSyncPayloadRef.current && modelsToSync.length > 0) {
2339
+ try {
2340
+ await syncModels(modelsToSync);
2341
+ lastSyncPayloadRef.current = payload;
2342
+ } catch {
2343
+ }
2344
+ }
2345
+ await refreshSynced();
2346
+ if (!silent) {
2347
+ setSyncStatus("synced");
2348
+ clearTimeout(syncTimerRef.current);
2349
+ syncTimerRef.current = setTimeout(() => setSyncStatus("idle"), 1500);
2350
+ }
2351
+ },
2352
+ [refreshProviders, refreshModels, refreshSynced]
2353
+ );
2354
+ useEffect15(() => {
2355
+ if (connectionStatus !== "connected" || page !== "dashboard") return;
2356
+ const interval = setInterval(() => refreshAll(true), 1500);
2357
+ return () => clearInterval(interval);
2358
+ }, [connectionStatus, page, refreshAll]);
2359
+ const handleQuit = useCallback10(() => {
2360
+ runner.stop();
2361
+ exit();
2362
+ }, [runner, exit]);
2363
+ const handleOnboardingComplete = useCallback10(() => {
2364
+ retryConnection();
2365
+ refreshAll();
2366
+ setPage("dashboard");
2367
+ }, [retryConnection, refreshAll]);
2368
+ const handleNavigate = useCallback10(
2369
+ (id) => {
2370
+ switch (id) {
2371
+ case "interfaces":
2372
+ setPage("interfaces");
2373
+ break;
2374
+ case "auth":
2375
+ setPage("onboarding");
2376
+ break;
2377
+ case "setup":
2378
+ setPage("setup");
2379
+ break;
2380
+ case "refresh":
2381
+ refreshAll();
2382
+ break;
2383
+ case "quit":
2384
+ handleQuit();
2385
+ break;
2386
+ }
2387
+ },
2388
+ [refreshAll, handleQuit]
2389
+ );
2390
+ const subpageMenuItems = [
2391
+ { id: "back", label: "Back", description: "Return to dashboard" }
2392
+ ];
2393
+ const handleSubpageNavigate = useCallback10(
2394
+ (id) => {
2395
+ if (id === "back") {
2396
+ setPage("dashboard");
2397
+ } else {
2398
+ handleNavigate(id);
2399
+ }
2400
+ },
2401
+ [handleNavigate]
2402
+ );
2403
+ const [termSize, setTermSize] = useState15({
2404
+ rows: stdout?.rows ?? 24,
2405
+ columns: stdout?.columns ?? 80
2406
+ });
2407
+ useEffect15(() => {
2408
+ if (!stdout) return;
2409
+ const onResize = () => {
2410
+ stdout.write("\x1B[2J\x1B[H");
2411
+ setTermSize({ rows: stdout.rows, columns: stdout.columns });
2412
+ };
2413
+ stdout.on("resize", onResize);
2414
+ return () => {
2415
+ stdout.off("resize", onResize);
2416
+ };
2417
+ }, [stdout]);
2418
+ const termHeight = termSize.rows - 4;
2419
+ const compactHeader = termSize.rows <= 45 || termSize.columns <= 90;
2420
+ return /* @__PURE__ */ jsx11(Box10, { flexDirection: "column", height: termHeight, overflow: "hidden", children: page === "onboarding" ? /* @__PURE__ */ jsx11(OnboardingPage, { onComplete: handleOnboardingComplete }) : /* @__PURE__ */ jsxs10(Fragment6, { children: [
2421
+ /* @__PURE__ */ jsx11(
2422
+ Header,
2423
+ {
2424
+ connection: connectionStatus,
2425
+ environment,
2426
+ configPath: getConfigPath(),
2427
+ connectionError,
2428
+ compact: compactHeader
2429
+ }
2430
+ ),
2431
+ page === "dashboard" && /* @__PURE__ */ jsx11(
2432
+ DashboardPage,
2433
+ {
2434
+ requests,
2435
+ models,
2436
+ modelWarnings,
2437
+ providers,
2438
+ providersLoading,
2439
+ syncedNames,
2440
+ modelsLoading,
2441
+ syncStatus,
2442
+ onNavigate: handleNavigate
2443
+ }
2444
+ ),
2445
+ page === "setup" && /* @__PURE__ */ jsx11(SetupPage, { onBack: () => setPage("dashboard") }),
2446
+ page === "interfaces" && /* @__PURE__ */ jsx11(
2447
+ InterfacesPage,
2448
+ {
2449
+ onBack: () => setPage("dashboard")
2450
+ }
2451
+ ),
2452
+ page !== "dashboard" && page !== "setup" && page !== "interfaces" && /* @__PURE__ */ jsx11(Box10, { flexGrow: 1 }),
2453
+ page !== "dashboard" && page !== "setup" && page !== "interfaces" && /* @__PURE__ */ jsx11(
2454
+ NavigationMenu,
2455
+ {
2456
+ items: subpageMenuItems,
2457
+ onSelect: handleSubpageNavigate
2458
+ }
2459
+ )
2460
+ ] }) });
2461
+ }
2462
+
2463
+ // src/update.ts
2464
+ import { createRequire as createRequire2 } from "module";
2465
+ var require3 = createRequire2(import.meta.url);
2466
+ var pkg2 = require3("../package.json");
2467
+ function getCurrentVersion() {
2468
+ return pkg2.version;
2469
+ }
2470
+ async function fetchLatestVersion() {
2471
+ try {
2472
+ const res = await fetch(
2473
+ "https://registry.npmjs.org/@mindstudio-ai/local-model-tunnel/latest",
2474
+ { signal: AbortSignal.timeout(5e3) }
2475
+ );
2476
+ if (!res.ok) return null;
2477
+ const data = await res.json();
2478
+ return data.version ?? null;
2479
+ } catch {
2480
+ return null;
2481
+ }
2482
+ }
2483
+ function isNewerVersion(current, latest) {
2484
+ const currentParts = current.split(".").map(Number);
2485
+ const latestParts = latest.split(".").map(Number);
2486
+ for (let i = 0; i < Math.max(currentParts.length, latestParts.length); i++) {
2487
+ const c = currentParts[i] ?? 0;
2488
+ const l = latestParts[i] ?? 0;
2489
+ if (l > c) return true;
2490
+ if (l < c) return false;
2491
+ }
2492
+ return false;
2493
+ }
2494
+ async function checkForUpdate() {
2495
+ const currentVersion = getCurrentVersion();
2496
+ const latestVersion = await fetchLatestVersion();
2497
+ if (!latestVersion) return null;
2498
+ if (!isNewerVersion(currentVersion, latestVersion)) return null;
2499
+ return { currentVersion, latestVersion };
2500
+ }
2501
+
2502
+ // src/tui/components/UpdatePrompt.tsx
2503
+ import { Box as Box11, Text as Text11, useInput as useInput7 } from "ink";
2504
+ import { jsx as jsx12, jsxs as jsxs11 } from "react/jsx-runtime";
2505
+ function UpdatePrompt({
2506
+ currentVersion,
2507
+ latestVersion,
2508
+ onChoice
2509
+ }) {
2510
+ useInput7((input) => {
2511
+ if (input.toLowerCase() === "y") {
2512
+ onChoice(true);
2513
+ } else {
2514
+ onChoice(false);
2515
+ }
2516
+ });
2517
+ return /* @__PURE__ */ jsxs11(Box11, { flexDirection: "column", paddingY: 1, paddingX: 2, children: [
2518
+ /* @__PURE__ */ jsxs11(Text11, { children: [
2519
+ /* @__PURE__ */ jsx12(Text11, { color: "yellow", bold: true, children: "Update available:" }),
2520
+ /* @__PURE__ */ jsxs11(Text11, { children: [
2521
+ " ",
2522
+ "v",
2523
+ currentVersion,
2524
+ " ",
2525
+ "\u2192",
2526
+ " v",
2527
+ latestVersion
2528
+ ] })
2529
+ ] }),
2530
+ /* @__PURE__ */ jsx12(Box11, { marginTop: 1, children: /* @__PURE__ */ jsxs11(Text11, { children: [
2531
+ "Press ",
2532
+ /* @__PURE__ */ jsx12(Text11, { bold: true, color: "cyan", children: "y" }),
2533
+ " to update, any other key to skip"
2534
+ ] }) })
2535
+ ] });
2536
+ }
2537
+
2538
+ // src/tui/index.tsx
2539
+ import { jsx as jsx13 } from "react/jsx-runtime";
2540
+ async function promptForUpdate(currentVersion, latestVersion) {
2541
+ return new Promise((resolve) => {
2542
+ const { unmount } = render(
2543
+ /* @__PURE__ */ jsx13(
2544
+ UpdatePrompt,
2545
+ {
2546
+ currentVersion,
2547
+ latestVersion,
2548
+ onChoice: (shouldUpdate) => {
2549
+ unmount();
2550
+ resolve(shouldUpdate);
2551
+ }
2552
+ }
2553
+ ),
2554
+ { exitOnCtrlC: true }
2555
+ );
2556
+ });
2557
+ }
2558
+ async function startTUI() {
2559
+ console.clear();
2560
+ const update = await checkForUpdate();
2561
+ if (update) {
2562
+ const shouldUpdate = await promptForUpdate(
2563
+ update.currentVersion,
2564
+ update.latestVersion
2565
+ );
2566
+ if (shouldUpdate) {
2567
+ console.log("\nUpdating to v" + update.latestVersion + "...\n");
2568
+ try {
2569
+ execSync2("npm install -g @mindstudio-ai/local-model-tunnel@latest", {
2570
+ stdio: "inherit"
2571
+ });
2572
+ console.log("\nRestarting...\n");
2573
+ execFileSync(process.execPath, process.argv.slice(1), {
2574
+ stdio: "inherit"
2575
+ });
2576
+ } catch {
2577
+ console.error("\nUpdate failed. Continuing with current version.\n");
2578
+ }
2579
+ return;
2580
+ }
2581
+ console.clear();
2582
+ }
2583
+ const runner = new TunnelRunner();
2584
+ const { waitUntilExit } = render(
2585
+ /* @__PURE__ */ jsx13(App, { runner }),
2586
+ {
2587
+ exitOnCtrlC: true
2588
+ }
2589
+ );
2590
+ await waitUntilExit();
2591
+ runner.stop();
2592
+ }
2593
+ export {
2594
+ startTUI
2595
+ };
2596
+ //# sourceMappingURL=tui-BW6XKMWK.js.map