From f55361262b618251af1def5fcad843a597cd7abc Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Sat, 14 Nov 2026 20:47:38 -0800 Subject: [PATCH 1/2] fix(builds): a build's update check no longer blocks Delete, Copy or Start Opening a build's settings silently starts an update check for it. The check was registered as the build's running operation for as long as its network calls took, so anything that needs the build to itself was refused in that window: Delete and Update came back with " is currently in progress for this instance", Copy and Start with "Another operation is already running", and the build counted as busy when quitting. A check-update only reads what the remote offers and records it. It now runs without taking the build's operation slot and without stopping the build's background agent download. Actions that change the build still take both. Found through e2e/lifecycle-delete-untrack.test.ts on Windows: the popup moves to the next build after an untrack and starts its check, and the Delete that follows 100 to 450 ms later was refused in 2 of 20 repeats on main. lifecycle-copy.test.ts flaked the same way. --- .../lib/ipc/sessionActions/delegate.test.ts | 66 ++++++++ src/main/lib/ipc/sessionActions/delegate.ts | 20 ++- .../updateCheckOverlap.integration.test.ts | 156 ++++++++++++++++++ 3 files changed, 238 insertions(+), 4 deletions(-) create mode 100644 src/main/lib/ipc/updateCheckOverlap.integration.test.ts 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..d47541973 100644 --- a/src/main/lib/ipc/sessionActions/delegate.ts +++ b/src/main/lib/ipc/sessionActions/delegate.ts @@ -3,12 +3,22 @@ import type { ActionContext, ActionResult } from './types' import { appendLog } from '../../logsBroadcast' import { holdAgentPrefetch } from '../../agentRequirementsLaunch' +const LOOKUPS_THAT_LEAVE_THE_INSTALL_ALONE: ReadonlySet = new Set(['check-update']) + +function occupiesInstall(actionId: string): boolean { + return !LOOKUPS_THAT_LEAVE_THE_INSTALL_ALONE.has(actionId) +} + 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 +36,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 +47,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 +67,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/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 }) + }) +}) From 73bffcdfb81556652352ed154aee728440689a97 Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Sat, 14 Nov 2026 20:58:57 -0800 Subject: [PATCH 2/2] fix(builds): an operation that starts during an update check shows as the build's operation Now that an update, delete or launch can start while a build's update check is still in flight, the check must not keep the build's entry in the active-operation registry. The entry belongs to the first action for a build, so the later operation was never announced, and the check ending announced the build as idle while the operation was still running. A standalone build's card on the dashboard reads "Updating" from that entry. An action that changes the build now takes the entry over from a lookup, and an action only clears the entry it still holds. --- src/main/lib/ipc/sessionActions/delegate.ts | 7 +-- src/main/lib/ipc/sessionActions/index.test.ts | 55 +++++++++++++++++++ src/main/lib/ipc/sessionActions/index.ts | 11 +++- .../lib/ipc/sessionActions/occupiesInstall.ts | 5 ++ 4 files changed, 69 insertions(+), 9 deletions(-) create mode 100644 src/main/lib/ipc/sessionActions/occupiesInstall.ts diff --git a/src/main/lib/ipc/sessionActions/delegate.ts b/src/main/lib/ipc/sessionActions/delegate.ts index d47541973..7a105c3a2 100644 --- a/src/main/lib/ipc/sessionActions/delegate.ts +++ b/src/main/lib/ipc/sessionActions/delegate.ts @@ -2,12 +2,7 @@ import { installations, i18n, sourceMap, _operationAborts, MSG_CANCELLED } from import type { ActionContext, ActionResult } from './types' import { appendLog } from '../../logsBroadcast' import { holdAgentPrefetch } from '../../agentRequirementsLaunch' - -const LOOKUPS_THAT_LEAVE_THE_INSTALL_ALONE: ReadonlySet = new Set(['check-update']) - -function occupiesInstall(actionId: string): boolean { - return !LOOKUPS_THAT_LEAVE_THE_INSTALL_ALONE.has(actionId) -} +import { occupiesInstall } from './occupiesInstall' export async function handleDelegateToSource( { event, installationId, inst, actionData }: ActionContext, 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) +}