Skip to content
Merged
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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\<appID>` 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
Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.<event>.command` controls event commands only; a click command is available for any enabled popup.

Expand Down
4 changes: 4 additions & 0 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
22 changes: 22 additions & 0 deletions src/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" })
Expand Down
5 changes: 5 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@ export interface LinuxConfig {
grouping: boolean
}

export type WindowsScenario = "default" | "reminder"

export interface WindowsConfig {
appID: string
scenario: WindowsScenario
}

export interface MessageContext {
Expand Down Expand Up @@ -157,6 +160,7 @@ const DEFAULT_CONFIG: NotifierConfig = {
},
windows: {
appID: "opencode",
scenario: "default",
},
minDuration: 0,
deferCompleteUntilChildrenIdle: false,
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")) {
Expand Down
100 changes: 100 additions & 0 deletions src/notify-windows.test.ts
Original file line number Diff line number Diff line change
@@ -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("&lt;&amp;&gt;&quot;&apos;")
})

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('<toast scenario="reminder">')
expect(xml).toContain('<action content="Dismiss" arguments="dismiss" activationType="background"/>')
expect(xml).toContain("<text>OpenCode</text>")
expect(xml).toContain("<text>Session finished</text>")
expect(xml).not.toContain("<image")
})

test("includes an escaped app logo URI", () => {
const xml = buildWindowsToastXml("A & B", "done", "file:///C:/icon%20a&b.png")

expect(xml).toContain('src="file:///C:/icon%20a&amp;b.png"')
expect(xml).toContain("<text>A &amp; B</text>")
})
})

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: '<toast scenario="reminder"/>',
}
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)")
})
})
121 changes: 121 additions & 0 deletions src/notify-windows.ts
Original file line number Diff line number Diff line change
@@ -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 = '<actions><action content="Dismiss" arguments="dismiss" activationType="background"/></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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;")
}

// Drive-letter and, on WSL, /mnt/<drive> 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
? `<image placement="appLogoOverride" hint-crop="none" src="${escapeXml(iconUri)}"/>`
: ""
return `<toast scenario="reminder"><visual><binding template="ToastGeneric"><text>${escapeXml(title)}</text><text>${escapeXml(message)}</text>${image}</binding></visual>${REMINDER_ACTIONS}</toast>`
}

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<boolean> {
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)
}
})
}
11 changes: 10 additions & 1 deletion src/notify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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<void> {
const now = Date.now()
if (lastNotificationTime[message] && now - lastNotificationTime[message] < DEBOUNCE_MS) {
Expand Down Expand Up @@ -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".
Expand Down
Loading