From bcc726f39e54d1dd4445ceb21ab223ba1a4ddb73 Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Wed, 11 Nov 2026 10:54:43 -0800 Subject: [PATCH 1/8] feat(apps): run This computer apps on a ComfyUI the person already has A free run now uses a local ComfyUI the person already has when its version is at least what the app needs, before falling back to setting up the Apps build: - a compatible local install already running in Desktop is used as is: no launch, no settings change, never stopped on idle - else an installed, stopped, compatible local install is started in the background in console mode on a free apps port without changing its saved settings, and stopped on idle like the Apps build, only because apps started it - else the Apps build as before The version comes from the install's comfyui_version.py (what /system_stats reports), falling back to the version Desktop recorded. An install with no readable version, not installed, the legacy Desktop source, Cloud and remote installs, and installs Desktop is updating, launching or stopping are skipped. The newest compatible one wins and a running one is preferred, and the one apps already use is kept while it still fits. The page passes its minimum ComfyUI version to getLocal and startLocal; with none it is the Apps build version, so old pages behave as today. LocalState names the install used, with its version and own: true. Models download into the folder the picked install reads (the shared models folder, or its own when it does not share models). Uploads, outputs, the queue, websocket events and the /free after runs follow the picked install. Open in ComfyUI opens the install apps use and can show a window for one running in console mode. --- src/main/apps/appsBuild.ts | 31 ++++- src/main/apps/appsBuildRules.test.ts | 156 +++++++++++++++++++++- src/main/apps/appsBuildRules.ts | 68 ++++++++++ src/main/apps/localComfy.ts | 193 +++++++++++++++++++++------ src/main/apps/openInComfy.ts | 19 ++- src/preload/appsPreload.ts | 5 +- 6 files changed, 413 insertions(+), 59 deletions(-) diff --git a/src/main/apps/appsBuild.ts b/src/main/apps/appsBuild.ts index db66b0724..58f93f5a4 100644 --- a/src/main/apps/appsBuild.ts +++ b/src/main/apps/appsBuild.ts @@ -17,9 +17,10 @@ import { MARKER_FILE, sourceMap } from '../lib/ipc/shared' -import { installModelsDir } from '../lib/models' +import { installModelsDir, resolveComfyDir } from '../lib/models' import { dataDir, defaultDataRoot, defaultInstallDir } from '../lib/paths' import { findAvailablePort } from '../lib/process' +import { coreSemver, coreVerifiedSemver } from '../lib/version' import * as settings from '../settings' import { buildPinnedVariant } from '../sources/standalone' import { DEFAULT_LAUNCH_ARGS, variantMatchesHost } from '../sources/standalone/envPaths' @@ -33,10 +34,12 @@ import { appsLaunchArgs, appsModelDirs, appsOutputDir, + comfyuiFileVersion, downloadBytes, findAppsBuild, localOff, pickVariant, + reusableInstalls, type SetupEvent, setupEnd, setupEvent @@ -94,6 +97,17 @@ export async function findApps(): Promise { return inst } +export async function reusableLocal(): Promise { + return reusableInstalls(await installations.list(), categoryOf) +} + +export async function installVersion(inst: InstallationRecord): Promise { + const file = path.join(resolveComfyDir(inst.installPath), 'comfyui_version.py') + const text = await fsp.readFile(file, 'utf8').catch(() => null) + const onDisk = text === null ? null : comfyuiFileVersion(text) + return onDisk ?? coreVerifiedSemver(inst) ?? coreSemver(inst) +} + interface Plan { data: Record bytes: number @@ -263,11 +277,10 @@ export function cancelAppsSetup(): { cancelled: boolean } { return { cancelled: true } } -export async function launchAppsBuild( +export async function launchConsole( inst: InstallationRecord, withWindow = false ): Promise<{ ok: boolean; message?: string }> { - const fresh = (await installations.update(inst.id, await storageFor(inst))) ?? inst const taken = new Set([ ..._pendingPorts.keys(), ...[..._runningSessions.values()].map((s) => s.port) @@ -279,13 +292,21 @@ export async function launchAppsBuild( taken ).catch(() => null) if (!port) return { ok: false, message: 'No free port for ComfyUI for apps.' } - return launchInstall(fresh, { + return launchInstall(inst, { portOverride: port, ...(withWindow ? {} : { launchModeOverride: 'console' }) }) } -export function showAppsBuildWindow(inst: InstallationRecord): boolean { +export async function launchAppsBuild( + inst: InstallationRecord, + withWindow = false +): Promise<{ ok: boolean; message?: string }> { + const fresh = (await installations.update(inst.id, await storageFor(inst))) ?? inst + return launchConsole(fresh, withWindow) +} + +export function showComfyWindow(inst: InstallationRecord): boolean { const session = _runningSessions.get(inst.id) if (!session || !_onLaunch) return false const entry = getEntryByInstallationId(inst.id) diff --git a/src/main/apps/appsBuildRules.test.ts b/src/main/apps/appsBuildRules.test.ts index 3487d2b0d..face2cef0 100644 --- a/src/main/apps/appsBuildRules.test.ts +++ b/src/main/apps/appsBuildRules.test.ts @@ -5,10 +5,12 @@ import { describe, expect, it } from 'vitest' import { APPS_BUILD_IDLE_MS, APPS_BUILD_RELEASE, + APPS_BUILD_VERSION, APPS_SETUP_STAGE, appsLaunchArgs, appsModelDirs, appsOutputDir, + comfyuiFileVersion, downloadBytes, FREE_IDLE_MS, FREE_JSON, @@ -20,12 +22,16 @@ import { MAC_GPU_ONLY_ARG, MAC_GPU_ONLY_MIN_BYTES, MAC_NO_GPU, + pickComfy, pickOpenTarget, pickVariant, queueEmpty, + releaseVersion, + reusableInstalls, setupEnd, setupEvent, - shouldStopIdle + shouldStopIdle, + wantedVersion } from './appsBuildRules' import { localInstalls } from './guards' @@ -366,3 +372,151 @@ describe('which build Open in ComfyUI picks', () => { expect(pickOpenTarget([], new Map([['apps', 50]]))).toBeNull() }) }) + +describe('the ComfyUI version an app needs', () => { + it('is the Apps build version when the page names none', () => { + expect(APPS_BUILD_VERSION).toBe('0.42.1') + expect(wantedVersion(undefined)).toBe(APPS_BUILD_VERSION) + expect(wantedVersion({})).toBe(APPS_BUILD_VERSION) + }) + + it('takes the minimum the page names', () => { + expect(wantedVersion({ minVersion: '0.37.0' })).toBe('0.37.0') + expect(wantedVersion({ minVersion: 'v0.36.0' })).toBe('0.36.0') + }) + + it('falls back to the Apps build version for anything that is not a version', () => { + for (const minVersion of ['', 'latest', '0.37', '1.2.3.4', 37, null, ['0.37.0']]) { + expect(wantedVersion({ minVersion })).toBe(APPS_BUILD_VERSION) + } + expect(wantedVersion('0.37.0')).toBe(APPS_BUILD_VERSION) + }) + + it('reads a release tag as its ComfyUI version', () => { + expect(releaseVersion('v0.42.1-env1')).toBe('0.42.1') + expect(releaseVersion('0.44.0')).toBe('0.44.0') + expect(releaseVersion('abc1234')).toBeNull() + }) +}) + +describe('reading the ComfyUI version of an install', () => { + it('reads comfyui_version.py', () => { + expect(comfyuiFileVersion('# generated\n__version__ = "0.44.0"\n')).toBe('0.44.0') + expect(comfyuiFileVersion("__version__='0.3.40'")).toBe('0.3.40') + }) + + it('gives no version when the file names none', () => { + expect(comfyuiFileVersion('')).toBeNull() + expect(comfyuiFileVersion('version = "0.44.0"')).toBeNull() + expect(comfyuiFileVersion('__version__ = "dev"')).toBeNull() + }) +}) + +describe('which of the person own installs an app run may use', () => { + const kinds: Record = { + standalone: 'local', + git: 'local', + portable: 'local', + desktop: 'local', + cloud: 'cloud', + remote: 'remote' + } + const category = (inst: { sourceId: string }) => kinds[inst.sourceId] + const base = { installPath: '/x', status: 'installed' } + + it('keeps finished local installs', () => { + const list = [ + { id: 'a', sourceId: 'standalone', ...base }, + { id: 'b', sourceId: 'git', ...base }, + { id: 'c', sourceId: 'portable', ...base } + ] + expect(reusableInstalls(list, category).map((i) => i.id)).toEqual(['a', 'b', 'c']) + }) + + it('leaves out Cloud, remote, legacy Desktop and the Apps build', () => { + const list = [ + { id: 'cloud', sourceId: 'cloud', ...base }, + { id: 'remote', sourceId: 'remote', ...base }, + { id: 'legacy', sourceId: 'desktop', ...base }, + { id: 'apps', sourceId: 'standalone', appsBuild: true, ...base } + ] + expect(reusableInstalls(list, category)).toEqual([]) + }) + + it('leaves out installs that are not finished or have no folder', () => { + const list = [ + { id: 'installing', sourceId: 'standalone', installPath: '/x', status: 'installing' }, + { id: 'failed', sourceId: 'standalone', installPath: '/x', status: 'failed' }, + { id: 'unknown', sourceId: 'standalone', installPath: '/x' }, + { id: 'nowhere', sourceId: 'standalone', installPath: '', status: 'installed' } + ] + expect(reusableInstalls(list, category)).toEqual([]) + }) +}) + +describe('which ComfyUI an app run uses', () => { + const at = (id: string, version: string | null, running = false, busy = false) => ({ + id, + version, + running, + busy + }) + + it('uses one that is already running over a newer stopped one', () => { + const list = [at('stopped', '0.45.0'), at('running', '0.43.0', true)] + expect(pickComfy(list, '0.42.1')?.id).toBe('running') + }) + + it('picks the newest compatible one', () => { + const list = [at('old', '0.43.0'), at('new', '0.44.2'), at('mid', '0.44.0')] + expect(pickComfy(list, '0.42.1')?.id).toBe('new') + }) + + it('picks the newest of several running ones', () => { + const list = [at('a', '0.43.0', true), at('b', '0.44.0', true)] + expect(pickComfy(list, '0.42.1')?.id).toBe('b') + }) + + it('keeps list order between equal versions', () => { + const list = [at('first', '0.44.0'), at('second', '0.44.0')] + expect(pickComfy(list, '0.42.1')?.id).toBe('first') + }) + + it('accepts exactly the minimum version', () => { + expect(pickComfy([at('a', '0.37.0')], '0.37.0')?.id).toBe('a') + }) + + it('skips installs older than the app needs, even running ones', () => { + const list = [at('old', '0.36.9', true), at('ok', '0.37.0')] + expect(pickComfy(list, '0.37.0')?.id).toBe('ok') + expect(pickComfy([at('old', '0.41.0', true)], '0.42.1')).toBeNull() + }) + + it('treats an install whose version is unknown as not compatible', () => { + expect(pickComfy([at('unknown', null, true)], '0.30.0')).toBeNull() + }) + + it('skips installs Desktop is busy with', () => { + const list = [at('updating', '0.45.0', false, true), at('ok', '0.43.0')] + expect(pickComfy(list, '0.42.1')?.id).toBe('ok') + }) + + it('stays on the running one apps already use while it still fits', () => { + const list = [at('newer', '0.45.0', true), at('used', '0.43.0', true)] + expect(pickComfy(list, '0.42.1', 'used')?.id).toBe('used') + expect(pickComfy(list, '0.44.0', 'used')?.id).toBe('newer') + expect( + pickComfy([at('newer', '0.45.0', true), at('used', '0.43.0')], '0.42.1', 'used')?.id + ).toBe('newer') + }) + + it('finds none so the Apps build is used', () => { + expect(pickComfy([], '0.42.1')).toBeNull() + }) + + it('lets a page that needs less use an older install', () => { + const list = [at('song', '0.36.0')] + expect(pickComfy(list, '0.36.0')?.id).toBe('song') + expect(pickComfy(list, APPS_BUILD_VERSION)).toBeNull() + }) +}) diff --git a/src/main/apps/appsBuildRules.ts b/src/main/apps/appsBuildRules.ts index 00182290e..3a15808ae 100644 --- a/src/main/apps/appsBuildRules.ts +++ b/src/main/apps/appsBuildRules.ts @@ -1,8 +1,10 @@ import path from 'path' +import semver from 'semver' import { isAppsBuild } from '../../shared/appsBuild' export const APPS_BUILD_NAME = 'Apps' export const APPS_BUILD_RELEASE = 'v0.42.1-env1' +export const APPS_BUILD_VERSION = releaseVersion(APPS_BUILD_RELEASE)! export const APPS_BUILD_FIRST_PORT = 8288 export const APPS_BUILD_LAST_PORT = 8388 export const APPS_BUILD_IDLE_MS = 10 * 60_000 @@ -197,3 +199,69 @@ export function pickOpenTarget( .sort((a, b) => startedAt.get(b.id)! - startedAt.get(a.id)!) return running[0] ?? own[0] ?? null } + +export function releaseVersion(tag: unknown): string | null { + if (typeof tag !== 'string') return null + const m = /^v?(\d{1,6}\.\d{1,6}\.\d{1,6})(?:$|[-+])/.exec(tag.trim()) + return m ? semver.valid(m[1]!) : null +} + +export function wantedVersion(input: unknown): string { + const raw = + input && typeof input === 'object' ? (input as { minVersion?: unknown }).minVersion : undefined + return releaseVersion(raw) ?? APPS_BUILD_VERSION +} + +export function comfyuiFileVersion(text: string): string | null { + const m = /^__version__\s*=\s*['"]([^'"]+)['"]/m.exec(text) + return m ? releaseVersion(m[1]) : null +} + +export interface ReuseInstall { + id: string + sourceId: string + installPath?: string + status?: string + appsBuild?: unknown +} + +export function reusableInstalls( + list: readonly T[], + categoryOf: (inst: T) => string | undefined +): T[] { + return list.filter( + (inst) => + categoryOf(inst) === 'local' && + inst.sourceId !== 'desktop' && + !isAppsBuild(inst) && + inst.status === 'installed' && + typeof inst.installPath === 'string' && + inst.installPath !== '' + ) +} + +export interface ComfyChoice { + id: string + version: string | null + running: boolean + busy: boolean +} + +export function pickComfy( + list: readonly T[], + min: string, + inUse?: string | null +): T | null { + const fits = list + .map((c, i) => ({ c, i })) + .filter(({ c }) => !c.busy && c.version !== null && semver.gte(c.version, min)) + const kept = fits.find(({ c }) => c.running && c.id === inUse) + if (kept) return kept.c + fits.sort( + (a, b) => + Number(b.c.running) - Number(a.c.running) || + semver.rcompare(a.c.version!, b.c.version!) || + a.i - b.i + ) + return fits[0]?.c ?? null +} diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index 4eacbd992..b96bf0c6d 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -7,7 +7,10 @@ import type { InstallationRecord } from '../installations' import { _getActiveLaunchIds, _getLaunchingInstances, + _isStopping, + _operationAborts, _runningSessions, + type SessionInfo, sessionLifecycleEvents, stopRunning } from '../lib/ipc/shared' @@ -20,18 +23,24 @@ import { cancelAppsSetup, ensureAppsBuild, findApps, + installVersion, launchAppsBuild, - planAppsBuild + launchConsole, + planAppsBuild, + reusableLocal } from './appsBuild' import { APPS_BUILD_NAME, + type ComfyChoice, FREE_IDLE_MS, FREE_JSON, freeWait, isRunEnd, + pickComfy, queueEmpty, type SetupEvent, - shouldStopIdle + shouldStopIdle, + wantedVersion } from './appsBuildRules' import { type DownloadRequest, @@ -52,6 +61,8 @@ import { export interface LocalState { state: 'running' | 'starting' | 'stopped' | 'none' | 'unsupported' name?: string + version?: string + own?: boolean clientId?: string error?: string setup?: boolean @@ -69,14 +80,33 @@ let starting: Promise | null = null let lastUse = Date.now() const runsSeen = new Map() +interface Target { + id: string + name: string + version: string | null + own: boolean +} + +let target: Target | null = null +const startedHere = new Set() + function touch(): void { lastUse = Date.now() } +function localSession(id: string): SessionInfo | null { + const s = _runningSessions.get(id) + return s && !s.url && s.port > 0 && (s.sourceInstallationId ?? id) === id ? s : null +} + export function appsRunning(): { id: string; name: string; port: number } | null { - const id = appsBuildId() - const s = id ? _runningSessions.get(id) : undefined - return id && s && !s.url && s.port > 0 ? { id, name: s.installationName, port: s.port } : null + const id = target?.id ?? appsBuildId() + const s = id ? localSession(id) : null + return id && s ? { id, name: s.installationName, port: s.port } : null +} + +export function ownInUse(): string | null { + return target?.own ? (appsRunning()?.id ?? null) : null } function launching(id: string): boolean { @@ -86,33 +116,89 @@ function launching(id: string): boolean { ) } -async function currentState(): Promise<{ state: LocalState; install?: InstallationRecord }> { +function busy(id: string, running: boolean): boolean { + if (_isStopping(id)) return true + if (running || startedHere.has(id)) return false + return _operationAborts.has(id) || launching(id) +} + +interface Candidate extends ComfyChoice { + inst: InstallationRecord + own: boolean +} + +async function candidate(inst: InstallationRecord, own: boolean): Promise { + const running = localSession(inst.id) !== null + return { + id: inst.id, + inst, + own, + running, + busy: busy(inst.id, running), + version: await installVersion(inst) + } +} + +async function choose(min: string, apps: InstallationRecord | null): Promise { + const own = await Promise.all((await reusableLocal()).map((inst) => candidate(inst, true))) + const appsRunningNow = apps && localSession(apps.id) ? [await candidate(apps, false)] : [] + return pickComfy([...own, ...appsRunningNow], min, appsRunning()?.id) +} + +function aimAt(pick: Candidate | null): void { + target = pick ? { id: pick.id, name: pick.inst.name, version: pick.version, own: pick.own } : null +} + +function shown(): Pick { + if (!target?.own) return {} + return { name: target.name, own: true, ...(target.version ? { version: target.version } : {}) } +} + +interface Current { + state: LocalState + pick: Candidate | null +} + +async function currentState(want: unknown, adopt: boolean): Promise { const off = await appsLocalOff() - if (off) return { state: { state: 'unsupported', error: off } } + if (off) return { state: { state: 'unsupported', error: off }, pick: null } const inst = await findApps() + if (adopt) { + const pick = await choose(wantedVersion(want), inst?.status === 'installed' ? inst : null) + aimAt(pick) + if (pick?.own && !pick.running) { + const state = launching(pick.id) ? 'starting' : 'stopped' + return { state: { state, ...shown() }, pick } + } + } const run = appsRunning() if (run) { return { - state: { state: 'running', name: run.name, clientId: CLIENT_ID }, - ...(inst ? { install: inst } : {}) + state: { state: 'running', name: run.name, ...shown(), clientId: CLIENT_ID }, + pick: null } } + if (target?.own) return { state: { state: 'starting', ...shown() }, pick: null } if (appsSetupRunning()) - return { state: { state: 'starting', name: APPS_BUILD_NAME, setup: true } } + return { state: { state: 'starting', name: APPS_BUILD_NAME, setup: true }, pick: null } if (!inst || inst.status !== 'installed') { const download = await planAppsBuild().then( (p) => p.bytes, () => 0 ) - return { state: { state: 'none', name: APPS_BUILD_NAME, ...(download ? { download } : {}) } } + return { + state: { state: 'none', name: APPS_BUILD_NAME, ...(download ? { download } : {}) }, + pick: null + } } - if (launching(inst.id)) return { state: { state: 'starting', name: inst.name }, install: inst } - return { state: { state: 'stopped', name: inst.name }, install: inst } + if (launching(inst.id)) return { state: { state: 'starting', name: inst.name }, pick: null } + return { state: { state: 'stopped', name: inst.name }, pick: null } } -export async function getLocal(): Promise { +export async function getLocal(want?: unknown): Promise { + syncLocalSocket() + const { state } = await currentState(want, !starting) syncLocalSocket() - const { state } = await currentState() return state.state === 'stopped' && starting ? { ...state, state: 'starting' } : state } @@ -130,24 +216,21 @@ async function answers(port: number): Promise { const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) -async function untilAnswering(name: string | undefined): Promise { +async function untilAnswering(id: string, name: string | undefined): Promise { const deadline = Date.now() + COMFY_BOOT_TIMEOUT_MS while (Date.now() < deadline) { const run = appsRunning() if (run && (await answers(run.port))) { touch() syncLocalSocket() - return { state: 'running', name: run.name, clientId: CLIENT_ID } + return { state: 'running', name: run.name, ...shown(), clientId: CLIENT_ID } } - if (!run) { - const { state } = await currentState() - if (state.state !== 'starting') { - return { state: 'stopped', name, error: 'ComfyUI stopped before it was ready.' } - } + if (!run && !launching(id)) { + return { state: 'stopped', name, ...shown(), error: 'ComfyUI stopped before it was ready.' } } await sleep(1000) } - return { state: 'stopped', name, error: 'ComfyUI did not answer within 5 minutes.' } + return { state: 'stopped', name, ...shown(), error: 'ComfyUI did not answer within 5 minutes.' } } function shortError(message: string | undefined): string { @@ -159,9 +242,24 @@ function sendSetup(event: SetupEvent): void { forward({ type: 'setup', data: event }) } -async function start(): Promise { - const { state } = await currentState() +async function startOwn(inst: InstallationRecord): Promise { + touch() + if (!appsRunning() && !launching(inst.id)) { + startedHere.add(inst.id) + const result = await launchConsole(inst) + if (!result.ok && !appsRunning()) { + if (!localSession(inst.id) && !launching(inst.id)) startedHere.delete(inst.id) + return { state: 'stopped', name: inst.name, ...shown(), error: shortError(result.message) } + } + } + return untilAnswering(inst.id, inst.name) +} + +async function start(want: unknown): Promise { + const { state, pick } = await currentState(want, true) + syncLocalSocket() if (state.state === 'unsupported' || state.state === 'running') return state + if (pick?.own) return startOwn(pick.inst) let inst: InstallationRecord try { inst = await ensureAppsBuild(sendSetup) @@ -175,11 +273,11 @@ async function start(): Promise { return { state: 'stopped', name: inst.name, error: shortError(result.message) } } } - return untilAnswering(inst.name) + return untilAnswering(inst.id, inst.name) } -export function startLocal(): Promise { - starting ??= start().finally(() => (starting = null)) +export function startLocal(want?: unknown): Promise { + starting ??= start(want).finally(() => (starting = null)) return starting } @@ -278,7 +376,7 @@ async function runDownload(installationId: string, req: DownloadRequest): Promis export async function localDownload(input: unknown): Promise { const req = downloadRequest(input) if ('error' in req) return { state: 'failed', error: req.error } - const installationId = appsRunning()?.id ?? (await findApps())?.id + const installationId = appsRunning()?.id ?? target?.id ?? (await findApps())?.id if (!installationId) return { state: 'failed', error: 'Start ComfyUI for apps first.' } touch() const key = [installationId, req.url, req.folder, req.name].join('\n') @@ -387,19 +485,32 @@ function scheduleFree(port: number, wait = FREE_IDLE_MS): void { }, wait) } +function startedByApps(): string[] { + if (!starting) { + for (const id of startedHere) { + if (!localSession(id) && !launching(id)) startedHere.delete(id) + } + } + const apps = appsBuildId() + return [...(apps ? [apps] : []), ...[...startedHere].filter((id) => id !== apps)] +} + async function stopWhenIdle(): Promise { - const run = appsRunning() - if (!run) return - const entry = getEntryByInstallationId(run.id) - const idle = shouldStopIdle({ - mode: _runningSessions.get(run.id)?.mode ?? '', - hasWindow: !!entry && !entry.window.isDestroyed(), - lastUse, - now: Date.now() - }) - if (!idle) return - if (downloads.size > 0 || starting || !(await queueIsEmpty(run.port))) return touch() - await stopRunning(run.id) + for (const id of startedByApps()) { + const s = localSession(id) + if (!s) continue + const entry = getEntryByInstallationId(id) + const idle = shouldStopIdle({ + mode: s.mode, + hasWindow: !!entry && !entry.window.isDestroyed(), + lastUse, + now: Date.now() + }) + if (!idle) continue + if (downloads.size > 0 || starting || !(await queueIsEmpty(s.port))) return touch() + await stopRunning(id) + startedHere.delete(id) + } } export function initLocalComfy(pages: () => WebContents[]): void { diff --git a/src/main/apps/openInComfy.ts b/src/main/apps/openInComfy.ts index 15cc22b68..edc152605 100644 --- a/src/main/apps/openInComfy.ts +++ b/src/main/apps/openInComfy.ts @@ -3,13 +3,7 @@ import { getEntryByInstallationId } from '../host/registry' import type { ComfyWindowEntry } from '../host/registry' import * as installations from '../installations' import { _runningSessions } from '../lib/ipc/shared' -import { - categoryOf, - findApps, - launchAppsBuild, - launchInstall, - showAppsBuildWindow -} from './appsBuild' +import { categoryOf, findApps, launchAppsBuild, launchInstall, showComfyWindow } from './appsBuild' import { pickOpenTarget } from './appsBuildRules' import { COMFY_READY_SCRIPT, @@ -19,6 +13,7 @@ import { openRequest, openWorkflowScript } from './guards' +import { ownInUse } from './localComfy' export type OpenResult = { opened: true } | { opened: false; error: string } @@ -46,7 +41,7 @@ function startedAt(): Map { } async function running(inst: installations.InstallationRecord): Promise { - if (_runningSessions.has(inst.id)) return inst.id + if (_runningSessions.has(inst.id)) return showComfyWindow(inst) ? inst.id : null const result = await launchInstall(inst) return result.ok || _runningSessions.has(inst.id) ? inst.id : null } @@ -54,13 +49,17 @@ async function running(inst: installations.InstallationRecord): Promise { const apps = await findApps() if (apps?.status !== 'installed') return null - if (_runningSessions.has(apps.id)) return showAppsBuildWindow(apps) ? apps.id : null + if (_runningSessions.has(apps.id)) return showComfyWindow(apps) ? apps.id : null const result = await launchAppsBuild(apps, true) return result.ok || _runningSessions.has(apps.id) ? apps.id : null } async function localInstallId(build?: string): Promise { - const target = pickOpenTarget(await ownBuilds(), startedAt(), build) + const own = await ownBuilds() + const used = build === undefined ? ownInUse() : null + const inUse = used ? own.find((inst) => inst.id === used) : undefined + if (inUse) return running(inUse) + const target = pickOpenTarget(own, startedAt(), build) if (target) return running(target) return build === undefined ? appsBuildWindow() : null } diff --git a/src/preload/appsPreload.ts b/src/preload/appsPreload.ts index fa281bede..600363696 100644 --- a/src/preload/appsPreload.ts +++ b/src/preload/appsPreload.ts @@ -53,8 +53,9 @@ contextBridge.exposeInMainWorld('comfyDesktopApps', { ipcRenderer.invoke('comfy-apps:save-versions', app, bytes), readVersions: (app: string) => ipcRenderer.invoke('comfy-apps:read-versions', app), getNodePrice: (node: string) => ipcRenderer.invoke('comfy-apps:get-node-price', node), - getLocal: () => ipcRenderer.invoke('comfy-apps:get-local'), - startLocal: () => ipcRenderer.invoke('comfy-apps:start-local'), + getLocal: (want?: { minVersion?: string }) => ipcRenderer.invoke('comfy-apps:get-local', want), + startLocal: (want?: { minVersion?: string }) => + ipcRenderer.invoke('comfy-apps:start-local', want), cancelSetup: () => ipcRenderer.invoke('comfy-apps:cancel-setup'), localBuilds: () => ipcRenderer.invoke('comfy-apps:local-builds'), localFetch: (req: { method: string; path: string; body?: unknown; fileName?: string }) => From a4a6dd4cfadea52c5f3847811156a5aab3d5526f Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Thu, 12 Nov 2026 17:22:03 -0800 Subject: [PATCH 2/8] fix(apps): keep reused ComfyUI runs, versions, sessions and data apart - A page that asks for a newer ComfyUI no longer takes the ComfyUI away from another app's queued or running run: the switch waits until those runs leave the queue and the page is told ComfyUI is busy. A page check only moves to a ComfyUI that is already running, and a check that finishes after a newer start chose another ComfyUI is dropped. History, file and stop requests go to the ComfyUI that ran them. - An app that joins a start already under way checks the started ComfyUI against its own minimum and starts a fitting one when it is older. - A running ComfyUI is judged by the version its process reports in /system_stats. comfyui_version.py changes on a Git Pull while the old process keeps running; it is still used for a stopped install. - A person's ComfyUI is reused only from 0.3.57, the first release whose /interrupt honours prompt_id (comfyanonymous/ComfyUI#9607). Older servers interrupt whatever runs, so cancelling an app run would stop the person's workflow. Older installs fall back to the Apps build. - Idle stop records the session apps launched, forgets it when that session ends, and checks it again before stopping, so a session the person starts later on the same install is never stopped. - On a person's ComfyUI, apps read history and stop or remove only the runs they queued, view only files those runs made or apps uploaded, and see other queued runs without their ids. The Apps build keeps its current behaviour. --- src/main/apps/appsBuildRules.test.ts | 28 ++ src/main/apps/appsBuildRules.ts | 16 +- src/main/apps/guards.test.ts | 96 +++++ src/main/apps/guards.ts | 114 +++++- src/main/apps/localComfy.test.ts | 520 +++++++++++++++++++++++++++ src/main/apps/localComfy.ts | 290 ++++++++++++--- 6 files changed, 999 insertions(+), 65 deletions(-) create mode 100644 src/main/apps/localComfy.test.ts diff --git a/src/main/apps/appsBuildRules.test.ts b/src/main/apps/appsBuildRules.test.ts index face2cef0..8e689cfb6 100644 --- a/src/main/apps/appsBuildRules.test.ts +++ b/src/main/apps/appsBuildRules.test.ts @@ -28,9 +28,12 @@ import { queueEmpty, releaseVersion, reusableInstalls, + reuseMinimum, setupEnd, setupEvent, shouldStopIdle, + statsVersion, + TARGETED_INTERRUPT_VERSION, wantedVersion } from './appsBuildRules' import { localInstalls } from './guards' @@ -399,6 +402,31 @@ describe('the ComfyUI version an app needs', () => { }) }) +describe('the lowest ComfyUI an app run may reuse', () => { + it('is the first release whose interrupt stops only the named run', () => { + expect(TARGETED_INTERRUPT_VERSION).toBe('0.3.57') + expect(reuseMinimum('0.3.31')).toBe('0.3.57') + expect(reuseMinimum('0.37.0')).toBe('0.37.0') + }) + + it('keeps an older install out of the pick even when the page allows it', () => { + const old = { id: 'old', version: '0.3.56', running: true, busy: false } + expect(pickComfy([old], reuseMinimum('0.3.31'))).toBeNull() + }) +}) + +describe('reading the ComfyUI version a running process reports', () => { + it('reads system_stats', () => { + expect(statsVersion({ system: { comfyui_version: '0.36.0' } })).toBe('0.36.0') + }) + + it('gives no version when system_stats names none', () => { + expect(statsVersion({ system: {} })).toBeNull() + expect(statsVersion(null)).toBeNull() + expect(statsVersion({ system: { comfyui_version: 'dev' } })).toBeNull() + }) +}) + describe('reading the ComfyUI version of an install', () => { it('reads comfyui_version.py', () => { expect(comfyuiFileVersion('# generated\n__version__ = "0.44.0"\n')).toBe('0.44.0') diff --git a/src/main/apps/appsBuildRules.ts b/src/main/apps/appsBuildRules.ts index 3a15808ae..4bdd02820 100644 --- a/src/main/apps/appsBuildRules.ts +++ b/src/main/apps/appsBuildRules.ts @@ -5,6 +5,7 @@ import { isAppsBuild } from '../../shared/appsBuild' export const APPS_BUILD_NAME = 'Apps' export const APPS_BUILD_RELEASE = 'v0.42.1-env1' export const APPS_BUILD_VERSION = releaseVersion(APPS_BUILD_RELEASE)! +export const TARGETED_INTERRUPT_VERSION = '0.3.57' export const APPS_BUILD_FIRST_PORT = 8288 export const APPS_BUILD_LAST_PORT = 8388 export const APPS_BUILD_IDLE_MS = 10 * 60_000 @@ -212,6 +213,19 @@ export function wantedVersion(input: unknown): string { return releaseVersion(raw) ?? APPS_BUILD_VERSION } +export function reuseMinimum(min: string): string { + return semver.gt(min, TARGETED_INTERRUPT_VERSION) ? min : TARGETED_INTERRUPT_VERSION +} + +export function meetsMinimum(version: string | null, min: string): boolean { + return version !== null && semver.gte(version, min) +} + +export function statsVersion(stats: unknown): string | null { + const system = (stats as { system?: { comfyui_version?: unknown } } | null)?.system + return releaseVersion(system?.comfyui_version) +} + export function comfyuiFileVersion(text: string): string | null { const m = /^__version__\s*=\s*['"]([^'"]+)['"]/m.exec(text) return m ? releaseVersion(m[1]) : null @@ -254,7 +268,7 @@ export function pickComfy( ): T | null { const fits = list .map((c, i) => ({ c, i })) - .filter(({ c }) => !c.busy && c.version !== null && semver.gte(c.version, min)) + .filter(({ c }) => !c.busy && meetsMinimum(c.version, min)) const kept = fits.find(({ c }) => c.running && c.id === inUse) if (kept) return kept.c fits.sort( diff --git a/src/main/apps/guards.test.ts b/src/main/apps/guards.test.ts index 1f700107d..02d299b4f 100644 --- a/src/main/apps/guards.test.ts +++ b/src/main/apps/guards.test.ts @@ -10,6 +10,9 @@ import { COMFY_READY_SCRIPT, collectOutputs, downloadRequest, + eventFiles, + fileKey, + historyFiles, inJobGrace, interruptJson, JOB_GRACE_MS, @@ -28,23 +31,28 @@ import { localEvent, localInstalls, localRequest, + noteOwner, noteRun, noteSubmitted, openRequest, openWorkflowScript, outputKind, + promptRunId, queueAnswer, queueJson, queueView, readable, readCapped, reconnectDelay, + requestFile, + requestRuns, type RunSeen, safeUploadName, saveExt, savedFileName, textAnswer, toOutputFile, + uploadedFile, uploadForm, viewQuery, workflowName @@ -961,3 +969,91 @@ describe('reading the local queue', () => { expect(queueAnswer(200, new TextEncoder().encode('not json'), new Map()).status).toBe(502) }) }) + +describe('which runs and files a local request touches', () => { + const ask = (input: unknown) => { + const req = localRequest(input) + if (!('kind' in req)) throw new Error(req.error) + return req + } + + it('names the run a history read, an interrupt or a queue removal is about', () => { + expect(requestRuns(ask({ method: 'GET', path: '/history/ab-1' }))).toEqual(['ab-1']) + expect( + requestRuns(ask({ method: 'POST', path: '/interrupt', body: { prompt_id: 'ab-1' } })) + ).toEqual(['ab-1']) + expect( + requestRuns(ask({ method: 'POST', path: '/queue', body: { delete: ['a', 'b'] } })) + ).toEqual(['a', 'b']) + expect(requestRuns(ask({ method: 'GET', path: '/queue' }))).toEqual([]) + expect(requestRuns(ask({ method: 'GET', path: '/system_stats' }))).toEqual([]) + }) + + it('names the file a view reads', () => { + const req = ask({ method: 'GET', path: '/view?filename=a.png&subfolder=apps&type=output' }) + expect(requestFile(req)).toBe(fileKey({ filename: 'a.png', subfolder: 'apps', type: 'output' })) + expect(requestFile(ask({ method: 'GET', path: '/history/ab-1' }))).toBeNull() + }) +}) + +describe('what ComfyUI says apps made', () => { + const bytes = (v: unknown) => new TextEncoder().encode(JSON.stringify(v)) + + it('reads the run id a queued prompt got', () => { + expect(promptRunId(bytes({ prompt_id: 'ab-1', number: 3 }))).toBe('ab-1') + expect(promptRunId(bytes({ error: 'x' }))).toBeNull() + expect(promptRunId(new TextEncoder().encode('not json'))).toBeNull() + }) + + it('reads the input file an upload kept', () => { + expect(uploadedFile(bytes({ name: 'p.png', subfolder: '', type: 'input' }))).toBe( + fileKey({ filename: 'p.png', subfolder: '', type: 'input' }) + ) + expect(uploadedFile(bytes({}))).toBeNull() + }) + + it('reads the output files of one run from its history', () => { + const history = { + r1: { + outputs: { '9': { images: [{ filename: 'a.png', subfolder: 'apps', type: 'output' }] } } + } + } + expect(historyFiles(bytes(history), 'r1')).toEqual([ + fileKey({ filename: 'a.png', subfolder: 'apps', type: 'output' }) + ]) + expect(historyFiles(bytes(history), 'r2')).toEqual([]) + }) + + it('reads the files an executed event names', () => { + const msg = { + type: 'executed', + data: { + prompt_id: 'r1', + node: '9', + output: { images: [{ filename: 'a.png', type: 'temp' }] } + } + } + expect(eventFiles(msg)).toEqual({ + runId: 'r1', + files: [fileKey({ filename: 'a.png', subfolder: '', type: 'temp' })] + }) + expect(eventFiles({ type: 'progress', data: { prompt_id: 'r1' } })).toBeNull() + }) + + it('keeps only the newest owners', () => { + const owners = new Map() + for (let i = 0; i < 5; i++) noteOwner(owners, `r${i}`, 'x', 3) + expect([...owners.keys()]).toEqual(['r2', 'r3', 'r4']) + }) + + it('hides the queued runs apps do not own but keeps their place', () => { + const raw = { + queue_running: [[0, 'theirs', {}, { comfy_app: { name: 'Mine' } }, []]], + queue_pending: [[1, 'ours', {}, {}, []]] + } + expect(queueView(raw, new Map(), (id) => id === 'ours')).toEqual({ + running: [{ id: '', app: null, seconds: null }], + pending: [{ id: 'ours', app: null, seconds: null }] + }) + }) +}) diff --git a/src/main/apps/guards.ts b/src/main/apps/guards.ts index 481a915f9..7eff3827f 100644 --- a/src/main/apps/guards.ts +++ b/src/main/apps/guards.ts @@ -407,13 +407,25 @@ function appTag(extra: unknown): { app: string | null; seconds: number | null } } } -function queueRuns(list: unknown, seen: ReadonlyMap): QueueRun[] { +export type RunOwned = (runId: string) => boolean + +const HIDDEN_RUN: QueueRun = { id: '', app: null, seconds: null } + +function queueRuns( + list: unknown, + seen: ReadonlyMap, + owned?: RunOwned +): QueueRun[] { if (!Array.isArray(list)) return [] const runs: Array<{ n: number; run: QueueRun }> = [] for (const item of list) { if (!Array.isArray(item)) continue const n = typeof item[0] === 'number' && Number.isFinite(item[0]) ? item[0] : 0 const id = isRunId(item[1]) ? item[1] : '' + if (owned && !owned(id)) { + runs.push({ n, run: { ...HIDDEN_RUN } }) + continue + } const s = id ? seen.get(id) : undefined runs.push({ n, @@ -431,18 +443,26 @@ function queueRuns(list: unknown, seen: ReadonlyMap): QueueRun[ .map((r) => r.run) } -export function queueView(raw: unknown, seen: ReadonlyMap = new Map()): QueueView { +export function queueView( + raw: unknown, + seen: ReadonlyMap = new Map(), + owned?: RunOwned +): QueueView { const q = (raw && typeof raw === 'object' ? raw : {}) as { queue_running?: unknown queue_pending?: unknown } - return { running: queueRuns(q.queue_running, seen), pending: queueRuns(q.queue_pending, seen) } + return { + running: queueRuns(q.queue_running, seen, owned), + pending: queueRuns(q.queue_pending, seen, owned) + } } export function queueAnswer( status: number, body: Uint8Array, - seen: ReadonlyMap + seen: ReadonlyMap, + owned?: RunOwned ): LocalAnswer { if (status < 200 || status >= 300) return textAnswer(status, 'ComfyUI did not show its queue.') let raw: unknown @@ -454,7 +474,7 @@ export function queueAnswer( return { status: 200, contentType: 'application/json', - body: new TextEncoder().encode(JSON.stringify(queueView(raw, seen))) + body: new TextEncoder().encode(JSON.stringify(queueView(raw, seen, owned))) } } @@ -530,6 +550,90 @@ export function localRequest(input: unknown): LocalRequest | LocalRefusal { return { status: 405, error: 'Apps can only GET and POST.' } } +export function fileKey(file: { filename: string; subfolder?: string; type: string }): string { + return [file.type, file.subfolder ?? '', file.filename].join('\n') +} + +const HISTORY_PATH = /^\/history\/([A-Za-z0-9-]{1,64})$/ + +export function requestRuns(req: LocalRequest): string[] { + if (req.kind === 'get') { + const id = HISTORY_PATH.exec(req.path)?.[1] + return id ? [id] : [] + } + if (req.kind !== 'json') return [] + const v = JSON.parse(req.json) as { prompt_id?: string; delete?: string[] } + return req.path === '/interrupt' ? [v.prompt_id!] : v.delete! +} + +export function requestFile(req: LocalRequest): string | null { + if (req.kind !== 'get' || !req.path.startsWith('/view?')) return null + const q = new URLSearchParams(req.path.slice('/view?'.length)) + return fileKey({ + filename: q.get('filename') ?? '', + subfolder: q.get('subfolder') ?? '', + type: q.get('type') ?? '' + }) +} + +function jsonOf(body: Uint8Array): unknown { + try { + return JSON.parse(new TextDecoder().decode(body)) + } catch { + return null + } +} + +export function promptRunId(body: Uint8Array): string | null { + const id = (jsonOf(body) as { prompt_id?: unknown } | null)?.prompt_id + return isRunId(id) ? id : null +} + +export function uploadedFile(body: Uint8Array): string | null { + const v = jsonOf(body) as { name?: unknown; subfolder?: unknown; type?: unknown } | null + if (typeof v?.name !== 'string' || !v.name) return null + return fileKey({ + filename: v.name, + subfolder: typeof v.subfolder === 'string' ? v.subfolder : '', + type: typeof v.type === 'string' ? v.type : 'input' + }) +} + +export function historyFiles(body: Uint8Array, runId: string): string[] { + const entry = (jsonOf(body) as Record | null)?.[runId] + return collectOutputs(entry?.outputs).files.map(fileKey) +} + +export function eventFiles(msg: { type: string; data: unknown }): { + runId: string + files: string[] +} | null { + if (msg.type !== 'executed') return null + const data = (msg.data ?? {}) as { prompt_id?: unknown; node?: unknown; output?: unknown } + if (!isRunId(data.prompt_id)) return null + const node = typeof data.node === 'string' ? data.node : '' + return { + runId: data.prompt_id, + files: collectOutputs({ [node]: data.output }).files.map(fileKey) + } +} + +export const MAX_OWNED = 2000 + +export function noteOwner( + owners: Map, + key: string, + owner: string, + max = MAX_OWNED +): void { + owners.delete(key) + owners.set(key, owner) + for (const old of owners.keys()) { + if (owners.size <= max) break + owners.delete(old) + } +} + export async function readCapped( res: Response, max: number, diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts new file mode 100644 index 000000000..20d65ab43 --- /dev/null +++ b/src/main/apps/localComfy.test.ts @@ -0,0 +1,520 @@ +// @vitest-environment node +import type { EventEmitter } from 'events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type * as LocalComfyModule from './localComfy' + +interface FakeSession { + proc: null + port: number + mode: string + installationName: string + startedAt: number +} + +interface FakeInstall { + id: string + name: string + sourceId: string + installPath: string + status: string +} + +interface FakeComfy { + version: string + running: unknown[] + pending: unknown[] + history: Record + files: Set + calls: string[] +} + +const fake = vi.hoisted(() => ({ + sessions: new Map(), + lifecycle: null as EventEmitter | null, + installs: [] as FakeInstall[], + diskVersion: new Map(), + ports: new Map(), + apps: { id: null as string | null, inst: null as FakeInstall | null }, + versionGate: null as Promise | null, + servers: new Map(), + sockets: [] as Array<{ url: string; closed: boolean }> +})) + +function sessionFor(id: string, mode = 'console'): FakeSession { + const inst = [...fake.installs, fake.apps.inst].find((i) => i?.id === id) + return { + proc: null, + port: fake.ports.get(id)!, + mode, + installationName: inst?.name ?? id, + startedAt: Date.now() + } +} + +const launchConsole = vi.hoisted(() => + vi.fn(async (inst: { id: string }) => { + fake.sessions.set(inst.id, sessionFor(inst.id)) + fake.lifecycle!.emit('changed') + return { ok: true } + }) +) + +const stopRunning = vi.hoisted(() => + vi.fn(async (id: string) => { + fake.sessions.delete(id) + fake.lifecycle!.emit('changed') + }) +) + +vi.mock('../host/registry', () => ({ getEntryByInstallationId: () => undefined })) +vi.mock('../lib/comfyDownloadManager', () => ({ startManagedModelJob: vi.fn() })) +vi.mock('../lib/process', () => ({ COMFY_BOOT_TIMEOUT_MS: 5_000 })) +vi.mock('../lib/ipc/shared', async () => { + const { EventEmitter: Emitter } = await import('events') + fake.lifecycle ??= new Emitter() + return { + _getActiveLaunchIds: () => [], + _getLaunchingInstances: () => [], + _isStopping: () => false, + _operationAborts: new Map(), + _runningSessions: fake.sessions, + sessionLifecycleEvents: fake.lifecycle, + stopRunning + } +}) +vi.mock('./appsBuild', () => ({ + appsBuildId: () => fake.apps.id, + appsLocalOff: async () => null, + appsSetupRunning: () => false, + cancelAppsSetup: () => ({ cancelled: false }), + ensureAppsBuild: async () => { + fake.apps.inst = { + id: 'apps', + name: 'Apps', + sourceId: 'standalone', + installPath: '/apps', + status: 'installed' + } + fake.apps.id = 'apps' + return fake.apps.inst + }, + findApps: async () => fake.apps.inst, + installVersion: async (inst: { id: string }) => { + const gate = fake.versionGate + fake.versionGate = null + if (gate) await gate + return fake.diskVersion.get(inst.id) ?? null + }, + launchAppsBuild: launchConsole, + launchConsole, + planAppsBuild: async () => ({ data: {}, bytes: 0 }), + reusableLocal: async () => fake.installs +})) + +class FakeSocket { + url: string + closed = false + binaryType = '' + onopen: (() => void) | null = null + onmessage: ((ev: { data: unknown }) => void) | null = null + onerror: (() => void) | null = null + onclose: (() => void) | null = null + constructor(url: string) { + this.url = url + fake.sockets.push(this) + } + close(): void { + this.closed = true + } +} + +const json = (value: unknown, status = 200) => + new Response(JSON.stringify(value), { + status, + headers: { 'Content-Type': 'application/json' } + }) + +function fakeFetch(input: string | URL, init?: RequestInit): Promise { + const url = new URL(String(input)) + const server = fake.servers.get(Number(url.port)) + if (!server || ![...fake.sessions.values()].some((s) => s.port === Number(url.port))) { + return Promise.reject(new TypeError('fetch failed')) + } + const method = init?.method ?? 'GET' + server.calls.push(`${method} ${url.pathname}`) + const p = url.pathname + if (p === '/system_stats') + return Promise.resolve(json({ system: { comfyui_version: server.version } })) + if (p === '/prompt' && method === 'GET') { + return Promise.resolve( + json({ exec_info: { queue_remaining: server.running.length + server.pending.length } }) + ) + } + if (p === '/prompt') { + const id = `apps-${server.calls.length}` + server.pending.push([server.pending.length, id, {}, {}, []]) + return Promise.resolve(json({ prompt_id: id, number: 1, node_errors: {} })) + } + if (p === '/queue' && method === 'GET') { + return Promise.resolve(json({ queue_running: server.running, queue_pending: server.pending })) + } + if (p.startsWith('/history/')) { + const id = p.slice('/history/'.length) + return Promise.resolve(json(id in server.history ? { [id]: server.history[id] } : {})) + } + if (p === '/view') { + const key = [ + url.searchParams.get('type'), + url.searchParams.get('subfolder'), + url.searchParams.get('filename') + ].join('/') + return Promise.resolve( + server.files.has(key) + ? new Response(new Uint8Array([1, 2, 3])) + : new Response('', { status: 404 }) + ) + } + if (p === '/upload/image') { + server.files.add('input//photo.png') + return Promise.resolve(json({ name: 'photo.png', subfolder: '', type: 'input' })) + } + return Promise.resolve(new Response('', { status: 200 })) +} + +function addInstall(id: string, port: number, disk: string, served = disk): FakeComfy { + fake.installs.push({ + id, + name: `ComfyUI ${id}`, + sourceId: 'standalone', + installPath: `/${id}`, + status: 'installed' + }) + fake.diskVersion.set(id, disk) + fake.ports.set(id, port) + const server: FakeComfy = { + version: served, + running: [], + pending: [], + history: {}, + files: new Set(), + calls: [] + } + fake.servers.set(port, server) + return server +} + +function addAppsServer(port: number): FakeComfy { + fake.ports.set('apps', port) + const server: FakeComfy = { + version: '0.42.1', + running: [], + pending: [], + history: {}, + files: new Set(), + calls: [] + } + fake.servers.set(port, server) + return server +} + +function run(id: string, mode = 'console'): void { + fake.sessions.set(id, sessionFor(id, mode)) +} + +type LocalComfy = typeof LocalComfyModule + +async function load(): Promise { + const mod = await import('./localComfy') + mod.initLocalComfy(() => [{ isDestroyed: () => false, send: () => {} } as never]) + return mod +} + +const text = (body: Uint8Array) => new TextDecoder().decode(body) + +beforeEach(() => { + vi.resetModules() + fake.lifecycle?.removeAllListeners() + fake.sessions.clear() + fake.installs.length = 0 + fake.diskVersion.clear() + fake.ports.clear() + fake.servers.clear() + fake.sockets.length = 0 + fake.apps.id = null + fake.apps.inst = null + fake.versionGate = null + launchConsole.mockClear() + stopRunning.mockClear() + vi.stubGlobal('fetch', vi.fn(fakeFetch)) + vi.stubGlobal('WebSocket', FakeSocket) +}) + +afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +describe('an app run keeps its ComfyUI while another app asks for a newer one', () => { + it('keeps routing the first app run when a second page asks for a higher minimum', async () => { + const x = addInstall('x', 8188, '0.36.0') + addInstall('y', 8288, '0.42.4') + run('x') + const local = await load() + + expect(await local.getLocal({ minVersion: '0.36.0' })).toMatchObject({ + state: 'running', + own: true + }) + const queued = await local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } }) + const runId = JSON.parse(text(queued.body)).prompt_id as string + x.history[runId] = { status: { completed: false }, outputs: {} } + + await local.getLocal({ minVersion: '0.37.0' }) + const second = await local.startLocal({ minVersion: '0.37.0' }) + + expect(second.state, 'the second app waits instead of taking the ComfyUI away').not.toBe( + 'running' + ) + expect(second.error).toMatch(/busy/) + expect(launchConsole).not.toHaveBeenCalled() + const history = await local.localFetch({ method: 'GET', path: `/history/${runId}` }) + expect(history.status).toBe(200) + expect(JSON.parse(text(history.body))).toHaveProperty(runId) + expect(fake.sockets.filter((s) => !s.closed).map((s) => s.url)).toEqual([ + expect.stringContaining(':8188/') + ]) + }) + + it('drops a page check that finishes after a newer start chose another ComfyUI', async () => { + addInstall('z', 8188, '0.36.0') + addInstall('y', 8288, '0.42.4') + run('z') + const local = await load() + + let release!: () => void + fake.versionGate = new Promise((r) => (release = r)) + const slow = local.getLocal({ minVersion: '0.36.0' }) + await new Promise((r) => setTimeout(r, 0)) + const started = await local.startLocal({ minVersion: '0.40.0' }) + expect(started).toMatchObject({ state: 'running', name: 'ComfyUI y' }) + + release() + await slow + expect(local.ownInUse()).toBe('y') + }) +}) + +describe('an app that joins a start already under way', () => { + it('does not get a ComfyUI older than its own minimum', async () => { + addInstall('x', 8188, '0.36.0') + addAppsServer(8300) + const local = await load() + + const [first, second] = await Promise.all([ + local.startLocal({ minVersion: '0.36.0' }), + local.startLocal({ minVersion: '0.37.0' }) + ]) + + expect(first).toMatchObject({ state: 'running', name: 'ComfyUI x', version: '0.36.0' }) + expect(second.state).toBe('running') + expect(second.name).toBe('Apps') + }) +}) + +describe('the version of a ComfyUI that is already running', () => { + it('is what the running process reports, not the files a pull changed', async () => { + addInstall('x', 8188, '0.42.4', '0.36.0') + run('x') + const local = await load() + + const state = await local.getLocal({ minVersion: '0.37.0' }) + + expect(state.state).not.toBe('running') + expect(state.own).toBeUndefined() + }) + + it('still reuses a running ComfyUI whose process is new enough', async () => { + addInstall('x', 8188, '0.36.0', '0.42.4') + run('x') + const local = await load() + + expect(await local.getLocal({ minVersion: '0.37.0' })).toMatchObject({ + state: 'running', + own: true, + version: '0.42.4' + }) + }) +}) + +describe('reusing a ComfyUI old enough to stop every run on interrupt', () => { + it('leaves a ComfyUI older than targeted interrupt alone even when the app allows it', async () => { + addInstall('x', 8188, '0.3.56') + run('x') + const local = await load() + + const state = await local.getLocal({ minVersion: '0.3.31' }) + + expect(state.state).toBe('none') + expect(state.own).toBeUndefined() + }) + + it('reuses a ComfyUI from the first release that interrupts only the named run', async () => { + addInstall('x', 8188, '0.3.57') + run('x') + const local = await load() + + expect(await local.getLocal({ minVersion: '0.3.31' })).toMatchObject({ + state: 'running', + own: true, + version: '0.3.57' + }) + }) +}) + +describe('stopping a ComfyUI that apps started when apps go idle', () => { + async function startedThenIdle(replace: boolean): Promise { + vi.useFakeTimers({ toFake: ['setInterval', 'Date'] }) + addInstall('x', 8188, '0.42.4') + const local = await load() + expect(await local.startLocal({ minVersion: '0.37.0' })).toMatchObject({ state: 'running' }) + if (replace) { + fake.sessions.delete('x') + fake.lifecycle!.emit('changed') + run('x') + fake.lifecycle!.emit('changed') + } + await vi.advanceTimersByTimeAsync(11 * 60_000) + } + + it('stops the session apps launched', async () => { + await startedThenIdle(false) + expect(stopRunning).toHaveBeenCalledWith('x') + }) + + it('leaves alone a session the person started after the apps one ended', async () => { + await startedThenIdle(true) + expect(stopRunning).not.toHaveBeenCalled() + expect(fake.sessions.has('x')).toBe(true) + }) +}) + +describe('what apps can see on a ComfyUI the person already uses', () => { + async function reused(): Promise<{ local: LocalComfy; server: FakeComfy; runId: string }> { + const server = addInstall('x', 8188, '0.42.4') + run('x', 'window') + server.running.push([0, 'mine-1', { secret: {} }, {}, []]) + server.history['mine-0'] = { + prompt: [0, 'mine-0', { secret: {} }], + status: { completed: true }, + outputs: { '9': { images: [{ filename: 'private.png', subfolder: '', type: 'output' }] } } + } + server.files.add('output//private.png') + const local = await load() + expect(await local.getLocal({ minVersion: '0.37.0' })).toMatchObject({ + state: 'running', + own: true + }) + const queued = await local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } }) + const runId = JSON.parse(text(queued.body)).prompt_id as string + server.history[runId] = { + status: { completed: true }, + outputs: { + '9': { images: [{ filename: 'apps_00001_.png', subfolder: 'apps', type: 'output' }] } + } + } + server.files.add('output/apps/apps_00001_.png') + return { local, server, runId } + } + + const view = (filename: string, subfolder: string, type: string) => + `/view?${new URLSearchParams({ filename, subfolder, type })}` + + it('reads the history and output files of the runs apps queued', async () => { + const { local, runId } = await reused() + const history = await local.localFetch({ method: 'GET', path: `/history/${runId}` }) + expect(history.status).toBe(200) + const file = await local.localFetch({ + method: 'GET', + path: view('apps_00001_.png', 'apps', 'output') + }) + expect(file.status).toBe(200) + }) + + it('does not read the history or files of the person own runs', async () => { + const { local, server } = await reused() + const history = await local.localFetch({ method: 'GET', path: '/history/mine-0' }) + expect(history.status).toBe(403) + expect(text(history.body)).not.toContain('secret') + const file = await local.localFetch({ method: 'GET', path: view('private.png', '', 'output') }) + expect(file.status).toBe(403) + expect(server.calls).not.toContain('GET /view') + }) + + it('cannot stop or remove the person own runs', async () => { + const { local, server } = await reused() + const stop = await local.localFetch({ + method: 'POST', + path: '/interrupt', + body: { prompt_id: 'mine-1' } + }) + expect(stop.status).toBe(403) + const remove = await local.localFetch({ + method: 'POST', + path: '/queue', + body: { delete: ['mine-1'] } + }) + expect(remove.status).toBe(403) + expect(server.calls).not.toContain('POST /interrupt') + expect(server.calls).not.toContain('POST /queue') + }) + + it('can stop its own run', async () => { + const { local, server, runId } = await reused() + const stop = await local.localFetch({ + method: 'POST', + path: '/interrupt', + body: { prompt_id: runId } + }) + expect(stop.status).toBe(200) + expect(server.calls).toContain('POST /interrupt') + }) + + it('sees how many runs are ahead in the queue but not the ids of the person own runs', async () => { + const { local, runId } = await reused() + const queue = JSON.parse(text((await local.localFetch({ method: 'GET', path: '/queue' })).body)) + expect(queue.running).toEqual([{ id: '', app: null, seconds: null }]) + expect(queue.pending.map((r: { id: string }) => r.id)).toEqual([runId]) + }) + + it('views an input file apps uploaded', async () => { + const { local } = await reused() + const up = await local.localFetch({ + method: 'POST', + path: '/upload/image', + body: new Uint8Array([1]), + fileName: 'photo.png' + }) + expect(up.status).toBe(200) + const file = await local.localFetch({ method: 'GET', path: view('photo.png', '', 'input') }) + expect(file.status).toBe(200) + }) + + it('keeps reading any run on the Apps build, which only apps use', async () => { + const server = addAppsServer(8300) + fake.apps.inst = { + id: 'apps', + name: 'Apps', + sourceId: 'standalone', + installPath: '/apps', + status: 'installed' + } + fake.apps.id = 'apps' + run('apps') + server.history['other'] = { status: { completed: true }, outputs: {} } + const local = await load() + expect(await local.getLocal()).toMatchObject({ state: 'running', name: 'Apps' }) + const history = await local.localFetch({ method: 'GET', path: '/history/other' }) + expect(history.status).toBe(200) + }) +}) diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index dfd7f2061..59e33a54e 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -31,30 +31,43 @@ import { } from './appsBuild' import { APPS_BUILD_NAME, + APPS_BUILD_VERSION, type ComfyChoice, FREE_IDLE_MS, FREE_JSON, freeWait, isRunEnd, + meetsMinimum, pickComfy, queueEmpty, + reuseMinimum, type SetupEvent, shouldStopIdle, + statsVersion, wantedVersion } from './appsBuildRules' import { type DownloadRequest, downloadRequest, + eventFiles, + historyFiles, type LocalAnswer, localEvent, + type LocalRequest, localRequest, MAX_UPLOAD_BYTES, + noteOwner, noteRun, + promptRunId, queueAnswer, + queueView, readCapped, reconnectDelay, + requestFile, + requestRuns, type RunSeen, textAnswer, + uploadedFile, uploadForm } from './guards' @@ -74,6 +87,10 @@ export const LOCAL_EVENT_CHANNEL = 'comfy-apps:local-event' const CLIENT_ID = randomUUID() const FETCH_TIMEOUT_MS = 60_000 const IDLE_CHECK_MS = 60_000 +const BUSY_ERROR = + 'ComfyUI on this computer is busy with another app. Run this one when it finishes.' +const NOT_APPS_RUN = 'Apps can only see and stop the runs they started.' +const NOT_APPS_FILE = 'Apps can only open files their runs made or they uploaded.' let appsPages: () => WebContents[] = () => [] let starting: Promise | null = null @@ -88,7 +105,11 @@ interface Target { } let target: Target | null = null -const startedHere = new Set() +let selections = 0 +const LAUNCHING = 'launching' +const startedHere = new Map() +const appsRuns = new Map() +const appsFiles = new Map() function touch(): void { lastUse = Date.now() @@ -99,12 +120,25 @@ function localSession(id: string): SessionInfo | null { return s && !s.url && s.port > 0 && (s.sourceInstallationId ?? id) === id ? s : null } -export function appsRunning(): { id: string; name: string; port: number } | null { - const id = target?.id ?? appsBuildId() +interface Serving { + id: string + name: string + port: number +} + +function serving(id: string | null | undefined): Serving | null { const s = id ? localSession(id) : null return id && s ? { id, name: s.installationName, port: s.port } : null } +export function appsRunning(): Serving | null { + return serving(target?.id ?? appsBuildId()) +} + +function targetVersion(): string | null { + return target ? target.version : APPS_BUILD_VERSION +} + export function ownInUse(): string | null { return target?.own ? (appsRunning()?.id ?? null) : null } @@ -127,22 +161,33 @@ interface Candidate extends ComfyChoice { own: boolean } +async function servedVersion(port: number): Promise { + try { + const res = await fetch(`http://127.0.0.1:${port}/system_stats`, { + signal: AbortSignal.timeout(5000) + }) + return res.ok ? statsVersion(await res.json()) : null + } catch { + return null + } +} + async function candidate(inst: InstallationRecord, own: boolean): Promise { - const running = localSession(inst.id) !== null + const session = localSession(inst.id) return { id: inst.id, inst, own, - running, - busy: busy(inst.id, running), - version: await installVersion(inst) + running: session !== null, + busy: busy(inst.id, session !== null), + version: session ? await servedVersion(session.port) : await installVersion(inst) } } async function choose(min: string, apps: InstallationRecord | null): Promise { const own = await Promise.all((await reusableLocal()).map((inst) => candidate(inst, true))) const appsRunningNow = apps && localSession(apps.id) ? [await candidate(apps, false)] : [] - return pickComfy([...own, ...appsRunningNow], min, appsRunning()?.id) + return pickComfy([...own, ...appsRunningNow], reuseMinimum(min), appsRunning()?.id) } function aimAt(pick: Candidate | null): void { @@ -154,52 +199,95 @@ function shown(): Pick { return { name: target.name, own: true, ...(target.version ? { version: target.version } : {}) } } -interface Current { - state: LocalState - pick: Candidate | null +function runningState(run: Serving): LocalState { + return { state: 'running', name: run.name, ...shown(), clientId: CLIENT_ID } } -async function currentState(want: unknown, adopt: boolean): Promise { - const off = await appsLocalOff() - if (off) return { state: { state: 'unsupported', error: off }, pick: null } - const inst = await findApps() - if (adopt) { - const pick = await choose(wantedVersion(want), inst?.status === 'installed' ? inst : null) - aimAt(pick) - if (pick?.own && !pick.running) { - const state = launching(pick.id) ? 'starting' : 'stopped' - return { state: { state, ...shown() }, pick } - } - } - const run = appsRunning() - if (run) { - return { - state: { state: 'running', name: run.name, ...shown(), clientId: CLIENT_ID }, - pick: null - } +function pickState(pick: Candidate): LocalState { + return { + state: launching(pick.id) ? 'starting' : 'stopped', + name: pick.inst.name, + ...(pick.own ? { own: true } : {}), + ...(pick.own && pick.version ? { version: pick.version } : {}) } - if (target?.own) return { state: { state: 'starting', ...shown() }, pick: null } - if (appsSetupRunning()) - return { state: { state: 'starting', name: APPS_BUILD_NAME, setup: true }, pick: null } +} + +async function appsBuildState(inst: InstallationRecord | null): Promise { + const run = target ? null : appsRunning() + if (run) return runningState(run) + if (appsSetupRunning()) return { state: 'starting', name: APPS_BUILD_NAME, setup: true } if (!inst || inst.status !== 'installed') { const download = await planAppsBuild().then( (p) => p.bytes, () => 0 ) - return { - state: { state: 'none', name: APPS_BUILD_NAME, ...(download ? { download } : {}) }, - pick: null - } + return { state: 'none', name: APPS_BUILD_NAME, ...(download ? { download } : {}) } + } + if (launching(inst.id)) return { state: 'starting', name: inst.name } + return { state: 'stopped', name: inst.name } +} + +async function reportCurrent(inst: InstallationRecord | null): Promise { + const run = appsRunning() + if (run) return runningState(run) + if (target?.own) return { state: 'starting', ...shown() } + return appsBuildState(inst) +} + +function busyState(): LocalState { + return { + state: 'stopped', + name: appsRunning()?.name ?? APPS_BUILD_NAME, + ...shown(), + error: BUSY_ERROR + } +} + +function selectionCurrent(gen: number, forStart: boolean): boolean { + return gen === selections && (forStart || !starting) +} + +type Adoption = 'aimed' | 'stale' | 'busy' + +async function adopt(pick: Candidate | null, gen: number, forStart: boolean): Promise { + if (!selectionCurrent(gen, forStart)) return 'stale' + const run = appsRunning() + if (run && (pick?.id ?? appsBuildId()) !== run.id && (await appsWorkOn(run))) return 'busy' + if (!selectionCurrent(gen, forStart)) return 'stale' + aimAt(pick) + return 'aimed' +} + +interface Current { + state: LocalState + pick: Candidate | null +} + +async function currentState(want: unknown, forStart: boolean): Promise { + const off = await appsLocalOff() + if (off) return { state: { state: 'unsupported', error: off }, pick: null } + const inst = await findApps() + if (!forStart && starting) return { state: await reportCurrent(inst), pick: null } + const gen = ++selections + const pick = await choose(wantedVersion(want), inst?.status === 'installed' ? inst : null) + if (forStart || pick?.running) { + const adopted = await adopt(pick, gen, forStart) + if (adopted === 'busy') return { state: busyState(), pick: null } + if (adopted === 'stale') return { state: await reportCurrent(inst), pick: null } } - if (launching(inst.id)) return { state: { state: 'starting', name: inst.name }, pick: null } - return { state: { state: 'stopped', name: inst.name }, pick: null } + const run = pick?.running ? serving(pick.id) : null + if (run) return { state: runningState(run), pick } + if (pick) return { state: pickState(pick), pick } + return { state: await appsBuildState(inst), pick: null } } export async function getLocal(want?: unknown): Promise { syncLocalSocket() - const { state } = await currentState(want, !starting) + const { state } = await currentState(want, false) syncLocalSocket() - return state.state === 'stopped' && starting ? { ...state, state: 'starting' } : state + return state.state === 'stopped' && starting && !state.error + ? { ...state, state: 'starting' } + : state } async function answers(port: number): Promise { @@ -223,7 +311,7 @@ async function untilAnswering(id: string, name: string | undefined): Promise { touch() if (!appsRunning() && !launching(inst.id)) { - startedHere.add(inst.id) + startedHere.set(inst.id, LAUNCHING) const result = await launchConsole(inst) if (!result.ok && !appsRunning()) { - if (!localSession(inst.id) && !launching(inst.id)) startedHere.delete(inst.id) + settleStarted(inst.id) return { state: 'stopped', name: inst.name, ...shown(), error: shortError(result.message) } } } - return untilAnswering(inst.id, inst.name) + const state = await untilAnswering(inst.id, inst.name) + settleStarted(inst.id) + return state } async function start(want: unknown): Promise { const { state, pick } = await currentState(want, true) syncLocalSocket() - if (state.state === 'unsupported' || state.state === 'running') return state + if (state.state === 'unsupported' || state.state === 'running' || state.error) return state if (pick?.own) return startOwn(pick.inst) let inst: InstallationRecord try { @@ -276,20 +384,52 @@ async function start(want: unknown): Promise { return untilAnswering(inst.id, inst.name) } -export function startLocal(want?: unknown): Promise { - starting ??= start(want).finally(() => (starting = null)) - return starting +export async function startLocal(want?: unknown): Promise { + const min = wantedVersion(want) + while (starting) { + const shared = await starting + if (shared.state !== 'running' || meetsMinimum(targetVersion(), min)) return shared + } + const mine: Promise = start(want).finally(() => { + if (starting === mine) starting = null + }) + starting = mine + return mine } export function cancelSetup(): { cancelled: boolean } { return cancelAppsSetup() } +function routeFor(runs: string[], file: string | null): Serving | null { + const owner = runs.length ? appsRuns.get(runs[0]!) : file ? appsFiles.get(file) : undefined + return serving(owner) ?? appsRunning() +} + +function noteOwned(req: LocalRequest, runs: string[], body: Uint8Array, owner: string): void { + if (req.kind === 'prompt') { + const id = promptRunId(body) + if (id) noteOwner(appsRuns, id, owner) + } else if (req.kind === 'upload') { + const file = uploadedFile(body) + if (file) noteOwner(appsFiles, file, owner) + } else if (req.kind === 'get' && runs.length) { + for (const file of historyFiles(body, runs[0]!)) noteOwner(appsFiles, file, owner) + } +} + export async function localFetch(input: unknown): Promise { const req = localRequest(input) if (!('kind' in req)) return textAnswer(req.status, req.error) - const run = appsRunning() + const runs = requestRuns(req) + const file = requestFile(req) + const run = routeFor(runs, file) if (!run) return textAnswer(503, 'ComfyUI for apps is not running on this computer.') + const personal = run.id !== appsBuildId() + if (personal && runs.some((id) => appsRuns.get(id) !== run.id)) { + return textAnswer(403, NOT_APPS_RUN) + } + if (personal && file && appsFiles.get(file) !== run.id) return textAnswer(403, NOT_APPS_FILE) touch() syncLocalSocket() const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS) @@ -308,7 +448,11 @@ export async function localFetch(input: unknown): Promise { const res = await fetch(`http://127.0.0.1:${run.port}${req.path}`, init) const body = await readCapped(res, MAX_UPLOAD_BYTES) if (!body) return textAnswer(502, 'ComfyUI answered more than 50 MB.') - if (req.kind === 'queue') return queueAnswer(res.status, body, runsSeen) + if (req.kind === 'queue') { + const owned = personal ? (id: string) => appsRuns.get(id) === run.id : undefined + return queueAnswer(res.status, body, runsSeen, owned) + } + if (res.ok) noteOwned(req, runs, body, run.id) return { status: res.status, contentType: res.headers.get('content-type') ?? 'application/octet-stream', @@ -325,6 +469,22 @@ export type LocalDownload = { state: 'done' } | { state: 'failed'; error: string const downloads = new Map>() +async function appsWorkOn(run: Serving): Promise { + if (downloads.size > 0) return true + const ids = new Set([...appsRuns].filter(([, owner]) => owner === run.id).map(([id]) => id)) + if (!ids.size) return false + try { + const res = await fetch(`http://127.0.0.1:${run.port}/queue`, { + signal: AbortSignal.timeout(5000) + }) + if (!res.ok) return true + const q = queueView(await res.json()) + return [...q.running, ...q.pending].some((r) => ids.has(r.id)) + } catch { + return localSession(run.id) !== null + } +} + async function runDownload(installationId: string, req: DownloadRequest): Promise { let done = 0 let total = 0 @@ -417,6 +577,7 @@ function connect(s: Socket): void { if (!msg) return touch() noteRun(runsSeen, msg, Date.now()) + noteMade(msg) if (isRunEnd(msg.type)) scheduleFree(s.port) forward(msg) } @@ -428,6 +589,13 @@ function connect(s: Socket): void { } } +function noteMade(msg: { type: string; data: unknown }): void { + const made = eventFiles(msg) + const owner = made ? appsRuns.get(made.runId) : undefined + if (!made || !owner) return + for (const file of made.files) noteOwner(appsFiles, file, owner) +} + function closeSocket(): void { if (!socket) return socket.closed = true @@ -488,18 +656,19 @@ function scheduleFree(port: number, wait = FREE_IDLE_MS): void { } function startedByApps(): string[] { - if (!starting) { - for (const id of startedHere) { - if (!localSession(id) && !launching(id)) startedHere.delete(id) - } - } const apps = appsBuildId() - return [...(apps ? [apps] : []), ...[...startedHere].filter((id) => id !== apps)] + return [...(apps ? [apps] : []), ...[...startedHere.keys()].filter((id) => id !== apps)] +} + +function appsSession(id: string): SessionInfo | null { + const s = localSession(id) + if (!s || id === appsBuildId()) return s + return startedHere.get(id) === s ? s : null } async function stopWhenIdle(): Promise { for (const id of startedByApps()) { - const s = localSession(id) + const s = appsSession(id) if (!s) continue const entry = getEntryByInstallationId(id) const idle = shouldStopIdle({ @@ -511,7 +680,7 @@ async function stopWhenIdle(): Promise { if (!idle) continue const seen = lastUse if (downloads.size > 0 || starting || !(await queueIsEmpty(s.port))) return touch() - if (lastUse !== seen || downloads.size > 0 || starting) return + if (lastUse !== seen || downloads.size > 0 || starting || appsSession(id) !== s) return await stopRunning(id) startedHere.delete(id) } @@ -519,6 +688,9 @@ async function stopWhenIdle(): Promise { export function initLocalComfy(pages: () => WebContents[]): void { appsPages = pages - sessionLifecycleEvents.on('changed', syncLocalSocket) + sessionLifecycleEvents.on('changed', () => { + trackStarted() + syncLocalSocket() + }) setInterval(() => void stopWhenIdle(), IDLE_CHECK_MS).unref?.() } From 52d3945375ed09e8decafac557b44310a4704c13 Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Thu, 12 Nov 2026 17:42:05 -0800 Subject: [PATCH 3/8] fix(apps): open each page's files from the ComfyUI its run used, and keep live runs Two ComfyUI installs can save different pictures under the same name. File ownership was one map keyed by file name, and the latest history answer won. A late history answer from the earlier install sent the current page's file read there, so the page saved the other install's picture. File claims are now kept per app page, and a claim from an older run never replaces one from a newer run. Files a run makes over the socket go to the page that queued it. Run and file records were capped at 2,000 and dropped oldest first, even while a run was still queued or running. Its history and Stop then got 403 and the page kept polling. A history with more than 2,000 files dropped its own first file before the page read it. Runs are now kept until they finish: their history comes back, an end event arrives, the page removes them from the queue, or their ComfyUI stops. Only finished runs are dropped, oldest first, with their files. A new run is refused with 429 while 2,000 runs have not finished. --- src/main/apps/appsView.ts | 12 ++- src/main/apps/guards.test.ts | 100 +++++++++++++++++++++++-- src/main/apps/guards.ts | 118 +++++++++++++++++++++++++++--- src/main/apps/localComfy.test.ts | 121 ++++++++++++++++++++++++++++++- src/main/apps/localComfy.ts | 60 ++++++++++----- src/main/apps/wiring.test.ts | 2 +- 6 files changed, 373 insertions(+), 40 deletions(-) diff --git a/src/main/apps/appsView.ts b/src/main/apps/appsView.ts index 16c0d3138..51529d6c7 100644 --- a/src/main/apps/appsView.ts +++ b/src/main/apps/appsView.ts @@ -564,6 +564,16 @@ function handleFromApps( }) } +function handleFromAppsPage( + channel: string, + fn: (arg: A, page: number) => Promise | R +): void { + ipcMain.handle(channel, async (event, arg) => { + if (!fromAppsPage(event)) throw new Error('Not allowed.') + return fn(arg as A, event.sender.id) + }) +} + function appsPages(): WebContents[] { return [...views.values()] .map((v) => v.webContents) @@ -595,7 +605,7 @@ export function registerAppsIpc(): void { handleFromApps('comfy-apps:start-local', startLocal) handleFromApps('comfy-apps:cancel-setup', cancelSetup) handleFromApps('comfy-apps:local-builds', localBuilds) - handleFromApps('comfy-apps:local-fetch', localFetch) + handleFromAppsPage('comfy-apps:local-fetch', localFetch) handleFromApps('comfy-apps:local-download', localDownload) handleFromApps('comfy-apps:open-in-comfy', openInComfy) } diff --git a/src/main/apps/guards.test.ts b/src/main/apps/guards.test.ts index 02d299b4f..3e340e996 100644 --- a/src/main/apps/guards.test.ts +++ b/src/main/apps/guards.test.ts @@ -4,15 +4,18 @@ import { describe, expect, it, vi } from 'vitest' import { isAllowedAppsPermission, + AppsOwnership, appsOrigin, appsUrl, cleanSaveName, COMFY_READY_SCRIPT, collectOutputs, downloadRequest, + endedRun, eventFiles, fileKey, historyFiles, + historyHas, inJobGrace, interruptJson, JOB_GRACE_MS, @@ -31,7 +34,6 @@ import { localEvent, localInstalls, localRequest, - noteOwner, noteRun, noteSubmitted, openRequest, @@ -1040,12 +1042,100 @@ describe('what ComfyUI says apps made', () => { expect(eventFiles({ type: 'progress', data: { prompt_id: 'r1' } })).toBeNull() }) - it('keeps only the newest owners', () => { - const owners = new Map() - for (let i = 0; i < 5; i++) noteOwner(owners, `r${i}`, 'x', 3) - expect([...owners.keys()]).toEqual(['r2', 'r3', 'r4']) + it('tells when a history answer has the run, finished or not', () => { + expect(historyHas(bytes({ r1: { outputs: {} } }), 'r1')).toBe(true) + expect(historyHas(bytes({}), 'r1')).toBe(false) + expect(historyHas(new TextEncoder().encode('not json'), 'r1')).toBe(false) }) + it('reads which run an end event is about', () => { + expect(endedRun({ type: 'execution_success', data: { prompt_id: 'r1' } })).toBe('r1') + expect(endedRun({ type: 'execution_interrupted', data: { prompt_id: 'r1' } })).toBe('r1') + expect(endedRun({ type: 'executing', data: { prompt_id: 'r1' } })).toBeNull() + }) +}) + +describe('which ComfyUI owns the runs and files apps made', () => { + const file = fileKey({ filename: 'ComfyUI_00001_.png', subfolder: '', type: 'output' }) + + it('keeps every run that has not finished and says when no more fit', () => { + const owned = new AppsOwnership(3) + for (let i = 0; i < 3; i++) owned.addRun(`r${i}`, 'x', 1) + expect(owned.full()).toBe(true) + expect(owned.runOwner('r0')).toBe('x') + owned.finish('r0') + expect(owned.full()).toBe(false) + }) + + it('forgets the oldest finished run first, and its files with it', () => { + const owned = new AppsOwnership(2) + for (let i = 0; i < 3; i++) { + owned.addRun(`r${i}`, 'x', 1) + owned.addRunFiles(`r${i}`, 1, [fileKey({ filename: `${i}.png`, type: 'output' })]) + } + owned.addRun('live', 'x', 1) + for (const id of ['r0', 'r1', 'r2']) owned.finish(id) + expect(owned.runOwner('r0')).toBeUndefined() + expect(owned.fileOwner(1, fileKey({ filename: '0.png', type: 'output' }))).toBeUndefined() + expect(owned.runOwner('r2')).toBe('x') + expect(owned.fileOwner(1, fileKey({ filename: '2.png', type: 'output' }))).toBe('x') + expect(owned.runOwner('live')).toBe('x') + }) + + it('keeps every file one history answer names', () => { + const owned = new AppsOwnership(2) + owned.addRun('r1', 'x', 1) + const files = [0, 1, 2, 3].map((i) => fileKey({ filename: `${i}.png`, type: 'output' })) + owned.addRunFiles('r1', 1, files) + owned.finish('r1') + for (const f of files) expect(owned.fileOwner(1, f)).toBe('x') + }) + + it('keeps each page file on the ComfyUI its run used', () => { + const owned = new AppsOwnership() + owned.addRun('rx', 'x', 1) + owned.addRun('ry', 'y', 2) + owned.addRunFiles('ry', 2, [file]) + owned.addRunFiles('rx', 1, [file]) + expect(owned.fileOwner(2, file)).toBe('y') + expect(owned.fileOwner(1, file)).toBe('x') + expect(owned.fileOwner(3, file)).toBeUndefined() + }) + + it('does not let a late answer about an older run take a file from a newer one', () => { + const owned = new AppsOwnership() + owned.addRun('rx', 'x', 1) + owned.addRun('ry', 'y', 1) + owned.addRunFiles('ry', 1, [file]) + owned.addRunFiles('rx', 1, [file]) + expect(owned.fileOwner(1, file)).toBe('y') + }) + + it('gives files a run made to the page that queued it', () => { + const owned = new AppsOwnership() + owned.addRun('r1', 'x', 4) + owned.addRunFiles('r1', null, [file]) + expect(owned.fileOwner(4, file)).toBe('x') + }) + + it('keeps the newest uploads', () => { + const owned = new AppsOwnership(2) + const ups = [0, 1, 2].map((i) => fileKey({ filename: `${i}.png`, type: 'input' })) + for (const f of ups) owned.addUpload(1, f, 'x') + expect(ups.map((f) => owned.fileOwner(1, f))).toEqual([undefined, 'x', 'x']) + }) + + it('finishes the runs of a ComfyUI that stopped', () => { + const owned = new AppsOwnership(1) + owned.addRun('r1', 'x', 1) + expect(owned.full()).toBe(true) + owned.finishAll((id) => id !== 'x') + expect(owned.full()).toBe(false) + expect(owned.runOwner('r1')).toBe('x') + }) +}) + +describe('the queue apps see', () => { it('hides the queued runs apps do not own but keeps their place', () => { const raw = { queue_running: [[0, 'theirs', {}, { comfy_app: { name: 'Mine' } }, []]], diff --git a/src/main/apps/guards.ts b/src/main/apps/guards.ts index 7eff3827f..d5bcd7e8e 100644 --- a/src/main/apps/guards.ts +++ b/src/main/apps/guards.ts @@ -618,20 +618,116 @@ export function eventFiles(msg: { type: string; data: unknown }): { } } +export function historyHas(body: Uint8Array, runId: string): boolean { + const v = jsonOf(body) + return !!v && typeof v === 'object' && runId in v +} + +export function endedRun(msg: { type: string; data: unknown }): string | null { + if (!RUN_END_TYPES.includes(msg.type)) return null + const id = (msg.data as { prompt_id?: unknown } | null)?.prompt_id + return isRunId(id) ? id : null +} + export const MAX_OWNED = 2000 -export function noteOwner( - owners: Map, - key: string, - owner: string, - max = MAX_OWNED -): void { - owners.delete(key) - owners.set(key, owner) - for (const old of owners.keys()) { - if (owners.size <= max) break - owners.delete(old) +interface OwnedRun { + owner: string + page: number + order: number + claims: Set +} + +interface FileClaim { + owner: string + order: number +} + +export class AppsOwnership { + private readonly runs = new Map() + private readonly finished = new Set() + private readonly files = new Map() + private readonly uploads: Array<{ key: string; claim: FileClaim }> = [] + private order = 0 + + constructor(private readonly max = MAX_OWNED) {} + + full(): boolean { + return this.runs.size - this.finished.size >= this.max + } + + addRun(id: string, owner: string, page: number): void { + this.forget(id) + this.runs.set(id, { owner, page, order: ++this.order, claims: new Set() }) + } + + runOwner(id: string): string | undefined { + return this.runs.get(id)?.owner + } + + runsOn(owner: string): string[] { + return [...this.runs].filter(([, r]) => r.owner === owner).map(([id]) => id) + } + + addRunFiles(runId: string, page: number | null, files: readonly string[]): void { + const run = this.runs.get(runId) + if (!run) return + for (const file of files) { + const key = claimKey(page ?? run.page, file) + const claim = { owner: run.owner, order: run.order } + if (this.claim(key, claim)) run.claims.add(key) + } + } + + addUpload(page: number, file: string, owner: string): void { + const key = claimKey(page, file) + const claim = { owner, order: ++this.order } + if (!this.claim(key, claim)) return + this.uploads.push({ key, claim }) + while (this.uploads.length > this.max) { + const old = this.uploads.shift()! + if (this.files.get(old.key) === old.claim) this.files.delete(old.key) + } + } + + fileOwner(page: number, file: string): string | undefined { + return this.files.get(claimKey(page, file))?.owner + } + + finish(id: string): void { + if (!this.runs.has(id) || this.finished.has(id)) return + this.finished.add(id) + for (const old of this.finished) { + if (this.finished.size <= this.max) break + this.forget(old) + } } + + finishAll(stillRunning: (owner: string) => boolean): void { + for (const [id, run] of this.runs) if (!stillRunning(run.owner)) this.finish(id) + } + + private claim(key: string, claim: FileClaim): boolean { + const held = this.files.get(key) + if (held && held.order > claim.order) return false + this.files.set(key, claim) + return true + } + + private forget(id: string): void { + const run = this.runs.get(id) + if (!run) return + for (const key of run.claims) { + const held = this.files.get(key) + if (held?.owner === run.owner && held.order === run.order) this.files.delete(key) + } + this.runs.delete(id) + this.finished.delete(id) + } +} + +function claimKey(page: number, file: string): string { + return `${page}\n${file}` } export async function readCapped( diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index 20d65ab43..4601b6cc3 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -152,7 +152,7 @@ function fakeFetch(input: string | URL, init?: RequestInit): Promise { ) } if (p === '/prompt') { - const id = `apps-${server.calls.length}` + const id = `apps-${url.port}-${server.calls.length}` server.pending.push([server.pending.length, id, {}, {}, []]) return Promise.resolve(json({ prompt_id: id, number: 1, node_errors: {} })) } @@ -171,7 +171,7 @@ function fakeFetch(input: string | URL, init?: RequestInit): Promise { ].join('/') return Promise.resolve( server.files.has(key) - ? new Response(new Uint8Array([1, 2, 3])) + ? new Response(new TextEncoder().encode(`${url.port}/${key}`)) : new Response('', { status: 404 }) ) } @@ -305,6 +305,77 @@ describe('an app run keeps its ComfyUI while another app asks for a newer one', }) }) +describe('files two ComfyUIs give the same name', () => { + const made = { + status: { completed: true }, + outputs: { + '9': { images: [{ filename: 'ComfyUI_00001_.png', subfolder: '', type: 'output' }] } + } + } + const sameName = '/view?filename=ComfyUI_00001_.png&subfolder=&type=output' + + async function runOnEach( + pageX: number, + pageY: number + ): Promise<{ local: LocalComfy; runX: string; runY: string }> { + const x = addInstall('x', 8188, '0.37.0') + const y = addInstall('y', 8288, '0.42.4') + run('x') + const local = await load() + expect(await local.getLocal({ minVersion: '0.37.0' })).toMatchObject({ name: 'ComfyUI x' }) + const queuedX = await local.localFetch( + { method: 'POST', path: '/prompt', body: { prompt: {} } }, + pageX + ) + const runX = JSON.parse(text(queuedX.body)).prompt_id as string + x.pending.length = 0 + x.history[runX] = made + x.files.add('output//ComfyUI_00001_.png') + + run('y') + expect(await local.getLocal({ minVersion: '0.41.0' })).toMatchObject({ name: 'ComfyUI y' }) + const queuedY = await local.localFetch( + { method: 'POST', path: '/prompt', body: { prompt: {} } }, + pageY + ) + const runY = JSON.parse(text(queuedY.body)).prompt_id as string + y.pending.length = 0 + y.history[runY] = made + y.files.add('output//ComfyUI_00001_.png') + return { local, runX, runY } + } + + it('gives each page the file from the ComfyUI its run used, whichever history came last', async () => { + const { local, runX, runY } = await runOnEach(1, 2) + + expect((await local.localFetch({ method: 'GET', path: `/history/${runY}` }, 2)).status).toBe( + 200 + ) + expect((await local.localFetch({ method: 'GET', path: `/history/${runX}` }, 1)).status).toBe( + 200 + ) + + const forY = await local.localFetch({ method: 'GET', path: sameName }, 2) + expect(text(forY.body), 'the Y page gets the picture Y made').toBe( + '8288/output//ComfyUI_00001_.png' + ) + const forX = await local.localFetch({ method: 'GET', path: sameName }, 1) + expect(text(forX.body), 'the X page gets the picture X made').toBe( + '8188/output//ComfyUI_00001_.png' + ) + }) + + it('keeps the newer run file when a late history of an older run on another ComfyUI arrives', async () => { + const { local, runX, runY } = await runOnEach(1, 1) + + await local.localFetch({ method: 'GET', path: `/history/${runY}` }, 1) + await local.localFetch({ method: 'GET', path: `/history/${runX}` }, 1) + + const file = await local.localFetch({ method: 'GET', path: sameName }, 1) + expect(text(file.body)).toBe('8288/output//ComfyUI_00001_.png') + }) +}) + describe('an app that joins a start already under way', () => { it('does not get a ComfyUI older than its own minimum', async () => { addInstall('x', 8188, '0.36.0') @@ -500,6 +571,52 @@ describe('what apps can see on a ComfyUI the person already uses', () => { expect(file.status).toBe(200) }) + it('keeps a run it can read and stop while 2,000 newer runs wait behind it', async () => { + const { local, server, runId } = await reused() + const statuses: number[] = [] + for (let i = 0; i < 2000; i++) { + const queued = await local.localFetch({ + method: 'POST', + path: '/prompt', + body: { prompt: {} } + }) + statuses.push(queued.status) + } + + expect(statuses.slice(0, 1999).every((s) => s === 200)).toBe(true) + expect(statuses[1999], 'Desktop refuses a run it could not keep track of').toBe(429) + const stop = await local.localFetch({ + method: 'POST', + path: '/interrupt', + body: { prompt_id: runId } + }) + expect(stop.status).toBe(200) + const history = await local.localFetch({ method: 'GET', path: `/history/${runId}` }) + expect(history.status).toBe(200) + expect(server.calls.filter((c) => c === 'POST /prompt')).toHaveLength(2000) + + const after = await local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } }) + expect(after.status, 'a finished run makes room for a new one').toBe(200) + }) + + it('opens every file of a run that made more than 2,000', async () => { + const { local, server, runId } = await reused() + const images = Array.from({ length: 2001 }, (_, i) => { + server.files.add(`output/apps/many_${i}.png`) + return { filename: `many_${i}.png`, subfolder: 'apps', type: 'output' } + }) + server.history[runId] = { status: { completed: true }, outputs: { '9': { images } } } + + expect((await local.localFetch({ method: 'GET', path: `/history/${runId}` })).status).toBe(200) + for (const i of [0, 2000]) { + const file = await local.localFetch({ + method: 'GET', + path: view(`many_${i}.png`, 'apps', 'output') + }) + expect(file.status, `file ${i}`).toBe(200) + } + }) + it('keeps reading any run on the Apps build, which only apps use', async () => { const server = addAppsServer(8300) fake.apps.inst = { diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index 59e33a54e..ef32ad00e 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -47,16 +47,19 @@ import { wantedVersion } from './appsBuildRules' import { + AppsOwnership, type DownloadRequest, downloadRequest, + endedRun, eventFiles, historyFiles, + historyHas, type LocalAnswer, localEvent, type LocalRequest, localRequest, + MAX_OWNED, MAX_UPLOAD_BYTES, - noteOwner, noteRun, promptRunId, queueAnswer, @@ -91,6 +94,7 @@ const BUSY_ERROR = 'ComfyUI on this computer is busy with another app. Run this one when it finishes.' const NOT_APPS_RUN = 'Apps can only see and stop the runs they started.' const NOT_APPS_FILE = 'Apps can only open files their runs made or they uploaded.' +const TOO_MANY_RUNS = `Apps already have ${MAX_OWNED.toLocaleString('en-US')} runs waiting on ComfyUI. Run this one when some finish.` let appsPages: () => WebContents[] = () => [] let starting: Promise | null = null @@ -108,8 +112,7 @@ let target: Target | null = null let selections = 0 const LAUNCHING = 'launching' const startedHere = new Map() -const appsRuns = new Map() -const appsFiles = new Map() +const owned = new AppsOwnership() function touch(): void { lastUse = Date.now() @@ -401,35 +404,51 @@ export function cancelSetup(): { cancelled: boolean } { return cancelAppsSetup() } -function routeFor(runs: string[], file: string | null): Serving | null { - const owner = runs.length ? appsRuns.get(runs[0]!) : file ? appsFiles.get(file) : undefined +function routeFor(runs: string[], file: string | null, page: number): Serving | null { + const owner = runs.length + ? owned.runOwner(runs[0]!) + : file + ? owned.fileOwner(page, file) + : undefined return serving(owner) ?? appsRunning() } -function noteOwned(req: LocalRequest, runs: string[], body: Uint8Array, owner: string): void { +function noteOwned( + req: LocalRequest, + runs: string[], + body: Uint8Array, + owner: string, + page: number +): void { if (req.kind === 'prompt') { const id = promptRunId(body) - if (id) noteOwner(appsRuns, id, owner) + if (id) owned.addRun(id, owner, page) } else if (req.kind === 'upload') { const file = uploadedFile(body) - if (file) noteOwner(appsFiles, file, owner) + if (file) owned.addUpload(page, file, owner) } else if (req.kind === 'get' && runs.length) { - for (const file of historyFiles(body, runs[0]!)) noteOwner(appsFiles, file, owner) + owned.addRunFiles(runs[0]!, page, historyFiles(body, runs[0]!)) + if (historyHas(body, runs[0]!)) owned.finish(runs[0]!) + } else if (req.kind === 'json' && req.path === '/queue') { + for (const id of runs) owned.finish(id) } } -export async function localFetch(input: unknown): Promise { +export async function localFetch(input: unknown, page = 0): Promise { const req = localRequest(input) if (!('kind' in req)) return textAnswer(req.status, req.error) const runs = requestRuns(req) const file = requestFile(req) - const run = routeFor(runs, file) + const run = routeFor(runs, file, page) if (!run) return textAnswer(503, 'ComfyUI for apps is not running on this computer.') const personal = run.id !== appsBuildId() - if (personal && runs.some((id) => appsRuns.get(id) !== run.id)) { + if (personal && runs.some((id) => owned.runOwner(id) !== run.id)) { return textAnswer(403, NOT_APPS_RUN) } - if (personal && file && appsFiles.get(file) !== run.id) return textAnswer(403, NOT_APPS_FILE) + if (personal && file && owned.fileOwner(page, file) !== run.id) { + return textAnswer(403, NOT_APPS_FILE) + } + if (req.kind === 'prompt' && owned.full()) return textAnswer(429, TOO_MANY_RUNS) touch() syncLocalSocket() const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS) @@ -449,10 +468,10 @@ export async function localFetch(input: unknown): Promise { const body = await readCapped(res, MAX_UPLOAD_BYTES) if (!body) return textAnswer(502, 'ComfyUI answered more than 50 MB.') if (req.kind === 'queue') { - const owned = personal ? (id: string) => appsRuns.get(id) === run.id : undefined - return queueAnswer(res.status, body, runsSeen, owned) + const ours = personal ? (id: string) => owned.runOwner(id) === run.id : undefined + return queueAnswer(res.status, body, runsSeen, ours) } - if (res.ok) noteOwned(req, runs, body, run.id) + if (res.ok) noteOwned(req, runs, body, run.id, page) return { status: res.status, contentType: res.headers.get('content-type') ?? 'application/octet-stream', @@ -471,7 +490,7 @@ const downloads = new Map>() async function appsWorkOn(run: Serving): Promise { if (downloads.size > 0) return true - const ids = new Set([...appsRuns].filter(([, owner]) => owner === run.id).map(([id]) => id)) + const ids = new Set(owned.runsOn(run.id)) if (!ids.size) return false try { const res = await fetch(`http://127.0.0.1:${run.port}/queue`, { @@ -591,9 +610,9 @@ function connect(s: Socket): void { function noteMade(msg: { type: string; data: unknown }): void { const made = eventFiles(msg) - const owner = made ? appsRuns.get(made.runId) : undefined - if (!made || !owner) return - for (const file of made.files) noteOwner(appsFiles, file, owner) + if (made) owned.addRunFiles(made.runId, null, made.files) + const ended = endedRun(msg) + if (ended) owned.finish(ended) } function closeSocket(): void { @@ -690,6 +709,7 @@ export function initLocalComfy(pages: () => WebContents[]): void { appsPages = pages sessionLifecycleEvents.on('changed', () => { trackStarted() + owned.finishAll((id) => localSession(id) !== null) syncLocalSocket() }) setInterval(() => void stopWhenIdle(), IDLE_CHECK_MS).unref?.() diff --git a/src/main/apps/wiring.test.ts b/src/main/apps/wiring.test.ts index a81fad95b..8237576e4 100644 --- a/src/main/apps/wiring.test.ts +++ b/src/main/apps/wiring.test.ts @@ -15,7 +15,7 @@ const exposed = all( /^ {2}(\w+):/gm ) const invoked = all(preload, /ipcRenderer\.invoke\('([\w:-]+)'/g) -const handled = all(main, /handleFromApps\('([\w:-]+)'/g) +const handled = all(main, /handleFromApps(?:Page)?\('([\w:-]+)'/g) describe('Apps bridge wiring', () => { it('getInfo names exactly the calls the page gets', () => { From 4f108a080b0ede356569a0a191846edcfe76a4ed Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Thu, 12 Nov 2026 18:06:24 -0800 Subject: [PATCH 4/8] fix(apps): wait for unanswered runs, settle runs cleared from the queue, and keep private inputs private - Count app runs sent to a ComfyUI but not yet answered, and treat that ComfyUI as busy until they are, so Desktop does not switch to another ComfyUI while one is in flight. - Check every running and waiting run when deciding whether a ComfyUI still has app work, not only the first 100 that the page is shown. - When the 2,000-run limit is reached, compare the unfinished runs with each ComfyUI's queue first; a run the queue no longer has (cleared or deleted in ComfyUI) counts as finished. Its record and file claims stay, so its history and files remain readable. - Reuse a personal ComfyUI only when it uses the shared input folder, the one the Apps install uses; one with its own input folder falls back to the Apps install, so apps cannot list or load the files in it. - Uploads to a reused ComfyUI no longer send overwrite, so ComfyUI gives a taken name a new one and the page gets that name. The Apps install and Cloud uploads keep overwrite. --- src/main/apps/appsBuildRules.test.ts | 9 ++ src/main/apps/appsBuildRules.ts | 4 +- src/main/apps/guards.test.ts | 34 ++++ src/main/apps/guards.ts | 28 +++- src/main/apps/localComfy.test.ts | 232 +++++++++++++++++++++++---- src/main/apps/localComfy.ts | 70 ++++++-- 6 files changed, 328 insertions(+), 49 deletions(-) diff --git a/src/main/apps/appsBuildRules.test.ts b/src/main/apps/appsBuildRules.test.ts index 8e689cfb6..5661ed1e6 100644 --- a/src/main/apps/appsBuildRules.test.ts +++ b/src/main/apps/appsBuildRules.test.ts @@ -480,6 +480,15 @@ describe('which of the person own installs an app run may use', () => { ] expect(reusableInstalls(list, category)).toEqual([]) }) + + it('leaves out installs that keep their own input folder instead of the shared one apps use', () => { + const list = [ + { id: 'shared', sourceId: 'standalone', useSharedInput: true, ...base }, + { id: 'default', sourceId: 'standalone', ...base }, + { id: 'private', sourceId: 'standalone', useSharedInput: false, ...base } + ] + expect(reusableInstalls(list, category).map((i) => i.id)).toEqual(['shared', 'default']) + }) }) describe('which ComfyUI an app run uses', () => { diff --git a/src/main/apps/appsBuildRules.ts b/src/main/apps/appsBuildRules.ts index 4bdd02820..d05f91566 100644 --- a/src/main/apps/appsBuildRules.ts +++ b/src/main/apps/appsBuildRules.ts @@ -237,6 +237,7 @@ export interface ReuseInstall { installPath?: string status?: string appsBuild?: unknown + useSharedInput?: boolean } export function reusableInstalls( @@ -250,7 +251,8 @@ export function reusableInstalls( !isAppsBuild(inst) && inst.status === 'installed' && typeof inst.installPath === 'string' && - inst.installPath !== '' + inst.installPath !== '' && + inst.useSharedInput !== false ) } diff --git a/src/main/apps/guards.test.ts b/src/main/apps/guards.test.ts index 3e340e996..19d57732f 100644 --- a/src/main/apps/guards.test.ts +++ b/src/main/apps/guards.test.ts @@ -41,6 +41,7 @@ import { outputKind, promptRunId, queueAnswer, + queueIds, queueJson, queueView, readable, @@ -403,6 +404,12 @@ describe('uploadForm', () => { expect(form.getAll('image')).toHaveLength(1) expect(form.getAll('overwrite')).toEqual(['true']) }) + + it('leaves overwrite off when asked, so ComfyUI gives a taken name a new one', () => { + const form = uploadForm(new Uint8Array([7]), 'photo.png', false) + expect((form.get('image') as File).name).toBe('photo.png') + expect(form.has('overwrite')).toBe(false) + }) }) describe('readCapped', () => { @@ -1133,6 +1140,33 @@ describe('which ComfyUI owns the runs and files apps made', () => { expect(owned.full()).toBe(false) expect(owned.runOwner('r1')).toBe('x') }) + + it('lists the runs that have not finished by the ComfyUI they went to', () => { + const owned = new AppsOwnership() + owned.addRun('r1', 'x', 1) + owned.addRun('r2', 'y', 1) + owned.addRun('r3', 'x', 2) + owned.finish('r3') + expect([...owned.unfinished()]).toEqual([ + ['x', ['r1']], + ['y', ['r2']] + ]) + }) +}) + +describe('the runs a ComfyUI still has queued', () => { + it('names every running and waiting run, past the 100 apps are shown', () => { + const pending = Array.from({ length: 150 }, (_, i) => [i, `p${i}`, {}, {}, []]) + const ids = queueIds({ queue_running: [[0, 'r0', {}, {}, []]], queue_pending: pending }) + expect(ids.size).toBe(151) + expect(ids.has('r0')).toBe(true) + expect(ids.has('p149')).toBe(true) + }) + + it('names nothing for a queue it cannot read', () => { + expect(queueIds(null).size).toBe(0) + expect(queueIds({ queue_pending: 'x', queue_running: [['bad']] }).size).toBe(0) + }) }) describe('the queue apps see', () => { diff --git a/src/main/apps/guards.ts b/src/main/apps/guards.ts index d5bcd7e8e..df3fc0de2 100644 --- a/src/main/apps/guards.ts +++ b/src/main/apps/guards.ts @@ -263,10 +263,10 @@ export function isVersionsIndex(bytes: unknown): bytes is Uint8Array { } } -export function uploadForm(bytes: Uint8Array, name: unknown): FormData { +export function uploadForm(bytes: Uint8Array, name: unknown, overwrite = true): FormData { const form = new FormData() form.append('image', new Blob([new Uint8Array(bytes)]), safeUploadName(name)) - form.append('overwrite', 'true') + if (overwrite) form.append('overwrite', 'true') return form } @@ -458,6 +458,19 @@ export function queueView( } } +export function queueIds(raw: unknown): Set { + const q = (raw && typeof raw === 'object' ? raw : {}) as { + queue_running?: unknown + queue_pending?: unknown + } + const ids = new Set() + for (const list of [q.queue_running, q.queue_pending]) { + if (!Array.isArray(list)) continue + for (const item of list) if (Array.isArray(item) && isRunId(item[1])) ids.add(item[1]) + } + return ids +} + export function queueAnswer( status: number, body: Uint8Array, @@ -669,6 +682,17 @@ export class AppsOwnership { return [...this.runs].filter(([, r]) => r.owner === owner).map(([id]) => id) } + unfinished(): Map { + const byOwner = new Map() + for (const [id, run] of this.runs) { + if (this.finished.has(id)) continue + const ids = byOwner.get(run.owner) + if (ids) ids.push(id) + else byOwner.set(run.owner, [id]) + } + return byOwner + } + addRunFiles(runId: string, page: number | null, files: readonly string[]): void { const run = this.runs.get(runId) if (!run) return diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index 4601b6cc3..e2cabc151 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -18,6 +18,8 @@ interface FakeInstall { sourceId: string installPath: string status: string + useSharedInput?: boolean + inputDir?: string } interface FakeComfy { @@ -27,6 +29,7 @@ interface FakeComfy { history: Record files: Set calls: string[] + replaced: string[] } const fake = vi.hoisted(() => ({ @@ -37,6 +40,7 @@ const fake = vi.hoisted(() => ({ ports: new Map(), apps: { id: null as string | null, inst: null as FakeInstall | null }, versionGate: null as Promise | null, + promptGate: null as Promise | null, servers: new Map(), sockets: [] as Array<{ url: string; closed: boolean }> })) @@ -83,34 +87,37 @@ vi.mock('../lib/ipc/shared', async () => { stopRunning } }) -vi.mock('./appsBuild', () => ({ - appsBuildId: () => fake.apps.id, - appsLocalOff: async () => null, - appsSetupRunning: () => false, - cancelAppsSetup: () => ({ cancelled: false }), - ensureAppsBuild: async () => { - fake.apps.inst = { - id: 'apps', - name: 'Apps', - sourceId: 'standalone', - installPath: '/apps', - status: 'installed' - } - fake.apps.id = 'apps' - return fake.apps.inst - }, - findApps: async () => fake.apps.inst, - installVersion: async (inst: { id: string }) => { - const gate = fake.versionGate - fake.versionGate = null - if (gate) await gate - return fake.diskVersion.get(inst.id) ?? null - }, - launchAppsBuild: launchConsole, - launchConsole, - planAppsBuild: async () => ({ data: {}, bytes: 0 }), - reusableLocal: async () => fake.installs -})) +vi.mock('./appsBuild', async () => { + const { reusableInstalls } = await import('./appsBuildRules') + return { + appsBuildId: () => fake.apps.id, + appsLocalOff: async () => null, + appsSetupRunning: () => false, + cancelAppsSetup: () => ({ cancelled: false }), + ensureAppsBuild: async () => { + fake.apps.inst = { + id: 'apps', + name: 'Apps', + sourceId: 'standalone', + installPath: '/apps', + status: 'installed' + } + fake.apps.id = 'apps' + return fake.apps.inst + }, + findApps: async () => fake.apps.inst, + installVersion: async (inst: { id: string }) => { + const gate = fake.versionGate + fake.versionGate = null + if (gate) await gate + return fake.diskVersion.get(inst.id) ?? null + }, + launchAppsBuild: launchConsole, + launchConsole, + planAppsBuild: async () => ({ data: {}, bytes: 0 }), + reusableLocal: async () => reusableInstalls(fake.installs, () => 'local') + } +}) class FakeSocket { url: string @@ -154,7 +161,8 @@ function fakeFetch(input: string | URL, init?: RequestInit): Promise { if (p === '/prompt') { const id = `apps-${url.port}-${server.calls.length}` server.pending.push([server.pending.length, id, {}, {}, []]) - return Promise.resolve(json({ prompt_id: id, number: 1, node_errors: {} })) + const answer = () => json({ prompt_id: id, number: 1, node_errors: {} }) + return fake.promptGate ? fake.promptGate.then(answer) : Promise.resolve(answer()) } if (p === '/queue' && method === 'GET') { return Promise.resolve(json({ queue_running: server.running, queue_pending: server.pending })) @@ -176,8 +184,17 @@ function fakeFetch(input: string | URL, init?: RequestInit): Promise { ) } if (p === '/upload/image') { - server.files.add('input//photo.png') - return Promise.resolve(json({ name: 'photo.png', subfolder: '', type: 'input' })) + const form = init!.body as FormData + const asked = (form.get('image') as File).name + const overwrite = form.get('overwrite') === 'true' + const dot = asked.lastIndexOf('.') + let name = asked + for (let i = 1; !overwrite && server.files.has(`input//${name}`); i++) { + name = `${asked.slice(0, dot)} (${i})${asked.slice(dot)}` + } + if (server.files.has(`input//${name}`)) server.replaced.push(name) + server.files.add(`input//${name}`) + return Promise.resolve(json({ name, subfolder: '', type: 'input' })) } return Promise.resolve(new Response('', { status: 200 })) } @@ -198,7 +215,8 @@ function addInstall(id: string, port: number, disk: string, served = disk): Fake pending: [], history: {}, files: new Set(), - calls: [] + calls: [], + replaced: [] } fake.servers.set(port, server) return server @@ -212,7 +230,8 @@ function addAppsServer(port: number): FakeComfy { pending: [], history: {}, files: new Set(), - calls: [] + calls: [], + replaced: [] } fake.servers.set(port, server) return server @@ -244,6 +263,7 @@ beforeEach(() => { fake.apps.id = null fake.apps.inst = null fake.versionGate = null + fake.promptGate = null launchConsole.mockClear() stopRunning.mockClear() vi.stubGlobal('fetch', vi.fn(fakeFetch)) @@ -286,6 +306,56 @@ describe('an app run keeps its ComfyUI while another app asks for a newer one', ]) }) + it('keeps the first ComfyUI while an app run sent to it has not been answered yet', async () => { + const x = addInstall('x', 8188, '0.36.0') + addInstall('y', 8288, '0.42.4') + run('x') + const local = await load() + expect(await local.getLocal({ minVersion: '0.36.0' })).toMatchObject({ own: true }) + + let answer!: () => void + fake.promptGate = new Promise((r) => (answer = r)) + const sending = local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } }) + await new Promise((r) => setTimeout(r, 0)) + expect(x.pending, 'ComfyUI x has the run but has not answered').toHaveLength(1) + + await local.getLocal({ minVersion: '0.37.0' }) + const second = await local.startLocal({ minVersion: '0.37.0' }) + + expect(second.error).toMatch(/busy/) + expect(launchConsole).not.toHaveBeenCalled() + answer() + const runId = JSON.parse(text((await sending).body)).prompt_id as string + x.history[runId] = { status: { completed: true }, outputs: {} } + expect((await local.localFetch({ method: 'GET', path: `/history/${runId}` })).status).toBe(200) + expect(fake.sockets.filter((s) => !s.closed).map((s) => s.url)).toEqual([ + expect.stringContaining(':8188/') + ]) + }) + + it('keeps the first ComfyUI while its app run waits behind more than 100 of the person runs', async () => { + const x = addInstall('x', 8188, '0.36.0') + addInstall('y', 8288, '0.42.4') + run('x') + const local = await load() + expect(await local.getLocal({ minVersion: '0.36.0' })).toMatchObject({ own: true }) + const queued = await local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } }) + const runId = JSON.parse(text(queued.body)).prompt_id as string + x.pending = [ + ...Array.from({ length: 150 }, (_, i) => [i, `mine-${i}`, {}, {}, []]), + [150, runId, {}, {}, []] + ] + + await local.getLocal({ minVersion: '0.37.0' }) + const second = await local.startLocal({ minVersion: '0.37.0' }) + + expect(second.error).toMatch(/busy/) + expect(launchConsole).not.toHaveBeenCalled() + expect(fake.sockets.filter((s) => !s.closed).map((s) => s.url)).toEqual([ + expect.stringContaining(':8188/') + ]) + }) + it('drops a page check that finishes after a newer start chose another ComfyUI', async () => { addInstall('z', 8188, '0.36.0') addInstall('y', 8288, '0.42.4') @@ -443,6 +513,46 @@ describe('reusing a ComfyUI old enough to stop every run on interrupt', () => { }) }) +describe('a ComfyUI that keeps its own input folder', () => { + it('is not reused, so apps cannot list or load the files in it', async () => { + addInstall('x', 8188, '0.42.4') + Object.assign(fake.installs[0]!, { useSharedInput: false, inputDir: '/x/private-input' }) + run('x') + const local = await load() + + const state = await local.getLocal({ minVersion: '0.37.0' }) + + expect(state.own).toBeUndefined() + expect(state.name).toBe('Apps') + expect(fake.servers.get(8188)!.calls).toEqual([]) + }) + + it('is not reused even with no folder named, since ComfyUI then reads its own', async () => { + addInstall('x', 8188, '0.42.4') + fake.installs[0]!.useSharedInput = false + run('x') + const local = await load() + + expect((await local.getLocal({ minVersion: '0.37.0' })).own).toBeUndefined() + }) + + it('leaves the next ComfyUI that shares the apps input folder to be reused', async () => { + addInstall('x', 8188, '0.42.4') + fake.installs[0]!.useSharedInput = false + addInstall('y', 8288, '0.42.4') + fake.installs[1]!.useSharedInput = true + run('x') + run('y') + const local = await load() + + expect(await local.getLocal({ minVersion: '0.37.0' })).toMatchObject({ + state: 'running', + own: true, + name: 'ComfyUI y' + }) + }) +}) + describe('stopping a ComfyUI that apps started when apps go idle', () => { async function startedThenIdle(replace: boolean): Promise { vi.useFakeTimers({ toFake: ['setInterval', 'Date'] }) @@ -599,6 +709,62 @@ describe('what apps can see on a ComfyUI the person already uses', () => { expect(after.status, 'a finished run makes room for a new one').toBe(200) }) + it('takes new runs again after the person clears apps runs from the ComfyUI queue', async () => { + const { local, server, runId } = await reused() + for (let i = 0; i < 1999; i++) { + await local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } }) + } + expect( + (await local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } })).status + ).toBe(429) + + server.pending = server.pending.filter((p) => (p as unknown[])[1] === runId) + + const after = await local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } }) + expect(after.status, 'runs ComfyUI dropped no longer hold a place').toBe(200) + const stop = await local.localFetch({ + method: 'POST', + path: '/interrupt', + body: { prompt_id: runId } + }) + expect(stop.status, 'a run still in the queue stays the app run').toBe(200) + expect((await local.localFetch({ method: 'GET', path: `/history/${runId}` })).status).toBe(200) + expect( + ( + await local.localFetch({ + method: 'POST', + path: '/interrupt', + body: { prompt_id: 'mine-1' } + }) + ).status + ).toBe(403) + }) + + it('does not replace an input file of the same name already in the person ComfyUI', async () => { + const { local, server } = await reused() + server.files.add('input//photo.png') + + const up = await local.localFetch({ + method: 'POST', + path: '/upload/image', + body: new Uint8Array([1]), + fileName: 'photo.png' + }) + + expect(up.status).toBe(200) + expect(server.replaced).toEqual([]) + const name = JSON.parse(text(up.body)).name as string + expect(name).toBe('photo (1).png') + expect( + (await local.localFetch({ method: 'GET', path: view(name, '', 'input') })).status, + 'the page opens the file under the name ComfyUI gave it' + ).toBe(200) + expect( + (await local.localFetch({ method: 'GET', path: view('photo.png', '', 'input') })).status, + 'the person file stays closed to apps' + ).toBe(403) + }) + it('opens every file of a run that made more than 2,000', async () => { const { local, server, runId } = await reused() const images = Array.from({ length: 2001 }, (_, i) => { diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index ef32ad00e..0843dae39 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -63,7 +63,7 @@ import { noteRun, promptRunId, queueAnswer, - queueView, + queueIds, readCapped, reconnectDelay, requestFile, @@ -113,6 +113,17 @@ let selections = 0 const LAUNCHING = 'launching' const startedHere = new Map() const owned = new AppsOwnership() +const sending = new Map() + +function submitting(id: string): boolean { + return (sending.get(id) ?? 0) > 0 +} + +function markSending(id: string, step: 1 | -1): void { + const left = (sending.get(id) ?? 0) + step + if (left > 0) sending.set(id, left) + else sending.delete(id) +} function touch(): void { lastUse = Date.now() @@ -255,8 +266,10 @@ type Adoption = 'aimed' | 'stale' | 'busy' async function adopt(pick: Candidate | null, gen: number, forStart: boolean): Promise { if (!selectionCurrent(gen, forStart)) return 'stale' const run = appsRunning() - if (run && (pick?.id ?? appsBuildId()) !== run.id && (await appsWorkOn(run))) return 'busy' + const moving = !!run && (pick?.id ?? appsBuildId()) !== run.id + if (moving && (await appsWorkOn(run))) return 'busy' if (!selectionCurrent(gen, forStart)) return 'stale' + if (moving && submitting(run.id)) return 'busy' aimAt(pick) return 'aimed' } @@ -448,7 +461,24 @@ export async function localFetch(input: unknown, page = 0): Promise if (personal && file && owned.fileOwner(page, file) !== run.id) { return textAnswer(403, NOT_APPS_FILE) } - if (req.kind === 'prompt' && owned.full()) return textAnswer(429, TOO_MANY_RUNS) + if (req.kind !== 'prompt') return send(req, runs, run, personal, page) + markSending(run.id, 1) + try { + if (owned.full()) await settleDropped() + if (owned.full()) return textAnswer(429, TOO_MANY_RUNS) + return await send(req, runs, run, personal, page) + } finally { + markSending(run.id, -1) + } +} + +async function send( + req: LocalRequest, + runs: string[], + run: Serving, + personal: boolean, + page: number +): Promise { touch() syncLocalSocket() const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS) @@ -461,7 +491,7 @@ export async function localFetch(input: unknown, page = 0): Promise signal } : req.kind === 'upload' - ? { method: 'POST', body: uploadForm(req.bytes, req.fileName), signal } + ? { method: 'POST', body: uploadForm(req.bytes, req.fileName, !personal), signal } : { method: 'GET', signal } try { const res = await fetch(`http://127.0.0.1:${run.port}${req.path}`, init) @@ -488,22 +518,36 @@ export type LocalDownload = { state: 'done' } | { state: 'failed'; error: string const downloads = new Map>() -async function appsWorkOn(run: Serving): Promise { - if (downloads.size > 0) return true - const ids = new Set(owned.runsOn(run.id)) - if (!ids.size) return false +async function liveRuns(port: number): Promise | null> { try { - const res = await fetch(`http://127.0.0.1:${run.port}/queue`, { + const res = await fetch(`http://127.0.0.1:${port}/queue`, { signal: AbortSignal.timeout(5000) }) - if (!res.ok) return true - const q = queueView(await res.json()) - return [...q.running, ...q.pending].some((r) => ids.has(r.id)) + return res.ok ? queueIds(await res.json()) : null } catch { - return localSession(run.id) !== null + return null } } +async function appsWorkOn(run: Serving): Promise { + if (downloads.size > 0 || submitting(run.id)) return true + const ids = owned.runsOn(run.id) + if (!ids.length) return false + const live = await liveRuns(run.port) + if (!live) return localSession(run.id) !== null + return ids.some((id) => live.has(id)) +} + +async function settleDropped(): Promise { + await Promise.all( + [...owned.unfinished()].map(async ([owner, ids]) => { + const on = serving(owner) + const live = on ? await liveRuns(on.port) : null + if (live) for (const id of ids) if (!live.has(id)) owned.finish(id) + }) + ) +} + async function runDownload(installationId: string, req: DownloadRequest): Promise { let done = 0 let total = 0 From ca654ccd365f016023b170f241361ce1473c81e5 Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Thu, 12 Nov 2026 18:19:55 -0800 Subject: [PATCH 5/8] fix(apps): keep the first ComfyUI when an app run starts and finishes during the switch check The switch check read the app runs on the current ComfyUI, then waited on its /queue reply. A /prompt sent and accepted during that wait was missing from the list it checked, so Desktop could switch to another ComfyUI while the new run was still queued on the first. Count every app run submission and treat the check as busy when one started while it waited. --- src/main/apps/localComfy.test.ts | 51 +++++++++++++++++++++++++++++++- src/main/apps/localComfy.ts | 5 +++- 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index e2cabc151..ab51ec9aa 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -41,6 +41,7 @@ const fake = vi.hoisted(() => ({ apps: { id: null as string | null, inst: null as FakeInstall | null }, versionGate: null as Promise | null, promptGate: null as Promise | null, + queueGate: null as { open: Promise; answerAsAsked: boolean } | null, servers: new Map(), sockets: [] as Array<{ url: string; closed: boolean }> })) @@ -165,7 +166,13 @@ function fakeFetch(input: string | URL, init?: RequestInit): Promise { return fake.promptGate ? fake.promptGate.then(answer) : Promise.resolve(answer()) } if (p === '/queue' && method === 'GET') { - return Promise.resolve(json({ queue_running: server.running, queue_pending: server.pending })) + const answer = () => json({ queue_running: server.running, queue_pending: server.pending }) + const gate = fake.queueGate + fake.queueGate = null + if (!gate) return Promise.resolve(answer()) + if (!gate.answerAsAsked) return gate.open.then(answer) + const asked = answer() + return gate.open.then(() => asked) } if (p.startsWith('/history/')) { const id = p.slice('/history/'.length) @@ -264,6 +271,7 @@ beforeEach(() => { fake.apps.inst = null fake.versionGate = null fake.promptGate = null + fake.queueGate = null launchConsole.mockClear() stopRunning.mockClear() vi.stubGlobal('fetch', vi.fn(fakeFetch)) @@ -333,6 +341,47 @@ describe('an app run keeps its ComfyUI while another app asks for a newer one', ]) }) + it.each([ + ['answered before the new run reached it', true], + ['answered after the new run reached it', false] + ])( + 'keeps the first ComfyUI when an app run is sent and accepted while its queue is checked, %s', + async (_when, answerAsAsked) => { + const x = addInstall('x', 8188, '0.37.0') + addInstall('y', 8288, '0.42.4') + run('x') + const local = await load() + expect(await local.getLocal({ minVersion: '0.37.0' })).toMatchObject({ own: true }) + const earlier = await local.localFetch({ + method: 'POST', + path: '/prompt', + body: { prompt: {} } + }) + expect(earlier.status).toBe(200) + x.pending.length = 0 + + let release!: () => void + fake.queueGate = { open: new Promise((r) => (release = r)), answerAsAsked } + const second = local.startLocal({ minVersion: '0.41.0' }) + await vi.waitFor(() => expect(x.calls).toContain('GET /queue')) + + const sent = await local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } }) + expect(sent.status, 'ComfyUI x took the new run').toBe(200) + const runId = JSON.parse(text(sent.body)).prompt_id as string + release() + + expect((await second).error).toMatch(/busy/) + expect(launchConsole).not.toHaveBeenCalled() + x.history[runId] = { status: { completed: true }, outputs: {} } + expect((await local.localFetch({ method: 'GET', path: `/history/${runId}` })).status).toBe( + 200 + ) + expect(fake.sockets.filter((s) => !s.closed).map((s) => s.url)).toEqual([ + expect.stringContaining(':8188/') + ]) + } + ) + it('keeps the first ComfyUI while its app run waits behind more than 100 of the person runs', async () => { const x = addInstall('x', 8188, '0.36.0') addInstall('y', 8288, '0.42.4') diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index 0843dae39..015471435 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -114,12 +114,14 @@ const LAUNCHING = 'launching' const startedHere = new Map() const owned = new AppsOwnership() const sending = new Map() +let sendsStarted = 0 function submitting(id: string): boolean { return (sending.get(id) ?? 0) > 0 } function markSending(id: string, step: 1 | -1): void { + if (step > 0) sendsStarted++ const left = (sending.get(id) ?? 0) + step if (left > 0) sending.set(id, left) else sending.delete(id) @@ -267,9 +269,10 @@ async function adopt(pick: Candidate | null, gen: number, forStart: boolean): Pr if (!selectionCurrent(gen, forStart)) return 'stale' const run = appsRunning() const moving = !!run && (pick?.id ?? appsBuildId()) !== run.id + const sendsBefore = sendsStarted if (moving && (await appsWorkOn(run))) return 'busy' if (!selectionCurrent(gen, forStart)) return 'stale' - if (moving && submitting(run.id)) return 'busy' + if (moving && (submitting(run.id) || sendsStarted !== sendsBefore)) return 'busy' aimAt(pick) return 'aimed' } From 7bed8075a718dbc049a90a2a2a51093bddeeadc6 Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Thu, 12 Nov 2026 18:31:46 -0800 Subject: [PATCH 6/8] fix(apps): reuse a running ComfyUI only when it was started with shared input Turning shared input on in storage settings saves at once but needs a restart, so a ComfyUI started with its own input folder kept reading it while apps reuse saw only the saved setting and picked it. The session now records the input folder it was launched with, and a running ComfyUI of yours is reused only when that folder is the current shared input folder. A session with no recorded folder is not reused. A stopped install still launches with the saved settings, so the saved check stays the rule there. --- src/main/apps/appsBuild.ts | 4 ++ src/main/apps/localComfy.test.ts | 46 ++++++++++++++++++- src/main/apps/localComfy.ts | 11 ++++- .../ipc/sessionActions/launch.storage.test.ts | 3 +- src/main/lib/ipc/sessionActions/launch.ts | 20 ++++---- src/main/lib/ipc/shared.ts | 5 +- 6 files changed, 73 insertions(+), 16 deletions(-) diff --git a/src/main/apps/appsBuild.ts b/src/main/apps/appsBuild.ts index b705c4a81..345fe65b9 100644 --- a/src/main/apps/appsBuild.ts +++ b/src/main/apps/appsBuild.ts @@ -101,6 +101,10 @@ export async function reusableLocal(): Promise { return reusableInstalls(await installations.list(), categoryOf) } +export function sharedInputDir(): string { + return settings.get('inputDir') || settings.defaults.inputDir +} + export async function installVersion(inst: InstallationRecord): Promise { const file = path.join(resolveComfyDir(inst.installPath), 'comfyui_version.py') const text = await fsp.readFile(file, 'utf8').catch(() => null) diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index ab51ec9aa..79c310eee 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -10,6 +10,7 @@ interface FakeSession { mode: string installationName: string startedAt: number + inputDir?: string } interface FakeInstall { @@ -33,6 +34,7 @@ interface FakeComfy { } const fake = vi.hoisted(() => ({ + sharedInput: '/shared/input', sessions: new Map(), lifecycle: null as EventEmitter | null, installs: [] as FakeInstall[], @@ -53,7 +55,8 @@ function sessionFor(id: string, mode = 'console'): FakeSession { port: fake.ports.get(id)!, mode, installationName: inst?.name ?? id, - startedAt: Date.now() + startedAt: Date.now(), + inputDir: inst?.useSharedInput === false ? inst.inputDir : fake.sharedInput } } @@ -116,7 +119,8 @@ vi.mock('./appsBuild', async () => { launchAppsBuild: launchConsole, launchConsole, planAppsBuild: async () => ({ data: {}, bytes: 0 }), - reusableLocal: async () => reusableInstalls(fake.installs, () => 'local') + reusableLocal: async () => reusableInstalls(fake.installs, () => 'local'), + sharedInputDir: () => fake.sharedInput } }) @@ -272,6 +276,7 @@ beforeEach(() => { fake.versionGate = null fake.promptGate = null fake.queueGate = null + fake.sharedInput = '/shared/input' launchConsole.mockClear() stopRunning.mockClear() vi.stubGlobal('fetch', vi.fn(fakeFetch)) @@ -585,6 +590,43 @@ describe('a ComfyUI that keeps its own input folder', () => { expect((await local.getLocal({ minVersion: '0.37.0' })).own).toBeUndefined() }) + it.each([ + ['its own folder', '/x/private-input'], + ['no folder named', undefined] + ])( + 'is not reused while it still runs with %s after shared input is turned on', + async (_, inputDir) => { + addInstall('x', 8188, '0.42.4') + Object.assign(fake.installs[0]!, { useSharedInput: false, inputDir }) + run('x') + fake.installs[0]!.useSharedInput = true + const local = await load() + + const state = await local.getLocal({ minVersion: '0.37.0' }) + + expect(state.own, 'the running process still reads its private folder').toBeUndefined() + expect(fake.servers.get(8188)!.calls).toEqual([]) + } + ) + + it('is not reused while it runs with a shared folder that is no longer the shared one', async () => { + addInstall('x', 8188, '0.42.4') + run('x') + fake.sharedInput = '/moved/input' + const local = await load() + + expect((await local.getLocal({ minVersion: '0.37.0' })).own).toBeUndefined() + }) + + it('is not reused when its session does not say which input folder it reads', async () => { + addInstall('x', 8188, '0.42.4') + run('x') + delete fake.sessions.get('x')!.inputDir + const local = await load() + + expect((await local.getLocal({ minVersion: '0.37.0' })).own).toBeUndefined() + }) + it('leaves the next ComfyUI that shares the apps input folder to be reused', async () => { addInstall('x', 8188, '0.42.4') fake.installs[0]!.useSharedInput = false diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index 015471435..ec06bf27f 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -27,7 +27,8 @@ import { launchAppsBuild, launchConsole, planAppsBuild, - reusableLocal + reusableLocal, + sharedInputDir } from './appsBuild' import { APPS_BUILD_NAME, @@ -200,8 +201,14 @@ async function candidate(inst: InstallationRecord, own: boolean): Promise { - const own = await Promise.all((await reusableLocal()).map((inst) => candidate(inst, true))) + const reusable = (await reusableLocal()).filter(readsSharedInput) + const own = await Promise.all(reusable.map((inst) => candidate(inst, true))) const appsRunningNow = apps && localSession(apps.id) ? [await candidate(apps, false)] : [] return pickComfy([...own, ...appsRunningNow], reuseMinimum(min), appsRunning()?.id) } diff --git a/src/main/lib/ipc/sessionActions/launch.storage.test.ts b/src/main/lib/ipc/sessionActions/launch.storage.test.ts index a43eb53fc..55b9ee997 100644 --- a/src/main/lib/ipc/sessionActions/launch.storage.test.ts +++ b/src/main/lib/ipc/sessionActions/launch.storage.test.ts @@ -302,7 +302,8 @@ describe('applyStorageLaunchArgs', () => { preLaunchExtras: [], manageModelFolders: true, modelDirsForLaunch: [path.resolve(shared), path.resolve(owned)], - modelSyncOptions: { yamlPath: target, primaryDir: path.resolve(shared) } + modelSyncOptions: { yamlPath: target, primaryDir: path.resolve(shared) }, + inputDir: globalInput }) }) diff --git a/src/main/lib/ipc/sessionActions/launch.ts b/src/main/lib/ipc/sessionActions/launch.ts index ec4028df4..1dd4b9822 100644 --- a/src/main/lib/ipc/sessionActions/launch.ts +++ b/src/main/lib/ipc/sessionActions/launch.ts @@ -474,6 +474,7 @@ export interface StorageLaunchState { manageModelFolders: boolean modelDirsForLaunch: string[] | undefined modelSyncOptions: ModelPathsOptions + inputDir: string | undefined } export function applyStorageLaunchArgs( @@ -487,6 +488,7 @@ export function applyStorageLaunchArgs( let modelDirsForLaunch: string[] | undefined let modelSyncOptions: ModelPathsOptions = {} let manageModelFolders = false + let inputDir: string | undefined if (argsAvailable) { const sharedDirs = storage.modelsDirs ?? [] const { dirs, primaryDir } = resolveLauncherModelDirs(inst, sharedDirs) @@ -513,16 +515,12 @@ export function applyStorageLaunchArgs( if (argsAvailable) { const useSharedInput = (inst.useSharedInput as boolean | undefined) !== false const useSharedOutput = (inst.useSharedOutput as boolean | undefined) !== false - if (useSharedInput) { - const inputDir = storage.inputDir || settings.defaults.inputDir + inputDir = useSharedInput + ? storage.inputDir || settings.defaults.inputDir + : (inst.inputDir as string | undefined) || undefined + if (inputDir) { fs.mkdirSync(inputDir, { recursive: true }) launchCmd.args!.push('--input-directory', inputDir) - } else { - const perInstallInput = inst.inputDir as string | undefined - if (perInstallInput) { - fs.mkdirSync(perInstallInput, { recursive: true }) - launchCmd.args!.push('--input-directory', perInstallInput) - } } if (useSharedOutput) { const outputDir = storage.outputDir || settings.defaults.outputDir @@ -537,7 +535,7 @@ export function applyStorageLaunchArgs( } } - return { preLaunchExtras, manageModelFolders, modelDirsForLaunch, modelSyncOptions } + return { preLaunchExtras, manageModelFolders, modelDirsForLaunch, modelSyncOptions, inputDir } } export function isCrashedExit(code: number | null, signal: NodeJS.Signals | null): boolean { @@ -1403,7 +1401,7 @@ async function runLaunch( } startHandedBack() - const { preLaunchExtras, manageModelFolders, modelDirsForLaunch, modelSyncOptions } = + const { preLaunchExtras, manageModelFolders, modelDirsForLaunch, modelSyncOptions, inputDir } = applyStorageLaunchArgs(inst, installationId, launchCmd, storageSettings) let serverUp = false @@ -1583,6 +1581,7 @@ async function runLaunch( mode, installationName: inst.name, coreBetaArgs: coreBeta.applied.map(toBetaArgView), + inputDir, getAcceleratorInfo: () => hwTap.getAcceleratorInfo(), flushTelemetry: () => { execTap.flushSummary() @@ -2165,6 +2164,7 @@ async function runLaunch( mode, installationName: inst.name, coreBetaArgs: coreBeta.applied.map(toBetaArgView), + inputDir, getAcceleratorInfo: () => hwTap.getAcceleratorInfo(), flushTelemetry: () => { execTap.flushSummary() diff --git a/src/main/lib/ipc/shared.ts b/src/main/lib/ipc/shared.ts index cbf9f3d9c..7abf1e558 100644 --- a/src/main/lib/ipc/shared.ts +++ b/src/main/lib/ipc/shared.ts @@ -291,6 +291,7 @@ export interface SessionInfo { flushTelemetry?: () => void getAcceleratorInfo?: () => AcceleratorSnapshot | null coreBetaArgs?: readonly BetaArgView[] + inputDir?: string } export interface LaunchCallbackInfo { @@ -917,7 +918,8 @@ export function _addSession( installationName, flushTelemetry, getAcceleratorInfo, - coreBetaArgs + coreBetaArgs, + inputDir }: Omit, bootTimeMs?: number, retries?: { portRetries: number; rebootRetries: number }, @@ -933,6 +935,7 @@ export function _addSession( flushTelemetry, getAcceleratorInfo, coreBetaArgs, + inputDir, startedAt: Date.now() }) _launchingInstances.delete(installationId) From 8a24e380682d049be5ae76a96682c0720c388ea4 Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Thu, 12 Nov 2026 18:47:07 -0800 Subject: [PATCH 7/8] fix(apps): skip a ComfyUI mid-action, keep prereleases and run events apart - A running ComfyUI of yours is not reused while an action such as Git Pull runs on it, since its files are changing. It was skipped only while stopped. - The version a ComfyUI reports, from its process or comfyui_version.py, keeps a prerelease: 0.42.1-rc1 is older than 0.42.1, so an app that needs 0.42.1 no longer picks it. App minimums and release tags such as v0.42.1-env1 read as before. - On a ComfyUI of yours, the app page gets live events only for runs apps queued, plus the queue status. Events ComfyUI sends for a run before it answers the run are held until it does, then passed on if the run is an apps one. The Apps build passes every event as before. - A file's ownership key is the JSON of its type, folder and name, so a name with a line break cannot match a file in another folder. --- src/main/apps/appsBuildRules.test.ts | 10 +++ src/main/apps/appsBuildRules.ts | 8 ++- src/main/apps/guards.test.ts | 10 +++ src/main/apps/guards.ts | 2 +- src/main/apps/localComfy.test.ts | 91 +++++++++++++++++++++++++++- src/main/apps/localComfy.ts | 38 ++++++++++-- 6 files changed, 149 insertions(+), 10 deletions(-) diff --git a/src/main/apps/appsBuildRules.test.ts b/src/main/apps/appsBuildRules.test.ts index 5661ed1e6..ba5e869c7 100644 --- a/src/main/apps/appsBuildRules.test.ts +++ b/src/main/apps/appsBuildRules.test.ts @@ -420,6 +420,12 @@ describe('reading the ComfyUI version a running process reports', () => { expect(statsVersion({ system: { comfyui_version: '0.36.0' } })).toBe('0.36.0') }) + it('keeps a prerelease, which is older than its release', () => { + expect(statsVersion({ system: { comfyui_version: '0.42.1-rc1' } })).toBe('0.42.1-rc1') + const rc = { id: 'rc', version: '0.42.1-rc1', running: true, busy: false } + expect(pickComfy([rc], '0.42.1')).toBeNull() + }) + it('gives no version when system_stats names none', () => { expect(statsVersion({ system: {} })).toBeNull() expect(statsVersion(null)).toBeNull() @@ -433,6 +439,10 @@ describe('reading the ComfyUI version of an install', () => { expect(comfyuiFileVersion("__version__='0.3.40'")).toBe('0.3.40') }) + it('keeps a prerelease in comfyui_version.py', () => { + expect(comfyuiFileVersion('__version__ = "0.42.1-rc1"')).toBe('0.42.1-rc1') + }) + it('gives no version when the file names none', () => { expect(comfyuiFileVersion('')).toBeNull() expect(comfyuiFileVersion('version = "0.44.0"')).toBeNull() diff --git a/src/main/apps/appsBuildRules.ts b/src/main/apps/appsBuildRules.ts index d05f91566..23c516b39 100644 --- a/src/main/apps/appsBuildRules.ts +++ b/src/main/apps/appsBuildRules.ts @@ -221,14 +221,18 @@ export function meetsMinimum(version: string | null, min: string): boolean { return version !== null && semver.gte(version, min) } +function comfyVersion(raw: unknown): string | null { + return typeof raw === 'string' ? semver.valid(raw.trim()) : null +} + export function statsVersion(stats: unknown): string | null { const system = (stats as { system?: { comfyui_version?: unknown } } | null)?.system - return releaseVersion(system?.comfyui_version) + return comfyVersion(system?.comfyui_version) } export function comfyuiFileVersion(text: string): string | null { const m = /^__version__\s*=\s*['"]([^'"]+)['"]/m.exec(text) - return m ? releaseVersion(m[1]) : null + return m ? comfyVersion(m[1]) : null } export interface ReuseInstall { diff --git a/src/main/apps/guards.test.ts b/src/main/apps/guards.test.ts index 19d57732f..f707d99d1 100644 --- a/src/main/apps/guards.test.ts +++ b/src/main/apps/guards.test.ts @@ -1065,6 +1065,16 @@ describe('what ComfyUI says apps made', () => { describe('which ComfyUI owns the runs and files apps made', () => { const file = fileKey({ filename: 'ComfyUI_00001_.png', subfolder: '', type: 'output' }) + it('does not let a file name with a line break claim a file in another folder', () => { + const owned = new AppsOwnership() + owned.addRun('r1', 'x', 1) + owned.addRunFiles('r1', 1, [fileKey({ filename: 'b\nc.png', subfolder: 'a', type: 'output' })]) + + expect( + owned.fileOwner(1, fileKey({ filename: 'c.png', subfolder: 'a\nb', type: 'output' })) + ).toBeUndefined() + }) + it('keeps every run that has not finished and says when no more fit', () => { const owned = new AppsOwnership(3) for (let i = 0; i < 3; i++) owned.addRun(`r${i}`, 'x', 1) diff --git a/src/main/apps/guards.ts b/src/main/apps/guards.ts index df3fc0de2..d3e8e41e2 100644 --- a/src/main/apps/guards.ts +++ b/src/main/apps/guards.ts @@ -564,7 +564,7 @@ export function localRequest(input: unknown): LocalRequest | LocalRefusal { } export function fileKey(file: { filename: string; subfolder?: string; type: string }): string { - return [file.type, file.subfolder ?? '', file.filename].join('\n') + return JSON.stringify([file.type, file.subfolder ?? '', file.filename]) } const HISTORY_PATH = /^\/history\/([A-Za-z0-9-]{1,64})$/ diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index 79c310eee..e0cb0e557 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -45,7 +45,9 @@ const fake = vi.hoisted(() => ({ promptGate: null as Promise | null, queueGate: null as { open: Promise; answerAsAsked: boolean } | null, servers: new Map(), - sockets: [] as Array<{ url: string; closed: boolean }> + sockets: [] as FakeSocket[], + operations: new Map(), + sent: [] as Array<{ type: string; data: unknown }> })) function sessionFor(id: string, mode = 'console'): FakeSession { @@ -85,7 +87,7 @@ vi.mock('../lib/ipc/shared', async () => { _getActiveLaunchIds: () => [], _getLaunchingInstances: () => [], _isStopping: () => false, - _operationAborts: new Map(), + _operationAborts: fake.operations, _runningSessions: fake.sessions, sessionLifecycleEvents: fake.lifecycle, stopRunning @@ -256,7 +258,12 @@ type LocalComfy = typeof LocalComfyModule async function load(): Promise { const mod = await import('./localComfy') - mod.initLocalComfy(() => [{ isDestroyed: () => false, send: () => {} } as never]) + mod.initLocalComfy(() => [ + { + isDestroyed: () => false, + send: (_channel: string, msg: { type: string; data: unknown }) => fake.sent.push(msg) + } as never + ]) return mod } @@ -271,6 +278,8 @@ beforeEach(() => { fake.ports.clear() fake.servers.clear() fake.sockets.length = 0 + fake.operations.clear() + fake.sent.length = 0 fake.apps.id = null fake.apps.inst = null fake.versionGate = null @@ -542,6 +551,20 @@ describe('the version of a ComfyUI that is already running', () => { }) }) +describe('a running ComfyUI the person is changing', () => { + it('is not reused while a Git Pull or other action runs on it', async () => { + addInstall('x', 8188, '0.42.4') + run('x') + fake.operations.set('x', new AbortController()) + const local = await load() + + const state = await local.getLocal({ minVersion: '0.37.0' }) + + expect(state.state).not.toBe('running') + expect(state.own).toBeUndefined() + }) +}) + describe('reusing a ComfyUI old enough to stop every run on interrupt', () => { it('leaves a ComfyUI older than targeted interrupt alone even when the app allows it', async () => { addInstall('x', 8188, '0.3.56') @@ -874,6 +897,48 @@ describe('what apps can see on a ComfyUI the person already uses', () => { } }) + it('passes the page live events of apps runs and the queue status, not of the person own runs', async () => { + const { runId } = await reused() + const ws = fake.sockets.find((s) => !s.closed && s.url.includes(':8188/'))! + const event = (type: string, data: unknown) => + ws.onmessage!({ data: JSON.stringify({ type, data }) }) + + event('executing', { node: '3', prompt_id: 'mine-1' }) + event('progress', { value: 1, max: 4, prompt_id: 'mine-1', node: '3' }) + event('executed', { + node: '9', + prompt_id: 'mine-1', + output: { images: [{ filename: 'private.png', subfolder: '', type: 'output' }] } + }) + event('executing', { node: '3', prompt_id: runId }) + event('status', { status: { exec_info: { queue_remaining: 2 } } }) + + expect(fake.sent).toEqual([ + { type: 'executing', data: { node: '3', prompt_id: runId } }, + { type: 'status', data: { status: { exec_info: { queue_remaining: 2 } } } } + ]) + }) + + it('passes the page events of an apps run that ComfyUI sends before it answers the run', async () => { + const { local, server } = await reused() + server.pending.length = 0 + const ws = fake.sockets.find((s) => !s.closed && s.url.includes(':8188/'))! + const event = (type: string, data: unknown) => + ws.onmessage!({ data: JSON.stringify({ type, data }) }) + let answer!: () => void + fake.promptGate = new Promise((r) => (answer = r)) + const sending = local.localFetch({ method: 'POST', path: '/prompt', body: { prompt: {} } }) + await vi.waitFor(() => expect(server.pending).toHaveLength(1)) + const runId = (server.pending[0] as unknown[])[1] as string + + event('execution_start', { prompt_id: runId }) + event('execution_start', { prompt_id: 'mine-2' }) + answer() + await sending + + expect(fake.sent).toEqual([{ type: 'execution_start', data: { prompt_id: runId } }]) + }) + it('keeps reading any run on the Apps build, which only apps use', async () => { const server = addAppsServer(8300) fake.apps.inst = { @@ -891,4 +956,24 @@ describe('what apps can see on a ComfyUI the person already uses', () => { const history = await local.localFetch({ method: 'GET', path: '/history/other' }) expect(history.status).toBe(200) }) + + it('passes the page live events of any run on the Apps build', async () => { + addAppsServer(8300) + fake.apps.inst = { + id: 'apps', + name: 'Apps', + sourceId: 'standalone', + installPath: '/apps', + status: 'installed' + } + fake.apps.id = 'apps' + run('apps') + const local = await load() + expect(await local.getLocal()).toMatchObject({ state: 'running', name: 'Apps' }) + const ws = fake.sockets.find((s) => !s.closed && s.url.includes(':8300/'))! + + ws.onmessage!({ data: JSON.stringify({ type: 'executing', data: { prompt_id: 'other' } }) }) + + expect(fake.sent).toEqual([{ type: 'executing', data: { prompt_id: 'other' } }]) + }) }) diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index ec06bf27f..beffffbda 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -116,6 +116,8 @@ const startedHere = new Map() const owned = new AppsOwnership() const sending = new Map() let sendsStarted = 0 +const MAX_HELD_EVENTS = 500 +const held: Array<{ id: string; msg: { type: string; data: unknown } }> = [] function submitting(id: string): boolean { return (sending.get(id) ?? 0) > 0 @@ -169,7 +171,8 @@ function launching(id: string): boolean { function busy(id: string, running: boolean): boolean { if (_isStopping(id)) return true - if (running || startedHere.has(id)) return false + if (running) return _operationAborts.has(id) + if (startedHere.has(id)) return false return _operationAborts.has(id) || launching(id) } @@ -446,6 +449,7 @@ function noteOwned( if (req.kind === 'prompt') { const id = promptRunId(body) if (id) owned.addRun(id, owner, page) + releaseHeld(owner) } else if (req.kind === 'upload') { const file = uploadedFile(body) if (file) owned.addUpload(page, file, owner) @@ -479,6 +483,7 @@ export async function localFetch(input: unknown, page = 0): Promise return await send(req, runs, run, personal, page) } finally { markSending(run.id, -1) + releaseHeld(run.id) } } @@ -622,6 +627,7 @@ export async function localDownload(input: unknown): Promise { } interface Socket { + id: string port: number ws: WebSocket | null timer: ReturnType | null @@ -652,7 +658,8 @@ function connect(s: Socket): void { noteRun(runsSeen, msg, Date.now()) noteMade(msg) if (isRunEnd(msg.type)) scheduleFree(s.port) - forward(msg) + if (pageMaySee(s.id, msg)) forward(msg) + else if (submitting(s.id)) hold(s.id, msg) } ws.onerror = () => {} ws.onclose = () => { @@ -662,6 +669,28 @@ function connect(s: Socket): void { } } +function pageMaySee(id: string, msg: { type: string; data: unknown }): boolean { + if (id === appsBuildId() || msg.type === 'status') return true + const runId = (msg.data as { prompt_id?: unknown } | null)?.prompt_id + return typeof runId === 'string' && owned.runOwner(runId) === id +} + +function hold(id: string, msg: { type: string; data: unknown }): void { + held.push({ id, msg }) + if (held.length > MAX_HELD_EVENTS) held.shift() +} + +function releaseHeld(id: string): void { + const waiting = submitting(id) + const kept = held.filter((h) => { + if (h.id !== id) return true + if (pageMaySee(id, h.msg)) forward(h.msg) + else return waiting + return false + }) + held.splice(0, held.length, ...kept) +} + function noteMade(msg: { type: string; data: unknown }): void { const made = eventFiles(msg) if (made) owned.addRunFiles(made.runId, null, made.files) @@ -676,14 +705,15 @@ function closeSocket(): void { socket.ws?.close() socket = null runsSeen.clear() + held.length = 0 } export function syncLocalSocket(): void { const run = appsPages().length ? appsRunning() : null - if (socket && run && socket.port === run.port) return + if (socket && run && socket.port === run.port && socket.id === run.id) return closeSocket() if (!run) return - socket = { port: run.port, ws: null, timer: null, attempt: 0, closed: false } + socket = { id: run.id, port: run.port, ws: null, timer: null, attempt: 0, closed: false } connect(socket) } From 388680e1546b74171f59b79f3e496444735e0f29 Mon Sep 17 00:00:00 2001 From: Vinh Trinh Date: Thu, 12 Nov 2026 18:54:21 -0800 Subject: [PATCH 8/8] fix(apps): recheck a reused ComfyUI's input folder on every request Selection only reuses a person's ComfyUI while its session reads the shared input folder, but the chosen target kept only an installation ID. After a restart with a private input folder, localFetch, owned-run routing and the event socket still went to it. appsRunning and routeFor now repeat the selection check on the current session and drop the target when it fails, falling back to the Apps build as when no reusable ComfyUI exists. --- src/main/apps/localComfy.test.ts | 25 +++++++++++++++++++++++++ src/main/apps/localComfy.ts | 19 ++++++++++++------- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/src/main/apps/localComfy.test.ts b/src/main/apps/localComfy.test.ts index e0cb0e557..aedbbf3b7 100644 --- a/src/main/apps/localComfy.test.ts +++ b/src/main/apps/localComfy.test.ts @@ -650,6 +650,31 @@ describe('a ComfyUI that keeps its own input folder', () => { expect((await local.getLocal({ minVersion: '0.37.0' })).own).toBeUndefined() }) + it('stops getting app requests once the person restarts it with its own folder', async () => { + const server = addInstall('x', 8188, '0.42.4') + run('x') + const local = await load() + expect(await local.getLocal({ minVersion: '0.37.0' })).toMatchObject({ own: true }) + Object.assign(fake.installs[0]!, { useSharedInput: false, inputDir: '/x/private-input' }) + fake.sessions.delete('x') + fake.lifecycle!.emit('changed') + run('x') + fake.lifecycle!.emit('changed') + server.calls.length = 0 + + const nodes = await local.localFetch({ method: 'GET', path: '/object_info/LoadImage' }) + const queued = await local.localFetch({ + method: 'POST', + path: '/prompt', + body: { prompt: {} } + }) + + expect(nodes.status).toBe(503) + expect(queued.status).toBe(503) + expect(server.calls, 'the private input folder is never read').toEqual([]) + expect(local.ownInUse()).toBeNull() + }) + it('leaves the next ComfyUI that shares the apps input folder to be reused', async () => { addInstall('x', 8188, '0.42.4') fake.installs[0]!.useSharedInput = false diff --git a/src/main/apps/localComfy.ts b/src/main/apps/localComfy.ts index beffffbda..9907d3013 100644 --- a/src/main/apps/localComfy.ts +++ b/src/main/apps/localComfy.ts @@ -150,7 +150,17 @@ function serving(id: string | null | undefined): Serving | null { return id && s ? { id, name: s.installationName, port: s.port } : null } +function readsSharedInput(id: string): boolean { + const session = localSession(id) + return !session || session.inputDir === sharedInputDir() +} + +function reusable(id: string): boolean { + return id === appsBuildId() || readsSharedInput(id) +} + export function appsRunning(): Serving | null { + if (target && !reusable(target.id)) target = null return serving(target?.id ?? appsBuildId()) } @@ -204,13 +214,8 @@ async function candidate(inst: InstallationRecord, own: boolean): Promise { - const reusable = (await reusableLocal()).filter(readsSharedInput) + const reusable = (await reusableLocal()).filter((inst) => readsSharedInput(inst.id)) const own = await Promise.all(reusable.map((inst) => candidate(inst, true))) const appsRunningNow = apps && localSession(apps.id) ? [await candidate(apps, false)] : [] return pickComfy([...own, ...appsRunningNow], reuseMinimum(min), appsRunning()?.id) @@ -436,7 +441,7 @@ function routeFor(runs: string[], file: string | null, page: number): Serving | : file ? owned.fileOwner(page, file) : undefined - return serving(owner) ?? appsRunning() + return (owner && reusable(owner) ? serving(owner) : null) ?? appsRunning() } function noteOwned(