Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(tray): claim the background-hint marker with one exclusive create

review4053767fd898
diff --git a/src/main/background-mode.test.ts b/src/main/background-mode.test.ts
index e49ed17c8..969597fc4 100644
--- a/src/main/background-mode.test.ts
+++ b/src/main/background-mode.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, it } from 'vitest'
-import { readFileSync } from 'fs'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'fs'
+import os from 'os'
import { join } from 'path'
-import { resolveBackgroundOnClose, shouldShowBackgroundHint } from './background-mode'
+import { claimOnceMarker, resolveBackgroundOnClose, shouldShowBackgroundHint } from './background-mode'
describe('resolveBackgroundOnClose', () => {
it("'auto' is on for Windows and off for Linux", () => {
@@ -48,3 +49,28 @@ describe('main/index.ts background-mode wiring (source guard)', () => {
expect(src).toMatch(/onAction: \(action\) => \(action === 'open' \? showMainWindowFromBackground\(\) : app\.quit\(\)\)/)
})
})
+
+describe('claimOnceMarker (exclusive create — no exists-then-write race)', () => {
+ it('claims once, then reports already; the first content is kept', () => {
+ const dir = mkdtempSync(join(os.tmpdir(), 'nt-bg-marker-'))
+ try {
+ const f = join(dir, 'marker')
+ expect(claimOnceMarker(f, 'first')).toBe('claimed')
+ expect(claimOnceMarker(f, 'second')).toBe('already')
+ expect(readFileSync(f, 'utf8')).toBe('first')
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+ it('reports failed (not already) when the marker cannot be written', () => {
+ const dir = mkdtempSync(join(os.tmpdir(), 'nt-bg-marker-'))
+ try {
+ expect(claimOnceMarker(join(dir, 'missing-dir', 'marker'), 'x')).toBe('failed')
+ // A directory squatting on the name is an existing entry: the notice is not repeated.
+ mkdirSync(join(dir, 'squat'))
+ expect(claimOnceMarker(join(dir, 'squat'), 'x')).toBe('already')
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/src/main/background-mode.ts b/src/main/background-mode.ts
index 37bb4b136..a5b1e62b3 100644
--- a/src/main/background-mode.ts
+++ b/src/main/background-mode.ts
@@ -5,6 +5,7 @@
// Pure + Electron-free so the policy is pressable on any CI box. The controller is ./tray.ts; the
// close-event decision is `closeAction` in ./main-window.ts, which takes the resolved flag.
+import { writeFileSync } from 'fs'
import type { BackgroundOnCloseSetting } from '../shared/types'
/**
@@ -51,3 +52,20 @@ export function shouldShowBackgroundHint(opts: {
}): boolean {
return opts.platform !== 'darwin' && opts.backgroundOnClose && !opts.alreadyShown
}
+
+/**
+ * Claim a once-per-install marker file in ONE step: an exclusive create (`wx` = O_CREAT|O_EXCL).
+ * `'claimed'` — we just created it, so this is the first time; `'already'` — it existed;
+ * `'failed'` — it could not be written for another reason (unwritable userData), which the caller
+ * treats like the old write failure: warn and still show. An exists-check followed by a separate
+ * write is a check-then-use race (CodeQL js/file-system-race) — two hides in quick succession could
+ * both see "absent" — and this answers both questions with one syscall.
+ */
+export function claimOnceMarker(file: string, content: string): 'claimed' | 'already' | 'failed' {
+ try {
+ writeFileSync(file, content, { flag: 'wx' })
+ return 'claimed'
+ } catch (e) {
+ return (e as NodeJS.ErrnoException).code === 'EEXIST' ? 'already' : 'failed'
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index b23ed71b1..1d80e34c5 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -9,7 +9,7 @@ import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sw
import { startTriggerService } from '../core/trigger-service'
import { readAgentSessionName, type AgentSessionNameDeps } from '../core/agent-session-name'
import { readFile, readdir as fsReaddir, realpath as fsRealpath, lstat as fsLstat, writeFile as fsWriteFile } from 'fs/promises'
-import { existsSync, statSync, openSync, fstatSync, readFileSync, closeSync, writeFileSync } from 'fs'
+import { existsSync, statSync, openSync, fstatSync, readFileSync, closeSync } from 'fs'
import { homedir, hostname } from 'os'
import { randomUUID } from 'crypto'
import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeImage, Notification, powerMonitor, safeStorage, screen, shell, systemPreferences, webContents } from 'electron'
@@ -268,7 +268,8 @@ import {
resolveBackgroundOnClose,
shouldShowBackgroundHint,
BACKGROUND_HINT,
- BACKGROUND_HINT_MARKER
+ BACKGROUND_HINT_MARKER,
+ claimOnceMarker
} from './background-mode'
import { createBackgroundTray, type BackgroundTray } from './tray'
import { normalizeUnread, trayIconPath, type TrayState } from './tray-model'
@@ -875,19 +876,12 @@ function syncBackgroundTray(): void {
/** The window was just hidden into the tray: tell the user once per install that the app is still
* running (on Windows a vanished window otherwise reads as "it quit"). */
function noteBackgroundHide(): void {
- const marker = join(app.getPath('userData'), BACKGROUND_HINT_MARKER)
- let alreadyShown = true
- try {
- alreadyShown = existsSync(marker)
- } catch {
- /* unreadable userData: err on the side of silence */
- }
- if (!shouldShowBackgroundHint({ platform: process.platform, backgroundOnClose: backgroundOnCloseActive(), alreadyShown })) return
- try {
- writeFileSync(marker, new Date().toISOString())
- } catch (e) {
- console.warn('[tray] could not record the background hint marker', e)
- }
+ // Policy first (platform + background mode), then claim the marker with ONE exclusive create —
+ // no exists-check followed by a separate write (see claimOnceMarker).
+ if (!shouldShowBackgroundHint({ platform: process.platform, backgroundOnClose: backgroundOnCloseActive(), alreadyShown: false })) return
+ const claim = claimOnceMarker(join(app.getPath('userData'), BACKGROUND_HINT_MARKER), new Date().toISOString())
+ if (claim === 'already') return
+ if (claim === 'failed') console.warn('[tray] could not record the background hint marker')
if (!Notification.isSupported()) return
const n = new Notification({ title: BACKGROUND_HINT.title, body: BACKGROUND_HINT.body })
n.on('click', showMainWindowFromBackground)