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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@ All notable changes to this project will be documented in this file.
- KDE focus suppression and jump-back accept KWin UUID window IDs and resolve the originating terminal/editor through process ancestry, so background VS Code clients no longer capture Ghostty; explicit IDs override both checks and ambiguous or closed targets never redirect to another terminal (#141; issue #133).
- V2 alerts prefer a client with the completed session's family open, preventing an unrelated Ghostty or VS Code client from claiming an Obsidian session's jump action; clicking also selects the completed session in the delivering client (#141; issue #133).
- Linux Jump to terminal and Run command buttons remain actionable while hovered popups outlive the requested timeout; their sender and handlers stay connected until notification closure or client shutdown (#142; issue #134).
- OpenCode V2 terminals skip alert deduplication and open-session presence when their shared temp directory is a symlink, owned by another user, or writable by others, so cleanup can no longer delete files outside it (#146; issue #145).

### Upgrade notes

- V2 clients now share open-session presence as well as event claims; when no eligible client has the session open, alerts still use the first claim, and V1 delivery is unchanged.
- No config changes. Terminals sharing a normal temp directory still deliver each alert once, and existing claim directories keep working.

### Contributors

- Thanks to @kriss-spy for the KDE focus and V2 session routing fixes in #141 and the Linux action lifetime fix in #142.
- Thanks to @YuriNek0 for reporting and fixing the claim cleanup issue in #146.

## [1.0.0] - 2026-10-14

Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,9 @@ If native notification delivery crashes OpenCode, disable native notifications a

Debug lines go to stderr. On V2 the full-screen terminal UI hides them, and they are not written to OpenCode's log file. On V2, check behavior directly: put another window in front, trigger an event, and see whether the alert arrives.

**OpenCode 2: Duplicate alerts across terminals?**
Terminals share one directory under the system temp directory (usually `/tmp/opencode-notifier-<uid>` on Linux) for event claims and open-session presence, so only one alerts per event. If that path is a symlink, belongs to another user, is writable by others, or cannot be used, claims and presence are skipped and each terminal alerts on its own. A symlinked `/tmp` itself is fine.

## TypeScript imports

Loading this plugin through OpenCode configuration does not require installing SDKs separately. If a TypeScript project imports the package directly, its declarations reference both OpenCode SDK generations. Install the optional type peers in that project:
Expand Down
2 changes: 1 addition & 1 deletion SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. The claim is a marker file in the user's temp directory; if it cannot be written, every terminal delivers.
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.
7. Sound: at most one sound per second across all events.

Expand Down
185 changes: 162 additions & 23 deletions src/claim.test.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,167 @@
import { afterAll, expect, test } from "bun:test"
import { mkdtempSync, rmSync, writeFileSync } from "fs"
import { afterAll, expect, spyOn, test } from "bun:test"
import { createHash } from "crypto"
import { chmodSync, existsSync, lstatSync, lutimesSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "fs"
import { tmpdir } from "os"
import { join } from "path"
import { claimDelivery } from "./claim"
import { createDeliveryClaimer } from "./claim"

const fixture = mkdtempSync(join(tmpdir(), "notifier-claim-test-"))
const oldTmpdir = process.env.TMPDIR
afterAll(() => {
if (oldTmpdir === undefined) delete process.env.TMPDIR
else process.env.TMPDIR = oldTmpdir
rmSync(fixture, { recursive: true, force: true })
})

test("only the first claim for a key delivers", () => {
process.env.TMPDIR = fixture
expect(claimDelivery("event-1")).toBe(true)
expect(claimDelivery("event-1")).toBe(false)
expect(claimDelivery("event-2")).toBe(true)
})

test("an unusable temp directory fails open", () => {
const file = join(fixture, "not-a-directory")
writeFileSync(file, "")
process.env.TMPDIR = file
expect(claimDelivery("event-1")).toBe(true)
expect(claimDelivery("event-1")).toBe(true)
afterAll(() => rmSync(fixture, { recursive: true, force: true }))

const MINUTE_MS = 60_000
const hash = (key: string) => createHash("sha256").update(key).digest("hex")
const directoryName = `opencode-notifier-${process.getuid?.() ?? "claims"}`
const posix = process.platform !== "win32"

// Each test gets an isolated temp root, separate from running sessions' markers.
// true permits delivery; false suppresses a duplicate alert.
function setup() {
const tempRoot = mkdtempSync(join(fixture, "temp-"))
return { tempRoot, dir: join(tempRoot, directoryName), claim: createDeliveryClaimer(tempRoot) }
}

function expiredFile(path: string): string {
writeFileSync(path, "")
utimesSync(path, new Date(0), new Date(0))
return path
}

test("two terminals sharing a temp root deliver each event only once", () => {
const { tempRoot, claim } = setup()
const otherTerminalClaim = createDeliveryClaimer(tempRoot)
expect(claim("event-1")).toBe(true)
expect(otherTerminalClaim("event-1")).toBe(false)
expect(claim("event-2")).toBe(true)
})

test("a missing temp root is created and still deduplicates", () => {
const { tempRoot } = setup()
const claim = createDeliveryClaimer(join(tempRoot, "missing", "nested"))
expect(claim("event")).toBe(true)
expect(claim("event")).toBe(false)
})

test("a file blocking the claim directory allows repeated deliveries", () => {
const { dir, claim } = setup()
writeFileSync(dir, "not a directory")
expect(claim("event")).toBe(true)
expect(claim("event")).toBe(true)
})

// Symlink creation on Windows can require privileges unavailable to the test runner.
test.skipIf(!posix)("a symlinked claim directory allows repeated deliveries without touching its target", () => {
const { dir, claim } = setup()
const target = mkdtempSync(join(fixture, "target-"))
// Looks like an expired marker; following the symlink during cleanup would delete it.
const sentinel = expiredFile(join(target, hash("sentinel")))
symlinkSync(target, dir)

expect(claim("event")).toBe(true)
expect(claim("event")).toBe(true)
expect(existsSync(sentinel)).toBe(true)
expect(existsSync(join(target, hash("event")))).toBe(false)
})

test.skipIf(!posix)("a symlinked temp root still deduplicates through its real claim directory", () => {
const { tempRoot, dir, claim } = setup()
const linkedRoot = join(fixture, "linked-temp")
symlinkSync(tempRoot, linkedRoot)

expect(createDeliveryClaimer(linkedRoot)("event")).toBe(true)
expect(claim("event")).toBe(false)
expect(existsSync(join(dir, hash("event")))).toBe(true)
})

test.skipIf(!posix)("a claim directory others can write allows repeated deliveries without cleanup", () => {
for (const mode of [0o770, 0o777]) {
const { dir, claim } = setup()
mkdirSync(dir)
chmodSync(dir, mode)
const stale = expiredFile(join(dir, hash("stale")))
expect(claim("event")).toBe(true)
expect(claim("event")).toBe(true)
expect(existsSync(stale)).toBe(true)
expect(existsSync(join(dir, hash("event")))).toBe(false)
}
})

test.skipIf(!posix)("a claim directory owned by another user allows repeated deliveries", () => {
const { tempRoot, claim } = setup()
const realUid = process.getuid!()
const getuid = spyOn(process, "getuid").mockReturnValue(realUid + 1)
try {
// Created by us under the other uid's name, so its owner differs from the faked uid.
const dir = join(tempRoot, `opencode-notifier-${realUid + 1}`)
mkdirSync(dir, { mode: 0o700 })
const stale = expiredFile(join(dir, hash("stale")))
expect(claim("event")).toBe(true)
expect(claim("event")).toBe(true)
expect(existsSync(stale)).toBe(true)
} finally {
getuid.mockRestore()
}
})

test("a throwing debug logger still lets unusable storage deliver", () => {
const { dir, claim } = setup()
writeFileSync(dir, "not a directory")
const oldDebug = process.env.OPENCODE_NOTIFIER_DEBUG
process.env.OPENCODE_NOTIFIER_DEBUG = "1"
const log = spyOn(console, "error").mockImplementation(() => {
throw new Error("stderr closed")
})
try {
expect(claim("event")).toBe(true)
expect(claim("event")).toBe(true)
} finally {
log.mockRestore()
if (oldDebug === undefined) delete process.env.OPENCODE_NOTIFIER_DEBUG
else process.env.OPENCODE_NOTIFIER_DEBUG = oldDebug
}
})

test.skipIf(!posix)("an existing private claim directory from an earlier release keeps deduplicating", () => {
for (const mode of [0o700, 0o755]) {
const { dir, claim } = setup()
mkdirSync(dir)
chmodSync(dir, mode)
expect(claim("event")).toBe(true)
expect(claim("event")).toBe(false)
}
})

test("cleanup deletes expired markers but preserves recent markers, other names, and link targets", () => {
const { dir, claim } = setup()
const now = Date.now()
expect(claim("seed", now)).toBe(true)
const stale = expiredFile(join(dir, hash("stale")))
const unrelated = expiredFile(join(dir, "unrelated"))
const target = expiredFile(join(mkdtempSync(join(fixture, "target-")), "kept"))
const link = join(dir, hash("symlink"))
if (posix) {
symlinkSync(target, link)
lutimesSync(link, new Date(0), new Date(0))
}

// Past the ten-minute cleanup interval; the seed is still under the one-hour expiry.
expect(claim("after-prune", now + 11 * MINUTE_MS)).toBe(true)
expect(existsSync(stale)).toBe(false)
expect(existsSync(unrelated)).toBe(true)
expect(existsSync(join(dir, hash("seed")))).toBe(true)
expect(existsSync(target)).toBe(true)
if (posix) expect(() => lstatSync(link)).toThrow()
expect(claim("stale", now + 11 * MINUTE_MS)).toBe(true)
})

test("cleanup waits more than ten minutes between scans", () => {
const { dir, claim } = setup()
const now = Date.now()
expect(claim("seed", now)).toBe(true)
// Added after the first scan, so only the throttle keeps it.
const stale = expiredFile(join(dir, hash("stale")))

expect(claim("at-interval", now + 10 * MINUTE_MS)).toBe(true)
expect(existsSync(stale)).toBe(true)
expect(claim("past-interval", now + 10 * MINUTE_MS + 1)).toBe(true)
expect(existsSync(stale)).toBe(false)
})
75 changes: 57 additions & 18 deletions src/claim.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,69 @@
import { createHash } from "crypto"
import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "fs"
import { lstatSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from "fs"
import { tmpdir } from "os"
import { join } from "path"

const MARKER_TTL_MS = 60 * 60_000
let lastPrune = 0
const MARKER_NAME = /^[a-f0-9]{64}$/

// Several V2 terminals on one machine can show the same session. Each one claims an event before
// delivering it by creating a marker file named after the event; only the first create succeeds.
// Any other failure fails open, so a broken temp directory never mutes alerts.
export function claimDelivery(key: string, now = Date.now()): boolean {
const dir = join(tmpdir(), `opencode-notifier-${process.getuid?.() ?? "claims"}`)
// Logging must never turn a fail-open path into a dropped alert.
function debug(message: string): void {
try {
if (process.env.OPENCODE_NOTIFIER_DEBUG) console.error(`[opencode-notifier] claim: ${message}`)
} catch {}
}

// The directory V2 terminals share for event claims and open-session presence. It must be a real
// directory we own that no one else can write; otherwise another user could swap it for a symlink
// and steer our cleanup into unrelated files. undefined means unsafe or unavailable: callers skip
// coordination and deliver. The temp root itself is trusted.
export function sharedDirectory(tempRoot?: string): string | undefined {
try {
const uid = process.getuid?.()
const dir = join(tempRoot ?? tmpdir(), `opencode-notifier-${uid ?? "claims"}`)
mkdirSync(dir, { recursive: true, mode: 0o700 })
if (now - lastPrune > MARKER_TTL_MS / 6) {
lastPrune = now
for (const name of readdirSync(dir)) {
const path = join(dir, name)
try {
if (now - statSync(path).mtimeMs > MARKER_TTL_MS) unlinkSync(path)
} catch {}
const info = lstatSync(dir)
if (info.isDirectory() && (uid === undefined || (info.uid === uid && (info.mode & 0o022) === 0))) return dir
debug("shared directory is not a private directory we own; delivering")
} catch (error) {
debug(`shared directory unavailable (${(error as NodeJS.ErrnoException).code ?? "unknown"}); delivering`)
}
}

// V2 terminals deduplicate alerts by exclusively creating a marker for each event.
// true permits delivery; false means another terminal claimed it.
// Tests can supply a throwaway temp root; each instance tracks its own cleanup interval.
export function createDeliveryClaimer(tempRoot?: string) {
let lastPrune = 0
return function claimDelivery(key: string, now = Date.now()): boolean {
try {
const dir = sharedDirectory(tempRoot)
if (!dir) return true

if (now - lastPrune > MARKER_TTL_MS / 6) {
lastPrune = now
for (const name of readdirSync(dir)) {
if (!MARKER_NAME.test(name)) continue
const path = join(dir, name)
try {
if (now - lstatSync(path).mtimeMs > MARKER_TTL_MS) unlinkSync(path)
} catch {}
}
}

try {
writeFileSync(join(dir, createHash("sha256").update(key).digest("hex")), "", { flag: "wx", mode: 0o600 })
} catch (error) {
// Only an existing marker means another terminal claimed the event.
if ((error as NodeJS.ErrnoException).code === "EEXIST") return false
throw error
}
return true
} catch (error) {
debug(`marker unavailable (${(error as NodeJS.ErrnoException).code ?? "unknown"}); delivering`)
return true
}
writeFileSync(join(dir, createHash("sha256").update(key).digest("hex")), "", { flag: "wx" })
return true
} catch (error) {
return (error as NodeJS.ErrnoException).code !== "EEXIST"
}
}

export const claimDelivery = createDeliveryClaimer()
19 changes: 18 additions & 1 deletion src/terminal-clients.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterAll, expect, test } from "bun:test"
import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "fs"
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "fs"
import { tmpdir } from "os"
import { join } from "path"
import { createTerminalClients } from "./terminal-clients"
Expand Down Expand Up @@ -57,6 +57,23 @@ test("clients without UI state and a broken registry preserve fail-open alerts",
} finally { client.dispose() }
})

// Symlink creation on Windows can require privileges unavailable to the test runner.
test.skipIf(process.platform === "win32")("a symlinked shared directory skips presence without touching its target", async () => {
const { directory, location, files } = fixture()
const target = mkdtempSync(join(root, "target-"))
mkdirSync(join(target, "clients"))
// Looks like a stale peer; following the symlink would delete it.
const victim = join(target, "clients", "00000000-0000-0000-0000-000000000000.json")
writeFileSync(victim, "{}")
symlinkSync(target, join(files, ".."))
const client = createTerminalClients(() => ({ location, sessions: [] }))
try {
expect(await client.claim("question", "unknown")).toBe(true)
expect(readdirSync(join(target, "clients"))).toEqual(["00000000-0000-0000-0000-000000000000.json"])
expect(readdirSync(directory)).toHaveLength(1)
} finally { client.dispose() }
})

test("another workspace cannot take ownership of this client's event", async () => {
const { location } = fixture()
const other = createTerminalClients(() => ({ location, sessions: [] }))
Expand Down
Loading