diff --git a/e2e/launch-own-window.test.ts b/e2e/launch-own-window.test.ts index f68f64c5f..4729662bb 100644 --- a/e2e/launch-own-window.test.ts +++ b/e2e/launch-own-window.test.ts @@ -5,37 +5,57 @@ import { test, expect } from '@playwright/test' import { launchApp, type AppContext } from './launchApp' import { reserveFreePort, writeFakeComfyInstall } from './support/fakeComfyInstall' import { evalWithRetry } from './support/evalRetry' +import { openPickerViaTitlePill } from './support/chooserHelpers' +import { WebContentsPage } from './support/cdpPages' +import { byTestId, TID } from './support/testIds' const INSTALL_ID = 'inst-own-window' const INSTALL_NAME = 'Own Window Fixture' const CARD = `[data-testid="home-build"][data-build-id="${INSTALL_ID}"]` +const SECOND_INSTALL_ID = 'inst-own-window-second' +const SECOND_INSTALL_NAME = 'Second Window Fixture' let ctx: AppContext let installPath: string +let secondInstallPath: string let port = 0 +let secondPort = 0 + +function fakeComfyBuilderInstall(id: string, name: string, path: string, buildPort: number) { + return { + id, + name, + sourceId: 'comfybuilder', + sourceLabel: 'ComfyBuilder', + installPath: path, + status: 'installed', + launchArgs: `--port ${buildPort}`, + launchMode: 'window', + browserPartition: 'unique', + seen: true + } +} test.describe.configure({ mode: 'serial', timeout: 180_000 }) test.beforeAll(async () => { installPath = await mkdtemp(path.join(os.tmpdir(), 'comfyui-own-window-')) + secondInstallPath = await mkdtemp(path.join(os.tmpdir(), 'comfyui-own-window-second-')) port = await reserveFreePort() + secondPort = await reserveFreePort() await writeFakeComfyInstall({ installPath, port }) + await writeFakeComfyInstall({ installPath: secondInstallPath, port: secondPort }) ctx = await launchApp( { settings: { firstUseCompleted: true, telemetryEnabled: false }, installations: [ - { - id: INSTALL_ID, - name: INSTALL_NAME, - sourceId: 'comfybuilder', - sourceLabel: 'ComfyBuilder', - installPath, - status: 'installed', - launchArgs: `--port ${port}`, - launchMode: 'window', - browserPartition: 'unique', - seen: true - } + fakeComfyBuilderInstall(INSTALL_ID, INSTALL_NAME, installPath, port), + fakeComfyBuilderInstall( + SECOND_INSTALL_ID, + SECOND_INSTALL_NAME, + secondInstallPath, + secondPort + ) ] }, { stayOnHome: true } @@ -46,6 +66,7 @@ test.beforeAll(async () => { test.afterAll(async () => { await ctx?.cleanup() if (installPath) await rm(installPath, { recursive: true, force: true }) + if (secondInstallPath) await rm(secondInstallPath, { recursive: true, force: true }) }) interface WindowState { @@ -94,3 +115,69 @@ test('Start on a Home card opens ComfyUI in its own window and the dashboard sta message: 'the Home card never showed Running' }) }) + +interface TwoBuildWindows { + windows: number + firstBuildWindowIds: number[] + secondBuildWindows: number + desktopWindows: number +} + +function twoBuildWindows(): Promise { + return evalWithRetry(() => + ctx.app.evaluate( + ({ BrowserWindow, WebContentsView }, ports) => { + const wins = BrowserWindow.getAllWindows().filter((w) => !w.isDestroyed()) + const hosts = (w: Electron.BrowserWindow, p: number): boolean => + w.contentView.children.some( + (v) => v instanceof WebContentsView && v.webContents.getURL().includes(`:${p}`) + ) + return { + windows: wins.length, + firstBuildWindowIds: wins.filter((w) => hosts(w, ports.first)).map((w) => w.id), + secondBuildWindows: wins.filter((w) => hosts(w, ports.second)).length, + desktopWindows: wins.filter((w) => !hosts(w, ports.first) && !hosts(w, ports.second)) + .length + } + }, + { first: port, second: secondPort } + ) + ) +} + +test('Start on another build from a build window opens it in its own window and keeps this one @linux', async () => { + const before = await twoBuildWindows() + expect(before.firstBuildWindowIds, 'the first build is running in its own window').toHaveLength(1) + const [firstBuildWindowId] = before.firstBuildWindowIds + + const firstBuildTitleBar = new WebContentsPage( + ctx.app, + `comfyTitleBar.html?installationId=${INSTALL_ID}` + ) + const popup = await openPickerViaTitlePill(ctx.app, firstBuildTitleBar) + const secondRow = byTestId(TID.pickerRow(SECOND_INSTALL_ID)) + await popup.waitForVisible(secondRow, { timeout: 15_000 }) + expect(await popup.click(secondRow), 'second build selected').toBe(true) + await expect + .poll(() => popup.textOf(byTestId(TID.pickerPrimaryCta)), { + timeout: 10_000, + intervals: [200, 400] + }) + .toContain('Start') + expect(await popup.click(byTestId(TID.pickerPrimaryCta)), 'Start clicked').toBe(true) + + const runAll = '[data-testid="base-alert-secondary"]' + await ctx.panel.waitForVisible(runAll, { timeout: 15_000 }) + expect( + await ctx.panel.textOf(runAll), + 'the Desktop window asks before running a second build' + ).toContain('Run All') + expect(await ctx.panel.click(runAll), 'Run All keeps the first build running').toBe(true) + + await expect.poll(twoBuildWindows, { timeout: 90_000, intervals: [250, 500, 1_000] }).toEqual({ + windows: 3, + firstBuildWindowIds: [firstBuildWindowId], + secondBuildWindows: 1, + desktopWindows: 1 + }) +}) diff --git a/e2e/nav-matrix-cloud.test.ts b/e2e/nav-matrix-cloud.test.ts index cb3abc57d..2f02dcd7a 100644 --- a/e2e/nav-matrix-cloud.test.ts +++ b/e2e/nav-matrix-cloud.test.ts @@ -3,7 +3,7 @@ import { launchApp, type AppContext } from './launchApp' import { expectChooserVisible } from './support/chooserHelpers' import { closeTitlePopupIfOpen, isPopupVisible, titlePopupPage } from './support/cdpPages' import { clearRunningSessions, getIpcInvocations, resetIpcInvocations } from './support/devHooks' -import { liveWindowCount, openPicker } from './support/navMatrixHelpers' +import { desktopWindowCount, openPicker } from './support/navMatrixHelpers' import { byTestId, TID } from './support/testIds' let ctx: AppContext @@ -13,21 +13,26 @@ const CLOUD_NAME = 'Nav Cloud Target' test.describe.configure({ mode: 'serial' }) -async function newWindowCalls(): Promise<{ installationId?: string; focusedExisting?: boolean }[]> { - return (await getIpcInvocations(ctx.app, 'open-install-new-window')) as never +async function cloudRunActions(): Promise<{ installationId?: string }[]> { + return (await getIpcInvocations(ctx.app, 'run-action')) as never } -async function openCloudInNewWindow(): Promise { - await openPicker(ctx.app, ctx.panel, 'openInstallNewWindow') +async function openCloudFromPicker(): Promise { + await openPicker(ctx.app, ctx.panel) const popup = titlePopupPage(ctx.app) const cloudRow = byTestId(TID.pickerRow(CLOUD_ID)) await popup.waitForVisible(cloudRow) expect(await popup.click(cloudRow), 'Cloud instance selected').toBe(true) - await popup.waitForVisible(byTestId(TID.pickerNewWindow)) - expect(await popup.click(byTestId(TID.pickerNewWindow)), 'Window options clicked').toBe(true) - const openNewItem = byTestId(TID.pinBottomAction('nav:0')) - await popup.waitForVisible(openNewItem) - expect(await popup.click(openNewItem), 'Open in new window clicked').toBe(true) + await expect + .poll(() => popup.textOf(byTestId(TID.pickerPrimaryCta)), { + timeout: 5_000, + intervals: [100, 200] + }) + .toContain('Open Cloud') + expect(await popup.exists(byTestId(TID.pickerNewWindow)), 'no "Open in new window" caret').toBe( + false + ) + expect(await popup.click(byTestId(TID.pickerPrimaryCta)), 'Open Cloud clicked').toBe(true) await expect .poll(() => isPopupVisible(ctx.app, 'comfyTitlePopup.html'), { timeout: 5_000, @@ -52,24 +57,19 @@ test.afterAll(async () => { test.beforeEach(async () => { await closeTitlePopupIfOpen(ctx.app) - await resetIpcInvocations(ctx.app, 'open-install-new-window') + await resetIpcInvocations(ctx.app, 'run-action') await clearRunningSessions(ctx.app) }) -test('cloud target with no window: opens a new window @windows @macos @linux', async () => { - const before = await liveWindowCount(ctx.app) - await openCloudInNewWindow() +test('cloud target with no window: Open Cloud starts it from the Desktop window, no second Desktop window @windows @macos @linux', async () => { + const desktopWindowsBefore = await desktopWindowCount(ctx.app) + await openCloudFromPicker() await expect - .poll( - async () => - (await newWindowCalls()).some( - (c) => c.installationId === CLOUD_ID && c.focusedExisting === false - ), - { timeout: 5_000, intervals: [100, 250] } - ) + .poll(async () => (await cloudRunActions()).some((c) => c.installationId === CLOUD_ID), { + timeout: 10_000, + intervals: [200, 500] + }) .toBe(true) - await expect - .poll(() => liveWindowCount(ctx.app), { timeout: 5_000, intervals: [200, 400] }) - .toBe(before + 1) + expect(await desktopWindowCount(ctx.app), 'no second Desktop window').toBe(desktopWindowsBefore) }) diff --git a/e2e/nav-matrix-dashboard.test.ts b/e2e/nav-matrix-dashboard.test.ts index b3493df2d..b1af70ccf 100644 --- a/e2e/nav-matrix-dashboard.test.ts +++ b/e2e/nav-matrix-dashboard.test.ts @@ -11,7 +11,12 @@ import { resetIpcInvocations, seedRunningSession } from './support/devHooks' -import { expectNoIpcInvocation, liveWindowCount, openPicker } from './support/navMatrixHelpers' +import { + desktopWindowCount, + expectNoIpcInvocation, + liveWindowCount, + openPicker +} from './support/navMatrixHelpers' import { byTestId, TID } from './support/testIds' let ctx: AppContext @@ -72,7 +77,7 @@ test.beforeEach(async () => { await closeTitlePopupIfOpen(ctx.app) await resetIpcInvocations(ctx.app, 'focus-comfy-window') await resetIpcInvocations(ctx.app, 'run-action') - await resetIpcInvocations(ctx.app, 'open-install-new-window') + await resetIpcInvocations(ctx.app, 'open-build') await clearRunningSessions(ctx.app) }) @@ -96,7 +101,7 @@ test('Home → Builds → Update settings opens the selected installation @windo test('Dashboard → stopped instance: same-window launch, no new window @windows @macos @linux', async () => { const before = await liveWindowCount(ctx.app) - await openPicker(ctx.app, ctx.panel, 'pickInstall') + await openPicker(ctx.app, ctx.panel) const popup = titlePopupPage(ctx.app) await popup.evaluate( @@ -135,7 +140,7 @@ test('Dashboard → running instance: focus existing window @windows @macos @lin installationName: INSTALL_A_NAME }) const before = await liveWindowCount(ctx.app) - await openPicker(ctx.app, ctx.panel, 'pickInstall') + await openPicker(ctx.app, ctx.panel) const popup = titlePopupPage(ctx.app) await popup.evaluate( @@ -160,29 +165,36 @@ test('Dashboard → running instance: focus existing window @windows @macos @lin expect(await liveWindowCount(ctx.app)).toBe(before) }) -test('Dashboard → cloud via "Open in new window": spawns a new window @windows @macos @linux', async () => { - const before = await liveWindowCount(ctx.app) - await openPicker(ctx.app, ctx.panel, 'pickInstall') +test('Dashboard → closed Cloud: Open Cloud starts it from this Desktop window, no second Desktop window @windows @macos @linux', async () => { + const desktopWindowsBefore = await desktopWindowCount(ctx.app) + await openPicker(ctx.app, ctx.panel) const popup = titlePopupPage(ctx.app) - await popup.evaluate( - `window.__comfyTitlePopup.openInstallNewWindow(${JSON.stringify(CLOUD_ID)})` - ) + await popup.evaluate(`window.__comfyTitlePopup.pickInstall(${JSON.stringify(CLOUD_ID)})`) await expect .poll( async () => { - const calls = (await getIpcInvocations(ctx.app, 'open-install-new-window')) as { + const calls = (await getIpcInvocations(ctx.app, 'open-build')) as { installationId?: string - focusedExisting?: boolean + route?: string }[] - return calls.some((c) => c.installationId === CLOUD_ID && c.focusedExisting === false) + return calls.some((c) => c.installationId === CLOUD_ID && c.route === 'start-from') }, { timeout: 5_000, intervals: [100, 250] } ) .toBe(true) await expect - .poll(() => liveWindowCount(ctx.app), { timeout: 5_000, intervals: [200, 400] }) - .toBe(before + 1) + .poll( + async () => { + const calls = (await getIpcInvocations(ctx.app, 'run-action')) as { + installationId?: string + }[] + return calls.some((c) => c.installationId === CLOUD_ID) + }, + { timeout: 10_000, intervals: [200, 500] } + ) + .toBe(true) + expect(await desktopWindowCount(ctx.app), 'no second Desktop window').toBe(desktopWindowsBefore) }) diff --git a/e2e/nav-matrix-instance.test.ts b/e2e/nav-matrix-instance.test.ts index 598fb9367..f6d2663c9 100644 --- a/e2e/nav-matrix-instance.test.ts +++ b/e2e/nav-matrix-instance.test.ts @@ -11,7 +11,12 @@ import { resetIpcInvocations, seedRunningSession } from './support/devHooks' -import { expectNoIpcInvocation, liveWindowCount, openPicker } from './support/navMatrixHelpers' +import { + desktopWindowCount, + expectNoIpcInvocation, + liveWindowCount, + openPicker +} from './support/navMatrixHelpers' let ctx: AppContext let installPathA: string @@ -68,37 +73,47 @@ test.beforeEach(async () => { await closeTitlePopupIfOpen(ctx.app) await resetIpcInvocations(ctx.app, 'focus-comfy-window') await resetIpcInvocations(ctx.app, 'run-action') - await resetIpcInvocations(ctx.app, 'open-install-new-window') + await resetIpcInvocations(ctx.app, 'open-build') await clearRunningSessions(ctx.app) }) -test('Instance B via "Open in new window": spawns a new window (no swap of the host) @windows @macos @linux', async () => { - const before = await liveWindowCount(ctx.app) - await openPicker(ctx.app, ctx.panel, 'openInstallNewWindow') +test('Instance B (stopped): Start starts B from this Desktop window and opens no second Desktop window @windows @macos @linux', async () => { + const desktopWindowsBefore = await desktopWindowCount(ctx.app) + await openPicker(ctx.app, ctx.panel) const popup = titlePopupPage(ctx.app) await popup.evaluate( - `window.__comfyTitlePopup.openInstallNewWindow(${JSON.stringify(INSTALL_B_ID)})` + `window.__comfyTitlePopup.pickInstall(${JSON.stringify(INSTALL_B_ID)})` ) await expect .poll( async () => { - const calls = (await getIpcInvocations(ctx.app, 'open-install-new-window')) as { + const calls = (await getIpcInvocations(ctx.app, 'open-build')) as { installationId?: string - focusedExisting?: boolean + route?: string }[] - return calls.some((c) => c.installationId === INSTALL_B_ID && c.focusedExisting === false) + return calls.some((c) => c.installationId === INSTALL_B_ID && c.route === 'start-from') }, { timeout: 5_000, intervals: [100, 250] } ) .toBe(true) await expect - .poll(() => liveWindowCount(ctx.app), { timeout: 5_000, intervals: [200, 400] }) - .toBe(before + 1) + .poll( + async () => { + const calls = (await getIpcInvocations(ctx.app, 'run-action')) as { + installationId?: string + actionId?: string + }[] + return calls.some((c) => c.installationId === INSTALL_B_ID && c.actionId === 'launch') + }, + { timeout: 10_000, intervals: [200, 500] } + ) + .toBe(true) + expect(await desktopWindowCount(ctx.app), 'no second Desktop window').toBe(desktopWindowsBefore) await expectNoIpcInvocation(ctx.app, 'focus-comfy-window', () => true, { - message: 'unexpected focus-comfy-window when opening B in a new window' + message: 'unexpected focus-comfy-window when starting B' }) }) @@ -108,7 +123,7 @@ test('Instance B (running elsewhere): focus its existing window @windows @macos installationName: INSTALL_B_NAME }) const before = await liveWindowCount(ctx.app) - await openPicker(ctx.app, ctx.panel, 'openInstallNewWindow') + await openPicker(ctx.app, ctx.panel) const popup = titlePopupPage(ctx.app) await popup.evaluate( diff --git a/e2e/support/navMatrixHelpers.ts b/e2e/support/navMatrixHelpers.ts index 0a1afddd0..294526c5f 100644 --- a/e2e/support/navMatrixHelpers.ts +++ b/e2e/support/navMatrixHelpers.ts @@ -13,17 +13,27 @@ export async function liveWindowCount(app: ElectronApplication): Promise ) } -export async function openPicker( - app: ElectronApplication, - panel: WebContentsPage, - bridgeFn: 'pickInstall' | 'openInstallNewWindow' -): Promise { +export async function desktopWindowCount(app: ElectronApplication): Promise { + return evalWithRetry(() => + app.evaluate( + ({ webContents }) => + webContents.getAllWebContents().filter((wc) => { + if (wc.isDestroyed()) return false + const url = wc.getURL() + if (!url.includes('panel.html')) return false + return new URL(url).searchParams.get('installationId') === '' + }).length + ) + ) +} + +export async function openPicker(app: ElectronApplication, panel: WebContentsPage): Promise { await panel.evaluate(`(() => { window.api.openInstancePicker({}); return true })()`) await waitForWebContents(app, 'comfyTitlePopup.html') const popup = titlePopupPage(app) await popup.waitFor( async () => - popup.evaluate(`typeof window.__comfyTitlePopup?.${bridgeFn} === "function"`), + popup.evaluate(`typeof window.__comfyTitlePopup?.pickInstall === "function"`), { timeout: 10_000, message: 'picker bridge never appeared' } ) } diff --git a/locales/en.json b/locales/en.json index c457f752d..33d8b9069 100644 --- a/locales/en.json +++ b/locales/en.json @@ -1953,7 +1953,6 @@ "switch": "Switch", "openCloud": "Open Cloud", "openRemote": "Open Remote", - "openInNewWindow": "Open in new window", "windowOptions": "Window options", "moreWindowOptions": "Window options", "restartConfirmTitle": "Restart this build?", @@ -1963,12 +1962,6 @@ "confirmHeadsUp": "Heads up", "restartConfirmItem1": "Restarting will stop the running session.", "restartConfirmItem2": "Any unsaved work in the workflow will be lost.", - "switchConfirmTitle": "Switch build?", - "switchConfirmMessage": "Switch to {name}?", - "switchConfirmAction": "Switch", - "switchConfirmSecondary": "Open in new window", - "switchConfirmItem1": "Switch stops the current build and replaces it in this window.", - "switchConfirmItem2": "Open in new window keeps the current build running.", "more": "More", "settings": "Settings", "snapshots": "Snapshots", diff --git a/locales/zh.json b/locales/zh.json index 502ac2d03..ebe69c26f 100644 --- a/locales/zh.json +++ b/locales/zh.json @@ -1953,7 +1953,6 @@ "switch": "切换", "openCloud": "打开云端", "openRemote": "打开远程", - "openInNewWindow": "在新窗口中打开", "windowOptions": "窗口选项", "moreWindowOptions": "窗口选项", "restartConfirmTitle": "重启此构建?", @@ -1963,12 +1962,6 @@ "confirmHeadsUp": "请注意", "restartConfirmItem1": "重启将停止正在运行的会话。", "restartConfirmItem2": "工作流中任何未保存的工作都会丢失。", - "switchConfirmTitle": "切换构建?", - "switchConfirmMessage": "切换到 {name}?", - "switchConfirmAction": "切换", - "switchConfirmSecondary": "在新窗口中打开", - "switchConfirmItem1": "切换会停止当前构建并在此窗口中将其替换。", - "switchConfirmItem2": "在新窗口中打开会让当前构建继续运行。", "more": "更多", "settings": "设置", "snapshots": "快照", diff --git a/src/main/host/registry.test.ts b/src/main/host/registry.test.ts index a9f280553..3d100d50d 100644 --- a/src/main/host/registry.test.ts +++ b/src/main/host/registry.test.ts @@ -33,6 +33,7 @@ import { nextWindowKey, forceRevealHostWindow, openOrFocusHomeHostWindow, + routeBuildOpen, hasRunningSessionForEntry, raiseAllHostWindows, registerHostEntry, @@ -669,3 +670,90 @@ describe('openOrFocusHomeHostWindow', () => { expect(createChooser).toHaveBeenCalledTimes(1) }) }) + +describe('routeBuildOpen', () => { + it('focuses the window a build already has, whoever asks', () => { + const buildWindow = makeEntry({ installationId: 'inst-B' }) + const desktop = makeEntry({ installationId: null }) + registerHostEntry(buildWindow) + registerHostEntry(desktop) + + expect(routeBuildOpen('inst-B', desktop, [])).toEqual({ kind: 'focus', entry: buildWindow }) + expect(routeBuildOpen('inst-B', undefined, [])).toEqual({ kind: 'focus', entry: buildWindow }) + }) + + it('focuses the Desktop window that is becoming the build window, instead of opening another Desktop window', () => { + const becomingB = makeEntry({ installationId: null }) + const buildA = makeEntry({ installationId: 'inst-A' }) + registerHostEntry(becomingB) + registerHostEntry(buildA) + claimAttachHost('inst-B', becomingB.windowKey) + + expect(routeBuildOpen('inst-B', buildA, ['inst-B'])).toEqual({ + kind: 'focus', + entry: becomingB + }) + }) + + it('shows a build that is already starting from the Desktop window instead of starting it again', () => { + const desktop = makeEntry({ installationId: null }) + const buildA = makeEntry({ installationId: 'inst-A' }) + registerHostEntry(desktop) + registerHostEntry(buildA) + + expect(routeBuildOpen('inst-B', buildA, ['inst-B'])).toEqual({ + kind: 'show-starting', + entry: null + }) + expect(routeBuildOpen('inst-B', desktop, ['inst-B'])).toEqual({ + kind: 'show-starting', + entry: desktop + }) + }) + + it('shows a starting build in the Desktop window that asked, not the first one registered', () => { + const firstDesktop = makeEntry({ installationId: null }) + const secondDesktop = makeEntry({ installationId: null }) + registerHostEntry(firstDesktop) + registerHostEntry(secondDesktop) + + expect(routeBuildOpen('inst-B', secondDesktop, ['inst-B'])).toEqual({ + kind: 'show-starting', + entry: secondDesktop + }) + }) + + it('starts a build from the Desktop window that asked for it', () => { + const desktop = makeEntry({ installationId: null }) + registerHostEntry(desktop) + + expect(routeBuildOpen('inst-B', desktop, [])).toEqual({ kind: 'start-from', entry: desktop }) + }) + + it('never hands another build to a build window: it starts from the Desktop window instead', () => { + const buildA = makeEntry({ installationId: 'inst-A' }) + registerHostEntry(buildA) + + expect(routeBuildOpen('inst-B', buildA, [])).toEqual({ kind: 'start-from-home' }) + }) + + it('treats a Desktop window that is becoming a build window like a build window', () => { + const claimed = makeEntry({ installationId: null }) + registerHostEntry(claimed) + claimAttachHost('inst-A', claimed.windowKey) + + expect(routeBuildOpen('inst-B', claimed, [])).toEqual({ kind: 'start-from-home' }) + }) + + it('does nothing when a build window asks for itself', () => { + const buildA = makeEntry({ installationId: 'inst-A' }) + buildA.window.isDestroyed = () => false + comfyWindows.set(buildA.windowKey, buildA) + + expect(routeBuildOpen('inst-A', buildA, [])).toEqual({ kind: 'ignore' }) + }) + + it('starts from the Desktop window when the request names no window', () => { + expect(routeBuildOpen('inst-B', undefined, [])).toEqual({ kind: 'start-from-home' }) + }) +}) diff --git a/src/main/host/registry.ts b/src/main/host/registry.ts index e6166c3ca..d73360688 100644 --- a/src/main/host/registry.ts +++ b/src/main/host/registry.ts @@ -335,9 +335,12 @@ function isHandingOffToBuild(entry: ComfyWindowEntry): boolean { return false } +export function isHomeHostEntry(entry: ComfyWindowEntry): boolean { + return !entry.window.isDestroyed() && isChooserHost(entry) && !isHandingOffToBuild(entry) +} + function findHomeHostWindow(): BrowserWindow | null { - const entry = findPreferredHostByVisibility((e) => isChooserHost(e) && !isHandingOffToBuild(e)) - return entry?.window ?? null + return findPreferredHostByVisibility(isHomeHostEntry)?.window ?? null } export function openOrFocusHomeHostWindow(): BrowserWindow { @@ -349,6 +352,37 @@ export function openOrFocusHomeHostWindow(): BrowserWindow { return requireChooserFactory()() } +export type BuildOpenRoute = + | { kind: 'focus'; entry: ComfyWindowEntry } + | { kind: 'start-from'; entry: ComfyWindowEntry } + | { kind: 'start-from-home' } + | { kind: 'show-starting'; entry: ComfyWindowEntry | null } + | { kind: 'ignore' } + +function findWindowForBuild(installationId: string): ComfyWindowEntry | undefined { + const hosted = getEntryByInstallationId(installationId) + if (hosted && !hosted.window.isDestroyed()) return hosted + const claimedKey = pendingAttachClaims.get(installationId) + const claimed = claimedKey === undefined ? undefined : comfyWindows.get(claimedKey) + return claimed && !claimed.window.isDestroyed() ? claimed : undefined +} + +export function routeBuildOpen( + installationId: string, + requester: ComfyWindowEntry | undefined, + launchingInstallationIds: readonly string[] +): BuildOpenRoute { + const own = findWindowForBuild(installationId) + if (own) return { kind: 'focus', entry: own } + if (requester?.installationId === installationId) return { kind: 'ignore' } + const homeRequester = requester && isHomeHostEntry(requester) ? requester : null + if (launchingInstallationIds.includes(installationId)) { + return { kind: 'show-starting', entry: homeRequester } + } + if (homeRequester) return { kind: 'start-from', entry: homeRequester } + return { kind: 'start-from-home' } +} + export function openOrFocusAnyHostWindow(): BrowserWindow { const installWin = findPreferredInstallHostWindow() if (installWin) { diff --git a/src/main/index.ts b/src/main/index.ts index 6bcffbd9e..6281074df 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -36,12 +36,7 @@ import { pruneCrashDumps } from './lib/crashDumps' import { createStartupReentryGate } from './lib/startupReentryGate' import { registerTitleTooltipIpc } from './popups/titleTooltip' import { registerTitleCoachmarkIpc } from './popups/titleCoachmark' -import { - openSystemModal, - openSystemModalAsync, - openSystemModalChoiceAsync, - registerSystemModalIpc -} from './popups/systemModal' +import { openSystemModal, openSystemModalAsync, registerSystemModalIpc } from './popups/systemModal' import { registerTitlePopupIpc, triggerPickerSnapshotBroadcast, @@ -133,6 +128,7 @@ import { initUserTier } from './lib/userTier' import { readSmartAppControlState } from './lib/smartAppControl' import { + bringToFront, canRestartFromPicker, claimAttachHost, comfyWindows, @@ -149,10 +145,11 @@ import { openOrFocusChooserHostWindow, openOrFocusHomeHostWindow, raiseAllHostWindows, + routeBuildOpen, setHostFactories, shouldConfirmKillForEntry } from './host/registry' -import type { ComfyWindowEntry } from './host/registry' +import type { BuildOpenRoute, ComfyWindowEntry } from './host/registry' import { applyChooserHostThemeToAll, createHostWindow, @@ -1077,107 +1074,48 @@ if (app.isPackaged && !app.requestSingleInstanceLock()) { }) } - const openInstallInNewWindow = async ( - installationId: string, - opts?: { allowDuplicate?: boolean } - ): Promise => { - const existing = getEntryByInstallationId(installationId) - const willFocusExisting = - !!existing && !existing.window.isDestroyed() && !opts?.allowDuplicate - recordIpcInvocation('open-install-new-window', { - installationId, - allowDuplicate: opts?.allowDuplicate === true, - focusedExisting: willFocusExisting - }) - if (willFocusExisting) { - existing.window.show() - existing.window.focus() - return - } - try { - const inst = await getInstallation(installationId) - if (!inst) { - console.error('openInstallInNewWindow: unknown installation, not spawning', { - installationId - }) - return - } - const target = findEntryByHostWindow(openChooserHostWindow()) - if (!target) { - console.error('openInstallInNewWindow: spawned chooser host not in registry', { - installationId - }) - return - } + const recordBuildOpen = (installationId: string, route: BuildOpenRoute): void => { + recordIpcInvocation('open-build', { installationId, route: route.kind }) + if (route.kind === 'start-from' || route.kind === 'start-from-home') { mainTelemetry.emit('comfy.desktop.instance.opened_new_window', { to_installation_id: installationId, method: 'picker' }) - deliverPickToEntry(target, installationId) - } catch (err) { - console.error('openInstallInNewWindow failed:', err) } } - const pickInstallFromPicker = async ( - installationId: string, - parentEntryId: number, - opts?: { confirmed?: boolean } - ): Promise => { - const existing = getEntryByInstallationId(installationId) - if (existing && !existing.window.isDestroyed()) { - existing.window.show() - existing.window.focus() - return - } - const parentEntry = comfyWindows.get(parentEntryId) - if (!parentEntry || parentEntry.window.isDestroyed()) return - - if (parentEntry.installationId === installationId) return - - if (parentEntry.installationId != null) { - if (!opts?.confirmed && shouldConfirmKillForEntry(parentEntry)) { - let targetName = installationId - try { - const target = await getInstallation(installationId) - if (target?.name) targetName = target.name - } catch {} - const choice = await openSystemModalChoiceAsync({ - parent: parentEntry.window, - spec: { - title: 'Switch instance?', - message: `Switch to ${targetName}?`, - details: [ - { - label: 'Heads up', - items: [ - 'Switch stops the current instance and replaces it in this window.', - 'Open in new window keeps the current instance running.' - ] - } - ], - confirmLabel: 'Switch', - secondaryLabel: 'Open in new window', - cancelLabel: 'Cancel', - confirmStyle: 'primary', - theme: parentEntry.lastTheme - } - }) - if (choice === 'cancel') return - if (choice === 'secondary') { - openInstallInNewWindow(installationId) + const openBuild = async (installationId: string, requesterEntryId: number): Promise => { + const requester = comfyWindows.get(requesterEntryId) + const route = routeBuildOpen(installationId, requester, _getLaunchingInstallationIds()) + recordBuildOpen(installationId, route) + switch (route.kind) { + case 'ignore': + return + case 'focus': + bringToFront(route.entry.window) + return + case 'show-starting': + if (route.entry) bringToFront(route.entry.window) + else openOrFocusHomeHostWindow() + return + case 'start-from': + deliverPickToEntry(route.entry, installationId) + return + case 'start-from-home': { + const inst = await getInstallation(installationId) + if (!inst) { + console.error('openBuild: unknown installation, not starting it', { installationId }) + return + } + const homeEntry = findEntryByHostWindow(openOrFocusHomeHostWindow()) + if (!homeEntry) { + console.error('openBuild: Desktop window not in registry', { installationId }) return } + deliverPickToEntry(homeEntry, installationId) + return } - mainTelemetry.emit('comfy.desktop.instance.switched', { - from_installation_id: parentEntry.installationId, - to_installation_id: installationId, - method: 'picker' - }) - parentEntry.detachInstall() } - - deliverPickToEntry(parentEntry, installationId) } registerTitlePopupIpc({ @@ -1494,8 +1432,7 @@ if (app.isPackaged && !app.requestSingleInstanceLock()) { return { ok: false, message: err instanceof Error ? err.message : 'Action failed.' } } }, - pickInstallFromPicker, - openInstallInNewWindow, + pickInstallFromPicker: openBuild, restartInstallFromPicker: async (installationId, parentEntryId, opts) => { const parentEntry = comfyWindows.get(parentEntryId) if (!parentEntry || parentEntry.window.isDestroyed()) return diff --git a/src/main/popups/systemModal.ts b/src/main/popups/systemModal.ts index 92264a64b..93907875c 100644 --- a/src/main/popups/systemModal.ts +++ b/src/main/popups/systemModal.ts @@ -165,12 +165,6 @@ export function openSystemModalAsync(opts: OpenSystemModalOpts): Promise action === 'confirm') } -export function openSystemModalChoiceAsync( - opts: OpenSystemModalOpts -): Promise<'confirm' | 'cancel' | 'secondary'> { - return openSystemModalResolving(opts, (action) => action) -} - export function registerSystemModalIpc(): void { ipcMain.on('comfy-systemmodal:ready', (event) => { const entry = systemModalsByWebContents.get(event.sender.id) diff --git a/src/main/popups/titlePopup.test.ts b/src/main/popups/titlePopup.test.ts index fdac8828a..f00f698a2 100644 --- a/src/main/popups/titlePopup.test.ts +++ b/src/main/popups/titlePopup.test.ts @@ -907,43 +907,3 @@ describe('buildGlobalSettingsSnapshot telemetry grant', () => { expect(snapshotWithConsent(false).telemetryGranted).toBe(false) }) }) - -describe('build page open-in-new-window IPC', () => { - type IpcListener = (event: Electron.IpcMainEvent, installationId: unknown) => void - const panelContents = {} - const openInstallInNewWindow = vi.fn(async () => {}) - let open: IpcListener - - beforeAll(async () => { - const { ipcMain } = await import('electron') - vi.mocked(ipcMain.on).mockClear() - registerTitlePopupIpc({ openInstallInNewWindow } as unknown as TitlePopupHostBindings) - const call = vi - .mocked(ipcMain.on) - .mock.calls.find(([channel]) => channel === 'comfy-window:open-install-new-window') - if (!call) throw new Error('IPC listener not registered') - open = call[1] as IpcListener - }) - - beforeEach(() => { - openInstallInNewWindow.mockClear() - comfyWindows.set(nextWindowKey(), { - panelView: { webContents: panelContents } - } as unknown as ComfyWindowEntry) - }) - - it('opens the build for a window panel', () => { - open({ sender: panelContents } as Electron.IpcMainEvent, 'inst-a') - - expect(openInstallInNewWindow).toHaveBeenCalledExactlyOnceWith('inst-a') - }) - - it.each([ - ['a sender that is not a panel', {}, 'inst-a'], - ['a missing installation id', panelContents, undefined] - ])('ignores %s', (_label, sender, installationId) => { - open({ sender } as Electron.IpcMainEvent, installationId) - - expect(openInstallInNewWindow).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/popups/titlePopup.ts b/src/main/popups/titlePopup.ts index e8e0b87bb..8cb18f4d5 100644 --- a/src/main/popups/titlePopup.ts +++ b/src/main/popups/titlePopup.ts @@ -48,7 +48,6 @@ import { getEntryByInstallationId, hostInstallEvents, isChooserHost, - isPanelSender, unhostedLaunches } from '../host/registry' import type { ComfyPanelKey, ComfyWindowEntry } from '../host/registry' @@ -981,15 +980,7 @@ export interface TitlePopupHostBindings { getRunningInstallationIds: () => string[] getRunningSessionStartedAt?: () => Record getLaunchingInstallationIds: () => string[] - pickInstallFromPicker: ( - installationId: string, - parentEntryId: number, - opts?: { confirmed?: boolean } - ) => Promise | void - openInstallInNewWindow: ( - installationId: string, - opts?: { allowDuplicate?: boolean } - ) => Promise | void + pickInstallFromPicker: (installationId: string, parentEntryId: number) => Promise | void restartInstallFromPicker: ( installationId: string, parentEntryId: number, @@ -1762,42 +1753,14 @@ export function registerTitlePopupIpc(bindings: TitlePopupHostBindings): void { } ) - ipcMain.on( - 'comfy-titlepopup:pick-install', - (event, payload: { installationId?: unknown; confirmed?: unknown }) => { - const entry = titlePopupsByWebContents.get(event.sender.id) - if (!entry || entry.kind !== POPUP_KIND.instancePicker) return - const installationId = payload?.installationId - if (typeof installationId !== 'string' || installationId.length === 0) return - const confirmed = payload?.confirmed === true - hideTitlePopup(entry, { releaseFocusToParent: false }) - Promise.resolve( - bindings.pickInstallFromPicker(installationId, entry.parentEntryId, { confirmed }) - ).catch((err) => console.error('pickInstallFromPicker failed:', err)) - } - ) - - ipcMain.on( - 'comfy-titlepopup:open-install-new-window', - (event, payload: { installationId?: unknown; allowDuplicate?: unknown }) => { - const entry = titlePopupsByWebContents.get(event.sender.id) - if (!entry || entry.kind !== POPUP_KIND.instancePicker) return - const installationId = payload?.installationId - if (typeof installationId !== 'string' || installationId.length === 0) return - hideTitlePopup(entry, { releaseFocusToParent: false }) - Promise.resolve( - bindings.openInstallInNewWindow(installationId, { - allowDuplicate: payload?.allowDuplicate === true - }) - ).catch((err) => console.error('openInstallInNewWindow failed:', err)) - } - ) - - ipcMain.on('comfy-window:open-install-new-window', (event, installationId: unknown) => { - if (!isPanelSender(event.sender)) return + ipcMain.on('comfy-titlepopup:pick-install', (event, payload: { installationId?: unknown }) => { + const entry = titlePopupsByWebContents.get(event.sender.id) + if (!entry || entry.kind !== POPUP_KIND.instancePicker) return + const installationId = payload?.installationId if (typeof installationId !== 'string' || installationId.length === 0) return - Promise.resolve(bindings.openInstallInNewWindow(installationId)).catch((err) => - console.error('openInstallInNewWindow failed:', err) + hideTitlePopup(entry, { releaseFocusToParent: false }) + Promise.resolve(bindings.pickInstallFromPicker(installationId, entry.parentEntryId)).catch( + (err) => console.error('pickInstallFromPicker failed:', err) ) }) diff --git a/src/preload/api.ts b/src/preload/api.ts index 8c2e2541a..7e726b16a 100644 --- a/src/preload/api.ts +++ b/src/preload/api.ts @@ -84,8 +84,6 @@ export function buildElectronApi(): ElectronApi { terminalResize: (installationId, cols, rows) => ipcRenderer.invoke('terminal-resize', installationId, cols, rows), terminalRestart: (installationId) => ipcRenderer.invoke('terminal-restart', installationId), - openInstallInNewWindow: (installationId) => - ipcRenderer.send('comfy-window:open-install-new-window', installationId), openInstallWindow: (installationId) => ipcRenderer.invoke('open-install-window', installationId), closeComfyWindow: (installationId, opts) => diff --git a/src/preload/comfyTitlePopupPreload.ts b/src/preload/comfyTitlePopupPreload.ts index 511bd6e5f..b0d9ce31b 100644 --- a/src/preload/comfyTitlePopupPreload.ts +++ b/src/preload/comfyTitlePopupPreload.ts @@ -157,8 +157,7 @@ export interface ComfyTitlePopupBridge { openDownloadsModal(): void requestSize(height: number): void onInstancePickerSnapshot(cb: (snapshot: PopupInstancePickerSnapshot) => void): () => void - pickInstall(installationId: string, opts?: { confirmed?: boolean }): void - openInstallNewWindow(installationId: string, opts?: { allowDuplicate?: boolean }): void + pickInstall(installationId: string): void openNewInstall(): void restartInstall(installationId: string, opts?: { confirmed?: boolean }): void getDownloadThumbnail(savePath: string): Promise @@ -452,17 +451,8 @@ const bridge: ComfyTitlePopupBridge = { ipcRenderer.on('comfy-titlepopup:installs-changed', handler) return () => ipcRenderer.removeListener('comfy-titlepopup:installs-changed', handler) }, - pickInstall: (installationId, opts) => { - ipcRenderer.send('comfy-titlepopup:pick-install', { - installationId, - confirmed: opts?.confirmed === true - }) - }, - openInstallNewWindow: (installationId, opts) => { - ipcRenderer.send('comfy-titlepopup:open-install-new-window', { - installationId, - allowDuplicate: opts?.allowDuplicate === true - }) + pickInstall: (installationId) => { + ipcRenderer.send('comfy-titlepopup:pick-install', { installationId }) }, openNewInstall: () => { ipcRenderer.send('comfy-titlepopup:open-new-install') diff --git a/src/renderer/src/comfyTitlePopup/InstancePickerView.test.ts b/src/renderer/src/comfyTitlePopup/InstancePickerView.test.ts index 3c973a974..83da1b02f 100644 --- a/src/renderer/src/comfyTitlePopup/InstancePickerView.test.ts +++ b/src/renderer/src/comfyTitlePopup/InstancePickerView.test.ts @@ -6,27 +6,9 @@ import { useSessionStore } from '../stores/sessionStore' import { NAV_LABEL, type NavDecision } from '../../../shared/navigation/navDecision' import InstancePickerView from './InstancePickerView.vue' -const SWITCH_DECISION: NavDecision = { - window: 'same', - verb: 'switch', - primaryLabel: NAV_LABEL.start, - secondary: [], - telemetry: 'instance.switched' -} -const RESTART_DECISION: NavDecision = { - window: 'same', - verb: 'restart', - primaryLabel: NAV_LABEL.restart, - secondary: [], - telemetry: null -} -const FOCUS_DECISION: NavDecision = { - window: 'same', - verb: 'focus', - primaryLabel: NAV_LABEL.switch, - secondary: [], - telemetry: null -} +const START_DECISION: NavDecision = { verb: 'start', primaryLabel: NAV_LABEL.start } +const RESTART_DECISION: NavDecision = { verb: 'restart', primaryLabel: NAV_LABEL.restart } +const FOCUS_DECISION: NavDecision = { verb: 'focus', primaryLabel: NAV_LABEL.switch } import type { SnapshotListData } from '../types/ipc' vi.mock('../views/comfyUISettings/ConsoleTerminalPane.vue', () => ({ @@ -83,6 +65,8 @@ interface MockSnapshot { pickerSelectionEpoch?: number selectedSettings?: unknown[] | null selectedSnapshots?: unknown | null + currentView?: 'dashboard' | 'instance' | 'cloud' + currentCategory?: string | null } interface BridgeState { @@ -513,7 +497,7 @@ describe('comfyTitlePopup/InstancePickerView', () => { }) const settings = wrapper.findComponent(ComfyUISettingsContent) expect(settings.exists()).toBe(true) - settings.vm.$emit('primary-action', SWITCH_DECISION) + settings.vm.$emit('primary-action', START_DECISION) await flushPromises() expect(bridge.picks).toEqual(['a']) expect(bridge.restarts).toEqual([]) @@ -566,6 +550,29 @@ describe('comfyTitlePopup/InstancePickerView', () => { expect(bridge.picks).toEqual([]) }) + it('starts another stopped build from a build window in its own window, with no Switch prompt', async () => { + const { useDialogs } = await import('../composables/useDialogs') + const wrapper = await mountPicker({ + installs: [ + makeInstall({ id: 'a', name: 'Alpha', sourceCategory: 'local' }), + makeInstall({ id: 'b', name: 'Bravo', sourceCategory: 'local' }) + ], + activeInstallationId: 'a', + selectedInstallationId: 'b', + runningInstallationIds: ['a'], + currentView: 'instance', + currentCategory: 'local' + }) + await flushPromises() + const primary = wrapper.get('[data-testid="picker-primary-cta"]') + expect(primary.text()).toBe('Start') + await primary.trigger('click') + await flushPromises() + expect(useDialogs().state.open).toBe(false) + expect(bridge.picks).toEqual(['b']) + expect(bridge.restarts).toEqual([]) + }) + it('keeps Switch from the dashboard for a build another window is starting', async () => { const wrapper = await mountPicker({ installs: [makeInstall({ id: 'a', name: 'Alpha', sourceCategory: 'local' })], diff --git a/src/renderer/src/comfyTitlePopup/InstancePickerView.vue b/src/renderer/src/comfyTitlePopup/InstancePickerView.vue index 7e16c5ff3..be2f2a86b 100644 --- a/src/renderer/src/comfyTitlePopup/InstancePickerView.vue +++ b/src/renderer/src/comfyTitlePopup/InstancePickerView.vue @@ -130,7 +130,6 @@ interface PickerBridge { activate?: (id: string) => void close?: () => void pickInstall: (installationId: string) => void - openInstallNewWindow: (installationId: string, opts?: { allowDuplicate?: boolean }) => void restartInstall: (installationId: string, opts?: { confirmed?: boolean }) => void setPickerSelectedInstall: (installationId: string | null) => void pickerUpdateField: ( @@ -433,26 +432,6 @@ const instanceActions = useInstanceActions({ ] }) return result === 'primary' - }, - confirmSwitch: async (inst) => { - const hostIsLocalInstall = - props.snapshot.currentView === 'instance' && props.snapshot.currentCategory === 'local' - if (!hostIsLocalInstall) return 'switch' - const result = await dialogs.confirm({ - title: t('instancePicker.switchConfirmTitle'), - message: t('instancePicker.switchConfirmMessage', { name: inst.name }), - confirmLabel: t('instancePicker.switchConfirmAction'), - secondaryLabel: t('instancePicker.switchConfirmSecondary'), - cancelLabel: t('common.cancel'), - showCancel: true, - messageDetails: [ - { - label: t('instancePicker.confirmHeadsUp'), - items: [t('instancePicker.switchConfirmItem1'), t('instancePicker.switchConfirmItem2')] - } - ] - }) - return result === 'primary' ? 'switch' : result === 'secondary' ? 'new-window' : 'cancel' } }) @@ -600,7 +579,6 @@ async function handleExpandedNav(decision: NavDecision): Promise { @request-close="handleSettingsNavigateList" @request-dismiss="handleClose" @primary-action="handleExpandedNav" - @open-new-window="handleExpandedNav" @op-cancel="handleInlineProgressCancel" @op-retry="handleInlineProgressRetry" @op-dismiss="handleInlineProgressDismiss" diff --git a/src/renderer/src/components/settings/ComfyUISettingsContent.test.ts b/src/renderer/src/components/settings/ComfyUISettingsContent.test.ts index 61d325cec..0726dd78c 100644 --- a/src/renderer/src/components/settings/ComfyUISettingsContent.test.ts +++ b/src/renderer/src/components/settings/ComfyUISettingsContent.test.ts @@ -540,10 +540,10 @@ describe('ComfyUISettingsContent', () => { function emittedDecision(wrapper: VueWrapper) { const calls = wrapper.emitted('primary-action') as unknown[][] | undefined - return calls?.[0]?.[0] as { window: string; verb: string } | undefined + return calls?.[0]?.[0] as { verb: string } | undefined } - it('labels "Start" and emits a same-window switch decision when not running', async () => { + it('labels "Start" and emits a start decision when not running', async () => { const w = await mountContent({ currentView: 'dashboard', currentCategory: null, @@ -551,7 +551,7 @@ describe('ComfyUISettingsContent', () => { }) expect(w.find('.settings-v2-relaunch').text()).toBe('Start') await w.find('.settings-v2-relaunch').trigger('click') - expect(emittedDecision(w)).toMatchObject({ window: 'same', verb: 'switch' }) + expect(emittedDecision(w)).toMatchObject({ verb: 'start' }) }) it('labels "Restart" and emits a restart decision when running in THIS window', async () => { @@ -563,7 +563,7 @@ describe('ComfyUISettingsContent', () => { }) expect(w.find('.settings-v2-relaunch').text()).toBe('Restart') await w.find('.settings-v2-relaunch').trigger('click') - expect(emittedDecision(w)).toMatchObject({ window: 'same', verb: 'restart' }) + expect(emittedDecision(w)).toMatchObject({ verb: 'restart' }) }) it('labels "Switch" and emits a focus decision when running in ANOTHER window', async () => { @@ -602,7 +602,7 @@ describe('ComfyUISettingsContent', () => { }) expect(w.find('.settings-v2-relaunch').text()).toBe('Restart to apply changes') await w.find('.settings-v2-relaunch').trigger('click') - expect(emittedDecision(w)).toMatchObject({ window: 'same', verb: 'restart' }) + expect(emittedDecision(w)).toMatchObject({ verb: 'restart' }) } finally { useComfyUISettingsState.pendingRestartFieldIds.value = new Set() } @@ -622,7 +622,7 @@ describe('ComfyUISettingsContent', () => { const menu = wrapper .findAllComponents({ name: 'MoreMenu' }) .map((m) => m.props('actions') as { id: string }[] | undefined) - .find((acts) => acts?.some((a) => a.id === 'stop' || a.id.startsWith('nav:'))) + .find((acts) => acts?.some((a) => a.id === 'stop')) return menu } @@ -653,7 +653,7 @@ describe('ComfyUISettingsContent', () => { expect(w.find('.settings-v2-cta-caret').exists()).toBe(false) }) - it('stopped cloud target (dashboard host) → caret still offers "Open in new window"', async () => { + it('stopped cloud target (dashboard host) → Open Cloud with no "Open in new window" caret', async () => { useComfyUISettingsState.pinBottomActions.value = [] const w = await mountContent({ currentView: 'dashboard', @@ -661,8 +661,8 @@ describe('ComfyUISettingsContent', () => { activeInstallationId: null, installation: { ...SAMPLE_INSTALL, sourceCategory: 'cloud' } }) - const actions = caretActions(w) - expect(actions?.some((a) => a.id.startsWith('nav:'))).toBe(true) + expect(w.find('.settings-v2-relaunch').text()).toBe('Open Cloud') + expect(w.find('.settings-v2-cta-caret').exists()).toBe(false) }) }) diff --git a/src/renderer/src/components/settings/ComfyUISettingsContent.vue b/src/renderer/src/components/settings/ComfyUISettingsContent.vue index ee2f26d85..f4c34b2a3 100644 --- a/src/renderer/src/components/settings/ComfyUISettingsContent.vue +++ b/src/renderer/src/components/settings/ComfyUISettingsContent.vue @@ -21,7 +21,6 @@ import { Play, RotateCcw, LayoutDashboard, - SquareArrowOutUpRight, Copy, CopyPlus, FolderOpen, @@ -117,7 +116,6 @@ const emit = defineEmits<{ 'request-close': [] 'request-dismiss': [] 'primary-action': [decision: NavDecision] - 'open-new-window': [decision: NavDecision] 'op-cancel': [] 'op-retry': [] 'op-dismiss': [] @@ -478,7 +476,7 @@ function handleSnapshotsRefresh(): void { const isRunningInThisWindow = installCta.runningInThisWindow -const primaryDecision = computed(() => decideNavigation(navState.navInput('primary'))) +const primaryDecision = computed(() => decideNavigation(navState.navInput())) const primaryRestartsTarget = computed( () => isRunningInThisWindow.value || primaryDecision.value.verb === 'restart' @@ -513,8 +511,6 @@ function navIcon(labelKey: string): Component { return RotateCcw case 'instancePicker.switch': return Repeat2 - case 'instancePicker.openInNewWindow': - return SquareArrowOutUpRight case 'instancePicker.open': return Play default: @@ -536,20 +532,10 @@ const primaryActionIcon = computed(() => const stopAction = computed(() => pinBottomActions.value.find((a) => a.id === 'stop') ) -const NAV_ITEM_PREFIX = 'nav:' const caretActions = computed(() => { - if (primaryDecision.value.verb === 'focus') { - return stopAction.value ? [{ ...stopAction.value, icon: actionIcon('stop') }] : [] - } - const navItems: MenuAction[] = primaryDecision.value.secondary.map((alt, i) => ({ - id: `${NAV_ITEM_PREFIX}${i}`, - label: resolveNavLabel(alt.primaryLabel), - icon: navIconFor(alt.primaryLabel) - })) - if (primaryDecision.value.verb === 'restart' && stopAction.value) { - navItems.push({ ...stopAction.value, icon: actionIcon('stop') }) - } - return navItems + const verb = primaryDecision.value.verb + if (!stopAction.value || (verb !== 'focus' && verb !== 'restart')) return [] + return [{ ...stopAction.value, icon: actionIcon('stop') }] }) function actionIcon(id: string): Component { @@ -614,12 +600,6 @@ function closeCaretMenu(): void { } function handleCaretPick(action: ActionDef): void { if (!installation.value) return - if (action.id.startsWith(NAV_ITEM_PREFIX)) { - const index = Number(action.id.slice(NAV_ITEM_PREFIX.length)) - const picked = primaryDecision.value.secondary[index] - if (picked) emit('open-new-window', picked) - return - } void runAction(action) } diff --git a/src/renderer/src/composables/useInstanceActions.test.ts b/src/renderer/src/composables/useInstanceActions.test.ts index ad07a6745..4728e099c 100644 --- a/src/renderer/src/composables/useInstanceActions.test.ts +++ b/src/renderer/src/composables/useInstanceActions.test.ts @@ -7,7 +7,6 @@ function makeBridge() { return { pickInstall: vi.fn(), restartInstall: vi.fn(), - openInstallNewWindow: vi.fn(), openNewInstall: vi.fn() } satisfies InstanceActionsBridge } @@ -18,11 +17,8 @@ function installation(over: Partial = {}): Installation { function decision(over: Partial): NavDecision { return { - window: 'same', - verb: 'switch', - primaryLabel: 'instancePicker.switch', - secondary: [], - telemetry: null, + verb: 'start', + primaryLabel: 'instancePicker.open', ...over } } @@ -34,34 +30,17 @@ function makeDeps( return { bridge, confirmLocalKill: vi.fn().mockResolvedValue(true), - confirmSwitch: vi.fn().mockResolvedValue('switch'), ...over } } describe('useInstanceActions.dispatch', () => { - it('switch → confirm in-drawer then pickInstall(confirmed:true)', async () => { + it('start → pickInstall, with no confirm because nothing is replaced', async () => { const bridge = makeBridge() const deps = makeDeps(bridge) - await useInstanceActions(deps).dispatch(decision({ verb: 'switch' }), installation()) - expect(deps.confirmSwitch).toHaveBeenCalled() - expect(bridge.pickInstall).toHaveBeenCalledWith('a', { confirmed: true }) - }) - - it('switch → "new-window" choice routes to openInstallNewWindow, not pickInstall', async () => { - const bridge = makeBridge() - const deps = makeDeps(bridge, { confirmSwitch: vi.fn().mockResolvedValue('new-window') }) - await useInstanceActions(deps).dispatch(decision({ verb: 'switch' }), installation()) - expect(bridge.openInstallNewWindow).toHaveBeenCalledWith('a') - expect(bridge.pickInstall).not.toHaveBeenCalled() - }) - - it('switch → cancel fires nothing', async () => { - const bridge = makeBridge() - const deps = makeDeps(bridge, { confirmSwitch: vi.fn().mockResolvedValue('cancel') }) - await useInstanceActions(deps).dispatch(decision({ verb: 'switch' }), installation()) - expect(bridge.pickInstall).not.toHaveBeenCalled() - expect(bridge.openInstallNewWindow).not.toHaveBeenCalled() + await useInstanceActions(deps).dispatch(decision({ verb: 'start' }), installation()) + expect(bridge.pickInstall).toHaveBeenCalledExactlyOnceWith('a') + expect(deps.confirmLocalKill).not.toHaveBeenCalled() }) it('routes restart → restartInstall(confirmed:true) after a confirm', async () => { @@ -79,22 +58,13 @@ describe('useInstanceActions.dispatch', () => { expect(bridge.restartInstall).not.toHaveBeenCalled() }) - it('routes open-new → openInstallNewWindow', async () => { + it('routes open-new → pickInstall, the one channel main routes every build pick through', async () => { const bridge = makeBridge() await useInstanceActions(makeDeps(bridge)).dispatch( - decision({ verb: 'open-new', window: 'new' }), + decision({ verb: 'open-new' }), installation() ) - expect(bridge.openInstallNewWindow).toHaveBeenCalledWith('a', expect.objectContaining({})) - }) - - it('passes allowDuplicate through to openInstallNewWindow when a decision sets it', async () => { - const bridge = makeBridge() - await useInstanceActions(makeDeps(bridge)).dispatch( - decision({ verb: 'open-new', window: 'new', allowDuplicate: true }), - installation({ sourceCategory: 'cloud' }) - ) - expect(bridge.openInstallNewWindow).toHaveBeenCalledWith('a', { allowDuplicate: true }) + expect(bridge.pickInstall).toHaveBeenCalledExactlyOnceWith('a') }) it('routes focus → pickInstall (main short-circuits to focus when already up)', async () => { @@ -117,13 +87,12 @@ describe('useInstanceActions.dispatch', () => { await useInstanceActions(makeDeps(bridge)).dispatch(decision({ verb: 'no-op' }), installation()) expect(bridge.pickInstall).not.toHaveBeenCalled() expect(bridge.restartInstall).not.toHaveBeenCalled() - expect(bridge.openInstallNewWindow).not.toHaveBeenCalled() }) it('no-ops when the bridge is undefined', async () => { const deps = { ...makeDeps(makeBridge()), bridge: undefined } await expect( - useInstanceActions(deps).dispatch(decision({ verb: 'switch' }), installation()) + useInstanceActions(deps).dispatch(decision({ verb: 'start' }), installation()) ).resolves.toBeUndefined() }) diff --git a/src/renderer/src/composables/useInstanceActions.ts b/src/renderer/src/composables/useInstanceActions.ts index 424559add..7cb345049 100644 --- a/src/renderer/src/composables/useInstanceActions.ts +++ b/src/renderer/src/composables/useInstanceActions.ts @@ -1,19 +1,15 @@ import type { NavDecision } from '../../../shared/navigation/navDecision' import type { Installation } from '../types/ipc' -export type SwitchChoice = 'switch' | 'new-window' | 'cancel' - export interface InstanceActionsBridge { - pickInstall: (installationId: string, opts?: { confirmed?: boolean }) => void + pickInstall: (installationId: string) => void restartInstall: (installationId: string, opts?: { confirmed?: boolean }) => void - openInstallNewWindow?: (installationId: string, opts?: { allowDuplicate?: boolean }) => void openNewInstall?: () => void } export interface InstanceActionsDeps { bridge: InstanceActionsBridge | undefined confirmLocalKill: (inst: Installation) => Promise - confirmSwitch: (inst: Installation) => Promise } export interface InstanceActions { @@ -32,21 +28,9 @@ export function useInstanceActions(deps: InstanceActionsDeps): InstanceActions { bridge.restartInstall(target.id, { confirmed: true }) return } - case 'switch': { - const choice = await deps.confirmSwitch(target) - if (choice === 'cancel') return - if (choice === 'new-window') { - bridge.openInstallNewWindow?.(target.id) - return - } - bridge.pickInstall(target.id, { confirmed: true }) - return - } + case 'start': + case 'focus': case 'open-new': { - bridge.openInstallNewWindow?.(target.id, { allowDuplicate: decision.allowDuplicate }) - return - } - case 'focus': { bridge.pickInstall(target.id) return } diff --git a/src/renderer/src/composables/useInstanceNavState.test.ts b/src/renderer/src/composables/useInstanceNavState.test.ts index 1962acac4..0d1c347b4 100644 --- a/src/renderer/src/composables/useInstanceNavState.test.ts +++ b/src/renderer/src/composables/useInstanceNavState.test.ts @@ -152,34 +152,30 @@ describe('useInstanceNavState → decideNavigation (end to end)', () => { activeInstallationId: null, startingWithoutWindow: true }) - const decision = decideNavigation(navState.navInput('primary')) + const decision = decideNavigation(navState.navInput()) expect(decision.verb).toBe('restart') expect(decision.primaryLabel).toBe(NAV_LABEL.restart) }) - it('instance host picking a stopped local instance → switch in place', () => { + it('instance host picking a stopped local instance → Start in its own window', () => { const navState = useInstanceNavState(ref(installation('B', 'local')), { currentView: 'instance' as ViewKind, currentCategory: 'local' as Category, activeInstallationId: 'A' }) - const decision = decideNavigation(navState.navInput('primary')) - expect(decision).toMatchObject({ window: 'same', verb: 'switch' }) + const decision = decideNavigation(navState.navInput()) + expect(decision).toEqual({ verb: 'start', primaryLabel: NAV_LABEL.start }) }) - it('dashboard host picking a stopped cloud install → Open Cloud + new-window caret', () => { + it('dashboard host picking a stopped cloud install → Open Cloud', () => { const navState = useInstanceNavState(ref(installation('cloud', 'cloud')), { currentView: 'dashboard' as ViewKind, currentCategory: null, activeInstallationId: null }) - const primaryDecision = decideNavigation(navState.navInput('primary')) - expect(primaryDecision).toMatchObject({ verb: 'switch', primaryLabel: NAV_LABEL.openCloud }) - const caretDecision = decideNavigation(navState.navInput('new-window')) - expect(caretDecision).toMatchObject({ - window: 'new', - verb: 'open-new', - primaryLabel: NAV_LABEL.openInNewWindow + expect(decideNavigation(navState.navInput())).toEqual({ + verb: 'start', + primaryLabel: NAV_LABEL.openCloud }) }) @@ -189,8 +185,8 @@ describe('useInstanceNavState → decideNavigation (end to end)', () => { currentCategory: 'cloud' as Category, activeInstallationId: 'cloud' }) - const decision = decideNavigation(navState.navInput('primary')) - expect(decision).toMatchObject({ window: 'new', verb: 'open-new' }) + const decision = decideNavigation(navState.navInput()) + expect(decision).toEqual({ verb: 'start', primaryLabel: NAV_LABEL.start }) }) it('cloud host picking a stopped REMOTE connection → opens in a new window (not a dead no-op)', () => { @@ -199,12 +195,8 @@ describe('useInstanceNavState → decideNavigation (end to end)', () => { currentCategory: 'cloud' as Category, activeInstallationId: 'cloud' }) - const decision = decideNavigation(navState.navInput('primary')) - expect(decision).toMatchObject({ - window: 'new', - verb: 'open-new', - primaryLabel: NAV_LABEL.openInNewWindow - }) + const decision = decideNavigation(navState.navInput()) + expect(decision).toEqual({ verb: 'start', primaryLabel: NAV_LABEL.openCloud }) }) it('instance host → stopped REMOTE routes identically to stopped Cloud (no in-place 3-way)', () => { @@ -214,12 +206,12 @@ describe('useInstanceNavState → decideNavigation (end to end)', () => { activeInstallationId: 'A' } const remote = decideNavigation( - useInstanceNavState(ref(installation('R', 'remote')), sources).navInput('primary') + useInstanceNavState(ref(installation('R', 'remote')), sources).navInput() ) const cloud = decideNavigation( - useInstanceNavState(ref(installation('C', 'cloud')), sources).navInput('primary') + useInstanceNavState(ref(installation('C', 'cloud')), sources).navInput() ) - expect(remote).toMatchObject({ window: 'new', verb: 'open-new' }) + expect(remote).toEqual({ verb: 'start', primaryLabel: NAV_LABEL.openCloud }) expect(remote).toEqual(cloud) }) }) diff --git a/src/renderer/src/composables/useInstanceNavState.ts b/src/renderer/src/composables/useInstanceNavState.ts index f565d8539..685736ace 100644 --- a/src/renderer/src/composables/useInstanceNavState.ts +++ b/src/renderer/src/composables/useInstanceNavState.ts @@ -15,7 +15,7 @@ export interface InstanceNavState { isTargetCurrentHost: ComputedRef isTargetRunningElsewhere: ComputedRef isTargetRunningHere: ComputedRef - navInput: (intent: NavInput['intent']) => NavInput + navInput: () => NavInput } export interface InstanceNavStateSources { @@ -62,11 +62,10 @@ export function useInstanceNavState( return 'stopped' }) - const navInput = (intent: NavInput['intent']): NavInput => ({ + const navInput = (): NavInput => ({ currentView: toValue(sources.currentView), target: targetKind.value, - targetRun: targetRun.value, - intent + targetRun: targetRun.value }) return { diff --git a/src/renderer/src/panel/BuildDetailsView.test.ts b/src/renderer/src/panel/BuildDetailsView.test.ts index 48c0c8423..785a731c7 100644 --- a/src/renderer/src/panel/BuildDetailsView.test.ts +++ b/src/renderer/src/panel/BuildDetailsView.test.ts @@ -10,14 +10,7 @@ vi.mock('../components/settings/ComfyUISettingsContent.vue', () => ({ default: { name: 'ComfyUISettingsContent', props: ['installation', 'globalSettingsSnapshot', 'pageActionsTarget', 'pageTitleTarget'], - emits: [ - 'show-progress', - 'navigate-list', - 'request-close', - 'request-dismiss', - 'primary-action', - 'open-new-window' - ], + emits: ['show-progress', 'navigate-list', 'request-close', 'request-dismiss', 'primary-action'], template: '
{{ installation.name }}
' } @@ -38,7 +31,6 @@ const INSTALL: Installation = { } const unsubscribeSettings = vi.fn() -const openInstallInNewWindow = vi.fn() beforeEach(() => { vi.clearAllMocks() @@ -46,8 +38,7 @@ beforeEach(() => { getBuildStorageSnapshot: vi.fn().mockResolvedValue(SNAPSHOT), onSettingsChanged: vi.fn(() => unsubscribeSettings), onInstallationsChanged: vi.fn(() => () => {}), - onInstallationsVersionsUpdated: vi.fn(() => () => {}), - openInstallInNewWindow + onInstallationsVersionsUpdated: vi.fn(() => () => {}) } setActivePinia(createPinia()) }) @@ -95,20 +86,11 @@ describe('BuildDetailsView', () => { it('launches the build from the primary action', async () => { const { wrapper, content } = await mountDetails() - content.vm.$emit('primary-action', { verb: 'switch' }) + content.vm.$emit('primary-action', { verb: 'start' }) expect(wrapper.emitted('launch')).toEqual([[INSTALL]]) }) - it('opens the build in its own window instead of launching it into this one', async () => { - const { wrapper, content } = await mountDetails() - - content.vm.$emit('open-new-window', { verb: 'open-new' }) - - expect(openInstallInNewWindow).toHaveBeenCalledExactlyOnceWith('a') - expect(wrapper.emitted('launch')).toBeUndefined() - }) - it.each(['navigate-list', 'request-close', 'request-dismiss'])( 'returns to the list on %s', async (event) => { diff --git a/src/renderer/src/panel/BuildDetailsView.vue b/src/renderer/src/panel/BuildDetailsView.vue index 6a7c1604a..21daef5e4 100644 --- a/src/renderer/src/panel/BuildDetailsView.vue +++ b/src/renderer/src/panel/BuildDetailsView.vue @@ -71,10 +71,6 @@ const status = computed(() => { const storage = ref() -function openInNewWindow(): void { - window.api.openInstallInNewWindow(installation.id) -} - async function loadStorage(): Promise { storage.value = await window.api.getBuildStorageSnapshot() } @@ -159,7 +155,6 @@ onUnmounted(() => unsubscribeSettings?.()) @request-close="emit('back')" @request-dismiss="emit('back')" @primary-action="emit('launch', installation)" - @open-new-window="openInNewWindow" /> diff --git a/src/renderer/src/preview/fakeBridge.ts b/src/renderer/src/preview/fakeBridge.ts index cf5f2bb9e..21033098f 100644 --- a/src/renderer/src/preview/fakeBridge.ts +++ b/src/renderer/src/preview/fakeBridge.ts @@ -242,7 +242,6 @@ export function createFakeBridge(seed: BridgeSeed = {}): FakeBridge { terminalResize: async () => {}, terminalRestart: async () => ({ buffer: [], size: { cols: 80, rows: 24 }, exited: false }), openInstallWindow: async () => true, - openInstallInNewWindow: () => {}, closeComfyWindow: async () => true, closeHostWindow: async () => true, returnToDashboard: async () => true, diff --git a/src/shared/navigation/navDecision.test.ts b/src/shared/navigation/navDecision.test.ts index 0f8759517..004f8afea 100644 --- a/src/shared/navigation/navDecision.test.ts +++ b/src/shared/navigation/navDecision.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest' import { decideNavigation, NAV_LABEL, - type Intent, type NavInput, type TargetKind, type TargetRun @@ -13,14 +12,12 @@ import en from '../../../locales/en.json' const VIEWS: ViewKind[] = ['dashboard', 'instance', 'cloud'] const TARGETS: TargetKind[] = ['dashboard', 'instance', 'cloud', 'new-instance'] const RUNS: TargetRun[] = ['stopped', 'running-elsewhere', 'self', 'starting-unhosted'] -const INTENTS: Intent[] = ['primary', 'new-window'] function input(over: Partial): NavInput { return { currentView: 'dashboard', target: 'instance', targetRun: 'stopped', - intent: 'primary', ...over } } @@ -29,15 +26,20 @@ describe('decideNavigation — totality', () => { it('returns a valid decision for the entire input cross-product', () => { for (const currentView of VIEWS) for (const target of TARGETS) - for (const targetRun of RUNS) - for (const intent of INTENTS) { - const d = decideNavigation(input({ currentView, target, targetRun, intent })) - expect(d).toBeDefined() - expect(['same', 'new']).toContain(d.window) - expect(d.verb).toBeTruthy() - expect(Object.values(NAV_LABEL)).toContain(d.primaryLabel) - expect(Array.isArray(d.secondary)).toBe(true) - } + for (const targetRun of RUNS) { + const d = decideNavigation(input({ currentView, target, targetRun })) + expect(d).toBeDefined() + expect(d.verb).toBeTruthy() + expect(Object.values(NAV_LABEL)).toContain(d.primaryLabel) + } + }) + + it('asks main to start a stopped build the same way from every window, since main picks the window', () => { + for (const currentView of VIEWS) + for (const target of ['instance', 'cloud'] as const) { + const d = decideNavigation(input({ currentView, target, targetRun: 'stopped' })) + expect(d.verb, `${currentView} → ${target} (stopped)`).toBe('start') + } }) it('never produces a dead no-op CTA for a reachable (host, install-target, run) combo', () => { @@ -66,39 +68,37 @@ describe('decideNavigation — totality', () => { }) }) -describe('decideNavigation — the CURRENT-behavior matrix (baseline before #926 deltas)', () => { +describe('decideNavigation — every build opens in its own window', () => { const decisionFor = (currentView: ViewKind, target: TargetKind, targetRun: TargetRun) => decideNavigation(input({ currentView, target, targetRun })) it('Dashboard → Dashboard: no-op', () => { expect(decisionFor('dashboard', 'dashboard', 'self').verb).toBe('no-op') }) - it('Dashboard → Instance (stopped): Start in same window, no caret', () => { - const decision = decisionFor('dashboard', 'instance', 'stopped') - expect(decision).toMatchObject({ - window: 'same', - verb: 'switch', + it('Dashboard → stopped build: Start from this Desktop window', () => { + expect(decisionFor('dashboard', 'instance', 'stopped')).toEqual({ + verb: 'start', primaryLabel: NAV_LABEL.start }) - expect(decision.secondary).toHaveLength(0) }) - it('Dashboard → Instance (running elsewhere): focus, label Switch, no caret', () => { - const decision = decisionFor('dashboard', 'instance', 'running-elsewhere') - expect(decision).toMatchObject({ - window: 'same', + it('Dashboard → closed Cloud: Open Cloud from this Desktop window', () => { + expect(decisionFor('dashboard', 'cloud', 'stopped')).toEqual({ + verb: 'start', + primaryLabel: NAV_LABEL.openCloud + }) + }) + it('Dashboard → build running elsewhere: focus its window, label Switch', () => { + expect(decisionFor('dashboard', 'instance', 'running-elsewhere')).toEqual({ verb: 'focus', primaryLabel: NAV_LABEL.switch }) - expect(decision.secondary).toHaveLength(0) + expect(decisionFor('dashboard', 'cloud', 'running-elsewhere').verb).toBe('focus') }) - it('Dashboard → Instance (starting with no window): Restart, no caret', () => { - const decision = decisionFor('dashboard', 'instance', 'starting-unhosted') - expect(decision).toMatchObject({ - window: 'same', + it('Dashboard → build starting with no window: Restart', () => { + expect(decisionFor('dashboard', 'instance', 'starting-unhosted')).toEqual({ verb: 'restart', primaryLabel: NAV_LABEL.restart }) - expect(decision.secondary).toHaveLength(0) }) it('a build starting with no window reads as running elsewhere outside Dashboard → Instance', () => { const elsewhere: Array<[ViewKind, TargetKind]> = [ @@ -114,176 +114,71 @@ describe('decideNavigation — the CURRENT-behavior matrix (baseline before #926 ) } }) - it('Dashboard → Cloud (closed): Open Cloud same window + new-window caret', () => { - const decision = decisionFor('dashboard', 'cloud', 'stopped') - expect(decision).toMatchObject({ - window: 'same', - verb: 'switch', - primaryLabel: NAV_LABEL.openCloud - }) - expect(decision.secondary.some((alt) => alt.window === 'new' && alt.verb === 'open-new')).toBe( - true - ) - }) it('Dashboard → New Instance: install wizard', () => { expect(decisionFor('dashboard', 'new-instance', 'stopped').verb).toBe('install-wizard') }) - it('Instance → Dashboard: NEW window (instance keeps running)', () => { - const decision = decisionFor('instance', 'dashboard', 'self') - expect(decision).toMatchObject({ - window: 'new', - verb: 'open-new', - primaryLabel: NAV_LABEL.openDashboard + it('build window → stopped build B: Start opens B in its own window', () => { + expect(decisionFor('instance', 'instance', 'stopped')).toEqual({ + verb: 'start', + primaryLabel: NAV_LABEL.start + }) + }) + it('build window → closed Cloud: Open Cloud in its own window', () => { + expect(decisionFor('instance', 'cloud', 'stopped')).toEqual({ + verb: 'start', + primaryLabel: NAV_LABEL.openCloud }) }) - it('Instance → self: Restart in place', () => { - const decision = decisionFor('instance', 'instance', 'self') - expect(decision).toMatchObject({ - window: 'same', + it('build window → itself: Restart in place', () => { + expect(decisionFor('instance', 'instance', 'self')).toEqual({ verb: 'restart', primaryLabel: NAV_LABEL.restart }) }) - it('Instance → Instance B (stopped): switch in place + new-window caret (matrix row 9)', () => { - const decision = decisionFor('instance', 'instance', 'stopped') - expect(decision).toMatchObject({ window: 'same', verb: 'switch' }) - expect(decision.secondary.some((alt) => alt.window === 'new' && alt.verb === 'open-new')).toBe( - true - ) - }) - it('Instance → Instance B (running elsewhere): focus, no caret', () => { - const decision = decisionFor('instance', 'instance', 'running-elsewhere') - expect(decision.verb).toBe('focus') - expect(decision.secondary).toHaveLength(0) + it('build window → build running elsewhere: focus its window', () => { + expect(decisionFor('instance', 'instance', 'running-elsewhere').verb).toBe('focus') + expect(decisionFor('instance', 'cloud', 'running-elsewhere').verb).toBe('focus') }) - it('Instance → Cloud (closed): NEW window, keeps the instance running', () => { - const decision = decisionFor('instance', 'cloud', 'stopped') - expect(decision).toMatchObject({ - window: 'new', + it('build window → Dashboard: open-new', () => { + expect(decisionFor('instance', 'dashboard', 'self')).toEqual({ verb: 'open-new', - primaryLabel: NAV_LABEL.openCloud + primaryLabel: NAV_LABEL.openDashboard }) }) - it('Cloud → Dashboard: new window today (chip is not table-driven)', () => { - const decision = decisionFor('cloud', 'dashboard', 'self') - expect(decision).toMatchObject({ - window: 'new', - verb: 'open-new', - primaryLabel: NAV_LABEL.openDashboard + it('Cloud window → stopped build: Start opens it in its own window', () => { + expect(decisionFor('cloud', 'instance', 'stopped')).toEqual({ + verb: 'start', + primaryLabel: NAV_LABEL.start }) }) - it('Cloud → Instance (stopped): NEW window, keeps the cloud session running', () => { - const decision = decisionFor('cloud', 'instance', 'stopped') - expect(decision).toMatchObject({ - window: 'new', - verb: 'open-new', - primaryLabel: NAV_LABEL.openInNewWindow + it('Cloud window → another closed Cloud or remote build: Open Cloud in its own window', () => { + expect(decisionFor('cloud', 'cloud', 'stopped')).toEqual({ + verb: 'start', + primaryLabel: NAV_LABEL.openCloud }) }) - it('Cloud/Remote → self: Restart in place (second view of one session unsupported)', () => { - const decision = decisionFor('cloud', 'cloud', 'self') - expect(decision).toMatchObject({ - window: 'same', + it('Cloud window → itself: Restart in place', () => { + expect(decisionFor('cloud', 'cloud', 'self')).toEqual({ verb: 'restart', primaryLabel: NAV_LABEL.restart }) }) - it('Cloud → a DIFFERENT cloud/remote running elsewhere: focus (not a dead Start)', () => { - const decision = decisionFor('cloud', 'cloud', 'running-elsewhere') - expect(decision).toMatchObject({ - window: 'same', + it('Cloud window → build running elsewhere: focus its window', () => { + expect(decisionFor('cloud', 'cloud', 'running-elsewhere')).toEqual({ verb: 'focus', primaryLabel: NAV_LABEL.switch }) + expect(decisionFor('cloud', 'instance', 'running-elsewhere').verb).toBe('focus') }) - it('Cloud → a stopped cloud/remote target: opens in a new window (not a dead Start)', () => { - const decision = decisionFor('cloud', 'cloud', 'stopped') - expect(decision).toMatchObject({ - window: 'new', - verb: 'open-new', - primaryLabel: NAV_LABEL.openInNewWindow - }) - }) - it('Cloud → New Instance: install wizard in a new window', () => { - const decision = decisionFor('cloud', 'new-instance', 'stopped') - expect(decision).toMatchObject({ window: 'new', verb: 'install-wizard' }) - }) -}) - -describe('decideNavigation — boundary rules', () => { - it('new-window intent selects the new-window secondary when offered', () => { - const d = decideNavigation( - input({ - currentView: 'dashboard', - target: 'cloud', - targetRun: 'stopped', - intent: 'new-window' - }) - ) - expect(d).toMatchObject({ - window: 'new', - verb: 'open-new', - primaryLabel: NAV_LABEL.openInNewWindow - }) - }) - - it('new-window intent falls back to the primary when no secondary exists', () => { - const primary = decideNavigation( - input({ currentView: 'instance', target: 'instance', targetRun: 'self', intent: 'primary' }) - ) - const viaCaret = decideNavigation( - input({ - currentView: 'instance', - target: 'instance', - targetRun: 'self', - intent: 'new-window' - }) - ) - expect(viaCaret).toEqual(primary) - }) -}) - -describe('decideNavigation — caret (new-window intent)', () => { - it('instance host → stopped instance B: caret selects the new-window alternative', () => { - const primary = decideNavigation( - input({ - currentView: 'instance', - target: 'instance', - targetRun: 'stopped', - intent: 'primary' - }) - ) - expect(primary).toMatchObject({ window: 'same', verb: 'switch' }) - const caret = decideNavigation( - input({ - currentView: 'instance', - target: 'instance', - targetRun: 'stopped', - intent: 'new-window' - }) - ) - expect(caret).toMatchObject({ - window: 'new', - verb: 'open-new', - primaryLabel: NAV_LABEL.openInNewWindow - }) + it('Cloud window → New Instance: install wizard', () => { + expect(decisionFor('cloud', 'new-instance', 'stopped').verb).toBe('install-wizard') }) - - it('dashboard host → open cloud: caret selects the new-window alternative', () => { - const caret = decideNavigation( - input({ - currentView: 'dashboard', - target: 'cloud', - targetRun: 'stopped', - intent: 'new-window' - }) - ) - expect(caret).toMatchObject({ - window: 'new', + it('Cloud window → Dashboard: open-new', () => { + expect(decisionFor('cloud', 'dashboard', 'self')).toEqual({ verb: 'open-new', - primaryLabel: NAV_LABEL.openInNewWindow + primaryLabel: NAV_LABEL.openDashboard }) }) }) diff --git a/src/shared/navigation/navDecision.ts b/src/shared/navigation/navDecision.ts index 6421e7bb8..84db3853f 100644 --- a/src/shared/navigation/navDecision.ts +++ b/src/shared/navigation/navDecision.ts @@ -4,9 +4,7 @@ export type TargetKind = 'dashboard' | 'instance' | 'cloud' | 'new-instance' export type TargetRun = 'stopped' | 'running-elsewhere' | 'self' | 'starting-unhosted' -export type Intent = 'primary' | 'new-window' - -export type Verb = 'switch' | 'restart' | 'open-new' | 'focus' | 'no-op' | 'install-wizard' +export type Verb = 'start' | 'restart' | 'open-new' | 'focus' | 'no-op' | 'install-wizard' export const NAV_LABEL = { start: 'instancePicker.open', @@ -14,165 +12,60 @@ export const NAV_LABEL = { switch: 'instancePicker.switch', openDashboard: 'instancePicker.openDashboard', openCloud: 'instancePicker.openCloud', - openInNewWindow: 'instancePicker.openInNewWindow', newInstall: 'instancePicker.newInstance' } as const export type NavLabelKey = (typeof NAV_LABEL)[keyof typeof NAV_LABEL] export interface NavDecision { - readonly window: 'same' | 'new' readonly verb: Verb readonly primaryLabel: NavLabelKey - readonly secondary: readonly NavDecision[] - readonly allowDuplicate?: true } export interface NavInput { currentView: ViewKind target: TargetKind targetRun: TargetRun - intent: Intent } type CellKey = `${ViewKind}|${TargetKind}|${TargetRun}` const cellKey = (view: ViewKind, target: TargetKind, run: TargetRun): CellKey => `${view}|${target}|${run}` -const NO_OP: NavDecision = Object.freeze({ - window: 'same', - verb: 'no-op', - primaryLabel: NAV_LABEL.start, - secondary: [] -}) - -const dec = ( - over: Partial & Pick -): NavDecision => - Object.freeze({ - ...over, - secondary: Object.freeze(over.secondary ?? []) - }) +const dec = (verb: Verb, primaryLabel: NavLabelKey): NavDecision => + Object.freeze({ verb, primaryLabel }) -const OPEN_NEW_WINDOW_SECONDARY: NavDecision = dec({ - window: 'new', - verb: 'open-new', - primaryLabel: NAV_LABEL.openInNewWindow -}) +const NO_OP = dec('no-op', NAV_LABEL.start) const TABLE: ReadonlyMap = new Map([ [cellKey('dashboard', 'dashboard', 'self'), NO_OP], - [ - cellKey('dashboard', 'instance', 'stopped'), - dec({ window: 'same', verb: 'switch', primaryLabel: NAV_LABEL.start }) - ], - [ - cellKey('dashboard', 'instance', 'running-elsewhere'), - dec({ window: 'same', verb: 'focus', primaryLabel: NAV_LABEL.switch }) - ], - [ - cellKey('dashboard', 'instance', 'starting-unhosted'), - dec({ window: 'same', verb: 'restart', primaryLabel: NAV_LABEL.restart }) - ], - [ - cellKey('dashboard', 'cloud', 'stopped'), - dec({ - window: 'same', - verb: 'switch', - primaryLabel: NAV_LABEL.openCloud, - secondary: [OPEN_NEW_WINDOW_SECONDARY] - }) - ], - [ - cellKey('dashboard', 'cloud', 'running-elsewhere'), - dec({ - window: 'same', - verb: 'focus', - primaryLabel: NAV_LABEL.switch, - secondary: [OPEN_NEW_WINDOW_SECONDARY] - }) - ], - [ - cellKey('dashboard', 'new-instance', 'stopped'), - dec({ window: 'same', verb: 'install-wizard', primaryLabel: NAV_LABEL.newInstall }) - ], - - [ - cellKey('instance', 'dashboard', 'self'), - dec({ window: 'new', verb: 'open-new', primaryLabel: NAV_LABEL.openDashboard }) - ], - [ - cellKey('instance', 'instance', 'self'), - dec({ window: 'same', verb: 'restart', primaryLabel: NAV_LABEL.restart }) - ], - [ - cellKey('instance', 'instance', 'stopped'), - dec({ - window: 'same', - verb: 'switch', - primaryLabel: NAV_LABEL.switch, - secondary: [OPEN_NEW_WINDOW_SECONDARY] - }) - ], - [ - cellKey('instance', 'instance', 'running-elsewhere'), - dec({ window: 'same', verb: 'focus', primaryLabel: NAV_LABEL.switch }) - ], - [ - cellKey('instance', 'cloud', 'stopped'), - dec({ window: 'new', verb: 'open-new', primaryLabel: NAV_LABEL.openCloud }) - ], - [ - cellKey('instance', 'cloud', 'running-elsewhere'), - dec({ - window: 'same', - verb: 'focus', - primaryLabel: NAV_LABEL.switch, - secondary: [OPEN_NEW_WINDOW_SECONDARY] - }) - ], - - [ - cellKey('cloud', 'dashboard', 'self'), - dec({ window: 'new', verb: 'open-new', primaryLabel: NAV_LABEL.openDashboard }) - ], - [ - cellKey('cloud', 'instance', 'stopped'), - dec({ window: 'new', verb: 'open-new', primaryLabel: NAV_LABEL.openInNewWindow }) - ], - [ - cellKey('cloud', 'instance', 'running-elsewhere'), - dec({ window: 'same', verb: 'focus', primaryLabel: NAV_LABEL.switch }) - ], - [ - cellKey('cloud', 'cloud', 'self'), - dec({ window: 'same', verb: 'restart', primaryLabel: NAV_LABEL.restart }) - ], - [ - cellKey('cloud', 'cloud', 'running-elsewhere'), - dec({ window: 'same', verb: 'focus', primaryLabel: NAV_LABEL.switch }) - ], - [ - cellKey('cloud', 'cloud', 'stopped'), - dec({ window: 'new', verb: 'open-new', primaryLabel: NAV_LABEL.openInNewWindow }) - ], - [ - cellKey('cloud', 'new-instance', 'stopped'), - dec({ window: 'new', verb: 'install-wizard', primaryLabel: NAV_LABEL.newInstall }) - ] + [cellKey('dashboard', 'instance', 'stopped'), dec('start', NAV_LABEL.start)], + [cellKey('dashboard', 'instance', 'running-elsewhere'), dec('focus', NAV_LABEL.switch)], + [cellKey('dashboard', 'instance', 'starting-unhosted'), dec('restart', NAV_LABEL.restart)], + [cellKey('dashboard', 'cloud', 'stopped'), dec('start', NAV_LABEL.openCloud)], + [cellKey('dashboard', 'cloud', 'running-elsewhere'), dec('focus', NAV_LABEL.switch)], + [cellKey('dashboard', 'new-instance', 'stopped'), dec('install-wizard', NAV_LABEL.newInstall)], + + [cellKey('instance', 'dashboard', 'self'), dec('open-new', NAV_LABEL.openDashboard)], + [cellKey('instance', 'instance', 'self'), dec('restart', NAV_LABEL.restart)], + [cellKey('instance', 'instance', 'stopped'), dec('start', NAV_LABEL.start)], + [cellKey('instance', 'instance', 'running-elsewhere'), dec('focus', NAV_LABEL.switch)], + [cellKey('instance', 'cloud', 'stopped'), dec('start', NAV_LABEL.openCloud)], + [cellKey('instance', 'cloud', 'running-elsewhere'), dec('focus', NAV_LABEL.switch)], + + [cellKey('cloud', 'dashboard', 'self'), dec('open-new', NAV_LABEL.openDashboard)], + [cellKey('cloud', 'instance', 'stopped'), dec('start', NAV_LABEL.start)], + [cellKey('cloud', 'instance', 'running-elsewhere'), dec('focus', NAV_LABEL.switch)], + [cellKey('cloud', 'cloud', 'self'), dec('restart', NAV_LABEL.restart)], + [cellKey('cloud', 'cloud', 'running-elsewhere'), dec('focus', NAV_LABEL.switch)], + [cellKey('cloud', 'cloud', 'stopped'), dec('start', NAV_LABEL.openCloud)], + [cellKey('cloud', 'new-instance', 'stopped'), dec('install-wizard', NAV_LABEL.newInstall)] ]) -function tableCell(input: NavInput): NavDecision | undefined { - const exact = TABLE.get(cellKey(input.currentView, input.target, input.targetRun)) - if (exact || input.targetRun !== 'starting-unhosted') return exact - return TABLE.get(cellKey(input.currentView, input.target, 'running-elsewhere')) -} - export function decideNavigation(input: NavInput): NavDecision { - const primary = tableCell(input) ?? NO_OP - - if (input.intent === 'new-window') { - const alt = primary.secondary.find((s) => s.window === 'new') - return alt ?? primary + const exact = TABLE.get(cellKey(input.currentView, input.target, input.targetRun)) + if (exact) return exact + if (input.targetRun === 'starting-unhosted') { + return TABLE.get(cellKey(input.currentView, input.target, 'running-elsewhere')) ?? NO_OP } - return primary + return NO_OP } diff --git a/src/types/ipc.ts b/src/types/ipc.ts index 0bf443e7f..263658151 100644 --- a/src/types/ipc.ts +++ b/src/types/ipc.ts @@ -1153,7 +1153,6 @@ export interface ElectronApi { terminalResize(installationId: string, cols: number, rows: number): Promise terminalRestart(installationId: string): Promise openInstallWindow(installationId: string): Promise - openInstallInNewWindow(installationId: string): void closeComfyWindow(installationId: string, opts?: { skipConfirm?: boolean }): Promise closeHostWindow(): Promise returnToDashboard(): Promise