diff --git a/src/main/lib/ipc/sessionActions/delegate.test.ts b/src/main/lib/ipc/sessionActions/delegate.test.ts index c76604adc..3ef053f6d 100644 --- a/src/main/lib/ipc/sessionActions/delegate.test.ts +++ b/src/main/lib/ipc/sessionActions/delegate.test.ts @@ -28,6 +28,7 @@ vi.mock('../../pip', () => ({ })) import { handleDelegateToSource } from './delegate' +import { _operationAborts } from '../shared' import { _resetAgentPrefetchesForTest, prefetchAgentRequirements, @@ -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 () => { diff --git a/src/main/lib/ipc/sessionActions/delegate.ts b/src/main/lib/ipc/sessionActions/delegate.ts index 82da7696f..7a105c3a2 100644 --- a/src/main/lib/ipc/sessionActions/delegate.ts +++ b/src/main/lib/ipc/sessionActions/delegate.ts @@ -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 { 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): void => { try { @@ -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 => { @@ -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, @@ -55,6 +62,6 @@ export async function handleDelegateToSource( return { ok: false, message: (err as Error).message } } finally { releasePrefetch() - _operationAborts.delete(installationId) + vacate() } } diff --git a/src/main/lib/ipc/sessionActions/index.test.ts b/src/main/lib/ipc/sessionActions/index.test.ts index 8a9146be3..7ea7bf8f6 100644 --- a/src/main/lib/ipc/sessionActions/index.test.ts +++ b/src/main/lib/ipc/sessionActions/index.test.ts @@ -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 diff --git a/src/main/lib/ipc/sessionActions/index.ts b/src/main/lib/ipc/sessionActions/index.ts index 9d4e1ea2e..bea133dde 100644 --- a/src/main/lib/ipc/sessionActions/index.ts +++ b/src/main/lib/ipc/sessionActions/index.ts @@ -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' @@ -83,9 +84,13 @@ export async function dispatchSessionAction( actionId: string ): Promise { 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 { @@ -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 }) } diff --git a/src/main/lib/ipc/sessionActions/occupiesInstall.ts b/src/main/lib/ipc/sessionActions/occupiesInstall.ts new file mode 100644 index 000000000..8e1945fcc --- /dev/null +++ b/src/main/lib/ipc/sessionActions/occupiesInstall.ts @@ -0,0 +1,5 @@ +const LOOKUPS_THAT_LEAVE_THE_INSTALL_ALONE: ReadonlySet = new Set(['check-update']) + +export function occupiesInstall(actionId: string): boolean { + return !LOOKUPS_THAT_LEAVE_THE_INSTALL_ALONE.has(actionId) +} diff --git a/src/main/lib/ipc/updateCheckOverlap.integration.test.ts b/src/main/lib/ipc/updateCheckOverlap.integration.test.ts new file mode 100644 index 000000000..3ecf86cab --- /dev/null +++ b/src/main/lib/ipc/updateCheckOverlap.integration.test.ts @@ -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() + +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) => + 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) => { + 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 +) => Promise + +const BUILD_ID = 'inst-being-checked' + +function runAction(actionId: string, actionData?: Record): Promise { + 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((resolve) => (finishSourceAction = resolve)) + ) + h.handle.mockClear() + registerSessionHandlers() + }) + + afterEach(() => { + finishSourceAction({ ok: true }) + vi.restoreAllMocks() + fs.rmSync(tmpRoot, { recursive: true, force: true }) + }) + + async function sourceActionStarted(): Promise { + 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 }) + }) +})