repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/lib/focus.ts
RawFile outline
/**
* Terminal focus detection via DECSET ?1004.
*
* Singleton with ref-counting. Multiple consumers call attach()/detach()
* safely — only the last detach disables focus reporting.
*
* Supported: iTerm2, Ghostty, Alacritty, Kitty, WezTerm, xterm,
* VS Code terminal, Warp. tmux needs `set -g focus-events on`.
*
* Based on focus reporting from tmustier/pi-extensions (session-recap).
* MIT License — https://github.com/tmustier/pi-extensions
*/
const FOCUS_ENABLE = "\x1b[?1004h";
const FOCUS_DISABLE = "\x1b[?1004l";
const FOCUS_IN_SEQ = "\x1b[I";
const FOCUS_OUT_SEQ = "\x1b[O";
export type FocusListener = (focused: boolean) => void;
let refs = 0;
let focused = true;
let listener: ((chunk: Buffer) => void) | undefined;
const listeners = new Set<FocusListener>();
const notify = (next: boolean) => {
if (next === focused) return;
focused = next;
for (const fn of listeners) {
try { fn(focused); } catch { /* best-effort */ }
}
};
/** Current focus state. */
export function isFocused(): boolean {
return focused;
}
/** Register for focus change events. */
export function onFocus(fn: FocusListener): void {
listeners.add(fn);
}
/** Unregister. */
export function offFocus(fn: FocusListener): void {
listeners.delete(fn);
}
/** Enable focus reporting (ref-counted — call detach() when done). */
export function attach(): void {
if (!process.stdout.isTTY || !process.stdin.isTTY) return;
refs++;
if (refs > 1) return; // already active
try {
process.stdout.write(FOCUS_ENABLE);
} catch {
return;
}
const MAX_SEQ = Math.max(FOCUS_IN_SEQ.length, FOCUS_OUT_SEQ.length);
let buf = "";
const handler = (chunk: Buffer) => {
try {
buf += chunk.toString("binary");
let i = 0;
while (i + MAX_SEQ <= buf.length) {
if (buf.startsWith(FOCUS_IN_SEQ, i)) {
notify(true);
i += FOCUS_IN_SEQ.length;
} else if (buf.startsWith(FOCUS_OUT_SEQ, i)) {
notify(false);
i += FOCUS_OUT_SEQ.length;
} else {
i++;
}
}
buf = buf.slice(i);
if (buf.length > 64) buf = buf.slice(-(MAX_SEQ - 1));
} catch { /* best-effort */ }
};
process.stdin.on("data", handler);
listener = handler;
}
/** Disable focus reporting (ref-counted — only last caller actually disables). */
export function detach(): void {
if (refs <= 0) return;
refs--;
if (refs > 0) return;
if (listener) {
try { process.stdin.off("data", listener); } catch { /* noop */ }
listener = undefined;
}
try { process.stdout.write(FOCUS_DISABLE); } catch { /* noop */ }
}