Skip to content

Commit 079f17a

Browse files
feat(desktop): close to tray instead of exiting
- Windows/Linux: closing the last window hides it to the system tray so background agent work keeps running; tray menu offers Show/Quit and single/double click restores the window. - macOS: no behavior change (native close-to-Dock preserved). - Real quits (tray Quit, app menu, Cmd+Q, SIGTERM) close normally. - Pure resolveCloseAction decision logic with unit tests; tray module mocked-tested; window registry exposes isQuitting(). Closes anomalyco#18134 (desktop close-to-tray)
1 parent 0bff28d commit 079f17a

8 files changed

Lines changed: 304 additions & 3 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { resolveCloseAction } from "./close-behavior"
3+
4+
const win = { isQuitting: false, otherWindows: 0, platform: "win32" as NodeJS.Platform }
5+
6+
describe("resolveCloseAction", () => {
7+
test("hides the last window while the app is running (windows)", () => {
8+
expect(resolveCloseAction(win)).toBe("hide")
9+
})
10+
11+
test("hides the last window while the app is running (linux)", () => {
12+
expect(resolveCloseAction({ ...win, platform: "linux" })).toBe("hide")
13+
})
14+
15+
test("closes a window when others remain open", () => {
16+
expect(resolveCloseAction({ ...win, otherWindows: 1 })).toBe("close")
17+
expect(resolveCloseAction({ ...win, otherWindows: 3 })).toBe("close")
18+
})
19+
20+
test("closes every window during a real quit", () => {
21+
expect(resolveCloseAction({ ...win, isQuitting: true })).toBe("close")
22+
expect(resolveCloseAction({ ...win, isQuitting: true, otherWindows: 2 })).toBe("close")
23+
})
24+
25+
test("keeps native close behavior on macOS (no interception)", () => {
26+
expect(resolveCloseAction({ ...win, platform: "darwin" })).toBe("close")
27+
expect(resolveCloseAction({ ...win, platform: "darwin", isQuitting: true })).toBe("close")
28+
expect(resolveCloseAction({ ...win, platform: "darwin", otherWindows: 0 })).toBe("close")
29+
})
30+
})
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Pure decision logic for the window close event.
3+
*
4+
* Tray mode (Windows/Linux only): closing the LAST window hides it to the
5+
* system tray so background work (agents, servers) keeps running; closing a
6+
* window while others remain open closes it normally. During a real quit
7+
* (tray "Quit", app menu quit, Cmd+Q, SIGTERM) every window closes normally.
8+
*
9+
* macOS is intentionally untouched: it keeps the native close-to-Dock
10+
* behavior (window closes, app stays in the Dock, `activate` restores it),
11+
* exactly as before this feature.
12+
*
13+
* Kept free of Electron imports so unit tests can cover every branch.
14+
*/
15+
export type CloseAction = "hide" | "close"
16+
17+
export function resolveCloseAction(input: {
18+
isQuitting: boolean
19+
/** Number of OTHER windows still open (excluding the one being closed). */
20+
otherWindows: number
21+
/** Process platform; darwin keeps its native close behavior. */
22+
platform: NodeJS.Platform
23+
}): CloseAction {
24+
if (input.platform === "darwin") return "close"
25+
if (input.isQuitting) return "close"
26+
if (input.otherWindows > 0) return "close"
27+
return "hide"
28+
}

