neurastream 0.2.65 → 0.2.66

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,111 @@
1
+ // The one config.yml editor. setConfigKeys edits dotted keys line by line and keeps every other
2
+ // line byte-for-byte (comments, order, other sections): it never re-serialises YAML.
3
+ // checkEdited proves an edited file still loads before anything is written.
4
+
5
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { ConfigError, loadConfig } from "./config.ts";
9
+
10
+ const leading = (line: string): number => line.length - line.trimStart().length;
11
+ const isBlank = (line: string): boolean => line.trim() === "";
12
+
13
+ // Leaf dotted paths: a mapping recurses; a scalar, a list or null is a leaf.
14
+ export function leafKeys(node: unknown, prefix: string[] = []): string[] {
15
+ if (node === null || typeof node !== "object" || Array.isArray(node)) return [prefix.join(".")];
16
+ return Object.entries(node).flatMap(([k, v]) => leafKeys(v, [...prefix, k]));
17
+ }
18
+
19
+ export function valueAt(cfg: unknown, key: string): unknown {
20
+ let node = cfg;
21
+ for (const seg of key.split(".")) node = (node as Record<string, unknown>)[seg];
22
+ return node;
23
+ }
24
+
25
+ // A value as YAML text for setConfigKeys: lists in flow style on one line ([a, b]); scalars as JSON, which is valid YAML.
26
+ export function yamlValue(value: unknown): string {
27
+ return Array.isArray(value) ? `[${value.map((x) => JSON.stringify(x)).join(", ")}]` : JSON.stringify(value);
28
+ }
29
+
30
+ // First line at or after `from` that is not part of a block whose keys sit at column `col`.
31
+ // A block is the following lines that are blank or indented deeper than the key.
32
+ function blockEnd(lines: string[], from: number, col: number): number {
33
+ let j = from;
34
+ while (j < lines.length && (isBlank(lines[j]!) || leading(lines[j]!) > col)) j++;
35
+ return j;
36
+ }
37
+
38
+ // Just past the last non-blank line in [from, end): where a new line joins that block.
39
+ function afterLast(lines: string[], from: number, end: number): number {
40
+ let at = from;
41
+ for (let i = from; i < end; i++) if (!isBlank(lines[i]!)) at = i + 1;
42
+ return at;
43
+ }
44
+
45
+ // Sets one path segment list inside the block of `parent` (-1 = the whole file). `indent` is the
46
+ // column its keys sit at. Recurses one level per segment, so a.b.c only matches inside a's and b's blocks.
47
+ function setPath(lines: string[], segs: string[], value: string, parent: number, indent: string): void {
48
+ const [seg, ...deeper] = segs as [string, ...string[]];
49
+ const lo = parent < 0 ? 0 : parent + 1;
50
+ const hi = parent < 0 ? lines.length : blockEnd(lines, lo, leading(lines[parent]!));
51
+ const re = new RegExp("^" + indent + seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(\\s*):(.*)$");
52
+ let k = -1;
53
+ for (let i = lo; i < hi; i++) {
54
+ if (re.test(lines[i]!)) {
55
+ k = i;
56
+ break;
57
+ }
58
+ }
59
+ if (deeper.length === 0) {
60
+ if (k < 0) {
61
+ lines.splice(afterLast(lines, lo, hi), 0, `${indent}${seg}: ${value}`);
62
+ return;
63
+ }
64
+ // Replace the leaf and any child lines under it; keep its trailing comment.
65
+ const rest = re.exec(lines[k]!)![2]!;
66
+ const comment = rest.match(/\s+#.*$/)?.[0] ?? "";
67
+ const cut = afterLast(lines, k + 1, blockEnd(lines, k + 1, indent.length));
68
+ lines.splice(k, cut - k, `${indent}${seg}: ${value}${comment}`);
69
+ return;
70
+ }
71
+ if (k < 0) {
72
+ k = afterLast(lines, lo, hi);
73
+ lines.splice(k, 0, `${indent}${seg}:`);
74
+ }
75
+ const end = blockEnd(lines, k + 1, indent.length);
76
+ const child = lines.slice(k + 1, end).find((l) => !isBlank(l));
77
+ const childIndent = child === undefined ? `${indent} ` : /^[ \t]*/.exec(child)![0];
78
+ setPath(lines, deeper, value, k, childIndent);
79
+ }
80
+
81
+ // `values` maps each dotted key to its already-formatted YAML value text (`true`, `7788`,
82
+ // `["a", "b"]`, `"quoted"`). A value with a line break is refused: it would write extra keys.
83
+ export function setConfigKeys(text: string | null, values: Record<string, string>): string {
84
+ for (const [key, value] of Object.entries(values)) {
85
+ if (/[\n\r]/.test(value)) throw new ConfigError(`config ${key}: a value cannot contain a line break`);
86
+ }
87
+ // "".split("\n") is [""], so an empty file still ends with a newline after the first insert.
88
+ let base = text ?? "";
89
+ if (base !== "" && !base.endsWith("\n")) base += "\n";
90
+ const lines = base.split("\n");
91
+ for (const [key, value] of Object.entries(values)) setPath(lines, key.split("."), value, -1, "");
92
+ return lines.join("\n");
93
+ }
94
+
95
+ // Proves an edited config still loads through loadConfig before anything is written. The copy goes
96
+ // to a fresh mkdtemp dir (mode 0700, unpredictable name, so no planted symlink can redirect it);
97
+ // the dir is removed in finally. Returns false after reporting the error when the file does not load.
98
+ export function checkEdited(edited: string, home: string, error: (line: string) => void): boolean {
99
+ const dir = mkdtempSync(join(tmpdir(), "neurastream-check-"));
100
+ try {
101
+ const file = join(dir, "config.yml");
102
+ writeFileSync(file, edited, { mode: 0o600 });
103
+ loadConfig({ file, home });
104
+ return true;
105
+ } catch (err) {
106
+ error(err instanceof ConfigError ? err.message : String(err));
107
+ return false;
108
+ } finally {
109
+ rmSync(dir, { recursive: true, force: true });
110
+ }
111
+ }
@@ -11,6 +11,7 @@ import { checkDiagram } from "./diagram-check.ts";
11
11
  import { gitRaw } from "./proc.ts";
12
12
  import { recordPublish } from "./pages-expiry.ts";
13
13
  import { realTailscale, type Tailscale } from "./tailscale.ts";
14
+ import { checkEdited, setConfigKeys } from "./config-edit.ts";
14
15
  const HERE = dirname(fileURLToPath(import.meta.url));
15
16
  export const PAGES_UNIT_TEMPLATE = join(HERE, "../../templates/systemd/neurastream-pages.service");
16
17
  const DATA_MARK = "/* === DATA === */";
@@ -19,30 +20,13 @@ export interface RunnerResult { status: number | null; stderr: string; stdout?:
19
20
  export type Runner = (args: string[]) => RunnerResult;
20
21
  export const systemRunner: Runner = args => { const r = spawnSync("systemctl", args, { encoding:"utf8" }); return { status:r.status, stderr:r.stderr ?? "", stdout:r.stdout ?? "" }; };
21
22
  export interface Setup { home?: string; runner?: Runner; tailscale?: Tailscale }
22
- function editBlock(text: string | null, values: { enabled: boolean; port: number; dir: string }): string {
23
- const fresh = ["pages:", ` enabled: ${values.enabled}`, ` port: ${values.port}`, ` dir: "${values.dir.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`];
24
- if (text === null) return `${fresh.join("\n")}\n`;
25
- const lines = text.split("\n");
26
- let start = -1;
27
- for (let i = 0; i < lines.length; i++) if (/^pages\s*:(\s*(?:#.*)?)?$/.test(lines[i] ?? "")) { start = i; break; }
28
- if (start < 0) return `${text === "" || text.endsWith("\n") ? text : `${text}\n`}${fresh.join("\n")}\n`;
29
- let end = start + 1;
30
- while (end < lines.length && (lines[end] === "" || /^[ \t]/.test(lines[end]!))) end++;
31
- const setKey = (key: string, value: string): void => {
32
- const re = new RegExp(`^([ \\t]+)${key}\\s*:.*$`);
33
- for (let i = start + 1; i < end; i++) if (re.test(lines[i]!)) { lines[i] = lines[i]!.replace(re, `$1${key}: ${value}`); return; }
34
- let at = start + 1;
35
- for (let i = start + 1; i < end; i++) if (lines[i]!.trim() !== "") at = i + 1;
36
- lines.splice(at, 0, ` ${key}: ${value}`); end++;
37
- };
38
- setKey("enabled", String(values.enabled)); setKey("port", String(values.port)); setKey("dir", `"${values.dir.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`);
39
- return lines.join("\n");
40
- }
41
23
  export function pagesOn(opts: Setup & { port?: number; dir?: string }): number {
42
24
  const home = opts.home ?? homedir(), runner = opts.runner ?? systemRunner, ts = opts.tailscale ?? realTailscale;
43
25
  const file = configFile(home), old = existsSync(file) ? readFileSync(file,"utf8") : null; const cfg = loadConfig({ home });
44
26
  const port = opts.port ?? cfg.pages.port, dir = opts.dir ?? cfg.pages.dir;
45
- const edited = editBlock(old, { enabled:true, port, dir }); mkdirSync(dirname(file), { recursive:true }); writeFileSync(file, edited);
27
+ const edited = setConfigKeys(old, { "pages.enabled": "true", "pages.port": String(port), "pages.dir": JSON.stringify(dir) });
28
+ if (!checkEdited(edited, home, msg => console.error(msg))) return 1;
29
+ mkdirSync(dirname(file), { recursive:true }); writeFileSync(file, edited);
46
30
  mkdirSync(dir, { recursive:true });
47
31
  mkdirSync(join(home,".config/systemd/user"),{recursive:true}); copyFileSync(PAGES_UNIT_TEMPLATE, join(home,".config/systemd/user/neurastream-pages.service"));
48
32
  for (const args of [["--user","daemon-reload"],["--user","enable","--now","neurastream-pages"]]) { const r=runner(args); if(r.status!==0){console.error(r.stderr);return 1;} }
@@ -50,7 +34,8 @@ export function pagesOn(opts: Setup & { port?: number; dir?: string }): number {
50
34
  }
51
35
  export function pagesOff(opts: Setup = {}): number {
52
36
  const home=opts.home ?? homedir(), runner=opts.runner ?? systemRunner, file=configFile(home), old=existsSync(file)?readFileSync(file,"utf8"):null;
53
- const cfg=loadConfig({home}); writeFileSync(file,editBlock(old,{enabled:false,port:cfg.pages.port,dir:cfg.pages.dir}));
37
+ const cfg=loadConfig({home}); const edited=setConfigKeys(old,{"pages.enabled":"false","pages.port":String(cfg.pages.port),"pages.dir":JSON.stringify(cfg.pages.dir)});
38
+ if(!checkEdited(edited,home,msg=>console.error(msg))) return 1; writeFileSync(file,edited);
54
39
  const r=runner(["--user","stop","neurastream-pages"]); if(r.status!==0){console.error(r.stderr);return 1;} return 0;
55
40
  }
56
41
  /**
@@ -0,0 +1,120 @@
1
+ // `neurastream setup` detection (plan 20261028_2356 P3): reads the machine and returns one typed
2
+ // object. Pure over injected seams (HOME as the fs root, a PATH lookup, the Tailscale seam, os
3
+ // facts): no prompts, no writes. realSeams wires the node fs/os, the given PATH and realTailscale.
4
+ // Core names no harness: the caller passes the harness binaries (the adapter registry lives in
5
+ // src/adapters, which core may not import).
6
+
7
+ import { existsSync, readdirSync, statfsSync, statSync } from "node:fs";
8
+ import { availableParallelism, homedir, totalmem } from "node:os";
9
+ import { join } from "node:path";
10
+ import { configFile, loadConfig, type Config } from "./config.ts";
11
+ import { PROXY_BIN } from "./secret-redact.ts";
12
+ import { realTailscale, type Tailscale, type TailscaleState } from "./tailscale.ts";
13
+
14
+ export interface HarnessBin {
15
+ name: string;
16
+ /** The binary name looked up on PATH. */
17
+ bin: string;
18
+ }
19
+
20
+ export interface OsFacts {
21
+ cores: number;
22
+ ramMb: number;
23
+ /** Free space on the filesystem holding HOME, in GB (1e9 bytes, as the machine guard counts). */
24
+ diskFreeGb: number;
25
+ }
26
+
27
+ export interface SetupSeams {
28
+ /** HOME: the fs root the config and the work roots resolve against. */
29
+ home: string;
30
+ onPath(bin: string): boolean;
31
+ harnesses: HarnessBin[];
32
+ tailscale: Tailscale;
33
+ os: OsFacts;
34
+ }
35
+
36
+ export interface MachineProposal {
37
+ load_over_cores: number;
38
+ avail_min_mb: number;
39
+ disk_min_gb: number;
40
+ }
41
+
42
+ export interface SetupFacts {
43
+ /** Absolute paths of HOME's direct non-dot children that hold a git repo one level down, sorted. */
44
+ workRoots: string[];
45
+ /** Names of the harnesses whose binary is on PATH. */
46
+ harnesses: string[];
47
+ tailscale: { state: TailscaleState; logins: string[] | null };
48
+ secretgate: boolean;
49
+ machine: OsFacts;
50
+ /** The values setup would write: the config.yml values on a re-run, else computed from the machine. */
51
+ proposed: MachineProposal;
52
+ /** The loaded config when config.yml exists; null on a first run. */
53
+ current: Config | null;
54
+ }
55
+
56
+ function hasRepoBelow(dir: string): boolean {
57
+ try {
58
+ return readdirSync(dir, { withFileTypes: true }).some(c => c.isDirectory() && existsSync(join(dir, c.name, ".git")));
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+
64
+ function workRoots(home: string): string[] {
65
+ return readdirSync(home, { withFileTypes: true })
66
+ .filter(d => d.isDirectory() && !d.name.startsWith("."))
67
+ .map(d => join(home, d.name))
68
+ .filter(hasRepoBelow)
69
+ .toSorted();
70
+ }
71
+
72
+ export function detect(seams: SetupSeams): SetupFacts {
73
+ // env {} so a live QUEUE_* override never leaks into what setup proposes.
74
+ const cfg = loadConfig({ home: seams.home, env: {} });
75
+ const current = existsSync(configFile(seams.home)) ? cfg : null;
76
+ const os = seams.os;
77
+ // Without a config.yml, loadConfig returns the shipped template, so its machine values are the defaults.
78
+ const proposed: MachineProposal = current
79
+ ? { load_over_cores: cfg.machine.load_over_cores, avail_min_mb: cfg.machine.avail_min_mb, disk_min_gb: cfg.machine.disk_min_gb }
80
+ : {
81
+ load_over_cores: cfg.machine.load_over_cores,
82
+ avail_min_mb: Math.max(1024, Math.round(os.ramMb * 0.1)),
83
+ disk_min_gb: Math.max(1, Math.min(cfg.machine.disk_min_gb, Math.floor(os.diskFreeGb * 0.1))),
84
+ };
85
+ return {
86
+ workRoots: workRoots(seams.home),
87
+ harnesses: seams.harnesses.filter(h => seams.onPath(h.bin)).map(h => h.name),
88
+ tailscale: { state: seams.tailscale.state(), logins: seams.tailscale.logins() },
89
+ secretgate: seams.onPath(PROXY_BIN),
90
+ machine: os,
91
+ proposed,
92
+ current,
93
+ };
94
+ }
95
+
96
+ function binOnPath(bin: string, env: NodeJS.ProcessEnv): boolean {
97
+ for (const dir of (env.PATH ?? "").split(":")) {
98
+ if (dir === "") continue;
99
+ try {
100
+ if (statSync(join(dir, bin)).isFile()) return true;
101
+ } catch {}
102
+ }
103
+ return false;
104
+ }
105
+
106
+ /** The production seams: node fs/os, the given PATH, realTailscale. */
107
+ export function realSeams(harnesses: HarnessBin[], home: string = homedir(), env: NodeJS.ProcessEnv = process.env): SetupSeams {
108
+ const st = statfsSync(home);
109
+ return {
110
+ home,
111
+ onPath: bin => binOnPath(bin, env),
112
+ harnesses,
113
+ tailscale: realTailscale,
114
+ os: {
115
+ cores: availableParallelism(),
116
+ ramMb: totalmem() / 1024 / 1024,
117
+ diskFreeGb: (Number(st.bavail) * Number(st.bsize)) / 1e9,
118
+ },
119
+ };
120
+ }
@@ -4,6 +4,8 @@
4
4
 
5
5
  import { spawnSync } from "node:child_process";
6
6
 
7
+ export type TailscaleState = "missing" | "stopped" | "running";
8
+
7
9
  export interface Tailscale {
8
10
  /** This machine's tailnet IPv4 address (first line of `tailscale ip -4`), or null when tailscale fails or answers nothing. */
9
11
  ip4(): string | null;
@@ -13,6 +15,8 @@ export interface Tailscale {
13
15
  whois(peer: string): string | null;
14
16
  /** Every `User[*].LoginName` of `tailscale status --json`, or null when tailscale fails or the answer is unreadable — callers then skip their login check with a printed warning, never refuse on a tailscale failure. */
15
17
  logins(): string[] | null;
18
+ /** `missing` when the binary does not exist; `stopped` when it is installed but `tailscale status --json` fails, answers unreadably, or its BackendState is not "Running"; else `running`. */
19
+ state(): TailscaleState;
16
20
  }
17
21
 
18
22
  function firstStdoutLine(args: string[]): string | null {
@@ -33,6 +37,16 @@ export function parseWhoisLogin(stdout: string): string | null {
33
37
  }
34
38
  }
35
39
 
40
+ /** `running` only when `BackendState` of `tailscale status --json` is "Running"; unreadable JSON or any other state is `stopped`. */
41
+ export function parseBackendState(stdout: string): "running" | "stopped" {
42
+ try {
43
+ const parsed = JSON.parse(stdout) as { BackendState?: unknown };
44
+ return parsed.BackendState === "Running" ? "running" : "stopped";
45
+ } catch {
46
+ return "stopped";
47
+ }
48
+ }
49
+
36
50
  export const realTailscale: Tailscale = {
37
51
  ip4() {
38
52
  return firstStdoutLine(["ip", "-4"]);
@@ -70,4 +84,10 @@ export const realTailscale: Tailscale = {
70
84
  return null;
71
85
  }
72
86
  },
87
+ state() {
88
+ const r = spawnSync("tailscale", ["status", "--json"], { encoding: "utf8", timeout: 8000 });
89
+ if (r.error) return (r.error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "stopped";
90
+ if (r.status !== 0) return "stopped";
91
+ return parseBackendState(r.stdout ?? "");
92
+ },
73
93
  };
@@ -5,12 +5,13 @@
5
5
  // ones), so tests record argv and never run systemctl or the tailscale binary.
6
6
 
7
7
  import { spawnSync } from "node:child_process";
8
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
- import { homedir, tmpdir } from "node:os";
8
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
10
  import { dirname, join } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { ConfigError, configFile, loadConfig } from "./config.ts";
13
13
  import { realTailscale, type Tailscale } from "./tailscale.ts";
14
+ import { checkEdited, setConfigKeys } from "./config-edit.ts";
14
15
 
15
16
  const HERE = dirname(fileURLToPath(import.meta.url));
16
17
  export const UI_UNIT_TEMPLATE = join(HERE, "../../templates/systemd/neurastream-ui.service");
@@ -28,6 +29,29 @@ export const systemRunner: Runner = args => {
28
29
  return { status: r.status, stderr: r.stderr ?? "" };
29
30
  };
30
31
 
32
+ export interface Terminal {
33
+ /** Prints the question on the terminal and returns the answer line. */
34
+ ask(question: string): string;
35
+ /** Opens a URL in the default browser. */
36
+ open(url: string): void;
37
+ }
38
+
39
+ // Production terminal. sh reads the answer from the inherited terminal, so uiOn stays synchronous.
40
+ export const systemTerminal: Terminal = {
41
+ ask(question) {
42
+ const r = spawnSync("sh", ["-c", 'printf "%s" "$1" >&2; read -r answer; printf "%s" "$answer"', "sh", question], { encoding: "utf8", stdio: ["inherit", "pipe", "inherit"] });
43
+ return r.stdout ?? "";
44
+ },
45
+ open(url) {
46
+ spawnSync(process.platform === "darwin" ? "open" : "xdg-open", [url], { stdio: "ignore" });
47
+ },
48
+ };
49
+
50
+ const TAILSCALE_DOWNLOAD = "https://tailscale.com/download";
51
+ const TAILSCALE_MISSING = "The phone page needs Tailscale (free, private network for your devices). Install it: Linux `curl -fsSL https://tailscale.com/install.sh | sh` (asks for your password), macOS: the App Store app, others: https://tailscale.com/download. Then run `neurastream ui on` again.";
52
+ const TAILSCALE_STOPPED = "Tailscale is installed but not connected. Run `sudo tailscale up` (Linux) or open the Tailscale app (macOS), then run this again.";
53
+ export { TAILSCALE_MISSING, TAILSCALE_STOPPED };
54
+
31
55
  export interface UiSetupOptions {
32
56
  /** HOME the config file and the user unit resolve against. Default: the real home. */
33
57
  home?: string;
@@ -43,64 +67,8 @@ export interface UiOnOptions extends UiSetupOptions {
43
67
  login: string;
44
68
  /** The --port N of the command line; null leaves the config's ui.port in place. */
45
69
  port?: number | null;
46
- }
47
-
48
- // Line-based edit of the top-level `ui:` block: replaces only the enabled/owner_login/port
49
- // lines inside it, keeps every other line of the file byte-for-byte (comments, order, other
50
- // sections), and appends a fresh block when the config has none. Never re-serialises YAML.
51
- function editUiBlock(text: string | null, values: { enabled: boolean; owner_login: string | null; port: number | null }): string {
52
- const fresh = ["ui:", ` enabled: ${values.enabled}`];
53
- if (values.owner_login !== null) fresh.push(` owner_login: ${values.owner_login}`);
54
- if (values.port !== null) fresh.push(` port: ${values.port}`);
55
- if (text === null) return `${fresh.join("\n")}\n`;
56
- const lines = text.split("\n");
57
- let start = -1;
58
- for (let i = 0; i < lines.length; i++) {
59
- if (/^ui\s*:(\s*(?:#.*)?)?$/.test(lines[i] ?? "")) {
60
- start = i;
61
- break;
62
- }
63
- }
64
- if (start === -1) {
65
- const base = text === "" || text.endsWith("\n") ? text : `${text}\n`;
66
- return `${base}${fresh.join("\n")}\n`;
67
- }
68
- let end = start + 1;
69
- while (end < lines.length && (lines[end] === "" || /^[ \t]/.test(lines[end]!))) end++;
70
- const setKey = (key: string, value: string): void => {
71
- const re = new RegExp(`^([ \\t]+)${key}\\s*:.*$`);
72
- for (let i = start + 1; i < end; i++) {
73
- const line = lines[i]!;
74
- if (re.test(line)) {
75
- lines[i] = line.replace(re, `$1${key}: ${value}`);
76
- return;
77
- }
78
- }
79
- // The block has no such key: insert after its last non-blank line, at two-space indent.
80
- let at = start + 1;
81
- for (let i = start + 1; i < end; i++) if (lines[i]!.trim() !== "") at = i + 1;
82
- lines.splice(at, 0, ` ${key}: ${value}`);
83
- };
84
- setKey("enabled", String(values.enabled));
85
- if (values.owner_login !== null) setKey("owner_login", values.owner_login);
86
- if (values.port !== null) setKey("port", String(values.port));
87
- return lines.join("\n");
88
- }
89
-
90
- // Validates the edited text through loadConfig before anything is written: if it would not
91
- // load, nothing is written and the caller reports the error (the real file stays untouched).
92
- function checkEdited(edited: string, home: string, what: string, error: (line: string) => void): boolean {
93
- const check = join(tmpdir(), `neurastream-ui-${what}-check-${process.pid}.yml`);
94
- try {
95
- writeFileSync(check, edited);
96
- loadConfig({ file: check, home });
97
- return true;
98
- } catch (err) {
99
- error(err instanceof ConfigError ? err.message : String(err));
100
- return false;
101
- } finally {
102
- rmSync(check, { force: true });
103
- }
70
+ /** Terminal seam for the missing-tailscale question. Absent: no question, only the message. src/cli/ui.ts passes the real one on a TTY. */
71
+ terminal?: Terminal;
104
72
  }
105
73
 
106
74
  export function uiOn(opts: UiOnOptions): number {
@@ -109,6 +77,18 @@ export function uiOn(opts: UiOnOptions): number {
109
77
  const tailscale = opts.tailscale ?? realTailscale;
110
78
  const print = opts.print ?? console.log;
111
79
  const error = opts.error ?? console.error;
80
+ // Tailscale comes first (plan 20261028_2356 P2): nothing is read, written or run unless it is up.
81
+ const state = tailscale.state();
82
+ if (state === "missing") {
83
+ error(`neurastream ui: ${TAILSCALE_MISSING}`);
84
+ const terminal = opts.terminal;
85
+ if (terminal && terminal.ask("Open the Tailscale download page now? [y/N] ").trim().toLowerCase() === "y") terminal.open(TAILSCALE_DOWNLOAD);
86
+ return 1;
87
+ }
88
+ if (state === "stopped") {
89
+ error(`neurastream ui: ${TAILSCALE_STOPPED}`);
90
+ return 1;
91
+ }
112
92
  const file = configFile(home);
113
93
  let cfg;
114
94
  try {
@@ -125,8 +105,16 @@ export function uiOn(opts: UiOnOptions): number {
125
105
  return 1;
126
106
  }
127
107
  const original = existsSync(file) ? readFileSync(file, "utf8") : null;
128
- const edited = editUiBlock(original, { enabled: true, owner_login: opts.login, port: opts.port ?? null });
129
- if (!checkEdited(edited, home, "on", error)) return 1;
108
+ const values: Record<string, string> = { "ui.enabled": "true", "ui.owner_login": opts.login };
109
+ if (typeof opts.port === "number") values["ui.port"] = String(opts.port);
110
+ let edited: string;
111
+ try {
112
+ edited = setConfigKeys(original, values);
113
+ } catch (err) {
114
+ error(err instanceof ConfigError ? err.message : String(err));
115
+ return 1;
116
+ }
117
+ if (!checkEdited(edited, home, error)) return 1;
130
118
  const unitPath = join(home, ".config", "systemd", "user", "neurastream-ui.service");
131
119
  mkdirSync(dirname(unitPath), { recursive: true });
132
120
  copyFileSync(UI_UNIT_TEMPLATE, unitPath);
@@ -165,8 +153,8 @@ export function uiOff(opts: UiSetupOptions): number {
165
153
  }
166
154
  const file = configFile(home);
167
155
  if (existsSync(file)) {
168
- const edited = editUiBlock(readFileSync(file, "utf8"), { enabled: false, owner_login: null, port: null });
169
- if (!checkEdited(edited, home, "off", error)) return 1;
156
+ const edited = setConfigKeys(readFileSync(file, "utf8"), { "ui.enabled": "false" });
157
+ if (!checkEdited(edited, home, error)) return 1;
170
158
  writeFileSync(file, edited);
171
159
  }
172
160
  return 0;