From 35b8a6b0acfe07ec3d84bb4047bbaffb9d416f7a Mon Sep 17 00:00:00 2001 From: NGC13009 Date: Tue, 24 Nov 2026 20:45:08 +0800 Subject: [PATCH 1/9] feat(windows): keep reminder toasts on screen until dismissed Windows toasts vanished after a few seconds, so a missed alert had no way to stay visible. windows.scenario: "reminder" now sends the toast through PowerShell and the WinRT toast API with scenario="reminder" and a Dismiss action, which Windows requires before it honors that scenario. Windows silently drops reminder toasts for an AppUserModelID it does not know, so the toast script registers windows.appID under HKCU\Software\Classes\AppUserModelId with a display name and icon before showing it. An unset windows.scenario still produces today's banner, and a failed PowerShell call falls back to the regular transient toast. Reminder toasts have no activation callback, so focusOnClick and onClickCommand do not run for them. Verified on Windows with the new notify-windows tests and config tests; WSL uses the same code path but was not run on real hardware. --- CHANGELOG.md | 8 ++ README.md | 8 +- SPEC.md | 4 + src/config.test.ts | 22 ++++++ src/config.ts | 5 ++ src/delivery.ts | 2 +- src/notify-windows.test.ts | 112 ++++++++++++++++++++++++++ src/notify-windows.ts | 157 +++++++++++++++++++++++++++++++++++++ src/notify.ts | 11 ++- 9 files changed, 326 insertions(+), 3 deletions(-) create mode 100644 src/notify-windows.test.ts create mode 100644 src/notify-windows.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index dcd4264..d975566 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Added + +- `windows.scenario` option: set it to `"reminder"` to keep a Windows or WSL toast on screen until the user dismisses it. The default, `"default"`, keeps the current banner behavior. Reminder toasts register the configured AppUserModelID under `HKCU\Software\Classes\AppUserModelId`, since Windows drops them for an unregistered ID. + +### Upgrade notes + +- Existing configurations are unchanged: an unset `windows.scenario` behaves as before. Reminder toasts do not run `focusOnClick` or `onClickCommand`. + ## [1.1.3] - 2026-11-14 ### Fixed diff --git a/README.md b/README.md index 3d5bf0e..5b3e660 100644 --- a/README.md +++ b/README.md @@ -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 registered under (default: `"opencode"`). Reminder toasts register it per-user under `HKCU\Software\Classes\AppUserModelId` so Windows will display them +- `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 carry a Dismiss button and register the configured AppUserModelID automatically; Windows drops reminder toasts for an unregistered ID. Reminder toasts do not deliver click callbacks, so `focusOnClick` and `onClickCommand` do not run for them. If PowerShell cannot display the reminder, the plugin falls back to a normal toast ### 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..2a7786f 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. Before showing it, the plugin registers the configured `windows.appID` under `HKCU\Software\Classes\AppUserModelId` with a display name and icon, because Windows silently drops reminder toasts for an unregistered AppUserModelID. 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. If PowerShell is unavailable or the toast cannot be shown, delivery falls back to the regular transient toast. The default scenario reproduces the normal banner behavior. + ## 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..cfa67e3 --- /dev/null +++ b/src/notify-windows.test.ts @@ -0,0 +1,112 @@ +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("toWindowsFileUri", () => { + test("converts a Windows drive path", () => { + expect(toWindowsFileUri("C:\\Users\\Me\\logo.png", false)).toBe("file:///C:/Users/Me/logo.png") + }) + + test("encodes spaces and keeps forward slashes", () => { + expect(toWindowsFileUri("C:/Program Files/logo.png", false)).toBe("file:///C:/Program%20Files/logo.png") + }) + + test("returns null for a WSL filesystem path Windows cannot read", () => { + expect(toWindowsFileUri("/home/me/.cache/logo.png", true)).toBeNull() + }) + + test("returns null when there is no icon", () => { + expect(toWindowsFileUri(undefined, false)).toBeNull() + }) +}) + +describe("toWindowsIconPath", () => { + test("normalizes a Windows drive path for the AUMID registry entry", () => { + 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 WSL filesystem path Windows cannot read", () => { + expect(toWindowsIconPath("/home/me/.cache/logo.png", true)).toBeNull() + }) +}) + +describe("buildWindowsToastXml", () => { + test("adds reminder scenario and the background action Windows requires", () => { + const xml = buildWindowsToastXml("OpenCode", "Session finished", null, "reminder") + + expect(xml).toContain('') + expect(xml).toContain('') + expect(xml).toContain("OpenCode") + expect(xml).toContain("Session finished") + expect(xml).not.toContain(" { + const xml = buildWindowsToastXml("OpenCode", "Session finished", null, "default") + + expect(xml).not.toContain("scenario=") + expect(xml).not.toContain("") + }) + + test("includes an escaped app logo URI", () => { + const xml = buildWindowsToastXml("A & B", "done", "file:///C:/icon%20a&b.png", "reminder") + + 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( + "OpenCode", "done", "C:\\icon.png", "opencode", "reminder", 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("Set-ItemProperty -Path $appKey -Name DisplayName") + expect(script).toContain("Set-ItemProperty -Path $appKey -Name IconUri") + 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..4843d7f --- /dev/null +++ b/src/notify-windows.ts @@ -0,0 +1,157 @@ +import { execFile } from "child_process" +import { pathToFileURL } from "url" +import type { WindowsScenario } from "./config" + +// Windows ignores scenario="reminder" unless the toast contains at least one +// background action, so the reminder carries an explicit dismiss button. +const REMINDER_ACTIONS = '' + +const POWERSHELL_TIMEOUT_MS = 5000 + +export interface WindowsToastPayload { + appId: string + displayName: string + iconPath: string | null + xml: string +} + +const WINDOWS_APP_DISPLAY_NAME = "OpenCode" + +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, "'") +} + +// Toast images need a Windows file URI. WSL runs this code on Linux, where +// pathToFileURL would produce a Linux path Windows cannot read, so drive +// paths are converted explicitly. Unsupported paths drop the icon. +export function toWindowsFileUri(iconPath: string | undefined, wsl: boolean): string | null { + const value = iconPath?.trim() + if (!value) return null + + const normalized = value.replace(/\\/g, "/") + const drive = normalized.match(/^([A-Za-z]):\/(.*)$/) + if (drive) { + const segments = drive[2].split("/").map(segment => encodeURIComponent(segment)) + return `file:///${drive[1].toUpperCase()}:/${segments.join("/")}` + } + + if (!wsl && normalized.startsWith("/")) { + try { + return pathToFileURL(value).href + } catch { + return null + } + } + + return null +} + +// The AUMID registration stores a Windows path, not a file URI. WSL paths +// under /mnt/ are translated so Windows can read the icon. +export function toWindowsIconPath(iconPath: string | undefined, wsl: boolean): string | null { + const value = iconPath?.trim() + if (!value) return null + + const normalized = value.replace(/\\/g, "/") + const drive = normalized.match(/^([A-Za-z]):\/(.*)$/) + if (drive) return `${drive[1].toUpperCase()}:/${drive[2]}` + + const wslDrive = normalized.match(/^\/mnt\/([a-z])\/(.*)$/i) + if (wsl && wslDrive) return `${wslDrive[1].toUpperCase()}:/${wslDrive[2]}` + + if (!wsl && normalized.startsWith("/")) return value + + return null +} + +export function buildWindowsToastXml( + title: string, + message: string, + iconUri: string | null, + scenario: WindowsScenario +): string { + const image = iconUri + ? `` + : "" + const scenarioAttribute = scenario === "default" ? "" : ` scenario="${scenario}"` + const actions = scenario === "reminder" ? REMINDER_ACTIONS : "" + return `${escapeXml(title)}${escapeXml(message)}${image}${actions}` +} + +export function buildWindowsToastPayload( + title: string, + message: string, + iconPath: string | undefined, + appID: string, + scenario: WindowsScenario, + wsl: boolean +): WindowsToastPayload { + return { + appId: appID, + displayName: WINDOWS_APP_DISPLAY_NAME, + iconPath: toWindowsIconPath(iconPath, wsl), + xml: buildWindowsToastXml(title, message, toWindowsFileUri(iconPath, wsl), scenario), + } +} + +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 +$appKey = "HKCU:\\Software\\Classes\\AppUserModelId\\$($payload.appId)" +$registered = Get-ItemProperty -Path $appKey -ErrorAction SilentlyContinue +$needsIcon = $payload.iconPath -and ($null -eq $registered -or $registered.IconUri -ne $payload.iconPath) +if ($null -eq $registered -or $registered.DisplayName -ne $payload.displayName -or $needsIcon) { + New-Item -Path $appKey -Force | Out-Null + Set-ItemProperty -Path $appKey -Name DisplayName -Value $payload.displayName + if ($payload.iconPath) { + Set-ItemProperty -Path $appKey -Name IconUri -Value $payload.iconPath + } +} +[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( + title: string, + message: string, + iconPath: string | undefined, + appID: string, + wsl: boolean +): Promise { + const payload = buildWindowsToastPayload(title, message, iconPath, appID, "reminder", wsl) + const script = buildWindowsToastScript(payload) + const encoded = Buffer.from(script, "utf16le").toString("base64") + // WinRT toast classes are only available in Windows PowerShell 5.1, not pwsh. + const command = wsl ? "powershell.exe" : "powershell" + + return new Promise((resolve) => { + execFile( + command, + ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], + { timeout: POWERSHELL_TIMEOUT_MS, windowsHide: true }, + (error) => { + if (error) debug(`reminder toast failed: ${String(error)}`) + resolve(!error) + } + ) + }) +} diff --git a/src/notify.ts b/src/notify.ts index dae0f97..6e0b005 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") { + if (await sendWindowsReminderNotification(title, message, iconPath, windowsAppID ?? "opencode", isWsl)) { + 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". From 3bd70c37ab00f1eff230d8883b67fab602768d59 Mon Sep 17 00:00:00 2001 From: NGC13009 Date: Tue, 24 Nov 2026 21:31:24 +0800 Subject: [PATCH 2/9] fix(windows): bound reminder fallback delay and cover the fallback path A broken PowerShell could delay the regular toast by five seconds; the call now times out after two. The reminder/default/fallback decision has unit tests with a stubbed execFile, and WSL /mnt icon paths are translated for the toast image the same way as the AUMID icon. Docs now state the reminder-toast registry entry and that the plugin never removes it. --- CHANGELOG.md | 3 +- README.md | 4 +- SPEC.md | 2 +- src/notify-windows.test.ts | 8 ++- src/notify-windows.ts | 102 +++++++++++++++++----------- src/notify.ts | 47 +++++++------ src/notify.windows-reminder.test.ts | 94 +++++++++++++++++++++++++ 7 files changed, 192 insertions(+), 68 deletions(-) create mode 100644 src/notify.windows-reminder.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d975566..6b3036e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,12 @@ All notable changes to this project will be documented in this file. ### Added -- `windows.scenario` option: set it to `"reminder"` to keep a Windows or WSL toast on screen until the user dismisses it. The default, `"default"`, keeps the current banner behavior. Reminder toasts register the configured AppUserModelID under `HKCU\Software\Classes\AppUserModelId`, since Windows drops them for an unregistered ID. +- `windows.scenario` option: set it to `"reminder"` to keep a Windows or WSL toast on screen until the user dismisses it. The default, `"default"`, keeps the current banner behavior. Reminder toasts register the configured AppUserModelID under `HKCU\Software\Classes\AppUserModelId`, with the display name `OpenCode` and the icon when Windows can read it, since Windows drops them for an unregistered ID. ### Upgrade notes - Existing configurations are unchanged: an unset `windows.scenario` behaves as before. Reminder toasts do not run `focusOnClick` or `onClickCommand`. +- Reminder toasts write a per-user `HKCU` key that the plugin never removes; delete `HKCU\Software\Classes\AppUserModelId\` if you stop using the option. ## [1.1.3] - 2026-11-14 diff --git a/README.md b/README.md index 5b3e660..73b9f9b 100644 --- a/README.md +++ b/README.md @@ -211,8 +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 registered under (default: `"opencode"`). Reminder toasts register it per-user under `HKCU\Software\Classes\AppUserModelId` so Windows will display them -- `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 carry a Dismiss button and register the configured AppUserModelID automatically; Windows drops reminder toasts for an unregistered ID. Reminder toasts do not deliver click callbacks, so `focusOnClick` and `onClickCommand` do not run for them. If PowerShell cannot display the reminder, the plugin falls back to a normal toast +- `windows.appID` - Windows and WSL only: AppUserModelID the toast is registered under (default: `"opencode"`). Reminder toasts register it per-user under `HKCU\Software\Classes\AppUserModelId` with the display name `OpenCode` and, when Windows can read the icon file, its icon, because Windows drops reminder toasts for an unregistered ID. The plugin never removes that key +- `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 carry a Dismiss button and register the configured AppUserModelID automatically. Reminder toasts do not deliver click callbacks, so `focusOnClick` and `onClickCommand` do not run for them. If PowerShell cannot show the reminder within two seconds, the plugin falls back to a normal toast ### Events diff --git a/SPEC.md b/SPEC.md index 2a7786f..5c415a0 100644 --- a/SPEC.md +++ b/SPEC.md @@ -59,7 +59,7 @@ Actionable popups are sent and handled on one persistent session D-Bus connectio ## Windows reminder notifications -`windows.scenario: "reminder"` sends the popup through Windows PowerShell and the WinRT toast API. Before showing it, the plugin registers the configured `windows.appID` under `HKCU\Software\Classes\AppUserModelId` with a display name and icon, because Windows silently drops reminder toasts for an unregistered AppUserModelID. 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. If PowerShell is unavailable or the toast cannot be shown, delivery falls back to the regular transient toast. The default scenario reproduces the normal banner behavior. +`windows.scenario: "reminder"` sends the popup through Windows PowerShell and the WinRT toast API. Before showing it, the plugin registers the configured `windows.appID` under `HKCU\Software\Classes\AppUserModelId` with the display name `OpenCode` and, when the icon path is one Windows can read, the icon, because Windows silently drops reminder toasts for an unregistered AppUserModelID. 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 two seconds; when PowerShell is unavailable, the call fails, or it times out, delivery falls back to the regular transient toast. The default scenario reproduces the normal banner behavior. ## Release tracks diff --git a/src/notify-windows.test.ts b/src/notify-windows.test.ts index cfa67e3..c6e2752 100644 --- a/src/notify-windows.test.ts +++ b/src/notify-windows.test.ts @@ -27,6 +27,10 @@ describe("toWindowsFileUri", () => { expect(toWindowsFileUri("C:/Program Files/logo.png", false)).toBe("file:///C:/Program%20Files/logo.png") }) + test("translates a WSL mounted Windows path", () => { + expect(toWindowsFileUri("/mnt/c/Users/Me/logo.png", true)).toBe("file:///C:/Users/Me/logo.png") + }) + test("returns null for a WSL filesystem path Windows cannot read", () => { expect(toWindowsFileUri("/home/me/.cache/logo.png", true)).toBeNull() }) @@ -79,7 +83,8 @@ describe("buildWindowsToastXml", () => { describe("buildWindowsToastPayload", () => { test("carries the app id, display name, icon path and XML for the PowerShell script", () => { const payload = buildWindowsToastPayload( - "OpenCode", "done", "C:\\icon.png", "opencode", "reminder", false + { title: "OpenCode", message: "done", iconPath: "C:\\icon.png", appID: "opencode", wsl: false }, + "reminder" ) expect(payload.appId).toBe("opencode") @@ -106,6 +111,7 @@ describe("buildWindowsToastScript", () => { expect(script).toContain("Software\\Classes\\AppUserModelId") expect(script).toContain("Set-ItemProperty -Path $appKey -Name DisplayName") expect(script).toContain("Set-ItemProperty -Path $appKey -Name IconUri") + expect(script).toContain("Remove-ItemProperty -Path $appKey -Name IconUri") 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 index 4843d7f..1e971bd 100644 --- a/src/notify-windows.ts +++ b/src/notify-windows.ts @@ -6,7 +6,20 @@ import type { WindowsScenario } from "./config" // background action, so the reminder carries an explicit dismiss button. const REMINDER_ACTIONS = '' -const POWERSHELL_TIMEOUT_MS = 5000 +// Bounds how long a broken PowerShell can delay the fallback toast. +const POWERSHELL_TIMEOUT_MS = 2000 + +// 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 @@ -15,8 +28,6 @@ export interface WindowsToastPayload { xml: string } -const WINDOWS_APP_DISPLAY_NAME = "OpenCode" - function debug(message: string): void { if (process.env.OPENCODE_NOTIFIER_DEBUG) console.error(`[opencode-notifier] ${message}`) } @@ -33,21 +44,31 @@ export function escapeXml(value: string): string { .replace(/'/g, "'") } -// Toast images need a Windows file URI. WSL runs this code on Linux, where -// pathToFileURL would produce a Linux path Windows cannot read, so drive -// paths are converted explicitly. Unsupported paths drop the icon. +// Drive-letter and, on WSL, /mnt/ paths are the only ones Windows can +// read. Everything else is dropped instead of producing an unreadable URI. +function toWindowsDrivePath(value: string, wsl: boolean): string | null { + const normalized = value.replace(/\\/g, "/") + const drive = normalized.match(/^([A-Za-z]):\/(.*)$/) + if (drive) return `${drive[1].toUpperCase()}:/${drive[2]}` + + const wslDrive = normalized.match(/^\/mnt\/([a-z])\/(.*)$/i) + if (wsl && wslDrive) return `${wslDrive[1].toUpperCase()}:/${wslDrive[2]}` + + return null +} + +// Toast images need a Windows file URI. Unsupported paths drop the icon. export function toWindowsFileUri(iconPath: string | undefined, wsl: boolean): string | null { const value = iconPath?.trim() if (!value) return null - const normalized = value.replace(/\\/g, "/") - const drive = normalized.match(/^([A-Za-z]):\/(.*)$/) - if (drive) { - const segments = drive[2].split("/").map(segment => encodeURIComponent(segment)) - return `file:///${drive[1].toUpperCase()}:/${segments.join("/")}` + const drivePath = toWindowsDrivePath(value, wsl) + if (drivePath) { + const [drive, ...segments] = drivePath.split("/") + return `file:///${drive}/${segments.map(segment => encodeURIComponent(segment)).join("/")}` } - if (!wsl && normalized.startsWith("/")) { + if (!wsl && value.replace(/\\/g, "/").startsWith("/")) { try { return pathToFileURL(value).href } catch { @@ -58,20 +79,15 @@ export function toWindowsFileUri(iconPath: string | undefined, wsl: boolean): st return null } -// The AUMID registration stores a Windows path, not a file URI. WSL paths -// under /mnt/ are translated so Windows can read the icon. +// The AUMID registration stores a Windows path, not a file URI. export function toWindowsIconPath(iconPath: string | undefined, wsl: boolean): string | null { const value = iconPath?.trim() if (!value) return null - const normalized = value.replace(/\\/g, "/") - const drive = normalized.match(/^([A-Za-z]):\/(.*)$/) - if (drive) return `${drive[1].toUpperCase()}:/${drive[2]}` - - const wslDrive = normalized.match(/^\/mnt\/([a-z])\/(.*)$/i) - if (wsl && wslDrive) return `${wslDrive[1].toUpperCase()}:/${wslDrive[2]}` + const drivePath = toWindowsDrivePath(value, wsl) + if (drivePath) return drivePath - if (!wsl && normalized.startsWith("/")) return value + if (!wsl && value.replace(/\\/g, "/").startsWith("/")) return value return null } @@ -91,18 +107,14 @@ export function buildWindowsToastXml( } export function buildWindowsToastPayload( - title: string, - message: string, - iconPath: string | undefined, - appID: string, - scenario: WindowsScenario, - wsl: boolean + request: WindowsToastRequest, + scenario: WindowsScenario ): WindowsToastPayload { return { - appId: appID, - displayName: WINDOWS_APP_DISPLAY_NAME, - iconPath: toWindowsIconPath(iconPath, wsl), - xml: buildWindowsToastXml(title, message, toWindowsFileUri(iconPath, wsl), scenario), + appId: request.appID, + displayName: WINDOWS_TOAST_DISPLAY_NAME, + iconPath: toWindowsIconPath(request.iconPath, request.wsl), + xml: buildWindowsToastXml(request.title, request.message, toWindowsFileUri(request.iconPath, request.wsl), scenario), } } @@ -113,11 +125,14 @@ $payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encode $appKey = "HKCU:\\Software\\Classes\\AppUserModelId\\$($payload.appId)" $registered = Get-ItemProperty -Path $appKey -ErrorAction SilentlyContinue $needsIcon = $payload.iconPath -and ($null -eq $registered -or $registered.IconUri -ne $payload.iconPath) -if ($null -eq $registered -or $registered.DisplayName -ne $payload.displayName -or $needsIcon) { +$staleIcon = -not $payload.iconPath -and $null -ne $registered -and $null -ne $registered.IconUri +if ($null -eq $registered -or $registered.DisplayName -ne $payload.displayName -or $needsIcon -or $staleIcon) { New-Item -Path $appKey -Force | Out-Null Set-ItemProperty -Path $appKey -Name DisplayName -Value $payload.displayName if ($payload.iconPath) { Set-ItemProperty -Path $appKey -Name IconUri -Value $payload.iconPath + } elseif ($staleIcon) { + Remove-ItemProperty -Path $appKey -Name IconUri } } [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null @@ -130,18 +145,12 @@ $toast = [Windows.UI.Notifications.ToastNotification]::new($xml) // 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( - title: string, - message: string, - iconPath: string | undefined, - appID: string, - wsl: boolean -): Promise { - const payload = buildWindowsToastPayload(title, message, iconPath, appID, "reminder", wsl) +export function sendWindowsReminderNotification(request: WindowsToastRequest): Promise { + const payload = buildWindowsToastPayload(request, "reminder") const script = buildWindowsToastScript(payload) const encoded = Buffer.from(script, "utf16le").toString("base64") // WinRT toast classes are only available in Windows PowerShell 5.1, not pwsh. - const command = wsl ? "powershell.exe" : "powershell" + const command = request.wsl ? "powershell.exe" : "powershell" return new Promise((resolve) => { execFile( @@ -155,3 +164,14 @@ export function sendWindowsReminderNotification( ) }) } + +// Reminders are opt-in and best-effort: the default scenario, a failed +// reminder and an unavailable PowerShell all end at the regular toast. +export async function deliverWindowsNotification( + scenario: WindowsScenario, + request: WindowsToastRequest, + sendDefault: () => Promise +): Promise { + if (scenario === "reminder" && await sendWindowsReminderNotification(request)) return + await sendDefault() +} diff --git a/src/notify.ts b/src/notify.ts index 6e0b005..8119eaa 100644 --- a/src/notify.ts +++ b/src/notify.ts @@ -5,7 +5,7 @@ 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 { deliverWindowsNotification } from "./notify-windows" import type { WindowsScenario } from "./config" const DEBOUNCE_MS = 1000 @@ -251,27 +251,30 @@ export async function sendNotification( } } - if ((platform === "Windows_NT" || isWsl) && windowsScenario === "reminder") { - if (await sendWindowsReminderNotification(title, message, iconPath, windowsAppID ?? "opencode", isWsl)) { - return - } + const sendDefaultNotification = (): Promise => { + 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". + const notificationOptions = (platform === "Linux" || platform.match(/BSD$/)) && !isWsl + ? { title, message, timeout, icon: iconPath, "app-name": "opencode" } + : buildWindowsNotificationOptions(title, message, timeout, iconPath, windowsAppID) + + platformNotifier.notify( + notificationOptions, + (_error, response, metadata) => { + if (onClick && (response === "activate" || metadata?.activationType === "default" || metadata?.activationType === "activated")) { + try { onClick() } catch {} + } + resolve() + } + ) + }) } - 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". - const notificationOptions = (platform === "Linux" || platform.match(/BSD$/)) && !isWsl - ? { title, message, timeout, icon: iconPath, "app-name": "opencode" } - : buildWindowsNotificationOptions(title, message, timeout, iconPath, windowsAppID) - - platformNotifier.notify( - notificationOptions, - (_error, response, metadata) => { - if (onClick && (response === "activate" || metadata?.activationType === "default" || metadata?.activationType === "activated")) { - try { onClick() } catch {} - } - resolve() - } - ) - }) + if (platform === "Windows_NT" || isWsl) { + const request = { title, message, iconPath, appID: windowsAppID ?? "opencode", wsl: isWsl } + return deliverWindowsNotification(windowsScenario, request, sendDefaultNotification) + } + + return sendDefaultNotification() } diff --git a/src/notify.windows-reminder.test.ts b/src/notify.windows-reminder.test.ts new file mode 100644 index 0000000..27f67d5 --- /dev/null +++ b/src/notify.windows-reminder.test.ts @@ -0,0 +1,94 @@ +import { beforeEach, describe, expect, mock, test } from "bun:test" + +interface ExecCall { + command: string + args: string[] + options: { timeout?: number; windowsHide?: boolean } +} + +const execCalls: ExecCall[] = [] +let execError: Error | null = null + +// Stub the PowerShell boundary so the reminder path runs for real without +// spawning a process. +mock.module("child_process", () => ({ + execFile( + command: string, + args: string[], + options: ExecCall["options"], + callback: (error: Error | null) => void + ) { + execCalls.push({ command, args, options }) + callback(execError) + return { kill() {} } + }, +})) + +const { deliverWindowsNotification } = await import("./notify-windows") + +const request = { + title: "OpenCode", + message: "Session finished", + iconPath: "C:\\icon.png", + appID: "opencode", + wsl: false, +} + +function fallback() { + let count = 0 + return { + count: () => count, + deliver: async () => { + count++ + }, + } +} + +beforeEach(() => { + execCalls.length = 0 + execError = null +}) + +describe("deliverWindowsNotification", () => { + test("shows the regular toast without starting PowerShell for the default scenario", async () => { + const defaultToast = fallback() + + await deliverWindowsNotification("default", request, defaultToast.deliver) + + expect(execCalls).toHaveLength(0) + expect(defaultToast.count()).toBe(1) + }) + + test("replaces the regular toast once the reminder is shown", async () => { + const defaultToast = fallback() + + await deliverWindowsNotification("reminder", request, defaultToast.deliver) + + expect(defaultToast.count()).toBe(0) + expect(execCalls).toHaveLength(1) + expect(execCalls[0].command).toBe("powershell") + expect(execCalls[0].args).toContain("-EncodedCommand") + expect(execCalls[0].options.windowsHide).toBe(true) + // A broken PowerShell must not delay the fallback toast for long. + expect(execCalls[0].options.timeout).toBeLessThanOrEqual(2000) + }) + + test("falls back to the regular toast when PowerShell fails", async () => { + execError = new Error("powershell is unavailable") + const defaultToast = fallback() + + await deliverWindowsNotification("reminder", request, defaultToast.deliver) + + expect(execCalls).toHaveLength(1) + expect(defaultToast.count()).toBe(1) + }) + + test("launches powershell.exe under WSL", async () => { + const defaultToast = fallback() + + await deliverWindowsNotification("reminder", { ...request, wsl: true }, defaultToast.deliver) + + expect(execCalls[0].command).toBe("powershell.exe") + expect(defaultToast.count()).toBe(0) + }) +}) From a8c2e9789516cad5059eb8ccd7229c8242e63128 Mon Sep 17 00:00:00 2001 From: NGC13009 Date: Tue, 24 Nov 2026 21:38:44 +0800 Subject: [PATCH 3/9] docs: describe loading the local checkout in OpenCode 2 The directory-plugin loader uses package.json name and exports, so the checkout loads dist/index.js and dist/tui.js and needs a build plus restart, not a shim directory. --- CONTRIBUTING.md | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6b39b26..39103c8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,18 +20,13 @@ bun run build To try your build in OpenCode, use a throwaway notifier config through `OPENCODE_NOTIFIER_CONFIG_PATH`. - OpenCode 1: point the `plugin` list in a scratch project's `opencode.json` at your local checkout. -- OpenCode 2: a local directory plugin is loaded from `index.js` and `tui.js` at the directory root, not from `package.json` exports, so pointing at the checkout loads nothing. From the repo root, make a private shim directory that re-exports the build: +- OpenCode 2: list the checkout in `plugins`. The package has `name` and `exports`, so OpenCode loads the built parts from `dist/index.js` (server) and `dist/tui.js` (terminal), which means `bun run build` must run before testing: - ```bash - shim=$(mktemp -d) && - echo "export { default } from \"$PWD/dist/index.js\"" > "$shim/index.js" && - echo "export { default } from \"$PWD/dist/tui.js\"" > "$shim/tui.js" && - echo "file://$shim" + ```json + { "plugins": ["file:///absolute/path/to/opencode-notifier"] } ``` - List the printed URL under `plugins`: `{ "plugins": ["file:///tmp/tmp.XXXXXX"] }`. - - Run `opencode --standalone` so the test uses a private server instead of your background service. + The checkout is not a watched configuration directory, so a rebuild only loads after a restart: `opencode service restart` for the server, then reopen the TUI. Run `opencode --standalone` so the test uses a private server instead of your background service. ## Rules for a PR From d5a1de0fcc813d3d2ae3a1c8ddc13be14993e060 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Tue, 24 Nov 2026 23:04:28 +0000 Subject: [PATCH 4/9] Revert "docs: describe loading the local checkout in OpenCode 2" This reverts commit a8c2e9789516cad5059eb8ccd7229c8242e63128. --- CONTRIBUTING.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 39103c8..6b39b26 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,13 +20,18 @@ bun run build To try your build in OpenCode, use a throwaway notifier config through `OPENCODE_NOTIFIER_CONFIG_PATH`. - OpenCode 1: point the `plugin` list in a scratch project's `opencode.json` at your local checkout. -- OpenCode 2: list the checkout in `plugins`. The package has `name` and `exports`, so OpenCode loads the built parts from `dist/index.js` (server) and `dist/tui.js` (terminal), which means `bun run build` must run before testing: +- OpenCode 2: a local directory plugin is loaded from `index.js` and `tui.js` at the directory root, not from `package.json` exports, so pointing at the checkout loads nothing. From the repo root, make a private shim directory that re-exports the build: - ```json - { "plugins": ["file:///absolute/path/to/opencode-notifier"] } + ```bash + shim=$(mktemp -d) && + echo "export { default } from \"$PWD/dist/index.js\"" > "$shim/index.js" && + echo "export { default } from \"$PWD/dist/tui.js\"" > "$shim/tui.js" && + echo "file://$shim" ``` - The checkout is not a watched configuration directory, so a rebuild only loads after a restart: `opencode service restart` for the server, then reopen the TUI. Run `opencode --standalone` so the test uses a private server instead of your background service. + List the printed URL under `plugins`: `{ "plugins": ["file:///tmp/tmp.XXXXXX"] }`. + + Run `opencode --standalone` so the test uses a private server instead of your background service. ## Rules for a PR From 8af4744793709b8c6e1043317626de36c434ec9f Mon Sep 17 00:00:00 2001 From: mohak34 Date: Tue, 24 Nov 2026 23:04:51 +0000 Subject: [PATCH 5/9] fix(windows): never overwrite an app ID that is already registered Co-Authored-By: Claude Opus 5.5 --- src/notify-windows.test.ts | 7 ++++--- src/notify-windows.ts | 19 ++++++++----------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/notify-windows.test.ts b/src/notify-windows.test.ts index c6e2752..c567a16 100644 --- a/src/notify-windows.test.ts +++ b/src/notify-windows.test.ts @@ -109,9 +109,10 @@ describe("buildWindowsToastScript", () => { expect(encoded).toBeString() expect(JSON.parse(Buffer.from(encoded!, "base64").toString("utf8"))).toEqual(payload) expect(script).toContain("Software\\Classes\\AppUserModelId") - expect(script).toContain("Set-ItemProperty -Path $appKey -Name DisplayName") - expect(script).toContain("Set-ItemProperty -Path $appKey -Name IconUri") - expect(script).toContain("Remove-ItemProperty -Path $appKey -Name IconUri") + expect(script).toContain("if (-not (Test-Path -LiteralPath $appKey)) { New-Item") + expect(script).toContain("-Name IconUri") + expect(script.indexOf("-Name DisplayName")).toBeGreaterThan(script.indexOf("-Name IconUri")) + expect(script).not.toContain("Remove-ItemProperty") 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 index 1e971bd..4da0303 100644 --- a/src/notify-windows.ts +++ b/src/notify-windows.ts @@ -118,22 +118,19 @@ export function buildWindowsToastPayload( } } +// New-Item -Force deletes an existing key, and appID may belong to another app, +// so a registered ID is left alone. 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 $appKey = "HKCU:\\Software\\Classes\\AppUserModelId\\$($payload.appId)" -$registered = Get-ItemProperty -Path $appKey -ErrorAction SilentlyContinue -$needsIcon = $payload.iconPath -and ($null -eq $registered -or $registered.IconUri -ne $payload.iconPath) -$staleIcon = -not $payload.iconPath -and $null -ne $registered -and $null -ne $registered.IconUri -if ($null -eq $registered -or $registered.DisplayName -ne $payload.displayName -or $needsIcon -or $staleIcon) { - New-Item -Path $appKey -Force | Out-Null - Set-ItemProperty -Path $appKey -Name DisplayName -Value $payload.displayName - if ($payload.iconPath) { - Set-ItemProperty -Path $appKey -Name IconUri -Value $payload.iconPath - } elseif ($staleIcon) { - Remove-ItemProperty -Path $appKey -Name IconUri - } +$registered = Get-ItemProperty -LiteralPath $appKey -ErrorAction SilentlyContinue +if ($null -eq $registered.DisplayName) { + if (-not (Test-Path -LiteralPath $appKey)) { New-Item -Path $appKey -Force | Out-Null } + if ($payload.iconPath) { Set-ItemProperty -LiteralPath $appKey -Name IconUri -Value $payload.iconPath } + Set-ItemProperty -LiteralPath $appKey -Name DisplayName -Value $payload.displayName } [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom, ContentType = WindowsRuntime] | Out-Null From f1e55b5636c9a0dd5ce89a93a71aa8b40d635ace Mon Sep 17 00:00:00 2001 From: mohak34 Date: Tue, 24 Nov 2026 23:05:19 +0000 Subject: [PATCH 6/9] fix(windows): fall back when PowerShell cannot be spawned, allow a slow start Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- SPEC.md | 2 +- src/notify-windows.ts | 26 ++++++++++++++++---------- src/notify.windows-reminder.test.ts | 2 +- 4 files changed, 19 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 73b9f9b..545a851 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,7 @@ Create `~/.config/opencode/opencode-notifier.json` with this example configurati - `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 registered under (default: `"opencode"`). Reminder toasts register it per-user under `HKCU\Software\Classes\AppUserModelId` with the display name `OpenCode` and, when Windows can read the icon file, its icon, because Windows drops reminder toasts for an unregistered ID. The plugin never removes that key -- `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 carry a Dismiss button and register the configured AppUserModelID automatically. Reminder toasts do not deliver click callbacks, so `focusOnClick` and `onClickCommand` do not run for them. If PowerShell cannot show the reminder within two seconds, the plugin falls back to a normal toast +- `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 carry a Dismiss button and register the configured AppUserModelID automatically. Reminder toasts do not deliver click callbacks, so `focusOnClick` and `onClickCommand` do not run for them. If PowerShell cannot show the reminder within five seconds, the plugin falls back to a normal toast ### Events diff --git a/SPEC.md b/SPEC.md index 5c415a0..5e3087b 100644 --- a/SPEC.md +++ b/SPEC.md @@ -59,7 +59,7 @@ Actionable popups are sent and handled on one persistent session D-Bus connectio ## Windows reminder notifications -`windows.scenario: "reminder"` sends the popup through Windows PowerShell and the WinRT toast API. Before showing it, the plugin registers the configured `windows.appID` under `HKCU\Software\Classes\AppUserModelId` with the display name `OpenCode` and, when the icon path is one Windows can read, the icon, because Windows silently drops reminder toasts for an unregistered AppUserModelID. 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 two seconds; when PowerShell is unavailable, the call fails, or it times out, delivery falls back to the regular transient toast. The default scenario reproduces the normal banner behavior. +`windows.scenario: "reminder"` sends the popup through Windows PowerShell and the WinRT toast API. Before showing it, the plugin registers the configured `windows.appID` under `HKCU\Software\Classes\AppUserModelId` with the display name `OpenCode` and, when the icon path is one Windows can read, the icon, because Windows silently drops reminder toasts for an unregistered AppUserModelID. 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. The default scenario reproduces the normal banner behavior. ## Release tracks diff --git a/src/notify-windows.ts b/src/notify-windows.ts index 4da0303..8042fbf 100644 --- a/src/notify-windows.ts +++ b/src/notify-windows.ts @@ -7,7 +7,7 @@ import type { WindowsScenario } from "./config" const REMINDER_ACTIONS = '' // Bounds how long a broken PowerShell can delay the fallback toast. -const POWERSHELL_TIMEOUT_MS = 2000 +const POWERSHELL_TIMEOUT_MS = 5000 // Windows shows this name in notification settings; the configurable appID // stays the identity. @@ -150,15 +150,21 @@ export function sendWindowsReminderNotification(request: WindowsToastRequest): P const command = request.wsl ? "powershell.exe" : "powershell" return new Promise((resolve) => { - execFile( - command, - ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], - { timeout: POWERSHELL_TIMEOUT_MS, windowsHide: true }, - (error) => { - if (error) debug(`reminder toast failed: ${String(error)}`) - resolve(!error) - } - ) + const finish = (error: unknown) => { + if (error) debug(`reminder toast failed: ${String(error)}`) + resolve(!error) + } + try { + execFile( + command, + ["-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.windows-reminder.test.ts b/src/notify.windows-reminder.test.ts index 27f67d5..1f25825 100644 --- a/src/notify.windows-reminder.test.ts +++ b/src/notify.windows-reminder.test.ts @@ -70,7 +70,7 @@ describe("deliverWindowsNotification", () => { expect(execCalls[0].args).toContain("-EncodedCommand") expect(execCalls[0].options.windowsHide).toBe(true) // A broken PowerShell must not delay the fallback toast for long. - expect(execCalls[0].options.timeout).toBeLessThanOrEqual(2000) + expect(execCalls[0].options.timeout).toBeLessThanOrEqual(5000) }) test("falls back to the regular toast when PowerShell fails", async () => { From 07e1248548f19b8ca2c4ab04de9fe83be883c6f9 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Tue, 24 Nov 2026 23:05:53 +0000 Subject: [PATCH 7/9] refactor(windows): keep the regular toast path untouched and test it on both hosts Co-Authored-By: Claude Opus 5.5 --- src/notify-windows.test.ts | 50 ++++------- src/notify-windows.ts | 98 +++++---------------- src/notify.ts | 45 +++++----- src/notify.windows-reminder.test.ts | 131 +++++++++++----------------- 4 files changed, 109 insertions(+), 215 deletions(-) diff --git a/src/notify-windows.test.ts b/src/notify-windows.test.ts index c567a16..713b763 100644 --- a/src/notify-windows.test.ts +++ b/src/notify-windows.test.ts @@ -18,45 +18,35 @@ describe("escapeXml", () => { }) }) -describe("toWindowsFileUri", () => { - test("converts a Windows drive path", () => { - expect(toWindowsFileUri("C:\\Users\\Me\\logo.png", false)).toBe("file:///C:/Users/Me/logo.png") - }) - - test("encodes spaces and keeps forward slashes", () => { - expect(toWindowsFileUri("C:/Program Files/logo.png", false)).toBe("file:///C:/Program%20Files/logo.png") +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(toWindowsFileUri("/mnt/c/Users/Me/logo.png", true)).toBe("file:///C:/Users/Me/logo.png") - }) - - test("returns null for a WSL filesystem path Windows cannot read", () => { - expect(toWindowsFileUri("/home/me/.cache/logo.png", true)).toBeNull() + expect(toWindowsIconPath("/mnt/c/Users/Me/logo.png", true)).toBe("C:/Users/Me/logo.png") }) - test("returns null when there is no icon", () => { - expect(toWindowsFileUri(undefined, false)).toBeNull() + 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("toWindowsIconPath", () => { - test("normalizes a Windows drive path for the AUMID registry entry", () => { - 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") +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("drops a WSL filesystem path Windows cannot read", () => { - expect(toWindowsIconPath("/home/me/.cache/logo.png", true)).toBeNull() + 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, "reminder") + const xml = buildWindowsToastXml("OpenCode", "Session finished", null) expect(xml).toContain('') expect(xml).toContain('') @@ -65,15 +55,8 @@ describe("buildWindowsToastXml", () => { expect(xml).not.toContain(" { - const xml = buildWindowsToastXml("OpenCode", "Session finished", null, "default") - - expect(xml).not.toContain("scenario=") - expect(xml).not.toContain("") - }) - test("includes an escaped app logo URI", () => { - const xml = buildWindowsToastXml("A & B", "done", "file:///C:/icon%20a&b.png", "reminder") + 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") @@ -83,8 +66,7 @@ describe("buildWindowsToastXml", () => { 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 }, - "reminder" + { title: "OpenCode", message: "done", iconPath: "C:\\icon.png", appID: "opencode", wsl: false } ) expect(payload.appId).toBe("opencode") diff --git a/src/notify-windows.ts b/src/notify-windows.ts index 8042fbf..8b3090d 100644 --- a/src/notify-windows.ts +++ b/src/notify-windows.ts @@ -1,6 +1,4 @@ import { execFile } from "child_process" -import { pathToFileURL } from "url" -import type { WindowsScenario } from "./config" // Windows ignores scenario="reminder" unless the toast contains at least one // background action, so the reminder carries an explicit dismiss button. @@ -45,76 +43,34 @@ export function escapeXml(value: string): string { } // Drive-letter and, on WSL, /mnt/ paths are the only ones Windows can -// read. Everything else is dropped instead of producing an unreadable URI. -function toWindowsDrivePath(value: string, wsl: boolean): string | null { - const normalized = value.replace(/\\/g, "/") - const drive = normalized.match(/^([A-Za-z]):\/(.*)$/) - if (drive) return `${drive[1].toUpperCase()}:/${drive[2]}` - - const wslDrive = normalized.match(/^\/mnt\/([a-z])\/(.*)$/i) - if (wsl && wslDrive) return `${wslDrive[1].toUpperCase()}:/${wslDrive[2]}` - - return null -} - -// Toast images need a Windows file URI. Unsupported paths drop the icon. -export function toWindowsFileUri(iconPath: string | undefined, wsl: boolean): string | null { - const value = iconPath?.trim() - if (!value) return null - - const drivePath = toWindowsDrivePath(value, wsl) - if (drivePath) { - const [drive, ...segments] = drivePath.split("/") - return `file:///${drive}/${segments.map(segment => encodeURIComponent(segment)).join("/")}` - } - - if (!wsl && value.replace(/\\/g, "/").startsWith("/")) { - try { - return pathToFileURL(value).href - } catch { - return null - } - } - - return null -} - -// The AUMID registration stores a Windows path, not a file URI. +// read. Everything else drops the icon. The AUMID registration takes this path. export function toWindowsIconPath(iconPath: string | undefined, wsl: boolean): string | null { - const value = iconPath?.trim() - if (!value) return null - - const drivePath = toWindowsDrivePath(value, wsl) - if (drivePath) return drivePath - - if (!wsl && value.replace(/\\/g, "/").startsWith("/")) return value + 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 +} - return 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, - scenario: WindowsScenario -): string { +export function buildWindowsToastXml(title: string, message: string, iconUri: string | null): string { const image = iconUri ? `` : "" - const scenarioAttribute = scenario === "default" ? "" : ` scenario="${scenario}"` - const actions = scenario === "reminder" ? REMINDER_ACTIONS : "" - return `${escapeXml(title)}${escapeXml(message)}${image}${actions}` + return `${escapeXml(title)}${escapeXml(message)}${image}${REMINDER_ACTIONS}` } -export function buildWindowsToastPayload( - request: WindowsToastRequest, - scenario: WindowsScenario -): WindowsToastPayload { +export function buildWindowsToastPayload(request: WindowsToastRequest): WindowsToastPayload { + const iconPath = toWindowsIconPath(request.iconPath, request.wsl) return { appId: request.appID, displayName: WINDOWS_TOAST_DISPLAY_NAME, - iconPath: toWindowsIconPath(request.iconPath, request.wsl), - xml: buildWindowsToastXml(request.title, request.message, toWindowsFileUri(request.iconPath, request.wsl), scenario), + iconPath, + xml: buildWindowsToastXml(request.title, request.message, toWindowsFileUri(iconPath)), } } @@ -143,20 +99,17 @@ $toast = [Windows.UI.Notifications.ToastNotification]::new($xml) // 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 { - const payload = buildWindowsToastPayload(request, "reminder") - const script = buildWindowsToastScript(payload) - const encoded = Buffer.from(script, "utf16le").toString("base64") - // WinRT toast classes are only available in Windows PowerShell 5.1, not pwsh. - const command = request.wsl ? "powershell.exe" : "powershell" - 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( - command, + request.wsl ? "powershell.exe" : "powershell", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], { timeout: POWERSHELL_TIMEOUT_MS, windowsHide: true }, finish @@ -167,14 +120,3 @@ export function sendWindowsReminderNotification(request: WindowsToastRequest): P } }) } - -// Reminders are opt-in and best-effort: the default scenario, a failed -// reminder and an unavailable PowerShell all end at the regular toast. -export async function deliverWindowsNotification( - scenario: WindowsScenario, - request: WindowsToastRequest, - sendDefault: () => Promise -): Promise { - if (scenario === "reminder" && await sendWindowsReminderNotification(request)) return - await sendDefault() -} diff --git a/src/notify.ts b/src/notify.ts index 8119eaa..cf78788 100644 --- a/src/notify.ts +++ b/src/notify.ts @@ -5,7 +5,7 @@ export { disposeLinuxNotifications } from "./notify-linux" import notifier from "node-notifier" import isWsl from "is-wsl" import { ensureSnoreToastExecutable } from "./snoretoast" -import { deliverWindowsNotification } from "./notify-windows" +import { sendWindowsReminderNotification } from "./notify-windows" import type { WindowsScenario } from "./config" const DEBOUNCE_MS = 1000 @@ -251,30 +251,27 @@ export async function sendNotification( } } - const sendDefaultNotification = (): Promise => { - 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". - const notificationOptions = (platform === "Linux" || platform.match(/BSD$/)) && !isWsl - ? { title, message, timeout, icon: iconPath, "app-name": "opencode" } - : buildWindowsNotificationOptions(title, message, timeout, iconPath, windowsAppID) - - platformNotifier.notify( - notificationOptions, - (_error, response, metadata) => { - if (onClick && (response === "activate" || metadata?.activationType === "default" || metadata?.activationType === "activated")) { - try { onClick() } catch {} - } - resolve() - } - ) - }) - } - - if (platform === "Windows_NT" || isWsl) { + if ((platform === "Windows_NT" || isWsl) && windowsScenario === "reminder") { const request = { title, message, iconPath, appID: windowsAppID ?? "opencode", wsl: isWsl } - return deliverWindowsNotification(windowsScenario, request, sendDefaultNotification) + // Fail open: when the reminder cannot be shown, fall through to the regular toast. + if (await sendWindowsReminderNotification(request)) return } - return sendDefaultNotification() + 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". + const notificationOptions = (platform === "Linux" || platform.match(/BSD$/)) && !isWsl + ? { title, message, timeout, icon: iconPath, "app-name": "opencode" } + : buildWindowsNotificationOptions(title, message, timeout, iconPath, windowsAppID) + + platformNotifier.notify( + notificationOptions, + (_error, response, metadata) => { + if (onClick && (response === "activate" || metadata?.activationType === "default" || metadata?.activationType === "activated")) { + try { onClick() } catch {} + } + resolve() + } + ) + }) } diff --git a/src/notify.windows-reminder.test.ts b/src/notify.windows-reminder.test.ts index 1f25825..4d71c9e 100644 --- a/src/notify.windows-reminder.test.ts +++ b/src/notify.windows-reminder.test.ts @@ -1,94 +1,67 @@ -import { beforeEach, describe, expect, mock, test } from "bun:test" +import { describe, expect, test } from "bun:test" +import { join } from "path" -interface ExecCall { - command: string - args: string[] - options: { timeout?: number; windowsHide?: boolean } -} - -const execCalls: ExecCall[] = [] -let execError: Error | null = null - -// Stub the PowerShell boundary so the reminder path runs for real without -// spawning a process. -mock.module("child_process", () => ({ - execFile( - command: string, - args: string[], - options: ExecCall["options"], - callback: (error: Error | null) => void - ) { - execCalls.push({ command, args, options }) - callback(execError) - return { kill() {} } - }, -})) - -const { deliverWindowsNotification } = await import("./notify-windows") +type PowerShell = "shown" | "failed" | "throws" -const request = { - title: "OpenCode", - message: "Session finished", - iconPath: "C:\\icon.png", - appID: "opencode", - wsl: false, +interface Delivery { + powershell: { command: string; args: string[]; options: { timeout: number; windowsHide: boolean } }[] + toasts: Record[] } -function fallback() { - let count = 0 - return { - count: () => count, - deliver: async () => { - count++ - }, - } +// 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()) } -beforeEach(() => { - execCalls.length = 0 - execError = null -}) - -describe("deliverWindowsNotification", () => { - test("shows the regular toast without starting PowerShell for the default scenario", async () => { - const defaultToast = fallback() - - await deliverWindowsNotification("default", request, defaultToast.deliver) +const REGULAR_TOAST = { title: "OpenCode", message: "Session finished", timeout: 5, icon: "C:\\icon.png", appName: "opencode" } - expect(execCalls).toHaveLength(0) - expect(defaultToast.count()).toBe(1) +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("replaces the regular toast once the reminder is shown", async () => { - const defaultToast = fallback() + test("a reminder replaces the regular toast", async () => { + const { powershell, toasts } = await deliver(host, "shown", "reminder") - await deliverWindowsNotification("reminder", request, defaultToast.deliver) - - expect(defaultToast.count()).toBe(0) - expect(execCalls).toHaveLength(1) - expect(execCalls[0].command).toBe("powershell") - expect(execCalls[0].args).toContain("-EncodedCommand") - expect(execCalls[0].options.windowsHide).toBe(true) - // A broken PowerShell must not delay the fallback toast for long. - expect(execCalls[0].options.timeout).toBeLessThanOrEqual(5000) - }) - - test("falls back to the regular toast when PowerShell fails", async () => { - execError = new Error("powershell is unavailable") - const defaultToast = fallback() - - await deliverWindowsNotification("reminder", request, defaultToast.deliver) - - expect(execCalls).toHaveLength(1) - expect(defaultToast.count()).toBe(1) + 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("launches powershell.exe under WSL", async () => { - const defaultToast = fallback() - - await deliverWindowsNotification("reminder", { ...request, wsl: true }, defaultToast.deliver) + 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(execCalls[0].command).toBe("powershell.exe") - expect(defaultToast.count()).toBe(0) + expect(powershell).toHaveLength(1) + expect(toasts).toEqual([REGULAR_TOAST]) }) }) From 10b9015e9ecbc822b8f600d47f87d4842799624e Mon Sep 17 00:00:00 2001 From: mohak34 Date: Tue, 24 Nov 2026 23:05:53 +0000 Subject: [PATCH 8/9] docs: describe reminder registration, WSL status and credit Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 +++++++--- README.md | 6 +++--- SPEC.md | 2 +- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b3036e..649db33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,12 +6,16 @@ All notable changes to this project will be documented in this file. ### Added -- `windows.scenario` option: set it to `"reminder"` to keep a Windows or WSL toast on screen until the user dismisses it. The default, `"default"`, keeps the current banner behavior. Reminder toasts register the configured AppUserModelID under `HKCU\Software\Classes\AppUserModelId`, with the display name `OpenCode` and the icon when Windows can read it, since Windows drops them for an unregistered ID. +- `windows.scenario: "reminder"` keeps a Windows or WSL toast on screen until you dismiss it (#154; issue #153). ### Upgrade notes -- Existing configurations are unchanged: an unset `windows.scenario` behaves as before. Reminder toasts do not run `focusOnClick` or `onClickCommand`. -- Reminder toasts write a per-user `HKCU` key that the plugin never removes; delete `HKCU\Software\Classes\AppUserModelId\` if you stop using the option. +- 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 diff --git a/README.md b/README.md index 545a851..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`. @@ -211,8 +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 registered under (default: `"opencode"`). Reminder toasts register it per-user under `HKCU\Software\Classes\AppUserModelId` with the display name `OpenCode` and, when Windows can read the icon file, its icon, because Windows drops reminder toasts for an unregistered ID. The plugin never removes that key -- `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 carry a Dismiss button and register the configured AppUserModelID automatically. Reminder toasts do not deliver click callbacks, so `focusOnClick` and `onClickCommand` do not run for them. If PowerShell cannot show the reminder within five seconds, the plugin falls back to a normal toast +- `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 diff --git a/SPEC.md b/SPEC.md index 5e3087b..08a8423 100644 --- a/SPEC.md +++ b/SPEC.md @@ -59,7 +59,7 @@ Actionable popups are sent and handled on one persistent session D-Bus connectio ## Windows reminder notifications -`windows.scenario: "reminder"` sends the popup through Windows PowerShell and the WinRT toast API. Before showing it, the plugin registers the configured `windows.appID` under `HKCU\Software\Classes\AppUserModelId` with the display name `OpenCode` and, when the icon path is one Windows can read, the icon, because Windows silently drops reminder toasts for an unregistered AppUserModelID. 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. The default scenario reproduces the normal banner behavior. +`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 From 0436bd01edd131cd6ebac0c6a8b87ba28edd1de4 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Tue, 24 Nov 2026 23:08:24 +0000 Subject: [PATCH 9/9] fix(windows): register the app ID without racing other terminals Co-Authored-By: Claude Opus 5.5 --- src/notify-windows.test.ts | 7 +++---- src/notify-windows.ts | 17 ++++++++--------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/notify-windows.test.ts b/src/notify-windows.test.ts index 713b763..67b9f20 100644 --- a/src/notify-windows.test.ts +++ b/src/notify-windows.test.ts @@ -91,10 +91,9 @@ describe("buildWindowsToastScript", () => { expect(encoded).toBeString() expect(JSON.parse(Buffer.from(encoded!, "base64").toString("utf8"))).toEqual(payload) expect(script).toContain("Software\\Classes\\AppUserModelId") - expect(script).toContain("if (-not (Test-Path -LiteralPath $appKey)) { New-Item") - expect(script).toContain("-Name IconUri") - expect(script.indexOf("-Name DisplayName")).toBeGreaterThan(script.indexOf("-Name IconUri")) - expect(script).not.toContain("Remove-ItemProperty") + 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 index 8b3090d..ac91b8e 100644 --- a/src/notify-windows.ts +++ b/src/notify-windows.ts @@ -74,20 +74,19 @@ export function buildWindowsToastPayload(request: WindowsToastRequest): WindowsT } } -// New-Item -Force deletes an existing key, and appID may belong to another app, -// so a registered ID is left alone. DisplayName is written last to mark a -// complete registration. +// 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 -$appKey = "HKCU:\\Software\\Classes\\AppUserModelId\\$($payload.appId)" -$registered = Get-ItemProperty -LiteralPath $appKey -ErrorAction SilentlyContinue -if ($null -eq $registered.DisplayName) { - if (-not (Test-Path -LiteralPath $appKey)) { New-Item -Path $appKey -Force | Out-Null } - if ($payload.iconPath) { Set-ItemProperty -LiteralPath $appKey -Name IconUri -Value $payload.iconPath } - Set-ItemProperty -LiteralPath $appKey -Name DisplayName -Value $payload.displayName +$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