diff --git a/CHANGELOG.md b/CHANGELOG.md index dcd4264..649db33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Added + +- `windows.scenario: "reminder"` keeps a Windows or WSL toast on screen until you dismiss it (#154; issue #153). + +### Upgrade notes + +- Nothing changes unless you set `windows.scenario` to `"reminder"`. Reminder toasts do not run `focusOnClick` or `onClickCommand`, and reminders on WSL are untested. +- A reminder adds a per-user `HKCU\Software\Classes\AppUserModelId\` key when that ID is not registered yet; the plugin never removes it, so delete it if you stop using the option. + +### Contributors + +- Thanks to @NGC13009 for proposing and implementing Windows reminder toasts in #154. + ## [1.1.3] - 2026-11-14 ### Fixed diff --git a/README.md b/README.md index 3d5bf0e..957d2ed 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ For sounds, you need one of: `paplay`, `aplay`, `mpv`, or `ffplay` - Only `.wav` files work (not mp3) - Use full paths like `C:/Users/You/sounds/alert.wav` not `~/` -**WSL**: Set `customIconPath` to a file on the Windows filesystem to avoid icon-path translation issues. You can copy an icon from this repository's `logos` folder. The path is passed to `snoretoast-*.exe`. +**WSL**: Set `customIconPath` to a file on the Windows filesystem to avoid icon-path translation issues. You can copy an icon from this repository's `logos` folder. Use a drive path (`C:\\...` or `/mnt/c/...`) with `windows.scenario: "reminder"`; other paths show the reminder without an icon. The plugin also restores the execute bit on node-notifier's bundled snoreToast executable when it loads, so a fresh install or update does not need a manual `chmod +x`. @@ -111,6 +111,10 @@ Create `~/.config/opencode/opencode-notifier.json` with this example configurati "linux": { "grouping": false }, + "windows": { + "appID": "opencode", + "scenario": "default" + }, "minDuration": 0, "command": { "enabled": false, @@ -207,6 +211,8 @@ Create `~/.config/opencode/opencode-notifier.json` with this example configurati - `suppressGhosttySound` - macOS only: when `true` with `notificationSystem: "ghostty"`, skips the plugin's sound to avoid duplicating macOS Notification Center's default sound (default: false) - `minDuration` - Suppress `complete` and `subagent_complete` notifications when session finishes faster than this many seconds (default: 0). See [Minimum duration threshold](#minimum-duration-threshold) - `linux.grouping` - Linux only: replace notifications in-place instead of stacking (default: false). Actionable popups use D-Bus; plain popups require `notify-send` 0.8+ +- `windows.appID` - Windows and WSL only: AppUserModelID the toast is sent as (default: `"opencode"`) +- `windows.scenario` - Windows and WSL only: `"default"` shows a normal banner, `"reminder"` keeps the toast on screen until the user dismisses it (default: `"default"`). Reminder toasts do not run `focusOnClick` or `onClickCommand`. If PowerShell cannot show the reminder within five seconds, the plugin falls back to a normal toast. Windows drops reminders from an unregistered `windows.appID`, so the plugin adds a missing one under `HKCU\Software\Classes\AppUserModelId` with the name `OpenCode` and the icon, leaves an existing one alone, and never removes it. Untested on WSL ### Events @@ -382,7 +388,7 @@ scripts you trust. } ``` -On Linux, use the explicit **Run command** action button; popup body clicks are not reliably delivered. The notification daemon must support actions. Actionable popups use a persistent D-Bus connection, so clicks remain available until the daemon closes the notification, including when hovering extends its lifetime. Windows toasts and macOS `node-notifier` deliver their activation callback; AppleScript and Ghostty OSC notifications do not support this command. +On Linux, use the explicit **Run command** action button; popup body clicks are not reliably delivered. The notification daemon must support actions. Actionable popups use a persistent D-Bus connection, so clicks remain available until the daemon closes the notification, including when hovering extends its lifetime. Windows default toasts and macOS `node-notifier` deliver their activation callback; Windows `reminder` toasts, AppleScript and Ghostty OSC notifications do not support this command. `focusOnClick` defaults to `true` and enables the built-in KDE/GNOME jump-back when available. On V2, jump-back also selects the completed session in the delivering client, using its tab or session route. Set it to `false` for a script-only action. When both are enabled, clicking runs your script and focuses the terminal. On V2, configure click commands in the local terminal's configuration and event commands on the server. `events..command` controls event commands only; a click command is available for any enabled popup. diff --git a/SPEC.md b/SPEC.md index 09c5aae..08a8423 100644 --- a/SPEC.md +++ b/SPEC.md @@ -57,6 +57,10 @@ An event is delivered on a channel only if every check passes, in this order: Actionable popups are sent and handled on one persistent session D-Bus connection. Delivery resolves when `Notify` returns the notification ID. Popup expiry is requested with `timeout`; it is not a sender or handler deadline. Handlers are removed on `NotificationClosed`, after one activation, when replaced, or when the host disposes the plugin. Replacements route clicks to the newest handler. Daemon restarts clear IDs and handlers. The connection does not keep an exiting host alive. To bound retained handlers, the oldest popup is explicitly closed before exceeding 128 handlers. Calls time out after two seconds; failed delivery falls back to a plain popup without actions. +## Windows reminder notifications + +`windows.scenario: "reminder"` sends the popup through Windows PowerShell and the WinRT toast API. Windows silently drops reminder toasts for an unregistered AppUserModelID, so when the configured `windows.appID` has no display name under `HKCU\Software\Classes\AppUserModelId`, the plugin registers it with the display name `OpenCode` and, when the icon path is one Windows can read, the icon. An ID that already has a display name is left unchanged. The plugin does not remove the key when the option is turned off. The toast carries `scenario="reminder"` plus a background dismiss action, which Windows requires before it honors the reminder scenario. The toast stays on screen until the user dismisses it. Reminder toasts have no activation callback, so `focusOnClick` and `onClickCommand` do not run for them. The PowerShell call is bounded to five seconds; when PowerShell is unavailable, the call fails, or it times out, delivery falls back to the regular transient toast. With the default scenario, PowerShell is not started and nothing is registered. + ## Release tracks `vX.Y.Z-beta.N` tags publish to npm `beta`, `vX.Y.Z` tags to `latest`. Same code, different version string. A stable release follows a confirmed beta. diff --git a/src/config.test.ts b/src/config.test.ts index e686e82..66191e3 100644 --- a/src/config.test.ts +++ b/src/config.test.ts @@ -351,6 +351,28 @@ describe("Config", () => { expect(config.minDuration).toBe(0) }) + test("loadConfig defaults the Windows toast scenario to default", async () => { + const { loadConfig } = await import("./config") + + expect(loadConfig().windows).toEqual({ appID: "opencode", scenario: "default" }) + }) + + test("loadConfig parses the reminder Windows toast scenario", async () => { + writeFileSync(testConfigPath, JSON.stringify({ windows: { appID: "my-app", scenario: "reminder" } })) + + const { loadConfig } = await import("./config") + + expect(loadConfig().windows).toEqual({ appID: "my-app", scenario: "reminder" }) + }) + + test("loadConfig falls back for an unknown Windows toast scenario", async () => { + writeFileSync(testConfigPath, JSON.stringify({ windows: { scenario: "alarm" } })) + + const { loadConfig } = await import("./config") + + expect(loadConfig().windows.scenario).toBe("default") + }) + test("interpolateMessage substitutes {timestamp} placeholder", async () => { const { interpolateMessage } = await import("./config") const result = interpolateMessage("Event at {timestamp}", { timestamp: "14:30:05" }) diff --git a/src/config.ts b/src/config.ts index 25b0d64..0652a0c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -39,8 +39,11 @@ export interface LinuxConfig { grouping: boolean } +export type WindowsScenario = "default" | "reminder" + export interface WindowsConfig { appID: string + scenario: WindowsScenario } export interface MessageContext { @@ -157,6 +160,7 @@ const DEFAULT_CONFIG: NotifierConfig = { }, windows: { appID: "opencode", + scenario: "default", }, minDuration: 0, deferCompleteUntilChildrenIdle: false, @@ -345,6 +349,7 @@ export function loadConfig(): NotifierConfig { appID: typeof userConfig.windows?.appID === "string" && userConfig.windows.appID.length > 0 ? userConfig.windows.appID : DEFAULT_CONFIG.windows.appID, + scenario: userConfig.windows?.scenario === "reminder" ? "reminder" : DEFAULT_CONFIG.windows.scenario, }, minDuration: typeof userConfig.minDuration === "number" && Number.isFinite(userConfig.minDuration) && userConfig.minDuration >= 0 diff --git a/src/delivery.ts b/src/delivery.ts index b155401..42afffe 100644 --- a/src/delivery.ts +++ b/src/delivery.ts @@ -160,7 +160,7 @@ export async function handleEvent( } } : undefined promises.push(sendNotification(title, message, config.timeout, iconPath, config.notificationSystem, config.linux.grouping, - onNotificationClick, config.windows.appID, focusOnClick ? "Jump to terminal" : "Run command")) + onNotificationClick, config.windows.appID, focusOnClick ? "Jump to terminal" : "Run command", config.windows.scenario)) } if (isEventSoundEnabled(config, eventType) && !muted.has("sound")) { diff --git a/src/notify-windows.test.ts b/src/notify-windows.test.ts new file mode 100644 index 0000000..67b9f20 --- /dev/null +++ b/src/notify-windows.test.ts @@ -0,0 +1,100 @@ +import { describe, test, expect } from "bun:test" +import { + buildWindowsToastPayload, + buildWindowsToastScript, + buildWindowsToastXml, + escapeXml, + toWindowsFileUri, + toWindowsIconPath, +} from "./notify-windows" + +describe("escapeXml", () => { + test("escapes XML entities", () => { + expect(escapeXml(`<&>"'`)).toBe("<&>"'") + }) + + test("strips control characters that XML cannot carry but keeps tabs and newlines", () => { + expect(escapeXml("a\u0000b\u0008c\td\ne\rf")).toBe("abc\td\ne\rf") + }) +}) + +describe("toWindowsIconPath", () => { + test("normalizes a Windows drive path", () => { + expect(toWindowsIconPath("c:\\Users\\Me\\logo.png", false)).toBe("C:/Users/Me/logo.png") + }) + + test("translates a WSL mounted Windows path", () => { + expect(toWindowsIconPath("/mnt/c/Users/Me/logo.png", true)).toBe("C:/Users/Me/logo.png") + }) + + test("drops a path Windows cannot read, and a missing icon", () => { + expect(toWindowsIconPath("/home/me/.cache/logo.png", true)).toBeNull() + expect(toWindowsIconPath("/mnt/c/logo.png", false)).toBeNull() + expect(toWindowsIconPath(undefined, false)).toBeNull() + }) +}) + +describe("toWindowsFileUri", () => { + test("encodes spaces and keeps the drive and separators", () => { + expect(toWindowsFileUri("C:/Program Files/logo.png")).toBe("file:///C:/Program%20Files/logo.png") + }) + + test("returns null without an icon", () => { + expect(toWindowsFileUri(null)).toBeNull() + }) +}) + +describe("buildWindowsToastXml", () => { + test("adds reminder scenario and the background action Windows requires", () => { + const xml = buildWindowsToastXml("OpenCode", "Session finished", null) + + expect(xml).toContain('') + expect(xml).toContain('') + expect(xml).toContain("OpenCode") + expect(xml).toContain("Session finished") + expect(xml).not.toContain(" { + const xml = buildWindowsToastXml("A & B", "done", "file:///C:/icon%20a&b.png") + + expect(xml).toContain('src="file:///C:/icon%20a&b.png"') + expect(xml).toContain("A & B") + }) +}) + +describe("buildWindowsToastPayload", () => { + test("carries the app id, display name, icon path and XML for the PowerShell script", () => { + const payload = buildWindowsToastPayload( + { title: "OpenCode", message: "done", iconPath: "C:\\icon.png", appID: "opencode", wsl: false } + ) + + expect(payload.appId).toBe("opencode") + expect(payload.displayName).toBe("OpenCode") + expect(payload.iconPath).toBe("C:/icon.png") + expect(payload.xml).toContain('scenario="reminder"') + expect(payload.xml).toContain("file:///C:/icon.png") + }) +}) + +describe("buildWindowsToastScript", () => { + test("registers the AppUserModelID before showing the toast", () => { + const payload = { + appId: "opencode", + displayName: "OpenCode", + iconPath: "C:/icon.png", + xml: '', + } + const script = buildWindowsToastScript(payload) + const encoded = script.match(/FromBase64String\('([^']+)'\)/)?.[1] + + expect(encoded).toBeString() + expect(JSON.parse(Buffer.from(encoded!, "base64").toString("utf8"))).toEqual(payload) + expect(script).toContain("Software\\Classes\\AppUserModelId") + expect(script).toContain("if ($null -eq $key.GetValue('DisplayName'))") + expect(script.indexOf("SetValue('DisplayName'")).toBeGreaterThan(script.indexOf("SetValue('IconUri'")) + expect(script).not.toContain("New-Item") + expect(script).toContain("Windows.UI.Notifications.ToastNotificationManager") + expect(script).toContain("CreateToastNotifier($payload.appId).Show($toast)") + }) +}) diff --git a/src/notify-windows.ts b/src/notify-windows.ts new file mode 100644 index 0000000..ac91b8e --- /dev/null +++ b/src/notify-windows.ts @@ -0,0 +1,121 @@ +import { execFile } from "child_process" + +// Windows ignores scenario="reminder" unless the toast contains at least one +// background action, so the reminder carries an explicit dismiss button. +const REMINDER_ACTIONS = '' + +// Bounds how long a broken PowerShell can delay the fallback toast. +const POWERSHELL_TIMEOUT_MS = 5000 + +// Windows shows this name in notification settings; the configurable appID +// stays the identity. +const WINDOWS_TOAST_DISPLAY_NAME = "OpenCode" + +export interface WindowsToastRequest { + title: string + message: string + iconPath?: string + appID: string + wsl: boolean +} + +export interface WindowsToastPayload { + appId: string + displayName: string + iconPath: string | null + xml: string +} + +function debug(message: string): void { + if (process.env.OPENCODE_NOTIFIER_DEBUG) console.error(`[opencode-notifier] ${message}`) +} + +// XML 1.0 text cannot carry most C0 controls. Strip them before escaping so a +// session title cannot make LoadXml fail. +export function escapeXml(value: string): string { + return value + .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g, "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'") +} + +// Drive-letter and, on WSL, /mnt/ paths are the only ones Windows can +// read. Everything else drops the icon. The AUMID registration takes this path. +export function toWindowsIconPath(iconPath: string | undefined, wsl: boolean): string | null { + const normalized = iconPath?.trim().replace(/\\/g, "/") ?? "" + const match = normalized.match(/^([A-Za-z]):\/(.*)$/) ?? (wsl ? normalized.match(/^\/mnt\/([a-z])\/(.*)$/i) : null) + return match ? `${match[1].toUpperCase()}:/${match[2]}` : null +} + +// Toast images need a file URI. +export function toWindowsFileUri(windowsPath: string | null): string | null { + if (!windowsPath) return null + const [drive, ...segments] = windowsPath.split("/") + return `file:///${drive}/${segments.map(encodeURIComponent).join("/")}` +} + +export function buildWindowsToastXml(title: string, message: string, iconUri: string | null): string { + const image = iconUri + ? `` + : "" + return `${escapeXml(title)}${escapeXml(message)}${image}${REMINDER_ACTIONS}` +} + +export function buildWindowsToastPayload(request: WindowsToastRequest): WindowsToastPayload { + const iconPath = toWindowsIconPath(request.iconPath, request.wsl) + return { + appId: request.appID, + displayName: WINDOWS_TOAST_DISPLAY_NAME, + iconPath, + xml: buildWindowsToastXml(request.title, request.message, toWindowsFileUri(iconPath)), + } +} + +// appID may belong to another app and several terminals may register at once. +// CreateSubKey opens an existing key without changing it (New-Item -Force would +// delete it), and DisplayName is written last to mark a complete registration. +export function buildWindowsToastScript(payload: WindowsToastPayload): string { + const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString("base64") + return `$ErrorActionPreference = 'Stop' +$payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded}')) | ConvertFrom-Json +$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey("Software\\Classes\\AppUserModelId\\$($payload.appId)") +if ($null -eq $key.GetValue('DisplayName')) { + if ($payload.iconPath) { $key.SetValue('IconUri', $payload.iconPath) } + $key.SetValue('DisplayName', $payload.displayName) +} +$key.Close() +[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null +[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom, ContentType = WindowsRuntime] | Out-Null +$xml = New-Object Windows.Data.Xml.Dom.XmlDocument +$xml.LoadXml($payload.xml) +$toast = [Windows.UI.Notifications.ToastNotification]::new($xml) +[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($payload.appId).Show($toast)` +} + +// Returns false when PowerShell is unavailable or the toast cannot be shown. +// The caller then falls back to the regular transient toast. +export function sendWindowsReminderNotification(request: WindowsToastRequest): Promise { + return new Promise((resolve) => { + const finish = (error: unknown) => { + if (error) debug(`reminder toast failed: ${String(error)}`) + resolve(!error) + } + try { + const script = buildWindowsToastScript(buildWindowsToastPayload(request)) + const encoded = Buffer.from(script, "utf16le").toString("base64") + // WinRT toast classes are only available in Windows PowerShell 5.1, not pwsh. + execFile( + request.wsl ? "powershell.exe" : "powershell", + ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], + { timeout: POWERSHELL_TIMEOUT_MS, windowsHide: true }, + finish + ) + } catch (error) { + // An oversized command line throws instead of reaching the callback. + finish(error) + } + }) +} diff --git a/src/notify.ts b/src/notify.ts index dae0f97..cf78788 100644 --- a/src/notify.ts +++ b/src/notify.ts @@ -5,6 +5,8 @@ export { disposeLinuxNotifications } from "./notify-linux" import notifier from "node-notifier" import isWsl from "is-wsl" import { ensureSnoreToastExecutable } from "./snoretoast" +import { sendWindowsReminderNotification } from "./notify-windows" +import type { WindowsScenario } from "./config" const DEBOUNCE_MS = 1000 @@ -184,7 +186,8 @@ export async function sendNotification( linuxGrouping: boolean = true, onClick?: () => void, windowsAppID?: string, - clickActionLabel: string = LINUX_FOCUS_ACTION_LABEL + clickActionLabel: string = LINUX_FOCUS_ACTION_LABEL, + windowsScenario: WindowsScenario = "default" ): Promise { const now = Date.now() if (lastNotificationTime[message] && now - lastNotificationTime[message] < DEBOUNCE_MS) { @@ -248,6 +251,12 @@ export async function sendNotification( } } + if ((platform === "Windows_NT" || isWsl) && windowsScenario === "reminder") { + const request = { title, message, iconPath, appID: windowsAppID ?? "opencode", wsl: isWsl } + // Fail open: when the reminder cannot be shown, fall through to the regular toast. + if (await sendWindowsReminderNotification(request)) return + } + return new Promise((resolve) => { // node-notifier's NotifySend only maps the kebab-case "app-name" key to // --app-name; without it daemons label the popup "notify-send". diff --git a/src/notify.windows-reminder.test.ts b/src/notify.windows-reminder.test.ts new file mode 100644 index 0000000..4d71c9e --- /dev/null +++ b/src/notify.windows-reminder.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, test } from "bun:test" +import { join } from "path" + +type PowerShell = "shown" | "failed" | "throws" + +interface Delivery { + powershell: { command: string; args: string[]; options: { timeout: number; windowsHide: boolean } }[] + toasts: Record[] +} + +// Runs sendNotification in a child process as if on WSL or Windows, with PowerShell and SnoreToast stubbed, +// so module mocks never leak into other test files and no real toast is shown. +async function deliver(host: "wsl" | "windows", powershell: PowerShell, scenario?: string): Promise { + const module = (name: string) => JSON.stringify(join(import.meta.dir, name)) + const script = ` + const { mock } = await import("bun:test") + const os = { ...await import("os") } + const childProcess = { ...await import("child_process") } + const delivery = { powershell: [], toasts: [] } + mock.module("os", () => ({ ...os, default: { ...os.default, type: () => ${JSON.stringify(host === "wsl" ? "Linux" : "Windows_NT")} } })) + mock.module("is-wsl", () => ({ default: ${host === "wsl"} })) + mock.module(${module("snoretoast.ts")}, () => ({ ensureSnoreToastExecutable: () => {} })) + mock.module("node-notifier", () => ({ default: { WindowsToaster: class { + notify(options, callback) { delivery.toasts.push(options); callback(null, "timeout") } + } } })) + mock.module("child_process", () => ({ ...childProcess, execFile: (command, args, options, callback) => { + delivery.powershell.push({ command, args, options }) + if (${JSON.stringify(powershell)} === "throws") throw new Error("spawn E2BIG") + callback(${JSON.stringify(powershell)} === "failed" ? new Error("powershell is unavailable") : null) + } })) + const { sendNotification } = await import(${module("notify.ts")}) + await sendNotification("OpenCode", "Session finished", 5, "C:\\\\icon.png", "osascript", false, undefined, "opencode", undefined, + ...${JSON.stringify(scenario ? [scenario] : [])}) + process.stdout.write(JSON.stringify(delivery)) + ` + const child = Bun.spawn([process.execPath, "--eval", script], { stdout: "pipe", stderr: "pipe" }) + const errors = await new Response(child.stderr).text() + expect(await child.exited, errors).toBe(0) + return JSON.parse(await new Response(child.stdout).text()) +} + +const REGULAR_TOAST = { title: "OpenCode", message: "Session finished", timeout: 5, icon: "C:\\icon.png", appName: "opencode" } + +describe.each(["wsl", "windows"] as const)("Windows toast on %s", (host) => { + test("stays the regular toast, without PowerShell, unless reminder is set", async () => { + for (const scenario of [undefined, "default"]) { + expect(await deliver(host, "shown", scenario)).toEqual({ powershell: [], toasts: [REGULAR_TOAST] }) + } + }) + + test("a reminder replaces the regular toast", async () => { + const { powershell, toasts } = await deliver(host, "shown", "reminder") + + expect(toasts).toEqual([]) + expect(powershell).toHaveLength(1) + expect(powershell[0].command).toBe(host === "wsl" ? "powershell.exe" : "powershell") + expect(powershell[0].args).toContain("-EncodedCommand") + expect(powershell[0].options).toEqual({ timeout: 5000, windowsHide: true }) + }) + + test.each(["failed", "throws"] as const)("falls back to the regular toast when PowerShell %s", async (outcome) => { + const { powershell, toasts } = await deliver(host, outcome, "reminder") + + expect(powershell).toHaveLength(1) + expect(toasts).toEqual([REGULAR_TOAST]) + }) +})