Skip to content

Conversation

@shilman
Copy link
Member

@shilman shilman commented Oct 20, 2025

Closes #

What I did

We want to know whether the preview successfully loaded to help identify and eliminate key setup errors in newly initialized Storybooks.

This pull request introduces a new telemetry event, preview-first-load, to track when the preview is initialized for the first time. The implementation includes a new PREVIEW_INITIALIZED event, updates to the event system and telemetry logic, and integration into the preview lifecycle. These changes help improve analytics and session tracking for preview initialization.

Checklist for Contributors

Testing

The changes in this PR are covered in the following automated tests:

  • stories
  • unit tests
  • integration tests
  • end-to-end tests

Manual testing

  1. Install the canary into a fresh test project with STORYBOOK_TELEMETRY_DEBUG=1. After dev it should emit a preview-first-load event with isInitSession: true.
  2. Restart storybook. It should not send a preview-first-load because it is the same session.
  3. Delete node_modules/.cache and restart Storybook. It should send a preview-first-load event with isInitSession: false.
  4. Edit a component to trigger HMR. No preview-first-load should be sent.
  5. Edit a story to trigger HMR. No preview-first-load should be sent.

Documentation

  • Add or update documentation reflecting your changes
  • If you are deprecating/removing a feature, make sure to update
    MIGRATION.MD

Checklist for Maintainers

  • When this PR is ready for testing, make sure to add ci:normal, ci:merged or ci:daily GH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found in code/lib/cli-storybook/src/sandbox-templates.ts

  • Make sure this PR contains one of the labels below:

    Available labels
    • bug: Internal changes that fixes incorrect behavior.
    • maintenance: User-facing maintenance tasks.
    • dependencies: Upgrading (sometimes downgrading) dependencies.
    • build: Internal-facing build tooling & test updates. Will not show up in release changelog.
    • cleanup: Minor cleanup style change. Will not show up in release changelog.
    • documentation: Documentation only changes. Will not show up in release changelog.
    • feature request: Introducing a new feature.
    • BREAKING CHANGE: Changes that break compatibility in some way with current major version.
    • other: Changes that don't fit in the above categories.

🦋 Canary release

This pull request has been released as version 0.0.0-pr-32770-sha-44d650a9. Try it out in a new sandbox by running npx [email protected] sandbox or in an existing project with npx [email protected] upgrade.

More information
Published version 0.0.0-pr-32770-sha-44d650a9
Triggered by @yannbf
Repository storybookjs/storybook
Branch shilman/preview-first-load
Commit 44d650a9
Datetime Fri Oct 24 11:37:30 UTC 2025 (1761305850)
Workflow run 18778591375

To request a new release of this pull request, mention the @storybookjs/core team.

core team members can create a new canary release here or locally with gh workflow run --repo storybookjs/storybook publish.yml --field pr=32770

Summary by CodeRabbit

  • New Features

    • Added a preview-initialized event and client-side emission to signal preview startup and include user agent.
    • Captures and reports a "preview-first-load" telemetry event with timing and environment info.
  • Improvements

    • Enhanced telemetry helpers and caching to track recent events and ensure save operations are awaited more reliably.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 20, 2025

📝 Walkthrough

Walkthrough

Adds a PREVIEW_INITIALIZED event emitted after preview initialization and wires server-side handling that records a "preview-first-load" telemetry event (timeSinceInit, isInitSession, userAgent) when telemetry is enabled and no previous preview-first-load exists.

Changes

Cohort / File(s) Summary
Event Definition
code/core/src/core-events/index.ts, code/core/src/manager/globals/exports.ts
Added PREVIEW_INITIALIZED event enum member and exposed it in public exports (storybook/internal/core-events).
Preview Initialization
code/core/src/preview-api/modules/preview-web/Preview.tsx
Imports PREVIEW_INITIALIZED and emits it after initialization with payload { userAgent }.
Server Channel Registration
code/core/src/core-server/presets/common-preset.ts
Imports and invokes initPreviewInitializedChannel during server channel setup.
Telemetry Channel Handler
code/core/src/core-server/server-channel/preview-initialized-channel.ts
New module: subscribes to PREVIEW_INITIALIZED, checks telemetry settings, reads session and last events, and emits preview-first-load telemetry if appropriate; errors are swallowed.
Telemetry Cache & Types
code/core/src/telemetry/event-cache.ts, code/core/src/telemetry/types.ts
Added exported getLastEvents helper and added 'preview-first-load' to EventType union.
Telemetry Sending Logic
code/core/src/telemetry/telemetry.ts
Adjusted sendTelemetry wait strategy to await saveToCache alongside current/all tasks depending on options.immediate, and cleans up current request from global tasks in finally.

