diff --git a/plagin_tokens/src/config.ts b/plagin_tokens/src/config.ts index f015dd5..501a858 100644 --- a/plagin_tokens/src/config.ts +++ b/plagin_tokens/src/config.ts @@ -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, } } diff --git a/plagin_tokens/src/plugin.ts b/plagin_tokens/src/plugin.ts index df06f6a..6526263 100644 --- a/plagin_tokens/src/plugin.ts +++ b/plagin_tokens/src/plugin.ts @@ -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) }, } diff --git a/plagin_tokens/src/popup.ts b/plagin_tokens/src/popup.ts new file mode 100644 index 0000000..3ce518d --- /dev/null +++ b/plagin_tokens/src/popup.ts @@ -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>() + 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, '\\"') +} diff --git a/plagin_tokens/src/server.ts b/plagin_tokens/src/server.ts index f7f2640..381be93 100644 --- a/plagin_tokens/src/server.ts +++ b/plagin_tokens/src/server.ts @@ -25,6 +25,71 @@ interface Client { } const overlayDir = join(import.meta.dir, "overlay") +const POPUP_HTML = ` + + + + +Token Speed HUD + + + +
+
0.0
+
tokens: 00s
+
idle
+
+
+ + + + + +` function corsHeaders(): Record { return { @@ -178,7 +243,16 @@ export function startServer(opts: SpeedServerOptions): SpeedServer { if (sessionMatch) return sessionHistory(decodeURIComponent(sessionMatch[2])) switch (url.pathname) { - case "/health": + 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": return json(latest) diff --git a/plagin_tokens/test/popup.test.ts b/plagin_tokens/test/popup.test.ts new file mode 100644 index 0000000..195cc5d --- /dev/null +++ b/plagin_tokens/test/popup.test.ts @@ -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) + }) +})