‎packages/desktop/src/main/index.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,17 @@ import {
3232
type SidecarListener,
3333
} from "./server"
3434
import { setupAutoUpdater, showUpdaterDialog } from "./updater"
35+
import { createTray } from "./tray"
3536
import { safeWebContentsURL } from "./window-state"
3637
import {
3738
getLastFocusedWindow,
39+
iconPath,
3840
registerRendererProtocol,
3941
setRelaunchHandler,
4042
setAppQuitting,
4143
setBackgroundColor,
4244
setDockIcon,
45+
showMainWindow,
4346
restoreMainWindows,
4447
} from "./windows"
4548
import { createWslServersController } from "./wsl/servers"
@@ -409,14 +412,18 @@ const main = Effect.gen(function* () {
409412
yield* Fiber.await(loadingTask)
410413

411414
app.on("window-all-closed", () => {
412-
if (process.platform === "darwin") return
413-
app.quit()
415+
// Tray mode: the app stays alive in the system tray (Windows/Linux) or
416+
// the Dock (macOS) when every window is closed/hidden, so background
417+
// agent work keeps running. A real quit goes through `before-quit`
418+
// (sets the quitting flag) and exits normally.
414419
})
415420
app.on("activate", () => {
416421
if (BrowserWindow.getAllWindows().length > 0) return
417422
restoreMainWindows()
418423
})
419424

425+
createTray(iconPath(), () => showMainWindow())
426+
420427
const windows = restoreMainWindows()
421428
if (windows.length) createMenu(menuDeps)
422429
})
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from "bun:test"
2+
3+
let createTray: (iconPath: string, onShow: () => void) => unknown
4+
let destroyTray: () => void
5+
6+
const state = {
7+
trayCreated: 0,
8+
trayDestroyed: 0,
9+
toolTip: "",
10+
menu: undefined as undefined | { label?: string; type?: string; click?: () => void }[],
11+
clickHandler: undefined as undefined | (() => void),
12+
doubleClickHandler: undefined as undefined | (() => void),
13+
quitCalls: 0,
14+
}
15+
16+
beforeAll(async () => {
17+
const api = {
18+
app: {
19+
quit: () => {
20+
state.quitCalls++
21+
},
22+
},
23+
Menu: {
24+
buildFromTemplate: (template: { label?: string; type?: string; click?: () => void }[]) => {
25+
state.menu = template
26+
return template
27+
},
28+
},
29+
nativeImage: {
30+
createFromPath: () => ({ isEmpty: () => false }),
31+
},
32+
Tray: function Tray() {
33+
state.trayCreated++
34+
return {
35+
setToolTip: (tip: string) => {
36+
state.toolTip = tip
37+
},
38+
setContextMenu: () => {},
39+
on: (event: string, handler: () => void) => {
40+
if (event === "click") state.clickHandler = handler
41+
if (event === "double-click") state.doubleClickHandler = handler
42+
},
43+
destroy: () => {
44+
state.trayDestroyed++
45+
},
46+
}
47+
},
48+
}
49+
mock.module("electron", () => ({ ...api, default: api }))
50+
const mod = await import("./tray")
51+
createTray = mod.createTray
52+
destroyTray = mod.destroyTray
53+
})
54+
55+
const originalPlatform = process.platform
56+
57+
function setPlatform(platform: NodeJS.Platform) {
58+
Object.defineProperty(process, "platform", { value: platform, configurable: true })
59+
}
60+
61+
beforeEach(() => {
62+
// Reset the module-level tray singleton so every test starts clean;
63+
// otherwise the idempotent createTray returns the instance created by an
64+
// earlier test and no new Tray is constructed.
65+
destroyTray()
66+
state.trayCreated = 0
67+
state.trayDestroyed = 0
68+
state.toolTip = ""
69+
state.menu = undefined
70+
state.clickHandler = undefined
71+
state.doubleClickHandler = undefined
72+
state.quitCalls = 0
73+
setPlatform("win32")
74+
})
75+
76+
afterAll(() => {
77+
setPlatform(originalPlatform)
78+
mock.restore()
79+
})
80+
81+
describe("tray", () => {
82+
test("creates a tray with Show and Quit entries on windows", () => {
83+
const tray = createTray("/fake/icon.ico", () => {})
84+
expect(tray).toBeDefined()
85+
expect(state.trayCreated).toBe(1)
86+
expect(state.toolTip).toBe("OpenCode")
87+
const labels = state.menu?.map((item) => item.label ?? item.type)
88+
expect(labels).toEqual(["Show OpenCode", "separator", "Quit"])
89+
})
90+
91+
test("is idempotent: creating again returns the same instance", () => {
92+
createTray("/fake/icon.ico", () => {})
93+
createTray("/fake/icon.ico", () => {})
94+
expect(state.trayCreated).toBe(1)
95+
})
96+
97+
test("single and double click both restore the window", () => {
98+
const show = mock(() => {})
99+
createTray("/fake/icon.ico", show)
100+
state.clickHandler?.()
101+
state.doubleClickHandler?.()
102+
expect(show).toHaveBeenCalledTimes(2)
103+
})
104+
105+
test("tray Show entry restores the window", () => {
106+
const show = mock(() => {})
107+
createTray("/fake/icon.ico", show)
108+
const showEntry = state.menu?.find((item) => item.label === "Show OpenCode")
109+
showEntry?.click?.()
110+
expect(show).toHaveBeenCalledTimes(1)
111+
})
112+
113+
test("tray Quit entry quits the app", () => {
114+
createTray("/fake/icon.ico", () => {})
115+
const quitEntry = state.menu?.find((item) => item.label === "Quit")
116+
quitEntry?.click?.()
117+
expect(state.quitCalls).toBe(1)
118+
})
119+
120+
test("does not create a tray on macOS", () => {
121+
setPlatform("darwin")
122+
expect(createTray("/fake/icon.png", () => {})).toBeUndefined()
123+
expect(state.trayCreated).toBe(0)
124+
})
125+
126+
test("destroy removes the tray instance", () => {
127+
createTray("/fake/icon.ico", () => {})
128+
destroyTray()
129+
expect(state.trayDestroyed).toBe(1)
130+
// A destroyed tray can be recreated.
131+
createTray("/fake/icon.ico", () => {})
132+
expect(state.trayCreated).toBe(2)
133+
})
134+
})

