@conveno/cli 0.2.0-rc.2 → 0.2.0-rc.3

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