From dd3c618438a30b98c8fc7382ef6b5b8220a9d8dd Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Sun, 15 Nov 2026 20:01:51 -0800 Subject: [PATCH] refactor(install): remove the starter-template install pipeline No install path selects a starter workflow any more: first-run onboarding dropped the step, Install on Set up skipped it since #2072, and the New Build modal never asked. The main process still carried the whole per-install pipeline behind the standalone `bundledTemplate` field, so this removes it end to end: - standalone source: no `bundledTemplate` field, options or record fields - installation records: drop `bundledTemplateId`, `bundledTemplateSizeBytes`, `pendingTemplateOpen`, `downloadTemplateModels` and `clearPendingTemplateOpen`; attach no longer deep-links a template - install handler no longer starts or aborts a starter-model download; first open no longer auto-opens the Downloads tray for it - templateDownloadTask keeps only the task the performance test page runs, and now requires the workflow JSON it is given - drop the remote starter-templates reader, the built-in curated list, the starter catalog loader with its live-index substitution, and the install-based model and input-asset resolvers - retire the `skipTemplatePickerStep` setting through the removed-keys list - renderer setup plan and install wizard stop special-casing the field The performance test page keeps TemplatePickerStep, useTemplateTabs, hydrateTemplates and its example downloads. installations.json records that still carry the old template fields load, list and update as before. --- locales/en.json | 3 - locales/zh.json | 3 - src/main/host/attach.ts | 21 +- src/main/index.ts | 24 +- src/main/installations.test.ts | 53 +- src/main/installations.ts | 17 - .../lib/ipc/registerInstallationHandlers.ts | 10 - .../launchStarterModels.integration.test.ts | 423 -------------- src/main/popups/titlePopup.ts | 17 - src/main/settings.test.ts | 13 + src/main/settings.ts | 8 +- .../standalone/curatedTemplates.test.ts | 91 +-- .../sources/standalone/curatedTemplates.ts | 206 ------- src/main/sources/standalone/index.test.ts | 177 +----- src/main/sources/standalone/index.ts | 56 +- .../standalone/remoteStarterTemplates.test.ts | 531 ------------------ .../standalone/remoteStarterTemplates.ts | 167 ------ .../standalone/templateCatalog.test.ts | 299 +++------- .../sources/standalone/templateCatalog.ts | 126 +---- .../standalone/templateDownloadTask.test.ts | 202 +++---- .../standalone/templateDownloadTask.ts | 40 +- .../templateInputAssets.integration.test.ts | 18 +- .../standalone/templateInputAssets.test.ts | 44 +- .../sources/standalone/templateInputAssets.ts | 17 +- .../sources/standalone/templateModels.test.ts | 58 +- src/main/sources/standalone/templateModels.ts | 8 - src/renderer/src/lib/setupPlan.ts | 8 +- .../src/panel/BuildProgressDialog.test.ts | 5 +- .../src/views/FirstUseTakeover.test.ts | 13 +- .../src/views/InstallWizardModal.test.ts | 65 +-- src/renderer/src/views/InstallWizardModal.vue | 8 +- .../views/releaseChannelSwitchLayout.test.ts | 11 +- 32 files changed, 325 insertions(+), 2417 deletions(-) delete mode 100644 src/main/lib/ipc/sessionActions/launchStarterModels.integration.test.ts delete mode 100644 src/main/sources/standalone/remoteStarterTemplates.test.ts delete mode 100644 src/main/sources/standalone/remoteStarterTemplates.ts diff --git a/locales/en.json b/locales/en.json index 255bc4431..171e7fd15 100644 --- a/locales/en.json +++ b/locales/en.json @@ -1141,9 +1141,6 @@ "currentVersion": "Current Version", "variant": "Hardware", "comfyVersion": "Version", - "starterTemplate": "Starter template", - "starterTemplateNone": "None", - "starterTemplateNoneDesc": "Start with a blank canvas", "templatePickerTitle": "Choose a starter workflow", "templateModelsDownloaded": "Downloaded", "templateTabsAria": "Filter starter workflows by type", diff --git a/locales/zh.json b/locales/zh.json index 908c5b9fd..dae5dbdc0 100644 --- a/locales/zh.json +++ b/locales/zh.json @@ -1141,9 +1141,6 @@ "currentVersion": "当前版本", "variant": "硬件", "comfyVersion": "ComfyUI 版本", - "starterTemplate": "入门模板", - "starterTemplateNone": "无", - "starterTemplateNoneDesc": "从空白画布开始", "templatePickerTitle": "选择入门工作流", "templateModelsDownloaded": "已下载", "templateTabsAria": "按类型筛选入门工作流", diff --git a/src/main/host/attach.ts b/src/main/host/attach.ts index a740e8283..168520b71 100644 --- a/src/main/host/attach.ts +++ b/src/main/host/attach.ts @@ -18,13 +18,7 @@ import { deactivateFirebaseAuthReporter } from '../lib/firebaseAuthIdentity' import { convertLevelToZoomPercent } from '../lib/zoom' -import { - clearPendingTemplateOpen, - installationEvents, - type InstallationRecord -} from '../installations' -import { buildTemplateDeeplink } from '../sources/standalone/curatedTemplates' -import { abortTemplateDownload } from '../sources/standalone/templateDownloadTask' +import { installationEvents, type InstallationRecord } from '../installations' import { abortModelStaging } from '../sources/comfybuilder/modelStagingTask' import { dropInstallationIndex, @@ -423,17 +417,7 @@ export function attachInstall(entry: ComfyWindowEntry, opts: AttachInstallOpts): attachSessionDownloadHandler(comfyContents.session) - let urlToLoad = comfyUrl - const pendingTemplate = - typeof installation.pendingTemplateOpen === 'string' ? installation.pendingTemplateOpen : null - if (isLocal && pendingTemplate) { - urlToLoad = buildTemplateDeeplink(comfyUrl, pendingTemplate) - void clearPendingTemplateOpen(installationId).catch((err) => { - console.warn(`[templates] Failed to clear pendingTemplateOpen for ${installationId}:`, err) - }) - } - - comfyContents.loadURL(urlToLoad) + comfyContents.loadURL(comfyUrl) entry._installCleanup = (): void => { if (entry._installCleanup === null) return @@ -457,7 +441,6 @@ export function attachInstall(entry: ComfyWindowEntry, opts: AttachInstallOpts): inFlight.abort() _operationAborts.delete(id) } - abortTemplateDownload(id) abortModelStaging(id) const relaunch = fx.relaunchStates.get(id) as { navBlocker: (...args: unknown[]) => void } | undefined diff --git a/src/main/index.ts b/src/main/index.ts index 4d821e74d..89b51ea66 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -45,7 +45,6 @@ import { import { registerTitlePopupIpc, triggerPickerSnapshotBroadcast, - openDownloadsTrayForInstall, type InstancePickerInstall } from './popups/titlePopup' import { registerPickerSettingsIpc } from './popups/pickerSettingsHandlers' @@ -74,11 +73,7 @@ import { } from './lib/comfyDownloadManager' import { stopAgentPrefetches } from './lib/agentRequirementsLaunch' import { prefetchEnrolledAgents } from './lib/agentPrefetch' -import { - hasActiveTemplateDownloads, - getTemplateDownloadState -} from './sources/standalone/templateDownloadTask' -import { isTerminal as isTemplateDownloadTerminal } from './sources/standalone/templateDownloadCore' +import { hasActiveTemplateDownloads } from './sources/standalone/templateDownloadTask' import { registerAssetDownloadHandlers } from './lib/ipc/registerAssetDownloadHandlers' import { registerDownloadHandlers } from './lib/ipc/registerDownloadHandlers' import { registerTemplateInputAssetHandlers } from './lib/ipc/registerTemplateInputAssetHandlers' @@ -518,7 +513,6 @@ function onLaunch({ if (proc) { proc.on('exit', () => {}) } - scheduleTemplateTrayAutoOpen(installationId) return } @@ -534,7 +528,6 @@ function onLaunch({ if (proc) { proc.on('exit', () => {}) } - scheduleTemplateTrayAutoOpen(installationId) return } } @@ -573,21 +566,6 @@ function onLaunch({ if (proc) { proc.on('exit', () => {}) } - - scheduleTemplateTrayAutoOpen(installationId) -} - -const TEMPLATE_TRAY_AUTO_OPEN_MS = 2500 - -function scheduleTemplateTrayAutoOpen(installationId: string): void { - const state = getTemplateDownloadState(installationId) - if (!state || isTemplateDownloadTerminal(state.status)) return - setTimeout(() => { - const cur = getTemplateDownloadState(installationId) - if (cur && !isTemplateDownloadTerminal(cur.status)) { - openDownloadsTrayForInstall(installationId) - } - }, TEMPLATE_TRAY_AUTO_OPEN_MS) } ipcMain.handle('quit-app', () => quitApp()) diff --git a/src/main/installations.test.ts b/src/main/installations.test.ts index 92703af85..bf7281540 100644 --- a/src/main/installations.test.ts +++ b/src/main/installations.test.ts @@ -782,40 +782,35 @@ describe('installations.enforceCloudName', () => { }) }) -describe('installations.clearPendingTemplateOpen', () => { - it('clears the one-shot flag once, then is a no-op on the cleared record', async () => { +describe('installations.load (a build made when first run offered a starter workflow)', () => { + it('lists, finds and updates a record that still carries the starter-template fields', async () => { + fs.writeFileSync( + path.join(userDataPath, 'installations.json'), + JSON.stringify([ + { + id: 'starter-build', + name: 'Starter Build', + installPath: path.join(tmpRoot, 'starter'), + sourceId: 'standalone', + status: 'installed', + createdAt: new Date().toISOString(), + bundledTemplateId: 'image_z_image_turbo', + bundledTemplateSizeBytes: 5_000_000_000, + pendingTemplateOpen: 'image_z_image_turbo', + downloadTemplateModels: true + } + ]) + ) const installations = await loadInstallations() - const entry = await installations.add({ - name: 'With Template', - installPath: path.join(tmpRoot, 't'), - sourceId: 'standalone', - status: 'installed', - bundledTemplateId: 'flux_schnell', - pendingTemplateOpen: 'flux_schnell', - downloadTemplateModels: true - }) - expect(await installations.clearPendingTemplateOpen(entry.id)).toBe(true) - expect((await installations.get(entry.id))!.pendingTemplateOpen).toBeNull() - expect(await installations.clearPendingTemplateOpen(entry.id)).toBe(false) - }) - - it('is a no-op for a legacy record with no template fields (migration-safe)', async () => { - const installations = await loadInstallations() - const entry = await installations.add({ - name: 'Legacy', - installPath: path.join(tmpRoot, 'legacy'), - sourceId: 'standalone', + expect((await installations.list()).map((record) => record.id)).toEqual(['starter-build']) + expect(await installations.get('starter-build')).toMatchObject({ + name: 'Starter Build', status: 'installed' }) - expect(entry.pendingTemplateOpen).toBeUndefined() - expect(entry.bundledTemplateId).toBeUndefined() - expect(await installations.clearPendingTemplateOpen(entry.id)).toBe(false) - }) - it('returns false when the install is gone', async () => { - const installations = await loadInstallations() - expect(await installations.clearPendingTemplateOpen('does-not-exist')).toBe(false) + await installations.update('starter-build', { name: 'Renamed' }) + expect((await installations.get('starter-build'))!.name).toBe('Renamed') }) }) diff --git a/src/main/installations.ts b/src/main/installations.ts index 1250b9842..9e723d2a6 100644 --- a/src/main/installations.ts +++ b/src/main/installations.ts @@ -30,10 +30,6 @@ export interface InstallationRecord { modelDirsPrimary?: string | null inputDir?: string outputDir?: string - bundledTemplateId?: string - bundledTemplateSizeBytes?: number - pendingTemplateOpen?: string | null - downloadTemplateModels?: boolean [key: string]: unknown } @@ -362,19 +358,6 @@ export async function markLaunched( return updated } -export async function clearPendingTemplateOpen(installationId: string): Promise { - return enqueue(async () => { - const list = await loadForWrite() - const index = list.findIndex((i) => i.id === installationId) - if (index === -1) return false - const existing = list[index]! - if (existing.pendingTemplateOpen == null) return false - list[index] = { ...existing, pendingTemplateOpen: null } as InstallationRecord - await save(list) - return true - }) -} - export async function getRecent(): Promise { const list = await load() let best: InstallationRecord | null = null diff --git a/src/main/lib/ipc/registerInstallationHandlers.ts b/src/main/lib/ipc/registerInstallationHandlers.ts index 871b7cfa5..0ebf5642d 100644 --- a/src/main/lib/ipc/registerInstallationHandlers.ts +++ b/src/main/lib/ipc/registerInstallationHandlers.ts @@ -43,10 +43,6 @@ import { restoreSnapshotIntoInstallation } from '../standaloneMigration' import * as mainTelemetry from '../telemetry' import { buildErrorFields } from '../../../shared/errorEvent' import { invalidateModelDownloadStartupPass } from '../comfyDownloadManager' -import { - startTemplateDownload, - abortTemplateDownload -} from '../../sources/standalone/templateDownloadTask' import { abortModelStaging } from '../../sources/comfybuilder/modelStagingTask' import { recordIpcInvocation } from '../e2eOverrides' import { DEFAULT_INSTALL_NAME } from '../../../shared/defaultInstallName' @@ -279,11 +275,6 @@ export function registerInstallationHandlers(): void { let snapshotRestoreError: string | null = null - if (inst.bundledTemplateId && inst.downloadTemplateModels && inst.pendingTemplateOpen) { - const sizeBytes = inst.bundledTemplateSizeBytes ?? 0 - startTemplateDownload(inst, sizeBytes, { sendOutput }) - } - const cache = createCache( settings.get('cacheDir') as string, settings.get('maxCachedDownloads') as number @@ -327,7 +318,6 @@ export function registerInstallationHandlers(): void { if (!snapshotRestoreError) sendProgress('done', { percent: 100, status: 'Complete' }) } catch (err) { _operationAborts.delete(installationId) - abortTemplateDownload(installationId) abortModelStaging(installationId) if (abort.signal.aborted) { if (isComfyUpdate) { diff --git a/src/main/lib/ipc/sessionActions/launchStarterModels.integration.test.ts b/src/main/lib/ipc/sessionActions/launchStarterModels.integration.test.ts deleted file mode 100644 index c39423848..000000000 --- a/src/main/lib/ipc/sessionActions/launchStarterModels.integration.test.ts +++ /dev/null @@ -1,423 +0,0 @@ -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' - -const electronHome = vi.hoisted(() => { - const overrides = [ - 'XDG_CONFIG_HOME', - 'XDG_CACHE_HOME', - 'XDG_DATA_HOME', - 'XDG_STATE_HOME', - 'LOCALAPPDATA' - ] - const saved = Object.fromEntries(overrides.map((name) => [name, process.env[name]])) - for (const name of overrides) delete process.env[name] - return { dir: '', saved } -}) - -vi.mock('electron', () => ({ - app: { - isPackaged: false, - getPath: () => - (electronHome.dir ||= fs.mkdtempSync(path.join(os.tmpdir(), 'launch-starter-home-'))), - getVersion: () => '0.0.0-test', - getLocale: () => 'en', - on: () => {} - }, - ipcMain: { handle: vi.fn(), on: vi.fn(), off: vi.fn() }, - dialog: {}, - shell: {}, - nativeImage: {}, - net: { isOnline: () => true }, - session: { defaultSession: {}, fromPartition: () => ({}) }, - WebContentsView: class {}, - BrowserWindow: { getAllWindows: () => [] }, - nativeTheme: { on: vi.fn(), shouldUseDarkColors: false } -})) - -const builds = vi.hoisted(() => ({ - commands: new Map>() -})) - -vi.mock('../shared', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - get _onLaunch() { - return actual._onLaunch - }, - captureSnapshotIfChanged: async () => ({ saved: false }), - sourceMap: { - ...actual.sourceMap, - standalone: { - ...actual.sourceMap.standalone, - getLaunchCommand: (inst: { id: string }) => { - const command = builds.commands.get(inst.id) - return command ? { ...command, args: [...(command.args as string[])] } : null - } - } - } - } -}) - -vi.mock('../../comfyProcessRecord', () => ({ - resolvePriorProcess: async () => null, - holderIsInstall: async () => false, - trackSpawn: () => {}, - markStopRequested: () => {}, - listRecords: () => [] -})) - -interface Transfer { - url: string - finalPath: string - stoppedBy: 'pause' | 'cancel' | null - settle: (outcome: Record) => void -} - -const network = vi.hoisted(() => ({ - unreachable: false, - transfers: [] as Transfer[] -})) - -vi.mock('../../modelDownloadTransport', () => ({ - startModelTransfer: (opts: { url: string; finalPath: string }) => { - let settle!: (outcome: Record) => void - const done = new Promise>((resolve) => { - settle = resolve - }) - const transfer: Transfer = { url: opts.url, finalPath: opts.finalPath, stoppedBy: null, settle } - network.transfers.push(transfer) - if (network.unreachable) settle({ outcome: 'error', error: 'connection reset' }) - return { - done, - pause: () => { - transfer.stoppedBy = 'pause' - settle({ outcome: 'paused' }) - return true - }, - cancel: () => { - transfer.stoppedBy = 'cancel' - settle({ outcome: 'cancelled' }) - return true - } - } - } -})) - -import { handleLaunch } from './launch' -import { - _operationAborts, - _pendingPorts, - _runningSessions, - killProcessTree, - setCallbacks -} from '../shared' -import type { InstallationRecord, LaunchCallbackInfo } from '../shared' -import type * as SharedModule from '../shared' -import * as installations from '../../../installations' -import * as i18n from '../../i18n' -import { lookupEnMessage } from '../../localeTestHelper' -import { isPortListening } from '../../process' -import { getVenvDir } from '../../pythonEnv' -import * as telemetry from '../../telemetry' -import { cancelModelDownload, getDownloadsTrayState } from '../../comfyDownloadManager' -import { DEFAULT_LAUNCH_PHASES } from '../../launchPhases' -import { - forgetTemplateDownload, - getTemplateDownloadState, - startTemplateDownload -} from '../../../sources/standalone/templateDownloadTask' -import type { ActionContext, ActionResult } from './types' - -const FAKE_COMFY = ` -const http = require('node:http') -const fs = require('node:fs') -const path = require('node:path') -const args = process.argv.slice(2) -const valueOf = (flag) => args[args.lastIndexOf(flag) + 1] -const port = Number(valueOf('--port')) -const name = valueOf('--name') -const state = valueOf('--state') -const server = http.createServer((req, res) => res.end(name)) -fs.writeFileSync(path.join(state, 'starting'), '') -const listenOnceAllowed = () => { - if (fs.existsSync(path.join(state, 'hold-boot'))) return setTimeout(listenOnceAllowed, 20) - server.listen(port, '127.0.0.1') -} -listenOnceAllowed() -` - -const STARTER_WORKFLOW = 'flux_starter' -const STARTER_MODELS_BYTES = 4 * 1024 * 1024 - -interface StarterBuild { - record: InstallationRecord - model: { name: string; url: string; directory: string } - progress: Record[] -} - -let workDir = '' -let script = '' -let buildCount = 0 -let opened: LaunchCallbackInfo[] = [] -const started: StarterBuild[] = [] -const launches: Promise[] = [] - -async function freePort(): Promise { - for (;;) { - const candidate = 30_000 + Math.floor(Math.random() * 10_000) - if (!(await isPortListening(candidate))) return candidate - } -} - -function sitePackagesOf(installPath: string): string { - const venv = getVenvDir(installPath) - return process.platform === 'win32' - ? path.join(venv, 'Lib', 'site-packages') - : path.join(venv, 'lib', 'python3.12', 'site-packages') -} - -async function buildWithStarterWorkflow(): Promise { - const slug = `starter-build-${++buildCount}` - const installPath = path.join(workDir, slug) - const model = { - name: `${slug}.safetensors`, - url: `https://huggingface.co/Comfy-Org/starter/resolve/main/${slug}.safetensors`, - directory: 'checkpoints' - } - const templates = path.join( - sitePackagesOf(installPath), - 'comfyui_workflow_templates', - 'templates' - ) - fs.mkdirSync(templates, { recursive: true }) - fs.writeFileSync( - path.join(templates, `${STARTER_WORKFLOW}.json`), - JSON.stringify({ models: [model], nodes: [] }) - ) - const record = await installations.add({ - name: slug, - sourceId: 'standalone', - installPath, - status: 'installed', - launchMode: 'window', - useSharedModels: false, - bundledTemplateId: STARTER_WORKFLOW, - bundledTemplateSizeBytes: STARTER_MODELS_BYTES, - pendingTemplateOpen: STARTER_WORKFLOW, - downloadTemplateModels: true - }) - const port = await freePort() - builds.commands.set(record.id, { - cmd: process.execPath, - args: [script, '--port', String(port), '--name', record.id, '--state', installPath], - cwd: installPath, - port, - skipSharedPaths: true - }) - const build = { record, model, progress: [] } - started.push(build) - return build -} - -async function installStartsTheStarterDownload(build: StarterBuild): Promise { - startTemplateDownload(build.record, STARTER_MODELS_BYTES, { sendOutput: () => {} }) - await vi.waitFor(() => expect(transfersOf(build)).toHaveLength(1), { timeout: 10_000 }) - expect(getTemplateDownloadState(build.record.id)?.status).toBe('downloading') -} - -function transfersOf(build: StarterBuild): Transfer[] { - return network.transfers.filter((transfer) => transfer.url === build.model.url) -} - -function downloadsTrayRow( - build: StarterBuild, - list: 'active' | 'recent' -): { id?: string; status: string } | undefined { - return getDownloadsTrayState()[list].find((row) => row.filename === build.model.name) -} - -function start(build: StarterBuild): Promise { - const ctx: ActionContext = { - event: { - sender: { - isDestroyed: () => false, - send: (channel: string, payload: Record) => { - if (channel === 'install-progress') build.progress.push(payload) - } - } - } as unknown as Electron.IpcMainInvokeEvent, - installationId: build.record.id, - inst: build.record - } - const launching = handleLaunch(ctx) - launches.push(launching.catch(() => {})) - return launching -} - -function holdComfyBoot(build: StarterBuild): void { - fs.writeFileSync(path.join(build.record.installPath, 'hold-boot'), '') -} - -async function comfyIsStarting(build: StarterBuild): Promise { - await vi.waitFor( - () => expect(fs.existsSync(path.join(build.record.installPath, 'starting'))).toBe(true), - { timeout: 15_000 } - ) -} - -function letComfyFinishBooting(build: StarterBuild): void { - fs.rmSync(path.join(build.record.installPath, 'hold-boot')) -} - -function windowsOpenedFor(): string[] { - return opened.map((info) => info.installation.id) -} - -function launchStepsShown(build: StarterBuild): string[] { - const steps = build.progress.flatMap((payload) => - payload.phase === 'steps' ? (payload.steps as { phase: string }[]) : [] - ) - return [...new Set(steps.map((step) => step.phase))] -} - -function stepsShownAsFailed(build: StarterBuild): Record[] { - return build.progress.filter((payload) => payload.error === true) -} - -async function whoAnswersOn(port: number): Promise { - return (await fetch(`http://127.0.0.1:${port}/`)).text() -} - -function finishDownloading(transfer: Transfer): void { - fs.mkdirSync(path.dirname(transfer.finalPath), { recursive: true }) - fs.writeFileSync(transfer.finalPath, 'model weights') - transfer.settle({ outcome: 'completed', savePath: transfer.finalPath, finalBytes: 13 }) -} - -function loseTheConnection(build: StarterBuild): void { - network.unreachable = true - for (const transfer of transfersOf(build)) { - transfer.settle({ outcome: 'error', error: 'connection reset' }) - } -} - -function cancelInTheDownloadsTray(build: StarterBuild): void { - expect(cancelModelDownload(downloadsTrayRow(build, 'active')!.id!)).toBe(true) -} - -beforeAll(() => { - workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'launch-starter-')) - script = path.join(workDir, 'fake-comfy.cjs') - fs.writeFileSync(script, FAKE_COMFY) -}) - -beforeEach(() => { - opened = [] - network.unreachable = false - setCallbacks({ onLaunch: (info) => opened.push(info) }) - vi.spyOn(telemetry, 'emit').mockImplementation(() => {}) - vi.spyOn(telemetry, 'capture').mockReturnValue(true) - vi.spyOn(i18n, 't').mockImplementation((key, params) => - lookupEnMessage(key).replace(/\{(\w+)\}/g, (_, name: string) => String(params?.[name] ?? '')) - ) -}) - -afterEach(async () => { - for (const build of started.splice(0)) { - forgetTemplateDownload(build.record.id) - const row = downloadsTrayRow(build, 'active') - if (row?.id) cancelModelDownload(row.id) - } - for (const abort of _operationAborts.values()) abort.abort() - await Promise.all(launches.splice(0)) - const running = [..._runningSessions.values()] - for (const id of [..._runningSessions.keys()]) _runningSessions.delete(id) - await Promise.all(running.map((session) => (session.proc ? killProcessTree(session.proc) : null))) - _pendingPorts.clear() - builds.commands.clear() - setCallbacks({}) - vi.restoreAllMocks() -}) - -afterAll(() => { - for (const [name, value] of Object.entries(electronHome.saved)) { - if (value !== undefined) process.env[name] = value - } - fs.rmSync(workDir, { recursive: true, force: true, maxRetries: 3 }) - if (electronHome.dir) fs.rmSync(electronHome.dir, { recursive: true, force: true, maxRetries: 3 }) -}) - -describe( - 'first launch of a build whose starter models are still downloading', - { - timeout: 60_000 - }, - () => { - it('opens ComfyUI as soon as its server answers, and the download carries on to the end', async () => { - const build = await buildWithStarterWorkflow() - await installStartsTheStarterDownload(build) - - const launching = start(build) - await vi.waitFor(() => expect(windowsOpenedFor()).toEqual([build.record.id]), { - timeout: 20_000 - }) - const result = await launching - - expect(result.ok, result.message).toBe(true) - expect(await whoAnswersOn(result.port!)).toBe(build.record.id) - expect(opened[0]!.port).toBe(result.port) - expect( - opened[0]!.installation.pendingTemplateOpen, - 'the window still opens on the starter workflow' - ).toBe(STARTER_WORKFLOW) - expect(getTemplateDownloadState(build.record.id)?.status).toBe('downloading') - expect(downloadsTrayRow(build, 'active'), 'listed in the Downloads tray').toBeDefined() - expect(transfersOf(build).map((transfer) => transfer.stoppedBy)).toEqual([null]) - expect(launchStepsShown(build)).toEqual(DEFAULT_LAUNCH_PHASES.map((step) => step.phase)) - expect(stepsShownAsFailed(build)).toEqual([]) - - finishDownloading(transfersOf(build)[0]!) - - await vi.waitFor( - () => expect(getTemplateDownloadState(build.record.id)?.status).toBe('done'), - { - timeout: 10_000 - } - ) - expect(downloadsTrayRow(build, 'recent')?.status).toBe('completed') - expect(transfersOf(build), 'the download was never restarted').toHaveLength(1) - }) - - it.each([ - ['fails', loseTheConnection], - ['is cancelled in the Downloads tray', cancelInTheDownloadsTray] - ])( - 'opens ComfyUI with no failed step when the download %s while ComfyUI starts', - async (_how, breakTheDownload) => { - const build = await buildWithStarterWorkflow() - holdComfyBoot(build) - await installStartsTheStarterDownload(build) - - const launching = start(build) - await comfyIsStarting(build) - breakTheDownload(build) - await vi.waitFor( - () => expect(getTemplateDownloadState(build.record.id)?.status).toBe('error'), - { timeout: 10_000 } - ) - expect(windowsOpenedFor(), 'ComfyUI is still starting').toEqual([]) - letComfyFinishBooting(build) - const result = await launching - - expect(result.ok, result.message).toBe(true) - expect(windowsOpenedFor()).toEqual([build.record.id]) - expect(await whoAnswersOn(result.port!)).toBe(build.record.id) - expect(launchStepsShown(build)).toEqual(DEFAULT_LAUNCH_PHASES.map((step) => step.phase)) - expect(stepsShownAsFailed(build)).toEqual([]) - } - ) - } -) diff --git a/src/main/popups/titlePopup.ts b/src/main/popups/titlePopup.ts index 3cb8b7104..0e422ac35 100644 --- a/src/main/popups/titlePopup.ts +++ b/src/main/popups/titlePopup.ts @@ -967,23 +967,6 @@ function openTitlePopup(opts: OpenTitlePopupOpts): void { showTitlePopupNow(entry) } -export function openDownloadsTrayForInstall(installationId: string): void { - const entry = getEntryByInstallationId(installationId) - if (!entry || entry.window.isDestroyed()) return - const existing = titlePopupsByParent.get(entry.window.id) - if (existing && (existing.view.isOpen || existing.view.pendingShowTimer !== null)) { - return - } - openTitlePopup({ - parent: entry.window, - parentEntryId: entry.windowKey, - kind: 'downloads', - anchor: { x: entry.window.getContentBounds().width, y: TITLEBAR_HEIGHT }, - theme: entry.lastTheme, - titleBarSender: entry.titleBarView.webContents - }) -} - export interface TitlePopupHostBindings { openChooserHostWindow: (initialPanel?: ComfyPanelKey) => void returnToDashboard: (parentEntryId: number) => Promise | void diff --git a/src/main/settings.test.ts b/src/main/settings.test.ts index 192da5d9d..03b646a58 100644 --- a/src/main/settings.test.ts +++ b/src/main/settings.test.ts @@ -157,6 +157,19 @@ describe('settings unset/default semantics', () => { expect(persisted['maxCachedDownloads']).toBe(1) }) + it('discards the retired skipTemplatePickerStep key from the starter workflow step', () => { + fs.mkdirSync(path.dirname(settingsPath), { recursive: true }) + fs.writeFileSync( + settingsPath, + JSON.stringify({ skipTemplatePickerStep: true, theme: 'dark' }, null, 2), + 'utf-8' + ) + + expect(settings.get('skipTemplatePickerStep')).toBeUndefined() + expect(settings.get('theme')).toBe('dark') + expect(readPersistedSettings()).not.toHaveProperty('skipTemplatePickerStep') + }) + it('preserves a manual maxCachedDownloads edit', () => { fs.mkdirSync(path.dirname(settingsPath), { recursive: true }) fs.writeFileSync(settingsPath, JSON.stringify({ maxCachedDownloads: 9 }, null, 2), 'utf-8') diff --git a/src/main/settings.ts b/src/main/settings.ts index ec8558ca8..77b83d9bc 100644 --- a/src/main/settings.ts +++ b/src/main/settings.ts @@ -49,7 +49,6 @@ export interface KnownSettings { oemManagedModelDirs?: string[] oemWorkflowImportVersion?: number lastSaveDialogDir?: string - skipTemplatePickerStep?: boolean dashboardWorkspaceId?: string pendingDownloadedUpdateVersion?: string lastStartupUpdateAttemptVersion?: string @@ -177,10 +176,6 @@ const SETTINGS_SCHEMA = { oemManagedModelDirs: { nullable: false, telemetry: { policy: 'presence' } }, oemWorkflowImportVersion: { nullable: false, telemetry: { policy: 'omit' } }, lastSaveDialogDir: { nullable: true, telemetry: { policy: 'presence' } }, - skipTemplatePickerStep: { - nullable: false, - telemetry: { policy: 'value', toTelemetry: (raw) => raw === true } - }, dashboardWorkspaceId: { nullable: false, telemetry: { policy: 'omit' } }, pendingDownloadedUpdateVersion: { nullable: true, telemetry: { policy: 'omit' } }, lastStartupUpdateAttemptVersion: { nullable: true, telemetry: { policy: 'omit' } }, @@ -359,7 +354,8 @@ function loadOutcome(preRead?: SafeReadOutcome): { 'primaryInstallId', 'pinnedInstallIds', 'maxCachedFiles', - 'closeDirectlyOnLastWindow' + 'closeDirectlyOnLastWindow', + 'skipTemplatePickerStep' ]) { if (Object.prototype.hasOwnProperty.call(result, key)) { delete result[key] diff --git a/src/main/sources/standalone/curatedTemplates.test.ts b/src/main/sources/standalone/curatedTemplates.test.ts index 385734a7a..1b5bac1fa 100644 --- a/src/main/sources/standalone/curatedTemplates.test.ts +++ b/src/main/sources/standalone/curatedTemplates.test.ts @@ -1,22 +1,14 @@ import { describe, it, expect } from 'vitest' import { - buildTemplateDeeplink, thumbnailUrlFor, isPersistableTemplateId, - CURATED_TEMPLATES, NO_TEMPLATE_VALUE, - TEMPLATE_MODALITY_ORDER, RAW_TEMPLATES_BASE } from './curatedTemplates' describe('isPersistableTemplateId', () => { - it('accepts every curated id', () => { - for (const t of CURATED_TEMPLATES) { - expect(isPersistableTemplateId(t.id), t.id).toBe(true) - } - }) - - it('accepts a live-index substitute id (dotted/hyphenated) not in the curated set', () => { + it('accepts plain, dotted and hyphenated template ids', () => { + expect(isPersistableTemplateId('image_z_image_turbo')).toBe(true) expect(isPersistableTemplateId('some_live_image_model')).toBe(true) expect(isPersistableTemplateId('image_flux2_klein-v1.2')).toBe(true) }) @@ -38,27 +30,6 @@ describe('isPersistableTemplateId', () => { }) }) -describe('buildTemplateDeeplink', () => { - it('appends ?template=&source=default and round-trips the id', () => { - const out = buildTemplateDeeplink('http://127.0.0.1:8188/', 'flux_schnell') - const parsed = new URL(out) - expect(parsed.searchParams.get('template')).toBe('flux_schnell') - expect(parsed.searchParams.get('source')).toBe('default') - }) - - it('preserves an existing query and host/port', () => { - const out = buildTemplateDeeplink('http://localhost:8000/?foo=bar', 'text_to_video_wan') - const parsed = new URL(out) - expect(parsed.host).toBe('localhost:8000') - expect(parsed.searchParams.get('foo')).toBe('bar') - expect(parsed.searchParams.get('template')).toBe('text_to_video_wan') - }) - - it('returns the input unchanged when the URL cannot be parsed', () => { - expect(buildTemplateDeeplink('not a url', 'flux_schnell')).toBe('not a url') - }) -}) - describe('thumbnailUrlFor', () => { it('builds the -1. preview URL for image subtypes', () => { expect(thumbnailUrlFor('flux_schnell', 'webp')).toBe( @@ -75,61 +46,3 @@ describe('thumbnailUrlFor', () => { expect(thumbnailUrlFor('audio_song', 'mp3')).toBeNull() }) }) - -describe('CURATED_TEMPLATES manifest', () => { - const ID_PATTERN = /^[a-zA-Z0-9_.-]+$/ - - it('offers exactly 4 templates per modality', () => { - for (const modality of TEMPLATE_MODALITY_ORDER) { - const count = CURATED_TEMPLATES.filter((t) => t.modality === modality).length - expect(count, modality).toBe(4) - } - }) - - it('marks at most one recommended template per modality', () => { - for (const modality of TEMPLATE_MODALITY_ORDER) { - const recommended = CURATED_TEMPLATES.filter((t) => t.modality === modality && t.recommended) - expect(recommended.length, modality).toBeLessThanOrEqual(1) - } - }) - - it('uses only deeplink-safe ids', () => { - for (const t of CURATED_TEMPLATES) { - expect(t.id, t.id).toMatch(ID_PATTERN) - } - }) - - it('carries a non-empty offline snapshot for every entry', () => { - for (const t of CURATED_TEMPLATES) { - expect(t.snapshot.title, t.id).toBeTruthy() - expect(t.snapshot.description, t.id).toBeTruthy() - expect(t.snapshot.mediaSubtype, t.id).toBeTruthy() - } - }) - - it('sizes every local template and no API-node one', () => { - for (const t of CURATED_TEMPLATES) { - if (t.apiNode) expect(t.snapshot.sizeBytes, t.id).toBe(0) - else expect(t.snapshot.sizeBytes, t.id).toBeGreaterThan(0) - } - }) - - it('offers exactly one API-node template per modality', () => { - for (const modality of TEMPLATE_MODALITY_ORDER) { - const apiTemplate = CURATED_TEMPLATES.filter((t) => t.modality === modality && t.apiNode) - expect(apiTemplate.length, modality).toBe(1) - } - }) - - it('never recommends a template that spends credits', () => { - for (const t of CURATED_TEMPLATES) { - if (t.apiNode) expect(t.recommended, t.id).toBeFalsy() - } - }) - - it('only uses modalities declared in the tab order', () => { - for (const t of CURATED_TEMPLATES) { - expect(TEMPLATE_MODALITY_ORDER).toContain(t.modality) - } - }) -}) diff --git a/src/main/sources/standalone/curatedTemplates.ts b/src/main/sources/standalone/curatedTemplates.ts index fc48090f2..1963e165b 100644 --- a/src/main/sources/standalone/curatedTemplates.ts +++ b/src/main/sources/standalone/curatedTemplates.ts @@ -7,15 +7,6 @@ export interface TemplateSnapshot { mediaSubtype: string } -interface CuratedTemplateBase { - id: string - modality: TemplateModality - snapshot: TemplateSnapshot -} - -export type CuratedTemplate = CuratedTemplateBase & - ({ recommended?: true; apiNode?: never } | { apiNode: true; recommended?: never }) - export const TEMPLATE_MODALITY_ORDER: readonly TemplateModality[] = [ 'video', 'image', @@ -37,17 +28,6 @@ export function thumbnailUrlFor(id: string, mediaSubtype: string): string | null return `${RAW_TEMPLATES_BASE}/${id}-1.${ext}` } -export function buildTemplateDeeplink(comfyUrl: string, templateId: string): string { - try { - const url = new URL(comfyUrl) - url.searchParams.set('template', templateId) - url.searchParams.set('source', 'default') - return url.toString() - } catch { - return comfyUrl - } -} - export const NO_TEMPLATE_VALUE = 'none' const TEMPLATE_ID_PATTERN = /^[a-zA-Z0-9_.-]+$/ @@ -61,189 +41,3 @@ export function isPersistableTemplateId(value: unknown): value is string { TEMPLATE_ID_PATTERN.test(value) ) } - -export const CURATED_TEMPLATES: readonly CuratedTemplate[] = [ - { - id: 'image_z_image_turbo', - modality: 'image', - recommended: true, - snapshot: { - title: 'Z-Image-Turbo Text to Image', - description: - 'An Efficient Image Generation Foundation Model with Single-Stream Diffusion Transformer, supports English & Chinese.', - sizeBytes: 20830591386, - mediaSubtype: 'webp' - } - }, - { - id: 'api_bytedance_seedream_5_0_pro_image_edit', - modality: 'image', - apiNode: true, - snapshot: { - title: 'Seedream 5.0 Pro: Image Edit', - description: - 'Edit images with precision using Seedream 5.0 Pro, targeting specific regions while preserving lighting, depth, and texture. The workflow takes 1 input image and produces 2 output images through an optional Painter node and preview. Ideal for product photography edits, portrait consistency adjustments, and creating structured layouts with multilingual text.', - sizeBytes: 0, - mediaSubtype: 'webp' - } - }, - { - id: 'sdxlturbo_example', - modality: 'image', - snapshot: { - title: 'SDXL Turbo', - description: 'Generate images in a single step using SDXL Turbo.', - sizeBytes: 6936372183, - mediaSubtype: 'webp' - } - }, - { - id: 'image_pixeldit_t2i', - modality: 'image', - snapshot: { - title: 'PixelDiT: Text to Image', - description: - "Input a text prompt and optional negative prompt. Generate a 1024px image using PixelDiT's VAE-free pixel diffusion transformer.", - sizeBytes: 7838315315, - mediaSubtype: 'webp' - } - }, - - { - id: 'video_minimax_h3_t2v', - modality: 'video', - recommended: true, - snapshot: { - title: 'MiniMax H3: Text to Video', - description: - 'Generate video with native stereo audio directly from a text prompt using MiniMax H3, an omni-modal model that synthesizes voice, sound effects, and music in a single pass. Output is up to 2K resolution, 24fps, and roughly 15 seconds long, with no file inputs required — just a prompt to one video output. Ideal for rapid concept visualization, social media content creation, and audio-synced storytelling.', - sizeBytes: 56908316672, - mediaSubtype: 'webp' - } - }, - { - id: 'api_seedance2_5_r2v', - modality: 'video', - apiNode: true, - snapshot: { - title: 'Seedance 2.5: Reference to Video', - description: - 'Generate reference-driven videos with Seedance 2.5 by supplying up to 20 images, 6 video clips, and 6 audio clips to control character consistency, visual style, and motion rhythm in a single 4–30 second output with synchronized sound and lip-synced dialogue. Ideal for e-commerce product showcases, brand advertising, and character-driven short series.', - sizeBytes: 0, - mediaSubtype: 'webp' - } - }, - { - id: 'wan2.1_fun_inp', - modality: 'video', - snapshot: { - title: 'Wan 2.1 Inpainting', - description: 'Generate videos from start and end frames using Wan 2.1 inpainting.', - sizeBytes: 11381663334, - mediaSubtype: 'webp' - } - }, - { - id: 'video_wan2.1_fun_camera_v1.1_1.3B', - modality: 'video', - snapshot: { - title: 'Wan 2.1 Fun Camera 1.3B', - description: - 'Generate dynamic videos with cinematic camera movements using Wan 2.1 Fun Camera 1.3B model.', - sizeBytes: 11489037517, - mediaSubtype: 'webp' - } - }, - - { - id: '3d_triposplat_image_to_gaussian_splat', - modality: '3d', - recommended: true, - snapshot: { - title: 'TripoSplat: Image to Gaussian Splat', - description: - 'Upload a single 2D image. Generate a high-quality 3D Gaussian splat representation with controllable density and budget for rendering.', - sizeBytes: 3972844749, - mediaSubtype: 'webp' - } - }, - { - id: 'api_tripo3_1_image_to_model', - modality: '3d', - apiNode: true, - snapshot: { - title: 'Tripo H3.1: Image to Model', - description: - 'Upload a reference image of your object. Generate a high-detail 3D model with dense geometry and PBR-ready materials.', - sizeBytes: 0, - mediaSubtype: 'webp' - } - }, - { - id: '3d_moge_perspective_to_mesh', - modality: '3d', - snapshot: { - title: 'MoGe: Perspective Geometry Estimation', - description: - 'Upload an image to estimate its perspective geometry. Generate a 3D depth map and surface normals from the input.', - sizeBytes: 644245094, - mediaSubtype: 'webp' - } - }, - { - id: '3d_hunyuan3d_multiview_to_model_turbo', - modality: '3d', - snapshot: { - title: 'HY 3D 2.0 MV Turbo', - description: 'Generate 3D models from multiple views using Hunyuan3D 2.0 MV Turbo.', - sizeBytes: 4928474972, - mediaSubtype: 'webp' - } - }, - - { - id: 'audio_stable_audio_3_medium', - modality: 'audio', - recommended: true, - snapshot: { - title: 'Stable Audio 3.0 Medium', - description: - 'Input a short text idea, optional duration, seed, and category. Generate stereo audio (music, SFX, or instruments) using Stable Audio 3 with optional AI-driven text expansion.', - sizeBytes: 15676630630, - mediaSubtype: 'webp' - } - }, - { - id: 'api_bytedance_seed_audio1_0_t2a', - modality: 'audio', - apiNode: true, - snapshot: { - title: 'Seed Audio 1.0: Text to Audio', - description: - 'Input a text prompt to generate speech, dialogue, background music, and sound effects in one audio file. Describe voices, emotion, and scene details to create multi-speaker audio up to 2 minutes.', - sizeBytes: 0, - mediaSubtype: 'webp' - } - }, - { - id: 'audio_stable_audio_example', - modality: 'audio', - snapshot: { - title: 'Stable Audio 1.0: Text to Audio', - description: 'Generate audio from text prompts using Stable Audio.', - sizeBytes: 5690831667, - mediaSubtype: 'webp' - } - }, - { - id: 'audio_ace_step_1_5_checkpoint', - modality: 'audio', - snapshot: { - title: 'ACE-Step 1.5 Music Generation AIO', - description: - 'Input style tags and lyrics to generate a full song. The workflow uses the ACE-Step 1.5 model to produce commercial-grade music in under 10 seconds on consumer hardware.', - sizeBytes: 10737418240, - mediaSubtype: 'mp3' - } - } -] as const diff --git a/src/main/sources/standalone/index.test.ts b/src/main/sources/standalone/index.test.ts index 4c3a1ab9f..f628639df 100644 --- a/src/main/sources/standalone/index.test.ts +++ b/src/main/sources/standalone/index.test.ts @@ -16,8 +16,6 @@ vi.mock('../../lib/comfyui-releases', () => ({ })) import { standalone, buildPinnedVariant } from './index' -import { resetTemplateCatalogCache } from './templateCatalog' -import { CURATED_TEMPLATES, NO_TEMPLATE_VALUE, INDEX_URL } from './curatedTemplates' import { fetchJSON } from '../../lib/fetch' import { getLatestStableTag } from '../../lib/comfyui-releases' import { PLATFORM_PREFIX } from './envPaths' @@ -132,166 +130,27 @@ describe('standalone.buildInstallation', () => { expect(result.originalTorchVersion).toBe('2.7.0') }) - describe('starter template', () => { - const base = { - release: makeRelease('stable', 'v0.18.2-env1'), - variant: makeVariant(VENDOR_ID) - } - const template = (value: string, sizeBytes?: number): FieldOption => ({ - value, - label: value, - ...(sizeBytes !== undefined ? { data: { sizeBytes } } : {}) - }) - - it('records an API-node pick for auto-open even though it downloads nothing', () => { - const apiTemplate = CURATED_TEMPLATES.find((t) => t.apiNode)! - const result = standalone.buildInstallation({ - ...base, - bundledTemplate: template(apiTemplate.id, 0) - }) - expect(result.bundledTemplateId).toBe(apiTemplate.id) - expect(result.pendingTemplateOpen).toBe(apiTemplate.id) - expect(result.bundledTemplateSizeBytes).toBe(0) - }) - - it('"Skip & Install" (template = none) builds NO model download', () => { - const result = standalone.buildInstallation({ - ...base, - bundledTemplate: template(NO_TEMPLATE_VALUE) - }) - expect(result.bundledTemplateId).toBeUndefined() - expect(result.pendingTemplateOpen).toBeUndefined() - expect(result.downloadTemplateModels).toBeUndefined() - expect(result.bundledTemplateSizeBytes).toBeUndefined() - }) - - it('"Skip & Install" with no bundledTemplate selection at all builds no download', () => { - const result = standalone.buildInstallation(base) - expect(result.bundledTemplateId).toBeUndefined() - expect(result.downloadTemplateModels).toBeUndefined() - }) - - it('picking a real template records the id, one-shot open flag, and download opt-in', () => { - const realId = CURATED_TEMPLATES[0]!.id - const result = standalone.buildInstallation({ ...base, bundledTemplate: template(realId) }) - expect(result.bundledTemplateId).toBe(realId) - expect(result.pendingTemplateOpen).toBe(realId) - expect(result.downloadTemplateModels).toBe(true) - }) - - it('freezes the hydrated size on the record so the download estimate matches consent', () => { - const realId = CURATED_TEMPLATES[0]!.id - const result = standalone.buildInstallation({ - ...base, - bundledTemplate: template(realId, 1234) - }) - expect(result.bundledTemplateSizeBytes).toBe(1234) - }) - - it('defaults size to 0 when the selection carries no hydrated size', () => { - const realId = CURATED_TEMPLATES[0]!.id - const result = standalone.buildInstallation({ ...base, bundledTemplate: template(realId) }) - expect(result.bundledTemplateSizeBytes).toBe(0) - }) - - it('persists a live-index substitute id not in the curated set (substitution survives the gate)', () => { - const substituteId = 'some_live_image_model' - expect(CURATED_TEMPLATES.some((t) => t.id === substituteId)).toBe(false) - const result = standalone.buildInstallation({ - ...base, - bundledTemplate: template(substituteId, 5) - }) - expect(result.bundledTemplateId).toBe(substituteId) - expect(result.pendingTemplateOpen).toBe(substituteId) - expect(result.downloadTemplateModels).toBe(true) - }) - - it('rejects a forged id that could escape a path/URL', () => { - const result = standalone.buildInstallation({ - ...base, - bundledTemplate: template('../../etc/passwd') - }) - expect(result.bundledTemplateId).toBeUndefined() - expect(result.downloadTemplateModels).toBeUndefined() - }) - }) -}) - -describe('standalone.getFieldOptions bundledTemplate', () => { - beforeEach(() => { - mockedFetchJSON.mockReset() - resetTemplateCatalogCache() - }) - - it('leads with the skip sentinel, then one option per curated template', async () => { - mockedFetchJSON.mockResolvedValue([]) - const options = await standalone.getFieldOptions!('bundledTemplate', {}, {}) - expect(options[0]!.value).toBe(NO_TEMPLATE_VALUE) - expect(options.length).toBe(CURATED_TEMPLATES.length + 1) - }) - - it('marks the per-modality recommended picks (not the skip option)', async () => { - mockedFetchJSON.mockResolvedValue([]) - const options = await standalone.getFieldOptions!('bundledTemplate', {}, {}) - const skip = options.find((o) => o.value === NO_TEMPLATE_VALUE)! - expect(skip.recommended).toBeFalsy() - const recommendedIds = options.filter((o) => o.recommended).map((o) => o.value) - expect(recommendedIds.sort()).toEqual( - CURATED_TEMPLATES.filter((t) => t.recommended) - .map((t) => t.id) - .sort() - ) - }) - - it('falls back to snapshot metadata when the index fetch fails (offline)', async () => { - mockedFetchJSON.mockImplementation((url: string) => - String(url).includes('index.json') - ? Promise.reject(new Error('offline')) - : Promise.resolve(null) - ) - const options = await standalone.getFieldOptions!('bundledTemplate', {}, {}) - const first = CURATED_TEMPLATES[0]! - const card = options.find((o) => o.value === first.id)! - expect(card.label).toBe(first.snapshot.title) - expect(card.data!.sizeBytes).toBe(first.snapshot.sizeBytes) + it('asks a new install only for its release, ComfyUI version and variant', () => { + expect(standalone.fields.map((field) => field.id)).toEqual([ + 'release', + 'comfyVersion', + 'variant' + ]) }) - it('hydrates title/size from the live index, overriding the snapshot', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockImplementation((url: string) => { - if (url === INDEX_URL) { - return Promise.resolve([ - { - title: 'Image', - templates: [ - { - name: first.id, - title: 'Live Title', - description: 'Live desc', - size: 999, - mediaSubtype: 'webp' - } - ] - } - ]) - } - return Promise.resolve(undefined) + it('writes no starter workflow onto a new install, even from a stale template selection', () => { + const result = standalone.buildInstallation({ + release: makeRelease('stable', 'v0.18.2-env1'), + variant: makeVariant(VENDOR_ID), + bundledTemplate: { value: 'image_z_image_turbo', label: 'Z-Image', data: { sizeBytes: 5 } } }) - const options = await standalone.getFieldOptions!('bundledTemplate', {}, {}) - const card = options.find((o) => o.value === first.id)! - expect(card.label).toBe('Live Title') - expect(card.description).toBe('Live desc') - expect(card.data!.sizeBytes).toBe(999) - expect(card.data!.category).toBe('Image') - }) - - it('carries the API-node flag to the card, and never on the skip option', async () => { - mockedFetchJSON.mockResolvedValue([]) - const options = await standalone.getFieldOptions!('bundledTemplate', {}, {}) - expect(options.find((o) => o.value === NO_TEMPLATE_VALUE)!.data?.apiNode).toBeUndefined() - for (const curated of CURATED_TEMPLATES) { - const card = options.find((o) => o.value === curated.id)! - expect(card.data!.apiNode, curated.id).toBe(curated.apiNode === true) + for (const field of [ + 'bundledTemplateId', + 'bundledTemplateSizeBytes', + 'pendingTemplateOpen', + 'downloadTemplateModels' + ]) { + expect(result, field).not.toHaveProperty(field) } }) }) diff --git a/src/main/sources/standalone/index.ts b/src/main/sources/standalone/index.ts index 9136de876..0cc20b7ae 100644 --- a/src/main/sources/standalone/index.ts +++ b/src/main/sources/standalone/index.ts @@ -6,7 +6,6 @@ import { t } from '../../lib/i18n' import { launchAction } from '../../lib/actions' import { getLatestStableTag, getStableTags } from '../../lib/comfyui-releases' import { copyDirWithProgress } from '../../lib/copy' -import { resolveModelsPresence } from '../../lib/modelDownloadPaths' import { PLATFORM_PREFIX, DEFAULT_LAUNCH_ARGS, @@ -19,10 +18,6 @@ import { writeComfyEnvironment } from './envPaths' import { install, installSteps, postInstall, probeInstallation } from './install' -import { NO_TEMPLATE_VALUE, isPersistableTemplateId } from './curatedTemplates' -import { loadTemplateCatalog, toTemplateFieldOption } from './templateCatalog' -import { resolveTemplateModels } from './templateModels' -import * as installations from '../../installations' import { getListPreview, getStatusTag, getDetailSections, R2_BASE_URL } from './updateSections' import { handleAction } from './actions' @@ -40,8 +35,6 @@ interface VariantData { downloadFiles: { url: string; filename: string; size: number }[] } -const MODELS_PRESENT_BUDGET_MS = 2500 - function buildVariantOption( vendorId: string, release: R2Variant, @@ -112,12 +105,6 @@ export const standalone: SourcePlugin = { label: t('standalone.variant'), type: 'select' as const, renderAs: 'cards' as const - }, - { - id: 'bundledTemplate', - label: t('standalone.starterTemplate'), - type: 'select' as const, - renderAs: 'cards' as const } ] }, @@ -149,12 +136,6 @@ export const standalone: SourcePlugin = { ? selections.comfyVersion.value : undefined : undefined - const tplValue = selections.bundledTemplate?.value - const bundledTemplateId = isPersistableTemplateId(tplValue) ? tplValue : undefined - const bundledTemplateSizeBytes = - typeof selections.bundledTemplate?.data?.sizeBytes === 'number' - ? (selections.bundledTemplate.data.sizeBytes as number) - : 0 return { version: r2Release?.comfyui_version || manifest?.comfyui_ref || releaseTag, releaseTag, @@ -170,15 +151,7 @@ export const standalone: SourcePlugin = { ...(isStable || isLatest ? { autoUpdateComfyUI: true } : {}), ...(isStable ? { updateChannel: 'stable' } : {}), ...(isLatest ? { updateChannel: 'latest' } : {}), - ...(pickedComfyTag ? { comfyVersionTag: pickedComfyTag } : {}), - ...(bundledTemplateId - ? { - bundledTemplateId, - bundledTemplateSizeBytes, - pendingTemplateOpen: bundledTemplateId, - downloadTemplateModels: true - } - : {}) + ...(pickedComfyTag ? { comfyVersionTag: pickedComfyTag } : {}) } }, @@ -413,33 +386,6 @@ export const standalone: SourcePlugin = { .filter((item): item is FieldOption => item != null) } - if (fieldId === 'bundledTemplate') { - const catalog = await loadTemplateCatalog() - - const installId = typeof context.installationId === 'string' ? context.installationId : null - const installation = installId ? await installations.get(installId) : null - const { presence: presenceById, timedOut } = await resolveModelsPresence( - catalog.map(({ id }) => id), - installId, - (id) => resolveTemplateModels(installation, id), - MODELS_PRESENT_BUDGET_MS - ) - if (timedOut) { - console.warn( - `Template models-present check hit ${MODELS_PRESENT_BUDGET_MS}ms budget for install ${installId ?? '(none)'}; some cards unbadged` - ) - } - - return [ - { - value: NO_TEMPLATE_VALUE, - label: t('standalone.starterTemplateNone'), - description: t('standalone.starterTemplateNoneDesc') - }, - ...catalog.map((tpl) => toTemplateFieldOption(tpl, presenceById.get(tpl.id) ?? false)) - ] - } - return [] } } diff --git a/src/main/sources/standalone/remoteStarterTemplates.test.ts b/src/main/sources/standalone/remoteStarterTemplates.test.ts deleted file mode 100644 index e1b63b139..000000000 --- a/src/main/sources/standalone/remoteStarterTemplates.test.ts +++ /dev/null @@ -1,531 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' - -vi.mock('../../lib/fetch', () => ({ fetchJSON: vi.fn() })) - -import { - STARTER_TEMPLATES_URL, - parseRemoteStarterTemplates, - resolveStarterTemplates, - loadStarterTemplates, - _resetStarterTemplatesForTest -} from './remoteStarterTemplates' -import { CURATED_TEMPLATES, TEMPLATE_MODALITY_ORDER } from './curatedTemplates' -import { fetchJSON } from '../../lib/fetch' - -const mockedFetchJSON = vi.mocked(fetchJSON) - -const SNAPSHOT = { - title: 'T', - description: 'D', - sizeBytes: 10, - mediaSubtype: 'webp' -} - -function entry(over: Record = {}): Record { - return { id: 'remote_one', modality: 'image', snapshot: { ...SNAPSHOT }, ...over } -} - -function doc(templates: unknown[]): Record { - return { schemaVersion: 1, templates } -} - -function bakedIds(modality: string): string[] { - return CURATED_TEMPLATES.filter((t) => t.modality === modality).map((t) => t.id) -} - -describe('A. an unusable document is ignored entirely', () => { - it.each([ - ['not an object', 'nope'], - ['a bare array', [{ id: 'a', modality: 'image' }]], - ['null', null], - ['undefined', undefined], - ['a number', 42], - ['schemaVersion missing', { templates: [{ id: 'a', modality: 'image', snapshot: SNAPSHOT }] }], - [ - 'schemaVersion from the future', - { schemaVersion: 2, templates: [{ id: 'a', modality: 'image', snapshot: SNAPSHOT }] } - ], - [ - 'schemaVersion as a string', - { schemaVersion: '1', templates: [{ id: 'a', modality: 'image', snapshot: SNAPSHOT }] } - ], - ['templates missing', { schemaVersion: 1 }], - ['templates not an array', { schemaVersion: 1, templates: {} }], - ['templates empty', { schemaVersion: 1, templates: [] }], - ['every entry invalid', { schemaVersion: 1, templates: [{ id: 42 }, null] }] - ])('%s yields null, so the caller keeps the hardcoded list', (_label, raw) => { - expect(parseRemoteStarterTemplates(raw)).toBeNull() - }) - - it('accepts the escaped-JSON-string form as well as a parsed object', () => { - const parsed = parseRemoteStarterTemplates(JSON.stringify(doc([entry()]))) - expect(parsed?.map((t) => t.id)).toEqual(['remote_one']) - }) -}) - -describe('B. one bad entry drops alone', () => { - it.each([ - ['id not a string', { id: 42 }], - ['id empty', { id: '' }], - ['id with a path segment', { id: '../../etc/passwd' }], - ['id with a slash', { id: 'a/b' }], - ['id with a space', { id: 'a b' }], - ['id far too long', { id: 'a'.repeat(129) }], - ['modality unknown', { modality: 'gif' }], - ['snapshot not an object', { snapshot: 'x' }], - ['title empty', { snapshot: { ...SNAPSHOT, title: '' } }], - ['title not a string', { snapshot: { ...SNAPSHOT, title: 5 } }], - ['description empty', { snapshot: { ...SNAPSHOT, description: '' } }], - ['mediaSubtype empty', { snapshot: { ...SNAPSHOT, mediaSubtype: '' } }], - ['sizeBytes not a number', { snapshot: { ...SNAPSHOT, sizeBytes: 'big' } }], - ['sizeBytes negative', { snapshot: { ...SNAPSHOT, sizeBytes: -1 } }], - ['sizeBytes NaN', { snapshot: { ...SNAPSHOT, sizeBytes: Number.NaN } }], - ['sizeBytes Infinity', { snapshot: { ...SNAPSHOT, sizeBytes: Number.POSITIVE_INFINITY } }] - ])('%s drops that entry but keeps its neighbour', (_label, over) => { - const parsed = parseRemoteStarterTemplates( - doc([entry({ id: 'bad_one', ...over }), entry({ id: 'good_one' })]) - ) - expect( - parsed?.map((t) => t.id), - 'only the valid neighbour survives' - ).toEqual(['good_one']) - }) - - it.each([ - ['a missing id', { id: undefined }], - ['a missing modality', { modality: undefined }], - ['a missing snapshot', { snapshot: undefined }] - ])('%s drops that entry but keeps its neighbour', (_label, over) => { - const bad = entry() - delete bad[Object.keys(over)[0]!] - const parsed = parseRemoteStarterTemplates(doc([bad, entry({ id: 'good_one' })])) - expect(parsed?.map((t) => t.id)).toEqual(['good_one']) - }) - - it.each([ - ['a null entry', null], - ['a string entry', 'nope'], - ['a number entry', 7] - ])('%s drops alone', (_label, bad) => { - const parsed = parseRemoteStarterTemplates(doc([bad, entry({ id: 'good_one' })])) - expect(parsed?.map((t) => t.id)).toEqual(['good_one']) - }) - - it('drops a duplicate id, keeping the first occurrence', () => { - const parsed = parseRemoteStarterTemplates( - doc([entry({ id: 'dup', snapshot: { ...SNAPSHOT, title: 'first' } }), entry({ id: 'dup' })]) - ) - expect(parsed).toHaveLength(1) - expect(parsed![0]!.snapshot.title, 'the first occurrence wins').toBe('first') - }) - - it('keeps a zero sizeBytes, which is how an API-node card is spelled', () => { - const parsed = parseRemoteStarterTemplates( - doc([entry({ apiNode: true, snapshot: { ...SNAPSHOT, sizeBytes: 0 } })]) - ) - expect(parsed).toHaveLength(1) - }) -}) - -describe('C. composition rules survive a hostile document', () => { - it('leaves exactly one auto-pick per tab when the document flags several', () => { - const remote = parseRemoteStarterTemplates( - doc([ - entry({ id: 'a', recommended: true }), - entry({ id: 'b', recommended: true }), - entry({ id: 'c', recommended: true }) - ]) - ) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - expect( - image.filter((t) => t.recommended), - 'the resolved slots are where this rule is enforced' - ).toHaveLength(1) - expect(image.find((t) => t.recommended)!.id, 'document order breaks the tie').toBe('a') - }) - - it('drops a card claiming to be both paid and recommended', () => { - const parsed = parseRemoteStarterTemplates( - doc([entry({ id: 'paid', apiNode: true, recommended: true }), entry({ id: 'ok' })]) - ) - expect( - parsed?.map((t) => t.id), - 'contradictory under our own invariant, so dropped not rewritten' - ).toEqual(['ok']) - }) - - it.each([ - ['a string', 'true'], - ['a number', 1], - ['null', null], - ['an object', {}] - ])('drops an entry whose apiNode is %s rather than a boolean', (_label, apiNode) => { - const parsed = parseRemoteStarterTemplates( - doc([entry({ id: 'bad', apiNode }), entry({ id: 'ok' })]) - ) - expect( - parsed?.map((t) => t.id), - 'a truthy-but-not-true flag would offer a paid card as free' - ).toEqual(['ok']) - }) - - it.each([ - ['a string', 'true'], - ['a number', 1], - ['null', null] - ])('drops an entry whose recommended is %s rather than a boolean', (_label, recommended) => { - const parsed = parseRemoteStarterTemplates( - doc([entry({ id: 'bad', recommended }), entry({ id: 'ok' })]) - ) - expect(parsed?.map((t) => t.id)).toEqual(['ok']) - }) - - it('never lets non-boolean flags smuggle a paid card into the auto-pick', () => { - const remote = parseRemoteStarterTemplates( - doc([entry({ id: 'sneaky', apiNode: 'true', recommended: 'true' })]) - ) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - expect( - image.find((c) => c.id === 'sneaky'), - 'the malformed row never renders' - ).toBeUndefined() - expect(image.find((c) => c.recommended)!.apiNode, 'the auto-pick stays free').toBeFalsy() - }) - - it('keeps a paid card that makes no claim to the badge', () => { - const parsed = parseRemoteStarterTemplates(doc([entry({ id: 'paid', apiNode: true })])) - expect(parsed![0]!.apiNode).toBe(true) - expect(parsed![0]!.recommended).toBeUndefined() - }) - - it('allows one recommended per modality independently', () => { - const remote = parseRemoteStarterTemplates( - doc([ - entry({ id: 'i', modality: 'image', recommended: true }), - entry({ id: 'v', modality: 'video', recommended: true }) - ]) - ) - const resolved = resolveStarterTemplates(remote) - expect(resolved.find((t) => t.modality === 'image' && t.recommended)!.id).toBe('i') - expect(resolved.find((t) => t.modality === 'video' && t.recommended)!.id).toBe('v') - }) -}) - -describe('D. the hardcoded list is the floor', () => { - it('fills every modality to four when there is no remote list', () => { - const resolved = resolveStarterTemplates(null) - for (const modality of TEMPLATE_MODALITY_ORDER) { - expect( - resolved.filter((t) => t.modality === modality), - modality - ).toHaveLength(4) - } - }) - - it('keeps three good remote entries and backfills the fourth slot', () => { - const remote = parseRemoteStarterTemplates( - doc([ - entry({ id: 'r1', modality: 'image' }), - entry({ id: 'r2', modality: 'image' }), - entry({ id: 'r3', modality: 'image' }), - entry({ id: 'bad', modality: 'nope' }) - ]) - ) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - expect(image.map((t) => t.id).slice(0, 3), 'remote entries lead').toEqual(['r1', 'r2', 'r3']) - expect(image, 'the broken slot is backfilled').toHaveLength(4) - expect(bakedIds('image'), 'the fourth comes from the hardcoded list').toContain(image[3]!.id) - }) - - it('shows only remote cards when a modality is fully specified', () => { - const ids = ['r1', 'r2', 'r3', 'r4'] - const remote = parseRemoteStarterTemplates( - doc(ids.map((id) => entry({ id, modality: 'image' }))) - ) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - expect( - image.map((t) => t.id), - 'no hardcoded card leaks in' - ).toEqual(ids) - }) - - it('caps a modality at four even when the document sends more', () => { - const remote = parseRemoteStarterTemplates( - doc(Array.from({ length: 9 }, (_, i) => entry({ id: `r${i}`, modality: 'image' }))) - ) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - expect(image).toHaveLength(4) - expect(image.map((t) => t.id)).toEqual(['r0', 'r1', 'r2', 'r3']) - }) - - it('backfills untouched modalities entirely from the hardcoded list', () => { - const remote = parseRemoteStarterTemplates(doc([entry({ id: 'r1', modality: 'image' })])) - const resolved = resolveStarterTemplates(remote) - for (const modality of TEMPLATE_MODALITY_ORDER.filter((m) => m !== 'image')) { - expect( - resolved.filter((t) => t.modality === modality).map((t) => t.id), - modality - ).toEqual(bakedIds(modality)) - } - }) - - it('never repeats an id a remote entry already claimed', () => { - const taken = bakedIds('image')[1]! - const remote = parseRemoteStarterTemplates(doc([entry({ id: taken, modality: 'image' })])) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - expect(new Set(image.map((t) => t.id)).size, 'ids collide on the picker option key').toBe( - image.length - ) - expect(image, 'a uniqueness check alone would pass on a short tab').toHaveLength(4) - }) - - it('holds every invariant across all four tabs at once', () => { - const resolved = resolveStarterTemplates( - parseRemoteStarterTemplates(doc([entry({ id: 'solo', modality: 'audio' })])) - ) - for (const modality of TEMPLATE_MODALITY_ORDER) { - const cards = resolved.filter((t) => t.modality === modality) - expect(cards, `${modality} card count`).toHaveLength(4) - expect( - cards.filter((c) => c.recommended).length, - `${modality} auto-picks` - ).toBeLessThanOrEqual(1) - expect( - cards.filter((c) => c.recommended && c.apiNode), - `${modality} paid auto-pick` - ).toEqual([]) - } - expect(new Set(resolved.map((t) => t.id)).size, 'catalog-wide id uniqueness').toBe( - resolved.length - ) - }) - - it('gives a tab with no free card no recommendation at all', () => { - const remote = parseRemoteStarterTemplates( - doc( - Array.from({ length: 4 }, (_, i) => - entry({ id: `paid${i}`, modality: 'image', apiNode: true }) - ) - ) - ) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - expect( - image.filter((c) => c.recommended), - 'the wizard offers skip instead' - ).toEqual([]) - }) - - it('promotes a free card when the document names no recommendation', () => { - const remote = parseRemoteStarterTemplates( - doc(['a', 'b', 'c', 'd'].map((id) => entry({ id, modality: 'image' }))) - ) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - expect(image.filter((c) => c.recommended)).toHaveLength(1) - expect(image.find((c) => c.recommended)!.apiNode).toBeFalsy() - }) - - it('keeps the tab order the picker renders in', () => { - const resolved = resolveStarterTemplates(null) - const seen = resolved.map((t) => t.modality).filter((m, i, a) => m !== a[i - 1]) - expect(seen).toEqual([...TEMPLATE_MODALITY_ORDER]) - }) -}) - -describe('F. a remote document cannot starve or hijack a tab', () => { - it('cannot drain a tab by filing its built-in ids under another modality', () => { - const imageIds = bakedIds('image') - const remote = parseRemoteStarterTemplates( - doc(imageIds.map((id) => entry({ id, modality: 'video' }))) - ) - const resolved = resolveStarterTemplates(remote) - for (const modality of TEMPLATE_MODALITY_ORDER) { - expect( - resolved.filter((t) => t.modality === modality), - `${modality} must keep its four cards` - ).toHaveLength(4) - } - }) - - it('ignores a single built-in id filed under the wrong tab', () => { - const stolen = bakedIds('image')[0]! - const remote = parseRemoteStarterTemplates(doc([entry({ id: stolen, modality: 'video' })])) - const resolved = resolveStarterTemplates(remote) - expect( - resolved.filter((t) => t.modality === 'image'), - 'the image tab keeps its own card' - ).toHaveLength(4) - expect( - resolved.find((t) => t.id === stolen)!.modality, - 'the id stays on the tab it belongs to' - ).toBe('image') - }) - - it('keeps the badge on a remote card when the tab is partly backfilled', () => { - const remote = parseRemoteStarterTemplates( - doc(['r1', 'r2', 'r3'].map((id) => entry({ id, modality: 'image' }))) - ) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - const winner = image.find((c) => c.recommended) - expect(winner, 'a tab with a free card always has an auto-pick').toBeDefined() - expect( - ['r1', 'r2', 'r3'], - 'the backfilled card must not steal the badge content did not give it' - ).toContain(winner!.id) - }) - - it('honours the remote entry that does claim the badge', () => { - const remote = parseRemoteStarterTemplates( - doc([ - entry({ id: 'r1', modality: 'image' }), - entry({ id: 'r2', modality: 'image', recommended: true }) - ]) - ) - const image = resolveStarterTemplates(remote).filter((t) => t.modality === 'image') - expect(image.find((c) => c.recommended)!.id).toBe('r2') - }) -}) - -describe('G. an oversized or hostile document cannot cost more than it should', () => { - it('stops reading long past the point where every slot could be filled', () => { - const huge = Array.from({ length: 5000 }, (_, i) => entry({ id: `r${i}`, modality: 'image' })) - const parsed = parseRemoteStarterTemplates(doc(huge)) - expect(parsed!.length, 'parsing stops at the MAX_ENTRIES cap').toBe(256) - }) - - it.each([ - ['an absurd magnitude', 1.5e300], - ['past the cap', 3 * 1024 ** 4], - ['a fractional byte count', 1.5] - ])('rejects a sizeBytes that is %s', (_label, sizeBytes) => { - const parsed = parseRemoteStarterTemplates( - doc([entry({ id: 'bad', snapshot: { ...SNAPSHOT, sizeBytes } }), entry({ id: 'ok' })]) - ) - expect( - parsed?.map((t) => t.id), - 'this value drives the install-time disk-space gate' - ).toEqual(['ok']) - }) - - it.each([ - ['a blank title', { title: ' ' }], - ['a newline-only description', { description: '\n\n' }], - ['a blank mediaSubtype', { mediaSubtype: ' ' }] - ])('rejects %s that would render as an empty card', (_label, over) => { - const parsed = parseRemoteStarterTemplates( - doc([entry({ id: 'blank', snapshot: { ...SNAPSHOT, ...over } }), entry({ id: 'ok' })]) - ) - expect(parsed?.map((t) => t.id)).toEqual(['ok']) - }) - - it('trims surrounding whitespace rather than rendering it', () => { - const parsed = parseRemoteStarterTemplates( - doc([entry({ snapshot: { ...SNAPSHOT, title: ' Padded ' } })]) - ) - expect(parsed![0]!.snapshot.title).toBe('Padded') - }) - - it.each([['.'], ['..']])('rejects %s, a directory rather than a template', (id) => { - const parsed = parseRemoteStarterTemplates(doc([entry({ id }), entry({ id: 'ok' })])) - expect( - parsed?.map((t) => t.id), - 'a path segment must never reach a URL or a file path' - ).toEqual(['ok']) - }) - - it('rejects the skip sentinel smuggled in as an id', () => { - const parsed = parseRemoteStarterTemplates(doc([entry({ id: 'none' }), entry({ id: 'ok' })])) - expect( - parsed?.map((t) => t.id), - 'the sentinel drops while its valid neighbour survives' - ).toEqual(['ok']) - }) -}) - -describe('E. the network is never trusted to behave', () => { - beforeEach(() => { - mockedFetchJSON.mockReset() - _resetStarterTemplatesForTest() - }) - - it('serves the remote list when the fetch succeeds', async () => { - mockedFetchJSON.mockResolvedValue(doc([entry({ id: 'r1', modality: 'image' })])) - const loaded = await loadStarterTemplates() - expect(loaded.find((t) => t.id === 'r1')).toBeDefined() - }) - - it.each([ - ['the request rejects', () => Promise.reject(new Error('offline'))], - ['the body is garbage', () => Promise.resolve('502')], - ['the body is null', () => Promise.resolve(null)] - ])('falls back to the hardcoded list when %s', async (_label, impl) => { - mockedFetchJSON.mockImplementation(impl) - const loaded = await loadStarterTemplates() - expect([...loaded].map((t) => t.id).sort(), 'every built-in card, and nothing else').toEqual( - [...CURATED_TEMPLATES].map((t) => t.id).sort() - ) - }) - - it('is cleared by the catalog reset, so fetch counts stay order-independent', async () => { - const { resetTemplateCatalogCache } = await import('./templateCatalog') - mockedFetchJSON.mockResolvedValue(doc([entry()])) - await loadStarterTemplates() - resetTemplateCatalogCache() - await loadStarterTemplates() - expect( - mockedFetchJSON, - 'a half-cleared cache makes suites order-dependent' - ).toHaveBeenCalledTimes(2) - }) - - it('fetches once per process, not once per picker open', async () => { - mockedFetchJSON.mockResolvedValue(doc([entry({ id: 'r1', modality: 'image' })])) - await Promise.all([loadStarterTemplates(), loadStarterTemplates()]) - await loadStarterTemplates() - expect(mockedFetchJSON, 'a content change lands on the next boot').toHaveBeenCalledTimes(1) - }) - - it('reads from R2, bypassing any stale cached copy', async () => { - mockedFetchJSON.mockResolvedValue(doc([entry()])) - await loadStarterTemplates() - const [url, opts] = mockedFetchJSON.mock.calls[0] as [string, Record] - expect(url).toBe(STARTER_TEMPLATES_URL) - expect(opts, 'a stale ETag would strand users on withdrawn content').toMatchObject({ - refresh: true - }) - }) - - it('always returns a full picker, whatever the document says', async () => { - mockedFetchJSON.mockResolvedValue(doc([entry({ id: 'r1', modality: 'image' })])) - const loaded = await loadStarterTemplates() - expect(loaded, 'four cards in each of four tabs').toHaveLength( - TEMPLATE_MODALITY_ORDER.length * 4 - ) - for (const modality of TEMPLATE_MODALITY_ORDER) { - expect( - loaded.filter((t) => t.modality === modality), - modality - ).toHaveLength(4) - } - }) - - it('falls back rather than hanging when the fetch never settles', async () => { - vi.useFakeTimers() - try { - mockedFetchJSON.mockImplementation(() => new Promise(() => {})) - const pending = loadStarterTemplates() - await vi.advanceTimersByTimeAsync(10_000) - const loaded = await pending - expect( - loaded.map((t) => t.id).sort(), - 'a stalled read must not leave the picker rendering nothing' - ).toEqual([...CURATED_TEMPLATES].map((t) => t.id).sort()) - } finally { - vi.useRealTimers() - } - }) - - it('never rejects, whatever the network does', async () => { - mockedFetchJSON.mockImplementation(() => Promise.reject(new Error('boom'))) - await expect(loadStarterTemplates()).resolves.toBeDefined() - }) -}) diff --git a/src/main/sources/standalone/remoteStarterTemplates.ts b/src/main/sources/standalone/remoteStarterTemplates.ts deleted file mode 100644 index 5ff2841a4..000000000 --- a/src/main/sources/standalone/remoteStarterTemplates.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { fetchJSON } from '../../lib/fetch' -import { R2_BASE_URL } from '../../lib/r2Mirror' -import { - CURATED_TEMPLATES, - TEMPLATE_MODALITY_ORDER, - isPersistableTemplateId, - type CuratedTemplate, - type TemplateModality, - type TemplateSnapshot -} from './curatedTemplates' - -export const STARTER_TEMPLATES_URL = `${R2_BASE_URL}/starter-templates.json` - -const SCHEMA_VERSION = 1 -const SLOTS_PER_MODALITY = 4 -const MAX_ID_LENGTH = 128 -const MAX_TEXT_LENGTH = 4096 -const MAX_SIZE_BYTES = 2 * 1024 ** 4 -const MAX_ENTRIES = 256 -const FETCH_TIMEOUT_MS = 5000 - -function isOptionalBoolean(value: unknown): boolean { - return value === undefined || typeof value === 'boolean' -} - -function isModality(value: unknown): value is TemplateModality { - return typeof value === 'string' && (TEMPLATE_MODALITY_ORDER as readonly string[]).includes(value) -} - -function safeText(value: unknown): string | null { - if (typeof value !== 'string' || value.length > MAX_TEXT_LENGTH) return null - const trimmed = value.trim() - return trimmed || null -} - -function parseSnapshot(value: unknown): TemplateSnapshot | null { - if (!value || typeof value !== 'object' || Array.isArray(value)) return null - const r = value as Record - const title = safeText(r.title) - const description = safeText(r.description) - const mediaSubtype = safeText(r.mediaSubtype) - if (!title || !description || !mediaSubtype) return null - const { sizeBytes } = r - if (!Number.isInteger(sizeBytes) || (sizeBytes as number) < 0) return null - if ((sizeBytes as number) > MAX_SIZE_BYTES) return null - return { title, description, sizeBytes: sizeBytes as number, mediaSubtype } -} - -function parseEntry(value: unknown): CuratedTemplate | null { - if (!value || typeof value !== 'object' || Array.isArray(value)) return null - const r = value as Record - - const { id } = r - if (!isPersistableTemplateId(id) || id.length > MAX_ID_LENGTH) return null - if (!isModality(r.modality)) return null - - const snapshot = parseSnapshot(r.snapshot) - if (!snapshot) return null - - if (!isOptionalBoolean(r.apiNode) || !isOptionalBoolean(r.recommended)) return null - - const base = { id, modality: r.modality, snapshot } - if (r.apiNode === true) { - if (r.recommended === true) return null - return { ...base, apiNode: true } - } - return { ...base, ...(r.recommended === true ? { recommended: true as const } : {}) } -} - -export function parseRemoteStarterTemplates(raw: unknown): CuratedTemplate[] | null { - let data = raw - if (typeof data === 'string') { - try { - data = JSON.parse(data) - } catch { - return null - } - } - if (!data || typeof data !== 'object' || Array.isArray(data)) return null - - const payload = data as Record - if (payload.schemaVersion !== SCHEMA_VERSION) return null - if (!Array.isArray(payload.templates)) return null - - const seen = new Set() - const entries: CuratedTemplate[] = [] - for (const value of payload.templates.slice(0, MAX_ENTRIES)) { - const entry = parseEntry(value) - if (!entry || seen.has(entry.id)) continue - seen.add(entry.id) - entries.push(entry) - } - return entries.length > 0 ? entries : null -} - -function enforceOneRecommended(cards: CuratedTemplate[], fromRemote: number): CuratedTemplate[] { - const preferred = fromRemote > 0 ? cards.slice(0, fromRemote) : cards - const free = (c: CuratedTemplate): boolean => c.apiNode !== true - const winner = - preferred.find((c) => c.recommended === true && free(c)) ?? - preferred.find(free) ?? - cards.find(free) - - return cards.map((card) => { - if (card.apiNode === true) return card - const { recommended: _drop, ...base } = card - return card === winner ? { ...base, recommended: true } : base - }) -} - -const BUILT_IN_MODALITY = new Map(CURATED_TEMPLATES.map((t) => [t.id, t.modality])) - -export function resolveStarterTemplates( - remote: readonly CuratedTemplate[] | null -): CuratedTemplate[] { - const eligible = remote?.filter((entry) => { - const builtIn = BUILT_IN_MODALITY.get(entry.id) - return builtIn === undefined || builtIn === entry.modality - }) - - const used = new Set() - const resolved: CuratedTemplate[] = [] - - for (const modality of TEMPLATE_MODALITY_ORDER) { - const slots: CuratedTemplate[] = [] - let fromRemote = 0 - - const take = (candidates: readonly CuratedTemplate[]): void => { - for (const candidate of candidates) { - if (slots.length >= SLOTS_PER_MODALITY) break - if (candidate.modality !== modality || used.has(candidate.id)) continue - used.add(candidate.id) - slots.push(candidate) - } - } - - if (eligible) { - take(eligible) - fromRemote = slots.length - } - take(CURATED_TEMPLATES) - - resolved.push(...enforceOneRecommended(slots, fromRemote)) - } - return resolved -} - -let inFlight: Promise | null = null - -export function loadStarterTemplates(): Promise { - inFlight ??= Promise.race([ - fetchJSON(STARTER_TEMPLATES_URL, { refresh: true }), - new Promise((_resolve, reject) => { - setTimeout( - () => reject(new Error('starter-templates fetch timed out')), - FETCH_TIMEOUT_MS - ).unref?.() - }) - ]) - .then((raw) => resolveStarterTemplates(parseRemoteStarterTemplates(raw))) - .catch(() => resolveStarterTemplates(null)) - return inFlight -} - -export function _resetStarterTemplatesForTest(): void { - inFlight = null -} diff --git a/src/main/sources/standalone/templateCatalog.test.ts b/src/main/sources/standalone/templateCatalog.test.ts index f61511dd3..7583f44bc 100644 --- a/src/main/sources/standalone/templateCatalog.test.ts +++ b/src/main/sources/standalone/templateCatalog.test.ts @@ -2,14 +2,29 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' vi.mock('../../lib/fetch', () => ({ fetchJSON: vi.fn() })) -import { loadTemplateCatalog, resetTemplateCatalogCache } from './templateCatalog' -import { CURATED_TEMPLATES, TEMPLATE_MODALITY_ORDER, thumbnailUrlFor } from './curatedTemplates' +import { hydrateTemplates } from './templateCatalog' +import { thumbnailUrlFor, type TemplateModality } from './curatedTemplates' import { fetchJSON } from '../../lib/fetch' const mockedFetchJSON = vi.mocked(fetchJSON) -const indexFetches = (): number => - mockedFetchJSON.mock.calls.filter(([url]) => String(url).includes('index.json')).length +type ExampleTemplate = Parameters[0][number] + +const IMAGE: ExampleTemplate = { + id: 'image_example', + modality: 'image', + recommended: true, + snapshot: { + title: 'Snapshot Title', + description: 'Snapshot description', + sizeBytes: 1234, + mediaSubtype: 'webp' + } +} + +function example(id: string, modality: TemplateModality): ExampleTemplate { + return { id, modality, snapshot: { ...IMAGE.snapshot } } +} function indexFor(overrides: Record>, category = 'Image'): unknown { return [ @@ -20,31 +35,34 @@ function indexFor(overrides: Record>, category = ] } -describe('loadTemplateCatalog', () => { +async function hydrateOne( + template: ExampleTemplate, + index: unknown +): Promise>[number]> { + mockedFetchJSON.mockResolvedValue(index) + const [card] = await hydrateTemplates([template]) + return card! +} + +describe('hydrateTemplates', () => { beforeEach(() => { mockedFetchJSON.mockReset() - resetTemplateCatalogCache() }) - it('returns every curated template, ordered by modality', async () => { + it('returns one card per template, in the order given', async () => { mockedFetchJSON.mockResolvedValue([]) - const catalog = await loadTemplateCatalog() - expect(catalog.length).toBe(CURATED_TEMPLATES.length) - - const rank = (m: string) => TEMPLATE_MODALITY_ORDER.indexOf(m as never) - for (let i = 1; i < catalog.length; i++) { - expect(rank(catalog[i]!.modality)).toBeGreaterThanOrEqual(rank(catalog[i - 1]!.modality)) - } + const cards = await hydrateTemplates([example('b_video', 'video'), IMAGE]) + expect(cards.map((card) => card.id)).toEqual(['b_video', 'image_example']) + expect(cards.map((card) => card.recommended)).toEqual([false, true]) }) it('prefers live index metadata over the offline snapshot', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue( + const card = await hydrateOne( + IMAGE, indexFor({ - [first.id]: { title: 'Live', description: 'LiveDesc', size: 42, mediaSubtype: 'webp' } + [IMAGE.id]: { title: 'Live', description: 'LiveDesc', size: 42, mediaSubtype: 'webp' } }) ) - const card = (await loadTemplateCatalog()).find((c) => c.id === first.id)! expect(card.title).toBe('Live') expect(card.description).toBe('LiveDesc') expect(card.sizeBytes).toBe(42) @@ -52,270 +70,95 @@ describe('loadTemplateCatalog', () => { }) it('derives a short name + task from the title and tags', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue( + const card = await hydrateOne( + IMAGE, indexFor({ - [first.id]: { title: 'Z-Image-Turbo Text to Image', tags: ['Image', 'Text to Image'] } + [IMAGE.id]: { title: 'Z-Image-Turbo Text to Image', tags: ['Image', 'Text to Image'] } }) ) - const card = (await loadTemplateCatalog()).find((c) => c.id === first.id)! expect(card.name).toBe('Z-Image-Turbo') expect(card.task).toBe('Text to Image') }) it('splits a colon title and skips the bare modality tag for the task', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue( + const card = await hydrateOne( + IMAGE, indexFor({ - [first.id]: { + [IMAGE.id]: { title: 'Flux.2 [Klein] 4B Distilled: Image Edit', tags: ['Image', 'Image Edit'] } }) ) - const card = (await loadTemplateCatalog()).find((c) => c.id === first.id)! expect(card.name).toBe('Flux.2 [Klein] 4B Distilled') expect(card.task).toBe('Image Edit') }) it('falls back to a modality-default task when no task tag is present', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue( - indexFor({ [first.id]: { title: 'SDXL Turbo', tags: ['Image'] } }) + const card = await hydrateOne( + IMAGE, + indexFor({ [IMAGE.id]: { title: 'SDXL Turbo', tags: ['Image'] } }) ) - const card = (await loadTemplateCatalog()).find((c) => c.id === first.id)! expect(card.name).toBe('SDXL Turbo') expect(card.task).toBe('Text to Image') }) it('ignores blank/whitespace tags and uses the modality default', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue( - indexFor({ [first.id]: { title: 'X', tags: ['', ' ', 'Image'] } }) + const card = await hydrateOne( + IMAGE, + indexFor({ [IMAGE.id]: { title: 'X', tags: ['', ' ', 'Image'] } }) ) - const card = (await loadTemplateCatalog()).find((c) => c.id === first.id)! expect(card.task).toBe('Text to Image') }) - it('skips the API tag so an API-node card is not subtitled "API"', async () => { - const apiTemplate = CURATED_TEMPLATES.find((t) => t.apiNode)! - mockedFetchJSON.mockResolvedValue( + it('skips the API tag so a card is not subtitled "API"', async () => { + const card = await hydrateOne( + IMAGE, indexFor({ - [apiTemplate.id]: { title: 'Seedream 5.0 Pro: Image Edit', tags: ['API', 'Image Edit'] } + [IMAGE.id]: { title: 'Seedream 5.0 Pro: Image Edit', tags: ['API', 'Image Edit'] } }) ) - const card = (await loadTemplateCatalog()).find((c) => c.id === apiTemplate.id)! expect(card.task).toBe('Image Edit') expect(card.name).toBe('Seedream 5.0 Pro') }) it('treats "3D Model" as a kind, not a task', async () => { - const apiTemplate = CURATED_TEMPLATES.find((t) => t.apiNode && t.modality === '3d')! - mockedFetchJSON.mockResolvedValue( + const card = await hydrateOne( + example('3d_example', '3d'), indexFor( - { [apiTemplate.id]: { title: 'Tripo H3.1: Image to Model', tags: ['3D Model', 'API'] } }, + { '3d_example': { title: 'Tripo H3.1: Image to Model', tags: ['3D Model', 'API'] } }, '3D Model' ) ) - const card = (await loadTemplateCatalog()).find((c) => c.id === apiTemplate.id)! expect(card.task).toBe('Image to 3D') }) - it('flags API-node templates from the manifest, offline included', async () => { - mockedFetchJSON.mockImplementation((url: string) => - String(url).includes('index.json') - ? Promise.reject(new Error('offline')) - : Promise.resolve(null) - ) - const catalog = await loadTemplateCatalog() - for (const curated of CURATED_TEMPLATES) { - expect(catalog.find((c) => c.id === curated.id)!.apiNode, curated.id).toBe( - curated.apiNode === true - ) - } - }) - - it('does not infer API-node status from a closed-source index flag', async () => { - const local = CURATED_TEMPLATES.find((t) => !t.apiNode)! - mockedFetchJSON.mockResolvedValue( - indexFor({ [local.id]: { openSource: false, size: 142_000_000_000 } }) - ) - const card = (await loadTemplateCatalog()).find((c) => c.id === local.id)! - expect(card.apiNode).toBe(false) - expect(card.sizeBytes).toBe(142_000_000_000) - }) - - it('falls back to the snapshot when the index omits a curated id', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue([]) - const card = (await loadTemplateCatalog()).find((c) => c.id === first.id)! - expect(card.title).toBe(first.snapshot.title) - expect(card.sizeBytes).toBe(first.snapshot.sizeBytes) - expect(card.thumbnailUrl).toBe(thumbnailUrlFor(first.id, first.snapshot.mediaSubtype)) + it('falls back to the snapshot when the index omits the id', async () => { + const card = await hydrateOne(IMAGE, []) + expect(card.title).toBe(IMAGE.snapshot.title) + expect(card.sizeBytes).toBe(IMAGE.snapshot.sizeBytes) + expect(card.thumbnailUrl).toBe(thumbnailUrlFor(IMAGE.id, IMAGE.snapshot.mediaSubtype)) }) it('ignores a live size of 0 and keeps the snapshot estimate', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue(indexFor({ [first.id]: { size: 0 } })) - const card = (await loadTemplateCatalog()).find((c) => c.id === first.id)! - expect(card.sizeBytes).toBe(first.snapshot.sizeBytes) + const card = await hydrateOne(IMAGE, indexFor({ [IMAGE.id]: { size: 0 } })) + expect(card.sizeBytes).toBe(IMAGE.snapshot.sizeBytes) }) - it('returns a snapshot-only catalog when the fetch rejects (offline)', async () => { - mockedFetchJSON.mockImplementation((url: string) => - String(url).includes('index.json') - ? Promise.reject(new Error('offline')) - : Promise.resolve(null) - ) - const catalog = await loadTemplateCatalog() - expect(catalog.length).toBe(CURATED_TEMPLATES.length) - const first = CURATED_TEMPLATES[0]! - expect(catalog.find((c) => c.id === first.id)!.title).toBe(first.snapshot.title) + it('returns snapshot-only cards when the index fetch rejects (offline)', async () => { + mockedFetchJSON.mockRejectedValue(new Error('offline')) + const [card] = await hydrateTemplates([IMAGE]) + expect(card!.title).toBe(IMAGE.snapshot.title) }) it('survives a malformed index without throwing', async () => { - mockedFetchJSON.mockResolvedValue({ not: 'an array' }) - const catalog = await loadTemplateCatalog() - expect(catalog.length).toBe(CURATED_TEMPLATES.length) + const card = await hydrateOne(IMAGE, { not: 'an array' }) + expect(card.title).toBe(IMAGE.snapshot.title) }) - it('fetches the index exactly once regardless of curated count', async () => { + it('fetches the index exactly once regardless of template count', async () => { mockedFetchJSON.mockResolvedValue([]) - await loadTemplateCatalog() - expect(indexFetches()).toBe(1) - }) - - const imageCategory = (templates: Array>): unknown => [ - { title: 'Image', type: 'image', templates } - ] - - it('substitutes a live same-modality template when a curated id has vanished', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue( - imageCategory([ - { - name: 'fresh_image_model', - title: 'Fresh Model', - size: 5, - tags: ['Image', 'Text to Image'] - } - ]) - ) - const catalog = await loadTemplateCatalog() - const recImage = catalog.find((c) => c.modality === 'image' && c.recommended)! - expect(recImage.id).toBe('fresh_image_model') - expect(recImage.name).toBe('Fresh Model') - expect(catalog.some((c) => c.id === first.id)).toBe(false) - }) - - it('skips api/size-less candidates when substituting (must be locally installable)', async () => { - mockedFetchJSON.mockResolvedValue( - imageCategory([ - { name: 'api_cloud_thing', title: 'Cloud', size: 5 }, - { name: 'no_size_model', title: 'No Size' }, - { name: 'good_local', title: 'Good Local', size: 9 } - ]) - ) - const recImage = (await loadTemplateCatalog()).find( - (c) => c.modality === 'image' && c.recommended - )! - expect(recImage.id).toBe('good_local') - }) - - it('gives distinct substitutes when several ids in a modality vanish', async () => { - mockedFetchJSON.mockResolvedValue( - imageCategory([ - { name: 'sub_a', title: 'A', size: 1 }, - { name: 'sub_b', title: 'B', size: 2 }, - { name: 'sub_c', title: 'C', size: 3 }, - { name: 'sub_d', title: 'D', size: 4 } - ]) - ) - const images = (await loadTemplateCatalog()).filter((c) => c.modality === 'image') - const ids = images.map((c) => c.id) - expect(new Set(ids).size).toBe(ids.length) - }) - - it('falls back to the snapshot when online but no substitute exists', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue( - imageCategory([{ name: 'api_only', title: 'Cloud', size: 0 }]) - ) - const catalog = await loadTemplateCatalog() - expect(catalog.find((c) => c.id === first.id)!.title).toBe(first.snapshot.title) - }) - - it('never substitutes a local download into a vanished API-node slot', async () => { - const apiTemplate = CURATED_TEMPLATES.find((t) => t.apiNode && t.modality === 'image')! - mockedFetchJSON.mockResolvedValue( - imageCategory([ - { name: 'sub_a', title: 'A', size: 1 }, - { name: 'sub_b', title: 'B', size: 2 }, - { name: 'sub_c', title: 'C', size: 3 }, - { name: 'sub_d', title: 'D', size: 4 } - ]) - ) - const catalog = await loadTemplateCatalog() - const card = catalog.find((c) => c.id === apiTemplate.id) - expect(card, 'API-node slot kept its snapshot').toBeDefined() - expect(card!.apiNode).toBe(true) - expect(card!.sizeBytes).toBe(0) - expect( - catalog.some((c) => c.id === 'sub_d'), - 'no local substitute took the slot' - ).toBe(false) - }) - - it('keeps the curated snapshot card when offline (empty index → no substitution)', async () => { - const first = CURATED_TEMPLATES[0]! - mockedFetchJSON.mockResolvedValue([]) - const catalog = await loadTemplateCatalog() - expect(catalog.length).toBe(CURATED_TEMPLATES.length) - expect(catalog.find((c) => c.id === first.id)!.title).toBe(first.snapshot.title) - }) - - it('never yields duplicate ids', async () => { - mockedFetchJSON.mockResolvedValue([]) - const ids = (await loadTemplateCatalog()).map((c) => c.id) - expect(new Set(ids).size).toBe(ids.length) - }) - - it('only emits modalities the picker can tab', async () => { - mockedFetchJSON.mockResolvedValue([]) - const catalog = await loadTemplateCatalog() - for (const card of catalog) { - expect(TEMPLATE_MODALITY_ORDER).toContain(card.modality) - } - }) - - it('coalesces concurrent reads into a single index fetch', async () => { - mockedFetchJSON.mockResolvedValue([]) - const [a, b] = await Promise.all([loadTemplateCatalog(), loadTemplateCatalog()]) - expect(indexFetches()).toBe(1) - expect(a).toBe(b) - }) - - it('serves a cached result on a follow-up read, then refetches after reset', async () => { - mockedFetchJSON.mockResolvedValue([]) - await loadTemplateCatalog() - await loadTemplateCatalog() - expect(indexFetches()).toBe(1) - - resetTemplateCatalogCache() - await loadTemplateCatalog() - expect(indexFetches()).toBe(2) - }) - - it('refetches once the TTL lapses', async () => { - vi.useFakeTimers() - try { - mockedFetchJSON.mockResolvedValue([]) - await loadTemplateCatalog() - vi.advanceTimersByTime(60_001) - await loadTemplateCatalog() - expect(indexFetches()).toBe(2) - } finally { - vi.useRealTimers() - } + await hydrateTemplates([IMAGE, example('a', 'audio'), example('v', 'video')]) + expect(mockedFetchJSON).toHaveBeenCalledOnce() }) }) diff --git a/src/main/sources/standalone/templateCatalog.ts b/src/main/sources/standalone/templateCatalog.ts index bb588593f..df977067f 100644 --- a/src/main/sources/standalone/templateCatalog.ts +++ b/src/main/sources/standalone/templateCatalog.ts @@ -1,9 +1,7 @@ import { fetchJSON } from '../../lib/fetch' import type { FieldOption } from '../../types/sources' -import { loadStarterTemplates, _resetStarterTemplatesForTest } from './remoteStarterTemplates' import { INDEX_URL, - TEMPLATE_MODALITY_ORDER, thumbnailUrlFor, type TemplateModality, type TemplateSnapshot @@ -34,20 +32,12 @@ interface IndexEntry { interface IndexCategory { title?: unknown - type?: unknown templates?: unknown } interface IndexLocation { entry: IndexEntry category: string - modality: TemplateModality | null -} - -function modalityFromType(type: unknown): TemplateModality | null { - return typeof type === 'string' && (TEMPLATE_MODALITY_ORDER as readonly string[]).includes(type) - ? (type as TemplateModality) - : null } function indexById(index: unknown): Map { @@ -57,13 +47,12 @@ function indexById(index: unknown): Map { if (!rawCategory || typeof rawCategory !== 'object') continue const category = rawCategory as IndexCategory const categoryTitle = typeof category.title === 'string' ? category.title : '' - const modality = modalityFromType(category.type) if (!Array.isArray(category.templates)) continue for (const rawEntry of category.templates) { if (!rawEntry || typeof rawEntry !== 'object') continue const entry = rawEntry as IndexEntry if (typeof entry.name !== 'string' || byId.has(entry.name)) continue - byId.set(entry.name, { entry, category: categoryTitle, modality }) + byId.set(entry.name, { entry, category: categoryTitle }) } } return byId @@ -102,22 +91,19 @@ function hydrateOne(card: { id: string modality: TemplateModality recommended: boolean - apiNode: boolean location: IndexLocation | undefined - snapshot?: TemplateSnapshot + snapshot: TemplateSnapshot }): HydratedTemplate { - const { id, modality, recommended, apiNode, location, snapshot } = card + const { id, modality, recommended, location, snapshot } = card const entry = location?.entry - const title = typeof entry?.title === 'string' ? entry.title : (snapshot?.title ?? id) + const title = typeof entry?.title === 'string' ? entry.title : snapshot.title const description = - typeof entry?.description === 'string' ? entry.description : (snapshot?.description ?? '') + typeof entry?.description === 'string' ? entry.description : snapshot.description const sizeBytes = - typeof entry?.size === 'number' && entry.size > 0 ? entry.size : (snapshot?.sizeBytes ?? 0) + typeof entry?.size === 'number' && entry.size > 0 ? entry.size : snapshot.sizeBytes const mediaSubtype = - typeof entry?.mediaSubtype === 'string' - ? entry.mediaSubtype - : (snapshot?.mediaSubtype ?? 'webp') + typeof entry?.mediaSubtype === 'string' ? entry.mediaSubtype : snapshot.mediaSubtype const task = taskOf(entry?.tags, modality) @@ -130,92 +116,12 @@ function hydrateOne(card: { task, description, sizeBytes, - apiNode, + apiNode: false, thumbnailUrl: thumbnailUrlFor(id, mediaSubtype), category: location?.category ?? '' } } -function byModalityOrder(a: HydratedTemplate, b: HydratedTemplate): number { - return TEMPLATE_MODALITY_ORDER.indexOf(a.modality) - TEMPLATE_MODALITY_ORDER.indexOf(b.modality) -} - -const CATALOG_TTL_MS = 60_000 -let catalogInFlight: Promise | null = null -let catalogCache: { at: number; value: HydratedTemplate[] } | null = null - -export function loadTemplateCatalog(): Promise { - if (catalogCache && Date.now() - catalogCache.at < CATALOG_TTL_MS) { - return Promise.resolve(catalogCache.value) - } - if (catalogInFlight) return catalogInFlight - catalogInFlight = loadTemplateCatalogUncached() - .then((value) => { - catalogCache = { at: Date.now(), value } - return value - }) - .finally(() => { - catalogInFlight = null - }) - return catalogInFlight -} - -export function resetTemplateCatalogCache(): void { - catalogInFlight = null - catalogCache = null - _resetStarterTemplatesForTest() -} - -async function loadTemplateCatalogUncached(): Promise { - const [starterTemplates, index] = await Promise.all([ - loadStarterTemplates(), - fetchJSON(INDEX_URL).catch(() => null) - ]) - - const byId = index ? indexById(index) : new Map() - const online = byId.size > 0 - - const used = new Set() - const catalog: HydratedTemplate[] = [] - for (const curated of starterTemplates) { - if (!curated?.id || used.has(curated.id) || !curated.snapshot) continue - - const recommended = curated.recommended === true - const apiNode = curated.apiNode === true - - const { modality, snapshot } = curated - const location = byId.get(curated.id) - if (location || !online) { - used.add(curated.id) - catalog.push( - hydrateOne({ id: curated.id, modality, recommended, apiNode, location, snapshot }) - ) - continue - } - - const sub = apiNode ? null : firstUnusedOfModality(byId, modality, used) - if (sub) { - used.add(sub.entry.name) - catalog.push( - hydrateOne({ id: sub.entry.name, modality, recommended, apiNode: false, location: sub }) - ) - } else { - used.add(curated.id) - catalog.push( - hydrateOne({ - id: curated.id, - modality, - recommended, - apiNode, - location: undefined, - snapshot - }) - ) - } - } - return catalog.sort(byModalityOrder) -} - export function toTemplateFieldOption( template: HydratedTemplate, modelsPresent: boolean @@ -253,24 +159,8 @@ export async function hydrateTemplates( id, modality, recommended: recommended === true, - apiNode: false, location: byId.get(id), snapshot }) ) } - -function firstUnusedOfModality( - byId: Map, - modality: TemplateModality, - used: Set -): IndexLocation | null { - for (const location of byId.values()) { - const { entry } = location - if (location.modality !== modality || used.has(entry.name)) continue - if (entry.name.startsWith('api_')) continue - if (typeof entry.size !== 'number' || entry.size <= 0) continue - return location - } - return null -} diff --git a/src/main/sources/standalone/templateDownloadTask.test.ts b/src/main/sources/standalone/templateDownloadTask.test.ts index 44aa260fe..09f347d8a 100644 --- a/src/main/sources/standalone/templateDownloadTask.test.ts +++ b/src/main/sources/standalone/templateDownloadTask.test.ts @@ -1,12 +1,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const resolveTemplateModels = vi.fn<() => Promise>>>() +const resolveTemplateModelsFromJson = vi.fn<(json: unknown) => Array>>() const startManagedModelJob = vi.fn() const getDiskSpace = vi.fn(async (_dir: string) => ({ free: 1e15, total: 1e15 })) const resolveDownloadContextById = vi.fn(async (_id: string): Promise => null) const areModelsPresent = vi.fn(async (_id: string, _models: unknown[]) => false) -vi.mock('./templateModels', () => ({ resolveTemplateModels: () => resolveTemplateModels() })) +vi.mock('./templateModels', () => ({ + resolveTemplateModelsFromJson: (json: unknown) => resolveTemplateModelsFromJson(json) +})) vi.mock('./templateInputAssets', () => ({ downloadTemplateInputAssets: vi.fn(async () => []) })) vi.mock('../../lib/disk', () => ({ getDiskSpace: (dir: string) => getDiskSpace(dir) })) vi.mock('../../lib/comfyDownloadManager', () => ({ @@ -27,22 +29,37 @@ vi.mock('fs', () => ({ })) import { - abortTemplateDownload, forgetTemplateDownload, - startTemplateDownload, - getTemplateDownloadState, + startTemplateDownloadTask, subscribeTemplateDownload } from './templateDownloadTask' -import { DISK_SPACE_ERROR } from './templateDownloadCore' +import { DISK_SPACE_ERROR, type TemplateDownloadSummary } from './templateDownloadCore' +import type { InstallationRecord } from '../../installations' const sendOutput = vi.fn() +const WORKFLOW = { nodes: [] } +const ONE_MODEL = [{ filename: 'm.safetensors', directory: 'checkpoints', url: 'u' }] + +function start( + taskId: string, + { installationId = 'install-1', estimatedSizeBytes = 0 } = {} +): void { + startTemplateDownloadTask( + taskId, + { id: installationId } as unknown as InstallationRecord, + 'example', + estimatedSizeBytes, + { sendOutput }, + WORKFLOW + ) +} -function makeInstall(id: string) { - return { - id, - bundledTemplateId: 't', - bundledTemplateModelBytes: 1024 - } as unknown as Parameters[0] +function latest(taskId: string): TemplateDownloadSummary | undefined { + let summary: TemplateDownloadSummary | undefined + subscribeTemplateDownload(taskId, (s) => { + summary ??= s + })() + return summary } const jobReleases = new Map>() @@ -59,6 +76,23 @@ function hangingJob(url: string) { } } +function settlingJob(url: string) { + let complete!: () => void + const completion = new Promise((resolve) => { + complete = () => resolve({ status: 'completed', savePath: `/tmp/models/checkpoints/${url}` }) + }) + return { + job: { + id: `id-${url}`, + url, + savePath: `/tmp/models/checkpoints/${url}`, + completion, + release: vi.fn() + }, + complete: () => complete() + } +} + async function flush(): Promise { for (let i = 0; i < 8; i++) { await Promise.resolve() @@ -66,105 +100,84 @@ async function flush(): Promise { } } -describe('starter model download task', () => { +function resetMocks(): void { + resolveTemplateModelsFromJson.mockReset().mockReturnValue(ONE_MODEL) + startManagedModelJob.mockReset().mockImplementation(async () => hangingJob('u')) + jobReleases.clear() + sendOutput.mockReset() + getDiskSpace.mockReset().mockResolvedValue({ free: 1e15, total: 1e15 }) + resolveDownloadContextById.mockReset().mockResolvedValue(null) + areModelsPresent.mockReset().mockResolvedValue(false) +} + +describe('template model download task', () => { beforeEach(() => { vi.useFakeTimers() - resolveTemplateModels.mockReset() - startManagedModelJob.mockReset() - jobReleases.clear() - sendOutput.mockReset() - getDiskSpace.mockReset().mockResolvedValue({ free: 1e15, total: 1e15 }) - resolveDownloadContextById.mockReset().mockResolvedValue(null) - areModelsPresent.mockReset().mockResolvedValue(false) + resetMocks() }) afterEach(() => { vi.useRealTimers() }) - it('is done at once when the starter workflow needs no models', async () => { - resolveTemplateModels.mockResolvedValue([]) - startTemplateDownload(makeInstall('done-1'), 0, { sendOutput }) + it('is done at once when the workflow needs no models', async () => { + resolveTemplateModelsFromJson.mockReturnValue([]) + start('done-1') await flush() - expect(getTemplateDownloadState('done-1')?.status).toBe('done') + expect(latest('done-1')?.status).toBe('done') expect(startManagedModelJob).not.toHaveBeenCalled() }) - it('fails when the model list cannot be resolved', async () => { - resolveTemplateModels.mockRejectedValue(new Error('network down')) - startTemplateDownload(makeInstall('err-1'), 0, { sendOutput }) + it('reads the model list from the workflow it was given', async () => { + start('workflow-1') await flush() - expect(getTemplateDownloadState('err-1')).toMatchObject({ - status: 'error', - error: 'network down' + expect(resolveTemplateModelsFromJson).toHaveBeenCalledWith(WORKFLOW) + forgetTemplateDownload('workflow-1') + }) + + it("fails when the workflow's model list cannot be read", async () => { + resolveTemplateModelsFromJson.mockImplementation(() => { + throw new Error('malformed workflow') }) + start('err-1') + await flush() + + expect(latest('err-1')).toMatchObject({ status: 'error', error: 'malformed workflow' }) }) it('fails before downloading anything when the disk is too small', async () => { - resolveTemplateModels.mockResolvedValue([ - { filename: 'm.safetensors', directory: 'checkpoints', url: 'u' } - ]) getDiskSpace.mockResolvedValue({ free: 1, total: 1e15 }) - startTemplateDownload(makeInstall('err-disk'), 10 * 1024 ** 3, { sendOutput }) + start('err-disk', { estimatedSizeBytes: 10 * 1024 ** 3 }) await flush() - expect(getTemplateDownloadState('err-disk')).toMatchObject({ - status: 'error', - error: DISK_SPACE_ERROR - }) + expect(latest('err-disk')).toMatchObject({ status: 'error', error: DISK_SPACE_ERROR }) expect(startManagedModelJob).not.toHaveBeenCalled() }) it('skips the disk pre-flight when every model is already on disk', async () => { - resolveTemplateModels.mockResolvedValue([ - { filename: 'm.safetensors', directory: 'checkpoints', url: 'u' } - ]) getDiskSpace.mockResolvedValue({ free: 1, total: 1e15 }) areModelsPresent.mockResolvedValue(true) - startManagedModelJob.mockImplementation(async () => hangingJob('u')) - startTemplateDownload(makeInstall('present-1'), 10 * 1024 ** 3, { sendOutput }) + start('present-1', { estimatedSizeBytes: 10 * 1024 ** 3 }) await vi.waitFor(() => expect(startManagedModelJob).toHaveBeenCalled()) expect(getDiskSpace).not.toHaveBeenCalled() - expect(getTemplateDownloadState('present-1')?.status).toBe('downloading') - abortTemplateDownload('present-1') - }) - - it('is cancelled by abortTemplateDownload, which releases its model jobs', async () => { - resolveTemplateModels.mockResolvedValue([ - { filename: 'm.safetensors', directory: 'checkpoints', url: 'u' } - ]) - startManagedModelJob.mockImplementation(async () => hangingJob('u')) - startTemplateDownload(makeInstall('cancel-1'), 0, { sendOutput }) - await vi.waitFor(() => expect(startManagedModelJob).toHaveBeenCalled()) - - abortTemplateDownload('cancel-1') - - await vi.waitFor(() => expect(jobReleases.get('id-u')).toHaveBeenCalled()) - expect(getTemplateDownloadState('cancel-1')?.status).toBe('cancelled') + expect(latest('present-1')?.status).toBe('downloading') + forgetTemplateDownload('present-1') }) - it('forgetTemplateDownload aborts an in-flight task and drops its state', async () => { - resolveTemplateModels.mockResolvedValue([ - { filename: 'm.safetensors', directory: 'checkpoints', url: 'u' } - ]) - startManagedModelJob.mockImplementation(async () => hangingJob('u')) - startTemplateDownload(makeInstall('forget-1'), 0, { sendOutput }) + it('forgetTemplateDownload aborts an in-flight task, releases its model jobs and drops its state', async () => { + start('forget-1') await vi.waitFor(() => expect(startManagedModelJob).toHaveBeenCalled()) forgetTemplateDownload('forget-1') await vi.waitFor(() => expect(jobReleases.get('id-u')).toHaveBeenCalled()) - expect(getTemplateDownloadState('forget-1')).toBeUndefined() + expect(latest('forget-1')).toBeUndefined() }) - it('starts each template model as a real managed model job (issue #1322)', async () => { - resolveTemplateModels.mockResolvedValue([ - { filename: 'm.safetensors', directory: 'checkpoints', url: 'u' } - ]) - startManagedModelJob.mockImplementation(async () => hangingJob('u')) - startTemplateDownload(makeInstall('job-1'), 0, { sendOutput }) + it("starts each model as a managed model job owned by the task's installation (issue #1322)", async () => { + start('job-1', { installationId: 'install-job' }) await flush() expect(startManagedModelJob).toHaveBeenCalledWith( @@ -172,63 +185,54 @@ describe('starter model download task', () => { url: 'u', filename: 'm.safetensors', directory: 'checkpoints', - installationId: 'job-1', + installationId: 'install-job', onProgress: expect.any(Function) }) ) - abortTemplateDownload('job-1') + forgetTemplateDownload('job-1') }) - it("uses the install's effective primary models dir for preflight, not a global dir (#1376)", async () => { - resolveTemplateModels.mockResolvedValue([ - { filename: 'm.safetensors', directory: 'checkpoints', url: 'u' } - ]) + it("uses the installation's effective primary models dir for preflight, not a global dir (#1376)", async () => { resolveDownloadContextById.mockResolvedValue({ downloadBaseDir: '/install/models', modelRoots: ['/install/models'], extraPaths: [] }) - startManagedModelJob.mockImplementation(async () => hangingJob('u')) - startTemplateDownload(makeInstall('dest-1'), 1024, { sendOutput }) + start('dest-1', { installationId: 'install-dest', estimatedSizeBytes: 1024 }) await flush() - expect(resolveDownloadContextById).toHaveBeenCalledWith('dest-1') + expect(resolveDownloadContextById).toHaveBeenCalledWith('install-dest') expect(getDiskSpace).toHaveBeenCalledWith('/install/models') - abortTemplateDownload('dest-1') + forgetTemplateDownload('dest-1') }) }) describe('subscribeTemplateDownload', () => { beforeEach(() => { vi.useFakeTimers() - resolveTemplateModels - .mockReset() - .mockResolvedValue([{ filename: 'm.safetensors', directory: 'checkpoints', url: 'u' }]) - startManagedModelJob.mockReset().mockImplementation(async () => hangingJob('u')) - jobReleases.clear() - getDiskSpace.mockReset().mockResolvedValue({ free: 1e15, total: 1e15 }) - resolveDownloadContextById.mockReset().mockResolvedValue(null) - areModelsPresent.mockReset().mockResolvedValue(false) + resetMocks() }) afterEach(() => { vi.useRealTimers() }) it('publishes every 500 ms while the task runs, then once when it settles', async () => { + const { job, complete } = settlingJob('u') + startManagedModelJob.mockImplementation(async () => job) const listener = vi.fn() subscribeTemplateDownload('sub-paced', listener) expect(listener).not.toHaveBeenCalled() - startTemplateDownload(makeInstall('sub-paced'), 0, { sendOutput }) + start('sub-paced') await vi.waitFor(() => expect(startManagedModelJob).toHaveBeenCalled()) listener.mockClear() await vi.advanceTimersByTimeAsync(500) expect(listener).toHaveBeenCalledTimes(1) expect(listener).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'downloading' })) - abortTemplateDownload('sub-paced') + complete() await vi.waitFor(() => - expect(listener).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'cancelled' })) + expect(listener).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'done' })) ) const calls = listener.mock.calls.length await vi.advanceTimersByTimeAsync(2000) @@ -236,7 +240,7 @@ describe('subscribeTemplateDownload', () => { }) it('reports a running task at once and stops after unsubscribe', async () => { - startTemplateDownload(makeInstall('sub-running'), 0, { sendOutput }) + start('sub-running') await vi.waitFor(() => expect(startManagedModelJob).toHaveBeenCalled()) const listener = vi.fn() @@ -247,14 +251,14 @@ describe('subscribeTemplateDownload', () => { unsubscribe() await vi.advanceTimersByTimeAsync(2000) expect(listener).toHaveBeenCalledOnce() - abortTemplateDownload('sub-running') + forgetTemplateDownload('sub-running') }) it('reports a settled task once', async () => { - resolveTemplateModels.mockResolvedValue([]) - startTemplateDownload(makeInstall('sub-settled'), 0, { sendOutput }) + resolveTemplateModelsFromJson.mockReturnValue([]) + start('sub-settled') await flush() - expect(getTemplateDownloadState('sub-settled')?.status).toBe('done') + expect(latest('sub-settled')?.status).toBe('done') const listener = vi.fn() subscribeTemplateDownload('sub-settled', listener) @@ -264,7 +268,7 @@ describe('subscribeTemplateDownload', () => { }) it('forgetTemplateDownload drops the listeners with the task', async () => { - startTemplateDownload(makeInstall('sub-forget'), 0, { sendOutput }) + start('sub-forget') await vi.waitFor(() => expect(startManagedModelJob).toHaveBeenCalled()) const listener = vi.fn() subscribeTemplateDownload('sub-forget', listener) diff --git a/src/main/sources/standalone/templateDownloadTask.ts b/src/main/sources/standalone/templateDownloadTask.ts index eefb69921..ce9253714 100644 --- a/src/main/sources/standalone/templateDownloadTask.ts +++ b/src/main/sources/standalone/templateDownloadTask.ts @@ -8,7 +8,7 @@ import { } from '../../lib/modelDownloadPaths' import { STAGING_META_SUFFIX, STAGING_META_TMP_SUFFIX } from '../../lib/modelDownloadStaging' import { getDiskSpace } from '../../lib/disk' -import { resolveTemplateModels, resolveTemplateModelsFromJson } from './templateModels' +import { resolveTemplateModelsFromJson } from './templateModels' import { downloadTemplateInputAssets } from './templateInputAssets' import { isTerminal, @@ -39,24 +39,18 @@ export function hasActiveTemplateDownloads(): boolean { return false } -export function getTemplateDownloadState( - installationId: string -): TemplateDownloadState | undefined { - return _templateDownloads.get(installationId) -} - -export function abortTemplateDownload(installationId: string): void { - const ctrl = _templateAborts.get(installationId) +function abortTemplateDownload(taskId: string): void { + const ctrl = _templateAborts.get(taskId) if (ctrl) { ctrl.abort() - _templateAborts.delete(installationId) + _templateAborts.delete(taskId) } - const leases = _templateJobLeases.get(installationId) + const leases = _templateJobLeases.get(taskId) if (leases) { for (const release of [...leases]) release() - _templateJobLeases.delete(installationId) + _templateJobLeases.delete(taskId) } - const state = _templateDownloads.get(installationId) + const state = _templateDownloads.get(taskId) if (state && !isTerminal(state.status)) { state.status = 'cancelled' } @@ -66,23 +60,13 @@ interface StartOpts { sendOutput: (text: string) => void } -export function startTemplateDownload( - installation: InstallationRecord, - estimatedSizeBytes: number, - opts: StartOpts -): void { - const templateId = installation.bundledTemplateId - if (!templateId) return - startTemplateDownloadTask(installation.id, installation, templateId, estimatedSizeBytes, opts) -} - export function startTemplateDownloadTask( taskId: string, installation: InstallationRecord, templateId: string, estimatedSizeBytes: number, opts: StartOpts, - workflowJson?: unknown + workflowJson: unknown ): void { const existing = _templateDownloads.get(taskId) if (existing && !isTerminal(existing.status)) return @@ -201,18 +185,16 @@ async function runTask( state: TemplateDownloadState, signal: AbortSignal, { sendOutput }: StartOpts, - workflowJson?: unknown + workflowJson: unknown ): Promise { - await downloadTemplateInputAssets(installation, templateId, sendOutput, signal, workflowJson) + await downloadTemplateInputAssets(installation, workflowJson, sendOutput, signal) if (signal.aborted) { state.status = 'cancelled' return } sendOutput(`[templates] Resolving model list for "${templateId}"...\n`) - const models = workflowJson - ? resolveTemplateModelsFromJson(workflowJson) - : await resolveTemplateModels(installation, templateId) + const models = resolveTemplateModelsFromJson(workflowJson) if (signal.aborted) { state.status = 'cancelled' diff --git a/src/main/sources/standalone/templateInputAssets.integration.test.ts b/src/main/sources/standalone/templateInputAssets.integration.test.ts index 5f7dd8e0d..d189a1102 100644 --- a/src/main/sources/standalone/templateInputAssets.integration.test.ts +++ b/src/main/sources/standalone/templateInputAssets.integration.test.ts @@ -56,13 +56,7 @@ describe('a downloaded template input asset', () => { status: 'missing' }) - const placed = await downloadTemplateInputAssets( - installation(), - 'template-a', - log, - undefined, - workflow - ) + const placed = await downloadTemplateInputAssets(installation(), workflow, log) expect(placed).toEqual([{ filename: ASSET, downloaded: true }]) expect(await availability(ASSET)).toEqual({ @@ -72,16 +66,10 @@ describe('a downloaded template input asset', () => { }) it('is not fetched again when it is already there', async () => { - await downloadTemplateInputAssets(installation(), 'template-a', log, undefined, workflow) + await downloadTemplateInputAssets(installation(), workflow, log) download.mockClear() - const placed = await downloadTemplateInputAssets( - installation(), - 'template-a', - log, - undefined, - workflow - ) + const placed = await downloadTemplateInputAssets(installation(), workflow, log) expect(placed).toEqual([{ filename: ASSET, downloaded: false }]) expect(download).not.toHaveBeenCalled() diff --git a/src/main/sources/standalone/templateInputAssets.test.ts b/src/main/sources/standalone/templateInputAssets.test.ts index 329aef0a5..baf3f62be 100644 --- a/src/main/sources/standalone/templateInputAssets.test.ts +++ b/src/main/sources/standalone/templateInputAssets.test.ts @@ -13,24 +13,31 @@ vi.mock('./templateModels', () => ({ import { resolveInputDir, resolveTemplateInputAssetAvailability, - resolveTemplateInputAssets, - resolveTemplateInputAssetSnapshot + resolveTemplateInputAssetSnapshot, + type TemplateInputAsset } from './templateInputAssets' import { TEMPLATE_INPUT_BASE } from './curatedTemplates' import type { InstallationRecord } from '../../installations' -const inst = { id: 'i1', bundledTemplateId: 't' } as unknown as InstallationRecord +const inst = { id: 'i1' } as unknown as InstallationRecord + +let snapshotSeq = 0 +async function freshSnapshot(): Promise { + const assets = await resolveTemplateInputAssetSnapshot(inst, `fresh-${++snapshotSeq}`) + if (assets === null) throw new Error('the template workflow did not resolve') + return assets +} const loadNode = (type: string, filename: unknown) => ({ type, widgets_values: [filename] }) beforeEach(() => loadTemplateJson.mockReset()) -describe('resolveTemplateInputAssets', () => { +describe('resolveTemplateInputAssetSnapshot', () => { it('derives trusted preview metadata from a declared LoadImage input', async () => { loadTemplateJson.mockResolvedValue({ nodes: [loadNode('LoadImage', 'white-hotel-on-rocky-island.png')] }) - const assets = await resolveTemplateInputAssets(inst, 't') + const assets = await freshSnapshot() expect(assets).toEqual([ { assetId: 'white-hotel-on-rocky-island.png', @@ -47,7 +54,7 @@ describe('resolveTemplateInputAssets', () => { nodes: [], definitions: { subgraphs: [{ nodes: [loadNode('LoadImage', 'subject.png')] }] } }) - const assets = await resolveTemplateInputAssets(inst, 't') + const assets = await freshSnapshot() expect(assets.map((a) => a.filename)).toEqual(['subject.png']) }) @@ -55,7 +62,7 @@ describe('resolveTemplateInputAssets', () => { loadTemplateJson.mockResolvedValue({ nodes: [loadNode('LoadVideo', 'clip.mp4'), loadNode('LoadAudio', 'voice.mp3')] }) - expect(await resolveTemplateInputAssets(inst, 't')).toMatchObject([ + expect(await freshSnapshot()).toMatchObject([ { filename: 'clip.mp4', mediaType: 'video' }, { filename: 'voice.mp3', mediaType: 'audio' } ]) @@ -70,7 +77,7 @@ describe('resolveTemplateInputAssets', () => { ] }) - expect(await resolveTemplateInputAssets(inst, 't')).toMatchObject([ + expect(await freshSnapshot()).toMatchObject([ { filename: 'clip.mp4', mediaType: 'video' }, { filename: 'still.webp', mediaType: 'image' }, { filename: 'voice.wav', mediaType: 'audio' } @@ -81,7 +88,7 @@ describe('resolveTemplateInputAssets', () => { loadTemplateJson.mockResolvedValue({ nodes: [loadNode('LoadImage', 'dup.png'), loadNode('LoadImage', 'dup.png')] }) - expect(await resolveTemplateInputAssets(inst, 't')).toHaveLength(1) + expect(await freshSnapshot()).toHaveLength(1) }) it('rejects path-traversal and absolute names', async () => { @@ -92,31 +99,26 @@ describe('resolveTemplateInputAssets', () => { loadNode('LoadImage', 'C:\\evil.png') ] }) - expect(await resolveTemplateInputAssets(inst, 't')).toEqual([]) + expect(await freshSnapshot()).toEqual([]) }) it('rejects non-media extensions (no arbitrary payloads through input/)', async () => { loadTemplateJson.mockResolvedValue({ nodes: [loadNode('LoadImage', 'weights.safetensors'), loadNode('LoadImage', 'script.py')] }) - expect(await resolveTemplateInputAssets(inst, 't')).toEqual([]) + expect(await freshSnapshot()).toEqual([]) }) it('ignores non-loader nodes and non-string widget values', async () => { loadTemplateJson.mockResolvedValue({ nodes: [loadNode('KSampler', 'not-an-input.png'), loadNode('LoadImage', 42)] }) - expect(await resolveTemplateInputAssets(inst, 't')).toEqual([]) + expect(await freshSnapshot()).toEqual([]) }) it('strips query params before validating + naming', async () => { loadTemplateJson.mockResolvedValue({ nodes: [loadNode('LoadImage', 'a.png?v=2')] }) - expect((await resolveTemplateInputAssets(inst, 't'))[0]!.filename).toBe('a.png') - }) - - it('returns [] when the workflow JSON cannot be resolved', async () => { - loadTemplateJson.mockResolvedValue(null) - expect(await resolveTemplateInputAssets(inst, 't')).toEqual([]) + expect((await freshSnapshot())[0]!.filename).toBe('a.png') }) it('resolves the workflow once across a burst for the same template', async () => { @@ -164,10 +166,10 @@ describe('resolveTemplateInputAssets', () => { }) it('keeps unresolved metadata distinct from a resolved template with no inputs', async () => { - loadTemplateJson.mockResolvedValue(null) + loadTemplateJson.mockResolvedValueOnce(null).mockResolvedValueOnce({ nodes: [] }) - await expect(resolveTemplateInputAssetSnapshot(inst, 't')).resolves.toBeNull() - await expect(resolveTemplateInputAssets(inst, 't')).resolves.toEqual([]) + await expect(resolveTemplateInputAssetSnapshot(inst, 'unresolved')).resolves.toBeNull() + await expect(resolveTemplateInputAssetSnapshot(inst, 'no-inputs')).resolves.toEqual([]) }) }) diff --git a/src/main/sources/standalone/templateInputAssets.ts b/src/main/sources/standalone/templateInputAssets.ts index a6258f1a2..10ac928bc 100644 --- a/src/main/sources/standalone/templateInputAssets.ts +++ b/src/main/sources/standalone/templateInputAssets.ts @@ -95,14 +95,6 @@ export async function resolveTemplateInputAssetSnapshot( return snapshot } -export async function resolveTemplateInputAssets( - installation: InstallationRecord, - templateId: string -): Promise { - const json = await loadTemplateJson(installation, templateId) - return resolveTemplateInputAssetsFromJson(json) -} - function resolveTemplateInputAssetsFromJson(json: unknown): TemplateInputAsset[] { if (!json || typeof json !== 'object') return [] @@ -185,14 +177,11 @@ export interface PlacedInputAsset { export async function downloadTemplateInputAssets( installation: InstallationRecord, - templateId: string, + workflowJson: unknown, log: (text: string) => void, - signal?: AbortSignal, - workflowJson?: unknown + signal?: AbortSignal ): Promise { - const assets = workflowJson - ? resolveTemplateInputAssetsFromJson(workflowJson) - : await resolveTemplateInputAssets(installation, templateId) + const assets = resolveTemplateInputAssetsFromJson(workflowJson) if (assets.length === 0) return [] let destDir: string diff --git a/src/main/sources/standalone/templateModels.test.ts b/src/main/sources/standalone/templateModels.test.ts index 017e80ae6..0cfa6b9e6 100644 --- a/src/main/sources/standalone/templateModels.test.ts +++ b/src/main/sources/standalone/templateModels.test.ts @@ -1,26 +1,12 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userdata' }, ipcMain: { handle: vi.fn() } })) +vi.mock('../../lib/fetch', () => ({ fetchJSON: vi.fn() })) -const fetchJSON = vi.fn() -vi.mock('../../lib/fetch', () => ({ fetchJSON: (...a: unknown[]) => fetchJSON(...a) })) -vi.mock('fs', () => ({ - default: { promises: { readFile: vi.fn().mockRejectedValue(new Error('ENOENT')) } } -})) -vi.mock('../../lib/pythonEnv', () => ({ getActiveVenvDir: () => null })) -vi.mock('./envPaths', async (importOriginal) => ({ - ...(await importOriginal()), - findSitePackages: () => null -})) - -import { sanitizeModelPath, resolveTemplateModels } from './templateModels' -import type * as EnvPaths from './envPaths' -import type { InstallationRecord } from '../../installations' - -const inst = { id: 'i1', bundledTemplateId: 't' } as unknown as InstallationRecord +import { sanitizeModelPath, resolveTemplateModelsFromJson } from './templateModels' const model = (over: Record) => ({ name: 'm.safetensors', @@ -74,48 +60,38 @@ describe('sanitizeModelPath', () => { }) }) -describe('resolveTemplateModels — URL + path guards', () => { - beforeEach(() => { - fetchJSON.mockReset() - }) - afterEach(() => vi.clearAllMocks()) - - async function resolveWith( - models: unknown[] - ): Promise>> { - fetchJSON.mockResolvedValue({ models }) - return resolveTemplateModels(inst, 't') - } +describe('resolveTemplateModelsFromJson — URL + path guards', () => { + const resolveWith = (models: unknown[]) => resolveTemplateModelsFromJson({ models }) - it('accepts a whitelisted HTTPS model', async () => { - const out = await resolveWith([model({})]) + it('accepts a whitelisted HTTPS model', () => { + const out = resolveWith([model({})]) expect(out).toEqual([ { filename: 'm.safetensors', url: model({}).url, directory: 'checkpoints' } ]) }) - it('rejects plain http:// (insecure transport)', async () => { - const out = await resolveWith([model({ url: 'http://huggingface.co/x/m.safetensors' })]) + it('rejects plain http:// (insecure transport)', () => { + const out = resolveWith([model({ url: 'http://huggingface.co/x/m.safetensors' })]) expect(out).toEqual([]) }) - it('rejects a non-whitelisted host', async () => { - const out = await resolveWith([model({ url: 'https://evil.example.com/m.safetensors' })]) + it('rejects a non-whitelisted host', () => { + const out = resolveWith([model({ url: 'https://evil.example.com/m.safetensors' })]) expect(out).toEqual([]) }) - it('rejects a non-model extension', async () => { - const out = await resolveWith([model({ url: 'https://huggingface.co/x/m.zip' })]) + it('rejects a non-model extension', () => { + const out = resolveWith([model({ url: 'https://huggingface.co/x/m.zip' })]) expect(out).toEqual([]) }) - it('drops an entry whose directory traverses out of the models dir', async () => { - const out = await resolveWith([model({ directory: '../../etc' })]) + it('drops an entry whose directory traverses out of the models dir', () => { + const out = resolveWith([model({ directory: '../../etc' })]) expect(out).toEqual([]) }) - it('drops an entry whose filename carries a path separator', async () => { - const out = await resolveWith([model({ name: 'sub/m.safetensors' })]) + it('drops an entry whose filename carries a path separator', () => { + const out = resolveWith([model({ name: 'sub/m.safetensors' })]) expect(out).toEqual([]) }) }) diff --git a/src/main/sources/standalone/templateModels.ts b/src/main/sources/standalone/templateModels.ts index 45441d3b2..ba0a318bb 100644 --- a/src/main/sources/standalone/templateModels.ts +++ b/src/main/sources/standalone/templateModels.ts @@ -109,14 +109,6 @@ function walkNodes(nodes: unknown, out: RawModel[]): void { } } -export async function resolveTemplateModels( - installation: InstallationRecord | null, - templateId: string -): Promise { - const json = await loadTemplateJson(installation, templateId) - return resolveTemplateModelsFromJson(json) -} - export function resolveTemplateModelsFromJson(json: unknown): TemplateModelDownload[] { if (!json || typeof json !== 'object') return [] diff --git a/src/renderer/src/lib/setupPlan.ts b/src/renderer/src/lib/setupPlan.ts index f94146355..820e02e74 100644 --- a/src/renderer/src/lib/setupPlan.ts +++ b/src/renderer/src/lib/setupPlan.ts @@ -2,7 +2,6 @@ import { DEFAULT_INSTALL_NAME } from '../../../shared/defaultInstallName' import type { FieldOption, Source } from '../types/ipc' import type { SystemInfo } from '../../../types/ipc' -export const NO_TEMPLATE_VALUE = 'none' export const INSTALL_SPACE_FACTOR = 2.25 export interface WorkspaceBuildChoice { @@ -49,10 +48,7 @@ export interface SavedSetup { export class SetupPlanUnavailable extends Error {} -function pickOption(fieldId: string, options: FieldOption[]): FieldOption | undefined { - if (fieldId === 'bundledTemplate') { - return options.find((o) => o.value === NO_TEMPLATE_VALUE) ?? options[0] - } +function pickOption(options: FieldOption[]): FieldOption | undefined { return options.find((o) => o.recommended) ?? options[0] } @@ -84,7 +80,7 @@ export async function resolveSetupPlan(): Promise { field.id === 'release' ? { includeLatestStable: true } : undefined ) if (field.id === 'comfyVersion' && options.length === 0) continue - const pick = pickOption(field.id, options ?? []) + const pick = pickOption(options ?? []) if (!pick) throw new SetupPlanUnavailable(`no options for ${field.id}`) selections[field.id] = pick } diff --git a/src/renderer/src/panel/BuildProgressDialog.test.ts b/src/renderer/src/panel/BuildProgressDialog.test.ts index 127182c6c..47225e02f 100644 --- a/src/renderer/src/panel/BuildProgressDialog.test.ts +++ b/src/renderer/src/panel/BuildProgressDialog.test.ts @@ -90,10 +90,7 @@ const stepNames = (w: Dialog) => const activeStepDetail = (w: Dialog) => w.get('[data-testid="build-progress-step-detail"]').text() function startLikeMain() { - const phases = buildLaunchPhases(null, { - preLaunchPhases: ['repair', 'torchRepair'], - templateModels: true - }) + const phases = buildLaunchPhases(null, { preLaunchPhases: ['repair', 'torchRepair'] }) let sentPhases: string[] = [] const tracker = createLaunchProgressTracker({ phases, diff --git a/src/renderer/src/views/FirstUseTakeover.test.ts b/src/renderer/src/views/FirstUseTakeover.test.ts index a2b84e84a..501e1e554 100644 --- a/src/renderer/src/views/FirstUseTakeover.test.ts +++ b/src/renderer/src/views/FirstUseTakeover.test.ts @@ -64,8 +64,7 @@ function installApi(overrides: ApiOverrides = {}): void { fields: [ { id: 'release', label: 'Release', type: 'select' }, { id: 'comfyVersion', label: 'ComfyUI version', type: 'select' }, - { id: 'variant', label: 'Variant', type: 'select' }, - { id: 'bundledTemplate', label: 'Starter template', type: 'select' } + { id: 'variant', label: 'Variant', type: 'select' } ] } ]), @@ -94,10 +93,7 @@ function installApi(overrides: ApiOverrides = {}): void { } ] } - return [ - { value: 'flux', label: 'Flux' }, - { value: 'none', label: 'None' } - ] + return [] }), setFirstUseMode: vi.fn() } as unknown as typeof window.api @@ -187,7 +183,7 @@ describe('Set up, the first screen', () => { expect(plan.selections.release?.value).toBe('stable') expect(plan.selections.comfyVersion?.value).toBe('v0.42.4') expect(plan.selections.variant?.value).toBe('mac-mps') - expect(plan.selections.bundledTemplate?.value).toBe('none') + expect(Object.keys(plan.selections)).toEqual(['release', 'comfyVersion', 'variant']) expect(emitTelemetryAction).toHaveBeenCalledWith( 'comfy.desktop.first_use.completed', expect.objectContaining({ exit_path: 'local-new' }) @@ -207,8 +203,7 @@ describe('Set up, the first screen', () => { value: 'mac-cpu', label: 'CPU', data: { variantId: 'mac-cpu', downloadFiles: [] } - }, - bundledTemplate: { value: 'none', label: 'None' } + } }, installRoot: '/Volumes/Studio SSD', downloadBytes: 0, diff --git a/src/renderer/src/views/InstallWizardModal.test.ts b/src/renderer/src/views/InstallWizardModal.test.ts index a800838bf..4c119aff8 100644 --- a/src/renderer/src/views/InstallWizardModal.test.ts +++ b/src/renderer/src/views/InstallWizardModal.test.ts @@ -544,37 +544,6 @@ describe('InstallWizardModal heading', () => { }) }) -describe('InstallWizardModal starter workflow', () => { - it('saves a first-use setup with no starter workflow, even when the catalog offers one', async () => { - ;(window.api.getSources as ReturnType).mockResolvedValue([ - { - id: 'standalone', - label: 'Standalone', - fields: [{ id: 'bundledTemplate', label: 'Starter Template', type: 'select' }] - } - ]) - ;(window.api.getFieldOptions as ReturnType).mockResolvedValue([ - { value: 'none', label: 'None' }, - { - value: 'starter', - label: 'Starter Workflow', - recommended: true, - data: { modality: 'image', sizeBytes: 20_000_000_000 } - } - ]) - const wrapper = mountModal({ hideBackToDashboard: true }) - await wrapper.vm.open({ cameFromSetup: true, entrypoint: 'first_use' }) - await flushPromises() - - expect(wrapper.text()).not.toContain('Starter Workflow') - await wrapper.get('[data-testid="config-save-changes"]').trigger('click') - await flushPromises() - - expect(wrapper.get('.setup-modal-title').text()).toBe('Change setup') - expect(savedSetups(wrapper)[0]?.plan.selections.bundledTemplate?.value).toBe('none') - }) -}) - describe('InstallWizardModal install-location field', () => { it('renders the default install location as a clickable path that opens the folder', async () => { const wrapper = mountModal() @@ -892,18 +861,18 @@ describe('InstallWizardModal workspace Builds', () => { ]) }) - it('installs Standalone directly without asking for a starter template', async () => { + it('installs Standalone directly with the recommended choice for each field', async () => { signInToWorkspace([{ id: 'ready', name: 'Ready Build', state: 'installable' }]) ;(window.api.getSources as ReturnType).mockResolvedValue([ { id: 'standalone', label: 'Standalone', - fields: [{ id: 'bundledTemplate', label: 'Starter Template', type: 'select' }] + fields: [{ id: 'variant', label: 'Variant', type: 'select' }] } ]) ;(window.api.getFieldOptions as ReturnType).mockResolvedValue([ - { value: 'none', label: 'None' }, - { value: 'starter', label: 'Starter Workflow' } + { value: 'cpu', label: 'CPU' }, + { value: 'nvidia', label: 'NVIDIA', recommended: true } ]) const wrapper = await openWorkspaceModal() @@ -924,24 +893,15 @@ describe('InstallWizardModal workspace Builds', () => { expect(wrapper.find('.config-advanced__summary').exists()).toBe(false) expect(wrapper.get('#source-fields').exists()).toBe(true) expect(wrapper.get('#source-fields label').classes()).toContain('config-label') - expect(window.api.getFieldOptions).toHaveBeenCalledWith( - 'standalone', - 'bundledTemplate', - {}, - undefined - ) - - expect((wrapper.get('.config-source-field').element as HTMLElement).style.display).toBe('none') + expect(window.api.getFieldOptions).toHaveBeenCalledWith('standalone', 'variant', {}, undefined) await wrapper.get('[data-testid="config-save-changes"]').trigger('click') await wrapper.get('.config-continue').trigger('click') await flushPromises() - expect(wrapper.find('.template-shell').exists()).toBe(false) - expect(window.api.buildInstallation).toHaveBeenCalledWith( - 'standalone', - expect.objectContaining({ bundledTemplate: expect.objectContaining({ value: 'none' }) }) - ) + expect(window.api.buildInstallation).toHaveBeenCalledWith('standalone', { + variant: expect.objectContaining({ value: 'nvidia' }) + }) expect(window.api.comfybuilder.installBuild).not.toHaveBeenCalled() }) @@ -1064,18 +1024,17 @@ describe('InstallWizardModal workspace Builds', () => { expect(window.api.comfybuilder.listBuilds).toHaveBeenCalledOnce() }) - it('never shows the template picker for a Managed install after visiting the Public tab', async () => { + it('installs the team build after a visit to the Standalone tab', async () => { signInToWorkspace([{ id: 'ready', name: 'Ready Build', state: 'installable' }]) ;(window.api.getSources as ReturnType).mockResolvedValue([ { id: 'standalone', label: 'Standalone', - fields: [{ id: 'bundledTemplate', label: 'Starter Template', type: 'select' }] + fields: [{ id: 'variant', label: 'Variant', type: 'select' }] } ]) ;(window.api.getFieldOptions as ReturnType).mockResolvedValue([ - { value: 'none', label: 'None' }, - { value: 'starter', label: 'Starter Workflow' } + { value: 'nvidia', label: 'NVIDIA', recommended: true } ]) ;(window.api.comfybuilder.installBuild as ReturnType).mockResolvedValue({ ok: true, @@ -1092,8 +1051,8 @@ describe('InstallWizardModal workspace Builds', () => { await wrapper.get('.config-continue').trigger('click') await flushPromises() - expect(wrapper.find('.template-shell').exists()).toBe(false) expect(window.api.comfybuilder.installBuild).toHaveBeenCalledOnce() + expect(window.api.buildInstallation).not.toHaveBeenCalled() }) it('saves a team build picked in first-use Change back to Set up without installing it', async () => { diff --git a/src/renderer/src/views/InstallWizardModal.vue b/src/renderer/src/views/InstallWizardModal.vue index fa7801753..3e7870c10 100644 --- a/src/renderer/src/views/InstallWizardModal.vue +++ b/src/renderer/src/views/InstallWizardModal.vue @@ -45,7 +45,6 @@ import type { import { stripVariantPrefix, sortedCardOptions } from '../lib/variants' import { INSTALL_SPACE_FACTOR, - NO_TEMPLATE_VALUE, downloadBytesOf, type ChangeSetupDraft, type NewInstallSetup, @@ -848,11 +847,7 @@ async function loadFieldOptions(fieldIndex: number): Promise { fieldOptions.value.set(field.id, options) heldFields.value.delete(field.id) - if (field.id === 'bundledTemplate') { - const none = options.find((opt) => opt.value === NO_TEMPLATE_VALUE) - if (none) selections.value[field.id] = none - else delete selections.value[field.id] - } else if (options.length > 0) { + if (options.length > 0) { let defaultIndex = options.findIndex((opt) => opt.recommended) if (defaultIndex < 0) defaultIndex = 0 const defaultOption = options[defaultIndex] @@ -1385,7 +1380,6 @@ async function discardChangeSetup(): Promise { function isHiddenWhenEmpty(field: SourceField): boolean { const held = heldFields.value.get(field.id) if (held) return held.hidden - if (field.id === 'bundledTemplate') return true if (field.type === 'text' || field.renderAs === 'cards') return false const options = fieldOptions.value.get(field.id) if (options === undefined) return false diff --git a/src/renderer/src/views/releaseChannelSwitchLayout.test.ts b/src/renderer/src/views/releaseChannelSwitchLayout.test.ts index 861289f69..757063038 100644 --- a/src/renderer/src/views/releaseChannelSwitchLayout.test.ts +++ b/src/renderer/src/views/releaseChannelSwitchLayout.test.ts @@ -37,8 +37,7 @@ const STANDALONE = { fields: [ { id: 'release', label: 'Release', type: 'select' }, { id: 'comfyVersion', label: 'ComfyUI version', type: 'select' }, - { id: 'variant', label: 'Hardware', type: 'select', renderAs: 'cards' }, - { id: 'bundledTemplate', label: 'Starter workflow', type: 'select', renderAs: 'cards' } + { id: 'variant', label: 'Hardware', type: 'select', renderAs: 'cards' } ] } @@ -83,10 +82,7 @@ function installStandaloneApi(gate: LoadGate) { ] } if (fieldId === 'variant') return hardwareOptions(selections) - return [ - { value: 'none', label: 'No starter workflow' }, - { value: 'flux', label: 'Flux Schnell', data: { sizeBytes: 12_000_000_000 } } - ] + return [] } ) window.api = { @@ -388,12 +384,11 @@ describe('switching the release channel in Change setup', () => { expect(hardwareDescriptions().some((text) => text.includes('nightly'))).toBe(false) }) - it('never shows the starter workflow row in first-run setup while the other channel loads', async () => { + it('keeps the first-run Change setup still while the other channel loads', async () => { const gate = createLoadGate() installStandaloneApi(gate) await openChangeSetup({ hideBackToDashboard: true }) const settled = formLayout() - expect(settled.map((box) => box.what)).not.toContain('Starter workflow') gate.hold() releaseButton('Latest on GitHub').click()