feat: add macOS floating HUD popup for token metrics
This commit is contained in:
@@ -4,6 +4,10 @@ export interface TokenSpeedConfig {
|
||||
windowMs: number
|
||||
idleTimeoutMs: number
|
||||
overlayBaseUrl: string
|
||||
macosHud: boolean
|
||||
macosNotifications: boolean
|
||||
macosNotifyMinIntervalMs: number
|
||||
macosPopupHtml: boolean
|
||||
}
|
||||
|
||||
function num(value: string | undefined, fallback: number): number {
|
||||
@@ -22,5 +26,13 @@ export function loadConfig(): TokenSpeedConfig {
|
||||
windowMs: num(process.env.PLAGIN_TOKENS_WINDOW_MS, 4000),
|
||||
idleTimeoutMs: num(process.env.PLAGIN_TOKENS_IDLE_MS, 4000),
|
||||
overlayBaseUrl,
|
||||
macosHud: (process.env.PLAGIN_TOKENS_MACOS_HUD ?? "1") === "1",
|
||||
macosNotifications:
|
||||
(process.env.PLAGIN_TOKENS_MACOS_NOTIFICATIONS ?? "1") === "1",
|
||||
macosNotifyMinIntervalMs: num(
|
||||
process.env.PLAGIN_TOKENS_MACOS_NOTIFY_MIN_MS,
|
||||
3000,
|
||||
),
|
||||
macosPopupHtml: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { loadConfig } from "./config"
|
||||
import { routeEvent } from "./events"
|
||||
import { startServer, type SpeedServer } from "./server"
|
||||
import { Tracker } from "./tracker"
|
||||
import { MacOSPopup } from "./popup"
|
||||
import type { SpeedSnapshot, SessionStats } from "./types"
|
||||
|
||||
interface SharedServer {
|
||||
@@ -71,12 +72,19 @@ export const TokenSpeedPlugin: Plugin = async ({ client }) => {
|
||||
})
|
||||
|
||||
let server: SpeedServer | null = null
|
||||
let popup: MacOSPopup | null = null
|
||||
try {
|
||||
server = acquireServer(config.host, config.port, () => tracker.snapshot(), {
|
||||
getAllSessionStats: () => tracker.getAllSessionStats(),
|
||||
getSessionStats: (sessionID) => tracker.getSessionStats(sessionID),
|
||||
getCurrentSessionStats: () => tracker.getCurrentSessionStats(),
|
||||
})
|
||||
popup = new MacOSPopup({
|
||||
baseUrl: server.url,
|
||||
hud: config.macosHud,
|
||||
notifications: config.macosNotifications,
|
||||
notifyMinIntervalMs: config.macosNotifyMinIntervalMs,
|
||||
})
|
||||
await client.app
|
||||
.log({
|
||||
body: {
|
||||
@@ -98,9 +106,13 @@ export const TokenSpeedPlugin: Plugin = async ({ client }) => {
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
const unsubscribe = server
|
||||
? tracker.onChange((snapshot) => server?.publish(snapshot))
|
||||
: () => {}
|
||||
const onSnapshot = (snapshot: SpeedSnapshot) => {
|
||||
server?.publish(snapshot)
|
||||
popup?.update(snapshot)
|
||||
}
|
||||
const unsubscribe =
|
||||
server || popup ? tracker.onChange(onSnapshot) : () => {}
|
||||
if (popup) popup.start(tracker.snapshot())
|
||||
const ticker = setInterval(() => tracker.refresh(), 1000)
|
||||
|
||||
return {
|
||||
@@ -110,6 +122,7 @@ export const TokenSpeedPlugin: Plugin = async ({ client }) => {
|
||||
dispose: async () => {
|
||||
clearInterval(ticker)
|
||||
unsubscribe()
|
||||
popup?.dispose()
|
||||
releaseServer(config.host, config.port)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import {
|
||||
spawn as nodeSpawn,
|
||||
type ChildProcess,
|
||||
} from "node:child_process"
|
||||
import { writeFileSync, unlinkSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import type { SpeedSnapshot } from "./types"
|
||||
|
||||
export interface MacOSPopupOptions {
|
||||
baseUrl: string
|
||||
hud?: boolean
|
||||
notifications?: boolean
|
||||
notifyMinIntervalMs?: number
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export interface MacOSPopupDeps {
|
||||
platform?: NodeJS.Platform
|
||||
spawnFn?: (...args: any[]) => any
|
||||
writeFileFn?: (path: string, data: string) => void
|
||||
unlinkFn?: (path: string) => void
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
function buildHudScript(baseUrl: string): string {
|
||||
return [
|
||||
'ObjC.import("Foundation");',
|
||||
'ObjC.import("AppKit");',
|
||||
"var app = $.NSApplication.sharedApplication;",
|
||||
"app.setActivationPolicy(1);",
|
||||
"var screen = $.NSScreen.mainScreen.visibleFrame;",
|
||||
"var w = 340, h = 160;",
|
||||
"var rect = $.NSMakeRect(screen.size.width - w - 24, screen.size.height - h - 40, w, h);",
|
||||
"var style = $.NSTitledWindowMask;",
|
||||
"var window = $.NSWindow.alloc.initWithContentRectStyleMaskBackingDefer(rect, style, $.NSBackingStoreBuffered, false);",
|
||||
"window.level = $.NSFloatingWindowLevel;",
|
||||
'window.title = "Token Speed";',
|
||||
"window.collectionBehavior = (1 << 0) | (1 << 8);",
|
||||
'var big = $.NSTextField.alloc.initWithFrame($.NSMakeRect(14, 92, 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, 12, w - 28, 78));',
|
||||
"small.editable = false; small.bordered = false; small.drawsBackground = false;",
|
||||
"small.font = $.NSFont.systemFontOfSize(12); small.alignment = 0;",
|
||||
"small.lineBreakMode = 0;",
|
||||
'window.contentView.addSubview(big); window.contentView.addSubview(small);',
|
||||
"window.makeKeyAndOrderFront(null);",
|
||||
"app.activateIgnoringOtherApps(true);",
|
||||
"var base = " + JSON.stringify(baseUrl) + ";",
|
||||
"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: "" });',
|
||||
"while (true) {",
|
||||
" var snap = null;",
|
||||
" try {",
|
||||
' var url = $.NSURL.URLWithString(base + "/speed");',
|
||||
" var data = $.NSData.dataWithContentsOfURL(url);",
|
||||
" if (data) {",
|
||||
" var str = $.NSString.alloc.initWithData_encoding(data, $.NSUTF8StringEncoding);",
|
||||
" if (str && str.js) snap = JSON.parse(str.js);",
|
||||
" }",
|
||||
" } catch (e) {",
|
||||
' small.stringValue = "Server unavailable";',
|
||||
" }",
|
||||
" if (snap) text(snap);",
|
||||
" $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.5));",
|
||||
"}",
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
export class MacOSPopup {
|
||||
private readonly isDarwin: boolean
|
||||
private readonly hudEnabled: boolean
|
||||
private readonly notificationsEnabled: boolean
|
||||
private readonly notifyMinIntervalMs: number
|
||||
private readonly baseUrl: string
|
||||
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 child: ChildProcess | null = null
|
||||
private scriptPath: string | null = null
|
||||
private opened = false
|
||||
private disposed = false
|
||||
private reopenAttempts = 0
|
||||
private timers = new Set<ReturnType<typeof setTimeout>>()
|
||||
private previousState: string | null = null
|
||||
private lastNotifyAt = 0
|
||||
|
||||
constructor(options: MacOSPopupOptions, deps: MacOSPopupDeps = {}) {
|
||||
this.isDarwin = (deps.platform ?? process.platform) === "darwin"
|
||||
this.hudEnabled = options.hud ?? true
|
||||
this.notificationsEnabled = options.notifications ?? true
|
||||
this.notifyMinIntervalMs = options.notifyMinIntervalMs ?? 3000
|
||||
this.baseUrl = options.baseUrl
|
||||
this.clock = options.now ?? deps.now ?? Date.now
|
||||
this.spawnFn = deps.spawnFn ?? nodeSpawn
|
||||
this.writeFileFn = deps.writeFileFn ?? writeFileSync
|
||||
this.unlinkFn = deps.unlinkFn ?? unlinkSync
|
||||
}
|
||||
|
||||
start(snapshot?: SpeedSnapshot): void {
|
||||
if (!this.isDarwin || this.disposed) return
|
||||
if (this.hudEnabled) this.openHud()
|
||||
if (snapshot) this.update(snapshot)
|
||||
}
|
||||
|
||||
update(snapshot: SpeedSnapshot): void {
|
||||
if (!this.isDarwin || this.disposed) return
|
||||
if (this.hudEnabled && !this.opened) this.openHud()
|
||||
if (this.notificationsEnabled) this.maybeNotify(snapshot)
|
||||
this.previousState = snapshot.state
|
||||
}
|
||||
|
||||
private openHud(): void {
|
||||
if (this.opened || this.disposed) return
|
||||
this.opened = true
|
||||
const path = join(tmpdir(), `plagin-tokens-hud-${process.pid}-${this.clock()}.js`)
|
||||
this.scriptPath = path
|
||||
try {
|
||||
this.writeFileFn(path, buildHudScript(this.baseUrl))
|
||||
} catch {
|
||||
this.opened = false
|
||||
this.scriptPath = null
|
||||
return
|
||||
}
|
||||
this.child = this.spawnFn("osascript", ["-l", "JavaScript", path], {
|
||||
stdio: "ignore",
|
||||
detached: true,
|
||||
}) as ChildProcess
|
||||
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
|
||||
this.child = null
|
||||
if (this.disposed) return
|
||||
if (this.reopenAttempts < 3) {
|
||||
this.reopenAttempts += 1
|
||||
const timer = setTimeout(() => this.openHud(), 1500)
|
||||
this.timers.add(timer)
|
||||
}
|
||||
})
|
||||
this.child.on("error", () => {})
|
||||
}
|
||||
}
|
||||
|
||||
private maybeNotify(snapshot: SpeedSnapshot): void {
|
||||
const justFinished =
|
||||
this.previousState !== "finished" && snapshot.state === "finished"
|
||||
if (!justFinished) return
|
||||
if (snapshot.outputTokens <= 0) return
|
||||
const now = this.clock()
|
||||
if (now - this.lastNotifyAt < this.notifyMinIntervalMs) return
|
||||
this.lastNotifyAt = now
|
||||
const seconds = (snapshot.elapsedMs / 1000).toFixed(1)
|
||||
const model = snapshot.model ?? "opencode"
|
||||
const message = `${snapshot.tokensPerSecond} tok/s · ${snapshot.outputTokens} tokens · ${seconds}s`
|
||||
const script = `display notification "${escapeAppleScript(
|
||||
message,
|
||||
)}" with title "${escapeAppleScript("Token Speed")}" subtitle "${escapeAppleScript(model)}"`
|
||||
try {
|
||||
const child = this.spawnFn("osascript", ["-e", script], {
|
||||
stdio: "ignore",
|
||||
})
|
||||
if (child && typeof child.on === "function") child.on("error", () => {})
|
||||
} catch {
|
||||
// ignore spawn failures
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed = true
|
||||
for (const timer of this.timers) clearTimeout(timer)
|
||||
this.timers.clear()
|
||||
if (this.child) {
|
||||
try {
|
||||
this.child.kill()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.child = null
|
||||
}
|
||||
this.opened = false
|
||||
if (this.scriptPath) {
|
||||
try {
|
||||
this.unlinkFn(this.scriptPath)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.scriptPath = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function escapeAppleScript(value: string): string {
|
||||
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')
|
||||
}
|
||||
@@ -25,6 +25,71 @@ interface Client {
|
||||
}
|
||||
|
||||
const overlayDir = join(import.meta.dir, "overlay")
|
||||
const POPUP_HTML = `<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Token Speed HUD</title>
|
||||
<style>
|
||||
body{margin:0;background:#0b1022;color:#e8f3ff;font-family:system-ui,-apple-system,Arial,sans-serif;user-select:none;overflow:hidden}
|
||||
.wrap{padding:14px;display:grid;gap:4px}
|
||||
.big{font-size:36px;font-weight:800;color:#22c55e;line-height:1}
|
||||
.row{display:flex;justify-content:space-between;font-size:13px;color:#9ec3ff}
|
||||
.state{font-size:12px;opacity:.85}
|
||||
button{position:absolute;right:8px;bottom:8px;padding:6px 10px;border:0;border-radius:8px;background:#1e293b;color:#fff;font-size:12px;cursor:pointer}
|
||||
button:hover{background:#334155}
|
||||
canvas{position:absolute;left:-9999px;top:0}
|
||||
video{position:absolute;left:-9999px}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<div class="big" id="rate">0.0</div>
|
||||
<div class="row"><span id="tokens">tokens: 0</span><span id="elapsed">0s</span></div>
|
||||
<div class="state" id="state">idle</div>
|
||||
<div class="row"><span id="model"></span></div>
|
||||
</div>
|
||||
<button id="pip">Float (PiP)</button>
|
||||
<canvas id="c" width="300" height="110"></canvas>
|
||||
<video id="pipVideo" muted playsinline></video>
|
||||
<script>
|
||||
const source = new EventSource('/stream');
|
||||
let last = {};
|
||||
function fmt(n){const x=Number(n);return (!isFinite(x)||x<0)?'0.0':x.toFixed(1);}
|
||||
function render(){
|
||||
document.getElementById('rate').textContent = fmt(last.tokensPerSecond) + ' tok/s';
|
||||
document.getElementById('tokens').textContent = 'tokens: ' + (last.outputTokens||0);
|
||||
document.getElementById('elapsed').textContent = Math.round((last.elapsedMs||0)/1000) + 's';
|
||||
document.getElementById('state').textContent = last.state || 'idle';
|
||||
document.getElementById('model').textContent = last.model || '';
|
||||
drawCanvas(last);
|
||||
}
|
||||
function drawCanvas(s){
|
||||
const c=document.getElementById('c'); const ctx=c.getContext('2d');
|
||||
ctx.fillStyle='#0b1022'; ctx.fillRect(0,0,c.width,c.height);
|
||||
ctx.fillStyle='#22c55e'; ctx.font='bold 34px system-ui'; ctx.fillText(fmt(s.tokensPerSecond)+' tok/s',10,44);
|
||||
ctx.fillStyle='#e8f3ff'; ctx.font='12px system-ui';
|
||||
ctx.fillText('tokens: '+(s.outputTokens||0)+' elapsed: '+Math.round((s.elapsedMs||0)/1000)+'s',10,68);
|
||||
ctx.fillText('state: '+(s.state||'idle'),10,90);
|
||||
ctx.fillText((s.model||'').slice(0,38),10,108);
|
||||
}
|
||||
source.onmessage = function(e){ if(!e.data) return; try { last=JSON.parse(e.data); render(); } catch (err) {} };
|
||||
fetch('/speed').then(function(r){return r.json();}).then(function(d){last=d;render();}).catch(function(){});
|
||||
async function enterPip(){
|
||||
try {
|
||||
const c=document.getElementById('c');
|
||||
const stream = c.captureStream(10);
|
||||
const v=document.getElementById('pipVideo');
|
||||
v.srcObject = stream; v.muted = true; await v.play();
|
||||
await v.requestPictureInPicture();
|
||||
} catch (err) { console.error(err); }
|
||||
}
|
||||
document.getElementById('pip').addEventListener('click', enterPip);
|
||||
setInterval(function(){ drawCanvas(last); }, 250);
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
function corsHeaders(): Record<string, string> {
|
||||
return {
|
||||
@@ -178,6 +243,15 @@ export function startServer(opts: SpeedServerOptions): SpeedServer {
|
||||
if (sessionMatch) return sessionHistory(decodeURIComponent(sessionMatch[2]))
|
||||
|
||||
switch (url.pathname) {
|
||||
case "/popup":
|
||||
return new Response(POPUP_HTML, {
|
||||
status: 200,
|
||||
headers: {
|
||||
...corsHeaders(),
|
||||
"Content-Type": "text/html; charset=utf-8",
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
})
|
||||
case "/health":
|
||||
return json({ ok: true, snapshot: latest })
|
||||
case "/speed":
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { MacOSPopup } from "../src/popup"
|
||||
import type { SpeedSnapshot } from "../src/types"
|
||||
|
||||
function snap(state: SpeedSnapshot["state"]): SpeedSnapshot {
|
||||
return {
|
||||
sessionID: "s1",
|
||||
messageID: "m1",
|
||||
model: "model",
|
||||
providerID: "prov",
|
||||
tokensPerSecond: 12.3,
|
||||
outputTokens: 40,
|
||||
elapsedMs: 2300,
|
||||
state,
|
||||
updatedAt: 0,
|
||||
}
|
||||
}
|
||||
|
||||
function makeEnv(platform = "darwin", notifyMinIntervalMs = 3000) {
|
||||
const calls: any[] = []
|
||||
const spawnFn = (...args: any[]) => {
|
||||
const child = { unref() {}, on() {}, kill() {} }
|
||||
calls.push(args)
|
||||
return child
|
||||
}
|
||||
const writeFileFn = () => {}
|
||||
const unlinkFn = () => {}
|
||||
let clock = 0
|
||||
const now = () => clock
|
||||
const popup = new MacOSPopup(
|
||||
{
|
||||
baseUrl: "http://127.0.0.1:7878",
|
||||
hud: true,
|
||||
notifications: true,
|
||||
notifyMinIntervalMs,
|
||||
now,
|
||||
},
|
||||
{ platform: platform as NodeJS.Platform, spawnFn, writeFileFn, unlinkFn, now },
|
||||
)
|
||||
return { popup, calls, setClock: (value: number) => (clock = value) }
|
||||
}
|
||||
|
||||
describe("MacOSPopup", () => {
|
||||
test("is a no-op on non-Darwin platforms", () => {
|
||||
const env = makeEnv("linux")
|
||||
env.popup.start(snap("streaming"))
|
||||
env.popup.update(snap("finished"))
|
||||
expect(env.calls).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("opens a native floating HUD on Darwin at start", () => {
|
||||
const env = makeEnv()
|
||||
env.popup.start(snap("idle"))
|
||||
expect(env.calls).toHaveLength(1)
|
||||
expect(env.calls[0][0]).toBe("osascript")
|
||||
expect(env.calls[0][1][0]).toBe("-l")
|
||||
expect(env.calls[0][1][1]).toBe("JavaScript")
|
||||
})
|
||||
|
||||
test("notifies on transition to finished", () => {
|
||||
const env = makeEnv("darwin", 0)
|
||||
env.popup.start(snap("streaming"))
|
||||
env.popup.update(snap("finished"))
|
||||
expect(env.calls).toHaveLength(2)
|
||||
expect(env.calls[1][0]).toBe("osascript")
|
||||
expect(env.calls[1][1][0]).toBe("-e")
|
||||
expect(env.calls[1][1][1]).toContain("display notification")
|
||||
})
|
||||
|
||||
test("does not duplicate operations for continued streaming", () => {
|
||||
const env = makeEnv()
|
||||
env.popup.start(snap("streaming"))
|
||||
env.popup.update(snap("streaming"))
|
||||
env.popup.update(snap("streaming"))
|
||||
expect(env.calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("throttles notifications by min interval", () => {
|
||||
const env = makeEnv("darwin", 3000)
|
||||
env.popup.start(snap("streaming"))
|
||||
env.setClock(0)
|
||||
env.popup.update(snap("finished"))
|
||||
const afterFirst = env.calls.length
|
||||
env.setClock(100)
|
||||
env.popup.update(snap("streaming"))
|
||||
env.popup.update(snap("finished"))
|
||||
expect(env.calls.length).toBe(afterFirst)
|
||||
env.setClock(4000)
|
||||
env.popup.update(snap("streaming"))
|
||||
env.popup.update(snap("finished"))
|
||||
expect(env.calls.length).toBe(afterFirst + 1)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user