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
66 changes: 66 additions & 0 deletions src/main/lib/ipc/sessionActions/delegate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ vi.mock('../../pip', () => ({
}))

import { handleDelegateToSource } from './delegate'
import { _operationAborts } from '../shared'
import {
_resetAgentPrefetchesForTest,
prefetchAgentRequirements,
Expand Down Expand Up @@ -106,6 +107,71 @@ describe('handleDelegateToSource', () => {
).toBe(true)
})

it("lets an update check run alongside the install's background download and leaves the install free for other actions", async () => {
const downloadStopped = vi.fn()
vi.mocked(installFilteredRequirementsDetailed).mockImplementation(async (...args) => {
const signal = args[6] as AbortSignal
return new Promise((resolve) =>
signal.addEventListener(
'abort',
() => {
downloadStopped()
resolve({ code: 1, output: '' })
},
{ once: true }
)
)
})
const background: PrefetchRequest = {
plan: {
reqPath: path.join(dir, 'agent_requirements.txt'),
uvPath: '/uv',
pythonPath: '/py',
installPath: dir
},
steps: [{ text: 'comfy-agent==0.2.0\n' }],
signature: 'core',
eager: true
}
expect(prefetchAgentRequirements(background, () => {})).toBe(true)
await vi.waitFor(() => expect(installFilteredRequirementsDetailed).toHaveBeenCalled())
let occupiedDuringCheck: boolean | undefined
harness.handleAction = async () => {
occupiedDuringCheck = _operationAborts.has('i')
return { ok: true }
}
const ctx = {
event: { sender: { isDestroyed: () => false, send: () => {} } },
installationId: 'i',
inst: { id: 'i', sourceId: 'stub', installPath: dir },
actionData: { silent: true }
}

expect(await handleDelegateToSource(ctx as never, 'check-update')).toEqual({ ok: true })

expect(occupiedDuringCheck, 'a check only reads what the remote offers').toBe(false)
expect(downloadStopped, 'the check touches nothing uv holds open').not.toHaveBeenCalled()
})

it('occupies the install for exactly as long as an action that changes it runs', async () => {
let occupiedDuringUpdate: boolean | undefined
harness.handleAction = async () => {
occupiedDuringUpdate = _operationAborts.has('i')
return { ok: true }
}
const ctx = {
event: { sender: { isDestroyed: () => false, send: () => {} } },
installationId: 'i',
inst: { id: 'i', sourceId: 'stub', installPath: dir },
actionData: {}
}

expect(await handleDelegateToSource(ctx as never, 'update-comfyui')).toEqual({ ok: true })

expect(occupiedDuringUpdate).toBe(true)
expect(_operationAborts.has('i'), 'freed once the update ends').toBe(false)
})

