diff --git a/src/components/rightSidePanel/errors/useErrorGroups.test.ts b/src/components/rightSidePanel/errors/useErrorGroups.test.ts index fc53e93505d..d8a07377eda 100644 --- a/src/components/rightSidePanel/errors/useErrorGroups.test.ts +++ b/src/components/rightSidePanel/errors/useErrorGroups.test.ts @@ -7,6 +7,7 @@ import { LGraphNode, SubgraphNode } from '@/lib/litegraph/src/litegraph' import { createBoundaryLinkedSubgraph } from '@/lib/litegraph/src/subgraph/__fixtures__/subgraphHelpers' import type { MissingMediaCandidate } from '@/platform/missingMedia/types' import { useMissingNodesErrorStore } from '@/platform/nodeReplacement/missingNodesErrorStore' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' import { useExecutionErrorStore } from '@/stores/executionErrorStore' import type { useComfyRegistryService } from '@/services/comfyRegistryService' import type { MissingNodeType } from '@/platform/nodeReplacement/types' @@ -57,6 +58,7 @@ vi.mock(import('@/platform/distribution/types'), () => ({ vi.mock(import('@/i18n'), () => { const messages: Record = { + 'deploymentSwitcher.deployment': '{build} v{version}', 'errorCatalog.validationErrors.required_input_missing.title': 'Missing connection', 'errorCatalog.validationErrors.required_input_missing.message': @@ -376,6 +378,33 @@ describe('useErrorGroups', () => { ) }) + it('names the deployment this page booted on in the missing_node copy', async () => { + mockIsCloud.value = true + useDeploymentPickStore().$patch({ + bootDeployment: { + deployment_id: 'dep-2', + release_id: 'r-2', + build_name: 'Studio Build', + release_version: 2, + status: 'ready', + created_at: '2026-10-01T00:00:00Z' + } + }) + const { groups } = createErrorGroups() + const missingNodesStore = useMissingNodesErrorStore() + missingNodesStore.setMissingNodeTypes([ + makeMissingNodeType('NodeA', { cnrId: 'pack-1' }) + ]) + await nextTick() + + const missingGroup = groups.allErrorGroups.value.find( + (g) => g.type === 'missing_node' + ) + expect(missingGroup?.displayMessage).toBe( + "These nodes aren't on Studio Build v2. Replace them, or pick a deployment that has them." + ) + }) + it('includes swap_nodes group when replaceable nodes exist', async () => { const { groups } = createErrorGroups() const missingNodesStore = useMissingNodesErrorStore() diff --git a/src/components/rightSidePanel/errors/useErrorGroups.ts b/src/components/rightSidePanel/errors/useErrorGroups.ts index b0762c90dd8..ddec9b4e6e4 100644 --- a/src/components/rightSidePanel/errors/useErrorGroups.ts +++ b/src/components/rightSidePanel/errors/useErrorGroups.ts @@ -11,6 +11,7 @@ import { useComfyRegistryStore } from '@/stores/comfyRegistryStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { app } from '@/scripts/app' import { isCloud } from '@/platform/distribution/types' +import { useBootDeploymentLabel } from '@/platform/workspace/composables/useDeploymentLabels' import { SubgraphNode } from '@/lib/litegraph/src/litegraph' import type { LGraphNode } from '@/lib/litegraph/src/litegraph' @@ -269,6 +270,7 @@ export function useErrorGroups(searchQuery: MaybeRefOrGetter) { const collapseState = reactive>({}) const errorClassification = useErrorClassification() + const deploymentLabel = isCloud ? useBootDeploymentLabel() : undefined const selectedNodeInfo = computed(() => { const rootGraph = app.rootGraphOrUndefined @@ -743,7 +745,8 @@ export function useErrorGroups(searchQuery: MaybeRefOrGetter) { kind: 'missing_node', nodeTypes: error.nodeTypes, count: packCount, - isCloud + isCloud, + deploymentLabel: deploymentLabel?.value }) }) } @@ -773,7 +776,8 @@ export function useErrorGroups(searchQuery: MaybeRefOrGetter) { kind: 'missing_model', groups: missingModelGroups.value, count, - isCloud + isCloud, + deploymentLabel: deploymentLabel?.value }) } ] @@ -886,7 +890,8 @@ export function useErrorGroups(searchQuery: MaybeRefOrGetter) { kind: 'missing_model', groups: missingModelGroupsForSelection.value, count, - isCloud + isCloud, + deploymentLabel: deploymentLabel?.value }) } ] diff --git a/src/composables/graph/useErrorClearingHooks.test.ts b/src/composables/graph/useErrorClearingHooks.test.ts index 45fe73bcb03..8b30736b445 100644 --- a/src/composables/graph/useErrorClearingHooks.test.ts +++ b/src/composables/graph/useErrorClearingHooks.test.ts @@ -24,6 +24,7 @@ import { useMissingMediaStore } from '@/platform/missingMedia/missingMediaStore' import * as missingModelScan from '@/platform/missingModel/missingModelScan' import { useMissingModelStore } from '@/platform/missingModel/missingModelStore' import { useMissingNodesErrorStore } from '@/platform/nodeReplacement/missingNodesErrorStore' +import { cloudReleaseModelOptions } from '@/platform/missingModel/releaseModelOptions' import { app } from '@/scripts/app' import { ChangeTracker } from '@/scripts/changeTracker' import { useExecutionErrorStore } from '@/stores/executionErrorStore' @@ -34,6 +35,11 @@ import { nodeError, validationError } from '@/utils/__tests__/nodeErrorHelpers' import type { MissingMediaCandidate } from '@/platform/missingMedia/types' import type { MissingModelCandidate } from '@/platform/missingModel/types' +vi.mock(import('@/platform/missingModel/releaseModelOptions'), () => ({ + cloudReleaseModelOptions: vi.fn(), + releaseModelOptions: vi.fn() +})) + function stubAppRootGraph(graph: LGraph | undefined) { vi.spyOn(app, 'rootGraphOrUndefined', 'get').mockReturnValue(graph) } @@ -1483,6 +1489,31 @@ describe('realtime scan verifies pending cloud candidates', () => { }) }) + it('hands the scan the lookup of the models the boot Release has', async () => { + const releaseModelOptions = vi.fn(async () => ['release.safetensors']) + vi.mocked(cloudReleaseModelOptions).mockReturnValue(releaseModelOptions) + const graph = new LGraph() + const node = new LGraphNode('CheckpointLoaderSimple') + node.mode = LGraphEventMode.BYPASS + graph.add(node) + stubAppRootGraph(graph) + const scanSpy = vi + .spyOn(missingModelScan, 'scanNodeModelCandidates') + .mockReturnValue([]) + vi.spyOn(missingMediaScan, 'scanNodeMediaCandidates').mockReturnValue([]) + + installErrorClearingHooks(graph) + setNodeMode(graph, node, LGraphEventMode.ALWAYS) + + expect(scanSpy).toHaveBeenCalledWith( + graph, + node, + expect.any(Function), + expect.any(Function), + releaseModelOptions + ) + }) + it('does not add candidates that remain confirmed-present after verification', async () => { const graph = new LGraph() const node = new LGraphNode('CheckpointLoaderSimple') @@ -1795,19 +1826,22 @@ describe('scan skips interior of bypassed subgraph containers', () => { rootGraph, outerSubgraphNode, expect.any(Function), - expect.any(Function) + expect.any(Function), + undefined ) expect(modelScanSpy).toHaveBeenCalledWith( rootGraph, leafNode, expect.any(Function), - expect.any(Function) + expect.any(Function), + undefined ) expect(modelScanSpy).toHaveBeenCalledWith( rootGraph, innerSubgraphNode, expect.any(Function), - expect.any(Function) + expect.any(Function), + undefined ) expect(mediaScanSpy).toHaveBeenCalledWith(rootGraph, outerSubgraphNode) expect(mediaScanSpy).toHaveBeenCalledWith(rootGraph, leafNode) diff --git a/src/composables/graph/useErrorClearingHooks.ts b/src/composables/graph/useErrorClearingHooks.ts index e96aef508f3..4c410b13e87 100644 --- a/src/composables/graph/useErrorClearingHooks.ts +++ b/src/composables/graph/useErrorClearingHooks.ts @@ -28,6 +28,7 @@ import { verifyAssetSupportedCandidates } from '@/platform/missingModel/missingModelScan' import { useMissingModelStore } from '@/platform/missingModel/missingModelStore' +import { cloudReleaseModelOptions } from '@/platform/missingModel/releaseModelOptions' import { isMissingMediaCandidateActive, isMissingMediaCandidateScopeActive, @@ -219,7 +220,8 @@ function scanSingleNodeModelsAndTypes( rootGraph, node, assetService.shouldUseWidgetAssetPicker, - (nodeType) => useModelToNodeStore().getCategoryForNodeType(nodeType) + (nodeType) => useModelToNodeStore().getCategoryForNodeType(nodeType), + cloudReleaseModelOptions() ) const confirmedModels = modelCandidates.filter((c) => c.isMissing === true) if (confirmedModels.length) { diff --git a/src/composables/useUrlActionLoaders.test.ts b/src/composables/useUrlActionLoaders.test.ts index 5a1556be3ab..d6b5c611026 100644 --- a/src/composables/useUrlActionLoaders.test.ts +++ b/src/composables/useUrlActionLoaders.test.ts @@ -14,6 +14,7 @@ vi.mock(import('@/platform/distribution/types'), () => ({ const mocks = vi.hoisted(() => ({ reportError: vi.fn(), + loadDeployment: vi.fn(async (): Promise => false), loadWorkspace: vi.fn(async (): Promise => undefined), loadInvite: vi.fn(async () => undefined), loadCreateWorkspace: vi.fn(async () => undefined), @@ -22,6 +23,7 @@ const mocks = vi.hoisted(() => ({ loadSettings: vi.fn(), loadAssets: vi.fn(async () => undefined), loadPaymentReturn: vi.fn(async () => undefined), + useDeployment: vi.fn(), useWorkspace: vi.fn(), useInvite: vi.fn(), useCreateWorkspace: vi.fn(), @@ -31,6 +33,9 @@ const mocks = vi.hoisted(() => ({ useAssets: vi.fn(), usePaymentReturn: vi.fn() })) +mocks.useDeployment.mockImplementation(() => ({ + loadDeploymentFromUrl: mocks.loadDeployment +})) mocks.useWorkspace.mockImplementation(() => ({ loadWorkspaceFromUrl: mocks.loadWorkspace })) @@ -66,6 +71,12 @@ const router = createRouter({ routes: [{ path: '/:pathMatch(.*)*', component: { template: '
' } }] }) +vi.mock( + import('@/platform/workspace/composables/useDeploymentUrlLoader'), + () => ({ + useDeploymentUrlLoader: mocks.useDeployment + }) +) vi.mock( import('@/platform/workspace/composables/useWorkspaceUrlLoader'), () => ({ @@ -111,6 +122,9 @@ vi.mock(import('@/platform/telemetry/reportError'), () => ({ describe('useUrlActionLoaders', () => { beforeEach(async () => { mockIsCloud.value = true + mocks.useDeployment.mockImplementation(() => ({ + loadDeploymentFromUrl: mocks.loadDeployment + })) mocks.useWorkspace.mockImplementation(() => ({ loadWorkspaceFromUrl: mocks.loadWorkspace })) @@ -204,6 +218,7 @@ describe('useUrlActionLoaders', () => { const { runUrlActionLoaders } = useUrlActionLoaders() await runUrlActionLoaders() + expect(mocks.useDeployment).not.toHaveBeenCalled() expect(mocks.useWorkspace).not.toHaveBeenCalled() expect(mocks.useInvite).not.toHaveBeenCalled() expect(mocks.useCreateWorkspace).not.toHaveBeenCalled() @@ -213,6 +228,7 @@ describe('useUrlActionLoaders', () => { expect(mocks.useAssets).not.toHaveBeenCalled() expect(mocks.usePaymentReturn).not.toHaveBeenCalled() expect(useSubscriptionDialog).not.toHaveBeenCalled() + expect(mocks.loadDeployment).not.toHaveBeenCalled() expect(mocks.loadWorkspace).not.toHaveBeenCalled() expect(mocks.loadInvite).not.toHaveBeenCalled() expect(mocks.loadCreateWorkspace).not.toHaveBeenCalled() @@ -230,6 +246,7 @@ describe('useUrlActionLoaders', () => { const { runUrlActionLoaders } = useUrlActionLoaders() await runUrlActionLoaders() + expect(mocks.loadDeployment).toHaveBeenCalledOnce() expect(mocks.loadWorkspace).toHaveBeenCalledOnce() expect(mocks.loadInvite).toHaveBeenCalledOnce() expect(mocks.loadCreateWorkspace).toHaveBeenCalledOnce() @@ -258,6 +275,49 @@ describe('useUrlActionLoaders', () => { ) }) + // With ?deployment the deployment link owns ?workspace too: the workspace + // loader alone would strip ?workspace and switch, and the boot after that + // reload would find a link with no workspace in it. + it('reads a deployment link before the workspace link', async () => { + const { runUrlActionLoaders } = useUrlActionLoaders() + await runUrlActionLoaders() + + expect(mocks.loadDeployment.mock.invocationCallOrder[0]).toBeLessThan( + mocks.loadWorkspace.mock.invocationCallOrder[0] + ) + }) + + // The deployment link keeps both params across its own workspace switch, + // so the boot after the reload can pick; nothing may strip them first. + it('stops before every other step, the sweep included, when the deployment link reloads', async () => { + await router.replace({ + path: '/', + query: { workspace: 'w-2', deployment: 'dep-1' } + }) + mocks.loadDeployment.mockResolvedValueOnce(true) + + const { runUrlActionLoaders } = useUrlActionLoaders() + await runUrlActionLoaders() + + expect(mocks.loadWorkspace).not.toHaveBeenCalled() + expect(router.currentRoute.value.query).toEqual({ + workspace: 'w-2', + deployment: 'dep-1' + }) + }) + + it('clears a deployment param no loader acted on', async () => { + await router.replace({ + path: '/', + query: { deployment: 'dep-1', workflow: 'keep-me' } + }) + + const { runUrlActionLoaders } = useUrlActionLoaders() + await runUrlActionLoaders() + + expect(router.currentRoute.value.query).toEqual({ workflow: 'keep-me' }) + }) + it('isolates a workspace-loader failure so it does not abort the boot chain', async () => { mocks.loadWorkspace.mockRejectedValueOnce(new Error('boom')) diff --git a/src/composables/useUrlActionLoaders.ts b/src/composables/useUrlActionLoaders.ts index 4e5b52125ca..b8688cd285e 100644 --- a/src/composables/useUrlActionLoaders.ts +++ b/src/composables/useUrlActionLoaders.ts @@ -13,6 +13,7 @@ import { isCloud } from '@/platform/distribution/types' import { useSettingsUrlLoader } from '@/platform/settings/composables/useSettingsUrlLoader' import { reportError } from '@/platform/telemetry/reportError' import { useCreateWorkspaceUrlLoader } from '@/platform/workspace/composables/useCreateWorkspaceUrlLoader' +import { useDeploymentUrlLoader } from '@/platform/workspace/composables/useDeploymentUrlLoader' import { useInviteUrlLoader } from '@/platform/workspace/composables/useInviteUrlLoader' import { useWorkspaceUrlLoader } from '@/platform/workspace/composables/useWorkspaceUrlLoader' @@ -26,6 +27,7 @@ interface UrlActionStep { } type UrlActionLoaders = { + deploymentUrlLoader: ReturnType | null workspaceUrlLoader: ReturnType | null inviteUrlLoader: ReturnType | null createWorkspaceUrlLoader: ReturnType< @@ -50,10 +52,13 @@ type UrlActionLoaders = { * rejected `router.replace` and returns normally, so a failed strip needs * this backstop rather than leaving the link live with no retry. A * successful switch reloads the page and stops the loop before this step - * runs, so it never re-strips a live workspace switch. + * runs, so it never re-strips a live workspace switch. `deployment` likewise: + * the deployment link keeps both params only across its own switch reload, + * which also stops the loop first. */ const HANDLED_PARAMS = [ 'workspace', + 'deployment', 'invite', 'create_workspace', 'pricing', @@ -66,17 +71,31 @@ const HANDLED_PARAMS = [ ...BILLING_WEB_RETURN_PARAMS ] +function deploymentLinkSteps( + loader: UrlActionLoaders['deploymentUrlLoader'] +): UrlActionStep[] { + if (!loader) return [] + return [ + { + failureMessage: 'Failed to open deployment from URL:', + run: () => loader.loadDeploymentFromUrl() + } + ] +} + /** - * Orders the deep-link loaders: workspace first, so `?invite`, - * `?create_workspace`, `?pricing`, `?topup`, `?settings`, `?assets` all act - * on the requested workspace rather than the one the app happened to load - * with. Only the loaders present (cloud-gated by the caller) become steps. + * Orders the deep-link loaders: the deployment link first, since with + * `?deployment` it owns `?workspace` too (it switches, then picks after the + * reload); then workspace, so `?invite`, `?create_workspace`, `?pricing`, + * `?topup`, `?settings`, `?assets` all act on the requested workspace rather + * than the one the app happened to load with. Only the loaders present + * (cloud-gated by the caller) become steps. */ function buildUrlActionSteps( loaders: UrlActionLoaders, router: ReturnType ): UrlActionStep[] { - const steps: UrlActionStep[] = [] + const steps = deploymentLinkSteps(loaders.deploymentUrlLoader) if (loaders.workspaceUrlLoader) { const loader = loaders.workspaceUrlLoader @@ -201,14 +220,15 @@ function useIfCloud(create: () => T): T | null { /** * Aggregates the query-param "deep link" loaders the cloud app checks on mount - * (`?workspace`, `?invite`, `?create_workspace`, `?pricing`, `?topup`, - * `?settings`, `?assets`), then recovers an interrupted checkout. The loaders + * (`?deployment`, `?workspace`, `?invite`, `?create_workspace`, `?pricing`, + * `?topup`, `?settings`, `?assets`), then recovers an interrupted checkout. The loaders * are instantiated in setup so their `useRoute`/`useRouter` resolve; call * `runUrlActionLoaders()` from `onMounted` once the app is ready. */ export function useUrlActionLoaders() { const router = useRouter() + const deploymentUrlLoader = useIfCloud(useDeploymentUrlLoader) const workspaceUrlLoader = useIfCloud(useWorkspaceUrlLoader) const inviteUrlLoader = useIfCloud(useInviteUrlLoader) const createWorkspaceUrlLoader = useIfCloud(useCreateWorkspaceUrlLoader) @@ -222,6 +242,7 @@ export function useUrlActionLoaders() { const steps = isCloud ? buildUrlActionSteps( { + deploymentUrlLoader, workspaceUrlLoader, inviteUrlLoader, createWorkspaceUrlLoader, diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 47e427dafd4..7875e4a98cb 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -3866,6 +3866,38 @@ "managedByOrganization": "Your organization manages your workspaces, so you can't create one.", "failedToSwitch": "Failed to switch workspace" }, + "deploymentSwitcher": { + "runningOn": "Running on", + "comfyCloud": "Comfy Cloud", + "comfyCloudCaption": "Comfy's own node set", + "deployment": "{build} v{version}", + "unnamedDeployment": "Deployment {id}", + "pickGone": "The deployment you picked no longer exists.", + "pickGoneDetail": "This browser now runs on Comfy Cloud. Pick a deployment again from the account menu to use one.", + "defaultGone": "The workspace's default deployment no longer exists.", + "namedDeployment": "{name}", + "namedCaption": "{release} · {caption}", + "caption": "{id}, {status}", + "captionDefault": "{id}, {status} · Workspace default", + "noDeployments": "This workspace has no deployments yet. Deploy a Release on the Developer Platform first.", + "buildsHidden": "Build names are not visible to this account.", + "reloadNote": "Picking reloads the editor with the deployment's nodes. When the deployment is updated to another Release, reload to get its new nodes.", + "releaseChanged": "This deployment now runs a different Release. Reload to get its nodes.", + "deploymentChanged": "This browser now runs on {deployment}. Reload to get its nodes.", + "reload": "Reload", + "failedToSwitch": "Could not switch", + "workspaceDefault": "Workspace default", + "workspaceDefaultIs": "Workspace default: {deployment}", + "noWorkspaceDefault": "No workspace default: members start on Comfy Cloud.", + "followWorkspace": "Use the workspace default", + "followWorkspaceCaption": "Drop this browser's own pick and run on {deployment}", + "setAsDefault": "Set as workspace default", + "clearDefault": "Clear workspace default", + "failedToSetDefault": "Could not change the workspace default", + "linkTimedOut": "This deployment took too long to open. Try the link again.", + "linkRefused": "Couldn't open this deployment", + "linkWorkspaceRefused": "Couldn't switch to that workspace. You're still in {workspaceName}." + }, "selectionToolbox": { "executeButton": { "tooltip": "Execute to selected output nodes (Highlighted with orange border)", @@ -4871,7 +4903,12 @@ "toastMessageOneCloud": "This node isn't supported on Cloud.", "toastMessageOneOss": "This workflow uses a custom node that isn't installed. Install it from the registry or replace the node.", "toastMessageManyCloud": "This workflow uses nodes that aren't supported on Cloud.", - "toastMessageManyOss": "{count} nodes require missing node packs." + "toastMessageManyOss": "{count} nodes require missing node packs.", + "displayMessageDeployment": "These nodes aren't on {deployment}. Replace them, or pick a deployment that has them.", + "toastTitleOneDeployment": "{nodeType} isn't on {deployment}", + "toastTitleManyDeployment": "Nodes aren't on {deployment}", + "toastMessageOneDeployment": "Replace this node, or pick a deployment that has it.", + "toastMessageManyDeployment": "Replace these nodes, or pick a deployment that has them." }, "swap_nodes": { "displayMessage": "Some nodes can be replaced with alternatives", @@ -4890,7 +4927,12 @@ "toastMessageOneCloud": "This model isn't supported. Choose a different one.", "toastMessageOneOss": "{nodeName} is missing a required model file.", "toastMessageManyCloud": "Some models aren't supported. Choose different ones.", - "toastMessageManyOss": "{count} model files are missing." + "toastMessageManyOss": "{count} model files are missing.", + "displayMessageDeployment": "These models aren't on {deployment}. Open the node to choose one it has.", + "toastTitleOneDeployment": "{modelName} isn't on {deployment}", + "toastTitleManyDeployment": "Models aren't on {deployment}", + "toastMessageOneDeployment": "Choose a different model, or pick a deployment that has it.", + "toastMessageManyDeployment": "Choose different models, or pick a deployment that has them." }, "missing_media": { "displayMessage": "A required media input has no file selected.", diff --git a/src/platform/cloud/onboarding/utils/previousFullPath.test.ts b/src/platform/cloud/onboarding/utils/previousFullPath.test.ts index d7d12d6c67c..201c4a75d22 100644 --- a/src/platform/cloud/onboarding/utils/previousFullPath.test.ts +++ b/src/platform/cloud/onboarding/utils/previousFullPath.test.ts @@ -15,6 +15,17 @@ describe('getSafePreviousFullPath', () => { expect(getSafePreviousFullPath(query)).toBe('/some/path?x=1') }) + // A deployment link (BE-20294) opened signed out comes back with both + // params, so the editor opens on the deployment after sign-in. + test('keeps the query of a link to the editor root', () => { + const query: LocationQuery = { + previousFullPath: encodeURIComponent('/?workspace=ws-1&deployment=dep-1') + } + expect(getSafePreviousFullPath(query)).toBe( + '/?workspace=ws-1&deployment=dep-1' + ) + }) + test('rejects protocol-relative urls', () => { const query: LocationQuery = { previousFullPath: encodeURIComponent('//evil.com') diff --git a/src/platform/errorCatalog/errorMessageResolver.test.ts b/src/platform/errorCatalog/errorMessageResolver.test.ts index 99c64c3c1c7..e437f3b3928 100644 --- a/src/platform/errorCatalog/errorMessageResolver.test.ts +++ b/src/platform/errorCatalog/errorMessageResolver.test.ts @@ -1697,6 +1697,73 @@ describe('errorMessageResolver', () => { }) }) + it('names the deployment the editor runs on instead of Cloud in missing node copy', () => { + const onDeployment = { isCloud: true, deploymentLabel: 'Studio Build v2' } + expect( + resolveMissingErrorMessage({ + kind: 'missing_node', + nodeTypes: [missingNodeType('FooNode', '7', 'foo-pack')], + count: 1, + ...onDeployment + }) + ).toEqual({ + catalogId: 'missing_node', + displayTitle: 'Missing Node Packs', + displayMessage: + "These nodes aren't on Studio Build v2. Replace them, or pick a deployment that has them.", + toastTitle: "FooNode isn't on Studio Build v2", + toastMessage: 'Replace this node, or pick a deployment that has it.' + }) + + expect( + resolveMissingErrorMessage({ + kind: 'missing_node', + nodeTypes: [ + missingNodeType('FooNode', '7', 'foo-pack'), + missingNodeType('BarNode', '9', 'bar-pack') + ], + count: 2, + ...onDeployment + }) + ).toMatchObject({ + toastTitle: "Nodes aren't on Studio Build v2", + toastMessage: 'Replace these nodes, or pick a deployment that has them.' + }) + }) + + it('names the deployment the editor runs on instead of Cloud in missing model copy', () => { + const onDeployment = { isCloud: true, deploymentLabel: 'Studio Build v2' } + expect( + resolveMissingErrorMessage({ + kind: 'missing_model', + groups: missingModelGroups('sdxl.safetensors'), + count: 1, + ...onDeployment + }) + ).toEqual({ + catalogId: 'missing_model', + displayTitle: 'Missing Models', + displayMessage: + "These models aren't on Studio Build v2. Open the node to choose one it has.", + toastTitle: "sdxl.safetensors isn't on Studio Build v2", + toastMessage: + 'Choose a different model, or pick a deployment that has it.' + }) + + expect( + resolveMissingErrorMessage({ + kind: 'missing_model', + groups: missingModelGroups('sdxl.safetensors', 'vae.safetensors'), + count: 2, + ...onDeployment + }) + ).toMatchObject({ + toastTitle: "Models aren't on Studio Build v2", + toastMessage: + 'Choose different models, or pick a deployment that has them.' + }) + }) + it('preserves special characters in catalog copy for model names', () => { const modelName = 'sd&xl.safetensors' expect( diff --git a/src/platform/errorCatalog/missingErrorResolver.ts b/src/platform/errorCatalog/missingErrorResolver.ts index ec99a95d4a5..cec93621686 100644 --- a/src/platform/errorCatalog/missingErrorResolver.ts +++ b/src/platform/errorCatalog/missingErrorResolver.ts @@ -2,6 +2,7 @@ import type { MissingErrorMessageSource, ResolvedMissingErrorMessage } from './types' +import type { CatalogParams } from './catalogI18n' import { normalizeNodeName, translateCatalogMessage } from './catalogI18n' import { countMissingMediaReferences } from '@/platform/missingMedia/missingMediaGrouping' import { countMissingModels } from '@/platform/missingModel/missingModelGrouping' @@ -44,7 +45,31 @@ function isMissingNodeType(nodeType: NodeTypeErrorItem): boolean { return typeof nodeType === 'string' || !nodeType.isReplaceable } +/** + * On a developer-platform deployment (FE-2434) the editor's nodes and models + * are its Release's, so a message names the deployment instead of Cloud. + * Null on Comfy Cloud and outside Cloud. + */ +function deploymentMessage( + source: { deploymentLabel?: string }, + key: string, + fallback: string, + params: CatalogParams = {} +): string | null { + if (!source.deploymentLabel) return null + return translateCatalogMessage(key, fallback, { + ...params, + deployment: source.deploymentLabel + }) +} + function resolveMissingNodeDisplayMessage(source: MissingNodeSource): string { + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_node.displayMessageDeployment', + "These nodes aren't on {deployment}. Replace them, or pick a deployment that has them." + ) + if (onDeployment) return onDeployment const key = source.isCloud ? 'errorCatalog.missingErrors.missing_node.displayMessageCloud' : 'errorCatalog.missingErrors.missing_node.displayMessageOss' @@ -60,6 +85,13 @@ function resolveMissingNodeToastTitle(source: MissingNodeSource): string { ) const [firstLabel] = labels if (labels.length === 1 && firstLabel) { + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_node.toastTitleOneDeployment', + "{nodeType} isn't on {deployment}", + { nodeType: firstLabel } + ) + if (onDeployment) return onDeployment const key = source.isCloud ? 'errorCatalog.missingErrors.missing_node.toastTitleOneCloud' : 'errorCatalog.missingErrors.missing_node.toastTitleOneOss' @@ -69,6 +101,12 @@ function resolveMissingNodeToastTitle(source: MissingNodeSource): string { return translateCatalogMessage(key, fallback, { nodeType: firstLabel }) } + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_node.toastTitleManyDeployment', + "Nodes aren't on {deployment}" + ) + if (onDeployment) return onDeployment const key = source.isCloud ? 'errorCatalog.missingErrors.missing_node.toastTitleManyCloud' : 'errorCatalog.missingErrors.missing_node.toastTitleManyOss' @@ -85,6 +123,12 @@ function resolveMissingNodeToastMessage(source: MissingNodeSource): string { const count = labels.length || source.count if (count === 1) { + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_node.toastMessageOneDeployment', + 'Replace this node, or pick a deployment that has it.' + ) + if (onDeployment) return onDeployment const key = source.isCloud ? 'errorCatalog.missingErrors.missing_node.toastMessageOneCloud' : 'errorCatalog.missingErrors.missing_node.toastMessageOneOss' @@ -94,6 +138,12 @@ function resolveMissingNodeToastMessage(source: MissingNodeSource): string { return translateCatalogMessage(key, fallback) } + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_node.toastMessageManyDeployment', + 'Replace these nodes, or pick a deployment that has them.' + ) + if (onDeployment) return onDeployment const key = source.isCloud ? 'errorCatalog.missingErrors.missing_node.toastMessageManyCloud' : 'errorCatalog.missingErrors.missing_node.toastMessageManyOss' @@ -172,6 +222,12 @@ function getMissingModelCount(source: MissingModelSource): number { } function resolveMissingModelDisplayMessage(source: MissingModelSource): string { + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_model.displayMessageDeployment', + "These models aren't on {deployment}. Open the node to choose one it has." + ) + if (onDeployment) return onDeployment const key = source.isCloud ? 'errorCatalog.missingErrors.missing_model.displayMessageCloud' : 'errorCatalog.missingErrors.missing_model.displayMessageOss' @@ -186,17 +242,43 @@ function resolveMissingModelToastTitle(source: MissingModelSource): string { const count = getMissingModelCount(source) if (count === 1 && firstModel) { - const key = source.isCloud - ? 'errorCatalog.missingErrors.missing_model.toastTitleOneCloud' - : 'errorCatalog.missingErrors.missing_model.toastTitleOneOss' - const fallback = source.isCloud - ? "{modelName} isn't available on Cloud" - : '{modelName} is missing' - return translateCatalogMessage(key, fallback, { - modelName: firstModel.name - }) + return resolveOneMissingModelToastTitle(source, firstModel.name) } + return resolveManyMissingModelsToastTitle(source, count) +} + +function resolveOneMissingModelToastTitle( + source: MissingModelSource, + modelName: string +): string { + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_model.toastTitleOneDeployment', + "{modelName} isn't on {deployment}", + { modelName } + ) + if (onDeployment) return onDeployment + const key = source.isCloud + ? 'errorCatalog.missingErrors.missing_model.toastTitleOneCloud' + : 'errorCatalog.missingErrors.missing_model.toastTitleOneOss' + const fallback = source.isCloud + ? "{modelName} isn't available on Cloud" + : '{modelName} is missing' + return translateCatalogMessage(key, fallback, { modelName }) +} +function resolveManyMissingModelsToastTitle( + source: MissingModelSource, + count: number +): string { + if (count > 1) { + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_model.toastTitleManyDeployment', + "Models aren't on {deployment}" + ) + if (onDeployment) return onDeployment + } const useCloudPluralTitle = source.isCloud && count > 1 const key = useCloudPluralTitle ? 'errorCatalog.missingErrors.missing_model.toastTitleManyCloud' @@ -221,6 +303,12 @@ function resolveMissingModelToastMessage(source: MissingModelSource): string { const count = getMissingModelCount(source) if (!firstModel || count !== 1) { + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_model.toastMessageManyDeployment', + 'Choose different models, or pick a deployment that has them.' + ) + if (onDeployment) return onDeployment const key = source.isCloud ? 'errorCatalog.missingErrors.missing_model.toastMessageManyCloud' : 'errorCatalog.missingErrors.missing_model.toastMessageManyOss' @@ -230,6 +318,12 @@ function resolveMissingModelToastMessage(source: MissingModelSource): string { return translateCatalogMessage(key, fallback, { count }) } + const onDeployment = deploymentMessage( + source, + 'errorCatalog.missingErrors.missing_model.toastMessageOneDeployment', + 'Choose a different model, or pick a deployment that has it.' + ) + if (onDeployment) return onDeployment if (source.isCloud) { return translateCatalogMessage( 'errorCatalog.missingErrors.missing_model.toastMessageOneCloud', @@ -337,12 +431,13 @@ export function resolveMissingErrorMessage( case 'missing_node': return { catalogId: 'missing_node', - displayTitle: source.isCloud - ? st( - 'rightSidePanel.missingNodePacks.unsupportedTitle', - 'Unsupported Node Packs' - ) - : st('rightSidePanel.missingNodePacks.title', 'Missing Node Packs'), + displayTitle: + source.isCloud && !source.deploymentLabel + ? st( + 'rightSidePanel.missingNodePacks.unsupportedTitle', + 'Unsupported Node Packs' + ) + : st('rightSidePanel.missingNodePacks.title', 'Missing Node Packs'), displayMessage: resolveMissingNodeDisplayMessage(source), toastTitle: resolveMissingNodeToastTitle(source), toastMessage: resolveMissingNodeToastMessage(source) diff --git a/src/platform/errorCatalog/types.ts b/src/platform/errorCatalog/types.ts index 87957d09cc8..f39fd9c4067 100644 --- a/src/platform/errorCatalog/types.ts +++ b/src/platform/errorCatalog/types.ts @@ -58,6 +58,11 @@ export type MissingErrorMessageSource = nodeTypes: MissingNodeType[] count: number isCloud: boolean + /** + * The deployment the editor runs on (FE-2434), named instead of Cloud; + * absent on Comfy Cloud and outside Cloud. + */ + deploymentLabel?: string } | { kind: 'swap_nodes' @@ -70,6 +75,11 @@ export type MissingErrorMessageSource = groups: MissingModelGroup[] count: number isCloud: boolean + /** + * The deployment the editor runs on (FE-2434), named instead of Cloud; + * absent on Comfy Cloud and outside Cloud. + */ + deploymentLabel?: string } | { kind: 'missing_media' diff --git a/src/platform/missingModel/missingModelPipeline.test.ts b/src/platform/missingModel/missingModelPipeline.test.ts index e399b600aee..6a3fe3804ac 100644 --- a/src/platform/missingModel/missingModelPipeline.test.ts +++ b/src/platform/missingModel/missingModelPipeline.test.ts @@ -11,6 +11,8 @@ import type { LGraph } from '@/lib/litegraph/src/litegraph' import { LGraphNode, LGraphEventMode } from '@/lib/litegraph/src/litegraph' import { promoteValueWidgetViaSubgraphInput } from '@/core/graph/subgraph/promotionUtils' import type { MissingModelCandidate } from '@/platform/missingModel/types' +import type { ReleaseModelOptions } from '@/platform/missingModel/missingModelScan' +import { cloudReleaseModelOptions } from '@/platform/missingModel/releaseModelOptions' import type { ComfyWorkflowJSON, ModelFile @@ -47,7 +49,8 @@ const { mockHandles } = vi.hoisted(() => { ( _graph: LGraph, _isAssetSupported: (nodeType: string, widgetName: string) => boolean, - _getDirectory?: (nodeType: string) => string | undefined + _getDirectory?: (nodeType: string) => string | undefined, + _releaseModelOptions?: ReleaseModelOptions ): MissingModelCandidate[] => [] ), enrichWithEmbeddedMetadata: vi.fn( @@ -97,9 +100,15 @@ vi.mock(import('@/platform/missingModel/missingModelScan'), () => ({ scanAllModelCandidates: ( graph: LGraph, isAssetSupported: (nodeType: string, widgetName: string) => boolean, - getDirectory?: (nodeType: string) => string | undefined + getDirectory?: (nodeType: string) => string | undefined, + releaseModelOptions?: ReleaseModelOptions ) => - mockHandles.scanAllModelCandidates(graph, isAssetSupported, getDirectory), + mockHandles.scanAllModelCandidates( + graph, + isAssetSupported, + getDirectory, + releaseModelOptions + ), enrichWithEmbeddedMetadata: ( candidates: readonly MissingModelCandidate[], graphData: ComfyWorkflowJSON @@ -116,6 +125,11 @@ vi.mock(import('@/scripts/api'), () => ({ } })) +vi.mock(import('@/platform/missingModel/releaseModelOptions'), () => ({ + cloudReleaseModelOptions: vi.fn(), + releaseModelOptions: vi.fn() +})) + vi.mock(import('@/platform/missingModel/missingModelDownload'), () => ({ fetchModelMetadata: (url: string) => mockHandles.fetchModelMetadata(url) })) @@ -779,6 +793,25 @@ describe('missingModelPipeline', () => { }) }) + it('hands the scan the lookup of the models the boot Release has', async () => { + const releaseModelOptions = vi.fn(async () => ['release.safetensors']) + vi.mocked(cloudReleaseModelOptions).mockReturnValue(releaseModelOptions) + const graph = createGraph() + + await runMissingModelPipeline({ + graph, + graphData: createWorkflowGraphData(), + missingModelStore: useMissingModelStore() + }) + + expect(mockHandles.scanAllModelCandidates).toHaveBeenCalledWith( + graph, + expect.any(Function), + expect.any(Function), + releaseModelOptions + ) + }) + it('returns confirmed missing models and caches pending warning candidates', async () => { const confirmedCandidate = { nodeType: 'CheckpointLoaderSimple', diff --git a/src/platform/missingModel/missingModelPipeline.ts b/src/platform/missingModel/missingModelPipeline.ts index 6edf453950b..ede5c049483 100644 --- a/src/platform/missingModel/missingModelPipeline.ts +++ b/src/platform/missingModel/missingModelPipeline.ts @@ -9,6 +9,7 @@ import { verifyAssetSupportedCandidates } from '@/platform/missingModel/missingModelScan' import type { MissingModelWorkflowData } from '@/platform/missingModel/missingModelScan' +import { cloudReleaseModelOptions } from '@/platform/missingModel/releaseModelOptions' import type { MissingModelCandidate, MissingModelPipelineResult @@ -119,7 +120,8 @@ export async function runMissingModelPipeline({ const candidates = scanAllModelCandidates( graph, isAssetBrowserWidget, - getDirectory + getDirectory, + cloudReleaseModelOptions() ) const enrichedAll = enrichWithEmbeddedMetadata(candidates, graphData) diff --git a/src/platform/missingModel/missingModelScan.test.ts b/src/platform/missingModel/missingModelScan.test.ts index 971f36c2b7a..5cb8e674374 100644 --- a/src/platform/missingModel/missingModelScan.test.ts +++ b/src/platform/missingModel/missingModelScan.test.ts @@ -20,6 +20,7 @@ import { verifyAssetSupportedCandidates, MODEL_FILE_EXTENSIONS } from '@/platform/missingModel/missingModelScan' +import type { ReleaseModelOptions } from '@/platform/missingModel/missingModelScan' import type { MissingModelCandidate } from '@/platform/missingModel/types' import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' import { useWidgetValueStore } from '@/stores/widgetValueStore' @@ -1973,6 +1974,131 @@ describe('verifyAssetSupportedCandidates', () => { }) }) +describe('on a developer-platform deployment', () => { + const releaseModelOptions = async (nodeType: string, widgetName: string) => + nodeType === 'CheckpointLoaderSimple' && widgetName === 'ckpt_name' + ? ['release_model.safetensors'] + : undefined + + beforeEach(() => { + mockUpdateModelsForNodeType.mockResolvedValue(undefined) + mockGetAssets.mockReturnValue([]) + }) + + it.for([ + { + when: 'the Release lists the model', + widget: makeAssetWidget('ckpt_name', 'release_model.safetensors'), + options: releaseModelOptions, + isMissing: false + }, + { + when: 'the Release lists the model on an asset-supported combo', + widget: makeComboWidget('ckpt_name', 'release_model.safetensors'), + options: releaseModelOptions, + isMissing: false + }, + { + when: 'the Release does not list the model', + widget: makeAssetWidget('ckpt_name', 'other_model.safetensors'), + options: releaseModelOptions, + isMissing: true + }, + { + when: 'the editor runs on Comfy Cloud', + widget: makeAssetWidget('ckpt_name', 'release_model.safetensors'), + options: undefined, + isMissing: true + } + ])( + 'takes the model as missing: $isMissing, when $when', + async ({ widget, options, isMissing }) => { + const graph = makeGraph([makeNode(1, 'CheckpointLoaderSimple', [widget])]) + const candidates = scanAllModelCandidates( + graph, + () => true, + undefined, + options + ) + + await verifyAssetSupportedCandidates(candidates) + + expect(candidates).toHaveLength(1) + expect(candidates[0].isMissing).toBe(isMissing) + } + ) +}) + +describe("while the page's deployment listing is slow", () => { + beforeEach(() => { + mockUpdateModelsForNodeType.mockResolvedValue(undefined) + mockGetAssets.mockReturnValue([]) + }) + + function scanReleaseModel(releaseModelOptions: ReleaseModelOptions) { + const graph = makeGraph([ + makeNode(1, 'CheckpointLoaderSimple', [ + makeAssetWidget('ckpt_name', 'release_model.safetensors') + ]) + ]) + return scanAllModelCandidates( + graph, + () => true, + undefined, + releaseModelOptions + ) + } + + it('takes the model the Release lists as present when the options answer after 6 seconds', async () => { + const candidates = scanReleaseModel( + () => + new Promise((resolve) => + setTimeout(() => resolve(['release_model.safetensors']), 6000) + ) + ) + + const verifying = verifyAssetSupportedCandidates(candidates) + await vi.advanceTimersByTimeAsync(6000) + await verifying + + expect(candidates[0].isMissing).toBe(false) + expect(mockUpdateModelsForNodeType).not.toHaveBeenCalled() + }) + + it('checks the model against the library when the Release options are unknown', async () => { + const candidates = scanReleaseModel(async () => undefined) + + await verifyAssetSupportedCandidates(candidates) + + expect(candidates[0].isMissing).toBe(true) + expect(mockUpdateModelsForNodeType).toHaveBeenCalledWith( + 'CheckpointLoaderSimple' + ) + }) + + it('settles at once when the scan is aborted before the options answer', async () => { + const candidates = scanReleaseModel( + (_nodeType, _widgetName, signal) => + new Promise((resolve) => + signal?.addEventListener('abort', () => resolve(undefined), { + once: true + }) + ) + ) + const controller = new AbortController() + + const verifying = verifyAssetSupportedCandidates( + candidates, + controller.signal + ) + controller.abort() + await verifying + + expect(candidates[0].isMissing).toBeUndefined() + expect(mockUpdateModelsForNodeType).not.toHaveBeenCalled() + }) +}) + describe('remote combo inventory', () => { function makeRemoteCombo(value: string) { const widget = makeComboWidget('file_name', value, ['0', '1']) diff --git a/src/platform/missingModel/missingModelScan.ts b/src/platform/missingModel/missingModelScan.ts index 50746b81365..bef95dbc2fc 100644 --- a/src/platform/missingModel/missingModelScan.ts +++ b/src/platform/missingModel/missingModelScan.ts @@ -46,6 +46,19 @@ type DeferredVerification = ( signal?: AbortSignal ) => Promise +/** + * On a developer-platform deployment (FE-2434) the editor's node catalog is + * the deployment's Release, so a loader's model options there are models the + * deployment has. Resolves those options for a loader input, or undefined + * when the editor runs on Comfy Cloud, when that is not known yet, or once + * `signal` aborts. + */ +export type ReleaseModelOptions = ( + nodeType: string, + widgetName: string, + signal?: AbortSignal +) => Promise + const pendingVerifications = new WeakMap< MissingModelCandidate, DeferredVerification @@ -154,7 +167,8 @@ export function isModelFileName(name: string): boolean { export function scanAllModelCandidates( rootGraph: LGraph, isAssetSupported: (nodeType: string, widgetName: string) => boolean, - getDirectory?: (nodeType: string) => string | undefined + getDirectory?: (nodeType: string) => string | undefined, + releaseModelOptions?: ReleaseModelOptions ): MissingModelCandidate[] { const allNodes = collectAllNodes(rootGraph) const candidates: MissingModelCandidate[] = [] @@ -167,7 +181,8 @@ export function scanAllModelCandidates( rootGraph, node, isAssetSupported, - getDirectory + getDirectory, + releaseModelOptions ) ) } @@ -180,7 +195,8 @@ export function scanNodeModelCandidates( rootGraph: LGraph, node: LGraphNode, isAssetSupported: (nodeType: string, widgetName: string) => boolean, - getDirectory?: (nodeType: string) => string | undefined + getDirectory?: (nodeType: string) => string | undefined, + releaseModelOptions?: ReleaseModelOptions ): MissingModelCandidate[] { const isSubgraphNode = typeof node.isSubgraphNode === 'function' && node.isSubgraphNode() @@ -206,9 +222,14 @@ export function scanNodeModelCandidates( let candidate: MissingModelCandidate | null = null if (isAssetScanTarget(target)) { - candidate = scanAssetWidget(target, getDirectory) + candidate = scanAssetWidget(target, getDirectory, releaseModelOptions) } else if (isComboScanTarget(target)) { - candidate = scanComboWidget(target, isAssetSupported, getDirectory) + candidate = scanComboWidget( + target, + isAssetSupported, + getDirectory, + releaseModelOptions + ) } if (!candidate) continue @@ -298,15 +319,38 @@ function isComboScanTarget( return isComboWidget(target.definitionWidget) } +/** + * Verification then takes a model the deployment's Release lists for this + * loader as present, whatever Cloud's model library holds. A model the + * Release does not list, and every model on Comfy Cloud, falls through to + * the library check. + */ +function deferToReleaseOptions( + candidate: MissingModelCandidate, + target: ModelWidgetScanTarget, + releaseModelOptions: ReleaseModelOptions | undefined +): void { + if (!releaseModelOptions) return + pendingVerifications.set(candidate, async (signal) => { + const options = await releaseModelOptions( + target.nodeType, + target.definitionWidgetName, + signal + ) + return options?.includes(candidate.name) ? false : undefined + }) +} + function scanAssetWidget( target: ModelWidgetScanTarget & { definitionWidget: IAssetWidget }, - getDirectory: ((nodeType: string) => string | undefined) | undefined + getDirectory: ((nodeType: string) => string | undefined) | undefined, + releaseModelOptions: ReleaseModelOptions | undefined ): MissingModelCandidate | null { const value = target.valueWidget.value if (typeof value !== 'string' || !value.trim()) return null if (!isModelFileName(value)) return null - return { + const candidate: MissingModelCandidate = { nodeId: target.executionId, ...(target.sourceExecutionId && { sourceExecutionId: target.sourceExecutionId @@ -318,12 +362,15 @@ function scanAssetWidget( directory: getDirectory?.(target.nodeType), isMissing: undefined } + deferToReleaseOptions(candidate, target, releaseModelOptions) + return candidate } function scanComboWidget( target: ModelWidgetScanTarget & { definitionWidget: IComboWidget }, isAssetSupported: (nodeType: string, widgetName: string) => boolean, - getDirectory: ((nodeType: string) => string | undefined) | undefined + getDirectory: ((nodeType: string) => string | undefined) | undefined, + releaseModelOptions: ReleaseModelOptions | undefined ): MissingModelCandidate | null { const value = target.valueWidget.value if (typeof value !== 'string' || !value.trim()) return null @@ -345,7 +392,10 @@ function scanComboWidget( directory: getDirectory?.(target.nodeType), isMissing: undefined } - if (nodeIsAssetSupported) return candidate + if (nodeIsAssetSupported) { + deferToReleaseOptions(candidate, target, releaseModelOptions) + return candidate + } const isAbsentFromOptions = () => !resolveComboValues(target.definitionWidget).includes(value) diff --git a/src/platform/missingModel/releaseModelOptions.test.ts b/src/platform/missingModel/releaseModelOptions.test.ts new file mode 100644 index 00000000000..1d45c9e69db --- /dev/null +++ b/src/platform/missingModel/releaseModelOptions.test.ts @@ -0,0 +1,188 @@ +import { fromAny, fromPartial } from '@total-typescript/shoehorn' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + cloudReleaseModelOptions, + releaseModelOptions +} from '@/platform/missingModel/releaseModelOptions' +import { + DEPLOYMENT_LISTING_BACKSTOP_MS, + DEPLOYMENT_LISTING_TIMEOUT_MS +} from '@/platform/workspace/api/deploymentListingTimeouts' +import type { WorkspaceDeploymentList } from '@/platform/workspace/api/workspaceApi' +import { workspaceApi } from '@/platform/workspace/api/workspaceApi' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { useNodeDefStore } from '@/stores/nodeDefStore' + +const distribution = vi.hoisted(() => ({ isCloud: false })) + +vi.mock(import('@/platform/distribution/types'), () => ({ + get DISTRIBUTION() { + return distribution.isCloud ? 'cloud' : 'localhost' + }, + isDesktop: false, + get isCloud() { + return distribution.isCloud + }, + isNightly: false +})) + +const deployment = { + deployment_id: 'dep-2', + release_id: 'r-2', + status: 'ready', + created_at: '2026-10-01T00:00:00Z' +} + +const bootListing: WorkspaceDeploymentList = { + builds_visible: true, + picked_deployment_id: deployment.deployment_id, + pick_source: 'browser', + items: [deployment] +} + +function loadCatalog() { + const nodeDefStore = useNodeDefStore() + nodeDefStore.nodeDefsByName = { + LoraLoader: fromPartial<(typeof nodeDefStore.nodeDefsByName)[string]>({ + inputs: { + lora_name: { + type: 'COMBO', + name: 'lora_name', + options: ['homestead_private_v1.safetensors'] + }, + strength_model: { type: 'FLOAT', name: 'strength_model' } + } + }) + } +} + +describe('releaseModelOptions', () => { + it.for([ + { + booted: 'a deployment', + bootDeployment: deployment, + input: 'lora_name', + options: ['homestead_private_v1.safetensors'] + }, + { + booted: 'a deployment', + bootDeployment: deployment, + input: 'strength_model', + options: undefined + }, + { + booted: 'Comfy Cloud', + bootDeployment: null, + input: 'lora_name', + options: undefined + } + ])( + 'gives the $input options of the catalog the page booted on $booted', + async ({ bootDeployment, input, options }) => { + loadCatalog() + useDeploymentPickStore().$patch({ bootDeployment }) + + await expect(releaseModelOptions('LoraLoader', input)).resolves.toEqual( + options + ) + } + ) + + it('checks the library as on Comfy Cloud once the backstop passes when the listing never answers', async () => { + loadCatalog() + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-1' }) + vi.spyOn(workspaceApi, 'listDeployments').mockReturnValue( + new Promise(() => {}) + ) + let options: readonly (string | number)[] | undefined | 'pending' = + 'pending' + void releaseModelOptions('LoraLoader', 'lora_name').then((result) => { + options = result + }) + + await vi.advanceTimersByTimeAsync(DEPLOYMENT_LISTING_BACKSTOP_MS - 1) + expect(options).toBe('pending') + await vi.advanceTimersByTimeAsync(1) + expect(options).toBeUndefined() + }) + + it('waits for a listing that answers just inside the request timeout', async () => { + loadCatalog() + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-1' }) + vi.spyOn(workspaceApi, 'listDeployments').mockReturnValue( + new Promise((resolve) => + setTimeout( + () => resolve(bootListing), + DEPLOYMENT_LISTING_TIMEOUT_MS - 1 + ) + ) + ) + const options = releaseModelOptions('LoraLoader', 'lora_name') + + await vi.advanceTimersByTimeAsync(DEPLOYMENT_LISTING_TIMEOUT_MS) + + await expect(options).resolves.toEqual(['homestead_private_v1.safetensors']) + }) + it.for([ + { + listing: 'fails', + answer: () => Promise.reject(new Error('timeout of 30000ms exceeded')) + }, + { + listing: 'cannot be read', + answer: () => + Promise.resolve( + fromAny({ builds_visible: true }) + ) + } + ])( + 'checks the library as on Comfy Cloud when the listing $listing', + async ({ answer }) => { + loadCatalog() + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-1' }) + vi.spyOn(workspaceApi, 'listDeployments').mockImplementation(answer) + + await expect( + releaseModelOptions('LoraLoader', 'lora_name') + ).resolves.toBeUndefined() + } + ) + + it('gives up at once when the check is aborted before the listing answers', async () => { + loadCatalog() + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-1' }) + vi.spyOn(workspaceApi, 'listDeployments').mockReturnValue( + new Promise(() => {}) + ) + const controller = new AbortController() + + const options = releaseModelOptions( + 'LoraLoader', + 'lora_name', + controller.signal + ) + controller.abort() + + await expect(options).resolves.toBeUndefined() + }) +}) + +describe('cloudReleaseModelOptions', () => { + afterEach(() => { + distribution.isCloud = false + }) + + it.for([ + { runsOn: 'Comfy Cloud', isCloud: true, gives: releaseModelOptions }, + { runsOn: 'Local', isCloud: false, gives: undefined } + ])( + 'gives releaseModelOptions only on Comfy Cloud: on $runsOn', + ({ isCloud, gives }) => { + distribution.isCloud = isCloud + + expect(cloudReleaseModelOptions()).toBe(gives) + } + ) +}) diff --git a/src/platform/missingModel/releaseModelOptions.ts b/src/platform/missingModel/releaseModelOptions.ts new file mode 100644 index 00000000000..1c81422a0f0 --- /dev/null +++ b/src/platform/missingModel/releaseModelOptions.ts @@ -0,0 +1,62 @@ +import { isCloud } from '@/platform/distribution/types' +import type { ReleaseModelOptions } from '@/platform/missingModel/missingModelScan' +import { DEPLOYMENT_LISTING_BACKSTOP_MS } from '@/platform/workspace/api/deploymentListingTimeouts' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' +import { isComboInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2' +import { useNodeDefStore } from '@/stores/nodeDefStore' + +/** + * A loader input's model options in the node catalog this page booted with, + * when it booted on a developer-platform deployment (FE-2434): ingest served + * that catalog from the deployment's Release. Waits for the boot listing + * that says where the page runs, at most `DEPLOYMENT_LISTING_BACKSTOP_MS` + * (its sign-in step can hang before the request timeout starts), or until + * `signal` aborts; undefined on Comfy Cloud, when the listing failed or did + * not answer in time, and when the check was aborted. + */ +export const releaseModelOptions: ReleaseModelOptions = async ( + nodeType, + widgetName, + signal +) => { + const deploymentPick = useDeploymentPickStore() + await settledWithin( + deploymentPick.loadOnce(), + DEPLOYMENT_LISTING_BACKSTOP_MS, + signal + ) + if (signal?.aborted || !deploymentPick.bootDeployment) return undefined + const input = useNodeDefStore().getNodeDefByName(nodeType)?.inputs[widgetName] + return input && isComboInputSpec(input) ? input.options : undefined +} + +/** + * `releaseModelOptions` where the page can boot on a deployment (Comfy + * Cloud), undefined elsewhere so a scan never waits on the listing. + */ +export function cloudReleaseModelOptions(): ReleaseModelOptions | undefined { + return isCloud ? releaseModelOptions : undefined +} + +/** + * Resolves once `work` settles, `ceilingMs` passes or `signal` aborts; never + * rejects. + */ +function settledWithin( + work: Promise, + ceilingMs: number, + signal?: AbortSignal +): Promise { + if (signal?.aborted) return Promise.resolve() + return new Promise((resolve) => { + const ceiling = setTimeout(done, ceilingMs) + signal?.addEventListener('abort', done, { once: true }) + work.then(done, done) + + function done() { + clearTimeout(ceiling) + signal?.removeEventListener('abort', done) + resolve() + } + }) +} diff --git a/src/platform/navigation/preservedQueryDefinitions.test.ts b/src/platform/navigation/preservedQueryDefinitions.test.ts index 40c69f2f6fb..8844dd65c8e 100644 --- a/src/platform/navigation/preservedQueryDefinitions.test.ts +++ b/src/platform/navigation/preservedQueryDefinitions.test.ts @@ -20,7 +20,9 @@ describe('PRESERVED_QUERY_DEFINITIONS', () => { [PRESERVED_QUERY_NAMESPACES.TOPUP, 'topup'], [PRESERVED_QUERY_NAMESPACES.INVITE, 'invite'], [PRESERVED_QUERY_NAMESPACES.CREATE_WORKSPACE, 'create_workspace'], - [PRESERVED_QUERY_NAMESPACES.PRICING, 'pricing'] + [PRESERVED_QUERY_NAMESPACES.PRICING, 'pricing'], + [PRESERVED_QUERY_NAMESPACES.WORKSPACE, 'workspace'], + [PRESERVED_QUERY_NAMESPACES.DEPLOYMENT, 'deployment'] ])('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 2975260ff1e..ab98105c089 100644 --- a/src/platform/navigation/preservedQueryDefinitions.ts +++ b/src/platform/navigation/preservedQueryDefinitions.ts @@ -55,5 +55,10 @@ export const PRESERVED_QUERY_DEFINITIONS: PreservedQueryDefinition[] = [ namespace: PRESERVED_QUERY_NAMESPACES.WORKSPACE, keys: ['workspace'], rejectRepeated: true + }, + { + namespace: PRESERVED_QUERY_NAMESPACES.DEPLOYMENT, + keys: ['deployment'], + rejectRepeated: true } ] diff --git a/src/platform/navigation/preservedQueryNamespaces.ts b/src/platform/navigation/preservedQueryNamespaces.ts index 0ea79e6293f..0bdee02890b 100644 --- a/src/platform/navigation/preservedQueryNamespaces.ts +++ b/src/platform/navigation/preservedQueryNamespaces.ts @@ -10,5 +10,6 @@ export const PRESERVED_QUERY_NAMESPACES = { SETTINGS: 'settings', ASSETS: 'assets', DESKTOP_LOGIN: 'desktop_login', - WORKSPACE: 'workspace' + WORKSPACE: 'workspace', + DEPLOYMENT: 'deployment' } as const diff --git a/src/platform/workspace/__fixtures__/deploymentListing.ts b/src/platform/workspace/__fixtures__/deploymentListing.ts new file mode 100644 index 00000000000..ef4350b9f28 --- /dev/null +++ b/src/platform/workspace/__fixtures__/deploymentListing.ts @@ -0,0 +1,16 @@ +import { vi } from 'vitest' + +import type { WorkspaceDeploymentList } from '@/platform/workspace/api/workspaceApi' + +import { workspaceApi } from '@/platform/workspace/api/workspaceApi' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' + +vi.mock(import('@/platform/workspace/api/workspaceApi')) + +export function mockDeploymentListing( + listing: WorkspaceDeploymentList, + workspaceId = 'ws-1' +) { + Object.assign(useTeamWorkspaceStore(), { workspaceId }) + vi.mocked(workspaceApi.listDeployments).mockResolvedValue(listing) +} diff --git a/src/platform/workspace/api/__mocks__/workspaceApi.ts b/src/platform/workspace/api/__mocks__/workspaceApi.ts index 956e326e5f9..010577271c5 100644 --- a/src/platform/workspace/api/__mocks__/workspaceApi.ts +++ b/src/platform/workspace/api/__mocks__/workspaceApi.ts @@ -39,6 +39,11 @@ export const workspaceApi = vi.mockObject( created_at: '2026-01-01T00:00:00Z', joined_at: '2026-01-01T00:00:00Z' }), + listDeployments: async () => ({ items: [], builds_visible: true }), + pickDeployment: async () => {}, + clearDeployment: async () => {}, + setDefaultDeployment: async () => {}, + clearDefaultDeployment: async () => {}, delete: async () => {}, leave: async () => {}, listMembers: async () => ({ diff --git a/src/platform/workspace/api/deploymentListingTimeouts.ts b/src/platform/workspace/api/deploymentListingTimeouts.ts new file mode 100644 index 00000000000..a366f4d6b06 --- /dev/null +++ b/src/platform/workspace/api/deploymentListingTimeouts.ts @@ -0,0 +1,17 @@ +/** + * How long the deployment listing request may take once sent. Ingest + * answers it with several upstream calls in a row (deployments, builds, + * then each Build's Releases). + */ +export const DEPLOYMENT_LISTING_TIMEOUT_MS = 30_000 + +/** + * How long the editor's missing-model check waits for the boot listing + * before it checks the library as on Comfy Cloud. The request timeout only + * starts once the sign-in step before it has answered, and that step can + * hang (the token exchange is a plain fetch), so this ceiling sits above + * it: a listing that answers within the request timeout is still waited + * for, and a hung sign-in never holds the check forever. + */ +export const DEPLOYMENT_LISTING_BACKSTOP_MS = + DEPLOYMENT_LISTING_TIMEOUT_MS + 15_000 diff --git a/src/platform/workspace/api/workspaceApi.test.ts b/src/platform/workspace/api/workspaceApi.test.ts index 67440ca8544..7a4ec51d9c3 100644 --- a/src/platform/workspace/api/workspaceApi.test.ts +++ b/src/platform/workspace/api/workspaceApi.test.ts @@ -12,6 +12,7 @@ const { mockAxiosInstance } = vi.hoisted(() => ({ mockAxiosInstance: { get: vi.fn(), post: vi.fn(), + put: vi.fn(), patch: vi.fn(), delete: vi.fn(), interceptors: { response: { use: vi.fn() } } @@ -351,6 +352,111 @@ describe('workspaceApi', () => { }) }) + describe('deployment picking', () => { + it('listDeployments() sends GET /workspaces/:id/deployments with a 30 second timeout', async () => { + const data = { items: [], builds_visible: true } + mockAxiosInstance.get.mockResolvedValue({ data }) + + const result = await workspaceApi.listDeployments('ws-1') + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/api/workspaces/ws-1/deployments', + { headers: AUTH_HEADER, timeout: 30_000 } + ) + expect(result).toEqual(data) + }) + + it('pickDeployment() sends PUT /workspaces/:id/deployment with the deployment', async () => { + mockAxiosInstance.put.mockResolvedValue({}) + + await workspaceApi.pickDeployment('ws-1', { deployment_id: 'dep-1' }) + + expect(mockAxiosInstance.put).toHaveBeenCalledWith( + '/api/workspaces/ws-1/deployment', + { deployment_id: 'dep-1' }, + { headers: AUTH_HEADER } + ) + }) + + it('does not dispatch a canceled deployment selection when authorization finishes late', async () => { + let finishAuth!: (headers: typeof AUTH_HEADER) => void + const auth = new Promise((resolve) => { + finishAuth = resolve + }) + vi.mocked(useAuthStore().getWorkspaceAuthHeaderOrThrow).mockReturnValue( + auth + ) + const controller = new AbortController() + const selected = workspaceApi.pickDeployment( + 'ws-1', + { deployment_id: 'dep-1' }, + controller.signal + ) + controller.abort() + finishAuth(AUTH_HEADER) + await expect(selected).rejects.toMatchObject({ name: 'AbortError' }) + expect(mockAxiosInstance.put).not.toHaveBeenCalled() + }) + + it('forwards deployment selection cancellation to the transport', async () => { + mockAxiosInstance.put.mockResolvedValue({}) + const controller = new AbortController() + await workspaceApi.pickDeployment( + 'ws-1', + { deployment_id: 'dep-1' }, + controller.signal + ) + expect(mockAxiosInstance.put).toHaveBeenCalledWith( + '/api/workspaces/ws-1/deployment', + { deployment_id: 'dep-1' }, + { headers: AUTH_HEADER, signal: controller.signal } + ) + }) + + it('clearDeployment() sends DELETE /workspaces/:id/deployment, with follow=workspace only when asked', async () => { + mockAxiosInstance.delete.mockResolvedValue({}) + + await workspaceApi.clearDeployment('ws-1') + await workspaceApi.clearDeployment('ws-1', { follow: 'workspace' }) + + expect(mockAxiosInstance.delete).toHaveBeenNthCalledWith( + 1, + '/api/workspaces/ws-1/deployment', + { headers: AUTH_HEADER, params: undefined } + ) + expect(mockAxiosInstance.delete).toHaveBeenNthCalledWith( + 2, + '/api/workspaces/ws-1/deployment', + { headers: AUTH_HEADER, params: { follow: 'workspace' } } + ) + }) + + it('setDefaultDeployment() sends PUT /workspaces/:id/default-deployment with the deployment', async () => { + mockAxiosInstance.put.mockResolvedValue({}) + + await workspaceApi.setDefaultDeployment('ws-1', { + deployment_id: 'dep-1' + }) + + expect(mockAxiosInstance.put).toHaveBeenCalledWith( + '/api/workspaces/ws-1/default-deployment', + { deployment_id: 'dep-1' }, + { headers: AUTH_HEADER } + ) + }) + + it('clearDefaultDeployment() sends DELETE /workspaces/:id/default-deployment', async () => { + mockAxiosInstance.delete.mockResolvedValue({}) + + await workspaceApi.clearDefaultDeployment('ws-1') + + expect(mockAxiosInstance.delete).toHaveBeenCalledWith( + '/api/workspaces/ws-1/default-deployment', + { headers: AUTH_HEADER } + ) + }) + }) + describe('member management', () => { it('listMembers() sends GET with params', async () => { const data = { diff --git a/src/platform/workspace/api/workspaceApi.ts b/src/platform/workspace/api/workspaceApi.ts index 2ddf2200a95..70f9995b60c 100644 --- a/src/platform/workspace/api/workspaceApi.ts +++ b/src/platform/workspace/api/workspaceApi.ts @@ -21,6 +21,7 @@ import type { PaymentPortalRequest, PaymentPortalResponse, PendingInvite, + PickWorkspaceDeploymentRequest, Plan, PreviewSubscribeRequest, PreviewSubscribeResponse, @@ -40,6 +41,8 @@ import type { TeamCreditStops, TeamCreditStopSummary, UpdateWorkspaceRequest, + WorkspaceDeployment, + WorkspaceDeploymentList, WorkspaceWithRole } from '@comfyorg/ingest-types' import { @@ -59,6 +62,7 @@ import { errorResponseFromBody } from '@/platform/remote/comfyui/errors' import { attachCapabilityRevisionInterceptor } from '@/platform/workspace/api/capabilityRevision' +import { DEPLOYMENT_LISTING_TIMEOUT_MS } from '@/platform/workspace/api/deploymentListingTimeouts' import type { WorkspaceId, WorkspaceInviteId @@ -156,6 +160,9 @@ export type BillingRecoveryAction = NonNullable< BillingOpStatusResponse['recovery_action'] > +export type { WorkspaceDeployment } +export type { WorkspaceDeploymentList } + interface GetBillingEventsParams { page?: number limit?: number @@ -306,6 +313,114 @@ export const workspaceApi = { } }, + /** + * List the developer-platform deployments this browser may pick, each + * with the Release it runs now, and which one it picked. 403 when the account is outside the rollout. + * Times out `DEPLOYMENT_LISTING_TIMEOUT_MS` after it is sent; the + * sign-in step before it is not covered and can hang. + * GET /api/workspaces/:id/deployments + */ + async listDeployments( + workspaceId: WorkspaceId + ): Promise { + const auth = await requestAuth() + try { + const response = await workspaceApiClient.get( + workspaceApiUrl(`/workspaces/${workspaceId}/deployments`), + { ...auth, timeout: DEPLOYMENT_LISTING_TIMEOUT_MS } + ) + return response.data + } catch (err) { + handleAxiosError(err, 'listDeployments') + } + }, + + /** + * Pick the deployment this browser runs on; it follows the deployment's + * updates to new Releases. The pick is a cookie on the + * response; nothing about the workspace changes. + * PUT /api/workspaces/:id/deployment + */ + async pickDeployment( + workspaceId: WorkspaceId, + payload: PickWorkspaceDeploymentRequest, + signal?: AbortSignal + ): Promise { + const auth = await requestAuth() + signal?.throwIfAborted() + try { + await workspaceApiClient.put( + workspaceApiUrl(`/workspaces/${workspaceId}/deployment`), + payload, + { ...auth, ...(signal ? { signal } : {}) } + ) + } catch (err) { + handleAxiosError(err, 'pickDeployment') + } + }, + + /** + * Clear the pick: this browser runs on Comfy Cloud, or with + * `follow: 'workspace'` on whatever the workspace says (its default + * deployment, or Comfy Cloud when it has none). + * DELETE /api/workspaces/:id/deployment + */ + async clearDeployment( + workspaceId: WorkspaceId, + options: { follow?: 'workspace' } = {} + ): Promise { + const auth = await requestAuth() + try { + await workspaceApiClient.delete( + workspaceApiUrl(`/workspaces/${workspaceId}/deployment`), + { + ...auth, + params: options.follow ? { follow: options.follow } : undefined + } + ) + } catch (err) { + handleAxiosError(err, 'clearDeployment') + } + }, + + /** + * Set the deployment members of the workspace run on when their browser has + * no pick of its own (BE-17480). Owner only. + * PUT /api/workspaces/:id/default-deployment + */ + async setDefaultDeployment( + workspaceId: WorkspaceId, + payload: PickWorkspaceDeploymentRequest + ): Promise { + const auth = await requestAuth() + try { + await workspaceApiClient.put( + workspaceApiUrl(`/workspaces/${workspaceId}/default-deployment`), + payload, + auth + ) + } catch (err) { + handleAxiosError(err, 'setDefaultDeployment') + } + }, + + /** + * Clear the workspace's default deployment; members with no pick are back on + * Comfy Cloud. Owner only. + * DELETE /api/workspaces/:id/default-deployment + */ + async clearDefaultDeployment(workspaceId: WorkspaceId): Promise { + const auth = await requestAuth() + try { + await workspaceApiClient.delete( + workspaceApiUrl(`/workspaces/${workspaceId}/default-deployment`), + auth + ) + } catch (err) { + handleAxiosError(err, 'clearDefaultDeployment') + } + }, + /** * Delete a workspace (owner only) * DELETE /api/workspaces/:id diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index 84e9fb1db53..0c9d08149a1 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts @@ -103,6 +103,10 @@ const WorkspaceSwitcherPopoverStub = defineComponent({ ` }) +const DeploymentSwitcherStub = defineComponent({ + template: '
' +}) + const SubscribeButtonStub = defineComponent({ props: { label: { type: String, required: true } @@ -135,7 +139,8 @@ function renderComponent( WorkspaceSwitcherPopover: WorkspaceSwitcherPopoverStub, SubscribeButton: SubscribeButtonStub, WorkspaceProfilePic: true, - Divider: true + Divider: true, + DeploymentSwitcher: DeploymentSwitcherStub } } }) @@ -304,6 +309,19 @@ describe('CurrentUserPopoverWorkspace', () => { }) }) + it('shows the deployment switcher on Cloud', () => { + renderComponent() + + expect(screen.getByTestId('deployment-switcher')).toBeInTheDocument() + }) + + it('does not show the deployment switcher on Local', () => { + state.isCloud = false + renderComponent() + + expect(screen.queryByTestId('deployment-switcher')).not.toBeInTheDocument() + }) + it('exposes the full workspace name on hover', async () => { const user = userEvent.setup() renderComponent('team') diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue index b377a4f7fa1..f0dfbc3eab3 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -88,6 +88,13 @@
+ + +
@@ -262,6 +269,7 @@ import { useI18n } from 'vue-i18n' import { formatCreditsFromCents } from '@/base/credits/comfyCredits' import UserAvatar from '@/components/common/UserAvatar.vue' import WorkspaceProfilePic from '@/platform/workspace/components/WorkspaceProfilePic.vue' +import DeploymentSwitcher from '@/platform/workspace/components/DeploymentSwitcher.vue' import WorkspaceSwitcherPopover from '@/platform/workspace/components/WorkspaceSwitcherPopover.vue' import Button from '@/components/ui/button/Button.vue' import Skeleton from '@/components/ui/skeleton/Skeleton.vue' diff --git a/src/platform/workspace/components/DeploymentSwitcher.stories.ts b/src/platform/workspace/components/DeploymentSwitcher.stories.ts new file mode 100644 index 00000000000..07f8ca8f90f --- /dev/null +++ b/src/platform/workspace/components/DeploymentSwitcher.stories.ts @@ -0,0 +1,211 @@ +import type { Meta, StoryObj } from '@storybook/vue3-vite' + +import type { WorkspaceDeployment } from '@/platform/workspace/api/workspaceApi' +import type { DeploymentPickState } from '@/platform/workspace/deploymentPickState' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' + +import DeploymentSwitcher from './DeploymentSwitcher.vue' + +/** + * The deployment switcher under the workspace selector in the user popover: + * which developer-platform deployment this browser runs its Cloud jobs on, + * and the list it may pick from. Each row is titled by the deployment's name, + * with the Build and Release it runs now in its caption; a pick follows the deployment when its owner updates it. Each story seeds the store's state directly; the + * Storybook team-workspace stub has no active workspace, so the store never + * calls the listing route here. Click the trigger to open the panel. + */ +const meta: Meta = { + title: 'Components/DeploymentSwitcher', + component: DeploymentSwitcher, + tags: ['autodocs'], + parameters: { layout: 'centered' }, + decorators: [ + (story) => ({ + components: { story }, + template: + '
' + }) + ] +} + +export default meta +type Story = StoryObj + +const studioProd: WorkspaceDeployment = { + deployment_id: 'dep-f24d36bb-fd1f-4cd7-bfa9-fe015b5cd33d', + deployment_name: 'Studio production', + release_id: '6f1c2b0e-3c4d-4e5f-8a9b-0c1d2e3f4a5b', + build_id: 'b-1', + build_name: 'Studio Build', + release_version: 2, + status: 'ready', + created_at: '2026-09-16T18:00:00Z' +} + +const studioStaging: WorkspaceDeployment = { + deployment_id: 'dep-0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d', + deployment_name: 'Studio staging', + release_id: 'c4a8e2f0-5b6c-4d7e-8f90-1a2b3c4d5e6f', + build_id: 'b-1', + build_name: 'Studio Build', + release_version: 3, + status: 'starting', + created_at: '2026-09-12T09:30:00Z' +} + +const experiments: WorkspaceDeployment = { + deployment_id: 'dep-c0ffee00-1111-4222-8333-444455556666', + release_id: 'c0ffee00-1111-4222-8333-444455556666', + build_id: 'b-2', + build_name: 'Experiments', + release_version: 3, + status: 'stopped', + created_at: '2026-09-15T12:00:00Z' +} + +// The store is seeded from a component's setup(), where the app's Pinia is +// injected; a story beforeEach runs before any component and has no active +// Pinia. +function seeded(state: DeploymentPickState): Story { + return { + decorators: [ + (story) => ({ + components: { story }, + setup() { + useDeploymentPickStore().state = state + }, + template: '' + }) + ] + } +} + +/** Nothing picked: this browser runs on Comfy Cloud. */ +export const Default: Story = seeded({ + phase: 'ready', + deployments: [studioProd, experiments, studioStaging], + pickedDeploymentId: null, + pickSource: null, + defaultDeploymentId: null, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true +}) + +/** A deployment picked; the trigger names it. */ +export const Picked: Story = seeded({ + phase: 'ready', + deployments: [studioProd, experiments, studioStaging], + pickedDeploymentId: studioProd.deployment_id, + pickSource: 'browser', + defaultDeploymentId: null, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true +}) + +/** + * An owner set a workspace default (BE-17480) and this browser has no pick + * of its own, so it follows it; the trigger says so. + */ +export const FollowingWorkspaceDefault: Story = seeded({ + phase: 'ready', + deployments: [studioProd, experiments, studioStaging], + pickedDeploymentId: studioProd.deployment_id, + pickSource: 'workspace_default', + defaultDeploymentId: studioProd.deployment_id, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true +}) + +/** + * This browser picked for itself while the workspace has a default: the + * panel offers the default as a row to go back to. + */ +export const OwnPickOverWorkspaceDefault: Story = seeded({ + phase: 'ready', + deployments: [studioProd, experiments, studioStaging], + pickedDeploymentId: experiments.deployment_id, + pickSource: 'browser', + defaultDeploymentId: studioProd.deployment_id, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true +}) + +/** + * The workspace default this browser followed is gone (deleted, or no + * longer the workspace's): ingest serves Comfy Cloud, and the trigger says why. + */ +export const DefaultGone: Story = seeded({ + phase: 'ready', + deployments: [studioProd, experiments], + pickedDeploymentId: null, + pickSource: null, + defaultDeploymentId: null, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: studioStaging.deployment_id, + buildsVisible: true +}) + +/** A workspace with no deployments yet. */ +export const Empty: Story = seeded({ + phase: 'ready', + deployments: [], + pickedDeploymentId: null, + pickSource: null, + defaultDeploymentId: null, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true +}) + +/** + * comfy-builder refused the caller (its routes sit behind the Builds beta): + * the deployments are listed by name without their Build and Release, an + * unnamed one by id, and the panel says why. + */ +export const BuildsHidden: Story = seeded({ + phase: 'ready', + deployments: [ + { + deployment_id: studioProd.deployment_id, + deployment_name: studioProd.deployment_name, + release_id: studioProd.release_id, + status: 'ready', + created_at: studioProd.created_at + }, + { + deployment_id: experiments.deployment_id, + release_id: experiments.release_id, + status: 'stopped', + created_at: experiments.created_at + } + ], + pickedDeploymentId: studioProd.deployment_id, + pickSource: 'browser', + defaultDeploymentId: null, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: false +}) + +export const NamedDeployments: Story = seeded({ + phase: 'ready', + deployments: [ + { ...studioProd, deployment_name: 'Agency A production' }, + { + ...studioProd, + deployment_id: studioStaging.deployment_id, + deployment_name: 'Agency A staging' + }, + experiments + ], + pickedDeploymentId: studioProd.deployment_id, + pickSource: 'workspace_default', + defaultDeploymentId: studioProd.deployment_id, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true +}) diff --git a/src/platform/workspace/components/DeploymentSwitcher.test.ts b/src/platform/workspace/components/DeploymentSwitcher.test.ts new file mode 100644 index 00000000000..9b9f998b423 --- /dev/null +++ b/src/platform/workspace/components/DeploymentSwitcher.test.ts @@ -0,0 +1,711 @@ +import { render, screen, waitFor, within } from '@testing-library/vue' +import userEvent from '@testing-library/user-event' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { nextTick } from 'vue' +import { createI18n } from 'vue-i18n' + +import type { WorkspaceDeploymentList } from '@/platform/workspace/api/workspaceApi' + +import enMessages from '@/locales/en/main.json' +import { useToast } from '@/components/ui/toast/toastStore' +import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' + +import DeploymentSwitcher from './DeploymentSwitcher.vue' + +const mockWorkspaceApi = vi.hoisted(() => ({ + listDeployments: vi.fn(), + pickDeployment: vi.fn(), + clearDeployment: vi.fn(), + setDefaultDeployment: vi.fn(), + clearDefaultDeployment: vi.fn() +})) + +vi.mock(import('@/platform/workspace/api/workspaceApi'), async () => { + class WorkspaceApiError extends Error { + constructor( + message: string, + public readonly status?: number, + public readonly code?: string + ) { + super(message) + this.name = 'WorkspaceApiError' + } + } + return { workspaceApi: mockWorkspaceApi, WorkspaceApiError } +}) + +const i18n = createI18n({ + legacy: false, + locale: 'en', + messages: { en: enMessages } +}) + +const D2 = 'dep-a2a2a2a2-0000-4000-8000-000000000002' +const D1 = 'dep-a1a1a1a1-0000-4000-8000-000000000001' +const D9 = 'dep-b9b9b9b9-0000-4000-8000-000000000009' +const GONE = 'dep-0e0e0e0e-0000-4000-8000-0000000000a2' + +const listing: WorkspaceDeploymentList = { + builds_visible: true, + items: [ + { + deployment_id: D2, + release_id: 'r-2', + build_id: 'b-1', + build_name: 'Studio Build', + release_version: 2, + status: 'ready', + created_at: '2026-10-01T00:00:00Z' + }, + { + deployment_id: D1, + release_id: 'r-1', + build_id: 'b-1', + build_name: 'Studio Build', + release_version: 1, + status: 'stopped', + created_at: '2026-09-20T00:00:00Z' + }, + { + deployment_id: D9, + release_id: 'r-9', + status: 'stopped', + created_at: '2026-09-10T00:00:00Z' + } + ] +} + +function renderSwitcher() { + return render(DeploymentSwitcher, { + global: { + plugins: [i18n] + } + }) +} + +describe('DeploymentSwitcher', () => { + const reload = vi.fn() + + beforeEach(() => { + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-1' }) + Object.defineProperty(window, 'location', { + value: { reload, origin: 'http://localhost' }, + writable: true, + configurable: true + }) + }) + + it('distinguishes two named deployments on one Release and renders names as plain text', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: D2, + items: [ + { + ...listing.items[0], + deployment_name: "Studio's production & R&D" + }, + { ...listing.items[0], deployment_id: D1, deployment_name: 'staging' } + ] + }) + renderSwitcher() + const trigger = await screen.findByTestId('deployment-switcher-trigger') + expect(screen.getByTestId('deployment-switcher-current')).toHaveTextContent( + "Studio's production & R&D" + ) + await userEvent.click(trigger) + expect( + within(screen.getByTestId(`deployment-row-${D2}`)).getByText( + "Studio's production & R&D" + ) + ).toBeVisible() + expect( + within(screen.getByTestId(`deployment-row-${D1}`)).getByText('staging') + ).toBeVisible() + expect(screen.getByTestId(`deployment-row-${D2}`)).toHaveTextContent( + 'Studio Build v2 · dep-a2a2a2a2, ready' + ) + expect(screen.getByTestId(`deployment-row-${D1}`)).toHaveTextContent( + 'Studio Build v2 · dep-a1a1a1a1, ready' + ) + }) + + it('renders nothing when the account is outside the rollout', async () => { + mockWorkspaceApi.listDeployments.mockRejectedValue( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + renderSwitcher() + await waitFor(() => + expect(useDeploymentPickStore().state.phase).toBe('hidden') + ) + expect(mockWorkspaceApi.listDeployments).toHaveBeenCalledWith('ws-1') + expect(screen.queryByTestId('deployment-switcher')).toBeNull() + }) + + it('says Comfy Cloud when nothing is picked, and lists the deployments', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + renderSwitcher() + + await waitFor(() => + expect( + screen.getByTestId('deployment-switcher-current') + ).toHaveTextContent('Comfy Cloud') + ) + await userEvent.click(screen.getByTestId('deployment-switcher-trigger')) + + const panel = screen.getByTestId('deployment-switcher-panel') + expect(panel).toHaveTextContent('Studio Build v2') + expect(panel).toHaveTextContent('dep-a2a2a2a2, ready') + expect(panel).toHaveTextContent('Studio Build v1') + expect(panel).toHaveTextContent('dep-a1a1a1a1, stopped') + expect(panel).toHaveTextContent('Deployment dep-b9b9b9b9') + expect(screen.getByTestId('deployment-row-cloud')).toHaveAttribute( + 'aria-checked', + 'true' + ) + // A stopped deployment can still be picked; a job submitted to it is + // refused until it is ready. + expect(screen.getByTestId(`deployment-row-${D1}`)).not.toBeDisabled() + // Comfy Cloud with no workspace default: nothing to say it follows. + expect(screen.queryByTestId('deployment-switcher-following')).toBeNull() + expect(screen.queryByTestId('deployment-row-follow')).toBeNull() + }) + + it('shows the picked deployment by its Build and Release', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: D2 + }) + renderSwitcher() + await waitFor(() => + expect( + screen.getByTestId('deployment-switcher-current') + ).toHaveTextContent('Studio Build v2') + ) + }) + + const pickGone = 'The deployment you picked no longer exists.' + const defaultGone = "The workspace's default deployment no longer exists." + + it.for([ + { + gone: 'its own pick, with no default', + reply: { gone_picked_deployment_id: GONE }, + line: pickGone + }, + { + gone: 'its own pick, with a live default', + reply: { + pick_source: 'browser', + default_deployment_id: D1, + gone_picked_deployment_id: GONE + }, + line: pickGone + }, + { + gone: 'the default it follows', + reply: { gone_default_deployment_id: GONE }, + line: defaultGone + } + ] satisfies { + gone: string + reply: Partial + line: string + }[])( + 'says Comfy Cloud when $gone is gone, and offers it to no one', + async ({ reply, line }) => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + ...reply + }) + renderSwitcher() + + await waitFor(() => + expect( + screen.getByTestId('deployment-switcher-current') + ).toHaveTextContent('Comfy Cloud') + ) + expect(screen.getByTestId('deployment-switcher-gone')).toHaveTextContent( + line + ) + expect(screen.queryByTestId('deployment-switcher-following')).toBeNull() + await userEvent.click(screen.getByTestId('deployment-switcher-trigger')) + expect(screen.getByTestId('deployment-row-cloud')).toHaveAttribute( + 'aria-checked', + 'true' + ) + expect(screen.queryByTestId('deployment-switcher-set-default')).toBeNull() + } + ) + + it("does not tell an owner with a pick of its own that the default it doesn't follow is gone", async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: D2, + pick_source: 'browser', + gone_default_deployment_id: GONE + }) + renderSwitcher() + + await waitFor(() => + expect( + screen.getByTestId('deployment-switcher-current') + ).toHaveTextContent('Studio Build v2') + ) + expect(screen.queryByTestId('deployment-switcher-gone')).toBeNull() + }) + + it.for([ + { + change: 'its deployment now runs another Release', + boot: { ...listing, picked_deployment_id: D2, pick_source: 'browser' }, + next: { + ...listing, + picked_deployment_id: D2, + pick_source: 'browser', + items: [ + { ...listing.items[0], release_id: 'r-3', release_version: 3 }, + ...listing.items.slice(1) + ] + }, + text: 'This deployment now runs a different Release. Reload to get its nodes.' + }, + { + change: 'the workspace default it follows was cleared', + boot: { + ...listing, + picked_deployment_id: D2, + pick_source: 'workspace_default', + default_deployment_id: D2 + }, + next: listing, + text: 'This browser now runs on Comfy Cloud. Reload to get its nodes.' + } + ] satisfies { + change: string + boot: WorkspaceDeploymentList + next: WorkspaceDeploymentList + text: string + }[])( + 'offers a reload when $change since the page loaded', + async ({ boot, next, text }) => { + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce(boot) + .mockResolvedValue(next) + renderSwitcher() + await screen.findByTestId('deployment-switcher-trigger') + expect(screen.queryByTestId('deployment-switcher-changed')).toBeNull() + + await useDeploymentPickStore().load() + + expect( + await screen.findByTestId('deployment-switcher-changed') + ).toHaveTextContent(text) + await userEvent.click(screen.getByTestId('deployment-switcher-reload')) + expect(reload).toHaveBeenCalledOnce() + } + ) + + it('picks a deployment, which reloads the editor', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + mockWorkspaceApi.pickDeployment.mockResolvedValue(undefined) + renderSwitcher() + await userEvent.click( + await screen.findByTestId('deployment-switcher-trigger') + ) + + await userEvent.click(screen.getByTestId(`deployment-row-${D2}`)) + + expect(mockWorkspaceApi.pickDeployment).toHaveBeenCalledWith('ws-1', { + deployment_id: D2 + }) + await waitFor(() => expect(reload).toHaveBeenCalledOnce()) + }) + + it('goes back to Comfy Cloud through the clear route', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: D2 + }) + mockWorkspaceApi.clearDeployment.mockResolvedValue(undefined) + renderSwitcher() + await userEvent.click( + await screen.findByTestId('deployment-switcher-trigger') + ) + + await userEvent.click(screen.getByTestId('deployment-row-cloud')) + + expect(mockWorkspaceApi.clearDeployment).toHaveBeenCalledWith('ws-1') + await waitFor(() => expect(reload).toHaveBeenCalledOnce()) + }) + + it('renders nothing until the listing answers', async () => { + let resolve: (value: WorkspaceDeploymentList) => void = () => {} + mockWorkspaceApi.listDeployments.mockReturnValue( + new Promise((r) => { + resolve = r + }) + ) + renderSwitcher() + await nextTick() + expect(screen.queryByTestId('deployment-switcher')).toBeNull() + + resolve(listing) + expect( + await screen.findByTestId('deployment-switcher-current') + ).toHaveTextContent('Comfy Cloud') + }) + + it('renders nothing when the listing fails', async () => { + mockWorkspaceApi.listDeployments.mockRejectedValue( + new WorkspaceApiError('404 page not found', 404) + ) + renderSwitcher() + await waitFor(() => + expect(useDeploymentPickStore().state.phase).toBe('hidden') + ) + expect(screen.queryByTestId('deployment-switcher')).toBeNull() + }) + + it('disables the trigger while a pick is in flight', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + mockWorkspaceApi.pickDeployment.mockReturnValue(new Promise(() => {})) + renderSwitcher() + const trigger = await screen.findByTestId('deployment-switcher-trigger') + await userEvent.click(trigger) + expect(trigger).not.toBeDisabled() + + await userEvent.click(screen.getByTestId(`deployment-row-${D2}`)) + expect(trigger).toBeDisabled() + }) + + it("shows the server's refusal as a toast, does not reload, and lets the user pick again", async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + mockWorkspaceApi.pickDeployment.mockRejectedValue( + new WorkspaceApiError("deployment is not one of this workspace's", 422) + ) + renderSwitcher() + const trigger = await screen.findByTestId('deployment-switcher-trigger') + await userEvent.click(trigger) + await userEvent.click(screen.getByTestId(`deployment-row-${D2}`)) + + await waitFor(() => + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + kind: 'error', + description: "deployment is not one of this workspace's" + }) + ) + ) + expect(reload).not.toHaveBeenCalled() + expect(screen.queryByTestId('deployment-switcher-panel')).toBeNull() + expect(trigger).not.toBeDisabled() + }) + + it('says it follows the workspace default, and marks that deployment in the list', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: D2, + pick_source: 'workspace_default', + default_deployment_id: D2 + }) + renderSwitcher() + await waitFor(() => + expect( + screen.getByTestId('deployment-switcher-current') + ).toHaveTextContent('Studio Build v2') + ) + expect( + screen.getByTestId('deployment-switcher-following') + ).toHaveTextContent('Workspace default') + await userEvent.click(screen.getByTestId('deployment-switcher-trigger')) + expect(screen.getByTestId(`deployment-row-${D2}`)).toHaveTextContent( + 'Workspace default' + ) + expect(screen.queryByTestId('deployment-row-follow')).toBeNull() + expect(screen.queryByTestId('deployment-switcher-owner')).toBeNull() + }) + + it('offers a browser with its own pick the workspace default, which clears with follow=workspace', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + pick_source: 'browser', + default_deployment_id: D2 + }) + mockWorkspaceApi.clearDeployment.mockResolvedValue(undefined) + renderSwitcher() + await userEvent.click( + await screen.findByTestId('deployment-switcher-trigger') + ) + expect(screen.queryByTestId('deployment-switcher-following')).toBeNull() + + const follow = screen.getByTestId('deployment-row-follow') + expect(follow).toHaveTextContent('Studio Build v2') + await userEvent.click(follow) + + expect(mockWorkspaceApi.clearDeployment).toHaveBeenCalledWith('ws-1', { + follow: 'workspace' + }) + await waitFor(() => expect(reload).toHaveBeenCalledOnce()) + }) + + it('lets an owner set the picked deployment as the workspace default, and clear it', async () => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce({ + ...listing, + picked_deployment_id: D2, + pick_source: 'browser' + }) + .mockResolvedValue({ + ...listing, + picked_deployment_id: D2, + pick_source: 'browser', + default_deployment_id: D2 + }) + mockWorkspaceApi.setDefaultDeployment.mockResolvedValue(undefined) + mockWorkspaceApi.clearDefaultDeployment.mockResolvedValue(undefined) + renderSwitcher() + await userEvent.click( + await screen.findByTestId('deployment-switcher-trigger') + ) + + const owner = screen.getByTestId('deployment-switcher-owner') + expect(owner).toHaveTextContent('No workspace default') + expect(screen.queryByTestId('deployment-switcher-clear-default')).toBeNull() + await userEvent.click(screen.getByTestId('deployment-switcher-set-default')) + + expect(mockWorkspaceApi.setDefaultDeployment).toHaveBeenCalledWith('ws-1', { + deployment_id: D2 + }) + await waitFor(() => + expect(owner).toHaveTextContent('Workspace default: Studio Build v2') + ) + expect(reload).not.toHaveBeenCalled() + expect(screen.queryByTestId('deployment-switcher-set-default')).toBeNull() + + await userEvent.click( + screen.getByTestId('deployment-switcher-clear-default') + ) + expect(mockWorkspaceApi.clearDefaultDeployment).toHaveBeenCalledWith('ws-1') + }) + + it('lets an owner clear a workspace default that no longer exists', async () => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + const ownPick = { + ...listing, + picked_deployment_id: D2, + pick_source: 'browser' as const + } + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce({ ...ownPick, gone_default_deployment_id: GONE }) + .mockResolvedValue(ownPick) + mockWorkspaceApi.clearDefaultDeployment.mockResolvedValue(undefined) + renderSwitcher() + await userEvent.click( + await screen.findByTestId('deployment-switcher-trigger') + ) + + const owner = screen.getByTestId('deployment-switcher-owner') + expect(owner).toHaveTextContent( + "The workspace's default deployment no longer exists." + ) + await userEvent.click( + screen.getByTestId('deployment-switcher-clear-default') + ) + + expect(mockWorkspaceApi.clearDefaultDeployment).toHaveBeenCalledWith('ws-1') + await waitFor(() => expect(owner).toHaveTextContent('No workspace default')) + expect(screen.queryByTestId('deployment-switcher-clear-default')).toBeNull() + expect(reload).not.toHaveBeenCalled() + }) + + it("disables the trigger and the owner's buttons while a default is being set", async () => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: D2, + pick_source: 'browser', + default_deployment_id: D1 + }) + mockWorkspaceApi.setDefaultDeployment.mockReturnValue(new Promise(() => {})) + renderSwitcher() + const trigger = await screen.findByTestId('deployment-switcher-trigger') + await userEvent.click(trigger) + const setDefault = screen.getByTestId('deployment-switcher-set-default') + const clearDefault = screen.getByTestId('deployment-switcher-clear-default') + expect(setDefault).not.toBeDisabled() + expect(clearDefault).not.toBeDisabled() + + await userEvent.click(setDefault) + + expect(trigger).toBeDisabled() + expect(setDefault).toBeDisabled() + expect(clearDefault).toBeDisabled() + }) + + it('shows the new default in the footer and the list even when the refresh after it fails', async () => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce({ + ...listing, + picked_deployment_id: D2, + pick_source: 'browser', + default_deployment_id: D1 + }) + .mockRejectedValue(new WorkspaceApiError('Network Error')) + mockWorkspaceApi.setDefaultDeployment.mockResolvedValue(undefined) + renderSwitcher() + await userEvent.click( + await screen.findByTestId('deployment-switcher-trigger') + ) + const owner = screen.getByTestId('deployment-switcher-owner') + expect(owner).toHaveTextContent('Workspace default: Studio Build v1') + + await userEvent.click(screen.getByTestId('deployment-switcher-set-default')) + + await waitFor(() => + expect(mockWorkspaceApi.listDeployments).toHaveBeenCalledTimes(2) + ) + await waitFor(() => + expect(owner).toHaveTextContent('Workspace default: Studio Build v2') + ) + expect(screen.getByTestId(`deployment-row-${D2}`)).toHaveTextContent( + 'Workspace default' + ) + expect(screen.getByTestId(`deployment-row-${D1}`)).not.toHaveTextContent( + 'Workspace default' + ) + expect(useToast().toasts).toEqual([]) + expect(reload).not.toHaveBeenCalled() + }) + + it('offers no way back to a workspace default when there is none', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: D2, + pick_source: 'browser' + }) + renderSwitcher() + await userEvent.click( + await screen.findByTestId('deployment-switcher-trigger') + ) + expect(screen.getByTestId(`deployment-row-${D2}`)).toHaveAttribute( + 'aria-checked', + 'true' + ) + expect(screen.queryByTestId('deployment-row-follow')).toBeNull() + }) + + it('shows a member the workspace default but no way to change it', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: D2, + pick_source: 'browser', + default_deployment_id: D9 + }) + renderSwitcher() + await userEvent.click( + await screen.findByTestId('deployment-switcher-trigger') + ) + expect(screen.queryByTestId('deployment-switcher-owner')).toBeNull() + expect(screen.getByTestId('deployment-row-follow')).toHaveTextContent( + 'Deployment dep-b9b9b9b9' + ) + }) + + describe('with the app i18n, which escapes message parameters', () => { + const escapingI18n = createI18n({ + legacy: false, + locale: 'en', + escapeParameter: true, + messages: { en: enMessages } + }) + const oddlyNamed: WorkspaceDeploymentList = { + ...listing, + items: listing.items.map((item) => ({ + ...item, + build_name: item.build_name && "Vinh's R&D/Prod" + })) + } + + function renderEscaping() { + return render(DeploymentSwitcher, { + global: { plugins: [escapingI18n] } + }) + } + + it("shows a Build name with ', & and / as written in the label, the list, the follow row and the owner's footer", async () => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...oddlyNamed, + picked_deployment_id: D2, + pick_source: 'browser', + default_deployment_id: D1 + }) + renderEscaping() + + await waitFor(() => + expect( + screen.getByTestId('deployment-switcher-current') + ).toHaveTextContent("Vinh's R&D/Prod v2") + ) + await userEvent.click(screen.getByTestId('deployment-switcher-trigger')) + expect(screen.getByTestId(`deployment-row-${D1}`)).toHaveTextContent( + "Vinh's R&D/Prod v1dep-a1a1a1a1, stopped · Workspace default" + ) + expect(screen.getByTestId('deployment-row-follow')).toHaveTextContent( + "Drop this browser's own pick and run on Vinh's R&D/Prod v1" + ) + expect(screen.getByTestId('deployment-switcher-owner')).toHaveTextContent( + "Workspace default: Vinh's R&D/Prod v1" + ) + }) + + it("shows a Build name with ', & and / as written in the reload notice", async () => { + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce({ + ...oddlyNamed, + picked_deployment_id: D2, + pick_source: 'workspace_default', + default_deployment_id: D2 + }) + .mockResolvedValue({ + ...oddlyNamed, + picked_deployment_id: D1, + pick_source: 'workspace_default', + default_deployment_id: D1 + }) + renderEscaping() + await screen.findByTestId('deployment-switcher-trigger') + + await useDeploymentPickStore().load() + + expect( + await screen.findByTestId('deployment-switcher-changed') + ).toHaveTextContent( + "This browser now runs on Vinh's R&D/Prod v1. Reload to get its nodes." + ) + }) + }) +}) diff --git a/src/platform/workspace/components/DeploymentSwitcher.vue b/src/platform/workspace/components/DeploymentSwitcher.vue new file mode 100644 index 00000000000..09455b5aed5 --- /dev/null +++ b/src/platform/workspace/components/DeploymentSwitcher.vue @@ -0,0 +1,214 @@ + + + + diff --git a/src/platform/workspace/components/DeploymentSwitcherList.vue b/src/platform/workspace/components/DeploymentSwitcherList.vue new file mode 100644 index 00000000000..4b3dc0d6991 --- /dev/null +++ b/src/platform/workspace/components/DeploymentSwitcherList.vue @@ -0,0 +1,78 @@ + + + + diff --git a/src/platform/workspace/components/DeploymentSwitcherOwnerFooter.vue b/src/platform/workspace/components/DeploymentSwitcherOwnerFooter.vue new file mode 100644 index 00000000000..36aca24a96f --- /dev/null +++ b/src/platform/workspace/components/DeploymentSwitcherOwnerFooter.vue @@ -0,0 +1,68 @@ + + + + diff --git a/src/platform/workspace/components/DeploymentSwitcherRow.vue b/src/platform/workspace/components/DeploymentSwitcherRow.vue new file mode 100644 index 00000000000..345a5a63cec --- /dev/null +++ b/src/platform/workspace/components/DeploymentSwitcherRow.vue @@ -0,0 +1,36 @@ + + + + diff --git a/src/platform/workspace/composables/useDeploymentLabels.test.ts b/src/platform/workspace/composables/useDeploymentLabels.test.ts new file mode 100644 index 00000000000..7f46fe90a06 --- /dev/null +++ b/src/platform/workspace/composables/useDeploymentLabels.test.ts @@ -0,0 +1,147 @@ +import type { WorkspaceDeployment } from '@comfyorg/ingest-types' +import { render } from '@testing-library/vue' +import { assert, describe, expect, it } from 'vitest' +import { createI18n } from 'vue-i18n' + +import enMessages from '@/locales/en/main.json' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' + +import { + useBootDeploymentLabel, + useDeploymentLabels +} from './useDeploymentLabels' + +const deployment: WorkspaceDeployment = { + deployment_id: 'dep-12345678-0000-4000-8000-000000000001', + release_id: 'release-2', + build_name: 'Studio Build', + release_version: 2, + status: 'ready', + created_at: '2026-10-01T00:00:00Z' +} + +function mountLabels() { + let labels: ReturnType | undefined + render( + { + setup() { + labels = useDeploymentLabels() + }, + template: '
' + }, + { + global: { + plugins: [ + createI18n({ + legacy: false, + locale: 'en', + escapeParameter: true, + messages: { en: enMessages } + }) + ] + } + } + ) + assert.exists(labels) + return labels +} + +describe('deployment labels', () => { + it.for([ + { + name: 'named', + fields: { deployment_name: 'production' }, + title: 'production', + caption: 'Studio Build v2 · dep-12345678, ready' + }, + { + name: 'unnamed', + fields: {}, + title: 'Studio Build v2', + caption: 'dep-12345678, ready' + }, + { + name: 'empty name', + fields: { deployment_name: '' }, + title: 'Studio Build v2', + caption: 'dep-12345678, ready' + }, + { + name: 'named without Build', + fields: { deployment_name: 'staging', build_name: undefined }, + title: 'staging', + caption: 'dep-12345678, ready' + }, + { + name: 'named without Release version', + fields: { deployment_name: 'staging', release_version: undefined }, + title: 'staging', + caption: 'dep-12345678, ready' + }, + { + name: 'unnamed without Build', + fields: { build_name: undefined }, + title: 'Deployment dep-12345678', + caption: 'dep-12345678, ready' + }, + { + name: 'punctuation', + fields: { + deployment_name: "Studio's R&D/Prod", + build_name: "Artist's R&D" + }, + title: "Studio's R&D/Prod", + caption: "Artist's R&D v2 · dep-12345678, ready" + } + ] satisfies { + name: string + fields: Partial + title: string + caption: string + }[])('labels a $name deployment', ({ fields, title, caption }) => { + const labels = mountLabels() + const row = { ...deployment, ...fields } + expect(labels.deploymentLabel(row)).toBe(title) + expect(labels.deploymentCaption(row)).toBe(caption) + }) + + it('updates current and default names after a listing refresh while the boot label keeps its original deployment', () => { + const store = useDeploymentPickStore() + const named = { ...deployment, deployment_name: 'production' } + store.state = { + phase: 'ready', + deployments: [named], + pickedDeploymentId: deployment.deployment_id, + pickSource: 'workspace_default', + defaultDeploymentId: deployment.deployment_id, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true + } + store.bootDeployment = named + const labels = mountLabels() + const bootLabel = useBootDeploymentLabel() + expect(labels.currentLabel.value).toBe('production') + expect(labels.defaultLabel.value).toBe('production') + expect(bootLabel.value).toBe('production') + expect(labels.deploymentCaption(named)).toBe( + 'Studio Build v2 · dep-12345678, ready · Workspace default' + ) + + const renamed = { ...named, deployment_name: 'Studio production' } + store.state = { ...store.state, deployments: [renamed] } + expect(labels.currentLabel.value).toBe('Studio production') + expect(labels.defaultLabel.value).toBe('Studio production') + expect(labels.deploymentCaption(renamed)).toBe( + 'Studio Build v2 · dep-12345678, ready · Workspace default' + ) + + const updated = { ...renamed, release_id: 'release-3', release_version: 3 } + store.state = { ...store.state, deployments: [updated] } + expect(labels.currentLabel.value).toBe('Studio production') + expect(labels.deploymentCaption(updated)).toBe( + 'Studio Build v3 · dep-12345678, ready · Workspace default' + ) + expect(bootLabel.value).toBe('production') + }) +}) diff --git a/src/platform/workspace/composables/useDeploymentLabels.ts b/src/platform/workspace/composables/useDeploymentLabels.ts new file mode 100644 index 00000000000..716cc1b54cf --- /dev/null +++ b/src/platform/workspace/composables/useDeploymentLabels.ts @@ -0,0 +1,118 @@ +import type { WorkspaceDeployment } from '@/platform/workspace/api/workspaceApi' +import { storeToRefs } from 'pinia' +import { computed } from 'vue' +import { useI18n } from 'vue-i18n' + +import { t as translate } from '@/i18n' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' + +/** `dep-f24d36bb` out of `dep-f24d36bb-fd1f-...`: enough to tell two apart. */ +function shortId(deploymentId: string): string { + return deploymentId.slice(0, 12) +} + +function labelMessage( + deployment: WorkspaceDeployment +): [key: string, values: Record] { + if (deployment.deployment_name) { + return [ + 'deploymentSwitcher.namedDeployment', + { name: deployment.deployment_name } + ] + } + if ( + deployment.build_name !== undefined && + deployment.release_version !== undefined + ) { + return [ + 'deploymentSwitcher.deployment', + { build: deployment.build_name, version: deployment.release_version } + ] + } + return [ + 'deploymentSwitcher.unnamedDeployment', + { id: shortId(deployment.deployment_id) } + ] +} + +/** + * The label of the deployment this page booted on, for text outside the + * switcher that names where the editor runs (FE-2434); undefined on Comfy + * Cloud and until the first listing answers. Works outside a component. + */ +export function useBootDeploymentLabel() { + const { bootDeployment } = storeToRefs(useDeploymentPickStore()) + return computed(() => { + if (!bootDeployment.value) return undefined + const [key, values] = labelMessage(bootDeployment.value) + return translate(key, values, { escapeParameter: false }) + }) +} + +export function useDeploymentLabels() { + const { t } = useI18n() + const { pickedDeployment, defaultDeploymentId, defaultDeployment } = + storeToRefs(useDeploymentPickStore()) + + function deploymentLabel(deployment: WorkspaceDeployment): string { + const [key, values] = labelMessage(deployment) + return t(key, values, { escapeParameter: false }) + } + + function deploymentCaption(deployment: WorkspaceDeployment): string { + const key = + deployment.deployment_id === defaultDeploymentId.value + ? 'deploymentSwitcher.captionDefault' + : 'deploymentSwitcher.caption' + const caption = t( + key, + { id: shortId(deployment.deployment_id), status: deployment.status }, + { escapeParameter: false } + ) + if ( + !deployment.deployment_name || + deployment.build_name === undefined || + deployment.release_version === undefined + ) + return caption + + const release = t( + 'deploymentSwitcher.deployment', + { + build: deployment.build_name, + version: deployment.release_version + }, + { escapeParameter: false } + ) + return t( + 'deploymentSwitcher.namedCaption', + { release, caption }, + { escapeParameter: false } + ) + } + + function labelFor( + deploymentId: string | null, + deployment: WorkspaceDeployment | null + ): string { + if (deploymentId === null) return t('deploymentSwitcher.comfyCloud') + if (deployment) return deploymentLabel(deployment) + return t( + 'deploymentSwitcher.unnamedDeployment', + { id: shortId(deploymentId) }, + { escapeParameter: false } + ) + } + + /** A pick the listing no longer has runs on Comfy Cloud. */ + const currentLabel = computed(() => + pickedDeployment.value + ? deploymentLabel(pickedDeployment.value) + : t('deploymentSwitcher.comfyCloud') + ) + const defaultLabel = computed(() => + labelFor(defaultDeploymentId.value, defaultDeployment.value) + ) + + return { deploymentLabel, deploymentCaption, currentLabel, defaultLabel } +} diff --git a/src/platform/workspace/composables/useDeploymentPickAtBoot.test.ts b/src/platform/workspace/composables/useDeploymentPickAtBoot.test.ts new file mode 100644 index 00000000000..f605100b3be --- /dev/null +++ b/src/platform/workspace/composables/useDeploymentPickAtBoot.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it, vi } from 'vitest' + +import type { WorkspaceDeploymentList } from '@/platform/workspace/api/workspaceApi' + +import { useToast } from '@/components/ui/toast/toastStore' +import { workspaceApi } from '@/platform/workspace/api/workspaceApi' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' + +import { useDeploymentPickAtBoot } from './useDeploymentPickAtBoot' + +vi.mock(import('@/platform/workspace/api/workspaceApi')) + +const listing: WorkspaceDeploymentList = { + builds_visible: true, + items: [ + { + deployment_id: 'dep-1', + release_id: 'r-1', + build_name: 'Studio Build', + release_version: 1, + status: 'ready', + created_at: '2026-10-01T00:00:00Z' + } + ] +} + +describe('useDeploymentPickAtBoot', () => { + it('tells the person once that the deployment they picked is gone and the browser runs on Comfy Cloud', async () => { + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-1' }) + vi.mocked(workspaceApi.listDeployments).mockResolvedValue({ + ...listing, + gone_picked_deployment_id: 'dep-gone' + }) + + await useDeploymentPickAtBoot() + + expect(useDeploymentPickStore().bootDeployment).toBeNull() + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'The deployment you picked no longer exists.', + description: + 'This browser now runs on Comfy Cloud. Pick a deployment again from the account menu to use one.', + duration: 10000 + }) + ]) + }) + + it('tells the person their pick is gone when a newer listing answers before the boot listing that said so', async () => { + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-1' }) + let answerBoot: (reply: WorkspaceDeploymentList) => void = () => {} + vi.mocked(workspaceApi.listDeployments) + .mockReturnValueOnce( + new Promise((resolve) => { + answerBoot = resolve + }) + ) + .mockResolvedValue(listing) + + const booting = useDeploymentPickAtBoot() + await useDeploymentPickStore().load() + answerBoot({ ...listing, gone_picked_deployment_id: 'dep-gone' }) + await booting + + expect(useDeploymentPickStore().goneDeployment).toBe('pick') + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'The deployment you picked no longer exists.' + }) + ]) + }) + + it.for([ + { + when: 'its pick is listed', + reply: { picked_deployment_id: 'dep-1', pick_source: 'browser' } + }, + { when: 'it has no pick', reply: {} }, + { + when: 'only the workspace default it follows is gone', + reply: { gone_default_deployment_id: 'dep-gone' } + } + ] satisfies { when: string; reply: Partial }[])( + 'says nothing when $when', + async ({ reply }) => { + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-1' }) + vi.mocked(workspaceApi.listDeployments).mockResolvedValue({ + ...listing, + ...reply + }) + + await useDeploymentPickAtBoot() + + expect(useDeploymentPickStore().isVisible).toBe(true) + expect(useToast().toasts).toEqual([]) + } + ) +}) diff --git a/src/platform/workspace/composables/useDeploymentPickAtBoot.ts b/src/platform/workspace/composables/useDeploymentPickAtBoot.ts new file mode 100644 index 00000000000..3163af3e46c --- /dev/null +++ b/src/platform/workspace/composables/useDeploymentPickAtBoot.ts @@ -0,0 +1,20 @@ +import { t } from '@/i18n' +import { useToast } from '@/components/ui/toast/toastStore' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' + +/** + * Starts the page's boot listing (FE-2434), so the editor learns which + * deployment it booted on, and tells the person when that listing says their + * own pick is gone. Ingest says so on that one listing only, while clearing + * the pick, so without this a person who never opens the switcher would not + * learn that this browser now runs on Comfy Cloud. + */ +export async function useDeploymentPickAtBoot(): Promise { + const store = useDeploymentPickStore() + await store.loadOnce() + if (store.goneDeployment !== 'pick') return + useToast().warning(t('deploymentSwitcher.pickGone'), { + description: t('deploymentSwitcher.pickGoneDetail'), + duration: 10000 + }) +} diff --git a/src/platform/workspace/composables/useDeploymentUrlLoader.test.ts b/src/platform/workspace/composables/useDeploymentUrlLoader.test.ts new file mode 100644 index 00000000000..8fc9efa0352 --- /dev/null +++ b/src/platform/workspace/composables/useDeploymentUrlLoader.test.ts @@ -0,0 +1,348 @@ +import { setImmediate } from 'node:timers/promises' +import { fromAny } from '@total-typescript/shoehorn' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { computed, createApp, defineComponent } from 'vue' +import type { App } from 'vue' +import { createI18n } from 'vue-i18n' + +import { useToast } from '@/components/ui/toast/toastStore' +import { useCurrentUser } from '@/composables/auth/useCurrentUser' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' + +import { useDeploymentUrlLoader as createDeploymentUrlLoader } from './useDeploymentUrlLoader' + +vi.mock(import('@/composables/auth/useCurrentUser')) + +const preservedQueryMocks = vi.hoisted(() => ({ + clearPreservedQuery: vi.fn(), + hydratePreservedQuery: vi.fn(), + mergePreservedQueryIntoQuery: vi.fn() +})) + +vi.mock( + import('@/platform/navigation/preservedQueryManager'), + () => preservedQueryMocks +) + +const mockRouteQuery = vi.hoisted(() => ({ + value: {} as Record +})) +const mockRouterReplace = vi.hoisted(() => vi.fn(async () => undefined)) + +vi.mock(import('vue-router'), () => ({ + useRoute: () => ({ + query: mockRouteQuery.value + }), + useRouter: () => ({ + replace: mockRouterReplace + }) +})) + +const apps: App[] = [] + +function useDeploymentUrlLoader(): ReturnType< + typeof createDeploymentUrlLoader +> { + let result: ReturnType | undefined + const app = createApp( + defineComponent({ + setup() { + result = createDeploymentUrlLoader() + return () => null + } + }) + ) + app.use( + createI18n({ + legacy: false, + locale: 'en', + messages: { + en: { + deploymentSwitcher: { + linkRefused: "Couldn't open this deployment", + linkTimedOut: + 'This deployment took too long to open. Try the link again.', + linkWorkspaceRefused: + "Couldn't switch to that workspace. You're still in {workspaceName}." + } + } + } + }) + ) + app.mount(document.createElement('div')) + apps.push(app) + if (!result) throw new Error('deployment URL loader not initialized') + return result +} + +afterEach(() => { + for (const app of apps.splice(0)) app.unmount() +}) + +const homeBase = { + id: 'ws-1', + name: 'Home Base', + type: 'personal' as const, + role: 'owner' as const, + created_at: '2026-01-01T00:00:00Z', + joined_at: '2026-01-01T00:00:00Z' +} +const studio = { + ...homeBase, + id: 'ws-2', + name: 'Studio', + type: 'team' as const, + role: 'member' as const +} + +const STAYED = "Couldn't switch to that workspace. You're still in Home Base." + +describe('useDeploymentUrlLoader', () => { + beforeEach(() => { + sessionStorage.clear() + mockRouteQuery.value = {} + preservedQueryMocks.mergePreservedQueryIntoQuery.mockReturnValue(undefined) + mockRouterReplace.mockResolvedValue(undefined) + Object.assign(useTeamWorkspaceStore(), { activeWorkspace: homeBase }) + vi.mocked(useTeamWorkspaceStore().switchWorkspace).mockResolvedValue( + undefined + ) + vi.mocked(useDeploymentPickStore().pickFromLink).mockResolvedValue({ + kind: 'picked' + }) + }) + + it('does nothing when the URL has no deployment link', async () => { + mockRouteQuery.value = { workflow: 'keep-me' } + + const { loadDeploymentFromUrl } = useDeploymentUrlLoader() + await expect(loadDeploymentFromUrl()).resolves.toBe(false) + + expect(mockRouterReplace).not.toHaveBeenCalled() + expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() + expect(useDeploymentPickStore().pickFromLink).not.toHaveBeenCalled() + }) + + it('in the named workspace, strips both params and then picks the deployment', async () => { + mockRouteQuery.value = { + workspace: 'ws-1', + deployment: 'dep-1', + other: 'param' + } + + const { loadDeploymentFromUrl } = useDeploymentUrlLoader() + await expect(loadDeploymentFromUrl()).resolves.toBe(true) + + expect(mockRouterReplace).toHaveBeenCalledWith({ + query: { other: 'param' } + }) + expect(useDeploymentPickStore().pickFromLink).toHaveBeenCalledWith('dep-1') + // The pick reloads the page, which would run the link again if the + // params were still in the address. + expect(mockRouterReplace.mock.invocationCallOrder[0]).toBeLessThan( + vi.mocked(useDeploymentPickStore().pickFromLink).mock + .invocationCallOrder[0] + ) + expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() + expect(useToast().error).not.toHaveBeenCalled() + }) + + it('waits for URL cleanup to complete before starting the pick', async () => { + mockRouteQuery.value = { workspace: 'ws-1', deployment: 'dep-1' } + let finishCleanup!: () => void + const cleanup = new Promise((resolve) => { + finishCleanup = () => resolve(undefined) + }) + mockRouterReplace.mockReturnValue(cleanup) + const loading = useDeploymentUrlLoader().loadDeploymentFromUrl() + await setImmediate() + expect(useDeploymentPickStore().pickFromLink).not.toHaveBeenCalled() + finishCleanup() + await expect(loading).resolves.toBe(true) + expect(useDeploymentPickStore().pickFromLink).toHaveBeenCalledWith('dep-1') + }) + + it('stays in the workspace when the retry marker cannot be saved', async () => { + mockRouteQuery.value = { workspace: 'ws-2', deployment: 'dep-1' } + const save = vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => { + throw new DOMException('Storage full', 'QuotaExceededError') + }) + try { + await expect( + useDeploymentUrlLoader().loadDeploymentFromUrl() + ).resolves.toBe(false) + expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() + expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) + expect(useToast().error).toHaveBeenCalledWith(STAYED, { duration: 8000 }) + } finally { + save.mockRestore() + } + }) + + it('switches to another workspace keeping the link, and picks on the boot after the reload', async () => { + mockRouteQuery.value = { workspace: 'ws-2', deployment: 'dep-1' } + + await expect( + useDeploymentUrlLoader().loadDeploymentFromUrl() + ).resolves.toBe(true) + + expect(useTeamWorkspaceStore().switchWorkspace).toHaveBeenCalledWith('ws-2') + expect(mockRouterReplace).not.toHaveBeenCalled() + expect(useDeploymentPickStore().pickFromLink).not.toHaveBeenCalled() + + // The reload lands in the named workspace with the link still there. + Object.assign(useTeamWorkspaceStore(), { activeWorkspace: studio }) + await expect( + useDeploymentUrlLoader().loadDeploymentFromUrl() + ).resolves.toBe(true) + + expect(useTeamWorkspaceStore().switchWorkspace).toHaveBeenCalledOnce() + expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) + expect(useDeploymentPickStore().pickFromLink).toHaveBeenCalledWith('dep-1') + }) + + it('stays put and says so when the switch to the named workspace is refused', async () => { + mockRouteQuery.value = { workspace: 'ws-9', deployment: 'dep-1' } + vi.mocked(useTeamWorkspaceStore().switchWorkspace).mockRejectedValue( + new Error('Workspace not found or access denied') + ) + + const { loadDeploymentFromUrl } = useDeploymentUrlLoader() + await expect(loadDeploymentFromUrl()).resolves.toBe(false) + + expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) + expect(useDeploymentPickStore().pickFromLink).not.toHaveBeenCalled() + expect(useToast().error).toHaveBeenCalledWith(STAYED, { duration: 8000 }) + }) + + // A switch reloads the page; if the boot after it lands elsewhere (the + // workspace was left meanwhile), switching again would reload forever. + it('never switches twice for one link when the switch did not land', async () => { + mockRouteQuery.value = { workspace: 'ws-2', deployment: 'dep-1' } + await useDeploymentUrlLoader().loadDeploymentFromUrl() + + await expect( + useDeploymentUrlLoader().loadDeploymentFromUrl() + ).resolves.toBe(false) + + expect(useTeamWorkspaceStore().switchWorkspace).toHaveBeenCalledOnce() + expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) + expect(useDeploymentPickStore().pickFromLink).not.toHaveBeenCalled() + expect(useToast().error).toHaveBeenCalledWith(STAYED, { duration: 8000 }) + }) + + it("shows the server's refusal of the pick, strips the params, and stays", async () => { + mockRouteQuery.value = { workspace: 'ws-1', deployment: 'dep-gone' } + vi.mocked(useDeploymentPickStore().pickFromLink).mockResolvedValue({ + kind: 'refused', + message: "deployment dep-gone is not one of this workspace's" + }) + + const { loadDeploymentFromUrl } = useDeploymentUrlLoader() + await expect(loadDeploymentFromUrl()).resolves.toBe(false) + + expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) + expect(useToast().error).toHaveBeenCalledWith( + "Couldn't open this deployment", + { + description: "deployment dep-gone is not one of this workspace's", + duration: 8000 + } + ) + }) + + it('lets startup continue with a retry message after the listing times out', async () => { + mockRouteQuery.value = { workspace: 'ws-1', deployment: 'dep-1' } + vi.mocked(useDeploymentPickStore().pickFromLink).mockResolvedValue({ + kind: 'timedOut' + }) + await expect( + useDeploymentUrlLoader().loadDeploymentFromUrl() + ).resolves.toBe(false) + expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) + expect(useToast().error).toHaveBeenCalledWith( + 'This deployment took too long to open. Try the link again.', + { duration: 8000 } + ) + }) + + it('strips the params and says nothing when the browser already runs on the deployment', async () => { + mockRouteQuery.value = { workspace: 'ws-1', deployment: 'dep-2' } + vi.mocked(useDeploymentPickStore().pickFromLink).mockResolvedValue({ + kind: 'unchanged' + }) + + const { loadDeploymentFromUrl } = useDeploymentUrlLoader() + await expect(loadDeploymentFromUrl()).resolves.toBe(false) + + expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) + expect(useToast().error).not.toHaveBeenCalled() + }) + + it('acts on a link the sign-in redirect carried in the preserved-query stash', async () => { + mockRouteQuery.value = {} + preservedQueryMocks.mergePreservedQueryIntoQuery.mockImplementation( + (namespace: string, query: Record) => + namespace === 'workspace' + ? { ...query, workspace: 'ws-1' } + : { ...query, deployment: 'dep-1' } + ) + + const { loadDeploymentFromUrl } = useDeploymentUrlLoader() + await expect(loadDeploymentFromUrl()).resolves.toBe(true) + + expect(useDeploymentPickStore().pickFromLink).toHaveBeenCalledWith('dep-1') + expect(preservedQueryMocks.clearPreservedQuery).toHaveBeenCalledWith( + 'workspace' + ) + expect(preservedQueryMocks.clearPreservedQuery).toHaveBeenCalledWith( + 'deployment' + ) + }) + + // An API-key session is bound to one workspace and cannot pick. + it('does not act for an API-key login, and leaves ?workspace to its own loader', async () => { + Object.assign(useCurrentUser(), { isApiKeyLogin: computed(() => true) }) + mockRouteQuery.value = { workspace: 'ws-2', deployment: 'dep-1' } + + const { loadDeploymentFromUrl } = useDeploymentUrlLoader() + await expect(loadDeploymentFromUrl()).resolves.toBe(false) + + expect(mockRouterReplace).toHaveBeenCalledWith({ + query: { workspace: 'ws-2' } + }) + expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() + expect(useDeploymentPickStore().pickFromLink).not.toHaveBeenCalled() + }) + + it.for([ + { when: 'the workspace is missing', query: { deployment: 'dep-1' } }, + { + when: 'the deployment is empty', + query: { workspace: 'ws-2', deployment: '' } + }, + { + when: 'the deployment is bare', + query: { workspace: 'ws-2', deployment: null } + }, + { + when: 'the deployment is repeated', + query: { workspace: 'ws-2', deployment: ['dep-1', 'dep-2'] } + }, + { + when: 'the stash joined a repeated deployment', + query: { workspace: 'ws-2', deployment: 'dep-1,dep-2' } + } + ])('does not act when $when', async ({ query }) => { + mockRouteQuery.value = fromAny, unknown>(query) + + const { loadDeploymentFromUrl } = useDeploymentUrlLoader() + await expect(loadDeploymentFromUrl()).resolves.toBe(false) + + const { deployment: _dropped, ...kept } = query + expect(mockRouterReplace).toHaveBeenCalledWith({ query: kept }) + expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() + expect(useDeploymentPickStore().pickFromLink).not.toHaveBeenCalled() + }) +}) diff --git a/src/platform/workspace/composables/useDeploymentUrlLoader.ts b/src/platform/workspace/composables/useDeploymentUrlLoader.ts new file mode 100644 index 00000000000..7ad84989e64 --- /dev/null +++ b/src/platform/workspace/composables/useDeploymentUrlLoader.ts @@ -0,0 +1,199 @@ +import { storeToRefs } from 'pinia' +import { useI18n } from 'vue-i18n' +import type { LocationQueryRaw } from 'vue-router' +import { useRoute, useRouter } from 'vue-router' + +import { useToast } from '@/components/ui/toast/toastStore' +import { useCurrentUser } from '@/composables/auth/useCurrentUser' +import { + clearPreservedQuery, + hydratePreservedQuery, + mergePreservedQueryIntoQuery +} from '@/platform/navigation/preservedQueryManager' +import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' + +import { useWorkspaceSwitch } from './useWorkspaceSwitch' + +const WORKSPACE_NAMESPACE = PRESERVED_QUERY_NAMESPACES.WORKSPACE +const DEPLOYMENT_NAMESPACE = PRESERVED_QUERY_NAMESPACES.DEPLOYMENT +const SWITCH_KEY = WORKSPACE_STORAGE_KEYS.DEPLOYMENT_LINK_SWITCH + +/** + * One usable value: a non-empty string. Null for absent, empty, a bare + * `?deployment` (null), and a repeated value (an array, or the stash's `,` + * join of one), so a link that names two deployments picks neither. + */ +function readLinkValue(raw: unknown): string | null { + if (typeof raw !== 'string') return null + const value = raw.trim() + return value && !value.includes(',') ? value : null +} + +/** The link's query: the URL's, plus what the sign-in redirect stashed. */ +function linkQuery(routeQuery: LocationQueryRaw): LocationQueryRaw { + hydratePreservedQuery(WORKSPACE_NAMESPACE) + hydratePreservedQuery(DEPLOYMENT_NAMESPACE) + const withWorkspace = + mergePreservedQueryIntoQuery(WORKSPACE_NAMESPACE, routeQuery) ?? routeQuery + return ( + mergePreservedQueryIntoQuery(DEPLOYMENT_NAMESPACE, withWorkspace) ?? + withWorkspace + ) +} + +/** + * The workspace this page switched to for a deployment link, taken once: the + * next boot reads and drops it, so a switch that did not land is never tried + * again. + */ +function takeSwitchTarget(): string | null { + try { + const id = sessionStorage.getItem(SWITCH_KEY) + sessionStorage.removeItem(SWITCH_KEY) + return id + } catch { + return null + } +} + +function setSwitchTarget(workspaceId: string | null): boolean { + try { + if (workspaceId === null) sessionStorage.removeItem(SWITCH_KEY) + else sessionStorage.setItem(SWITCH_KEY, workspaceId) + return true + } catch { + return false + } +} + +/** + * Opens the editor on the deployment a link names (BE-20294): + * `/?workspace=&deployment=`. Runs before the + * `?workspace=` loader and owns both params when `deployment` is present. + * + * In another workspace it switches there first, keeping both params so the + * boot after the switch's reload picks; a switch that fails, or that did not + * land after its reload, stays in the active workspace and says so. In the + * named workspace it strips both params, then picks with the switcher's own + * request, which reloads onto the deployment's nodes; a refused pick (outside + * the rollout, a deployment gone or not the workspace's) shows the server's + * reason and changes nothing. A link without both values, or an API-key + * session (bound to one workspace, no pick), does nothing but drop + * `deployment`. Signed out, the router sends the person to sign in with the + * full path, query included, to come back to; both params are also stashed + * by the preserved-query tracker. + */ +export function useDeploymentUrlLoader() { + const route = useRoute() + const router = useRouter() + const { t } = useI18n() + const toast = useToast() + const { isApiKeyLogin } = useCurrentUser() + const { switchWorkspace } = useWorkspaceSwitch() + const { activeWorkspace, workspaceName } = storeToRefs( + useTeamWorkspaceStore() + ) + const pickStore = useDeploymentPickStore() + + /** Strips the given params, keeping the rest, and clears their stashes. + * Must complete before a pick reloads the page, or the reload would run + * the link again. */ + async function stripParams( + query: LocationQueryRaw, + keys: ('workspace' | 'deployment')[] + ) { + const cleanQuery = { ...query } + for (const key of keys) delete cleanQuery[key] + try { + await router.replace({ query: cleanQuery }) + } catch (error) { + console.warn( + '[useDeploymentUrlLoader] Failed to clean URL params:', + error + ) + } + if (keys.includes('workspace')) clearPreservedQuery(WORKSPACE_NAMESPACE) + clearPreservedQuery(DEPLOYMENT_NAMESPACE) + } + + function notifyWorkspaceRefused() { + toast.error( + t( + 'deploymentSwitcher.linkWorkspaceRefused', + { workspaceName: workspaceName.value }, + { escapeParameter: false } + ), + { duration: 8000 } + ) + } + + /** + * In another workspace: switch there, keeping the link for the boot after + * the switch's reload. Returns `true` when that reload is in flight. + */ + async function openWorkspace( + query: LocationQueryRaw, + workspaceId: string, + switchedTo: string | null + ): Promise { + // A switch this link already made did not land: never reload again. + if (switchedTo !== workspaceId && setSwitchTarget(workspaceId)) { + if (await switchWorkspace(workspaceId)) return true + setSwitchTarget(null) + } + await stripParams(query, ['workspace', 'deployment']) + notifyWorkspaceRefused() + return false + } + + /** + * In the named workspace: strip the link, then pick. Returns `true` when + * the pick took and the page is reloading onto the deployment. + */ + async function pickDeployment( + query: LocationQueryRaw, + deploymentId: string + ): Promise { + await stripParams(query, ['workspace', 'deployment']) + const outcome = await pickStore.pickFromLink(deploymentId) + if (outcome.kind === 'timedOut') { + toast.error(t('deploymentSwitcher.linkTimedOut'), { duration: 8000 }) + } + if (outcome.kind === 'refused') { + toast.error(t('deploymentSwitcher.linkRefused'), { + description: outcome.message, + duration: 8000 + }) + } + return outcome.kind === 'picked' + } + + /** + * Reads the link and acts on it. Returns `true` when a reload is in flight + * (a workspace switch or a pick), so the caller stops running loaders. + */ + async function loadDeploymentFromUrl(): Promise { + const query = linkQuery(route.query) + const switchedTo = takeSwitchTarget() + if (!('deployment' in query)) return false + + const workspaceId = readLinkValue(query.workspace) + const deploymentId = readLinkValue(query.deployment) + // `workspace` stays for its own loader, which opens the workspace alone. + if (!workspaceId || !deploymentId || isApiKeyLogin.value) { + await stripParams(query, ['deployment']) + return false + } + if (activeWorkspace.value?.id !== workspaceId) { + return openWorkspace(query, workspaceId, switchedTo) + } + return pickDeployment(query, deploymentId) + } + + return { + loadDeploymentFromUrl + } +} diff --git a/src/platform/workspace/deploymentPickState.test.ts b/src/platform/workspace/deploymentPickState.test.ts new file mode 100644 index 00000000000..9e072868e61 --- /dev/null +++ b/src/platform/workspace/deploymentPickState.test.ts @@ -0,0 +1,326 @@ +import { describe, expect, it } from 'vitest' + +import type { WorkspaceDeployment } from '@/platform/workspace/api/workspaceApi' + +import type { + DeploymentPickEvent, + DeploymentPickState +} from './deploymentPickState' +import { + changeBetween, + loadedEvent, + reduceDeploymentPick +} from './deploymentPickState' + +const deployment: WorkspaceDeployment = { + deployment_id: 'dep-1', + release_id: 'r-1', + build_name: 'Studio Build', + release_version: 1, + status: 'ready', + created_at: '2026-10-01T00:00:00Z' +} + +const loaded: DeploymentPickEvent = { + type: 'loaded', + deployments: [deployment], + pickedDeploymentId: 'dep-1', + pickSource: 'browser', + defaultDeploymentId: null, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true +} + +const ready: DeploymentPickState = { + phase: 'ready', + deployments: [deployment], + pickedDeploymentId: 'dep-1', + pickSource: 'browser', + defaultDeploymentId: null, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true +} + +describe('reduceDeploymentPick', () => { + const switching: DeploymentPickState = { + ...ready, + phase: 'switching', + target: null + } + + const nothingShown: DeploymentPickState[] = [ + { phase: 'idle' }, + { phase: 'hidden' } + ] + + it.for(nothingShown)( + 'loads into ready from $phase, or into hidden when refused or failed', + (state) => { + expect(reduceDeploymentPick(state, loaded)).toEqual(ready) + expect(reduceDeploymentPick(state, { type: 'loadRefused' })).toEqual({ + phase: 'hidden' + }) + expect(reduceDeploymentPick(state, { type: 'loadFailed' })).toEqual({ + phase: 'hidden' + }) + } + ) + + it('keeps a listing on screen when a reload of it fails, but hides on a refusal', () => { + expect(reduceDeploymentPick(ready, { type: 'loadFailed' })).toBe(ready) + expect(reduceDeploymentPick(switching, { type: 'loadFailed' })).toBe( + switching + ) + expect(reduceDeploymentPick(ready, { type: 'loadRefused' })).toEqual({ + phase: 'hidden' + }) + }) + + it('restores the listing after a failed switch', () => { + expect( + reduceDeploymentPick(ready, { type: 'switchStarted', target: null }) + ).toEqual(switching) + expect(reduceDeploymentPick(switching, { type: 'switchFailed' })).toEqual( + ready + ) + expect(reduceDeploymentPick(ready, { type: 'switchFailed' })).toBe(ready) + }) + + it.for(nothingShown)( + 'tracks a link switch without a listing from $phase', + (state) => { + const pending = reduceDeploymentPick(state, { + type: 'switchStarted', + target: 'dep-1' + }) + expect(pending.phase).toBe('switching') + expect(reduceDeploymentPick(pending, { type: 'loadFailed' })).toBe( + pending + ) + expect(reduceDeploymentPick(pending, { type: 'switchFailed' })).toEqual( + state + ) + expect(reduceDeploymentPick(pending, loaded)).toEqual({ + ...ready, + phase: 'switching', + target: 'dep-1' + }) + const refused = reduceDeploymentPick(pending, { type: 'loadRefused' }) + expect(refused.phase).toBe('switching') + expect( + reduceDeploymentPick(refused, { + type: 'defaultChanged', + defaultDeploymentId: 'dep-1' + }) + ).toEqual({ phase: 'hidden' }) + expect(reduceDeploymentPick(refused, { type: 'switchFailed' })).toEqual({ + phase: 'hidden' + }) + } + ) + + it.for([ready, switching])( + 'forgets the listing from $phase when the workspace changes', + (state) => { + expect(reduceDeploymentPick(state, { type: 'workspaceChanged' })).toEqual( + { phase: 'idle' } + ) + } + ) + + it('keeps a switch in flight when a listing lands, and takes the new listing', () => { + const newer: DeploymentPickEvent = { + ...loaded, + pickedDeploymentId: null, + pickSource: null, + defaultDeploymentId: 'dep-1' + } + const landed = reduceDeploymentPick( + { ...switching, target: 'dep-1' }, + newer + ) + expect(landed).toEqual({ + phase: 'switching', + target: 'dep-1', + deployments: [deployment], + pickedDeploymentId: null, + pickSource: null, + defaultDeploymentId: 'dep-1', + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: true + }) + // A refused switch then returns to the newer listing, not the old one. + expect(reduceDeploymentPick(landed, { type: 'switchFailed' })).toEqual({ + ...ready, + pickedDeploymentId: null, + pickSource: null, + defaultDeploymentId: 'dep-1' + }) + }) + + it('keeps a switch in flight, hidden, when a refresh is refused, until it ends or a listing lands', () => { + const refused = reduceDeploymentPick( + { ...switching, target: 'dep-1' }, + { type: 'loadRefused' } + ) + expect(refused).toEqual({ + phase: 'switching', + target: 'dep-1', + previousPhase: 'hidden' + }) + expect(reduceDeploymentPick(refused, { type: 'loadFailed' })).toBe(refused) + expect( + reduceDeploymentPick(refused, { type: 'switchStarted', target: null }) + ).toBe(refused) + expect(reduceDeploymentPick(refused, loaded)).toEqual({ + ...ready, + phase: 'switching', + target: 'dep-1' + }) + expect(reduceDeploymentPick(refused, { type: 'switchFailed' })).toEqual({ + phase: 'hidden' + }) + expect( + reduceDeploymentPick(refused, { + type: 'defaultChanged', + defaultDeploymentId: 'dep-1' + }) + ).toEqual({ phase: 'hidden' }) + expect(reduceDeploymentPick(refused, { type: 'workspaceChanged' })).toEqual( + { phase: 'idle' } + ) + }) + + it('a new default the server took ends the switch and shows at once', () => { + expect( + reduceDeploymentPick(switching, { + type: 'defaultChanged', + defaultDeploymentId: 'dep-1' + }) + ).toEqual({ ...ready, defaultDeploymentId: 'dep-1' }) + expect( + reduceDeploymentPick( + { ...switching, defaultDeploymentId: 'dep-1' }, + { type: 'defaultChanged', defaultDeploymentId: null } + ) + ).toEqual(ready) + expect( + reduceDeploymentPick( + { ...switching, goneDefaultDeploymentId: 'dep-gone' }, + { type: 'defaultChanged', defaultDeploymentId: null } + ) + ).toEqual(ready) + // A refusal that landed meanwhile still hides it. + const hidden: DeploymentPickState = { phase: 'hidden' } + expect( + reduceDeploymentPick(hidden, { + type: 'defaultChanged', + defaultDeploymentId: 'dep-1' + }) + ).toBe(hidden) + }) +}) + +describe('loadedEvent', () => { + it('carries the gone pick and the gone default ingest reports', () => { + expect( + loadedEvent({ + items: [deployment], + builds_visible: true, + gone_picked_deployment_id: 'dep-9', + gone_default_deployment_id: 'dep-8' + }) + ).toMatchObject({ + pickedDeploymentId: null, + defaultDeploymentId: null, + gonePickedDeploymentId: 'dep-9', + goneDefaultDeploymentId: 'dep-8' + }) + }) + + it('carries the listing, with absent fields as null', () => { + expect( + loadedEvent({ + items: [deployment], + pick_source: 'browser', + builds_visible: false + }) + ).toEqual({ + type: 'loaded', + deployments: [deployment], + pickedDeploymentId: null, + pickSource: 'browser', + defaultDeploymentId: null, + gonePickedDeploymentId: null, + goneDefaultDeploymentId: null, + buildsVisible: false + }) + }) + + it('keeps the pick and the workspace default the listing names', () => { + expect( + loadedEvent({ + items: [deployment], + picked_deployment_id: 'dep-1', + pick_source: 'workspace_default', + default_deployment_id: 'dep-1', + builds_visible: true + }) + ).toMatchObject({ + pickedDeploymentId: 'dep-1', + pickSource: 'workspace_default', + defaultDeploymentId: 'dep-1' + }) + }) +}) + +describe('changeBetween', () => { + const updated = { ...deployment, release_id: 'r-2' } + const other = { ...deployment, deployment_id: 'dep-2', release_id: 'r-3' } + const sameRelease = { ...deployment, deployment_id: 'dep-2' } + + it.for([ + { + name: 'the same deployment', + boot: deployment, + now: deployment, + change: null + }, + { name: 'Comfy Cloud both times', boot: null, now: null, change: null }, + { + name: 'a new Release', + boot: deployment, + now: updated, + change: 'release' + }, + { + name: 'another deployment', + boot: deployment, + now: other, + change: 'deployment' + }, + { + name: 'Comfy Cloud after a deployment', + boot: deployment, + now: null, + change: 'deployment' + }, + { + name: 'a deployment after Comfy Cloud', + boot: null, + now: deployment, + change: 'deployment' + }, + { + name: 'another deployment on the same Release', + boot: deployment, + now: sameRelease, + change: null + } + ])('reports $change for $name', ({ boot, now, change }) => { + expect(changeBetween(boot, now)).toBe(change) + }) +}) diff --git a/src/platform/workspace/deploymentPickState.ts b/src/platform/workspace/deploymentPickState.ts new file mode 100644 index 00000000000..a0d0869bff7 --- /dev/null +++ b/src/platform/workspace/deploymentPickState.ts @@ -0,0 +1,196 @@ +import type { + WorkspaceDeployment, + WorkspaceDeploymentList +} from '@/platform/workspace/api/workspaceApi' + +/** + * Which developer-platform deployment this browser runs its Cloud jobs on, and + * the list it may pick from (FE-2434). A deployment keeps one URL while its + * owner updates it to new Releases, so a pick follows those updates. The pick + * itself is an HttpOnly cookie ingest sets; the editor learns it from the + * listing and never reads it. + */ +/** Where the current pick came from (BE-17480). */ +export type DeploymentPickSource = 'browser' | 'workspace_default' + +interface DeploymentListing { + deployments: WorkspaceDeployment[] + pickedDeploymentId: string | null + /** + * `browser` when this browser picked for itself (a deployment, or + * Comfy Cloud); `workspace_default` when it follows the workspace's default + * deployment; null when there is neither, so it runs on Comfy Cloud. + */ + pickSource: DeploymentPickSource | null + /** The workspace's default deployment an owner set, or null. */ + defaultDeploymentId: string | null + /** + * This browser's own pick, when ingest found it gone (deleted, or no + * longer the workspace's) and cleared it. Only the listing that cleared + * it says so; the browser is on Comfy Cloud. + */ + gonePickedDeploymentId: string | null + /** + * The workspace's default deployment, when it is gone; then + * `defaultDeploymentId` is null. Said on every listing until an owner + * sets or clears the default. + */ + goneDefaultDeploymentId: string | null + buildsVisible: boolean +} + +/** + * A reload of the listing does not change the state until it answers: the + * last listing stays on screen (or the switcher stays hidden) meanwhile, so + * reopening the popover never flashes "Comfy Cloud" or no default. A listing + * that lands while a switch is in flight updates what is shown but does not + * end the switch, so a second pick cannot go out before the first answers. + */ +export type DeploymentPickState = + /** Nothing has answered yet; the switcher is not shown. */ + | { phase: 'idle' } + /** + * The account is outside the rollout, the session cannot pick, or the + * first listing failed (for example ingest without these routes). + */ + | { phase: 'hidden' } + | ({ phase: 'ready' } & DeploymentListing) + /** + * A pick, a clear or a new default is in flight. A pick or a clear reloads + * the page on success; a new default reloads it only when this browser has + * no pick of its own, since only then does it change what this browser + * runs on. + */ + | ({ phase: 'switching'; target: string | null } & DeploymentListing) + | { + phase: 'switching' + target: string | null + previousPhase: 'idle' | 'hidden' + } + +export type DeploymentPickEvent = + | ({ type: 'loaded' } & DeploymentListing) + /** A 403: the account is outside the rollout, whatever was shown before. */ + | { type: 'loadRefused' } + /** Any other failure: keep a listing already shown, else stay hidden. */ + | { type: 'loadFailed' } + | { type: 'switchStarted'; target: string | null } + /** The server refused the switch. */ + | { type: 'switchFailed' } + /** + * The server took a new workspace default (or its clearing) and this + * browser does not reload: show it now, whatever the refresh after it + * answers, and end the switch. + */ + | { type: 'defaultChanged'; defaultDeploymentId: string | null } + /** Another workspace or account: nothing shown belongs to it. */ + | { type: 'workspaceChanged' } + +/** The `loaded` event for a listing from GET /api/workspaces/{id}/deployments. */ +export function loadedEvent( + listing: WorkspaceDeploymentList +): DeploymentPickEvent { + return { + type: 'loaded', + deployments: listing.items, + pickedDeploymentId: listing.picked_deployment_id ?? null, + pickSource: listing.pick_source ?? null, + defaultDeploymentId: listing.default_deployment_id ?? null, + gonePickedDeploymentId: listing.gone_picked_deployment_id ?? null, + goneDefaultDeploymentId: listing.gone_default_deployment_id ?? null, + buildsVisible: listing.builds_visible + } +} + +/** The listing fields of a state or a `loaded` event, without the rest. */ +function listingOf(source: DeploymentListing): DeploymentListing { + return { + deployments: source.deployments, + pickedDeploymentId: source.pickedDeploymentId, + pickSource: source.pickSource, + defaultDeploymentId: source.defaultDeploymentId, + gonePickedDeploymentId: source.gonePickedDeploymentId, + goneDefaultDeploymentId: source.goneDefaultDeploymentId, + buildsVisible: source.buildsVisible + } +} + +export function reduceDeploymentPick( + state: DeploymentPickState, + event: DeploymentPickEvent +): DeploymentPickState { + switch (event.type) { + case 'loaded': + return withListing(state, listingOf(event)) + case 'loadRefused': + return state.phase === 'switching' + ? { phase: 'switching', target: state.target, previousPhase: 'hidden' } + : { phase: 'hidden' } + case 'loadFailed': + return state.phase === 'switching' || 'deployments' in state + ? state + : { phase: 'hidden' } + case 'switchStarted': + return startSwitch(state, event.target) + case 'switchFailed': + return endSwitch(state, (listing) => listing) + case 'defaultChanged': + return endSwitch(state, (listing) => ({ + ...listing, + defaultDeploymentId: event.defaultDeploymentId, + goneDefaultDeploymentId: null + })) + case 'workspaceChanged': + return { phase: 'idle' } + } +} + +function withListing( + state: DeploymentPickState, + listing: DeploymentListing +): DeploymentPickState { + if (state.phase !== 'switching') return { phase: 'ready', ...listing } + return { phase: 'switching', target: state.target, ...listing } +} + +function startSwitch( + state: DeploymentPickState, + target: string | null +): DeploymentPickState { + if (state.phase === 'switching') return state + if (state.phase === 'ready') { + return { phase: 'switching', target, ...listingOf(state) } + } + return { phase: 'switching', target, previousPhase: state.phase } +} + +function endSwitch( + state: DeploymentPickState, + shown: (listing: DeploymentListing) => DeploymentListing +): DeploymentPickState { + if (state.phase !== 'switching') return state + if (!('deployments' in state)) return { phase: state.previousPhase } + return { phase: 'ready', ...shown(listingOf(state)) } +} + +/** + * What changed between the deployment a page booted on and the one it runs + * on now (null for Comfy Cloud in both): `release` when the same deployment + * runs another Release, `deployment` when it runs on another deployment or + * Comfy Cloud with other nodes, null when its nodes are the same. + */ +export function changeBetween( + boot: WorkspaceDeployment | null, + now: WorkspaceDeployment | null +): 'release' | 'deployment' | null { + if (releaseOf(boot) === releaseOf(now)) return null + return deploymentOf(boot) === deploymentOf(now) ? 'release' : 'deployment' +} + +function releaseOf(deployment: WorkspaceDeployment | null): string | null { + return deployment?.release_id ?? null +} + +function deploymentOf(deployment: WorkspaceDeployment | null): string | null { + return deployment?.deployment_id ?? null +} diff --git a/src/platform/workspace/stores/deploymentPickStore.test.ts b/src/platform/workspace/stores/deploymentPickStore.test.ts new file mode 100644 index 00000000000..b846f52e236 --- /dev/null +++ b/src/platform/workspace/stores/deploymentPickStore.test.ts @@ -0,0 +1,1221 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { WorkspaceDeploymentList } from '@/platform/workspace/api/workspaceApi' + +import { DEPLOYMENT_LISTING_BACKSTOP_MS } from '@/platform/workspace/api/deploymentListingTimeouts' + +import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' + +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' + +import { useDeploymentPickStore } from './deploymentPickStore' + +const mockWorkspaceApi = vi.hoisted(() => ({ + listDeployments: vi.fn(), + pickDeployment: vi.fn(), + clearDeployment: vi.fn(), + setDefaultDeployment: vi.fn(), + clearDefaultDeployment: vi.fn() +})) + +vi.mock(import('@/platform/workspace/api/workspaceApi'), async () => { + class WorkspaceApiError extends Error { + constructor( + message: string, + public readonly status?: number, + public readonly code?: string + ) { + super(message) + this.name = 'WorkspaceApiError' + } + } + return { workspaceApi: mockWorkspaceApi, WorkspaceApiError } +}) + +const listing: WorkspaceDeploymentList = { + builds_visible: true, + picked_deployment_id: 'dep-2', + pick_source: 'browser', + items: [ + { + deployment_id: 'dep-2', + release_id: 'r-2', + build_id: 'b-1', + build_name: 'Studio Build', + release_version: 2, + status: 'ready', + created_at: '2026-10-01T00:00:00Z' + }, + { + deployment_id: 'dep-1', + release_id: 'r-1', + build_id: 'b-1', + build_name: 'Studio Build', + release_version: 1, + status: 'stopped', + created_at: '2026-09-20T00:00:00Z' + } + ] +} + +describe('useDeploymentPickStore', () => { + const reload = vi.fn() + + beforeEach(() => { + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-1' }) + Object.defineProperty(window, 'location', { + value: { reload, origin: 'http://localhost' }, + writable: true, + configurable: true + }) + }) + + it('loads the listing and knows which deployment is picked', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + const store = useDeploymentPickStore() + expect(store.isVisible).toBe(false) + + await store.load() + + expect(mockWorkspaceApi.listDeployments).toHaveBeenCalledWith('ws-1') + expect(store.state.phase).toBe('ready') + expect(store.isVisible).toBe(true) + expect(store.deployments).toHaveLength(2) + expect(store.pickedDeploymentId).toBe('dep-2') + expect(store.pickedDeployment?.build_name).toBe('Studio Build') + expect(store.pickSource).toBe('browser') + expect(store.followsWorkspace).toBe(false) + expect(store.defaultDeploymentId).toBeNull() + expect(store.canSetDefault).toBe(false) + }) + + it('remembers the deployment the page booted on from the first listing only', async () => { + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce(listing) + .mockResolvedValue({ ...listing, picked_deployment_id: 'dep-1' }) + const store = useDeploymentPickStore() + expect(store.bootDeployment).toBeUndefined() + + await Promise.all([store.loadOnce(), store.loadOnce()]) + expect(mockWorkspaceApi.listDeployments).toHaveBeenCalledOnce() + expect(store.bootDeployment?.deployment_id).toBe('dep-2') + + await store.load() + expect(store.pickedDeploymentId).toBe('dep-1') + expect(store.bootDeployment?.deployment_id).toBe('dep-2') + }) + + it('boots on Comfy Cloud when ingest reports the pick gone', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: undefined, + gone_picked_deployment_id: 'dep-gone' + }) + const store = useDeploymentPickStore() + await store.loadOnce() + + expect(store.goneDeployment).toBe('pick') + expect(store.bootDeployment).toBeNull() + }) + + it.for(['browser', 'workspace_default'] as const)( + 'does not invent a gone %s deployment from an inconsistent listing', + async (pickSource) => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: 'dep-unlisted', + pick_source: pickSource + } satisfies WorkspaceDeploymentList) + const store = useDeploymentPickStore() + + await store.loadOnce() + + expect(store.goneDeployment).toBeNull() + } + ) + + it('keeps saying the pick is gone after the one listing that reported it', async () => { + const onCloud = { + ...listing, + picked_deployment_id: undefined, + pick_source: undefined + } + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce({ ...onCloud, gone_picked_deployment_id: 'dep-x' }) + .mockResolvedValue(onCloud) + const store = useDeploymentPickStore() + await store.loadOnce() + expect(store.goneDeployment).toBe('pick') + + await store.load() + + expect(store.goneDeployment).toBe('pick') + expect(store.bootDeployment).toBeNull() + }) + + it('stops saying the pick is gone once a later listing shows a picked deployment', async () => { + const onCloud = { + ...listing, + picked_deployment_id: undefined, + pick_source: undefined + } + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce({ ...onCloud, gone_picked_deployment_id: 'dep-x' }) + .mockResolvedValueOnce(onCloud) + .mockResolvedValue({ ...listing, picked_deployment_id: 'dep-1' }) + const store = useDeploymentPickStore() + await store.loadOnce() + await store.load() + expect(store.goneDeployment).toBe('pick') + + await store.load() + + expect(store.pickedDeployment?.deployment_id).toBe('dep-1') + expect(store.goneDeployment).toBeNull() + }) + + it.for([ + { now: 'the same deployment and Release', next: listing, change: null }, + { + now: 'its deployment on another Release', + next: { + ...listing, + items: [{ ...listing.items[0], release_id: 'r-3' }, listing.items[1]] + }, + change: 'release' + }, + { + now: 'another deployment with another Release', + next: { ...listing, picked_deployment_id: 'dep-1' }, + change: 'deployment' + }, + { + now: 'another deployment of the same Release', + next: { + ...listing, + picked_deployment_id: 'dep-1', + items: [listing.items[0], { ...listing.items[1], release_id: 'r-2' }] + }, + change: null + }, + { + now: 'Comfy Cloud', + next: { + ...listing, + picked_deployment_id: undefined, + pick_source: undefined + }, + change: 'deployment' + } + ] satisfies { + now: string + next: WorkspaceDeploymentList + change: 'release' | 'deployment' | null + }[])( + 'says what changed when a later listing runs on $now', + async ({ next, change }) => { + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce(listing) + .mockResolvedValue(next) + const store = useDeploymentPickStore() + await store.loadOnce() + expect(store.changeSinceBoot).toBeNull() + + await store.load() + + expect(store.changeSinceBoot).toBe(change) + } + ) + + it('follows the workspace default when the browser has no pick of its own', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + pick_source: 'workspace_default', + default_deployment_id: 'dep-2' + }) + const store = useDeploymentPickStore() + await store.load() + + expect(store.pickedDeploymentId).toBe('dep-2') + expect(store.pickSource).toBe('workspace_default') + expect(store.followsWorkspace).toBe(true) + expect(store.defaultDeploymentId).toBe('dep-2') + expect(store.defaultDeployment?.release_version).toBe(2) + + // Already following: nothing to drop. + await expect(store.followWorkspace()).resolves.toBeNull() + expect(mockWorkspaceApi.clearDeployment).not.toHaveBeenCalled() + + // Picking Comfy Cloud is this browser's own choice, even though the + // browser runs on dep-2 only because it follows the default: it goes + // through the clear route and reloads. + mockWorkspaceApi.clearDeployment.mockResolvedValue(undefined) + await expect(store.pick(null)).resolves.toBeNull() + expect(mockWorkspaceApi.clearDeployment).toHaveBeenCalledWith('ws-1') + expect(reload).toHaveBeenCalledOnce() + }) + + it('drops its own pick to follow the workspace, through the clear route with follow=workspace', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: 'dep-1', + default_deployment_id: 'dep-2' + }) + mockWorkspaceApi.clearDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.followWorkspace()).resolves.toBeNull() + + expect(mockWorkspaceApi.clearDeployment).toHaveBeenCalledWith('ws-1', { + follow: 'workspace' + }) + expect(reload).toHaveBeenCalledOnce() + }) + + it('an owner sets the picked deployment as the workspace default and the listing refreshes', async () => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce(listing) + .mockResolvedValueOnce({ ...listing, default_deployment_id: 'dep-2' }) + mockWorkspaceApi.setDefaultDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + expect(store.canSetDefault).toBe(true) + + await expect(store.setDefault('dep-2')).resolves.toBeNull() + + expect(mockWorkspaceApi.setDefaultDeployment).toHaveBeenCalledWith('ws-1', { + deployment_id: 'dep-2' + }) + expect(reload).not.toHaveBeenCalled() + expect(store.state.phase).toBe('ready') + expect(store.defaultDeploymentId).toBe('dep-2') + + // Clearing it, likewise; setting what is already set is a no-op. + await expect(store.setDefault('dep-2')).resolves.toBeNull() + expect(mockWorkspaceApi.setDefaultDeployment).toHaveBeenCalledOnce() + mockWorkspaceApi.listDeployments.mockResolvedValueOnce(listing) + mockWorkspaceApi.clearDefaultDeployment.mockResolvedValue(undefined) + await expect(store.setDefault(null)).resolves.toBeNull() + expect(mockWorkspaceApi.clearDefaultDeployment).toHaveBeenCalledWith('ws-1') + expect(store.defaultDeploymentId).toBeNull() + }) + + it('a browser that follows the workspace reloads when its owner changes the default', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: undefined, + pick_source: undefined + }) + mockWorkspaceApi.setDefaultDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + expect(store.followsWorkspace).toBe(true) + + await expect(store.setDefault('dep-2')).resolves.toBeNull() + expect(reload).toHaveBeenCalledOnce() + }) + + it('an owner clears a workspace default that no longer exists, and a browser that follows it reloads', async () => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: undefined, + pick_source: undefined, + gone_default_deployment_id: 'dep-gone' + }) + mockWorkspaceApi.clearDefaultDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + expect(store.defaultDeploymentId).toBeNull() + expect(store.goneDeployment).toBe('default') + + await expect(store.setDefault(null)).resolves.toBeNull() + + expect(mockWorkspaceApi.clearDefaultDeployment).toHaveBeenCalledWith('ws-1') + expect(reload).toHaveBeenCalledOnce() + }) + + it("hands back the server's refusal of a default and stays ready", async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + mockWorkspaceApi.setDefaultDeployment.mockRejectedValue( + new WorkspaceApiError( + 'only a workspace owner can set the default deployment', + 403 + ) + ) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.setDefault('dep-1')).resolves.toBe( + 'only a workspace owner can set the default deployment' + ) + expect(store.state.phase).toBe('ready') + expect(store.defaultDeploymentId).toBeNull() + expect(reload).not.toHaveBeenCalled() + }) + + it('hides itself when the account is outside the rollout', async () => { + mockWorkspaceApi.listDeployments.mockRejectedValue( + new WorkspaceApiError( + 'not enabled for this account yet', + 403, + 'FORBIDDEN' + ) + ) + const store = useDeploymentPickStore() + await store.load() + expect(store.state.phase).toBe('hidden') + expect(store.isVisible).toBe(false) + }) + + it('picks a deployment and reloads the page', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + mockWorkspaceApi.pickDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.pick('dep-1')).resolves.toBeNull() + + expect(mockWorkspaceApi.pickDeployment).toHaveBeenCalledWith('ws-1', { + deployment_id: 'dep-1' + }) + expect(reload).toHaveBeenCalledOnce() + }) + + it('clears the pick for Comfy Cloud and reloads', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + mockWorkspaceApi.clearDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.pick(null)).resolves.toBeNull() + + expect(mockWorkspaceApi.clearDeployment).toHaveBeenCalledWith('ws-1') + expect(mockWorkspaceApi.pickDeployment).not.toHaveBeenCalled() + expect(reload).toHaveBeenCalledOnce() + }) + + it('hands back a refused pick and stays ready, without reloading', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + mockWorkspaceApi.pickDeployment.mockRejectedValue( + new WorkspaceApiError( + "deployment dep-1 is not one of this workspace's", + 422 + ) + ) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.pick('dep-1')).resolves.toBe( + "deployment dep-1 is not one of this workspace's" + ) + expect(store.state.phase).toBe('ready') + expect(store.pickedDeploymentId).toBe('dep-2') + expect(reload).not.toHaveBeenCalled() + }) + + it('picking the current deployment is a no-op', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.pick('dep-2')).resolves.toBeNull() + expect(mockWorkspaceApi.pickDeployment).not.toHaveBeenCalled() + expect(reload).not.toHaveBeenCalled() + }) + + it('ignores a listing that arrives after the workspace changed', async () => { + let resolve: (value: WorkspaceDeploymentList) => void = () => {} + mockWorkspaceApi.listDeployments.mockReturnValue( + new Promise((r) => { + resolve = r + }) + ) + const store = useDeploymentPickStore() + const loading = store.load() + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-2' }) + resolve(listing) + await loading + + expect(store.state.phase).toBe('idle') + expect(store.deployments).toEqual([]) + }) + + it("hides the last workspace's listing as soon as the workspace changes", async () => { + mockWorkspaceApi.listDeployments.mockResolvedValueOnce(listing) + const store = useDeploymentPickStore() + await store.load() + expect(store.pickedDeploymentId).toBe('dep-2') + + mockWorkspaceApi.listDeployments.mockRejectedValue(new Error('offline')) + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-2' }) + expect(store.isVisible).toBe(false) + expect(store.deployments).toEqual([]) + expect(store.pickedDeploymentId).toBeNull() + + await store.load() + expect(mockWorkspaceApi.listDeployments).toHaveBeenLastCalledWith('ws-2') + expect(store.state.phase).toBe('hidden') + }) + + it("loads the new workspace's listing on the next loadOnce", async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + const store = useDeploymentPickStore() + await store.loadOnce() + + Object.assign(useTeamWorkspaceStore(), { workspaceId: 'ws-2' }) + await store.loadOnce() + + expect(mockWorkspaceApi.listDeployments).toHaveBeenLastCalledWith('ws-2') + expect(store.pickedDeploymentId).toBe('dep-2') + }) + + describe('a pick from a link', () => { + it('keeps a link pick exclusive when a late listing arrives after a failed boot listing', async () => { + const listed = deferred() + const put = deferred() + const started = deferred() + mockWorkspaceApi.listDeployments + .mockRejectedValueOnce(new Error('listing failed')) + .mockReturnValueOnce(listed.promise) + mockWorkspaceApi.pickDeployment.mockImplementation(() => { + started.resolve() + return put.promise + }) + const store = useDeploymentPickStore() + await store.loadOnce() + const refresh = store.load() + const linked = store.pickFromLink('dep-1') + await started.promise + listed.resolve(listing) + await refresh + const competing = store.pick('dep-other') + put.resolve() + await Promise.all([linked, competing]) + expect(mockWorkspaceApi.pickDeployment).toHaveBeenCalledTimes(1) + expect(reload).toHaveBeenCalledTimes(1) + }) + + it('stops waiting for a stalled listing and never picks when it eventually answers', async () => { + vi.useFakeTimers() + const listed = deferred() + mockWorkspaceApi.listDeployments.mockReturnValue(listed.promise) + const store = useDeploymentPickStore() + const settled = vi.fn() + const linked = store.pickFromLink('dep-1').then(settled) + await vi.advanceTimersByTimeAsync(DEPLOYMENT_LISTING_BACKSTOP_MS - 1) + expect(settled).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(settled).toHaveBeenCalledWith({ kind: 'timedOut' }) + listed.resolve(listing) + await linked + expect(mockWorkspaceApi.pickDeployment).not.toHaveBeenCalled() + expect(reload).not.toHaveBeenCalled() + }) + + it('times out and cancels a stalled selection after a slow failed listing without reloading on late success', async () => { + vi.useFakeTimers() + const listed = deferred() + const selected = deferred() + let selectionSignal: AbortSignal | undefined + mockWorkspaceApi.listDeployments.mockReturnValue(listed.promise) + mockWorkspaceApi.pickDeployment.mockImplementation( + (_id: string, _payload: unknown, signal?: AbortSignal) => { + selectionSignal = signal + return selected.promise + } + ) + const store = useDeploymentPickStore() + const settled = vi.fn() + const linked = store.pickFromLink('dep-1').then(settled) + await vi.advanceTimersByTimeAsync(30_000) + listed.reject(new Error('listing timed out')) + await vi.advanceTimersByTimeAsync(0) + expect(mockWorkspaceApi.pickDeployment).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(DEPLOYMENT_LISTING_BACKSTOP_MS) + expect(settled).toHaveBeenCalledWith({ kind: 'timedOut' }) + expect(selectionSignal?.aborted).toBe(true) + expect(store.isSwitching).toBe(false) + selected.resolve() + await linked + await vi.advanceTimersByTimeAsync(0) + expect(reload).not.toHaveBeenCalled() + }) + + it.for([12_000, DEPLOYMENT_LISTING_BACKSTOP_MS - 1])( + 'selects the linked deployment when the listing succeeds after %i ms', + async (delay) => { + vi.useFakeTimers() + const listed = deferred() + mockWorkspaceApi.listDeployments.mockReturnValue(listed.promise) + mockWorkspaceApi.pickDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + const linked = store.pickFromLink('dep-1') + await vi.advanceTimersByTimeAsync(delay) + listed.resolve(listing) + await expect(linked).resolves.toEqual({ kind: 'picked' }) + expect(mockWorkspaceApi.pickDeployment).toHaveBeenCalledExactlyOnceWith( + 'ws-1', + { deployment_id: 'dep-1' }, + expect.any(AbortSignal) + ) + expect(reload).toHaveBeenCalledOnce() + } + ) + + it('waits for the first listing, then picks and reloads', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + mockWorkspaceApi.pickDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + + await expect(store.pickFromLink('dep-1')).resolves.toEqual({ + kind: 'picked' + }) + + expect(mockWorkspaceApi.listDeployments).toHaveBeenCalledOnce() + expect(mockWorkspaceApi.pickDeployment).toHaveBeenCalledWith( + 'ws-1', + { + deployment_id: 'dep-1' + }, + expect.any(AbortSignal) + ) + expect(reload).toHaveBeenCalledOnce() + }) + + it('does nothing for the deployment this browser already runs on', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + const store = useDeploymentPickStore() + + await expect(store.pickFromLink('dep-2')).resolves.toEqual({ + kind: 'unchanged' + }) + expect(mockWorkspaceApi.pickDeployment).not.toHaveBeenCalled() + expect(reload).not.toHaveBeenCalled() + }) + + // The switcher stays hidden outside the rollout, but a link still asks, + // so the person learns why nothing changed. + it("hands back the server's refusal when the account is outside the rollout", async () => { + mockWorkspaceApi.listDeployments.mockRejectedValue( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + mockWorkspaceApi.pickDeployment.mockRejectedValue( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + const store = useDeploymentPickStore() + + await expect(store.pickFromLink('dep-1')).resolves.toEqual({ + kind: 'refused', + message: 'not enabled for this account yet' + }) + expect(store.state.phase).toBe('hidden') + expect(reload).not.toHaveBeenCalled() + }) + + it("hands back a refused pick and keeps the listing's pick", async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue(listing) + mockWorkspaceApi.pickDeployment.mockRejectedValue( + new WorkspaceApiError('deployment not found', 422) + ) + const store = useDeploymentPickStore() + + await expect(store.pickFromLink('dep-gone')).resolves.toEqual({ + kind: 'refused', + message: 'deployment not found' + }) + expect(store.state.phase).toBe('ready') + expect(store.pickedDeploymentId).toBe('dep-2') + expect(reload).not.toHaveBeenCalled() + }) + }) + + it('does nothing without an active workspace', async () => { + Object.assign(useTeamWorkspaceStore(), { workspaceId: null }) + const store = useDeploymentPickStore() + await store.load() + expect(mockWorkspaceApi.listDeployments).not.toHaveBeenCalled() + expect(store.state.phase).toBe('idle') + }) + + describe('while the listing loads', () => { + it('stays hidden until the first listing answers', async () => { + const listed = deferred() + mockWorkspaceApi.listDeployments.mockReturnValue(listed.promise) + const store = useDeploymentPickStore() + + const loading = store.load() + expect(store.isVisible).toBe(false) + + listed.resolve(listing) + await loading + expect(store.isVisible).toBe(true) + }) + + it('stays hidden while it reloads for an account the last answer hid', async () => { + mockWorkspaceApi.listDeployments.mockRejectedValueOnce( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + const store = useDeploymentPickStore() + await store.load() + expect(store.isVisible).toBe(false) + + // The popover remounts the switcher on every open, so every open reloads. + const listed = deferred() + mockWorkspaceApi.listDeployments.mockReturnValue(listed.promise) + void store.load() + expect(store.isVisible).toBe(false) + }) + + it('keeps the last listing on screen until the new one lands', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValueOnce({ + ...listing, + default_deployment_id: 'dep-1' + }) + const store = useDeploymentPickStore() + await store.load() + + const listed = deferred() + mockWorkspaceApi.listDeployments.mockReturnValue(listed.promise) + const reloading = store.load() + expect(store.isVisible).toBe(true) + expect(store.pickedDeploymentId).toBe('dep-2') + expect(store.defaultDeploymentId).toBe('dep-1') + expect(store.deployments).toHaveLength(2) + + listed.resolve({ ...listing, picked_deployment_id: 'dep-1' }) + await reloading + expect(store.pickedDeploymentId).toBe('dep-1') + }) + + it('shows the new default at once while the listing refreshes after an owner changes it', async () => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments.mockResolvedValueOnce({ + ...listing, + default_deployment_id: 'dep-1' + }) + mockWorkspaceApi.setDefaultDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + + const listed = deferred() + mockWorkspaceApi.listDeployments.mockReturnValue(listed.promise) + const setting = store.setDefault('dep-2') + await vi.waitFor(() => + expect(mockWorkspaceApi.listDeployments).toHaveBeenCalledTimes(2) + ) + expect(store.defaultDeploymentId).toBe('dep-2') + expect(store.isSwitching).toBe(false) + + listed.resolve({ ...listing, default_deployment_id: 'dep-2' }) + await setting + expect(store.defaultDeploymentId).toBe('dep-2') + }) + + it('keeps the switcher locked when a listing lands while a pick is in flight', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValueOnce(listing) + const store = useDeploymentPickStore() + await store.load() + + // The popover was reopened: a reload is in flight, the rows are clickable. + const listed = deferred() + mockWorkspaceApi.listDeployments.mockReturnValueOnce(listed.promise) + const reloading = store.load() + const put = deferred() + mockWorkspaceApi.pickDeployment.mockReturnValueOnce(put.promise) + const picking = store.pick('dep-1') + + listed.resolve({ ...listing, default_deployment_id: 'dep-1' }) + await reloading + expect(store.isSwitching).toBe(true) + expect(store.state).toMatchObject({ phase: 'switching', target: 'dep-1' }) + expect(store.defaultDeploymentId).toBe('dep-1') + + // A second pick cannot go out while the first is in flight. + await expect(store.pick(null)).resolves.toBeNull() + expect(mockWorkspaceApi.clearDeployment).not.toHaveBeenCalled() + + put.resolve() + await picking + expect(mockWorkspaceApi.pickDeployment).toHaveBeenCalledOnce() + expect(reload).toHaveBeenCalledOnce() + }) + + it.for([ + { then: 'a listing answers', outcome: 'loaded' }, + { then: 'nothing more answers', outcome: 'refused' } + ])( + 'keeps the switcher locked when a refresh is refused while a pick is in flight and $then', + async ({ outcome }) => { + mockWorkspaceApi.listDeployments.mockResolvedValueOnce(listing) + const store = useDeploymentPickStore() + await store.load() + const put = deferred() + mockWorkspaceApi.pickDeployment.mockReturnValueOnce(put.promise) + const picking = store.pick('dep-1') + + mockWorkspaceApi.listDeployments.mockRejectedValueOnce( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + await store.load() + expect(store.isVisible).toBe(false) + expect(store.isSwitching).toBe(true) + if (outcome === 'loaded') { + mockWorkspaceApi.listDeployments.mockResolvedValueOnce(listing) + await store.load() + expect(store.isVisible).toBe(true) + } + + await expect(store.pick(null)).resolves.toBeNull() + await expect(store.setDefault('dep-1')).resolves.toBeNull() + expect(mockWorkspaceApi.clearDeployment).not.toHaveBeenCalled() + expect(mockWorkspaceApi.setDefaultDeployment).not.toHaveBeenCalled() + + put.resolve() + await picking + expect(mockWorkspaceApi.pickDeployment).toHaveBeenCalledOnce() + expect(reload).toHaveBeenCalledOnce() + } + ) + + it('hides itself when a pick refused after a refresh said the account left the rollout', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValueOnce(listing) + const store = useDeploymentPickStore() + await store.load() + const put = deferred() + mockWorkspaceApi.pickDeployment.mockReturnValueOnce(put.promise) + const picking = store.pick('dep-1') + mockWorkspaceApi.listDeployments.mockRejectedValueOnce( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + await store.load() + + put.reject(new WorkspaceApiError('not enabled for this account yet', 403)) + await expect(picking).resolves.toBe('not enabled for this account yet') + expect(store.state.phase).toBe('hidden') + expect(reload).not.toHaveBeenCalled() + }) + + it('returns to the newer listing when a pick that a listing overtook is refused', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValueOnce(listing) + const store = useDeploymentPickStore() + await store.load() + + const listed = deferred() + mockWorkspaceApi.listDeployments.mockReturnValueOnce(listed.promise) + const reloading = store.load() + const put = deferred() + mockWorkspaceApi.pickDeployment.mockReturnValueOnce(put.promise) + const picking = store.pick('dep-1') + listed.resolve({ ...listing, default_deployment_id: 'dep-1' }) + await reloading + + put.reject( + new WorkspaceApiError("deployment is not one of this workspace's", 422) + ) + await expect(picking).resolves.toBe( + "deployment is not one of this workspace's" + ) + expect(store.state.phase).toBe('ready') + expect(store.defaultDeploymentId).toBe('dep-1') + expect(reload).not.toHaveBeenCalled() + }) + }) + + describe('when the listing fails', () => { + it.for([ + ['a 400', new WorkspaceApiError('invalid workspace id', 400)], + ['a 401', new WorkspaceApiError('Authentication required', 401)], + ['a 403', new WorkspaceApiError('not enabled for this account yet', 403)], + [ + 'a 404 (ingest without the routes)', + new WorkspaceApiError('404 page not found', 404) + ], + ['a 500', new WorkspaceApiError('Failed to list deployments', 500)], + [ + 'a 503', + new WorkspaceApiError( + 'could not list deployments from comfy-deploy; try again', + 503 + ) + ], + ['a network error', new WorkspaceApiError('Network Error')], + ['no signed-in user', new Error('User not authenticated')] + ] as const)( + 'hides itself on a first load that fails with %s', + async ([, err]) => { + mockWorkspaceApi.listDeployments.mockRejectedValue(err) + const store = useDeploymentPickStore() + await store.load() + expect(store.state.phase).toBe('hidden') + expect(store.isVisible).toBe(false) + } + ) + + it('keeps the last listing when a refresh fails', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValueOnce(listing) + const store = useDeploymentPickStore() + await store.load() + + mockWorkspaceApi.listDeployments.mockRejectedValueOnce( + new WorkspaceApiError( + 'could not list deployments from comfy-deploy; try again', + 503 + ) + ) + await store.load() + expect(store.state.phase).toBe('ready') + expect(store.isVisible).toBe(true) + expect(store.pickedDeploymentId).toBe('dep-2') + }) + + it('hides itself when a refresh says the account left the rollout', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValueOnce(listing) + const store = useDeploymentPickStore() + await store.load() + + mockWorkspaceApi.listDeployments.mockRejectedValueOnce( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + await store.load() + expect(store.isVisible).toBe(false) + }) + + it('ends the switch when the refresh after a new default fails', async () => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce(listing) + .mockRejectedValueOnce(new WorkspaceApiError('Bad Gateway', 502)) + mockWorkspaceApi.setDefaultDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.setDefault('dep-2')).resolves.toBeNull() + expect(store.isSwitching).toBe(false) + expect(store.state.phase).toBe('ready') + }) + + it.for([ + ['sets', 'dep-2', 'dep-2'], + ['clears', null, null] + ] as const)( + 'shows the default an owner %s even when the refresh after it fails', + async ([, target, shown]) => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce({ ...listing, default_deployment_id: 'dep-1' }) + .mockRejectedValueOnce( + new WorkspaceApiError( + 'could not list deployments from comfy-deploy; try again', + 503 + ) + ) + mockWorkspaceApi.setDefaultDeployment.mockResolvedValue(undefined) + mockWorkspaceApi.clearDefaultDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.setDefault(target)).resolves.toBeNull() + expect(mockWorkspaceApi.listDeployments).toHaveBeenCalledTimes(2) + expect(store.defaultDeploymentId).toBe(shown) + expect(store.state.phase).toBe('ready') + // This browser has its own pick, so the new default does not reload it. + expect(reload).not.toHaveBeenCalled() + } + ) + }) + + describe('when answers arrive out of order', () => { + it.for([ + [ + 'fails', + () => + mockWorkspaceApi.listDeployments.mockRejectedValueOnce( + new WorkspaceApiError( + 'could not list deployments from comfy-deploy; try again', + 503 + ) + ) + ], + [ + 'answers first', + () => + mockWorkspaceApi.listDeployments.mockResolvedValueOnce({ + ...listing, + default_deployment_id: 'dep-2' + }) + ] + ] as const)( + 'keeps a new default when a listing asked for before it lands last and the refresh %s', + async ([, queueRefresh]) => { + Object.assign(useTeamWorkspaceStore(), { + workspaceId: 'ws-1', + activeWorkspace: { id: 'ws-1', role: 'owner' } + }) + mockWorkspaceApi.listDeployments.mockResolvedValueOnce({ + ...listing, + default_deployment_id: 'dep-1' + }) + mockWorkspaceApi.setDefaultDeployment.mockResolvedValue(undefined) + const store = useDeploymentPickStore() + await store.load() + + // The popover was reopened: a listing with the old default is in flight. + const stale = deferred() + mockWorkspaceApi.listDeployments.mockReturnValueOnce(stale.promise) + const reloading = store.load() + + queueRefresh() + await expect(store.setDefault('dep-2')).resolves.toBeNull() + expect(store.defaultDeploymentId).toBe('dep-2') + + stale.resolve({ ...listing, default_deployment_id: 'dep-1' }) + await reloading + expect(store.defaultDeploymentId).toBe('dep-2') + expect(store.state.phase).toBe('ready') + } + ) + + it('keeps the newer listing when an older one lands after it', async () => { + const older = deferred() + mockWorkspaceApi.listDeployments + .mockReturnValueOnce(older.promise) + .mockResolvedValueOnce({ ...listing, picked_deployment_id: 'dep-1' }) + const store = useDeploymentPickStore() + const first = store.load() + await store.load() + expect(store.pickedDeploymentId).toBe('dep-1') + + older.resolve(listing) + await first + expect(store.pickedDeploymentId).toBe('dep-1') + }) + + it.for([ + { newer: 'shows no pick', reply: {}, gone: 'pick' }, + { + newer: 'shows a deployment picked', + reply: { picked_deployment_id: 'dep-1', pick_source: 'browser' }, + gone: null + } + ] satisfies { + newer: string + reply: Partial + gone: 'pick' | null + }[])( + 'says the pick is gone: $gone, when an older listing reports it gone after a newer one that $newer answered', + async ({ reply, gone }) => { + const older = deferred() + mockWorkspaceApi.listDeployments + .mockReturnValueOnce(older.promise) + .mockResolvedValueOnce({ + ...listing, + picked_deployment_id: undefined, + pick_source: undefined, + ...reply + }) + const store = useDeploymentPickStore() + const first = store.load() + await store.load() + + older.resolve({ + ...listing, + picked_deployment_id: undefined, + pick_source: undefined, + gone_picked_deployment_id: 'dep-gone' + }) + await first + + expect(store.goneDeployment).toBe(gone) + } + ) + + it('stays visible when an older listing fails after a newer one answered', async () => { + const older = deferred() + mockWorkspaceApi.listDeployments + .mockReturnValueOnce(older.promise) + .mockResolvedValueOnce(listing) + const store = useDeploymentPickStore() + const first = store.load() + await store.load() + + older.reject( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + await first + expect(store.isVisible).toBe(true) + expect(store.pickedDeploymentId).toBe('dep-2') + }) + + // The popover was closed and reopened before the first listing answered, + // so two listings are in flight on the first load. + it.for([ + ['a 503', new WorkspaceApiError('upstream', 503)], + ['a network error', new Error('Network Error')] + ] as const)( + 'shows an older listing that answered when the newer one fails with %s', + async ([, error]) => { + const newer = deferred() + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce(listing) + .mockReturnValueOnce(newer.promise) + const store = useDeploymentPickStore() + const first = store.load() + const second = store.load() + await first + expect(store.isVisible).toBe(true) + expect(store.pickedDeploymentId).toBe('dep-2') + + newer.reject(error) + await second + expect(store.state.phase).toBe('ready') + expect(store.pickedDeploymentId).toBe('dep-2') + } + ) + + it('shows an older listing that answered while the newer one never answers', async () => { + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce(listing) + .mockReturnValueOnce(new Promise(() => {})) + const store = useDeploymentPickStore() + const first = store.load() + void store.load() + await first + expect(store.state.phase).toBe('ready') + expect(store.pickedDeploymentId).toBe('dep-2') + }) + + it('shows an older listing that answers after the newer one failed', async () => { + const older = deferred() + mockWorkspaceApi.listDeployments + .mockReturnValueOnce(older.promise) + .mockRejectedValueOnce(new Error('Network Error')) + const store = useDeploymentPickStore() + const first = store.load() + await store.load() + expect(store.isVisible).toBe(false) + + older.resolve(listing) + await first + expect(store.state.phase).toBe('ready') + expect(store.pickedDeploymentId).toBe('dep-2') + }) + + it('hides itself when the newer listing says the account left the rollout', async () => { + const newer = deferred() + mockWorkspaceApi.listDeployments + .mockResolvedValueOnce(listing) + .mockReturnValueOnce(newer.promise) + const store = useDeploymentPickStore() + const first = store.load() + const second = store.load() + await first + + newer.reject( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + await second + expect(store.state.phase).toBe('hidden') + }) + + it('takes an older 403 at once while a newer listing is still in flight', async () => { + const older = deferred() + const newer = deferred() + mockWorkspaceApi.listDeployments + .mockReturnValueOnce(older.promise) + .mockReturnValueOnce(newer.promise) + const store = useDeploymentPickStore() + const first = store.load() + const second = store.load() + + older.reject( + new WorkspaceApiError('not enabled for this account yet', 403) + ) + await first + // A refusal is an answer about the account, unlike a plain failure. + expect(store.state.phase).toBe('hidden') + + newer.resolve(listing) + await second + expect(store.state.phase).toBe('ready') + }) + + it('ignores an older failure while a newer listing is still in flight', async () => { + const older = deferred() + const newer = deferred() + mockWorkspaceApi.listDeployments + .mockReturnValueOnce(older.promise) + .mockReturnValueOnce(newer.promise) + const store = useDeploymentPickStore() + const first = store.load() + const second = store.load() + + older.reject(new Error('Network Error')) + await first + // Still waiting on the newer listing, not settled on "the load failed". + expect(store.state.phase).toBe('idle') + + newer.resolve(listing) + await second + expect(store.state.phase).toBe('ready') + }) + }) + + describe('clicking the row already checked', () => { + it('does nothing on Comfy Cloud with no pick and no default', async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + picked_deployment_id: undefined, + pick_source: undefined + }) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.pick(null)).resolves.toBeNull() + expect(mockWorkspaceApi.clearDeployment).not.toHaveBeenCalled() + expect(reload).not.toHaveBeenCalled() + }) + + it("does nothing on the workspace default's row, so the browser keeps following it", async () => { + mockWorkspaceApi.listDeployments.mockResolvedValue({ + ...listing, + pick_source: 'workspace_default', + default_deployment_id: 'dep-2' + }) + const store = useDeploymentPickStore() + await store.load() + + await expect(store.pick('dep-2')).resolves.toBeNull() + expect(mockWorkspaceApi.pickDeployment).not.toHaveBeenCalled() + expect(reload).not.toHaveBeenCalled() + expect(store.followsWorkspace).toBe(true) + }) + }) +}) + +function deferred() { + let resolve: (value: T) => void = () => {} + let reject: (err: unknown) => void = () => {} + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} diff --git a/src/platform/workspace/stores/deploymentPickStore.ts b/src/platform/workspace/stores/deploymentPickStore.ts new file mode 100644 index 00000000000..62743a5af99 --- /dev/null +++ b/src/platform/workspace/stores/deploymentPickStore.ts @@ -0,0 +1,436 @@ +import type { WorkspaceDeployment } from '@/platform/workspace/api/workspaceApi' +import { defineStore } from 'pinia' +import { computed, shallowRef, watch } from 'vue' + +import { pendingServerFact } from '@/platform/serverFacts/pendingServerFact' +import { DEPLOYMENT_LISTING_BACKSTOP_MS } from '@/platform/workspace/api/deploymentListingTimeouts' +import { + WorkspaceApiError, + workspaceApi +} from '@/platform/workspace/api/workspaceApi' +import type { + DeploymentPickEvent, + DeploymentPickSource, + DeploymentPickState +} from '@/platform/workspace/deploymentPickState' +import { + changeBetween, + loadedEvent, + reduceDeploymentPick +} from '@/platform/workspace/deploymentPickState' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' + +/** + * What picking a linked deployment did: `picked` (the page is reloading onto + * it), `unchanged` (this browser already runs on it), or `refused` with the + * server's reason. + */ +type LinkPickOutcome = + | { kind: 'picked' } + | { kind: 'unchanged' } + | { kind: 'timedOut' } + | { kind: 'refused'; message: string } + +/** + * The deployment this browser runs on and the deployments it may pick + * (FE-2434), plus the workspace's default deployment an owner sets for + * members with no pick of their own (BE-17480). A deployment keeps its URL + * while its owner updates it to new Releases, so a pick follows those updates. + * + * A pick changes what the editor is served at boot (the node + * catalog of the Release the deployment runs and its packs' JavaScript), so a successful pick or clear reloads + * the page rather than patching the running editor. + */ +export const useDeploymentPickStore = defineStore('deploymentPick', () => { + const workspaceStore = useTeamWorkspaceStore() + + const state = shallowRef({ phase: 'idle' }) + + function dispatch(event: DeploymentPickEvent) { + state.value = reduceDeploymentPick(state.value, event) + } + + const deployments = computed(() => + 'deployments' in state.value ? state.value.deployments : [] + ) + const pickedDeploymentId = computed(() => + 'pickedDeploymentId' in state.value ? state.value.pickedDeploymentId : null + ) + const pickedDeployment = computed( + () => + deployments.value.find( + (d) => d.deployment_id === pickedDeploymentId.value + ) ?? null + ) + const pickSource = computed(() => + 'pickSource' in state.value ? state.value.pickSource : null + ) + /** + * The workspace's default deployment when it is gone: still recorded, so + * an owner can clear it, but members on it run on Comfy Cloud. + */ + const goneDefaultDeploymentId = computed(() => + 'goneDefaultDeploymentId' in state.value + ? state.value.goneDefaultDeploymentId + : null + ) + /** + * Set once a listing says ingest found this browser's own pick gone and + * cleared it. Only that one listing says so, so the page keeps it until a + * later listing shows a deployment picked again. + */ + const sawPickGone = shallowRef(false) + const goneDeployment = computed<'pick' | 'default' | null>(() => { + if (sawPickGone.value) return 'pick' + if ( + goneDefaultDeploymentId.value !== null && + pickSource.value !== 'browser' + ) { + return 'default' + } + return null + }) + const defaultDeploymentId = computed(() => + 'defaultDeploymentId' in state.value + ? state.value.defaultDeploymentId + : null + ) + const defaultDeployment = computed( + () => + deployments.value.find( + (d) => d.deployment_id === defaultDeploymentId.value + ) ?? null + ) + /** + * True when this browser has no pick of its own and so runs on whatever + * the workspace says: its default deployment, or Comfy Cloud without one. + */ + const followsWorkspace = computed(() => pickSource.value !== 'browser') + const canSetDefault = computed(() => + pendingServerFact( + 'BE-20674', + workspaceStore.activeWorkspace?.role === 'owner' + ) + ) + const buildsVisible = computed(() => + 'buildsVisible' in state.value ? state.value.buildsVisible : true + ) + /** + * True once a listing has answered, and while a reload of it is in flight. + * False before any listing answers, when the account cannot pick, and when + * the load failed with no listing to show. A listing that answered is shown + * even when a newer load fails or never answers. + */ + const isVisible = computed(() => 'deployments' in state.value) + const isSwitching = computed(() => state.value.phase === 'switching') + /** + * The deployment this page booted on, from the first listing that + * answered: null for Comfy Cloud (a gone pick included), undefined before + * any listing answered. The editor's node catalog is that deployment's + * Release as it was at boot, since a pick or a workspace switch reloads + * the page. + */ + const bootDeployment = shallowRef( + undefined + ) + /** + * A change made elsewhere since this page booted that its nodes do not + * show, read from the latest listing: `release` when its deployment now + * runs another Release, `deployment` when it now runs on another + * deployment or Comfy Cloud with other nodes (an owner changed the + * default it follows, or its pick is gone). Jobs already run on the new + * one; only a reload brings its nodes. Null when nothing changed. + */ + const changeSinceBoot = computed(() => { + const boot = bootDeployment.value + if (boot === undefined || !isVisible.value) return null + return changeBetween(boot, pickedDeployment.value) + }) + + /** + * Orders the answers. Each `load()` takes the next number (`latestRequest`); + * `lastApplied` is the number of the newest answer put on screen. A listing + * or a 403 applies when it is newer than that, so a listing that answered + * stays shown when a newer load fails or never answers; an older listing + * still passes on a gone pick it reports. A plain failure + * applies only when it is the latest load asked for and nothing newer has + * applied, so it never replaces a listing that may still arrive. A default + * the server took moves `lastApplied` up to `latestRequest`, which drops + * every listing asked for before the change. + */ + let latestRequest = 0 + let lastApplied = 0 + + async function load(): Promise { + const id = workspaceStore.workspaceId + if (!id) return + const request = ++latestRequest + const event = await listingEvent(id) + // The workspace may have changed while the listing was in flight. + if (workspaceStore.workspaceId !== id) return + applyAnswer(request, event) + } + + function applyAnswer(request: number, event: DeploymentPickEvent) { + if (request <= lastApplied) { + if (event.type === 'loaded') keepPickGone(event.gonePickedDeploymentId) + return + } + if (event.type === 'loadFailed') { + if (request === latestRequest) dispatch(event) + return + } + lastApplied = request + dispatch(event) + if (event.type === 'loaded') noteListing(event.gonePickedDeploymentId) + } + + function keepPickGone(gonePickedDeploymentId: string | null) { + if (gonePickedDeploymentId !== null && pickedDeployment.value === null) { + sawPickGone.value = true + } + } + + function noteListing(gonePickedDeploymentId: string | null) { + if (gonePickedDeploymentId !== null) sawPickGone.value = true + else if (pickedDeployment.value !== null) sawPickGone.value = false + if (bootDeployment.value === undefined) { + bootDeployment.value = pickedDeployment.value + } + } + + let firstLoad: Promise | null = null + + /** + * Another workspace, or another account (signed in without a reload), has + * its own deployments: drop the old listing at once rather than show it + * until the new one answers, and drop any listing still in flight. The + * deployment this page booted on stays, since its nodes are still the + * editor's until a reload. + */ + watch( + () => workspaceStore.workspaceId, + () => { + dispatch({ type: 'workspaceChanged' }) + sawPickGone.value = false + lastApplied = latestRequest + firstLoad = null + }, + { flush: 'sync' } + ) + + /** + * The page's first `load()`, started at boot so the editor learns which + * deployment it booted on; later calls wait on that same load. + */ + function loadOnce(): Promise { + if (!firstLoad && workspaceStore.workspaceId) firstLoad = load() + return firstLoad ?? Promise.resolve() + } + + /** + * Pick a deployment for this browser, or null for Comfy Cloud, then reload so + * the editor boots on it. Resolves to the server's refusal, or null when + * the pick took (the page is reloading) or there was nothing to do. + * Choosing what this browser already runs on does nothing, so a browser + * that follows the workspace default keeps following it. Picking Comfy + * Cloud while following a default is this browser's own choice: it wins + * over the default, until `followWorkspace` drops it. + */ + async function pick(deploymentId: string | null): Promise { + const id = workspaceStore.workspaceId + if (!id || state.value.phase !== 'ready') return null + if (deploymentId === pickedDeploymentId.value) return null + return pickAndReload(id, deploymentId) + } + + /** + * Pick the deployment a link names (BE-20294), then reload like `pick`. + * It waits for the page's first listing, so a link to what this browser + * already runs on does nothing, but it does not need that listing to have + * answered: an account outside the rollout, or a deployment that is gone + * or not the workspace's, gets the server's refusal rather than nothing. + */ + async function pickFromLink(deploymentId: string): Promise { + const id = workspaceStore.workspaceId + if (!id || state.value.phase === 'switching') return { kind: 'unchanged' } + let timeout: ReturnType | undefined + const completed = await Promise.race([ + loadOnce().then(() => true), + new Promise((resolve) => { + timeout = setTimeout( + () => resolve(false), + DEPLOYMENT_LISTING_BACKSTOP_MS + ) + }) + ]).finally(() => clearTimeout(timeout)) + if (!completed) return { kind: 'timedOut' } + if (workspaceStore.workspaceId !== id || isSwitching.value) { + return { kind: 'unchanged' } + } + if (deploymentId === pickedDeploymentId.value) return { kind: 'unchanged' } + return pickLinkAndReload(id, deploymentId) + } + + async function pickLinkAndReload( + workspaceId: string, + deploymentId: string + ): Promise { + dispatch({ type: 'switchStarted', target: deploymentId }) + const controller = new AbortController() + let timeout: ReturnType | undefined + const selection = workspaceApi + .pickDeployment( + workspaceId, + { deployment_id: deploymentId }, + controller.signal + ) + .then( + () => ({ kind: 'picked' }), + (error: unknown) => ({ kind: 'refused', message: errorMessage(error) }) + ) + const outcome = await Promise.race([ + selection, + new Promise((resolve) => { + timeout = setTimeout(() => { + resolve({ kind: 'timedOut' }) + controller.abort() + }, DEPLOYMENT_LISTING_BACKSTOP_MS) + }) + ]).finally(() => clearTimeout(timeout)) + if (workspaceStore.workspaceId !== workspaceId) return { kind: 'unchanged' } + if (outcome.kind === 'picked') window.location.reload() + else dispatch({ type: 'switchFailed' }) + return outcome + } + + async function pickAndReload( + workspaceId: string, + deploymentId: string | null + ): Promise { + dispatch({ type: 'switchStarted', target: deploymentId }) + try { + if (deploymentId === null) { + await workspaceApi.clearDeployment(workspaceId) + } else { + await workspaceApi.pickDeployment(workspaceId, { + deployment_id: deploymentId + }) + } + } catch (err) { + dispatch({ type: 'switchFailed' }) + return errorMessage(err) + } + window.location.reload() + return null + } + + /** + * Drop this browser's own pick so it runs on whatever the workspace says + * (its default deployment, or Comfy Cloud), then reload. Resolves like `pick`. + */ + async function followWorkspace(): Promise { + const id = workspaceStore.workspaceId + if (!id || state.value.phase !== 'ready') return null + if (followsWorkspace.value) return null + dispatch({ type: 'switchStarted', target: defaultDeploymentId.value }) + try { + await workspaceApi.clearDeployment(id, { follow: 'workspace' }) + } catch (err) { + dispatch({ type: 'switchFailed' }) + return errorMessage(err) + } + window.location.reload() + return null + } + + /** + * Set the workspace's default deployment (owner only), or clear it with null. + * Members with no pick of their own move to it at their next boot. This + * browser reloads only when it has no pick of its own, since only then + * does the new default change what it runs on. Otherwise the new default + * shows at once and the listing is refreshed to confirm it; a failed + * refresh keeps the new default on screen, since the server has it, and a + * listing asked for before the change is dropped when it lands. + * Resolves to the server's refusal, or null when the default took. + */ + async function setDefault( + deploymentId: string | null + ): Promise { + const id = workspaceStore.workspaceId + if (!id || state.value.phase !== 'ready') return null + const recordedDefault = + defaultDeploymentId.value ?? goneDefaultDeploymentId.value + if (deploymentId === recordedDefault) return null + dispatch({ type: 'switchStarted', target: pickedDeploymentId.value }) + try { + if (deploymentId === null) { + await workspaceApi.clearDefaultDeployment(id) + } else { + await workspaceApi.setDefaultDeployment(id, { + deployment_id: deploymentId + }) + } + } catch (err) { + dispatch({ type: 'switchFailed' }) + return errorMessage(err) + } + if (followsWorkspace.value) { + window.location.reload() + return null + } + lastApplied = latestRequest + dispatch({ type: 'defaultChanged', defaultDeploymentId: deploymentId }) + await load() + return null + } + + return { + state, + deployments, + pickedDeploymentId, + pickedDeployment, + goneDeployment, + pickSource, + defaultDeploymentId, + goneDefaultDeploymentId, + defaultDeployment, + followsWorkspace, + canSetDefault, + buildsVisible, + isVisible, + isSwitching, + bootDeployment, + changeSinceBoot, + load, + loadOnce, + pick, + pickFromLink, + followWorkspace, + setDefault + } +}) + +async function listingEvent(workspaceId: string): Promise { + try { + return loadedEvent(await workspaceApi.listDeployments(workspaceId)) + } catch (err) { + return loadFailure(err) + } +} + +/** + * A 403 means the account is outside the rollout: hide the switcher. Any + * other failure (a 404 from an ingest without these routes, a 5xx, a network + * error, no signed-in user) hides it too unless a listing is already shown. + */ +function loadFailure(err: unknown): DeploymentPickEvent { + if (err instanceof WorkspaceApiError && err.status === 403) { + return { type: 'loadRefused' } + } + return { type: 'loadFailed' } +} + +function errorMessage(err: unknown): string { + return err instanceof Error ? err.message : String(err) +} diff --git a/src/platform/workspace/workspaceConstants.ts b/src/platform/workspace/workspaceConstants.ts index 307bc2c994b..d8b815a674e 100644 --- a/src/platform/workspace/workspaceConstants.ts +++ b/src/platform/workspace/workspaceConstants.ts @@ -5,6 +5,7 @@ export const WORKSPACE_STORAGE_KEYS = { EXPIRES_AT: 'Comfy.Workspace.ExpiresAt', OWNER_UID: 'Comfy.Workspace.OwnerUid', SWITCH_TARGET_ID: 'Comfy.Workspace.SwitchTargetId', + DEPLOYMENT_LINK_SWITCH: 'Comfy.Workspace.DeploymentLinkSwitch', // localStorage key (persists across browser sessions) LAST_WORKSPACE_ID: 'Comfy.Workspace.LastWorkspaceId' } as const diff --git a/src/views/GraphView.test.ts b/src/views/GraphView.test.ts index ff3a2276667..50cd7303688 100644 --- a/src/views/GraphView.test.ts +++ b/src/views/GraphView.test.ts @@ -6,6 +6,8 @@ import { useReconnectQueueRefresh } from '@/composables/useReconnectQueueRefresh import { useReconnectingNotification } from '@/composables/useReconnectingNotification' import type * as DistributionTypes from '@/platform/distribution/types' import { useVersionCompatibilityStore } from '@/platform/updates/common/versionCompatibilityStore' +import { mockDeploymentListing } from '@/platform/workspace/__fixtures__/deploymentListing' +import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' import { app } from '@/scripts/app' import { useAssetsStore } from '@/stores/assetsStore' import { useExecutionStore } from '@/stores/executionStore' @@ -347,3 +349,35 @@ describe('GraphView - partner nodes education card', () => { expect(screen.queryByTestId('education-card-stub')).not.toBeInTheDocument() }) }) + +describe('GraphView - deployment pick at startup', () => { + const pickGone = 'The deployment you picked no longer exists.' + + beforeEach(() => { + mockDeploymentListing({ + items: [], + builds_visible: true, + gone_picked_deployment_id: 'dep-gone' + }) + vi.spyOn(useDeploymentPickStore(), 'loadOnce') + }) + + afterEach(() => { + distribution.isCloud = false + }) + + it("warns on Cloud that this browser's picked deployment is gone, without opening the account menu", async () => { + distribution.isCloud = true + + render(GraphView, { global: { plugins: [i18n] } }) + + expect(await screen.findByText(pickGone)).toBeInTheDocument() + }) + + it('does not look up the deployment on a local build', () => { + render(GraphView, { global: { plugins: [i18n] } }) + + expect(useDeploymentPickStore().loadOnce).not.toHaveBeenCalled() + expect(screen.queryByText(pickGone)).toBeNull() + }) +}) diff --git a/src/views/GraphView.vue b/src/views/GraphView.vue index 9efb39eac71..15e03b154f5 100644 --- a/src/views/GraphView.vue +++ b/src/views/GraphView.vue @@ -89,6 +89,7 @@ import { getShellLayoutSnapshot } from '@/platform/telemetry/utils/getShellLayou import { getPageVisibilityMetadata } from '@/workbench/extensions/agent/utils/getPageVisibilityMetadata' import { useFrontendVersionMismatchWarning } from '@/platform/updates/common/useFrontendVersionMismatchWarning' import { useVersionCompatibilityStore } from '@/platform/updates/common/versionCompatibilityStore' +import { useDeploymentPickAtBoot } from '@/platform/workspace/composables/useDeploymentPickAtBoot' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import type { StatusWsMessageStatus } from '@/platform/remote/comfyui/execution/types' import { api } from '@/scripts/api' @@ -185,6 +186,9 @@ const telemetry = useTelemetry() const authStore = useAuthStore() let hasTrackedLogin = false +// Learn which developer-platform deployment this page booted on (FE-2434). +if (isCloud) void useDeploymentPickAtBoot() + watch( () => colorPaletteStore.completedActivePalette, (newTheme) => {