From a7dd7ce59df5d44561c7bce8823a47f27cb3b729 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:19:29 +0000 Subject: [PATCH 01/10] fix(v2): silent terminals no longer claim alerts from other terminals Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ SPEC.md | 2 +- src/delivery.ts | 37 +++++++++++++++++++++++-------------- src/notifier.ts | 13 ++++++++++--- src/v2.regression.test.ts | 9 ++++++++- 5 files changed, 46 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c867f37..f982e10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Fixed + +- On OpenCode 2, a terminal that would stay silent for an event (its channels off or muted by focus) no longer claims it, so another terminal on the same machine can still alert (issue #147). + ## [1.1.1] - 2026-10-24 ### Fixed diff --git a/SPEC.md b/SPEC.md index 7efa6a3..e1eb265 100644 --- a/SPEC.md +++ b/SPEC.md @@ -41,7 +41,7 @@ An event is delivered on a channel only if every check passes, in this order: 2. `complete` and `subagent_complete`: the session ran longer than `minDuration`. 3. `complete` with `deferCompleteUntilChildrenIdle`: a parent that goes idle with tracked child sessions running waits for them, at most `deferredCompleteTimeout`. Once none run, it waits a further 2 seconds for the parent to resume. A parent run cancels the alert, and the parent's next idle decides again, so a parent that resumes within those 2 seconds alerts once, after its final turn. A parent that resumes later alerts early and again after its final turn. A child that starts during those 2 seconds restarts the wait when it stops. An expired wait drops the alert. 4. `permission`: the request is still pending after a 300 ms grace (auto-approved requests stay silent), and the same request has not already alerted. -5. OpenCode 2 terminals: eligible clients with the session's family open in a tab or current route take priority over unrelated clients in the same project/workspace. They publish temporary presence with a one-second heartbeat; dead processes and presence older than five seconds are ignored. Among open-session owners, only the first to claim the event delivers. Without an owner, a client still claims after a brief grace. Unavailable UI state or registry fails open to the existing claim. Claims and presence live in a directory under the user's temp directory. If that directory is not a real directory owned by the user and closed to writes by others, or a claim cannot be written, every terminal delivers. The temp directory itself is trusted. +5. OpenCode 2 terminals: eligible clients with the session's family open in a tab or current route take priority over unrelated clients in the same project/workspace. They publish temporary presence with a one-second heartbeat; dead processes and presence older than five seconds are ignored. Among open-session owners, only the first to claim the event delivers. A terminal that would deliver nothing, because the event's channels are off, muted by focus, or below `minDuration`, does not claim it. Without an owner, a client still claims after a brief grace. Unavailable UI state or registry fails open to the existing claim. Claims and presence live in a directory under the user's temp directory. If that directory is not a real directory owned by the user and closed to writes by others, or a claim cannot be written, every terminal delivers. The temp directory itself is trusted. 6. Focus: with `suppressWhenFocused`, skip when the OpenCode terminal (and its pane, under tmux, WezTerm or Zellij) is in front. `true` skips every channel; a list of channels skips only those. Unknown focus means not focused. 7. Sound: at most one sound per second across all events. diff --git a/src/delivery.ts b/src/delivery.ts index a9e0049..f146d94 100644 --- a/src/delivery.ts +++ b/src/delivery.ts @@ -88,6 +88,26 @@ export function shouldResolveSessionContextForEvent(config: NotifierConfig, even .some(value => value.includes("{agentName}") || value.includes("{sessionTitle}"))) } +// Channels focus suppression mutes right now. Focus is only queried when some channel cares about it. +export function mutedChannels(config: NotifierConfig): Set { + const focusChannels = config.suppressWhenFocused === true ? CHANNELS : config.suppressWhenFocused || [] + return new Set(focusChannels.length > 0 && isTerminalFocused() ? focusChannels : []) +} + +function isTooShort(config: NotifierConfig, eventType: EventType, elapsedSeconds?: number | null): boolean { + return (eventType === "complete" || eventType === "subagent_complete") && + typeof elapsedSeconds === "number" && + Number.isFinite(elapsedSeconds) && + elapsedSeconds < config.minDuration +} + +// Whether handleEvent would deliver at least one channel. V2 terminals check this before claiming +// an event, so a terminal that stays silent never blocks another terminal that would alert. +export function deliversAny(config: NotifierConfig, eventType: EventType, muted: Set, elapsedSeconds?: number | null): boolean { + if (isTooShort(config, eventType, elapsedSeconds)) return false + return CHANNELS.some(channel => config.events[eventType][channel] && !muted.has(channel) && (channel !== "command" || config.command.enabled)) +} + export async function handleEvent( config: NotifierConfig, eventType: EventType, @@ -96,21 +116,10 @@ export async function handleEvent( sessionTitle?: string | null, sessionID?: string | null, agentName?: string | null, - focusSession?: (sessionID: string) => void + focusSession?: (sessionID: string) => void, + muted: Set = mutedChannels(config) ): Promise { - // Focus is only queried when some channel cares about it. - const focusChannels = config.suppressWhenFocused === true ? CHANNELS : config.suppressWhenFocused || [] - const muted = new Set(focusChannels.length > 0 && isTerminalFocused() ? focusChannels : []) - if (muted.size === CHANNELS.length) { - return - } - - if ( - (eventType === "complete" || eventType === "subagent_complete") && - typeof elapsedSeconds === "number" && - Number.isFinite(elapsedSeconds) && - elapsedSeconds < config.minDuration - ) { + if (muted.size === CHANNELS.length || isTooShort(config, eventType, elapsedSeconds)) { return } diff --git a/src/notifier.ts b/src/notifier.ts index 5012072..fd5f7dd 100644 --- a/src/notifier.ts +++ b/src/notifier.ts @@ -1,8 +1,9 @@ import { basename } from "path" import { loadConfig } from "./config" -import type { EventType, NotifierConfig } from "./config" +import type { Channel, EventType, NotifierConfig } from "./config" import { claimDelivery } from "./claim" -import { extractAgentNameFromSessionTitle, handleEvent, shouldResolveSessionContextForEvent } from "./delivery" +import { deliversAny, extractAgentNameFromSessionTitle, handleEvent, mutedChannels, shouldResolveSessionContextForEvent } from "./delivery" +import { debugFocusState as debug } from "./focus" import { shouldSuppressPermissionAlert, prunePermissionAlertState } from "./permission-dedupe" // Allow immediate auto-approval to settle before checking the pending list. @@ -116,14 +117,20 @@ export function createNotifier(access: SessionAccess, directory: string, deliver agentName = info.agentName ?? null } if (disposed || !valid()) return + let muted: Set | undefined if (key && delivery === "terminal") { + muted = mutedChannels(current) + if (!deliversAny(current, event, muted, elapsed)) { + debug(`${event}: nothing to deliver in this terminal, leaving the event to other terminals`) + return + } const identity = `${directory}\0${key}` if (!(hooks.claim ? await hooks.claim(identity, sessionID, () => !disposed && valid()) : claimDelivery(identity))) return } if (disposed || !valid()) return commit?.() const project = directory ? (current.showFullPath ? directory : basename(directory)) : null - await handleEvent(current, event, project, elapsed, sessionTitle, sessionID, agentName ?? extractAgentNameFromSessionTitle(sessionTitle), hooks.focusSession) + await handleEvent(current, event, project, elapsed, sessionTitle, sessionID, agentName ?? extractAgentNameFromSessionTitle(sessionTitle), hooks.focusSession, muted) } function track(sessionID: string, parentID?: string | null) { diff --git a/src/v2.regression.test.ts b/src/v2.regression.test.ts index 4cd0712..6ca0b7a 100644 --- a/src/v2.regression.test.ts +++ b/src/v2.regression.test.ts @@ -36,12 +36,13 @@ async function exercise(events: OpenCodeEvent[], options: { agentName?: string sessionLocation?: { directory: string; workspaceID?: string } onGet?: () => void + silent?: boolean } = {}) { writeFileSync(configPath, JSON.stringify({ suppressWhenFocused: false, sound: false, bell: false, notificationSystem: "ghostty", minDuration: options.minDuration ?? 0, command: { enabled: options.command ?? false, path: process.execPath, args: [commandScript, commandLog, "{event}"], minDuration: options.commandMinDuration ?? 0 }, - events: { session_started: false, client_connected: false, user_message: { notification: true }, complete: { notification: true }, subagent_complete: options.agentName ? { notification: true } : false }, + events: { session_started: false, client_connected: false, user_message: { notification: true }, complete: options.silent ? false : { notification: true }, subagent_complete: options.agentName ? { notification: true } : false }, messages: { user_message: "PROBE_USER {turn}", complete: "PROBE_DONE {turn}", error: "PROBE_ERROR {turn}", question: "PROBE_QUESTION {turn}", subagent_complete: "PROBE_AGENT {agentName} {turn}" }, })) const oldConfig = process.env.OPENCODE_NOTIFIER_CONFIG_PATH @@ -114,6 +115,12 @@ test("terminals on one machine alert once for an event they both receive", async expect((await exercise([event("session.execution.succeeded", { sessionID: "shared" })])).length).toBe(1) }) +test("a terminal with nothing to deliver leaves the event to another terminal", async () => { + const finished = event("session.execution.succeeded", { sessionID: "silent-first" }) + expect((await exercise([finished], { silent: true })).length).toBe(0) + expect((await exercise([finished])).length).toBe(1) +}) + test("a new run clears error suppression", async () => { const output = await exercise([ event("session.execution.failed", { sessionID: "retry", error: {} }), From 0616ed816dd8c2fbce3422d1232e930dbf8ce1c6 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:20:03 +0000 Subject: [PATCH 02/10] fix(linux): tmux or Zellij panes over SSH no longer mute alerts Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++++ README.md | 2 +- SPEC.md | 2 +- src/focus.test.ts | 11 +++++++++++ src/focus.ts | 9 +++++++-- 5 files changed, 25 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f982e10..5a2d34c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ All notable changes to this project will be documented in this file. ### Fixed - On OpenCode 2, a terminal that would stay silent for an event (its channels off or muted by focus) no longer claims it, so another terminal on the same machine can still alert (issue #147). +- Over SSH on Linux, an active tmux or Zellij pane no longer mutes alerts when no desktop window can be checked, so bells reach a terminal tab that is in the background (issue #147). + +### Upgrade notes + +- Local sessions and SSH sessions with a detected desktop window keep the same focus behavior. Over SSH inside tmux or Zellij, alerts now fire even while you are looking at the pane. ## [1.1.1] - 2026-10-24 diff --git a/README.md b/README.md index e6bab26..24e1d04 100644 --- a/README.md +++ b/README.md @@ -459,7 +459,7 @@ tmux source-file ~/.tmux.conf ## Focus detection -When `suppressWhenFocused` is `true` (the default), popups, sounds, bells, and V1 event commands are skipped when the terminal running OpenCode is focused. Supported terminal and multiplexer pane checks also apply. V2 server event commands run independently of local focus. +When `suppressWhenFocused` is `true` (the default), popups, sounds, bells, and V1 event commands are skipped when the terminal running OpenCode is focused. Supported terminal and multiplexer pane checks also apply. Over SSH on Linux, when no desktop window can be checked, an active tmux or Zellij pane does not count as focused, because it cannot tell whether your local terminal is in front; alerts are delivered. V2 server event commands run independently of local focus. On macOS, focus detection reads the app name from either the `lsappinfo` name=value output or its multiline application report. If no valid name can be extracted, it falls back to AppleScript (`System Events`). Failed queries keep notifications enabled. diff --git a/SPEC.md b/SPEC.md index e1eb265..c2acac5 100644 --- a/SPEC.md +++ b/SPEC.md @@ -42,7 +42,7 @@ An event is delivered on a channel only if every check passes, in this order: 3. `complete` with `deferCompleteUntilChildrenIdle`: a parent that goes idle with tracked child sessions running waits for them, at most `deferredCompleteTimeout`. Once none run, it waits a further 2 seconds for the parent to resume. A parent run cancels the alert, and the parent's next idle decides again, so a parent that resumes within those 2 seconds alerts once, after its final turn. A parent that resumes later alerts early and again after its final turn. A child that starts during those 2 seconds restarts the wait when it stops. An expired wait drops the alert. 4. `permission`: the request is still pending after a 300 ms grace (auto-approved requests stay silent), and the same request has not already alerted. 5. OpenCode 2 terminals: eligible clients with the session's family open in a tab or current route take priority over unrelated clients in the same project/workspace. They publish temporary presence with a one-second heartbeat; dead processes and presence older than five seconds are ignored. Among open-session owners, only the first to claim the event delivers. A terminal that would deliver nothing, because the event's channels are off, muted by focus, or below `minDuration`, does not claim it. Without an owner, a client still claims after a brief grace. Unavailable UI state or registry fails open to the existing claim. Claims and presence live in a directory under the user's temp directory. If that directory is not a real directory owned by the user and closed to writes by others, or a claim cannot be written, every terminal delivers. The temp directory itself is trusted. -6. Focus: with `suppressWhenFocused`, skip when the OpenCode terminal (and its pane, under tmux, WezTerm or Zellij) is in front. `true` skips every channel; a list of channels skips only those. Unknown focus means not focused. +6. Focus: with `suppressWhenFocused`, skip when the OpenCode terminal (and its pane, under tmux, WezTerm or Zellij) is in front. `true` skips every channel; a list of channels skips only those. Unknown focus means not focused. On Linux over SSH (`SSH_CONNECTION` or `SSH_TTY` set) with no captured desktop window, tmux and Zellij pane state is not focus evidence. 7. Sound: at most one sound per second across all events. ## Guarantees diff --git a/src/focus.test.ts b/src/focus.test.ts index 9777228..7ab4bc0 100644 --- a/src/focus.test.ts +++ b/src/focus.test.ts @@ -129,6 +129,17 @@ describe("isLinuxTerminalFocused", () => { })).toBe(false) }) + test("over SSH without a window id, an active tmux or Zellij pane does not count as focus", () => { + expect(isLinuxTerminalFocused({ + cachedWindowId: null, currentWindowId: null, wezTermPaneActive: true, + tmuxPaneActive: true, ssh: true, + })).toBe(false) + expect(isLinuxTerminalFocused({ + cachedWindowId: null, currentWindowId: null, wezTermPaneActive: true, + tmuxPaneActive: null, zellijPaneActive: true, ssh: true, + })).toBe(false) + }) + test("falls back to tmux pane state when window id is unavailable", () => { expect( isLinuxTerminalFocused({ diff --git a/src/focus.ts b/src/focus.ts index b384b98..64a1141 100644 --- a/src/focus.ts +++ b/src/focus.ts @@ -569,11 +569,14 @@ export function isLinuxTerminalFocused(params: { wezTermPaneActive: boolean tmuxPaneActive: boolean | null zellijPaneActive?: boolean | null + // Over SSH, pane state on this host says nothing about whether the local terminal is in front. + ssh?: boolean }): boolean { - const { cachedWindowId, currentWindowId, wezTermPaneActive, tmuxPaneActive, zellijPaneActive } = params + const { cachedWindowId, currentWindowId, wezTermPaneActive, tmuxPaneActive, zellijPaneActive, ssh } = params if (zellijPaneActive === false) return false if (!cachedWindowId) { + if (ssh) return false if (!wezTermPaneActive) return false if (tmuxPaneActive !== null) return tmuxPaneActive if (zellijPaneActive != null) return zellijPaneActive @@ -627,6 +630,7 @@ export function isTerminalFocused(): boolean { debugFocusState("linux focus: KDE originating window is unknown, notifying") return false } + const ssh = !!(process.env.SSH_CONNECTION || process.env.SSH_TTY) const tmuxPaneActive = process.env.TMUX ? isTmuxPaneActive() : null const currentWindowId = getActiveWindowId() const focused = isLinuxTerminalFocused({ @@ -635,9 +639,10 @@ export function isTerminalFocused(): boolean { wezTermPaneActive: isWezTermPaneActive(), tmuxPaneActive, zellijPaneActive, + ssh, }) debugFocusState( - `linux focus: backend=${getLinuxFocusBackendName()} session=${process.env.XDG_SESSION_TYPE ?? "?"} desktop=${process.env.XDG_CURRENT_DESKTOP ?? process.env.DESKTOP_SESSION ?? "?"} cached=${cachedWindowId ?? "null"} current=${currentWindowId ?? "null"} tmux=${String(tmuxPaneActive)} zellij=${String(zellijPaneActive)} focused=${focused}` + `linux focus: backend=${getLinuxFocusBackendName()} session=${process.env.XDG_SESSION_TYPE ?? "?"} desktop=${process.env.XDG_CURRENT_DESKTOP ?? process.env.DESKTOP_SESSION ?? "?"} cached=${cachedWindowId ?? "null"} current=${currentWindowId ?? "null"} tmux=${String(tmuxPaneActive)} zellij=${String(zellijPaneActive)} ssh=${ssh} focused=${focused}` ) return focused } catch { From 7f8439af12c03658bcd5678f671ae7552a376543 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:20:09 +0000 Subject: [PATCH 03/10] docs: fix the local plugin recipe for OpenCode 2 Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d3731f4..70ee8d3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,7 +17,22 @@ bun run typecheck bun run build ``` -To try your build in OpenCode, point a scratch project's `opencode.json` at your local checkout and use a throwaway config through `OPENCODE_NOTIFIER_CONFIG_PATH`. +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. Make a shim directory that re-exports the build and list it under `plugins`: + + ```bash + mkdir -p /tmp/notifier-shim + echo 'export { default } from "/path/to/opencode-notifier/dist/index.js"' > /tmp/notifier-shim/index.js + echo 'export { default } from "/path/to/opencode-notifier/dist/tui.js"' > /tmp/notifier-shim/tui.js + ``` + + ```json + { "plugins": ["file:///tmp/notifier-shim"] } + ``` + + Run `opencode --standalone` so the test uses a private server instead of your background service. ## Rules for a PR From 50d2cda8a2e385a5650eccb24a294ae7ef32f3db Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:26:08 +0000 Subject: [PATCH 04/10] perf(v2): skip the focus probe when an event has no channel enabled Co-Authored-By: Claude Opus 5.5 --- src/notifier.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/notifier.ts b/src/notifier.ts index fd5f7dd..7992436 100644 --- a/src/notifier.ts +++ b/src/notifier.ts @@ -119,8 +119,9 @@ export function createNotifier(access: SessionAccess, directory: string, deliver if (disposed || !valid()) return let muted: Set | undefined if (key && delivery === "terminal") { - muted = mutedChannels(current) - if (!deliversAny(current, event, muted, elapsed)) { + // Focus is probed only when some channel would deliver at all. + muted = deliversAny(current, event, new Set(), elapsed) ? mutedChannels(current) : undefined + if (!muted || !deliversAny(current, event, muted, elapsed)) { debug(`${event}: nothing to deliver in this terminal, leaving the event to other terminals`) return } From dd14aa3347f40ae5c05baec6c2b533564adcdd33 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:26:19 +0000 Subject: [PATCH 05/10] docs: private shim dir in the recipe, SSH note in tmux and Zellij sections Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 13 ++++++------- README.md | 4 ++-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 70ee8d3..a47051b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,17 +20,16 @@ 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. Make a shim directory that re-exports the build and list it under `plugins`: +- 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: ```bash - mkdir -p /tmp/notifier-shim - echo 'export { default } from "/path/to/opencode-notifier/dist/index.js"' > /tmp/notifier-shim/index.js - echo 'export { default } from "/path/to/opencode-notifier/dist/tui.js"' > /tmp/notifier-shim/tui.js + 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:///tmp/notifier-shim"] } - ``` + 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. diff --git a/README.md b/README.md index 24e1d04..507c080 100644 --- a/README.md +++ b/README.md @@ -527,11 +527,11 @@ Work from third-party delegation plugins without native child-session events, or **Unsupported compositors**: Wayland has no standard protocol for querying the focused window. Each compositor has its own IPC. Without a window backend, supported pane checks provide a best-effort fallback. If neither can determine focus, notifications are allowed. -**tmux/screen**: When running inside tmux, focus detection uses tmux pane state (`session_attached`, `window_active`, `pane_active`) via `tmux display-message`. This keeps suppression accurate when switching panes/windows/sessions. On Linux setups where window focus cannot be detected at all, tmux pane state is also used as a best-effort fallback. GNU Screen has no pane detection, but ordinary terminal-window focus detection can still suppress notifications. +**tmux/screen**: When running inside tmux, focus detection uses tmux pane state (`session_attached`, `window_active`, `pane_active`) via `tmux display-message`. This keeps suppression accurate when switching panes/windows/sessions. On Linux setups where window focus cannot be detected at all, tmux pane state is also used as a best-effort fallback, except over SSH, where alerts are always delivered. GNU Screen has no pane detection, but ordinary terminal-window focus detection can still suppress notifications. **WezTerm panes**: When running in WezTerm with `WEZTERM_PANE` set, focus suppression is pane-aware via `wezterm cli list-clients --format json`. This means notifications are shown when you switch to a different WezTerm pane/tab. -**Zellij panes**: With `ZELLIJ_SESSION_NAME` and `ZELLIJ_PANE_ID` set, suppression also checks `zellij --session action list-clients`. Switching away from the OpenCode pane or tab allows notifications even when the terminal window stays focused. With multiple clients, the pane counts as focused if any attached client focuses it. A missing tool, failed query, or detached session allows notifications. On Linux without window detection, pane focus is a best-effort fallback, as with tmux. +**Zellij panes**: With `ZELLIJ_SESSION_NAME` and `ZELLIJ_PANE_ID` set, suppression also checks `zellij --session action list-clients`. Switching away from the OpenCode pane or tab allows notifications even when the terminal window stays focused. With multiple clients, the pane counts as focused if any attached client focuses it. A missing tool, failed query, or detached session allows notifications. On Linux without window detection, pane focus is a best-effort fallback, as with tmux, and is ignored over SSH. **Fail-open design**: If window and supported pane checks cannot determine focus, focus suppression allows notifications. Other settings such as event disabling and minimum duration still apply. From a8a3fa852d2b9447da9babe78ab3bbe61cbf40bc Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:30:03 +0000 Subject: [PATCH 06/10] fix(v2): claim on config alone and keep focus probes in the winning terminal Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- SPEC.md | 2 +- src/delivery.ts | 20 ++++++++++---------- src/notifier.ts | 13 +++++-------- 4 files changed, 17 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a2d34c..1dfb381 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project will be documented in this file. ### Fixed -- On OpenCode 2, a terminal that would stay silent for an event (its channels off or muted by focus) no longer claims it, so another terminal on the same machine can still alert (issue #147). +- On OpenCode 2, a terminal whose config turns off every channel for an event no longer claims it, so another terminal on the same machine can still alert (issue #147). - Over SSH on Linux, an active tmux or Zellij pane no longer mutes alerts when no desktop window can be checked, so bells reach a terminal tab that is in the background (issue #147). ### Upgrade notes diff --git a/SPEC.md b/SPEC.md index c2acac5..fe27a55 100644 --- a/SPEC.md +++ b/SPEC.md @@ -41,7 +41,7 @@ An event is delivered on a channel only if every check passes, in this order: 2. `complete` and `subagent_complete`: the session ran longer than `minDuration`. 3. `complete` with `deferCompleteUntilChildrenIdle`: a parent that goes idle with tracked child sessions running waits for them, at most `deferredCompleteTimeout`. Once none run, it waits a further 2 seconds for the parent to resume. A parent run cancels the alert, and the parent's next idle decides again, so a parent that resumes within those 2 seconds alerts once, after its final turn. A parent that resumes later alerts early and again after its final turn. A child that starts during those 2 seconds restarts the wait when it stops. An expired wait drops the alert. 4. `permission`: the request is still pending after a 300 ms grace (auto-approved requests stay silent), and the same request has not already alerted. -5. OpenCode 2 terminals: eligible clients with the session's family open in a tab or current route take priority over unrelated clients in the same project/workspace. They publish temporary presence with a one-second heartbeat; dead processes and presence older than five seconds are ignored. Among open-session owners, only the first to claim the event delivers. A terminal that would deliver nothing, because the event's channels are off, muted by focus, or below `minDuration`, does not claim it. Without an owner, a client still claims after a brief grace. Unavailable UI state or registry fails open to the existing claim. Claims and presence live in a directory under the user's temp directory. If that directory is not a real directory owned by the user and closed to writes by others, or a claim cannot be written, every terminal delivers. The temp directory itself is trusted. +5. OpenCode 2 terminals: eligible clients with the session's family open in a tab or current route take priority over unrelated clients in the same project/workspace. They publish temporary presence with a one-second heartbeat; dead processes and presence older than five seconds are ignored. Among open-session owners, only the first to claim the event delivers. A terminal whose config enables no channel for the event, or whose session is below `minDuration`, does not claim it. Focus is checked after the claim, so a focused winner stays silent and other terminals do not alert. Without an owner, a client still claims after a brief grace. Unavailable UI state or registry fails open to the existing claim. Claims and presence live in a directory under the user's temp directory. If that directory is not a real directory owned by the user and closed to writes by others, or a claim cannot be written, every terminal delivers. The temp directory itself is trusted. 6. Focus: with `suppressWhenFocused`, skip when the OpenCode terminal (and its pane, under tmux, WezTerm or Zellij) is in front. `true` skips every channel; a list of channels skips only those. Unknown focus means not focused. On Linux over SSH (`SSH_CONNECTION` or `SSH_TTY` set) with no captured desktop window, tmux and Zellij pane state is not focus evidence. 7. Sound: at most one sound per second across all events. diff --git a/src/delivery.ts b/src/delivery.ts index f146d94..c39382d 100644 --- a/src/delivery.ts +++ b/src/delivery.ts @@ -89,7 +89,7 @@ export function shouldResolveSessionContextForEvent(config: NotifierConfig, even } // Channels focus suppression mutes right now. Focus is only queried when some channel cares about it. -export function mutedChannels(config: NotifierConfig): Set { +function mutedChannels(config: NotifierConfig): Set { const focusChannels = config.suppressWhenFocused === true ? CHANNELS : config.suppressWhenFocused || [] return new Set(focusChannels.length > 0 && isTerminalFocused() ? focusChannels : []) } @@ -101,11 +101,12 @@ function isTooShort(config: NotifierConfig, eventType: EventType, elapsedSeconds elapsedSeconds < config.minDuration } -// Whether handleEvent would deliver at least one channel. V2 terminals check this before claiming -// an event, so a terminal that stays silent never blocks another terminal that would alert. -export function deliversAny(config: NotifierConfig, eventType: EventType, muted: Set, elapsedSeconds?: number | null): boolean { +// Whether the config enables any channel for this event. V2 terminals check this before claiming +// an event, so a terminal with every channel off never blocks one that would alert. Focus is checked +// after the claim: probes can block for seconds, so only the winning terminal runs them. +export function deliversAny(config: NotifierConfig, eventType: EventType, elapsedSeconds?: number | null): boolean { if (isTooShort(config, eventType, elapsedSeconds)) return false - return CHANNELS.some(channel => config.events[eventType][channel] && !muted.has(channel) && (channel !== "command" || config.command.enabled)) + return CHANNELS.some(channel => config.events[eventType][channel] && (channel !== "command" || config.command.enabled)) } export async function handleEvent( @@ -116,12 +117,11 @@ export async function handleEvent( sessionTitle?: string | null, sessionID?: string | null, agentName?: string | null, - focusSession?: (sessionID: string) => void, - muted: Set = mutedChannels(config) + focusSession?: (sessionID: string) => void ): Promise { - if (muted.size === CHANNELS.length || isTooShort(config, eventType, elapsedSeconds)) { - return - } + if (isTooShort(config, eventType, elapsedSeconds)) return + const muted = mutedChannels(config) + if (muted.size === CHANNELS.length) return const promises: Promise[] = [] diff --git a/src/notifier.ts b/src/notifier.ts index 7992436..d8c65bb 100644 --- a/src/notifier.ts +++ b/src/notifier.ts @@ -1,8 +1,8 @@ import { basename } from "path" import { loadConfig } from "./config" -import type { Channel, EventType, NotifierConfig } from "./config" +import type { EventType, NotifierConfig } from "./config" import { claimDelivery } from "./claim" -import { deliversAny, extractAgentNameFromSessionTitle, handleEvent, mutedChannels, shouldResolveSessionContextForEvent } from "./delivery" +import { deliversAny, extractAgentNameFromSessionTitle, handleEvent, shouldResolveSessionContextForEvent } from "./delivery" import { debugFocusState as debug } from "./focus" import { shouldSuppressPermissionAlert, prunePermissionAlertState } from "./permission-dedupe" @@ -117,12 +117,9 @@ export function createNotifier(access: SessionAccess, directory: string, deliver agentName = info.agentName ?? null } if (disposed || !valid()) return - let muted: Set | undefined if (key && delivery === "terminal") { - // Focus is probed only when some channel would deliver at all. - muted = deliversAny(current, event, new Set(), elapsed) ? mutedChannels(current) : undefined - if (!muted || !deliversAny(current, event, muted, elapsed)) { - debug(`${event}: nothing to deliver in this terminal, leaving the event to other terminals`) + if (!deliversAny(current, event, elapsed)) { + debug(`${event}: no channel enabled in this terminal, leaving the event to other terminals`) return } const identity = `${directory}\0${key}` @@ -131,7 +128,7 @@ export function createNotifier(access: SessionAccess, directory: string, deliver if (disposed || !valid()) return commit?.() const project = directory ? (current.showFullPath ? directory : basename(directory)) : null - await handleEvent(current, event, project, elapsed, sessionTitle, sessionID, agentName ?? extractAgentNameFromSessionTitle(sessionTitle), hooks.focusSession, muted) + await handleEvent(current, event, project, elapsed, sessionTitle, sessionID, agentName ?? extractAgentNameFromSessionTitle(sessionTitle), hooks.focusSession) } function track(sessionID: string, parentID?: string | null) { From 55901c0efdc7157ef99def604efe7ad3621eaddf Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:30:09 +0000 Subject: [PATCH 07/10] docs: stop the shim recipe if mktemp fails Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a47051b..6b39b26 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,10 +23,10 @@ To try your build in OpenCode, use a throwaway notifier config through `OPENCODE - 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: ```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" + 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" ``` List the printed URL under `plugins`: `{ "plugins": ["file:///tmp/tmp.XXXXXX"] }`. From c5faea7293f602040dc8cce5b02bfb2461de5822 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:34:17 +0000 Subject: [PATCH 08/10] fix(v2): short sessions claim as before so deferred completions clear Co-Authored-By: Claude Opus 5.5 --- SPEC.md | 2 +- src/delivery.ts | 34 ++++++++++++++++------------------ src/notifier.ts | 2 +- 3 files changed, 18 insertions(+), 20 deletions(-) diff --git a/SPEC.md b/SPEC.md index fe27a55..09c5aae 100644 --- a/SPEC.md +++ b/SPEC.md @@ -41,7 +41,7 @@ An event is delivered on a channel only if every check passes, in this order: 2. `complete` and `subagent_complete`: the session ran longer than `minDuration`. 3. `complete` with `deferCompleteUntilChildrenIdle`: a parent that goes idle with tracked child sessions running waits for them, at most `deferredCompleteTimeout`. Once none run, it waits a further 2 seconds for the parent to resume. A parent run cancels the alert, and the parent's next idle decides again, so a parent that resumes within those 2 seconds alerts once, after its final turn. A parent that resumes later alerts early and again after its final turn. A child that starts during those 2 seconds restarts the wait when it stops. An expired wait drops the alert. 4. `permission`: the request is still pending after a 300 ms grace (auto-approved requests stay silent), and the same request has not already alerted. -5. OpenCode 2 terminals: eligible clients with the session's family open in a tab or current route take priority over unrelated clients in the same project/workspace. They publish temporary presence with a one-second heartbeat; dead processes and presence older than five seconds are ignored. Among open-session owners, only the first to claim the event delivers. A terminal whose config enables no channel for the event, or whose session is below `minDuration`, does not claim it. Focus is checked after the claim, so a focused winner stays silent and other terminals do not alert. Without an owner, a client still claims after a brief grace. Unavailable UI state or registry fails open to the existing claim. Claims and presence live in a directory under the user's temp directory. If that directory is not a real directory owned by the user and closed to writes by others, or a claim cannot be written, every terminal delivers. The temp directory itself is trusted. +5. OpenCode 2 terminals: eligible clients with the session's family open in a tab or current route take priority over unrelated clients in the same project/workspace. They publish temporary presence with a one-second heartbeat; dead processes and presence older than five seconds are ignored. Among open-session owners, only the first to claim the event delivers. A terminal whose config enables no channel for the event does not claim it. Focus is checked after the claim, so a focused winner stays silent and other terminals do not alert. Without an owner, a client still claims after a brief grace. Unavailable UI state or registry fails open to the existing claim. Claims and presence live in a directory under the user's temp directory. If that directory is not a real directory owned by the user and closed to writes by others, or a claim cannot be written, every terminal delivers. The temp directory itself is trusted. 6. Focus: with `suppressWhenFocused`, skip when the OpenCode terminal (and its pane, under tmux, WezTerm or Zellij) is in front. `true` skips every channel; a list of channels skips only those. Unknown focus means not focused. On Linux over SSH (`SSH_CONNECTION` or `SSH_TTY` set) with no captured desktop window, tmux and Zellij pane state is not focus evidence. 7. Sound: at most one sound per second across all events. diff --git a/src/delivery.ts b/src/delivery.ts index c39382d..b155401 100644 --- a/src/delivery.ts +++ b/src/delivery.ts @@ -88,24 +88,10 @@ export function shouldResolveSessionContextForEvent(config: NotifierConfig, even .some(value => value.includes("{agentName}") || value.includes("{sessionTitle}"))) } -// Channels focus suppression mutes right now. Focus is only queried when some channel cares about it. -function mutedChannels(config: NotifierConfig): Set { - const focusChannels = config.suppressWhenFocused === true ? CHANNELS : config.suppressWhenFocused || [] - return new Set(focusChannels.length > 0 && isTerminalFocused() ? focusChannels : []) -} - -function isTooShort(config: NotifierConfig, eventType: EventType, elapsedSeconds?: number | null): boolean { - return (eventType === "complete" || eventType === "subagent_complete") && - typeof elapsedSeconds === "number" && - Number.isFinite(elapsedSeconds) && - elapsedSeconds < config.minDuration -} - // Whether the config enables any channel for this event. V2 terminals check this before claiming // an event, so a terminal with every channel off never blocks one that would alert. Focus is checked // after the claim: probes can block for seconds, so only the winning terminal runs them. -export function deliversAny(config: NotifierConfig, eventType: EventType, elapsedSeconds?: number | null): boolean { - if (isTooShort(config, eventType, elapsedSeconds)) return false +export function deliversAny(config: NotifierConfig, eventType: EventType): boolean { return CHANNELS.some(channel => config.events[eventType][channel] && (channel !== "command" || config.command.enabled)) } @@ -119,9 +105,21 @@ export async function handleEvent( agentName?: string | null, focusSession?: (sessionID: string) => void ): Promise { - if (isTooShort(config, eventType, elapsedSeconds)) return - const muted = mutedChannels(config) - if (muted.size === CHANNELS.length) return + // Focus is only queried when some channel cares about it. + const focusChannels = config.suppressWhenFocused === true ? CHANNELS : config.suppressWhenFocused || [] + const muted = new Set(focusChannels.length > 0 && isTerminalFocused() ? focusChannels : []) + if (muted.size === CHANNELS.length) { + return + } + + if ( + (eventType === "complete" || eventType === "subagent_complete") && + typeof elapsedSeconds === "number" && + Number.isFinite(elapsedSeconds) && + elapsedSeconds < config.minDuration + ) { + return + } const promises: Promise[] = [] diff --git a/src/notifier.ts b/src/notifier.ts index d8c65bb..87d1bb6 100644 --- a/src/notifier.ts +++ b/src/notifier.ts @@ -118,7 +118,7 @@ export function createNotifier(access: SessionAccess, directory: string, deliver } if (disposed || !valid()) return if (key && delivery === "terminal") { - if (!deliversAny(current, event, elapsed)) { + if (!deliversAny(current, event)) { debug(`${event}: no channel enabled in this terminal, leaving the event to other terminals`) return } From 5059020e41ec1dfa995ef2a364eaa8410ff3a3bc Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:37:01 +0000 Subject: [PATCH 09/10] docs: qualify the SSH upgrade note Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dfb381..1613b75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ All notable changes to this project will be documented in this file. ### Upgrade notes -- Local sessions and SSH sessions with a detected desktop window keep the same focus behavior. Over SSH inside tmux or Zellij, alerts now fire even while you are looking at the pane. +- Local sessions and SSH sessions with a detected desktop window keep the same focus behavior. Over SSH inside tmux or Zellij with no detected desktop window, alerts now fire even while you are looking at the pane. ## [1.1.1] - 2026-10-24 From 5ed33a4d1919a6c302257d094a2c74a521892e6d Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sun, 1 Nov 2026 03:42:51 +0000 Subject: [PATCH 10/10] docs: link changelog entries to #149 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1613b75..99c03f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,8 @@ All notable changes to this project will be documented in this file. ### Fixed -- On OpenCode 2, a terminal whose config turns off every channel for an event no longer claims it, so another terminal on the same machine can still alert (issue #147). -- Over SSH on Linux, an active tmux or Zellij pane no longer mutes alerts when no desktop window can be checked, so bells reach a terminal tab that is in the background (issue #147). +- On OpenCode 2, a terminal whose config turns off every channel for an event no longer claims it, so another terminal on the same machine can still alert (#149; issue #147). +- Over SSH on Linux, an active tmux or Zellij pane no longer mutes alerts when no desktop window can be checked, so bells reach a terminal tab that is in the background (#149; issue #147). ### Upgrade notes