Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions e2e/apps-local.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>(`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}`)
})
101 changes: 101 additions & 0 deletions src/main/apps/localComfy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,91 @@ 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.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)
})

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('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)

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', () => {
Expand All @@ -757,4 +842,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([])
})
})
64 changes: 54 additions & 10 deletions src/main/apps/localComfy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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' | '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 'replaced'
return isEmpty(queue) ? 'idle' : 'busy'
}

async function stopIdleBuilds(): Promise<void> {
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' || state === 'replaced') continue
startedHere.delete(id)
await stopRunning(id)
if (state === 'idle') await stopRunning(id)
}
if (startedHere.size > 0) noteUse()
}
Expand Down Expand Up @@ -216,6 +230,36 @@ async function launchWithoutWindow(installationId: string): Promise<ActionResult
return result
}

export function isRunningForAppsOnly(installationId: string): boolean {
return (
startedHere.has(installationId) &&
runningPortOf(installationId) !== null &&
!getEntryByInstallationId(installationId)
)
}

export function hasBuildsRunningForAppsOnly(): boolean {
return [...startedHere].some(isRunningForAppsOnly)
}

async function stopIfIdle(installationId: string): Promise<void> {
if ((await idleState(installationId)) !== 'idle') return
startedHere.delete(installationId)
await stopRunning(installationId)
}

export async function stopBuildsRunningForAppsOnly(): Promise<void> {
await Promise.all([...startedHere].filter(isRunningForAppsOnly).map(stopIfIdle))
noteUse()
}

export async function stopEveryBuildRunningForAppsOnly(): Promise<void> {
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<ActionResult> {
const pending = launches.get(installationId)
if (pending) return pending
Expand Down
92 changes: 91 additions & 1 deletion src/main/host/createHostWindow.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { describe, expect, it, vi } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'

import type * as SettingsModule from '../settings'

const mocks = vi.hoisted(() => ({
appsBuildRunning: false,
stopAppsBuilds: vi.fn(async () => {})
}))

vi.mock('electron', () => ({
app: {
Expand All @@ -15,10 +22,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<typeof SettingsModule>()
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,
Expand Down Expand Up @@ -228,3 +251,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<Electron.BrowserWindow>(),
consultPanelRendererClose: () =>
new Promise<CloseConsultResult>((resolve) => consults.push(resolve)),
confirmCloseInstanceWindow: async (
_window: Electron.BrowserWindow,
isLastWindow: boolean,
stopsLocalComfy: boolean
): Promise<CloseWindowChoice> => {
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)
})
})
Loading
Loading