Sequence Diagram(s)

sequenceDiagram
    participant Preview as Preview.tsx
    participant Channel as Channel
    participant ServerHandler as preview-initialized-channel
    participant Telemetry as Telemetry

    Preview->>Preview: initialize()
    Preview->>Preview: initializeWithProjectAnnotations()
    Note right of Preview: capture userAgent
    Preview->>Channel: emit PREVIEW_INITIALIZED { userAgent }

    Channel->>ServerHandler: subscribed event
    Note right of ServerHandler: if telemetry enabled
    ServerHandler->>ServerHandler: getSessionId()
    ServerHandler->>ServerHandler: getLastEvents()
    alt no prior "preview-first-load"
        ServerHandler->>Telemetry: emit "preview-first-load" { timeSinceInit, isInitSession, userAgent }
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch shilman/preview-first-load

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d45a7f9 and 9f2733d.

📒 Files selected for processing (1)
  • code/core/src/core-server/server-channel/preview-initialized-channel.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • code/core/src/core-server/server-channel/preview-initialized-channel.ts

Comment @coderabbitai help to get the list of available commands and usage tips.

@shilman shilman added maintenance User-facing maintenance tasks patch:yes Bugfix & documentation PR that need to be picked to main branch core telemetry ci:normal labels Oct 20, 2025
@nx-cloud
Copy link

nx-cloud bot commented Oct 20, 2025

View your CI Pipeline Execution ↗ for commit 44d650a

Command Status Duration Result
nx run-many -t build --parallel=3 ✅ Succeeded 47s View ↗

☁️ Nx Cloud last updated this comment at 2025-10-24 11:57:08 UTC

@shilman shilman marked this pull request as ready for review October 22, 2025 13:42
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f47e861 and d45a7f9.

📒 Files selected for processing (8)
  • code/core/src/core-events/index.ts (2 hunks)
  • code/core/src/core-server/presets/common-preset.ts (2 hunks)
  • code/core/src/core-server/server-channel/preview-initialized-channel.ts (1 hunks)
  • code/core/src/manager/globals/exports.ts (1 hunks)
  • code/core/src/preview-api/modules/preview-web/Preview.tsx (2 hunks)
  • code/core/src/telemetry/event-cache.ts (1 hunks)
  • code/core/src/telemetry/telemetry.ts (1 hunks)
  • code/core/src/telemetry/types.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,json,html,ts,tsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,jsx,json,html,ts,tsx,mjs}: Run Prettier formatting on changed files before committing
Run ESLint on changed files and fix all errors/warnings before committing (use yarn lint:js:cmd <file>)

Files:

  • code/core/src/core-events/index.ts
  • code/core/src/manager/globals/exports.ts
  • code/core/src/preview-api/modules/preview-web/Preview.tsx
  • code/core/src/core-server/server-channel/preview-initialized-channel.ts
  • code/core/src/telemetry/event-cache.ts
  • code/core/src/core-server/presets/common-preset.ts
  • code/core/src/telemetry/types.ts
  • code/core/src/telemetry/telemetry.ts
