diff --git a/CHANGELOG.md b/CHANGELOG.md index 00a0311..70dc910 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Fixed + +- On WSL in Windows Terminal, `suppressWhenFocused` now checks whether the Windows Terminal window OpenCode started in is in front, instead of Linux desktop focus (#156; issue #155). + +### Upgrade notes + +- Only WSL sessions in Windows Terminal change: alerts now stay silent while that terminal window is focused, as `suppressWhenFocused` (on by default) already does on other platforms. Detection is per window, not per tab. + +### Contributors + +- Thanks to @Nicholas-hosein-pw for reporting and fixing WSL focus suppression in #156. + ## [1.2.0] - 2026-11-26 ### Added diff --git a/README.md b/README.md index 957d2ed..c8834c0 100644 --- a/README.md +++ b/README.md @@ -528,11 +528,14 @@ Work from third-party delegation plugins without native child-session events, or | Linux Wayland (GNOME) | Optional Shell bridge, then AT-SPI (`gdbus`) | `gdbus` installed | AT-SPI tested (Ubuntu 26.04.1 LTS + GNOME Shell 50.1 + Ghostty 1.3.0); Shell bridge and persistent popup actions need desktop validation | | Linux Wayland (river, dwl, Cosmic, etc.) | No window backend; pane fallback when available | - | Notifies when focus cannot be determined | | Windows | Foreground window vs. OpenCode's console owner, via PowerShell | None | Untested | +| WSL / Windows Terminal | Foreground Windows window vs. captured terminal window | `powershell.exe`, `WT_SESSION` | Untested | **GNOME Wayland**: Focus detection first tries the optional Shell extension described under [Jump back to terminal](#linux-jump-back-to-terminal-from-notification), then falls back to the accessibility bus. Without the extension, restricted Shell APIs and XWayland tools such as `xdotool` cannot provide the native Wayland window identity used here. The AT-SPI fallback selects the terminal window with its `ACTIVE` state bit set. Ghostty is matched by its `/com/mitchellh/ghostty` AT-SPI path, other terminals by app name, including the `gnome-terminal-server` alias. AT-SPI window identity is `bus@path` since paths repeat across processes. This fallback was verified on Ubuntu 26.04.1 LTS + GNOME Shell 50.1 + Ghostty 1.3.0; the new Shell bridge still needs live desktop validation. With several terminal windows open, suppression compares against the window that was active at startup. Set `OPENCODE_NOTIFIER_DEBUG=1` to log the focus backend decision. **Windows**: Alerts are suppressed only when the window hosting OpenCode is provably in front. Windows Terminal and the classic console are matched by window handle, so another terminal window or any other app does not suppress alerts. For hosts that do not own their console window, such as VS Code, WezTerm, and Alacritty, the host is the nearest parent process with a visible window. It counts only when it has exactly one such window and is not Explorer, so VS Code with several windows open always alerts. Anything uncertain delivers the alert. Tabs are not distinguished: with OpenCode in a background Windows Terminal tab, the window still counts as focused. Set `OPENCODE_NOTIFIER_DEBUG=1` to log each decision with the raw probe output. +**WSL / Windows Terminal**: With `WT_SESSION` set, focus is checked through Windows PowerShell rather than Linux desktop tools. The plugin captures the foreground Windows Terminal window at startup, or the sole terminal window when only one is open. Start OpenCode with its terminal window focused when several windows are open. An ambiguous startup, a closed window, a failed query, or an SSH session keeps notifications enabled; the plugin never switches to another window after startup. PowerShell queries are asynchronous and limited to five seconds. This applies to V1 alerts and V2 terminal alerts; V2 server commands remain unaffected. Detection is window-level, not tab-level: another tab in the same Windows Terminal window still counts as focused. Supported tmux, WezTerm and Zellij pane checks still apply. Other WSL terminal hosts keep their existing focus behavior. Set `OPENCODE_NOTIFIER_DEBUG=1` to log the decision. + **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, except over SSH, where alerts are always delivered. GNU Screen has no pane detection, but ordinary terminal-window focus detection can still suppress notifications. diff --git a/SPEC.md b/SPEC.md index 08a8423..4218080 100644 --- a/SPEC.md +++ b/SPEC.md @@ -49,6 +49,7 @@ An event is delivered on a channel only if every check passes, in this order: - No hook throws into or blocks the host. Failures are swallowed, and logged when `OPENCODE_NOTIFIER_DEBUG=1`. - Focus detection fails open. On KDE, a valid `OPENCODE_NOTIFIER_WINDOW_ID` overrides the captured host window for both suppression and jump-back; numeric IDs and braced KWin UUIDs are accepted. Capture first resolves terminal/editor ancestors to their window, using the foreground window only to disambiguate multiple windows belonging to that host. Without host ancestry, focused-startup capture supports embedded launchers, rejecting a foreground app that conflicts with a known `TERM_PROGRAM`. Unknown or ambiguous targets keep notifications enabled and have no jump action. Capture does not modify the process environment, and failed activation never selects another terminal. V2 jump-back selects the event's session in the delivering terminal's UI before activating its host window. V1 activates the host window only. +- On WSL in Windows Terminal (`WT_SESSION` set), capture the foreground Windows Terminal window at startup, or the sole terminal window if unambiguous. Suppress only while the captured window and process still exist and that window is foreground, subject to existing pane checks. Never recapture at event time or use Windows focus for an SSH client. Unknown targets and failed queries deliver alerts. Queries are asynchronous and bounded to five seconds. This is window-level detection; Windows Terminal tabs are not distinguished. V1 and V2 terminal delivery share this check; V2 server commands remain independent of focus. - A missing or invalid config file means defaults. Config path: `OPENCODE_NOTIFIER_CONFIG_PATH`, else `~/.config/opencode/opencode-notifier.json`. - Unset new options reproduce the previous release's behavior. - A volume of `0` skips playback on every platform. diff --git a/src/delivery.focus.test.ts b/src/delivery.focus.test.ts index ce77a35..40ca699 100644 --- a/src/delivery.focus.test.ts +++ b/src/delivery.focus.test.ts @@ -8,7 +8,7 @@ afterAll(() => rmSync(fixtureRoot, { recursive: true, force: true })) // Runs handleEvent in a child process with the terminal reported as focused and every channel stubbed, // so module mocks never leak into other test files. Returns the channels that delivered. -async function deliveredWhileFocused(suppressWhenFocused: unknown): Promise { +async function deliveredWhileFocused(suppressWhenFocused: unknown, asyncFocus = false, focused = true): Promise { const configPath = join(fixtureRoot, "config.json") writeFileSync(configPath, JSON.stringify({ suppressWhenFocused, bell: true, @@ -19,7 +19,7 @@ async function deliveredWhileFocused(suppressWhenFocused: unknown): Promise process.stdout.write(line + "\\n") mock.module(${module("focus.ts")}, () => ({ - isTerminalFocused: () => (log("focus-query"), true), + isTerminalFocused: () => (log("focus-query"), ${asyncFocus ? `Promise.resolve(${focused})` : focused}), focusTerminal: async () => {}, isTerminalJumpBackSupported: () => false, debugFocusState: () => {}, })) mock.module(${module("notify.ts")}, () => ({ sendNotification: async () => log("notification") })) @@ -55,3 +55,9 @@ test("suppressWhenFocused list skips only the listed channels", async () => { test("an empty suppressWhenFocused list never queries focus", async () => { expect(await deliveredWhileFocused([])).toEqual(["bell", "command", "notification", "sound"]) }) + +test("awaits asynchronous WSL focus instead of treating a Promise as focused", async () => { + expect(await deliveredWhileFocused(true, true, true)).toEqual(["focus-query"]) + expect(await deliveredWhileFocused(true, true, false)).toEqual(["bell", "command", "focus-query", "notification", "sound"]) + expect(await deliveredWhileFocused(["notification"], true, true)).toEqual(["bell", "command", "focus-query", "sound"]) +}) diff --git a/src/delivery.ts b/src/delivery.ts index 42afffe..0b85029 100644 --- a/src/delivery.ts +++ b/src/delivery.ts @@ -107,7 +107,7 @@ export async function handleEvent( ): 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 : []) + const muted = new Set(focusChannels.length > 0 && await isTerminalFocused() ? focusChannels : []) if (muted.size === CHANNELS.length) { return } diff --git a/src/focus-windows.ts b/src/focus-windows.ts index acf5cb4..f31f290 100644 --- a/src/focus-windows.ts +++ b/src/focus-windows.ts @@ -46,7 +46,7 @@ export function decideWindowsFocus(facts: WindowsFocusFacts): WindowsFocusDecisi return { focused: facts.foreground === host.windows[0], reason: `host ${host.name}` } } -function isHandle(value: unknown): value is number { +export function isHandle(value: unknown): value is number { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 } diff --git a/src/focus-wsl.test.ts b/src/focus-wsl.test.ts new file mode 100644 index 0000000..20b33df --- /dev/null +++ b/src/focus-wsl.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, test } from "bun:test" +import { join } from "path" +import { chooseWslTerminalWindow, decideWslFocus, parseWslFocusFacts } from "./focus-wsl" +import type { WslFocusFacts } from "./focus-wsl" + +const origin = { handle: 100, pid: 10 } +const other = { handle: 200, pid: 10 } +const facts: WslFocusFacts = { foreground: 100, windows: [origin, other] } + +describe("WSL focus facts", () => { + test("parses PowerShell output including warnings and no foreground window", () => { + expect(parseWslFocusFacts(`#< CLIXML\r\n${JSON.stringify(facts)}\r\n`)).toEqual(facts) + expect(parseWslFocusFacts('{"foreground":0,"windows":[]}')).toEqual({ foreground: 0, windows: [] }) + }) + + test("rejects missing, malformed and mistyped facts", () => { + for (const output of [null, "", "{", "null", '{"foreground":"100","windows":[]}', + '{"foreground":-1,"windows":[]}', '{"foreground":100,"windows":[null]}', + '{"foreground":100,"windows":[{"handle":0,"pid":10}]}', + '{"foreground":100,"windows":[{"handle":100,"pid":"10"}]}']) { + expect(parseWslFocusFacts(output)).toBe(null) + } + }) + + test("captures the foreground terminal or the only terminal, but not an ambiguous one", () => { + expect(chooseWslTerminalWindow(facts)).toEqual(origin) + expect(chooseWslTerminalWindow({ foreground: 999, windows: [origin] })).toEqual(origin) + expect(chooseWslTerminalWindow({ ...facts, foreground: 999 })).toBe(null) + expect(chooseWslTerminalWindow({ foreground: 999, windows: [] })).toBe(null) + }) + + test("requires the same window and process, not just another terminal in front", () => { + expect(decideWslFocus(facts, origin).focused).toBe(true) + expect(decideWslFocus({ ...facts, foreground: other.handle }, origin).focused).toBe(false) + expect(decideWslFocus({ ...facts, foreground: 999 }, origin).focused).toBe(false) + expect(decideWslFocus({ ...facts, windows: [{ ...origin, pid: 20 }] }, origin).focused).toBe(false) + expect(decideWslFocus({ ...facts, windows: [] }, origin).focused).toBe(false) + expect(decideWslFocus(null, origin).focused).toBe(false) + expect(decideWslFocus(facts, null).focused).toBe(false) + }) +}) + +// Isolate module state and child_process mocks. No test calls real PowerShell, +// changes window focus, reads the user's config or delivers a notification. +async function runFocus(script: string, env: Record = {}) { + const child = Bun.spawn([process.execPath, "--eval", ` + const { mock } = await import("bun:test") + const childProcess = { ...await import("child_process") } + let facts = ${JSON.stringify(facts)} + let probeError = false, probeThrows = false, probeOutput, calls = 0, paneOutput = "1 1 1" + mock.module("is-wsl", () => ({ default: true })) + mock.module("child_process", () => ({ + ...childProcess, + execSync: () => "", + execFileSync: () => paneOutput, + execFile(command, args, options, callback) { + if (command !== "powershell.exe" || options.timeout !== 5000) throw new Error("Unexpected probe") + if (!args.includes("-EncodedCommand")) throw new Error("Expected encoded PowerShell script") + calls++ + if (probeThrows) throw new Error("spawn failed") + const output = probeOutput ?? JSON.stringify(facts) + setTimeout(() => callback(probeError ? new Error("PowerShell unavailable or timed out") : null, output), 10) + }, + })) + const focus = await import(${JSON.stringify(join(import.meta.dir, "focus.ts"))}) + const wsl = await import(${JSON.stringify(join(import.meta.dir, "focus-wsl.ts"))}) + ${script} + `], { + env: { + ...process.env, WT_SESSION: "fixture", SSH_CONNECTION: undefined, SSH_TTY: undefined, + KDE_SESSION_VERSION: undefined, WAYLAND_DISPLAY: undefined, DISPLAY: undefined, + TMUX: undefined, WEZTERM_PANE: undefined, ZELLIJ_SESSION_NAME: undefined, ZELLIJ_PANE_ID: undefined, + OPENCODE_NOTIFIER_DEBUG: undefined, ...env, + }, + stdout: "pipe", stderr: "pipe", + }) + const output = await new Response(child.stdout).text() + const error = await new Response(child.stderr).text() + expect(await child.exited, error).toBe(0) + return output.trim() +} + +test.skipIf(process.platform !== "linux")("WSL routing captures once and checks Windows rather than Linux desktop focus", async () => { + expect(await runFocus(` + await focus.captureStartupWindowId() + console.log(await focus.isTerminalFocused()) + await wsl.captureWslTerminalWindow() + console.log(await focus.isTerminalFocused()) + facts.foreground = 200 + console.log(await focus.isTerminalFocused()) + await focus.captureStartupWindowId() + facts.foreground = 100 + console.log(await focus.isTerminalFocused(), calls) + `)).toBe("false\ntrue\nfalse\ntrue 4") +}) + +test.skipIf(process.platform !== "linux")("ambiguous startup does not recapture another terminal at event time", async () => { + expect(await runFocus(` + facts.foreground = 999 + await focus.captureStartupWindowId(); await wsl.captureWslTerminalWindow() + facts.foreground = 100 + console.log(await focus.isTerminalFocused(), calls) + `)).toBe("false 1") +}) + +test.skipIf(process.platform !== "linux")("failed startup and failed or malformed later probes fail open", async () => { + expect(await runFocus(` + probeError = true + await focus.captureStartupWindowId(); await wsl.captureWslTerminalWindow() + probeError = false + console.log(await focus.isTerminalFocused(), calls) + `)).toBe("false 1") + expect(await runFocus(` + await focus.captureStartupWindowId(); await wsl.captureWslTerminalWindow() + probeError = true + console.log(await focus.isTerminalFocused()) + probeError = false + probeOutput = "not JSON" + console.log(await focus.isTerminalFocused()) + probeOutput = undefined + probeThrows = true + console.log(await focus.isTerminalFocused()) + `)).toBe("false\nfalse\nfalse") +}) + +test.skipIf(process.platform !== "linux")("concurrent probes share asynchronous work without caching stale decisions", async () => { + expect(await runFocus(` + const first = wsl.probeWslFocus() + const second = wsl.probeWslFocus() + console.log(first === second, calls) + await first + facts.foreground = 999 + console.log((await wsl.probeWslFocus()).foreground, calls) + `)).toBe("true 1\n999 2") +}) + +test.skipIf(process.platform !== "linux")("SSH and unsupported WSL terminals do not query Windows focus", async () => { + for (const env of [{ SSH_CONNECTION: "fixture" }, { SSH_TTY: "/dev/pts/1" }, { WT_SESSION: undefined }]) { + expect(await runFocus(` + await focus.captureStartupWindowId() + console.log(await focus.isTerminalFocused(), calls) + `, env)).toBe("false 0") + } +}) + +test.skipIf(process.platform !== "linux")("a Windows-focused terminal still respects inactive tmux, WezTerm and Zellij panes", async () => { + for (const env of [{ TMUX: "fixture", TMUX_PANE: "%1" }, { WEZTERM_PANE: "1" }, + { ZELLIJ_SESSION_NAME: "fixture", ZELLIJ_PANE_ID: "1" }]) { + expect(await runFocus(` + await focus.captureStartupWindowId(); await wsl.captureWslTerminalWindow() + paneOutput = "" + console.log(await focus.isTerminalFocused(), calls) + `, env)).toBe("false 1") + } +}) diff --git a/src/focus-wsl.ts b/src/focus-wsl.ts new file mode 100644 index 0000000..ba139fe --- /dev/null +++ b/src/focus-wsl.ts @@ -0,0 +1,125 @@ +import { execFile } from "child_process" +import { isHandle, type WindowsFocusDecision } from "./focus-windows" + +export interface WslTerminalWindow { + handle: number + pid: number +} + +export interface WslFocusFacts { + foreground: number + windows: WslTerminalWindow[] +} + +export function parseWslFocusFacts(output: string | null): WslFocusFacts | null { + const line = output?.split(/\r?\n/).map(value => value.trim()).find(value => value.startsWith("{")) + if (!line) return null + let value: unknown + try { + value = JSON.parse(line) + } catch { + return null + } + if (typeof value !== "object" || value === null) return null + const { foreground, windows } = value as Record + if (!isHandle(foreground) || !Array.isArray(windows)) return null + const parsed: WslTerminalWindow[] = [] + for (const entry of windows) { + if (typeof entry !== "object" || entry === null) return null + const { handle, pid } = entry as Record + if (!isHandle(handle) || !isHandle(pid) || handle === 0 || pid === 0) return null + parsed.push({ handle, pid }) + } + return { foreground, windows: parsed } +} + +export function chooseWslTerminalWindow(facts: WslFocusFacts): WslTerminalWindow | null { + // A sole terminal is unambiguous even during background startup. Otherwise + // the user must start OpenCode with its Windows Terminal window focused. + return facts.windows.find(window => window.handle === facts.foreground) + ?? (facts.windows.length === 1 ? facts.windows[0]! : null) +} + +export function decideWslFocus(facts: WslFocusFacts | null, origin: WslTerminalWindow | null): WindowsFocusDecision { + if (!origin) return { focused: false, reason: "originating Windows Terminal window is unknown" } + if (!facts) return { focused: false, reason: "WSL focus probe failed" } + if (!facts.windows.some(window => window.handle === origin.handle && window.pid === origin.pid)) { + return { focused: false, reason: "originating Windows Terminal window is no longer available" } + } + return { focused: facts.foreground === origin.handle, reason: `Windows Terminal window ${origin.handle}` } +} + +// WSL's process.pid is a Linux PID, not something AttachConsole can use. +// Enumerate real Windows Terminal windows without attaching a console or +// changing focus. C# 5 syntax also works with Windows PowerShell 5.1. +const WSL_FOCUS_SCRIPT = String.raw`$ErrorActionPreference = 'Stop' +Add-Type -TypeDefinition @' +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace OpenCodeNotifier { + public class WslWindow { public long handle; public int pid; } + public class WslFacts { public long foreground; public WslWindow[] windows; } + public static class WslFocusProbe { + delegate bool Callback(IntPtr window, IntPtr parameter); + [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr window); + [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr window, uint command); + [DllImport("user32.dll")] static extern int GetWindowLong(IntPtr window, int index); + [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, out uint process); + [DllImport("user32.dll")] static extern bool EnumWindows(Callback callback, IntPtr parameter); + + public static WslFacts Probe() { + var windows = new List(); + bool success = EnumWindows(delegate(IntPtr window, IntPtr parameter) { + if (!IsWindowVisible(window) || GetWindow(window, 4) != IntPtr.Zero) return true; + if ((GetWindowLong(window, -20) & 0x80) != 0) return true; + uint pid; + GetWindowThreadProcessId(window, out pid); + try { + using (var process = Process.GetProcessById((int)pid)) { + if (String.Equals(process.ProcessName, "WindowsTerminal", StringComparison.OrdinalIgnoreCase)) + windows.Add(new WslWindow { handle = window.ToInt64(), pid = (int)pid }); + } + } catch (ArgumentException) { } + return true; + }, IntPtr.Zero); + if (!success) throw new InvalidOperationException("EnumWindows failed"); + return new WslFacts { foreground = GetForegroundWindow().ToInt64(), windows = windows.ToArray() }; + } + } +} +'@ +[OpenCodeNotifier.WslFocusProbe]::Probe() | ConvertTo-Json -Compress -Depth 4` + +let pendingProbe: Promise | undefined + +export function probeWslFocus(): Promise { + // Concurrent events share a query, but never reuse an old focus decision. + pendingProbe ??= new Promise(resolve => { + const encoded = Buffer.from(WSL_FOCUS_SCRIPT, "utf16le").toString("base64") + execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], { + timeout: 5000, encoding: "utf-8", windowsHide: true, + }, (error, stdout) => resolve(error ? null : parseWslFocusFacts(stdout))) + }).catch(() => null).finally(() => { pendingProbe = undefined }) + return pendingProbe +} + +let origin: WslTerminalWindow | null = null +let startupCapture: Promise | undefined + +export async function captureWslTerminalWindow(): Promise { + startupCapture ??= (async () => { + const facts = await probeWslFocus() + origin = facts ? chooseWslTerminalWindow(facts) : null + })() + await startupCapture +} + +export async function getWslFocus(): Promise { + // Do not capture lazily: the foreground terminal at event time may belong + // to another session. A closed or unknown startup window stays unknown. + return decideWslFocus(origin ? await probeWslFocus() : null, origin) +} diff --git a/src/focus.kde.test.ts b/src/focus.kde.test.ts index b947729..fd81e42 100644 --- a/src/focus.kde.test.ts +++ b/src/focus.kde.test.ts @@ -53,6 +53,7 @@ async function run(script: string, pinned?: string, vscodeHost = false, options: HYPRLAND_INSTANCE_SIGNATURE: undefined, SWAYSOCK: undefined, NIRI_SOCKET: undefined, TMUX: undefined, WEZTERM_PANE: undefined, ZELLIJ_SESSION_NAME: undefined, ZELLIJ_PANE_ID: undefined, TERM_PROGRAM: options.termProgram, OPENCODE_NOTIFIER_WINDOW_ID: pinned, + WT_SESSION: undefined, FIXTURE_HOST_WINDOWS: options.hostWindows, FIXTURE_ACTIVATION_FAILS: options.activationFails ? "1" : undefined, DBUS_SESSION_BUS_ADDRESS: "fixture", OPENCODE_NOTIFIER_CONFIG_PATH: configPath, OPENCODE_CLIENT: "cli", @@ -168,7 +169,7 @@ test.skipIf(process.platform !== "linux")("KDE X11 without kdotool keeps xdotool env: { ...process.env, PATH: xdotoolDirectory, DISPLAY: ":0", KDE_SESSION_VERSION: "6", WAYLAND_DISPLAY: undefined, TMUX: undefined, WEZTERM_PANE: undefined, ZELLIJ_SESSION_NAME: undefined, ZELLIJ_PANE_ID: undefined, - OPENCODE_NOTIFIER_WINDOW_ID: undefined, + OPENCODE_NOTIFIER_WINDOW_ID: undefined, WT_SESSION: undefined, }, stdout: "pipe", stderr: "pipe", }) const output = await new Response(child.stdout).text() diff --git a/src/focus.test.ts b/src/focus.test.ts index 7ab4bc0..67d77cc 100644 --- a/src/focus.test.ts +++ b/src/focus.test.ts @@ -255,14 +255,18 @@ describe("getCachedWindowTitle", () => { }) describe("captureStartupWindowId", () => { - test("does not set env var when kde jump back is unsupported", () => { + test("does not set env var when kde jump back is unsupported", async () => { const original = process.env.OPENCODE_NOTIFIER_WINDOW_ID + const originalWtSession = process.env.WT_SESSION delete process.env.OPENCODE_NOTIFIER_WINDOW_ID + delete process.env.WT_SESSION try { - captureStartupWindowId() + await captureStartupWindowId() expect(process.env.OPENCODE_NOTIFIER_WINDOW_ID).toBeUndefined() } finally { + if (originalWtSession === undefined) delete process.env.WT_SESSION + else process.env.WT_SESSION = originalWtSession if (original) { process.env.OPENCODE_NOTIFIER_WINDOW_ID = original } else { diff --git a/src/focus.ts b/src/focus.ts index 64a1141..33f7238 100644 --- a/src/focus.ts +++ b/src/focus.ts @@ -2,6 +2,8 @@ import { execFile, execFileSync, execSync } from "child_process" import { accessSync, constants, readFileSync, statSync } from "fs" import { delimiter, join } from "path" import { getWindowsFocus } from "./focus-windows" +import isWsl from "is-wsl" +import { captureWslTerminalWindow, getWslFocus } from "./focus-wsl" const LINUX_TERMINAL_APPS = new Set([ "ghostty", @@ -605,7 +607,7 @@ function isWezTermPaneActive(): boolean { return focusedPaneId === weztermPane } -export function isTerminalFocused(): boolean { +export function isTerminalFocused(): boolean | Promise { try { const zellijPaneActive = process.env.ZELLIJ_SESSION_NAME || process.env.ZELLIJ_PANE_ID ? isZellijPaneActive() : null if (zellijPaneActive === false) return false @@ -625,6 +627,16 @@ export function isTerminalFocused(): boolean { if (process.platform === "win32") return isWindowsHostFocused() + if (process.platform === "linux" && isWsl && process.env.WT_SESSION) { + // A Windows window is not evidence of a remote SSH client's focus. + if (process.env.SSH_CONNECTION || process.env.SSH_TTY) return false + if (!isWezTermPaneActive() || (process.env.TMUX && !isTmuxPaneActive())) return false + return getWslFocus().then(({ focused, reason }) => { + debugFocusState(`WSL focus: ${reason} focused=${focused}`) + return focused + }).catch(() => false) + } + // An unresolved KDE host must not let a focused tmux or Zellij pane stand in for desktop focus. if (!cachedWindowId && isKDEJumpBackSupported()) { debugFocusState("linux focus: KDE originating window is unknown, notifying") @@ -949,6 +961,11 @@ function focusLinuxWindowNiri(windowId: string): void { let startupWindowCapture: Promise | undefined export async function captureStartupWindowId(): Promise { + if (process.platform === "linux" && isWsl && process.env.WT_SESSION) { + // PowerShell can take seconds, so capture in the background; focus fails open until it finishes. + if (!process.env.SSH_CONNECTION && !process.env.SSH_TTY) void captureWslTerminalWindow() + return + } if (process.platform !== "linux" || !process.env.KDE_SESSION_VERSION) return startupWindowCapture ??= (async () => { cachedKDEJumpBackSupport = await execFileAsync("kdotool", ["--help"], 1000) !== null