@conveno/cli 0.2.0-rc.6 → 0.2.0-rc.8

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.
@@ -1,4465 +0,0 @@
1
- import { Box, Text, render, useApp, useInput, useStdin, useWindowSize } from "ink";
2
- import { n as connectOpts, t as adapterEnv } from "./ctx-tYftvhz_.js";
3
- import { t as daemonProblem } from "./daemonError-CdLataBW.js";
4
- import { a as fail, n as cmd, s as plainError, u as tilde } from "./fmt-C2SsP5Y0.js";
5
- import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
6
- import { readFileSync, readdirSync, writeFileSync } from "node:fs";
7
- import { Readable } from "node:stream";
8
- import { E as compatStatus, Ft as spawnSession, H as fetchAccountStatus, Kt as writeSettings, M as dataPaths, Pt as spawnRecordPath, St as realSpawnDeps, bt as readSettings, gt as readAccountTokens, xt as readSpawnRecord } from "./dist-BTLBO1Rp.js";
9
- import { homedir } from "node:os";
10
- import { i as tokens, n as detectColorLevel, r as detectUnicode } from "./dist-BRjg9CLd.js";
11
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
- import { basename, join, resolve } from "node:path";
13
- import { r as stopRequestPath, t as killProcessTree } from "./dist-BAlMjYqQ.js";
14
- import { g as PAIR_TIMEOUT_MS, h as unifiedDiff, l as StaleError, r as collectPlans, t as inspect, u as applyChanges, y as openInBrowser } from "./doctor-DjwXJvKw.js";
15
- // \0rolldown/runtime.js
16
- var __defProp = Object.defineProperty;
17
- var __exportAll = (all, flags) => {
18
- let target = Object.setPrototypeOf({}, null);
19
- for (var name in all) __defProp(target, name, {
20
- get: all[name],
21
- enumerable: true
22
- });
23
- if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
24
- return flags & 2 ? target : Object.preventExtensions(target);
25
- };
26
- // src/tui/contract.ts
27
- function layoutFor(columns) {
28
- if (columns >= 120) return "wide";
29
- if (columns >= 80) return "normal";
30
- if (columns >= 60) return "narrow";
31
- return "tiny";
32
- }
33
- const SCREENS = [
34
- {
35
- id: "sessions",
36
- key: "1",
37
- title: "Sessions"
38
- },
39
- {
40
- id: "new",
41
- key: "2",
42
- title: "New"
43
- },
44
- {
45
- id: "devices",
46
- key: "3",
47
- title: "Devices"
48
- },
49
- {
50
- id: "setup",
51
- key: "4",
52
- title: "Setup"
53
- }
54
- ];
55
- // src/tui/mouse.ts
56
- /**
57
- * Mouse support for the app, with no React in it: an SGR mouse parser, a stream that sits between
58
- * the real stdin and Ink and strips mouse reports out of the bytes, and a hub that hit-tests
59
- * registered boxes. `ui.tsx` wraps the hub in hooks.
60
- */
61
- const ESC = "\x1B";
62
- const PASTE_START = `${ESC}[200~`;
63
- const PASTE_END = `${ESC}[201~`;
64
- const SGR = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])/;
65
- const SGR_PREFIX = /^\x1b(?:\[(?:<[0-9;]*)?)?$/;
66
- /** Turn the numbers of an SGR report into an event. */
67
- function sgrEvent(b, x, y, final) {
68
- const wheel = (b & 64) !== 0;
69
- const motion = (b & 32) !== 0;
70
- const low = b & 3;
71
- return {
72
- kind: wheel ? "wheel" : motion ? "move" : final === "m" ? "release" : "press",
73
- button: wheel ? "left" : low === 1 ? "middle" : low === 2 ? "right" : "left",
74
- x: Math.max(0, x - 1),
75
- y: Math.max(0, y - 1),
76
- delta: wheel ? (b & 1) === 0 ? -1 : 1 : 0,
77
- shift: (b & 4) !== 0,
78
- alt: (b & 8) !== 0,
79
- ctrl: (b & 16) !== 0
80
- };
81
- }
82
- /**
83
- * Takes the bytes the terminal sends and splits them into the text Ink should see and mouse
84
- * events. A report cut by a chunk boundary is held until the rest arrives (`flush` gives it up
85
- * when nothing follows). Bracketed paste passes through as it is, mouse-looking text included.
86
- */
87
- var MouseParser = class {
88
- held = "";
89
- inPaste = false;
90
- push(chunk) {
91
- const s = this.held + chunk;
92
- this.held = "";
93
- const events = [];
94
- let text = "";
95
- let i = 0;
96
- while (i < s.length) {
97
- if (this.inPaste) {
98
- const end = s.indexOf(PASTE_END, i);
99
- if (end >= 0) {
100
- text += s.slice(i, end + PASTE_END.length);
101
- i = end + PASTE_END.length;
102
- this.inPaste = false;
103
- continue;
104
- }
105
- let keep = 0;
106
- for (let n = Math.min(PASTE_END.length - 1, s.length - i); n > 0; n--) if (PASTE_END.startsWith(s.slice(s.length - n))) {
107
- keep = n;
108
- break;
109
- }
110
- text += s.slice(i, s.length - keep);
111
- this.held = s.slice(s.length - keep);
112
- break;
113
- }
114
- const esc = s.indexOf(ESC, i);
115
- if (esc < 0) {
116
- text += s.slice(i);
117
- break;
118
- }
119
- text += s.slice(i, esc);
120
- const rest = s.slice(esc);
121
- const m = SGR.exec(rest);
122
- if (m) {
123
- events.push(sgrEvent(Number(m[1]), Number(m[2]), Number(m[3]), m[4]));
124
- i = esc + m[0].length;
125
- continue;
126
- }
127
- if (rest.startsWith(PASTE_START)) {
128
- text += PASTE_START;
129
- this.inPaste = true;
130
- i = esc + PASTE_START.length;
131
- continue;
132
- }
133
- if (SGR_PREFIX.test(rest) || rest.length < PASTE_START.length && isPasteStartPrefix(rest)) {
134
- this.held = rest;
135
- break;
136
- }
137
- text += ESC;
138
- i = esc + 1;
139
- }
140
- return {
141
- text,
142
- events
143
- };
144
- }
145
- /** Whether bytes are being held back. */
146
- get pending() {
147
- return this.held !== "";
148
- }
149
- /** Give up what is held: it was not a mouse report after all. */
150
- flush() {
151
- const h = this.held;
152
- this.held = "";
153
- return h;
154
- }
155
- };
156
- function isPasteStartPrefix(s) {
157
- return PASTE_START.startsWith(s);
158
- }
159
- /** Position of a box on the screen, in cells. Zero size when it is not laid out or hidden. */
160
- function boxRect(node) {
161
- const own = node.yogaNode;
162
- if (!own) return {
163
- x: 0,
164
- y: 0,
165
- w: 0,
166
- h: 0
167
- };
168
- let x = own.getComputedLeft();
169
- let y = own.getComputedTop();
170
- for (let p = node.parentNode; p; p = p.parentNode) if (p.yogaNode) {
171
- x += p.yogaNode.getComputedLeft();
172
- y += p.yogaNode.getComputedTop();
173
- }
174
- return {
175
- x,
176
- y,
177
- w: own.getComputedWidth(),
178
- h: own.getComputedHeight()
179
- };
180
- }
181
- function depthOf(node) {
182
- let d = 0;
183
- for (let p = node.parentNode; p; p = p.parentNode) d++;
184
- return d;
185
- }
186
- const ENABLE_SEQ = "\x1B[?1000h\x1B[?1006h";
187
- const DISABLE_SEQ = "\x1B[?1006l\x1B[?1002l\x1B[?1000l";
188
- /** Hit testing and dispatch. One per running app. */
189
- var MouseHub = class {
190
- targets = [];
191
- listeners = /* @__PURE__ */ new Set();
192
- fallbacks = /* @__PURE__ */ new Set();
193
- last;
194
- on;
195
- reporter;
196
- available;
197
- forcedOff;
198
- showHint;
199
- inject;
200
- persist;
201
- markHint;
202
- now;
203
- constructor(opts = {}) {
204
- this.available = opts.available ?? true;
205
- this.forcedOff = opts.forcedOff ?? false;
206
- this.on = this.available && !this.forcedOff && (opts.enabled ?? true);
207
- this.showHint = (opts.showHint ?? false) && this.on;
208
- this.inject = opts.inject ?? (() => void 0);
209
- this.persist = opts.persist;
210
- this.markHint = opts.markHintShown;
211
- this.now = opts.now ?? Date.now;
212
- }
213
- get enabled() {
214
- return this.on;
215
- }
216
- /** Switch the mouse on or off at once; with `persist` the choice is also kept. */
217
- setEnabled(on, persist = false) {
218
- if (persist) this.persist?.(on);
219
- const next = on && this.available && !this.forcedOff;
220
- if (next === this.on) return;
221
- this.on = next;
222
- this.last = void 0;
223
- this.reporter?.(next);
224
- for (const l of this.listeners) l();
225
- }
226
- /** Called by the stream that sends the enable and disable sequences. */
227
- attachReporter(fn) {
228
- this.reporter = fn;
229
- }
230
- subscribe = (l) => {
231
- this.listeners.add(l);
232
- return () => this.listeners.delete(l);
233
- };
234
- getEnabled = () => this.on;
235
- hintShown() {
236
- this.markHint?.();
237
- }
238
- /** Type keys into the app, as if pressed. */
239
- press(keys) {
240
- this.inject(keys);
241
- }
242
- register(t) {
243
- this.targets.push(t);
244
- return () => {
245
- this.targets = this.targets.filter((x) => x !== t);
246
- };
247
- }
248
- /** Called with a press that no box took. */
249
- onUnhandled(fn) {
250
- this.fallbacks.add(fn);
251
- return () => this.fallbacks.delete(fn);
252
- }
253
- /** The innermost active target of a kind under a cell. */
254
- hit(kind, x, y) {
255
- let best;
256
- for (const t of this.targets) {
257
- if (t.kind !== kind || !t.active()) continue;
258
- const el = t.el();
259
- if (!el) continue;
260
- const r = boxRect(el);
261
- if (r.w <= 0 || r.h <= 0) continue;
262
- if (x < r.x || x >= r.x + r.w || y < r.y || y >= r.y + r.h) continue;
263
- const depth = depthOf(el);
264
- if (!best || depth >= best.depth) best = {
265
- t,
266
- rx: x - r.x,
267
- ry: y - r.y,
268
- depth
269
- };
270
- }
271
- return best;
272
- }
273
- /** Handle one mouse event from the terminal. */
274
- dispatch(e) {
275
- if (!this.on) return;
276
- if (e.kind === "wheel") {
277
- this.hit("wheel", e.x, e.y)?.t.wheel?.(e.delta);
278
- return;
279
- }
280
- if (e.kind !== "press") return;
281
- let double = false;
282
- if (e.button === "left") {
283
- const t = this.now();
284
- double = this.last !== void 0 && this.last.x === e.x && this.last.y === e.y && t - this.last.t <= 400;
285
- this.last = double ? void 0 : {
286
- x: e.x,
287
- y: e.y,
288
- t
289
- };
290
- }
291
- const h = this.hit("click", e.x, e.y);
292
- if (h) {
293
- h.t.click?.({
294
- x: h.rx,
295
- y: h.ry,
296
- button: e.button,
297
- double,
298
- shift: e.shift
299
- });
300
- return;
301
- }
302
- for (const f of this.fallbacks) f(e);
303
- }
304
- };
305
- const HOLD_MS = 15;
306
- /** The stream Ink reads. Looks like the terminal's stdin, without the mouse reports. */
307
- var FilteredStdin = class extends Readable {
308
- real;
309
- out;
310
- hub;
311
- isTTY = true;
312
- isRaw = false;
313
- parser = new MouseParser();
314
- timer;
315
- reporting = false;
316
- raw = false;
317
- shut = false;
318
- onData = (chunk) => {
319
- const { text, events } = this.parser.push(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
320
- for (const e of events) this.hub.dispatch(e);
321
- if (text) this.push(text);
322
- if (this.timer) clearTimeout(this.timer);
323
- this.timer = void 0;
324
- if (this.parser.pending) this.timer = setTimeout(() => {
325
- this.timer = void 0;
326
- const rest = this.parser.flush();
327
- if (rest) this.push(rest);
328
- }, HOLD_MS);
329
- };
330
- constructor(real, out, hub) {
331
- super();
332
- this.real = real;
333
- this.out = out;
334
- this.hub = hub;
335
- real.setEncoding("utf8");
336
- real.on("data", this.onData);
337
- hub.attachReporter((on) => this.report(on));
338
- }
339
- _read() {}
340
- setRawMode(on) {
341
- this.real.setRawMode?.(on);
342
- this.raw = on;
343
- this.isRaw = on;
344
- this.report(on && this.hub.enabled);
345
- return this;
346
- }
347
- ref() {
348
- this.real.ref?.();
349
- return this;
350
- }
351
- unref() {
352
- this.real.unref?.();
353
- return this;
354
- }
355
- /** Put keys in front of Ink as if typed. */
356
- inject(keys) {
357
- this.push(keys);
358
- }
359
- report(on) {
360
- const want = on && this.raw && !this.shut;
361
- if (want === this.reporting) return;
362
- this.reporting = want;
363
- try {
364
- this.out.write(want ? ENABLE_SEQ : DISABLE_SEQ);
365
- } catch {}
366
- }
367
- /** Stop reading and make sure the terminal is out of mouse mode. */
368
- close() {
369
- if (this.shut) return;
370
- this.shut = true;
371
- if (this.timer) clearTimeout(this.timer);
372
- this.real.removeListener("data", this.onData);
373
- this.hub.attachReporter(void 0);
374
- try {
375
- this.real.pause();
376
- } catch {}
377
- this.out.write(DISABLE_SEQ);
378
- this.reporting = false;
379
- }
380
- };
381
- /**
382
- * Put the mouse filter between the real stdin and Ink. Reporting is switched on when Ink turns raw
383
- * mode on and off again on every way out: dispose, process exit (which also covers an uncaught
384
- * error), SIGTERM and SIGHUP.
385
- */
386
- function createMouseInput(ctx, real = process.stdin, out = process.stdout) {
387
- const usable = real.isTTY === true && out.isTTY === true && typeof real.setRawMode === "function";
388
- const forcedOff = mouseForcedOff(ctx);
389
- const hint = usable && getMouseSetting(ctx) && !hintWasShown(ctx);
390
- let stream;
391
- const hub = new MouseHub({
392
- available: usable,
393
- forcedOff,
394
- enabled: getMouseSetting(ctx),
395
- showHint: hint,
396
- inject: (k) => stream?.inject(k),
397
- persist: (on) => saveSetting(ctx, { appMouse: on }),
398
- markHintShown: () => saveSetting(ctx, { appMouseHintShown: true })
399
- });
400
- if (!usable) return {
401
- stdin: real,
402
- hub,
403
- dispose: () => void 0
404
- };
405
- stream = new FilteredStdin(real, out, hub);
406
- const restore = () => {
407
- try {
408
- out.write(DISABLE_SEQ);
409
- } catch {}
410
- };
411
- const onTerm = (sig) => {
412
- restore();
413
- process.removeListener("SIGTERM", onTerm);
414
- process.removeListener("SIGHUP", onTerm);
415
- process.kill(process.pid, sig);
416
- };
417
- process.on("exit", restore);
418
- process.on("SIGTERM", onTerm);
419
- process.on("SIGHUP", onTerm);
420
- let done = false;
421
- return {
422
- stdin: stream,
423
- hub,
424
- dispose() {
425
- if (done) return;
426
- done = true;
427
- stream?.close();
428
- process.removeListener("exit", restore);
429
- process.removeListener("SIGTERM", onTerm);
430
- process.removeListener("SIGHUP", onTerm);
431
- }
432
- };
433
- }
434
- function settingsFile(ctx) {
435
- return dataPaths(ctx.platform, ctx.dataDir).settings;
436
- }
437
- function readRaw(ctx) {
438
- try {
439
- const v = JSON.parse(readFileSync(settingsFile(ctx), "utf8"));
440
- return typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
441
- } catch {
442
- return {};
443
- }
444
- }
445
- function saveSetting(ctx, patch) {
446
- try {
447
- writeSettings(settingsFile(ctx), patch);
448
- } catch {}
449
- }
450
- function hintWasShown(ctx) {
451
- return readRaw(ctx).appMouseHintShown === true;
452
- }
453
- /** `CONVENO_MOUSE=0` (or `off`, `false`) switches the mouse off whatever was saved. */
454
- function mouseForcedOff(ctx) {
455
- const v = ctx.env.CONVENO_MOUSE?.trim().toLowerCase();
456
- return v === "0" || v === "off" || v === "false" || v === "no";
457
- }
458
- /** Whether the mouse should be on: on unless forced off or saved as off (`appMouse: false`). */
459
- function getMouseSetting(ctx) {
460
- if (mouseForcedOff(ctx)) return false;
461
- return readRaw(ctx).appMouse !== false;
462
- }
463
- // src/tui/ui.tsx
464
- /**
465
- * Small building blocks every screen shares. Colours come from the brand tokens; with NO_COLOR or
466
- * a terminal without colour every colour is undefined and state is carried by words.
467
- */
468
- /** The selected-row highlight from the approved mockup. */
469
- const SELECT_BG = "#1B2A40";
470
- const NAMES = [
471
- "ground",
472
- "surface",
473
- "sunken",
474
- "ink",
475
- "quiet",
476
- "rule",
477
- "entry",
478
- "stamp",
479
- "ok",
480
- "warn",
481
- "error",
482
- "info"
483
- ];
484
- /** Build the UI theme from the environment. Tests pass their own. */
485
- function makeUiTheme(env = process.env, opts = {}) {
486
- const ctx = {
487
- env,
488
- isTTY: Boolean(process.stdout.isTTY),
489
- platform: process.platform
490
- };
491
- const level = opts.colourLevel ?? detectColorLevel(ctx);
492
- const unicode = opts.unicode ?? detectUnicode(ctx);
493
- const c = {};
494
- if (level > 0) {
495
- for (const n of NAMES) c[n] = tokens.color.dark[n];
496
- c.select = SELECT_BG;
497
- }
498
- return {
499
- c,
500
- ascii: !unicode,
501
- colour: level > 0
502
- };
503
- }
504
- /** Same as `makeUiTheme` but from a CLI `Theme`, so the app follows the command line's choices. */
505
- function uiThemeFrom(theme) {
506
- return makeUiTheme(process.env, {
507
- colourLevel: theme.colorLevel,
508
- unicode: theme.unicode
509
- });
510
- }
511
- const ThemeContext = createContext(void 0);
512
- function ThemeProvider({ theme, children }) {
513
- const value = useMemo(() => theme ?? makeUiTheme(), [theme]);
514
- return /* @__PURE__ */ jsx(ThemeContext.Provider, {
515
- value,
516
- children
517
- });
518
- }
519
- function useTheme() {
520
- return useContext(ThemeContext) ?? FALLBACK;
521
- }
522
- const FALLBACK = {
523
- c: {},
524
- ascii: true,
525
- colour: false
526
- };
527
- const MouseContext = createContext(void 0);
528
- /** The shell provides the hub that turns terminal mouse reports into clicks and wheel turns. */
529
- const MouseProvider = MouseContext.Provider;
530
- const ScopeContext = createContext(true);
531
- /** Everything below gets no mouse events while `active` is false (a screen under an overlay). */
532
- function MouseScope({ active, children }) {
533
- const outer = useContext(ScopeContext);
534
- return /* @__PURE__ */ jsx(ScopeContext.Provider, {
535
- value: outer && active,
536
- children
537
- });
538
- }
539
- function useTarget(kind, ref, fn, isActive) {
540
- const hub = useContext(MouseContext);
541
- const scope = useContext(ScopeContext);
542
- const fnRef = useRef(fn);
543
- fnRef.current = fn;
544
- const activeRef = useRef(true);
545
- activeRef.current = (isActive ?? true) && scope;
546
- useEffect(() => {
547
- if (!hub) return;
548
- const call = (a) => fnRef.current(a);
549
- return hub.register({
550
- kind,
551
- el: () => ref.current,
552
- active: () => activeRef.current,
553
- ...kind === "click" ? { click: call } : { wheel: call }
554
- });
555
- }, [
556
- hub,
557
- kind,
558
- ref
559
- ]);
560
- }
561
- /** Make a Box react to clicks. The handler gets the position inside the box. */
562
- function useClick(ref, onClick, opts) {
563
- useTarget("click", ref, onClick, opts?.isActive);
564
- }
565
- /** Make a Box a wheel target. `delta` is -1 (up) or +1 (down) per notch. */
566
- function useWheel(ref, onWheel, opts) {
567
- useTarget("wheel", ref, onWheel, opts?.isActive);
568
- }
569
- const NO_SUBSCRIBE = () => () => void 0;
570
- /** Whether the mouse is on, to show hints like "click to open". */
571
- function useMouseEnabled() {
572
- const hub = useContext(MouseContext);
573
- return useSyncExternalStore(hub?.subscribe ?? NO_SUBSCRIBE, hub?.getEnabled ?? (() => false));
574
- }
575
- /** For the Setup switch: the state, whether it can be on at all, and a setter that is kept. */
576
- function useMouseControl() {
577
- const hub = useContext(MouseContext);
578
- return {
579
- enabled: useMouseEnabled(),
580
- available: hub?.available ?? false,
581
- forcedOff: hub?.forcedOff ?? false,
582
- set: (on) => hub?.setEnabled(on, true)
583
- };
584
- }
585
- /** A ready-made clickable piece of text. */
586
- function Clickable({ onClick, children, isActive }) {
587
- const ref = useRef(null);
588
- useClick(ref, onClick, isActive === void 0 ? void 0 : { isActive });
589
- return /* @__PURE__ */ jsx(Box, {
590
- ref,
591
- children
592
- });
593
- }
594
- /** Cut a string to `width` columns, with an ellipsis. */
595
- function cut(text, width, ascii = false) {
596
- const dots = ascii ? "..." : "…";
597
- const chars = [...text];
598
- if (width <= 0) return "";
599
- if (chars.length <= width) return text;
600
- if (width <= dots.length) return dots.slice(0, width);
601
- return chars.slice(0, width - dots.length).join("") + dots;
602
- }
603
- /** Swap the few Unicode glyphs the app uses for plain ones, when the terminal needs that. */
604
- function plain(text, ascii) {
605
- if (!ascii) return text;
606
- return text.replace(/·/g, "-").replace(/⏎/g, "Enter").replace(/↑↓/g, "Up/Down").replace(/›/g, ">").replace(/…/g, "...");
607
- }
608
- /** One line of text, cut with `…`. Never wraps. */
609
- function Ell({ width, color, bold, dim, children }) {
610
- const { ascii } = useTheme();
611
- const one = children.replace(/\s*\n\s*/g, " ");
612
- return /* @__PURE__ */ jsx(Text, {
613
- wrap: "truncate",
614
- ...color ? { color } : {},
615
- ...bold ? { bold } : {},
616
- ...dim ? { dimColor: dim } : {},
617
- children: cut(one, width, ascii)
618
- });
619
- }
620
- const CHIPS = {
621
- claude: "cl",
622
- codex: "cx",
623
- opencode: "oc",
624
- antigravity: "ag",
625
- grok: "gr",
626
- cursor: "cu",
627
- copilot: "cp"
628
- };
629
- /** Two-letter monogram of a CLI. */
630
- function chipText(cli) {
631
- return CHIPS[cli] ?? cli.slice(0, 2).toLowerCase();
632
- }
633
- function Chip({ cli, dim }) {
634
- const { c } = useTheme();
635
- const text = chipText(cli).padEnd(2).slice(0, 2);
636
- if (!c.surface) return /* @__PURE__ */ jsx(Text, {
637
- ...dim ? { dimColor: true } : {},
638
- children: `[${text}]`
639
- });
640
- return /* @__PURE__ */ jsx(Text, {
641
- bold: true,
642
- backgroundColor: c.surface,
643
- ...c.entry ? { color: c.entry } : {},
644
- ...dim ? { dimColor: true } : {},
645
- children: ` ${text} `
646
- });
647
- }
648
- /** A small, dim, uppercase section label. */
649
- function Label({ children }) {
650
- const { c, ascii } = useTheme();
651
- return /* @__PURE__ */ jsx(Text, {
652
- ...c.quiet ? { color: c.quiet } : { dimColor: true },
653
- children: plain(children.toUpperCase(), ascii)
654
- });
655
- }
656
- /** A bordered box. */
657
- function Card({ accent, width, fill, children }) {
658
- const { c, ascii } = useTheme();
659
- const color = accent ?? c.rule;
660
- return /* @__PURE__ */ jsx(Box, {
661
- flexDirection: "column",
662
- borderStyle: ascii ? "classic" : "round",
663
- ...color ? { borderColor: color } : {},
664
- paddingX: 1,
665
- ...fill && c.surface ? { backgroundColor: c.surface } : {},
666
- ...width !== void 0 ? { width } : {},
667
- children
668
- });
669
- }
670
- /** "now", "3m", "2h", "2 days ago". */
671
- function relTime(iso, now = Date.now()) {
672
- const t = Date.parse(iso);
673
- if (Number.isNaN(t)) return "";
674
- const s = Math.max(0, Math.floor((now - t) / 1e3));
675
- if (s < 60) return "now";
676
- const m = Math.floor(s / 60);
677
- if (m < 60) return `${m}m`;
678
- const h = Math.floor(m / 60);
679
- if (h < 24) return `${h}h`;
680
- const d = Math.floor(h / 24);
681
- return d === 1 ? "1 day ago" : `${d} days ago`;
682
- }
683
- /**
684
- * The home folder as `~`. Knows this machine's home and the usual homes of other machines:
685
- * `/home/x`, `/Users/x`, and `C:\Users\x` or `C:/Users/x` in any case. Separators stay as given.
686
- */
687
- function homePath(path, home = homedir()) {
688
- const h = home.replace(/[\\/]+$/, "");
689
- if (h !== "" && path.length >= h.length) {
690
- const head = path.slice(0, h.length);
691
- const next = path[h.length];
692
- if ((/^[A-Za-z]:/.test(h) ? head.toLowerCase() === h.toLowerCase() : head === h) && (next === void 0 || next === "/" || next === "\\")) return `~${path.slice(h.length)}`;
693
- }
694
- return path.replace(/^(?:\/home\/[^/]+|\/Users\/[^/]+|[A-Za-z]:[\\/]Users[\\/][^\\/]+)(?=[\\/]|$)/i, "~");
695
- }
696
- /**
697
- * A folder for a column `width` wide: home as `~`, and when it is too long, cut from the left so
698
- * the end stays: `…/NOV-2026/win-trouble`. Separators are kept as the path has them.
699
- */
700
- function shortPath$1(path, width, ascii = false, home) {
701
- const dots = ascii ? "..." : "…";
702
- const p = homePath(path, home);
703
- if (width <= 0) return "";
704
- if ([...p].length <= width) return p;
705
- const sep = p.lastIndexOf("\\") > p.lastIndexOf("/") ? "\\" : "/";
706
- const parts = p.split(/[\\/]+/).filter((x) => x !== "");
707
- const kept = [];
708
- let used = dots.length + 1;
709
- for (let i = parts.length - 1; i >= 0; i--) {
710
- const part = parts[i] ?? "";
711
- const add = [...part].length + (kept.length > 0 ? 1 : 0);
712
- if (used + add > width) break;
713
- used += add;
714
- kept.unshift(part);
715
- }
716
- if (kept.length > 0) return `${dots}${sep}${kept.join(sep)}`;
717
- const last = [...parts[parts.length - 1] ?? p];
718
- return dots + last.slice(Math.max(0, last.length - (width - dots.length))).join("");
719
- }
720
- /** A full-width bar on the surface colour. */
721
- function Band({ width, children }) {
722
- const { c } = useTheme();
723
- return /* @__PURE__ */ jsx(Box, {
724
- width,
725
- height: 1,
726
- flexShrink: 0,
727
- paddingX: 1,
728
- ...c.surface ? { backgroundColor: c.surface } : {},
729
- children
730
- });
731
- }
732
- /** A horizontal rule. */
733
- function Rule({ width }) {
734
- const { c, ascii } = useTheme();
735
- return /* @__PURE__ */ jsx(Text, {
736
- ...c.rule ? { color: c.rule } : { dimColor: true },
737
- children: (ascii ? "-" : "─").repeat(Math.max(0, width))
738
- });
739
- }
740
- /**
741
- * The side panel: sunken colour, a vertical rule on its left. `width` includes the rule and one
742
- * column of padding each side, so the text inside gets `width - 3`.
743
- */
744
- const paneInner = (width) => Math.max(4, width - 3);
745
- function Pane({ width, height, children }) {
746
- const { c, ascii } = useTheme();
747
- return /* @__PURE__ */ jsx(Box, {
748
- width,
749
- flexShrink: 0,
750
- flexDirection: "column",
751
- overflow: "hidden",
752
- borderStyle: ascii ? "classic" : "single",
753
- borderTop: false,
754
- borderRight: false,
755
- borderBottom: false,
756
- ...c.rule ? { borderColor: c.rule } : { borderDimColor: true },
757
- ...c.sunken ? {
758
- backgroundColor: c.sunken,
759
- borderLeftBackgroundColor: c.sunken
760
- } : {},
761
- paddingX: 1,
762
- ...height !== void 0 ? { height } : {},
763
- children
764
- });
765
- }
766
- /**
767
- * Split a screen into main part and side panel. On very wide terminals the main part stops at
768
- * `maxMain` and the panel sits right after it. Without a panel, main is capped alone.
769
- */
770
- function splitWidths(columns, panel, opts = {}) {
771
- const maxMain = opts.maxMain ?? 130;
772
- if (!panel) return {
773
- mainW: Math.min(columns, maxMain),
774
- panelW: 0
775
- };
776
- const panelW = opts.panelW ?? (columns >= 160 ? 40 : 36);
777
- return {
778
- mainW: Math.min(maxMain, Math.max(30, columns - panelW)),
779
- panelW
780
- };
781
- }
782
- /** One cell of a table row: `w` columns wide, the last `gap` of them empty. Never overflows. */
783
- function Cell({ w, gap = 2, color, bold, dim, children }) {
784
- return /* @__PURE__ */ jsx(Box, {
785
- width: w,
786
- flexShrink: 0,
787
- children: /* @__PURE__ */ jsx(Ell, {
788
- width: Math.max(0, w - gap),
789
- color,
790
- ...bold ? { bold } : {},
791
- ...dim ? { dim } : {},
792
- children
793
- })
794
- });
795
- }
796
- /** A table row. The selected one gets the highlight across the whole width. */
797
- function Row({ width, selected, children }) {
798
- const { c } = useTheme();
799
- return /* @__PURE__ */ jsx(Box, {
800
- width,
801
- flexShrink: 0,
802
- ...selected && c.select ? { backgroundColor: c.select } : {},
803
- children
804
- });
805
- }
806
- /** The header row of a table: small, dim capitals. */
807
- function HeaderRow({ width, cols }) {
808
- const { c } = useTheme();
809
- return /* @__PURE__ */ jsx(Box, {
810
- width,
811
- flexShrink: 0,
812
- children: cols.map((col) => /* @__PURE__ */ jsx(Cell, {
813
- w: col.w,
814
- ...col.gap !== void 0 ? { gap: col.gap } : {},
815
- color: c.quiet,
816
- dim: !c.quiet,
817
- children: col.text.toUpperCase()
818
- }, col.text || col.w))
819
- });
820
- }
821
- /** A list that keeps the selected row in view and says how many rows are hidden. */
822
- function ScrollList({ items, selected, height, renderItem, keyOf, onSelect, onActivate, isActive }) {
823
- const { c, ascii } = useTheme();
824
- const box = useRef(null);
825
- const h = Math.max(1, height);
826
- const total = items.length;
827
- let slots = h;
828
- let start = 0;
829
- if (total > h) for (let pass = 0; pass < 3; pass++) {
830
- slots = Math.max(1, h - (start > 0 ? 1 : 0) - (start + slots < total ? 1 : 0));
831
- if (selected < start) start = selected;
832
- if (selected >= start + slots) start = selected - slots + 1;
833
- start = Math.max(0, Math.min(start, total - slots));
834
- }
835
- const end = Math.min(total, start + slots);
836
- const view = useRef({
837
- start,
838
- end,
839
- selected,
840
- total
841
- });
842
- view.current = {
843
- start,
844
- end,
845
- selected,
846
- total
847
- };
848
- useClick(box, (e) => {
849
- if (e.button !== "left") return;
850
- const v = view.current;
851
- const kids = box.current?.childNodes ?? [];
852
- const first = v.start > 0 ? 1 : 0;
853
- for (let i = v.start; i < v.end; i++) {
854
- const kid = kids[first + i - v.start];
855
- const y = kid && "yogaNode" in kid ? kid.yogaNode : void 0;
856
- if (!y) continue;
857
- const top = y.getComputedTop();
858
- if (e.y < top || e.y >= top + y.getComputedHeight()) continue;
859
- if (i !== v.selected) onSelect?.(i);
860
- if (i === v.selected || e.double) onActivate?.(i);
861
- return;
862
- }
863
- }, { isActive: (isActive ?? true) && (onSelect !== void 0 || onActivate !== void 0) });
864
- useWheel(box, (d) => {
865
- const v = view.current;
866
- onSelect?.(Math.max(0, Math.min(v.total - 1, v.selected + d)));
867
- }, { isActive: (isActive ?? true) && onSelect !== void 0 });
868
- if (total === 0) return null;
869
- const above = start;
870
- const below = total - end;
871
- const dots = ascii ? "..." : "…";
872
- const quiet = c.quiet ? { color: c.quiet } : { dimColor: true };
873
- return /* @__PURE__ */ jsxs(Box, {
874
- ref: box,
875
- flexDirection: "column",
876
- children: [
877
- above > 0 ? /* @__PURE__ */ jsx(Text, {
878
- ...quiet,
879
- children: `${dots} ${above} more`
880
- }) : null,
881
- items.slice(start, end).map((item, i) => /* @__PURE__ */ jsx(Box, { children: renderItem(item, start + i === selected, start + i) }, keyOf(item, start + i))),
882
- below > 0 ? /* @__PURE__ */ jsx(Text, {
883
- ...quiet,
884
- children: `${dots} ${below} more`
885
- }) : null
886
- ]
887
- });
888
- }
889
- /**
890
- * The shell provides this. A text box with unsent text tells it when Ctrl+C cleared that text,
891
- * so the shell shows a hint instead of quitting.
892
- */
893
- const DraftContext = createContext({ cleared: () => void 0 });
894
- const DraftProvider = DraftContext.Provider;
895
- /** A small input. Enter sends; Shift+Enter (or Ctrl+J) adds a line when `multiline`. */
896
- function TextBox({ value, onChange, onSubmit, placeholder, focus, multiline, onCancel, onFocusRequest }) {
897
- const { c, ascii } = useTheme();
898
- const area = useRef(null);
899
- useClick(area, () => onFocusRequest?.(), { isActive: onFocusRequest !== void 0 });
900
- const [cursor, setCursor] = useState(value.length);
901
- const pos = Math.min(cursor, value.length);
902
- const draft = useContext(DraftContext);
903
- useInput((input, key) => {
904
- if (key.ctrl && input === "c") {
905
- if (value !== "") {
906
- onChange("");
907
- setCursor(0);
908
- draft.cleared();
909
- }
910
- return;
911
- }
912
- if (key.escape) {
913
- onCancel?.();
914
- return;
915
- }
916
- if (key.return) {
917
- if (multiline && key.shift) {
918
- onChange(`${value.slice(0, pos)}\n${value.slice(pos)}`);
919
- setCursor(pos + 1);
920
- } else onSubmit(value);
921
- return;
922
- }
923
- if (key.leftArrow) return setCursor(Math.max(0, pos - 1));
924
- if (key.rightArrow) return setCursor(Math.min(value.length, pos + 1));
925
- if (key.ctrl && input === "a") return setCursor(0);
926
- if (key.ctrl && input === "e") return setCursor(value.length);
927
- if (key.ctrl && input === "u") {
928
- onChange(value.slice(pos));
929
- return setCursor(0);
930
- }
931
- if (key.backspace || key.delete) {
932
- if (pos === 0) return;
933
- onChange(value.slice(0, pos - 1) + value.slice(pos));
934
- return setCursor(pos - 1);
935
- }
936
- if (key.ctrl && input === "j" && multiline) {
937
- onChange(`${value.slice(0, pos)}\n${value.slice(pos)}`);
938
- return setCursor(pos + 1);
939
- }
940
- if (key.ctrl || key.meta || key.upArrow || key.downArrow || key.tab) return;
941
- if (input) {
942
- const clean = multiline ? input.replace(/\r\n?/g, "\n") : input.replace(/[\r\n]+/g, " ");
943
- onChange(value.slice(0, pos) + clean + value.slice(pos));
944
- setCursor(pos + clean.length);
945
- }
946
- }, { isActive: focus });
947
- const quiet = c.quiet ? { color: c.quiet } : { dimColor: true };
948
- const wrap = (node) => onFocusRequest ? /* @__PURE__ */ jsx(Box, {
949
- ref: area,
950
- children: node
951
- }) : node;
952
- if (value.length === 0) return wrap(/* @__PURE__ */ jsxs(Text, { children: [focus ? /* @__PURE__ */ jsx(Text, {
953
- inverse: true,
954
- children: " "
955
- }) : null, /* @__PURE__ */ jsx(Text, {
956
- ...quiet,
957
- children: placeholder ?? ""
958
- })] }));
959
- const before = value.slice(0, pos);
960
- const at = value[pos] ?? " ";
961
- const after = value.slice(pos + 1);
962
- return wrap(/* @__PURE__ */ jsxs(Text, { children: [
963
- before,
964
- focus ? /* @__PURE__ */ jsx(Text, {
965
- inverse: true,
966
- children: at === "\n" ? " \n" : at
967
- }) : at,
968
- after
969
- ] }));
970
- }
971
- // src/tui/palette.tsx
972
- /** The command palette and the all-keys help, drawn over the screen body. */
973
- /**
974
- * Subsequence match. Higher is better; undefined means no match. Starts of words and runs of
975
- * letters score more, so "ses" finds "Go to Sessions" before "Pause everything".
976
- */
977
- function fuzzy(query, text) {
978
- const q = query.toLowerCase().replace(/\s+/g, "");
979
- if (q === "") return 0;
980
- const t = text.toLowerCase();
981
- let score = 0;
982
- let from = 0;
983
- let run = 0;
984
- for (const ch of q) {
985
- const i = t.indexOf(ch, from);
986
- if (i < 0) return void 0;
987
- const startOfWord = i === 0 || t[i - 1] === " ";
988
- run = i === from ? run + 1 : 0;
989
- score += 1 + run * 2 + (startOfWord ? 4 : 0) - Math.min(i - from, 5) * .2;
990
- from = i + 1;
991
- }
992
- return score;
993
- }
994
- function filterCommands(cmds, query) {
995
- return cmds.map((c, i) => ({
996
- c,
997
- i,
998
- s: fuzzy(query, c.label)
999
- })).filter((x) => x.s !== void 0).sort((a, b) => b.s - a.s || (a.c.rank ?? 50) - (b.c.rank ?? 50) || a.i - b.i).map((x) => x.c);
1000
- }
1001
- function Palette({ commands, width, height, onClose }) {
1002
- const { c, ascii } = useTheme();
1003
- const [query, setQuery] = useState("");
1004
- const [sel, setSel] = useState(0);
1005
- const shown = useMemo(() => filterCommands(commands, query), [commands, query]);
1006
- const index = Math.min(sel, Math.max(0, shown.length - 1));
1007
- const rowsMax = Math.max(1, height - 5);
1008
- useInput((_input, key) => {
1009
- if (key.upArrow) setSel(Math.max(0, index - 1));
1010
- else if (key.downArrow) setSel(Math.min(shown.length - 1, index + 1));
1011
- });
1012
- const runCmd = (cmd) => {
1013
- onClose();
1014
- if (cmd) Promise.resolve(cmd.run()).catch(() => void 0);
1015
- };
1016
- const run = () => runCmd(shown[index]);
1017
- const list = useRef(null);
1018
- useWheel(list, (d) => setSel(Math.max(0, Math.min(shown.length - 1, index + d))));
1019
- const inner = Math.max(10, width - 4);
1020
- const start = Math.max(0, Math.min(index - rowsMax + 1, shown.length - rowsMax));
1021
- const view = shown.slice(start, start + rowsMax);
1022
- return /* @__PURE__ */ jsx(Clickable, {
1023
- onClick: () => void 0,
1024
- children: /* @__PURE__ */ jsxs(Card, {
1025
- ...c.entry ? { accent: c.entry } : {},
1026
- fill: true,
1027
- width,
1028
- children: [
1029
- /* @__PURE__ */ jsx(TextBox, {
1030
- value: query,
1031
- onChange: (v) => {
1032
- setQuery(v);
1033
- setSel(0);
1034
- },
1035
- onSubmit: run,
1036
- onCancel: onClose,
1037
- placeholder: "Type to find something to do",
1038
- focus: true
1039
- }),
1040
- /* @__PURE__ */ jsx(Box, {
1041
- ref: list,
1042
- flexDirection: "column",
1043
- marginTop: 1,
1044
- children: view.length === 0 ? /* @__PURE__ */ jsx(Text, {
1045
- ...c.quiet ? { color: c.quiet } : { dimColor: true },
1046
- children: "Nothing matches that."
1047
- }) : view.map((cmd) => {
1048
- const on = cmd === shown[index];
1049
- return /* @__PURE__ */ jsxs(PaletteRow, {
1050
- onPick: () => runCmd(cmd),
1051
- children: [
1052
- /* @__PURE__ */ jsxs(Text, {
1053
- ...on ? c.select ? {
1054
- backgroundColor: c.select,
1055
- bold: true
1056
- } : { inverse: true } : {},
1057
- children: [on ? ascii ? "> " : "› " : " ", /* @__PURE__ */ jsx(Ell, {
1058
- width: Math.max(4, inner - 12),
1059
- children: cmd.label
1060
- })]
1061
- }),
1062
- /* @__PURE__ */ jsx(Box, { flexGrow: 1 }),
1063
- /* @__PURE__ */ jsx(Text, {
1064
- ...c.quiet ? { color: c.quiet } : { dimColor: true },
1065
- children: plain(cmd.key ?? "", ascii)
1066
- })
1067
- ]
1068
- }, cmd.id);
1069
- })
1070
- }),
1071
- /* @__PURE__ */ jsx(Box, {
1072
- marginTop: 1,
1073
- children: /* @__PURE__ */ jsx(Text, {
1074
- ...c.quiet ? { color: c.quiet } : { dimColor: true },
1075
- children: plain("↑↓ move · ⏎ run · Esc close", ascii)
1076
- })
1077
- })
1078
- ]
1079
- })
1080
- });
1081
- }
1082
- /** One palette row: a click selects it and runs it. */
1083
- function PaletteRow({ onPick, children }) {
1084
- const ref = useRef(null);
1085
- useClick(ref, (e) => {
1086
- if (e.button === "left") onPick();
1087
- });
1088
- return /* @__PURE__ */ jsx(Box, {
1089
- ref,
1090
- children
1091
- });
1092
- }
1093
- function Help({ screenTitle, screenKeys, width, onClose }) {
1094
- const { c, ascii } = useTheme();
1095
- useInput((input, key) => {
1096
- if (key.escape || input === "?" || input === "q" || key.return) onClose();
1097
- });
1098
- const global = [
1099
- {
1100
- key: "1-4",
1101
- label: "go to a screen"
1102
- },
1103
- {
1104
- key: "/ or Ctrl+K",
1105
- label: "find anything to do"
1106
- },
1107
- {
1108
- key: "?",
1109
- label: "this list"
1110
- },
1111
- {
1112
- key: "Esc",
1113
- label: "back"
1114
- },
1115
- {
1116
- key: "q",
1117
- label: "quit (sessions keep running)"
1118
- },
1119
- {
1120
- key: "Ctrl+C",
1121
- label: "quit now"
1122
- }
1123
- ];
1124
- const row = (k) => /* @__PURE__ */ jsxs(Box, { children: [/* @__PURE__ */ jsx(Box, {
1125
- width: 14,
1126
- children: /* @__PURE__ */ jsx(Text, {
1127
- bold: true,
1128
- ...c.ink ? { color: c.ink } : {},
1129
- children: plain(k.key, ascii)
1130
- })
1131
- }), /* @__PURE__ */ jsx(Ell, {
1132
- width: Math.max(8, width - 20),
1133
- children: plain(k.label, ascii)
1134
- })] }, `${k.key}-${k.label}`);
1135
- return /* @__PURE__ */ jsx(Clickable, {
1136
- onClick: () => void 0,
1137
- children: /* @__PURE__ */ jsxs(Card, {
1138
- ...c.entry ? { accent: c.entry } : {},
1139
- fill: true,
1140
- width,
1141
- children: [
1142
- /* @__PURE__ */ jsx(Label, { children: "Everywhere" }),
1143
- global.map(row),
1144
- /* @__PURE__ */ jsx(Box, {
1145
- marginTop: 1,
1146
- children: /* @__PURE__ */ jsx(Label, { children: screenTitle })
1147
- }),
1148
- screenKeys.length === 0 ? /* @__PURE__ */ jsx(Text, {
1149
- ...c.quiet ? { color: c.quiet } : { dimColor: true },
1150
- children: "No other keys here."
1151
- }) : screenKeys.map(row),
1152
- /* @__PURE__ */ jsx(Box, {
1153
- marginTop: 1,
1154
- children: /* @__PURE__ */ jsx(Text, {
1155
- ...c.quiet ? { color: c.quiet } : { dimColor: true },
1156
- children: "Esc or ? to close"
1157
- })
1158
- })
1159
- ]
1160
- })
1161
- });
1162
- }
1163
- // src/tui/screens/kit.tsx
1164
- /** Small helpers the New, Devices and Setup screens share. */
1165
- /** A Box that takes left clicks and/or the wheel. Other props go to the Box. */
1166
- function Hit({ onClick, onWheel, isActive = true, children, ...box }) {
1167
- const ref = useRef(null);
1168
- useClick(ref, (e) => {
1169
- if (e.button === "left") onClick?.(e);
1170
- }, { isActive: isActive && onClick !== void 0 });
1171
- useWheel(ref, (d) => onWheel?.(d), { isActive: isActive && onWheel !== void 0 });
1172
- return /* @__PURE__ */ jsx(Box, {
1173
- ref,
1174
- ...box,
1175
- children
1176
- });
1177
- }
1178
- /** A counter that ticks every `ms` while `on`. Drives spinners and countdowns. */
1179
- function useTick(on, ms = 120) {
1180
- const [n, setN] = useState(0);
1181
- useEffect(() => {
1182
- if (!on) return;
1183
- const id = setInterval(() => setN((x) => x + 1), ms);
1184
- return () => clearInterval(id);
1185
- }, [on, ms]);
1186
- return n;
1187
- }
1188
- const FRAMES = [
1189
- "⠋",
1190
- "⠙",
1191
- "⠹",
1192
- "⠸",
1193
- "⠼",
1194
- "⠴",
1195
- "⠦",
1196
- "⠧",
1197
- "⠇",
1198
- "⠏"
1199
- ];
1200
- const ASCII_FRAMES = [
1201
- "|",
1202
- "/",
1203
- "-",
1204
- "\\"
1205
- ];
1206
- function Spinner({ tick }) {
1207
- const { ascii, c } = useTheme();
1208
- const f = ascii ? ASCII_FRAMES : FRAMES;
1209
- return /* @__PURE__ */ jsx(Text, {
1210
- ...c.info ? { color: c.info } : {},
1211
- children: f[tick % f.length]
1212
- });
1213
- }
1214
- /** Marks that carry meaning without colour. */
1215
- function useMarks() {
1216
- const { ascii } = useTheme();
1217
- return {
1218
- ok: ascii ? "ok" : "✓",
1219
- warn: "!",
1220
- error: ascii ? "x" : "✗",
1221
- info: ascii ? "-" : "·",
1222
- pending: ascii ? "." : "○",
1223
- enter: ascii ? "Enter" : "⏎",
1224
- ellipsis: ascii ? "..." : "…",
1225
- radioOn: ascii ? "(*)" : "◉",
1226
- radioOff: ascii ? "( )" : "○",
1227
- cursor: ascii ? ">" : "▸"
1228
- };
1229
- }
1230
- /** `m:ss` from milliseconds. */
1231
- function clock(ms) {
1232
- const s = Math.max(0, Math.ceil(ms / 1e3));
1233
- return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
1234
- }
1235
- // src/tui/screens/devices.tsx
1236
- var devices_exports = /* @__PURE__ */ __exportAll({
1237
- accountLine: () => accountLine,
1238
- default: () => DevicesScreen,
1239
- machinesOf: () => machinesOf
1240
- });
1241
- /** Machines to list, this one first. Pure, for tests. */
1242
- function machinesOf(state) {
1243
- const list = state.devices?.devices;
1244
- if (list && list.length > 0) return [...list].sort((a, b) => Number(b.self) - Number(a.self));
1245
- const r = state.relay;
1246
- if (!r) return [];
1247
- return [{
1248
- deviceId: r.device.deviceId,
1249
- name: r.device.name,
1250
- fingerprint: r.device.fingerprint,
1251
- self: true,
1252
- online: true,
1253
- sessions: 0
1254
- }, ...r.peers];
1255
- }
1256
- /** `Signed in · Pro trial, 12 days left (u to manage)`. Pure, for tests. */
1257
- function accountLine(a) {
1258
- if (!a?.signedIn) return "Not signed in";
1259
- const plan = a.plan ?? "";
1260
- const days = a.trialDaysLeft;
1261
- const trial = days !== void 0 && days >= 0;
1262
- return `Signed in · ${/pro/i.test(plan) ? trial ? `Pro trial, ${days} ${days === 1 ? "day" : "days"} left` : "Pro" : plan || "Free"} (u to manage)`;
1263
- }
1264
- function DevicesScreen(props) {
1265
- const { state, actions, layout, rows, columns, active, setKeys, setCommands, toast, setTyping } = props;
1266
- const { c } = useTheme();
1267
- const m = useMarks();
1268
- const [sel, setSel] = useState(0);
1269
- const [phase, setPhase] = useState({ k: "idle" });
1270
- const [ask, setAsk] = useState();
1271
- const cancelled = useRef(false);
1272
- const startCount = useRef(0);
1273
- const machines = useMemo(() => machinesOf(state), [state]);
1274
- const relayState = state.relay?.state;
1275
- const pitch = state.connection === "ready" && ((state.account ? !state.account.signedIn : false) || relayState === "logged_out" || relayState === "not_pro");
1276
- const pairing = phase.k !== "idle" && phase.k !== "done" && phase.k !== "failed";
1277
- const typing = phase.k === "confirm" && !phase.sending;
1278
- const at = Math.min(sel, Math.max(0, machines.length - 1));
1279
- const tick = useTick(phase.k === "waiting" || phase.k === "finishing" || phase.k === "confirm");
1280
- useEffect(() => {
1281
- setTyping(typing && active);
1282
- return () => setTyping(false);
1283
- }, [
1284
- typing,
1285
- active,
1286
- setTyping
1287
- ]);
1288
- const startPairing = useCallback(async () => {
1289
- if (pairing) return;
1290
- if (pitch || !state.relay || state.relay.state === "revoked") return toast("Sync isn't on for this machine yet. Press u to sign in.", "warn");
1291
- cancelled.current = false;
1292
- startCount.current = state.devices?.devices.length ?? 0;
1293
- const since = Date.now();
1294
- setPhase({
1295
- k: "waiting",
1296
- since
1297
- });
1298
- try {
1299
- const r = await actions.pair();
1300
- if (cancelled.current) return;
1301
- setPhase({
1302
- k: "confirm",
1303
- words: r.words,
1304
- expiresAt: Date.parse(r.expiresAt) || since + 3e5,
1305
- code: ""
1306
- });
1307
- } catch (e) {
1308
- if (cancelled.current) return;
1309
- setPhase({
1310
- k: "failed",
1311
- error: e instanceof Error ? e.message : "Pairing did not start."
1312
- });
1313
- }
1314
- }, [
1315
- pairing,
1316
- pitch,
1317
- state.relay,
1318
- state.devices,
1319
- actions,
1320
- toast
1321
- ]);
1322
- const decline = useCallback(async () => {
1323
- cancelled.current = true;
1324
- setPhase({ k: "idle" });
1325
- await actions.cancelPair().catch(() => void 0);
1326
- toast("Nothing got linked.", "ok");
1327
- }, [actions, toast]);
1328
- const submitCode = useCallback(async (code) => {
1329
- if (phase.k !== "confirm" || phase.sending) return;
1330
- const clean = code.trim();
1331
- if (!clean) return;
1332
- setPhase({
1333
- ...phase,
1334
- sending: true
1335
- });
1336
- try {
1337
- await actions.confirmPair(clean);
1338
- setPhase({ k: "finishing" });
1339
- } catch (e) {
1340
- setPhase({
1341
- ...phase,
1342
- sending: false,
1343
- code: "",
1344
- error: e instanceof Error ? e.message : "That is not the code the other machine shows."
1345
- });
1346
- }
1347
- }, [phase, actions]);
1348
- useEffect(() => {
1349
- if (phase.k !== "finishing") return;
1350
- const id = setInterval(() => {
1351
- (async () => {
1352
- const s = await actions.pairStatus().catch(() => void 0);
1353
- if (s?.state === "done") setPhase({ k: "done" });
1354
- else if (s?.state === "failed") setPhase({
1355
- k: "failed",
1356
- error: s.error ?? "The other machine stopped."
1357
- });
1358
- })();
1359
- }, 500);
1360
- return () => clearInterval(id);
1361
- }, [phase.k, actions]);
1362
- useEffect(() => {
1363
- if (phase.k === "finishing" && (state.devices?.devices.length ?? 0) > startCount.current) setPhase({ k: "done" });
1364
- }, [phase.k, state.devices]);
1365
- useEffect(() => {
1366
- if (phase.k === "done") toast("Linked. The two machines now see each other.", "ok");
1367
- }, [phase.k, toast]);
1368
- useEffect(() => {
1369
- if (phase.k !== "confirm") return;
1370
- const left = phase.expiresAt - Date.now();
1371
- if (left <= 0) return setPhase({
1372
- k: "failed",
1373
- error: "The code ran out. Start again on both machines."
1374
- });
1375
- const id = setTimeout(() => setPhase({
1376
- k: "failed",
1377
- error: "The code ran out. Start again on both machines."
1378
- }), left);
1379
- return () => clearTimeout(id);
1380
- }, [phase]);
1381
- useEffect(() => {
1382
- if (phase.k === "confirm" && !phase.sending) setKeys([{
1383
- key: m.enter,
1384
- label: "confirm code"
1385
- }, {
1386
- key: "Esc",
1387
- label: "different? stop"
1388
- }]);
1389
- else if (pairing) setKeys([{
1390
- key: "Esc",
1391
- label: "stop"
1392
- }]);
1393
- else if (pitch) setKeys([{
1394
- key: "u",
1395
- label: "sign in"
1396
- }]);
1397
- else setKeys([
1398
- {
1399
- key: "p",
1400
- label: "add a machine"
1401
- },
1402
- {
1403
- key: "r",
1404
- label: "remove"
1405
- },
1406
- {
1407
- key: "R",
1408
- label: "remove all"
1409
- },
1410
- {
1411
- key: "u",
1412
- label: "account"
1413
- }
1414
- ]);
1415
- }, [
1416
- phase,
1417
- pairing,
1418
- pitch,
1419
- setKeys,
1420
- m.enter
1421
- ]);
1422
- useEffect(() => {
1423
- setCommands([{
1424
- id: "devices.pair",
1425
- label: "Add a machine",
1426
- key: "p",
1427
- run: () => void startPairing()
1428
- }, {
1429
- id: "devices.account",
1430
- label: "Sign in or manage my account",
1431
- key: "u",
1432
- run: () => void actions.openAccountPage()
1433
- }]);
1434
- }, [
1435
- setCommands,
1436
- startPairing,
1437
- actions
1438
- ]);
1439
- const answer = useCallback(async (yes) => {
1440
- const a = ask;
1441
- setAsk(void 0);
1442
- if (!yes || !a) return;
1443
- try {
1444
- if (a.k === "revoke") {
1445
- await actions.revokeDevice(a.device.deviceId);
1446
- toast(`Removed ${a.device.name}`, "ok");
1447
- } else {
1448
- await actions.openAccountPage();
1449
- toast("Sign in in your browser. Then run conveno devices reset here.", "ok");
1450
- }
1451
- } catch (e) {
1452
- toast(e instanceof Error ? e.message : "That did not work.", "error");
1453
- }
1454
- }, [
1455
- ask,
1456
- actions,
1457
- toast
1458
- ]);
1459
- const removeSelected = () => {
1460
- const d = machines[at];
1461
- if (!d) return;
1462
- if (d.self) return toast("That's this machine. Remove it from another machine.", "warn");
1463
- setAsk({
1464
- k: "revoke",
1465
- device: d
1466
- });
1467
- };
1468
- const closePair = () => setPhase({ k: "idle" });
1469
- useInput((input, key) => {
1470
- if (ask) {
1471
- if (input === "y") return void answer(true);
1472
- if (input === "n" || key.escape) return void answer(false);
1473
- return;
1474
- }
1475
- if (phase.k === "waiting" || phase.k === "finishing") {
1476
- if (input === "n" || key.escape) return void decline();
1477
- return;
1478
- }
1479
- if (phase.k === "confirm") return;
1480
- if (phase.k === "done" || phase.k === "failed") {
1481
- if (key.return || key.escape || input === "p") setPhase({ k: "idle" });
1482
- return;
1483
- }
1484
- if (key.upArrow) return setSel(Math.max(0, at - 1));
1485
- if (key.downArrow) return setSel(Math.min(machines.length - 1, at + 1));
1486
- if (input === "p") return void startPairing();
1487
- if (input === "u") return void actions.openAccountPage();
1488
- if (input === "r") return removeSelected();
1489
- if (input === "R") return setAsk({ k: "all" });
1490
- }, { isActive: active && !typing });
1491
- const wide = layout === "wide";
1492
- const split = splitWidths(columns, wide, {
1493
- panelW: 50,
1494
- maxMain: 100
1495
- });
1496
- const sideW = paneInner(split.panelW);
1497
- const mainW = wide ? split.mainW - 2 : Math.min(columns, 100);
1498
- const quiet = c.quiet ? { color: c.quiet } : { dimColor: true };
1499
- const pairPanel = (width) => /* @__PURE__ */ jsxs(Box, {
1500
- flexDirection: "column",
1501
- width,
1502
- children: [/* @__PURE__ */ jsx(Label, { children: "Add a machine" }), phase.k === "idle" ? /* @__PURE__ */ jsx(Hit, {
1503
- onClick: () => void (pitch || !state.relay ? actions.openAccountPage() : startPairing()),
1504
- isActive: active,
1505
- children: /* @__PURE__ */ jsx(Text, {
1506
- ...quiet,
1507
- children: pitch || !state.relay ? "Sign in first (u)." : "Press p to link another machine."
1508
- })
1509
- }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1510
- /* @__PURE__ */ jsx(Text, { children: "1. On the other machine, run" }),
1511
- /* @__PURE__ */ jsx(Text, {
1512
- bold: true,
1513
- children: " conveno devices join"
1514
- }),
1515
- phase.k === "waiting" ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Spinner, { tick }), ` Waiting for it${m.ellipsis} ${clock(phase.since + 3e5 - Date.now())}`] }), /* @__PURE__ */ jsx(Hit, {
1516
- onClick: () => void decline(),
1517
- isActive: active,
1518
- children: /* @__PURE__ */ jsx(Text, {
1519
- ...quiet,
1520
- children: "Esc stops"
1521
- })
1522
- })] }) : null,
1523
- phase.k === "confirm" ? /* @__PURE__ */ jsxs(Fragment, { children: [
1524
- /* @__PURE__ */ jsx(Text, { children: "2. This machine shows" }),
1525
- /* @__PURE__ */ jsx(Card, {
1526
- accent: c.info,
1527
- width: Math.min(width, 30),
1528
- children: /* @__PURE__ */ jsx(Text, {
1529
- bold: true,
1530
- children: ` ${phase.words.join(" ")}`
1531
- })
1532
- }),
1533
- /* @__PURE__ */ jsx(Text, { children: "3. Type that on the other machine. It shows a different code. Type it here:" }),
1534
- /* @__PURE__ */ jsxs(Box, { children: [/* @__PURE__ */ jsx(Text, {
1535
- bold: true,
1536
- children: " > "
1537
- }), /* @__PURE__ */ jsx(TextBox, {
1538
- value: phase.code,
1539
- onChange: (v) => setPhase({
1540
- ...phase,
1541
- code: v
1542
- }),
1543
- onSubmit: (v) => void submitCode(v),
1544
- onCancel: () => void decline(),
1545
- focus: active && !phase.sending,
1546
- placeholder: "the other machine's code"
1547
- })] }),
1548
- phase.error ? /* @__PURE__ */ jsx(Text, {
1549
- ...c.error ? { color: c.error } : {},
1550
- children: phase.error
1551
- }) : null,
1552
- /* @__PURE__ */ jsxs(Box, {
1553
- flexWrap: "wrap",
1554
- children: [
1555
- /* @__PURE__ */ jsx(Text, {
1556
- ...quiet,
1557
- children: "Wrong or different? "
1558
- }),
1559
- /* @__PURE__ */ jsx(Hit, {
1560
- onClick: () => void decline(),
1561
- isActive: active,
1562
- children: /* @__PURE__ */ jsx(Text, {
1563
- ...quiet,
1564
- children: "Press Esc"
1565
- })
1566
- }),
1567
- /* @__PURE__ */ jsx(Text, {
1568
- ...quiet,
1569
- children: ` and nothing gets linked. ${clock(phase.expiresAt - Date.now())} left`
1570
- })
1571
- ]
1572
- })
1573
- ] }) : null,
1574
- phase.k === "finishing" ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Spinner, { tick }), ` Waiting for the other machine to confirm${m.ellipsis}`] }), /* @__PURE__ */ jsx(Hit, {
1575
- onClick: () => void decline(),
1576
- isActive: active,
1577
- children: /* @__PURE__ */ jsx(Text, {
1578
- ...quiet,
1579
- children: "Esc stops"
1580
- })
1581
- })] }) : null,
1582
- phase.k === "done" ? /* @__PURE__ */ jsx(Hit, {
1583
- onClick: closePair,
1584
- isActive: active,
1585
- children: /* @__PURE__ */ jsx(Text, {
1586
- ...c.ok ? { color: c.ok } : {},
1587
- children: `${m.ok} Linked. Press ${m.enter}.`
1588
- })
1589
- }) : null,
1590
- phase.k === "failed" ? /* @__PURE__ */ jsx(Hit, {
1591
- onClick: closePair,
1592
- isActive: active,
1593
- children: /* @__PURE__ */ jsx(Text, {
1594
- ...c.error ? { color: c.error } : {},
1595
- wrap: "wrap",
1596
- children: `${m.error} ${phase.error} (${m.enter} to close)`
1597
- })
1598
- }) : null
1599
- ] })]
1600
- });
1601
- if (!state.relay && state.connection === "ready" && !state.account) return /* @__PURE__ */ jsx(Text, {
1602
- ...quiet,
1603
- children: `Checking sync${m.ellipsis}`
1604
- });
1605
- if (pitch) return /* @__PURE__ */ jsxs(Box, {
1606
- flexDirection: "column",
1607
- width: Math.min(mainW, 70),
1608
- children: [
1609
- /* @__PURE__ */ jsx(Label, { children: "Your machines" }),
1610
- /* @__PURE__ */ jsx(Text, { children: "Pro links your machines so sessions can talk across them." }),
1611
- /* @__PURE__ */ jsx(Hit, {
1612
- onClick: () => void actions.openAccountPage(),
1613
- isActive: active,
1614
- children: /* @__PURE__ */ jsxs(Text, { children: [
1615
- "Press ",
1616
- /* @__PURE__ */ jsx(Text, {
1617
- bold: true,
1618
- children: "u"
1619
- }),
1620
- " to sign in."
1621
- ] })
1622
- }),
1623
- /* @__PURE__ */ jsx(Text, {
1624
- ...quiet,
1625
- children: "We only see machine names and message sizes. Never what's inside."
1626
- })
1627
- ]
1628
- });
1629
- if (relayState === "revoked") return /* @__PURE__ */ jsxs(Box, {
1630
- flexDirection: "column",
1631
- width: mainW,
1632
- children: [/* @__PURE__ */ jsx(Text, {
1633
- ...c.error ? { color: c.error } : {},
1634
- children: "This machine was removed from your account."
1635
- }), /* @__PURE__ */ jsx(Text, { children: "Run conveno devices reset here, then link it again." })]
1636
- });
1637
- const longest = machines.reduce((n, d) => Math.max(n, [...d.self ? `${d.name} (this one)` : d.name].length), 0);
1638
- const nameW = Math.max(12, Math.min(40, longest + 1));
1639
- const sessionsW = Math.max(0, mainW - 2 - nameW - 2 - 9 - 2 - 20 - 2);
1640
- const showPair = pairing || phase.k === "done" || phase.k === "failed";
1641
- const table = /* @__PURE__ */ jsxs(Box, {
1642
- flexDirection: "column",
1643
- width: mainW,
1644
- children: [
1645
- /* @__PURE__ */ jsx(Hit, {
1646
- onClick: () => void actions.openAccountPage(),
1647
- isActive: active,
1648
- children: /* @__PURE__ */ jsx(Text, {
1649
- ...quiet,
1650
- children: accountLine(state.account)
1651
- })
1652
- }),
1653
- state.relay && state.relay.state !== "connected" && state.relay.state !== "unpaired" ? /* @__PURE__ */ jsx(Text, {
1654
- ...quiet,
1655
- children: state.relay.detail ?? (state.relay.state === "connecting" ? "Connecting…" : "Sync is offline, it keeps trying.")
1656
- }) : null,
1657
- /* @__PURE__ */ jsx(Text, { children: " " }),
1658
- /* @__PURE__ */ jsx(Label, { children: `Your machines · ${machines.length}` }),
1659
- machines.length === 0 ? /* @__PURE__ */ jsx(Hit, {
1660
- onClick: () => void startPairing(),
1661
- isActive: active,
1662
- children: /* @__PURE__ */ jsx(Text, {
1663
- ...quiet,
1664
- children: "Only this machine so far. Press p to add another."
1665
- })
1666
- }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(HeaderRow, {
1667
- width: mainW,
1668
- cols: [
1669
- {
1670
- w: 2,
1671
- text: "",
1672
- gap: 0
1673
- },
1674
- {
1675
- w: nameW + 2,
1676
- text: "Machine"
1677
- },
1678
- {
1679
- w: 11,
1680
- text: "Status"
1681
- },
1682
- {
1683
- w: 22,
1684
- text: "Added"
1685
- },
1686
- {
1687
- w: sessionsW,
1688
- text: "Sessions",
1689
- gap: 0
1690
- }
1691
- ]
1692
- }), /* @__PURE__ */ jsx(Hit, {
1693
- onWheel: (d) => setSel(Math.max(0, Math.min(machines.length - 1, at + (d < 0 ? -1 : 1)))),
1694
- isActive: active,
1695
- flexDirection: "column",
1696
- children: /* @__PURE__ */ jsx(ScrollList, {
1697
- items: machines,
1698
- selected: at,
1699
- height: Math.max(3, rows - 12),
1700
- keyOf: (d) => d.deviceId,
1701
- renderItem: (d, isSel, i) => /* @__PURE__ */ jsx(Hit, {
1702
- onClick: () => setSel(i),
1703
- isActive: active,
1704
- children: /* @__PURE__ */ jsxs(Row, {
1705
- width: mainW,
1706
- selected: isSel,
1707
- children: [
1708
- /* @__PURE__ */ jsx(Cell, {
1709
- w: 2,
1710
- gap: 0,
1711
- color: c.entry,
1712
- children: isSel ? `${m.cursor} ` : " "
1713
- }),
1714
- /* @__PURE__ */ jsx(Cell, {
1715
- w: nameW + 2,
1716
- bold: isSel,
1717
- children: d.self ? `${d.name} (this one)` : d.name
1718
- }),
1719
- /* @__PURE__ */ jsx(Cell, {
1720
- w: 11,
1721
- color: d.online ? c.ok : c.quiet,
1722
- dim: !d.online,
1723
- children: d.online ? "online" : "offline"
1724
- }),
1725
- /* @__PURE__ */ jsx(Cell, {
1726
- w: 22,
1727
- color: c.quiet,
1728
- children: d.self ? "" : d.addedAt ? `added ${relTime(d.addedAt)}` : ""
1729
- }),
1730
- /* @__PURE__ */ jsx(Cell, {
1731
- w: sessionsW,
1732
- gap: 0,
1733
- color: c.quiet,
1734
- children: d.self ? "" : `${d.sessions} ${d.sessions === 1 ? "session" : "sessions"}`
1735
- })
1736
- ]
1737
- })
1738
- })
1739
- })
1740
- })] }),
1741
- state.devices?.conflict ? /* @__PURE__ */ jsx(Text, {
1742
- ...c.error ? { color: c.error } : {},
1743
- wrap: "wrap",
1744
- children: `${m.error} Your machines' lists don't match. Run conveno devices for the steps.`
1745
- }) : null,
1746
- /* @__PURE__ */ jsx(Text, { children: " " }),
1747
- /* @__PURE__ */ jsx(Text, {
1748
- ...quiet,
1749
- children: "We only see machine names and message sizes. Never what's inside."
1750
- }),
1751
- ask ? /* @__PURE__ */ jsxs(Box, { children: [/* @__PURE__ */ jsx(Box, {
1752
- flexShrink: 1,
1753
- children: /* @__PURE__ */ jsxs(Text, {
1754
- wrap: "wrap",
1755
- children: [/* @__PURE__ */ jsx(Text, {
1756
- bold: true,
1757
- children: ask.k === "revoke" ? `Remove ${ask.device.name}?` : "Remove all machines?"
1758
- }), ask.k === "revoke" ? " It can't read or send messages for your sessions." : " This opens your browser to sign in. Then run conveno devices reset here."]
1759
- })
1760
- }), /* @__PURE__ */ jsxs(Box, {
1761
- flexShrink: 0,
1762
- children: [
1763
- /* @__PURE__ */ jsx(Text, { children: " " }),
1764
- /* @__PURE__ */ jsx(Hit, {
1765
- onClick: () => void answer(true),
1766
- isActive: active,
1767
- children: /* @__PURE__ */ jsx(Text, { children: "y" })
1768
- }),
1769
- /* @__PURE__ */ jsx(Text, { children: "/" }),
1770
- /* @__PURE__ */ jsx(Hit, {
1771
- onClick: () => void answer(false),
1772
- isActive: active,
1773
- children: /* @__PURE__ */ jsx(Text, { children: "n" })
1774
- })
1775
- ]
1776
- })] }) : /* @__PURE__ */ jsxs(Box, {
1777
- flexWrap: "wrap",
1778
- children: [
1779
- /* @__PURE__ */ jsx(Hit, {
1780
- onClick: () => void startPairing(),
1781
- isActive: active,
1782
- children: /* @__PURE__ */ jsx(Text, {
1783
- ...quiet,
1784
- children: "p adds a machine"
1785
- })
1786
- }),
1787
- /* @__PURE__ */ jsx(Text, {
1788
- ...quiet,
1789
- children: ". Lost a machine? "
1790
- }),
1791
- /* @__PURE__ */ jsx(Hit, {
1792
- onClick: removeSelected,
1793
- isActive: active,
1794
- children: /* @__PURE__ */ jsx(Text, {
1795
- ...quiet,
1796
- children: "r removes it"
1797
- })
1798
- }),
1799
- /* @__PURE__ */ jsx(Text, {
1800
- ...quiet,
1801
- children: ". "
1802
- }),
1803
- /* @__PURE__ */ jsx(Hit, {
1804
- onClick: () => setAsk({ k: "all" }),
1805
- isActive: active,
1806
- children: /* @__PURE__ */ jsx(Text, {
1807
- ...quiet,
1808
- children: "R removes all of them"
1809
- })
1810
- }),
1811
- /* @__PURE__ */ jsx(Text, {
1812
- ...quiet,
1813
- children: " (you sign in again first)."
1814
- })
1815
- ]
1816
- })
1817
- ]
1818
- });
1819
- if (wide) return /* @__PURE__ */ jsxs(Box, {
1820
- flexDirection: "row",
1821
- height: rows,
1822
- children: [/* @__PURE__ */ jsx(Box, {
1823
- width: split.mainW,
1824
- flexShrink: 0,
1825
- children: table
1826
- }), /* @__PURE__ */ jsx(Pane, {
1827
- width: split.panelW,
1828
- height: rows,
1829
- children: pairPanel(sideW)
1830
- })]
1831
- });
1832
- return showPair ? pairPanel(Math.min(columns - 2, 70)) : table;
1833
- }
1834
- // src/tui/screens/new.tsx
1835
- /** Screen 2: Start a new worker. */
1836
- var new_exports = /* @__PURE__ */ __exportAll({
1837
- completeDir: () => completeDir,
1838
- default: () => NewScreen,
1839
- expandPath: () => expandPath,
1840
- shortPath: () => shortPath,
1841
- spawnCommand: () => spawnCommand,
1842
- suggestName: () => suggestName
1843
- });
1844
- /** `~/code/api` to an absolute path. */
1845
- function expandPath(input, home, cwd) {
1846
- if (input === "~") return home;
1847
- if (input.startsWith("~/")) return join(home, input.slice(2));
1848
- return resolve(cwd, input);
1849
- }
1850
- /** An absolute path with `~` for the home folder. */
1851
- function shortPath(abs, home) {
1852
- if (abs === home) return "~";
1853
- return abs.startsWith(`${home}/`) ? `~/${abs.slice(home.length + 1)}` : abs;
1854
- }
1855
- /** Longest shared start of some strings. */
1856
- function commonStart(words) {
1857
- let out = words[0] ?? "";
1858
- for (const w of words) while (!w.startsWith(out)) out = out.slice(0, -1);
1859
- return out;
1860
- }
1861
- /** Tab completion for a folder: extends what is typed, or adds `/` when one folder fits. */
1862
- function completeDir(input, home, cwd) {
1863
- const slash = input.lastIndexOf("/");
1864
- const parentTyped = slash >= 0 ? input.slice(0, slash + 1) : "";
1865
- const prefix = slash >= 0 ? input.slice(slash + 1) : input;
1866
- const parentAbs = expandPath(parentTyped === "" ? "." : parentTyped, home, cwd);
1867
- let names;
1868
- try {
1869
- names = readdirSync(parentAbs, { withFileTypes: true }).filter((d) => d.isDirectory() && d.name.startsWith(prefix) && (prefix.startsWith(".") || !d.name.startsWith("."))).map((d) => d.name).sort();
1870
- } catch {
1871
- return input;
1872
- }
1873
- if (names.length === 0) return input;
1874
- if (names.length === 1) return `${parentTyped}${names[0]}/`;
1875
- const common = commonStart(names);
1876
- return common.length > prefix.length ? `${parentTyped}${common}` : input;
1877
- }
1878
- /** `<cli>-<folder>`, safe for a session name. */
1879
- function suggestName(cli, folder) {
1880
- const raw = basename(folder.replace(/\/+$/, ""));
1881
- const clean = (raw === "~" ? "home" : raw || "home").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1882
- return clean ? `${cli}-${clean}` : cli;
1883
- }
1884
- const quote = (s) => /^[\w@%+=:,./~-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
1885
- /** The `conveno spawn …` line that does the same. */
1886
- function spawnCommand(p) {
1887
- const parts = [
1888
- "conveno",
1889
- "spawn",
1890
- p.cli,
1891
- "--cwd",
1892
- quote(p.folder)
1893
- ];
1894
- if (p.name) parts.push("--name", quote(p.name));
1895
- if (p.window) parts.push("--window");
1896
- if (p.task.trim()) parts.push("--task", quote(p.task.trim().replace(/\s*\n\s*/g, " ")));
1897
- return [parts.join(" ")];
1898
- }
1899
- const ORDER = [
1900
- "cli",
1901
- "folder",
1902
- "name",
1903
- "task",
1904
- "window"
1905
- ];
1906
- const TEXT_FIELDS = [
1907
- "folder",
1908
- "name",
1909
- "task"
1910
- ];
1911
- function NewScreen(props) {
1912
- const { state, actions, layout, columns, active, setKeys, setCommands, go, toast, setTyping } = props;
1913
- const { c } = useTheme();
1914
- const m = useMarks();
1915
- const home = homedir();
1916
- const cwd = process.cwd();
1917
- const installed = useMemo(() => (state.setup?.clis ?? []).filter((x) => x.status !== "not-installed"), [state.setup]);
1918
- const [field, setField] = useState("cli");
1919
- const [cliIx, setCliIx] = useState(0);
1920
- const [folder, setFolder] = useState(shortPath(cwd, home));
1921
- const [folderKey, setFolderKey] = useState(0);
1922
- const [name, setName] = useState("");
1923
- const [task, setTask] = useState("");
1924
- const [inWindow, setInWindow] = useState(false);
1925
- const [busy, setBusy] = useState(false);
1926
- const [error, setError] = useState();
1927
- const asked = useRef(false);
1928
- const cli = installed[Math.min(cliIx, installed.length - 1)];
1929
- const suggested = cli ? suggestName(cli.cli, folder) : "";
1930
- const finalName = name.trim() || suggested;
1931
- const typing = TEXT_FIELDS.includes(field);
1932
- const tick = useTick(busy);
1933
- useEffect(() => {
1934
- if (!asked.current && !state.setup) {
1935
- asked.current = true;
1936
- actions.refreshSetup().catch(() => void 0);
1937
- }
1938
- }, [state.setup, actions]);
1939
- useEffect(() => {
1940
- setTyping(typing && active);
1941
- return () => setTyping(false);
1942
- }, [
1943
- typing,
1944
- active,
1945
- setTyping
1946
- ]);
1947
- useEffect(() => {
1948
- setKeys([
1949
- {
1950
- key: "Tab",
1951
- label: "next"
1952
- },
1953
- {
1954
- key: "Space",
1955
- label: "tick"
1956
- },
1957
- {
1958
- key: m.enter,
1959
- label: "start"
1960
- },
1961
- {
1962
- key: "Esc",
1963
- label: "cancel"
1964
- }
1965
- ]);
1966
- }, [setKeys, m.enter]);
1967
- const start = useCallback(async () => {
1968
- if (busy) return;
1969
- if (!cli) return setError("No CLI found yet. Set one up on screen 4.");
1970
- setError(void 0);
1971
- setBusy(true);
1972
- try {
1973
- const res = await actions.spawn({
1974
- cli: cli.cli,
1975
- cwd: expandPath(folder, home, cwd),
1976
- window: inWindow,
1977
- name: finalName,
1978
- prompt: task.trim()
1979
- });
1980
- toast(`Started ${finalName}`, "ok");
1981
- if (res.sessionId) go("sessions", res.sessionId);
1982
- else go("sessions");
1983
- } catch (e) {
1984
- setBusy(false);
1985
- setError(e instanceof Error ? e.message : "It did not start.");
1986
- }
1987
- }, [
1988
- busy,
1989
- cli,
1990
- task,
1991
- actions,
1992
- folder,
1993
- home,
1994
- cwd,
1995
- finalName,
1996
- inWindow,
1997
- toast,
1998
- go
1999
- ]);
2000
- useEffect(() => {
2001
- setCommands([{
2002
- id: "new.start",
2003
- label: "Start this worker",
2004
- key: "⏎",
2005
- rank: 5,
2006
- run: () => void start()
2007
- }]);
2008
- }, [setCommands, start]);
2009
- const move = (d) => {
2010
- const i = ORDER.indexOf(field);
2011
- const next = ORDER[(i + d + ORDER.length) % ORDER.length];
2012
- if (next) setField(next);
2013
- };
2014
- useInput((input, key) => {
2015
- if (busy) return;
2016
- if (key.escape) return go("sessions");
2017
- if (key.tab) {
2018
- if (field === "folder" && !key.shift) {
2019
- const next = completeDir(folder, home, cwd);
2020
- if (next !== folder) {
2021
- setFolder(next);
2022
- setFolderKey((k) => k + 1);
2023
- }
2024
- return;
2025
- }
2026
- return move(key.shift ? -1 : 1);
2027
- }
2028
- if (field === "cli") {
2029
- if (key.upArrow) return setCliIx(Math.max(0, cliIx - 1));
2030
- if (key.downArrow) return setCliIx(Math.min(installed.length - 1, cliIx + 1));
2031
- if (key.return) return move(1);
2032
- return;
2033
- }
2034
- if (field === "window") {
2035
- if (input === " ") return setInWindow(!inWindow);
2036
- if (key.upArrow) return move(-1);
2037
- if (key.return) return void start();
2038
- return;
2039
- }
2040
- if (key.upArrow) return move(-1);
2041
- if (key.downArrow) return move(1);
2042
- }, { isActive: active });
2043
- const wide = layout === "wide";
2044
- const split = splitWidths(columns, wide, {
2045
- panelW: 46,
2046
- maxMain: 100
2047
- });
2048
- const sideW = paneInner(split.panelW);
2049
- const mainW = wide ? split.mainW - 2 : Math.min(columns, 100);
2050
- const fieldW = Math.max(20, Math.min(72, mainW - 4));
2051
- const focusField = (f) => {
2052
- if (!busy) setField(f);
2053
- };
2054
- const field_ = (f, node) => /* @__PURE__ */ jsx(Hit, {
2055
- onClick: () => focusField(f),
2056
- marginLeft: 2,
2057
- width: fieldW,
2058
- paddingX: 1,
2059
- ...c.surface ? { backgroundColor: c.surface } : {},
2060
- children: node
2061
- });
2062
- const label = (f, text) => /* @__PURE__ */ jsx(Hit, {
2063
- onClick: () => focusField(f),
2064
- children: /* @__PURE__ */ jsx(Text, {
2065
- ...field === f ? { bold: true } : {},
2066
- ...c.quiet && field !== f ? { color: c.quiet } : {},
2067
- children: `${field === f ? m.cursor : " "} ${text.toUpperCase()}`
2068
- })
2069
- });
2070
- const steps = [{ text: `${finalName || "your worker"} is ready` }, { text: "waiting for its first reply" }];
2071
- const cmdLines = cli ? spawnCommand({
2072
- cli: cli.cli,
2073
- folder,
2074
- window: inWindow,
2075
- name: finalName,
2076
- task
2077
- }) : [];
2078
- return /* @__PURE__ */ jsxs(Box, {
2079
- flexDirection: "row",
2080
- height: props.rows,
2081
- children: [/* @__PURE__ */ jsx(Box, {
2082
- flexDirection: "column",
2083
- width: wide ? split.mainW : mainW,
2084
- flexShrink: 0,
2085
- children: installed.length === 0 ? /* @__PURE__ */ jsx(Text, {
2086
- dimColor: true,
2087
- children: state.setup ? "No CLI found. Set one up on screen 4 first." : `Looking for your CLIs${m.ellipsis}`
2088
- }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2089
- label("cli", "CLI"),
2090
- /* @__PURE__ */ jsx(Box, {
2091
- flexDirection: "column",
2092
- marginLeft: 2,
2093
- children: installed.map((x, i) => /* @__PURE__ */ jsxs(Hit, {
2094
- onClick: () => {
2095
- if (busy) return;
2096
- setCliIx(i);
2097
- setField("cli");
2098
- },
2099
- children: [/* @__PURE__ */ jsx(Text, { children: `${i === cliIx ? m.radioOn : m.radioOff} ${x.label}` }), x.status === "not-set-up" || x.status === "needs-update" ? /* @__PURE__ */ jsx(Text, {
2100
- dimColor: true,
2101
- children: ` ${x.status === "not-set-up" ? "not set up yet" : "needs update"}`
2102
- }) : null]
2103
- }, x.cli))
2104
- }),
2105
- label("folder", "Folder"),
2106
- field_("folder", /* @__PURE__ */ jsx(TextBox, {
2107
- value: folder,
2108
- onChange: setFolder,
2109
- onSubmit: () => move(1),
2110
- focus: active && field === "folder",
2111
- placeholder: "~/code/my-project"
2112
- }, folderKey)),
2113
- label("name", "Name"),
2114
- field_("name", /* @__PURE__ */ jsx(TextBox, {
2115
- value: name,
2116
- onChange: setName,
2117
- onSubmit: () => move(1),
2118
- focus: active && field === "name",
2119
- placeholder: suggested
2120
- })),
2121
- label("task", "Task"),
2122
- field_("task", /* @__PURE__ */ jsx(TextBox, {
2123
- value: task,
2124
- onChange: setTask,
2125
- onSubmit: () => void start(),
2126
- focus: active && field === "task",
2127
- multiline: true,
2128
- placeholder: "What should it start on? (optional)"
2129
- })),
2130
- label("window", "Where"),
2131
- /* @__PURE__ */ jsx(Hit, {
2132
- marginLeft: 2,
2133
- onClick: () => {
2134
- if (busy) return;
2135
- setField("window");
2136
- setInWindow(!inWindow);
2137
- },
2138
- children: /* @__PURE__ */ jsx(Text, { children: `${inWindow ? "[x]" : "[ ]"} in a window, so you can watch it` })
2139
- }),
2140
- /* @__PURE__ */ jsx(Text, { children: " " }),
2141
- busy ? /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Spinner, { tick }), ` Starting ${finalName}${m.ellipsis}`] }) : /* @__PURE__ */ jsxs(Box, { children: [
2142
- /* @__PURE__ */ jsx(Hit, {
2143
- onClick: () => void start(),
2144
- children: /* @__PURE__ */ jsx(Text, {
2145
- bold: true,
2146
- children: `${m.enter} Start`
2147
- })
2148
- }),
2149
- /* @__PURE__ */ jsx(Text, {
2150
- dimColor: true,
2151
- children: " Tab next "
2152
- }),
2153
- /* @__PURE__ */ jsx(Hit, {
2154
- onClick: () => go("sessions"),
2155
- children: /* @__PURE__ */ jsx(Text, {
2156
- dimColor: true,
2157
- children: "Esc cancel"
2158
- })
2159
- })
2160
- ] }),
2161
- error ? /* @__PURE__ */ jsx(Text, {
2162
- ...c.error ? { color: c.error } : {},
2163
- children: `${m.error} ${error}`
2164
- }) : null
2165
- ] })
2166
- }), wide ? /* @__PURE__ */ jsxs(Pane, {
2167
- width: split.panelW,
2168
- height: props.rows,
2169
- children: [
2170
- /* @__PURE__ */ jsx(Label, { children: "After you press ⏎" }),
2171
- steps.map((s, i) => /* @__PURE__ */ jsxs(Box, { children: [
2172
- busy && i === 0 ? /* @__PURE__ */ jsx(Spinner, { tick }) : /* @__PURE__ */ jsx(Text, {
2173
- dimColor: true,
2174
- children: m.pending
2175
- }),
2176
- /* @__PURE__ */ jsx(Text, { children: " " }),
2177
- /* @__PURE__ */ jsx(Ell, {
2178
- width: sideW - 2,
2179
- ...busy ? {} : { dim: true },
2180
- children: s.text
2181
- })
2182
- ] }, s.text)),
2183
- /* @__PURE__ */ jsx(Text, { children: " " }),
2184
- /* @__PURE__ */ jsx(Label, { children: "Same as typing" }),
2185
- /* @__PURE__ */ jsx(Card, {
2186
- width: sideW,
2187
- children: cmdLines.map((l) => /* @__PURE__ */ jsx(Text, {
2188
- wrap: "wrap",
2189
- children: l
2190
- }, l))
2191
- })
2192
- ]
2193
- }) : null]
2194
- });
2195
- }
2196
- // src/tui/screens/sessions.tsx
2197
- var sessions_exports = /* @__PURE__ */ __exportAll({
2198
- agoText: () => agoText,
2199
- default: () => Sessions,
2200
- groupSessions: () => groupSessions,
2201
- listColumns: () => listColumns,
2202
- statusWord: () => statusWord
2203
- });
2204
- const STATUS_WIDTH = 10;
2205
- const GAP = 2;
2206
- /** Column widths for the list. The name takes what it needs, the folder takes the rest. */
2207
- function listColumns(width, longestName) {
2208
- const fixed = 24;
2209
- let name = Math.max(12, Math.min(32, longestName + 1));
2210
- let folder = width - fixed - name;
2211
- if (folder < 10) {
2212
- name = Math.max(8, name - (10 - folder));
2213
- folder = width - fixed - name;
2214
- }
2215
- return {
2216
- name,
2217
- folder: Math.max(0, folder)
2218
- };
2219
- }
2220
- /** Letters that are keys on this screen. A word starting with one of them needs `f` first. */
2221
- const BOUND = /* @__PURE__ */ new Set([
2222
- "m",
2223
- "n",
2224
- "l",
2225
- "r",
2226
- "x",
2227
- "q",
2228
- "f"
2229
- ]);
2230
- const quiet = (c) => c.quiet ? { color: c.quiet } : { dimColor: true };
2231
- /** `working` or `idle`. State is always in the word, never in colour alone. */
2232
- const statusWord = (s) => s.status === "busy" ? "working" : "idle";
2233
- /** "41m ago", "just now". */
2234
- function agoText(iso) {
2235
- const r = relTime(iso);
2236
- if (r === "") return "";
2237
- if (r === "now") return "just now";
2238
- return r.endsWith("ago") ? r : `${r} ago`;
2239
- }
2240
- function matches(s, q) {
2241
- const needle = q.toLowerCase();
2242
- return [
2243
- s.name,
2244
- s.cwd,
2245
- s.cli,
2246
- s.deviceName ?? ""
2247
- ].some((x) => x.toLowerCase().includes(needle));
2248
- }
2249
- /** Sessions grouped by machine: this one first, then the others by name. */
2250
- function groupSessions(sessions) {
2251
- const byLead = (a, b) => Number(b.isOrchestrator) - Number(a.isOrchestrator) || a.name.localeCompare(b.name);
2252
- const local = sessions.filter((s) => !s.remote).sort(byLead);
2253
- const remotes = /* @__PURE__ */ new Map();
2254
- for (const s of sessions) {
2255
- if (!s.remote) continue;
2256
- const k = s.deviceName ?? "OTHER PC";
2257
- remotes.set(k, [...remotes.get(k) ?? [], s]);
2258
- }
2259
- const groups = [];
2260
- if (local.length > 0) groups.push({
2261
- title: "THIS PC",
2262
- synced: false,
2263
- items: local
2264
- });
2265
- for (const k of [...remotes.keys()].sort()) groups.push({
2266
- title: k.toUpperCase(),
2267
- synced: true,
2268
- items: (remotes.get(k) ?? []).sort(byLead)
2269
- });
2270
- return groups;
2271
- }
2272
- function Sessions(props) {
2273
- const { state, actions, layout, rows, columns, active, setKeys, setCommands, go, toast, setTyping, claimKeys } = props;
2274
- const { c, ascii } = useTheme();
2275
- const wide = layout === "wide";
2276
- const [selectedId, setSelectedId] = useState(props.focus);
2277
- const [filter, setFilter] = useState(void 0);
2278
- const [mode, setMode] = useState(void 0);
2279
- const [draft, setDraft] = useState("");
2280
- const sending = useRef(false);
2281
- const groups = useMemo(() => {
2282
- const live = state.sessions.filter((s) => s.status !== "offline");
2283
- return groupSessions(filter ? live.filter((s) => matches(s, filter)) : live);
2284
- }, [state.sessions, filter]);
2285
- const flat = useMemo(() => groups.flatMap((g) => g.items), [groups]);
2286
- const rowsList = useMemo(() => groups.flatMap((g) => [{
2287
- t: "head",
2288
- key: `h:${g.title}`,
2289
- text: `${g.title} · ${g.items.length}`,
2290
- synced: g.synced
2291
- }, ...g.items.map((s) => ({
2292
- t: "session",
2293
- s
2294
- }))]), [groups]);
2295
- const found = flat.findIndex((s) => s.id === selectedId);
2296
- const selected = flat[Math.max(found, 0)];
2297
- const selRow = rowsList.findIndex((r) => r.t === "session" && r.s.id === selected?.id);
2298
- const filtering = filter !== void 0;
2299
- const taking = mode?.kind === "message" || mode?.kind === "rename";
2300
- const typing = active && (taking || filtering);
2301
- useEffect(() => {
2302
- setTyping(typing);
2303
- return () => setTyping(false);
2304
- }, [typing, setTyping]);
2305
- const asking = active && mode?.kind === "stop";
2306
- useEffect(() => {
2307
- claimKeys(asking ? ["y", "n"] : []);
2308
- return () => claimKeys([]);
2309
- }, [asking, claimKeys]);
2310
- useEffect(() => {
2311
- setKeys(taking ? [{
2312
- key: "⏎",
2313
- label: "send"
2314
- }, {
2315
- key: "Esc",
2316
- label: "cancel"
2317
- }] : [
2318
- {
2319
- key: "↑↓",
2320
- label: "move"
2321
- },
2322
- {
2323
- key: "l",
2324
- label: "make lead"
2325
- },
2326
- {
2327
- key: "m",
2328
- label: "message"
2329
- },
2330
- {
2331
- key: "r",
2332
- label: "rename"
2333
- },
2334
- {
2335
- key: "x",
2336
- label: "stop"
2337
- },
2338
- {
2339
- key: "n",
2340
- label: "new"
2341
- },
2342
- {
2343
- key: "f",
2344
- label: "filter"
2345
- }
2346
- ]);
2347
- }, [setKeys, taking]);
2348
- const local = (s) => {
2349
- if (!s.remote) return true;
2350
- toast("That session is on another machine. Change it there.", "warn");
2351
- return false;
2352
- };
2353
- function makeLead(s) {
2354
- if (!local(s)) return;
2355
- (s.isOrchestrator ? actions.clearLead() : actions.setLead(s.id)).then(() => toast(s.isOrchestrator ? "No lead now" : `${s.name} is the lead`), () => toast("Couldn't change the lead. Try again.", "error"));
2356
- }
2357
- function askStop(s) {
2358
- if (!local(s)) return;
2359
- if (!s.spawned) return toast("Conveno didn't start this one. Close it where it runs.", "warn");
2360
- setMode({
2361
- kind: "stop",
2362
- s
2363
- });
2364
- }
2365
- function startText(kind, s) {
2366
- if (kind === "rename" && !local(s)) return;
2367
- setDraft(kind === "rename" ? s.name : "");
2368
- setMode({
2369
- kind,
2370
- s
2371
- });
2372
- }
2373
- function stop(s) {
2374
- actions.stop(s.id).then(() => toast(`Stopped ${s.name}`), (e) => toast(e instanceof Error ? e.message : `Couldn't stop ${s.name}.`, "error"));
2375
- }
2376
- function submit(text) {
2377
- const t = text.trim();
2378
- if (!mode || t === "" || sending.current) return;
2379
- const { kind, s } = mode;
2380
- if (kind === "stop") return;
2381
- sending.current = true;
2382
- (kind === "message" ? actions.send(s.name, t) : actions.rename(s.id, t)).then(() => {
2383
- setMode(void 0);
2384
- setDraft("");
2385
- toast(kind === "message" ? s.status === "busy" ? `Sent to ${s.name}. It gets this when it finishes its step.` : `Sent to ${s.name}` : `Renamed to ${t}`);
2386
- }, (e) => toast(kind === "message" ? "Couldn't send that. Try again." : e instanceof Error ? e.message : "Couldn't rename it. Try again.", "error")).finally(() => {
2387
- sending.current = false;
2388
- });
2389
- }
2390
- const fn = useRef({
2391
- makeLead,
2392
- askStop,
2393
- startText
2394
- });
2395
- fn.current = {
2396
- makeLead,
2397
- askStop,
2398
- startText
2399
- };
2400
- useEffect(() => {
2401
- const cmds = [{
2402
- id: "sessions-new",
2403
- label: "Start a new worker",
2404
- key: "n",
2405
- run: () => go("new")
2406
- }];
2407
- if (selected) {
2408
- const s = selected;
2409
- cmds.push({
2410
- id: "sessions-lead",
2411
- label: s.isOrchestrator ? "Clear the lead" : `Make ${s.name} the lead`,
2412
- key: "l",
2413
- run: () => fn.current.makeLead(s)
2414
- }, {
2415
- id: "sessions-message",
2416
- label: `Message ${s.name}`,
2417
- key: "m",
2418
- run: () => fn.current.startText("message", s)
2419
- }, {
2420
- id: "sessions-rename",
2421
- label: `Rename ${s.name}`,
2422
- key: "r",
2423
- run: () => fn.current.startText("rename", s)
2424
- });
2425
- if (s.spawned && !s.remote) cmds.push({
2426
- id: "sessions-stop",
2427
- label: `Stop ${s.name}`,
2428
- key: "x",
2429
- run: () => fn.current.askStop(s)
2430
- });
2431
- }
2432
- cmds.push({
2433
- id: "sessions-filter",
2434
- label: "Filter sessions",
2435
- key: "f",
2436
- run: () => setFilter("")
2437
- });
2438
- setCommands(cmds);
2439
- }, [
2440
- setCommands,
2441
- go,
2442
- selected
2443
- ]);
2444
- function move(delta) {
2445
- if (flat.length === 0) return;
2446
- setSelectedId((prev) => {
2447
- const at = Math.max(0, flat.findIndex((s) => s.id === prev));
2448
- return flat[Math.max(0, Math.min(flat.length - 1, at + delta))]?.id;
2449
- });
2450
- }
2451
- useInput((input, key) => {
2452
- if (mode?.kind === "stop") {
2453
- if (input === "y") stop(mode.s);
2454
- setMode(void 0);
2455
- return;
2456
- }
2457
- if (key.upArrow) return move(-1);
2458
- if (key.downArrow) return move(1);
2459
- if (filtering) {
2460
- if (key.escape) return setFilter(void 0);
2461
- if (key.return) return;
2462
- if (key.backspace || key.delete) return setFilter(filter && filter.length > 1 ? filter.slice(0, -1) : filter === "" ? void 0 : "");
2463
- if (input && !key.ctrl && !key.meta && !key.tab) setFilter((f) => (f ?? "") + input);
2464
- return;
2465
- }
2466
- if (key.return) {
2467
- if (selected) startText("message", selected);
2468
- return;
2469
- }
2470
- if (key.ctrl || key.meta || key.tab || key.escape || input.length !== 1) return;
2471
- if (input === "m" && selected) return startText("message", selected);
2472
- if (input === "r" && selected) return startText("rename", selected);
2473
- if (input === "l" && selected) return makeLead(selected);
2474
- if (input === "x" && selected) return askStop(selected);
2475
- if (input === "n") return go("new");
2476
- if (input === "f") return setFilter("");
2477
- if (/\p{L}/u.test(input) && !BOUND.has(input.toLowerCase())) setFilter(input);
2478
- }, { isActive: active && !taking });
2479
- if (state.sessions.length === 0) return /* @__PURE__ */ jsx(Box, {
2480
- flexDirection: "column",
2481
- paddingTop: 1,
2482
- children: /* @__PURE__ */ jsx(Text, {
2483
- ...quiet(c),
2484
- children: "Nothing is running yet. Open one of your CLIs, or press n to start one."
2485
- })
2486
- });
2487
- const { mainW, panelW } = splitWidths(columns, wide);
2488
- const listW = wide ? mainW - 2 : columns;
2489
- const bodyH = Math.max(3, rows - 2);
2490
- const listH = Math.max(2, bodyH - 1);
2491
- const dot = ascii ? "*" : "◆";
2492
- const mid = ascii ? "-" : "·";
2493
- const { name: nameW, folder: folderW } = listColumns(listW, flat.reduce((n, s) => Math.max(n, [...s.name].length), 0));
2494
- const clickRow = (s, isSel, double) => {
2495
- setMode(void 0);
2496
- setSelectedId(s.id);
2497
- if (isSel || double) startText("message", s);
2498
- };
2499
- const renderRow = (r, isSel) => {
2500
- if (r.t === "head") return /* @__PURE__ */ jsxs(Box, {
2501
- width: listW,
2502
- children: [/* @__PURE__ */ jsx(Label, { children: plain(r.text, ascii) }), r.synced ? /* @__PURE__ */ jsx(Text, {
2503
- ...quiet(c),
2504
- children: ` synced`
2505
- }) : null]
2506
- });
2507
- const s = r.s;
2508
- const lead = s.isOrchestrator;
2509
- return /* @__PURE__ */ jsx(Hit, {
2510
- onClick: (e) => clickRow(s, isSel, e.double),
2511
- isActive: active && !taking,
2512
- children: /* @__PURE__ */ jsxs(Row, {
2513
- width: listW,
2514
- selected: isSel,
2515
- children: [
2516
- /* @__PURE__ */ jsx(Cell, {
2517
- w: 2,
2518
- gap: 0,
2519
- color: c.entry,
2520
- children: isSel ? ascii ? "> " : "▸ " : " "
2521
- }),
2522
- /* @__PURE__ */ jsx(Cell, {
2523
- w: 2,
2524
- gap: 0,
2525
- color: lead ? c.entry : c.quiet,
2526
- children: lead ? `${dot} ` : `${mid} `
2527
- }),
2528
- /* @__PURE__ */ jsx(Cell, {
2529
- w: nameW + GAP,
2530
- bold: isSel,
2531
- children: s.name
2532
- }),
2533
- /* @__PURE__ */ jsx(Box, {
2534
- width: 6,
2535
- flexShrink: 0,
2536
- children: /* @__PURE__ */ jsx(Chip, { cli: s.cli })
2537
- }),
2538
- /* @__PURE__ */ jsx(Cell, {
2539
- w: folderW + GAP,
2540
- color: c.quiet,
2541
- children: shortPath$1(s.cwd, folderW - GAP, ascii)
2542
- }),
2543
- /* @__PURE__ */ jsx(Cell, {
2544
- w: STATUS_WIDTH,
2545
- gap: 0,
2546
- color: s.status === "busy" ? c.info : c.quiet,
2547
- children: statusWord(s)
2548
- })
2549
- ]
2550
- })
2551
- });
2552
- };
2553
- const list = flat.length === 0 ? /* @__PURE__ */ jsx(Text, {
2554
- ...quiet(c),
2555
- children: `Nothing matches “${filter}”.`
2556
- }) : /* @__PURE__ */ jsx(ScrollList, {
2557
- items: rowsList,
2558
- selected: Math.max(0, selRow),
2559
- height: listH,
2560
- keyOf: (r, i) => r.t === "head" ? r.key : `${r.s.id}:${i}`,
2561
- renderItem: (r, _sel, i) => renderRow(r, i === selRow)
2562
- });
2563
- let bottom;
2564
- if (mode?.kind === "stop") {
2565
- const target = mode.s;
2566
- bottom = /* @__PURE__ */ jsxs(Box, { children: [
2567
- /* @__PURE__ */ jsx(Text, {
2568
- bold: true,
2569
- ...c.stamp ? { color: c.stamp } : {},
2570
- children: `Stop ${target.name}? `
2571
- }),
2572
- /* @__PURE__ */ jsx(Hit, {
2573
- onClick: () => {
2574
- stop(target);
2575
- setMode(void 0);
2576
- },
2577
- isActive: active,
2578
- children: /* @__PURE__ */ jsx(Text, {
2579
- bold: true,
2580
- ...c.stamp ? { color: c.stamp } : {},
2581
- children: "y"
2582
- })
2583
- }),
2584
- /* @__PURE__ */ jsx(Text, {
2585
- bold: true,
2586
- ...c.stamp ? { color: c.stamp } : {},
2587
- children: "/"
2588
- }),
2589
- /* @__PURE__ */ jsx(Hit, {
2590
- onClick: () => setMode(void 0),
2591
- isActive: active,
2592
- children: /* @__PURE__ */ jsx(Text, {
2593
- bold: true,
2594
- ...c.stamp ? { color: c.stamp } : {},
2595
- children: "n"
2596
- })
2597
- })
2598
- ] });
2599
- } else if (mode) {
2600
- const label = mode.kind === "message" ? `Message ${mode.s.name}` : `Rename ${mode.s.name} to`;
2601
- bottom = /* @__PURE__ */ jsxs(Box, { children: [/* @__PURE__ */ jsx(Text, {
2602
- ...quiet(c),
2603
- children: `${label} `
2604
- }), /* @__PURE__ */ jsx(Box, {
2605
- flexGrow: 1,
2606
- children: /* @__PURE__ */ jsx(TextBox, {
2607
- value: draft,
2608
- onChange: setDraft,
2609
- onSubmit: submit,
2610
- onCancel: () => {
2611
- setMode(void 0);
2612
- setDraft("");
2613
- },
2614
- focus: active,
2615
- placeholder: mode.kind === "message" ? "Type, then Enter" : "A new name"
2616
- })
2617
- })] });
2618
- } else if (filtering) bottom = /* @__PURE__ */ jsxs(Text, { children: [
2619
- /* @__PURE__ */ jsx(Text, {
2620
- ...quiet(c),
2621
- children: "Filter "
2622
- }),
2623
- /* @__PURE__ */ jsx(Text, {
2624
- bold: true,
2625
- children: filter
2626
- }),
2627
- /* @__PURE__ */ jsx(Text, {
2628
- inverse: true,
2629
- children: " "
2630
- }),
2631
- /* @__PURE__ */ jsx(Text, {
2632
- ...quiet(c),
2633
- children: ` Esc clears`
2634
- })
2635
- ] });
2636
- else {
2637
- const variants = [
2638
- `${dot} lead working = busy right now idle = ready for a message type to filter`,
2639
- `${dot} lead working = busy type to filter`,
2640
- `${dot} lead type to filter`
2641
- ];
2642
- const legend = variants.find((v) => [...v].length <= columns) ?? variants[2] ?? "";
2643
- const tail = "type to filter";
2644
- const head = legend.endsWith(tail) ? legend.slice(0, -14) : legend;
2645
- bottom = /* @__PURE__ */ jsxs(Box, { children: [/* @__PURE__ */ jsx(Ell, {
2646
- width: Math.min([...head].length, Math.max(0, columns - 14)),
2647
- color: c.quiet,
2648
- children: head
2649
- }), legend.endsWith(tail) ? /* @__PURE__ */ jsx(Hit, {
2650
- onClick: () => setFilter((f) => f ?? ""),
2651
- isActive: active,
2652
- children: /* @__PURE__ */ jsx(Ell, {
2653
- width: 14,
2654
- color: c.quiet,
2655
- children: tail
2656
- })
2657
- }) : null] });
2658
- }
2659
- return /* @__PURE__ */ jsxs(Box, {
2660
- flexDirection: "column",
2661
- width: columns,
2662
- children: [
2663
- /* @__PURE__ */ jsxs(Box, {
2664
- height: bodyH,
2665
- children: [/* @__PURE__ */ jsxs(Hit, {
2666
- flexDirection: "column",
2667
- width: wide ? mainW : columns,
2668
- flexShrink: 0,
2669
- onWheel: (d) => move(d < 0 ? -1 : 1),
2670
- isActive: active,
2671
- children: [/* @__PURE__ */ jsx(HeaderRow, {
2672
- width: listW,
2673
- cols: [
2674
- {
2675
- w: 4,
2676
- text: "",
2677
- gap: 0
2678
- },
2679
- {
2680
- w: nameW + GAP,
2681
- text: "Name"
2682
- },
2683
- {
2684
- w: 6,
2685
- text: "CLI"
2686
- },
2687
- {
2688
- w: folderW + GAP,
2689
- text: "Folder"
2690
- },
2691
- {
2692
- w: STATUS_WIDTH,
2693
- text: "Status",
2694
- gap: 0
2695
- }
2696
- ]
2697
- }), list]
2698
- }), wide ? /* @__PURE__ */ jsx(Pane, {
2699
- width: panelW,
2700
- height: bodyH,
2701
- children: selected ? /* @__PURE__ */ jsx(SidePanel, {
2702
- session: selected,
2703
- width: paneInner(panelW)
2704
- }) : null
2705
- }) : null]
2706
- }),
2707
- /* @__PURE__ */ jsx(Box, {
2708
- marginLeft: -1,
2709
- children: /* @__PURE__ */ jsx(Rule, { width: columns + 1 })
2710
- }),
2711
- /* @__PURE__ */ jsx(Box, {
2712
- height: 1,
2713
- children: bottom
2714
- })
2715
- ]
2716
- });
2717
- }
2718
- function SidePanel({ session, width }) {
2719
- const { c, ascii } = useTheme();
2720
- const role = session.isOrchestrator ? "lead" : "worker";
2721
- const sep = ascii ? "-" : "·";
2722
- const started = `started ${agoText(session.startedAt)}`;
2723
- const whole = `${role} ${sep} ${shortPath$1(session.cwd, 200, ascii)} ${sep} ${started}`;
2724
- const sub = [...whole].length <= width ? [whole] : [`${role} ${sep} ${started}`, shortPath$1(session.cwd, width, ascii)];
2725
- const status = session.statusText ?? "No update yet.";
2726
- return /* @__PURE__ */ jsxs(Box, {
2727
- flexDirection: "column",
2728
- width,
2729
- children: [
2730
- /* @__PURE__ */ jsxs(Box, { children: [
2731
- /* @__PURE__ */ jsx(Ell, {
2732
- width: width - 4 - 1,
2733
- bold: true,
2734
- children: session.name
2735
- }),
2736
- /* @__PURE__ */ jsx(Text, { children: " " }),
2737
- /* @__PURE__ */ jsx(Chip, { cli: session.cli })
2738
- ] }),
2739
- sub.map((l) => /* @__PURE__ */ jsx(Ell, {
2740
- width,
2741
- color: c.quiet,
2742
- children: l
2743
- }, l)),
2744
- /* @__PURE__ */ jsx(Box, {
2745
- marginTop: 1,
2746
- children: /* @__PURE__ */ jsx(Label, { children: "Right now" })
2747
- }),
2748
- /* @__PURE__ */ jsx(Text, {
2749
- wrap: "truncate-end",
2750
- children: status
2751
- })
2752
- ]
2753
- });
2754
- }
2755
- // src/tui/screens/setup.tsx
2756
- /** Screen 4: Setup. Your CLIs, extras and the checkup. */
2757
- var setup_exports = /* @__PURE__ */ __exportAll({
2758
- default: () => SetupScreen,
2759
- idsFor: () => idsFor
2760
- });
2761
- const STATUS_WORD = {
2762
- ready: "ready",
2763
- "needs-update": "needs update",
2764
- "not-set-up": "not set up",
2765
- blocked: "blocked",
2766
- "not-installed": "not installed"
2767
- };
2768
- /** `init:<cli>` ids for the picked rows, or the row under the cursor. Pure, for tests. */
2769
- function idsFor(clis, picked, cursorCli) {
2770
- const wanted = picked.size > 0 ? clis.filter((c) => picked.has(c.cli)) : clis.filter((c) => c.cli === cursorCli);
2771
- const ids = wanted.filter((c) => c.status !== "not-installed" && c.status !== "blocked").map((c) => `init:${c.cli}`);
2772
- if (ids.length > 0) return {
2773
- ids,
2774
- skipped: void 0
2775
- };
2776
- const first = wanted[0];
2777
- if (!first) return {
2778
- ids,
2779
- skipped: "Nothing to set up here."
2780
- };
2781
- return {
2782
- ids,
2783
- skipped: first.status === "not-installed" ? `Install ${first.label} first, then press g.` : `${first.label} is blocked: ${first.note ?? "see the note"}.`
2784
- };
2785
- }
2786
- function HealthLine({ item, width }) {
2787
- const { c } = useTheme();
2788
- const m = useMarks();
2789
- const mark = item.level === "ok" ? m.ok : item.level === "warn" ? m.warn : item.level === "error" ? m.error : m.info;
2790
- const color = item.level === "ok" ? c.ok : item.level === "warn" ? c.warn : item.level === "error" ? c.error : c.quiet;
2791
- return /* @__PURE__ */ jsxs(Box, { children: [/* @__PURE__ */ jsx(Text, {
2792
- ...color ? { color } : {},
2793
- children: `${mark} `
2794
- }), /* @__PURE__ */ jsx(Ell, {
2795
- width: width - 2,
2796
- children: item.text
2797
- })] });
2798
- }
2799
- function ReviewBox({ review, rows, width, active, onYes, onNo, onScroll }) {
2800
- const { c } = useTheme();
2801
- const body = [];
2802
- for (const f of review.files) {
2803
- body.push({
2804
- text: `${f.path}${f.isNew ? " (new file)" : f.deleted ? " (deleted)" : ""}`,
2805
- kind: "path"
2806
- });
2807
- body.push({
2808
- text: f.summary,
2809
- kind: "note"
2810
- });
2811
- for (const l of f.lines) body.push({
2812
- text: l,
2813
- kind: l.startsWith("@@") ? "hunk" : l.startsWith("+") ? "add" : l.startsWith("-") ? "del" : "plain"
2814
- });
2815
- body.push({
2816
- text: "",
2817
- kind: "plain"
2818
- });
2819
- }
2820
- const room = Math.max(3, rows - 8);
2821
- const start = Math.min(review.scroll, Math.max(0, body.length - room));
2822
- const shown = body.map((l, id) => ({
2823
- ...l,
2824
- id
2825
- })).slice(start, start + room);
2826
- const hidden = body.length - start - shown.length;
2827
- const inner = width - 4;
2828
- return /* @__PURE__ */ jsx(Hit, {
2829
- onWheel: (d) => onScroll(d < 0 ? -1 : 1),
2830
- isActive: active,
2831
- children: /* @__PURE__ */ jsxs(Card, {
2832
- accent: c.warn,
2833
- width,
2834
- children: [
2835
- /* @__PURE__ */ jsx(Text, {
2836
- bold: true,
2837
- children: review.title
2838
- }),
2839
- review.error ? /* @__PURE__ */ jsx(Text, {
2840
- ...c.error ? { color: c.error } : {},
2841
- children: `We can't plan this: ${review.error}`
2842
- }) : review.files.length === 0 ? /* @__PURE__ */ jsx(Text, { children: "Nothing to change. It is already how it should be." }) : /* @__PURE__ */ jsxs(Box, {
2843
- flexDirection: "column",
2844
- children: [shown.map((l) => /* @__PURE__ */ jsx(Ell, {
2845
- width: inner,
2846
- bold: l.kind === "path",
2847
- dim: l.kind === "note" || l.kind === "hunk",
2848
- color: l.kind === "add" ? c.ok : l.kind === "del" ? c.error : void 0,
2849
- children: l.text === "" ? " " : l.text
2850
- }, l.id)), hidden > 0 ? /* @__PURE__ */ jsx(Text, {
2851
- dimColor: true,
2852
- children: `… ${hidden} more lines (↑↓ to scroll)`
2853
- }) : null]
2854
- }),
2855
- /* @__PURE__ */ jsx(Text, { children: " " }),
2856
- review.busy ? /* @__PURE__ */ jsx(Text, { children: "Working…" }) : review.error || review.files.length === 0 ? /* @__PURE__ */ jsx(Hit, {
2857
- onClick: onNo,
2858
- isActive: active,
2859
- children: /* @__PURE__ */ jsx(Text, {
2860
- dimColor: true,
2861
- children: "Press n or Esc to close."
2862
- })
2863
- }) : /* @__PURE__ */ jsxs(Box, { children: [
2864
- /* @__PURE__ */ jsx(Text, {
2865
- bold: true,
2866
- children: "Apply? "
2867
- }),
2868
- /* @__PURE__ */ jsx(Hit, {
2869
- onClick: onYes,
2870
- isActive: active,
2871
- children: /* @__PURE__ */ jsx(Text, {
2872
- bold: true,
2873
- children: "y"
2874
- })
2875
- }),
2876
- /* @__PURE__ */ jsx(Text, {
2877
- bold: true,
2878
- children: "/"
2879
- }),
2880
- /* @__PURE__ */ jsx(Hit, {
2881
- onClick: onNo,
2882
- isActive: active,
2883
- children: /* @__PURE__ */ jsx(Text, {
2884
- bold: true,
2885
- children: "n"
2886
- })
2887
- }),
2888
- /* @__PURE__ */ jsx(Text, {
2889
- dimColor: true,
2890
- children: " We back up each file first."
2891
- })
2892
- ] })
2893
- ]
2894
- })
2895
- });
2896
- }
2897
- function SetupScreen(props) {
2898
- const { state, actions, layout, rows, columns, active, setKeys, setCommands, toast, go } = props;
2899
- const { c, ascii } = useTheme();
2900
- const m = useMarks();
2901
- const clis = state.setup?.clis ?? [];
2902
- const health = state.setup?.health ?? [];
2903
- const [cursor, setCursor] = useState(0);
2904
- const [picked, setPicked] = useState(/* @__PURE__ */ new Set());
2905
- const [review, setReview] = useState();
2906
- const [extras, setExtras] = useState({ helpers: false });
2907
- const mouse = useMouseControl();
2908
- const mouseOn = mouse.enabled;
2909
- const asked = useRef(false);
2910
- const total = clis.length + 2;
2911
- const at = Math.min(cursor, Math.max(0, total - 1));
2912
- const onCli = at < clis.length ? clis[at] : void 0;
2913
- const extraRow = at >= clis.length ? at - clis.length : -1;
2914
- const loadExtras = useCallback(() => {
2915
- actions.getExtras().then(setExtras).catch(() => void 0);
2916
- }, [actions]);
2917
- const refresh = useCallback(async () => {
2918
- try {
2919
- await actions.refreshSetup();
2920
- loadExtras();
2921
- } catch {
2922
- toast("Could not check your CLIs. Try g again.", "error");
2923
- }
2924
- }, [
2925
- actions,
2926
- loadExtras,
2927
- toast
2928
- ]);
2929
- useEffect(() => {
2930
- if (asked.current) return;
2931
- asked.current = true;
2932
- if (!state.setup) refresh();
2933
- else loadExtras();
2934
- }, [
2935
- state.setup,
2936
- refresh,
2937
- loadExtras
2938
- ]);
2939
- const preset = useRef(false);
2940
- useEffect(() => {
2941
- if (preset.current || !state.setup || state.setup.clis.length === 0) return;
2942
- preset.current = true;
2943
- const all = state.setup.clis;
2944
- if (all.some((x) => x.status === "ready")) return;
2945
- setPicked(new Set(all.filter((x) => x.status === "not-set-up" || x.status === "needs-update").map((x) => x.cli)));
2946
- }, [state.setup]);
2947
- const open = useCallback(async (ids, title) => {
2948
- setReview({
2949
- title,
2950
- ids,
2951
- files: [],
2952
- scroll: 0,
2953
- busy: true
2954
- });
2955
- const files = [];
2956
- let error;
2957
- for (const id of ids) {
2958
- const plan = await actions.planFix(id).catch((e) => ({
2959
- files: [],
2960
- error: e instanceof Error ? e.message : String(e)
2961
- }));
2962
- files.push(...plan.files);
2963
- error ??= plan.error;
2964
- }
2965
- setReview({
2966
- title,
2967
- ids,
2968
- files,
2969
- ...error ? { error } : {},
2970
- scroll: 0,
2971
- busy: false
2972
- });
2973
- }, [actions]);
2974
- const setUp = useCallback((target) => {
2975
- const row = target ? target.extra ?? -1 : extraRow;
2976
- const cur = target ? target.cli : onCli;
2977
- if (row === 1) {
2978
- if (mouse.forcedOff) {
2979
- toast("The mouse is off because CONVENO_MOUSE=0 is set.", "warn");
2980
- return;
2981
- }
2982
- if (!mouse.available) {
2983
- toast("This terminal can't send mouse clicks.", "warn");
2984
- return;
2985
- }
2986
- const next = !mouseOn;
2987
- mouse.set(next);
2988
- toast(next ? "Mouse is on." : "Mouse is off.", "ok");
2989
- return;
2990
- }
2991
- if (row === 0) {
2992
- const next = !extras.helpers;
2993
- actions.setHelpers(next).then(() => {
2994
- setExtras({
2995
- ...extras,
2996
- helpers: next
2997
- });
2998
- toast(next ? "Workers may get the helpers when needed." : "Workers won't fetch helpers.", "ok");
2999
- }, () => toast("Couldn't change that. Try again.", "error"));
3000
- return;
3001
- }
3002
- const { ids, skipped } = idsFor(clis, picked, cur?.cli);
3003
- if (ids.length === 0) return toast(skipped ?? "Nothing to set up here.", "warn");
3004
- const names = clis.filter((x) => ids.includes(`init:${x.cli}`)).map((x) => x.label);
3005
- open(ids, `Set up ${names.join(", ")}`);
3006
- }, [
3007
- extraRow,
3008
- onCli,
3009
- extras,
3010
- mouse,
3011
- mouseOn,
3012
- clis,
3013
- picked,
3014
- open,
3015
- toast,
3016
- actions
3017
- ]);
3018
- const remove = useCallback(() => {
3019
- if (!onCli) return toast("Pick a CLI in the list first.", "warn");
3020
- if (onCli.status === "not-installed") return toast(`${onCli.label} is not installed.`, "warn");
3021
- open([`uninstall:${onCli.cli}`], `Remove Conveno from ${onCli.label}`);
3022
- }, [
3023
- onCli,
3024
- open,
3025
- toast
3026
- ]);
3027
- const apply = useCallback(async () => {
3028
- if (!review) return;
3029
- setReview({
3030
- ...review,
3031
- busy: true
3032
- });
3033
- try {
3034
- for (const id of review.ids) await actions.applyFix(id);
3035
- toast("Done. Restart open sessions to pick it up.", "ok");
3036
- setReview(void 0);
3037
- setPicked(/* @__PURE__ */ new Set());
3038
- await refresh();
3039
- } catch (e) {
3040
- setReview(void 0);
3041
- toast(e instanceof Error ? e.message : "That did not work.", "error");
3042
- }
3043
- }, [
3044
- review,
3045
- actions,
3046
- toast,
3047
- refresh
3048
- ]);
3049
- useEffect(() => {
3050
- if (review) setKeys([
3051
- {
3052
- key: "y",
3053
- label: "apply"
3054
- },
3055
- {
3056
- key: "n",
3057
- label: "cancel"
3058
- },
3059
- {
3060
- key: "↑↓",
3061
- label: "scroll"
3062
- }
3063
- ]);
3064
- else setKeys([
3065
- {
3066
- key: "Space",
3067
- label: "pick"
3068
- },
3069
- {
3070
- key: m.enter,
3071
- label: "set up · fix"
3072
- },
3073
- {
3074
- key: "u",
3075
- label: "remove"
3076
- },
3077
- {
3078
- key: "g",
3079
- label: "refresh"
3080
- }
3081
- ]);
3082
- }, [
3083
- review,
3084
- setKeys,
3085
- m.enter
3086
- ]);
3087
- useEffect(() => {
3088
- setCommands([{
3089
- id: "setup.refresh",
3090
- label: "Check my CLIs again",
3091
- key: "g",
3092
- run: () => void refresh()
3093
- }, {
3094
- id: "setup.all",
3095
- label: "Set up every CLI that needs it",
3096
- rank: 5,
3097
- run: () => {
3098
- const ids = clis.filter((x) => x.status === "needs-update" || x.status === "not-set-up").map((x) => `init:${x.cli}`);
3099
- if (ids.length === 0) return toast("Everything is already set up.", "ok");
3100
- go("setup");
3101
- open(ids, "Set up every CLI that needs it");
3102
- }
3103
- }]);
3104
- }, [
3105
- setCommands,
3106
- refresh,
3107
- clis,
3108
- open,
3109
- go,
3110
- toast
3111
- ]);
3112
- const togglePick = (x) => {
3113
- const next = new Set(picked);
3114
- if (next.has(x.cli)) next.delete(x.cli);
3115
- else next.add(x.cli);
3116
- setPicked(next);
3117
- };
3118
- const fixable = (x) => x.status === "needs-update" || x.status === "not-set-up";
3119
- const clickRow = (i, x, double) => {
3120
- if (i === at || double) {
3121
- setCursor(i);
3122
- setUp({ cli: x });
3123
- } else setCursor(i);
3124
- };
3125
- const scrollReview = (d) => setReview((r) => r && !r.busy ? {
3126
- ...r,
3127
- scroll: Math.max(0, r.scroll + d)
3128
- } : r);
3129
- const closeReview = () => setReview((r) => r?.busy ? r : void 0);
3130
- useInput((input, key) => {
3131
- if (review) {
3132
- if (review.busy) return;
3133
- if (key.upArrow) return setReview({
3134
- ...review,
3135
- scroll: Math.max(0, review.scroll - 1)
3136
- });
3137
- if (key.downArrow) return setReview({
3138
- ...review,
3139
- scroll: review.scroll + 1
3140
- });
3141
- const closed = review.error || review.files.length === 0;
3142
- if (input === "n" || key.escape || closed && (key.return || input === "y")) return setReview(void 0);
3143
- if (input === "y" && !closed) apply();
3144
- return;
3145
- }
3146
- if (key.escape) return setPicked(/* @__PURE__ */ new Set());
3147
- if (key.upArrow) return setCursor(Math.max(0, at - 1));
3148
- if (key.downArrow) return setCursor(Math.min(total - 1, at + 1));
3149
- if (input === " ") {
3150
- if (onCli) togglePick(onCli);
3151
- else setUp();
3152
- return;
3153
- }
3154
- if (key.return) return setUp();
3155
- if (input === "u") return remove();
3156
- if (input === "g") return void refresh();
3157
- }, { isActive: active });
3158
- const wide = layout === "wide";
3159
- const split = splitWidths(columns, wide, {
3160
- panelW: 44,
3161
- maxMain: 110
3162
- });
3163
- const sideWidth = paneInner(split.panelW);
3164
- const mainWidth = wide ? split.mainW - 2 : Math.min(columns, 110);
3165
- const listHeight = Math.max(3, rows - 11);
3166
- const longestLabel = clis.reduce((n, x) => Math.max(n, [...x.label].length), 0);
3167
- const labelW = Math.max(12, Math.min(24, longestLabel + 1));
3168
- const noteW = Math.max(0, mainWidth - (11 + (labelW + 2) + 15));
3169
- const colourOf = (s) => s === "ready" ? c.ok : s === "needs-update" || s === "not-set-up" ? c.warn : s === "blocked" ? c.error : c.quiet;
3170
- const cliRows = useMemo(() => clis, [clis]);
3171
- if (review) {
3172
- const closed = review.error || review.files.length === 0;
3173
- return /* @__PURE__ */ jsx(ReviewBox, {
3174
- review,
3175
- rows,
3176
- width: Math.min(columns - 2, 100),
3177
- active,
3178
- onYes: () => closed ? closeReview() : void apply(),
3179
- onNo: closeReview,
3180
- onScroll: scrollReview
3181
- });
3182
- }
3183
- const box = (on) => on ? "[x]" : "[ ]";
3184
- const cursorMark = (on) => on ? m.cursor : " ";
3185
- return /* @__PURE__ */ jsxs(Box, {
3186
- flexDirection: "row",
3187
- height: rows,
3188
- children: [/* @__PURE__ */ jsxs(Box, {
3189
- flexDirection: "column",
3190
- width: wide ? split.mainW : mainWidth,
3191
- flexShrink: 0,
3192
- children: [
3193
- /* @__PURE__ */ jsx(Label, { children: "Your CLIs" }),
3194
- !state.setup ? /* @__PURE__ */ jsxs(Text, {
3195
- dimColor: true,
3196
- children: ["Looking for your CLIs", m.ellipsis]
3197
- }) : cliRows.length === 0 ? /* @__PURE__ */ jsx(Text, {
3198
- dimColor: true,
3199
- children: "No supported CLI found. Install one, then press g."
3200
- }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(HeaderRow, {
3201
- width: mainWidth,
3202
- cols: [
3203
- {
3204
- w: 6,
3205
- text: "",
3206
- gap: 0
3207
- },
3208
- {
3209
- w: 5,
3210
- text: "",
3211
- gap: 0
3212
- },
3213
- {
3214
- w: labelW + 2,
3215
- text: "CLI"
3216
- },
3217
- {
3218
- w: 15,
3219
- text: "Status"
3220
- },
3221
- {
3222
- w: noteW,
3223
- text: noteW > 4 ? "Note" : "",
3224
- gap: 0
3225
- }
3226
- ]
3227
- }), /* @__PURE__ */ jsx(Hit, {
3228
- flexDirection: "column",
3229
- onWheel: (d) => setCursor(Math.max(0, Math.min(total - 1, at + (d < 0 ? -1 : 1)))),
3230
- isActive: active,
3231
- children: /* @__PURE__ */ jsx(ScrollList, {
3232
- items: cliRows,
3233
- selected: Math.min(at, cliRows.length - 1),
3234
- height: listHeight,
3235
- keyOf: (x) => x.cli,
3236
- renderItem: (x, sel, i) => {
3237
- const off = x.status === "not-installed";
3238
- return /* @__PURE__ */ jsx(Hit, {
3239
- onClick: (e) => clickRow(i, x, e.double),
3240
- isActive: active,
3241
- children: /* @__PURE__ */ jsxs(Row, {
3242
- width: mainWidth,
3243
- selected: sel && at < clis.length,
3244
- children: [
3245
- /* @__PURE__ */ jsx(Cell, {
3246
- w: 2,
3247
- gap: 0,
3248
- color: c.entry,
3249
- children: cursorMark(sel && at < clis.length)
3250
- }),
3251
- /* @__PURE__ */ jsx(Hit, {
3252
- onClick: () => {
3253
- setCursor(i);
3254
- togglePick(x);
3255
- },
3256
- isActive: active,
3257
- children: /* @__PURE__ */ jsx(Cell, {
3258
- w: 4,
3259
- gap: 0,
3260
- children: `${box(picked.has(x.cli))} `
3261
- })
3262
- }),
3263
- /* @__PURE__ */ jsx(Box, {
3264
- width: 5,
3265
- flexShrink: 0,
3266
- children: /* @__PURE__ */ jsx(Chip, {
3267
- cli: x.cli,
3268
- dim: off
3269
- })
3270
- }),
3271
- /* @__PURE__ */ jsx(Cell, {
3272
- w: labelW + 2,
3273
- bold: sel,
3274
- dim: off,
3275
- children: x.label
3276
- }),
3277
- /* @__PURE__ */ jsx(Hit, {
3278
- onClick: () => {
3279
- setCursor(i);
3280
- if (fixable(x)) setUp({ cli: x });
3281
- },
3282
- isActive: active,
3283
- children: /* @__PURE__ */ jsx(Cell, {
3284
- w: 15,
3285
- color: colourOf(x.status),
3286
- dim: off,
3287
- children: STATUS_WORD[x.status]
3288
- })
3289
- }),
3290
- noteW > 4 ? /* @__PURE__ */ jsx(Cell, {
3291
- w: noteW,
3292
- gap: 0,
3293
- color: c.quiet,
3294
- dim: !c.quiet,
3295
- children: plain(x.note ?? (x.version ? x.version : ""), ascii)
3296
- }) : null
3297
- ]
3298
- })
3299
- });
3300
- }
3301
- })
3302
- })] }),
3303
- /* @__PURE__ */ jsx(Text, { children: " " }),
3304
- /* @__PURE__ */ jsx(Label, { children: "Extras" }),
3305
- /* @__PURE__ */ jsx(Hit, {
3306
- onClick: () => {
3307
- setCursor(clis.length);
3308
- setUp({ extra: 0 });
3309
- },
3310
- isActive: active,
3311
- children: /* @__PURE__ */ jsx(Text, { children: `${cursorMark(extraRow === 0)} ${box(extras.helpers)} Get the Claude and Codex helpers when needed` })
3312
- }),
3313
- /* @__PURE__ */ jsx(Hit, {
3314
- onClick: () => {
3315
- setCursor(clis.length + 1);
3316
- setUp({ extra: 1 });
3317
- },
3318
- isActive: active,
3319
- children: /* @__PURE__ */ jsx(Text, { children: `${cursorMark(extraRow === 1)} ${box(mouseOn)} Click and scroll with the mouse` })
3320
- }),
3321
- !wide && health.length > 0 && rows >= 22 ? /* @__PURE__ */ jsxs(Box, {
3322
- flexDirection: "column",
3323
- marginTop: 1,
3324
- children: [/* @__PURE__ */ jsx(Label, { children: "Checkup" }), health.slice(0, 4).map((h) => /* @__PURE__ */ jsx(HealthLine, {
3325
- item: h,
3326
- width: mainWidth
3327
- }, h.text))]
3328
- }) : null,
3329
- /* @__PURE__ */ jsx(Text, { children: " " }),
3330
- /* @__PURE__ */ jsx(Text, {
3331
- dimColor: true,
3332
- children: "You see every change before it happens. We back up each file first."
3333
- })
3334
- ]
3335
- }), wide ? /* @__PURE__ */ jsxs(Pane, {
3336
- width: split.panelW,
3337
- height: rows,
3338
- children: [
3339
- /* @__PURE__ */ jsx(Label, { children: "Checkup" }),
3340
- health.length === 0 ? /* @__PURE__ */ jsxs(Text, {
3341
- dimColor: true,
3342
- children: ["Checking", m.ellipsis]
3343
- }) : null,
3344
- health.map((h) => /* @__PURE__ */ jsx(HealthLine, {
3345
- item: h,
3346
- width: sideWidth
3347
- }, h.text)),
3348
- health.some((h) => h.fixId) ? /* @__PURE__ */ jsx(Text, {
3349
- dimColor: true,
3350
- children: `Press ${m.enter} on a CLI to fix it.`
3351
- }) : null
3352
- ]
3353
- }) : null]
3354
- });
3355
- }
3356
- // src/tui/screens/index.ts
3357
- /** A screen file exports its component as `default` or as `<Name>Screen`. */
3358
- const pick = (m, name) => {
3359
- const mod = m;
3360
- return mod.default ?? mod[`${name}Screen`];
3361
- };
3362
- const SCREEN_COMPONENTS = {
3363
- sessions: pick(sessions_exports, "Sessions"),
3364
- new: pick(new_exports, "New"),
3365
- devices: pick(devices_exports, "Devices"),
3366
- setup: pick(setup_exports, "Setup")
3367
- };
3368
- // src/tui/App.tsx
3369
- /** The app shell: top bar, tabs, one screen, key bar, and the palette and help overlays. */
3370
- const TOAST_MS = 3e3;
3371
- const MIN_COLUMNS = 60;
3372
- const SCREEN_LINE = {
3373
- sessions: (s) => {
3374
- const total = s.sessions.length;
3375
- if (total === 0) return "Nothing is running";
3376
- return `${total} ${total === 1 ? "session" : "sessions"} running`;
3377
- },
3378
- new: () => "Start something new",
3379
- devices: () => "Your machines",
3380
- setup: () => "Get your tools ready"
3381
- };
3382
- function TopBar({ state, screen, width }) {
3383
- const { c, ascii } = useTheme();
3384
- const dot = ascii ? "*" : "●";
3385
- let line = SCREEN_LINE[screen](state);
3386
- let lineColor = c.quiet;
3387
- if (state.connection === "connecting") line = "Connecting…";
3388
- else if (state.connection === "daemon-down") {
3389
- line = "Can't reach the background service. Trying again…";
3390
- lineColor = c.warn;
3391
- } else if (state.connection === "error") {
3392
- line = state.connectionDetail ?? "Something went wrong.";
3393
- lineColor = c.error;
3394
- }
3395
- if (ascii) line = line.replace(/·/g, "-");
3396
- const inner = width - 2;
3397
- const room = Math.max(0, inner - 11);
3398
- return /* @__PURE__ */ jsxs(Band, {
3399
- width,
3400
- children: [
3401
- /* @__PURE__ */ jsx(Text, {
3402
- bold: true,
3403
- ...c.ink ? { color: c.ink } : {},
3404
- children: "c"
3405
- }),
3406
- /* @__PURE__ */ jsx(Text, {
3407
- ...c.entry ? { color: c.entry } : {},
3408
- children: dot
3409
- }),
3410
- /* @__PURE__ */ jsxs(Text, {
3411
- bold: true,
3412
- ...c.ink ? { color: c.ink } : {},
3413
- children: [" ", "conveno"]
3414
- }),
3415
- /* @__PURE__ */ jsx(Text, { children: " " }),
3416
- /* @__PURE__ */ jsx(Box, {
3417
- width: room,
3418
- flexShrink: 0,
3419
- children: /* @__PURE__ */ jsx(Ell, {
3420
- width: room,
3421
- color: lineColor,
3422
- children: line
3423
- })
3424
- })
3425
- ]
3426
- });
3427
- }
3428
- /** The tab row, and under it the rule with the active tab underlined in the entry colour. */
3429
- function Tabs({ screen, layout, width, onGo }) {
3430
- const { c, ascii } = useTheme();
3431
- const narrow = layout === "narrow";
3432
- const labels = SCREENS.map((s) => {
3433
- const on = s.id === screen;
3434
- return {
3435
- id: s.id,
3436
- on,
3437
- text: narrow && !on ? s.key : `${s.key} ${s.title}`
3438
- };
3439
- });
3440
- const gap = 2;
3441
- let at = 1;
3442
- let from = 0;
3443
- let to = 0;
3444
- for (const l of labels) {
3445
- if (l.on) {
3446
- from = at;
3447
- to = at + l.text.length;
3448
- }
3449
- at += l.text.length + gap;
3450
- }
3451
- const thin = ascii ? "-" : "─";
3452
- const heavy = ascii ? "=" : "━";
3453
- const ruleColor = c.rule ? { color: c.rule } : { dimColor: true };
3454
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Box, {
3455
- width,
3456
- height: 1,
3457
- paddingX: 1,
3458
- gap,
3459
- children: labels.map((l) => /* @__PURE__ */ jsx(Clickable, {
3460
- onClick: () => onGo(l.id),
3461
- children: /* @__PURE__ */ jsx(Text, {
3462
- ...l.on ? { bold: true } : {},
3463
- ...l.on ? c.ink ? { color: c.ink } : {} : c.quiet ? { color: c.quiet } : {},
3464
- children: l.text
3465
- })
3466
- }, l.id))
3467
- }), /* @__PURE__ */ jsxs(Text, { children: [
3468
- /* @__PURE__ */ jsx(Text, {
3469
- ...ruleColor,
3470
- children: thin.repeat(from)
3471
- }),
3472
- /* @__PURE__ */ jsx(Text, {
3473
- ...c.entry ? { color: c.entry } : {},
3474
- children: heavy.repeat(to - from)
3475
- }),
3476
- /* @__PURE__ */ jsx(Text, {
3477
- ...ruleColor,
3478
- children: thin.repeat(Math.max(0, width - to))
3479
- })
3480
- ] })] });
3481
- }
3482
- /** The bytes a key hint stands for, or undefined when it is not one single key. */
3483
- function keySequence(key) {
3484
- const n = {
3485
- "⏎": "\r",
3486
- Enter: "\r",
3487
- Esc: "\x1B",
3488
- Tab: " ",
3489
- Space: " ",
3490
- "↑": "\x1B[A",
3491
- "↓": "\x1B[B",
3492
- "→": "\x1B[C",
3493
- "←": "\x1B[D",
3494
- PgUp: "\x1B[5~",
3495
- PgDn: "\x1B[6~"
3496
- }[key];
3497
- if (n) return n;
3498
- const ctrl = /^Ctrl\+([A-Za-z])$/.exec(key);
3499
- if (ctrl) return String.fromCharCode(ctrl[1].toUpperCase().charCodeAt(0) - 64);
3500
- return [...key].length === 1 ? key : void 0;
3501
- }
3502
- function KeyBar({ keys, toast, width, onKey, onHelp, onDismiss }) {
3503
- const { c, ascii } = useTheme();
3504
- const inner = width - 2;
3505
- if (toast) {
3506
- const color = toast.level === "ok" ? c.ok : toast.level === "warn" ? c.warn : c.error;
3507
- const mark = toast.level === "ok" ? "" : toast.level === "warn" ? "! " : "x ";
3508
- return /* @__PURE__ */ jsx(Band, {
3509
- width,
3510
- children: /* @__PURE__ */ jsx(Clickable, {
3511
- onClick: onDismiss,
3512
- children: /* @__PURE__ */ jsx(Ell, {
3513
- width: inner,
3514
- color,
3515
- children: mark + toast.text
3516
- })
3517
- })
3518
- });
3519
- }
3520
- const all = {
3521
- key: "?",
3522
- label: "all keys"
3523
- };
3524
- const shown = [];
3525
- let used = all.key.length + 1 + all.label.length;
3526
- for (const k0 of keys) {
3527
- const k = {
3528
- key: plain(k0.key, ascii),
3529
- label: plain(k0.label, ascii),
3530
- raw: k0.key
3531
- };
3532
- const w = k.key.length + 1 + k.label.length + 2;
3533
- if (used + w > inner) break;
3534
- used += w;
3535
- shown.push(k);
3536
- }
3537
- return /* @__PURE__ */ jsx(Band, {
3538
- width,
3539
- children: [...shown, all].map((k, i) => {
3540
- const seq = k === all ? void 0 : keySequence(k.raw ?? k.key);
3541
- return /* @__PURE__ */ jsx(Clickable, {
3542
- isActive: k === all || seq !== void 0,
3543
- onClick: () => k === all ? onHelp() : seq && onKey(seq),
3544
- children: /* @__PURE__ */ jsxs(Text, {
3545
- wrap: "truncate",
3546
- children: [
3547
- i > 0 ? " " : "",
3548
- /* @__PURE__ */ jsx(Text, {
3549
- bold: true,
3550
- ...c.ink ? { color: c.ink } : {},
3551
- children: k.key
3552
- }),
3553
- /* @__PURE__ */ jsx(Text, {
3554
- ...c.quiet ? { color: c.quiet } : {},
3555
- children: ` ${k.label}`
3556
- })
3557
- ]
3558
- })
3559
- }, `${k.key}-${k.label}`);
3560
- })
3561
- });
3562
- }
3563
- function App({ store, theme, onQuit, size, mouse }) {
3564
- return /* @__PURE__ */ jsx(ThemeProvider, {
3565
- ...theme ? { theme } : {},
3566
- children: /* @__PURE__ */ jsx(Shell, {
3567
- store,
3568
- onQuit,
3569
- size,
3570
- mouse
3571
- })
3572
- });
3573
- }
3574
- function Shell({ store, onQuit, size, mouse }) {
3575
- const { exit } = useApp();
3576
- const { stdin } = useStdin();
3577
- const stdinRef = useRef(stdin);
3578
- stdinRef.current = stdin;
3579
- const [hub] = useState(() => mouse ?? new MouseHub({ inject: (k) => stdinRef.current.write?.(k) }));
3580
- useEffect(() => {
3581
- if (mouse) return;
3582
- const parser = new MouseParser();
3583
- const onData = (chunk) => {
3584
- for (const e of parser.push(String(chunk)).events) hub.dispatch(e);
3585
- };
3586
- stdin.on("data", onData);
3587
- return () => {
3588
- stdin.removeListener("data", onData);
3589
- };
3590
- }, [
3591
- mouse,
3592
- hub,
3593
- stdin
3594
- ]);
3595
- const win = useWindowSize();
3596
- const columns = size?.columns ?? win.columns;
3597
- const rows = size?.rows ?? win.rows;
3598
- const layout = layoutFor(columns);
3599
- const state = useSyncExternalStore(store.subscribe, store.getState);
3600
- const [screen, setScreen] = useState("sessions");
3601
- const screenRef = useRef("sessions");
3602
- const movedRef = useRef(false);
3603
- const [focus, setFocus] = useState();
3604
- const [overlay, setOverlay] = useState("none");
3605
- const typingRef = useRef(false);
3606
- const overlayRef = useRef("none");
3607
- const [keys, setKeysState] = useState([]);
3608
- const [toast, setToast] = useState();
3609
- const [, bump] = useState(0);
3610
- const screenCommands = useRef([]);
3611
- const commandSig = useRef("");
3612
- const toastId = useRef(0);
3613
- const claimedRef = useRef(/* @__PURE__ */ new Set());
3614
- const draftCleared = useRef(false);
3615
- const askedSetup = useRef(false);
3616
- overlayRef.current = overlay;
3617
- const setTyping = useCallback((v) => {
3618
- typingRef.current = v;
3619
- }, []);
3620
- const claimKeys = useCallback((keys) => {
3621
- claimedRef.current = new Set(keys);
3622
- }, []);
3623
- const quit = useCallback(() => {
3624
- onQuit?.();
3625
- exit();
3626
- }, [exit, onQuit]);
3627
- const go = useCallback((to, f) => {
3628
- movedRef.current = true;
3629
- setFocus(f);
3630
- setOverlay("none");
3631
- if (to === screenRef.current) return;
3632
- screenRef.current = to;
3633
- setScreen(to);
3634
- setKeysState([]);
3635
- screenCommands.current = [];
3636
- commandSig.current = "";
3637
- typingRef.current = false;
3638
- claimedRef.current = /* @__PURE__ */ new Set();
3639
- }, []);
3640
- const setKeys = useCallback((next) => {
3641
- setKeysState((cur) => cur.length === next.length && cur.every((k, i) => k.key === next[i]?.key && k.label === next[i]?.label) ? cur : next);
3642
- }, []);
3643
- const setCommands = useCallback((cmds) => {
3644
- screenCommands.current = cmds;
3645
- const sig = cmds.map((c) => `${c.id}|${c.label}|${c.key ?? ""}`).join("\n");
3646
- if (sig !== commandSig.current) {
3647
- commandSig.current = sig;
3648
- bump((n) => n + 1);
3649
- }
3650
- }, []);
3651
- const showToast = useCallback((text, level = "ok", ms = TOAST_MS) => {
3652
- toastId.current += 1;
3653
- setToast({
3654
- id: toastId.current,
3655
- text,
3656
- level,
3657
- ms
3658
- });
3659
- }, []);
3660
- useEffect(() => {
3661
- if (!hub.showHint) return;
3662
- showToast("Mouse is on. Hold Shift to select text.", "ok", 1e4);
3663
- hub.hintShown();
3664
- }, [hub, showToast]);
3665
- useEffect(() => hub.onUnhandled(() => {
3666
- if (overlayRef.current !== "none") setOverlay("none");
3667
- }), [hub]);
3668
- useEffect(() => {
3669
- if (!toast) return;
3670
- const t = setTimeout(() => setToast((cur) => cur?.id === toast.id ? void 0 : cur), toast.ms);
3671
- return () => clearTimeout(t);
3672
- }, [toast]);
3673
- useEffect(() => {
3674
- if (askedSetup.current || !state.setup) return;
3675
- askedSetup.current = true;
3676
- if (movedRef.current) return;
3677
- if (!state.setup.clis.some((c) => c.status === "ready" || c.status === "needs-update") && state.setup.clis.length > 0) go("setup");
3678
- }, [state.setup, go]);
3679
- const draftCtx = useMemo(() => ({ cleared: () => {
3680
- draftCleared.current = true;
3681
- } }), []);
3682
- const globalCommands = useMemo(() => [
3683
- ...SCREENS.map((s) => ({
3684
- id: `go-${s.id}`,
3685
- label: `Go to ${s.title}`,
3686
- key: s.key,
3687
- rank: 90,
3688
- run: () => go(s.id)
3689
- })),
3690
- {
3691
- id: "help",
3692
- label: "Show all keys",
3693
- key: "?",
3694
- rank: 95,
3695
- run: () => setOverlay("help")
3696
- },
3697
- {
3698
- id: "account",
3699
- label: "Open my account page",
3700
- rank: 96,
3701
- run: () => store.actions.openAccountPage().catch(() => showToast("Couldn't open the browser.", "warn"))
3702
- },
3703
- {
3704
- id: "quit",
3705
- label: "Quit (sessions keep running)",
3706
- key: "q",
3707
- rank: 99,
3708
- run: quit
3709
- }
3710
- ], [
3711
- go,
3712
- quit,
3713
- showToast,
3714
- store
3715
- ]);
3716
- const commands = [...screenCommands.current.map((c) => ({
3717
- ...c,
3718
- rank: c.rank ?? 10
3719
- })), ...globalCommands];
3720
- useInput((input, key) => {
3721
- const overlayAtKey = overlayRef.current;
3722
- queueMicrotask(() => {
3723
- if (key.ctrl && input === "c") {
3724
- if (draftCleared.current) {
3725
- draftCleared.current = false;
3726
- return showToast("Press Ctrl+C again to quit", "warn");
3727
- }
3728
- return quit();
3729
- }
3730
- if (overlayAtKey !== "none" || overlayRef.current !== "none") return;
3731
- if (key.ctrl && input === "k") return setOverlay("palette");
3732
- if (typingRef.current) return;
3733
- if (claimedRef.current.has(input)) return;
3734
- if (layout === "tiny") {
3735
- if (input === "q") quit();
3736
- return;
3737
- }
3738
- const hit = SCREENS.find((s) => s.key === input);
3739
- if (hit) return go(hit.id);
3740
- if (input === "/") return setOverlay("palette");
3741
- if (input === "?") return setOverlay("help");
3742
- if (input === "q") return quit();
3743
- if (key.escape) setToast(void 0);
3744
- });
3745
- });
3746
- if (layout === "tiny") return /* @__PURE__ */ jsxs(Box, {
3747
- width: columns,
3748
- height: rows,
3749
- flexDirection: "column",
3750
- paddingX: 1,
3751
- children: [/* @__PURE__ */ jsx(Text, {
3752
- bold: true,
3753
- children: "Make the window a bit wider"
3754
- }), /* @__PURE__ */ jsxs(Text, {
3755
- dimColor: true,
3756
- children: [
3757
- "Conveno needs at least ",
3758
- MIN_COLUMNS,
3759
- " columns."
3760
- ]
3761
- })]
3762
- });
3763
- const Screen = SCREEN_COMPONENTS[screen];
3764
- const bodyRows = Math.max(3, rows - 4);
3765
- const inner = columns - 1;
3766
- const overlayWidth = Math.min(inner - 2, 72);
3767
- return /* @__PURE__ */ jsx(MouseProvider, {
3768
- value: hub,
3769
- children: /* @__PURE__ */ jsx(DraftProvider, {
3770
- value: draftCtx,
3771
- children: /* @__PURE__ */ jsxs(Box, {
3772
- width: columns,
3773
- height: rows,
3774
- flexDirection: "column",
3775
- children: [
3776
- /* @__PURE__ */ jsx(TopBar, {
3777
- state,
3778
- screen,
3779
- width: columns
3780
- }),
3781
- /* @__PURE__ */ jsx(Tabs, {
3782
- screen,
3783
- layout,
3784
- width: columns,
3785
- onGo: go
3786
- }),
3787
- /* @__PURE__ */ jsxs(Box, {
3788
- height: bodyRows,
3789
- width: columns,
3790
- paddingLeft: 1,
3791
- flexDirection: "column",
3792
- overflow: "hidden",
3793
- children: [overlay !== "none" ? /* @__PURE__ */ jsx(Box, {
3794
- height: bodyRows,
3795
- width: inner,
3796
- justifyContent: "center",
3797
- alignItems: "flex-start",
3798
- paddingTop: 1,
3799
- children: overlay === "palette" ? /* @__PURE__ */ jsx(Palette, {
3800
- commands,
3801
- width: overlayWidth,
3802
- height: bodyRows,
3803
- onClose: () => setOverlay("none")
3804
- }) : /* @__PURE__ */ jsx(Help, {
3805
- screenTitle: SCREENS.find((s) => s.id === screen)?.title ?? "",
3806
- screenKeys: keys,
3807
- width: overlayWidth,
3808
- onClose: () => setOverlay("none")
3809
- })
3810
- }) : null, /* @__PURE__ */ jsx(Box, {
3811
- display: overlay === "none" ? "flex" : "none",
3812
- flexDirection: "column",
3813
- height: bodyRows,
3814
- children: /* @__PURE__ */ jsx(MouseScope, {
3815
- active: overlay === "none",
3816
- children: /* @__PURE__ */ jsx(Screen, {
3817
- state,
3818
- actions: store.actions,
3819
- layout,
3820
- rows: bodyRows,
3821
- columns: inner,
3822
- active: overlay === "none",
3823
- focus,
3824
- setKeys,
3825
- setCommands,
3826
- go,
3827
- toast: showToast,
3828
- setTyping,
3829
- claimKeys
3830
- }, screen)
3831
- })
3832
- })]
3833
- }),
3834
- /* @__PURE__ */ jsx(KeyBar, {
3835
- keys,
3836
- ...toast ? { toast } : {},
3837
- width: columns,
3838
- onKey: (seq) => hub.press(seq),
3839
- onHelp: () => setOverlay("help"),
3840
- onDismiss: () => setToast(void 0)
3841
- })
3842
- ]
3843
- })
3844
- })
3845
- });
3846
- }
3847
- // src/tui/pair.ts
3848
- /** The pairing each client started, so `confirmPair` and `pairStatus` need no id. */
3849
- const current = /* @__PURE__ */ new WeakMap();
3850
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
3851
- /** `1234 5678` to `["1234", "5678"]`. */
3852
- const wordsOf = (sas) => sas.split(/\s+/).filter(Boolean);
3853
- /**
3854
- * Start pairing and wait until the other machine has joined and both codes are known. Takes
3855
- * as long as the other machine does, up to five minutes. Throws when the pairing fails.
3856
- */
3857
- async function startPair(client, opts = {}) {
3858
- const now = opts.now ?? Date.now;
3859
- const poll = opts.pollMs ?? 400;
3860
- const started = now();
3861
- const expiresAt = new Date(started + PAIR_TIMEOUT_MS).toISOString();
3862
- let s = await client["devices.pair"]({ role: "invite" });
3863
- current.set(client, s.pairingId);
3864
- while (now() < started + PAIR_TIMEOUT_MS) {
3865
- if (s.state === "failed") throw new Error(s.error ?? "The pairing failed.");
3866
- if (s.state === "done") throw new Error("That pairing already finished.");
3867
- if (s.state === "confirm" && s.sas) return {
3868
- words: wordsOf(s.sas),
3869
- expiresAt,
3870
- ...s.peer ? { peerName: s.peer.name } : {}
3871
- };
3872
- await sleep(poll);
3873
- s = await client["devices.pairStatus"]({ pairingId: s.pairingId });
3874
- }
3875
- throw new Error("Nobody joined in time. Start again on both machines.");
3876
- }
3877
- /** Where the pairing stands now. */
3878
- async function pairStatus(client) {
3879
- const pairingId = current.get(client);
3880
- if (!pairingId) return void 0;
3881
- return client["devices.pairStatus"]({ pairingId });
3882
- }
3883
- /** Stop pairing: nothing gets linked. A no-op when no pairing is running. */
3884
- async function cancelPair(client) {
3885
- if (!current.has(client)) return;
3886
- await confirmPair(client, false);
3887
- }
3888
- /**
3889
- * `match` false: stop, nothing gets linked. `match` true: `code` is what the other machine
3890
- * shows, as the owner typed it. Throws with the daemon's words when the code is wrong.
3891
- */
3892
- async function confirmPair(client, match, code) {
3893
- const pairingId = current.get(client);
3894
- if (!pairingId) throw new Error("No pairing is running.");
3895
- const s = await client["devices.pairConfirm"]({
3896
- pairingId,
3897
- accept: match,
3898
- ...match && code ? { code } : {}
3899
- });
3900
- if (!match) {
3901
- current.delete(client);
3902
- return s;
3903
- }
3904
- if (s.state === "confirm") throw new Error(s.error ?? "That is not the code the other machine shows.");
3905
- if (s.state === "failed") throw new Error(s.error ?? "The pairing failed.");
3906
- if (s.state === "done") current.delete(client);
3907
- return s;
3908
- }
3909
- // src/tui/setup-data.ts
3910
- /**
3911
- * What the Setup screen reads and does. Same facts as `conveno doctor`, in plain words, and the
3912
- * same code path as `conveno init` / `conveno uninstall` for changing files.
3913
- *
3914
- * No Ink or React in here: the store imports it.
3915
- */
3916
- const ready = (r) => r.mcp === "ok" && (r.hooks === null || r.hooks === "ok");
3917
- /** One CLI's row, from what `conveno doctor` found. Exported for tests. */
3918
- function checkFromRow(r, compat) {
3919
- const { adapter, detection } = r;
3920
- const base = {
3921
- cli: adapter.cli,
3922
- label: adapter.displayName
3923
- };
3924
- const version = detection.version;
3925
- const withVersion = version ? { version } : {};
3926
- if (!detection.installed) return {
3927
- ...base,
3928
- status: "not-installed",
3929
- note: "install it, then press g"
3930
- };
3931
- const c = compatStatus(adapter.cli, version, compat);
3932
- if (r.planError) return {
3933
- ...base,
3934
- ...withVersion,
3935
- status: "blocked",
3936
- note: "we can't read its settings file"
3937
- };
3938
- if (c.kind === "older") return {
3939
- ...base,
3940
- ...withVersion,
3941
- status: "blocked",
3942
- note: `too old, update it first (needs ${c.minimum} or newer)`
3943
- };
3944
- if (ready(r)) return {
3945
- ...base,
3946
- ...withVersion,
3947
- status: "ready",
3948
- ...c.kind === "newer" && c.minor ? { note: "a bit newer than we tested, should be fine" } : {}
3949
- };
3950
- const allMissing = [r.mcp, r.hooks].filter((p) => p !== null).every((p) => p === "missing");
3951
- return {
3952
- ...base,
3953
- ...withVersion,
3954
- status: allMissing ? "not-set-up" : "needs-update",
3955
- note: "press ⏎ to fix"
3956
- };
3957
- }
3958
- /** The checkup list. Exported for tests. */
3959
- function healthFrom(input) {
3960
- const out = [];
3961
- out.push(input.daemon === "running" ? {
3962
- level: "ok",
3963
- text: "Conveno is running"
3964
- } : input.daemon === "stopped" ? {
3965
- level: "warn",
3966
- text: "Conveno is not running yet. It starts with your first session."
3967
- } : {
3968
- level: "error",
3969
- text: "Conveno can't be reached"
3970
- });
3971
- const installed = input.clis.filter((c) => c.status !== "not-installed");
3972
- const good = installed.filter((c) => c.status === "ready").length;
3973
- out.push(installed.length === 0 ? {
3974
- level: "warn",
3975
- text: "No supported CLI found on this machine"
3976
- } : {
3977
- level: good === installed.length ? "ok" : "info",
3978
- text: `${good} of ${installed.length} CLIs ready`
3979
- });
3980
- let fixes = 0;
3981
- for (const c of installed) if (c.status === "needs-update") {
3982
- fixes++;
3983
- out.push({
3984
- level: "warn",
3985
- text: `${c.label} needs an update`,
3986
- fixId: `init:${c.cli}`
3987
- });
3988
- } else if (c.status === "not-set-up") {
3989
- fixes++;
3990
- out.push({
3991
- level: "warn",
3992
- text: `${c.label} is not set up yet`,
3993
- fixId: `init:${c.cli}`
3994
- });
3995
- } else if (c.status === "blocked") out.push({
3996
- level: "error",
3997
- text: `${c.label} is blocked: ${c.note ?? "see Setup"}`
3998
- });
3999
- if (input.sync === "online") out.push({
4000
- level: "ok",
4001
- text: "Sync is online"
4002
- });
4003
- else if (input.sync === "offline") out.push({
4004
- level: "warn",
4005
- text: "Sync is offline, it keeps trying"
4006
- });
4007
- if (fixes === 0) out.push({
4008
- level: "ok",
4009
- text: "Up to date"
4010
- });
4011
- return out;
4012
- }
4013
- /** The same facts as `conveno doctor`, as friendly rows. Never throws. */
4014
- async function loadSetup(ctx) {
4015
- const clis = (await Promise.all(ctx.adapters.map((a) => inspect(ctx, a)))).map((r) => checkFromRow(r, ctx.compat));
4016
- let daemon = "stopped";
4017
- let sync;
4018
- try {
4019
- const client = await ctx.connect(connectOpts(ctx, false));
4020
- try {
4021
- await client["session.list"]({});
4022
- daemon = "running";
4023
- const relay = await client["relay.status"]({}).catch(() => void 0);
4024
- if (relay) {
4025
- if (relay.state === "connected") sync = "online";
4026
- else if (relay.state === "connecting" || relay.state === "disconnected") sync = "offline";
4027
- }
4028
- } finally {
4029
- await client.close().catch(() => void 0);
4030
- }
4031
- } catch (e) {
4032
- daemon = daemonProblem(ctx.theme, e).notRunning ? "stopped" : "unreachable";
4033
- }
4034
- return {
4035
- clis,
4036
- health: healthFrom({
4037
- daemon,
4038
- ...sync ? { sync } : {},
4039
- clis
4040
- })
4041
- };
4042
- }
4043
- function parseFixId(fixId) {
4044
- const [kind, cli] = fixId.split(":");
4045
- if (kind === "init" && cli) return {
4046
- kind,
4047
- cli
4048
- };
4049
- if (kind === "uninstall" && cli) return {
4050
- kind,
4051
- cli
4052
- };
4053
- }
4054
- async function planFor(ctx, fixId) {
4055
- const parsed = parseFixId(fixId);
4056
- if (!parsed) return {
4057
- items: [],
4058
- error: "We don't know that fix."
4059
- };
4060
- const a = ctx.adapters.find((x) => x.cli === parsed.cli);
4061
- if (!a) return {
4062
- items: [],
4063
- error: "We don't know that CLI."
4064
- };
4065
- const adapters = [a];
4066
- const env = adapterEnv(ctx);
4067
- const found = [];
4068
- for (const adapter of adapters) {
4069
- const detection = await adapter.detect(env).catch(() => ({
4070
- installed: false,
4071
- configPaths: []
4072
- }));
4073
- if (detection.installed) found.push({
4074
- adapter,
4075
- detection
4076
- });
4077
- }
4078
- if (found.length === 0) return {
4079
- items: [],
4080
- error: "It isn't installed."
4081
- };
4082
- const { items, failures } = await collectPlans(ctx, found, parsed.kind === "init" ? "plan" : "uninstallPlan");
4083
- return {
4084
- items,
4085
- ...failures[0] ? { error: failures[0].message } : {}
4086
- };
4087
- }
4088
- /** Cap on diff lines kept per file, so one big file cannot fill the overlay. */
4089
- const MAX_DIFF_LINES = 60;
4090
- /** What `applyFix` would change, without changing anything. */
4091
- async function planFix(ctx, fixId) {
4092
- const { items, error } = await planFor(ctx, fixId);
4093
- return {
4094
- files: items.map(({ change }) => {
4095
- const lines = unifiedDiff(change.before, change.after);
4096
- return {
4097
- path: tilde(change.path, ctx.home),
4098
- isNew: change.before === null,
4099
- deleted: Boolean(change.deleteFile),
4100
- summary: change.description,
4101
- lines: lines.length > MAX_DIFF_LINES ? lines.slice(0, MAX_DIFF_LINES) : lines
4102
- };
4103
- }),
4104
- ...error ? { error } : {}
4105
- };
4106
- }
4107
- /**
4108
- * Make the change `planFix` showed: back up each file, then write. Same code path as
4109
- * `conveno init` (and `conveno uninstall` without a backup on record). Throws a friendly error.
4110
- */
4111
- async function applyFix(ctx, fixId) {
4112
- const { items, error } = await planFor(ctx, fixId);
4113
- if (error) throw new Error(error);
4114
- if (items.length === 0) return;
4115
- try {
4116
- await applyChanges(ctx, items, parseFixId(fixId)?.kind === "uninstall" ? { markRestored: true } : {});
4117
- } catch (e) {
4118
- if (e instanceof StaleError) throw new Error("A settings file changed while we waited. Press g, then try again.");
4119
- throw new Error(plainError(e));
4120
- }
4121
- }
4122
- async function getExtras(ctx) {
4123
- return { helpers: readSettings(dataPaths(ctx.platform, ctx.dataDir).settings).acpAdapterNpx === true };
4124
- }
4125
- /** Same answer as `conveno init --acp-adapters` / `--no-acp-adapters`. */
4126
- function setHelpers(ctx, on) {
4127
- writeSettings(dataPaths(ctx.platform, ctx.dataDir).settings, { acpAdapterNpx: on });
4128
- }
4129
- // src/tui/store.ts
4130
- /**
4131
- * The app's data layer: one daemon connection, the state the screens read, and every action they
4132
- * can take. It loads once, then follows `events.subscribe` and polls what has no event (sync and
4133
- * devices). When the daemon goes away it says so and reconnects with a growing wait.
4134
- */
4135
- const POLL_MS = 15e3;
4136
- const WATCH_MS = 5e3;
4137
- const STOP_WAIT_MS = 1e4;
4138
- const BACKOFF_MS = [
4139
- 500,
4140
- 1e3,
4141
- 2e3,
4142
- 4e3,
4143
- 8e3
4144
- ];
4145
- const initial = () => ({
4146
- connection: "connecting",
4147
- sessions: []
4148
- });
4149
- const reason = (e) => e instanceof Error ? e.message : String(e);
4150
- function upsert(list, item) {
4151
- const i = list.findIndex((x) => x.id === item.id);
4152
- if (i < 0) return [...list, item];
4153
- const next = list.slice();
4154
- next[i] = item;
4155
- return next;
4156
- }
4157
- /** Only sessions that are online show in the app. */
4158
- const online = (list) => list.filter((s) => s.status !== "offline");
4159
- async function createStore(ctx, opts = {}) {
4160
- const open = opts.connect ?? (() => ctx.connect(connectOpts(ctx, true)));
4161
- const backoff = opts.backoffMs ?? BACKOFF_MS;
4162
- let state = initial();
4163
- const listeners = /* @__PURE__ */ new Set();
4164
- let client;
4165
- let offEvent;
4166
- let closed = false;
4167
- let reconnecting = false;
4168
- const timers = /* @__PURE__ */ new Set();
4169
- const set = (patch) => {
4170
- state = {
4171
- ...state,
4172
- ...patch
4173
- };
4174
- for (const l of [...listeners]) l();
4175
- };
4176
- const live = () => {
4177
- if (!client || state.connection === "daemon-down") throw new Error("Conveno's background service is not running right now. Trying to reconnect.");
4178
- return client;
4179
- };
4180
- function applyEvent(e) {
4181
- switch (e.event) {
4182
- case "session.updated": {
4183
- const s = e.data.session;
4184
- if (e.data.change === "unregistered" || s.status === "offline") set({ sessions: state.sessions.filter((x) => x.id !== s.id) });
4185
- else set({ sessions: upsert(state.sessions, s) });
4186
- break;
4187
- }
4188
- case "orchestrator.changed": {
4189
- const id = e.data.orchestrator;
4190
- set({ sessions: state.sessions.map((s) => ({
4191
- ...s,
4192
- isOrchestrator: s.id === id
4193
- })) });
4194
- break;
4195
- }
4196
- }
4197
- }
4198
- async function pollRelay(c) {
4199
- const [relay, devices] = await Promise.all([c["relay.status"]({}).catch(() => void 0), c["devices.list"]({}).catch(() => void 0)]);
4200
- const patch = {};
4201
- if (relay) patch.relay = relay;
4202
- if (devices) patch.devices = devices;
4203
- if (relay || devices || state.relay || state.devices) set(patch);
4204
- }
4205
- async function loadAccount() {
4206
- const file = dataPaths(ctx.platform, ctx.dataDir).account;
4207
- const tokens = await readAccountTokens(file).catch(() => void 0);
4208
- if (!tokens) return set({ account: { signedIn: false } });
4209
- set({ account: { signedIn: true } });
4210
- try {
4211
- const s = await fetchAccountStatus(tokens.refreshToken, {
4212
- apiBase: ctx.env.CONVENO_API_URL || "https://api.conveno.dev",
4213
- now: () => ctx.now().getTime()
4214
- });
4215
- set({ account: {
4216
- signedIn: true,
4217
- plan: s.plan,
4218
- ...s.status === "trialing" && s.trialDaysLeft !== null && s.trialDaysLeft !== void 0 ? { trialDaysLeft: s.trialDaysLeft } : {}
4219
- } });
4220
- } catch {}
4221
- }
4222
- async function loadSetupData() {
4223
- try {
4224
- set({ setup: await loadSetup(ctx) });
4225
- } catch {}
4226
- }
4227
- /** Everything the screens need, in one pass. Safe to call again after a reconnect. */
4228
- async function load(c) {
4229
- const r = await c["session.list"]({});
4230
- set({ sessions: online(r.sessions) });
4231
- }
4232
- async function attach(c) {
4233
- client = c;
4234
- offEvent?.();
4235
- offEvent = c.onEvent(applyEvent);
4236
- await c["events.subscribe"]({});
4237
- await load(c);
4238
- await pollRelay(c);
4239
- set({ connection: "ready" });
4240
- }
4241
- async function reconnect() {
4242
- if (reconnecting || closed) return;
4243
- reconnecting = true;
4244
- if (state.connection !== "daemon-down") set({
4245
- connection: "daemon-down",
4246
- connectionDetail: "The background service stopped. Trying again."
4247
- });
4248
- const old = client;
4249
- client = void 0;
4250
- offEvent?.();
4251
- offEvent = void 0;
4252
- old?.close().catch(() => void 0);
4253
- for (let attempt = 0; !closed; attempt++) {
4254
- await new Promise((r) => setTimeout(r, backoff[Math.min(attempt, backoff.length - 1)] ?? 1e3));
4255
- if (closed) break;
4256
- try {
4257
- await attach(await open());
4258
- const { connectionDetail: _gone, ...rest } = state;
4259
- state = rest;
4260
- set({});
4261
- break;
4262
- } catch (e) {
4263
- set({
4264
- connection: "daemon-down",
4265
- connectionDetail: reason(e)
4266
- });
4267
- }
4268
- }
4269
- reconnecting = false;
4270
- }
4271
- /** A cheap call that tells us the daemon is still there, and fixes any events we missed. */
4272
- async function watch() {
4273
- const c = client;
4274
- if (!c || reconnecting || closed) return;
4275
- try {
4276
- const r = await c["session.list"]({});
4277
- set({ sessions: online(r.sessions) });
4278
- } catch {
4279
- reconnect();
4280
- }
4281
- }
4282
- const nameOf = (id) => state.sessions.find((s) => s.id === id)?.name;
4283
- const actions = {
4284
- async send(to, text) {
4285
- await live()["owner.send"]({
4286
- to,
4287
- text
4288
- });
4289
- },
4290
- async setLead(sessionId) {
4291
- await live()["orchestrator.claim"]({ sessionId });
4292
- set({ sessions: state.sessions.map((s) => ({
4293
- ...s,
4294
- isOrchestrator: s.id === sessionId
4295
- })) });
4296
- },
4297
- async clearLead() {
4298
- await live()["orchestrator.clear"]({});
4299
- set({ sessions: state.sessions.map((s) => ({
4300
- ...s,
4301
- isOrchestrator: false
4302
- })) });
4303
- },
4304
- async stop(sessionId) {
4305
- const name = nameOf(sessionId);
4306
- const rec = name ? readSpawnRecord(spawnRecordPath(ctx.dataDir, name)) : void 0;
4307
- if (!name || !rec) throw new Error("Only sessions started from Conveno on this machine can be stopped here.");
4308
- if (!rec.acp) throw new Error(`${name} runs in a window. Close it there.`);
4309
- const alive = () => rec.pid !== void 0 && ctx.isAlive(rec.pid);
4310
- writeFileSync(stopRequestPath(spawnRecordPath(ctx.dataDir, rec.name)), "", { mode: 384 });
4311
- const end = Date.now() + STOP_WAIT_MS;
4312
- while (alive() && Date.now() < end) await new Promise((r) => setTimeout(r, 100));
4313
- if (alive() && rec.pid !== void 0) killProcessTree(rec.pid, ctx.platform);
4314
- if (rec.agentPid !== void 0 && ctx.isAlive(rec.agentPid)) killProcessTree(rec.agentPid, ctx.platform);
4315
- },
4316
- async rename(sessionId, name) {
4317
- const res = await live()["session.rename"]({
4318
- sessionId,
4319
- name
4320
- });
4321
- set({ sessions: upsert(state.sessions, res.session) });
4322
- },
4323
- async spawn(p) {
4324
- const c = live();
4325
- const runner = ctx.spawnRunner ?? [process.execPath, process.argv[1] ?? "conveno"];
4326
- const deps = realSpawnDeps({
4327
- platform: ctx.platform,
4328
- env: ctx.env,
4329
- home: ctx.home,
4330
- dataDir: ctx.dataDir,
4331
- client: c,
4332
- runner
4333
- });
4334
- return { sessionId: (await spawnSession(deps, {
4335
- cli: p.cli,
4336
- callerCwd: ctx.cwd,
4337
- cwd: p.cwd,
4338
- name: p.name,
4339
- task: p.prompt,
4340
- window: p.window,
4341
- confineToHome: false
4342
- })).id };
4343
- },
4344
- async refreshSetup() {
4345
- await loadSetupData();
4346
- },
4347
- planFix: (fixId) => planFix(ctx, fixId),
4348
- async applyFix(fixId) {
4349
- await applyFix(ctx, fixId);
4350
- await loadSetupData();
4351
- },
4352
- getExtras: () => getExtras(ctx),
4353
- async setHelpers(on) {
4354
- setHelpers(ctx, on);
4355
- },
4356
- pair: async () => {
4357
- const r = await startPair(live());
4358
- return {
4359
- words: r.words,
4360
- expiresAt: r.expiresAt
4361
- };
4362
- },
4363
- async pairStatus() {
4364
- const s = await pairStatus(live());
4365
- return s ? {
4366
- state: s.state,
4367
- ...s.error ? { error: s.error } : {}
4368
- } : void 0;
4369
- },
4370
- async confirmPair(code) {
4371
- await confirmPair(live(), true, code);
4372
- await pollRelay(live());
4373
- },
4374
- async cancelPair() {
4375
- await cancelPair(live());
4376
- },
4377
- async revokeDevice(deviceId) {
4378
- await live()["devices.revoke"]({ device: deviceId });
4379
- await pollRelay(live());
4380
- },
4381
- async openAccountPage() {
4382
- const base = ctx.env.CONVENO_API_URL || "https://api.conveno.dev";
4383
- openInBrowser(ctx.platform, `${base}/account`);
4384
- }
4385
- };
4386
- try {
4387
- await attach(await open());
4388
- } catch (e) {
4389
- set({
4390
- connection: "daemon-down",
4391
- connectionDetail: reason(e)
4392
- });
4393
- reconnect();
4394
- }
4395
- if (!opts.skipExtras) {
4396
- loadAccount();
4397
- loadSetupData();
4398
- }
4399
- timers.add(setInterval(() => client && void pollRelay(client), opts.pollMs ?? POLL_MS));
4400
- timers.add(setInterval(() => void watch(), opts.watchMs ?? WATCH_MS));
4401
- for (const t of timers) t.unref();
4402
- return {
4403
- getState: () => state,
4404
- subscribe(l) {
4405
- listeners.add(l);
4406
- return () => listeners.delete(l);
4407
- },
4408
- actions,
4409
- async close() {
4410
- closed = true;
4411
- for (const t of timers) clearInterval(t);
4412
- offEvent?.();
4413
- await client?.close().catch(() => void 0);
4414
- }
4415
- };
4416
- }
4417
- // src/tui/run.tsx
4418
- /** Opens the app: connects to the daemon, draws the screen and puts the terminal back on exit. */
4419
- async function runTui(ctx) {
4420
- let first;
4421
- try {
4422
- first = await ctx.connect(connectOpts(ctx, true));
4423
- } catch (e) {
4424
- const problem = daemonProblem(ctx.theme, e);
4425
- return fail(ctx, {
4426
- what: "Conveno can't start its background service",
4427
- detail: [problem.why],
4428
- fix: problem.fix,
4429
- exit: 1,
4430
- ref: "e_daemon"
4431
- });
4432
- }
4433
- let used = false;
4434
- const store = await createStore(ctx, { connect: () => {
4435
- if (used) return ctx.connect(connectOpts(ctx, true));
4436
- used = true;
4437
- return Promise.resolve(first);
4438
- } });
4439
- const input = createMouseInput(ctx);
4440
- try {
4441
- await render(/* @__PURE__ */ jsx(App, {
4442
- store,
4443
- theme: uiThemeFrom(ctx.theme),
4444
- mouse: input.hub
4445
- }), {
4446
- stdin: input.stdin,
4447
- alternateScreen: true,
4448
- exitOnCtrlC: false,
4449
- patchConsole: true
4450
- }).waitUntilExit();
4451
- return 0;
4452
- } catch (e) {
4453
- return fail(ctx, {
4454
- what: "The Conveno app stopped",
4455
- detail: [e instanceof Error ? e.message : String(e)],
4456
- fix: `Run ${cmd(ctx.theme, "conveno doctor")}, or use the commands, such as ${cmd(ctx.theme, "conveno status")}.`,
4457
- exit: 1,
4458
- ref: "e_internal"
4459
- });
4460
- } finally {
4461
- input.dispose();
4462
- await store.close();
4463
- }
4464
- }
4465
- export { runTui };