diff --git a/CHANGELOG.md b/CHANGELOG.md index c867f37..99c03f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### 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 (#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 + +- 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 ### Fixed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d3731f4..6b39b26 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,7 +17,21 @@ 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. 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" + ``` + + 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 diff --git a/README.md b/README.md index e6bab26..507c080 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. @@ -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. diff --git a/SPEC.md b/SPEC.md index 7efa6a3..09c5aae 100644 --- a/SPEC.md +++ b/SPEC.md @@ -41,8 +41,8 @@ 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. -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. +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. ## Guarantees diff --git a/src/delivery.ts b/src/delivery.ts index a9e0049..b155401 100644 --- a/src/delivery.ts +++ b/src/delivery.ts @@ -88,6 +88,13 @@ export function shouldResolveSessionContextForEvent(config: NotifierConfig, even .some(value => value.includes("{agentName}") || value.includes("{sessionTitle}"))) } +// 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): boolean { + return CHANNELS.some(channel => config.events[eventType][channel] && (channel !== "command" || config.command.enabled)) +} + export async function handleEvent( config: NotifierConfig, eventType: EventType, 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 { diff --git a/src/notifier.ts b/src/notifier.ts index 5012072..87d1bb6 100644 --- a/src/notifier.ts +++ b/src/notifier.ts @@ -2,7 +2,8 @@ import { basename } from "path" import { loadConfig } from "./config" import type { EventType, NotifierConfig } from "./config" import { claimDelivery } from "./claim" -import { extractAgentNameFromSessionTitle, handleEvent, shouldResolveSessionContextForEvent } from "./delivery" +import { deliversAny, extractAgentNameFromSessionTitle, handleEvent, 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. @@ -117,6 +118,10 @@ export function createNotifier(access: SessionAccess, directory: string, deliver } if (disposed || !valid()) return if (key && delivery === "terminal") { + if (!deliversAny(current, event)) { + debug(`${event}: no channel enabled 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 } 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: {} }),