Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(notebooks): show widget beta pricing and generation costs (#104323)

Marius Andrab818090d333a
diff --git a/docs/internal/generated-notebook-widgets.md b/docs/internal/generated-notebook-widgets.md
index 12c0ffcb36d2..4dd4f2c08212 100644
--- a/docs/internal/generated-notebook-widgets.md
+++ b/docs/internal/generated-notebook-widgets.md
@@ -2,6 +2,16 @@
Notebooks can generate interactive widgets from instructions and the notebook's SQL and Python dataframe context.
+Generated widgets are in beta. Generation uses PostHog AI credits based on model token costs plus a 20% markup, including security review and retries.
+The insert menu, notebook widget toolbar, generation dialog, and reusable widget page show a **BETA** label.
+Before generating, improving, or regenerating a widget, the form says "Generation uses PostHog AI credits".
+The ungenerated widget preview includes a model selector directly above **Generate widget**, synchronized with the model in the edit panel.
+The notebook edit panel and reusable widget page show the selected version's estimated generation charge as a small USD amount beside the version controls.
+The info tooltip explains that the estimate includes all model requests in that successful generation job.
+Costs come from recorded gateway usage and include the same markup as PostHog AI credit billing; final credits can differ because billing rounds aggregated usage.
+Older versions and generations without available usage records do not show a cost.
+The estimate does not include separate failed or canceled generation jobs, or notebook compute.
+
- Generation runs as a durable background job. The notebook shows its phase, elapsed time, cancellation, and terminal errors. Queued jobs stop immediately when canceled.
- Failed jobs expose a stable error code and the failed source-generation, security-review, or publishing phase. AI request logs include upstream status and request IDs when available.
- Source generation and security review send Claude requests through the native Anthropic Messages format in both local and cloud environments.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 641421239754..87537f940809 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9760,6 +9760,14 @@ snapshots:
hash: v1.k794b7964.099228351b7624d666505094801048a76f10d19b6122bdae57095a2f248a85af.ceSOAt-JxUJXvTOF3O-qcPOyDJfYQy_JxLBIJTITHBU
scenes-app-notebooks-dataframe-hint--on-a-cell-with-no-dataframe-name--light:
hash: v1.k794b7964.9cb4583e02d3192ab41346398046f32619977f6a4d7d56644245f4018b1c1451.rqbs7lbVXIaK4wH1m1_NFxMizFc2esosnCWk6XB-_VQ
+ scenes-app-notebooks-generated-widgets--after-generation--dark:
+ hash: v1.k794b7964.d1d2b0fec7395326411e534a831ad533fcc0dc70d34828a4a4fa0c2abdbf3f21.XusZlQKYjdLywVbUTvIRNQjZAwRO2mzx_RK2bTl3QkE
+ scenes-app-notebooks-generated-widgets--after-generation--light:
+ hash: v1.k794b7964.986afdd0b4386ad2fa3f9906179742611beecb535f59eb62e1c1e5b82624e94c.eGNt5HvvSQW7br9YOxNI25E0-stgO3c9zpn1itVnwFk
+ scenes-app-notebooks-generated-widgets--before-generation--dark:
+ hash: v1.k794b7964.170cc8f24367e614fa935570b13f4ce7d5f83f617b567e045032502491a4530b.Z7u0Hvsxpxt0kN-NVXCmvNAunsxT4eu_x18JZOMjbf0
+ scenes-app-notebooks-generated-widgets--before-generation--light:
+ hash: v1.k794b7964.f8eabbbe270e16f6db6253fac4ccc1298d6486f4fcc54d086f39b494e32276bb.byEVF2WvcVULWZ_b-qJMNkCK-hCMqS-EcQNFNyVUVd4
scenes-app-notebooks-kernel-info--free-compute--dark:
hash: v1.k794b7964.e8e81cc18d66dcca3d1cd23cc5017833b040abcaa4a3be85c6161787fed0efcd.OiaNuBz69zbpOxiLQsFYOQuJn_226577RmjJ_GbOdyQ
scenes-app-notebooks-kernel-info--free-compute--light:
@@ -9800,6 +9808,18 @@ snapshots:
hash: v1.k794b7964.d6c551c581824287879e157abaa61874713bb6389caaa015b1bac305a69c36cb.szC1MJRFAMY6z5Cr9uPHF3D39RLL7VUUFs3FiiemlsA
scenes-app-notebooks-nodes-support-tickets--with-tickets--light:
hash: v1.k794b7964.10a73c98dea8faa9011e00a7f44278e12216eb077e68ffefb4f2799f0ab519ad.yCkGWzRUKGODRvA_V0WHSn9Pdm5FhPyEfJVEcilSpP8
+ scenes-app-notebooks-widget-generation-cost--less-than-one-cent--dark:
+ hash: v1.k794b7964.3d7ab4ed80e86dee207323ed0baf83d86a9c0b53c868f64769ddc708b4ab5881.RKwiZJnBL8K4kWfRM3MV6Aruoqr20twxVmepMy_SU6Y
+ scenes-app-notebooks-widget-generation-cost--less-than-one-cent--light:
+ hash: v1.k794b7964.622b0a479dc2756ed6cc29a905c1cbf5175353a26e7e00136ab56c3514a97269.eHq5b1x8B9WRQyVrE4fJvjYubM0n03L_h9wyY-_qt4I
+ scenes-app-notebooks-widget-generation-cost--recorded--dark:
+ hash: v1.k794b7964.cb77362ca79f991a86987bc65812169c0e182bec15e3ed4e48acdf04d65b5955.Nm3_ePm8q_cvbc9qHxQf9GpNRiyR2BNw_EKsrZtewPM
+ scenes-app-notebooks-widget-generation-cost--recorded--light:
+ hash: v1.k794b7964.3d99aad2a717fdc8686155905c9cadec070f0e7c0878d6901a79f93c9260021c.KFOtAeXYa5hBx9mpn2exGgH-A2Y7tKQuysoooaawKvU
+ scenes-app-notebooks-widget-generation-cost--unavailable--dark:
+ hash: v1.k794b7964.431c6fbce411efecf13ab5536c9129d8dac36dc5bbef4dacd3cb2fd35b406d68.KccBpMCll4d6YnEmZ3sCesR3PPCt4-V1_eSyswvcW-g
+ scenes-app-notebooks-widget-generation-cost--unavailable--light:
+ hash: v1.k794b7964.3f0d75a1e968543780ddeb9654999646b3fff702645421f0385ec674825035d1.gcQKz94AOWTJ53QZp5qfNnlRaMkd71BKlGH7ouDdn4c
scenes-app-notebooks-widget-views--action-views--dark:
hash: v1.k794b7964.9a752af48c274e00d922b4491c01aaef874019b886d91f65e891a8d4ce18361a.a8f4IjMdEHKLV_5jRIII-5EsmnVYuCpmuohpIwZVNZw
scenes-app-notebooks-widget-views--action-views--light:
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx
index 7eb9b6d534eb..233c4dabeba4 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx
@@ -106,7 +106,7 @@ describe('markdownNotebookRegistry', () => {
it('gates widget insertion and registers only the Widget component', () => {
expect(getInsertCommandsByLabel({ [FEATURE_FLAGS.NOTEBOOK_GENERATED_WIDGETS]: true }, 'Widget')).toEqual([
- { key: 'component-Widget', category: 'Common' },
+ { key: 'component-Widget', category: 'Common', badge: 'BETA' },
])
expect(getInsertCommandsByLabel({}, 'Widget')).toEqual([])
for (const legacyTag of ['GeneratedWidget', 'GenUI']) {
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
index 1de5e103da66..5e2f8e6cdfa9 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
@@ -311,6 +311,7 @@ export const MARKDOWN_NODE_DEFINITIONS: {
ToolbarComponent: NotebookGeneratedWidgetRunButton,
insertCommand: {
category: COMMON_INSERT_COMMAND_CATEGORY,
+ badge: 'BETA',
aliases: ['visualization', 'widget', '3d'],
defaultProps: () => ({
...getDefaultPropsForNodeType(NotebookNodeType.GeneratedWidget),
diff --git a/posthog/llm/billing.py b/posthog/llm/billing.py
new file mode 100644
index 000000000000..3b936cae0751
--- /dev/null
+++ b/posthog/llm/billing.py
@@ -0,0 +1 @@
+AI_COST_MARKUP_PERCENT = 0.2
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 104320b000f3..3c6f66427cfd 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -33,6 +33,7 @@ from posthog.cloud_utils import get_cached_instance_license
from posthog.constants import FlagRequestType
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
+from posthog.llm.billing import AI_COST_MARKUP_PERCENT
from posthog.logging.timing import timed_log
from posthog.models import OrganizationMembership, User
from posthog.models.ai_events.sql import TABLE_BASE_NAME as AI_EVENTS_TABLE
@@ -1728,8 +1729,6 @@ def get_teams_with_ai_event_count_in_period(
return [(team_id, max(0, count - sponsored_by_team.get(team_id, 0))) for team_id, count in base_counts]
-# AI billing markup: 20% markup on top of cost
-AI_COST_MARKUP_PERCENT = 0.2
# PostHog Desktop bills model costs as pure pass-through: no markup
POSTHOG_CODE_COST_MARKUP_PERCENT = 0.0
# Tools excluded from AI billing (traces with only these tools are not billed)
diff --git a/products/links/frontend/generated/api.zod.ts b/products/links/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..4b0d83f2d651
--- /dev/null
+++ b/products/links/frontend/generated/api.zod.ts
@@ -0,0 +1,85 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * Create, read, update, and delete links.
+ */
+export const linksCreateBodyRedirectUrlMax = 2048
+
+export const linksCreateBodyShortLinkDomainMax = 255
+
+export const linksCreateBodyShortCodeMax = 255
+
+export const LinksCreateBody = /* @__PURE__ */ zod.object({
+ redirect_url: zod.url().max(linksCreateBodyRedirectUrlMax).describe('Destination the short link redirects to.'),
+ short_link_domain: zod
+ .string()
+ .max(linksCreateBodyShortLinkDomainMax)
+ .describe('Domain the short link is hosted on. Only phog.gg is accepted.'),
+ short_code: zod
+ .string()
+ .max(linksCreateBodyShortCodeMax)
+ .describe("The unique code\/path that identifies the short link, e.g. 'abc123'"),
+ description: zod.string().nullish().describe('Free-form note about what the link is for.'),
+ _create_in_folder: zod.string().optional().describe('Folder path to file the link under in the project tree.'),
+})
+
+/**
+ * Create, read, update, and delete links.
+ */
+export const linksUpdateBodyRedirectUrlMax = 2048
+
+export const linksUpdateBodyShortLinkDomainMax = 255
+
+export const linksUpdateBodyShortCodeMax = 255
+
+export const LinksUpdateBody = /* @__PURE__ */ zod.object({
+ redirect_url: zod.url().max(linksUpdateBodyRedirectUrlMax).describe('Destination the short link redirects to.'),
+ short_link_domain: zod
+ .string()
+ .max(linksUpdateBodyShortLinkDomainMax)
+ .describe('Domain the short link is hosted on. Only phog.gg is accepted.'),
+ short_code: zod
+ .string()
+ .max(linksUpdateBodyShortCodeMax)
+ .describe("The unique code\/path that identifies the short link, e.g. 'abc123'"),
+ description: zod.string().nullish().describe('Free-form note about what the link is for.'),
+ _create_in_folder: zod.string().optional().describe('Folder path to file the link under in the project tree.'),
+})
+
+/**
+ * Create, read, update, and delete links.
+ */
+export const linksPartialUpdateBodyRedirectUrlMax = 2048
+
+export const linksPartialUpdateBodyShortLinkDomainMax = 255
+
+export const linksPartialUpdateBodyShortCodeMax = 255
+
+export const LinksPartialUpdateBody = /* @__PURE__ */ zod.object({
+ redirect_url: zod
+ .url()
+ .max(linksPartialUpdateBodyRedirectUrlMax)
+ .optional()
+ .describe('Destination the short link redirects to.'),
+ short_link_domain: zod
+ .string()
+ .max(linksPartialUpdateBodyShortLinkDomainMax)
+ .optional()
+ .describe('Domain the short link is hosted on. Only phog.gg is accepted.'),
+ short_code: zod
+ .string()
+ .max(linksPartialUpdateBodyShortCodeMax)
+ .optional()
+ .describe("The unique code\/path that identifies the short link, e.g. 'abc123'"),
+ description: zod.string().nullish().describe('Free-form note about what the link is for.'),
+ _create_in_folder: zod.string().optional().describe('Folder path to file the link under in the project tree.'),
+})
diff --git a/products/notebooks/backend/migrations/0023_generated_widget_generation_cost.py b/products/notebooks/backend/migrations/0023_generated_widget_generation_cost.py
new file mode 100644
index 000000000000..e2a67ae8237d
--- /dev/null
+++ b/products/notebooks/backend/migrations/0023_generated_widget_generation_cost.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.17 on 2026-09-22 12:47
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("notebooks", "0022_reusable_widgets"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="generatedwidgetversion",
+ name="generation_cost_usd",
+ field=models.DecimalField(blank=True, decimal_places=6, max_digits=12, null=True),
+ ),
+ ]
diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txt
index ca31c8d8d939..5874819f088b 100644
--- a/products/notebooks/backend/migrations/max_migration.txt
+++ b/products/notebooks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0022_reusable_widgets
+0023_generated_widget_generation_cost
diff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.py
index b0976bb44d0c..9300b94744fb 100644
--- a/products/notebooks/backend/models.py
+++ b/products/notebooks/backend/models.py
@@ -341,6 +341,7 @@ class GeneratedWidgetVersion(TeamScopedRootMixin, UUIDModel):
prompt_history: JSONField = JSONField(default=list)
model = models.CharField(max_length=64, blank=True, default="")
generator_version = models.CharField(max_length=32)
+ generation_cost_usd = models.DecimalField(max_digits=12, decimal_places=6, null=True, blank=True)
input_contract: JSONField = JSONField(default=list)
demo_data: JSONField = JSONField(default=dict, db_default={})
schema_hash = models.CharField(max_length=64)
diff --git a/products/notebooks/backend/presentation/reusable_widget_serializers.py b/products/notebooks/backend/presentation/reusable_widget_serializers.py
index 36cf606e98af..57a857b59009 100644
--- a/products/notebooks/backend/presentation/reusable_widget_serializers.py
+++ b/products/notebooks/backend/presentation/reusable_widget_serializers.py
@@ -144,6 +144,13 @@ class ReusableWidgetPageSerializer(serializers.Serializer):
class ReusableWidgetVersionDetailSerializer(serializers.Serializer):
+ generation_cost_usd = serializers.DecimalField(
+ max_digits=12,
+ decimal_places=6,
+ allow_null=True,
+ required=False,
+ help_text="Estimated generation charge in USD, including retries, security review, and the AI credit markup. Null when unavailable.",
+ )
id = serializers.UUIDField(help_text="Immutable widget version identifier.")
title = serializers.CharField(help_text="Title stored with this version.")
version = serializers.IntegerField(help_text="One-based version number.")
diff --git a/products/notebooks/backend/presentation/widget_serializers.py b/products/notebooks/backend/presentation/widget_serializers.py
index 66bc977cb69c..0f3767ad08a7 100644
--- a/products/notebooks/backend/presentation/widget_serializers.py
+++ b/products/notebooks/backend/presentation/widget_serializers.py
@@ -186,6 +186,13 @@ class WidgetStatusSerializer(serializers.Serializer):
class WidgetVersionSerializer(serializers.Serializer):
+ generation_cost_usd = serializers.DecimalField(
+ max_digits=12,
+ decimal_places=6,
+ allow_null=True,
+ required=False,
+ help_text="Estimated generation charge in USD, including retries, security review, and the AI credit markup. Null when unavailable.",
+ )
id = serializers.UUIDField(help_text="Immutable widget version identifier.")
parent_version_id = serializers.UUIDField(allow_null=True, help_text="Version this one was based on.")
version = serializers.IntegerField(min_value=1, help_text="One-based version number.")
diff --git a/products/notebooks/backend/reusable_widgets.py b/products/notebooks/backend/reusable_widgets.py
index 225e9d08b226..4f39ea3878f2 100644
--- a/products/notebooks/backend/reusable_widgets.py
+++ b/products/notebooks/backend/reusable_widgets.py
@@ -1,6 +1,7 @@
import json
from collections.abc import Callable
from datetime import datetime
+from decimal import Decimal
from typing import TYPE_CHECKING, Protocol, cast
from uuid import UUID
@@ -134,6 +135,7 @@ class ReusableWidgetVersionDetail:
security_review: WidgetSecurityReviewState | None
has_demo_data: bool
created_at: datetime
+ generation_cost_usd: Decimal | None = None
@frozen
@@ -246,6 +248,7 @@ def _version_detail(
security_review=_security_review_state(version),
has_demo_data=bool(version.demo_data),
created_at=version.created_at,
+ generation_cost_usd=version.generation_cost_usd,
)
diff --git a/products/notebooks/backend/test/test_widget_generation_cost.py b/products/notebooks/backend/test/test_widget_generation_cost.py
new file mode 100644
index 000000000000..5e0ef792cac9
--- /dev/null
+++ b/products/notebooks/backend/test/test_widget_generation_cost.py
@@ -0,0 +1,52 @@
+from decimal import Decimal
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase, override_settings
+
+import httpx
+from parameterized import parameterized
+
+from products.notebooks.backend.widget_generation_cost import get_widget_generation_cost
+
+
+@override_settings(AI_GATEWAY_URL="http://gateway.test/v1", AI_GATEWAY_API_KEY="test-gateway-key")
+class TestWidgetGenerationCost(SimpleTestCase):
+ def test_sums_generation_retries_and_review_with_billing_markup(self) -> None:
+ responses = [
+ httpx.Response(200, json={"cost_usd": cost}, request=httpx.Request("GET", "http://gateway.test"))
+ for cost in ("0.04", "0.01", "0.002")
+ ]
+ with patch.object(httpx.Client, "get", side_effect=responses) as get:
+ cost = get_widget_generation_cost(["generation", "retry", "review"])
+
+ assert cost == Decimal("0.062400")
+ assert [call.args[0] for call in get.call_args_list] == [
+ "usage/generation",
+ "usage/retry",
+ "usage/review",
+ ]
+
+ @parameterized.expand([(None,), ("not-a-cost",), ("NaN",), ("Infinity",), ("-1",)])
+ def test_invalid_cost_is_unavailable(self, amount: str | None) -> None:
+ response = httpx.Response(200, json={"cost_usd": amount}, request=httpx.Request("GET", "http://gateway.test"))
+ with patch.object(httpx.Client, "get", return_value=response):
+ assert get_widget_generation_cost(["generation"]) is None
+
+ def test_missing_request_ids_do_not_report_a_partial_total(self) -> None:
+ with patch.object(httpx.Client, "get") as get:
+ assert get_widget_generation_cost(["generation", None]) is None
+ assert get_widget_generation_cost([]) is None
+ get.assert_not_called()
+
+ @parameterized.expand([(404,), (503,)])
+ def test_missing_usage_does_not_fail_widget_generation(self, status: int) -> None:
+ response = httpx.Response(status, request=httpx.Request("GET", "http://gateway.test"))
+ with patch.object(httpx.Client, "get", return_value=response):
+ assert get_widget_generation_cost(["generation"]) is None
+
+ @override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")
+ def test_legacy_gateway_cost_is_unavailable(self) -> None:
+ with patch.object(httpx.Client, "get") as get:
+ assert get_widget_generation_cost(["generation"]) is None
+ get.assert_not_called()
diff --git a/products/notebooks/backend/test/test_widgets.py b/products/notebooks/backend/test/test_widgets.py
index 4470e53f7ddb..317d9939dd5c 100644
--- a/products/notebooks/backend/test/test_widgets.py
+++ b/products/notebooks/backend/test/test_widgets.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from decimal import Decimal
from types import SimpleNamespace
from typing import Any, cast
from uuid import uuid4
@@ -177,6 +178,9 @@ class TestWidgetGeneration(SimpleTestCase):
invalid_stream,
valid_stream,
]
+ invalid_stream.response.headers = {"x-request-id": "generation-first-attempt"}
+ valid_stream.response.headers = {"x-request-id": "generation-retry"}
+ request_ids: list[str | None] = []
source = generate_widget_source(
team_id=42,
@@ -185,9 +189,11 @@ class TestWidgetGeneration(SimpleTestCase):
schemas=[{"name": "locations_df", "columns": [{"name": "lat", "type": "float64"}]}],
input_names=["locations_df"],
client=client,
+ request_ids=request_ids,
)
assert source.title == "Interactive globe"
+ assert request_ids == ["generation-first-attempt", "generation-retry"]
assert source.source == "export default function Canvas() { return <div>Ready</div> }"
assert client.with_options.call_args.kwargs["max_retries"] == 0
assert client.messages.create.call_count == 2
@@ -362,6 +368,8 @@ class TestWidgetGeneration(SimpleTestCase):
client.with_options.return_value = client
stream = completion_stream(content)
client.messages.create.return_value = stream
+ stream.response.headers = {"x-request-id": "security-review"}
+ request_ids: list[str | None] = []
review = review_widget_source(
team_id=42,
@@ -369,9 +377,11 @@ class TestWidgetGeneration(SimpleTestCase):
source="export default function Widget() { return <div /> }",
input_names=["public_df"],
client=client,
+ request_ids=request_ids,
)
assert review.severity == expected_severity
+ assert request_ids == ["security-review"]
assert len(review.findings) == expected_findings
assert review.review_version == WIDGET_SECURITY_REVIEW_VERSION
request = client.messages.create.call_args.kwargs
@@ -888,6 +898,7 @@ class TestWidgetData(APIBaseTest):
prompt_delta="Make it lighter",
model="claude-sonnet-4-6",
generator_version="4",
+ generation_cost_usd=Decimal("0.123456"),
input_contract=initial_version.input_contract,
schema_hash="",
security_review_severity=GeneratedWidgetVersion.SecurityReviewSeverity.HIGH,
@@ -976,6 +987,7 @@ class TestWidgetData(APIBaseTest):
assert len(history_response.json()["results"]) == 1
assert history_response.json()["results"][0]["build_hash"] == "b" * 64
assert history_response.json()["results"][0]["security_review"]["severity"] == "high"
+ assert history_response.json()["results"][0]["generation_cost_usd"] == "0.123456"
def test_active_generation_hides_a_transient_preview_error(self) -> None:
instance = self._mapping()
@@ -1675,8 +1687,13 @@ class TestWidgetData(APIBaseTest):
publication_id = uuid4()
events: list[str] = []
- def perform_review(**_kwargs: object) -> WidgetSecurityReview:
+ def perform_generation(*, request_ids: list[str | None], **_kwargs: object) -> GeneratedWidgetSource:
+ request_ids.append("generation")
+ return GeneratedWidgetSource(title="Lighter globe", source=source)
+
+ def perform_review(*, request_ids: list[str | None], **_kwargs: object) -> WidgetSecurityReview:
events.append("review")
+ request_ids.append("review")
return security_review
def prepare_source(**_kwargs: object) -> MagicMock:
@@ -1684,9 +1701,17 @@ class TestWidgetData(APIBaseTest):
return MagicMock()
with (
+ self.settings(AI_GATEWAY_URL="http://gateway.test/v1", AI_GATEWAY_API_KEY="test-gateway-key"),
+ patch.object(
+ httpx.Client,
+ "get",
+ return_value=httpx.Response(
+ 200, json={"cost_usd": "0.05"}, request=httpx.Request("GET", "http://gateway.test")
+ ),
+ ),
patch(
"products.notebooks.backend.widget_generation.generate_widget_source",
- return_value=GeneratedWidgetSource(title="Lighter globe", source=source),
+ side_effect=perform_generation,
),
patch(
"products.notebooks.backend.widget_generation.review_widget_source",
@@ -1728,6 +1753,7 @@ class TestWidgetData(APIBaseTest):
assert version.security_review_model == WIDGET_SECURITY_REVIEW_MODEL
assert version.security_review_version == "1"
assert version.security_reviewed_at is not None
+ assert version.generation_cost_usd == Decimal("0.120000")
review.assert_called_once()
assert review.call_args.kwargs["team_id"] == self.team.id
assert review.call_args.kwargs["trace_id"] == f"notebook-widget-security-review-{job.id}"
diff --git a/products/notebooks/backend/widget_generation.py b/products/notebooks/backend/widget_generation.py
index a43e1044bae6..85cdc7077744 100644
--- a/products/notebooks/backend/widget_generation.py
+++ b/products/notebooks/backend/widget_generation.py
@@ -419,6 +419,7 @@ def review_widget_source(
source: str,
input_names: list[str],
client: Anthropic | None = None,
+ request_ids: list[str | None] | None = None,
is_cancelled: Callable[[], bool] = lambda: False,
) -> WidgetSecurityReview:
resolved_client = client or build_anthropic_client(
@@ -453,6 +454,8 @@ def review_widget_source(
stream=True,
timeout=remaining_seconds,
)
+ if request_ids is not None:
+ request_ids.append(stream.response.headers.get("x-request-id"))
content = _read_stream(stream, is_cancelled, deadline)
except WidgetSourceGenerationCancelled:
raise
@@ -515,6 +518,7 @@ def generate_widget_source(
input_names: list[str],
model: str = DEFAULT_WIDGET_MODEL,
client: Anthropic | None = None,
+ request_ids: list[str | None] | None = None,
is_cancelled: Callable[[], bool] = lambda: False,
base_source: str | None = None,
change_prompt: str | None = None,
@@ -580,6 +584,8 @@ def generate_widget_source(
stream=True,
timeout=min(WIDGET_MODEL_TIMEOUT_SECONDS[model], remaining_seconds),
)
+ if request_ids is not None:
+ request_ids.append(stream.response.headers.get("x-request-id"))
content = _read_stream(stream, is_cancelled, deadline)
except WidgetSourceGenerationCancelled:
raise
diff --git a/products/notebooks/backend/widget_generation_cost.py b/products/notebooks/backend/widget_generation_cost.py
new file mode 100644
index 000000000000..d7362d86c4d9
--- /dev/null
+++ b/products/notebooks/backend/widget_generation_cost.py
@@ -0,0 +1,43 @@
+from decimal import Decimal, InvalidOperation
+from urllib.parse import quote
+
+import httpx
+import structlog
+
+from posthog.llm.billing import AI_COST_MARKUP_PERCENT
+from posthog.llm.gateway_client import resolve_ai_gateway_config
+
+logger = structlog.get_logger(__name__)
+
+
+def get_widget_generation_cost(request_ids: list[str | None]) -> Decimal | None:
+ gateway = resolve_ai_gateway_config()
+ if gateway is None or not request_ids or any(request_id is None for request_id in request_ids):
+ return None
+
+ total = Decimal(0)
+ try:
+ with httpx.Client(
+ base_url=gateway.url.rstrip("/") + "/",
+ headers={"Authorization": f"Bearer {gateway.api_key}"},
+ timeout=3,
+ trust_env=False,
+ ) as client:
+ for request_id in dict.fromkeys(request_ids):
+ assert request_id is not None
+ response = client.get(f"usage/{quote(request_id, safe='')}")
+ response.raise_for_status()
+ body = response.json()
+ if not isinstance(body, dict):
+ return None
+ amount = body.get("cost_usd")
+ if not isinstance(amount, str):
+ return None
+ cost = Decimal(amount)
+ if not cost.is_finite() or cost < 0:
+ return None
+ total += cost
+ return (total * (1 + Decimal(str(AI_COST_MARKUP_PERCENT)))).quantize(Decimal("0.000001"))
+ except (httpx.HTTPError, ValueError, InvalidOperation):
+ logger.warning("notebook_widget_generation_cost_unavailable")
+ return None
diff --git a/products/notebooks/backend/widgets.py b/products/notebooks/backend/widgets.py
index da1a0f79fea2..d4a5f63983a5 100644
--- a/products/notebooks/backend/widgets.py
+++ b/products/notebooks/backend/widgets.py
@@ -5,6 +5,7 @@ import hashlib
import logging
from collections.abc import Callable
from datetime import datetime, timedelta
+from decimal import Decimal
from time import monotonic
from uuid import UUID
@@ -160,6 +161,7 @@ class WidgetVersionSummary:
is_current: bool
security_review: WidgetSecurityReviewState | None
build_hash: str | None = None
+ generation_cost_usd: Decimal | None = None
@frozen
@@ -1018,6 +1020,9 @@ def run_widget_generation_job(job_id: UUID, team_id: int) -> None:
generate_widget_source,
review_widget_source,
)
+ from products.notebooks.backend.widget_generation_cost import ( # noqa: PLC0415 - keeps the model client off Django startup
+ get_widget_generation_cost,
+ )
with transaction.atomic():
job = (
@@ -1111,6 +1116,7 @@ def run_widget_generation_job(job_id: UUID, team_id: int) -> None:
effective_prompt = _materialize_effective_prompt(job.base_version)
frames = _bounded_schema_context(job.input_contract)
frame_names = [str(item.get("slot")) for item in job.input_contract if item.get("slot")]
+ request_ids: list[str | None] = []
generated = generate_widget_source(
team_id=job.team_id,
trace_id=f"notebook-widget-{job.id}",
@@ -1121,6 +1127,7 @@ def run_widget_generation_job(job_id: UUID, team_id: int) -> None:
is_cancelled=is_cancelled,
base_source=base_source,
change_prompt=change_prompt,
+ request_ids=request_ids,
)
source = generated.source
title = generated.title or _display_name(effective_prompt)
@@ -1144,6 +1151,7 @@ def run_widget_generation_job(job_id: UUID, team_id: int) -> None:
source=source,
input_names=frame_names,
is_cancelled=is_cancelled,
+ request_ids=request_ids,
)
# Publication preserves the exact reviewed artifact for inspection. Browser consumers gate execution of
# every non-clean verdict on explicit trust for this version's immutable build hash.
@@ -1178,6 +1186,7 @@ def run_widget_generation_job(job_id: UUID, team_id: int) -> None:
job.base_version.canvas_source_version_id if job.base_version is not None else None
),
)
+ generation_cost_usd = get_widget_generation_cost(request_ids)
with canvas_facade.notebook_canvas_source_transaction(team_id=job.team_id, prepared=prepared_source):
locked_job = (
GeneratedWidgetGenerationJob.objects.for_team(job.team_id)
@@ -1226,6 +1235,7 @@ def run_widget_generation_job(job_id: UUID, team_id: int) -> None:
prompt_history=prompt_history,
model=job.model,
generator_version=GENERATOR_VERSION,
+ generation_cost_usd=generation_cost_usd,
input_contract=_version_input_contract(job.input_contract),
demo_data=(
job.base_version.demo_data
@@ -1583,6 +1593,7 @@ def list_widget_versions(*, notebook: Notebook, node_id: str, offset: int = 0, l
is_current=version.id == current_id,
security_review=_security_review_state(version),
build_hash=canvas_version.build_hash if canvas_version is not None else None,
+ generation_cost_usd=version.generation_cost_usd,
)
)
next_offset = offset + limit if offset + limit < count else None
diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx
index 6530d730b4f2..90aafb308dbd 100644
--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx
+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx
@@ -6,6 +6,7 @@ import { IconPlayFilled } from '@posthog/icons'
import { usePublishNotebookComponentRunHandler } from 'lib/components/MarkdownNotebook/componentRunHandlers'
import type { NotebookComponentToolbarProps } from 'lib/components/MarkdownNotebook/types'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -28,7 +29,14 @@ export function NotebookGeneratedWidgetRunButton({
return null
}
- return <EditableNotebookGeneratedWidgetRunButton node={node} updateProps={updateProps} />
+ return (
+ <>
+ <LemonTag type="warning" size="small">
+ BETA
+ </LemonTag>
+ <EditableNotebookGeneratedWidgetRunButton node={node} updateProps={updateProps} />
+ </>
+ )
}
function EditableNotebookGeneratedWidgetRunButton({
diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.stories.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.stories.tsx
new file mode 100644
index 000000000000..5e5118f90a49
--- /dev/null
+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.stories.tsx
@@ -0,0 +1,135 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { BindLogic, useActions, useMountedLogic } from 'kea'
+import { useEffect } from 'react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { notebookTestTemplate } from 'scenes/notebooks/Notebook/__mocks__/notebook-template-for-snapshot'
+import { buildMarkdownNotebookContent } from 'scenes/notebooks/Notebook/markdownNotebookV2'
+import { MarkdownNotebookV2 } from 'scenes/notebooks/Notebook/MarkdownNotebookV2Renderer'
+import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'
+
+import { mswDecorator } from '~/mocks/browser'
+
+const shortId = 'widget-generation'
+const notebook = {
+ ...notebookTestTemplate('Widget generation', []),
+ short_id: shortId,
+ content: buildMarkdownNotebookContent(
+ '# Widget generation\n\n<Widget showFilters showResults nodeId="chart" prompt="Create an interactive bar chart" />'
+ ),
+}
+
+function WidgetNotebook(): JSX.Element {
+ const logic = useMountedLogic(notebookLogic({ shortId, mode: 'notebook' }))
+ const { clearLocalContent, loadNotebook, setEditable } = useActions(logic)
+ useEffect(() => {
+ clearLocalContent()
+ loadNotebook()
+ setEditable(true)
+ }, [clearLocalContent, loadNotebook, setEditable])
+ return (
+ <BindLogic logic={notebookLogic} props={logic.props}>
+ <div className="max-w-3xl mx-auto p-4">
+ <MarkdownNotebookV2 />
+ </div>
+ </BindLogic>
+ )
+}
+
+const meta: Meta = {
+ title: 'Scenes-App/Notebooks/Generated widgets',
+ component: WidgetNotebook,
+ parameters: {
+ layout: 'fullscreen',
+ featureFlags: [FEATURE_FLAGS.NOTEBOOK_GENERATED_WIDGETS],
+ testOptions: {
+ waitForSelector: '[data-attr="notebook-generated-widget-run-button"]',
+ },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/notebooks/widget-generation': notebook,
+ },
+ }),
+ ],
+}
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const BeforeGeneration: Story = {
+ parameters: {
+ msw: {
+ mocks: {
+ get: {
+ '/api/projects/:team_id/notebooks/widget-generation/widgets/chart/status': {
+ lifecycle_status: 'awaiting_generation',
+ has_versions: false,
+ active_job: null,
+ artifact_url: null,
+ error_detail: null,
+ current_version_id: null,
+ pinned_version_id: null,
+ frame_names: [],
+ input_bindings: {},
+ input_contract: [],
+ security_review: null,
+ is_reusable: false,
+ build_hash: null,
+ },
+ },
+ },
+ },
+ },
+}
+
+export const AfterGeneration: Story = {
+ parameters: {
+ testOptions: { waitForSelector: '[data-attr="widget-generation-cost"]' },
+ msw: {
+ mocks: {
+ get: {
+ '/api/projects/:team_id/notebooks/widget-generation/widgets/chart/status': {
+ lifecycle_status: 'ready',
+ has_versions: true,
+ active_job: null,
+ artifact_url: null,
+ error_detail: null,
+ current_version_id: '00000000-0000-4000-8000-000000000001',
+ pinned_version_id: null,
+ frame_names: [],
+ input_bindings: {},
+ input_contract: [],
+ security_review: null,
+ is_reusable: false,
+ build_hash: null,
+ },
+ '/api/projects/:team_id/notebooks/widget-generation/widgets/chart/versions': {
+ results: [
+ {
+ id: '00000000-0000-4000-8000-000000000001',
+ parent_version_id: null,
+ version: 1,
+ version_operation: 'initial',
+ prompt_delta: 'Create an interactive bar chart',
+ effective_prompt: 'Create an interactive bar chart',
+ model: 'claude-sonnet-5',
+ generation_cost_usd: '0.123456',
+ created_at: '2026-09-01T12:00:00Z',
+ build_status: 'ready',
+ artifact_url: null,
+ frame_names: [],
+ is_current: true,
+ security_review: null,
+ build_hash: null,
+ },
+ ],
+ count: 1,
+ next_offset: null,
+ },
+ },
+ },
+ },
+ },
+}
diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx
index 7815822000fe..135e21cb34f6 100644
--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx
+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx
@@ -1,7 +1,7 @@
import { useActions, useMountedLogic, useValues } from 'kea'
import { type ReactNode, useEffect } from 'react'
-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonSelect } from '@posthog/lemon-ui'
import { useComponentPanelState } from 'lib/components/MarkdownNotebook/componentPanelContext'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
@@ -22,12 +22,13 @@ import {
notebookNodeGeneratedWidgetLogic,
} from './notebookNodeGeneratedWidgetLogic'
import { NotebookNodeGeneratedWidgetSettings } from './NotebookNodeGeneratedWidgetSettings'
+import { NotebookWidgetBetaNotice } from './NotebookWidgetBetaNotice'
import { NotebookWidgetGenerationModal } from './NotebookWidgetGenerationModal'
import { NotebookWidgetSourceModal } from './NotebookWidgetSourceModal'
import { NotebookWidgetTrustControls } from './NotebookWidgetTrustControls'
import { getNotebookWidgetTrust, notebookWidgetTrustLogic } from './notebookWidgetTrustLogic'
import { WidgetArtifactFrame } from './WidgetArtifactFrame'
-import { DEFAULT_WIDGET_MODEL, isWidgetModel, type WidgetModel } from './widgetModels'
+import { DEFAULT_WIDGET_MODEL, WIDGET_MODEL_OPTIONS, isWidgetModel, type WidgetModel } from './widgetModels'
export type NotebookNodeGeneratedWidgetAttributes = {
id?: string
@@ -131,7 +132,7 @@ function ExpandedWidget({
setRuntimeError,
} = useActions(logic)
const { trustBuild } = useActions(trustLogic)
- const { setMenuItems } = useActions(nodeLogic)
+ const { setMenuItems, updateAttributes } = useActions(nodeLogic)
const selectedBuildHash =
selectedVersionId === status?.current_version_id
? (status?.build_hash ?? null)
@@ -434,13 +435,16 @@ function ExpandedWidget({
Regenerate…
</LemonButton>
) : (
- <LemonButton
- type="primary"
- onClick={() => generateWidget(initialPrompt, model, 'initial')}
- loading={generationRequestLoading}
- >
- Generate widget
- </LemonButton>
+ <>
+ <NotebookWidgetBetaNotice />
+ <LemonButton
+ type="primary"
+ onClick={() => generateWidget(initialPrompt, model, 'initial')}
+ loading={generationRequestLoading}
+ >
+ Generate widget
+ </LemonButton>
+ </>
)
) : (
<div className="text-sm text-muted">
@@ -502,13 +506,25 @@ function ExpandedWidget({
<div className="flex flex-col items-center gap-3">
<div>This widget has not been generated yet.</div>
{isEditable ? (
- <LemonButton
- type="primary"
- onClick={() => generateWidget(initialPrompt, model, 'initial')}
- loading={generationRequestLoading}
- >
- Generate widget
- </LemonButton>
+ <>
+ <NotebookWidgetBetaNotice />
+ <LemonSelect
+ value={model}
+ options={WIDGET_MODEL_OPTIONS}
+ onChange={(model) => updateAttributes({ model })}
+ disabled={generationRequestLoading}
+ aria-label="Model"
+ data-attr="widget-preview-model-select"
+ className="max-w-full"
+ />
+ <LemonButton
+ type="primary"
+ onClick={() => generateWidget(initialPrompt, model, 'initial')}
+ loading={generationRequestLoading}
+ >
+ Generate widget
+ </LemonButton>
+ </>
) : (
<div className="text-sm text-muted">Ask an editor to generate this widget.</div>
)}
diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx
index 05577c186d7f..e7af4f422acf 100644
--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx
+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx
@@ -25,6 +25,8 @@ import {
notebookNodeGeneratedWidgetLogic,
notebookNodeGeneratedWidgetSettingsLogic,
} from './notebookNodeGeneratedWidgetLogic'
+import { NotebookWidgetBetaNotice } from './NotebookWidgetBetaNotice'
+import { NotebookWidgetGenerationCost } from './NotebookWidgetGenerationCost'
import { NotebookWidgetGenerationModal } from './NotebookWidgetGenerationModal'
import { NotebookWidgetSourceModal } from './NotebookWidgetSourceModal'
import { DEFAULT_WIDGET_MODEL, DEFAULT_WIDGET_PROMPT, WIDGET_MODEL_OPTIONS } from './widgetModels'
@@ -206,7 +208,12 @@ export function NotebookNodeGeneratedWidgetSettings({
) : (
<>
<div>
- <LemonLabel htmlFor={versionId}>Version history</LemonLabel>
+ <div className="flex items-center justify-between gap-2">
+ <LemonLabel htmlFor={versionId}>Version history</LemonLabel>
+ {selectedVersion ? (
+ <NotebookWidgetGenerationCost cost={selectedVersion.generation_cost_usd} />
+ ) : null}
+ </div>
<LemonSelect
id={versionId}
value={selectedVersionId ?? undefined}
@@ -277,6 +284,7 @@ export function NotebookNodeGeneratedWidgetSettings({
</>
)}
+ {!hasVersions && !isWorking ? <NotebookWidgetBetaNotice /> : null}
<div className="flex flex-wrap items-start gap-2">
{isWorking && workingStatus ? (
<>
diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetBetaNotice.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetBetaNotice.tsx
new file mode 100644
index 000000000000..3693a2c90cb0
--- /dev/null
+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetBetaNotice.tsx
@@ -0,0 +1,3 @@
+export function NotebookWidgetBetaNotice(): JSX.Element {
+ return <div className="text-sm text-secondary">Generation uses PostHog AI credits</div>
+}
diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationCost.stories.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationCost.stories.tsx
new file mode 100644
index 000000000000..31f4942d0229
--- /dev/null
+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationCost.stories.tsx
@@ -0,0 +1,22 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { NotebookWidgetGenerationCost } from './NotebookWidgetGenerationCost'
+
+const meta: Meta<typeof NotebookWidgetGenerationCost> = {
+ title: 'Scenes-App/Notebooks/Widget generation cost',
+ component: NotebookWidgetGenerationCost,
+ decorators: [
+ (Story) => (
+ <div className="max-w-lg p-3">
+ <Story />
+ </div>
+ ),
+ ],
+}
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const Recorded: Story = { args: { cost: '0.123456' } }
+export const LessThanOneCent: Story = { args: { cost: '0.004200' } }
+export const Unavailable: Story = { args: { cost: null } }
diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationCost.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationCost.tsx
new file mode 100644
index 000000000000..096bbea618ea
--- /dev/null
+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationCost.tsx
@@ -0,0 +1,34 @@
+import { IconInfo } from '@posthog/icons'
+import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+
+export function NotebookWidgetGenerationCost({ cost }: { cost: string | null | undefined }): JSX.Element | null {
+ if (cost == null) {
+ return null
+ }
+
+ return (
+ <div className="flex shrink-0 items-center gap-0.5 text-xs text-muted" data-attr="widget-generation-cost">
+ <span className="font-mono tabular-nums" translate="no">
+ {Number(cost) > 0 && Number(cost) < 0.01 ? '< $0.01' : `$${Number(cost).toFixed(2)}`}
+ </span>
+ <Tooltip
+ openOnClick
+ title={
+ <>
+ <div className="mb-1 font-semibold">Estimated generation cost</div>
+ Includes this version's generation, security review, retries, and 20% markup. Final PostHog AI
+ credits may differ due to billing rounding.
+ </>
+ }
+ >
+ <LemonButton
+ size="xsmall"
+ icon={<IconInfo />}
+ aria-label="About this generation's cost"
+ data-attr="widget-generation-cost-info"
+ className="text-muted"
+ />
+ </Tooltip>
+ </div>
+ )
+}
diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationModal.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationModal.tsx
index addf2780f950..057b4b7b78bd 100644
--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationModal.tsx
+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationModal.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { LemonBanner, LemonButton, LemonModal, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonModal, LemonSelect, LemonTag, LemonTextArea } from '@posthog/lemon-ui'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
@@ -8,6 +8,7 @@ import {
type NotebookNodeGeneratedWidgetLogicProps,
notebookNodeGeneratedWidgetLogic,
} from './notebookNodeGeneratedWidgetLogic'
+import { NotebookWidgetBetaNotice } from './NotebookWidgetBetaNotice'
import { MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH, MAX_WIDGET_PROMPT_LENGTH, WIDGET_MODEL_OPTIONS } from './widgetModels'
export function NotebookWidgetGenerationModal({
@@ -54,7 +55,14 @@ export function NotebookWidgetGenerationModal({
<LemonModal
isOpen={generationModalOperation !== null}
onClose={closeGenerationModal}
- title={modalTitle}
+ title={
+ <span className="flex flex-wrap items-center gap-2">
+ <span>{modalTitle}</span>
+ <LemonTag type="warning" size="small">
+ BETA
+ </LemonTag>
+ </span>
+ }
description={modalDescription}
width={640}
footer={
@@ -115,6 +123,7 @@ export function NotebookWidgetGenerationModal({
className="mt-1"
/>
</div>
+ <NotebookWidgetBetaNotice />
{generationError ? <LemonBanner type="error">{generationError}</LemonBanner> : null}
</div>
</LemonModal>
diff --git a/products/notebooks/frontend/ReusableWidget/ReusableWidgetScene.tsx b/products/notebooks/frontend/ReusableWidget/ReusableWidgetScene.tsx
index e1f949524ad3..cbb769c5390f 100644
--- a/products/notebooks/frontend/ReusableWidget/ReusableWidgetScene.tsx
+++ b/products/notebooks/frontend/ReusableWidget/ReusableWidgetScene.tsx
@@ -21,6 +21,8 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { reusableWidgetsDemoFrame } from 'products/notebooks/frontend/generated/api'
+import { NotebookWidgetBetaNotice } from '../NotebookNodeGeneratedWidget/NotebookWidgetBetaNotice'
+import { NotebookWidgetGenerationCost } from '../NotebookNodeGeneratedWidget/NotebookWidgetGenerationCost'
import { NotebookWidgetTrustControls } from '../NotebookNodeGeneratedWidget/NotebookWidgetTrustControls'
import { WidgetArtifactFrame } from '../NotebookNodeGeneratedWidget/WidgetArtifactFrame'
import { WIDGET_MODEL_OPTIONS } from '../NotebookNodeGeneratedWidget/widgetModels'
@@ -113,6 +115,11 @@ export function ReusableWidgetScene({ widgetId }: ReusableWidgetLogicProps): JSX
<SceneContent className="@container/reusable-widget flex-1 min-h-0">
<SceneTitleSection
name={reusableWidget.name}
+ nameSuffix={
+ <LemonTag type="warning" size="small">
+ BETA
+ </LemonTag>
+ }
description={reusableWidget.description || 'Reusable notebook widget'}
resourceType={{ type: 'notebook' }}
forceBackTo={{
@@ -288,6 +295,7 @@ export function ReusableWidgetScene({ widgetId }: ReusableWidgetLogicProps): JSX
data-attr="reusable-widget-model"
/>
</div>
+ <NotebookWidgetBetaNotice />
<div className="flex flex-wrap items-center gap-2">
<LemonButton
type="primary"
@@ -366,6 +374,7 @@ export function ReusableWidgetScene({ widgetId }: ReusableWidgetLogicProps): JSX
}}
data-attr="reusable-widget-version"
/>
+ <NotebookWidgetGenerationCost cost={version.generation_cost_usd} />
</div>
{versionHistoryError ? (
<LemonBanner type="warning" action={{ children: 'Retry', onClick: () => loadVersionHistory() }}>
diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.ts
index 4a22fa13e05a..d6d881aa818e 100644
--- a/products/notebooks/frontend/generated/api.schemas.ts
+++ b/products/notebooks/frontend/generated/api.schemas.ts
@@ -177,6 +177,12 @@ export interface WidgetSecurityReviewApi {
}
export interface ReusableWidgetVersionDetailApi {
+ /**
+ * Estimated generation charge in USD, including retries, security review, and the AI credit markup. Null when unavailable.
+ * @nullable
+ * @pattern ^-?\d{0,6}(?:\.\d{0,6})?$
+ */
+ generation_cost_usd?: string | null
/** Immutable widget version identifier. */
id: string
/** Title stored with this version. */
@@ -1267,6 +1273,12 @@ export interface WidgetRevertRequestApi {
}
export interface WidgetVersionApi {
+ /**
+ * Estimated generation charge in USD, including retries, security review, and the AI credit markup. Null when unavailable.
+ * @nullable
+ * @pattern ^-?\d{0,6}(?:\.\d{0,6})?$
+ */
+ generation_cost_usd?: string | null
/** Immutable widget version identifier. */
id: string
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 466ff1a3ee04..4e2b8e79eb09 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -84194,6 +84194,12 @@ export namespace Schemas {
}
export interface ReusableWidgetVersionDetail {
+ /**
+ * Estimated generation charge in USD, including retries, security review, and the AI credit markup. Null when unavailable.
+ * @nullable
+ * @pattern ^-?\d{0,6}(?:\.\d{0,6})?$
+ */
+ generation_cost_usd?: string | null;
/** Immutable widget version identifier. */
id: string;
/** Title stored with this version. */
@@ -98045,6 +98051,12 @@ export namespace Schemas {
}
export interface WidgetVersion {
+ /**
+ * Estimated generation charge in USD, including retries, security review, and the AI credit markup. Null when unavailable.
+ * @nullable
+ * @pattern ^-?\d{0,6}(?:\.\d{0,6})?$
+ */
+ generation_cost_usd?: string | null;
/** Immutable widget version identifier. */
id: string;
/**