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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(windows): keep running in the tray, set the AUMID, badge the taskbar
review3ec12dcc20f2
diff --git a/CLAUDE.md b/CLAUDE.mdindex 640506558..16cdaa88b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -724,6 +724,17 @@ Lifecycle, by intent:`'off'` drops GPU rendering entirely.- **Window close / app quit** → clients detach (`PtyManager.killAll()`); the tmux session keepsrunning. `killAll()` deliberately does NOT kill sessions.+- **Window close off macOS = background mode** (`settings.runInBackgroundOnClose`, `'auto'` = on for+ Windows, off for Linux; `resolveBackgroundOnClose` in `main/background-mode.ts`): the × HIDES the+ window into a notification-area tray (`main/tray.ts`, pure model `tray-model.ts`: Open / unread /+ phone-access status / Quit) so the phone relay host, hook server, notifications and updater keep+ running — the Dock analogue. A hide is not a quit, so no confirm dialog; tray **Quit** is plain+ `app.quit()` (before-quit + confirm run as for Ctrl+Q — never set `quitting` before it, a cancelled+ confirm must leave the × hiding). Hide only while the tray actually EXISTS+ (`backgroundOnCloseActive`), so a failed tray never turns × into a hide with no way back. The+ updater/update-prep quits keep flipping `quitting` first, or a hidden window would block them.+ First hide posts a one-time toast (userData marker file, not a settings key — the renderer's+ full-snapshot saves would overwrite a main-side settings write).- **Node reopen / app relaunch** (nothing parked) → a new PTY attaches to the same`nt-<nodeId>` session and tmux redraws current state.- **User clicks ×** → `destroy(persistKey)` runs `tmux kill-session`, permanently ending it. For a@@ -3296,6 +3307,12 @@ command-bearing opens; this does not add a human-confirm dialog or change mobileSettings (`notifyOnClaudeDone`). Selecting, focusing, dwelling into, or opening a session cardclears `unread` and ACKs the finish across phone/notch surfaces — existing read-on-view behavior.This NEVER changes the workflow bucket: read state is independent from agent state.+ The unread COUNT is the macOS Dock badge, and on **Windows** a taskbar overlay icon (pure+ `planBadge` + BGRA rasterizer `rasterizeBadge`, "9+" above nine, `main/taskbar-badge.ts`) plus a+ `flashFrame` when the count RISES while unfocused (cleared on focus); Linux shows nothing. Windows+ toasts need `app.setAppUserModelId` set before ready to the package.json `build.appId` the NSIS+ shortcut carries (`main/app-identity.ts`, pinned by test; `execPath` in dev) — without it toasts+ are dropped or mis-attributed silently (Windows never emits Notification `failed`).- **Sound alerts + custom sounds** (issue #289) — the `done` / `needsYou` alert (`SfxKind`) is asynthesized WebAudio chime (`renderer/lib/sfx.ts`, fired from Canvas's `alert` closure, gated by`soundEffects`, 5 s/node cooldown). Settings → Notifications lets the user replace either with theirdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex d258adf6a..94ff64457 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -499,6 +499,12 @@ anything else. Board-level fields survive every transform — `pullLinks` is onearguments and lines above cmd's limit fail explicitly. Keep stdin direct: PowerShell's textpipeline changes Unicode and line endings under Windows PowerShell 5.1.+- **Closing the window on Windows hides it to the tray (background mode), it does not quit.** The+ relay host, hook server and notifications must outlive the window there as they do on macOS. Any+ new app-initiated quit (updater-style) must set `quitting` before `app.quit()`, or the hidden+ window's close handler turns the quit back into a hide. Every new raise (`show`/`focus`) needs a+ user action and an entry in `window-raise.guard.test.ts`.+- **The phone reaches a Windows desktop through the relay only.** Everything the iOS app sends overSSH is POSIX sh plus tmux, and Windows OpenSSH hands out `cmd.exe`, so Windows pairing installs noSSH key and requires remote access instead of an SSH server (`src/shared/pairing-gate.ts`). Do notdiff --git a/src/main/index.ts b/src/main/index.tsindex 3372a392a..98963a90b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -9,10 +9,10 @@ import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-swimport { startTriggerService } from '../core/trigger-service'import { readAgentSessionName, type AgentSessionNameDeps } from '../core/agent-session-name'import { readFile, realpath as fsRealpath, lstat as fsLstat, writeFile as fsWriteFile } from 'fs/promises'-import { existsSync, statSync, openSync, fstatSync, readFileSync, closeSync } from 'fs'+import { existsSync, statSync, openSync, fstatSync, readFileSync, closeSync, writeFileSync } from 'fs'import { homedir, hostname } from 'os'import { randomUUID } from 'crypto'-import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, Notification, powerMonitor, safeStorage, screen, shell, systemPreferences, webContents } from 'electron'+import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeImage, Notification, powerMonitor, safeStorage, screen, shell, systemPreferences, webContents } from 'electron'import { IPC } from '../shared/ipc'// Debug log ring (issue #78): capture the process console from the first line — a packaged app@@ -260,6 +260,16 @@ import { PUSH_WEBHOOK_DEFAULT_API_BASE } from '../shared/push-webhook'import { initRemoteStatusPush } from './remote-ssh/remote-status-push'import { initCanvasSync } from '../core/canvas-sync'import { retainUntilDismissed } from './notifications'+import { appUserModelIdFor, notificationSettingsTarget } from './app-identity'+import {+ resolveBackgroundOnClose,+ shouldShowBackgroundHint,+ BACKGROUND_HINT,+ BACKGROUND_HINT_MARKER+} from './background-mode'+import { createBackgroundTray, type BackgroundTray } from './tray'+import { normalizeUnread, trayIconPath, type TrayState } from './tray-model'+import { planBadge, rasterizeBadge } from './taskbar-badge'import { createSubagentTail } from '../core/subagent-tail'import { ClaudeSubagentLifecycle } from '../core/claude-subagent-lifecycle'import { claudeSubagentTranscriptPath, isClaudeAgentId } from '../shared/agents/claude-subagents'@@ -786,8 +796,11 @@ function confirmQuit(parentWin: BrowserWindow | null): Promise<boolean> {message: 'Quit nodeterm?',detail: 'Terminal sessions keep running in the background and will still be here next time you open nodeterm.'}- const p =- parentWin && !parentWin.isDestroyed() ? dialog.showMessageBox(parentWin, opts) : dialog.showMessageBox(opts)+ // Off macOS a background-mode window may be HIDDEN (tray Quit): a dialog parented to it would be+ // modal to an invisible window, so it is shown unparented there. macOS keeps its sheet as before.+ const parentUsable =+ !!parentWin && !parentWin.isDestroyed() && (process.platform === 'darwin' || parentWin.isVisible())+ const p = parentUsable && parentWin ? dialog.showMessageBox(parentWin, opts) : dialog.showMessageBox(opts)return p.then(({ response }) => {quitConfirmationPending = falseconst confirmed = response === 1@@ -796,6 +809,87 @@ function confirmQuit(parentWin: BrowserWindow | null): Promise<boolean> {})}+// Windows/Linux background mode (src/main/background-mode.ts): with it on, closing the window hides+// it to a notification-area tray instead of quitting, so the phone relay host, hook server,+// notifications and updater keep running — what the Dock does for macOS. The tray exists exactly+// while the mode resolves on (`syncBackgroundTray`, on boot + every settings change) and is torn+// down in before-quit. Its state is fed from facts main already holds — the unread count the+// renderer sends for the badge, and the phone-access setting — never from the hook-event stream.+let backgroundTray: BackgroundTray | undefined+const trayState: TrayState = { unread: 0, phoneAccess: false }++/** Hide-on-close is in force off macOS only while the tray actually exists: a tray that failed to+ * construct must not turn the window's × into a hide with no way back. */+function backgroundOnCloseActive(): boolean {+ return process.platform !== 'darwin' && !!backgroundTray+}++function showMainWindowFromBackground(): void {+ const w = getMainWindow()+ if (w) {+ if (w.isMinimized()) w.restore()+ w.show()+ w.focus()+ } else if (BrowserWindow.getAllWindows().length === 0) {+ createWindow()+ }+}++function syncBackgroundTray(): void {+ const s = settingsStore.get()+ trayState.phoneAccess = !!s.phoneAccessEnabled+ const want = !quitting && resolveBackgroundOnClose(s.runInBackgroundOnClose, process.platform)+ if (!want) {+ backgroundTray?.destroy()+ backgroundTray = undefined+ return+ }+ if (backgroundTray) {+ backgroundTray.update({ ...trayState })+ return+ }+ try {+ backgroundTray = createBackgroundTray({+ iconPath: trayIconPath({+ isPackaged: app.isPackaged,+ resourcesPath: process.resourcesPath,+ devBuildDir: join(__dirname, '../../build'),+ join+ }),+ initial: { ...trayState },+ // Quit is the ordinary app.quit(): before-quit (and its confirm dialog) runs exactly as for+ // Ctrl+Q. `quitting` is NOT set here — a cancelled confirm must leave the × hiding again.+ onAction: (action) => (action === 'open' ? showMainWindowFromBackground() : app.quit())+ })+ } catch (e) {+ console.warn('[tray] could not create the notification-area icon; window close will quit', e)+ backgroundTray = undefined+ }+}++/** 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)+ }+ if (!Notification.isSupported()) return+ const n = new Notification({ title: BACKGROUND_HINT.title, body: BACKGROUND_HINT.body })+ n.on('click', showMainWindowFromBackground)+ retainUntilDismissed(n)+ n.show()+}+// Keep-awake tracker (created in whenReady next to the notch HUD, disposed in before-quit).let keepAwake: KeepAwakeTracker | undefined@@ -816,6 +910,13 @@ const nodeSubagents = new Map<string, Set<string>>() // nodeId → active subage// (`new-session -A -D`), whose `-D` detaches the first instance's clients — leaving// "[detached (from session ...)]" dead terminals. Bail out and focus the existing window// instead. (This guards against a stray real GUI launch.)+// Windows toast identity, BEFORE any Notification and before ready (src/main/app-identity.ts):+// without it Electron's generated `electron.app.<name>` id matches no Start-menu shortcut and+// toasts are dropped or mis-attributed — silently. Null (no call) on macOS/Linux.+{+ const aumid = appUserModelIdFor({ platform: process.platform, isPackaged: app.isPackaged, execPath: process.execPath })+ if (aumid) app.setAppUserModelId(aumid)+}const gotSingleInstanceLock = NT_MULTI || app.requestSingleInstanceLock()if (!gotSingleInstanceLock) {app.quit()@@ -1257,6 +1358,8 @@ function createWindow(): BrowserWindow {// The main window is a regular app window; establishing its Dock presence explicitly means the// later focusable:false Notch HUD panel can never leave the app looking like an accessory.win.on('show', () => assertRegularDockPresence())+ // Windows: the taskbar flash raised by an unread rise (appSetBadge) ends when the user comes back.+ if (process.platform === 'win32') win.on('focus', () => win.flashFrame(false))// macOS: closing the window hides it instead of destroying it. The app deliberately// outlives its window (tmux sessions, hook server, updater); destroying the window@@ -1268,10 +1371,12 @@ function createWindow(): BrowserWindow {// keeps a second ⌘W during the transition from stacking another listener.let leavingFullScreen = falsewin.on('close', (e) => {- const action = closeAction(process.platform, quitting, win.isFullScreen())+ const action = closeAction(process.platform, quitting, win.isFullScreen(), backgroundOnCloseActive())if (action === 'hide') {e.preventDefault()win.hide()+ // Off macOS this is a background-mode hide (nothing is quitting, so no confirm gate either).+ if (process.platform !== 'darwin') noteBackgroundHide()return}if (action === 'leave-fullscreen-then-hide') {@@ -1730,10 +1835,29 @@ app.whenReady().then(async () => {}))- // Dock badge: number of Claude nodes with unread output (macOS only). '' clears it.+ // Unread badge: number of agent nodes with unread output. macOS → the Dock badge ('' clears);+ // Windows → a taskbar overlay icon + a flash when the count rises in the background; Linux →+ // nothing. The decision is the pure `planBadge` (taskbar-badge.ts). The same count feeds the+ // background-mode tray's tooltip/menu (de-duplicated there, so a resend rebuilds nothing).+ let lastBadgeCount = 0ipcMain.on(IPC.appSetBadge, (_e, count: number) => {- if (process.platform !== 'darwin' || !app.dock) return- app.dock.setBadge(count > 0 ? String(count) : '')+ const n = normalizeUnread(count)+ const win = getMainWindow() as unknown as BrowserWindow | null+ const plan = planBadge(process.platform, n, lastBadgeCount, !!win?.isFocused())+ lastBadgeCount = n+ trayState.unread = n+ backgroundTray?.update({ ...trayState })+ if (plan.dock !== undefined && app.dock) app.dock.setBadge(plan.dock)+ if (plan.overlay !== undefined && win && !win.isDestroyed()) {+ if (plan.overlay === null) {+ win.setOverlayIcon(null, '')+ } else {+ const img = nativeImage.createFromBitmap(rasterizeBadge(plan.overlay.label, 16), { width: 16, height: 16 })+ img.addRepresentation({ scaleFactor: 2, width: 32, height: 32, buffer: rasterizeBadge(plan.overlay.label, 32) })+ win.setOverlayIcon(img, plan.overlay.description)+ }+ }+ if (plan.flash && win && !win.isDestroyed()) win.flashFrame(true)})// Show an OS notification — but only when the window is in the background. Clicking it@@ -1785,8 +1909,8 @@ app.whenReady().then(async () => {// main-side constant — deliberately NOT routed through shellOpenExternal's// http(s)-only allowlist, which must stay closed to renderer-supplied strings.ipcMain.handle(IPC.appOpenNotificationSettings, () => {- if (process.platform !== 'darwin') return- void shell.openExternal('x-apple.systempreferences:com.apple.Notifications-Settings.extension')+ const target = notificationSettingsTarget(process.platform)+ if (target) void shell.openExternal(target)})ipcMain.handle(IPC.announcementsFetch, async () => (await fetchCheck()).messages)@@ -2212,6 +2336,10 @@ app.whenReady().then(async () => {return undefined})const win = createWindow()+ // Windows/Linux background-mode tray — created now if the mode resolves on, and re-synced on+ // every settings change (the Behavior toggle, and the phone-access row it shows).+ syncBackgroundTray()+ settingsStore.onChange(() => syncBackgroundTray())if (hookStartupWarning) {console.error('[agent-hooks]', hookStartupWarning)void dialog.showMessageBox(win, { type: 'warning', title: 'Agent hooks unavailable', message: hookStartupWarning })@@ -5073,6 +5201,9 @@ app.whenReady().then(async () => {app.on('window-all-closed', () => {// On macOS the app stays alive, so the async final snapshots inside killAll can complete// in the background; on other platforms quitting goes through before-quit below.+ // Background mode (Windows/Linux) hides rather than closes, so reaching here with it on means+ // the window was destroyed some other way — the tray stays, and its Open recreates the window.+ if (process.platform !== 'darwin' && !quitting && backgroundOnCloseActive()) returnif (process.platform !== 'darwin') {app.quit()} else {@@ -5105,6 +5236,8 @@ app.on('before-quit', (e) => {}quitting = true // from here on, window close-events must NOT be turned into hidedestroyNotchHud()+ backgroundTray?.destroy()+ backgroundTray = undefined// Electron releases power assertions at exit anyway; disposing keeps the hold/release log// honest. Clearing the ref too keeps a hook edge that lands during the quit flush (the pty// teardown window below) from re-holding an assertion nothing will ever release.diff --git a/src/main/window-raise.guard.test.ts b/src/main/window-raise.guard.test.tsindex 4416e6f83..6cf845f5b 100644--- a/src/main/window-raise.guard.test.ts+++ b/src/main/window-raise.guard.test.ts@@ -54,13 +54,17 @@ const ALLOWED = new Map<string, { calls: number; why: string }>([['index.ts',{- calls: 14,+ calls: 18,why:'3 second-instance restore/show/focus (the user launched the app again); 1 first-paint ' +'show (once, never on — #737); 4 file-drop IPC restore/show/app.focus(steal)/focus, now ' +'sender-guarded (a real drop, and macOS does not activate a drop destination by itself); ' +'3 notification-CLICK restore/show/focus — the one legitimate exception, a tap; 1 ' +- "Notification.show() posting it; 2 app.on('activate') show/focus (Dock click)"+ "Notification.show() posting it; 2 app.on('activate') show/focus (Dock click); 3 " ++ 'showMainWindowFromBackground restore/show/focus — reached only from a tray click / tray ' ++ '"Open nodeterm" / a click on the background-hint toast (Windows/Linux background mode); ' ++ "1 Notification.show() posting that one-time hint, raised by the user's own window close " ++ '(a notification is not a window raise). The taskbar flashFrame(true) is attention, not a raise'}],[