Files
dais/tools/dais-top
T
Tommi Kyntola 48db46eca1 dais-top: keyboard lock, passthrough, target process/cwd labels
Three improvements to the cockpit, all about typing into the right window.

Target labels: `target list` now reports what is actually running in each
tmux target — pane_current_command and pane_current_path — so the header
reads `app:claude.0 claude ~/dais` instead of a bare pane spec. One
list-panes -a call (daemon/pane-details) serves every slot and doubles as
the liveness answer, which is cheaper than the per-slot pane-exists? calls
it replaces (those stay as the tmux-down fallback). Rows are indexed under
both the window-NAME and window-INDEX spec forms, because a stored target
may use either. A :focus target can't be introspected (no kdotool here), so
it stays bare. dais-top elides the cwd middle-first and then drops it, and
the command after it, as the header runs out of columns — the ear/armed/live
block is never the part pushed off screen.

Keyboard lock: dais-top is a single-key control surface, so typing into it
by mistake flips real state. `k` ignores every key (each swallowed one is
acknowledged in the footer); Ctrl-] or F12 always leaves a lock, and while
locked any other key just shows the way out. `K` cycles an idle auto-lock
(off -> 15 -> 30 -> 60s, persisted next to the theme file) — off by default,
and it never fires while an overlay is open.

Passthrough: `p` forwards keys to the active target instead of dropping
them, so the window you typed into by accident behaves like the pane you
meant. Printable runs go as text, the rest as chords (Enter, Tab, S-Tab,
arrows, C-<letter>, M-<char>). It refuses a :focus target and falls back to
keylock, re-checking per chunk since voice can move the active slot
mid-pass: ydotool types into whatever has focus, which during passthrough is
dais-top itself — every key would re-enter its own stdin.

New `send` op carries it: raw delivery to the active target, router
bypassed, exactly one of text or keys, chords still executor-validated so an
unknown one is refused rather than typed. Honors dry-run like any other
delivery. Deliberately NOT recorded — an event line per keystroke would turn
events/*.jsonl into a keylogger transcript. Also exposed as
`dais-ctl send [--keys]`, with zsh completion.

executor: the bridge needs unbracketed paste (a single keystroke must look
like typing, not a paste per character), so tmux-type-plan takes a
bracketed? flag; dictation stays bracketed as one deliberate paste, and text
still travels on stdin either way. And a latent bug it turned up: send-keys
"S-Tab" exits 0 but delivers a PLAIN Tab — shift-tab is its own tmux key
name, BTab. That silently broke shift-tab, which is how Claude Code cycles
permission modes.

ai/ records the tmux traps (BTab, per-pane info needs list-panes -a, the
bracketing, the focus feedback loop); tools/README.md documents the keys.
2026-08-17 12:59:04 +03:00

1092 lines
46 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
// 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}
// 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";
}
} 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;
}
// 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);
const spec = describeTarget(t);
let s = `${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) => {
if (tg?.ok) { S.targets = tg.targets ?? {}; S.activeSlot = tg.active_slot; }
});
}
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, 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) => {
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();