it.skipIf(process.platform === 'win32')(
'stops a uv a killed Desktop left running in the install before the action starts',
async () => {
Expand Down
15 changes: 11 additions & 4 deletions src/main/lib/ipc/sessionActions/delegate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@ import { installations, i18n, sourceMap, _operationAborts, MSG_CANCELLED } from
import type { ActionContext, ActionResult } from './types'
import { appendLog } from '../../logsBroadcast'
import { holdAgentPrefetch } from '../../agentRequirementsLaunch'
import { occupiesInstall } from './occupiesInstall'

export async function handleDelegateToSource(
{ event, installationId, inst, actionData }: ActionContext,
actionId: string
): Promise<ActionResult> {
const abort = new AbortController()
_operationAborts.set(installationId, abort)
const occupies = occupiesInstall(actionId)
if (occupies) _operationAborts.set(installationId, abort)
const vacate = (): void => {
if (occupies) _operationAborts.delete(installationId)
}
const sender = event.sender
const sendProgress = (phase: string, detail: Record<string, unknown>): void => {
try {
Expand All @@ -26,7 +31,7 @@ export async function handleDelegateToSource(
installations.update(installationId, data).then(() => {})
const source = sourceMap[inst.sourceId]
if (!source) {
_operationAborts.delete(installationId)
vacate()
return { ok: false, message: i18n.t('errors.unknownSource') }
}
const logFailure = (message: string): void => {
Expand All @@ -37,7 +42,9 @@ export async function handleDelegateToSource(
}
}
const releasePrefetch =
typeof inst.installPath === 'string' ? await holdAgentPrefetch(inst.installPath) : () => {}
occupies && typeof inst.installPath === 'string'
? await holdAgentPrefetch(inst.installPath)
: () => {}
try {
const result = await source.handleAction(actionId, inst, actionData, {
update,
Expand All @@ -55,6 +62,6 @@ export async function handleDelegateToSource(
return { ok: false, message: (err as Error).message }
} finally {
releasePrefetch()
_operationAborts.delete(installationId)
vacate()
}
}
55 changes: 55 additions & 0 deletions src/main/lib/ipc/sessionActions/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,61 @@ describe('dispatchSessionAction operation tracking', () => {
expect(_getActiveOperations()).toEqual([])
})

it('shows an update that starts during an update check as the operation, and keeps showing it after the check ends', async () => {
let finishCheck!: (value: { ok: boolean }) => void
let finishUpdate!: (value: { ok: boolean }) => void
delegate
.mockReturnValueOnce(new Promise((resolve) => (finishCheck = resolve)))
.mockReturnValueOnce(new Promise((resolve) => (finishUpdate = resolve)))

const check = dispatchSessionAction(ctx(), 'check-update')
const update = dispatchSessionAction(ctx(), 'update-comfyui')

expect(_getActiveOperations()).toEqual([
{ installationId: 'inst-1', actionId: 'update-comfyui' }
])

finishCheck({ ok: true })
await check

expect(_getActiveOperations(), 'the check ending does not end the update').toEqual([
{ installationId: 'inst-1', actionId: 'update-comfyui' }
])
expect(broadcast).not.toHaveBeenCalledWith('operation-changed', {
installationId: 'inst-1',
actionId: 'check-update',
active: false
})

finishUpdate({ ok: true })
await update

expect(_getActiveOperations()).toEqual([])
expect(broadcast).toHaveBeenLastCalledWith('operation-changed', {
installationId: 'inst-1',
actionId: 'update-comfyui',
active: false
})
})

it('keeps showing an update while an update check starts and ends during it', async () => {
let finishUpdate!: (value: { ok: boolean }) => void
delegate
.mockReturnValueOnce(new Promise((resolve) => (finishUpdate = resolve)))
.mockResolvedValueOnce({ ok: true })

const update = dispatchSessionAction(ctx(), 'update-comfyui')
await dispatchSessionAction(ctx(), 'check-update')

expect(_getActiveOperations()).toEqual([
{ installationId: 'inst-1', actionId: 'update-comfyui' }
])

finishUpdate({ ok: true })
await update
expect(_getActiveOperations()).toEqual([])
})

it('tracks concurrent actions on different installs independently', async () => {
let resolveA!: (value: { ok: boolean }) => void
let resolveB!: (value: { ok: boolean }) => void
Expand Down
11 changes: 8 additions & 3 deletions src/main/lib/ipc/sessionActions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { handleCopy, handleCopyUpdate, handleCopyChangePytorch, handleReleaseUpd
import { handleMigrateToStandalone } from './migrate'
import { handleLaunch } from './launch'
import { handleDelegateToSource } from './delegate'
import { occupiesInstall } from './occupiesInstall'

export type { ActionContext, ActionResult } from './types'
export { handleRemove, handleOpenFolder, handleRename } from './basic'
Expand Down Expand Up @@ -83,9 +84,13 @@ export async function dispatchSessionAction(
actionId: string
): Promise<ActionResult> {
const { installationId } = ctx
const owned = !_activeActions.has(installationId)
const running = _activeActions.get(installationId)
const takesOverFromLookup =
running !== undefined && occupiesInstall(actionId) && !occupiesInstall(running.actionId)
const owned = running === undefined || takesOverFromLookup
const entry = { actionId }
if (owned) {
_activeActions.set(installationId, { actionId })
_activeActions.set(installationId, entry)
_broadcastToRenderer('operation-changed', { installationId, actionId, active: true })
}
try {
Expand All @@ -94,7 +99,7 @@ export async function dispatchSessionAction(
}
return await handleDelegateToSource(ctx, actionId)
} finally {
if (owned) {
if (owned && _activeActions.get(installationId) === entry) {
_activeActions.delete(installationId)
_broadcastToRenderer('operation-changed', { installationId, actionId, active: false })
}
Expand Down
5 changes: 5 additions & 0 deletions src/main/lib/ipc/sessionActions/occupiesInstall.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const LOOKUPS_THAT_LEAVE_THE_INSTALL_ALONE: ReadonlySet<string> = new Set(['check-update'])

export function occupiesInstall(actionId: string): boolean {
return !LOOKUPS_THAT_LEAVE_THE_INSTALL_ALONE.has(actionId)
}
156 changes: 156 additions & 0 deletions src/main/lib/ipc/updateCheckOverlap.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import fs from 'fs'
import os from 'os'
import path from 'path'
import { EventEmitter } from 'events'
import type { InstallationRecord } from '../../installations'

const installationsStore = new Map<string, InstallationRecord>()

const h = vi.hoisted(() => ({ userDataDir: { value: '' }, handle: vi.fn() }))

vi.mock('electron', () => ({
app: {
isPackaged: false,
getPath: (name: string) => (name === 'userData' ? h.userDataDir.value : os.tmpdir()),
getVersion: () => '0.0.0-test',
getLocale: () => 'en'
},
ipcMain: { handle: h.handle, on: vi.fn(), off: vi.fn() },
dialog: {},
shell: {},
session: { fromPartition: () => ({ clearStorageData: async () => {} }) },
BrowserWindow: { getAllWindows: () => [] },
nativeTheme: { on: vi.fn(), shouldUseDarkColors: false }
}))

vi.mock('../i18n', () => ({
t: (key: string, params?: Record<string, unknown>) =>
params ? `${key}:${JSON.stringify(params)}` : key,
init: vi.fn(async () => {}),
getMessages: () => ({}),
getLocale: () => 'en',
getAvailableLocales: () => []
}))

vi.mock('../../settings', () => ({
get: vi.fn((_key: string): unknown => undefined),
set: vi.fn(async () => {}),
getAll: vi.fn(() => ({})),
getMirrorConfig: vi.fn(() => ({ pypiMirror: undefined, useChineseMirrors: false })),
defaults: { modelsDirs: ['/unused'], inputDir: '/unused', outputDir: '/unused' }
}))

vi.mock('../../installations', () => ({
installationEvents: new EventEmitter(),
list: vi.fn(async () => Array.from(installationsStore.values())),
get: vi.fn(async (id: string) => installationsStore.get(id) ?? null),
update: vi.fn(async (id: string, data: Record<string, unknown>) => {
const cur = installationsStore.get(id)
if (!cur) return null
const next = { ...cur, ...data } as InstallationRecord
installationsStore.set(id, next)
return next
}),
remove: vi.fn(async (id: string) => {
installationsStore.delete(id)
})
}))

vi.mock('../snapshots', () => ({
saveSnapshot: vi.fn(async () => 'noop.json'),
getSnapshotCount: vi.fn(async () => 0),
deduplicatePreUpdateSnapshot: vi.fn(async () => false)
}))
vi.mock('../pip', () => ({
installFilteredRequirements: vi.fn(async () => 0)
}))

import { registerSessionHandlers } from './registerSessionHandlers'
import { MARKER_FILE, sourceMap } from './shared'
import type { ActionResult } from './sessionActions'

type RunAction = (
event: unknown,
installationId: string,
actionId: string,
actionData?: Record<string, unknown>
) => Promise<ActionResult>

const BUILD_ID = 'inst-being-checked'

function runAction(actionId: string, actionData?: Record<string, unknown>): Promise<ActionResult> {
const registered = h.handle.mock.calls.find(([channel]) => channel === 'run-action')
expect(registered, 'run-action is registered').toBeDefined()
const handler = registered![1] as RunAction
const event = { sender: { isDestroyed: () => false, send: vi.fn() } }
return handler(event, BUILD_ID, actionId, actionData)
}

describe('acting on a build while one of its own actions is still running', () => {
let tmpRoot = ''
let installPath = ''
let finishSourceAction: (result: ActionResult) => void = () => {}

beforeEach(() => {
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'update-check-overlap-'))
h.userDataDir.value = path.join(tmpRoot, 'userData')
fs.mkdirSync(h.userDataDir.value, { recursive: true })
installPath = path.join(tmpRoot, 'build')
fs.mkdirSync(path.join(installPath, 'ComfyUI'), { recursive: true })
fs.writeFileSync(path.join(installPath, MARKER_FILE), BUILD_ID)
fs.writeFileSync(path.join(installPath, 'ComfyUI', 'main.py'), '# stub\n')
installationsStore.clear()
installationsStore.set(BUILD_ID, {
id: BUILD_ID,
name: 'Being checked',
sourceId: 'standalone',
installPath,
status: 'installed',
browserPartition: 'shared',
createdAt: new Date(0).toISOString()
} as InstallationRecord)
vi.spyOn(sourceMap['standalone']!, 'handleAction').mockImplementation(
() => new Promise<ActionResult>((resolve) => (finishSourceAction = resolve))
)
h.handle.mockClear()
registerSessionHandlers()
})

afterEach(() => {
finishSourceAction({ ok: true })
vi.restoreAllMocks()
fs.rmSync(tmpRoot, { recursive: true, force: true })
})

async function sourceActionStarted(): Promise<void> {
await vi.waitFor(() => expect(sourceMap['standalone']!.handleAction).toHaveBeenCalled())
}

it('deletes the build while the update check its settings started is still in flight', async () => {
const check = runAction('check-update', { silent: true })
await sourceActionStarted()

const deleted = await runAction('delete')

expect(deleted).toEqual({ ok: true, navigate: 'list' })
expect(fs.existsSync(installPath), 'the build directory is removed').toBe(false)
expect(installationsStore.has(BUILD_ID), 'the build is forgotten').toBe(false)
finishSourceAction({ ok: true })
expect(await check).toEqual({ ok: true })
})

it('still refuses to delete the build while an update is being applied to it', async () => {
const update = runAction('update-comfyui')
await sourceActionStarted()

const refused = await runAction('delete')

expect(refused.ok).toBe(false)
expect(refused.message).toContain('errors.operationInProgress')
expect(fs.existsSync(installPath), 'the build directory is kept').toBe(true)
expect(installationsStore.has(BUILD_ID), 'the build is kept').toBe(true)
finishSourceAction({ ok: true })
expect(await update).toEqual({ ok: true })
})
})
Loading