Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 15 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

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

Expand Down
4 changes: 2 additions & 2 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions src/delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
11 changes: 11 additions & 0 deletions src/focus.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
9 changes: 7 additions & 2 deletions src/focus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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({
Expand All @@ -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 {
Expand Down
7 changes: 6 additions & 1 deletion src/notifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down
9 changes: 8 additions & 1 deletion src/v2.regression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: {} }),
Expand Down