import { SessionMiddleware } from "tabby-terminal"; import { Observable, Subject } from "rxjs"; const oscPrefix = Buffer.from("\x1b]"); const oscSuffix = Buffer.from("\x07"); function cleanTitle(raw: string): string { const t = (raw ?? "").trim(); if (!t) return "Terminal"; if (t.includes("/") || t.includes("\\")) { const segs = t.split(/[/\\]/).filter(s => s.length > 0); return segs.length ? segs[segs.length - 1] : t; } return t; } export default class OscNotifyMiddleware extends SessionMiddleware { getTitle: () => string; onClick: () => void; constructor(getTitle: () => string, onClick: () => void) { super(); this.getTitle = getTitle; this.onClick = onClick; } get cwdReported$(): Observable { return this.cwdReported; } get copyRequested$(): Observable { return this.copyRequested; } private cwdReported = new Subject(); private copyRequested = new Subject(); private notifications: Notification[] = []; feedFromSession(data: Buffer): void { let startIndex = 0; while (data.includes(oscPrefix, startIndex) && data.includes(oscSuffix, startIndex)) { const params = data.subarray(data.indexOf(oscPrefix, startIndex) + oscPrefix.length); const oscString = params.subarray(0, params.indexOf(oscSuffix)).toString(); startIndex = data.indexOf(oscSuffix, startIndex) + oscSuffix.length; const [ oscCodeString, ...oscParams ] = oscString.split(";"); const oscCode = parseInt(oscCodeString); if (oscCode === 9) { this.showNotification(cleanTitle(this.getTitle()), oscParams[0] ?? ""); } else if (oscCode === 777 && oscParams[0] === "notify") { const title = oscParams[1] || cleanTitle(this.getTitle()); const body = oscParams.slice(2).join(";"); this.showNotification(title, body); } else { continue; } } super.feedFromSession(data); } private showNotification(title: string, body: string): void { const notification = new Notification(title || "Terminal", { body }); notification.onclick = () => this.onClick(); this.notifications.push(notification); } close(): void { this.notifications.forEach((notification) => notification.close()); this.notifications = []; this.cwdReported.complete(); this.copyRequested.complete(); super.close(); } }