‎packages/desktop/src/main/tray.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* System tray support for tray mode (Windows/Linux).
3+
*
4+
* macOS does not get a tray: the app stays in the Dock, `activate` restores
5+
* the window, and closing a window keeps the app alive (see index.ts).
6+
*
7+
* The tray holds the app alive when every window is hidden and offers
8+
* "Show OpenCode" / "Quit". Quitting goes through `app.quit()` so the
9+
* `before-quit` 鈫?`setAppQuitting` path lets windows close normally.
10+
*/
11+
import { app, Menu, nativeImage, Tray } from "electron"
12+
13+
// Module-scope reference so the Tray is never garbage-collected; a collected
14+
// tray drops its icon and stops responding for the rest of the session.
15+
let tray: Tray | undefined
16+
17+
// E2E hooks (intentionally exposed on globalThis for testability, matching
18+
// the __getIsQuitting pattern in index.ts).
19+
declare global {
20+
var __getTrayInstance: (() => Tray | undefined) | undefined
21+
var __triggerTrayMenuAction: ((label: string) => void) | undefined
22+
}
23+
24+
function buildTrayMenu(onShow: () => void) {
25+
return Menu.buildFromTemplate([
26+
{ label: "Show OpenCode", click: onShow },
27+
{ type: "separator" },
28+
{ label: "Quit", click: () => app.quit() },
29+
])
30+
}
31+
32+
export function createTray(iconPath: string, onShow: () => void): Tray | undefined {
33+
if (process.platform === "darwin") return undefined
34+
if (tray) return tray
35+
36+
tray = new Tray(nativeImage.createFromPath(iconPath))
37+
tray.setToolTip("OpenCode")
38+
tray.setContextMenu(buildTrayMenu(onShow))
39+
tray.on("click", onShow)
40+
tray.on("double-click", onShow)
41+
42+
globalThis.__getTrayInstance = () => tray
43+
globalThis.__triggerTrayMenuAction = (label: string) => {
44+
const item = buildTrayMenu(onShow).items.find((entry) => entry.label === label)
45+
if (item?.click) item.click()
46+
}
47+
48+
return tray
49+
}
50+
51+
export function destroyTray(): void {
52+
tray?.destroy()
53+
tray = undefined
54+
globalThis.__getTrayInstance = undefined
55+
globalThis.__triggerTrayMenuAction = undefined
56+
}

