diff --git a/e2e/home-auto-start.test.ts b/e2e/home-auto-start.test.ts new file mode 100644 index 000000000..311ab8a11 --- /dev/null +++ b/e2e/home-auto-start.test.ts @@ -0,0 +1,61 @@ +import os from 'node:os' +import path from 'node:path' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { test, expect } from '@playwright/test' +import { launchApp, type AppContext } from './launchApp' + +const MARKER_FILENAME = '.comfyui-desktop-2' +const BUILD = { id: 'inst-home-auto-start', name: 'Studio GPU' } +const TILE = `[data-testid="home-build"][data-build-id="${BUILD.id}"]` +const TILE_STATUS = `${TILE} [data-testid="home-build-status"]` +const MORE = `${TILE} [data-testid="home-build-more"]` +const AUTO_START_LINE = '[data-testid="build-menu-auto-start"]' + +let ctx: AppContext +let installPath = '' + +test.beforeAll(async () => { + installPath = await mkdtemp(path.join(os.tmpdir(), 'comfyui-launcher-home-auto-start-e2e-')) + await writeFile(path.join(installPath, MARKER_FILENAME), BUILD.id) + ctx = await launchApp( + { + settings: { firstUseCompleted: true, telemetryEnabled: false }, + installations: [{ ...BUILD, installPath, sourceId: 'standalone', status: 'installed' }] + }, + { stayOnHome: true } + ) +}) + +test.afterAll(async () => { + await ctx?.cleanup() + if (installPath) await rm(installPath, { recursive: true, force: true }) +}) + +function savedAutoStart(): Promise { + return ctx.panel.evaluate("window.api.getSetting('autoLaunchOnStartup')") +} + +async function pickAutoStartLine(expected: string): Promise { + expect(await ctx.panel.click(MORE), 'build menu opened from the tile ⋯').toBe(true) + await ctx.panel.waitForVisible(AUTO_START_LINE) + expect(await ctx.panel.textOf(AUTO_START_LINE)).toBe(expected) + expect(await ctx.panel.click(AUTO_START_LINE), `${expected} picked`).toBe(true) +} + +test('Auto start picked in a Home build menu saves that build and shows on its tile, and Turn off sets None @windows @macos @linux', async () => { + await ctx.panel.waitForVisible(TILE) + expect(await ctx.panel.textOf(TILE_STATUS)).toBe('Ready') + + await pickAutoStartLine('Auto start') + + await expect.poll(savedAutoStart).toBe(BUILD.id) + await expect.poll(() => ctx.panel.textOf(TILE_STATUS)).toBe('Auto start') + await expect + .poll(() => ctx.panel.exists(`${TILE} [data-testid="home-build-starts-with-desktop"]`)) + .toBe(true) + + await pickAutoStartLine('Turn off Auto start') + + await expect.poll(savedAutoStart).toBe('none') + await expect.poll(() => ctx.panel.textOf(TILE_STATUS)).toBe('Ready') +}) diff --git a/e2e/home.test.ts b/e2e/home.test.ts index 3a1336157..0a1136177 100644 --- a/e2e/home.test.ts +++ b/e2e/home.test.ts @@ -53,23 +53,3 @@ test('Home in the sidebar returns to Home @windows @macos @linux', async () => { await ctx.panel.waitForVisible(HOME_VIEW) expect(await ctx.panel.isVisible('.chooser-view')).toBe(false) }) - -test('Auto start on a Home card saves that build for the next start, and unticking sets None @windows @macos @linux', async () => { - const box = '[data-testid="home-build-auto-start"] [role="checkbox"]' - const saved = () => ctx.panel.evaluate("window.api.getSetting('autoLaunchOnStartup')") - const boxState = () => - ctx.panel.evaluate(`document.querySelector('${box}')?.getAttribute('aria-checked')`) - await ctx.panel.waitForVisible(box) - const buildId = await ctx.panel.evaluate( - `document.querySelector('[data-testid="home-build-auto-start"]').dataset.buildId` - ) - - expect(await ctx.panel.click(box)).toBe(true) - await expect.poll(saved).toBe(buildId) - await expect.poll(boxState).toBe('true') - expect(await ctx.panel.isVisible(HOME_VIEW)).toBe(true) - - expect(await ctx.panel.click(box)).toBe(true) - await expect.poll(saved).toBe('none') - await expect.poll(boxState).toBe('false') -}) diff --git a/e2e/shared-controls-input.test.ts b/e2e/shared-controls-input.test.ts index 347546846..9cf092f18 100644 --- a/e2e/shared-controls-input.test.ts +++ b/e2e/shared-controls-input.test.ts @@ -5,12 +5,12 @@ import { isPopupVisible } from './support/cdpPages' test('the WebContents facade drives shared selects and tabs with native input @windows @macos @linux', async () => { const ctx = await launchApp({ - settings: { firstUseCompleted: true, language: 'en', autoLaunchOnStartup: 'none' } + settings: { firstUseCompleted: true, language: 'en' } }) try { const popup = await openDesktopSettings(ctx.app, ctx.panel) - const trigger = '[data-field-id="autoLaunchOnStartup"] [role="combobox"]' + const trigger = '[data-field-id="language"] [role="combobox"]' await popup.waitForVisible(trigger) await popup.evaluate(`(() => { window.__inputEvents = [] @@ -31,12 +31,8 @@ test('the WebContents facade drives shared selects and tabs with native input @w { type: 'mouseup', trusted: true }, { type: 'click', trusted: true } ]) - expect(await popup.clickByText('[role="listbox"] [role="option"]', 'Last used build')).toBe( - true - ) - await expect - .poll(() => ctx.panel.evaluate("window.api.getSetting('autoLaunchOnStartup')")) - .toBe('last') + expect(await popup.clickByText('[role="listbox"] [role="option"]', '简体中文')).toBe(true) + await expect.poll(() => ctx.panel.evaluate("window.api.getSetting('language')")).toBe('zh') await expect .poll(() => @@ -50,10 +46,8 @@ test('the WebContents facade drives shared selects and tabs with native input @w await popup.pressKey('Escape') await expect.poll(() => popup.exists('[role="listbox"]')).toBe(false) expect(await isPopupVisible(ctx.app, 'comfyTitlePopup.html')).toBe(true) - await popup.selectOption(trigger, 'None (show dashboard)') - await expect - .poll(() => ctx.panel.evaluate("window.api.getSetting('autoLaunchOnStartup')")) - .toBe('none') + await popup.selectOption(trigger, 'English') + await expect.poll(() => ctx.panel.evaluate("window.api.getSetting('language')")).toBe('en') expect(await popup.clickNth('[role="tab"]', 2)).toBe(true) await expect.poll(() => popup.textOf('[role="tab"][aria-selected="true"]')).toBe('Storage') diff --git a/locales/en.json b/locales/en.json index d451fc31b..b2c6bcc64 100644 --- a/locales/en.json +++ b/locales/en.json @@ -145,8 +145,9 @@ "openComfyUIIn": "Open ComfyUI in {name}", "opensIn": "Opens in {name}", "allBuilds": "All builds", - "autoStart": "Auto start", - "autoStartHint": "Start this build when Comfy Desktop opens", + "turnOnAutoStart": "Auto start", + "turnOffAutoStart": "Turn off Auto start", + "autoStartOn": "Auto start", "buildRunning": "Running", "buildStarting": "Starting", "buildReady": "Ready", @@ -754,10 +755,6 @@ "autoUpdate": "Check for updates on startup", "autoInstallUpdates": "Automatically install Desktop updates", "appBehavior": "App Behavior", - "autoLaunchOnStartup": "Auto-launch on startup", - "autoLaunchOnStartupDescription": "Pick a build to launch automatically when Comfy Desktop opens. Defaults to None.", - "autoLaunchOnStartupNone": "None (show dashboard)", - "autoLaunchOnStartupLast": "Last used build", "confirmBeforeClosingWindow": "Confirm before closing a window", "confirmBeforeClosingWindowDescription": "Ask for confirmation before closing a window that's running a local install.", "warnBeforeRunningMultipleInstances": "Warn before running multiple builds", diff --git a/locales/zh.json b/locales/zh.json index 45bf0d158..86d411c03 100644 --- a/locales/zh.json +++ b/locales/zh.json @@ -145,8 +145,9 @@ "openComfyUIIn": "在 {name} 中打开 ComfyUI", "opensIn": "在 {name} 中打开", "allBuilds": "全部构建", - "autoStart": "自动启动", - "autoStartHint": "Comfy Desktop 打开时启动此构建", + "turnOnAutoStart": "自动启动", + "turnOffAutoStart": "关闭自动启动", + "autoStartOn": "自动启动", "buildRunning": "运行中", "buildStarting": "启动中", "buildReady": "就绪", @@ -754,10 +755,6 @@ "autoUpdate": "启动时检查更新", "autoInstallUpdates": "自动安装桌面端更新", "appBehavior": "应用行为", - "autoLaunchOnStartup": "启动时自动打开", - "autoLaunchOnStartupDescription": "选择 Comfy Desktop 打开时自动启动的构建。默认为“无”。", - "autoLaunchOnStartupNone": "无(显示主面板)", - "autoLaunchOnStartupLast": "上次使用的构建", "confirmBeforeClosingWindow": "关闭窗口前确认", "confirmBeforeClosingWindowDescription": "关闭正在运行本地安装的窗口前请求确认。", "warnBeforeRunningMultipleInstances": "运行多个构建前发出警告", diff --git a/src/main/index.ts b/src/main/index.ts index 6281074df..c14808d4f 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -97,8 +97,8 @@ import { } from './lib/ipc/shared' import { enrichInstallationsForRenderer } from './lib/ipc/registerInstallationHandlers' import { getSnapshotListData } from './lib/snapshots' -import { update as updateInstallation, resolveAutoLaunchInstall } from './installations' -import { AUTO_LAUNCH_NONE } from './settings' +import { update as updateInstallation } from './installations' +import { pinAutoStartToALocalBuild } from './lib/firstBuildAutoStart' import { lookupInstallUpdateOverride, recordIpcInvocation } from './lib/e2eOverrides' import * as mainTelemetry from './lib/telemetry' import { @@ -271,14 +271,11 @@ function revealStartupRestoreDashboard(windowKey: number): void { } async function openStartupSurface(): Promise { - const firstUseDone = settings.get('firstUseCompleted') === true - const autoLaunchValue = firstUseDone - ? (settings.get('autoLaunchOnStartup') as string | undefined) - : undefined - const explicitInst = - autoLaunchValue && autoLaunchValue !== AUTO_LAUNCH_NONE - ? await resolveAutoLaunchInstall(autoLaunchValue) - : null + const autoStartBuild = await pinAutoStartToALocalBuild().catch((err: unknown) => { + console.warn('[auto-start] could not read the Auto start build:', err) + return null + }) + const explicitInst = settings.get('firstUseCompleted') === true ? autoStartBuild : null const chooserWindow = explicitInst ? openChooserHostWindow('comfy', { deferColdStartReveal: true }) diff --git a/src/main/installations.test.ts b/src/main/installations.test.ts index fc26a1f05..3157ab9ec 100644 --- a/src/main/installations.test.ts +++ b/src/main/installations.test.ts @@ -312,51 +312,6 @@ describe('installations.getRecent', () => { }) }) -describe('installations.resolveAutoLaunchInstall', () => { - it('returns null for null / undefined / empty / "none"', async () => { - const installations = await loadInstallations() - expect(await installations.resolveAutoLaunchInstall(null)).toBeNull() - expect(await installations.resolveAutoLaunchInstall(undefined)).toBeNull() - expect(await installations.resolveAutoLaunchInstall('')).toBeNull() - expect(await installations.resolveAutoLaunchInstall('none')).toBeNull() - }) - - it('"last" resolves via getRecent and returns null when nothing has launched', async () => { - const installations = await loadInstallations() - expect(await installations.resolveAutoLaunchInstall('last')).toBeNull() - - await installations.add({ - name: 'older', - installPath: path.join(tmpRoot, 'older'), - sourceId: 'standalone', - status: 'installed', - lastLaunchedAt: 100 - }) - const newer = await installations.add({ - name: 'newer', - installPath: path.join(tmpRoot, 'newer'), - sourceId: 'standalone', - status: 'installed', - lastLaunchedAt: 500 - }) - const recent = await installations.resolveAutoLaunchInstall('last') - expect(recent!.id).toBe(newer.id) - }) - - it('an installation id resolves the matching install, or null when stale', async () => { - const installations = await loadInstallations() - const a = await installations.add({ - name: 'a', - installPath: path.join(tmpRoot, 'a'), - sourceId: 'standalone', - status: 'installed' - }) - const found = await installations.resolveAutoLaunchInstall(a.id) - expect(found!.id).toBe(a.id) - expect(await installations.resolveAutoLaunchInstall('inst-does-not-exist')).toBeNull() - }) -}) - describe('installations.load (legacy shared-storage flag migrations)', () => { function writeRawInstallations(records: Record[]): string { fs.mkdirSync(userDataPath, { recursive: true }) diff --git a/src/main/installations.ts b/src/main/installations.ts index 9cea68364..a800815c0 100644 --- a/src/main/installations.ts +++ b/src/main/installations.ts @@ -397,18 +397,6 @@ export async function getRecentByCategory( return best && bestTs > -Infinity ? best : null } -export async function resolveAutoLaunchInstall( - autoLaunchValue: string | undefined | null -): Promise { - if (autoLaunchValue == null || autoLaunchValue === '' || autoLaunchValue === 'none') { - return null - } - if (autoLaunchValue === 'last') { - return getRecent() - } - return get(autoLaunchValue) -} - export async function seedDefaults(defaults: Record[]): Promise { const seeded = await enqueue(async () => { const installations = await loadForWrite() diff --git a/src/main/lib/firstBuildAutoStart.test.ts b/src/main/lib/firstBuildAutoStart.test.ts new file mode 100644 index 000000000..1bcc68e28 --- /dev/null +++ b/src/main/lib/firstBuildAutoStart.test.ts @@ -0,0 +1,172 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { afterAll, afterEach, describe, expect, it, vi } from 'vitest' + +const electronHome = vi.hoisted(() => ({ dir: '' })) + +vi.mock('electron', () => ({ + app: { + isPackaged: false, + getPath: () => + (electronHome.dir ||= fs.mkdtempSync(path.join(os.tmpdir(), 'first-build-auto-start-'))), + getVersion: () => '0.0.0-test', + getLocale: () => 'en', + on: () => {} + }, + ipcMain: { handle: vi.fn(), on: vi.fn(), off: vi.fn() }, + dialog: {}, + shell: {}, + WebContentsView: class {}, + BrowserWindow: { getAllWindows: () => [] }, + nativeTheme: { on: vi.fn(), shouldUseDarkColors: false } +})) + +import * as installations from '../installations' +import * as settings from '../settings' +import { pinAutoStartToALocalBuild, startFirstBuildWithDesktop } from './firstBuildAutoStart' + +async function installedBuild(name: string, lastLaunchedAt?: number): Promise { + const entry = await installations.add({ + name, + sourceId: 'standalone', + status: 'installed', + installPath: path.join(electronHome.dir, name), + ...(lastLaunchedAt === undefined ? {} : { lastLaunchedAt }) + }) + return entry.id +} + +afterEach(async () => { + for (const inst of await installations.list()) await installations.remove(inst.id) + settings.set('autoLaunchOnStartup', undefined) + settings.set('autoStartAwaitingFirstStart', undefined) +}) + +afterAll(() => { + if (electronHome.dir) fs.rmSync(electronHome.dir, { recursive: true, force: true }) +}) + +describe('Auto start for a first build', () => { + it('gives the next first build Auto start after the old Auto start build was uninstalled', async () => { + const removed = await installedBuild('Old GPU build') + settings.set('autoLaunchOnStartup', removed) + await installations.remove(removed) + const fresh = await installedBuild('New GPU build') + + await startFirstBuildWithDesktop(fresh) + + expect(settings.get('autoLaunchOnStartup')).toBe(fresh) + expect(settings.get('autoStartAwaitingFirstStart')).toBe(fresh) + }) + + it('gives the new build Auto start while the old Auto start build is being uninstalled', async () => { + const leaving = await installedBuild('Old GPU build') + settings.set('autoLaunchOnStartup', leaving) + await installations.update(leaving, { status: 'partial-delete' }) + const fresh = await installedBuild('New GPU build') + + await startFirstBuildWithDesktop(fresh) + + expect(settings.get('autoLaunchOnStartup')).toBe(fresh) + }) + + it('leaves a picked build alone while that build is updating', async () => { + const picked = await installedBuild('Picked') + settings.set('autoLaunchOnStartup', picked) + await installations.update(picked, { status: 'updating' }) + const fresh = await installedBuild('Only installed build') + + await startFirstBuildWithDesktop(fresh) + + expect(settings.get('autoLaunchOnStartup')).toBe(picked) + }) + + it('leaves a saved Last used build alone', async () => { + settings.set('autoLaunchOnStartup', 'last') + const fresh = await installedBuild('Only build') + + await startFirstBuildWithDesktop(fresh) + + expect(settings.get('autoLaunchOnStartup')).toBe('last') + }) +}) + +describe('a saved Last used build, now that only a build can be picked', () => { + it('becomes the build that would have started, so its tile shows Auto start', async () => { + await installedBuild('Older', 1_000) + const recent = await installedBuild('Used yesterday', 2_000) + settings.set('autoLaunchOnStartup', 'last') + + const started = await pinAutoStartToALocalBuild() + + expect(settings.get('autoLaunchOnStartup')).toBe(recent) + expect(started?.id).toBe(recent) + }) + + it('becomes None when no build has ever started', async () => { + await installedBuild('Never started') + settings.set('autoLaunchOnStartup', 'last') + + await pinAutoStartToALocalBuild() + + expect(settings.get('autoLaunchOnStartup')).toBe('none') + }) + + it('leaves a picked build as it is', async () => { + const picked = await installedBuild('Picked', 1_000) + await installedBuild('Used more recently', 2_000) + settings.set('autoLaunchOnStartup', picked) + + const started = await pinAutoStartToALocalBuild() + + expect(settings.get('autoLaunchOnStartup')).toBe(picked) + expect(started?.id).toBe(picked) + }) + + it('becomes None when the build used last was Comfy Cloud', async () => { + await installedBuild('Local', 1_000) + await installations.add({ + name: 'Comfy Cloud', + sourceId: 'cloud', + status: 'installed', + lastLaunchedAt: 2_000 + }) + settings.set('autoLaunchOnStartup', 'last') + + await pinAutoStartToALocalBuild() + + expect(settings.get('autoLaunchOnStartup')).toBe('none') + }) +}) + +describe('Comfy Cloud picked in the old Settings dropdown', () => { + it('becomes None, since no tile can show or turn off Auto start on Cloud', async () => { + const cloud = await installations.add({ + name: 'Comfy Cloud', + sourceId: 'cloud', + status: 'installed' + }) + settings.set('autoLaunchOnStartup', cloud.id) + + const started = await pinAutoStartToALocalBuild() + + expect(settings.get('autoLaunchOnStartup')).toBe('none') + expect(started).toBeNull() + }) +}) + +describe('the build Desktop starts when it opens', () => { + it('is none when Auto start is off', async () => { + await installedBuild('Idle', 1_000) + + expect(await pinAutoStartToALocalBuild()).toBeNull() + }) + + it('is none when the Auto start build no longer exists, and the setting is left for the next first build', async () => { + settings.set('autoLaunchOnStartup', 'inst-gone') + + expect(await pinAutoStartToALocalBuild()).toBeNull() + expect(settings.get('autoLaunchOnStartup')).toBe('inst-gone') + }) +}) diff --git a/src/main/lib/firstBuildAutoStart.ts b/src/main/lib/firstBuildAutoStart.ts new file mode 100644 index 000000000..6e9cc42cf --- /dev/null +++ b/src/main/lib/firstBuildAutoStart.ts @@ -0,0 +1,68 @@ +import * as installations from '../installations' +import * as settings from '../settings' +import { AUTO_LAUNCH_LAST, AUTO_LAUNCH_NONE } from '../settings' +import { applySettingSet } from './ipc/registerSettingsHandlers' + +type InstallationRecord = installations.InstallationRecord + +function saveOrWarn(save: () => void): void { + try { + save() + } catch (err) { + console.warn('[auto-start] could not save the Auto start setting:', err) + } +} + +function isCloud(inst: InstallationRecord): boolean { + return inst.sourceId === installations.CLOUD_SOURCE_ID +} + +function isBeingUninstalled(inst: InstallationRecord): boolean { + return inst.status === 'partial-delete' +} + +async function isOnlyBuildWithoutAutoStart(installationId: string): Promise { + const builds = await installations.list() + const current = settings.get('autoLaunchOnStartup') + const chosen = + current === AUTO_LAUNCH_LAST || + builds.some((inst) => inst.id === current && !isCloud(inst) && !isBeingUninstalled(inst)) + if (chosen) return false + const localBuilds = builds.filter((inst) => !isCloud(inst) && inst.status === 'installed') + return localBuilds.length === 1 && localBuilds[0]!.id === installationId +} + +export async function startFirstBuildWithDesktop(installationId: string): Promise { + try { + if (!(await isOnlyBuildWithoutAutoStart(installationId))) return + settings.set('autoStartAwaitingFirstStart', installationId) + applySettingSet('autoLaunchOnStartup', installationId) + } catch (err) { + console.warn('[auto-start] could not give the first build Auto start:', err) + } +} + +export function settleAutoStartOnFirstStart(installationId: string, started: boolean): void { + if (settings.get('autoStartAwaitingFirstStart') !== installationId) return + saveOrWarn(() => { + settings.set('autoStartAwaitingFirstStart', undefined) + if (!started && settings.get('autoLaunchOnStartup') === installationId) { + applySettingSet('autoLaunchOnStartup', AUTO_LAUNCH_NONE) + } + }) +} + +async function savedAutoStartBuild(saved: string): Promise { + return saved === AUTO_LAUNCH_LAST ? installations.getRecent() : installations.get(saved) +} + +export async function pinAutoStartToALocalBuild(): Promise { + const saved = settings.get('autoLaunchOnStartup') + if (typeof saved !== 'string' || saved === '' || saved === AUTO_LAUNCH_NONE) return null + const build = await savedAutoStartBuild(saved) + const localBuild = build && !isCloud(build) ? build : null + if (saved === AUTO_LAUNCH_LAST || build !== localBuild) { + saveOrWarn(() => settings.set('autoLaunchOnStartup', localBuild?.id ?? AUTO_LAUNCH_NONE)) + } + return localBuild +} diff --git a/src/main/lib/ipc/installInstance.integration.test.ts b/src/main/lib/ipc/installInstance.integration.test.ts index a0717044e..ee17545ae 100644 --- a/src/main/lib/ipc/installInstance.integration.test.ts +++ b/src/main/lib/ipc/installInstance.integration.test.ts @@ -28,7 +28,8 @@ const h = vi.hoisted(() => ({ masterSha: '', updateScriptExitCode: 0, updateScriptRuns: [] as string[][], - restoredSnapshots: [] as string[] + restoredSnapshots: [] as string[], + settings: new Map() })) vi.mock('electron', () => ({ @@ -63,9 +64,15 @@ vi.mock('../../settings', () => ({ get: vi.fn((key: string): unknown => { if (key === 'cacheDir') return h.cacheDir if (key === 'maxCachedDownloads') return 5 - return undefined + if (key === 'autoLaunchOnStartup') return h.settings.get(key) ?? 'none' + return h.settings.get(key) }), - set: vi.fn(async () => {}), + set: vi.fn((key: string, value: unknown) => { + h.settings.set(key, value) + }), + getTrackedSettingsTelemetryProperties: vi.fn(() => ({})), + AUTO_LAUNCH_NONE: 'none', + AUTO_LAUNCH_LAST: 'last', getAll: vi.fn(() => ({})), getMirrorConfig: vi.fn(() => ({ pypiMirror: undefined, useChineseMirrors: false })), defaults: { modelsDirs: ['/unused'], inputDir: '/unused', outputDir: '/unused' } @@ -252,6 +259,9 @@ vi.mock('child_process', async (importOriginal) => { }) import { registerInstallationHandlers } from './registerInstallationHandlers' +import { download } from '../download' +import { restoreSnapshotIntoInstallation } from '../standaloneMigration' +import * as installations from '../../installations' import { getLogsBuffer } from '../logsBroadcast' import { clearVersionCache } from '../version-resolve' import { standalone } from '../../sources/standalone' @@ -411,6 +421,7 @@ describe.skipIf(!gitAvailable())('installing a standalone build', () => { h.updateScriptExitCode = 0 h.updateScriptRuns = [] h.restoredSnapshots = [] + h.settings.clear() buildBundle(root) clearVersionCache() sent = [] @@ -479,6 +490,109 @@ describe.skipIf(!gitAvailable())('installing a standalone build', () => { return h.records.get(installId) as unknown as InstallationRecord } + describe('Auto start after the first build installs', () => { + const autoStart = (): unknown => h.settings.get('autoLaunchOnStartup') ?? 'none' + const otherBuild = (id: string, sourceId: string): Record => ({ + id, + name: id, + sourceId, + installPath: path.join(root, id), + status: 'installed', + createdAt: new Date(0).toISOString() + }) + + it('starts the first build with Desktop once it installs', async () => { + h.records.set('cloud', otherBuild('cloud', 'cloud')) + + expect(await install(picked({ release: 'stable', comfyVersion: NEWEST_STABLE_TAG }))).toEqual( + { + ok: true + } + ) + + expect(autoStart()).toBe(installId) + expect( + h.settings.get('autoStartAwaitingFirstStart'), + 'its first start decides whether Auto start stays on' + ).toBe(installId) + }) + + it('leaves Auto start off when another build is already installed', async () => { + h.records.set('older', otherBuild('older', 'standalone')) + + await install(picked({ release: 'stable', comfyVersion: NEWEST_STABLE_TAG })) + + expect(autoStart()).toBe('none') + }) + + it('keeps a build the user already picked for Auto start', async () => { + h.settings.set('autoLaunchOnStartup', 'cloud') + h.records.set('cloud', otherBuild('cloud', 'cloud')) + + await install(picked({ release: 'stable', comfyVersion: NEWEST_STABLE_TAG })) + + expect(autoStart()).toBe('cloud') + }) + + it('still reports a finished install when the Auto start setting cannot be saved', async () => { + const settings = vi.mocked(await import('../../settings')) + const saveSetting = settings.set.getMockImplementation()! + settings.set.mockImplementation((key, value) => { + if (key === 'autoStartAwaitingFirstStart') + throw new Error('ENOSPC: no space left on device') + saveSetting(key, value) + }) + const warned = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const result = await install(picked({ release: 'stable', comfyVersion: NEWEST_STABLE_TAG })) + warned.mockRestore() + settings.set.mockImplementation(saveSetting) + + expect(result).toEqual({ ok: true }) + expect(record().status).toBe('installed') + }) + + it('leaves Auto start off when the install fails', async () => { + vi.mocked(download).mockRejectedValueOnce(new Error('The network went away')) + + const result = await install(picked({ release: 'stable', comfyVersion: NEWEST_STABLE_TAG })) + + expect(result.ok).toBe(false) + expect(autoStart()).toBe('none') + }) + + it('leaves Auto start off when the snapshot it was asked to restore fails', async () => { + const staged = path.join(root, 'staged-snapshot.json') + fs.writeFileSync(staged, '{}') + vi.mocked(restoreSnapshotIntoInstallation).mockRejectedValueOnce( + new Error('The snapshot could not be restored') + ) + + const result = await install({ + ...picked({ release: 'v0.3.48-env1' }), + pendingSnapshotRestore: staged + }) + + expect(result.ok).toBe(false) + expect(autoStart()).toBe('none') + }) + + it('keeps a build the user picks for Auto start while the build list is being read', async () => { + h.records.set('cloud', otherBuild('cloud', 'cloud')) + const list = vi.mocked(installations.list) + const readList = list.getMockImplementation()! + list.mockImplementationOnce(async () => { + const builds = await readList() + h.settings.set('autoLaunchOnStartup', 'cloud') + return builds + }) + + await install(picked({ release: 'stable', comfyVersion: NEWEST_STABLE_TAG })) + + expect(autoStart()).toBe('cloud') + }) + }) + it('lists four steps for the default install and names the version it will get', async () => { const result = await install(picked({ release: 'stable', comfyVersion: NEWEST_STABLE_TAG })) diff --git a/src/main/lib/ipc/registerInstallationHandlers.ts b/src/main/lib/ipc/registerInstallationHandlers.ts index 95b2ccbe5..1bf0bad87 100644 --- a/src/main/lib/ipc/registerInstallationHandlers.ts +++ b/src/main/lib/ipc/registerInstallationHandlers.ts @@ -53,6 +53,7 @@ import { markInstallSettled } from './installationVisibility' import { answerCoreBetaArgs } from '../coreBetaPreview' +import { startFirstBuildWithDesktop } from '../firstBuildAutoStart' function _kickReleaseCachePrewarm(allInstalls: InstallationRecord[]): void { void runStartupReleaseChecks(allInstalls, { @@ -407,6 +408,7 @@ export function registerInstallationHandlers(): void { method: express ? 'express' : 'manual', express: !!express }) + if (!snapshotRestoreError) await startFirstBuildWithDesktop(installationId) } if (snapshotRestoreError) { return snapshotRestoreFailureResult(installationId, snapshotRestoreError) diff --git a/src/main/lib/ipc/registerSettingsHandlers.test.ts b/src/main/lib/ipc/registerSettingsHandlers.test.ts index e176075bc..7979268f9 100644 --- a/src/main/lib/ipc/registerSettingsHandlers.test.ts +++ b/src/main/lib/ipc/registerSettingsHandlers.test.ts @@ -11,7 +11,7 @@ vi.mock('./shared', async () => { const { lookupEnMessage } = await import('../localeTestHelper') return { ipcMain: { handle: vi.fn(), on: vi.fn() }, - nativeTheme: {}, + nativeTheme: { on: vi.fn() }, sources: [], settings: { getAll: () => mockSettings, @@ -43,9 +43,14 @@ vi.mock('../globalSettingsEvents', () => ({ globalSettingsEvents: { on: vi.fn(), emit: vi.fn() } })) vi.mock('../e2eOverrides', () => ({ recordIpcInvocation: vi.fn() })) -vi.mock('../../settings', () => ({ AUTO_LAUNCH_NONE: 'none', AUTO_LAUNCH_LAST: 'last' })) +vi.mock('../../settings', () => ({})) -import { applySettingSet, buildSettingsSections } from './registerSettingsHandlers' +import { ipcMain } from './shared' +import { + applySettingSet, + buildSettingsSections, + registerSettingsHandlers +} from './registerSettingsHandlers' function resetMockSettings(): void { for (const key of Object.keys(mockSettings)) delete mockSettings[key] @@ -195,3 +200,19 @@ describe('applySettingSet beta enrolment consent', () => { expect(mockSettings.betaFeaturesEnabled).toBe(false) }) }) + +describe('picking the Auto start build by hand', () => { + it("ends the wait on a new build's first start, so a later failure keeps the pick", () => { + resetMockSettings() + registerSettingsHandlers() + const setSetting = vi + .mocked(ipcMain.handle) + .mock.calls.find(([channel]) => channel === 'set-setting')![1] + mockSettings['autoStartAwaitingFirstStart'] = 'fresh-install' + + void setSetting({} as Electron.IpcMainInvokeEvent, 'autoLaunchOnStartup', 'fresh-install') + + expect(mockSettings['autoStartAwaitingFirstStart']).toBeUndefined() + expect(mockSettings['autoLaunchOnStartup']).toBe('fresh-install') + }) +}) diff --git a/src/main/lib/ipc/registerSettingsHandlers.ts b/src/main/lib/ipc/registerSettingsHandlers.ts index fd9f0ca58..e614c5c63 100644 --- a/src/main/lib/ipc/registerSettingsHandlers.ts +++ b/src/main/lib/ipc/registerSettingsHandlers.ts @@ -18,11 +18,8 @@ import { globalSettingsEvents } from '../globalSettingsEvents' import { acknowledgeBetaActivationNotice, peekBetaActivationNotice } from '../betaActivationNotice' import { recordIpcInvocation } from '../e2eOverrides' import type { SettingsSection } from '../../../types/ipc' -import { AUTO_LAUNCH_LAST, AUTO_LAUNCH_NONE } from '../../settings' -export function buildSettingsSections( - installs?: Pick<{ id: string; name: string }, 'id' | 'name'>[] -): SettingsSection[] { +export function buildSettingsSections(): SettingsSection[] { const s = settings.getAll() const chineseMirrorsField = { id: 'useChineseMirrors', @@ -47,19 +44,6 @@ export function buildSettingsSections( options: i18n.getAvailableLocales() }, - { - id: 'autoLaunchOnStartup', - label: i18n.t('settings.autoLaunchOnStartup'), - type: 'select', - value: (s.autoLaunchOnStartup as string | undefined) ?? AUTO_LAUNCH_NONE, - options: [ - { value: AUTO_LAUNCH_NONE, label: i18n.t('settings.autoLaunchOnStartupNone') }, - { value: AUTO_LAUNCH_LAST, label: i18n.t('settings.autoLaunchOnStartupLast') }, - ...(installs ?? []).map((i) => ({ value: i.id, label: i.name })) - ], - tooltip: i18n.t('settings.autoLaunchOnStartupDescription') - }, - { id: 'confirmBeforeClosingWindow', label: i18n.t('settings.confirmBeforeClosingWindow'), @@ -287,6 +271,7 @@ export function registerSettingsHandlers(): void { ipcMain.handle('set-setting', (_event, key: string, value: unknown) => { recordIpcInvocation('set-setting', { key, value }) + if (key === 'autoLaunchOnStartup') settings.set('autoStartAwaitingFirstStart', undefined) applySettingSet(key, value) }) diff --git a/src/main/lib/ipc/sessionActions/launch.ts b/src/main/lib/ipc/sessionActions/launch.ts index 17d846bec..b5944df7e 100644 --- a/src/main/lib/ipc/sessionActions/launch.ts +++ b/src/main/lib/ipc/sessionActions/launch.ts @@ -83,6 +83,7 @@ import type { PreLaunchPhase } from '../../launchPhases' import { scanCustomNodes } from '../../nodes' import type { LaunchProgressTracker } from '../../launchProgress' import { clearCrash, recordCrash } from '../../crashBuffer' +import { settleAutoStartOnFirstStart } from '../../firstBuildAutoStart' import type { ComfyExitedData } from '../../../../types/ipc' import * as telemetry from '../../telemetry' import { buildErrorFields, errorTail } from '../../../../shared/errorEvent' @@ -904,8 +905,16 @@ export async function handleLaunch(ctx: ActionContext): Promise { } const launch = _beginLaunch(sessionId) const prefetchHold = { release: (): void => {} } + const settleFirstStart = (started: boolean): void => { + if (sessionId === installationId) settleAutoStartOnFirstStart(installationId, started) + } try { - return await runLaunch(ctx, launch.abort, prefetchHold) + const result = await runLaunch(ctx, launch.abort, prefetchHold) + if (!result.cancelled) settleFirstStart(result.ok) + return result + } catch (err) { + settleFirstStart(false) + throw err } finally { prefetchHold.release() if (_operationAborts.get(sessionId) === launch.abort) _operationAborts.delete(sessionId) diff --git a/src/main/lib/ipc/sessionActions/launchPorts.integration.test.ts b/src/main/lib/ipc/sessionActions/launchPorts.integration.test.ts index cf6a07e11..5101442f3 100644 --- a/src/main/lib/ipc/sessionActions/launchPorts.integration.test.ts +++ b/src/main/lib/ipc/sessionActions/launchPorts.integration.test.ts @@ -25,7 +25,8 @@ vi.mock('electron', () => ({ })) const builds = vi.hoisted(() => ({ - commands: new Map>() + commands: new Map>(), + unreadable: new Set() })) vi.mock('../shared', async (importOriginal) => { @@ -38,6 +39,7 @@ vi.mock('../shared', async (importOriginal) => { skipInstall: true, getDefaults: () => ({}), getLaunchCommand: (inst: { id: string }) => { + if (builds.unreadable.has(inst.id)) throw new Error('pyvenv.cfg is unreadable') const command = builds.commands.get(inst.id) return command ? { ...command, args: [...(command.args as string[])] } : null } @@ -67,6 +69,7 @@ import * as i18n from '../../i18n' import { lookupEnMessage } from '../../localeTestHelper' import { isPortListening } from '../../process' import * as telemetry from '../../telemetry' +import * as settings from '../../../settings' import type { ActionContext, ActionResult } from './types' const FAKE_COMFY = ` @@ -77,6 +80,10 @@ const args = process.argv.slice(2) const valueOf = (flag) => args[args.lastIndexOf(flag) + 1] const port = Number(valueOf('--port')) const name = valueOf('--name') +if (fs.existsSync(path.join(valueOf('--state'), 'crash-on-boot'))) { + process.stderr.write('RuntimeError: Torch not compiled with CUDA enabled\\n') + process.exit(1) +} const bootFile = path.join(valueOf('--state'), 'boot-ms') const bootMs = fs.existsSync(bootFile) ? Number(fs.readFileSync(bootFile, 'utf-8')) : 0 const server = http.createServer((req, res) => { @@ -137,6 +144,10 @@ async function whoAnswersOn(port: number): Promise { return (await fetch(`http://127.0.0.1:${port}/`)).text() } +function crashOnBoot(inst: InstallationRecord): void { + fs.writeFileSync(path.join(inst.installPath, 'crash-on-boot'), '') +} + function slowNextBoot(inst: InstallationRecord, ms: number): void { fs.writeFileSync(path.join(inst.installPath, 'boot-ms'), String(ms)) } @@ -184,6 +195,9 @@ afterEach(async () => { await Promise.all(outsiders.splice(0).map(stopOutsider)) _pendingPorts.clear() builds.commands.clear() + builds.unreadable.clear() + settings.set('autoLaunchOnStartup', undefined) + settings.set('autoStartAwaitingFirstStart', undefined) vi.restoreAllMocks() }) @@ -253,3 +267,58 @@ describe('two builds that want the same port', { timeout: 30_000 }, () => { expect(_runningSessions.has('studio')).toBe(false) }) }) + +describe('Auto start on the first build, decided by its first start', { timeout: 30_000 }, () => { + function justInstalled(inst: InstallationRecord): void { + settings.set('autoLaunchOnStartup', inst.id) + settings.set('autoStartAwaitingFirstStart', inst.id) + } + + it('keeps Auto start on once the new build starts', async () => { + const fresh = build('fresh-install') + justInstalled(fresh) + + const result = await start(fresh) + + expect(result.ok, result.message).toBe(true) + expect(settings.get('autoLaunchOnStartup')).toBe('fresh-install') + }) + + it('turns Auto start off when the new build fails to start', async () => { + const fresh = build('fresh-install') + crashOnBoot(fresh) + justInstalled(fresh) + + const result = await start(fresh) + + expect(result.ok).toBe(false) + expect(settings.get('autoLaunchOnStartup')).toBe('none') + }) + + it('turns Auto start off when the new build cannot even be set up to start', async () => { + const fresh = build('fresh-install') + builds.unreadable.add(fresh.id) + justInstalled(fresh) + + await expect(start(fresh)).rejects.toThrow('pyvenv.cfg is unreadable') + + expect(settings.get('autoLaunchOnStartup')).toBe('none') + }) + + it('leaves Auto start on when a build that already started once fails later', async () => { + const studio = build('studio') + justInstalled(studio) + expect((await start(studio)).ok).toBe(true) + for (const id of [..._runningSessions.keys()]) { + const session = _runningSessions.get(id) + _runningSessions.delete(id) + if (session?.proc) await killProcessTree(session.proc) + } + crashOnBoot(studio) + + const result = await start(studio) + + expect(result.ok).toBe(false) + expect(settings.get('autoLaunchOnStartup')).toBe('studio') + }) +}) diff --git a/src/main/popups/titlePopup.ts b/src/main/popups/titlePopup.ts index 8cb18f4d5..8345c1c69 100644 --- a/src/main/popups/titlePopup.ts +++ b/src/main/popups/titlePopup.ts @@ -39,7 +39,6 @@ import { buildInstallLocationFields } from '../lib/ipc/registerSettingsHandlers' import { globalSettingsEvents } from '../lib/globalSettingsEvents' -import * as installations from '../installations' import { getCachedGithubStarCount, getGithubStarCount } from '../lib/githubStars' import { comfyWindows, @@ -1040,7 +1039,7 @@ function openGlobalSettingsForHost( parent: parentEntry.window, parentEntryId, kind: 'global-settings', - snapshot: buildGlobalSettingsSnapshot(undefined, initialTab, highlightFieldId), + snapshot: buildGlobalSettingsSnapshot(initialTab, highlightFieldId), anchor: { x: 0, y: TITLEBAR_HEIGHT }, theme: parentEntry.lastTheme, titleBarSender @@ -1049,7 +1048,7 @@ function openGlobalSettingsForHost( await getGithubStarCount('comfy-org/ComfyUI').catch(() => null) githubStarsFetchAttempted = true if (parentEntry.window.isDestroyed()) return - await broadcastGlobalSettingsSnapshotToTitlePopups(bindings) + broadcastGlobalSettingsSnapshotToTitlePopups(bindings) })() } @@ -1283,11 +1282,10 @@ function findSettingsFields( } function buildGlobalSettingsSnapshot( - installs?: Pick<{ id: string; name: string }, 'id' | 'name'>[], initialTab: GlobalSettingsTab | null = null, highlightFieldId: string | null = null ): GlobalSettingsSnapshot { - const settingsSections = buildSettingsSections(installs) + const settingsSections = buildSettingsSections() const mediaSections = buildMediaSections() const modelsPayload = buildModelsPayload() const generalRaw = findSettingsFields(settingsSections, 'settings.general', 0) @@ -1352,19 +1350,12 @@ function buildGlobalSettingsSnapshot( } } -async function broadcastGlobalSettingsSnapshotToTitlePopups( - _bindings: TitlePopupHostBindings -): Promise { - const hasOpen = Array.from(titlePopupsByParent.values()).some( - (e) => e.kind === 'global-settings' && (e.view.isOpen || e.view.pendingShowTimer !== null) - ) - if (!hasOpen) return - const installs = (await installations.list()).map((i) => ({ id: i.id, name: i.name })) +function broadcastGlobalSettingsSnapshotToTitlePopups(_bindings: TitlePopupHostBindings): void { for (const entry of titlePopupsByParent.values()) { if (entry.kind !== 'global-settings') continue if (!entry.view.isOpen && entry.view.pendingShowTimer === null) continue if (entry.view.popup.webContents.isDestroyed()) continue - const snapshot = buildGlobalSettingsSnapshot(installs) + const snapshot = buildGlobalSettingsSnapshot() const snapshotJson = JSON.stringify(snapshot) if (entry.lastGlobalSettingsBroadcastJson === snapshotJson) continue entry.lastGlobalSettingsBroadcastJson = snapshotJson @@ -2082,7 +2073,7 @@ export function registerTitlePopupIpc(bindings: TitlePopupHostBindings): void { const value = payload?.value if (typeof value !== 'number' || !Number.isFinite(value)) return globalSettingsLastCheckedAt = value - void broadcastGlobalSettingsSnapshotToTitlePopups(bindings) + broadcastGlobalSettingsSnapshotToTitlePopups(bindings) } ) @@ -2090,7 +2081,7 @@ export function registerTitlePopupIpc(bindings: TitlePopupHostBindings): void { installationEvents.on('changed', () => { void refreshCachedInstallsForPicker() void broadcastInstancePickerSnapshotToTitlePopups(bindings) - void broadcastGlobalSettingsSnapshotToTitlePopups(bindings) + broadcastGlobalSettingsSnapshotToTitlePopups(bindings) }) hostInstallEvents.on('changed', () => { void broadcastInstancePickerSnapshotToTitlePopups(bindings) @@ -2099,11 +2090,11 @@ export function registerTitlePopupIpc(bindings: TitlePopupHostBindings): void { void broadcastInstancePickerSnapshotToTitlePopups(bindings) }) globalSettingsEvents.on('changed', () => { - void broadcastGlobalSettingsSnapshotToTitlePopups(bindings) + broadcastGlobalSettingsSnapshotToTitlePopups(bindings) void broadcastInstancePickerSnapshotToTitlePopups(bindings) }) updater.onUpdateStateChanged(() => { - void broadcastGlobalSettingsSnapshotToTitlePopups(bindings) + broadcastGlobalSettingsSnapshotToTitlePopups(bindings) }) ipcMain.on('comfy-popup-internal:noop', () => {}) } @@ -2111,7 +2102,7 @@ export function registerTitlePopupIpc(bindings: TitlePopupHostBindings): void { export function notifyGlobalSettingsDownloadProgress(progress: Record): void { lastAppUpdateProgress = progress if (!activeBindings) return - void broadcastGlobalSettingsSnapshotToTitlePopups(activeBindings) + broadcastGlobalSettingsSnapshotToTitlePopups(activeBindings) } export function _test_setTitlePopupEntry(webContentsId: number, entry: TitlePopupEntry): void { diff --git a/src/main/settings.ts b/src/main/settings.ts index 77b83d9bc..00c1cc7dc 100644 --- a/src/main/settings.ts +++ b/src/main/settings.ts @@ -30,6 +30,7 @@ export interface KnownSettings { autoUpdate?: boolean autoInstallUpdates?: boolean autoLaunchOnStartup?: string + autoStartAwaitingFirstStart?: string confirmBeforeClosingWindow?: boolean warnBeforeRunningMultipleInstances?: boolean hardwareAcceleration?: boolean @@ -142,6 +143,7 @@ const SETTINGS_SCHEMA = { } }, autoLaunchOnStartup: { nullable: false, telemetry: { policy: 'presence' } }, + autoStartAwaitingFirstStart: { nullable: false, telemetry: { policy: 'omit' } }, confirmBeforeClosingWindow: { nullable: false, telemetry: { policy: 'value', toTelemetry: (raw) => raw === true } diff --git a/src/renderer/src/composables/useAutoStartBuild.ts b/src/renderer/src/composables/useAutoStartBuild.ts index e4e19a3b3..686e83a47 100644 --- a/src/renderer/src/composables/useAutoStartBuild.ts +++ b/src/renderer/src/composables/useAutoStartBuild.ts @@ -1,9 +1,33 @@ -import { onScopeDispose, ref } from 'vue' +import { + getCurrentInstance, + hasInjectionContext, + inject, + onScopeDispose, + provide, + ref, + type InjectionKey +} from 'vue' const AUTO_START_SETTING = 'autoLaunchOnStartup' const AUTO_START_NONE = 'none' -export function useAutoStartBuild() { +export type AutoStartBuild = ReturnType + +const AUTO_START_BUILD: InjectionKey = Symbol('autoStartBuild') + +export function provideAutoStartBuild(): AutoStartBuild { + const autoStart = createAutoStartBuild() + provide(AUTO_START_BUILD, autoStart) + return autoStart +} + +export function useAutoStartBuild(): AutoStartBuild { + const shared = hasInjectionContext() ? inject(AUTO_START_BUILD, null) : null + if (shared) return shared + return getCurrentInstance() ? provideAutoStartBuild() : createAutoStartBuild() +} + +function createAutoStartBuild() { const autoStartValue = ref(undefined) let confirmedValue: unknown = undefined let revision = 0 diff --git a/src/renderer/src/composables/useInstallContextMenu.ts b/src/renderer/src/composables/useInstallContextMenu.ts index be7b1c085..1514ffc0e 100644 --- a/src/renderer/src/composables/useInstallContextMenu.ts +++ b/src/renderer/src/composables/useInstallContextMenu.ts @@ -8,6 +8,8 @@ import { Download, FolderOpen, History, + Power, + PowerOff, Settings2, Trash2 } from '@lucide/vue' @@ -16,6 +18,7 @@ import { useSessionStore } from '../stores/sessionStore' import { useProgressStore } from '../stores/progressStore' import { useModal } from './useModal' import { useStopAction } from './useStopAction' +import type { AutoStartBuild } from './useAutoStartBuild' import { revealInFolderLabel } from './usePlatform' import { progressOpKindForActionId, destroysInstanceForActionId } from '../lib/progressOpKind' import { shareLatestSnapshot } from '../lib/snapshots' @@ -33,6 +36,7 @@ export type InstallMenuActionId = | 'share' | 'promote-to-workspace' | 'copy-install' + | 'auto-start' | 'delete' export interface ManageOpenOptions { @@ -46,6 +50,7 @@ export function useInstallContextMenu( onShowProgress?: (showOpts: ShowProgressOpts) => void onUpdate?: (inst: Installation) => Promise canPromoteToWorkspace?: (inst: Installation) => boolean + autoStart?: AutoStartBuild } = {} ) { const { t } = useI18n() @@ -217,6 +222,17 @@ export function useInstallContextMenu( items.push(...cluster) } + if (opts.autoStart && isLocalLikeInstall(inst) && isInstalled(inst)) { + const startsOnOpen = opts.autoStart.startsOnOpen(inst.id) + const [head] = items + if (head) head.separator = true + items.unshift({ + id: 'auto-start', + label: startsOnOpen ? t('home.turnOffAutoStart') : t('home.turnOnAutoStart'), + icon: startsOnOpen ? PowerOff : Power + }) + } + return items } @@ -260,7 +276,11 @@ export function useInstallContextMenu( } } - async function triggerAction(id: string, inst: Installation): Promise { + async function triggerAction( + id: string, + inst: Installation, + actionOpts: { confirmed?: boolean } = {} + ): Promise { if (id === 'manage') { opts.onManage?.(inst) } else if (id === 'update') { @@ -310,19 +330,23 @@ export function useInstallContextMenu( setPromotingToWorkspace(inst.id, false) } if (failureMessage) await modal.alert({ title, message: failureMessage }) + } else if (id === 'auto-start') { + await opts.autoStart?.setStartsOnOpen(inst.id, !opts.autoStart.startsOnOpen(inst.id)) } else if (id === 'copy-install') { opts.onManage?.(inst, { autoAction: 'copy' }) } else if (id === 'delete') { if (opts.onShowProgress) { const deleteLabel = t('actions.delete') - const confirmed = await modal.confirm({ - title: t('actions.deleteConfirmTitle'), - message: `${inst.installPath ? inst.installPath + '\n\n' : ''}${t( - 'actions.deleteConfirmMessage' - )}\n\n${t('actions.deleteConfirmDetail')}`, - confirmLabel: deleteLabel, - confirmStyle: 'danger' - }) + const confirmed = + actionOpts.confirmed === true || + (await modal.confirm({ + title: t('actions.deleteConfirmTitle'), + message: `${inst.installPath ? inst.installPath + '\n\n' : ''}${t( + 'actions.deleteConfirmMessage' + )}\n\n${t('actions.deleteConfirmDetail')}`, + confirmLabel: deleteLabel, + confirmStyle: 'danger' + })) if (!confirmed) return opts.onShowProgress({ installationId: inst.id, @@ -385,6 +409,7 @@ export function useInstallContextMenu( return { ctxMenu, ctxMenuItems, + getMenuItems, openCardMenu, openKebabMenu, handleCtxMenuSelect, diff --git a/src/renderer/src/panel/AppSidebar.vue b/src/renderer/src/panel/AppSidebar.vue index eacf5bc1e..3a7dcdb84 100644 --- a/src/renderer/src/panel/AppSidebar.vue +++ b/src/renderer/src/panel/AppSidebar.vue @@ -1,5 +1,5 @@ - - diff --git a/src/renderer/src/panel/home/BuildMenu.test.ts b/src/renderer/src/panel/home/BuildMenu.test.ts new file mode 100644 index 000000000..189cd8ffb --- /dev/null +++ b/src/renderer/src/panel/home/BuildMenu.test.ts @@ -0,0 +1,413 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, h } from 'vue' +import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' + +import AppSidebar from '../AppSidebar.vue' +import HomeBuildCard from './HomeBuildCard.vue' +import { provideBuildMenuHost, type BuildMenuHost } from './useBuildMenu' +import { provideBuildLogs } from '../../composables/useBuildProgress' +import { useInstallationStore } from '../../stores/installationStore' +import { useProgressStore, type Operation } from '../../stores/progressStore' +import { useSessionStore } from '../../stores/sessionStore' +import type { Installation } from '../../types/ipc' + +const BUILD: Installation = { + id: 'flux', + name: 'Flux Sandbox', + sourceId: 'standalone', + sourceLabel: 'Standalone', + sourceCategory: 'local', + status: 'installed', + version: 'v0.42.4', + installPath: '/Users/someone/ComfyUI/Flux Sandbox' +} + +type State = 'ready' | 'starting' | 'installing' | 'running' | 'uninstalling' + +const REST = ['|', 'manage', 'copy-install', 'reveal-in-folder', '|', 'share', 'restore-snapshot'] +const EXPECTED: Record = { + ready: ['launch', '|', 'auto-start', ...REST, '|', 'delete'], + starting: ['view-logs', 'cancel', '|', 'auto-start', ...REST, '|', 'delete'], + installing: ['view-logs', 'cancel', '|', 'auto-start', ...REST, '|', 'delete'], + running: ['view-logs', 'restart', 'stop', '|', 'auto-start', ...REST, '|', 'delete'], + uninstalling: ['cancel', '|', 'auto-start', ...REST, '|', 'delete'] +} +const OPERATIONS: Partial>> = { + starting: { opKind: 'launch', flatPercent: 5 }, + installing: { opKind: 'install', flatPercent: 40 }, + uninstalling: { opKind: 'destructive', flatPercent: 18 } +} + +let host: BuildMenuHost & { [K in keyof BuildMenuHost]: ReturnType } +const mounted: VueWrapper[] = [] +const viewLogs = vi.fn() +const OTHER_BUILD_ID = 'other' +let saved: unknown + +beforeEach(() => { + saved = 'none' + for (const wrapper of mounted.splice(0)) wrapper.unmount() + document.body.innerHTML = '' + ;(window as unknown as { api: unknown }).api = { + platform: 'darwin', + navigatePanel: vi.fn(), + getAppsEnabled: vi.fn().mockResolvedValue(false), + getInstallations: vi.fn().mockResolvedValue([]), + onInstallationsChanged: vi.fn(() => () => {}), + onInstallationsVersionsUpdated: vi.fn(() => () => {}), + getSetting: vi.fn(async (key: string) => (key === 'autoLaunchOnStartup' ? saved : undefined)), + setSetting: vi.fn(async (key: string, value: unknown) => { + if (key === 'autoLaunchOnStartup') saved = value + }), + onSettingsChanged: vi.fn(() => () => {}), + comfybuilder: { + getAuthStatus: vi.fn().mockResolvedValue({ signedIn: false }), + onAuthChanged: vi.fn(() => () => {}) + } + } + host = { launch: vi.fn(), openDetails: vi.fn(), showProgress: vi.fn() } + viewLogs.mockReset() + setActivePinia(createPinia()) + useInstallationStore().installations = [BUILD] +}) + +function withHost(render: () => ReturnType) { + return defineComponent({ + setup() { + provideBuildMenuHost(host) + provideBuildLogs(viewLogs) + return render + } + }) +} + +function putIn(state: State): void { + const operation = OPERATIONS[state] + if (operation) { + useProgressStore().operations.set(BUILD.id, { + finished: false, + cancelRequested: false, + ...operation + } as Operation) + } + if (state === 'running') { + useSessionStore().runningInstances.set(BUILD.id, { + installationId: BUILD.id + } as never) + } +} + +async function mountTile(state: State): Promise { + const wrapper = mount( + withHost(() => h(HomeBuildCard, { build: BUILD, status: 'ready', tone: 'ember' })), + { attachTo: document.body } + ) + mounted.push(wrapper) + putIn(state) + await flushPromises() + return wrapper +} + +async function mountSidebar(state: State): Promise { + const wrapper = mount( + withHost(() => h(AppSidebar, { activePage: 'home' })), + { attachTo: document.body } + ) + mounted.push(wrapper) + putIn(state) + await flushPromises() + return wrapper +} + +async function shownMenu(): Promise { + await flushPromises() + await vi.waitFor(() => { + expect(document.querySelector('[data-testid="build-menu"]')).not.toBeNull() + }) + const menu = document.querySelector('[data-testid="build-menu"]')! + return [...menu.querySelectorAll('[role="menuitem"], [role="separator"]')].map((row) => + row.getAttribute('role') === 'separator' + ? '|' + : row.getAttribute('data-testid')!.replace('build-menu-', '') + ) +} + +async function closeMenu(): Promise { + document + .querySelector('[data-testid="build-menu"]') + ?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) + await flushPromises() + await vi.waitFor(() => { + expect(document.querySelector('[data-testid="build-menu"]')).toBeNull() + }) +} + +async function press(element: Element): Promise { + element.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })) + await new Promise((resolve) => setTimeout(resolve, 100)) + element.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 })) + await flushPromises() +} + +async function rightClick(element: Element): Promise { + element.dispatchEvent( + new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 40, clientY: 40 }) + ) + await flushPromises() +} + +describe('Build menu', () => { + it.each(Object.keys(EXPECTED) as State[])( + 'lists what a %s build can do now first, Uninstall last', + async (state) => { + const tile = await mountTile(state) + + await tile.get('[data-testid="home-build-more"]').trigger('click') + + expect(await shownMenu()).toEqual(EXPECTED[state]) + } + ) + + it.each(Object.keys(EXPECTED) as State[])( + 'opens the same items from the tile ⋯, a right-click on the tile and on the sidebar row for a %s build', + async (state) => { + const tile = await mountTile(state) + await tile.get('[data-testid="home-build-more"]').trigger('click') + const fromMore = await shownMenu() + await closeMenu() + + await rightClick(tile.get(`[data-build-id="${BUILD.id}"]`).element) + const fromTile = await shownMenu() + await closeMenu() + + const sidebar = await mountSidebar(state) + await rightClick(sidebar.get(`[data-testid="app-sidebar-build-${BUILD.id}"]`).element) + const fromSidebar = await shownMenu() + + expect(fromTile).toEqual(fromMore) + expect(fromSidebar).toEqual(fromMore) + } + ) + + it.each([ + ['a build whose install failed', { ...BUILD, id: 'broken', status: 'failed' }], + [ + 'Comfy Cloud', + { ...BUILD, id: 'cloud', sourceId: 'cloud', sourceCategory: 'cloud', installPath: undefined } + ] + ] satisfies [string, Installation][])('offers no Auto start for %s', async (_name, build) => { + const wrapper = mount( + withHost(() => h(HomeBuildCard, { build, status: 'ready', tone: 'ember' })), + { attachTo: document.body } + ) + mounted.push(wrapper) + await flushPromises() + + await wrapper.get('[data-testid="home-build-more"]').trigger('click') + + expect(await shownMenu()).not.toContain('auto-start') + }) + + it('asks inside the menu before it uninstalls, then uninstalls without another dialog', async () => { + const tile = await mountTile('ready') + await tile.get('[data-testid="home-build-more"]').trigger('click') + await shownMenu() + + document.querySelector('[data-testid="build-menu-delete"]')!.click() + await flushPromises() + + const question = document.querySelector('[data-testid="build-menu-uninstall-question"]') + expect(question?.textContent).toContain('Flux Sandbox') + expect(host.showProgress).not.toHaveBeenCalled() + + document.querySelector('[data-testid="build-menu-confirm-uninstall"]')!.click() + await flushPromises() + + expect(host.showProgress).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ installationId: BUILD.id, actionId: 'delete' }) + ) + expect(document.querySelector('[role="dialog"]')).toBeNull() + }) + + it('puts focus on the Uninstall answer when it asks', async () => { + const tile = await mountTile('ready') + await tile.get('[data-testid="home-build-more"]').trigger('click') + await shownMenu() + + document.querySelector('[data-testid="build-menu-delete"]')!.click() + await flushPromises() + + await vi.waitFor(() => + expect(document.activeElement).toBe( + document.querySelector('[data-testid="build-menu-confirm-uninstall"]') + ) + ) + }) + + it('closes the menu when the ⋯ button is pressed again', async () => { + const tile = await mountTile('ready') + const more = tile.get('[data-testid="home-build-more"]').element + await press(more) + await shownMenu() + + await press(more) + + await vi.waitFor(() => expect(document.querySelector('[data-testid="build-menu"]')).toBeNull()) + }) + + it('updates the sidebar menu when the build changes while it is open', async () => { + const sidebar = await mountSidebar('ready') + await rightClick(sidebar.get(`[data-testid="app-sidebar-build-${BUILD.id}"]`).element) + expect(await shownMenu()).toContain('auto-start') + + useInstallationStore().installations = [{ ...BUILD, status: 'failed' }] + await flushPromises() + + expect(await shownMenu()).not.toContain('auto-start') + }) + + it('drops the uninstall question when the build starts running, and never uninstalls it', async () => { + const tile = await mountTile('ready') + await tile.get('[data-testid="home-build-more"]').trigger('click') + await shownMenu() + document.querySelector('[data-testid="build-menu-delete"]')!.click() + await flushPromises() + expect(document.querySelector('[data-testid="build-menu-uninstall-question"]')).not.toBeNull() + + putIn('running') + await flushPromises() + + expect(document.querySelector('[data-testid="build-menu-uninstall-question"]')).toBeNull() + expect(document.querySelector('[data-testid="build-menu-confirm-uninstall"]')).toBeNull() + expect(host.showProgress).not.toHaveBeenCalled() + }) + + it('returns focus to the ⋯ button when the menu closes', async () => { + const tile = await mountTile('ready') + const more = tile.get('[data-testid="home-build-more"]') + more.element.focus() + await more.trigger('click') + await shownMenu() + + await closeMenu() + + await vi.waitFor(() => expect(document.activeElement).toBe(more.element)) + }) + + it('returns focus to the sidebar build when its menu closes', async () => { + const sidebar = await mountSidebar('ready') + const row = sidebar.get(`[data-testid="app-sidebar-build-${BUILD.id}"]`) + row.element.focus() + await rightClick(row.element) + await shownMenu() + + await closeMenu() + + await vi.waitFor(() => expect(document.activeElement).toBe(row.element)) + }) + + it('opens the logs when a starting build is clicked, and launches a ready one from the menu', async () => { + const tile = await mountTile('starting') + + await tile.get('[data-testid="home-build-starting"]').trigger('click') + expect(viewLogs).toHaveBeenCalledExactlyOnceWith(BUILD.id) + expect(host.launch).not.toHaveBeenCalled() + + useProgressStore().operations.clear() + await flushPromises() + await tile.get('[data-testid="home-build-more"]').trigger('click') + await shownMenu() + document.querySelector('[data-testid="build-menu-launch"]')!.click() + await flushPromises() + + expect(host.launch).toHaveBeenCalledExactlyOnceWith(BUILD) + }) + + it('opens no menu on a right-click on a page in the sidebar', async () => { + const sidebar = await mountSidebar('ready') + + for (const page of ['home', 'assets']) { + await rightClick(sidebar.get(`[data-testid="app-sidebar-${page}"]`).element) + } + + expect(document.querySelector('[data-reka-menu-content]')).toBeNull() + }) + + it.each([ + ['tile ⋯', 'more'], + ['sidebar row', 'sidebar'] + ] as const)( + 'from the %s, offers Auto start and saves this build when picked', + async (_name, from) => { + saved = OTHER_BUILD_ID + await openMenuFrom(from) + + const line = autoStartLine() + expect(line.textContent?.trim()).toBe('Auto start') + expect(line.querySelector('.lucide-power')).not.toBeNull() + line.click() + await flushPromises() + + expect(autoStartWrites()).toEqual([BUILD.id]) + expect(saved).toBe(BUILD.id) + } + ) + + it('offers Turn off Auto start on the build that starts with Desktop and sets None when picked', async () => { + saved = BUILD.id + const tile = await openMenuFrom('more') + + const line = autoStartLine() + expect(line.textContent?.trim()).toBe('Turn off Auto start') + expect(line.querySelector('.lucide-power-off')).not.toBeNull() + line.click() + await flushPromises() + + expect(autoStartWrites()).toEqual(['none']) + await vi.waitFor(() => expect(document.querySelector('[data-testid="build-menu"]')).toBeNull()) + await tile.get('[data-testid="home-build-more"]').trigger('click') + await shownMenu() + expect(autoStartLine().textContent?.trim()).toBe('Auto start') + }) + + it('keeps the Auto start line, in its own group, while the build installs', async () => { + const tile = await mountTile('installing') + await tile.get('[data-testid="home-build-more"]').trigger('click') + const shown = await shownMenu() + + expect(shown.slice(shown.indexOf('auto-start') - 1, shown.indexOf('auto-start') + 2)).toEqual([ + '|', + 'auto-start', + '|' + ]) + autoStartLine().click() + await flushPromises() + + expect(autoStartWrites()).toEqual([BUILD.id]) + }) +}) + +async function openMenuFrom(from: 'more' | 'sidebar'): Promise { + if (from === 'more') { + const tile = await mountTile('ready') + await tile.get('[data-testid="home-build-more"]').trigger('click') + await shownMenu() + return tile + } + const sidebar = await mountSidebar('ready') + await rightClick(sidebar.get(`[data-testid="app-sidebar-build-${BUILD.id}"]`).element) + await shownMenu() + return sidebar +} + +function autoStartWrites(): unknown[] { + return vi + .mocked(window.api.setSetting) + .mock.calls.filter(([key]) => key === 'autoLaunchOnStartup') + .map(([, value]) => value) +} + +function autoStartLine(): HTMLElement { + return document.querySelector('[data-testid="build-menu-auto-start"]')! +} diff --git a/src/renderer/src/panel/home/BuildMenu.vue b/src/renderer/src/panel/home/BuildMenu.vue new file mode 100644 index 000000000..9ecbcfc96 --- /dev/null +++ b/src/renderer/src/panel/home/BuildMenu.vue @@ -0,0 +1,157 @@ + + + diff --git a/src/renderer/src/panel/home/HomeBuildBusyActions.vue b/src/renderer/src/panel/home/HomeBuildBusyActions.vue deleted file mode 100644 index bb47cea25..000000000 --- a/src/renderer/src/panel/home/HomeBuildBusyActions.vue +++ /dev/null @@ -1,37 +0,0 @@ - - - diff --git a/src/renderer/src/panel/home/HomeBuildCard.vue b/src/renderer/src/panel/home/HomeBuildCard.vue index e5d9463c4..fb3c1fe37 100644 --- a/src/renderer/src/panel/home/HomeBuildCard.vue +++ b/src/renderer/src/panel/home/HomeBuildCard.vue @@ -1,12 +1,12 @@ diff --git a/src/renderer/src/panel/home/useBuildMenu.ts b/src/renderer/src/panel/home/useBuildMenu.ts new file mode 100644 index 000000000..fd7e652fa --- /dev/null +++ b/src/renderer/src/panel/home/useBuildMenu.ts @@ -0,0 +1,167 @@ +import { computed, inject, provide, type Component, type InjectionKey } from 'vue' +import { CircleStop, Play, RotateCw, ScrollText, X } from '@lucide/vue' +import { useI18n } from 'vue-i18n' +import { until } from '@vueuse/core' +import { useAutoStartBuild } from '../../composables/useAutoStartBuild' +import { buildProgressOf, useBuildProgress } from '../../composables/useBuildProgress' +import { useInstallContextMenu } from '../../composables/useInstallContextMenu' +import { useModal } from '../../composables/useModal' +import { useQuickUpdate } from '../../composables/useQuickUpdate' +import { openInstallManager } from '../../lib/openInstallManager' +import { useProgressStore } from '../../stores/progressStore' +import { useSessionStore } from '../../stores/sessionStore' +import type { Installation, ShowProgressOpts } from '../../types/ipc' + +export interface BuildMenuHost { + launch: (build: Installation, opts?: { isRestart?: boolean }) => void | Promise + openDetails: (build: Installation) => void | Promise + showProgress: (opts: ShowProgressOpts) => void | Promise +} + +export interface BuildMenuEntry { + id: string + label: string + icon?: Component + separator?: boolean + danger?: boolean + disabled?: boolean + title?: string +} + +const BUILD_MENU_HOST: InjectionKey = Symbol('buildMenuHost') +const NO_HOST: BuildMenuHost = { + launch: () => {}, + openDetails: () => {}, + showProgress: () => {} +} +const STOP_WAIT_MS = 15_000 + +export function provideBuildMenuHost(host: BuildMenuHost): void { + provide(BUILD_MENU_HOST, host) +} + +function startsGroup(entries: BuildMenuEntry[], items: BuildMenuEntry[]): void { + const [head] = entries + if (!head) return + head.separator = items.length > 0 + items.push(...entries) +} + +export function useBuildMenu(build: () => Installation) { + const { t } = useI18n() + const host = inject(BUILD_MENU_HOST, NO_HOST) + const modal = useModal() + const sessionStore = useSessionStore() + const progressStore = useProgressStore() + const install = useBuildProgress(build) + const { runQuickUpdate } = useQuickUpdate({ + onShowProgress: (opts) => void host.showProgress(opts), + onUnavailable: (inst) => openInstallManager(inst, { initialTab: 'update' }) + }) + const installMenu = useInstallContextMenu({ + onManage: (inst, options) => + options ? openInstallManager(inst, options) : void host.openDetails(inst), + onShowProgress: (opts) => void host.showProgress(opts), + onUpdate: runQuickUpdate, + autoStart: useAutoStartBuild() + }) + + function isLocal(inst: Installation): boolean { + return inst.sourceCategory !== 'cloud' + } + + const items = computed(() => { + const inst = build() + const progress = buildProgressOf(progressStore, inst.id) + const running = !progress && isLocal(inst) && sessionStore.isRunning(inst.id) + const items: BuildMenuEntry[] = [] + + const now: BuildMenuEntry[] = [] + if (progress) { + if (progress.kind !== 'uninstall') { + now.push({ id: 'view-logs', label: t('installProgress.viewLogs'), icon: ScrollText }) + } + now.push({ id: 'cancel', label: t('common.cancel'), icon: X, disabled: progress.cancelling }) + } else if (running) { + now.push( + { id: 'view-logs', label: t('installProgress.viewLogs'), icon: ScrollText }, + { id: 'restart', label: t('actions.restart'), icon: RotateCw }, + { id: 'stop', label: t('actions.stop'), icon: CircleStop } + ) + } else if (!sessionStore.isStopping(inst.id) && !sessionStore.isLaunching(inst.id)) { + now.push({ id: 'launch', label: t('actions.launch'), icon: Play }) + } + startsGroup(now, items) + + const existing = installMenu + .getMenuItems(inst) + .map(({ id, label, icon, disabled, title, style, separator }): BuildMenuEntry => ({ + id, + label, + icon, + disabled, + title, + separator, + danger: style === 'danger' + })) + + startsGroup( + existing.filter((item) => item.id === 'auto-start'), + items + ) + + startsGroup( + existing.filter( + (item) => item.id !== 'stop' && item.id !== 'delete' && item.id !== 'auto-start' + ), + items + ) + startsGroup( + existing.filter((item) => item.id === 'delete'), + items + ) + return items + }) + + async function restart(inst: Installation): Promise { + const confirmed = await modal.confirm({ + title: t('actions.restartConfirmTitle'), + message: t('actions.restartConfirmMessage'), + confirmLabel: t('actions.restartConfirm'), + confirmStyle: 'danger' + }) + if (!confirmed) return + try { + await window.api.stopComfyUI(inst.id) + } catch (err) { + await modal.alert({ + title: t('actions.restart'), + message: (err as Error)?.message || String(err) + }) + return + } + await until(() => sessionStore.isRunning(inst.id)).toBe(false, { timeout: STOP_WAIT_MS }) + if (sessionStore.isRunning(inst.id)) return + await host.launch(inst, { isRestart: true }) + } + + async function run(id: string, opts: { confirmed?: boolean } = {}): Promise { + const inst = build() + switch (id) { + case 'launch': + return host.launch(inst) + case 'view-logs': + if (install.progress.value) install.viewLogs() + else openInstallManager(inst, { initialTab: 'console' }) + return + case 'cancel': + return install.cancel() + case 'restart': + return restart(inst) + default: + return installMenu.triggerAction(id, inst, opts) + } + } + + return { items, run } +} diff --git a/src/renderer/src/preview/scenarios.ts b/src/renderer/src/preview/scenarios.ts index 8cdd6f680..87ab0f473 100644 --- a/src/renderer/src/preview/scenarios.ts +++ b/src/renderer/src/preview/scenarios.ts @@ -57,7 +57,7 @@ export const SCENARIOS: PreviewScenario[] = [ { id: 'installing', title: 'First build installing, on Home', - ready: '[data-testid="home-build-install-detail"]', + ready: '[data-testid="home-build-progress"]', seed: () => FIRST_USE, arrange: async (stage) => { stage.bridge.reply({ installInstance: installThatKeepsRunning(stage.bridge) }) @@ -72,7 +72,7 @@ export const SCENARIOS: PreviewScenario[] = [ arrange: async (stage) => { stage.bridge.reply({ installInstance: installThatKeepsRunning(stage.bridge) }) await acceptTermsAndInstall(stage) - await stage.click('[data-testid="home-build-view-logs"]') + await stage.click('[data-testid="home-build-open"]') } }, { diff --git a/src/renderer/src/views/ChooserView.test.ts b/src/renderer/src/views/ChooserView.test.ts index 419ad966b..f64713779 100644 --- a/src/renderer/src/views/ChooserView.test.ts +++ b/src/renderer/src/views/ChooserView.test.ts @@ -11,7 +11,6 @@ import { useAuthStore } from '../stores/authStore' import { useDashboardScopeStore } from '../stores/dashboardScopeStore' import { PERSONAL_WORKSPACE_ID } from '../../../shared/workspaces' import { TID } from '../../../shared/testIds' -import { setChecked } from './testHelpers' import type { DevPlatformBuild, Installation } from '../types/ipc' vi.mock('../components/ContextMenu.vue', () => ({ @@ -259,33 +258,63 @@ describe('ChooserView', () => { expect(wrapper.emitted('open-details')).toBeUndefined() }) - it('ticks auto start on a tile, moving it from the other build without opening either', async () => { + it('sets Auto start from a tile menu, moving it from the other build', async () => { + let saved: unknown = 'a' const api = installMockApi([ - makeInstall({ id: 'a', name: 'Alpha' }), - makeInstall({ id: 'b', name: 'Beta' }) + makeInstall({ id: 'a', name: 'Alpha', status: 'installed' }), + makeInstall({ id: 'b', name: 'Beta', status: 'installed' }) ]) api.getSetting.mockImplementation(async (key: string) => - key === 'autoLaunchOnStartup' ? 'a' : undefined + key === 'autoLaunchOnStartup' ? saved : undefined ) + api.setSetting.mockImplementation(async (key: string, value: unknown) => { + if (key === 'autoLaunchOnStartup') saved = value + }) const wrapper = mountChooser() await flushPromises() - const autoStartBox = (id: string) => - wrapper.get(`[data-testid="chooser-tile-auto-start-${id}"] [role="checkbox"]`) - expect(autoStartBox('a').attributes('aria-checked')).toBe('true') + const tile = (id: string) => wrapper.get(`[data-testid="${TID.dashboardTile(id)}"]`) + const autoStartWrites = () => + api.setSetting.mock.calls.filter(([key]) => key === 'autoLaunchOnStartup').map(([, v]) => v) + const startsWithDesktop = (id: string) => + tile(id).find(`[data-testid="chooser-tile-starts-with-desktop-${id}"]`).exists() + async function menuFor(id: string) { + await tile(id).trigger('contextmenu') + const menu = wrapper + .findAllComponents({ name: 'ContextMenu' }) + .find((candidate) => candidate.props('open') === true)! + return menu + } + + expect(wrapper.find('[role="checkbox"]').exists()).toBe(false) + expect(startsWithDesktop('a')).toBe(true) + expect(tile('a').text()).toContain('Auto start') + expect(startsWithDesktop('b')).toBe(false) + expect(tile('b').text()).toContain('Ready') - await setChecked(autoStartBox('b'), true) + const menuA = await menuFor('a') + const itemsA = menuA.props('items') as { id: string; label: string; separator?: boolean }[] + expect(itemsA[0]).toMatchObject({ id: 'auto-start', label: 'Turn off Auto start' }) + expect(itemsA[1]).toMatchObject({ id: 'manage', separator: true }) + + const menuB = await menuFor('b') + const itemsB = menuB.props('items') as { id: string; label: string }[] + expect(itemsB[0]).toMatchObject({ id: 'auto-start', label: 'Auto start' }) + menuB.vm.$emit('select', 'auto-start') await flushPromises() - expect(api.setSetting).toHaveBeenCalledWith('autoLaunchOnStartup', 'b') - expect(autoStartBox('a').attributes('aria-checked')).toBe('false') + expect(autoStartWrites()).toEqual(['b']) + expect(startsWithDesktop('a')).toBe(false) + expect(startsWithDesktop('b')).toBe(true) expect(wrapper.emitted('open-details')).toBeUndefined() expect(wrapper.emitted('pick')).toBeUndefined() - await setChecked(autoStartBox('b'), false) + const menuAgain = await menuFor('b') + expect((menuAgain.props('items') as { label: string }[])[0]!.label).toBe('Turn off Auto start') + menuAgain.vm.$emit('select', 'auto-start') await flushPromises() - expect(api.setSetting).toHaveBeenLastCalledWith('autoLaunchOnStartup', 'none') - expect(wrapper.emitted('open-details')).toBeUndefined() + expect(autoStartWrites()).toEqual(['b', 'none']) + expect(startsWithDesktop('b')).toBe(false) }) it('shows Update beside Start and keeps Start as the action', async () => { diff --git a/src/renderer/src/views/ChooserView.vue b/src/renderer/src/views/ChooserView.vue index 658681d2a..de8fc1266 100644 --- a/src/renderer/src/views/ChooserView.vue +++ b/src/renderer/src/views/ChooserView.vue @@ -8,6 +8,7 @@ import { useInstallationStore } from '../stores/installationStore' import { useAuthStore } from '../stores/authStore' import { useDashboardScopeStore } from '../stores/dashboardScopeStore' import { useInstallContextMenu } from '../composables/useInstallContextMenu' +import { useAutoStartBuild } from '../composables/useAutoStartBuild' import { useInstallList } from '../composables/useInstallList' import { useInstallingBuilds } from '../composables/useBuildProgress' import { useQuickUpdate } from '../composables/useQuickUpdate' @@ -198,7 +199,8 @@ const { options ? openInstallManager(inst, options) : emit('open-details', inst), onShowProgress: (showOpts) => emit('show-progress', showOpts), onUpdate: runQuickUpdate, - canPromoteToWorkspace + canPromoteToWorkspace, + autoStart: useAutoStartBuild() }) async function pickInstall(inst: Installation): Promise { diff --git a/src/renderer/src/views/chooser/ChooserFamilyGrid.vue b/src/renderer/src/views/chooser/ChooserFamilyGrid.vue index 382d2f72a..c504307a9 100644 --- a/src/renderer/src/views/chooser/ChooserFamilyGrid.vue +++ b/src/renderer/src/views/chooser/ChooserFamilyGrid.vue @@ -88,7 +88,6 @@ function unlockTileSize(el: Element): void { @trigger-action="(action, inst) => emit('trigger-action', action, inst)" @view-error="emit('view-error', $event)" @view-danger="emit('view-danger', $event)" - @auto-start="(inst, on) => autoStart.setStartsOnOpen(inst.id, on)" /> diff --git a/src/renderer/src/views/chooser/ChooserInstallTile.vue b/src/renderer/src/views/chooser/ChooserInstallTile.vue index 02a467762..e94de70f2 100644 --- a/src/renderer/src/views/chooser/ChooserInstallTile.vue +++ b/src/renderer/src/views/chooser/ChooserInstallTile.vue @@ -11,6 +11,7 @@ import { LoaderCircle, OctagonAlert, Play, + Power, Server, Check } from '@lucide/vue' @@ -27,7 +28,6 @@ import { import Tooltip from '../../components/ui/Tooltip.vue' import BuildDeviceArt from '../../panel/home/BuildDeviceArt.vue' import BuildProgressBar from '../../panel/home/BuildProgressBar.vue' -import BuildAutoStartCheckbox from '../../panel/home/BuildAutoStartCheckbox.vue' import TruncatedText from '../../components/TruncatedText.vue' import { TID } from '../../../../shared/testIds' import { isBuildInstall } from '../../devplatform/buildState' @@ -60,7 +60,6 @@ const emit = defineEmits<{ 'view-error': [installation: Installation] 'view-danger': [installation: Installation] 'why-cloud': [] - 'auto-start': [installation: Installation, on: boolean] }>() const { t } = useI18n() @@ -174,9 +173,11 @@ const showWhyCloudTrigger = computed( const hasUpdate = computed(() => inst.value.statusTag?.style === 'update') const hasMigratePrompt = computed(() => inst.value.statusTag?.style === 'migrate') -const restingLabel = computed(() => - isCloudBuild(inst.value) ? t('home.buildAlwaysOn') : t('home.buildReady') -) +const startsWithDesktop = computed(() => props.autoStart && !isCloudBuild(inst.value)) +const restingLabel = computed(() => { + if (isCloudBuild(inst.value)) return t('home.buildAlwaysOn') + return startsWithDesktop.value ? t('home.autoStartOn') : t('home.buildReady') +}) const isFromBuild = computed(() => isBuildInstall(inst.value)) @@ -372,6 +373,13 @@ function triggerInstallAction(action: 'update' | 'migrate'): void { class="size-1.5 shrink-0 rounded-full bg-[#59d38c] shadow-[0_0_0_3px_rgb(89_211_140/0.36)]" aria-hidden="true" /> +