feat: configurable resizable persistent macOS HUD

This commit is contained in:
Andrew Emelyaneko
2026-10-31 23:06:05 +03:00
parent e99819eb63
commit b6e51281de
3 changed files with 313 additions and 38 deletions
+131
View File
@@ -1,3 +1,17 @@
export interface MacOSHudStyle {
bg: string
fg: string
accent: string
title: string
width: number
height: number
bigFont: number
smallFont: number
resizable: boolean
minWidth: number
minHeight: number
}
export interface TokenSpeedConfig {
host: string
port: number
@@ -8,13 +22,127 @@ export interface TokenSpeedConfig {
macosNotifications: boolean
macosNotifyMinIntervalMs: number
macosPopupHtml: boolean
macosHudStyle: MacOSHudStyle
}
export type { MacOSHudStyle as MacOSHudStyleType }
function num(value: string | undefined, fallback: number): number {
const n = Number(value)
return Number.isFinite(n) && n > 0 ? n : fallback
}
function bool(value: string | undefined, fallback: boolean): boolean {
if (value === undefined) return fallback
return value === "1" || value.toLowerCase() === "true"
}
function hex(value: string | undefined, fallback: string): string {
if (typeof value !== "string") return fallback
const v = value.trim()
if (/^#[0-9a-fA-F]{3,8}$/.test(v)) return v
if (/^[0-9a-fA-F]{3,8}$/.test(v)) return `#${v}`
return fallback
}
const DEFAULT_STYLE: MacOSHudStyle = {
bg: "#0b1022",
fg: "#e8f3ff",
accent: "#22c55e",
title: "Token Speed",
width: 360,
height: 180,
bigFont: 30,
smallFont: 12,
resizable: true,
minWidth: 260,
minHeight: 130,
}
function parseStyle(raw: string | undefined): MacOSHudStyle {
let base: MacOSHudStyle = DEFAULT_STYLE
if (raw && raw.trim()) {
try {
const parsed = JSON.parse(raw)
base = {
bg: hex(typeof parsed.bg === "string" ? parsed.bg : undefined, base.bg),
fg: hex(typeof parsed.fg === "string" ? parsed.fg : undefined, base.fg),
accent: hex(
typeof parsed.accent === "string" ? parsed.accent : undefined,
base.accent,
),
title:
typeof parsed.title === "string" && parsed.title.trim()
? parsed.title
: base.title,
width: num(
typeof parsed.width === "number" ? String(parsed.width) : undefined,
base.width,
),
height: num(
typeof parsed.height === "number" ? String(parsed.height) : undefined,
base.height,
),
bigFont: num(
typeof parsed.bigFont === "number"
? String(parsed.bigFont)
: undefined,
base.bigFont,
),
smallFont: num(
typeof parsed.smallFont === "number"
? String(parsed.smallFont)
: undefined,
base.smallFont,
),
resizable:
typeof parsed.resizable === "boolean"
? parsed.resizable
: base.resizable,
minWidth: num(
typeof parsed.minWidth === "number"
? String(parsed.minWidth)
: undefined,
base.minWidth,
),
minHeight: num(
typeof parsed.minHeight === "number"
? String(parsed.minHeight)
: undefined,
base.minHeight,
),
}
} catch {
base = DEFAULT_STYLE
}
}
const env = process.env
return {
bg: hex(env.PLAGIN_TOKENS_MACOS_HUD_BG, base.bg),
fg: hex(env.PLAGIN_TOKENS_MACOS_HUD_FG, base.fg),
accent: hex(env.PLAGIN_TOKENS_MACOS_HUD_ACCENT, base.accent),
title:
typeof env.PLAGIN_TOKENS_MACOS_HUD_TITLE === "string" &&
env.PLAGIN_TOKENS_MACOS_HUD_TITLE.trim()
? env.PLAGIN_TOKENS_MACOS_HUD_TITLE
: base.title,
width: num(env.PLAGIN_TOKENS_MACOS_HUD_WIDTH, base.width),
height: num(env.PLAGIN_TOKENS_MACOS_HUD_HEIGHT, base.height),
bigFont: num(env.PLAGIN_TOKENS_MACOS_HUD_BIG_FONT, base.bigFont),
smallFont: num(env.PLAGIN_TOKENS_MACOS_HUD_SMALL_FONT, base.smallFont),
resizable: bool(env.PLAGIN_TOKENS_MACOS_HUD_RESIZABLE, base.resizable),
minWidth: num(
env.PLAGIN_TOKENS_MACOS_HUD_MIN_WIDTH,
base.minWidth,
),
minHeight: num(
env.PLAGIN_TOKENS_MACOS_HUD_MIN_HEIGHT,
base.minHeight,
),
}
}
export function loadConfig(): TokenSpeedConfig {
const host = process.env.PLAGIN_TOKENS_HOST || "127.0.0.1"
const port = num(process.env.PLAGIN_TOKENS_PORT, 7878)
@@ -34,5 +162,8 @@ export function loadConfig(): TokenSpeedConfig {
3000,
),
macosPopupHtml: true,
macosHudStyle: parseStyle(process.env.PLAGIN_TOKENS_MACOS_HUD_STYLE),
}
}
export { DEFAULT_STYLE as DEFAULT_MACOS_HUD_STYLE }
+1
View File
@@ -84,6 +84,7 @@ export const TokenSpeedPlugin: Plugin = async ({ client }) => {
hud: config.macosHud,
notifications: config.macosNotifications,
notifyMinIntervalMs: config.macosNotifyMinIntervalMs,
hudStyle: config.macosHudStyle,
})
await client.app
.log({
+181 -38
View File
@@ -6,12 +6,28 @@ import { writeFileSync, unlinkSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import type { SpeedSnapshot } from "./types"
import type { MacOSHudStyle } from "./config"
const DEFAULT_STYLE: MacOSHudStyle = {
bg: "#0b1022",
fg: "#e8f3ff",
accent: "#22c55e",
title: "Token Speed",
width: 360,
height: 180,
bigFont: 30,
smallFont: 12,
resizable: true,
minWidth: 260,
minHeight: 130,
}
export interface MacOSPopupOptions {
baseUrl: string
hud?: boolean
notifications?: boolean
notifyMinIntervalMs?: number
hudStyle?: MacOSHudStyle
now?: () => number
}
@@ -40,7 +56,16 @@ function popupRegistry(): Map<string, SharedPopup> {
return reg
}
function buildHudScript(baseUrl: string, parentPid: number): string {
function normalizeStyle(style?: MacOSHudStyle): MacOSHudStyle {
return { ...DEFAULT_STYLE, ...(style ?? {}) }
}
export function buildHudScript(
baseUrl: string,
parentPid: number,
hudStyle?: MacOSHudStyle,
): string {
const style = normalizeStyle(hudStyle)
return [
'ObjC.import("Foundation");',
'ObjC.import("AppKit");',
@@ -48,68 +73,184 @@ function buildHudScript(baseUrl: string, parentPid: number): string {
' name: "TokenSpeedWindowDelegate",',
' superclass: "NSObject",',
' methods: {',
' "windowDidMove:": {',
' types: ["v", ["@"]],',
' implementation: function(note) {',
' var window = note.object ? note.object : null;',
" saveFrame(window);",
" },",
" },",
' "windowDidEndLiveResize:": {',
' types: ["v", ["@"]],',
' implementation: function(note) {',
' var window = note.object ? note.object : null;',
" saveFrame(window);",
" },",
" },",
' "windowWillClose:": {',
' types: ["v", ["@"]],',
' implementation: function(note) {',
' $.NSApp.terminate(null);',
' },',
' },',
' },',
'});',
' var window = note.object ? note.object : null;',
" saveFrame(window);",
" $.NSApp.terminate(null);",
" },",
" },",
" },",
"});",
'var osa = Application.currentApplication();',
'osa.includeStandardAdditions = true;',
"var inspectParent = function(pid) {",
' try { osa.doShellScript("ps -p " + pid + " >/dev/null 2>&1"); return true } catch (e) { return false }',
"};",
'var framePath = $.NSHomeDirectory().stringByAppendingPathComponent(".plagin-tokens-hud-frame.json");',
'function decodedStyle(hex) {',
' var clean = String(hex || "").replace("#", "");',
' if (clean.length === 3) {',
" clean = clean.charAt(0) + clean.charAt(0) +",
" clean.charAt(1) + clean.charAt(1) +",
" clean.charAt(2) + clean.charAt(2);",
" }",
' if (clean.length < 6) clean = "0b1022";',
" var red = parseInt(clean.slice(0, 2), 16) / 255;",
" var green = parseInt(clean.slice(2, 4), 16) / 255;",
" var blue = parseInt(clean.slice(4, 6), 16) / 255;",
" var alpha = 1;",
" if (clean.length >= 8) alpha = parseInt(clean.slice(6, 8), 16) / 255;",
" if (!Number.isFinite(alpha)) alpha = 1;",
' return $.NSColor.colorWithCalibratedRedGreenBlueAlpha(red, green, blue, alpha);',
"}",
'function readFrameFile() {',
' var data = $.NSData.dataWithContentsOfFile(framePath);',
" var value = null;",
" if (data) {",
' try {',
' var raw = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding);',
' value = typeof raw.js !== "undefined" ? JSON.parse(raw.js) : JSON.parse(String(raw));',
' } catch (e) { value = null }',
" }",
" return value;",
"}",
'function savedFrameValue() {',
' return readFrameFile();',
"}",
'function validFrame(frame) {',
" if (!frame) return false;",
" return Number.isFinite(Number(frame.x)) &&",
" Number.isFinite(Number(frame.y)) &&",
" Number.isFinite(Number(frame.w)) &&",
" Number.isFinite(Number(frame.h)) &&",
" Number(frame.w) > 10 && Number(frame.h) > 10;",
"}",
'function saveFrame(window) {',
" if (!window || !window.frame) return;",
" var frame = window.frame;",
" var object = {",
" x: Number(frame.origin.x),",
" y: Number(frame.origin.y),",
" w: Number(frame.size.width),",
" h: Number(frame.size.height),",
" };",
" if (!validFrame(object)) return;",
' $.NSString.stringWithUTF8String(JSON.stringify(object)).writeToFileAtomicallyEncodingError(',
" framePath, true, $.NSUTF8StringEncoding, null,",
" );",
"}",
"var app = $.NSApplication.sharedApplication;",
"app.setActivationPolicy(1);",
"var base = " + JSON.stringify(baseUrl) + ";",
"var parentPid = " + parentPid + ";",
"var style = " + JSON.stringify(style) + ";",
"var width = Number(style.width) || 360;",
"var height = Number(style.height) || 180;",
"var defaultRect = $.NSMakeRect(0, 0, width, height);",
"var saved = savedFrameValue();",
"if (validFrame(saved)) {",
' defaultRect = $.NSMakeRect(Number(saved.x), Number(saved.y), Number(saved.w), Number(saved.h));',
"}",
"var screen = $.NSScreen.mainScreen.visibleFrame;",
"var w = 360, h = 180;",
"var rect = $.NSMakeRect(screen.size.width - w - 24, screen.size.height - h - 40, w, h);",
"var style = $.NSTitledWindowMask | $.NSClosableWindowMask | $.NSMiniaturizableWindowMask;",
"var window = $.NSWindow.alloc.initWithContentRectStyleMaskBackingDefer(rect, style, $.NSBackingStoreBuffered, false);",
"var fallbackRect = $.NSMakeRect(screen.size.width - width - 24, screen.size.height - height - 40, width, height);",
"var startRect = validFrame(saved) ? defaultRect : fallbackRect;",
'var styleMask = $.NSTitledWindowMask | $.NSClosableWindowMask | $.NSMiniaturizableWindowMask;',
"if (style.resizable) styleMask |= $.NSResizableWindowMask;",
"var window = $.NSWindow.alloc.initWithContentRectStyleMaskBackingDefer(",
" startRect, styleMask, $.NSBackingStoreBuffered, false,",
");",
"window.level = $.NSFloatingWindowLevel;",
'window.title = "Token Speed";',
"window.title = style.title;",
"window.collectionBehavior = (1 << 0) | (1 << 8) | (1 << 4);",
"window.minSize = $.NSMakeSize(Math.max(120, Number(style.minWidth) || 220), Math.max(90, Number(style.minHeight) || 110));",
"if (validFrame(saved)) {",
" window.setFrameDisplay(startRect, true);",
"}",
"window.opaque = decodedStyle(style.bg).alphaComponent < 1 ? false : true;",
"window.backgroundColor = decodedStyle(style.bg);",
"window.titlebarAppearsTransparent = false;",
'var delegate = $.TokenSpeedWindowDelegate.alloc.init;',
"window.delegate = delegate;",
'var big = $.NSTextField.alloc.initWithFrame($.NSMakeRect(14, 122, w - 28, 44));',
"big.editable = false; big.bordered = false; big.drawsBackground = false;",
"big.font = $.NSFont.boldSystemFontOfSize(30); big.alignment = 1;",
'var small = $.NSTextField.alloc.initWithFrame($.NSMakeRect(14, 14, w - 28, 108));',
'var big = $.NSTextField.alloc.initWithFrame($.NSMakeRect(14, height - 54, width - 28, 44));',
"big.editable = false; big.bordered = false; big.drawsBackground = false; big.alignment = 1;",
'big.font = $.NSFont.boldSystemFontOfSize(Number(style.bigFont) || 30);',
"big.textColor = decodedStyle(style.accent);",
'var small = $.NSTextField.alloc.initWithFrame(',
" $.NSMakeRect(14, 14, Math.max(120, width - 28), Math.max(40, height - 70)),",
");",
"small.editable = false; small.bordered = false; small.drawsBackground = false;",
"small.font = $.NSFont.systemFontOfSize(12); small.alignment = 0;",
'small.font = $.NSFont.systemFontOfSize(Number(style.smallFont) || 12);',
"small.textColor = decodedStyle(style.fg);",
"small.lineBreakMode = 0;",
"window.contentView.addSubview(big); window.contentView.addSubview(small);",
"window.contentView.addSubview(big);",
"window.contentView.addSubview(small);",
"window.makeKeyAndOrderFront(null);",
"app.activateIgnoringOtherApps(true);",
"var base = " + JSON.stringify(baseUrl) + ";",
"function text(snap) {",
'function text(snap) {',
' big.stringValue = ((snap.tokensPerSecond || 0).toFixed(1)) + " tok/s";',
' small.stringValue = "state: " + (snap.state || "idle") + "\\n" +',
' "tokens: " + (snap.outputTokens || 0) + " elapsed: " + Math.round((snap.elapsedMs || 0) / 1000) + "s\\n" +',
' (snap.model || "");',
"}",
'text({ tokensPerSecond: 0, outputTokens: 0, elapsedMs: 0, state: "idle", model: "" });',
"var closed = false;",
"function layout() {",
" var size = window.frame.size;",
" var frameWidth = Number(size.width) || width;",
" var frameHeight = Number(size.height) || height;",
' big.frame = $.NSMakeRect(14, Math.max(8, frameHeight - 54), Math.max(10, frameWidth - 28), 44);',
' small.frame = $.NSMakeRect(14, 14, Math.max(10, frameWidth - 28), Math.max(24, frameHeight - 74));',
"}",
"layout();",
"while (true) {",
' var winVisible = (window.isVisible === true);',
" if (!winVisible && window.miniaturized) {",
" $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.5));",
" continue;",
' var alive = inspectParent(parentPid);',
" if (!alive) {",
" saveFrame(window);",
" window.close();",
" break;",
" }",
" if (window.miniaturized) {",
" $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.5));",
' var mini = (window.miniaturized === true);',
" if (mini) {",
" layout();",
" saveFrame(window);",
' $.NSRunLoop.currentRunLoop.runUntilDate(',
" $.NSDate.dateWithTimeIntervalSinceNow(0.25),",
" );",
" continue;",
" }",
" layout();",
" saveFrame(window);",
" var snap = null;",
" try {",
' var url = $.NSURL.URLWithString(base + "/speed");',
" var data = $.NSData.dataWithContentsOfURL(url);",
" if (data) {",
' if (data) {',
" var str = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding);",
' if (str && typeof str.js !== "undefined") snap = JSON.parse(str.js);',
" else if (str) snap = JSON.parse(String(str));",
" }",
" } catch (e) {",
' small.stringValue = "Server unavailable";',
" }",
" if (snap) text(snap);",
" $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.5));",
' $.NSRunLoop.currentRunLoop.runUntilDate(',
' $.NSDate.dateWithTimeIntervalSinceNow(0.25),',
" );",
"}",
].join("\n")
}
@@ -120,10 +261,11 @@ export class MacOSPopup {
private readonly notificationsEnabled: boolean
private readonly notifyMinIntervalMs: number
private readonly baseUrl: string
private readonly hudStyle: MacOSHudStyle
private readonly clock: () => number
private readonly spawnFn: (...args: any[]) => any
private readonly writeFileFn: (path: string, data: string) => void
private readonly unlinkFn: (path: string) => void
private readonly unlinkFn: (path: string, ...args: any[]) => void
private child: ChildProcess | null = null
private scriptPath: string | null = null
private opened = false
@@ -141,6 +283,7 @@ export class MacOSPopup {
this.notificationsEnabled = options.notifications ?? true
this.notifyMinIntervalMs = options.notifyMinIntervalMs ?? 3000
this.baseUrl = options.baseUrl
this.hudStyle = normalizeStyle(options.hudStyle)
this.clock = options.now ?? deps.now ?? Date.now
this.spawnFn = deps.spawnFn ?? nodeSpawn
this.writeFileFn = deps.writeFileFn ?? writeFileSync
@@ -179,7 +322,10 @@ export class MacOSPopup {
const path = join(tmpdir(), `plagin-tokens-hud-${process.pid}-${this.clock()}.js`)
this.scriptPath = path
try {
this.writeFileFn(path, buildHudScript(this.baseUrl, process.pid))
this.writeFileFn(
path,
buildHudScript(this.baseUrl, process.pid, this.hudStyle),
)
} catch {
this.opened = false
this.scriptPath = null
@@ -189,7 +335,8 @@ export class MacOSPopup {
stdio: "ignore",
detached: true,
}) as ChildProcess
if (this.child && typeof this.child.unref === "function") this.child.unref()
if (this.child && typeof this.child.unref === "function")
this.child.unref()
if (this.child && typeof this.child.on === "function") {
this.child.on("exit", () => {
this.opened = false
@@ -199,7 +346,7 @@ export class MacOSPopup {
try {
this.unlinkFn(this.scriptPath)
} catch {
// ignore
// keep closure strict but errors ignored
}
this.scriptPath = null
}
@@ -219,13 +366,9 @@ export class MacOSPopup {
const seconds = (snapshot.elapsedMs / 1000).toFixed(1)
const model = snapshot.model ?? "opencode"
const message = `${snapshot.tokensPerSecond} tok/s \u00b7 ${snapshot.outputTokens} tokens \u00b7 ${seconds}s`
const script = `display notification "${escapeAppleScript(
message,
)}" with title "${escapeAppleScript("Token Speed")}" subtitle "${escapeAppleScript(model)}"`
const script = `display notification "${escapeAppleScript(message)}" with title "${escapeAppleScript("Token Speed")}" subtitle "${escapeAppleScript(model)}"`
try {
const child = this.spawnFn("osascript", ["-e", script], {
stdio: "ignore",
})
const child = this.spawnFn("osascript", ["-e", script], { stdio: "ignore" })
if (child && typeof child.on === "function") child.on("error", () => {})
} catch {
// ignore spawn failures