diff --git a/CHANGELOG.md b/CHANGELOG.md index c0d990f..7255d03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 1ea1ab0..e6bab26 100644 --- a/README.md +++ b/README.md @@ -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-` 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: diff --git a/SPEC.md b/SPEC.md index 87c8f7d..7efa6a3 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. 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. diff --git a/src/claim.test.ts b/src/claim.test.ts index 23bedc9..a93d8d8 100644 --- a/src/claim.test.ts +++ b/src/claim.test.ts @@ -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) }) diff --git a/src/claim.ts b/src/claim.ts index def537d..cd75ccc 100644 --- a/src/claim.ts +++ b/src/claim.ts @@ -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() diff --git a/src/terminal-clients.test.ts b/src/terminal-clients.test.ts index 3ba84e8..f86285e 100644 --- a/src/terminal-clients.test.ts +++ b/src/terminal-clients.test.ts @@ -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" @@ -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: [] })) diff --git a/src/terminal-clients.ts b/src/terminal-clients.ts index 84cb91c..202f877 100644 --- a/src/terminal-clients.ts +++ b/src/terminal-clients.ts @@ -2,7 +2,7 @@ import { randomUUID } from "crypto" import { mkdir, readdir, readFile, rename, unlink, writeFile } from "fs/promises" import { tmpdir } from "os" import { join } from "path" -import { claimDelivery } from "./claim" +import { claimDelivery, sharedDirectory } from "./claim" import { debugFocusState as debug } from "./focus" export interface TerminalState { @@ -32,8 +32,10 @@ function alive(pid: number): boolean { // Presence is separate from the event claim: a slower client with this session // open must be preferred before a faster, unrelated client wins the claim. export function createTerminalClients(getState: () => TerminalState, rootSession: (sessionID: string) => string = id => id) { - const directory = join(tmpdir(), `opencode-notifier-${process.getuid?.() ?? "claims"}`, "clients") - const path = join(directory, `${randomUUID()}.json`) + const tempRoot = tmpdir() + const fileName = `${randomUUID()}.json` + // Our presence file, once written. Unsafe shared storage skips presence entirely. + let path: string | undefined let disposed = false let state: TerminalState | undefined let writing: Promise | undefined @@ -42,19 +44,25 @@ export function createTerminalClients(getState: () => TerminalState, rootSession if (disposed) return try { state = getState() } catch { return } if (writing) return bounded(writing, undefined) + const shared = sharedDirectory(tempRoot) + if (!shared) return + const directory = join(shared, "clients") + const target = join(directory, fileName) const snapshot = state writing = (async () => { - const temporary = path + ".tmp" + const temporary = target + ".tmp" try { await mkdir(directory, { recursive: true, mode: 0o700 }) await writeFile(temporary, JSON.stringify({ pid: process.pid, updated: Date.now(), location: snapshot.location, sessions: snapshot.sessions?.slice(0, 2048) ?? null, }), { mode: 0o600 }) - if (!disposed) await rename(temporary, path) - else await unlink(temporary) + if (!disposed) { + await rename(temporary, target) + path = target + } else await unlink(temporary) // Disposal can race the asynchronous rename. - if (disposed) await unlink(path).catch(() => {}) + if (disposed) await unlink(target).catch(() => {}) } catch { await unlink(temporary).catch(() => {}) } })().finally(() => { writing = undefined }) await bounded(writing, undefined) @@ -62,12 +70,14 @@ export function createTerminalClients(getState: () => TerminalState, rootSession async function anotherOwner(sessionID: string, root: string): Promise { const current = state - if (!current) return false + const shared = sharedDirectory(tempRoot) + if (!current || !shared) return false + const directory = join(shared, "clients") return bounded((async () => { const names = (await readdir(directory)).filter(name => /^[\da-f-]{36}\.json$/.test(name)).slice(0, 256) const matches = await Promise.all(names.map(async name => { const candidate = join(directory, name) - if (candidate === path) return false + if (name === fileName) return false try { const raw = await readFile(candidate, "utf8") if (raw.length > 256_000) return false @@ -113,7 +123,7 @@ export function createTerminalClients(getState: () => TerminalState, rootSession dispose() { disposed = true clearInterval(heartbeat) - void unlink(path).catch(() => {}) + if (path) void unlink(path).catch(() => {}) }, } } diff --git a/src/v2.regression.test.ts b/src/v2.regression.test.ts index 8defeaa..4cd0712 100644 --- a/src/v2.regression.test.ts +++ b/src/v2.regression.test.ts @@ -5,18 +5,17 @@ import { tmpdir } from "os" import { createV2Notifier } from "./v2" import type { Delivery } from "./notifier" import type { OpenCodeEvent, SessionMessageUser } from "@opencode/client" +import { createDeliveryClaimer } from "./claim" const fixture = mkdtempSync(join(tmpdir(), "notifier-v2-test-")) const configPath = join(fixture, "config.json") const commandLog = join(fixture, "commands.txt") const commandScript = join(fixture, "record-command.mjs") writeFileSync(commandScript, 'import { appendFileSync } from "node:fs"; appendFileSync(process.argv[2], process.argv[3]+"\\n")') -// Delivery claims are machine-wide marker files under the temp directory; keep them in the fixture. -const oldTmpdir = process.env.TMPDIR -process.env.TMPDIR = fixture +// Share on-disk claims across simulated terminals inside an isolated temp root, +// so these tests never read or write a running session's markers. +const claim = createDeliveryClaimer(fixture) afterAll(() => { - if (oldTmpdir === undefined) delete process.env.TMPDIR - else process.env.TMPDIR = oldTmpdir rmSync(fixture, { recursive: true, force: true }) }) let eventID = 0 @@ -65,7 +64,7 @@ async function exercise(events: OpenCodeEvent[], options: { context: async () => [{ id: "message", type: "user", text: "hello", time: { created: Date.now() - (options.messageAge ?? 1000) } } satisfies SessionMessageUser], }, permission: { list: async () => [] }, - } as never, { directory: fixture }, options.delivery ?? "terminal") + } as never, { directory: fixture }, options.delivery ?? "terminal", { claim: async (key, _sessionID, valid) => valid() && claim(key) }) try { for (const input of events) await notifier.event(input) return writes.filter(w => w.includes("PROBE_"))