mirror of
https://github.com/Kynde/dais.git
synced 2026-10-20 08:32:28 +02:00
Driving, with the airc viewer on the car screen: an agent's input box is
visible and what you want to give it is a PROMPT, a sentence, not a keypress.
airc's buttons cover keypresses well and the Android app has IME dictation, but
the car browser has no dictation at all — so today a prompt means the laptop
keyboard. dais already transcribes locally and pastes into a tmux pane; what
was missing is a way to say "record now, and deliver it to the pane I am
looking at" without touching the laptop.
{"op":"dictate","action":"toggle","pane":"%19"}
start | stop | discard | toggle, the last resolved against the CURRENT mode so
a client that missed a poll — or a latch someone started at the desk — cannot
be inverted by a stale button. stop TRANSCRIBES and discard throws the
recording away, which is the existing latch-vs-voice-off rule and what makes a
remote ✕ useful: a misheard prompt can be dropped instead of typed. Omit the
pane and it is F10 over the socket.
The pane is an ephemeral override (:dictate-target), never a slot. transition!
persists on any :targets/:active-slot change, so writing a slot would churn
targets.edn and the digits addressed by voice; a reserved slot is worse, since
load-targets honors the overlay only while (get targets active-slot) is truthy
and a dangling active-slot silently discards every persisted target on the next
start. save-targets! writes only :targets/:active-slot, so nothing a car-side
tap aims at can survive a restart — asserted by a test rather than by new code.
Two orderings are load-bearing, and both are the opposite of the obvious one:
- The override is set in the same transition as the mode change and AFTER it.
Every mic OPEN drops a pending override (drop-override), which is exactly
what keeps a forgotten one from stealing a later utterance — so setting the
aim first would erase it.
- It is consumed after dispatch, not before, and only when the plan actually
DELIVERED. :armed is cleared before dispatch for the opposite reason; copying
that placement here would deliver to the slot instead. An utterance the
confidence gate refused ("say again?") keeps its aim, or the repeat lands in
the wrong pane.
No TTL. The plan sketched one; the rule set turned out not to need a clock,
because a mic open, a voice-off and any explicit target op all drop the aim,
and the only utterance that can reach a pending override is the one it was set
for. Dropping the TTL also removes the failure mode where an aim expires
mid-sentence.
state gains the precedence split the feature needs: active-target is where an
UTTERANCE goes (override, else slot) and is the single point everything the
router produces reads through; slot-target is the active slot ignoring any
override, and the desk-side router-bypassing paths now use it — the keystroke
bridge behind dais-top's passthrough lock and F11/esc are keys typed by
someone sitting at the machine, aimed at the slot they can see, and must not
follow a recording someone made from the car.
The ear's transcribe-vs-discard decision moves from a hardcoded via string to
ear/transcribing-stops, so the next caller that latches has one obvious place
to register — miss it and recordings vanish silently, which is a bad way to
find out.
The dictation run is now keyed on the delivery LABEL rather than the slot: an
override, a re-pointed slot and two slots naming one pane all have to answer
"same cursor?" correctly, and only the label does.
parse-target-value accepts a bare pane id ("%23"). tmux takes one anywhere a
target-pane goes, it is how airc reports panes, and it is the one spec form
immune to the pane_index renumbering trap — so `dais-ctl target set 3 %19`
starts working as a side effect.
Reporting: dictate_target rides along in state.json, the status query, the
state_changed broadcast and the target-list reply (a UI that missed an event
self-heals on the poll it already runs), and dais-top shows the override on the
target line so the cockpit never claims the slot while speech goes elsewhere.
tools/dais-ctl gains `dictate` with completion, which makes the whole feature
hand-testable without airc.
Also drops the last references to FABLE_PLAN.md, GOAL.md and CODEX_PLAN.md,
deleted in 9353d85: the README reading order, one code comment, and AGENTS.md's
claim that a missing file is normative.
1116 lines
47 KiB
JavaScript
Executable File
1116 lines
47 KiB
JavaScript
Executable File
#!/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
|
||
// x release slot · a arm · m mute · d dry-run · e enter-mode
|
||
// s strategy · w airc · c theme · k keylock · p passthrough
|
||
// K idle-lock · ? 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.)
|
||
//
|
||
// The lock (k / p) exists because this window sits next to the agent's: a
|
||
// sentence meant for the agent typed in here would otherwise toggle half the
|
||
// panel. k swallows keys; p forwards them to the target pane instead. Ctrl-]
|
||
// or F12 leaves either — deliberately keys no agent wants, since passthrough
|
||
// forwards everything else.
|
||
//
|
||
// 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);
|
||
// Look-and-feel picks live next to the daemon's state, one tiny file each:
|
||
// they are dais-top's own preferences, not daemon state, and must survive a
|
||
// restart without a config edit.
|
||
const STATE_DIR = path.join(
|
||
process.env.XDG_STATE_HOME ?? path.join(os.homedir(), ".local", "state"), "dais");
|
||
const THEME_FILE = path.join(STATE_DIR, "top-theme");
|
||
const AUTOLOCK_FILE = path.join(STATE_DIR, "top-autolock");
|
||
|
||
function savePref(file, text) {
|
||
fs.mkdir(STATE_DIR, { recursive: true }, (err) => {
|
||
if (!err) fs.writeFile(file, text + "\n", () => {});
|
||
});
|
||
}
|
||
function readPref(file) {
|
||
try { return fs.readFileSync(file, "utf8").trim(); } catch { return null; }
|
||
}
|
||
|
||
let theme = "solarized";
|
||
{
|
||
const t = readPref(THEME_FILE);
|
||
if (t && THEMES[t]) theme = t;
|
||
}
|
||
let C = THEMES[theme];
|
||
|
||
function cycleTheme() {
|
||
theme = THEME_ORDER[(THEME_ORDER.indexOf(theme) + 1) % THEME_ORDER.length];
|
||
C = THEMES[theme];
|
||
note(`theme: ${theme}`);
|
||
savePref(THEME_FILE, theme);
|
||
}
|
||
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, alive, command, path}
|
||
dictateTarget: null, // pane label while a dictate override is pending
|
||
// (airc's mic button aimed one utterance off-slot)
|
||
// Keyboard lock: "off" hot keys · "drop" keys ignored · "pass" keys
|
||
// forwarded to the target pane. See the lock section below.
|
||
lock: "off",
|
||
autoLockMs: 0, // 0 = off; idle auto-lock (K), persisted
|
||
lastKeyAt: Date.now(),
|
||
passEcho: "", // tail of what passthrough forwarded (footer feedback)
|
||
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
|
||
releasing: false, // x pressed: waiting for the slot digit to release
|
||
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)
|
||
};
|
||
{
|
||
const s = Number(readPref(AUTOLOCK_FILE));
|
||
if (Number.isFinite(s) && s > 0) S.autoLockMs = s * 1000;
|
||
}
|
||
|
||
// ---------- 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();
|
||
});
|
||
}
|
||
|
||
// ---------- keyboard lock ----------
|
||
// Two flavors of the same idea: this panel's keys are single-letter toggles,
|
||
// so typing a sentence into it (thinking it was the agent's pane) flips VAD,
|
||
// dry-run and the target slot in one go. "drop" makes the panel inert; "pass"
|
||
// makes it a keystroke bridge to the target pane, which turns the accident
|
||
// into the thing you meant. Auto-lock (K) engages "drop" only: auto-engaging
|
||
// DELIVERY would be a surprise with consequences.
|
||
const AUTOLOCK_STEPS = [0, 15, 30, 60]; // seconds; 0 = off
|
||
|
||
// The escape hatch out of a lock. In "pass" every other key is forwarded, so
|
||
// this cannot be a key an agent might want (not Esc, not Ctrl-C): Ctrl-] is
|
||
// terminal tradition for exactly this, F12 is the layout-independent backup
|
||
// (']' is AltGr+9 on a Finnish layout).
|
||
function isUnlockKey(k) {
|
||
return k === "\x1d" || /^\x1b\[24(;\d+)?~$/.test(k);
|
||
}
|
||
|
||
function lockLabel() {
|
||
return S.lock === "pass"
|
||
? `passthrough → ${describeTarget(S.targets[S.activeSlot])}`
|
||
: "keylock";
|
||
}
|
||
|
||
function setLock(mode) {
|
||
if (mode === "pass") {
|
||
// A focus target means ydotool types into the FOCUSED window — which is
|
||
// this one, so every forwarded key would come straight back in through
|
||
// our own stdin. Refuse, and fall back to the inert lock.
|
||
const t = S.targets[S.activeSlot];
|
||
if (t?.type !== "tmux") {
|
||
S.lock = "drop";
|
||
return note("passthrough needs a tmux target (focus would type into this window) — keylock instead");
|
||
}
|
||
}
|
||
S.lock = mode;
|
||
S.passEcho = "";
|
||
// Engaging needs no note — the badge and the footer both say it, loudly, for
|
||
// as long as it lasts. Leaving does, since nothing else marks the moment.
|
||
if (mode === "off") note("unlocked");
|
||
}
|
||
|
||
function cycleAutoLock() {
|
||
const cur = Math.round(S.autoLockMs / 1000);
|
||
const next = AUTOLOCK_STEPS[(AUTOLOCK_STEPS.indexOf(cur) + 1) % AUTOLOCK_STEPS.length];
|
||
S.autoLockMs = next * 1000;
|
||
savePref(AUTOLOCK_FILE, String(next));
|
||
note(next ? `auto-lock after ${next}s idle` : "auto-lock off");
|
||
}
|
||
|
||
function checkAutoLock() {
|
||
// The accidental-typing case is precisely the one where you did NOT reach
|
||
// for the lock, so a timer has to. Overlays hold it off — locking out of a
|
||
// half-finished pane pick would just be baffling.
|
||
if (S.autoLockMs && S.lock === "off" && !S.help && !S.picker && !S.releasing &&
|
||
Date.now() - S.lastKeyAt > S.autoLockMs) {
|
||
S.lock = "drop";
|
||
note("🔒 auto-locked (idle) · Ctrl-] or F12 unlocks");
|
||
}
|
||
}
|
||
|
||
// Raw stdin bytes -> tokens for the bridge. Printable runs travel as TEXT (the
|
||
// daemon delivers text on stdin, never argv); control bytes and escape
|
||
// sequences must map to a chord the executor whitelists. Anything unmapped is
|
||
// REFUSED rather than typed — a stray escape sequence must not land in the
|
||
// agent's prompt as literal garbage.
|
||
const PASS_KEYS = {
|
||
"\r": "Enter", "\n": "Enter", "\t": "Tab", "\b": "BSpace", "\x7f": "BSpace",
|
||
"\x1b": "Escape",
|
||
"\x1b[A": "Up", "\x1b[B": "Down", "\x1b[C": "Right", "\x1b[D": "Left",
|
||
"\x1bOA": "Up", "\x1bOB": "Down", "\x1bOC": "Right", "\x1bOD": "Left",
|
||
"\x1b[H": "Home", "\x1b[F": "End", "\x1b[1~": "Home", "\x1b[4~": "End",
|
||
"\x1b[5~": "PgUp", "\x1b[6~": "PgDn",
|
||
"\x1b[Z": "S-Tab", // shift-tab: Claude Code cycles modes with it
|
||
};
|
||
|
||
function passToken(s) {
|
||
const named = PASS_KEYS[s];
|
||
if (named) return { key: named };
|
||
if (s.length === 1) {
|
||
const c = s.charCodeAt(0);
|
||
if (c >= 1 && c <= 26) return { key: `C-${String.fromCharCode(96 + c)}` };
|
||
}
|
||
return { unknown: s };
|
||
}
|
||
|
||
function passTokens(chunk) {
|
||
const toks = [];
|
||
let text = "";
|
||
const flush = () => { if (text) { toks.push({ text }); text = ""; } };
|
||
let i = 0;
|
||
while (i < chunk.length) {
|
||
const ch = chunk[i];
|
||
if (ch === "\x1b") {
|
||
const m = /^\x1b(\[[0-9;]*[A-Za-z~]|O[A-Za-z])/.exec(chunk.slice(i));
|
||
if (m) { flush(); toks.push(passToken(m[0])); i += m[0].length; continue; }
|
||
const next = chunk[i + 1];
|
||
if (next && /^[a-z0-9]$/.test(next)) { // Alt-<char>
|
||
flush(); toks.push({ key: `M-${next}` }); i += 2; continue;
|
||
}
|
||
flush(); toks.push({ key: "Escape" }); i += 1; continue;
|
||
}
|
||
const code = ch.charCodeAt(0);
|
||
if (code < 32 || code === 127) { flush(); toks.push(passToken(ch)); i += 1; continue; }
|
||
text += ch;
|
||
i += 1;
|
||
}
|
||
flush();
|
||
return toks;
|
||
}
|
||
|
||
function passChunk(chunk) {
|
||
const t = S.targets[S.activeSlot];
|
||
if (t?.type !== "tmux") { // voice may have moved the slot
|
||
S.lock = "drop";
|
||
return note("passthrough: active target is no longer a tmux pane — keylock instead");
|
||
}
|
||
if (!S.connected) return note("passthrough: not connected");
|
||
for (const tok of passTokens(chunk)) {
|
||
if (tok.unknown) {
|
||
const hex = [...tok.unknown].map((c) => c.charCodeAt(0).toString(16)).join(" ");
|
||
note(`passthrough: ignored 0x${hex}`);
|
||
continue;
|
||
}
|
||
const req = tok.text ? { op: "send", text: tok.text } : { op: "send", keys: [tok.key] };
|
||
request(req, (resp) => { if (!resp?.ok) note(`✗ ${resp?.error ?? "send failed"}`); });
|
||
// Rolling tail of what went out — the target pane is usually off-screen,
|
||
// so this is the only confirmation that the bridge is live.
|
||
S.passEcho = (S.passEcho + (tok.text ?? `⟨${tok.key}⟩`)).slice(-28);
|
||
}
|
||
}
|
||
|
||
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";
|
||
// null is meaningful here (override dropped), so test for presence.
|
||
if ("dictate_target" in p) S.dictateTarget = p.dictate_target;
|
||
}
|
||
} 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);
|
||
}
|
||
|
||
// Fold a target-list response into state. One place because the list is the
|
||
// authority on slots AND on the dictate override — every caller must pick up
|
||
// both, or the header keeps claiming the slot while speech goes elsewhere.
|
||
function applyTargets(tg) {
|
||
if (!tg?.ok) return;
|
||
S.targets = tg.targets ?? {};
|
||
S.activeSlot = tg.active_slot;
|
||
S.dictateTarget = tg.dictate_target ?? null;
|
||
}
|
||
|
||
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;
|
||
S.dictateTarget = st.dictate_target ?? null;
|
||
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) => {
|
||
applyTargets(tg);
|
||
});
|
||
});
|
||
}
|
||
|
||
// ---------- 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;
|
||
}
|
||
|
||
// Visible width of a rendered string — ANSI escapes are zero-width. Used to
|
||
// budget the header, whose right-hand block (ear/armed/live) must never be the
|
||
// part that a long path pushes off the edge.
|
||
function vlen(s) {
|
||
return s.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").length;
|
||
}
|
||
|
||
// ~/code/lh/leanheat-app -> ~/…/leanheat-app when the budget is tight: the last
|
||
// segment names the checkout, the middle is noise. Elides in the middle rather
|
||
// than truncating the tail, which is what carries the meaning here.
|
||
function shortPath(p, max) {
|
||
const s = tilde(p ?? "");
|
||
if (s.length <= max) return s;
|
||
const segs = s.split("/");
|
||
const last = segs.pop() ?? "";
|
||
const mid = `${segs[0] ?? ""}/…/${last}`;
|
||
if (mid.length <= max) return mid;
|
||
return "…/" + last.slice(-Math.max(3, max - 2));
|
||
}
|
||
|
||
// 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++;
|
||
checkAutoLock();
|
||
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];
|
||
// 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}` : "";
|
||
// Lock badge: "drop" is inert so it reads gray; "pass" is DELIVERING every
|
||
// keystroke, which deserves the same loudness as ARMED. Unlocked but armed
|
||
// with an idle timer gets a quiet open-padlock hint.
|
||
const lockBadge = S.lock === "drop" ? ` ${C.bgGray} 🔒 LOCKED ${C.reset}`
|
||
: S.lock === "pass" ? ` ${C.bgMagenta} ⌨ PASS ${C.reset}`
|
||
: S.autoLockMs ? ` ${C.dim}🔓${Math.round(S.autoLockMs / 1000)}s${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}`;
|
||
const headLeft = ` ${title} ${modeBadge()}${mutedBadge}${lockBadge} `;
|
||
const headRight = ` ${right}${aircStr}`;
|
||
lines.push(headLeft +
|
||
targetSegment(activeT, tag, val,
|
||
(out.columns ?? 80) - vlen(headLeft) - vlen(headRight)) +
|
||
headRight);
|
||
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 row = ` ${mark} ${p.pane} ${C.dim}[${p.command}]${C.reset} ${C.dim}${shortPath(p.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, …).
|
||
// The release prompt is sticky (it awaits a digit); notes time out. While
|
||
// locked the key list would be a lie, so the way out takes its place.
|
||
const noteStr = S.releasing
|
||
? ` ${C.yellow}release which slot? ${C.bold}[1-5]${C.reset}${C.yellow} · any other key cancels${C.reset}`
|
||
: Date.now() < S.noteUntil ? ` ${C.yellow}${S.note}${C.reset}`
|
||
: S.lock === "pass" && S.passEcho
|
||
? ` ${C.dim}${S.execution === "dry-run" ? "would send" : "sent"}${C.reset} ${C.cyan}${S.passEcho}${C.reset}`
|
||
: "";
|
||
const keysTxt = S.lock === "off"
|
||
? "[v]ad [r]ec [1-5] [t]arget [a]rm [m]ute [d]ry [e]nter [k]lock [p]ass [?] help [q]uit"
|
||
: `🔒 ${lockLabel()} — Ctrl-] or F12 to leave`;
|
||
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 ?? "?";
|
||
}
|
||
|
||
// The active target, labeled with what its pane is RUNNING: the pane spec
|
||
// first (that is its identity), then the process and cwd from the target-list
|
||
// poll — "target [2] app:claude.0 claude ~/code/lh/leanheat-app". Two slots
|
||
// both running claude are otherwise indistinguishable at a glance.
|
||
//
|
||
// The extras are appended only while the header has room, so a narrow terminal
|
||
// drops the cwd, then the process; the pane spec never goes, and neither does
|
||
// the right-hand ear/armed/live block (the caller's budget reserves it).
|
||
function targetSegment(t, tag, val, budget) {
|
||
if (S.activeSlot == null) return tag("no target", 0);
|
||
// A pending dictate override (airc's mic button) leads the segment: it is
|
||
// where the next UTTERANCE lands. The slot segment stays, because it is still
|
||
// where keys go — passthrough and F11 ignore the override on purpose. Two
|
||
// destinations at once is exactly the thing a header must not hide.
|
||
// (Its width needs no budget arithmetic: `used` below measures the whole
|
||
// segment, so the command/cwd extras give way to it automatically.)
|
||
const aimed = S.dictateTarget
|
||
? `${C.bgOrange} 🎙 ${S.dictateTarget} ${C.reset} ` : "";
|
||
const spec = describeTarget(t);
|
||
let s = aimed + `${tag("target", 0)} ${C.bold}[${S.activeSlot}]${C.reset} ` +
|
||
(t?.alive === false
|
||
? `${C.red}${spec} ✗ gone${C.reset}`
|
||
: `${val}${spec}${C.reset}`);
|
||
let used = vlen(s);
|
||
if (t?.command && budget - used >= t.command.length + 1) {
|
||
s += ` ${C.cyan}${t.command}${C.reset}`;
|
||
used += t.command.length + 1;
|
||
}
|
||
if (t?.path && budget - used >= 12) {
|
||
s += ` ${C.dim}${shortPath(t.path, budget - used - 1)}${C.reset}`;
|
||
}
|
||
return s;
|
||
}
|
||
|
||
// 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("x", "release a slot (then 1-5) — frees the digit for reuse"));
|
||
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("k", "keylock: ignore every key (accidental typing goes nowhere)"));
|
||
L.push(key("p", "passthrough lock: forward every key to the target pane"));
|
||
L.push(key("K", `auto-lock after idle: ${AUTOLOCK_STEPS.map((s) => s || "off").join(" → ")}` +
|
||
` (now ${S.autoLockMs ? Math.round(S.autoLockMs / 1000) + "s" : "off"})`));
|
||
L.push(key("C-]", "leave any lock — F12 does the same (locks when unlocked)"));
|
||
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) {
|
||
S.lastKeyAt = Date.now();
|
||
// The lock gates come FIRST — ahead of Ctrl-C. While locked this panel must
|
||
// swallow (or forward) everything, and quitting by accident is exactly the
|
||
// class of accident the lock exists to prevent. Unlocked, the same gesture
|
||
// engages the keylock, so one key is enough to remember.
|
||
if (isUnlockKey(key)) return setLock(S.lock === "off" ? "drop" : "off");
|
||
if (S.lock === "pass") return passChunk(key);
|
||
// A swallowed key still gets an acknowledgement: silence would read as a
|
||
// hung panel, and the footer already carries the way out.
|
||
if (S.lock === "drop") return note("🔒 key ignored");
|
||
if (key === "\x03") return shutdown();
|
||
if (S.picker) return onPickerKey(key);
|
||
if (S.help) return onHelpKey(key);
|
||
if (S.releasing) return onReleaseKey(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();
|
||
// Release takes a digit rather than acting on the picker's highlighted row:
|
||
// a slot whose pane is GONE (the main reason to release) has no row there.
|
||
else if (key === "x") S.releasing = true;
|
||
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 === "k") setLock("drop");
|
||
else if (key === "p") setLock("pass");
|
||
else if (key === "K") cycleAutoLock();
|
||
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 onReleaseKey(key) {
|
||
S.releasing = false;
|
||
if (!/^[1-5]$/.test(key)) return note("release cancelled");
|
||
const slot = Number(key);
|
||
request({ op: "target", action: "release", slot }, ack(`slot ${slot} released`));
|
||
request({ op: "target", action: "list" }, (tg) => {
|
||
applyTargets(tg);
|
||
});
|
||
}
|
||
|
||
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) => {
|
||
applyTargets(tg);
|
||
});
|
||
} 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;
|
||
S.dictateTarget = st.dictate_target ?? null;
|
||
}
|
||
});
|
||
};
|
||
}
|
||
|
||
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, F-keys): wait briefly for a
|
||
// follow-up, then hand on whatever arrived REJOINED — a sequence split
|
||
// across chunks used to be dropped, which passthrough (and F12) can't
|
||
// afford.
|
||
if (escTimer) {
|
||
clearTimeout(escTimer);
|
||
escTimer = null;
|
||
onKey("\x1b" + k);
|
||
return;
|
||
}
|
||
if (k === "\x1b") {
|
||
escTimer = setTimeout(() => { escTimer = null; onKey("\x1b"); }, 120);
|
||
return;
|
||
}
|
||
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) => {
|
||
applyTargets(tg);
|
||
});
|
||
}, 1500);
|
||
// airc is independent of the daemon; a slow poll keeps the badge honest.
|
||
pollAirc();
|
||
setInterval(pollAirc, 5000);
|
||
}
|
||
|
||
main();
|