From a87543a75dc97c2b2659371a11670027c053e12f Mon Sep 17 00:00:00 2001 From: ShihChi Huang Date: Sun, 8 Nov 2026 01:19:55 +0000 Subject: [PATCH 1/2] feat: carry the Open on Cloud handoff through sign-in and import it on Cloud (#23074) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit

J4 and J10 handoff through sign-in

## Summary Two commits: - **J4, Open on Cloud to sign-in.** A signed-out user lands on the hosted sign-in page; the `from_local` nonce is now a preserved query, so it survives the login round trip back to the editor. - **J10, Browser to Cloud import.** On Cloud with the flag on, a `from_local` link asks its opener tab for the workflow by nonce, accepts it only from a local origin, loads it and says where it came from. A lost sender or closed tab gets retry guidance. With the flag off the link is stripped and nothing is requested. The loader handles only the browser handoff here; the Desktop import arrives in J8. ## Verification
J4 · Browser Open on Cloud → sign-in **1.** Load compatible workflow; open Cloud dialog.
J4 · Browser Open on Cloud → sign-in, step 1 **2.** New tab reaches the real PR-preview sign-in page.
J4 · Browser Open on Cloud → sign-in, step 2
J10 · Browser → Cloud import **1.** Load real EmptyImage → SaveImage in a localhost browser.
J10 · Browser → Cloud import, step 1 **2.** Real compatibility passes; Run on Comfy Cloud dialog shown.
J10 · Browser → Cloud import, step 2 **3.** Open Cloud tab; real opener/postMessage handoff sends the workflow.
J10 · Browser → Cloud import, step 3 **4.** Cloud auto-imports same ID and name/prefix; nonce cleared; Run enabled.
J10 · Browser → Cloud import, step 4
🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: huang47 <157390+huang47@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../fixtures/liveOpenOnCloudFixture.ts | 17 ++ .../tests/liveCloud/openOnCloudLogin.spec.ts | 49 ++++ .../openOnCloudSignInHandoff.spec.ts | 119 ++++++++ src/composables/useUrlActionLoaders.test.ts | 17 +- src/composables/useUrlActionLoaders.ts | 15 +- src/locales/en/main.json | 5 + .../preservedQueryDefinitions.test.ts | 3 +- .../navigation/preservedQueryDefinitions.ts | 4 + .../navigation/preservedQueryNamespaces.ts | 3 +- .../useLocalHandoffUrlLoader.test.ts | 255 ++++++++++++++++++ .../composables/useLocalHandoffUrlLoader.ts | 116 ++++++++ .../openOnCloud/localHandoffProtocol.ts | 9 +- .../useWorkflowPersistenceV2.test.ts | 15 +- .../composables/useWorkflowPersistenceV2.ts | 9 +- 14 files changed, 628 insertions(+), 8 deletions(-) create mode 100644 browser_tests/tests/liveCloud/openOnCloudLogin.spec.ts create mode 100644 browser_tests/tests/openOnCloud/openOnCloudSignInHandoff.spec.ts create mode 100644 src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.test.ts create mode 100644 src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.ts diff --git a/browser_tests/fixtures/liveOpenOnCloudFixture.ts b/browser_tests/fixtures/liveOpenOnCloudFixture.ts index ab20dff678e..e04b020a6d3 100644 --- a/browser_tests/fixtures/liveOpenOnCloudFixture.ts +++ b/browser_tests/fixtures/liveOpenOnCloudFixture.ts @@ -62,3 +62,20 @@ export const liveOpenOnCloudFixture = base.extend<{ await use(comfyPage) } }) + +export const liveOpenOnCloudLoginFixture = liveOpenOnCloudFixture.extend({ + liveNetworkOrigins: async ({ liveNetworkOrigins }, use) => { + await use([ + ...liveNetworkOrigins, + 'https://browser-intake-us5-datadoghq.com', + 'https://utt.impactcdn.com', + 'https://comfyui.sjv.io', + 'https://d.impct.site', + 'https://www.ojrq.net', + 'https://cdn.sy-d.io', + 'https://t.comfy.org', + 'https://o4507954455314432.ingest.us.sentry.io', + 'https://cdp.customer.io' + ]) + } +}) diff --git a/browser_tests/tests/liveCloud/openOnCloudLogin.spec.ts b/browser_tests/tests/liveCloud/openOnCloudLogin.spec.ts new file mode 100644 index 00000000000..ee1f4465a78 --- /dev/null +++ b/browser_tests/tests/liveCloud/openOnCloudLogin.spec.ts @@ -0,0 +1,49 @@ +import { expect } from '@playwright/test' + +import { liveOpenOnCloudLoginFixture as test } from '@e2e/fixtures/liveOpenOnCloudFixture' + +test.describe( + 'Open on Cloud live sign-in handoff', + { tag: ['@cloud-live', '@smoke', '@ui'] }, + () => { + test('opens the selected Cloud deployment login page for a signed-out user', async ({ + comfyPage, + cloudOrigin + }) => { + await test.step('Load the runnable workflow and check compatibility', async () => { + await comfyPage.workflow.loadWorkflow( + 'openOnCloud/01-runnable-on-cloud' + ) + await comfyPage.page.getByTestId('cloud-button').click() + await expect( + comfyPage.page.getByRole('heading', { + name: 'Run on Comfy Cloud', + exact: true + }) + ).toBeVisible() + }) + + await test.step('Open the real Cloud sign-in page for the workflow', async () => { + const cloudTabPromise = comfyPage.page.waitForEvent('popup') + await comfyPage.page + .getByRole('button', { name: 'Open on Comfy Cloud', exact: true }) + .click() + const cloudTab = await cloudTabPromise + await expect + .poll(() => new URL(cloudTab.url()).origin) + .toBe(cloudOrigin) + await expect( + cloudTab.getByRole('heading', { + name: 'Log in to your account', + exact: true + }) + ).toBeVisible() + await test.info().attach('cloud-sign-in.png', { + body: await cloudTab.screenshot(), + contentType: 'image/png' + }) + await cloudTab.close() + }) + }) + } +) diff --git a/browser_tests/tests/openOnCloud/openOnCloudSignInHandoff.spec.ts b/browser_tests/tests/openOnCloud/openOnCloudSignInHandoff.spec.ts new file mode 100644 index 00000000000..86a871fe20d --- /dev/null +++ b/browser_tests/tests/openOnCloud/openOnCloudSignInHandoff.spec.ts @@ -0,0 +1,119 @@ +import type { Page } from '@playwright/test' + +import type { operations } from '@/types/comfyRegistryTypes' + +import handedOverWorkflow from '@e2e/assets/nodes/note_nodes.json' with { type: 'json' } +import { + cloudAppExpect as expect, + cloudAppFixture as test +} from '@e2e/fixtures/cloudAppFixture' +import { + CLOUD_SELF_EMAIL, + CloudAuthHelper +} from '@e2e/fixtures/helpers/CloudAuthHelper' +import { + mockCloudBoot, + preselectCloudUser +} from '@e2e/fixtures/utils/cloudBootMocks' + +const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' +const OPENER_PATH = '/__e2e_local_opener' +const NONCE = '00000000-0000-4000-8000-000000000001' +const FILENAME = 'handed-over.json' + +type CreateCustomerResponse = + operations['createCustomer']['responses']['201']['content']['application/json'] + +async function openLocalOpener(page: Page): Promise { + await page.route(`**${OPENER_PATH}`, (route) => + route.fulfill({ contentType: 'text/html', body: '' }) + ) + await page.goto(`${APP_URL}${OPENER_PATH}`) + await page.evaluate( + ({ nonce, filename, workflow }) => { + window.addEventListener('message', (event) => { + const data: unknown = event.data + if ( + typeof data !== 'object' || + data === null || + !('nonce' in data) || + data.nonce !== nonce || + !event.source + ) + return + ;(event.source as Window).postMessage( + { type: 'comfy-local-handoff:workflow', nonce, filename, workflow }, + '*' + ) + }) + }, + { nonce: NONCE, filename: FILENAME, workflow: handedOverWorkflow } + ) +} + +async function openSignedOutCloudTab(opener: Page): Promise { + const [cloudTab] = await Promise.all([ + opener.waitForEvent('popup'), + opener.evaluate(() => { + window.open('about:blank', 'comfy-cloud') + }) + ]) + await mockCloudBoot(cloudTab, { + features: { open_on_cloud_enabled: true } + }) + await preselectCloudUser(cloudTab) + await cloudTab.route('**/customers', (route) => { + if (route.request().method() !== 'POST') return route.fallback() + return route.fulfill({ + status: 201, + json: { id: 'test-customer-e2e' } satisfies CreateCustomerResponse + }) + }) + await new CloudAuthHelper(cloudTab).mockLiveEmailSignIn() + await opener.evaluate((nonce) => { + window.open(`/?from_local=${nonce}`, 'comfy-cloud') + }, NONCE) + return cloudTab +} + +test.describe( + 'Open on Cloud handoff through sign-in', + { tag: '@cloud' }, + () => { + test('opens the handed-over workflow, uncovered, after a fresh account signs in', async ({ + page + }) => { + await openLocalOpener(page) + const cloudTab = await openSignedOutCloudTab(page) + + await expect( + cloudTab.getByRole('heading', { name: 'Log in to your account' }) + ).toBeVisible() + await cloudTab.getByRole('button', { name: 'Use email instead' }).click() + await cloudTab.locator('#cloud-sign-in-email').fill(CLOUD_SELF_EMAIL) + await cloudTab + .locator('#cloud-sign-in-password') + .fill('correct-horse-battery-staple') + await cloudTab.locator('#cloud-sign-in-password').blur() + await cloudTab.getByRole('button', { name: 'Sign in' }).click() + + await expect( + cloudTab.getByTestId('toast').filter({ + visible: true, + hasText: 'Opened from ComfyUI on your computer' + }) + ).toBeVisible() + await expect + .poll(() => + cloudTab.evaluate(() => + window.app?.graph.nodes.map((node) => node.type).toSorted() + ) + ) + .toEqual(['MarkdownNote', 'Note']) + await expect(cloudTab.getByRole('dialog')).toHaveCount(0) + await expect + .poll(() => new URL(cloudTab.url()).searchParams.has('from_local')) + .toBe(false) + }) + } +) diff --git a/src/composables/useUrlActionLoaders.test.ts b/src/composables/useUrlActionLoaders.test.ts index 605c8b022ef..df17a4332d3 100644 --- a/src/composables/useUrlActionLoaders.test.ts +++ b/src/composables/useUrlActionLoaders.test.ts @@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => ({ loadTopUp: vi.fn(async () => undefined), loadSettings: vi.fn(), loadAssets: vi.fn(async () => undefined), + loadLocalHandoff: vi.fn(async () => undefined), useDeployment: vi.fn(), useWorkspace: vi.fn(), useInvite: vi.fn(), @@ -34,7 +35,8 @@ const mocks = vi.hoisted(() => ({ usePricingTable: vi.fn(), useTopUp: vi.fn(), useSettings: vi.fn(), - useAssets: vi.fn() + useAssets: vi.fn(), + useLocalHandoff: vi.fn() })) mocks.useDeployment.mockImplementation(() => ({ loadDeploymentFromUrl: mocks.loadDeployment @@ -60,6 +62,9 @@ mocks.useSettings.mockImplementation(() => ({ mocks.useAssets.mockImplementation(() => ({ loadAssetsFromUrl: mocks.loadAssets })) +mocks.useLocalHandoff.mockImplementation(() => ({ + loadLocalHandoffFromUrl: mocks.loadLocalHandoff +})) // A real router rather than a stub: several assertions are the URL a reader // is left looking at, and only the real thing resolves and merges a query @@ -108,6 +113,10 @@ vi.mock(import('@/platform/settings/composables/useSettingsUrlLoader'), () => ({ vi.mock(import('@/platform/assets/composables/useAssetsUrlLoader'), () => ({ useAssetsUrlLoader: mocks.useAssets })) +vi.mock( + import('@/platform/openOnCloud/composables/useLocalHandoffUrlLoader'), + () => ({ useLocalHandoffUrlLoader: mocks.useLocalHandoff }) +) vi.mock( import('@/platform/billing/subscription/composables/useSubscriptionDialog') ) @@ -142,6 +151,9 @@ describe('useUrlActionLoaders', () => { mocks.useAssets.mockImplementation(() => ({ loadAssetsFromUrl: mocks.loadAssets })) + mocks.useLocalHandoff.mockImplementation(() => ({ + loadLocalHandoffFromUrl: mocks.loadLocalHandoff + })) vi.mocked(useRouter).mockReturnValue(router) await router.replace({ path: '/', query: {} }) }) @@ -216,6 +228,7 @@ describe('useUrlActionLoaders', () => { expect(mocks.useTopUp).not.toHaveBeenCalled() expect(mocks.useSettings).not.toHaveBeenCalled() expect(mocks.useAssets).not.toHaveBeenCalled() + expect(mocks.useLocalHandoff).not.toHaveBeenCalled() expect(useSubscriptionDialog).not.toHaveBeenCalled() expect(mocks.loadDeployment).not.toHaveBeenCalled() expect(mocks.loadWorkspace).not.toHaveBeenCalled() @@ -225,6 +238,7 @@ describe('useUrlActionLoaders', () => { expect(mocks.loadTopUp).not.toHaveBeenCalled() expect(mocks.loadSettings).not.toHaveBeenCalled() expect(mocks.loadAssets).not.toHaveBeenCalled() + expect(mocks.loadLocalHandoff).not.toHaveBeenCalled() expect( useSubscriptionDialog().resumePendingPricingFlow ).not.toHaveBeenCalled() @@ -242,6 +256,7 @@ describe('useUrlActionLoaders', () => { expect(mocks.loadTopUp).toHaveBeenCalledOnce() expect(mocks.loadSettings).toHaveBeenCalledOnce() expect(mocks.loadAssets).toHaveBeenCalledOnce() + expect(mocks.loadLocalHandoff).toHaveBeenCalledOnce() }) it('opens the requested workspace before any other loader reads the URL', async () => { diff --git a/src/composables/useUrlActionLoaders.ts b/src/composables/useUrlActionLoaders.ts index dff29d48698..738af44f5f0 100644 --- a/src/composables/useUrlActionLoaders.ts +++ b/src/composables/useUrlActionLoaders.ts @@ -11,6 +11,8 @@ import { import { isCloud } from '@/platform/distribution/types' import { clearPreservedQuery } from '@/platform/navigation/preservedQueryManager' import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces' +import { useLocalHandoffUrlLoader } from '@/platform/openOnCloud/composables/useLocalHandoffUrlLoader' +import { LOCAL_HANDOFF_PARAM } from '@/platform/openOnCloud/localHandoffProtocol' import { useSettingsUrlLoader } from '@/platform/settings/composables/useSettingsUrlLoader' import { reportError } from '@/platform/telemetry/reportError' import { useCreateWorkspaceUrlLoader } from '@/platform/workspace/composables/useCreateWorkspaceUrlLoader' @@ -38,6 +40,7 @@ type UrlActionLoaders = { topUpUrlLoader: ReturnType | null settingsUrlLoader: ReturnType | null assetsUrlLoader: ReturnType | null + localHandoffUrlLoader: ReturnType | null } /** @@ -70,6 +73,7 @@ const HANDLED_PARAMS = [ 'topup', 'settings', 'assets', + LOCAL_HANDOFF_PARAM, ...STRIPE_RETURN_PARAMS, ...BILLING_WEB_RETURN_PARAMS ] @@ -150,6 +154,13 @@ function buildUrlActionSteps( run: () => loader.loadAssetsFromUrl() }) } + if (loaders.localHandoffUrlLoader) { + const loader = loaders.localHandoffUrlLoader + steps.push({ + failureMessage: 'Failed to open the workflow handed over from local:', + run: () => loader.loadLocalHandoffFromUrl() + }) + } steps.push({ failureMessage: 'Failed to clear handled deep-link params from the URL:', @@ -230,6 +241,7 @@ export function useUrlActionLoaders() { const topUpUrlLoader = useIfCloud(useTopUpUrlLoader) const settingsUrlLoader = useIfCloud(useSettingsUrlLoader) const assetsUrlLoader = useIfCloud(useAssetsUrlLoader) + const localHandoffUrlLoader = useIfCloud(useLocalHandoffUrlLoader) const subscriptionDialog = useIfCloud(useSubscriptionDialog) const steps = isCloud @@ -242,7 +254,8 @@ export function useUrlActionLoaders() { pricingTableUrlLoader, topUpUrlLoader, settingsUrlLoader, - assetsUrlLoader + assetsUrlLoader, + localHandoffUrlLoader }, router ) diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 5ac6e3f03a6..cdde867b598 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -4213,6 +4213,11 @@ "pointApi": "Call it from your product as an autoscaling API", "pointNodes": "Bring your custom nodes and models" }, + "openedFromLocal": "Opened from ComfyUI on your computer", + "openedFromLocalDetail": "Comfy Cloud has every node and model this workflow uses. Press Run when you're ready.", + "handoffFailed": "Couldn't open the workflow from ComfyUI on your computer", + "handoffMissing": "Your workflow didn't arrive", + "handoffMissingDetail": "ComfyUI stops waiting after 10 minutes. Click Open on Comfy Cloud in ComfyUI again.", "popupBlocked": "Your browser blocked the Comfy Cloud tab. Allow pop-ups for this page and try again.", "prepareFailed": "Couldn't prepare this workflow for Comfy Cloud", "prepareFailedDetail": "Check the workflow for errors, save it, and try again.", diff --git a/src/platform/navigation/preservedQueryDefinitions.test.ts b/src/platform/navigation/preservedQueryDefinitions.test.ts index 35403dceb13..802f4b8c04b 100644 --- a/src/platform/navigation/preservedQueryDefinitions.test.ts +++ b/src/platform/navigation/preservedQueryDefinitions.test.ts @@ -23,7 +23,8 @@ describe('PRESERVED_QUERY_DEFINITIONS', () => { [PRESERVED_QUERY_NAMESPACES.PRICING, 'pricing'], [PRESERVED_QUERY_NAMESPACES.WORKSPACE, 'workspace'], [PRESERVED_QUERY_NAMESPACES.DEPLOYMENT, 'deployment'], - [PRESERVED_QUERY_NAMESPACES.WORKFLOWS, 'workflows'] + [PRESERVED_QUERY_NAMESPACES.WORKFLOWS, 'workflows'], + [PRESERVED_QUERY_NAMESPACES.LOCAL_HANDOFF, 'from_local'] ])('captures %s so a redirect cannot lose it', ([namespace, key]) => { expect(registered.get(namespace)).toContain(key) }) diff --git a/src/platform/navigation/preservedQueryDefinitions.ts b/src/platform/navigation/preservedQueryDefinitions.ts index 51d029848eb..ce6b53a2e2e 100644 --- a/src/platform/navigation/preservedQueryDefinitions.ts +++ b/src/platform/navigation/preservedQueryDefinitions.ts @@ -65,5 +65,9 @@ export const PRESERVED_QUERY_DEFINITIONS: PreservedQueryDefinition[] = [ namespace: PRESERVED_QUERY_NAMESPACES.WORKFLOWS, keys: ['workflows'], rejectRepeated: true + }, + { + namespace: PRESERVED_QUERY_NAMESPACES.LOCAL_HANDOFF, + keys: ['from_local'] } ] diff --git a/src/platform/navigation/preservedQueryNamespaces.ts b/src/platform/navigation/preservedQueryNamespaces.ts index 88d36c17a79..2d65e7cf041 100644 --- a/src/platform/navigation/preservedQueryNamespaces.ts +++ b/src/platform/navigation/preservedQueryNamespaces.ts @@ -12,5 +12,6 @@ export const PRESERVED_QUERY_NAMESPACES = { DESKTOP_LOGIN: 'desktop_login', WORKSPACE: 'workspace', DEPLOYMENT: 'deployment', - WORKFLOWS: 'workflows' + WORKFLOWS: 'workflows', + LOCAL_HANDOFF: 'local_handoff' } as const diff --git a/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.test.ts b/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.test.ts new file mode 100644 index 00000000000..ea727cdb05e --- /dev/null +++ b/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.test.ts @@ -0,0 +1,255 @@ +import { reportError } from '@comfyorg/telemetry/reportError' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useRoute, useRouter } from 'vue-router' + +import { useToast } from '@/components/ui/toast/toastStore' +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { useLocalHandoffUrlLoader } from '@/platform/openOnCloud/composables/useLocalHandoffUrlLoader' +import { app } from '@/scripts/app' +import { defaultGraph } from '@/scripts/defaultGraph' + +const preservedQueryMocks = vi.hoisted(() => ({ + clearPreservedQuery: vi.fn(), + hydratePreservedQuery: vi.fn(), + mergePreservedQueryIntoQuery: vi.fn() +})) + +vi.mock( + import('@/platform/navigation/preservedQueryManager'), + () => preservedQueryMocks +) +vi.mock(import('vue-router')) +vi.mock(import('@/composables/useFeatureFlags')) +vi.mock(import('@/scripts/app')) +vi.mock(import('@comfyorg/telemetry/reportError')) + +function linkWithNonce(): string { + const nonce = crypto.randomUUID() + useRoute().query.from_local = nonce + return nonce +} + +function handOff( + data: unknown, + { + source = window, + origin = 'http://127.0.0.1:8188' + }: { source?: MessageEventSource | null; origin?: string } = {} +): void { + window.dispatchEvent(new MessageEvent('message', { data, source, origin })) +} + +function workflowMessage(nonce: string, workflow: unknown = defaultGraph) { + return { + type: 'comfy-local-handoff:workflow', + nonce, + filename: 'portrait', + workflow + } +} + +async function loadWithOpener(opener: Window | null = window) { + const { loadLocalHandoffFromUrl } = useLocalHandoffUrlLoader(() => opener) + await loadLocalHandoffFromUrl() +} + +describe(useLocalHandoffUrlLoader, () => { + beforeEach(() => { + preservedQueryMocks.mergePreservedQueryIntoQuery.mockReturnValue(null) + vi.mocked(useFeatureFlags().flags).openOnCloudEnabled = true + vi.mocked(app.loadGraphData).mockResolvedValue(true) + vi.spyOn(window, 'postMessage') + }) + + it('does nothing without a from_local param', async () => { + await loadWithOpener() + + expect(useRouter().replace).not.toHaveBeenCalled() + expect(window.postMessage).not.toHaveBeenCalled() + }) + + it('strips the param and asks the opener for the workflow with its nonce', async () => { + const nonce = linkWithNonce() + useRoute().query.other = 'kept' + + await loadWithOpener() + + expect(useRouter().replace).toHaveBeenCalledWith({ + query: { other: 'kept' } + }) + expect(preservedQueryMocks.clearPreservedQuery).toHaveBeenCalledWith( + 'local_handoff' + ) + expect(window.postMessage).toHaveBeenCalledExactlyOnceWith( + { type: 'comfy-local-handoff:ready', nonce }, + '*' + ) + }) + + it('opens the handed-over workflow and says where it came from', async () => { + const nonce = linkWithNonce() + await loadWithOpener() + + handOff(workflowMessage(nonce)) + + await vi.waitFor(() => + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + kind: 'info', + title: 'Opened from ComfyUI on your computer', + description: + "Comfy Cloud has every node and model this workflow uses. Press Run when you're ready." + }) + ) + ) + expect(app.loadGraphData).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + nodes: expect.arrayContaining([ + expect.objectContaining({ type: 'KSampler' }) + ]) + }), + true, + true, + 'portrait' + ) + }) + + it.for<{ + name: string + sameNonce: boolean + source: Window | null + origin: string + }>([ + { + name: 'another window', + sameNonce: true, + source: null, + origin: 'http://127.0.0.1:8188' + }, + { + name: 'the opener with another nonce', + sameNonce: false, + source: window, + origin: 'http://127.0.0.1:8188' + }, + { + name: 'an opener that is not local', + sameNonce: true, + source: window, + origin: 'https://evil.example' + } + ])('ignores a workflow from $name', async ({ sameNonce, source, origin }) => { + const nonce = linkWithNonce() + await loadWithOpener() + + handOff(workflowMessage(sameNonce ? nonce : crypto.randomUUID()), { + source, + origin + }) + await vi.advanceTimersByTimeAsync(0) + + expect(app.loadGraphData).not.toHaveBeenCalled() + }) + + it.for([ + { name: 'the load fails', outcome: false }, + { name: 'a newer load replaces it', outcome: undefined } + ])('does not claim the workflow opened when $name', async ({ outcome }) => { + vi.mocked(app.loadGraphData).mockResolvedValue(outcome) + const nonce = linkWithNonce() + await loadWithOpener() + + handOff(workflowMessage(nonce)) + + await vi.waitFor(() => expect(app.loadGraphData).toHaveBeenCalled()) + await vi.advanceTimersByTimeAsync(0) + expect(useToast().toasts).not.toContainEqual( + expect.objectContaining({ title: 'Opened from ComfyUI on your computer' }) + ) + }) + + it('reports a load that throws and says the workflow did not open', async () => { + vi.mocked(app.loadGraphData).mockRejectedValue(new Error('configure')) + const nonce = linkWithNonce() + await loadWithOpener() + + handOff(workflowMessage(nonce)) + + await vi.waitFor(() => + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + kind: 'error', + title: "Couldn't open the workflow from ComfyUI on your computer" + }) + ) + ) + expect(reportError).toHaveBeenCalledExactlyOnceWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'failure_loading_open_on_cloud_workflow' + }) + ) + }) + + it('refuses a handed-over workflow that fails validation', async () => { + const nonce = linkWithNonce() + await loadWithOpener() + + handOff(workflowMessage(nonce, { nodes: 'not a workflow' })) + + await vi.waitFor(() => + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + kind: 'error', + title: "Couldn't open the workflow from ComfyUI on your computer" + }) + ) + ) + expect(app.loadGraphData).not.toHaveBeenCalled() + }) + + it('explains how to retry when the local sender no longer answers', async () => { + linkWithNonce() + await loadWithOpener() + + await vi.advanceTimersByTimeAsync(60_000) + + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + kind: 'error', + title: "Your workflow didn't arrive", + description: + 'ComfyUI stops waiting after 10 minutes. Click Open on Comfy Cloud in ComfyUI again.' + }) + ) + expect(app.loadGraphData).not.toHaveBeenCalled() + }) + + it('explains how to retry when the local tab is no longer available', async () => { + linkWithNonce() + await loadWithOpener(null) + + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + kind: 'error', + title: "Your workflow didn't arrive" + }) + ) + }) + + it.for([ + { name: 'the flag is off', flag: false, opener: window }, + { name: 'no tab opened this one', flag: true, opener: null } + ])( + 'cleans the query without messaging when $name', + async ({ flag, opener }) => { + vi.mocked(useFeatureFlags().flags).openOnCloudEnabled = flag + linkWithNonce() + + await loadWithOpener(opener) + + expect(useRouter().replace).toHaveBeenCalledWith({ query: {} }) + expect(window.postMessage).not.toHaveBeenCalled() + } + ) +}) diff --git a/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.ts b/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.ts new file mode 100644 index 00000000000..70dd0793143 --- /dev/null +++ b/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.ts @@ -0,0 +1,116 @@ +import { useRoute, useRouter } from 'vue-router' + +import { useToast } from '@/components/ui/toast/toastStore' +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { t } from '@/i18n' +import { + clearPreservedQuery, + hydratePreservedQuery, + mergePreservedQueryIntoQuery +} from '@/platform/navigation/preservedQueryManager' +import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces' +import { + LOCAL_HANDOFF_PARAM, + isLocalOrigin, + localHandoffReady, + zLocalHandoffWorkflow +} from '@/platform/openOnCloud/localHandoffProtocol' +import { reportError } from '@comfyorg/telemetry/reportError' +import { validateComfyWorkflow } from '@comfyorg/graph-model/workflowSchema' +import { app } from '@/scripts/app' + +const NAMESPACE = PRESERVED_QUERY_NAMESPACES.LOCAL_HANDOFF +const HANDOFF_WAIT_MS = 60_000 +const NOTICE_MS = 8000 + +function showMissingWorkflow() { + useToast().error(t('openOnCloud.handoffMissing'), { + description: t('openOnCloud.handoffMissingDetail'), + duration: NOTICE_MS + }) +} + +async function openHandedOffWorkflow( + filename: string, + data: unknown +): Promise { + const toast = useToast() + const workflow = await validateComfyWorkflow(data) + if (!workflow) { + toast.error(t('openOnCloud.handoffFailed'), { duration: NOTICE_MS }) + return + } + try { + const outcome = await app.loadGraphData(workflow, true, true, filename) + if (outcome === false || outcome === undefined) return + } catch (error) { + reportError(error, { + errorType: 'failure_loading_open_on_cloud_workflow', + surface: 'graph' + }) + toast.error(t('openOnCloud.handoffFailed'), { duration: NOTICE_MS }) + return + } + toast.info(t('openOnCloud.openedFromLocal'), { + description: t('openOnCloud.openedFromLocalDetail'), + duration: NOTICE_MS + }) +} + +function requestWorkflow(opener: Window, nonce: string): void { + function onMessage(event: MessageEvent) { + if (event.source !== opener || !isLocalOrigin(event.origin)) return + const handoff = zLocalHandoffWorkflow.safeParse(event.data) + if (!handoff.success || handoff.data.nonce !== nonce) return + stop() + void openHandedOffWorkflow(handoff.data.filename, handoff.data.workflow) + } + function stop() { + window.removeEventListener('message', onMessage) + clearTimeout(deadline) + } + const deadline = setTimeout(() => { + stop() + showMissingWorkflow() + }, HANDOFF_WAIT_MS) + window.addEventListener('message', onMessage) + opener.postMessage(localHandoffReady(nonce), '*') +} + +export function useLocalHandoffUrlLoader( + getOpener: () => Window | null = () => window.opener +) { + const route = useRoute() + const router = useRouter() + const { flags } = useFeatureFlags() + + async function receiveHandoff(nonce: string) { + if (!flags.openOnCloudEnabled) return + const opener = getOpener() + if (opener) requestWorkflow(opener, nonce) + else showMissingWorkflow() + } + + async function loadLocalHandoffFromUrl() { + hydratePreservedQuery(NAMESPACE) + const query = + mergePreservedQueryIntoQuery(NAMESPACE, route.query) ?? route.query + const nonce = query[LOCAL_HANDOFF_PARAM] + if (nonce === undefined) return + + const cleanQuery = { ...query } + delete cleanQuery[LOCAL_HANDOFF_PARAM] + const stripped = router.replace({ query: cleanQuery }).catch((error) => { + console.warn( + '[useLocalHandoffUrlLoader] Failed to clean URL params:', + error + ) + }) + clearPreservedQuery(NAMESPACE) + + if (typeof nonce === 'string') await receiveHandoff(nonce) + await stripped + } + + return { loadLocalHandoffFromUrl } +} diff --git a/src/platform/openOnCloud/localHandoffProtocol.ts b/src/platform/openOnCloud/localHandoffProtocol.ts index af1d4bd9cec..385dc9bb80e 100644 --- a/src/platform/openOnCloud/localHandoffProtocol.ts +++ b/src/platform/openOnCloud/localHandoffProtocol.ts @@ -2,7 +2,7 @@ import { z } from 'zod' import { getComfyCloudBaseUrl } from '@/config/comfyApi' -const LOCAL_HANDOFF_PARAM = 'from_local' +export const LOCAL_HANDOFF_PARAM = 'from_local' const READY = 'comfy-local-handoff:ready' const WORKFLOW = 'comfy-local-handoff:workflow' @@ -12,15 +12,20 @@ export const zLocalHandoffReady = z.object({ nonce: z.string() }) -const zLocalHandoffWorkflow = z.object({ +export const zLocalHandoffWorkflow = z.object({ type: z.literal(WORKFLOW), nonce: z.string(), filename: z.string(), workflow: z.unknown() }) +type LocalHandoffReady = z.infer type LocalHandoffWorkflow = z.infer +export function localHandoffReady(nonce: string): LocalHandoffReady { + return { type: READY, nonce } +} + export function localHandoffWorkflow( nonce: string, filename: string, diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts index cd553e5651b..a97cac8f5e8 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts @@ -114,7 +114,11 @@ vi.mock(import('@/platform/navigation/preservedQueryManager'), () => ({ vi.mock( import('@/platform/navigation/preservedQueryNamespaces'), () => ({ - PRESERVED_QUERY_NAMESPACES: { TEMPLATE: 'template', SHARE: 'share' } + PRESERVED_QUERY_NAMESPACES: { + TEMPLATE: 'template', + SHARE: 'share', + LOCAL_HANDOFF: 'local_handoff' + } }) ) @@ -804,6 +808,15 @@ describe('useWorkflowPersistenceV2', () => { [ 'template intent preserved across /user-select redirect', () => (preservedQueryMocks.payloads.template = { template: 'id' }) + ], + [ + 'local handoff param in URL', + () => (routeMocks.query = { from_local: 'nonce' }) + ], + [ + 'local handoff preserved across the sign-in redirect', + () => + (preservedQueryMocks.payloads.local_handoff = { from_local: 'nonce' }) ] ] as const)( 'reports url-intent, not fresh, with %s', diff --git a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts index 5e9f2626e0d..e9f3ac1efdc 100644 --- a/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts +++ b/src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts @@ -21,6 +21,7 @@ import { } from '@/platform/navigation/preservedQueryManager' import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces' import { isCloud } from '@/platform/distribution/types' +import { LOCAL_HANDOFF_PARAM } from '@/platform/openOnCloud/localHandoffProtocol' import { useSettingStore } from '@/platform/settings/settingStore' import { useFolderWorkflowsUrlLoader } from '@/platform/workflow/management/composables/useFolderWorkflowsUrlLoader' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -59,6 +60,7 @@ export function useWorkflowPersistenceV2() { let openedFolderWorkflows = false const TEMPLATE_NAMESPACE = PRESERVED_QUERY_NAMESPACES.TEMPLATE const SHARE_NAMESPACE = PRESERVED_QUERY_NAMESPACES.SHARE + const LOCAL_HANDOFF_NAMESPACE = PRESERVED_QUERY_NAMESPACES.LOCAL_HANDOFF const draftStore = useWorkflowDraftStoreV2() draftStore.setAuthSubject(isCloud ? null : undefined) const tabState = useWorkflowTabState() @@ -291,6 +293,9 @@ export function useWorkflowPersistenceV2() { const hasTemplateUrlIntent = () => hasPreservedIntent(TEMPLATE_NAMESPACE, 'template') + const hasLocalHandoffIntent = () => + hasPreservedIntent(LOCAL_HANDOFF_NAMESPACE, LOCAL_HANDOFF_PARAM) + const resolveStartupOutcome = async (): Promise => { if (settingStore.get('Comfy.TutorialCompleted')) { await comfyApp.loadGraphData() @@ -300,7 +305,9 @@ export function useWorkflowPersistenceV2() { await useWorkflowService().loadBlankWorkflow() await nextTick() discardStartupBlankDraft() - return hasSharedWorkflowIntent() || hasTemplateUrlIntent() + return hasSharedWorkflowIntent() || + hasTemplateUrlIntent() || + hasLocalHandoffIntent() ? 'url-intent' : 'fresh' } From c10347311c364c773a4b33dc7c45033a89bcd8cc Mon Sep 17 00:00:00 2001 From: huang47 <157390+huang47@users.noreply.github.com> Date: Mon, 9 Nov 2026 23:23:26 +0800 Subject: [PATCH 2/2] fix: adapt the Open on Cloud handoff loader to cloud/1.59 cloud/1.59 predates the telemetry and graph-model package extractions, so point @comfyorg/telemetry/reportError and @comfyorg/graph-model/workflowSchema at the in-tree modules on this branch. --- .../openOnCloud/composables/useLocalHandoffUrlLoader.test.ts | 4 ++-- .../openOnCloud/composables/useLocalHandoffUrlLoader.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.test.ts b/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.test.ts index ea727cdb05e..367792ece3c 100644 --- a/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.test.ts +++ b/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.test.ts @@ -1,4 +1,4 @@ -import { reportError } from '@comfyorg/telemetry/reportError' +import { reportError } from '@/platform/telemetry/reportError' import { beforeEach, describe, expect, it, vi } from 'vitest' import { useRoute, useRouter } from 'vue-router' @@ -21,7 +21,7 @@ vi.mock( vi.mock(import('vue-router')) vi.mock(import('@/composables/useFeatureFlags')) vi.mock(import('@/scripts/app')) -vi.mock(import('@comfyorg/telemetry/reportError')) +vi.mock(import('@/platform/telemetry/reportError')) function linkWithNonce(): string { const nonce = crypto.randomUUID() diff --git a/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.ts b/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.ts index 70dd0793143..bde6ca4467d 100644 --- a/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.ts +++ b/src/platform/openOnCloud/composables/useLocalHandoffUrlLoader.ts @@ -15,8 +15,8 @@ import { localHandoffReady, zLocalHandoffWorkflow } from '@/platform/openOnCloud/localHandoffProtocol' -import { reportError } from '@comfyorg/telemetry/reportError' -import { validateComfyWorkflow } from '@comfyorg/graph-model/workflowSchema' +import { reportError } from '@/platform/telemetry/reportError' +import { validateComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' import { app } from '@/scripts/app' const NAMESPACE = PRESERVED_QUERY_NAMESPACES.LOCAL_HANDOFF