diff --git a/apps/website/public/images/apps/background-removal/example.jpg b/apps/website/public/images/apps/background-removal/example.jpg new file mode 100644 index 00000000000..d9d80e5a238 Binary files /dev/null and b/apps/website/public/images/apps/background-removal/example.jpg differ diff --git a/apps/website/public/images/apps/hand-product-swap/result-can.jpg b/apps/website/public/images/apps/hand-product-swap/result-can.jpg new file mode 100644 index 00000000000..01236f57e2c Binary files /dev/null and b/apps/website/public/images/apps/hand-product-swap/result-can.jpg differ diff --git a/apps/website/public/images/apps/move-anything/example.jpg b/apps/website/public/images/apps/move-anything/example.jpg new file mode 100644 index 00000000000..9e3676fdf38 Binary files /dev/null and b/apps/website/public/images/apps/move-anything/example.jpg differ diff --git a/apps/website/public/images/apps/paparazzi-me/example-result.jpg b/apps/website/public/images/apps/paparazzi-me/example-result.jpg new file mode 100644 index 00000000000..1efeb3e987e Binary files /dev/null and b/apps/website/public/images/apps/paparazzi-me/example-result.jpg differ diff --git a/apps/website/public/images/apps/relight/example.jpg b/apps/website/public/images/apps/relight/example.jpg new file mode 100644 index 00000000000..7a140f8dcbb Binary files /dev/null and b/apps/website/public/images/apps/relight/example.jpg differ diff --git a/apps/website/public/images/apps/sprite-sheet/example.png b/apps/website/public/images/apps/sprite-sheet/example.png new file mode 100644 index 00000000000..ef51c235bf7 Binary files /dev/null and b/apps/website/public/images/apps/sprite-sheet/example.png differ diff --git a/apps/website/public/images/apps/virtual-try-on/person.jpg b/apps/website/public/images/apps/virtual-try-on/person.jpg new file mode 100644 index 00000000000..359b0000900 Binary files /dev/null and b/apps/website/public/images/apps/virtual-try-on/person.jpg differ diff --git a/apps/website/src/components/workshop/AppsHalf.vue b/apps/website/src/components/workshop/AppsHalf.vue new file mode 100644 index 00000000000..6878d713c74 --- /dev/null +++ b/apps/website/src/components/workshop/AppsHalf.vue @@ -0,0 +1,42 @@ + + + diff --git a/apps/website/src/components/workshop/CatalogueShowMore.vue b/apps/website/src/components/workshop/CatalogueShowMore.vue new file mode 100644 index 00000000000..cd5fdb30480 --- /dev/null +++ b/apps/website/src/components/workshop/CatalogueShowMore.vue @@ -0,0 +1,42 @@ + + + diff --git a/apps/website/src/components/workshop/DetailTrail.vue b/apps/website/src/components/workshop/DetailTrail.vue new file mode 100644 index 00000000000..d90165a1271 --- /dev/null +++ b/apps/website/src/components/workshop/DetailTrail.vue @@ -0,0 +1,62 @@ + + + diff --git a/apps/website/src/components/workshop/ExampleCard.vue b/apps/website/src/components/workshop/ExampleCard.vue new file mode 100644 index 00000000000..693b3bd7e90 --- /dev/null +++ b/apps/website/src/components/workshop/ExampleCard.vue @@ -0,0 +1,106 @@ + + + diff --git a/apps/website/src/components/workshop/ExampleMedia.vue b/apps/website/src/components/workshop/ExampleMedia.vue new file mode 100644 index 00000000000..d859d6cdb41 --- /dev/null +++ b/apps/website/src/components/workshop/ExampleMedia.vue @@ -0,0 +1,38 @@ + + + diff --git a/apps/website/src/components/workshop/HubApiTab.vue b/apps/website/src/components/workshop/HubApiTab.vue new file mode 100644 index 00000000000..bcadfec73be --- /dev/null +++ b/apps/website/src/components/workshop/HubApiTab.vue @@ -0,0 +1,348 @@ + + + diff --git a/apps/website/src/components/workshop/HubAppCard.vue b/apps/website/src/components/workshop/HubAppCard.vue new file mode 100644 index 00000000000..8211a113268 --- /dev/null +++ b/apps/website/src/components/workshop/HubAppCard.vue @@ -0,0 +1,80 @@ + + + diff --git a/apps/website/src/components/workshop/HubAppCatalogue.test.ts b/apps/website/src/components/workshop/HubAppCatalogue.test.ts new file mode 100644 index 00000000000..4fb24ae5feb --- /dev/null +++ b/apps/website/src/components/workshop/HubAppCatalogue.test.ts @@ -0,0 +1,129 @@ +import userEvent from '@testing-library/user-event' +import { render, screen, within } from '@testing-library/vue' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { CatalogueApp } from '@/lib/workshop/catalogue-apps' +import { captureWorkshopEvent } from '@/scripts/posthog' +import { + FakeIntersectionObserver, + setAllIntersecting, + stubIntersectionObserver +} from '@/test/fakeIntersectionObserver' +import HubAppCatalogue from './HubAppCatalogue.vue' + +vi.mock(import('@/scripts/posthog')) + +const apps: CatalogueApp[] = [ + { + key: 'apps/cinematic-studio', + name: 'Cinematic Studio', + task: 'Direct your shot like a film set', + href: '/hub/apps/cinematic-studio/' + }, + { + key: 'apps/reshoot', + name: 'Re-shoot a video', + task: 'Re-shoot from any angle', + href: '/hub/apps/reshoot/' + } +] + +const UPCOMING_EN = [ + 'Move anything', + 'Relight', + 'Hand product swap', + 'Background Removal', + 'Virtual try-on', + 'Sprite Sheet Generator', + 'Paparazzi me' +] + +beforeEach(() => { + stubIntersectionObserver() +}) + +const cardNamed = (name: string) => + screen + .getAllByTestId('workshop-app-card') + .find((card) => within(card).queryByRole('heading', { name })) + +describe('HubAppCatalogue', () => { + it('opens a live app in a new tab and lists the apps still being built after it', () => { + render(HubAppCatalogue, { props: { apps } }) + + const studio = screen.getByRole('link', { name: /Cinematic Studio/ }) + expect(studio).toHaveAttribute('href', '/hub/apps/cinematic-studio/') + expect(studio).toHaveAttribute('target', '_blank') + expect(studio).toHaveAttribute('rel', 'noopener') + expect(screen.getAllByRole('link')).toHaveLength(2) + expect( + screen.getAllByRole('heading', { level: 3 }).map((h) => h.textContent) + ).toEqual(['Cinematic Studio', 'Re-shoot a video', ...UPCOMING_EN]) + }) + + it.for([ + { name: 'Cinematic Studio', status: 'Open' }, + { name: 'Relight', status: 'Soon' } + ])('badges $name as $status', ({ name, status }) => { + render(HubAppCatalogue, { props: { apps } }) + + expect( + within(cardNamed(name)!).getByTestId('app-card-status') + ).toHaveTextContent(status) + }) + + it('names the grid for readers who move by heading', () => { + render(HubAppCatalogue, { props: { apps } }) + + expect(screen.getByRole('heading', { level: 2, name: 'Apps' })).toBeTruthy() + }) + + it('writes the apps still being built in Chinese on the Chinese page', () => { + render(HubAppCatalogue, { props: { apps: [], locale: 'zh-CN' } }) + + expect(screen.getByRole('heading', { name: '重新布光' })).toBeTruthy() + }) + + it('reports an opened app from the Hub grid and ignores the ones still being built', async () => { + const user = userEvent.setup() + render(HubAppCatalogue, { props: { apps } }) + + await user.click(cardNamed('Relight')!) + expect(captureWorkshopEvent).not.toHaveBeenCalled() + + const reshoot = screen.getByRole('link', { name: /Re-shoot a video/ }) + reshoot.addEventListener('click', (event) => event.preventDefault(), { + once: true + }) + await user.click(reshoot) + expect(captureWorkshopEvent).toHaveBeenCalledExactlyOnceWith({ + name: 'hub_item_clicked', + properties: { + surface: 'apps', + kind: 'app', + slug: 'apps/reshoot', + source: 'app_grid', + position: 1 + } + }) + }) + + it('reports only the apps a visitor can open once the grid scrolls into view', async () => { + render(HubAppCatalogue, { props: { apps } }) + + await setAllIntersecting(true) + + expect(FakeIntersectionObserver.instances[0].observed).toEqual([ + screen.getByTestId('app-grid-row') + ]) + expect(captureWorkshopEvent).toHaveBeenCalledExactlyOnceWith({ + name: 'hub_row_viewed', + properties: { + surface: 'apps', + source: 'app_grid', + item_count: 2, + row_slugs: ['apps/cinematic-studio', 'apps/reshoot'] + } + }) + }) +}) diff --git a/apps/website/src/components/workshop/HubAppCatalogue.vue b/apps/website/src/components/workshop/HubAppCatalogue.vue new file mode 100644 index 00000000000..b3bdc7cb50d --- /dev/null +++ b/apps/website/src/components/workshop/HubAppCatalogue.vue @@ -0,0 +1,77 @@ + + + diff --git a/apps/website/src/components/workshop/HubBreadcrumb.vue b/apps/website/src/components/workshop/HubBreadcrumb.vue new file mode 100644 index 00000000000..cc911c65d97 --- /dev/null +++ b/apps/website/src/components/workshop/HubBreadcrumb.vue @@ -0,0 +1,48 @@ + + + diff --git a/apps/website/src/components/workshop/HubExamplesTab.vue b/apps/website/src/components/workshop/HubExamplesTab.vue new file mode 100644 index 00000000000..dcde64be9a9 --- /dev/null +++ b/apps/website/src/components/workshop/HubExamplesTab.vue @@ -0,0 +1,111 @@ + + + diff --git a/apps/website/src/components/workshop/HubModelDetail.vue b/apps/website/src/components/workshop/HubModelDetail.vue new file mode 100644 index 00000000000..2bde2db26e6 --- /dev/null +++ b/apps/website/src/components/workshop/HubModelDetail.vue @@ -0,0 +1,1031 @@ + + + diff --git a/apps/website/src/components/workshop/HubModelPage.vue b/apps/website/src/components/workshop/HubModelPage.vue new file mode 100644 index 00000000000..323e6641d19 --- /dev/null +++ b/apps/website/src/components/workshop/HubModelPage.vue @@ -0,0 +1,174 @@ + + + diff --git a/apps/website/src/components/workshop/HubPlaygroundOutput.vue b/apps/website/src/components/workshop/HubPlaygroundOutput.vue new file mode 100644 index 00000000000..a0a12219e42 --- /dev/null +++ b/apps/website/src/components/workshop/HubPlaygroundOutput.vue @@ -0,0 +1,410 @@ + + + diff --git a/apps/website/src/components/workshop/ModelDetail.vue b/apps/website/src/components/workshop/ModelDetail.vue index 6c30716a54f..09d754ad95c 100644 --- a/apps/website/src/components/workshop/ModelDetail.vue +++ b/apps/website/src/components/workshop/ModelDetail.vue @@ -4,6 +4,7 @@ import { useEventListener, useMounted, useTimestamp } from '@vueuse/core' import { computed, effectScope, + inject, onMounted, onScopeDispose, onUnmounted, @@ -18,6 +19,7 @@ import { cn } from '@comfyorg/tailwind-utils' import Button from '@/components/ui/button/Button.vue' import CopyTextButton from '@/components/ui/copy-text-button/CopyTextButton.vue' import { useWorkshopFormDraft } from '@/composables/useWorkshopFormDraft' +import { LIVE_PAGE_HELD } from '@/lib/workshop/live-page-hold' import { useWorkshopDelivery } from '@/composables/useWorkshopDelivery' import { sameFormValues } from '@/lib/workshop/form-values' import { validateWorkshopMediaInputs } from '@/config/workshop-media-validation' @@ -188,12 +190,14 @@ const values = computed({ else fieldValues.value = value } }) +const held = inject(LIVE_PAGE_HELD, ref(false)) const { pending: draftPending, restoreFailed } = useWorkshopFormDraft( model.slug, schema, values, nativeJson, - !!model.execution && model.execution.inputs === undefined + !!model.execution && model.execution.inputs === undefined, + { held } ) // The marks are what the page itself put on the form, taken before anything // else can write. A restored draft is a reader's own work carried across a @@ -276,7 +280,7 @@ const signInHref = useSignInHref(locale) const docsHref = modelDocsHref(model) watch( - () => mounted.value && workshopEnabled.value, + () => mounted.value && workshopEnabled.value && !held.value, (visible) => { if (visible) { captureWorkshopEvent({ name: 'model_viewed', properties: modelAnalytics }) diff --git a/apps/website/src/components/workshop/ModelPageSwitch.ssr.test.ts b/apps/website/src/components/workshop/ModelPageSwitch.ssr.test.ts new file mode 100644 index 00000000000..a72ee96a9ce --- /dev/null +++ b/apps/website/src/components/workshop/ModelPageSwitch.ssr.test.ts @@ -0,0 +1,59 @@ +// @vitest-environment node +import { describe, expect, it, vi } from 'vitest' +import { createSSRApp, h, readonly, ref } from 'vue' +import { renderToString } from 'vue/server-renderer' + +import type { RouterWorkshopModelDetail } from '@/config/models-catalogue' +import { + useWorkshopEnabled, + useWorkshopEnabledSettled, + useWorkshopFlag +} from '@/scripts/posthog' +import ModelPageSwitch from './ModelPageSwitch.vue' + +vi.mock(import('@/scripts/posthog')) +vi.mock(import('@/config/workshop-session-state')) +vi.mock(import('@/config/workshop-credits')) + +const model: RouterWorkshopModelDetail = { + slug: 'demo', + name: 'Demo', + workflowCount: 1, + href: '/models/demo/', + routerId: 'demo/demo', + capabilities: [], + provider: 'Demo', + modality: 'image', + fields: [], + defaults: {}, + examples: [] +} + +describe('the model page on the server', () => { + it('renders the published page even for a visitor whose flag is already on, so hydration matches', async () => { + vi.mocked(useWorkshopFlag).mockReturnValue(readonly(ref(true))) + vi.mocked(useWorkshopEnabled).mockReturnValue(readonly(ref(true))) + vi.mocked(useWorkshopEnabledSettled).mockReturnValue(readonly(ref(true))) + + const html = await renderToString( + createSSRApp({ + render: () => + h(ModelPageSwitch, { + page: { + model, + related: [], + relatedHeading: 'Related models', + providerModels: [], + workflows: [], + shownTags: [], + restTags: [], + restTagCount: 0 + } + }) + }) + ) + + expect(html).toContain('data-testid="model-hero"') + expect(html).not.toContain('data-testid="model-trail"') + }) +}) diff --git a/apps/website/src/components/workshop/ModelPageSwitch.test.ts b/apps/website/src/components/workshop/ModelPageSwitch.test.ts new file mode 100644 index 00000000000..7e4a8a32921 --- /dev/null +++ b/apps/website/src/components/workshop/ModelPageSwitch.test.ts @@ -0,0 +1,134 @@ +import { render, screen } from '@testing-library/vue' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, h, inject, nextTick, readonly, ref, watch } from 'vue' +import type { Ref } from 'vue' + +import type { RouterWorkshopModelDetail } from '@/config/models-catalogue' +import { HUB_HOME_FLAG } from '@/lib/workshop/hub-section' +import { LIVE_PAGE_HELD } from '@/lib/workshop/live-page-hold' +import { useWorkshopEnabledSettled, useWorkshopFlag } from '@/scripts/posthog' +import ModelPageSwitch from './ModelPageSwitch.vue' + +vi.mock(import('@/scripts/posthog')) + +const heldSeen: boolean[] = [] + +const PublishedPageStub = defineComponent({ + props: { page: { type: Object, required: true } }, + setup() { + const held = inject(LIVE_PAGE_HELD, ref(false)) + watch(held, (value) => heldSeen.push(value), { immediate: true }) + return () => + h('div', { + 'data-testid': 'published-model-page', + 'data-held': String(held.value) + }) + } +}) + +let hubHome: Ref +let flagsSettled: Ref + +beforeEach(() => { + heldSeen.length = 0 + hubHome = ref(false) + flagsSettled = ref(true) + vi.mocked(useWorkshopFlag).mockImplementation((name) => + readonly(name === HUB_HOME_FLAG ? hubHome : ref(false)) + ) + vi.mocked(useWorkshopEnabledSettled).mockReturnValue(readonly(flagsSettled)) +}) + +const model: RouterWorkshopModelDetail = { + slug: 'provider--model--generate-images', + name: 'Example Model', + href: '/hub/models/provider--model--generate-images/', + routerId: 'provider/model', + workflowCount: 0, + capabilities: [], + fields: [], + examples: [], + defaults: {} +} + +const renderSwitch = () => + render(ModelPageSwitch, { + props: { + page: { + model, + related: [], + relatedHeading: 'Related models', + providerModels: [], + workflows: [], + shownTags: [], + restTags: [], + restTagCount: 0 + } + }, + global: { + stubs: { + ModelPage: PublishedPageStub, + HubModelPage: { template: '
' } + } + } + }) + +describe('the model page', () => { + it('keeps the page that is published today while the flag is closed', async () => { + renderSwitch() + + const published = await screen.findByTestId('published-model-page') + expect(published).toHaveAttribute('data-held', 'false') + expect(screen.queryByTestId('hub-model-page')).toBeNull() + }) + + it('swaps in the Hub page once the flag answers after the page is up', async () => { + renderSwitch() + await screen.findByTestId('published-model-page') + + hubHome.value = true + + expect(await screen.findByTestId('hub-model-page')).toBeTruthy() + expect(screen.queryByTestId('published-model-page')).toBeNull() + }) + + it('keeps the Hub page once chosen, even while the flag is asked again', async () => { + hubHome.value = true + renderSwitch() + await screen.findByTestId('hub-model-page') + + hubHome.value = false + await nextTick() + expect(screen.getByTestId('hub-model-page')).toBeTruthy() + + hubHome.value = true + await nextTick() + expect(screen.getByTestId('hub-model-page')).toBeTruthy() + expect(screen.queryByTestId('published-model-page')).toBeNull() + }) + + it('holds the published page back until the flag has answered', async () => { + flagsSettled.value = false + renderSwitch() + const published = await screen.findByTestId('published-model-page') + expect(published).toHaveAttribute('data-held', 'true') + + flagsSettled.value = true + await nextTick() + + expect(published).toHaveAttribute('data-held', 'false') + }) + + it('never lets a visitor bound for the Hub page restore or report on the published one', async () => { + flagsSettled.value = false + renderSwitch() + await screen.findByTestId('published-model-page') + + hubHome.value = true + flagsSettled.value = true + + await screen.findByTestId('hub-model-page') + expect(heldSeen.length).toBeGreaterThan(0) + expect(heldSeen).not.toContain(false) + }) +}) diff --git a/apps/website/src/components/workshop/ModelPageSwitch.vue b/apps/website/src/components/workshop/ModelPageSwitch.vue new file mode 100644 index 00000000000..d54770cc0f5 --- /dev/null +++ b/apps/website/src/components/workshop/ModelPageSwitch.vue @@ -0,0 +1,54 @@ + + + diff --git a/apps/website/src/components/workshop/ModelsCatalogue.apps.test.ts b/apps/website/src/components/workshop/ModelsCatalogue.apps.test.ts new file mode 100644 index 00000000000..195a88abfad --- /dev/null +++ b/apps/website/src/components/workshop/ModelsCatalogue.apps.test.ts @@ -0,0 +1,83 @@ +import { render, screen, within } from '@testing-library/vue' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { readonly, ref } from 'vue' +import type { Ref } from 'vue' + +import type { WorkshopModel } from '@/config/models-catalogue' +import { HUB_HOME_FLAG } from '@/lib/workshop/hub-section' +import { + useWorkshopAppsEnabled, + useWorkshopEnabled, + useWorkshopFlag +} from '@/scripts/posthog' +import ModelsCatalogue from './ModelsCatalogue.vue' + +vi.mock(import('@/scripts/posthog')) + +let hubHome: Ref + +const apps: WorkshopModel[] = [ + { + type: 'APP', + appId: 'studio', + slug: 'apps/cinematic-studio', + name: 'Cinematic Studio', + href: '/hub/apps/cinematic-studio/', + workflowCount: 0, + capabilities: [], + useCases: [] + } +] + +beforeEach(() => { + history.replaceState(null, '', '/hub/apps/') + hubHome = ref(false) + vi.mocked(useWorkshopEnabled).mockReturnValue(readonly(ref(true))) + vi.mocked(useWorkshopAppsEnabled).mockReturnValue(readonly(ref(true))) + vi.mocked(useWorkshopFlag).mockImplementation((name) => + readonly(name === HUB_HOME_FLAG ? hubHome : ref(true)) + ) +}) + +const renderApps = () => + render(ModelsCatalogue, { props: { models: apps, section: 'apps' } }) + +describe('the Apps half of the catalogue', () => { + it('keeps the catalogue that is published today while the flag is closed', async () => { + renderApps() + + expect(await screen.findByTestId('workshop-toolbar')).toBeTruthy() + expect(screen.queryByTestId('app-grid')).toBeNull() + }) + + it('swaps in the Hub catalogue once the flag answers for this visitor', async () => { + renderApps() + expect(await screen.findByTestId('workshop-toolbar')).toBeTruthy() + + hubHome.value = true + + expect(await screen.findByTestId('app-grid')).toBeTruthy() + expect(screen.queryByTestId('workshop-toolbar')).toBeNull() + expect(screen.queryByTestId('app-shelf')).toBeNull() + }) + + it('keeps the tabs to the other catalogues above the Hub grid', async () => { + hubHome.value = true + renderApps() + + const tabs = await screen.findByTestId('hub-apps-tabs') + expect(within(tabs).getByRole('link', { name: /Models/ })).toBeTruthy() + }) + + it('describes the open apps in the Hub catalogue words', async () => { + hubHome.value = true + renderApps() + + const card = (await screen.findAllByTestId('workshop-app-card'))[0] + expect(card.textContent).toContain( + 'Direct every shot. Pick the camera, lens, light and grade.' + ) + expect(card.textContent).not.toContain('Direct your shot like a film set') + expect(card.textContent).toContain('Image · 5 models') + }) +}) diff --git a/apps/website/src/components/workshop/ModelsCatalogue.vue b/apps/website/src/components/workshop/ModelsCatalogue.vue index f68b338c63b..7ab4e48c79d 100644 --- a/apps/website/src/components/workshop/ModelsCatalogue.vue +++ b/apps/website/src/components/workshop/ModelsCatalogue.vue @@ -21,14 +21,12 @@ import { } from '@/scripts/posthog' import type { CatalogueApp } from '@/lib/workshop/catalogue-apps' import { ac } from '@/lib/workshop/catalogue-apps' -import { - loadAppCatalogue, - loadWorkflowCatalogue -} from '@/lib/workshop/catalogue-components' +import { loadAppsHalf } from '@/lib/workshop/apps-half' +import { loadWorkflowCatalogue } from '@/lib/workshop/catalogue-components' import { isWorkshopModelShown } from '@/scripts/workshop-model-flags' const WorkflowCatalogue = defineAsyncComponent(loadWorkflowCatalogue) -const AppCatalogue = defineAsyncComponent(loadAppCatalogue) +const AppsHalf = defineAsyncComponent(loadAppsHalf) const { models, @@ -173,7 +171,7 @@ whenever( /> - - + diff --git a/apps/website/src/components/workshop/model-detail/ModelApiHeading.vue b/apps/website/src/components/workshop/model-detail/ModelApiHeading.vue new file mode 100644 index 00000000000..e5b9e34b3bd --- /dev/null +++ b/apps/website/src/components/workshop/model-detail/ModelApiHeading.vue @@ -0,0 +1,35 @@ + + + diff --git a/apps/website/src/components/workshop/model-detail/ModelPaths.vue b/apps/website/src/components/workshop/model-detail/ModelPaths.vue new file mode 100644 index 00000000000..537c84c2cc2 --- /dev/null +++ b/apps/website/src/components/workshop/model-detail/ModelPaths.vue @@ -0,0 +1,56 @@ + + + diff --git a/apps/website/src/components/workshop/model-detail/ModelSamples.vue b/apps/website/src/components/workshop/model-detail/ModelSamples.vue new file mode 100644 index 00000000000..848ed255f58 --- /dev/null +++ b/apps/website/src/components/workshop/model-detail/ModelSamples.vue @@ -0,0 +1,60 @@ + + + diff --git a/apps/website/src/components/workshop/model-detail/PlaygroundInputHeader.vue b/apps/website/src/components/workshop/model-detail/PlaygroundInputHeader.vue new file mode 100644 index 00000000000..519a1b0fa71 --- /dev/null +++ b/apps/website/src/components/workshop/model-detail/PlaygroundInputHeader.vue @@ -0,0 +1,34 @@ + + + diff --git a/apps/website/src/components/workshop/model-detail/ProviderMark.vue b/apps/website/src/components/workshop/model-detail/ProviderMark.vue new file mode 100644 index 00000000000..ac7eb176bc5 --- /dev/null +++ b/apps/website/src/components/workshop/model-detail/ProviderMark.vue @@ -0,0 +1,21 @@ + + + diff --git a/apps/website/src/components/workshop/model-detail/ProviderModelsTable.test.ts b/apps/website/src/components/workshop/model-detail/ProviderModelsTable.test.ts new file mode 100644 index 00000000000..f3511bb1e3d --- /dev/null +++ b/apps/website/src/components/workshop/model-detail/ProviderModelsTable.test.ts @@ -0,0 +1,66 @@ +import { render, screen, within } from '@testing-library/vue' +import { describe, expect, it } from 'vitest' + +import type { ProviderModelRow } from '@/config/models-page-data' +import ProviderModelsTable from './ProviderModelsTable.vue' + +const row = (slug: string, fields: Partial = {}) => ({ + slug, + name: slug, + href: `/hub/models/${slug}/`, + provider: 'Acme', + ...fields +}) + +function cells() { + return screen.getAllByTestId('provider-model-row').map((tr) => + within(tr) + .getAllByRole('cell') + .map((cell) => cell.textContent.trim()) + ) +} + +describe('ProviderModelsTable', () => { + it('names the provider and lists each model with its price, resolution and duration', () => { + render(ProviderModelsTable, { + props: { + provider: 'Acme', + rows: [ + row('painter', { + price: '~9.5 credits/Image', + resolution: '1K – 2K' + }), + row('director', { + resolution: '480p – 4K', + duration: { min: 4, max: 30 } + }), + row('clip', { duration: { min: 5, max: 5 } }), + row('open', { duration: { max: 15 } }) + ] + } + }) + + expect( + screen.getByRole('heading', { level: 2, name: 'More from Acme' }) + ).toBeTruthy() + expect( + screen.getAllByRole('columnheader').map((th) => th.textContent.trim()) + ).toEqual(['Model', 'Price', 'Resolution', 'Duration']) + expect(cells()).toEqual([ + ['~9.5 credits/Image', '1K – 2K', '—'], + ['—', '480p – 4K', '4 – 30s'], + ['—', '—', '5s'], + ['—', '—', 'up to 15s'] + ]) + expect(screen.getByRole('link', { name: 'director' })).toHaveAttribute( + 'href', + '/hub/models/director/' + ) + }) + + it('stays hidden without other models', () => { + render(ProviderModelsTable, { props: { provider: 'Acme', rows: [] } }) + + expect(screen.queryByTestId('related-models')).toBeNull() + }) +}) diff --git a/apps/website/src/components/workshop/model-detail/ProviderModelsTable.vue b/apps/website/src/components/workshop/model-detail/ProviderModelsTable.vue new file mode 100644 index 00000000000..6db8df3786d --- /dev/null +++ b/apps/website/src/components/workshop/model-detail/ProviderModelsTable.vue @@ -0,0 +1,126 @@ + + + diff --git a/apps/website/src/components/workshop/model-detail/RunGateAction.vue b/apps/website/src/components/workshop/model-detail/RunGateAction.vue new file mode 100644 index 00000000000..1817923cc50 --- /dev/null +++ b/apps/website/src/components/workshop/model-detail/RunGateAction.vue @@ -0,0 +1,149 @@ + + + diff --git a/apps/website/src/components/workshop/model-detail/RunRequestMeta.vue b/apps/website/src/components/workshop/model-detail/RunRequestMeta.vue new file mode 100644 index 00000000000..f0c4201a6b7 --- /dev/null +++ b/apps/website/src/components/workshop/model-detail/RunRequestMeta.vue @@ -0,0 +1,46 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputActions.vue b/apps/website/src/components/workshop/playground-output/OutputActions.vue new file mode 100644 index 00000000000..1baba2f7059 --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputActions.vue @@ -0,0 +1,65 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputEarlierRuns.vue b/apps/website/src/components/workshop/playground-output/OutputEarlierRuns.vue new file mode 100644 index 00000000000..51a0227e6a5 --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputEarlierRuns.vue @@ -0,0 +1,71 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputExpandedDialog.vue b/apps/website/src/components/workshop/playground-output/OutputExpandedDialog.vue new file mode 100644 index 00000000000..89de04a2a06 --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputExpandedDialog.vue @@ -0,0 +1,58 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputFailed.vue b/apps/website/src/components/workshop/playground-output/OutputFailed.vue new file mode 100644 index 00000000000..53f77559797 --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputFailed.vue @@ -0,0 +1,72 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputFileTabs.vue b/apps/website/src/components/workshop/playground-output/OutputFileTabs.vue new file mode 100644 index 00000000000..e692fde9859 --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputFileTabs.vue @@ -0,0 +1,51 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputIdle.vue b/apps/website/src/components/workshop/playground-output/OutputIdle.vue new file mode 100644 index 00000000000..29c6931b518 --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputIdle.vue @@ -0,0 +1,25 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputMediaBody.vue b/apps/website/src/components/workshop/playground-output/OutputMediaBody.vue new file mode 100644 index 00000000000..8f51615d4cb --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputMediaBody.vue @@ -0,0 +1,85 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputRunAgain.vue b/apps/website/src/components/workshop/playground-output/OutputRunAgain.vue new file mode 100644 index 00000000000..9f8224cb700 --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputRunAgain.vue @@ -0,0 +1,41 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputRunning.vue b/apps/website/src/components/workshop/playground-output/OutputRunning.vue new file mode 100644 index 00000000000..77b3ebf6939 --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputRunning.vue @@ -0,0 +1,50 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputStage.vue b/apps/website/src/components/workshop/playground-output/OutputStage.vue new file mode 100644 index 00000000000..6ae239fe0b4 --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputStage.vue @@ -0,0 +1,117 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/OutputThumbnails.vue b/apps/website/src/components/workshop/playground-output/OutputThumbnails.vue new file mode 100644 index 00000000000..d62ae13f02f --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/OutputThumbnails.vue @@ -0,0 +1,61 @@ + + + diff --git a/apps/website/src/components/workshop/playground-output/outputClasses.ts b/apps/website/src/components/workshop/playground-output/outputClasses.ts new file mode 100644 index 00000000000..afbf857c29b --- /dev/null +++ b/apps/website/src/components/workshop/playground-output/outputClasses.ts @@ -0,0 +1,12 @@ +import { cn } from '@comfyorg/tailwind-utils' + +export const MEDIA_CONTROL = + 'focus-visible:ring-primary-comfy-yellow/50 grid size-8 cursor-pointer place-items-center rounded-lg bg-primary-comfy-ink/70 text-primary-warm-white backdrop-blur-sm transition-colors outline-none hover:text-primary-comfy-yellow focus-visible:ring-2' + +export const outputStopClass = (active: boolean) => + cn( + 'flex size-12 shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-xl border-2 text-xs text-primary-warm-white transition-opacity', + active + ? 'border-primary-comfy-yellow' + : 'border-transparent opacity-60 hover:opacity-100' + ) diff --git a/apps/website/src/composables/usePagedList.test.ts b/apps/website/src/composables/usePagedList.test.ts new file mode 100644 index 00000000000..ee9e424414c --- /dev/null +++ b/apps/website/src/composables/usePagedList.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { nextTick, ref } from 'vue' + +import { usePagedList } from './usePagedList' + +const numbers = (count: number) => Array.from({ length: count }, (_, i) => i) + +describe('usePagedList', () => { + it('shows a page at a time until every item is out', () => { + const { shown, total, hasMore, showMore } = usePagedList(numbers(5), 2) + + expect(shown.value).toEqual([0, 1]) + expect(total.value).toBe(5) + showMore() + showMore() + expect(shown.value).toEqual(numbers(5)) + expect(hasMore.value).toBe(false) + }) + + it('starts again from the first page when the list itself changes', async () => { + const items = ref(numbers(5)) + const { shown, showMore } = usePagedList(items, 2) + + showMore() + items.value = numbers(6) + await nextTick() + + expect(shown.value).toEqual([0, 1]) + }) +}) diff --git a/apps/website/src/composables/usePagedList.ts b/apps/website/src/composables/usePagedList.ts new file mode 100644 index 00000000000..2c4311d65d3 --- /dev/null +++ b/apps/website/src/composables/usePagedList.ts @@ -0,0 +1,28 @@ +import { computed, ref, toValue, watch } from 'vue' +import type { MaybeRefOrGetter } from 'vue' + +const CATALOGUE_PAGE_SIZE = 12 + +export function usePagedList( + items: MaybeRefOrGetter, + pageSize = CATALOGUE_PAGE_SIZE +) { + const limit = ref(pageSize) + + watch( + () => toValue(items), + () => { + limit.value = pageSize + } + ) + + const shown = computed(() => toValue(items).slice(0, limit.value)) + const total = computed(() => toValue(items).length) + const hasMore = computed(() => total.value > limit.value) + + function showMore() { + limit.value += pageSize + } + + return { limit, shown, total, hasMore, showMore } +} diff --git a/apps/website/src/composables/useWorkshopFormDraft.test.ts b/apps/website/src/composables/useWorkshopFormDraft.test.ts index d3facff5844..846b587d54d 100644 --- a/apps/website/src/composables/useWorkshopFormDraft.test.ts +++ b/apps/website/src/composables/useWorkshopFormDraft.test.ts @@ -1,7 +1,8 @@ import { render, screen, waitFor } from '@testing-library/vue' import { IDBFactory } from 'fake-indexeddb' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { defineComponent, h, ref } from 'vue' +import { defineComponent, h, nextTick, ref } from 'vue' +import type { Ref } from 'vue' import * as storage from '@/config/workshop-draft-storage' import { workshopExampleFile } from '@/config/workshop-example-file' @@ -22,7 +23,7 @@ const schema: FieldSchema[] = [ } ] -function mountDraft() { +function mountDraft(held?: Ref) { const values = ref({ image: workshopExampleFile(original) }) const view = render( defineComponent({ @@ -32,7 +33,8 @@ function mountDraft() { ref(schema), values, ref(false), - false + false, + { held } ) return () => h( @@ -111,4 +113,33 @@ describe('workshop draft restoration', () => { await storage.readWorkshopDraft('token', new AbortController().signal) ).toEqual({ image: saved }) }) + + it('leaves the whole draft for the page that takes over while held', async () => { + sessionStorage.setItem('comfy-workshop-form:draft-test', '{"seed":7}') + const view = mountDraft(ref(true)) + await nextTick() + view.unmount() + + expect(view.values.value.image).toMatchObject({ sourceUrl: original }) + expect(sessionStorage.getItem('comfy-workshop-form:draft-test')).toBe( + '{"seed":7}' + ) + expect(sessionStorage.getItem(mediaKey)).toBe('token') + expect( + await storage.readWorkshopDraft('token', new AbortController().signal) + ).toEqual({ image: saved }) + }) + + it('restores the draft once the hold lifts', async () => { + const held = ref(true) + const view = mountDraft(held) + await nextTick() + expect(view.values.value.image).toMatchObject({ sourceUrl: original }) + + held.value = false + + await waitFor(() => + expect(view.values.value.image).toMatchObject({ sourceUrl: saved }) + ) + }) }) diff --git a/apps/website/src/composables/useWorkshopFormDraft.ts b/apps/website/src/composables/useWorkshopFormDraft.ts index 3be3a3b99d2..c2f11c01044 100644 --- a/apps/website/src/composables/useWorkshopFormDraft.ts +++ b/apps/website/src/composables/useWorkshopFormDraft.ts @@ -1,4 +1,4 @@ -import { useEventListener } from '@vueuse/core' +import { useEventListener, whenever } from '@vueuse/core' import { computed, onMounted, onScopeDispose, ref, watch } from 'vue' import type { Ref } from 'vue' @@ -23,7 +23,10 @@ export function useWorkshopFormDraft( values: Ref, nativeJson: Ref, allowNativeJson: boolean, - { persistFiles = false }: { persistFiles?: boolean } = {} + { + persistFiles = false, + held + }: { persistFiles?: boolean; held?: Readonly> } = {} ) { const key = `comfy-workshop-form:${slug}` const mediaKey = `${key}:media` @@ -33,8 +36,10 @@ export function useWorkshopFormDraft( let saveRevision = 0 const restoreFailed = ref(false) const controller = new AbortController() + let released = !held?.value function persistScalars() { + if (!released) return try { const scalars = Object.fromEntries( Object.entries(values.value) @@ -126,10 +131,15 @@ export function useWorkshopFormDraft( activity.value = 'idle' } } - onMounted(() => { + function startRestoring() { + released = true restoration = restore().finally(() => { restoration = undefined }) + } + onMounted(() => { + if (held?.value) whenever(() => !held.value, startRestoring, { once: true }) + else startRestoring() if (persistFiles) watch( schema.value diff --git a/apps/website/src/config/models-catalogue.ts b/apps/website/src/config/models-catalogue.ts index 4af1fcd7bc7..95244a2c2a0 100644 --- a/apps/website/src/config/models-catalogue.ts +++ b/apps/website/src/config/models-catalogue.ts @@ -4,6 +4,7 @@ import type { WorkshopContract } from './workshop-contract' import type { WorkshopInputDefinition } from './workshop-input-definition' import type { WorkshopWorkflowDefinition } from './workshop-workflow-definition' import { OTHER_FORMAT_USE_CASES } from './workshop-sections' +import type { Resolution } from '@/lib/workshop/resolution' export const MODALITIES = ['image', 'video', 'audio', '3d', 'text'] as const export type Modality = (typeof MODALITIES)[number] @@ -117,6 +118,7 @@ export interface GeneratedModel { } interface WorkshopPresentation { + readonly resolutions?: readonly Resolution[] readonly slug: string readonly name: string readonly workflowCount: number diff --git a/apps/website/src/config/models-page-data.ts b/apps/website/src/config/models-page-data.ts index 210b7ed704f..654cf34aa19 100644 --- a/apps/website/src/config/models-page-data.ts +++ b/apps/website/src/config/models-page-data.ts @@ -37,11 +37,25 @@ const detailSchema = z.union([routerDetailSchema, workflowDetailSchema]) const tagSchema = z.object({ label: z.string(), search: z.string() }) +const providerModelSchema = z.object({ + slug: z.string(), + name: z.string(), + href: z.string(), + provider: z.string(), + price: z.string().optional(), + resolution: z.string().optional(), + duration: z.object({ min: z.number().optional(), max: z.number() }).optional() +}) + +export type ProviderModelRow = z.output + const modelsPageDataSchema = z.object({ kind: z.literal('page'), model: detailSchema, related: z.array(modelSchema), relatedHeading: z.string(), + providerModels: z.array(providerModelSchema).default([]), + workflows: z.array(workflowModelSchema).default([]), successor: modelSchema.optional(), priceEstimate: z.string().optional(), useCaseLabel: z.string().optional(), diff --git a/apps/website/src/config/workflow-render.ts b/apps/website/src/config/workflow-render.ts index 63b90d1c750..ea598b532dd 100644 --- a/apps/website/src/config/workflow-render.ts +++ b/apps/website/src/config/workflow-render.ts @@ -113,6 +113,17 @@ async function uploadInput( return uploadFile(source, signal) } +export function workflowRunsHere( + model: Pick< + WorkflowWorkshopModelDetail, + 'type' | 'incompleteReason' | 'workflow' + > +): boolean { + return ( + model.type === 'CLOUD' && !model.incompleteReason && !!model.workflow.cloud + ) +} + export async function prepareWorkflowRender( model: WorkflowWorkshopModelDetail, inputs: FormValues, diff --git a/apps/website/src/lib/workshop/apps-half.ts b/apps/website/src/lib/workshop/apps-half.ts new file mode 100644 index 00000000000..1d421477c64 --- /dev/null +++ b/apps/website/src/lib/workshop/apps-half.ts @@ -0,0 +1,5 @@ +import { memoize } from 'es-toolkit' + +export const loadAppsHalf = memoize( + () => import('@/components/workshop/AppsHalf.vue') +) diff --git a/apps/website/src/lib/workshop/catalogue-components.ts b/apps/website/src/lib/workshop/catalogue-components.ts index e141894d1ca..f19fa77331a 100644 --- a/apps/website/src/lib/workshop/catalogue-components.ts +++ b/apps/website/src/lib/workshop/catalogue-components.ts @@ -6,3 +6,6 @@ export const loadWorkflowCatalogue = memoize( export const loadAppCatalogue = memoize( () => import('@/components/workshop/AppCatalogue.vue') ) +export const loadHubAppCatalogue = memoize( + () => import('@/components/workshop/HubAppCatalogue.vue') +) diff --git a/apps/website/src/lib/workshop/explorer/model-access.ts b/apps/website/src/lib/workshop/explorer/model-access.ts new file mode 100644 index 00000000000..e7e39d2fbe0 --- /dev/null +++ b/apps/website/src/lib/workshop/explorer/model-access.ts @@ -0,0 +1,11 @@ +import type { + WorkshopModel, + WorkshopModelDetail +} from '@/config/models-catalogue' + +/** Whether a visitor can start a run of this model from its Hub page. */ +export function runsHere(model: WorkshopModel | WorkshopModelDetail): boolean { + if (model.routerId === undefined || model.incompleteReason) return false + if (import.meta.env.PUBLIC_WORKSHOP_ROUTER_RUN !== '1') return false + return !('examples' in model) || !!model.execution +} diff --git a/apps/website/src/lib/workshop/hub-catalogue-apps.ts b/apps/website/src/lib/workshop/hub-catalogue-apps.ts new file mode 100644 index 00000000000..3c58605cb02 --- /dev/null +++ b/apps/website/src/lib/workshop/hub-catalogue-apps.ts @@ -0,0 +1,88 @@ +import type { Locale, LocalizedText, TranslationKey } from '@/i18n/translations' +import { translationsFor } from '@/i18n/translations' + +import type { CatalogueApp } from './catalogue-apps' + +/** + * Copy for the Apps half only. It ships with that half's lazy chunk rather + * than the site-wide translations every page loads. + */ +const copy = { + apps: { en: 'Apps', 'zh-CN': '应用' }, + studioTask: { + en: 'Direct every shot. Pick the camera, lens, light and grade.', + 'zh-CN': '执导每一个镜头。选择摄影机、镜头、光线和调色。' + }, + reshootTask: { + en: 'Upload a shot and re-frame it from a new camera angle.', + 'zh-CN': '上传一个镜头,从新的机位角度重新取景。' + }, + moveAnythingName: { en: 'Move anything', 'zh-CN': '随意移动' }, + moveAnythingTask: { + en: 'Drag an object in a still and get a clip where it moves.', + 'zh-CN': '在静态图中拖动物体,生成它移动起来的片段。' + }, + relightName: { en: 'Relight', 'zh-CN': '重新布光' }, + relightTask: { + en: 'Point the light where you want it.', + 'zh-CN': '把光打到你想要的地方。' + }, + handProductSwapName: { en: 'Hand product swap', 'zh-CN': '手持产品替换' }, + handProductSwapTask: { + en: 'Put a product in a hand', + 'zh-CN': '把产品放到手中' + }, + backgroundRemovalName: { en: 'Background Removal', 'zh-CN': '背景移除' }, + backgroundRemovalTask: { + en: 'Clean cut-outs for products and people in one click.', + 'zh-CN': '一键为产品和人物干净抠图。' + }, + virtualTryOnName: { en: 'Virtual try-on', 'zh-CN': '虚拟试穿' }, + virtualTryOnTask: { + en: 'Put any garment on any model photo.', + 'zh-CN': '把任意服装穿到任意模特照片上。' + }, + spriteSheetName: { en: 'Sprite Sheet Generator', 'zh-CN': '精灵图生成器' }, + spriteSheetTask: { + en: 'Animate a character for a game', + 'zh-CN': '为游戏制作角色动画' + }, + paparazziMeName: { en: 'Paparazzi me', 'zh-CN': '狗仔偶遇' }, + paparazziMeTask: { + en: 'Get snapped next to a star', + 'zh-CN': '和明星同框被拍' + } +} as const satisfies Record + +export function ac(key: keyof typeof copy, locale: Locale = 'en'): string { + return copy[key][locale === 'zh-CN' ? locale : 'en'] +} + +/** A card on the Hub's app grid. An app still being built has no `href`. */ +export interface HubCatalogueApp extends Omit { + readonly href?: string +} + +const OPEN_APPS = new Map< + string, + { task: 'studioTask' | 'reshootTask'; meta: TranslationKey } +>([ + [ + 'apps/cinematic-studio', + { task: 'studioTask', meta: 'cinematic.hub.studioMeta' } + ], + ['apps/reshoot', { task: 'reshootTask', meta: 'cinematic.hub.reshootMeta' }] +]) + +/** An open app in the Hub's words: its summary and what it makes and runs on. */ +export function hubOpenApp( + app: CatalogueApp, + locale: Locale = 'en' +): { app: HubCatalogueApp; meta?: string } { + const words = OPEN_APPS.get(app.key) + if (!words) return { app } + return { + app: { ...app, task: ac(words.task, locale) }, + meta: translationsFor(locale).t(words.meta) + } +} diff --git a/apps/website/src/lib/workshop/hub-coming-soon-apps.ts b/apps/website/src/lib/workshop/hub-coming-soon-apps.ts new file mode 100644 index 00000000000..c350e92c0d6 --- /dev/null +++ b/apps/website/src/lib/workshop/hub-coming-soon-apps.ts @@ -0,0 +1,35 @@ +import type { Locale } from '@/i18n/translations' +import type { HubCatalogueApp } from './hub-catalogue-apps' +import { ac } from './hub-catalogue-apps' + +const UPCOMING = [ + ['move-anything', 'moveAnything', '/images/apps/move-anything/example.jpg'], + ['relight', 'relight', '/images/apps/relight/example.jpg'], + [ + 'hand-product-swap', + 'handProductSwap', + '/images/apps/hand-product-swap/result-can.jpg' + ], + [ + 'background-removal', + 'backgroundRemoval', + '/images/apps/background-removal/example.jpg' + ], + ['virtual-try-on', 'virtualTryOn', '/images/apps/virtual-try-on/person.jpg'], + ['sprite-sheet', 'spriteSheet', '/images/apps/sprite-sheet/example.png'], + [ + 'paparazzi-me', + 'paparazziMe', + '/images/apps/paparazzi-me/example-result.jpg' + ] +] as const + +/** Apps still being built, listed without a page of their own yet. */ +export function upcomingApps(locale: Locale): readonly HubCatalogueApp[] { + return UPCOMING.map(([key, copy, url]) => ({ + key, + name: ac(`${copy}Name`, locale), + task: ac(`${copy}Task`, locale), + thumbnail: { url, kind: 'image' } + })) +} diff --git a/apps/website/src/lib/workshop/hub-list-memory.test.ts b/apps/website/src/lib/workshop/hub-list-memory.test.ts new file mode 100644 index 00000000000..39943e0c9f1 --- /dev/null +++ b/apps/website/src/lib/workshop/hub-list-memory.test.ts @@ -0,0 +1,56 @@ +import { beforeEach, describe, expect, it } from 'vitest' + +import { lastList } from './hub-list-memory' + +const KEY = 'comfy-hub-list' +const MODEL = '/hub/models/seedream-4-5/' + +const remember = (value: unknown) => + sessionStorage.setItem(KEY, JSON.stringify(value)) + +beforeEach(() => { + sessionStorage.clear() +}) + +describe('lastList', () => { + it('returns the list a model was opened from, once', () => { + remember({ href: '/hub/models/?q=video', label: 'Video', modelPath: MODEL }) + + expect(lastList(MODEL)).toEqual({ + href: '/hub/models/?q=video', + label: 'Video' + }) + expect(lastList(MODEL)).toBeUndefined() + }) + + it('forgets a list remembered for another model page', () => { + remember({ href: '/hub/models/', modelPath: '/hub/models/other/' }) + + expect(lastList(MODEL)).toBeUndefined() + expect(sessionStorage.getItem(KEY)).toBeNull() + }) + + it.for([ + ['malformed JSON', '{not json'], + [ + 'a list on another site', + JSON.stringify({ href: '//evil.com/', modelPath: MODEL }) + ], + [ + 'a backslash route to another site', + JSON.stringify({ href: '/\\evil.com', modelPath: MODEL }) + ], + [ + 'an absolute address', + JSON.stringify({ href: 'https://evil.com/', modelPath: MODEL }) + ], + [ + 'a label that is not text', + JSON.stringify({ href: '/hub/models/', label: 3, modelPath: MODEL }) + ] + ])('ignores %s', ([, stored]) => { + sessionStorage.setItem(KEY, stored) + + expect(lastList(MODEL)).toBeUndefined() + }) +}) diff --git a/apps/website/src/lib/workshop/hub-list-memory.ts b/apps/website/src/lib/workshop/hub-list-memory.ts new file mode 100644 index 00000000000..42064402559 --- /dev/null +++ b/apps/website/src/lib/workshop/hub-list-memory.ts @@ -0,0 +1,48 @@ +const KEY = 'comfy-hub-list' + +/** The list a model was opened from, for the way back to it. */ +export interface ListReturn { + readonly href: string + readonly label?: string +} + +interface StoredReturn extends ListReturn { + readonly modelPath: string +} + +/** The list remembered for this model page, consumed so it serves one navigation. */ +export function lastList(modelPath: string): ListReturn | undefined { + try { + const stored = sessionStorage.getItem(KEY) + sessionStorage.removeItem(KEY) + if (!stored) return undefined + const parsed: unknown = JSON.parse(stored) + if (!isStoredReturn(parsed) || parsed.modelPath !== modelPath) + return undefined + return parsed.label === undefined + ? { href: parsed.href } + : { href: parsed.href, label: parsed.label } + } catch { + return undefined + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +function isSameSitePath(href: unknown): href is string { + return ( + typeof href === 'string' && href.startsWith('/') && !/^\/[\\/]/.test(href) + ) +} + +function isStoredReturn(value: unknown): value is StoredReturn { + if (!isRecord(value)) return false + const { href, label, modelPath } = value + return ( + isSameSitePath(href) && + typeof modelPath === 'string' && + (label === undefined || typeof label === 'string') + ) +} diff --git a/apps/website/src/lib/workshop/live-page-hold.ts b/apps/website/src/lib/workshop/live-page-hold.ts new file mode 100644 index 00000000000..b018655fc5d --- /dev/null +++ b/apps/website/src/lib/workshop/live-page-hold.ts @@ -0,0 +1,5 @@ +import type { InjectionKey, Ref } from 'vue' + +/** True while the published model page waits on the Hub page choice. */ +export const LIVE_PAGE_HELD: InjectionKey>> = + Symbol('live-page-held') diff --git a/apps/website/src/lib/workshop/model-ranges.test.ts b/apps/website/src/lib/workshop/model-ranges.test.ts new file mode 100644 index 00000000000..400e998c2cc --- /dev/null +++ b/apps/website/src/lib/workshop/model-ranges.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' + +import { durationsIn, resolutionRange } from './model-ranges' + +describe('resolutionRange', () => { + it.for([ + { resolutions: [], range: undefined }, + { resolutions: ['1080p'], range: '1080p' }, + { resolutions: ['4K', '1080p', '480p'], range: '480p – 4K' } + ] as const)('reads $resolutions as $range', ({ resolutions, range }) => { + expect(resolutionRange(resolutions)).toBe(range) + }) +}) + +describe('durationsIn', () => { + it.for([ + { + label: 'an enum of lengths', + schema: { properties: { duration: { enum: ['5s', '10s'] } } }, + range: { min: 5, max: 10 } + }, + { + label: 'a minimum and maximum', + schema: { properties: { duration: { minimum: 2, maximum: 12 } } }, + range: { min: 2, max: 12 } + }, + { + label: 'only a ceiling', + schema: { properties: { duration: { maximum: 8 } } }, + range: { max: 8 } + }, + { + label: 'a sentinel for letting the model choose', + schema: { properties: { duration: { enum: [-1, 4, 6] } } }, + range: { min: 4, max: 6 } + }, + { + label: 'a duration nested in a variant', + schema: { anyOf: [{ properties: { duration: { enum: [3] } } }] }, + range: { min: 3, max: 3 } + }, + { + label: 'a schema with no duration', + schema: { properties: { prompt: { type: 'string' } } }, + range: undefined + }, + { label: 'no schema', schema: undefined, range: undefined } + ])('reads $label', ({ schema, range }) => { + expect(durationsIn(schema)).toEqual(range) + }) +}) diff --git a/apps/website/src/lib/workshop/model-ranges.ts b/apps/website/src/lib/workshop/model-ranges.ts new file mode 100644 index 00000000000..3c57fd76f82 --- /dev/null +++ b/apps/website/src/lib/workshop/model-ranges.ts @@ -0,0 +1,74 @@ +import type { Resolution } from './resolution' + +/** Seconds a model can generate; `min` is absent when only the ceiling is known. */ +export interface DurationRange { + readonly min?: number + readonly max: number +} + +/** "480p – 4K" from resolutions listed highest first, or the single one. */ +export function resolutionRange( + resolutions: readonly Resolution[] = [] +): string | undefined { + const highest = resolutions.at(0) + const lowest = resolutions.at(-1) + if (!highest || !lowest) return undefined + return highest === lowest ? highest : `${lowest} – ${highest}` +} + +const SECONDS = /^(\d+(?:\.\d+)?)s?$/ + +function positiveSeconds(value: unknown): number[] { + const parsed = + typeof value === 'number' + ? value + : typeof value === 'string' + ? Number(SECONDS.exec(value.trim())?.[1]) + : Number.NaN + return Number.isFinite(parsed) && parsed > 0 ? [parsed] : [] +} + +interface Bounds { + readonly lower: number[] + readonly upper: number[] +} + +function boundsOf(node: unknown): Bounds { + if (!node || typeof node !== 'object') return { lower: [], upper: [] } + const children = Array.isArray(node) ? node : Object.values(node) + const nested = children.map(boundsOf) + const listed = + 'enum' in node && Array.isArray(node.enum) + ? node.enum.flatMap(positiveSeconds) + : [] + const minimum = 'minimum' in node ? positiveSeconds(node.minimum) : [] + const maximum = 'maximum' in node ? positiveSeconds(node.maximum) : [] + return { + lower: [...listed, ...minimum, ...nested.flatMap((bound) => bound.lower)], + upper: [...listed, ...maximum, ...nested.flatMap((bound) => bound.upper)] + } +} + +function durationNodes(node: unknown): unknown[] { + if (!node || typeof node !== 'object') return [] + const entries = Array.isArray(node) + ? node.map((child): [string, unknown] => ['', child]) + : Object.entries(node) + return entries.flatMap(([key, child]) => + key === 'duration' ? [child] : durationNodes(child) + ) +} + +/** + * The clip lengths a Router input schema offers for `duration`, from its + * enum, minimum and maximum. Sentinels such as -1 (let the model choose) are + * not lengths and are left out. + */ +export function durationsIn(schema: unknown): DurationRange | undefined { + const bounds = durationNodes(schema).map(boundsOf) + const lower = bounds.flatMap((bound) => bound.lower) + const upper = bounds.flatMap((bound) => bound.upper) + if (!upper.length) return undefined + const max = Math.max(...upper) + return lower.length ? { min: Math.min(...lower), max } : { max } +} diff --git a/apps/website/src/lib/workshop/model-workflows.test.ts b/apps/website/src/lib/workshop/model-workflows.test.ts new file mode 100644 index 00000000000..1c7a4c9fc3d --- /dev/null +++ b/apps/website/src/lib/workshop/model-workflows.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' + +import type { WorkflowWorkshopModel } from '@/config/models-catalogue' +import { workflowsUsingModel } from './model-workflows' + +const workflow = (models: string[]): WorkflowWorkshopModel => ({ + slug: `workflows/${models.join('-')}`, + name: `Uses ${models.join(', ')}`, + href: `/hub/workflows/${models.join('-')}/`, + type: 'CLOUD', + workflowId: models.join('-'), + workflowCount: 1, + capabilities: [], + models +}) + +describe('workflowsUsingModel', () => { + it.for([ + { model: 'Seedream 4.5', used: 'Seedream 4.5', listed: true }, + { model: 'Flux 1 Dev', used: 'Flux 1', listed: true }, + { model: 'Kling Video 2.1', used: 'kling video', listed: true }, + { model: 'Seedream 4.5', used: 'Seedream 4', listed: false }, + { model: 'Wan 2.2', used: 'Wan 2', listed: false }, + { model: 'Seedream 4.5', used: 'Seedream', listed: false } + ])( + 'a workflow naming "$used" lists on $model: $listed', + ({ model, used, listed }) => { + const pages = [workflow([used])] + + expect(workflowsUsingModel({ name: model }, pages)).toEqual( + listed ? pages : [] + ) + } + ) + + it('lists only workflows, never models that share the name', () => { + const router = { + slug: 'seedream-4-5', + name: 'Seedream 4.5', + routerId: 'bytedance/seedream-4.5', + workflowCount: 0, + capabilities: [] + } + + expect(workflowsUsingModel({ name: 'Seedream 4.5' }, [router])).toEqual([]) + }) +}) diff --git a/apps/website/src/lib/workshop/model-workflows.ts b/apps/website/src/lib/workshop/model-workflows.ts new file mode 100644 index 00000000000..5a48aef9630 --- /dev/null +++ b/apps/website/src/lib/workshop/model-workflows.ts @@ -0,0 +1,40 @@ +import type { + WorkflowWorkshopModel, + WorkshopModel +} from '@/config/models-catalogue' + +const comparable = (name: string) => + name + .toLowerCase() + .replaceAll(/[^a-z0-9]+/g, ' ') + .trim() + +// A workflow names its models as people say them. A bare brand ("Seedream", +// "Flux") would claim every release under it, so only a name that picks out a +// release, with a version or more than one word, is read as this model. +const namesARelease = (name: string) => /\d/.test(name) || name.includes(' ') + +const continuesTheVersion = (release: string, rest: string) => + /\d$/.test(release) && /^\d/.test(rest) + +const namesAVariantOf = (name: string, release: string) => + name.startsWith(`${release} `) && + !continuesTheVersion(release, name.slice(release.length + 1)) + +export function workflowsUsingModel( + model: Pick, + pages: readonly WorkshopModel[] +): WorkflowWorkshopModel[] { + const name = comparable(model.name) + return pages.filter( + (page): page is WorkflowWorkshopModel => + page.workflowId !== undefined && + (page.models ?? []).some((used) => { + const release = comparable(used) + return ( + namesARelease(release) && + (name === release || namesAVariantOf(name, release)) + ) + }) + ) +} diff --git a/apps/website/src/lib/workshop/page-paths.test.ts b/apps/website/src/lib/workshop/page-paths.test.ts new file mode 100644 index 00000000000..78f5b82ce58 --- /dev/null +++ b/apps/website/src/lib/workshop/page-paths.test.ts @@ -0,0 +1,74 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { + WorkflowWorkshopModelDetail, + WorkshopModelDetail +} from '@/config/models-catalogue' +import { + getWorkshopPageDetail, + workshopPages +} from '@/config/workshop-page-content' +import { pagePaths } from './page-paths' + +const details = workshopPages + .map((page) => getWorkshopPageDetail(page.slug)) + .filter((detail): detail is WorkshopModelDetail => detail !== undefined) + +function firstDetail( + matches: (detail: WorkshopModelDetail) => detail is Detail +): Detail +function firstDetail( + matches: (detail: WorkshopModelDetail) => boolean +): WorkshopModelDetail +function firstDetail(matches: (detail: WorkshopModelDetail) => boolean) { + const detail = details.find(matches) + if (!detail) throw new Error('The catalogue has no such page') + return detail +} + +beforeEach(() => { + vi.stubEnv('PUBLIC_WORKSHOP_ROUTER_RUN', '1') +}) + +describe('pagePaths', () => { + it('runs a complete model here and offers its API from its contract', () => { + const model = firstDetail( + (detail) => + detail.routerId !== undefined && + !detail.incompleteReason && + detail.execution !== undefined + ) + + expect(pagePaths(model)).toEqual({ run: true, api: true }) + expect(pagePaths({ ...model, execution: undefined })).toEqual({ + run: false, + api: false + }) + }) + + it('never runs a model that is not complete', () => { + const model = firstDetail((detail) => detail.routerId !== undefined) + + expect( + pagePaths({ ...model, incompleteReason: 'missing-input-schema' }).run + ).toBe(false) + }) + + it('runs a workflow here, API included, only when it runs on Cloud', () => { + const workflow = firstDetail( + (detail): detail is WorkflowWorkshopModelDetail => + detail.routerId === undefined && + detail.type === 'CLOUD' && + !detail.incompleteReason && + !!detail.workflow.cloud + ) + + expect(pagePaths(workflow)).toEqual({ run: true, api: true }) + expect( + pagePaths({ + ...workflow, + workflow: { ...workflow.workflow, cloud: undefined } + }) + ).toEqual({ run: false, api: false }) + }) +}) diff --git a/apps/website/src/lib/workshop/page-paths.ts b/apps/website/src/lib/workshop/page-paths.ts new file mode 100644 index 00000000000..31fa6d3c66f --- /dev/null +++ b/apps/website/src/lib/workshop/page-paths.ts @@ -0,0 +1,17 @@ +import type { WorkshopModelDetail } from '@/config/models-catalogue' +import { workflowRunsHere } from '@/config/workflow-render' +import { runsHere } from '@/lib/workshop/explorer/model-access' + +/** The ways a model or workflow page can really be used from the Hub. */ +export interface PagePaths { + readonly run: boolean + readonly api: boolean +} + +export function pagePaths(model: WorkshopModelDetail): PagePaths { + if (model.routerId === undefined) { + const runs = workflowRunsHere(model) + return { run: runs, api: runs } + } + return { run: runsHere(model), api: !!model.execution } +} diff --git a/apps/website/src/lib/workshop/resolution.ts b/apps/website/src/lib/workshop/resolution.ts new file mode 100644 index 00000000000..6e2e3684df9 --- /dev/null +++ b/apps/website/src/lib/workshop/resolution.ts @@ -0,0 +1,12 @@ +const RESOLUTIONS = [ + '4K', + '3K', + '2K', + '1.5K', + '1080p', + '1K', + '720p', + '540p', + '480p' +] as const +export type Resolution = (typeof RESOLUTIONS)[number] diff --git a/apps/website/src/lib/workshop/run-gate.test.ts b/apps/website/src/lib/workshop/run-gate.test.ts new file mode 100644 index 00000000000..2bae49defb3 --- /dev/null +++ b/apps/website/src/lib/workshop/run-gate.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' + +import type { RunGate, RunGateInput } from './run-gate' +import { runGateFor } from './run-gate' + +const ready: RunGateInput = { + canRun: true, + mounted: true, + workshopEnabled: true, + workshopSettled: true, + draftPending: false, + authAvailable: true, + sessionSettled: true, + role: 'owner', + credits: 10 +} + +describe('runGateFor', () => { + it.for<[string, Partial, RunGate]>([ + ['a model the page cannot run', { canRun: false }, 'unavailable'], + ['before the page has mounted', { mounted: false }, 'resolving'], + [ + 'while the rollout flag is still answering', + { workshopEnabled: false, workshopSettled: false }, + 'resolving' + ], + [ + 'once the rollout flag has answered no', + { workshopEnabled: false }, + 'rollingOut' + ], + ['while a saved draft is restoring', { draftPending: true }, 'pending'], + ['when sign-in is unavailable', { authAvailable: false }, 'unavailable'], + [ + 'while the session is still minting', + { sessionSettled: false }, + 'pending' + ], + ['to a signed-out visitor', { role: undefined }, 'signedOut'], + ['to an owner with an empty balance', { credits: 0 }, 'noCredits'], + [ + 'to a member with an empty balance', + { role: 'member', credits: 0 }, + 'memberNoCredits' + ], + ['while the balance is unknown', { credits: undefined }, 'ready'], + ['to an owner with credits', {}, 'ready'] + ])('offers %s', ([, change, gate]) => { + expect(runGateFor({ ...ready, ...change })).toBe(gate) + }) +}) diff --git a/apps/website/src/lib/workshop/run-gate.ts b/apps/website/src/lib/workshop/run-gate.ts new file mode 100644 index 00000000000..adcff3f6c2a --- /dev/null +++ b/apps/website/src/lib/workshop/run-gate.ts @@ -0,0 +1,34 @@ +import type { StudioGate, StudioGateInput } from './cinematic-studio/gate' +import { studioGate } from './cinematic-studio/gate' + +export type RunGate = StudioGate | 'resolving' | 'rollingOut' + +export interface RunGateInput { + readonly canRun: boolean + readonly mounted: boolean + readonly workshopEnabled: boolean + readonly workshopSettled: boolean + readonly draftPending: boolean + readonly authAvailable: boolean + readonly sessionSettled: boolean + readonly role: StudioGateInput['role'] + readonly credits: StudioGateInput['credits'] +} + +/** What a model page's Run control offers, given where the visitor stands. */ +export function runGateFor(input: RunGateInput): RunGate { + if (!input.canRun) return 'unavailable' + if (!input.mounted) return 'resolving' + if (!input.workshopEnabled) + return input.workshopSettled ? 'rollingOut' : 'resolving' + if (input.draftPending) return 'pending' + return studioGate({ + runEnabled: true, + modelRunnable: true, + mounted: true, + authAvailable: input.authAvailable, + sessionSettled: input.sessionSettled, + role: input.role, + credits: input.credits + }) +} diff --git a/apps/website/src/lib/workshop/scroll-to-section.ts b/apps/website/src/lib/workshop/scroll-to-section.ts new file mode 100644 index 00000000000..63536d87482 --- /dev/null +++ b/apps/website/src/lib/workshop/scroll-to-section.ts @@ -0,0 +1,9 @@ +export function scrollToSection(id: string): void { + const reduceMotion = window.matchMedia( + '(prefers-reduced-motion: reduce)' + ).matches + document.getElementById(id)?.scrollIntoView({ + behavior: reduceMotion ? 'auto' : 'smooth', + block: 'start' + }) +} diff --git a/apps/website/src/locales/en/main.json b/apps/website/src/locales/en/main.json index a0ff5557cef..63267ce15f5 100644 --- a/apps/website/src/locales/en/main.json +++ b/apps/website/src/locales/en/main.json @@ -2566,6 +2566,13 @@ } } }, + "hubPages": { + "apps": { + "open": "Open", + "soon": "Soon", + "opensInNewTab": "(opens in a new tab)" + } + }, "hubspotForm": { "embedLoadErrorPrefix": "Unable to load the form. Email us at", "embedLoadErrorSuffix": "and we'll route your request." @@ -5431,25 +5438,10 @@ "subtitle": "What will you make next? Try the latest AI models with your own ideas, right in your browser." }, "hub": { - "title": "Browse models", - "workflows": "Workflows", - "search": "Search workflows, models, creators...", - "kind": { - "all": "All", - "graph": "Graphs", - "app": "Apps", - "models": "Models" - }, - "io": { - "image": "Image", - "video": "Video", - "audio": "Audio", - "3d": "3D" - }, - "sort": { - "popular": "Most Popular", - "newest": "Newest" - }, + "categories": "CATEGORIES", + "docs": "Read docs", + "empty": "No workflows match your filters", + "emptyHint": "Try removing some filters", "facets": { "clearAll": "Clear all", "search": "Search…", @@ -5462,17 +5454,34 @@ "show": "Show {n} workflows", "noResults": "No matches" }, + "io": { + "image": "Image", + "video": "Video", + "audio": "Audio", + "3d": "3D" + }, + "kind": { + "all": "All", + "graph": "Graphs", + "app": "Apps", + "models": "Models" + }, + "loadMore": "Load more", "models": "Models", - "categories": "CATEGORIES", - "docs": "Read docs", - "tryNow": "Try now", + "search": "Search workflows, models, creators...", + "showMore": "Show more", + "showing": "Showing {shown} of {total} workflows", + "showingOf": "Showing {shown} of {total}", + "sort": { + "popular": "Most Popular", + "newest": "Newest" + }, "tag": { "partnerNodes": "Partner Nodes" }, - "loadMore": "Load more", - "empty": "No workflows match your filters", - "emptyHint": "Try removing some filters", - "showing": "Showing {shown} of {total} workflows" + "title": "Browse models", + "tryNow": "Try now", + "workflows": "Workflows" }, "input": { "title": "Input" @@ -5536,7 +5545,23 @@ "priceNoteLabel": "How this price is estimated", "incomplete": "Incomplete", "notSupported": "Run not yet supported", - "missingInputSchema": "We do not know this model's inputs yet, so it cannot be run or called from code. Everything else on this page still works." + "missingInputSchema": "We do not know this model's inputs yet, so it cannot be run or called from code. Everything else on this page still works.", + "providerTable": { + "subtitle": "Compare {provider}'s other models. Price is the default setting; resolution and duration show the full range each model offers.", + "model": "Model", + "price": "Price", + "resolution": "Resolution", + "duration": "Duration", + "durationRange": "{min} – {max}s", + "durationOne": "{n}s", + "durationUpTo": "up to {max}s" + }, + "paths": { + "label": "Ways to use this model", + "cloud": "Open in Cloud", + "api": "Use via API" + }, + "usedBy": "Workflows that use {name}" }, "models": { "heading": "Models" @@ -5841,7 +5866,8 @@ "lostContact": "This page lost contact with the run. It may still be running on Cloud and using credits. Reconnect to see its current status.", "browserUnavailable": "Running workflows from this page is not available yet.", "tryCloud": "Try in Cloud", - "explore": "Explore the possibilities" + "explore": "Explore the possibilities", + "opensInNewTab": "(opens in a new tab)" } } } diff --git a/apps/website/src/locales/zh-CN/main.json b/apps/website/src/locales/zh-CN/main.json index e300341d057..c47d394cae1 100644 --- a/apps/website/src/locales/zh-CN/main.json +++ b/apps/website/src/locales/zh-CN/main.json @@ -2253,6 +2253,13 @@ } } }, + "hubPages": { + "apps": { + "open": "可用", + "soon": "即将推出", + "opensInNewTab": "(在新标签页中打开)" + } + }, "hubspotForm": { "embedLoadErrorPrefix": "表单无法加载。请发送邮件至", "embedLoadErrorSuffix": "我们会为您处理请求。" @@ -4855,7 +4862,9 @@ "loadMore": "加载更多", "models": "模型", "search": "搜索工作流、模型、创作者...", + "showMore": "显示更多", "showing": "显示 {shown} / {total} 个工作流", + "showingOf": "已显示 {shown} / {total}", "sort": { "newest": "最新", "popular": "最受欢迎" @@ -4929,7 +4938,23 @@ "playground": "Playground" }, "variablePrice": "费用取决于模型和设置。", - "versions": "{n} 个版本" + "versions": "{n} 个版本", + "providerTable": { + "subtitle": "比较 {provider} 的其他模型。价格为默认设置下的价格;分辨率和时长显示每个模型提供的完整范围。", + "model": "模型", + "price": "价格", + "resolution": "分辨率", + "duration": "时长", + "durationRange": "{min} – {max} 秒", + "durationOne": "{n} 秒", + "durationUpTo": "最长 {max} 秒" + }, + "paths": { + "label": "使用此模型的方式", + "cloud": "在 Cloud 中打开", + "api": "通过 API 使用" + }, + "usedBy": "使用 {name} 的工作流" }, "models": { "heading": "模型" @@ -5234,7 +5259,8 @@ "tryCloud": "在 Cloud 中试用", "zoomIn": "放大", "zoomOut": "缩小", - "zoomReset": "重置" + "zoomReset": "重置", + "opensInNewTab": "(在新标签页中打开)" } } } diff --git a/apps/website/src/routes/models/[slug].astro b/apps/website/src/routes/models/[slug].astro index 18f44d8a42d..9934b59a4f1 100644 --- a/apps/website/src/routes/models/[slug].astro +++ b/apps/website/src/routes/models/[slug].astro @@ -1,7 +1,7 @@ --- import type { GetStaticPaths } from 'astro' import BaseLayout from '@/layouts/BaseLayout.astro' -import ModelPage from '@/components/workshop/ModelPage.vue' +import ModelPageSwitch from '@/components/workshop/ModelPageSwitch.vue' import ModelsPage from '@/components/workshop/ModelsPage.vue' import ModelsShowcase from '@/components/models/ModelsShowcase.astro' import { @@ -74,7 +74,7 @@ const ogImage = modelOgImage(model) ) : ( - diff --git a/apps/website/src/routes/models/model-page.test.ts b/apps/website/src/routes/models/model-page.test.ts index a599b8ea1a8..5616a067146 100644 --- a/apps/website/src/routes/models/model-page.test.ts +++ b/apps/website/src/routes/models/model-page.test.ts @@ -1,17 +1,22 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { WorkshopModelDetail } from '@/config/models-catalogue' +import type { + RouterWorkshopModel, + WorkflowWorkshopModel, + WorkshopModelDetail +} from '@/config/models-catalogue' import { prepareModelPage } from './model-page' const mocks = vi.hoisted(() => ({ lookup: vi.fn(), related: vi.fn(), successor: vi.fn(), - price: vi.fn() + price: vi.fn(), + pages: [] as (RouterWorkshopModel | WorkflowWorkshopModel)[] })) vi.mock(import('@/config/workshop-page-content'), () => ({ getWorkshopPageDetail: mocks.lookup, - workshopPages: [] + workshopPages: mocks.pages })) vi.mock(import('@/config/workshop-related'), () => ({ relatedModels: mocks.related @@ -39,6 +44,7 @@ const model: WorkshopModelDetail = { } beforeEach(() => { + mocks.pages.length = 0 mocks.lookup.mockReturnValue(model) mocks.related.mockReturnValue([]) mocks.price.mockResolvedValue(undefined) @@ -171,4 +177,71 @@ describe('Models route preparation', () => { 'Unknown Models route: (missing)' ) }) + + describe('the Hub rows', () => { + const sibling: RouterWorkshopModel = { + slug: 'provider--sibling', + name: 'Sibling Model', + href: '/models/provider--sibling/', + routerId: 'provider/sibling', + workflowCount: 0, + provider: 'Example Provider', + capabilities: [], + resolutions: ['1080p', '720p'] + } + const stranger: RouterWorkshopModel = { + ...sibling, + slug: 'other--model', + routerId: 'other/model', + provider: 'Other Provider' + } + const usingWorkflow: WorkflowWorkshopModel = { + slug: 'workflows/example', + name: 'Example workflow', + href: '/hub/workflows/example/', + type: 'CLOUD', + workflowId: 'example', + workflowCount: 1, + capabilities: [], + models: ['Example Model'] + } + + it('lists the provider’s other models and the workflows that use this one', async () => { + mocks.pages.push(model, sibling, stranger, usingWorkflow) + mocks.price.mockResolvedValue('$0.04') + + const page = await prepareModelPage(model.slug) + + if (page.kind !== 'page') throw new Error('Expected canonical page') + expect(page.providerModels).toEqual([ + { + slug: 'provider--sibling', + name: 'Sibling Model', + href: '/models/provider--sibling/', + provider: 'Example Provider', + price: '$0.04', + resolution: '720p – 1080p' + } + ]) + expect(page.workflows).toEqual([usingWorkflow]) + }) + + it('builds neither row for a workflow page', async () => { + mocks.pages.push(sibling, usingWorkflow) + mocks.lookup.mockReturnValue({ + ...usingWorkflow, + provider: 'Example Provider', + fields: [], + examples: [], + defaults: {}, + workflow: {} + }) + + const page = await prepareModelPage(usingWorkflow.slug) + + if (page.kind !== 'page') throw new Error('Expected canonical page') + expect(page.providerModels).toEqual([]) + expect(page.workflows).toEqual([]) + }) + }) }) diff --git a/apps/website/src/routes/models/model-page.ts b/apps/website/src/routes/models/model-page.ts index 9e85bb8060f..32c51495297 100644 --- a/apps/website/src/routes/models/model-page.ts +++ b/apps/website/src/routes/models/model-page.ts @@ -1,5 +1,9 @@ import type { WorkshopModel } from '@/config/models-catalogue' -import { catalogSearch, useCaseFor } from '@/config/models-catalogue' +import { + catalogSearch, + sortWorkshopModels, + useCaseFor +} from '@/config/models-catalogue' import { getWorkshopModel } from '@/config/workshop-browse-content' import { getWorkshopPageDetail, @@ -11,6 +15,8 @@ import type { Locale } from '@/i18n/translations' import { translationsFor } from '@/i18n/translations' import { describesCapability } from '@/lib/workshop/model-tags' import { useCaseLabelKey } from '@/lib/workshop/use-case-label' +import { workflowsUsingModel } from '@/lib/workshop/model-workflows' +import { durationsIn, resolutionRange } from '@/lib/workshop/model-ranges' const TAGS_SHOWN = 3 @@ -28,6 +34,42 @@ export function modelOgImage( : model.thumbnail?.poster } +async function providerModelRows(model: WorkshopModel) { + const { provider } = model + if (!provider) return [] + const others = sortWorkshopModels( + workshopPages.filter( + (other) => + other.routerId !== undefined && + other.href !== undefined && + other.slug !== model.slug && + other.provider === provider + ), + 'popular' + ) + return Promise.all( + others.map(async (other) => { + const duration = durationsIn( + getWorkshopPageDetail(other.slug)?.execution?.inputSchema + ) + const resolution = resolutionRange(other.resolutions) + const price = await estimateWorkshopNodePrice( + other, + other.useCases?.length === 1 ? other.useCases[0] : undefined + ) + return { + slug: other.slug, + name: other.name, + href: other.href ?? '', + provider, + ...(price && { price }), + ...(resolution && { resolution }), + ...(duration && { duration }) + } + }) + ) +} + export async function prepareModelPage( slug: string | undefined, locale: Locale = 'en' @@ -76,6 +118,8 @@ export async function prepareModelPage( model.useCases?.length === 1 ? model.useCases[0] : undefined ), useCaseLabel: useCase ? t(useCaseLabelKey[useCase]) : undefined, + providerModels: model.routerId ? await providerModelRows(model) : [], + workflows: model.routerId ? workflowsUsingModel(model, workshopPages) : [], tags, ...splitShownTags(tags) } diff --git a/apps/website/src/scripts/hubNavigation.ts b/apps/website/src/scripts/hubNavigation.ts index 2eb2c0c7627..dff912bf716 100644 --- a/apps/website/src/scripts/hubNavigation.ts +++ b/apps/website/src/scripts/hubNavigation.ts @@ -1,6 +1,8 @@ import { getRoutes } from '@/config/routes' +import { loadAppsHalf } from '@/lib/workshop/apps-half' import { loadAppCatalogue, + loadHubAppCatalogue, loadWorkflowCatalogue } from '@/lib/workshop/catalogue-components' @@ -12,7 +14,8 @@ const catalogues: Readonly< > = { [routes.workshop]: undefined, [routes.hubWorkflows]: loadWorkflowCatalogue, - [routes.hubApps]: loadAppCatalogue + [routes.hubApps]: () => + Promise.all([loadAppsHalf(), loadAppCatalogue(), loadHubAppCatalogue()]) } const TOOLBAR = `#${HUB_TOOLBAR_ID}` diff --git a/apps/website/src/scripts/workshop-analytics.ts b/apps/website/src/scripts/workshop-analytics.ts index 5066b683a9e..c26af05f0c1 100644 --- a/apps/website/src/scripts/workshop-analytics.ts +++ b/apps/website/src/scripts/workshop-analytics.ts @@ -52,6 +52,7 @@ export type HubItemSource = | 'unplaced_grid' | 'category_row' | 'app_row' + | 'app_grid' | 'results_grid' export type HubFilter = 'catalogue' | 'use_case' | 'category' | 'model' | 'sort'