**/*.{ts,tsx,js,jsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Export functions from modules when they need to be unit-tested

Files:

  • code/core/src/core-events/index.ts
  • code/core/src/manager/globals/exports.ts
  • code/core/src/preview-api/modules/preview-web/Preview.tsx
  • code/core/src/core-server/server-channel/preview-initialized-channel.ts
  • code/core/src/telemetry/event-cache.ts
  • code/core/src/core-server/presets/common-preset.ts
  • code/core/src/telemetry/types.ts
  • code/core/src/telemetry/telemetry.ts
code/**/*.{ts,tsx,js,jsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

In application code, use Storybook loggers instead of console.* (client code: storybook/internal/client-logger; server code: storybook/internal/node-logger)

Files:

  • code/core/src/core-events/index.ts
  • code/core/src/manager/globals/exports.ts
  • code/core/src/preview-api/modules/preview-web/Preview.tsx
  • code/core/src/core-server/server-channel/preview-initialized-channel.ts
  • code/core/src/telemetry/event-cache.ts
  • code/core/src/core-server/presets/common-preset.ts
  • code/core/src/telemetry/types.ts
  • code/core/src/telemetry/telemetry.ts
{code/**,scripts/**}/**/*.{ts,tsx,js,jsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not use console.log, console.warn, or console.error directly unless in isolated files where importing loggers would significantly increase bundle size

Files:

  • code/core/src/core-events/index.ts
  • code/core/src/manager/globals/exports.ts
  • code/core/src/preview-api/modules/preview-web/Preview.tsx
  • code/core/src/core-server/server-channel/preview-initialized-channel.ts
  • code/core/src/telemetry/event-cache.ts
  • code/core/src/core-server/presets/common-preset.ts
  • code/core/src/telemetry/types.ts
  • code/core/src/telemetry/telemetry.ts
🧠 Learnings (1)
📚 Learning: 2025-09-24T09:39:39.233Z
Learnt from: ndelangen
PR: storybookjs/storybook#32507
File: code/core/src/manager/globals/globals-module-info.ts:25-33
Timestamp: 2025-09-24T09:39:39.233Z
Learning: In Storybook, storybook/actions/decorator is a preview-only entrypoint and should not be included in manager globals configuration. The duplicatedKeys array in code/core/src/manager/globals/globals-module-info.ts is specifically for manager-side externalization, not preview entrypoints.

Applied to files:

  • code/core/src/manager/globals/exports.ts
🧬 Code graph analysis (3)
code/core/src/preview-api/modules/preview-web/Preview.tsx (1)
code/renderers/web-components/template/components/Html.js (1)
  • globalThis (5-5)
code/core/src/core-server/server-channel/preview-initialized-channel.ts (3)
code/core/src/telemetry/types.ts (1)
  • Options (93-100)
code/core/src/types/modules/core-common.ts (1)
  • CoreConfig (20-57)
code/core/src/telemetry/event-cache.ts (1)
  • getLastEvents (31-33)
code/core/src/core-server/presets/common-preset.ts (1)
code/core/src/core-server/server-channel/preview-initialized-channel.ts (1)
  • initPreviewInitializedChannel (9-31)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: normal
  • GitHub Check: Core Unit Tests, windows-latest
🔇 Additional comments (10)
code/core/src/telemetry/event-cache.ts (1)

26-33: LGTM! Clean refactoring to improve reusability.

Extracting getLastEvents() as a separate exported function is a good refactoring that enables other modules to access the last events cache with a safe default.

code/core/src/core-server/presets/common-preset.ts (2)

36-36: LGTM! Proper integration of the new preview-initialized channel.

The import follows the established pattern for other server channel modules.


262-262: LGTM! Consistent with other channel initializations.

The initialization call follows the same pattern as the other channel initializers in this function.

code/core/src/core-events/index.ts (2)

61-62: LGTM! Standard event addition.

The new PREVIEW_INITIALIZED event follows the established naming and documentation conventions.


119-119: LGTM! Proper public export.

The event is correctly included in the named exports for external consumption.

code/core/src/telemetry/types.ts (1)

35-36: LGTM! Type extension for new telemetry event.

The new 'preview-first-load' event type is correctly added to the union.

code/core/src/telemetry/telemetry.ts (1)

117-118: LGTM! Improved consistency in awaiting cache operations.

The refactored logic ensures saveToCache is consistently awaited in both immediate and non-immediate modes, which is more reliable than the previous implementation.

code/core/src/preview-api/modules/preview-web/Preview.tsx (2)

12-12: LGTM! Proper import of the new event.

The PREVIEW_INITIALIZED event is correctly imported from the core-events module.


132-134: LGTM! Proper event emission after initialization.

The event is emitted at the right time (after initialization completes) with appropriate optional chaining for userAgent extraction. The eslint-disable comment acknowledges the browser compatibility consideration.

code/core/src/manager/globals/exports.ts (1)

570-570: LGTM! Proper export addition.

The PREVIEW_INITIALIZED event is correctly added to the manager globals exports in alphabetical order.

@storybook-app-bot
Copy link

storybook-app-bot bot commented Oct 22, 2025

Package Benchmarks

Commit: 44d650a, ran on 24 October 2025 at 11:50:16 UTC

No significant changes detected, all good. 👏

@yannbf yannbf merged commit 124987d into next Oct 24, 2025
60 checks passed
@yannbf yannbf deleted the shilman/preview-first-load branch October 24, 2025 14:22
yannbf added a commit that referenced this pull request Oct 24, 2025
Core: Add `preview-first-load` telemetry
(cherry picked from commit 124987d)
@github-actions github-actions bot mentioned this pull request Oct 24, 2025
5 tasks
@github-actions github-actions bot added the patch:done Patch/release PRs already cherry-picked to main/release branch label Oct 24, 2025
@ndelangen ndelangen removed the patch:yes Bugfix & documentation PR that need to be picked to main branch label Oct 28, 2025
@coderabbitai coderabbitai bot mentioned this pull request Nov 18, 2025
8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci:normal core maintenance User-facing maintenance tasks patch:done Patch/release PRs already cherry-picked to main/release branch telemetry

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants