Files
dais/tools/dais-top
T
Tommi Kyntola d927c2d965 dais-top: flip airc instead of deprecated swyd
The w toggle now drives the airc viewer (~/airc/tools/airc, DAIS_AIRC
override). airc's CLI mirrors swyd's (status --json -> {active}, on/off),
so only the binary, identifiers, and badge/help labels changed.
2026-06-17 19:30:34 +03:00

831 lines
35 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
// dais-top — live TUI cockpit for the dais daemon. Dependency-free ANSI.
//
// DAIS_SOCKET=... socket override (default $XDG_RUNTIME_DIR/dais/control.sock)
//
// Keys: v VAD · r latch · Esc escape · 1-5 target · Tab next-live · t pick
// a arm · m mute · d dry-run · e enter-mode · s strategy · w airc
// c theme · ? help · q quit
// (the footer shows only the frequent ones; ? lists everything,
// incl. > next / < prev target. Language switching is deliberately
// NOT bound here — it needs a multilingual model, i.e. a config swap;
// use dais-ctl set language.)
//
// Entirely optional: the daemon runs identically without it. Subscribing
// turns on the ear's ~8 Hz level meter events; they stop when we disconnect.
"use strict";
const net = require("node:net");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { execFile } = require("node:child_process");
const SOCKET =
process.env.DAIS_SOCKET ??
`${process.env.XDG_RUNTIME_DIR ?? "/tmp"}/dais/control.sock`;
// ---------- terminal ----------
const ESC = "\x1b[";
const out = process.stdout;
const fg = (n) => `${ESC}38;5;${n}m`;
const bgc = (b, f) => `${ESC}48;5;${b}m${ESC}38;5;${f}m`;
const RESET = `${ESC}0m`, BOLD = `${ESC}1m`;
// ---------- themes ----------
// Three looks, cycled with c (the pick persists across runs):
// solarized — the original: semantic ANSI colors that follow the terminal
// theme; 256-cube only where Solarized's remapping bites
// (grays, waveform). Calm instrument panel.
// vivid — same layout, hotter pigments: everything from the 256 cube,
// so it ignores the terminal theme and just glows.
// pollock — rainbow, Rubik's cube and a Jackson Pollock molten into one.
// Different colours all around; static, no effects.
//
// A theme is the C table plus optional hooks: sep(w), title(), footer(text),
// stamp(row), tag(word,i) for label words (each i is a stable per-word hue
// slot), and val, a plain color for values (counter numbers, the header pane
// name). Hooks that are absent fall back to the plain rendering.
const RAIN = [196, 202, 208, 214, 220, 226, 154, 46, 49, 51, 39, 63, 93, 129, 201, 198];
function rainbow(s) {
let o = "", j = 0;
for (const ch of s) o += ch === " " ? " " : fg(RAIN[j++ % RAIN.length]) + ch;
return o + RESET;
}
// Memoized colored separator: colorAt(i, w) picks the cube index per column.
const memoSep = (colorAt) => {
const memo = new Map();
return (w) => {
let s = memo.get(w);
if (!s) {
s = "";
for (let i = 0; i < w; i++) s += fg(colorAt(i, w)) + "─";
memo.set(w, s += RESET);
}
return s;
};
};
const THEMES = {
solarized: {
reset: RESET, bold: BOLD, dim: `${ESC}2m`,
green: `${ESC}32m`, red: `${ESC}31m`, yellow: `${ESC}33m`,
cyan: `${ESC}36m`, magenta: `${ESC}35m`,
// Neutral grays come from the 256-color cube, NOT ANSI bright-black:
// Solarized maps bright-black to (near-)background, which made the
// separators, waveform baseline and unfilled meter dots invisible.
// Indexes ≥16 are never remapped by terminal themes, so these read the
// same on solarized dark/light and stock xterm. Semantic colors above
// stay themed on purpose.
gray: fg(241),
// Waveform data colors, also from the cube: solarized renders ANSI green
// as olive (#859900) — a 1-cell band of it reads as a weird orange. The
// waveform is data viz, not themed UI, so it gets stable true hues.
speech: fg(77), // clear green
ambient: fg(66), // muted teal
// Badge backgrounds — picked for what SOLARIZED renders (the user's theme,
// not going anywhere): 42=olive-green, 41=red, 43=yellow-orange,
// 45=pink, 101=bright-red slot which solarized maps to true orange.
bgGreen: `${ESC}42;30m`, bgRed: `${ESC}41;37m`,
bgYellow: `${ESC}43;30m`, bgMagenta: `${ESC}45;30m`,
bgOrange: `${ESC}101;30m`, bgCyan: `${ESC}46;30m`,
bgGray: bgc(240, 253),
},
vivid: {
reset: RESET, bold: BOLD,
// "dim" is steel blue, not gray — de-emphasis still carries a hue here.
dim: fg(67),
green: fg(48), red: fg(203), yellow: fg(221),
cyan: fg(45), magenta: fg(213),
gray: fg(60),
speech: fg(118), ambient: fg(39),
bgGreen: bgc(41, 16), bgRed: bgc(197, 231),
bgYellow: bgc(220, 16), bgMagenta: bgc(201, 16),
bgOrange: bgc(208, 16), bgCyan: bgc(45, 16),
bgGray: bgc(60, 253),
val: fg(123),
tag: (() => {
const P = [45, 213, 221, 48, 209, 141];
return (s, i) => fg(P[i % P.length]) + s + RESET;
})(),
title: () => `${BOLD}${fg(51)}dais${RESET}`,
// One cyan→violet→pink sweep across the width.
sep: (() => {
const RAMP = [51, 45, 39, 63, 99, 135, 171, 207];
return memoSep((i, w) => RAMP[Math.floor((i / w) * RAMP.length)]);
})(),
},
pollock: {
reset: RESET, bold: BOLD,
dim: fg(141),
green: fg(46), red: fg(196), yellow: fg(226),
cyan: fg(51), magenta: fg(201),
gray: fg(245),
speech: fg(201), ambient: fg(81),
bgGreen: bgc(46, 16), bgRed: bgc(196, 231),
bgYellow: bgc(226, 16), bgMagenta: bgc(129, 231),
bgOrange: bgc(208, 16), bgCyan: bgc(51, 16),
bgGray: bgc(93, 231),
val: fg(220),
// Solid hue per word, Rubik's-cube style. i*5 strides the 16-color
// wheel so neighboring slots don't land on neighboring hues.
tag: (s, i) => fg(RAIN[(i * 5) % RAIN.length]) + s + RESET,
title: () => BOLD + rainbow("dais"),
// Rainbow bands, 4 columns each.
sep: memoSep((i) => RAIN[(i >> 2) % RAIN.length]),
footer: (text) => " " + rainbow(text),
stamp: (row) => fg(RAIN[row % RAIN.length]),
},
};
const THEME_ORDER = Object.keys(THEMES);
const THEME_FILE = path.join(
process.env.XDG_STATE_HOME ?? path.join(os.homedir(), ".local", "state"),
"dais", "top-theme");
let theme = "solarized";
try {
const t = fs.readFileSync(THEME_FILE, "utf8").trim();
if (THEMES[t]) theme = t;
} catch { /* first run */ }
let C = THEMES[theme];
function cycleTheme() {
theme = THEME_ORDER[(THEME_ORDER.indexOf(theme) + 1) % THEME_ORDER.length];
C = THEMES[theme];
note(`theme: ${theme}`);
fs.mkdir(path.dirname(THEME_FILE), { recursive: true }, (err) => {
if (!err) fs.writeFile(THEME_FILE, theme + "\n", () => {});
});
}
const SPARK = "▁▂▃▄▅▆▇█";
const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
function enterScreen() { out.write(`${ESC}?1049h${ESC}?25l`); }
function leaveScreen() { out.write(`${ESC}?1049l${ESC}?25h${C.reset}`); }
// ---------- state ----------
const S = {
connected: false,
mode: "off", // off | vad-listening | manual-recording
modeSince: Date.now(),
armed: false,
muted: false, // warm pause: mic on, utterances dropped until unmute
execution: "?", // "live" | "dry-run" (runtime-togglable)
earAlive: false,
strategy: "?",
enterMode: "?",
language: "?", // active transcription language (display only;
// switching is dais-ctl's job — needs a config swap)
activeSlot: null,
targets: {}, // slot -> {type, pane}
levels: [], // ring of {v: rms, sp: was-speech} samples (~8 Hz)
prob: 0,
speech: false,
transcribing: false,
heard: [], // {time, text, outcome, drop, trace}
picker: null, // {panes, idx, awaitSlot} while the t-overlay is open
help: null, // command reference from the daemon while ? is open
helpScroll: 0, // top row offset into the help body when it overflows
helpRows: 10, // visible help rows (set by render; used for paging)
flashUntil: 0,
counters: { listenMs: 0, utterances: 0, words: 0, drops: 0, asrMsSum: 0, asrN: 0 },
note: "", // transient footer note
noteUntil: 0,
airc: { state: "unknown", busy: false }, // Tesla terminal viewer (~/airc)
};
// ---------- airc (Tesla terminal viewer, a sibling project) ----------
// ~/airc serves the tmux session to the car over an ngrok tunnel. dais-top
// only shells out to its toggle tool: a badge while broadcasting (it IS a
// public URL — worth a loud indicator), w to flip. Hidden when absent.
const AIRC = process.env.DAIS_AIRC ??
path.join(os.homedir(), "airc", "tools", "airc");
function pollAirc() {
if (S.airc.busy || S.airc.state === "missing") return;
execFile(AIRC, ["status", "--json"], { timeout: 4000 }, (err, stdout) => {
if (err && err.code === "ENOENT") { S.airc.state = "missing"; return; }
try { S.airc.state = JSON.parse(stdout).active ? "on" : "off"; }
catch { /* transient — keep the previous state */ }
});
}
function toggleAirc() {
if (S.airc.state === "missing") return note("airc tool not found");
if (S.airc.busy) return;
const turningOn = S.airc.state !== "on";
S.airc.busy = true;
note(turningOn ? "airc: starting (tunnel may take a few seconds)…" : "airc: stopping…");
execFile(AIRC, [turningOn ? "on" : "off"], { timeout: 30000 }, (err, stdout, stderr) => {
S.airc.busy = false;
const line = String(err ? (stderr || stdout) : stdout).split("\n")[0]?.trim();
note(line || (err ? "airc: failed" : "airc: ok"));
pollAirc();
});
}
function today() { return new Date().toISOString().slice(0, 10); }
function clockOf(iso) { return iso ? iso.slice(11, 19) : "--:--:--"; }
// ---------- event ingestion (shared by replay + live) ----------
function ingest(ev, live) {
const t = ev.type;
const p = ev.payload ?? {};
if (t === "asr.level") {
// Keep the speech flag per sample so the waveform can color history:
// green where the VAD heard speech, cyan where it was ambient.
S.levels.push({ v: p.rms ?? 0, sp: !!p.speech });
if (S.levels.length > 240) S.levels.shift();
S.prob = p.prob ?? 0;
S.speech = !!p.speech;
return;
}
const isToday = (ev.time ?? "").startsWith(today());
if (t === "voice.transcript") {
if (live) S.transcribing = false;
if (!isToday) return;
S.counters.utterances += 1;
S.counters.words += (p.text ?? "").split(/\s+/).filter(Boolean).length;
if (p.asr_ms) { S.counters.asrMsSum += p.asr_ms; S.counters.asrN += 1; }
S.heard.unshift({ time: clockOf(ev.time), text: p.text ?? "", trace: ev.trace_id });
S.heard.length = Math.min(S.heard.length, 20);
} else if (t === "asr.dropped") {
if (live) S.transcribing = false;
if (!isToday) return;
S.counters.drops += 1;
S.heard.unshift({ time: clockOf(ev.time), drop: p.reason ?? "?", text: p.text ?? "" });
S.heard.length = Math.min(S.heard.length, 20);
} else if (t === "action.executed" || t === "action.error") {
const entry = S.heard.find((h) => h.trace && h.trace === ev.trace_id);
if (entry) {
entry.outcome = describeAction(t, p);
// What the router made of it — lets the heard list render dictation
// (verbatim speech) and commands (interpreted) differently.
entry.kind = p.plan?.action;
if (live) S.flashUntil = Date.now() + 600;
}
// Confidence-gated refusal: flash what was heard so repeating is a
// glance-and-go, not a dig through the heard list.
if (live && t === "action.error" && p.plan?.uncertain) {
note(`uncertain — say again? “${p.plan.text ?? ""}”`);
}
} else if (t === "control.state_changed") {
// Successful voice controls produce a state change, not action.executed —
// link it back to the heard entry so "mute" reads as a command there too.
const entry = S.heard.find((h) => h.trace && h.trace === ev.trace_id);
if (entry) {
entry.kind = "control";
entry.outcome = `→ ${(p.via ?? "").replace(/^voice:/, "")}`;
}
trackListenTime(p.mode, ev.time, live);
if (live) {
S.mode = p.mode ?? S.mode;
if (p.active_slot != null) S.activeSlot = p.active_slot;
if (p.muted != null) S.muted = p.muted;
if (p.dry_run != null) S.execution = p.dry_run ? "dry-run" : "live";
}
} else if (live && t === "asr.speech_start") {
S.speech = true;
} else if (live && t === "asr.speech_end") {
S.speech = false;
S.transcribing = true;
} else if (live && t === "asr.ready") {
S.earAlive = true;
} else if (live && t === "asr.error") {
note(`ear error: ${p.error ?? "?"}`);
}
}
function describeAction(t, p) {
if (t === "action.error") return `${C.red}✗ ${p.error ?? "error"}${C.reset}`;
const plan = p.plan ?? {};
if (plan.action === "press-keys") return `→ ${(plan.keys ?? []).join(" ")}`;
if (plan.action === "type-text") return plan.submit ? "→ typed ⏎" : "→ typed";
if (plan.action === "control") return `→ ${plan.control}`;
if (plan.action === "macro") return `→ macro (${plan.steps} steps)`;
return "→ done";
}
// listen-time bookkeeping from control.state_changed stream (replay + live)
let openSince = null; // epoch ms while mode != off
function trackListenTime(mode, isoTime, live) {
const at = live ? Date.now() : Date.parse(isoTime ?? "");
if (!Number.isFinite(at)) return;
const open = mode && mode !== "off";
if (open && openSince == null) openSince = at;
if (!open && openSince != null) {
if ((isoTime ?? "").startsWith(today()) || live) S.counters.listenMs += at - openSince;
openSince = null;
}
}
function liveListenMs() {
return S.counters.listenMs + (openSince != null ? Date.now() - openSince : 0);
}
function note(msg) { S.note = msg; S.noteUntil = Date.now() + 3000; }
// ---------- daemon connections ----------
let ctl = null; // request/response connection
const pending = []; // FIFO of response callbacks
function request(req, cb) {
if (!ctl || ctl.destroyed) { if (cb) cb(null); return; }
pending.push(cb ?? (() => {}));
ctl.write(JSON.stringify(req) + "\n");
}
function lineSplitter(onLine) {
let buf = "";
return (chunk) => {
buf += chunk;
let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl);
buf = buf.slice(nl + 1);
if (line.trim()) onLine(line);
}
};
}
function connect() {
// control connection: seed queries + key commands
ctl = net.createConnection({ path: SOCKET });
ctl.setEncoding("utf8");
ctl.on("data", lineSplitter((line) => {
const cb = pending.shift();
try { if (cb) cb(JSON.parse(line)); } catch { /* ignore */ }
}));
ctl.on("connect", () => { S.connected = true; seed(); });
ctl.on("error", () => {});
ctl.on("close", () => { S.connected = false; retry(); });
// subscription connection: the live feed
const sub = net.createConnection({ path: SOCKET });
sub.setEncoding("utf8");
let acked = false;
sub.on("connect", () => sub.write('{"op":"subscribe"}\n'));
sub.on("data", lineSplitter((line) => {
if (!acked) { acked = true; return; } // the {"ok":true,"subscribed":true} ack
try { ingest(JSON.parse(line), true); } catch { /* ignore */ }
}));
sub.on("error", () => {});
sub.on("close", () => { if (ctl && !ctl.destroyed) ctl.destroy(); });
}
let retryTimer = null;
function retry() {
if (retryTimer) return;
retryTimer = setTimeout(() => { retryTimer = null; connect(); }, 1500);
}
function seed() {
// reset day counters, replay today's log, then status + targets
S.counters = { listenMs: 0, utterances: 0, words: 0, drops: 0, asrMsSum: 0, asrN: 0 };
S.heard = [];
openSince = null;
request({ op: "events", last: 1000 }, (resp) => {
for (const ev of resp?.events ?? []) ingest(ev, false);
request({ op: "query", query: "status" }, (st) => {
if (!st?.ok) return;
S.mode = st.mode; S.armed = st.armed; S.execution = st.execution;
S.muted = st.muted; S.earAlive = st.ear_alive; S.strategy = st.strategy;
S.enterMode = st.enter_mode; S.activeSlot = st.active_slot;
if (st.language) S.language = st.language;
// status says we're currently open -> start the live clock now
if (st.mode !== "off" && openSince == null) openSince = Date.now();
if (st.mode === "off" && openSince != null) openSince = null;
});
request({ op: "target", action: "list" }, (tg) => {
if (tg?.ok) { S.targets = tg.targets ?? {}; S.activeSlot = tg.active_slot; }
});
});
}
// ---------- rendering ----------
let frame = 0;
function fmtDuration(ms) {
const s = Math.floor(ms / 1000);
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), r = s % 60;
return h ? `${h}h${String(m).padStart(2, "0")}m` : m ? `${m}m${String(r).padStart(2, "0")}s` : `${r}s`;
}
const REV = `${ESC}7m`;
// Mirrored full-width waveform from the level ring, newest at the right.
// The mirror axis is the seam BETWEEN the two rows: the top row rises to it
// with plain lower-block glyphs (which sit on their cell's floor = the axis),
// the bottom row hangs from it by reverse-videoing the complementary glyph
// (reverse paints the glyph's EMPTY part with the foreground color, so the
// colored area descends from the cell top = the axis). Silence is a single
// dim spine on the axis; speech swells symmetrically around it. Speech
// samples green, ambient teal. Scale follows the ring's own max, so it
// re-adapts to mic gain within ~30 s of history.
function waveform(width) {
const ring = S.levels.slice(-width);
let scale = 0.08;
for (const s of ring) if (s.v > scale) scale = s.v;
const pad = width - ring.length;
let top = pad ? C.gray + "▁".repeat(pad) + C.reset : "";
let bot = " ".repeat(pad);
for (const s of ring) {
const k = Math.min(8, Math.round((s.v / scale) * 8));
const col = s.sp ? C.speech : C.ambient;
top += k === 0 ? C.gray + "▁" + C.reset : col + SPARK[k - 1] + C.reset;
bot += k === 0 ? " " : REV + col + (k === 8 ? " " : SPARK[7 - k]) + C.reset;
}
return [top, bot];
}
function modeBadge() {
if (!S.connected) return `${C.bgGray} DISCONNECTED ${C.reset}`;
if (S.mode === "vad-listening") {
const dot = frame % 10 < 5 ? "●" : "◉";
return `${C.bgGreen} ${dot} LISTENING ${C.reset}`;
}
if (S.mode === "manual-recording") {
const dot = frame % 6 < 3 ? "⏺" : " ";
return `${C.bgRed} ${dot} RECORDING ${C.reset}`;
}
return `${C.bgGray} ○ OFF ${C.reset}`;
}
function truncate(s, n) {
return s.length > n ? s.slice(0, n - 1) + "…" : s;
}
// Clip a rendered line to `width` VISIBLE columns: ANSI escapes pass through
// at zero width, output is cut once the budget is spent, and a reset is
// appended so a cut can't leak styling into the next line. (Double-width
// emoji count as one — close enough; the lines carrying them are short.)
function clipLine(s, width) {
let out = "", vis = 0, i = 0;
while (i < s.length) {
if (s[i] === "\x1b") {
const m = /^\x1b\[[0-9;?]*[a-zA-Z]/.exec(s.slice(i));
if (m) { out += m[0]; i += m[0].length; continue; }
}
if (vis >= width) break;
out += s[i]; vis++; i++;
}
return out + C.reset;
}
function render() {
frame++;
const w = Math.max(60, out.columns ?? 80);
const h = out.rows ?? 24;
const sep = C.sep ? C.sep(w) : C.gray + "─".repeat(w) + C.reset;
const lines = [];
// Label words and values: themed when the theme says so, otherwise the
// fallback style (fb) — solarized renders exactly as before the themes.
const tag = (s, i, fb = "") => C.tag ? C.tag(s, i) : fb ? fb + s + C.reset : s;
const val = C.val ?? "";
// header
const activeT = S.targets[S.activeSlot];
const targetStr = S.activeSlot != null
? `${tag("target", 0)} ${C.bold}[${S.activeSlot}]${C.reset} ` +
(activeT?.alive === false
? `${C.red}${describeTarget(activeT)} ✗ gone${C.reset}`
: `${val}${describeTarget(activeT)}${C.reset}`)
: tag("no target", 0);
// Exceptional states get loud inverse badges; normal states stay calm
// text. live is bold green (it IS the state that delivers keystrokes).
const right = `${S.earAlive ? C.green + "ear ✓" : C.red + "ear ✗"}${C.reset} ` +
(S.armed ? `${C.bgMagenta} ARMED ${C.reset} ` : `${C.dim}armed –${C.reset} `) +
(S.execution === "dry-run" ? `${C.bgYellow} DRY-RUN ${C.reset}`
: S.execution === "live" ? `${C.bold}${C.green}live${C.reset}`
: `${C.dim}${S.execution}${C.reset}`);
const mutedBadge = S.muted ? ` ${C.bgOrange} 🔇 MUTED ${C.reset}` : "";
// Broadcasting badge: while airc is on, the terminal is on a public URL.
const aircStr = S.airc.busy ? ` ${C.dim}airc ⋯${C.reset}`
: S.airc.state === "on" ? ` ${C.bgCyan} AIRC ${C.reset}`
: S.airc.state === "off" ? ` ${C.dim}airc –${C.reset}` : "";
const title = C.title ? C.title() : `${C.bold}dais${C.reset}`;
lines.push(` ${title} ${modeBadge()}${mutedBadge} ${targetStr} ${right}${aircStr}`);
lines.push(sep);
// mic meter — a two-row mirrored waveform while VAD is live
if (S.mode === "vad-listening") {
const [wTop, wBot] = waveform(w - 7);
lines.push(` ${C.dim}mic${C.reset} ${wTop}`);
lines.push(` ${wBot}`);
const spin = S.transcribing ? `${C.magenta}${SPINNER[frame % SPINNER.length]} transcribing…${C.reset}` :
S.speech ? `${C.green}🗣 speech${C.reset}` : `${C.dim}listening${C.reset}`;
const dots = 10, on = Math.min(dots, Math.round(S.prob * dots));
const probBar = (S.prob >= 0.5 ? C.speech : C.gray) + "●".repeat(on) +
C.gray + "○".repeat(dots - on) + C.reset;
lines.push(` ${C.dim}vad${C.reset} ${probBar} ${S.prob >= 0.5 ? C.speech : C.dim}${S.prob.toFixed(2)}${C.reset} ${spin}`);
} else if (S.mode === "manual-recording") {
const pulse = "▰".repeat(1 + (frame % 8)) + "▱".repeat(8 - (frame % 8));
const spin = S.transcribing ? ` ${C.magenta}${SPINNER[frame % SPINNER.length]} transcribing…${C.reset}` : "";
lines.push(` mic ${C.red}${pulse}${C.reset} ${C.dim}recording (no meter in latch mode)${C.reset}${spin}`);
} else {
const spin = S.transcribing ? ` ${C.magenta}${SPINNER[frame % SPINNER.length]} transcribing…${C.reset}` : "";
lines.push(` mic ${C.dim}closed${C.reset}${spin}`);
}
lines.push(sep);
// targets — ✗ marks a target that cannot be delivered to right now
// (tmux pane gone / ydotoold socket missing); liveness comes from the
// periodic target-list poll.
const slots = Object.keys(S.targets).sort();
const tgts = slots.map((k) => {
const t = S.targets[k];
const active = String(S.activeSlot) === k;
const dead = t?.alive === false;
const label = `${k} ${describeTarget(t)}${dead ? " ✗" : ""}`;
const col = dead ? C.red : active ? C.cyan : C.dim;
return active ? `${C.bold}${col}[${label}]${C.reset}` : `${col} ${label} ${C.reset}`;
});
lines.push(` ${tag("targets", 1)} ${tgts.join(" ") || C.dim + "none configured" + C.reset}`);
lines.push(sep);
// heard list — or an overlay (help / pane picker) while open
if (S.help) {
const headerIdx = lines.length;
lines.push(""); // header filled in once we know scroll state
const body = helpBody(w);
const avail = Math.max(3, h - lines.length - 4);
S.helpRows = avail;
const maxScroll = Math.max(0, body.length - avail);
S.helpScroll = Math.min(S.helpScroll, maxScroll);
const shown = body.slice(S.helpScroll, S.helpScroll + avail);
const pos = maxScroll > 0
? ` ${C.dim}${S.helpScroll + 1}–${S.helpScroll + shown.length}/${body.length} · ↑↓ PgUp/PgDn${C.reset}`
: "";
lines[headerIdx] = ` ${C.bold}help${C.reset} ${C.dim}? or Esc to close${C.reset}${pos}`;
for (const ln of shown) lines.push(ln);
} else if (S.picker) {
const pk = S.picker;
const head = pk.awaitSlot
? `${C.yellow}assign ${C.bold}${pk.panes[pk.idx]?.pane}${C.reset}${C.yellow} to which slot? [1-5]${C.reset}`
: `${C.dim}↑/↓ choose · Enter assign · Esc cancel${C.reset}`;
lines.push(` ${C.bold}pick target pane${C.reset} ${head}`);
const rows = Math.max(3, h - lines.length - 4);
pk.panes.slice(0, rows).forEach((p, i) => {
const cur = i === pk.idx;
const mark = p.focus ? `${C.cyan}⌖${C.reset}`
: p.agent ? `${C.green}★${C.reset}` : " ";
const slot = p.slot != null ? ` ${C.cyan}=slot ${p.slot}${C.reset}` : "";
const path = tilde(p.path ?? "");
const row = ` ${mark} ${p.pane} ${C.dim}[${p.command}]${C.reset} ${C.dim}${truncate(path, 30)}${C.reset}${slot}`;
lines.push(cur ? `${ESC}7m${row}${C.reset}` : row);
});
} else {
lines.push(` ${C.bold}${tag("heard", 2)}${C.reset}`);
const heardRows = Math.max(3, h - lines.length - 4);
const flash = Date.now() < S.flashUntil;
S.heard.slice(0, heardRows).forEach((e, i) => {
const stamp = C.stamp ? C.stamp(i) : C.dim;
if (e.drop) {
lines.push(` ${stamp}${e.time}${C.reset} ${C.red}✗${C.reset} ${C.dim}dropped: ${e.drop}` +
(e.text ? ` (“${truncate(e.text, 24)}”)` : "") + C.reset);
} else {
// Dictation is verbatim speech — quoted, plain. A command was
// interpreted — yellow » marker so the two read apart at a glance.
const isCmd = e.kind && e.kind !== "type-text" && e.kind !== "none";
const hl = i === 0 && flash ? C.green : isCmd ? C.yellow : "";
const text = truncate(e.text, w - 32);
const shown = isCmd
? `${C.yellow}»${C.reset} ${hl}${text}${C.reset}`
: `${C.dim}“${C.reset}${hl}${text}${C.reset}${C.dim}”${C.reset}`;
lines.push(` ${stamp}${e.time}${C.reset} ${shown} ` +
`${C.cyan}${e.outcome ?? ""}${C.reset}`);
}
});
}
while (lines.length < h - 3) lines.push("");
// counters + footer
const c = S.counters;
const asr = c.asrN ? `asr ø${(c.asrMsSum / c.asrN / 1000).toFixed(1)}s` : "asr –";
lines.push(sep);
lines.push(` ${tag("today", 3, C.dim)} ${tag("listened", 4)} ${C.bold}${val}${fmtDuration(liveListenMs())}${C.reset}` +
` · ${C.bold}${val}${c.utterances}${C.reset} ${tag("utterances", 5)} · ${C.bold}${val}${c.words}${C.reset} ${tag("words", 6)}` +
` · ${C.bold}${val}${c.drops}${C.reset} ${tag("drops", 7)} · ${tag(asr, 8)}` +
` ${C.bold}${C.cyan}${S.strategy}${C.reset}${C.dim}/${C.reset}${C.bold}${C.green}${S.enterMode}${C.reset}${C.dim}/${C.reset}${C.bold}${C.magenta}${S.language}${C.reset}`);
// Frequent keys only — ? lists the rest (Esc, Tab, >/<, s, c, …).
const noteStr = Date.now() < S.noteUntil ? ` ${C.yellow}${S.note}${C.reset}` : "";
const keysTxt = "[v]ad [r]ec [1-5] [t]arget [a]rm [m]ute [d]ry [e]nter [?] help [q]uit";
lines.push((C.footer ? C.footer(keysTxt) : ` ${C.dim}${keysTxt}${C.reset}`) + noteStr);
// Hard-clip to the REAL terminal width (w has a 60-col floor for layout):
// a wrapped line scrolls the whole frame and rolls the top row off.
const realW = out.columns ?? 80;
out.write(`${ESC}H${ESC}2J` + lines.slice(0, h).map((l) => clipLine(l, realW)).join("\n"));
}
function describeTarget(t) {
if (!t) return "?";
return t.type === "focus" ? "focus" : t.pane ?? "?";
}
// Full key + voice-command reference shown behind ?. Keyboard rows are static;
// the voice section is the daemon's live vocabulary (config commands included).
function helpBody(w) {
const L = [];
const key = (k, desc) => ` ${C.bold}${k.padEnd(4)}${C.reset} ${C.dim}${desc}${C.reset}`;
L.push(` ${C.cyan}keyboard${C.reset}`);
L.push(key("v", "toggle VAD listening"));
L.push(key("r", "toggle manual record latch"));
L.push(key("Esc", "send Escape to the target"));
L.push(key("1-5", "switch to target slot"));
L.push(key("Tab", "next live target (skips dead ones)"));
L.push(key(">", "next target — cycle (incl. dead)"));
L.push(key("<", "previous target — cycle"));
L.push(key("t", "pick a target pane"));
L.push(key("a", "arm: next utterance must be a command"));
L.push(key("m", "toggle mute (warm pause; mic stays on)"));
L.push(key("d", "toggle dry-run (route & show, don't deliver)"));
L.push(key("e", "cycle enter-mode"));
L.push(key("s", "cycle router strategy"));
L.push(key("w", "toggle airc (Tesla terminal viewer — public tunnel!)"));
L.push(key("c", `color theme: ${THEME_ORDER.join(" → ")} (now ${theme})`));
L.push(key("q", "quit"));
const hd = S.help;
L.push("");
if (hd.loading) { L.push(` ${C.cyan}voice${C.reset} ${C.dim}loading…${C.reset}`); return L; }
if (!hd.ok) {
L.push(` ${C.cyan}voice${C.reset} ${C.red}unavailable: ${hd.error ?? "?"}${C.reset}`);
return L;
}
const ctx = `strategy ${hd.strategy} · enter ${hd.enter_mode}` +
(hd.strategy === "prefix" ? ` · prefix “${hd.prefix}”` : "");
L.push(` ${C.cyan}voice${C.reset} ${C.dim}${ctx}${C.reset}`);
const row = (say, does) =>
` ${C.green}${truncate(say, 22).padEnd(22)}${C.reset}${C.dim}${truncate(does, Math.max(20, w - 26))}${C.reset}`;
for (const c of hd.controls ?? []) L.push(row(c.say, c.does));
const cmds = hd.commands ?? [];
for (const c of cmds.filter((c) => !c.config)) L.push(row(c.say, c.does));
const configured = cmds.filter((c) => c.config);
if (configured.length) {
L.push(` ${C.cyan}configured${C.reset} ${C.dim}(config/dais.edn)${C.reset}`);
for (const c of configured) L.push(row(c.say, c.does));
}
const kp = hd.keypress;
if (kp) {
L.push(` ${C.dim}key presses: ${kp.triggers.join("/")} + keys${C.reset}`);
L.push(` ${C.dim}keys: ${kp.keys.join(" ")}${C.reset}`);
L.push(` ${C.dim}ignored: ${kp.ignored.join(" ")}${C.reset}`);
}
return L;
}
function tilde(p) {
const h = process.env.HOME;
return h && p.startsWith(h) ? "~" + p.slice(h.length) : p;
}
// ---------- input ----------
const ENTER_MODES = ["no-enter", "enter-auto", "enter-always"];
const STRATEGIES = ["whole-match", "prefix", "key-armed"];
function cycle(list, current) {
return list[(list.indexOf(current) + 1) % list.length];
}
function onKey(key) {
if (key === "\x03") return shutdown();
if (S.picker) return onPickerKey(key);
if (S.help) return onHelpKey(key);
if (key === "q") return shutdown();
if (key === "?") return openHelp();
if (key === "v") request({ op: "control", action: "toggle-vad" }, ack("vad"));
else if (key === "r") request({ op: "control", action: "toggle-record" }, ack("rec"));
else if (key === "a") request({ op: "control", action: "arm" }, ack("armed"));
else if (key === "m")
request({ op: "control", action: S.muted ? "unmute" : "mute" }, ack(S.muted ? "unmuted" : "muted"));
else if (key === "d") request({ op: "control", action: "toggle-dry-run" }, ack("dry-run toggled"));
else if (key === "t") openPicker();
else if (key === "e") {
const next = cycle(ENTER_MODES, S.enterMode);
request({ op: "settings", enter_mode: next }, ack(`enter: ${next}`));
} else if (key === "s") {
const next = cycle(STRATEGIES, S.strategy);
request({ op: "settings", strategy: next }, ack(`router: ${next}`));
} else if (key === "w") toggleAirc();
else if (key === "c") cycleTheme();
else if (key === "\x1b") request({ op: "control", action: "esc" }, ack("escape sent"));
else if (key === "\t") request({ op: "target", action: "next-live" }, ack("next live target"));
// Hidden cycle keys (documented only in the ? overlay): blind next/prev.
else if (key === ">") request({ op: "target", action: "next" }, ack("next target"));
else if (key === "<") request({ op: "target", action: "prev" }, ack("prev target"));
else if (/^[1-5]$/.test(key)) {
request({ op: "target", action: "use", slot: Number(key) }, ack(`target ${key}`));
}
}
function openHelp() {
S.help = { loading: true };
S.helpScroll = 0;
request({ op: "query", query: "commands" }, (resp) => {
if (S.help) S.help = resp ?? { ok: false, error: "no response" };
});
}
function onHelpKey(key) {
if (key === "?" || key === "\x1b" || key === "q") { S.help = null; return; }
const page = Math.max(1, S.helpRows - 1); // one line of overlap, like a pager
if (key === "\x1b[A" || key === "k") S.helpScroll -= 1;
else if (key === "\x1b[B" || key === "j") S.helpScroll += 1;
else if (key === "\x1b[5~") S.helpScroll -= page; // PgUp
else if (key === "\x1b[6~") S.helpScroll += page; // PgDn
if (S.helpScroll < 0) S.helpScroll = 0; // upper bound clamped in render
}
function openPicker() {
request({ op: "target", action: "panes" }, (resp) => {
// "focus" is a target TYPE, not a tmux pane, so the daemon's panes op
// can't list it. Synthesize a first row: reassigning a slot away from
// focus must be reversible from the TUI ("set" accepts pane:"focus").
const focusSlot = Object.keys(S.targets)
.find((k) => S.targets[k]?.type === "focus");
const focus = { pane: "focus", command: "ydotool", path: "the focused app",
focus: true, slot: focusSlot != null ? Number(focusSlot) : null };
if (!resp?.ok) note(`tmux panes unavailable (${resp?.error ?? "?"}) — focus only`);
S.picker = { panes: [focus, ...(resp?.ok ? resp.panes ?? [] : [])],
idx: 0, awaitSlot: false };
});
}
function onPickerKey(key) {
const pk = S.picker;
if (key === "\x1b" || key === "q" || key === "t") { S.picker = null; return; }
if (pk.awaitSlot) {
if (/^[1-5]$/.test(key)) {
const pane = pk.panes[pk.idx]?.pane;
S.picker = null;
request({ op: "target", action: "set", slot: Number(key), pane },
ack(`slot ${key} → ${pane}`));
request({ op: "target", action: "list" }, (tg) => {
if (tg?.ok) { S.targets = tg.targets ?? {}; S.activeSlot = tg.active_slot; }
});
} else {
pk.awaitSlot = false;
}
return;
}
if (key === "\x1b[A" || key === "k") pk.idx = Math.max(0, pk.idx - 1);
else if (key === "\x1b[B" || key === "j") pk.idx = Math.min(pk.panes.length - 1, pk.idx + 1);
else if (key === "\r" || key === "\n") pk.awaitSlot = pk.panes.length > 0;
}
function ack(what) {
return (resp) => {
if (resp?.ok) note(what);
else note(`✗ ${resp?.error ?? "failed"}`);
// refresh armed/slot/settings quickly after a control
request({ op: "query", query: "status" }, (st) => {
if (st?.ok) {
S.armed = st.armed; S.activeSlot = st.active_slot; S.mode = st.mode;
S.enterMode = st.enter_mode; S.strategy = st.strategy;
S.muted = st.muted; S.execution = st.execution;
}
});
};
}
function shutdown() {
leaveScreen();
process.exit(0);
}
// ---------- main ----------
function main() {
enterScreen();
process.stdin.setRawMode?.(true);
process.stdin.resume();
process.stdin.setEncoding("utf8");
let escTimer = null;
process.stdin.on("data", (k) => {
// lone Esc vs escape sequences (arrows etc.): wait briefly for a follow-up
if (k === "\x1b") {
escTimer = setTimeout(() => onKey("\x1b"), 120);
return;
}
if (escTimer && k.startsWith("[")) { clearTimeout(escTimer); escTimer = null; return; }
if (escTimer) { clearTimeout(escTimer); escTimer = null; }
onKey(k);
});
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
out.on("resize", render);
connect();
setInterval(render, 100);
// Modest liveness poll: refresh target slots (incl. alive flags) while
// connected. Only runs while dais-top itself runs — daemon stays idle
// otherwise.
setInterval(() => {
if (!S.connected) return;
request({ op: "target", action: "list" }, (tg) => {
if (tg?.ok) { S.targets = tg.targets ?? {}; S.activeSlot = tg.active_slot; }
});
}, 1500);
// airc is independent of the daemon; a slow poll keeps the badge honest.
pollAirc();
setInterval(pollAirc, 5000);
}
main();