Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
200 changes: 200 additions & 0 deletions browser_tests/fixtures/workflowLinkFixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import type { Page, Route } from '@playwright/test'

import type { UserDataFullInfo } from '@/types'
import type {
ErrorResponse,
WorkflowSidebarFileResponse
} from '@comfyorg/ingest-types'

import enMessages from '@/locales/en/main.json' with { type: 'json' }
import type { RemoteConfig } from '@/platform/remoteConfig/types'
import type { operations } from '@/types/comfyRegistryTypes'

import linkedWorkflow from '@e2e/assets/nodes/note_nodes.json' with { type: 'json' }
import {
cloudAppExpect,
cloudAppFixture,
waitForCloudApp
} from '@e2e/fixtures/cloudAppFixture'
import {
CLOUD_SELF_EMAIL,
CloudAuthHelper
} from '@e2e/fixtures/helpers/CloudAuthHelper'
import {
bootCloud,
mockCloudBoot,
preselectCloudUser
} from '@e2e/fixtures/utils/cloudBootMocks'
import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute'
import type { WorkspaceStore } from '@e2e/types/globals'

const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188'
const BOOT_FEATURES = {} satisfies RemoteConfig
const BOOT_SETTINGS = {
'Comfy.TutorialCompleted': true,
'Comfy.Workflow.Persist': true
}

type CreateCustomerResponse =
operations['createCustomer']['responses']['201']['content']['application/json']

export const workflowLinkScenario = {
workflowId: '82b98188-0c8f-41d2-9b91-617b9152b809',
path: 'workflows/links/linked-workflow.json',
tabName: 'linked-workflow',
notOpenedToast: enMessages.toastMessages.linkedWorkflowNotOpened
} as const

const linkedWorkflowBody = JSON.stringify(linkedWorkflow)

const listedFile: UserDataFullInfo = {
path: workflowLinkScenario.path.slice('workflows/'.length),
size: linkedWorkflowBody.length,
modified: 1_793_000_000_000
}

const sidebarFile: WorkflowSidebarFileResponse = {
...listedFile,
path: workflowLinkScenario.path
}

const outOfSync: ErrorResponse = {
code: 'WORKFLOW_OUT_OF_SYNC',
message: 'The workflow record does not match its sidebar file.',
details: { reason: 'content_mismatch' }
}

function userdataFile(route: Route): string {
const { pathname } = new URL(route.request().url())
return decodeURIComponent(pathname.split('/userdata/')[1] ?? '')
}

class WorkflowLinkHelper {
readonly linkUrl = `${APP_URL}/?workflowId=${workflowLinkScenario.workflowId}`
private readonly savedPaths: string[] = []

constructor(private readonly page: Page) {}

async mockSignedIn(): Promise<void> {
await this.mockBoot()
await bootCloud(this.page)
}

async mockSignedOut(): Promise<void> {
await this.mockBoot()
await preselectCloudUser(this.page)
await this.page.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(this.page).mockLiveEmailSignIn()
}

async serveLinkedFile(): Promise<void> {
await this.page.route(this.sidebarFileUrl(), (route) =>
route.fulfill(jsonRoute(sidebarFile))
)
await this.serveWorkflowsFolder()
}

async refuseLinkedFile(): Promise<void> {
await this.page.route(this.sidebarFileUrl(), (route) =>
route.fulfill({ status: 409, json: outOfSync })
)
}

async open(url: string): Promise<void> {
await this.page.goto(url)
await waitForCloudApp(this.page)
}

async openWithRestoredTabs(): Promise<void> {
await this.open(APP_URL)
await this.page.reload()
await waitForCloudApp(this.page)
}

async signInWithEmail(): Promise<void> {
await cloudAppExpect(
this.page.getByRole('heading', { name: 'Log in to your account' })
).toBeVisible()
await this.page.getByRole('button', { name: 'Use email instead' }).click()
await this.page.locator('#cloud-sign-in-email').fill(CLOUD_SELF_EMAIL)
await this.page
.locator('#cloud-sign-in-password')
.fill('correct-horse-battery-staple')
await this.page.locator('#cloud-sign-in-password').blur()
await this.page.getByRole('button', { name: 'Sign in' }).click()
await waitForCloudApp(this.page)
}

getActiveWorkflowPath(): Promise<string | undefined> {
return this.page.evaluate(
() =>
(window.app!.extensionManager as WorkspaceStore).workflow.activeWorkflow
?.path
)
}

hasLinkInUrl(): boolean {
return new URL(this.page.url()).searchParams.has('workflowId')
}

getSavedWorkflowPaths(): string[] {
return [...this.savedPaths]
}

private sidebarFileUrl(): string {
return `**/api/workflows/${workflowLinkScenario.workflowId}/sidebar-file`
}

private async mockBoot(): Promise<void> {
await mockCloudBoot(this.page, {
features: BOOT_FEATURES,
settings: BOOT_SETTINGS
})
}

private async serveWorkflowsFolder(): Promise<void> {
await this.page.route('**/api/userdata?*', (route) => {
const request = route.request()
const url = new URL(request.url())
if (request.method() !== 'GET') return route.fallback()
if (url.searchParams.get('dir') !== 'workflows') return route.fallback()
return route.fulfill(jsonRoute([listedFile]))
})

await this.page.route('**/api/userdata/*', (route) => {
const method = route.request().method()
const file = userdataFile(route)
if (method === 'GET' && file === workflowLinkScenario.path)
return route.fulfill({
contentType: 'application/json',
body: linkedWorkflowBody
})
if (
method !== 'POST' ||
!file.startsWith('workflows/') ||
file === 'workflows/.index.json'
)
return route.fallback()
this.savedPaths.push(file)
return route.fulfill(
jsonRoute({ ...listedFile, path: file } satisfies UserDataFullInfo)
)
})
}
}

