From 78fc766d8ccd07a71d7bded9acc1a1859bf604e9 Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Sat, 14 Nov 2026 17:14:51 -0500 Subject: [PATCH 1/6] fix(apps): Open shows a ComfyUI an app started, and closing Desktop stops it An app page that runs on this computer starts its build with no window. Open on that build then asked Desktop to focus a window that did not exist, fell back to focusing the Python process, reported success, and showed nothing. Closing the last Desktop window left Desktop and that ComfyUI running in the background, because the build counted as a running session. focus-comfy-window now opens a ComfyUI window on the running build when an app started it and no window is open yet. When every window closes, builds still running only for apps are stopped before Desktop decides whether to quit. Builds the person started themselves are unchanged. --- e2e/apps-local.test.ts | 12 +++++++ src/main/apps/localComfy.test.ts | 54 ++++++++++++++++++++++++++++++++ src/main/apps/localComfy.ts | 15 +++++++++ src/main/index.ts | 43 +++++++++++++++++++------ 4 files changed, 114 insertions(+), 10 deletions(-) diff --git a/e2e/apps-local.test.ts b/e2e/apps-local.test.ts index 5460573ee..0fa216c27 100644 --- a/e2e/apps-local.test.ts +++ b/e2e/apps-local.test.ts @@ -278,3 +278,15 @@ test('The page cannot reach anything that is not its own run @linux', async () = ).toHaveLength(1) expect(seen.interrupted).toEqual([]) }) + +test('Opening the build an app started shows ComfyUI in its own window @linux', async () => { + const windowsBefore = await windowCount() + + expect( + await ctx.panel.evaluate(`window.api.focusComfyWindow(${JSON.stringify(BUILD_ID)})`) + ).toBe(true) + + await expect.poll(() => windowCount(), LONG_WAIT).toBe(windowsBefore + 1) + const port = (await getRunningSessionSnapshot(ctx.app, BUILD_ID))?.port + await waitForWebContents(ctx.app, `127.0.0.1:${port}`) +}) diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index e38f12e2f..203cc7a20 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -745,6 +745,44 @@ describe('a ComfyUI that Desktop started for apps', () => { expect(stopped).toEqual([]) }) + + it('is known as running for apps only, so opening it shows a new ComfyUI window', () => { + expect(local.isRunningForAppsOnly(STUDIO)).toBe(true) + }) + + it('is no longer running for apps only once it stops', () => { + mocks.sessions.delete(STUDIO) + + expect(local.isRunningForAppsOnly(STUDIO)).toBe(false) + }) + + it('is no longer running for apps only once a window is open for it', () => { + mocks.windows.set(STUDIO, { window: {} }) + + expect(local.isRunningForAppsOnly(STUDIO)).toBe(false) + }) + + it('is stopped when every Desktop window closes', async () => { + await local.stopBuildsRunningForAppsOnly() + + expect(stopped).toEqual([STUDIO]) + expect(local.isRunningForAppsOnly(STUDIO)).toBe(false) + }) + + it('is not stopped twice once the idle stop comes round after that', async () => { + await local.stopBuildsRunningForAppsOnly() + await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS * 3) + + expect(stopped).toEqual([STUDIO]) + }) + + it('keeps running when every Desktop window closes once the person opened its window', async () => { + mocks.windows.set(STUDIO, { window: {} }) + + await local.stopBuildsRunningForAppsOnly() + + expect(stopped).toEqual([]) + }) }) describe('a ComfyUI the person started themselves', () => { @@ -757,4 +795,20 @@ describe('a ComfyUI the person started themselves', () => { expect(stopped).toEqual([]) }) + + it('is not running for apps only, so opening it keeps its own window', async () => { + running() + await startLocal(WANT) + + expect(local.isRunningForAppsOnly(STUDIO)).toBe(false) + }) + + it('is not stopped by apps when every Desktop window closes', async () => { + running() + await startLocal(WANT) + + await local.stopBuildsRunningForAppsOnly() + + expect(stopped).toEqual([]) + }) }) diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index 940c24015..ff874adf4 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -216,6 +216,21 @@ async function launchWithoutWindow(installationId: string): Promise { + const ids = [...startedHere].filter(isRunningForAppsOnly) + for (const id of ids) startedHere.delete(id) + noteUse() + await Promise.all(ids.map((id) => stopRunning(id))) +} + export function launchOnce(installationId: string): Promise { const pending = launches.get(installationId) if (pending) return pending diff --git a/src/main/index.ts b/src/main/index.ts index 3a69add82..e8bba7ab7 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -125,6 +125,8 @@ import { initCloudFreeRuns } from './lib/cloudFreeRuns' import { initCoreBetaFlags, refreshCoreBetaFlags } from './lib/coreBetaCampaignFlags' import { initEmbeddedSessionFlag } from './lib/embeddedSessionFlag' import { initAppsFlag } from './apps/appsFlag' +import { runningPortOf } from './apps/localBuild' +import { isRunningForAppsOnly, stopBuildsRunningForAppsOnly } from './apps/localComfy' import { initWorkspaceMintSwitchFlag } from './lib/workspaceMintSwitchFlag' import { getCloudSession } from './devplatform/session' import { initStaffFlagTargeting } from './lib/staffFlagTargeting' @@ -775,14 +777,32 @@ ipcMain.on('comfy-window:new-chooser-window', () => { openChooserHostWindow() }) -ipcMain.handle('focus-comfy-window', (_event, installationId: string) => { - recordIpcInvocation('focus-comfy-window', { installationId }) +function focusOpenComfyWindow(installationId: string): boolean { const entry = getEntryByInstallationId(installationId) - if (entry && !entry.window.isDestroyed()) { - entry.window.show() - entry.window.focus() - return true - } + if (!entry || entry.window.isDestroyed()) return false + entry.window.show() + entry.window.focus() + return true +} + +async function openWindowForAppsBuild(installationId: string): Promise { + const installation = await getInstallation(installationId) + if (focusOpenComfyWindow(installationId)) return true + const port = runningPortOf(installationId) + if (!installation || port === null) return false + onLaunch({ + port, + process: ipc.getSessionProcess(installationId), + installation, + mode: 'window' + }) + return focusOpenComfyWindow(installationId) +} + +ipcMain.handle('focus-comfy-window', async (_event, installationId: string) => { + recordIpcInvocation('focus-comfy-window', { installationId }) + if (focusOpenComfyWindow(installationId)) return true + if (isRunningForAppsOnly(installationId)) return openWindowForAppsBuild(installationId) const proc = ipc.getSessionProcess(installationId) if (proc?.pid) { @@ -1697,8 +1717,11 @@ if (app.isPackaged && !app.requestSingleInstanceLock()) { }) app.on('window-all-closed', () => { - if (!ipc.hasRunningSessions()) { - app.quit() - } + void stopBuildsRunningForAppsOnly().finally(() => { + if (BrowserWindow.getAllWindows().length > 0) return + if (!ipc.hasRunningSessions()) { + app.quit() + } + }) }) } From 9e351043fc2287e578a83ac55d434e5b4bb830b4 Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Sat, 14 Nov 2026 18:03:13 -0500 Subject: [PATCH 2/6] fix(apps): the idle stop checks again after reading the queue The idle stop for a ComfyUI that Desktop started for apps checked that no window was open for it, then waited for ComfyUI to say whether its queue was empty, then stopped it. Open can attach a window during that wait, and the stop then ended the server the new window was using. After the queue answer comes back, the idle stop now checks again that the build is still running for apps only, that no window is open for it, and that it is the same session it asked about. If any of that changed, it leaves the build alone and forgets it. --- src/main/apps/localComfy.test.ts | 24 ++++++++++++++++++++++ src/main/apps/localComfy.ts | 34 ++++++++++++++++++++++---------- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index 203cc7a20..8b17631b7 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -746,6 +746,30 @@ describe('a ComfyUI that Desktop started for apps', () => { expect(stopped).toEqual([]) }) + it('keeps running when its window opens while the idle stop is still reading its queue', async () => { + let answer: (queue: unknown) => void = () => {} + mocks.probeQueue = () => new Promise((resolve) => (answer = resolve)) + await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS) + + mocks.windows.set(STUDIO, { window: {} }) + answer({ running: 0, pending: 0 }) + await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS * 3) + + expect(stopped).toEqual([]) + }) + + it('keeps running when it was started again while the idle stop was reading its queue', async () => { + let answer: (queue: unknown) => void = () => {} + mocks.probeQueue = () => new Promise((resolve) => (answer = resolve)) + await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS) + + running() + answer({ running: 0, pending: 0 }) + await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS * 3) + + expect(stopped).toEqual([]) + }) + it('is known as running for apps only, so opening it shows a new ComfyUI window', () => { expect(local.isRunningForAppsOnly(STUDIO)).toBe(true) }) diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index ff874adf4..c2992445d 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -11,10 +11,16 @@ import * as installations from '../installations' import type { InstallationRecord } from '../installations' import { startManagedModelJob } from '../lib/comfyDownloadManager' import { probeQueue } from '../lib/comfyProcessRecord' +import type { QueueAnswer } from '../lib/comfyProcessRecord' import * as i18n from '../lib/i18n' import { handleLaunch } from '../lib/ipc/sessionActions/launch' import type { ActionResult } from '../lib/ipc/sessionActions/types' -import { _hasActiveLaunch, sessionLifecycleEvents, stopRunning } from '../lib/ipc/shared' +import { + _hasActiveLaunch, + _runningSessions, + sessionLifecycleEvents, + stopRunning +} from '../lib/ipc/shared' import { COMFY_BOOT_TIMEOUT_MS } from '../lib/process' import { liveAppsPages } from './appsPages' import { chooseLocalBuild, runningPortOf, usableLocalBuilds, wantedVersion } from './localBuild' @@ -117,20 +123,28 @@ function watchSessions(): void { sessionLifecycleEvents.on('changed', stopFollowingStoppedBuilds) } +function isEmpty(queue: QueueAnswer): boolean { + return queue !== null && queue !== 'not_queue' && queue.running + queue.pending === 0 +} + +async function idleState(installationId: string): Promise<'gone' | 'busy' | 'idle'> { + const port = runningPortOf(installationId) + if (port === null || !isRunningForAppsOnly(installationId)) return 'gone' + const session = _runningSessions.get(installationId) + const queue = await probeQueue(port) + if (!isRunningForAppsOnly(installationId)) return 'gone' + if (_runningSessions.get(installationId) !== session) return 'gone' + return isEmpty(queue) ? 'idle' : 'busy' +} + async function stopIdleBuilds(): Promise { idleTimer = null if (downloadsUnderWay > 0) return noteUse() for (const id of [...startedHere]) { - const port = runningPortOf(id) - if (port === null || getEntryByInstallationId(id)) { - startedHere.delete(id) - continue - } - const queue = await probeQueue(port) - const isIdle = queue !== null && queue !== 'not_queue' && queue.running + queue.pending === 0 - if (!isIdle) continue + const state = await idleState(id) + if (state === 'busy') continue startedHere.delete(id) - await stopRunning(id) + if (state === 'idle') await stopRunning(id) } if (startedHere.size > 0) noteUse() } From 60c178da9b9d6133826088caf8df07e9d4ab9afd Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Sat, 14 Nov 2026 18:04:26 -0500 Subject: [PATCH 3/6] fix(apps): closing the last window asks first, and spares a busy ComfyUI Closing the last Desktop window stopped a ComfyUI that Desktop started for apps without asking, even with "confirm before closing a window" on, and the work still queued in that ComfyUI was lost. With the setting on, closing the last window while such a ComfyUI is running now asks first, with the same "This stops ComfyUI and quits Comfy Desktop" question an install window asks. Cancel keeps the window and the ComfyUI. Close stops it, even mid-run. This covers the window's own close button and the Close Window menu item. With the setting off, or when the close goes through without that question, closing the last window stops that ComfyUI only once its queue is empty, as the idle stop already does. A ComfyUI with work queued keeps running, and the idle stop ends it once the work is done. --- src/main/apps/localComfy.test.ts | 11 +++++ src/main/apps/localComfy.ts | 15 +++++++ src/main/host/createHostWindow.ts | 16 ++++++- src/main/host/detach.test.ts | 74 ++++++++++++++++++++++++++++++- src/main/host/detach.ts | 8 +++- 5 files changed, 119 insertions(+), 5 deletions(-) diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index 8b17631b7..801a37eb4 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -793,6 +793,17 @@ describe('a ComfyUI that Desktop started for apps', () => { expect(local.isRunningForAppsOnly(STUDIO)).toBe(false) }) + it('keeps running when every Desktop window closes while it has work queued, and is stopped after that', async () => { + mocks.probeQueue = async () => ({ running: 1, pending: 2 }) + await local.stopBuildsRunningForAppsOnly() + expect(stopped).toEqual([]) + + mocks.probeQueue = async () => ({ running: 0, pending: 0 }) + await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS) + + expect(stopped).toEqual([STUDIO]) + }) + it('is not stopped twice once the idle stop comes round after that', async () => { await local.stopBuildsRunningForAppsOnly() await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS * 3) diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index c2992445d..f9bd9960b 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -238,7 +238,22 @@ export function isRunningForAppsOnly(installationId: string): boolean { ) } +export function hasBuildsRunningForAppsOnly(): boolean { + return [...startedHere].some(isRunningForAppsOnly) +} + +async function stopIfIdle(installationId: string): Promise { + if ((await idleState(installationId)) !== 'idle') return + startedHere.delete(installationId) + await stopRunning(installationId) +} + export async function stopBuildsRunningForAppsOnly(): Promise { + await Promise.all([...startedHere].filter(isRunningForAppsOnly).map(stopIfIdle)) + noteUse() +} + +export async function stopEveryBuildRunningForAppsOnly(): Promise { const ids = [...startedHere].filter(isRunningForAppsOnly) for (const id of ids) startedHere.delete(id) noteUse() diff --git a/src/main/host/createHostWindow.ts b/src/main/host/createHostWindow.ts index 8a26174e3..34981e6a0 100644 --- a/src/main/host/createHostWindow.ts +++ b/src/main/host/createHostWindow.ts @@ -3,6 +3,7 @@ import path from 'path' import type { DatadogForwardedError } from '../../types/ipc' import type { InstallationRecord } from '../installations' import { getAppVersion } from '../lib/ipc' +import { hasBuildsRunningForAppsOnly, stopEveryBuildRunningForAppsOnly } from '../apps/localComfy' import { attachContextMenu } from '../lib/contextMenu' import { tryOpenExternalUrl } from '../lib/openExternal' import { guardPermissionRequests } from '../lib/sessionPermissions' @@ -111,6 +112,13 @@ export function shouldShowInstallCloseConfirm( ) } +export function closeStopsLocalComfy( + entry: ComfyWindowEntry | null | undefined, + isLastWindow: boolean +): boolean { + return shouldConfirmKillForEntry(entry) || (isLastWindow && hasBuildsRunningForAppsOnly()) +} + export function shouldBailAfterCloseChoice( choice: CloseWindowChoice, forceClose: boolean @@ -554,11 +562,13 @@ export function createHostWindow(opts: CreateHostWindowOpts): CreateHostWindowRe const entryForClose = comfyWindows.get(windowKey) const isInstallHostWindow = !!entryForClose && isInstallHost(entryForClose) const isLastInstallWindow = isLastWindow && isInstallHostWindow + const stopsLocalComfy = closeStopsLocalComfy(entryForClose, isLastWindow) + let agreedToStopAppsBuilds = false if ( shouldShowInstallCloseConfirm( settings.get('confirmBeforeClosingWindow') === true, consult, - shouldConfirmKillForEntry(entryForClose), + stopsLocalComfy, fx.preClearedClose.has(comfyWindow), isLastInstallWindow ) && @@ -567,13 +577,15 @@ export function createHostWindow(opts: CreateHostWindowOpts): CreateHostWindowRe const closeChoice = await fx.confirmCloseInstanceWindow( comfyWindow, isLastWindow, - shouldConfirmKillForEntry(entryForClose), + stopsLocalComfy, entryForClose.lastTheme ) if (shouldBailAfterCloseChoice(closeChoice, fx.preClearedClose.has(comfyWindow))) return + agreedToStopAppsBuilds = isLastWindow && closeChoice === 'close' } fx.preClearedClose.delete(comfyWindow) if (comfyWindow.isDestroyed()) return + if (agreedToStopAppsBuilds) void stopEveryBuildRunningForAppsOnly() const safeTeardown = (source: string, fn: () => void): void => { try { fn() diff --git a/src/main/host/detach.test.ts b/src/main/host/detach.test.ts index 2a64266a9..c36d7d8e5 100644 --- a/src/main/host/detach.test.ts +++ b/src/main/host/detach.test.ts @@ -1,5 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ + confirmBeforeClosing: false, + appsBuildRunning: false, + agrees: true, + asked: [] as { spec: { message: string } }[], + stopAppsBuilds: vi.fn(async () => {}) +})) + vi.mock('electron', () => ({ app: { isPackaged: false, @@ -15,9 +23,34 @@ vi.mock('electron', () => ({ nativeTheme: { on: vi.fn(), shouldUseDarkColors: false } })) +vi.mock('../apps/localComfy', () => ({ + hasBuildsRunningForAppsOnly: () => mocks.appsBuildRunning, + stopEveryBuildRunningForAppsOnly: () => mocks.stopAppsBuilds() +})) +vi.mock('../popups/systemModal', async (importOriginal) => ({ + ...(await importOriginal()), + openSystemModalAsync: async (options: { spec: { message: string } }) => { + mocks.asked.push(options) + return mocks.agrees + } +})) +vi.mock('../settings', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + get: (key: string) => + key === 'confirmBeforeClosingWindow' ? mocks.confirmBeforeClosing : actual.get(key) + } +}) + import { _runningSessions } from '../lib/ipc/shared' import { comfyWindows, nextWindowKey, type ComfyWindowEntry } from './registry' -import { closeAllHostWindows, detachOrphanedInstallHosts, preClearedClose } from './detach' +import { + closeAllHostWindows, + confirmAndCloseHostWindow, + detachOrphanedInstallHosts, + preClearedClose +} from './detach' interface FakeWindow { destroyed: boolean @@ -193,3 +226,42 @@ describe('preClearedClose', () => { expect(preClearedClose.has(a as unknown as Electron.BrowserWindow)).toBe(false) }) }) + +describe('closing the last Desktop window while an app uses a ComfyUI Desktop started for it', () => { + function openDashboard(): FakeWindow { + const win = makeWindow() + const entry = makeEntry(win) + comfyWindows.set(entry.windowKey, entry) + return win + } + + beforeEach(() => { + mocks.confirmBeforeClosing = true + mocks.appsBuildRunning = true + mocks.agrees = true + mocks.asked = [] + mocks.stopAppsBuilds.mockClear() + }) + + it('asks first, and Cancel keeps both the window and that ComfyUI', async () => { + mocks.agrees = false + const win = openDashboard() + + await confirmAndCloseHostWindow(win as unknown as Electron.BrowserWindow) + + expect(mocks.asked.map((asked) => asked.spec.message)).toEqual([ + 'Close this window? This stops ComfyUI and quits Comfy Desktop.' + ]) + expect(win.closed).toBe(false) + expect(mocks.stopAppsBuilds).not.toHaveBeenCalled() + }) + + it('stops that ComfyUI and closes once the person agrees', async () => { + const win = openDashboard() + + await confirmAndCloseHostWindow(win as unknown as Electron.BrowserWindow) + + expect(mocks.stopAppsBuilds).toHaveBeenCalledTimes(1) + expect(win.closed).toBe(true) + }) +}) diff --git a/src/main/host/detach.ts b/src/main/host/detach.ts index 3c7689944..28575c178 100644 --- a/src/main/host/detach.ts +++ b/src/main/host/detach.ts @@ -1,5 +1,6 @@ import { ipcMain } from 'electron' import type { BrowserWindow, WebContentsView } from 'electron' +import { stopEveryBuildRunningForAppsOnly } from '../apps/localComfy' import * as ipc from '../lib/ipc' import { _runningSessions } from '../lib/ipc/shared' import { COMFY_BG } from '../lib/theme' @@ -14,6 +15,7 @@ import { applyChooserHostTheme, CHOOSER_HOST_TITLE_TEXT, CHOOSER_HOST_WINDOW_TITLE, + closeStopsLocalComfy, installCloseNeedsConfirm } from './createHostWindow' import type { CloseWindowChoice } from './createHostWindow' @@ -231,20 +233,22 @@ export async function confirmAndCloseHostWindow(parentWindow: BrowserWindow): Pr (e) => !e.window.isDestroyed() ).length const isLastWindow = liveWindowCount <= 1 + const stopsLocalComfy = closeStopsLocalComfy(entry, isLastWindow) if ( installCloseNeedsConfirm( settings.get('confirmBeforeClosingWindow') === true, - shouldConfirmKillForEntry(entry), + stopsLocalComfy, isLastWindow && isInstallHost(entry) ) ) { const choice = await confirmCloseInstanceWindow( entry.window, isLastWindow, - shouldConfirmKillForEntry(entry), + stopsLocalComfy, entry.lastTheme ) if (choice === 'cancel') return + if (isLastWindow) void stopEveryBuildRunningForAppsOnly() } preClearedClose.add(entry.window) entry.window.close() From 1a50ca5cae88e37e52a1b57e8703f9f7e291f19c Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Sat, 14 Nov 2026 18:20:51 -0500 Subject: [PATCH 4/6] fix(apps): a restarted ComfyUI stays started for apps when the idle stop read the old one When the build was started again while the idle stop waited for the old queue answer, the idle stop dropped the build from the apps-started list. The new ComfyUI then never stopped on idle or on the last window close, and Open no longer showed it. The idle stop now keeps it on the list and checks it again on the next round. --- src/main/apps/localComfy.test.ts | 34 +++++++++++++++++++++----------- src/main/apps/localComfy.ts | 6 +++--- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index 801a37eb4..654dac0ec 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -758,17 +758,29 @@ describe('a ComfyUI that Desktop started for apps', () => { expect(stopped).toEqual([]) }) - it('keeps running when it was started again while the idle stop was reading its queue', async () => { - let answer: (queue: unknown) => void = () => {} - mocks.probeQueue = () => new Promise((resolve) => (answer = resolve)) - await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS) - - running() - answer({ running: 0, pending: 0 }) - await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS * 3) - - expect(stopped).toEqual([]) - }) + it.each([ + ['an empty queue', { running: 0, pending: 0 }], + ['a busy queue', { running: 1, pending: 0 }], + ['no queue', null] + ])( + 'keeps running for apps only when it was started again while the idle stop read %s, and is stopped once idle after that', + async (_case, queue) => { + let answer: (value: unknown) => void = () => {} + mocks.probeQueue = () => new Promise((resolve) => (answer = resolve)) + await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS) + + running() + mocks.probeQueue = async () => ({ running: 0, pending: 0 }) + answer(queue) + await vi.advanceTimersByTimeAsync(0) + expect(stopped).toEqual([]) + expect(local.isRunningForAppsOnly(STUDIO)).toBe(true) + + await vi.advanceTimersByTimeAsync(LOCAL_IDLE_STOP_MS) + + expect(stopped).toEqual([STUDIO]) + } + ) it('is known as running for apps only, so opening it shows a new ComfyUI window', () => { expect(local.isRunningForAppsOnly(STUDIO)).toBe(true) diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index f9bd9960b..ac9c564b9 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -127,13 +127,13 @@ function isEmpty(queue: QueueAnswer): boolean { return queue !== null && queue !== 'not_queue' && queue.running + queue.pending === 0 } -async function idleState(installationId: string): Promise<'gone' | 'busy' | 'idle'> { +async function idleState(installationId: string): Promise<'gone' | 'busy' | 'replaced' | 'idle'> { const port = runningPortOf(installationId) if (port === null || !isRunningForAppsOnly(installationId)) return 'gone' const session = _runningSessions.get(installationId) const queue = await probeQueue(port) if (!isRunningForAppsOnly(installationId)) return 'gone' - if (_runningSessions.get(installationId) !== session) return 'gone' + if (_runningSessions.get(installationId) !== session) return 'replaced' return isEmpty(queue) ? 'idle' : 'busy' } @@ -142,7 +142,7 @@ async function stopIdleBuilds(): Promise { if (downloadsUnderWay > 0) return noteUse() for (const id of [...startedHere]) { const state = await idleState(id) - if (state === 'busy') continue + if (state === 'busy' || state === 'replaced') continue startedHere.delete(id) if (state === 'idle') await stopRunning(id) } From 97611464375e98a5404e9776bb2ebfaf93599324 Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Sat, 14 Nov 2026 19:48:17 -0500 Subject: [PATCH 5/6] fix(apps): count the open windows after the page answers, so the last close still asks The close flow counted the open windows before it asked the window's page whether it may close. If a second window closed while the first page was still answering, both counted two windows. The real last window then skipped the close confirmation and did not stop a ComfyUI started only for apps. The confirmation step is now confirmHostWindowClose, and it counts the open windows once the page has answered. --- src/main/host/createHostWindow.test.ts | 90 +++++++++++++++++++++++++- src/main/host/createHostWindow.ts | 85 ++++++++++++++---------- 2 files changed, 139 insertions(+), 36 deletions(-) diff --git a/src/main/host/createHostWindow.test.ts b/src/main/host/createHostWindow.test.ts index 7e892ae2b..588bb6645 100644 --- a/src/main/host/createHostWindow.test.ts +++ b/src/main/host/createHostWindow.test.ts @@ -1,4 +1,9 @@ -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + appsBuildRunning: false, + stopAppsBuilds: vi.fn(async () => {}) +})) vi.mock('electron', () => ({ app: { @@ -15,10 +20,26 @@ vi.mock('electron', () => ({ nativeTheme: { on: vi.fn(), shouldUseDarkColors: false } })) +vi.mock('../apps/localComfy', () => ({ + hasBuildsRunningForAppsOnly: () => mocks.appsBuildRunning, + stopEveryBuildRunningForAppsOnly: () => mocks.stopAppsBuilds() +})) +vi.mock('../settings', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + get: (key: string) => (key === 'confirmBeforeClosingWindow' ? true : actual.get(key)) + } +}) + import type { InstallationRecord } from '../installations' +import { comfyWindows, nextWindowKey, type ComfyWindowEntry } from './registry' import { buildFirebaseAuthForwardedError, cascadeOffsetForCollisions, + confirmHostWindowClose, + type CloseConsultResult, + type CloseWindowChoice, expectedPartitionFor, installCloseNeedsConfirm, isWindowLayoutable, @@ -228,3 +249,70 @@ describe('shouldBailAfterCloseChoice', () => { expect(shouldBailAfterCloseChoice('cancel', true)).toBe(false) }) }) + +describe('confirmHostWindowClose', () => { + interface FakeWindow { + destroyed: boolean + isDestroyed: () => boolean + } + + function openDashboard(): { win: FakeWindow; entry: ComfyWindowEntry } { + const win: FakeWindow = { destroyed: false, isDestroyed: () => win.destroyed } + const entry = { + windowKey: nextWindowKey(), + window: win, + panelView: null, + lastTheme: { bg: '#000', text: '#fff' }, + installationId: null, + sourceCategory: null + } as unknown as ComfyWindowEntry + comfyWindows.set(entry.windowKey, entry) + return { win, entry } + } + + afterEach(() => { + comfyWindows.clear() + mocks.appsBuildRunning = false + mocks.stopAppsBuilds.mockClear() + }) + + it('asks before the last window closes when another window closed while this one was being checked', async () => { + mocks.appsBuildRunning = true + const first = openDashboard() + const second = openDashboard() + const consults: ((result: CloseConsultResult) => void)[] = [] + const asked: { isLastWindow: boolean; stopsLocalComfy: boolean }[] = [] + const fx = { + preClearedClose: new WeakSet(), + consultPanelRendererClose: () => + new Promise((resolve) => consults.push(resolve)), + confirmCloseInstanceWindow: async ( + _window: Electron.BrowserWindow, + isLastWindow: boolean, + stopsLocalComfy: boolean + ): Promise => { + asked.push({ isLastWindow, stopsLocalComfy }) + return 'close' + } + } + + const closingFirst = confirmHostWindowClose( + first.win as unknown as Electron.BrowserWindow, + first.entry.windowKey, + fx + ) + const closingSecond = confirmHostWindowClose( + second.win as unknown as Electron.BrowserWindow, + second.entry.windowKey, + fx + ) + consults[0]('defer') + expect(await closingFirst).toBe(true) + first.win.destroyed = true + consults[1]('defer') + + expect(await closingSecond).toBe(true) + expect(asked).toEqual([{ isLastWindow: true, stopsLocalComfy: true }]) + expect(mocks.stopAppsBuilds).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/main/host/createHostWindow.ts b/src/main/host/createHostWindow.ts index 34981e6a0..67ecf3b43 100644 --- a/src/main/host/createHostWindow.ts +++ b/src/main/host/createHostWindow.ts @@ -370,6 +370,55 @@ export function isWindowLayoutable( return !win.isDestroyed() && !win.isMinimized() } +export async function confirmHostWindowClose( + comfyWindow: BrowserWindow, + windowKey: number, + fx: Pick< + HostWindowFactories, + 'consultPanelRendererClose' | 'confirmCloseInstanceWindow' | 'preClearedClose' + > +): Promise { + const entry = comfyWindows.get(windowKey) + const skipConsult = fx.preClearedClose.has(comfyWindow) + if (!skipConsult) hideTitlePopupForParent(comfyWindow) + const consult: CloseConsultResult = skipConsult + ? 'cleared' + : await fx.consultPanelRendererClose(entry?.panelView) + if (shouldBailAfterConsult(consult, fx.preClearedClose.has(comfyWindow))) return false + const entryForClose = comfyWindows.get(windowKey) + const isLastWindow = + Array.from(comfyWindows.values()).filter((e) => !e.window.isDestroyed()).length <= 1 + const isInstallHostWindow = !!entryForClose && isInstallHost(entryForClose) + const isLastInstallWindow = isLastWindow && isInstallHostWindow + const stopsLocalComfy = closeStopsLocalComfy(entryForClose, isLastWindow) + let agreedToStopAppsBuilds = false + if ( + shouldShowInstallCloseConfirm( + settings.get('confirmBeforeClosingWindow') === true, + consult, + stopsLocalComfy, + fx.preClearedClose.has(comfyWindow), + isLastInstallWindow + ) && + entryForClose + ) { + const closeChoice = await fx.confirmCloseInstanceWindow( + comfyWindow, + isLastWindow, + stopsLocalComfy, + entryForClose.lastTheme + ) + if (shouldBailAfterCloseChoice(closeChoice, fx.preClearedClose.has(comfyWindow))) { + return false + } + agreedToStopAppsBuilds = isLastWindow && closeChoice === 'close' + } + fx.preClearedClose.delete(comfyWindow) + if (comfyWindow.isDestroyed()) return false + if (agreedToStopAppsBuilds) void stopEveryBuildRunningForAppsOnly() + return true +} + export function createHostWindow(opts: CreateHostWindowOpts): CreateHostWindowResult { const fx = getFactories() const windowKey = nextWindowKey() @@ -551,41 +600,7 @@ export function createHostWindow(opts: CreateHostWindowOpts): CreateHostWindowRe void (async () => { try { const entry = comfyWindows.get(windowKey) - const skipConsult = fx.preClearedClose.has(comfyWindow) - const isLastWindow = - Array.from(comfyWindows.values()).filter((e) => !e.window.isDestroyed()).length <= 1 - if (!skipConsult) hideTitlePopupForParent(comfyWindow) - const consult: CloseConsultResult = skipConsult - ? 'cleared' - : await fx.consultPanelRendererClose(entry?.panelView) - if (shouldBailAfterConsult(consult, fx.preClearedClose.has(comfyWindow))) return - const entryForClose = comfyWindows.get(windowKey) - const isInstallHostWindow = !!entryForClose && isInstallHost(entryForClose) - const isLastInstallWindow = isLastWindow && isInstallHostWindow - const stopsLocalComfy = closeStopsLocalComfy(entryForClose, isLastWindow) - let agreedToStopAppsBuilds = false - if ( - shouldShowInstallCloseConfirm( - settings.get('confirmBeforeClosingWindow') === true, - consult, - stopsLocalComfy, - fx.preClearedClose.has(comfyWindow), - isLastInstallWindow - ) && - entryForClose - ) { - const closeChoice = await fx.confirmCloseInstanceWindow( - comfyWindow, - isLastWindow, - stopsLocalComfy, - entryForClose.lastTheme - ) - if (shouldBailAfterCloseChoice(closeChoice, fx.preClearedClose.has(comfyWindow))) return - agreedToStopAppsBuilds = isLastWindow && closeChoice === 'close' - } - fx.preClearedClose.delete(comfyWindow) - if (comfyWindow.isDestroyed()) return - if (agreedToStopAppsBuilds) void stopEveryBuildRunningForAppsOnly() + if (!(await confirmHostWindowClose(comfyWindow, windowKey, fx))) return const safeTeardown = (source: string, fn: () => void): void => { try { fn() From d77e29d3d4295b6570ed3145288a3b2f5e7f09ae Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Sat, 14 Nov 2026 19:50:39 -0500 Subject: [PATCH 6/6] test(host): type the mocked modules with type imports --- src/main/host/createHostWindow.test.ts | 8 +++++--- src/main/host/detach.test.ts | 7 +++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/main/host/createHostWindow.test.ts b/src/main/host/createHostWindow.test.ts index 588bb6645..1726d9e4c 100644 --- a/src/main/host/createHostWindow.test.ts +++ b/src/main/host/createHostWindow.test.ts @@ -1,5 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' +import type * as SettingsModule from '../settings' + const mocks = vi.hoisted(() => ({ appsBuildRunning: false, stopAppsBuilds: vi.fn(async () => {}) @@ -25,7 +27,7 @@ vi.mock('../apps/localComfy', () => ({ stopEveryBuildRunningForAppsOnly: () => mocks.stopAppsBuilds() })) vi.mock('../settings', async (importOriginal) => { - const actual = await importOriginal() + const actual = await importOriginal() return { ...actual, get: (key: string) => (key === 'confirmBeforeClosingWindow' ? true : actual.get(key)) @@ -306,10 +308,10 @@ describe('confirmHostWindowClose', () => { second.entry.windowKey, fx ) - consults[0]('defer') + consults[0]?.('defer') expect(await closingFirst).toBe(true) first.win.destroyed = true - consults[1]('defer') + consults[1]?.('defer') expect(await closingSecond).toBe(true) expect(asked).toEqual([{ isLastWindow: true, stopsLocalComfy: true }]) diff --git a/src/main/host/detach.test.ts b/src/main/host/detach.test.ts index c36d7d8e5..e9e7b7d1c 100644 --- a/src/main/host/detach.test.ts +++ b/src/main/host/detach.test.ts @@ -1,5 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as SystemModalModule from '../popups/systemModal' +import type * as SettingsModule from '../settings' + const mocks = vi.hoisted(() => ({ confirmBeforeClosing: false, appsBuildRunning: false, @@ -28,14 +31,14 @@ vi.mock('../apps/localComfy', () => ({ stopEveryBuildRunningForAppsOnly: () => mocks.stopAppsBuilds() })) vi.mock('../popups/systemModal', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal()), openSystemModalAsync: async (options: { spec: { message: string } }) => { mocks.asked.push(options) return mocks.agrees } })) vi.mock('../settings', async (importOriginal) => { - const actual = await importOriginal() + const actual = await importOriginal() return { ...actual, get: (key: string) =>