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(agents): status badges died after macOS close→dock-reopen (stale window ref)

enes3ea26d9a3ea2
diff --git a/src/main/index.ts b/src/main/index.ts
index 974f3c277..899b93bdd 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -13,6 +13,7 @@ import { generateCommitMessage, generateGroupName, generateTerminalName } from '
import { initUpdater } from './updater'
import { fetchCheck } from './check'
import { hookServer } from './agents/hook-server'
+import { setMainWindow, getMainWindow, sendToMain, shouldHideOnClose } from './main-window'
import { installManagedAgentHooks } from './agents/hooks'
import { createSubagentTail } from './subagent-tail'
import { createContextTail } from './context-tail'
@@ -83,9 +84,11 @@ let sshProjectManager: ReturnType<typeof initSshProject> | undefined
// project switch: the active SSH project's ref, or null for a local project (→ all git runs local).
let activeRemote: { cwd: string; ref: GitRemoteRef } | null = null
-// The single app window — kept at module scope so IPC handlers (e.g. notifications)
-// can check focus and route clicks back to the renderer.
-let mainWin: BrowserWindow | null = null
+// The single app window is tracked in ./main-window (setMainWindow/getMainWindow) and
+// resolved AT SEND TIME everywhere — a closure-captured window goes stale after the
+// macOS close→dock-reopen cycle and silently swallows every send.
+// True from the first before-quit on: lets window close-events through (see hide-on-close).
+let quitting = false
// Browser <webview> guest webContents id → its browser node id (for new-window capture).
const browserGuests = new Map<number, string>()
@@ -105,10 +108,11 @@ if (!gotSingleInstanceLock) {
app.quit()
} else {
app.on('second-instance', () => {
- if (!mainWin) return
- if (mainWin.isMinimized()) mainWin.restore()
- mainWin.show()
- mainWin.focus()
+ const win = getMainWindow()
+ if (!win) return
+ if (win.isMinimized()) win.restore()
+ win.show()
+ win.focus()
})
}
@@ -137,8 +141,22 @@ function createWindow(): BrowserWindow {
}
})
+ // Register as the live main window (send-time resolution via getMainWindow/sendToMain).
+ setMainWindow(win)
+
win.on('ready-to-show', () => win.show())
+ // macOS: closing the window hides it instead of destroying it. The app deliberately
+ // outlives its window (tmux sessions, hook server, updater); destroying the window
+ // would leave every window-bound subsystem (agent-status forwarding, tails, updater,
+ // license events) pointing at a dead webContents after a dock-reopen.
+ win.on('close', (e) => {
+ if (shouldHideOnClose(process.platform, quitting)) {
+ e.preventDefault()
+ win.hide()
+ }
+ })
+
// Intercept Cmd/Ctrl+M (default = minimize) and route it to the renderer for the
// markdown-view toggle instead.
win.webContents.on('before-input-event', (event, input) => {
@@ -199,8 +217,8 @@ app.whenReady().then(async () => {
// live at call time, so a guest registered later (on dom-ready) is seen when a popup fires.
contents.setWindowOpenHandler(({ url }) => {
const sourceNodeId = browserGuests.get(contents.id)
- if (sourceNodeId && /^https?:\/\//i.test(url) && mainWin && !mainWin.isDestroyed()) {
- mainWin.webContents.send(IPC.browserNewWindow, { url, sourceNodeId })
+ if (sourceNodeId && /^https?:\/\//i.test(url)) {
+ sendToMain(IPC.browserNewWindow, { url, sourceNodeId })
}
return { action: 'deny' }
})
@@ -258,17 +276,20 @@ app.whenReady().then(async () => {
ipcMain.handle(
IPC.appNotify,
(_e, payload: { title: string; body: string; nodeId: string; force?: boolean }) => {
- if (!mainWin || !Notification.isSupported()) return false
+ const win = getMainWindow()
+ if (!win || !Notification.isSupported()) return false
// `force` (permission request / confirmation) shows even when focused; normal
// completion notifications only show when the window is in the background.
- if (!payload.force && mainWin.isFocused()) return false
+ if (!payload.force && win.isFocused()) return false
const n = new Notification({ title: payload.title, body: payload.body })
n.on('click', () => {
- if (!mainWin) return
- if (mainWin.isMinimized()) mainWin.restore()
- mainWin.show()
- mainWin.focus()
- if (payload.nodeId) mainWin.webContents.send(IPC.appFocusNode, payload.nodeId)
+ // Re-resolve at click time — the window may have been hidden/recreated since.
+ const w = getMainWindow()
+ if (!w) return
+ if (w.isMinimized()) w.restore()
+ w.show()
+ w.focus()
+ if (payload.nodeId) w.webContents.send(IPC.appFocusNode, payload.nodeId)
})
n.show()
return true
@@ -340,7 +361,6 @@ app.whenReady().then(async () => {
})
const win = createWindow()
- mainWin = win
initUpdater(win)
// Agent hooks: install the managed hook script into each agent's config, then start the
@@ -459,9 +479,7 @@ app.whenReady().then(async () => {
buildHandoff({ sessionId, agentId, sourceNodeId, cwd })
)
installManagedAgentHooks()
- hookServer.setListener((e) => {
- if (!win.isDestroyed()) win.webContents.send(IPC.agentStatus, e)
- })
+ hookServer.setListener((e) => sendToMain(IPC.agentStatus, e))
// Security: hook POSTs now arrive over the remote reverse tunnel too (SSH Phase 2a), so a
// forged/remote POST could set transcript_path to an arbitrary LOCAL path (e.g. ~/.ssh/id_rsa)
// and have the app read it. The tails read the LOCAL filesystem; legitimate LOCAL transcripts
@@ -615,7 +633,8 @@ app.whenReady().then(async () => {
}
)
hookServer.setControlHandler(async ({ verb, nodeId, args }) => {
- if (!mainWin || mainWin.isDestroyed()) return { ok: false, error: 'window unavailable' }
+ const target = getMainWindow()
+ if (!target) return { ok: false, error: 'window unavailable' }
const requestId = randomUUID()
return await new Promise((resolve) => {
const timer = setTimeout(() => {
@@ -623,7 +642,7 @@ app.whenReady().then(async () => {
resolve({ ok: false, error: 'timed out (no response / not confirmed)' })
}, 120_000)
pendingControl.set(requestId, { resolve, timer })
- mainWin!.webContents.send(IPC.agentControl, { requestId, sourceNodeId: nodeId, verb, args })
+ target.webContents.send(IPC.agentControl, { requestId, sourceNodeId: nodeId, verb, args })
})
})
await hookServer.start()
@@ -652,7 +671,16 @@ app.whenReady().then(async () => {
})
app.on('activate', () => {
- if (BrowserWindow.getAllWindows().length === 0) createWindow()
+ // With hide-on-close the window usually still exists — just re-show it. Only a truly
+ // gone window (e.g. renderer crash) is recreated; createWindow re-registers it as the
+ // main window, so send-time resolution keeps agent-status forwarding alive.
+ const existing = getMainWindow()
+ if (existing) {
+ existing.show()
+ existing.focus()
+ } else if (BrowserWindow.getAllWindows().length === 0) {
+ createWindow()
+ }
})
})
@@ -671,6 +699,7 @@ app.on('window-all-closed', () => {
// the quit just long enough for them to land, capped so a hung tmux can never block quit.
let quitFlushed = false
app.on('before-quit', (e) => {
+ quitting = true // from here on, window close-events must NOT be turned into hide
sshProjectManager?.disconnectAll()
if (quitFlushed) return
quitFlushed = true
diff --git a/src/main/main-window.test.ts b/src/main/main-window.test.ts
new file mode 100644
index 000000000..f2c62bfc8
--- /dev/null
+++ b/src/main/main-window.test.ts
@@ -0,0 +1,107 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { setMainWindow, getMainWindow, sendToMain, shouldHideOnClose, type MainWindowLike } from './main-window'
+
+function fakeWindow(): MainWindowLike & {
+ sent: [string, ...unknown[]][]
+ destroy(): void
+ emitClosed(): void
+} {
+ let destroyed = false
+ const closedListeners: (() => void)[] = []
+ const sent: [string, ...unknown[]][] = []
+ return {
+ sent,
+ isDestroyed: () => destroyed,
+ isFocused: () => false,
+ isMinimized: () => false,
+ restore: vi.fn(),
+ show: vi.fn(),
+ focus: vi.fn(),
+ on: (event: 'closed', cb: () => void) => {
+ if (event === 'closed') closedListeners.push(cb)
+ },
+ webContents: {
+ send: (channel: string, ...args: unknown[]) => {
+ sent.push([channel, ...args])
+ }
+ },
+ destroy() {
+ destroyed = true
+ },
+ emitClosed() {
+ closedListeners.forEach((cb) => cb())
+ }
+ }
+}
+
+describe('main-window tracking', () => {
+ beforeEach(() => {
+ // Reset module state between tests: register a fresh window then let it close.
+ const w = fakeWindow()
+ setMainWindow(w)
+ w.destroy()
+ w.emitClosed()
+ })
+
+ it('sendToMain delivers to the registered window', () => {
+ const w = fakeWindow()
+ setMainWindow(w)
+ sendToMain('agent:status', { nodeId: 'n1' })
+ expect(w.sent).toEqual([['agent:status', { nodeId: 'n1' }]])
+ })
+
+ it('sendToMain is a silent no-op once the window is destroyed', () => {
+ const w = fakeWindow()
+ setMainWindow(w)
+ w.destroy()
+ expect(() => sendToMain('agent:status', {})).not.toThrow()
+ expect(w.sent).toEqual([])
+ expect(getMainWindow()).toBeNull()
+ })
+
+ // The original bug: hook events were bound to the FIRST window via closure, so after
+ // the macOS close→dock-reopen cycle every agent:status event was dropped forever.
+ it('sendToMain reaches a replacement window registered after the first one died', () => {
+ const first = fakeWindow()
+ setMainWindow(first)
+ first.destroy()
+ first.emitClosed()
+
+ const second = fakeWindow()
+ setMainWindow(second)
+ sendToMain('agent:status', { state: 'working' })
+
+ expect(first.sent).toEqual([])
+ expect(second.sent).toEqual([['agent:status', { state: 'working' }]])
+ expect(getMainWindow()).toBe(second)
+ })
+
+ it("a stale 'closed' from the old window does not clear a newer registration", () => {
+ const first = fakeWindow()
+ setMainWindow(first)
+ const second = fakeWindow()
+ setMainWindow(second)
+ first.emitClosed() // old window's closed event arrives late
+ expect(getMainWindow()).toBe(second)
+ })
+
+ it('getMainWindow returns null when nothing was registered or after closed', () => {
+ const w = fakeWindow()
+ setMainWindow(w)
+ w.emitClosed()
+ expect(getMainWindow()).toBeNull()
+ })
+})
+
+describe('shouldHideOnClose', () => {
+ it('hides instead of closing on macOS while the app is not quitting', () => {
+ expect(shouldHideOnClose('darwin', false)).toBe(true)
+ })
+ it('lets the close through when the app is quitting', () => {
+ expect(shouldHideOnClose('darwin', true)).toBe(false)
+ })
+ it('never intercepts close on other platforms', () => {
+ expect(shouldHideOnClose('win32', false)).toBe(false)
+ expect(shouldHideOnClose('linux', false)).toBe(false)
+ })
+})
diff --git a/src/main/main-window.ts b/src/main/main-window.ts
new file mode 100644
index 000000000..0759e3abc
--- /dev/null
+++ b/src/main/main-window.ts
@@ -0,0 +1,43 @@
+// Live main-window tracking. Everything in the main process that pushes IPC to the
+// renderer must resolve the window AT SEND TIME via getMainWindow()/sendToMain() —
+// never capture a BrowserWindow in a closure at init. On macOS the window can be
+// closed (app stays alive) and recreated from the dock; a captured reference then
+// points at a destroyed window and every send is silently dropped (that bug shipped:
+// agent status badges died after a close→reopen cycle).
+
+// Structural view of BrowserWindow (keeps this module electron-free and unit-testable).
+export interface MainWindowLike {
+ isDestroyed(): boolean
+ isFocused(): boolean
+ isMinimized(): boolean
+ restore(): void
+ show(): void
+ focus(): void
+ on(event: 'closed', cb: () => void): void
+ webContents: { send(channel: string, ...args: unknown[]): void }
+}
+
+let current: MainWindowLike | null = null
+
+export function setMainWindow(win: MainWindowLike): void {
+ current = win
+ win.on('closed', () => {
+ // Guard: a late 'closed' from a replaced window must not clear its successor.
+ if (current === win) current = null
+ })
+}
+
+export function getMainWindow(): MainWindowLike | null {
+ return current && !current.isDestroyed() ? current : null
+}
+
+export function sendToMain(channel: string, ...args: unknown[]): void {
+ getMainWindow()?.webContents.send(channel, ...args)
+}
+
+// macOS convention: closing the window hides it (the app — and its tmux sessions,
+// hook server, updater, license watchers — keeps running); a real close only happens
+// on quit. Other platforms quit on window close, so never intercept there.
+export function shouldHideOnClose(platform: NodeJS.Platform | string, quitting: boolean): boolean {
+ return platform === 'darwin' && !quitting
+}