export const workflowLinkFixture = cloudAppFixture.extend<{
workflowLink: WorkflowLinkHelper
}>({
workflowLink: async ({ page }, use) => {
await use(new WorkflowLinkHelper(page))
}
})

export { cloudAppExpect as expect }
87 changes: 87 additions & 0 deletions browser_tests/tests/workflow/cloudWorkflowLink.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { Topbar } from '@e2e/fixtures/components/Topbar'
import {
expect,
workflowLinkFixture as test,
workflowLinkScenario
} from '@e2e/fixtures/workflowLinkFixture'

test.describe('Cloud workflow-id link', { tag: '@cloud' }, () => {
test.describe('when Cloud finds the sidebar file', () => {
test.beforeEach(async ({ workflowLink }) => {
await workflowLink.mockSignedIn()
await workflowLink.serveLinkedFile()
})

test('opens the file, clears the link and saves back to the same file', async ({
page,
workflowLink
}) => {
const topbar = new Topbar(page)

await workflowLink.open(workflowLink.linkUrl)

await expect
.poll(() => workflowLink.getActiveWorkflowPath())
.toBe(workflowLinkScenario.path)
await expect(topbar.getActiveTab()).toContainText(
workflowLinkScenario.tabName
)
await expect.poll(() => workflowLink.hasLinkInUrl()).toBe(false)

await topbar.triggerTopbarCommand(['File', 'Save'])

await expect
.poll(() => workflowLink.getSavedWorkflowPaths())
.toEqual([workflowLinkScenario.path])
})
})

test.describe('when Cloud refuses the link', () => {
test.beforeEach(async ({ workflowLink }) => {
await workflowLink.mockSignedIn()
await workflowLink.refuseLinkedFile()
})

test('shows the error and leaves the restored tabs as they were', async ({
page,
toast,
workflowLink
}) => {
const topbar = new Topbar(page)
await workflowLink.openWithRestoredTabs()
await expect(topbar.tabs.first()).toBeVisible()
const restoredTabs = await topbar.getTabNames()
const restoredActiveTab = await topbar.getActiveTabName()

await workflowLink.open(workflowLink.linkUrl)

await expect(
toast.withText(workflowLinkScenario.notOpenedToast)
).toBeVisible()
await expect.poll(() => topbar.getTabNames()).toEqual(restoredTabs)
expect(await topbar.getActiveTabName()).toBe(restoredActiveTab)
await expect.poll(() => workflowLink.hasLinkInUrl()).toBe(false)
})
})

test.describe('when the visitor is signed out', () => {
test.beforeEach(async ({ workflowLink }) => {
await workflowLink.mockSignedOut()
await workflowLink.serveLinkedFile()
})

test('keeps the link through sign-in and opens the file after it', async ({
page,
workflowLink
}) => {
await page.goto(workflowLink.linkUrl)

await workflowLink.signInWithEmail()

await expect
.poll(() => workflowLink.getActiveWorkflowPath())
.toBe(workflowLinkScenario.path)
await expect.poll(() => workflowLink.hasLinkInUrl()).toBe(false)
})
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# ADR-WORKFLOW-LINKS-0053: Open Workflow Links Through the Sidebar File

Date: 2026-11-09

## Status

Proposed

## Context

A Cloud link of the form `?workflowId=<workflow id>` names one workflow. Cloud
keeps two copies of a saved workflow: the sidebar file, which the editor opens
and saves, and a workflow record with its own id, copied from that file on each
save. The copy is best effort, so the record can fall behind the file. Folder
links cannot name one file, and a path in the link breaks when the file is
renamed.

## Decision

Ask Cloud for the record's sidebar file with
`GET /api/workflows/{workflow_id}/sidebar-file`. Cloud answers with the file's
path only after it has checked that the file exists, that exactly one record
has that name, and that the file's bytes match the record's newest version.
Open that path through the existing workflow service, so Save writes back to
the same sidebar file.

Fail closed. A 404 or any 409 `WORKFLOW_OUT_OF_SYNC` shows "Couldn't open this
workflow" and opens nothing. The editor never falls back to a folder link or to
the record's own content, and restored tabs stay as they were.

Preserve the query through sign-in and onboarding. Defer the lookup while a
deployment or workspace link can reload the page, then resolve it after those
loaders finish. A workflow-id link takes precedence over a folder link, even
when it cannot be opened. Final handling clears both intents, and only for the
link it handled. A link the loader has not settled, such as a newer link the
browser navigated to meanwhile, stays in the URL and the stash. Nothing opens
it until the next page load. A workflow that opened stays open when another
navigation cancels that cleanup; the final URL-action sweep clears the link it
left. Only a reload in flight stops the URL actions. A link that is not settled
does not stop them: the other loaders run, and the final sweep removes their
params but leaves `workflowId` and its stash. A navigation guard can hold a
newer link in the stash while the URL still shows the old one. While the URL
and the stash name different links, the loader treats the stash as a navigation
still in flight: it makes no replace and clears neither carrier, even for a
link it already opened. An empty `?workflowId=` clears the stash when the
router captures it, so an older stashed link cannot keep the empty one from
being rejected as invalid. While the stash holds a link the loader never started
and the URL does not show, the sweep makes no replace either, so that link's
navigation is not cancelled.

The reply and the 409 body are validated with the generated
`@comfyorg/ingest-types` schemas. The spec types the 409 as `ErrorResponse` and
lists the `details.reason` values only in prose, saying the set may grow. The
loader keeps its list of known reasons as a telemetry classification and
records any other value as `unknown`.

Error reports for the link carry a fixed message, the error type and the
failing error's class name. They never carry the caught error or its message:
a failed file read names the file, and a parser error quotes the reply.

## Alternatives considered

- Open the record's own content: rejected because Save would write to a file
the record may not match, and an out-of-date copy would open without notice.
- Link by a new id on the sidebar file: rejected because Cloud's existing
`/api/workflows/{workflow_id}` routes already name a workflow by the record's
id, and a second id for the same workflow would need its own storage.
- Extend the folder loader: rejected because folder filtering and a single
checked lookup have different failure and selection rules.

## Consequences

The link resolves the current sidebar path at open time. Workflow state stays
path based after opening. PostHog records the result, the 409 reason and the
workspace, never a workflow name, path or id. A record that has fallen behind
its file cannot be opened from a link until the next save copies it again.
6 changes: 6 additions & 0 deletions packages/ingest-types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1042,6 +1042,11 @@ export type {
GetWorkflowErrors,
GetWorkflowResponse,
GetWorkflowResponses,
GetWorkflowSidebarFileData,
GetWorkflowSidebarFileError,
GetWorkflowSidebarFileErrors,
GetWorkflowSidebarFileResponse,
GetWorkflowSidebarFileResponses,
GetWorkflowTemplatesData,
GetWorkflowTemplatesResponse,
GetWorkflowTemplatesResponses,
Expand Down Expand Up @@ -1641,6 +1646,7 @@ export type {
WorkflowListResponse,
WorkflowPublishInfo,
WorkflowResponse,
WorkflowSidebarFileResponse,
WorkflowUploadUrlRequest,
WorkflowVersionContentResponse,
WorkflowVersionResponse,
Expand Down
Loading
Loading