From 04606339b9e13b9a2071d1d7f7a2b3b21721dd07 Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Mon, 12 Oct 2026 14:05:53 -0700 Subject: [PATCH 1/2] feat(storybook): explore the Create a New Instance setup screen Eight stories render the production InstallWizardModal with typed sample preload responses: Public Builds, Managed Builds, a Managed install handoff, simulated sign-in, no compatible builds, a recoverable build-list error, an install rejection, and low disk space for a starter template. Their play functions check each state; the low-disk play waits for the disk check's alert before checking Install. A decorator component installs a fresh fixture per mount and retires it on unmount: its methods never settle, its spies are cleared, and calls through references a store kept stop with it. Spies are created per mount, so the stories keep Storybook's per-render mock restore off. --- README.md | 5 + TESTING.md | 3 +- stories/InstallWizard.stories.ts | 153 +++++++++++++++++++ stories/InstallWizardPreview.vue | 42 +++++ stories/README.md | 44 ++++++ stories/desktopApi.ts | 253 +++++++++++++++++++++++++++++++ 6 files changed, 499 insertions(+), 1 deletion(-) create mode 100644 stories/InstallWizard.stories.ts create mode 100644 stories/InstallWizardPreview.vue create mode 100644 stories/desktopApi.ts diff --git a/README.md b/README.md index 8755a9140..f61c0eaf7 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,11 @@ components with the app's production styles, translations, and a fresh Pinia store per story. No Electron app, bootstrap Python, account, or ComfyUI installation is needed to run them. +Choose **Screens → Create a New Instance** to explore the setup screen with +sample Electron API responses: Public Builds, sample Managed Builds after a +simulated sign-in, target switching, a retried failed request, and empty and +error states. File and install actions are simulated. + The **Storybook** CI job builds a static Storybook from the commit it checks out and links it as a downloadable `storybook-` artifact in the job summary. On a pull request that commit is GitHub's test merge of the PR, which includes diff --git a/TESTING.md b/TESTING.md index 2ad510217..86ce1f7da 100644 --- a/TESTING.md +++ b/TESTING.md @@ -17,7 +17,8 @@ and a per-spec inventory, see [`e2e/README.md`](e2e/README.md). Where they live: - Unit: `src/**/*.test.ts` (excluding `*.integration.test.ts`) -- Storybook: `stories/**/*.stories.ts` (each story's play function is a test) +- Storybook: `stories/**/*.stories.ts` (each story's play function is a test; + the setup screen's sample preload responses live in `stories/desktopApi.ts`) - Integration: `src/**/*.integration.test.ts` - E2E + Lifecycle: `e2e/*.test.ts`, selected by tag in the test title (`@windows @macos @linux` vs `@lifecycle`), mapped to Playwright projects in diff --git a/stories/InstallWizard.stories.ts b/stories/InstallWizard.stories.ts new file mode 100644 index 000000000..4a4fcee16 --- /dev/null +++ b/stories/InstallWizard.stories.ts @@ -0,0 +1,153 @@ +import type { Meta, StoryObj } from '@storybook/vue3-vite' +import { expect, screen, userEvent, waitFor } from 'storybook/test' +import { defineComponent, h, onUnmounted } from 'vue' +import { useModal } from '../src/renderer/src/composables/useModal' +import InstallWizardPreview from './InstallWizardPreview.vue' +import { createDesktopApi, retireDesktopApi, type InstallScenario } from './desktopApi' + +const meta = { + title: 'Screens/Create a New Instance', + component: InstallWizardPreview, + tags: ['autodocs'], + parameters: { + desktopScenario: 'publicBuilds' satisfies InstallScenario, + // Each mount creates fresh spies; the default restore would clear their calls on rerender. + test: { restoreMocks: false }, + docs: { + description: { + component: + 'Explore the actual Desktop setup screen without launching Electron, signing in, or downloading ComfyUI. Public Builds are the standard ComfyUI environments. Managed Builds are setups published to a platform workspace. Sample Windows/NVIDIA responses stand in for the preload API; they do not test real hardware compatibility. File, browser and install actions are simulated.' + } + } + }, + decorators: [ + // Scoped to the Vue mount: toolbar and args rerenders re-run beforeEach without remounting. + (story, { parameters }) => { + const Story = story() + return defineComponent({ + setup() { + const api = createDesktopApi(parameters.desktopScenario) + window.api = api + useModal().dismiss() + onUnmounted(() => { + useModal().dismiss() + retireDesktopApi(api) + }) + return () => h(Story) + } + }) + } + ] +} satisfies Meta + +export default meta +type Story = StoryObj + +// The real takeover and its alerts teleport outside canvasElement, so plays query `screen`. + +export const PublicBuilds: Story = { + play: async () => { + await waitFor(() => + expect(screen.getByRole('heading', { name: 'Create a New Instance' })).toBeVisible() + ) + await waitFor(() => expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()) + await expect(screen.getByRole('radio', { name: 'Public Builds' })).toHaveAttribute( + 'aria-checked', + 'true' + ) + } +} + +export const ManagedBuilds: Story = { + parameters: { desktopScenario: 'managedBuilds' satisfies InstallScenario }, + play: async () => { + await waitFor(() => + expect(screen.getByTestId('workspace-build-field')).toHaveTextContent('Studio Image Build') + ) + await expect(screen.getByRole('radio', { name: 'Managed Builds' })).toHaveAttribute( + 'aria-checked', + 'true' + ) + await expect(screen.queryByText('Build for another platform')).not.toBeInTheDocument() + await expect(screen.getByText('Windows - NVIDIA (CUDA 13.0)')).toBeInTheDocument() + } +} + +export const ManagedInstallRequested: Story = { + parameters: { desktopScenario: 'managedBuilds' satisfies InstallScenario }, + play: async () => { + await waitFor(() => + expect(screen.getByTestId('workspace-build-field')).toHaveTextContent('Studio Image Build') + ) + const install = screen.getByRole('button', { name: 'Continue' }) + await waitFor(() => expect(install).toBeEnabled()) + await userEvent.click(install) + await expect( + await screen.findByText(/Simulated installation requested for preview-install/) + ).toBeVisible() + await expect(window.api.comfybuilder.installBuild).toHaveBeenCalledOnce() + } +} + +export const SignInToManagedBuilds: Story = { + play: async () => { + await waitFor(() => expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()) + await userEvent.click(await screen.findByRole('radio', { name: 'Managed Builds' })) + await waitFor(() => + expect(screen.getByTestId('workspace-build-field')).toHaveTextContent('Studio Image Build') + ) + await expect(window.api.comfybuilder.signIn).toHaveBeenCalledOnce() + } +} + +export const NoCompatibleBuilds: Story = { + parameters: { desktopScenario: 'noCompatibleBuilds' satisfies InstallScenario }, + play: async () => { + // The real screen defaults to Public Builds when the workspace has no + // compatible release. Select Managed Builds to inspect its empty state. + await waitFor(() => expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()) + await userEvent.click(screen.getByRole('radio', { name: 'Managed Builds' })) + await waitFor(() => + expect(screen.getByText('No compatible Builds are available to install.')).toBeVisible() + ) + await expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled() + } +} + +export const BuildLoadError: Story = { + parameters: { desktopScenario: 'buildLoadError' satisfies InstallScenario }, + play: async () => { + await waitFor(() => + expect(screen.getByRole('button', { name: "Couldn't load builds. Retry" })).toBeVisible() + ) + } +} + +export const InstallError: Story = { + parameters: { desktopScenario: 'installError' satisfies InstallScenario }, + play: async () => { + const install = await screen.findByRole('button', { name: 'Continue' }) + await waitFor(() => expect(install).toBeEnabled()) + await userEvent.click(install) + await waitFor(() => + expect(screen.getByText('This build is not compatible with this machine.')).toBeVisible() + ) + } +} + +export const LowDiskSpace: Story = { + parameters: { desktopScenario: 'lowDiskSpace' satisfies InstallScenario }, + play: async () => { + const next = await screen.findByRole('button', { name: 'Continue' }) + await waitFor(() => expect(next).toBeEnabled()) + await userEvent.click(next) + await userEvent.click(await screen.findByRole('radio', { name: /Starter Image Workflow/ })) + // Continue restarts the wizard's 300 ms disk check; the alert shows once it has settled. + await expect(await screen.findByRole('alert', {}, { timeout: 10_000 })).toHaveTextContent( + /only 11 GB free/ + ) + const install = screen.getByRole('button', { name: 'Install' }) + await expect(install).toHaveAttribute('aria-disabled', 'true') + await expect(install).toHaveAttribute('aria-describedby', 'tps-alerts') + } +} diff --git a/stories/InstallWizardPreview.vue b/stories/InstallWizardPreview.vue new file mode 100644 index 000000000..41bcb77e4 --- /dev/null +++ b/stories/InstallWizardPreview.vue @@ -0,0 +1,42 @@ + + + + + diff --git a/stories/README.md b/stories/README.md index 0df68a3e7..0ecb6ac50 100644 --- a/stories/README.md +++ b/stories/README.md @@ -15,6 +15,33 @@ page explains it and embeds isolated examples. | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | Components → BaseSelect | Open the select, move with the arrow keys (disabled options are skipped), pick with Enter, or close with Escape or a click outside. | +### Create a New Instance + +Under **Screens → Create a New Instance**, choose an example. Remounting resets +its sample data. + +| Example | What to try | +| ------------------------- | ----------------------------------------------------------------------------------------- | +| Public Builds | Change release/hardware, continue to the starter workflow picker. | +| Managed Builds | Inspect a sample workspace build and switch its installation target. | +| Managed Install Requested | See the simulated handoff after Continue requests a Managed Build install. | +| Sign In To Managed Builds | See the result of simulated sign-in; remount Public Builds to perform the click yourself. | +| No Compatible Builds | Inspect the empty picker and disabled installation button. | +| Build Load Error | Click Retry to recover the sample failed request. | +| Install Error | Inspect the alert after the sample installation request is rejected. | +| Low Disk Space | Inspect the blocked starter workflow, then pick a smaller one or None to proceed. | + +**Public Builds** are the standard ComfyUI environments. **Managed Builds** are +packaged setups published to a Comfy platform workspace. The **wizard** is this +Create a New Instance screen. + +The examples use a sample Windows/NVIDIA machine. Compatibility states are +predefined API responses, not the output of the real main-process compatibility +check. These stories cannot establish whether Python, PyTorch, or a GPU works on +a machine. Browser, folder, and install actions stay inside the preview; no files +are written and no external authentication is started. Public/remote submission +shows a preview-only alert. Managed submission displays a simulated handoff. + ## Add a story - Put `*.stories.ts` files under `stories/` and import the actual renderer @@ -27,6 +54,23 @@ page explains it and embeds isolated examples. - Stories run without Electron, so `window.api` does not exist. A component that calls the preload API needs a sample implementation, checked against the production IPC types, installed for each mount and released when it unmounts. +- The setup screen's sample responses live in `desktopApi.ts`. Implement every + preload method the screen calls. A missing method is `undefined`, and product + code that feature-detects optional methods or catches preload errors silently + takes its fallback path. +- Its decorator component installs a fresh fixture and resets shared modal state + in its setup. On unmount it resets the modal and passes the fixture to + `retireDesktopApi`. The fixture's methods then never settle, including through + references a store kept (the auth store keeps `comfybuilder`), so the + unmounted screen's late async work stops instead of throwing or continuing + against a fixture no example shows. Calls it makes through `window.api` only + after the next example has mounted reach that example's fixture. Retiring + also clears the fixture's spies, which Storybook keeps for the page's + lifetime, so their recorded calls do not keep the old fixture alive. + Storybook re-runs `beforeEach` on toolbar and args changes without + remounting, which would swap the fixture under the mounted screen. Keep + `test.restoreMocks: false` so those rerenders do not clear the fresh spies' + call history. - Query `screen` (the document body) for popovers, takeover screens and alerts, which teleport outside the story canvas. Use condition-based assertions instead of sleeps. diff --git a/stories/desktopApi.ts b/stories/desktopApi.ts new file mode 100644 index 000000000..2c0c570c2 --- /dev/null +++ b/stories/desktopApi.ts @@ -0,0 +1,253 @@ +import { fn, isMockFunction } from 'storybook/test' +import type { AuthStatus, DevPlatformBuild, ElectronApi, Source } from '../src/types/ipc' + +export type InstallScenario = + | 'publicBuilds' + | 'managedBuilds' + | 'noCompatibleBuilds' + | 'buildLoadError' + | 'installError' + | 'lowDiskSpace' + +const sources: Source[] = [ + { + id: 'standalone', + label: 'Public Builds', + fields: [ + { id: 'release', label: 'Release', type: 'select' }, + { id: 'comfyVersion', label: 'ComfyUI version', type: 'select' }, + { id: 'variant', label: 'Hardware', type: 'select', renderAs: 'cards' }, + { id: 'bundledTemplate', label: 'Starter Template', type: 'select', renderAs: 'cards' } + ] + }, + { + id: 'remote', + label: 'Remote Connection', + skipInstall: true, + hideInstallPath: true, + fields: [{ id: 'url', label: 'URL', type: 'text', defaultValue: 'http://localhost:8188' }] + } +] + +const builds: DevPlatformBuild[] = [ + { + id: 'studio-image', + name: 'Studio Image Build', + description: 'A published workspace setup for image workflows.', + version: '3', + state: 'installable', + sizeBytes: 8_000_000_000, + releaseTargets: [ + { + artifactId: 'windows-nvidia', + releaseVersion: 3, + os: 'windows', + gpu: 'nvidia', + accelVariant: 'cu130', + recommended: true + }, + { + artifactId: 'windows-cpu', + releaseVersion: 3, + os: 'windows', + gpu: 'cpu', + accelVariant: 'cpu', + recommended: false + } + ] + }, + { + id: 'other-platform', + name: 'Build for another platform', + state: 'platform-mismatch', + targetOs: ['linux'] + } +] + +// Same data shape as the standalone source's variant cards. +function variantOption( + variantId: string, + label: string, + sizeBytes: number, + comfyVersion: string, + recommended = false +) { + const filename = `${variantId}.7z` + return { + value: variantId, + label, + description: `ComfyUI ${comfyVersion} · Python 3.12 · ${(sizeBytes / 1048576).toFixed(0)} MB`, + recommended, + data: { + variantId, + downloadFiles: [{ url: `https://example.com/${filename}`, filename, size: sizeBytes }] + } + } +} + +const never = () => new Promise(() => {}) + +// Called on unmount. In place, because stores keep what they read at creation +// (the auth store keeps `comfybuilder`): the screen's late calls never settle +// rather than resolving against a fixture no example shows. +export function retireDesktopApi(api: ElectronApi): void { + for (const methods of [api, api.comfybuilder] as unknown as Record[]) { + for (const [key, value] of Object.entries(methods)) { + // Storybook keeps every spy for the page's lifetime, so drop the calls (and `this` objects) it recorded. + if (isMockFunction(value)) value.mockClear() + if (typeof value === 'function') methods[key] = /^on[A-Z]/.test(key) ? () => () => {} : never + } + } +} + +/** Browser-only responses at the preload boundary. No Electron or backend is imported. */ +export function createDesktopApi(scenario: InstallScenario): ElectronApi { + let status: AuthStatus = + scenario === 'publicBuilds' || scenario === 'lowDiskSpace' + ? { signedIn: false } + : signedInStatus() + const authListeners = new Set<(status: AuthStatus) => void>() + let buildRequests = 0 + + function signedInStatus(workspaceId = 'storybook-personal'): AuthStatus { + return { + signedIn: true, + workspaceId, + workspaceName: 'Personal workspace', + workspaceType: 'personal', + email: 'preview@example.com' + } + } + + function changeAuth(next: AuthStatus): AuthStatus { + status = next + for (const listener of authListeners) listener(next) + return next + } + + const api = { + platform: 'win32', + getSources: async () => structuredClone(sources), + getFieldOptions: async (_sourceId, fieldId, selections) => { + const stable = selections.release?.value === 'stable' + switch (fieldId) { + case 'release': + return [ + { + value: 'stable', + label: 'Stable', + description: 'Tested releases, recommended for most users', + recommended: true + }, + { + value: 'latest', + label: 'Latest on GitHub', + description: 'Newest commits from the master branch' + } + ] + case 'comfyVersion': + // Only the stable channel offers a version picker. + return stable + ? [ + { + value: 'v0.3.92', + label: 'v0.3.92', + recommended: true, + description: 'Latest stable' + } + ] + : [] + case 'variant': { + const comfyVersion = stable ? '0.3.92' : '0.3.92 (nightly)' + return [ + variantOption('win-nvidia', 'NVIDIA', 3_000_000_000, comfyVersion, true), + variantOption('win-cpu', 'CPU', 1_000_000_000, comfyVersion) + ] + } + case 'bundledTemplate': + return [ + { value: 'none', label: 'None', description: 'Start with a blank canvas' }, + { + value: 'starter-upscale', + label: 'Starter Upscale Workflow', + description: 'Upscale an existing image.', + data: { modality: 'image', sizeBytes: 2_000_000_000, modelsPresent: false } + }, + { + value: 'starter-image', + label: 'Starter Image Workflow', + description: 'Generate an image from a text prompt.', + data: { modality: 'image', sizeBytes: 20_000_000_000, modelsPresent: false } + } + ] + default: + throw new Error(`Add a Storybook fixture for field: ${fieldId}`) + } + }, + detectGPU: async () => ({ label: 'NVIDIA RTX 4090' }), + validateHardware: async () => ({ supported: true }), + checkNvidiaDriver: async () => null, + getDefaultInstallDir: async () => 'C:\\ComfyUI-Installs', + getUniqueName: async (name) => name, + getSetting: async () => false, + setSetting: fn(async () => {}), + getInstallationsSummary: async () => ({ + localCount: 0, + hasLaunchedCloud: false, + hasLegacyDesktop: false + }), + getDiskSpace: async () => ({ + free: scenario === 'lowDiskSpace' ? 12_000_000_000 : 500_000_000_000, + total: 1_000_000_000_000 + }), + validateInstallPath: async () => [], + browseFolder: fn(async () => 'C:\\Preview-Installs'), + openPath: fn(async () => {}), + openExternal: fn(async () => {}), + buildInstallation: async (sourceId) => ({ sourceId }), + // Public/remote submission stops at the boundary: no install is created. + addInstallation: fn(async () => ({ + ok: false, + message: 'Storybook preview: no installation was created.' + })), + installInstance: fn(async () => {}), + comfybuilder: { + getAuthStatus: async () => status, + signIn: fn(async () => changeAuth(signedInStatus())), + signOut: fn(async () => changeAuth({ signedIn: false })), + switchWorkspace: fn(async (workspaceId) => changeAuth(signedInStatus(workspaceId))), + onAuthChanged(callback) { + authListeners.add(callback) + return () => { + authListeners.delete(callback) + } + }, + listWorkspaces: async () => [ + { id: 'storybook-personal', name: 'Personal workspace', type: 'personal', role: 'owner' } + ], + listBuilds: fn(async () => { + if (scenario === 'buildLoadError' && ++buildRequests === 1) { + throw new Error('Sample workspace request failed') + } + return structuredClone( + scenario === 'noCompatibleBuilds' + ? builds.filter((b) => b.state !== 'installable') + : builds + ) + }), + openBuildsPage: fn(async () => {}), + installBuild: fn(async () => + scenario === 'installError' + ? { ok: false, message: 'This build is not compatible with this machine.' } + : { ok: true, entry: { id: 'preview-install', name: 'Studio Image Build' } } + ) + } + } satisfies Partial> & { + comfybuilder: Partial + } + + // Only the methods these screens call are provided. Missing methods are + // undefined, and callers that feature-detect or catch preload errors take + // their fallback path, so add every method a new screen uses. + return api as unknown as ElectronApi +} From 273aa90f4c15e4408bd97bb98c26010697519f7b Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Thu, 15 Oct 2026 05:49:57 -0700 Subject: [PATCH 2/2] test(storybook): share the preload fixture decorator and tighten install plays - Move the per-mount fixture lifecycle into a reusable `withDesktopApi` decorator and `desktopApiParameters` preset in stories/desktopApi.ts, so new preload-backed stories don't hand-copy it or forget restoreMocks. - Retire nested preload namespaces recursively instead of listing `comfybuilder` by name. - Managed Install Requested asserts the installBuild request (build, recommended target, install root). - Install Error asserts installBuild was called and no handoff happened. --- stories/InstallWizard.stories.ts | 39 +++++++++++--------------- stories/README.md | 12 ++++---- stories/desktopApi.ts | 47 ++++++++++++++++++++++++++------ 3 files changed, 62 insertions(+), 36 deletions(-) diff --git a/stories/InstallWizard.stories.ts b/stories/InstallWizard.stories.ts index 4a4fcee16..5d46282f9 100644 --- a/stories/InstallWizard.stories.ts +++ b/stories/InstallWizard.stories.ts @@ -1,18 +1,20 @@ import type { Meta, StoryObj } from '@storybook/vue3-vite' import { expect, screen, userEvent, waitFor } from 'storybook/test' -import { defineComponent, h, onUnmounted } from 'vue' -import { useModal } from '../src/renderer/src/composables/useModal' import InstallWizardPreview from './InstallWizardPreview.vue' -import { createDesktopApi, retireDesktopApi, type InstallScenario } from './desktopApi' +import { + createDesktopApi, + desktopApiParameters, + withDesktopApi, + type InstallScenario +} from './desktopApi' const meta = { title: 'Screens/Create a New Instance', component: InstallWizardPreview, tags: ['autodocs'], parameters: { + ...desktopApiParameters, desktopScenario: 'publicBuilds' satisfies InstallScenario, - // Each mount creates fresh spies; the default restore would clear their calls on rerender. - test: { restoreMocks: false }, docs: { description: { component: @@ -20,24 +22,7 @@ const meta = { } } }, - decorators: [ - // Scoped to the Vue mount: toolbar and args rerenders re-run beforeEach without remounting. - (story, { parameters }) => { - const Story = story() - return defineComponent({ - setup() { - const api = createDesktopApi(parameters.desktopScenario) - window.api = api - useModal().dismiss() - onUnmounted(() => { - useModal().dismiss() - retireDesktopApi(api) - }) - return () => h(Story) - } - }) - } - ] + decorators: [withDesktopApi(({ parameters }) => createDesktopApi(parameters.desktopScenario))] } satisfies Meta export default meta @@ -86,6 +71,12 @@ export const ManagedInstallRequested: Story = { await screen.findByText(/Simulated installation requested for preview-install/) ).toBeVisible() await expect(window.api.comfybuilder.installBuild).toHaveBeenCalledOnce() + await expect(window.api.comfybuilder.installBuild).toHaveBeenCalledWith({ + buildId: 'studio-image', + artifactId: 'windows-nvidia', + releaseVersion: 3, + installRoot: 'C:\\ComfyUI-Installs' + }) } } @@ -132,6 +123,8 @@ export const InstallError: Story = { await waitFor(() => expect(screen.getByText('This build is not compatible with this machine.')).toBeVisible() ) + await expect(window.api.comfybuilder.installBuild).toHaveBeenCalledOnce() + await expect(screen.queryByText(/Simulated installation requested/)).not.toBeInTheDocument() } } diff --git a/stories/README.md b/stories/README.md index 0ecb6ac50..17ed0778a 100644 --- a/stories/README.md +++ b/stories/README.md @@ -58,9 +58,11 @@ shows a preview-only alert. Managed submission displays a simulated handoff. preload method the screen calls. A missing method is `undefined`, and product code that feature-detects optional methods or catches preload errors silently takes its fallback path. -- Its decorator component installs a fresh fixture and resets shared modal state - in its setup. On unmount it resets the modal and passes the fixture to - `retireDesktopApi`. The fixture's methods then never settle, including through +- Use its `withDesktopApi` decorator and spread `desktopApiParameters` into the + meta's parameters instead of writing your own. The decorator component installs + a fresh fixture and resets shared modal state in its setup. On unmount it + resets the modal and retires the fixture, including nested namespaces such as + `comfybuilder`. The fixture's methods then never settle, including through references a store kept (the auth store keeps `comfybuilder`), so the unmounted screen's late async work stops instead of throwing or continuing against a fixture no example shows. Calls it makes through `window.api` only @@ -68,8 +70,8 @@ shows a preview-only alert. Managed submission displays a simulated handoff. also clears the fixture's spies, which Storybook keeps for the page's lifetime, so their recorded calls do not keep the old fixture alive. Storybook re-runs `beforeEach` on toolbar and args changes without - remounting, which would swap the fixture under the mounted screen. Keep - `test.restoreMocks: false` so those rerenders do not clear the fresh spies' + remounting, which would swap the fixture under the mounted screen. + `desktopApiParameters` sets `test.restoreMocks: false` so those rerenders do not clear the fresh spies' call history. - Query `screen` (the document body) for popovers, takeover screens and alerts, which teleport outside the story canvas. Use condition-based assertions diff --git a/stories/desktopApi.ts b/stories/desktopApi.ts index 2c0c570c2..d48cda3b7 100644 --- a/stories/desktopApi.ts +++ b/stories/desktopApi.ts @@ -1,4 +1,7 @@ +import type { Decorator, StoryContext } from '@storybook/vue3-vite' import { fn, isMockFunction } from 'storybook/test' +import { defineComponent, h, onUnmounted } from 'vue' +import { useModal } from '../src/renderer/src/composables/useModal' import type { AuthStatus, DevPlatformBuild, ElectronApi, Source } from '../src/types/ipc' export type InstallScenario = @@ -89,14 +92,42 @@ const never = () => new Promise(() => {}) // Called on unmount. In place, because stores keep what they read at creation // (the auth store keeps `comfybuilder`): the screen's late calls never settle -// rather than resolving against a fixture no example shows. -export function retireDesktopApi(api: ElectronApi): void { - for (const methods of [api, api.comfybuilder] as unknown as Record[]) { - for (const [key, value] of Object.entries(methods)) { - // Storybook keeps every spy for the page's lifetime, so drop the calls (and `this` objects) it recorded. - if (isMockFunction(value)) value.mockClear() - if (typeof value === 'function') methods[key] = /^on[A-Z]/.test(key) ? () => () => {} : never - } +// rather than resolving against a fixture no example shows. Recurses into +// namespaces such as `comfybuilder`. +function retireDesktopApi(api: object): void { + const methods = api as Record + for (const [key, value] of Object.entries(methods)) { + // Storybook keeps every spy for the page's lifetime, so drop the calls (and `this` objects) it recorded. + if (isMockFunction(value)) value.mockClear() + if (typeof value === 'function') methods[key] = /^on[A-Z]/.test(key) ? () => () => {} : never + else if (value && typeof value === 'object') retireDesktopApi(value) + } +} + +/** Spread into the meta's parameters: each mount creates fresh spies, and the default restore would clear their calls on rerender. */ +export const desktopApiParameters = { test: { restoreMocks: false } } + +/** + * Installs a fresh fixture as `window.api` for each Vue mount and retires it on + * unmount, resetting shared modal state both times. Scoped to the mount: + * toolbar and args rerenders re-run beforeEach without remounting. Pair with + * `desktopApiParameters`. + */ +export function withDesktopApi(create: (context: StoryContext) => ElectronApi): Decorator { + return (story, context) => { + const Story = story() + return defineComponent({ + setup() { + const api = create(context) + window.api = api + useModal().dismiss() + onUnmounted(() => { + useModal().dismiss() + retireDesktopApi(api) + }) + return () => h(Story) + } + }) } }