diff --git a/src/main/apps/appsBuild.ts b/src/main/apps/appsBuild.ts index 30cfc5f23..345fe65b9 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,21 @@ export async function findApps(): Promise { return inst } +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) + const onDisk = text === null ? null : comfyuiFileVersion(text) + return onDisk ?? coreVerifiedSemver(inst) ?? coreSemver(inst) +} + interface Plan { data: Record bytes: number @@ -275,11 +293,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) @@ -291,12 +308,20 @@ 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 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 diff --git a/src/main/apps/appsBuildRules.test.ts b/src/main/apps/appsBuildRules.test.ts index 3487d2b0d..ba5e869c7 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,19 @@ import { MAC_GPU_ONLY_ARG, MAC_GPU_ONLY_MIN_BYTES, MAC_NO_GPU, + pickComfy, pickOpenTarget, pickVariant, queueEmpty, + releaseVersion, + reusableInstalls, + reuseMinimum, setupEnd, setupEvent, - shouldStopIdle + shouldStopIdle, + statsVersion, + TARGETED_INTERRUPT_VERSION, + wantedVersion } from './appsBuildRules' import { localInstalls } from './guards' @@ -366,3 +375,195 @@ 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('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('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() + 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') + 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() + 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([]) + }) + + 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', () => { + 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..23c516b39 100644 --- a/src/main/apps/appsBuildRules.ts +++ b/src/main/apps/appsBuildRules.ts @@ -1,8 +1,11 @@ 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 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 @@ -197,3 +200,88 @@ 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 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) +} + +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 comfyVersion(system?.comfyui_version) +} + +export function comfyuiFileVersion(text: string): string | null { + const m = /^__version__\s*=\s*['"]([^'"]+)['"]/m.exec(text) + return m ? comfyVersion(m[1]) : null +} + +export interface ReuseInstall { + id: string + sourceId: string + installPath?: string + status?: string + appsBuild?: unknown + useSharedInput?: boolean +} + +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 !== '' && + inst.useSharedInput !== false + ) +} + +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 && meetsMinimum(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/appsView.ts b/src/main/apps/appsView.ts index de86e90c4..b06e9334a 100644 --- a/src/main/apps/appsView.ts +++ b/src/main/apps/appsView.ts @@ -563,6 +563,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) @@ -594,7 +604,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 25f7db1ce..354e2bfaf 100644 --- a/src/main/apps/guards.test.ts +++ b/src/main/apps/guards.test.ts @@ -4,12 +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, @@ -33,18 +39,23 @@ import { openRequest, openWorkflowScript, outputKind, + promptRunId, queueAnswer, + queueIds, queueJson, queueView, readable, readCapped, reconnectDelay, + requestFile, + requestRuns, type RunSeen, safeUploadName, saveExt, savedFileName, textAnswer, toOutputFile, + uploadedFile, uploadForm, viewQuery, workflowName @@ -404,6 +415,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', () => { @@ -972,3 +989,216 @@ 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('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('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) + 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') + }) + + 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', () => { + 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 4ce59c0fd..a26ba5427 100644 --- a/src/main/apps/guards.ts +++ b/src/main/apps/guards.ts @@ -267,10 +267,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 } @@ -411,13 +411,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, @@ -435,18 +447,39 @@ 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, owned), + pending: queueRuns(q.queue_pending, seen, owned) + } +} + +export function queueIds(raw: unknown): Set { 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) } + 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, - seen: ReadonlyMap + seen: ReadonlyMap, + owned?: RunOwned ): LocalAnswer { if (status < 200 || status >= 300) return textAnswer(status, 'ComfyUI did not show its queue.') let raw: unknown @@ -458,7 +491,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))) } } @@ -534,6 +567,197 @@ 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 JSON.stringify([file.type, file.subfolder ?? '', file.filename]) +} + +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 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 + +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) + } + + 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 + 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( 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..aedbbf3b7 --- /dev/null +++ b/src/main/apps/localComfy.test.ts @@ -0,0 +1,1004 @@ +// @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 + inputDir?: string +} + +interface FakeInstall { + id: string + name: string + sourceId: string + installPath: string + status: string + useSharedInput?: boolean + inputDir?: string +} + +interface FakeComfy { + version: string + running: unknown[] + pending: unknown[] + history: Record + files: Set + calls: string[] + replaced: string[] +} + +const fake = vi.hoisted(() => ({ + sharedInput: '/shared/input', + 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, + promptGate: null as Promise | null, + queueGate: null as { open: Promise; answerAsAsked: boolean } | null, + servers: new Map(), + sockets: [] as FakeSocket[], + operations: new Map(), + sent: [] as Array<{ type: string; data: unknown }> +})) + +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(), + inputDir: inst?.useSharedInput === false ? inst.inputDir : fake.sharedInput + } +} + +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: fake.operations, + _runningSessions: fake.sessions, + sessionLifecycleEvents: fake.lifecycle, + stopRunning + } +}) +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'), + sharedInputDir: () => fake.sharedInput + } +}) + +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-${url.port}-${server.calls.length}` + server.pending.push([server.pending.length, id, {}, {}, []]) + 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') { + 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) + 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 TextEncoder().encode(`${url.port}/${key}`)) + : new Response('', { status: 404 }) + ) + } + if (p === '/upload/image') { + 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 })) +} + +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: [], + replaced: [] + } + 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: [], + replaced: [] + } + 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: (_channel: string, msg: { type: string; data: unknown }) => fake.sent.push(msg) + } 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.operations.clear() + fake.sent.length = 0 + fake.apps.id = null + fake.apps.inst = null + fake.versionGate = null + fake.promptGate = null + fake.queueGate = null + fake.sharedInput = '/shared/input' + 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('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.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') + 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') + 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('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') + 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('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') + 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('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.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('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 + 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'] }) + 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 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('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) => { + 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('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 = { + 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) + }) + + 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 d8dac5c05..9907d3013 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,38 +23,63 @@ import { cancelAppsSetup, ensureAppsBuild, findApps, + installVersion, launchAppsBuild, - planAppsBuild + launchConsole, + planAppsBuild, + reusableLocal, + sharedInputDir } 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 + shouldStopIdle, + statsVersion, + wantedVersion } from './appsBuildRules' import { + AppsOwnership, type DownloadRequest, downloadRequest, + endedRun, + eventFiles, + historyFiles, + historyHas, type LocalAnswer, localEvent, + type LocalRequest, localRequest, + MAX_OWNED, MAX_UPLOAD_BYTES, noteRun, + promptRunId, queueAnswer, + queueIds, readCapped, reconnectDelay, + requestFile, + requestRuns, type RunSeen, textAnswer, + uploadedFile, uploadForm } from './guards' export interface LocalState { state: 'running' | 'starting' | 'stopped' | 'none' | 'unsupported' name?: string + version?: string + own?: boolean clientId?: string error?: string setup?: boolean @@ -63,20 +91,85 @@ 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.' +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 let lastUse = Date.now() const runsSeen = new Map() +interface Target { + id: string + name: string + version: string | null + own: boolean +} + +let target: Target | null = null +let selections = 0 +const LAUNCHING = 'launching' +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 +} + +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) +} + function touch(): void { lastUse = Date.now() } -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 +function localSession(id: string): SessionInfo | null { + const s = _runningSessions.get(id) + return s && !s.url && s.port > 0 && (s.sourceInstallationId ?? id) === id ? s : null +} + +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 +} + +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()) +} + +function targetVersion(): string | null { + return target ? target.version : APPS_BUILD_VERSION +} + +export function ownInUse(): string | null { + return target?.own ? (appsRunning()?.id ?? null) : null } function launching(id: string): boolean { @@ -86,34 +179,149 @@ function launching(id: string): boolean { ) } -async function currentState(): Promise<{ state: LocalState; install?: InstallationRecord }> { - const off = await appsLocalOff() - if (off) return { state: { state: 'unsupported', error: off } } - const inst = await findApps() - const run = appsRunning() - if (run) { - return { - state: { state: 'running', name: run.name, clientId: CLIENT_ID }, - ...(inst ? { install: inst } : {}) - } +function busy(id: string, running: boolean): boolean { + if (_isStopping(id)) return true + if (running) return _operationAborts.has(id) + if (startedHere.has(id)) return false + return _operationAborts.has(id) || launching(id) +} + +interface Candidate extends ComfyChoice { + inst: InstallationRecord + 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 } - if (appsSetupRunning()) - return { state: { state: 'starting', name: APPS_BUILD_NAME, setup: true } } +} + +async function candidate(inst: InstallationRecord, own: boolean): Promise { + const session = localSession(inst.id) + return { + id: inst.id, + inst, + own, + 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 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) +} + +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 } : {}) } +} + +function runningState(run: Serving): LocalState { + return { state: 'running', name: run.name, ...shown(), clientId: CLIENT_ID } +} + +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 } : {}) + } +} + +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 } : {}) } } + return { state: 'none', name: APPS_BUILD_NAME, ...(download ? { download } : {}) } } - 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: 'starting', name: inst.name } + return { state: 'stopped', name: inst.name } } -export async function getLocal(): Promise { +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() + 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) || sendsStarted !== sendsBefore)) return 'busy' + 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 } + } + 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, false) syncLocalSocket() - const { state } = await currentState() - 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 { @@ -130,24 +338,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 runningState(run) } - 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 +364,44 @@ function sendSetup(event: SetupEvent): void { forward({ type: 'setup', data: event }) } -async function start(): Promise { - const { state } = await currentState() - if (state.state === 'unsupported' || state.state === 'running') return state +function settleStarted(id: string): void { + if (startedHere.get(id) !== LAUNCHING) return + const s = localSession(id) + if (s) startedHere.set(id, s) + else if (!launching(id)) startedHere.delete(id) +} + +function trackStarted(): void { + for (const [id, owned] of startedHere) { + const s = localSession(id) + if (owned === LAUNCHING) { + if (s) startedHere.set(id, s) + } else if (s !== owned) { + startedHere.delete(id) + } + } +} + +async function startOwn(inst: InstallationRecord): Promise { + touch() + if (!appsRunning() && !launching(inst.id)) { + startedHere.set(inst.id, LAUNCHING) + const result = await launchConsole(inst) + if (!result.ok && !appsRunning()) { + settleStarted(inst.id) + return { state: 'stopped', name: inst.name, ...shown(), error: shortError(result.message) } + } + } + 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' || state.error) return state + if (pick?.own) return startOwn(pick.inst) let inst: InstallationRecord try { inst = await ensureAppsBuild(sendSetup) @@ -175,23 +415,90 @@ 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)) - 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() } -export async function localFetch(input: unknown): Promise { +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 (owner && reusable(owner) ? serving(owner) : null) ?? appsRunning() +} + +function noteOwned( + req: LocalRequest, + runs: string[], + body: Uint8Array, + owner: string, + page: number +): void { + 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) + } else if (req.kind === 'get' && runs.length) { + 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, page = 0): 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, 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) => owned.runOwner(id) !== run.id)) { + return textAnswer(403, NOT_APPS_RUN) + } + if (personal && file && owned.fileOwner(page, file) !== run.id) { + return textAnswer(403, NOT_APPS_FILE) + } + 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) + releaseHeld(run.id) + } +} + +async function send( + req: LocalRequest, + runs: string[], + run: Serving, + personal: boolean, + page: number +): Promise { touch() syncLocalSocket() const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS) @@ -204,13 +511,17 @@ export async function localFetch(input: unknown): 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) 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 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, page) return { status: res.status, contentType: res.headers.get('content-type') ?? 'application/octet-stream', @@ -227,6 +538,36 @@ export type LocalDownload = { state: 'done' } | { state: 'failed'; error: string const downloads = new Map>() +async function liveRuns(port: number): Promise | null> { + try { + const res = await fetch(`http://127.0.0.1:${port}/queue`, { + signal: AbortSignal.timeout(5000) + }) + return res.ok ? queueIds(await res.json()) : null + } catch { + 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 @@ -278,7 +619,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') @@ -291,6 +632,7 @@ export async function localDownload(input: unknown): Promise { } interface Socket { + id: string port: number ws: WebSocket | null timer: ReturnType | null @@ -319,8 +661,10 @@ 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) + if (pageMaySee(s.id, msg)) forward(msg) + else if (submitting(s.id)) hold(s.id, msg) } ws.onerror = () => {} ws.onclose = () => { @@ -330,6 +674,35 @@ 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) + const ended = endedRun(msg) + if (ended) owned.finish(ended) +} + function closeSocket(): void { if (!socket) return socket.closed = true @@ -337,14 +710,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) } @@ -389,25 +763,43 @@ function scheduleFree(port: number, wait = FREE_IDLE_MS): void { }, wait) } +function startedByApps(): string[] { + const apps = appsBuildId() + 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 { - 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 - const seen = lastUse - if (downloads.size > 0 || starting || !(await queueIsEmpty(run.port))) return touch() - if (lastUse !== seen || downloads.size > 0 || starting) return - await stopRunning(run.id) + for (const id of startedByApps()) { + const s = appsSession(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 + const seen = lastUse + if (downloads.size > 0 || starting || !(await queueIsEmpty(s.port))) return touch() + if (lastUse !== seen || downloads.size > 0 || starting || appsSession(id) !== s) return + await stopRunning(id) + startedHere.delete(id) + } } export function initLocalComfy(pages: () => WebContents[]): void { appsPages = pages - sessionLifecycleEvents.on('changed', syncLocalSocket) + sessionLifecycleEvents.on('changed', () => { + trackStarted() + owned.finishAll((id) => localSession(id) !== null) + syncLocalSocket() + }) setInterval(() => void stopWhenIdle(), IDLE_CHECK_MS).unref?.() } diff --git a/src/main/apps/openInComfy.test.ts b/src/main/apps/openInComfy.test.ts index 1ee4d4888..1571d19c7 100644 --- a/src/main/apps/openInComfy.test.ts +++ b/src/main/apps/openInComfy.test.ts @@ -16,6 +16,7 @@ vi.mock('./appsBuild', () => ({ launchInstall: (...args: unknown[]) => launchInstall(...args), showComfyWindow: vi.fn() })) +vi.mock('./localComfy', () => ({ ownInUse: () => null })) const { openInComfy } = await import('./openInComfy') diff --git a/src/main/apps/openInComfy.ts b/src/main/apps/openInComfy.ts index 76a5a9a5f..fac5233e6 100644 --- a/src/main/apps/openInComfy.ts +++ b/src/main/apps/openInComfy.ts @@ -13,6 +13,7 @@ import { openRequest, openWorkflowScript } from './guards' +import { ownInUse } from './localComfy' export type OpenResult = { opened: true } | { opened: false; error: string } @@ -57,7 +58,11 @@ async function appsBuildWindow(): Promise { } 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/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', () => { 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 f400ad996..cd4a47732 100644 --- a/src/main/lib/ipc/sessionActions/launch.ts +++ b/src/main/lib/ipc/sessionActions/launch.ts @@ -475,6 +475,7 @@ export interface StorageLaunchState { manageModelFolders: boolean modelDirsForLaunch: string[] | undefined modelSyncOptions: ModelPathsOptions + inputDir: string | undefined } export function applyStorageLaunchArgs( @@ -488,6 +489,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 - 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) - } } const outputDir = outputDirOverride(inst, storage.outputDir || settings.defaults.outputDir) if (outputDir) { @@ -531,7 +529,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 { @@ -1397,7 +1395,7 @@ async function runLaunch( } startHandedBack() - const { preLaunchExtras, manageModelFolders, modelDirsForLaunch, modelSyncOptions } = + const { preLaunchExtras, manageModelFolders, modelDirsForLaunch, modelSyncOptions, inputDir } = applyStorageLaunchArgs(inst, installationId, launchCmd, storageSettings) let serverUp = false @@ -1577,6 +1575,7 @@ async function runLaunch( mode, installationName: inst.name, coreBetaArgs: coreBeta.applied.map(toBetaArgView), + inputDir, getAcceleratorInfo: () => hwTap.getAcceleratorInfo(), flushTelemetry: () => { execTap.flushSummary() @@ -2159,6 +2158,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) 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 }) =>