From a9f6fb41cdc7145636cc050c3dfd71bae48bd5c2 Mon Sep 17 00:00:00 2001 From: Andrew Emelyaneko Date: Sat, 31 Oct 2026 22:47:31 +0300 Subject: [PATCH] fix: single reusable macOS floating HUD popup with close/minimize --- plagin_tokens/src/plugin.ts | 131 ------------------------------------ plagin_tokens/src/popup.ts | 125 ++++++++++++++++++++++++++++------ 2 files changed, 106 insertions(+), 150 deletions(-) diff --git a/plagin_tokens/src/plugin.ts b/plagin_tokens/src/plugin.ts index 6526263..e69de29 100644 --- a/plagin_tokens/src/plugin.ts +++ b/plagin_tokens/src/plugin.ts @@ -1,131 +0,0 @@ -import type { Plugin } from "@opencode-ai/plugin" -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 { - server: SpeedServer - refs: number -} - -const SHARED_KEY = Symbol.for("plagin-tokens.sharedServers") - -function registry(): Map { - const g = globalThis as unknown as Record - let reg = g[SHARED_KEY] as Map | undefined - if (!reg) { - reg = new Map() - g[SHARED_KEY] = reg - } - return reg -} - -function acquireServer( - host: string, - port: number, - getSnapshot: () => SpeedSnapshot, - providers: { - getAllSessionStats?: () => SessionStats[] - getSessionStats?: (sessionID: string) => SessionStats | null - getCurrentSessionStats?: () => SessionStats | null - } = {}, -): SpeedServer { - const reg = registry() - const key = `${host}:${port}` - const existing = reg.get(key) - if (existing) { - existing.refs += 1 - return existing.server - } - const server = startServer({ - host, - port, - getSnapshot, - getAllSessionStats: providers.getAllSessionStats, - getSessionStats: providers.getSessionStats, - getCurrentSessionStats: providers.getCurrentSessionStats, - }) - reg.set(key, { server, refs: 1 }) - return server -} - -function releaseServer(host: string, port: number): void { - const reg = registry() - const key = `${host}:${port}` - const entry = reg.get(key) - if (!entry) return - entry.refs -= 1 - if (entry.refs <= 0) { - entry.server.stop() - reg.delete(key) - } -} - -export const TokenSpeedPlugin: Plugin = async ({ client }) => { - const config = loadConfig() - const tracker = new Tracker({ - windowMs: config.windowMs, - idleTimeoutMs: config.idleTimeoutMs, - }) - - 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: { - service: "plagin-tokens", - level: "info", - message: `token speed overlay on ${server.url}`, - }, - }) - .catch(() => {}) - } catch (error) { - await client.app - .log({ - body: { - service: "plagin-tokens", - level: "error", - message: `failed to start overlay server: ${String(error)}`, - }, - }) - .catch(() => {}) - } - - 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 { - event: async ({ event }) => { - routeEvent(tracker, event) - }, - dispose: async () => { - clearInterval(ticker) - unsubscribe() - popup?.dispose() - releaseServer(config.host, config.port) - }, - } -} - -export default TokenSpeedPlugin diff --git a/plagin_tokens/src/popup.ts b/plagin_tokens/src/popup.ts index 3ce518d..f1f73d6 100644 --- a/plagin_tokens/src/popup.ts +++ b/plagin_tokens/src/popup.ts @@ -23,28 +23,59 @@ export interface MacOSPopupDeps { now?: () => number } -function buildHudScript(baseUrl: string): string { +interface SharedPopup { + popup: MacOSPopup + refs: number +} + +const SHARED_POPUP_KEY = Symbol.for("plagin-tokens.sharedPopups") + +function popupRegistry(): Map { + const g = globalThis as unknown as Record + let reg = g[SHARED_POPUP_KEY] as Map | undefined + if (!reg) { + reg = new Map() + g[SHARED_POPUP_KEY] = reg + } + return reg +} + +function buildHudScript(baseUrl: string, parentPid: number): string { return [ 'ObjC.import("Foundation");', 'ObjC.import("AppKit");', + 'ObjC.registerSubclass({', + ' name: "TokenSpeedWindowDelegate",', + ' superclass: "NSObject",', + ' methods: {', + ' "windowWillClose:": {', + ' types: ["v", ["@"]],', + ' implementation: function(note) {', + ' $.NSApp.terminate(null);', + ' },', + ' },', + ' },', + '});', "var app = $.NSApplication.sharedApplication;", "app.setActivationPolicy(1);", "var screen = $.NSScreen.mainScreen.visibleFrame;", - "var w = 340, h = 160;", + "var w = 360, h = 180;", "var rect = $.NSMakeRect(screen.size.width - w - 24, screen.size.height - h - 40, w, h);", - "var style = $.NSTitledWindowMask;", + "var style = $.NSTitledWindowMask | $.NSClosableWindowMask | $.NSMiniaturizableWindowMask;", "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));', + "window.collectionBehavior = (1 << 0) | (1 << 8) | (1 << 4);", + '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, 12, w - 28, 78));', + 'var small = $.NSTextField.alloc.initWithFrame($.NSMakeRect(14, 14, w - 28, 108));', "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.contentView.addSubview(big); window.contentView.addSubview(small);", "window.makeKeyAndOrderFront(null);", "app.activateIgnoringOtherApps(true);", "var base = " + JSON.stringify(baseUrl) + ";", @@ -55,14 +86,24 @@ function buildHudScript(baseUrl: string): string { ' (snap.model || "");', "}", 'text({ tokensPerSecond: 0, outputTokens: 0, elapsedMs: 0, state: "idle", model: "" });', + "var closed = false;", "while (true) {", + ' var winVisible = (window.isVisible === true);', + " if (!winVisible && window.miniaturized) {", + " $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.5));", + " continue;", + " }", + " if (window.miniaturized) {", + " $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.5));", + " continue;", + " }", " 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);", + ' if (str && typeof str.js !== "undefined") snap = JSON.parse(str.js);', " }", " } catch (e) {", ' small.stringValue = "Server unavailable";', @@ -87,8 +128,10 @@ export class MacOSPopup { private scriptPath: string | null = null private opened = false private disposed = false - private reopenAttempts = 0 private timers = new Set>() + private closedByUser = false + private openedForSession: string | null = null + private currentSession: string | null = null private previousState: string | null = null private lastNotifyAt = 0 @@ -106,24 +149,37 @@ export class MacOSPopup { start(snapshot?: SpeedSnapshot): void { if (!this.isDarwin || this.disposed) return - if (this.hudEnabled) this.openHud() - if (snapshot) this.update(snapshot) + if (snapshot) this.currentSession = snapshot.sessionID ?? null + if (this.hudEnabled) this.tryOpenHud(snapshot) + if (snapshot) this.previousState = snapshot.state } update(snapshot: SpeedSnapshot): void { if (!this.isDarwin || this.disposed) return - if (this.hudEnabled && !this.opened) this.openHud() + this.currentSession = snapshot.sessionID ?? this.currentSession + if (this.hudEnabled) this.tryOpenHud(snapshot) if (this.notificationsEnabled) this.maybeNotify(snapshot) this.previousState = snapshot.state } + private tryOpenHud(snapshot?: SpeedSnapshot): void { + if (this.opened) return + const sessionID = snapshot?.sessionID ?? this.currentSession + if (this.closedByUser && sessionID !== null && sessionID !== this.openedForSession) { + this.closedByUser = false + } + if (this.closedByUser) return + this.openedForSession = sessionID + this.openHud() + } + 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)) + this.writeFileFn(path, buildHudScript(this.baseUrl, process.pid)) } catch { this.opened = false this.scriptPath = null @@ -138,11 +194,14 @@ export class MacOSPopup { 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) + if (!this.disposed) this.closedByUser = true + if (this.scriptPath) { + try { + this.unlinkFn(this.scriptPath) + } catch { + // ignore + } + this.scriptPath = null } }) this.child.on("error", () => {}) @@ -159,7 +218,7 @@ export class MacOSPopup { 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 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)}"` @@ -197,6 +256,34 @@ export class MacOSPopup { } } +export function acquirePopup( + options: MacOSPopupOptions, + deps: MacOSPopupDeps = {}, +): MacOSPopup { + const reg = popupRegistry() + const key = "macos-popup" + const existing = reg.get(key) + if (existing) { + existing.refs += 1 + return existing.popup + } + const popup = new MacOSPopup(options, deps) + reg.set(key, { popup, refs: 1 }) + return popup +} + +export function releasePopup(): void { + const reg = popupRegistry() + const key = "macos-popup" + const entry = reg.get(key) + if (!entry) return + entry.refs -= 1 + if (entry.refs <= 0) { + entry.popup.dispose() + reg.delete(key) + } +} + function escapeAppleScript(value: string): string { return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"') }