‎packages/desktop/src/main/window-registry.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,13 @@ describe("window registry", () => {
8888
expect(app.state.stored).toEqual(["b"])
8989
expect(app.cleaned).toEqual(["a"])
9090
})
91+
92+
test("reports the quit flag for close interception", () => {
93+
const app = setup()
94+
expect(app.registry.isQuitting()).toBe(false)
95+
app.registry.setQuitting()
96+
expect(app.registry.isQuitting()).toBe(true)
97+
app.registry.setQuitting(false)
98+
expect(app.registry.isQuitting()).toBe(false)
99+
})
91100
})

‎packages/desktop/src/main/window-registry.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ export function createWindowRegistry<W>(persistence: {
2020
setQuitting(value = true) {
2121
quitting = value
2222
},
23+
isQuitting() {
24+
return quitting
25+
},
2326
register(id: string, window: W) {
2427
windows.set(id, window)
2528
const ids = persisted()

‎packages/desktop/src/main/windows.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { PINCH_ZOOM_ENABLED_KEY, WINDOW_IDS_KEY } from "./store-keys"
1414
import { createUnresponsiveSampler } from "./unresponsive"
1515
import { nativeT } from "./native-translations"
1616
import { createWindowRegistry } from "./window-registry"
17+
import { resolveCloseAction } from "./close-behavior"
1718
import { safeWindowURL } from "./window-state"
1819
import { resolveExternalURL, resolveLocalFilePath } from "./external-url"
1920

@@ -89,7 +90,7 @@ function iconsDir() {
8990
return app.isPackaged ? join(process.resourcesPath, "icons") : join(root, "../../resources/icons")
9091
}
9192

92-
function iconPath() {
93+
export function iconPath() {
9394
const ext = process.platform === "win32" ? "ico" : "png"
9495
return join(iconsDir(), `icon.${ext}`)
9596
}
@@ -159,6 +160,21 @@ export function restoreMainWindows() {
159160
return (ids.length ? ids : [randomUUID()]).map((id) => createMainWindow(id))
160161
}
161162

163+
/**
164+
* Restore the main window from the tray/Dock: show + focus an existing
165+
* window, or create a fresh one when none survives (e.g. macOS closed it).
166+
*/
167+
export function showMainWindow() {
168+
const existing =
169+
getLastFocusedWindow() ?? BrowserWindow.getAllWindows().find((win) => !win.isDestroyed())
170+
if (existing) {
171+
existing.show()
172+
existing.focus()
173+
return
174+
}
175+
createMainWindow()
176+
}
177+
162178
export function setDockIcon() {
163179
if (process.platform !== "darwin") return
164180
const icon = nativeImage.createFromPath(join(iconsDir(), "dock.png"))
@@ -272,6 +288,24 @@ function registerWindow(win: BrowserWindow, id: string) {
272288
registry.register(id, win)
273289

274290
win.on("focus", () => registry.focused(id))
291+
// Tray mode: closing the LAST window hides it to the tray instead of
292+
// quitting, so background work keeps running. A real quit (tray "Quit",
293+
// app menu, Cmd+Q, SIGTERM) sets the quitting flag first, so every window
294+
// closes normally and the process can exit.
295+
win.on("close", (event) => {
296+
const otherWindows = BrowserWindow.getAllWindows().filter(
297+
(candidate) => candidate !== win && !candidate.isDestroyed(),
298+
).length
299+
const action = resolveCloseAction({
300+
isQuitting: registry.isQuitting(),
301+
otherWindows,
302+
platform: process.platform,
303+
})
304+
if (action === "hide") {
305+
event.preventDefault()
306+
win.hide()
307+
}
308+
})
275309
// Windows never emits before-quit on OS shutdown/logoff, but each window
276310
// gets session-end before it closes; flag the quit so ids stay persisted.
277311
win.on("session-end", () => registry.setQuitting())

0 commit comments

Comments
 (0)