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(agent_platform): preview-mode isolation for draft revisions (#64453)

Dylan Martin113386ac6b4c
diff --git a/products/agent_platform/backend/migrations/0009_agentsession_agenttoolapprovalrequest_is_preview.py b/products/agent_platform/backend/migrations/0009_agentsession_agenttoolapprovalrequest_is_preview.py
new file mode 100644
index 000000000000..81f912cd2435
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0009_agentsession_agenttoolapprovalrequest_is_preview.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.14 on 2026-06-17 21:17
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("agent_platform", "0008_agent_identity_subject"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="agentsession",
+ name="is_preview",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ migrations.AddField(
+ model_name="agenttoolapprovalrequest",
+ name="is_preview",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/max_migration.txt b/products/agent_platform/backend/migrations/max_migration.txt
index c5873b89a946..4c9a8017a3d9 100644
--- a/products/agent_platform/backend/migrations/max_migration.txt
+++ b/products/agent_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0008_agent_identity_subject
+0009_agentsession_agenttoolapprovalrequest_is_preview
diff --git a/products/agent_platform/backend/models.py b/products/agent_platform/backend/models.py
index 1de9d814f08f..a4b38f684a10 100644
--- a/products/agent_platform/backend/models.py
+++ b/products/agent_platform/backend/models.py
@@ -177,6 +177,13 @@ class AgentSession(ProductTeamModel, UUIDModel):
pending_elevation_requests = models.JSONField(default=list, db_default=Value("[]"))
claimed_at = models.DateTimeField(null=True, blank=True)
retry_count = models.IntegerField(default=0, db_default=0)
+ # Set to true when the session was created via the preview ingress path
+ # (preview-proxy or direct ingress with a valid `aud=agent-ingress.preview`
+ # JWT). Output adapters (slack reply, webhook publish) noop on preview; the
+ # analytics sink tags `$ai_*` events so author iteration doesn't skew prod
+ # observability dashboards. Cron is implicitly safe (janitor only schedules
+ # off `live_revision_id`), so preview sessions never originate from cron.
+ is_preview = models.BooleanField(default=False, db_default=False)
usage_total = models.JSONField(
default=dict,
db_default=Value(
@@ -274,6 +281,13 @@ class AgentToolApprovalRequest(ProductTeamModel, UUIDModel):
decision_reason = models.TextField(null=True, blank=True)
decided_args = models.JSONField(null=True, blank=True)
dispatch_outcome = models.JSONField(null=True, blank=True)
+ # Mirrors `agent_session.is_preview` for the owning session. Approval rows
+ # are emitted from the runner with the session's value copied at insert
+ # time, so the listing serializer can render a preview badge without an
+ # additional join. Same flag drives the approval-dispatch path: a preview
+ # approval that resolves still routes its outcome through the runner's
+ # preview-aware adapter set, never the live publish surface.
+ is_preview = models.BooleanField(default=False, db_default=False)
created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
expires_at = models.DateTimeField()
diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.py
index 707d3f846e6b..aa4dedcacb3b 100644
--- a/products/agent_platform/backend/presentation/views.py
+++ b/products/agent_platform/backend/presentation/views.py
@@ -189,7 +189,11 @@ class JanitorUpstreamError(APIException):
AGENT_SESSION_LOG_SOURCE = "agent_session"
-def _mint_preview_jwt(application: AgentApplication, revision: AgentRevision, user: Any) -> tuple[str, int] | None:
+def _mint_preview_jwt(
+ application: AgentApplication,
+ revision: AgentRevision,
+ user: Any,
+) -> tuple[str, int] | None:
"""Mint a short-lived HS256 JWT scoped to (app, rev) for non-live invokes.
Returns `(token, ttl_seconds)` or `None` when no shared signing key is
@@ -197,11 +201,13 @@ def _mint_preview_jwt(application: AgentApplication, revision: AgentRevision, us
Bound to (app, rev) so a captured token can't be replayed against a
different draft, and to `aud = agent-ingress.preview` so it can't be
- replayed against any other agent-platform service.
+ replayed against any other agent-platform service. The token only admits
+ the non-live revision through routing; the revision runs against its own
+ `encrypted_env`, so there's no per-session secret payload to carry.
"""
if not settings.AGENT_INTERNAL_SIGNING_KEY:
return None
- ttl_seconds = 60
+ ttl_seconds = 15 * 60
payload: dict[str, Any] = {
"app": str(application.id),
"rev": str(revision.id),
@@ -534,6 +540,17 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# so it lives here even though it targets a non-live revision. The GET
# `listen` counterpart (read-only SSE tail) stays in read actions.
"preview_proxy",
+ # Minting a preview JWT is a write-class capability regardless of verb:
+ # the returned token lets a holder call `run`/`send`/`cancel` against a
+ # draft directly, equivalent to `preview_proxy`. BOTH verbs require
+ # `agents:write` — the POST (`preview_token_mint`) and the GET sibling
+ # (`preview_token`, kept only because EventSource can't set headers)
+ # return the identical usable token, so a read token must not be able to
+ # mint one via either path and hit ingress on its own. (The
+ # `preview_proxy*` actions differ: they use the JWT server-side and
+ # never hand it back, so the GET `preview_proxy_get` stays read-scoped.)
+ "preview_token_mint",
+ "preview_token",
]
scope_object_read_actions = [
"list",
@@ -546,8 +563,10 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# GET (SSE `listen`) → `preview_proxy_get`. DRF uses the bound function
# name as `view.action`, so the GET variant is its own scope-map entry;
# the mutating POST sibling (`preview_proxy`) is a write action above.
+ # The proxy uses the preview JWT server-side and never returns it, so
+ # this read-scoped GET can't leak a usable credential (unlike
+ # `preview_token`, which is write-scoped above).
"preview_proxy_get",
- "preview_token",
"approvals_list",
"approvals_retrieve",
]
@@ -768,59 +787,55 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# server-side mediation. Both share `_mint_preview_jwt` so the
# JWT payload + secret can't drift between paths.
- @extend_schema(
- operation_id="agent_applications_preview_token",
- parameters=[
- OpenApiParameter(
- "revision_id",
- OpenApiTypes.UUID,
- OpenApiParameter.QUERY,
- required=True,
- description="Target draft revision. Must belong to this application and not be live.",
- ),
- ],
- request=None,
- responses=OpenApiResponse(
- response=inline_serializer(
- name="AgentApplicationPreviewTokenResponse",
- fields={
- "token": drf_serializers.CharField(
- help_text="HS256 JWT bound to (app, rev) with a short TTL. Attach as the `x-agent-preview-token` header (POST/DELETE) or `preview_token` query param (GET, including EventSource) when calling ingress directly.",
- ),
- "expires_in": drf_serializers.IntegerField(
- help_text="Token TTL in seconds from issue. Clients should refresh before this elapses.",
- ),
- "ingress_slug": drf_serializers.CharField(
- help_text="Slug to use in the ingress URL — `<application_slug>-<revision_uuid_hex>`. Identifies the exact revision, placed in the host (domain mode) or path (path mode) routing prefix.",
- ),
- "endpoints": drf_serializers.JSONField(
- help_text="Per-trigger ingress URLs the caller can hit directly, derived from the revision's `spec.triggers[]`. Shape: `{<trigger_type>: {<route_name>: <absolute_url>}}`. Only includes triggers the spec actually declares. Empty when no public agent-ingress URL is configured for the active routing mode.",
- ),
- "auth": drf_serializers.JSONField(
- help_text="How to attach credentials to those endpoints: preview-token header/query names, the per-trigger accepted auth modes (`trigger_modes`), and a note about the live vs preview-mode gate split. Lets the caller wire auth without grepping the ingress source.",
- ),
- "preview_proxy": drf_serializers.JSONField(
- help_text="Server-side alternative — `/api/projects/<team>/agent_applications/<slug>/preview-proxy/<path>` mints the JWT for you. Strips caller Authorization, so it works for public-auth agents; agents with required auth need the direct endpoints above.",
- ),
- },
- )
+ # Reused by GET + POST so drf-spectacular emits one component and the two
+ # operations stay shape-locked. POST is the contract-faithful verb (minting
+ # is a write); GET stays for `EventSource` callers and back-compat.
+ _PREVIEW_TOKEN_RESPONSE = OpenApiResponse(
+ response=inline_serializer(
+ name="AgentApplicationPreviewTokenResponse",
+ fields={
+ "token": drf_serializers.CharField(
+ help_text="HS256 JWT bound to (app, rev) with a short TTL. Attach as the `x-agent-preview-token` header (POST/DELETE) or `preview_token` query param (GET, including EventSource) when calling ingress directly.",
+ ),
+ "expires_in": drf_serializers.IntegerField(
+ help_text="Token TTL in seconds from issue. Clients should refresh before this elapses.",
+ ),
+ "ingress_slug": drf_serializers.CharField(
+ help_text="Slug to use in the ingress URL — `<application_slug>-<revision_uuid_hex>`. Identifies the exact revision, placed in the host (domain mode) or path (path mode) routing prefix.",
+ ),
+ "endpoints": drf_serializers.JSONField(
+ help_text="Per-trigger ingress URLs the caller can hit directly, derived from the revision's `spec.triggers[]`. Shape: `{<trigger_type>: {<route_name>: <absolute_url>}}`. Only includes triggers the spec actually declares. Empty when no public agent-ingress URL is configured for the active routing mode.",
+ ),
+ "auth": drf_serializers.JSONField(
+ help_text="How to attach credentials to those endpoints: preview-token header/query names, the per-trigger accepted auth modes (`trigger_modes`), and a note about the live vs preview-mode gate split. Lets the caller wire auth without grepping the ingress source.",
+ ),
+ "preview_proxy": drf_serializers.JSONField(
+ help_text="Server-side alternative — `/api/projects/<team>/agent_applications/<slug>/preview-proxy/<path>` mints the JWT for you. Strips caller Authorization, so it works for public-auth agents; agents with required auth need the direct endpoints above.",
+ ),
+ },
),
)
- @action(detail=True, methods=["get"], url_path="preview-token")
- def preview_token(self, request: Request, **kwargs) -> Response:
- """Mint a short-lived JWT for talking to a non-live revision
- directly via the public ingress URL. The caller attaches it as
- the `x-agent-preview-token` header (or `?preview_token=` query
- param for `EventSource`). See `_mint_preview_jwt` for the
- payload + claim binding.
- The response also includes `endpoints`, `auth`, and
- `preview_proxy` blocks so the caller can wire a preview
- invocation without grepping the agent-ingress source for which
- path each trigger exposes or which header name carries the
- token. This is the "self-describing" half of preview-mode —
- every piece of info you need to hit ingress is in one response.
- """
+ _PREVIEW_TOKEN_PARAMETERS = [
+ OpenApiParameter(
+ "revision_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.QUERY,
+ required=True,
+ description="Target draft revision. Must belong to this application and not be live.",
+ ),
+ ]
+
+ # The two verbs live on separate action methods so DRF resolves them to
+ # distinct `view.action` names — `preview_token` (GET) and
+ # `preview_token_mint` (POST). Both are write-scoped (see the scope lists):
+ # the returned JWT is a usable credential for `run`/`send`/`cancel`, so
+ # minting it requires `agents:write` no matter the verb. The GET sibling
+ # exists only because EventSource can't set headers — it is NOT a
+ # read-only-safe alternative. A shared body keeps the response shape
+ # lock-stepped across both.
+
+ def _build_preview_token_response(self, request: Request) -> Response:
application = self.get_object()
if application is None:
raise NotFound("Application not found")
@@ -834,9 +849,9 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
raise ValidationError(
"preview-token is for non-live revisions only; the live revision is reachable without a token via its public ingress URL"
)
+ spec = revision.spec if isinstance(revision.spec, dict) else {}
token_pair = _mint_preview_jwt(application, revision, request.user)
ingress_slug = f"{application.slug}-{revision.id.hex}"
- spec = revision.spec if isinstance(revision.spec, dict) else {}
body: dict[str, Any] = {
"token": token_pair[0] if token_pair is not None else "",
"expires_in": token_pair[1] if token_pair is not None else 0,
@@ -847,6 +862,53 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
}
return Response(body)
+ @extend_schema(
+ operation_id="agent_applications_preview_token_mint",
+ parameters=_PREVIEW_TOKEN_PARAMETERS,
+ request=None,
+ responses=_PREVIEW_TOKEN_RESPONSE,
+ )
+ @action(detail=True, methods=["post"], url_path="preview-token")
+ def preview_token_mint(self, request: Request, **kwargs) -> Response:
+ """Mint a short-lived JWT for talking to a non-live revision
+ directly via the public ingress URL. The caller attaches it as
+ the `x-agent-preview-token` header (or `?preview_token=` query
+ param for `EventSource`). See `_mint_preview_jwt` for the
+ payload + claim binding.
+
+ The response also includes `endpoints`, `auth`, and
+ `preview_proxy` blocks so the caller can wire a preview
+ invocation without grepping the agent-ingress source for which
+ path each trigger exposes or which header name carries the
+ token. This is the "self-describing" half of preview-mode —
+ every piece of info you need to hit ingress is in one response.
+
+ POST is the canonical verb — minting credentials for downstream
+ `run`/`send`/`cancel` is a write-class capability. A GET sibling
+ exists at the same URL for `EventSource` callers (which can't set
+ headers); it is also write-scoped, since it returns the same token.
+ """
+ return self._build_preview_token_response(request)
+
+ @extend_schema(
+ operation_id="agent_applications_preview_token",
+ parameters=_PREVIEW_TOKEN_PARAMETERS,
+ request=None,
+ responses=_PREVIEW_TOKEN_RESPONSE,
+ )
+ @preview_token_mint.mapping.get
+ def preview_token(self, request: Request, **kwargs) -> Response:
+ """GET sibling of `preview_token_mint`. Same body and response
+ shape — exists because `EventSource` can't set headers, so SSE
+ callers fetch the token via GET and then attach `?preview_token=`
+ to the ingress URL. Behind the same URL (`url_path="preview-token"`)
+ thanks to DRF's `@<action>.mapping.get`; DRF resolves it to a
+ distinct `view.action`, but it is in `scope_object_write_actions`
+ alongside the POST sibling — both return a usable credential, so
+ both require `agents:write`.
+ """
+ return self._build_preview_token_response(request)
+
@extend_schema(
operation_id="agent_applications_stats",
parameters=[
@@ -949,6 +1011,14 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
),
"usage_total": _AGENT_SESSION_USAGE_TOTAL,
"retry_count": drf_serializers.IntegerField(),
+ "is_preview": drf_serializers.BooleanField(
+ help_text=(
+ "True when the session ran against a draft revision in preview mode. "
+ "Output adapters (Slack writes, failure notifier) no-op; `$ai_*` analytics "
+ "events are tagged with `$agent_is_preview: true`. Surface a preview badge "
+ "on the row so authors can distinguish iteration from live traffic."
+ ),
+ ),
"created_at": drf_serializers.DateTimeField(),
"updated_at": drf_serializers.DateTimeField(),
},
@@ -1158,6 +1228,14 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
help_text="Times the janitor has re-queued this session after a stuck-running detection.",
),
"usage_total": _AGENT_SESSION_USAGE_TOTAL,
+ "is_preview": drf_serializers.BooleanField(
+ help_text=(
+ "True when the session ran against a draft revision in preview mode. "
+ "Output adapters (Slack writes, failure notifier) no-op; `$ai_*` analytics "
+ "events are tagged with `$agent_is_preview: true`. Surface a preview badge "
+ "on session detail so authors can distinguish iteration from live traffic."
+ ),
+ ),
"created_at": drf_serializers.DateTimeField(),
"updated_at": drf_serializers.DateTimeField(),
"conversation_trimmed": drf_serializers.BooleanField(
@@ -1270,6 +1348,13 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"application_id": drf_serializers.UUIDField(help_text="UUID of the parent agent application."),
"team_id": drf_serializers.IntegerField(help_text="Team that owns the agent."),
"revision_id": drf_serializers.UUIDField(help_text="Revision the gated call was proposed against."),
+ "is_preview": drf_serializers.BooleanField(
+ help_text=(
+ "Mirrors the owning session's `is_preview`. True when the request originated from a "
+ "draft revision running in preview mode — render a preview badge in the approvals "
+ "queue so reviewers can tell author-iteration approvals apart from production traffic."
+ ),
+ ),
"turn": drf_serializers.IntegerField(help_text="Turn number within the session that emitted the call."),
"tool_call_id": drf_serializers.CharField(
help_text="pi-ai ToolCall.id from the original assistant message; matched into the synthetic tool_result."
@@ -2881,6 +2966,14 @@ class AgentFleetViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
help_text="Last assistant text (~120 chars). Null when no assistant turns yet.",
),
"usage_total": _AGENT_SESSION_USAGE_TOTAL,
+ "is_preview": drf_serializers.BooleanField(
+ help_text=(
+ "True when the session ran against a draft revision in preview mode. "
+ "Output adapters (Slack writes, failure notifier) no-op; `$ai_*` analytics "
+ "events are tagged with `$agent_is_preview: true`. Render a preview badge "
+ "on the row so author iteration is distinguishable from live traffic."
+ ),
+ ),
"created_at": drf_serializers.DateTimeField(),
"updated_at": drf_serializers.DateTimeField(),
},
diff --git a/products/agent_platform/backend/tests/test_preview_proxy.py b/products/agent_platform/backend/tests/test_preview_proxy.py
index 15c6e92b66d2..e39aa950d79c 100644
--- a/products/agent_platform/backend/tests/test_preview_proxy.py
+++ b/products/agent_platform/backend/tests/test_preview_proxy.py
@@ -21,14 +21,31 @@ playground flow:
from __future__ import annotations
+from typing import Any
+
from posthog.test.base import APIBaseTest
from parameterized import parameterized
+from ..models import AgentApplication, AgentRevision
from ..presentation.serializers import PreviewProxyInvokeRequestSerializer
from ..presentation.views import AgentApplicationViewSet, EventStreamRenderer
+def _base_spec() -> dict[str, Any]:
+ return {
+ "model": "anthropic/claude-sonnet-4-6",
+ "triggers": [{"type": "chat", "config": {}, "auth": {"modes": [{"type": "posthog", "scopes": []}]}}],
+ "tools": [],
+ "mcps": [],
+ "skills": [],
+ "integrations": [],
+ "secrets": [],
+ "limits": {"max_turns": 10, "max_tool_calls": 20, "max_wall_seconds": 60},
+ "entrypoint": "agent.md",
+ }
+
+
class TestPreviewProxyScope(APIBaseTest):
databases = {
"default",
@@ -99,3 +116,39 @@ class TestPreviewProxyInvokeBody(APIBaseTest):
self.assertTrue(
PreviewProxyInvokeRequestSerializer(data={"session_id": "s-1", "message": "another"}).is_valid()
)
+
+
+class TestPreviewProxyCrossAppRejection(APIBaseTest):
+ """Tenant boundary: minting via preview-proxy must not let a revision_id
+ from one app smuggle through under a sibling app's slug. Same contract as
+ `preview-token`, enforced via the same `application=application` filter."""
+
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def _app(self, slug: str) -> AgentApplication:
+ return AgentApplication.all_teams.create(team_id=self.team.id, slug=slug, name=slug, description="")
+
+ def _revision(self, app: AgentApplication) -> AgentRevision:
+ return AgentRevision.all_teams.create(
+ application=app, state="draft", bundle_uri=f"local://{app.slug}/v1", spec=_base_spec()
+ )
+
+ def test_revision_from_different_app_in_same_team_rejected(self) -> None:
+ app_a = self._app("preview-proxy-bot-a")
+ app_b = self._app("preview-proxy-bot-b")
+ rev_b = self._revision(app_b)
+ # Hit POST /run (the canonical mutating invoke). The view rejects
+ # before any upstream call, so no ingress is required.
+ res = self.client.post(
+ f"/api/projects/{self.team.id}/agent_applications/{app_a.slug}/preview-proxy/run/?revision_id={rev_b.id}",
+ data={"message": "hi"},
+ format="json",
+ )
+ assert res.status_code == 404, res.content
+ assert "Revision not found in this application" in res.content.decode()
diff --git a/products/agent_platform/backend/tests/test_preview_token.py b/products/agent_platform/backend/tests/test_preview_token.py
index fba84faaba91..4eff5e93d733 100644
--- a/products/agent_platform/backend/tests/test_preview_token.py
+++ b/products/agent_platform/backend/tests/test_preview_token.py
@@ -29,7 +29,11 @@ from posthog.test.base import APIBaseTest
from django.test import override_settings
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.utils import generate_random_token_personal
+
from ..models import AgentApplication, AgentRevision
+from ..presentation.views import AgentApplicationViewSet
def _base_spec(triggers: list[dict[str, Any]] | None = None, modes: list[str] | None = None) -> dict[str, Any]:
@@ -190,6 +194,21 @@ class TestPreviewTokenResponse(APIBaseTest):
assert res.status_code == 400, res.content
assert "revision_id" in res.content.decode()
+ def test_revision_from_different_app_in_same_team_rejected(self) -> None:
+ # A revision UUID that belongs to a SIBLING app in the same team must
+ # not mint a token under THIS app's slug — otherwise the slug-rev URL
+ # would route the caller to one app's resources via another app's
+ # access boundary. Filter is `application=application` in the view;
+ # this pins the contract end-to-end.
+ app_a = self._app("preview-bot-a")
+ app_b = self._app("preview-bot-b")
+ rev_b = self._revision(app_b, _base_spec())
+ res = self.client.get(
+ f"/api/projects/{self.team.id}/agent_applications/{app_a.slug}/preview-token/?revision_id={rev_b.id}"
+ )
+ assert res.status_code == 404, res.content
+ assert "Revision not found in this application" in res.content.decode()
+
@override_settings(
AGENT_INGRESS_ROUTING_MODE="domain",
@@ -291,3 +310,154 @@ class TestSlackUrlSerializer(APIBaseTest):
body = self._retrieve(self._app())
assert body["slack_events_url"] is None
assert body["slack_interactivity_url"] is None
+
+
+@override_settings(
+ AGENT_INGRESS_PUBLIC_URL="https://ingress.example.com",
+ AGENT_INTERNAL_SIGNING_KEY="dev-internal-signing-key-do-not-use-in-prod",
+)
+class TestPreviewTokenMintPost(APIBaseTest):
+ """POST mint verb (the contract-faithful one — minting is a write). It takes
+ no body: secrets are per-revision now, so there's no per-session override to
+ pass. The token only admits the non-live revision through routing."""
+
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def _app(self, slug: str = "preview-mint-bot") -> AgentApplication:
+ return AgentApplication.all_teams.create(team_id=self.team.id, slug=slug, name="X", description="")
+
+ def _revision(self, app: AgentApplication) -> AgentRevision:
+ return AgentRevision.all_teams.create(
+ application=app, state="draft", bundle_uri=f"local://{app.slug}/v1", spec=_base_spec()
+ )
+
+ def _url(self, app: AgentApplication, rev: AgentRevision) -> str:
+ return f"/api/projects/{self.team.id}/agent_applications/{app.slug}/preview-token/?revision_id={rev.id}"
+
+ def test_post_mints_token(self) -> None:
+ app = self._app()
+ rev = self._revision(app)
+ res = self.client.post(self._url(app, rev))
+ assert res.status_code == 200, res.content
+ body = res.json()
+ assert body["token"], "POST mint must return a non-empty token"
+ assert body["expires_in"] > 0
+ assert body["ingress_slug"] == f"{app.slug}-{rev.id.hex}"
+
+ def test_post_on_live_revision_rejected(self) -> None:
+ app = self._app()
+ rev = self._revision(app)
+ app.live_revision = rev
+ app.save(update_fields=["live_revision"])
+ res = self.client.post(self._url(app, rev))
+ assert res.status_code == 400, res.content
+ assert "non-live revisions only" in res.content.decode()
+
+ def test_post_revision_from_different_app_in_same_team_rejected(self) -> None:
+ # Same contract as the GET path: minting under one app's slug with a
+ # revision id from a sibling app must 404, not silently mint a token
+ # that crosses the app boundary.
+ app_a = self._app("preview-mint-bot-a")
+ app_b = self._app("preview-mint-bot-b")
+ rev_b = self._revision(app_b)
+ res = self.client.post(
+ f"/api/projects/{self.team.id}/agent_applications/{app_a.slug}/preview-token/?revision_id={rev_b.id}"
+ )
+ assert res.status_code == 404, res.content
+ assert "Revision not found in this application" in res.content.decode()
+
+
+@override_settings(
+ AGENT_INGRESS_PUBLIC_URL="https://ingress.example.com",
+ AGENT_INTERNAL_SIGNING_KEY="dev-internal-signing-key-do-not-use-in-prod",
+)
+class TestPreviewTokenScopeMapping(APIBaseTest):
+ """The preview-token endpoint serves both GET (back-compat, read-scoped) and
+ POST (canonical mint, write-scoped) at one URL. DRF resolves them to
+ distinct `view.action` names via `@preview_token_mint.mapping.get`, and the
+ scope-map split is what blocks an `agents:read` token from minting a JWT
+ and calling ingress `run`/`send`/`cancel` directly. These tests pin both
+ halves of that split."""
+
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def _app(self, slug: str = "preview-scope-bot") -> AgentApplication:
+ return AgentApplication.all_teams.create(team_id=self.team.id, slug=slug, name="X", description="")
+
+ def _revision(self, app: AgentApplication) -> AgentRevision:
+ return AgentRevision.all_teams.create(
+ application=app, state="draft", bundle_uri=f"local://{app.slug}/v1", spec=_base_spec()
+ )
+
+ def _url(self, app: AgentApplication, rev: AgentRevision) -> str:
+ return f"/api/projects/{self.team.id}/agent_applications/{app.slug}/preview-token/?revision_id={rev.id}"
+
+ def _pat(self, *, scopes: list[str]) -> str:
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="preview-scope", user=self.user, secure_value=hash_key_value(raw), scopes=scopes
+ )
+ return raw
+
+ # ── declared scope membership ───────────────────────────────────────
+
+ def test_post_mint_is_a_declared_write_action(self) -> None:
+ # `agents:read` PATs are rejected before reaching the action body when
+ # the action name isn't in this list; pin it so the next refactor
+ # can't accidentally re-merge POST back into the read-scoped GET
+ # action and reopen the scope hole.
+ assert "preview_token_mint" in AgentApplicationViewSet.scope_object_write_actions
+ assert "preview_token_mint" not in AgentApplicationViewSet.scope_object_read_actions
+
+ def test_get_preview_token_is_a_declared_write_action(self) -> None:
+ # The `EventSource`-friendly GET sibling returns the SAME usable token
+ # as the POST, so it must be write-scoped too — a read PAT minting a
+ # JWT via GET would reopen the scope hole. Pin it so a refactor can't
+ # silently move it back to read scope.
+ assert "preview_token" in AgentApplicationViewSet.scope_object_write_actions
+ assert "preview_token" not in AgentApplicationViewSet.scope_object_read_actions
+
+ # ── runtime gate (PAT) ──────────────────────────────────────────────
+
+ def test_read_scope_pat_can_neither_get_nor_post_mint(self) -> None:
+ # The safety property: an `agents:read` PAT must NOT be able to mint a
+ # preview JWT by EITHER verb (the token, attached as
+ # `x-agent-preview-token`, would let it hit ingress
+ # `run`/`send`/`cancel` directly). Both GET and POST require write.
+ app = self._app()
+ rev = self._revision(app)
+ raw = self._pat(scopes=["agents:read"])
+ # Drop the session auth APIBaseTest set up so the PAT is the sole
+ # credential the request carries; otherwise the session cookie
+ # promotes the request back to fully-scoped user auth.
+ self.client.logout()
+ post_res = self.client.post(self._url(app, rev), HTTP_AUTHORIZATION=f"Bearer {raw}")
+ assert post_res.status_code == 403, post_res.content
+ get_res = self.client.get(self._url(app, rev), HTTP_AUTHORIZATION=f"Bearer {raw}")
+ assert get_res.status_code == 403, get_res.content
+
+ def test_write_scope_pat_can_mint_via_both_verbs(self) -> None:
+ # The positive case: `agents:write` is required for minting, and it
+ # must succeed via both the canonical POST and the EventSource GET.
+ app = self._app("preview-scope-bot-write")
+ rev = self._revision(app)
+ raw = self._pat(scopes=["agents:write"])
+ self.client.logout()
+ post_res = self.client.post(self._url(app, rev), HTTP_AUTHORIZATION=f"Bearer {raw}")
+ assert post_res.status_code == 200, post_res.content
+ assert post_res.json()["token"]
+ get_res = self.client.get(self._url(app, rev), HTTP_AUTHORIZATION=f"Bearer {raw}")
+ assert get_res.status_code == 200, get_res.content
+ assert get_res.json()["token"]
diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.ts
index 56ab8744d5dd..bf30fb5da99c 100644
--- a/products/agent_platform/frontend/generated/api.schemas.ts
+++ b/products/agent_platform/frontend/generated/api.schemas.ts
@@ -1269,6 +1269,8 @@ export interface AgentApprovalRequestApi {
team_id: number
/** Revision the gated call was proposed against. */
revision_id: string
+ /** Mirrors the owning session's `is_preview`. True when the request originated from a draft revision running in preview mode — render a preview badge in the approvals queue so reviewers can tell author-iteration approvals apart from production traffic. */
+ is_preview: boolean
/** Turn number within the session that emitted the call. */
turn: number
/** pi-ai ToolCall.id from the original assistant message; matched into the synthetic tool_result. */
@@ -1489,6 +1491,8 @@ export interface AgentSessionSummaryApi {
*/
preview: string | null
retry_count: number
+ /** True when the session ran against a draft revision in preview mode. Output adapters (Slack writes, failure notifier) no-op; `$ai_*` analytics events are tagged with `$agent_is_preview: true`. Surface a preview badge on the row so authors can distinguish iteration from live traffic. */
+ is_preview: boolean
created_at: string
updated_at: string
}
@@ -1604,6 +1608,8 @@ export interface AgentApplicationSessionsRetrieveResponseApi {
pending_inputs: AgentConversationMessageApi[]
/** Times the janitor has re-queued this session after a stuck-running detection. */
retry_count: number
+ /** True when the session ran against a draft revision in preview mode. Output adapters (Slack writes, failure notifier) no-op; `$ai_*` analytics events are tagged with `$agent_is_preview: true`. Surface a preview badge on session detail so authors can distinguish iteration from live traffic. */
+ is_preview: boolean
created_at: string
updated_at: string
/** True when `?last_n=` was supplied AND the full conversation exceeded it. */
@@ -1701,6 +1707,8 @@ export interface AgentFleetLiveSessionSummaryApi {
* @nullable
*/
preview: string | null
+ /** True when the session ran against a draft revision in preview mode. Output adapters (Slack writes, failure notifier) no-op; `$ai_*` analytics events are tagged with `$agent_is_preview: true`. Render a preview badge on the row so author iteration is distinguishable from live traffic. */
+ is_preview: boolean
created_at: string
updated_at: string
}
@@ -1870,6 +1878,13 @@ export type AgentApplicationsPreviewTokenParams = {
revision_id: string
}
+export type AgentApplicationsPreviewTokenMintParams = {
+ /**
+ * Target draft revision. Must belong to this application and not be live.
+ */
+ revision_id: string
+}
+
export type AgentApplicationsSessionsListParams = {
/**
* ISO datetime — return sessions with created_at >= this.
diff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.ts
index d9f915b0cd45..4cb633517859 100644
--- a/products/agent_platform/frontend/generated/api.ts
+++ b/products/agent_platform/frontend/generated/api.ts
@@ -20,6 +20,7 @@ import type {
AgentApplicationsListParams,
AgentApplicationsPreviewProxyGetParams,
AgentApplicationsPreviewProxyParams,
+ AgentApplicationsPreviewTokenMintParams,
AgentApplicationsPreviewTokenParams,
AgentApplicationsRevisionsListParams,
AgentApplicationsSessionLogsParams,
@@ -1762,6 +1763,51 @@ export const getAgentApplicationsPreviewTokenUrl = (
: `/api/projects/${projectId}/agent_applications/${id}/preview-token/`
}
+/**
+ * GET sibling of `preview_token_mint`. Same body and response
+ * shape — exists because `EventSource` can't set headers, so SSE
+ * callers fetch the token via GET and then attach `?preview_token=`
+ * to the ingress URL. Behind the same URL (`url_path="preview-token"`)
+ * thanks to DRF's `@<action>.mapping.get`; DRF resolves it to a
+ * distinct `view.action`, but it is in `scope_object_write_actions`
+ * alongside the POST sibling — both return a usable credential, so
+ * both require `agents:write`.
+ */
+export const agentApplicationsPreviewToken = async (
+ projectId: string,
+ id: string,
+ params: AgentApplicationsPreviewTokenParams,
+ options?: RequestInit
+): Promise<AgentApplicationPreviewTokenResponseApi> => {
+ return apiMutator<AgentApplicationPreviewTokenResponseApi>(
+ getAgentApplicationsPreviewTokenUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAgentApplicationsPreviewTokenMintUrl = (
+ projectId: string,
+ id: string,
+ params: AgentApplicationsPreviewTokenMintParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/preview-token/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/preview-token/`
+}
+
/**
* Mint a short-lived JWT for talking to a non-live revision
* directly via the public ingress URL. The caller attaches it as
@@ -1775,18 +1821,23 @@ export const getAgentApplicationsPreviewTokenUrl = (
* path each trigger exposes or which header name carries the
* token. This is the "self-describing" half of preview-mode —
* every piece of info you need to hit ingress is in one response.
+ *
+ * POST is the canonical verb — minting credentials for downstream
+ * `run`/`send`/`cancel` is a write-class capability. A GET sibling
+ * exists at the same URL for `EventSource` callers (which can't set
+ * headers); it is also write-scoped, since it returns the same token.
*/
-export const agentApplicationsPreviewToken = async (
+export const agentApplicationsPreviewTokenMint = async (
projectId: string,
id: string,
- params: AgentApplicationsPreviewTokenParams,
+ params: AgentApplicationsPreviewTokenMintParams,
options?: RequestInit
): Promise<AgentApplicationPreviewTokenResponseApi> => {
return apiMutator<AgentApplicationPreviewTokenResponseApi>(
- getAgentApplicationsPreviewTokenUrl(projectId, id, params),
+ getAgentApplicationsPreviewTokenMintUrl(projectId, id, params),
{
...options,
- method: 'GET',
+ method: 'POST',
}
)
}
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/acl.test.ts b/products/agent_platform/services/agent-ingress/src/enqueue/acl.test.ts
index 677ef9b54cb3..6c129268aeac 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/acl.test.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/acl.test.ts
@@ -54,6 +54,7 @@ function makeSession(opts: { state?: AgentSession['state']; pending?: PendingEle
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: opts.pending ?? [],
+ is_preview: false,
created_at: '2026-05-27',
updated_at: '2026-05-27',
}
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts
index d3bc1c4c9a36..9e7bc74b7bb4 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts
@@ -213,6 +213,85 @@ describe('enqueueOrResume', () => {
}
})
+ it('isolates preview from live: a preview request does not resume a live session on the same external_key', async () => {
+ // Preview/live isolation contract. The runner reads suppression off
+ // the session row (`is_preview`), so a preview-authed request that
+ // resumed a live row would drive live secrets and un-suppressed
+ // external writes under preview auth. `findByExternalKey` is scoped to
+ // the request's preview/live boundary; a cross-scope match falls
+ // through to creating a new session.
+ const queue = new PgSessionQueue(pool)
+ const { app, rev } = makePair()
+ const draftRev: AgentRevision = { ...rev, id: randomUUID(), state: 'draft' }
+ const live = await enqueueOrResume(
+ { queue },
+ {
+ application: app,
+ revision: rev,
+ externalKey: 'slack:C01:thread-iso',
+ seed: { role: 'user', content: 'live opens thread', timestamp: Date.now() },
+ principal: ALICE,
+ trigger: 'slack',
+ isPreview: false,
+ }
+ )
+ const preview = await enqueueOrResume(
+ { queue },
+ {
+ application: app,
+ revision: draftRev,
+ externalKey: 'slack:C01:thread-iso',
+ seed: { role: 'user', content: 'preview author tests draft', timestamp: Date.now() },
+ principal: ALICE,
+ trigger: 'slack',
+ isPreview: true,
+ }
+ )
+ expect(preview.kind).toBe('created')
+ expect(preview.sessionId).not.toBe(live.sessionId)
+ // The new preview session is its own row with `is_preview = true` and
+ // the draft revision — the live session is untouched.
+ const previewSession = await queue.get(preview.sessionId)
+ expect(previewSession!.is_preview).toBe(true)
+ expect(previewSession!.revision_id).toBe(draftRev.id)
+ const liveSession = await queue.get(live.sessionId)
+ expect(liveSession!.is_preview).toBe(false)
+ expect(liveSession!.pending_inputs).toHaveLength(0)
+ // A second live request on the same key still resumes the live row —
+ // the new preview row doesn't poach it.
+ const liveAgain = await enqueueOrResume(
+ { queue },
+ {
+ application: app,
+ revision: rev,
+ externalKey: 'slack:C01:thread-iso',
+ seed: { role: 'user', content: 'live follow-up', timestamp: Date.now() },
+ principal: ALICE,
+ trigger: 'slack',
+ isPreview: false,
+ }
+ )
+ expect(liveAgain.kind).toBe('resumed')
+ expect(liveAgain.sessionId).toBe(live.sessionId)
+ // Two different draft revisions previewing the same external_key get
+ // distinct sessions — their conversation histories don't bleed.
+ const secondDraftRev: AgentRevision = { ...rev, id: randomUUID(), state: 'draft' }
+ const otherPreview = await enqueueOrResume(
+ { queue },
+ {
+ application: app,
+ revision: secondDraftRev,
+ externalKey: 'slack:C01:thread-iso',
+ seed: { role: 'user', content: 'other draft', timestamp: Date.now() },
+ principal: ALICE,
+ trigger: 'slack',
+ isPreview: true,
+ }
+ )
+ expect(otherPreview.kind).toBe('created')
+ expect(otherPreview.sessionId).not.toBe(preview.sessionId)
+ })
+
it('expires the oldest pending elevation request once the cap is exceeded', async () => {
const queue = new PgSessionQueue(pool)
const { app, rev } = makePair()
@@ -242,7 +321,9 @@ describe('enqueueOrResume', () => {
}
)
}
- const session = await queue.get((await queue.findByExternalKey(app.id, 'slack:C01:thread5'))!.id)
+ const session = await queue.get(
+ (await queue.findByExternalKey(app.id, 'slack:C01:thread5', { isPreview: false, revisionId: rev.id }))!.id
+ )
const pendings = session!.pending_elevation_requests.filter((r) => r.state === 'pending')
expect(pendings).toHaveLength(5)
const expired = session!.pending_elevation_requests.filter((r) => r.state === 'expired')
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
index d5521bf10035..9b48c3d9c196 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
@@ -87,6 +87,16 @@ export interface EnqueueInput {
* for audit. Defaults to false (owner-only, the fail-closed behaviour).
*/
bypassOwnerAcl?: boolean
+ /**
+ * True when the request that produced this enqueue carried a valid
+ * `aud=agent-ingress.preview` JWT (or arrived via the Django-side
+ * preview-proxy, which mints one server-side). Stamps the same value onto
+ * `agent_session.is_preview`. Triggers decide this based on the verified
+ * audience of the inbound token — never on a client-asserted query param.
+ * Defaults to false so the live-ingress path stays the no-extra-thought
+ * default.
+ */
+ isPreview?: boolean
}
export type EnqueueOutcome =
@@ -129,7 +139,17 @@ async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Pro
}
}
if (input.externalKey) {
- const existing = await deps.queue.findByExternalKey(input.application.id, input.externalKey)
+ // Scope the lookup to the request's preview/live boundary so a
+ // preview-authenticated request can't resume a live session (or vice
+ // versa). Without this, the runner would read `is_preview = false` off
+ // the live row even though the resuming request was preview-authed,
+ // and live secrets + un-suppressed external writes would fire under
+ // preview auth. Different draft revisions are also isolated — same
+ // external_key + two drafts gets two distinct sessions.
+ const existing = await deps.queue.findByExternalKey(input.application.id, input.externalKey, {
+ isPreview: input.isPreview === true,
+ revisionId: input.revision.id,
+ })
if (existing && existing.state !== 'closed' && existing.state !== 'failed') {
const incoming = input.principal ?? null
const check = input.bypassOwnerAcl ? ({ kind: 'allowed' } as const) : requireAclAccess(existing, incoming)
@@ -176,6 +196,7 @@ async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Pro
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: input.isPreview === true,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
}
diff --git a/products/agent_platform/services/agent-ingress/src/routing/resolver.ts b/products/agent_platform/services/agent-ingress/src/routing/resolver.ts
index cae5d67a3497..10d08f37ee58 100644
--- a/products/agent_platform/services/agent-ingress/src/routing/resolver.ts
+++ b/products/agent_platform/services/agent-ingress/src/routing/resolver.ts
@@ -33,6 +33,29 @@ export type RoutingMode = 'domain' | 'path'
export interface ResolvedAgent {
application: AgentApplication
revision: AgentRevision
+ /**
+ * True when the resolved revision is NOT the application's
+ * `live_revision_id` — i.e. the request reached us through the preview
+ * path (Django preview-proxy or a direct ingress call carrying a valid
+ * `aud=agent-ingress.preview` JWT). `assertPreviewGate` has already run
+ * by the time this is set on a non-live resolution, so the field
+ * doubles as "request was authenticated for preview." Triggers forward
+ * it to `enqueueOrResume` as `isPreview` so it lands on
+ * `agent_session.is_preview` and the runner's output adapters can
+ * noop external publishes for the session.
+ */
+ isPreview: boolean
+ /**
+ * Unix-seconds expiry of the preview JWT that authorized this
+ * resolution, or null on live requests / dev paths without a signing
+ * key. The chat `/listen` SSE handler schedules a
+ * `preview_token_required` event at this timestamp so a long-lived
+ * stream (15-min TTL token, multi-hour author session) closes with a
+ * specific auth-recovery signal the UI can act on, instead of an
+ * opaque connection drop. Only populated for preview resolutions —
+ * live revisions have nothing to expire.
+ */
+ previewJwtExp: number | null
}
/**
@@ -111,8 +134,15 @@ export class RevisionResolver {
if (!resolved) {
return null
}
- await this.assertPreviewGate(resolved, opts?.providedToken)
- return resolved
+ const gateResult = await this.assertPreviewGate(resolved, opts?.providedToken)
+ // `assertPreviewGate` either short-circuited on the live revision or
+ // verified a valid preview JWT for a non-live one. Either way, the
+ // revision-id comparison is now the authoritative preview signal.
+ return {
+ ...resolved,
+ isPreview: resolved.revision.id !== resolved.application.live_revision_id,
+ previewJwtExp: gateResult.exp,
+ }
}
/**
@@ -120,7 +150,12 @@ export class RevisionResolver {
* the suffix selects a non-live revision via prefix-match; otherwise we
* resolve to `application.live_revision`.
*/
- private async resolveBySlugInner(rawSlug: string): Promise<ResolvedAgent | null> {
+ // Inner resolver returns the pair before preview classification — the
+ // caller (`resolveBySlug`) stamps `isPreview` after `assertPreviewGate`
+ // so we only set the flag once we know the request was authorized.
+ private async resolveBySlugInner(
+ rawSlug: string
+ ): Promise<{ application: AgentApplication; revision: AgentRevision } | null> {
// Try `<slug>-<8..32 hex>` first. The prefix must be ≥ 8 hex chars to
// avoid colliding with normal slugs that contain trailing hex (the
// serializer already forbids trailing `-`, so `slug-` followed by ≥ 8
@@ -172,12 +207,19 @@ export class RevisionResolver {
* revision. The check is bypassed when `internalSigningKey` isn't
* configured (dev / harness path).
*/
- private async assertPreviewGate(resolved: ResolvedAgent, providedToken: string | undefined): Promise<void> {
+ // Returns the JWT's `exp` claim (unix seconds) when a preview token was
+ // validated, or `{exp: null}` when the request was live / the signing key
+ // isn't configured. Callers attach `exp` to `ResolvedAgent.previewJwtExp`
+ // for SSE expiry scheduling.
+ private async assertPreviewGate(
+ resolved: { application: AgentApplication; revision: AgentRevision },
+ providedToken: string | undefined
+ ): Promise<{ exp: number | null }> {
if (!this.opts.internalSigningKey) {
- return
+ return { exp: null }
}
if (resolved.revision.id === resolved.application.live_revision_id) {
- return
+ return { exp: null }
}
if (!providedToken) {
throw new MissingPreviewSecretError('missing_token')
@@ -198,6 +240,13 @@ export class RevisionResolver {
if (payload.rev !== resolved.revision.id) {
throw new MissingPreviewSecretError('rev_claim_mismatch')
}
+ // `verifyInternalJwt` is jose-backed and rejects expired tokens before
+ // returning, so `exp` here is always in the future. A missing `exp`
+ // claim would be a verifier contract violation, but if it happens we
+ // return null and skip the scheduled expiry event (live-style stream
+ // behavior) rather than crash the request.
+ const exp = typeof payload.exp === 'number' ? payload.exp : null
+ return { exp }
}
/**
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
index d9b16531a501..9a1eeb25fb9b 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
@@ -48,6 +48,7 @@ async function runHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatRunBodySchema>>
trigger: 'chat',
requesterDisplay: principalDisplay(sessionPrincipal),
triggerMetadata: clientKind ? { client_kind: clientKind } : undefined,
+ isPreview: resolved.isPreview,
}
)
if (outcome.kind === 'elevation_required') {
@@ -193,7 +194,7 @@ async function cancelHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatCancelBodySc
}
async function listenHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatListenQuerySchema>>): Promise<void> {
- const { req, res, deps } = ctx
+ const { req, res, deps, resolved } = ctx
const { session_id: sessionId } = ctx.parsed
const existing = await getOwnedSession(ctx, sessionId)
if (!existing) {
@@ -212,7 +213,17 @@ async function listenHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatListenQueryS
res.setHeader('Connection', 'keep-alive')
res.flushHeaders()
activeStreams.labels({ transport: 'chat' }).inc()
+ // `closed` is the single flag that gates both the bus callback and the
+ // expiry timer. The bus delivers events synchronously into the subscribe
+ // callback, but a publish that's already in flight when we unsubscribe
+ // can still land here — guarding `res.write` on `closed` is what makes
+ // it safe to end the response from the expiry path.
+ let closed = false
+ let expiryTimer: NodeJS.Timeout | undefined
const unsubscribe = deps.bus.subscribe(sessionId, (event) => {
+ if (closed) {
+ return
+ }
res.write(`data: ${JSON.stringify(event)}\n\n`)
})
// Keepalive: a comment frame every 20s keeps bytes flowing while the agent
@@ -220,13 +231,60 @@ async function listenHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatListenQueryS
// (Envoy stream-idle, ALB) can't reset the stream and surface as a "network
// error" in the client. The client's SSE parser keeps only `data:` lines,
// so comment frames are discarded. unref() so it never blocks shutdown.
- const heartbeat = setInterval(() => res.write(': keepalive\n\n'), 20_000)
+ const heartbeat = setInterval(() => {
+ if (closed) {
+ return
+ }
+ res.write(': keepalive\n\n')
+ }, 20_000)
heartbeat.unref()
- req.on('close', () => {
- clearInterval(heartbeat)
+ const cleanup = (): void => {
+ if (closed) {
+ return
+ }
+ closed = true
unsubscribe()
activeStreams.labels({ transport: 'chat' }).dec()
- })
+ clearInterval(heartbeat)
+ if (expiryTimer) {
+ clearTimeout(expiryTimer)
+ }
+ }
+ // Preview-mode streams: pre-emit `preview_token_required` at the JWT's
+ // expiry instead of letting the connection drop silently. The client
+ // (posthog/code agent-builder) handles the event by re-minting via
+ // `POST .../preview-token/` and re-attaching `/listen` transparently —
+ // the agent builder UI never shows a generic disconnect during a long
+ // author session.
+ //
+ // Skew margin (5s): fire just before the upstream `exp` so the client
+ // has a window to re-mint while its existing JWT is still valid for the
+ // POST. Caps the scheduled delay at the v8 setTimeout 32-bit ceiling
+ // (~24.8 days) — the 15-min TTL never approaches it, but a future
+ // longer-lived token wouldn't silently overflow into "fire immediately."
+ if (resolved.previewJwtExp !== null) {
+ const skewMs = 5_000
+ const delayMs = Math.min(Math.max(0, resolved.previewJwtExp * 1000 - Date.now() - skewMs), 2_147_483_647)
+ expiryTimer = setTimeout(() => {
+ if (closed) {
+ return
+ }
+ res.write(
+ `data: ${JSON.stringify({
+ session_id: sessionId,
+ kind: 'preview_token_required',
+ data: { reason: 'expired' },
+ ts: new Date().toISOString(),
+ })}\n\n`
+ )
+ // Unsubscribe before `res.end()` so a bus event arriving in the
+ // window between end-of-response and the `close` event firing
+ // can't reach `res.write` on the ended stream.
+ cleanup()
+ res.end()
+ }, delayMs)
+ }
+ req.on('close', cleanup)
}
async function clientToolResultHandler(
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts b/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts
index 1b401820cedb..f42fa93a9593 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts
@@ -240,6 +240,7 @@ async function mcpHandler(ctx: CustomAuthRouteCtx): Promise<void> {
principal: principal,
trigger: 'mcp',
requesterDisplay: principalDisplay(principal),
+ isPreview: resolved.isPreview,
}
)
if (freshOutcome.kind === 'elevation_required') {
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/slack-approval-interactivity.test.ts b/products/agent_platform/services/agent-ingress/src/triggers/slack-approval-interactivity.test.ts
index 3f938dc31ae7..f94c9eedd57d 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/slack-approval-interactivity.test.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack-approval-interactivity.test.ts
@@ -48,6 +48,7 @@ function fakeRow(over: Partial<ApprovalRequest> = {}): ApprovalRequest {
decision_reason: null,
decided_args: null,
dispatch_outcome: null,
+ is_preview: false,
created_at: '2026-01-01T00:00:00Z',
expires_at: '2026-01-02T00:00:00Z',
...over,
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
index f94ab123a3ce..3a3bf0b96a4b 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
@@ -164,7 +164,13 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {
res.json({ ok: true, dropped: 'mention_only' })
return
}
- const existing = await deps.queue.findByExternalKey(resolved.application.id, externalKey)
+ // Mention-only continuity is per-scope: a preview mention into a
+ // thread that only has a live owned session must not short-circuit,
+ // and vice versa. Same discriminator as `enqueueOrResume`.
+ const existing = await deps.queue.findByExternalKey(resolved.application.id, externalKey, {
+ isPreview: resolved.isPreview,
+ revisionId: resolved.revision.id,
+ })
if (!existing) {
log.info(
{ slug: resolved.application.slug, channel: event.channel, thread_ts: event.thread_ts },
@@ -180,23 +186,34 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {
// resolution + enqueue — so the user sees the emoji within Slack's 3s ack
// window. Fails open: a revoked/missing bot token, a slack.com 5xx, an
// `already_reacted`, or a missing channel must NOT break the handler.
+ //
+ // Preview-mode short-circuit: a draft revision must never write to a real
+ // Slack workspace. Matches the contract enforced by the runner-side native
+ // slack tools (see `isPreviewSideEffect`).
if (ackReaction) {
- void postAckReaction(deps, resolved.application, resolved.revision, {
- channel: event.channel,
- ts: event.ts,
- name: ackReaction,
- }).catch((err) => {
- log.warn(
- {
- slug: resolved.application.slug,
- channel: event.channel,
- ts: event.ts,
- reaction: ackReaction,
- err: err instanceof Error ? err.message : String(err),
- },
- 'ack_reaction_threw'
+ if (resolved.isPreview) {
+ log.info(
+ { slug: resolved.application.slug, channel: event.channel, ts: event.ts, reaction: ackReaction },
+ 'ack_reaction_skipped_preview'
)
- })
+ } else {
+ void postAckReaction(deps, resolved.application, resolved.revision, {
+ channel: event.channel,
+ ts: event.ts,
+ name: ackReaction,
+ }).catch((err) => {
+ log.warn(
+ {
+ slug: resolved.application.slug,
+ channel: event.channel,
+ ts: event.ts,
+ reaction: ackReaction,
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'ack_reaction_threw'
+ )
+ })
+ }
} else {
log.debug({ slug: resolved.application.slug }, 'ack_reaction_not_configured')
}
@@ -263,6 +280,7 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {
ts: event.ts,
thread_ts: event.thread_ts ?? event.ts,
},
+ isPreview: resolved.isPreview,
}
)
if (outcome.kind === 'elevation_required') {
@@ -270,13 +288,27 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {
// own. The message is parked as an elevation request; tell them
// in-thread why nothing happened. Awaited so the reply lands before we
// ack, but error-swallowed so it can never break the 200 Slack needs.
- await postThreadMessage(deps, resolved.application, resolved.revision, {
- channel: event.channel,
- thread_ts: event.thread_ts ?? event.ts,
- text:
- 'I can only act on messages from the person who started this thread. ' +
- '@-mention me in a new message to start your own.',
- })
+ //
+ // Preview-mode short-circuit: no real Slack write from a draft session.
+ if (resolved.isPreview) {
+ log.info(
+ {
+ slug: resolved.application.slug,
+ channel: event.channel,
+ thread_ts: event.thread_ts ?? event.ts,
+ elevation_request_id: outcome.elevationRequestId,
+ },
+ 'elevation_message_skipped_preview'
+ )
+ } else {
+ await postThreadMessage(deps, resolved.application, resolved.revision, {
+ channel: event.channel,
+ thread_ts: event.thread_ts ?? event.ts,
+ text:
+ 'I can only act on messages from the person who started this thread. ' +
+ '@-mention me in a new message to start your own.',
+ })
+ }
res.json({
ok: true,
session_id: outcome.sessionId,
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts b/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts
index cb79c2213109..9d5266f06112 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts
@@ -39,6 +39,7 @@ async function webhookHandler(ctx: AuthedRouteCtx<z.infer<typeof WebhookBodySche
principal: sessionPrincipal,
trigger: 'webhook',
requesterDisplay: principalDisplay(sessionPrincipal),
+ isPreview: resolved.isPreview,
}
)
if (outcome.kind === 'elevation_required') {
diff --git a/products/agent_platform/services/agent-janitor/src/cron-tick.test.ts b/products/agent_platform/services/agent-janitor/src/cron-tick.test.ts
index d8e1e059fd62..d5294b945dee 100644
--- a/products/agent_platform/services/agent-janitor/src/cron-tick.test.ts
+++ b/products/agent_platform/services/agent-janitor/src/cron-tick.test.ts
@@ -338,7 +338,7 @@ describe('cronTick', () => {
it('expands placeholders in external_key — same set as prompt', async () => {
const revisions = new PgRevisionStore(pool)
const queue = new PgSessionQueue(pool)
- const { app } = await deploy(revisions, {
+ const { app, rev } = await deploy(revisions, {
triggers: [
minimalCron({
schedule: '0 9 * * MON',
@@ -352,7 +352,10 @@ describe('cronTick', () => {
await cronTick({ revisions, queue, now: () => t0 }, state)
const t1 = new Date('2026-06-01T09:30:00Z')
await cronTick({ revisions, queue, now: () => t1 }, state)
- const byExternal = await queue.findByExternalKey(app.id, 'digest-2026-W23')
+ const byExternal = await queue.findByExternalKey(app.id, 'digest-2026-W23', {
+ isPreview: false,
+ revisionId: rev.id,
+ })
expect(byExternal).not.toBeNull()
})
diff --git a/products/agent_platform/services/agent-janitor/src/server.test.ts b/products/agent_platform/services/agent-janitor/src/server.test.ts
index 76e1bba9fe8d..a77af44c7394 100644
--- a/products/agent_platform/services/agent-janitor/src/server.test.ts
+++ b/products/agent_platform/services/agent-janitor/src/server.test.ts
@@ -79,6 +79,7 @@ function session(label: string): AgentSession {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: '2026-05-27',
updated_at: '2026-05-27',
}
diff --git a/products/agent_platform/services/agent-janitor/src/server.ts b/products/agent_platform/services/agent-janitor/src/server.ts
index 55d05e0a7e61..4cd422cd78a4 100644
--- a/products/agent_platform/services/agent-janitor/src/server.ts
+++ b/products/agent_platform/services/agent-janitor/src/server.ts
@@ -422,6 +422,7 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
preview: lastAssistantTextPreview(s.conversation),
usage_total: s.usage_total,
retry_count: s.retry_count,
+ is_preview: s.is_preview,
created_at: s.created_at,
updated_at: s.updated_at,
}))
@@ -479,6 +480,7 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
turns: s.conversation.length,
preview: lastAssistantTextPreview(s.conversation),
usage_total: s.usage_total,
+ is_preview: s.is_preview,
created_at: s.created_at,
updated_at: s.updated_at,
}))
@@ -500,12 +502,9 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
// recent turns. usage_total comes off the row regardless so cost
// reporting stays accurate.
if (q.last_n !== undefined && q.last_n < s.conversation.length) {
- const trimmed: AgentSession = {
+ res.json({
...s,
conversation: s.conversation.slice(-q.last_n),
- }
- res.json({
- ...trimmed,
conversation_total_turns: s.conversation.length,
conversation_trimmed: true,
})
@@ -609,6 +608,11 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
decision_at: r.decision_at,
decision_reason: r.decision_reason,
dispatch_outcome: r.dispatch_outcome,
+ // Preview-mode marker copied from `agent_session.is_preview` at insert
+ // time (see PgApprovalStore.upsertQueued). Surfaced to the inbox UI so
+ // the approvals queue can render a "preview" badge and (optionally)
+ // hide preview approvals from a default operator view.
+ is_preview: r.is_preview,
created_at: r.created_at,
expires_at: r.expires_at,
})
diff --git a/products/agent_platform/services/agent-janitor/src/sweep.test.ts b/products/agent_platform/services/agent-janitor/src/sweep.test.ts
index 0d905a3e0547..f055936640cb 100644
--- a/products/agent_platform/services/agent-janitor/src/sweep.test.ts
+++ b/products/agent_platform/services/agent-janitor/src/sweep.test.ts
@@ -70,6 +70,7 @@ function session(label: string, state: AgentSession['state'], updatedAt: string)
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: updatedAt,
updated_at: updatedAt,
}
diff --git a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts b/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
index f399e70f2830..97576f5cae8e 100644
--- a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
@@ -40,6 +40,7 @@ function makeSession(over: Partial<AgentSession> = {}): AgentSession {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-06-16',
updated_at: '2026-06-16',
diff --git a/products/agent_platform/services/agent-runner/src/loop/approval.ts b/products/agent_platform/services/agent-runner/src/loop/approval.ts
index b43e140546f0..2db4eef38c6e 100644
--- a/products/agent_platform/services/agent-runner/src/loop/approval.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/approval.ts
@@ -100,6 +100,9 @@ export async function queueApprovalResult(input: {
type: input.policy.type,
allow_edit: input.policy.allow_edit,
},
+ // Stamp the session's preview mode on the row so the dispatch path
+ // and the listing serializer don't have to re-join `agent_session`.
+ is_preview: input.session.is_preview,
expires_at: new Date(Date.now() + input.policy.ttl_ms).toISOString(),
})
diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts
index f77ffbae1e4b..4288a1671f0d 100644
--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts
@@ -130,6 +130,7 @@ function makeSession(): AgentSession {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-05-27',
updated_at: '2026-05-27',
@@ -335,6 +336,38 @@ describe('buildAgentTools', () => {
expect(tool.parameters).toEqual({ type: 'object', properties: { name: { type: 'string' } } })
})
+ describe('preview-mode side-effect suppression', () => {
+ const previewSession = (): AgentSession => ({ ...makeSession(), is_preview: true })
+
+ it('suppresses MCP calls in preview — returns synthetic, never reaches the remote', async () => {
+ const ref: McpRef = { id: 'linear', url: 'https://example.com/linear', secrets: [] }
+ // Handler throws if invoked; suppression must short-circuit before
+ // callTool, so a thrown handler error never surfaces.
+ const mcp = makeFakeMcp('linear', ref, {
+ 'create-issue': {
+ description: 'Open a new Linear issue.',
+ handler: async () => {
+ throw new Error('remote MCP must not be called in preview')
+ },
+ },
+ })
+ const rev = makeRev([], [], [ref])
+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp], session: previewSession() }))
+ const result = await byId(built, 'linear__create-issue').execute('c1', { title: 'x' })
+ expect(result.details?.output).toEqual({ preview_skipped: true, tool: 'linear__create-issue' })
+ })
+
+ it('suppresses custom-tool calls in preview before touching the sandbox', async () => {
+ // With no sandbox wired, a live custom tool throws "requires a
+ // sandbox"; in preview it must short-circuit to the synthetic skip
+ // first, proving suppression runs ahead of any sandbox access.
+ const rev = makeRev([{ kind: 'custom', id: 'fetch-acme', path: 'tools/fetch-acme/' }])
+ const built = await buildAgentTools(rev, makeDeps(rev, { sandbox: null, session: previewSession() }))
+ const result = await byId(built, 'fetch-acme').execute('c1', { name: 'world' })
+ expect(result.details?.output).toEqual({ preview_skipped: true, tool: 'fetch-acme' })
+ })
+ })
+
describe('mcp tools', () => {
it('emits one AgentTool per remote tool, name-prefixed with the client prefix', async () => {
const ref: McpRef = { id: 'linear', url: 'https://example.com/linear', secrets: [] }
diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
index 07544321f7fd..c057114716b3 100644
--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
@@ -36,6 +36,7 @@ import {
getSecretAllowedHosts,
HttpFetcher,
IdentityAuthRequiredError,
+ isPreviewSideEffect,
MemoryStore,
TabularStore,
Sandbox,
@@ -275,7 +276,7 @@ export async function buildAgentTools(rev: AgentRevision, deps: AgentToolDeps):
continue
}
seen.add(exposedName)
- tools.push(makeMcpTool(exposedName, client, remote))
+ tools.push(makeMcpTool(exposedName, client, remote, deps))
}
}
}
@@ -385,6 +386,16 @@ function makeCustomTool(
description,
parameters,
execute: async (_callId, args): Promise<AgentToolResult<ToolResultDetails>> => {
+ // Preview-mode stopgap: custom tools run author-supplied code in the
+ // sandbox and can perform arbitrary external writes, with no
+ // read-vs-write signal to gate on. Suppress every custom-tool call in
+ // preview (fail-closed) before resolving identity or touching the
+ // sandbox. Same accepted trade as MCP — blinds read-only custom tools
+ // too until the dispatch boundary gains a real classification.
+ if (isPreviewSideEffect(buildToolContext(deps), id, args as Record<string, unknown>)) {
+ const skipped = { preview_skipped: true, tool: id }
+ return { content: [{ type: 'text', text: JSON.stringify(skipped) }], details: { output: skipped } }
+ }
const gate = await gateIdentity(requiresIdentity ? { id: requiresIdentity, scopes: [] } : undefined, deps)
if (!gate.proceed) {
return gate.result
@@ -465,7 +476,8 @@ function makeClientTool(
function makeMcpTool(
exposedName: string,
client: OpenedMcp,
- remote: RemoteMcpTool
+ remote: RemoteMcpTool,
+ deps: AgentToolDeps
): AgentTool<TSchema, ToolResultDetails> {
return {
name: exposedName,
@@ -473,7 +485,20 @@ function makeMcpTool(
description: remote.description,
parameters: remote.inputSchema as TSchema,
execute: async (_callId, args): Promise<AgentToolResult<ToolResultDetails>> => {
- const result = await client.callTool(remote.name, (args ?? {}) as Record<string, unknown>)
+ const callArgs = (args ?? {}) as Record<string, unknown>
+ // Preview-mode stopgap: remote MCP servers can perform arbitrary
+ // external side effects and aren't yet classified read-vs-write, so
+ // suppress every MCP call in preview (fail-closed) rather than let a
+ // write reach the real world. Returns a shape-valid synthetic
+ // envelope so the model's next turn keeps reasoning; logs
+ // `tool_preview_skipped`. This also blinds MCP *reads* in preview —
+ // an accepted, temporary trade until the dispatch boundary gates on
+ // a real read/write signal (tracked follow-up).
+ if (isPreviewSideEffect(buildToolContext(deps), exposedName, callArgs)) {
+ const skipped = { preview_skipped: true, tool: exposedName }
+ return { content: [{ type: 'text', text: JSON.stringify(skipped) }], details: { output: skipped } }
+ }
+ const result = await client.callTool(remote.name, callArgs)
if (result.isError) {
// Surface the first text content as the error message — same
// shape as `resultText()` in the driver. Keeps the model's
@@ -530,6 +555,7 @@ function buildToolContext(deps: AgentToolDeps, resolvedIdentities?: ToolContext[
resolvedIdentities,
http: deps.http,
posthogApiBaseUrl: deps.posthogApiBaseUrl,
+ isPreview: deps.session.is_preview,
}
}
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts
index dbe244350ff6..682c44e75660 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts
@@ -91,6 +91,7 @@ function makeSession(over: Partial<AgentSession> = {}): AgentSession {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-05-29',
updated_at: '2026-05-29',
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.ts
index 2be369ad42da..b066384fb9f8 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts
@@ -241,7 +241,15 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
// message into the thread (see the turn_end handler). The model is told as
// much so it replies in natural language instead of forcing everything
// through the slack-post-message tool.
- const slackReply = isSlackTriggerMetadata(session.trigger_metadata) ? session.trigger_metadata : null
+ //
+ // Preview-mode isolation: when the session was created via the preview
+ // ingress path, the relay is disabled — author iteration must not post
+ // into the real Slack channel attached to the live revision. The
+ // system-prompt suppression below also drops the slack-relay guidance so
+ // the model isn't told to "just reply in natural language" while the
+ // platform is actually noop'ing the relay underneath it.
+ const slackReply =
+ !session.is_preview && isSlackTriggerMetadata(session.trigger_metadata) ? session.trigger_metadata : null
const system = await buildSystemPrompt(rev, deps.bundle, {
unavailableMcps: (deps.mcpFailures ?? []).map((f) => ({
id: f.ref.id,
@@ -666,6 +674,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
latency_ms: started ? Date.now() - started.t0 : 0,
is_error: event.isError,
error: errorText,
+ is_preview: session.is_preview,
},
])
}
@@ -795,6 +804,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
stop_reason: msg.stopReason,
is_error: msg.stopReason === 'error',
error: msg.stopReason === 'error' ? msg.errorMessage : undefined,
+ is_preview: session.is_preview,
},
])
await deps.onTurnPersist?.(session)
@@ -1063,6 +1073,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
latency_ms: Date.now() - t0,
is_error: d.isError,
error: d.error,
+ is_preview: session.is_preview,
},
])
} catch (obsErr) {
@@ -1158,6 +1169,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
trace_name: deps.applicationName ?? `agent:${session.application_id}`,
input_state: traceInput,
output_state: lastOutput,
+ is_preview: session.is_preview,
},
])
}
diff --git a/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.test.ts b/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.test.ts
index 2eadb8527931..736246bf8532 100644
--- a/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.test.ts
+++ b/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.test.ts
@@ -34,6 +34,7 @@ function freshSession(overrides: Record<string, unknown> = {}): never {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: '2026-05-27',
updated_at: '2026-05-27',
...overrides,
diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.test.ts b/products/agent_platform/services/agent-runner/src/workers/worker.test.ts
index d49452e6db5c..43f674373fc4 100644
--- a/products/agent_platform/services/agent-runner/src/workers/worker.test.ts
+++ b/products/agent_platform/services/agent-runner/src/workers/worker.test.ts
@@ -134,6 +134,7 @@ describe('Worker', () => {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-05-27',
updated_at: '2026-05-27',
@@ -202,6 +203,7 @@ describe('Worker', () => {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-05-27',
updated_at: '2026-05-27',
@@ -267,6 +269,7 @@ describe('Worker', () => {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-05-27',
updated_at: '2026-05-27',
@@ -364,6 +367,7 @@ describe('Worker', () => {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-05-27',
updated_at: '2026-05-27',
@@ -426,6 +430,7 @@ describe('Worker', () => {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-05-27',
updated_at: '2026-05-27',
@@ -548,6 +553,7 @@ describe('Worker', () => {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-05-27',
updated_at: '2026-05-27',
@@ -645,6 +651,7 @@ describe('Worker', () => {
retry_count: 0,
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
usage_total: { ...EMPTY_USAGE_TOTAL },
created_at: '2026-05-27',
updated_at: '2026-05-27',
diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-decision.test.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-decision.test.ts
index bca8ea1f0ec1..bfd270fc07b8 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/approval-decision.test.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-decision.test.ts
@@ -25,6 +25,7 @@ function fakeRow(over: Partial<ApprovalRequest> = {}): ApprovalRequest {
decision_reason: null,
decided_args: null,
dispatch_outcome: null,
+ is_preview: false,
created_at: '2026-01-01T00:00:00Z',
expires_at: '2026-01-02T00:00:00Z',
...over,
diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts
index 2db5f9b979c3..bd6b3a93e6c8 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts
@@ -66,6 +66,7 @@ function buildInput(overrides: Partial<UpsertApprovalRequestInput> = {}): Upsert
type: 'agent',
allow_edit: false,
},
+ is_preview: false,
expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
...overrides,
}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts
index 080e2ecf3fa0..b4ec14ffe3f2 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts
@@ -46,6 +46,15 @@ export interface ApprovalRequest {
decided_args: Record<string, unknown> | null
/** Set on terminal decision. `{result?, error?}`. */
dispatch_outcome: { result?: unknown; error?: string } | null
+ /**
+ * Mirrors `agent_session.is_preview` for the owning session, copied from
+ * the session row at insert time so the listing serializer can render a
+ * preview badge without a join. Drives dispatch routing too: a preview
+ * approval that resolves into a real tool call routes through the
+ * runner's preview-aware adapter set (Slack/webhook noop), never the
+ * live publish surface.
+ */
+ is_preview: boolean
created_at: string
expires_at: string
}
@@ -82,6 +91,12 @@ export interface UpsertApprovalRequestInput {
proposed_args: Record<string, unknown>
assistant_message: AssistantMessageRecord
approver_scope: ApprovalRequest['approver_scope']
+ /**
+ * Copied verbatim from the owning `agent_session.is_preview` at the call
+ * site (the runner's approval emit path). Stamped onto the row so the
+ * dispatcher and listing surfaces don't need to re-join `agent_session`.
+ */
+ is_preview: boolean
expires_at: string
}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-approval-store.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-approval-store.ts
index b73264d43294..0c2a1ff4c8a1 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-approval-store.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-approval-store.ts
@@ -23,7 +23,7 @@ const SELECT_COLS = `id, session_id, application_id, team_id, revision_id, turn,
tool_call_id, tool_name, proposed_args, args_hash,
assistant_message, approver_scope, state,
decision_by, decision_at, decision_reason, decided_args,
- dispatch_outcome, created_at, expires_at`
+ dispatch_outcome, is_preview, created_at, expires_at`
export class PgApprovalStore implements ApprovalStore {
constructor(private readonly pool: Pool) {}
@@ -38,9 +38,10 @@ export class PgApprovalStore implements ApprovalStore {
`INSERT INTO agent_tool_approval_request
(id, session_id, application_id, team_id, revision_id, turn,
tool_call_id, tool_name, proposed_args, args_hash,
- assistant_message, approver_scope, state, created_at, expires_at)
+ assistant_message, approver_scope, state, is_preview,
+ created_at, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11::jsonb,
- $12::jsonb, 'queued', NOW(), $13)
+ $12::jsonb, 'queued', $13, NOW(), $14)
ON CONFLICT (session_id, tool_name, args_hash) WHERE state = 'queued'
DO UPDATE SET tool_call_id = agent_tool_approval_request.tool_call_id
RETURNING ${SELECT_COLS}, (xmax = 0) AS _inserted`,
@@ -57,6 +58,7 @@ export class PgApprovalStore implements ApprovalStore {
argsHash,
JSON.stringify(input.assistant_message),
JSON.stringify(input.approver_scope),
+ input.is_preview,
input.expires_at,
]
)
@@ -236,6 +238,7 @@ interface DbRow {
decision_reason: string | null
decided_args: unknown | null
dispatch_outcome: unknown | null
+ is_preview: boolean
created_at: Date
expires_at: Date
}
@@ -260,6 +263,7 @@ function rowToRequest(row: DbRow): ApprovalRequest {
decision_reason: row.decision_reason,
decided_args: (row.decided_args as Record<string, unknown>) ?? null,
dispatch_outcome: (row.dispatch_outcome as ApprovalRequest['dispatch_outcome']) ?? null,
+ is_preview: row.is_preview === true,
created_at: row.created_at.toISOString(),
expires_at: row.expires_at.toISOString(),
}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts
index 8c9251a9906a..508cf49a95b5 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts
@@ -213,6 +213,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date(Date.now() + i).toISOString(),
updated_at: new Date(Date.now() + i).toISOString(),
})
@@ -282,6 +283,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
usage_total: { ...EMPTY_USAGE_TOTAL, cost_total: cost },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: created,
updated_at: created,
})
@@ -339,6 +341,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
})
@@ -352,7 +355,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
expect(after!.pending_inputs).toHaveLength(1)
})
- it('findByExternalKey resolves on (application_id, external_key)', async () => {
+ it('findByExternalKey resolves on (application_id, external_key, scope)', async () => {
if (!reachable) {
return
}
@@ -382,13 +385,22 @@ maybeDescribe('Postgres impls (real PG)', () => {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
})
- const found = await queue.findByExternalKey(app.id, 'slack:C01:T1')
+ const liveScope = { isPreview: false, revisionId: rev.id }
+ const found = await queue.findByExternalKey(app.id, 'slack:C01:T1', liveScope)
expect(found!.id).toBe('22222222-2222-2222-2222-222222222222')
- const missing = await queue.findByExternalKey(app.id, 'nope')
+ const missing = await queue.findByExternalKey(app.id, 'nope', liveScope)
expect(missing).toBeNull()
+ // A preview-scoped lookup on the same key + revision does not see the
+ // live row — preview/live sessions are isolated at the SQL filter.
+ const crossScope = await queue.findByExternalKey(app.id, 'slack:C01:T1', {
+ isPreview: true,
+ revisionId: rev.id,
+ })
+ expect(crossScope).toBeNull()
})
it('getForApplication scopes by (id, application_id) — null for another application', async () => {
@@ -423,6 +435,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
})
@@ -523,6 +536,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
})
@@ -621,6 +635,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
})
@@ -642,6 +657,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
proposed_args: { team_id: 42, dry_run: false },
assistant_message: asstMsg,
approver_scope: { type: 'agent' as const, allow_edit: false },
+ is_preview: false,
expires_at: new Date(Date.now() + 60_000).toISOString(),
}
@@ -707,6 +723,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
})
@@ -727,6 +744,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
tool_name: 'tool.dispatch',
assistant_message: asstMsg,
approver_scope: { type: 'agent' as const, allow_edit: false },
+ is_preview: false,
expires_at: new Date(Date.now() + 60_000).toISOString(),
}
@@ -799,6 +817,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: ts,
updated_at: ts,
})
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
index e3b9cfe7b76d..cd741a0f944d 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
@@ -30,7 +30,7 @@ import {
const SELECT_COLS = `id, application_id, revision_id, team_id, external_key,
idempotency_key, trigger_metadata, state,
conversation, pending_inputs, principal, retry_count,
- usage_total, acl, pending_elevation_requests,
+ usage_total, acl, pending_elevation_requests, is_preview,
created_at, updated_at`
export class PgSessionQueue implements SessionQueue {
@@ -38,14 +38,19 @@ export class PgSessionQueue implements SessionQueue {
async enqueue(session: AgentSession): Promise<void> {
await this.pool.query(
+ // `is_preview` is immutable post-create — intentionally NOT in the
+ // ON CONFLICT update set. A retried enqueue of the same id (rare,
+ // but possible via the runner's append flow) must not flip a live
+ // session into preview: the side-effect-isolation contract for the
+ // runner relies on it being stable across the row's lifetime.
`INSERT INTO agent_session
(id, application_id, revision_id, team_id, external_key,
idempotency_key, trigger_metadata, state,
conversation, pending_inputs, principal, retry_count,
- usage_total, acl, pending_elevation_requests,
+ usage_total, acl, pending_elevation_requests, is_preview,
created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9::jsonb, $10::jsonb,
- $11::jsonb, $12, $13::jsonb, $14::jsonb, $15::jsonb, $16, $17)
+ $11::jsonb, $12, $13::jsonb, $14::jsonb, $15::jsonb, $16, $17, $18)
ON CONFLICT (id) DO UPDATE SET
state = EXCLUDED.state,
conversation = EXCLUDED.conversation,
@@ -70,6 +75,7 @@ export class PgSessionQueue implements SessionQueue {
JSON.stringify(session.usage_total ?? EMPTY_USAGE_TOTAL),
JSON.stringify(session.acl ?? []),
JSON.stringify(session.pending_elevation_requests ?? []),
+ session.is_preview,
session.created_at,
session.updated_at,
]
@@ -378,14 +384,27 @@ export class PgSessionQueue implements SessionQueue {
return r.rowCount ?? 0
}
- async findByExternalKey(applicationId: string, externalKey: string): Promise<AgentSession | null> {
+ async findByExternalKey(
+ applicationId: string,
+ externalKey: string,
+ scope: { isPreview: boolean; revisionId: string }
+ ): Promise<AgentSession | null> {
+ // The preview/live discriminator lives in SQL, not in JS post-filtering
+ // — the `ORDER BY updated_at DESC LIMIT 1` would otherwise return the
+ // most recent row regardless of scope, and a JS-side reject would
+ // strand any older same-scope row. Filtering in the WHERE clause
+ // guarantees the lookup never reaches a row outside its scope.
+ // `revision_id` constrains only preview rows; see the interface docs.
const r = await this.pool.query<DbRow>(
`SELECT ${SELECT_COLS}
FROM agent_session
- WHERE application_id = $1 AND external_key = $2
+ WHERE application_id = $1
+ AND external_key = $2
+ AND is_preview = $3
+ AND ($3 = FALSE OR revision_id = $4)
ORDER BY updated_at DESC
LIMIT 1`,
- [applicationId, externalKey]
+ [applicationId, externalKey, scope.isPreview, scope.revisionId]
)
if (r.rowCount === 0) {
return null
@@ -558,6 +577,7 @@ interface DbRow {
usage_total: unknown
acl: unknown
pending_elevation_requests: unknown
+ is_preview: boolean
created_at: Date
updated_at: Date
}
@@ -615,6 +635,7 @@ function rowToSession(row: DbRow): AgentSession {
pending_elevation_requests: Array.isArray(row.pending_elevation_requests)
? (row.pending_elevation_requests as PendingElevationRequest[])
: [],
+ is_preview: row.is_preview === true,
created_at: row.created_at.toISOString(),
updated_at: row.updated_at.toISOString(),
}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/queue.ts b/products/agent_platform/services/agent-shared/src/persistence/queue.ts
index ce56cb3d54c5..6acb32289989 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/queue.ts
@@ -123,8 +123,34 @@ export interface SessionQueue extends SessionInputsStore {
* callers (runner claim loop, sweep) that legitimately fetch by id alone.
*/
getForApplication(sessionId: string, applicationId: string): Promise<AgentSession | null>
- /** Find an existing session matching (application_id, external_key). */
- findByExternalKey(applicationId: string, externalKey: string): Promise<AgentSession | null>
+ /**
+ * Find an existing session matching `(application_id, external_key)` within
+ * a preview/live scope. The `scope` discriminator is part of the lookup,
+ * not a filter the caller applies afterward, so a live (or preview)
+ * request can never match across the boundary:
+ *
+ * - `scope.isPreview = false` matches only live rows. Live continuity
+ * across upstream revision promotions is preserved (the runner sticks
+ * with whatever `revision_id` was on the row at session creation), so
+ * `scope.revisionId` does not constrain the match here.
+ * - `scope.isPreview = true` additionally requires `revision_id =
+ * scope.revisionId`. Two draft revisions of the same agent previewed
+ * against the same external_key get distinct sessions — their
+ * conversation histories must not bleed together.
+ *
+ * Without the discriminator, a preview-authenticated request resuming on a
+ * shared external_key would inherit a live session's `is_preview = false`
+ * row; the runner reads suppression off that row, so live secrets and
+ * un-suppressed external writes would fire under preview auth. The split
+ * SQL filter (rather than an after-the-fact JS guard) is what makes that
+ * unreachable: an older live row never wins the lookup over a fresh
+ * preview row keyed under the same external_key.
+ */
+ findByExternalKey(
+ applicationId: string,
+ externalKey: string,
+ scope: { isPreview: boolean; revisionId: string }
+ ): Promise<AgentSession | null>
/**
* Find an existing session matching (application_id, idempotency_key).
* Returns null if no row exists (including when the key was nulled by the
diff --git a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts
index 4bed54541c01..510354f937e4 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts
@@ -60,6 +60,17 @@ interface AnalyticsEventBase {
is_error?: boolean
/** Free-form failure detail; only set when `is_error` is true. */
error?: string
+ /**
+ * `true` when emitted from a preview-mode session
+ * (`agent_session.is_preview = true`). Stamped onto every `$ai_*` event
+ * as `$agent_is_preview` so PostHog's LLM Analytics dashboards can
+ * filter author-iteration noise out of production observability — the
+ * preview run still emits events (so the author can inspect their own
+ * generations), but it's marked for downstream filtering. Optional so
+ * tests + the analytics-sink unit tests can omit it; missing reads as
+ * "not preview" via a truthy check.
+ */
+ is_preview?: boolean
}
export interface AnalyticsGenerationEvent extends AnalyticsEventBase {
@@ -186,6 +197,13 @@ export function buildAnalyticsProperties(event: AnalyticsEvent): Record<string,
base.$ai_error = event.error
}
}
+ if (event.is_preview) {
+ // Preview-mode marker. PostHog's LLM Analytics dashboards filter on
+ // this so author iteration doesn't skew production observability.
+ // Emitted only when true (absent ≡ live), keeping the property bag
+ // tight and the dashboard default uncluttered.
+ base.$agent_is_preview = true
+ }
if (event.kind === 'generation') {
base.$ai_model = event.model
base.$ai_provider = event.provider
diff --git a/products/agent_platform/services/agent-shared/src/runtime/bus.ts b/products/agent_platform/services/agent-shared/src/runtime/bus.ts
index eeb67866b6eb..fa4a5e4cd28a 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/bus.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/bus.ts
@@ -98,6 +98,18 @@ export type SessionEventKind =
*/
| 'closed'
| 'failed'
+ /**
+ * Mid-stream signal that the preview JWT carrying the connection has
+ * expired or otherwise stopped validating. Carries
+ * `{ reason: 'expired' | 'invalid' }`. Fires from the ingress `/listen`
+ * SSE bridge when an upstream re-validation fails between turns; the
+ * runner itself never emits this. Consumers (posthog/code agent
+ * builder) re-mint a fresh token via `POST .../preview-token/` and
+ * re-attach `/listen` transparently. Distinct from `failed` so the UI
+ * can render an auth-recovery affordance instead of a generic error.
+ * Not a delta event — fires once before the stream closes.
+ */
+ | 'preview_token_required'
/**
* High-cardinality delta events that fire many times per turn. Filtered out
diff --git a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
index 93fe854ac112..e32e4563afd3 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
@@ -49,6 +49,7 @@ function makeSession(triggerMetadata: Record<string, unknown> | null): AgentSess
usage_total: { input_tokens: 0, output_tokens: 0, cost_total: 0 },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
} as unknown as AgentSession
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts
index 967f482a16f7..5d28828d2e28 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts
@@ -46,6 +46,7 @@ function makeSession(triggerMetadata: Record<string, unknown> | null): AgentSess
usage_total: { input_tokens: 0, output_tokens: 0, cost_total: 0 },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
} as unknown as AgentSession
@@ -189,6 +190,35 @@ describe('SlackFailureNotifier', () => {
expect(logger.warn.mock.calls[0]![0]).toMatchObject({ slack_error: 'channel_not_found' })
})
+ it('preview-mode short-circuit: no fetch, no resolver call, structured skip log', async () => {
+ // A draft revision running in preview mode must never reply into a real
+ // Slack workspace on failure — the author needs to inspect the failure
+ // surface in the agent-builder UI, not see noise on a customer channel.
+ // Pin the contract: the resolver isn't even reached (no token decrypt),
+ // and the skip is logged with the slug+channel for grep-ability.
+ const fetch = vi.fn()
+ const http: HttpFetcher = { fetch: fetch as unknown as HttpFetcher['fetch'] }
+ const logger = { warn: vi.fn(), info: vi.fn() }
+ const resolver = tokenResolver('xoxb-real-but-must-not-decrypt')
+ const n = new SlackFailureNotifier({ http, resolver, logger })
+
+ const session = makeSession(SLACK_META)
+ session.is_preview = true
+
+ await n.notify({
+ session,
+ application: APP,
+ revision: REV,
+ reason: 'docker run failed',
+ category: 'transient_infra',
+ })
+
+ expect(fetch).not.toHaveBeenCalled()
+ expect(resolver.resolve).not.toHaveBeenCalled()
+ expect(logger.info).toHaveBeenCalledTimes(1)
+ expect(logger.info.mock.calls[0]![1]).toBe('slack_failure_notifier_skipped_preview')
+ })
+
it('swallows resolver throws and skips post', async () => {
const fetch = vi.fn()
const http: HttpFetcher = { fetch: fetch as unknown as HttpFetcher['fetch'] }
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts
index 5aeb9fc474e0..8de51e4bac8d 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts
@@ -36,6 +36,22 @@ export class SlackFailureNotifier implements FailureNotifier {
if (!isSlackTriggerMetadata(meta)) {
return
}
+ // Preview-mode sessions never post failure notices into Slack —
+ // an author iterating on a draft must not have a failed run leak
+ // a synthetic error message into the live channel attached to the
+ // production revision. Log + return; the preview UI surfaces the
+ // failure to the author through the standard `failed` SSE event.
+ if (input.session.is_preview) {
+ this.deps.logger?.info?.(
+ {
+ session_id: input.session.id,
+ channel: meta.channel,
+ thread_ts: meta.thread_ts,
+ },
+ 'slack_failure_notifier_skipped_preview'
+ )
+ return
+ }
const token = await this.resolveTokenSafely(input.revision, input.application, input.session.id)
if (!token) {
return
diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.ts
index c2a7b79e23f2..55d0c793b21b 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts
@@ -1171,6 +1171,18 @@ export interface AgentSession {
* surfaces them in the chat UI / Slack thread.
*/
pending_elevation_requests: PendingElevationRequest[]
+ /**
+ * Author iteration session — created via the preview ingress path (the
+ * Django-side preview-proxy, or a direct ingress call carrying a valid
+ * `aud=agent-ingress.preview` JWT). Output adapters (slack reply, webhook
+ * publish) noop instead of POSTing externally; the analytics sink tags
+ * `$ai_*` events with `preview: true` so production observability
+ * dashboards can filter author iteration noise. Cron is implicitly safe
+ * because the janitor only schedules off `live_revision_id`, so preview
+ * sessions never originate from cron. False for every session created via
+ * the live ingress path.
+ */
+ is_preview: boolean
created_at: string
updated_at: string
}
diff --git a/products/agent_platform/services/agent-shared/src/spec/tool.ts b/products/agent_platform/services/agent-shared/src/spec/tool.ts
index 5e205f2d4b3b..18b6b75f0586 100644
--- a/products/agent_platform/services/agent-shared/src/spec/tool.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/tool.ts
@@ -146,6 +146,17 @@ export interface ToolContext {
* reads inside tool code.
*/
posthogApiBaseUrl: string
+ /**
+ * Mirrors `agent_session.is_preview` for the currently-executing session.
+ * Tools that publish externally (Slack post / update / react, webhook
+ * delivery, anything else with a real-world side effect) MUST short-
+ * circuit via `isPreviewSideEffect(...)` from this package when this is
+ * true. Read-only tools (slack read-channel / read-thread, query tools)
+ * are unaffected. The runner stamps the same flag from
+ * `session.is_preview`; tests can construct a context with `isPreview:
+ * true` to exercise the noop branch.
+ */
+ isPreview: boolean
}
/** Outcome of `ctx.identity.resolve`: a usable credential, a link to send, or no-go.
@@ -184,5 +195,29 @@ export function defineNativeTool<TArgsSchema extends TSchema, TReturnSchema exte
}
}
+/**
+ * Author-iteration guard for write-side native tools. Tools that publish
+ * externally (`@posthog/slack-post-message`, future webhook-publish tools,
+ * etc.) call this at the top of `run` to log a structured skip event when
+ * the session is in preview mode. The tool then returns a shape-valid
+ * synthetic response so the model's next turn sees a "successful" call and
+ * keeps reasoning naturally — the preview UX is "the agent acts like the
+ * side effect happened" while the platform keeps a `tool_preview_skipped`
+ * log entry for the author to inspect.
+ *
+ * Read-only tools (slack read-channel / read-thread, query tools, etc.) do
+ * NOT use this — reads have no external side effect, and treating them as
+ * such would defeat the author's ability to verify their agent's read paths.
+ *
+ * Returns true when the side effect should be suppressed.
+ */
+export function isPreviewSideEffect(ctx: ToolContext, toolId: string, args: Record<string, unknown>): boolean {
+ if (!ctx.isPreview) {
+ return false
+ }
+ ctx.log('info', 'tool_preview_skipped', { tool: toolId, args })
+ return true
+}
+
/** Re-export TypeBox `Type` so tool authors have one import. */
export { Type }
diff --git a/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts b/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts
index b5a8de3104a6..4dcf3944892e 100644
--- a/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts
@@ -60,7 +60,7 @@ describe('cron trigger: real e2e', () => {
})
const state = newCronTickState()
- const deps = { revisions: c.revisions, queue: c.queue }
+ const deps = { revisions: c.revisions, queue: c.queue, encryption: c.encryption }
// First tick seeds lastTickAt; no firings in (now, now].
const t0 = new Date('2026-06-01T09:00:00Z')
const r0 = await cronTick({ ...deps, now: () => t0 }, state)
diff --git a/products/agent_platform/services/agent-tests/src/cases/example-kudos-bot.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-kudos-bot.test.ts
index 3b7d1a71e431..a0cc0eaeff80 100644
--- a/products/agent_platform/services/agent-tests/src/cases/example-kudos-bot.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/example-kudos-bot.test.ts
@@ -489,7 +489,7 @@ describe('example: kudos-bot bundle', () => {
// 2026-06-08 is a Monday and 09:00 PDT = 16:00 UTC. Window is
// (lastTickAt, now], so t0 must land strictly before the firing.
const state = newCronTickState()
- const deps = { revisions: c.revisions, queue: c.queue }
+ const deps = { revisions: c.revisions, queue: c.queue, encryption: c.encryption }
const t0 = new Date('2026-06-08T15:59:00Z') // 08:59 PT — seeds the window
await cronTick({ ...deps, now: () => t0 }, state)
const t1 = new Date('2026-06-08T16:01:00Z') // window (15:59, 16:01] catches 16:00
diff --git a/products/agent_platform/services/agent-tests/src/cases/example-wake-me-up.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-wake-me-up.test.ts
index c4483d669094..9ae9ef33a031 100644
--- a/products/agent_platform/services/agent-tests/src/cases/example-wake-me-up.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/example-wake-me-up.test.ts
@@ -187,7 +187,7 @@ describe('example: wake-me-up bundle', () => {
// Window is (lastTickAt, now] (exclusive at start), so t0 must land
// strictly BEFORE the 08:00 PT firing for t1 to catch it.
const state = newCronTickState()
- const deps = { revisions: c.revisions, queue: c.queue }
+ const deps = { revisions: c.revisions, queue: c.queue, encryption: c.encryption }
// 2026-06-03 is a Wednesday; 08:00 PT (PDT, UTC-7) = 15:00 UTC.
const t0 = new Date('2026-06-03T14:59:00Z') // 07:59 PT — seeds
await cronTick({ ...deps, now: () => t0 }, state)
diff --git a/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts b/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts
index aba78498b8f7..2652b4bb6453 100644
--- a/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts
@@ -110,6 +110,7 @@ maybeDescribe('@posthog/identity-fetch × dogs (real PG + HTTP)', () => {
identity,
http: new HttpClient({}),
posthogApiBaseUrl: '',
+ isPreview: false,
}
const tool = getNativeTool('@posthog/identity-fetch')
@@ -156,6 +157,7 @@ maybeDescribe('@posthog/identity-fetch × dogs (real PG + HTTP)', () => {
identity,
http: new HttpClient({}),
posthogApiBaseUrl: '',
+ isPreview: false,
}
await expect(
getNativeTool('@posthog/identity-fetch').run({ provider: 'dogs', url: 'http://x/api' }, ctx)
@@ -202,6 +204,7 @@ maybeDescribe('@posthog/identity-fetch × dogs (real PG + HTTP)', () => {
identity,
http: new HttpClient({}),
posthogApiBaseUrl: '',
+ isPreview: false,
}
// Link first.
const init = await registry.require('dogs').initiate({
diff --git a/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts b/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts
index ea8294f29898..d208995ac940 100644
--- a/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts
@@ -162,6 +162,7 @@ describe('per-agent spec.model resolution: real e2e', () => {
usage_total: { ...EMPTY_USAGE_TOTAL },
acl: [],
pending_elevation_requests: [],
+ is_preview: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
})
diff --git a/products/agent_platform/services/agent-tests/src/cases/preview-mode.test.ts b/products/agent_platform/services/agent-tests/src/cases/preview-mode.test.ts
new file mode 100644
index 000000000000..ca59b5480733
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/cases/preview-mode.test.ts
@@ -0,0 +1,233 @@
+/**
+ * Preview-mode e2e: a session created via the preview ingress path stamps
+ * `agent_session.is_preview = true`, every `$ai_*` event the runner emits
+ * carries `$agent_is_preview: true`, and the session runs against the DRAFT
+ * revision it was addressed to (so per-revision secrets stay isolated from
+ * the live revision).
+ *
+ * The harness's `deployAgent` always promotes the revision to live, so the
+ * test creates a SECOND revision directly via `c.revisions.createRevision`
+ * and exercises the `<slug>-<rev-hex>` URL form that the resolver routes to
+ * the non-live revision. The preview JWT is minted with the dev signing key
+ * the harness wires both sides against.
+ */
+
+import request from 'supertest'
+
+import {
+ AgentSpecSchema,
+ DEV_INTERNAL_SIGNING_KEY,
+ INTERNAL_JWT_AUDIENCE,
+ mintInternalJwt,
+ TEST_S3_BUCKET,
+} from '@posthog/agent-shared'
+
+import { buildCluster, closeSharedPool, Cluster, fauxText } from '../harness'
+
+describe('preview-mode: real e2e', () => {
+ let c: Cluster
+
+ beforeEach(async () => {
+ c = await buildCluster()
+ })
+
+ afterEach(async () => {
+ await c.teardown()
+ })
+
+ afterAll(async () => {
+ await closeSharedPool()
+ })
+
+ it('preview run stamps is_preview on the session row and on every $ai_* event', async () => {
+ c.setScript([fauxText('hi from draft')])
+ // Live revision via the standard harness path — exists so the
+ // resolver has a `live_revision_id` to compare against (the
+ // preview gate exempts requests resolving to the live id).
+ const { application } = await c.deployAgent({ slug: 'preview-basic' })
+
+ // Draft revision attached to the same application — non-live, ready.
+ const draftSpec = AgentSpecSchema.parse({
+ model: 'faux/faux',
+ triggers: [
+ { type: 'chat', config: {}, auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] } },
+ ],
+ })
+ const draft = await c.revisions.createRevision({
+ application_id: application.id,
+ parent_revision_id: null,
+ created_by_id: null,
+ bundle_uri: `s3://${TEST_S3_BUCKET}/${c.bundlePrefix}/${application.id}/`,
+ spec: draftSpec,
+ })
+ await c.bundle.write(draft.id, 'agent.md', 'You are a draft agent.')
+ const sha = await c.bundle.freeze(draft.id)
+ await c.revisions.setRevisionState(draft.id, 'ready', sha)
+
+ // Preview JWT bound to (application, draft revision).
+ const token = await mintInternalJwt({
+ audience: INTERNAL_JWT_AUDIENCE.INGRESS_PREVIEW,
+ signingKey: DEV_INTERNAL_SIGNING_KEY,
+ claims: { app: application.id, rev: draft.id },
+ ttlSec: 900,
+ })
+
+ // Hit the `<slug>-<rev-hex>` form so the resolver picks the draft.
+ const slug = `preview-basic-${draft.id.replace(/-/g, '')}`
+ const res = await request(c.ingress)
+ .post(`/agents/${slug}/run`)
+ .set('x-agent-preview-token', token)
+ .send({ message: 'hi' })
+ expect(res.status).toBe(200)
+ const sessionId = res.body.session_id as string
+
+ await c.drain()
+ const session = await c.queue.get(sessionId)
+ expect(session).not.toBeNull()
+ expect(session!.is_preview).toBe(true)
+ expect(session!.revision_id).toBe(draft.id)
+
+ // Every emitted analytics event for this session carries the marker.
+ // CollectingAnalyticsSink exposes both the raw `AnalyticsEvent` (which
+ // we type-stamp with `is_preview`) and the resolved `$ai_*` property
+ // bag — assert both so a regression on either side fails the test.
+ const entries = c.analytics.forSession(sessionId)
+ expect(entries.length).toBeGreaterThan(0)
+ for (const e of entries) {
+ expect(e.event.is_preview).toBe(true)
+ expect(e.properties.$agent_is_preview).toBe(true)
+ }
+ })
+
+ it('live run leaves is_preview false (regression guard against accidental flag flip)', async () => {
+ c.setScript([fauxText('hi from live')])
+ await c.deployAgent({ slug: 'preview-live-baseline' })
+ const res = await request(c.ingress).post('/agents/preview-live-baseline/run').send({ message: 'hi' })
+ await c.drain()
+ const session = await c.queue.get(res.body.session_id)
+ expect(session!.is_preview).toBe(false)
+ })
+
+ it('preview run resolves to the draft revision carrying its own encrypted_env (per-revision secrets)', async () => {
+ c.setScript([fauxText('ran against the draft')])
+ const { application } = await c.deployAgent({ slug: 'preview-per-revision-secrets' })
+
+ // Draft revision with its OWN secret block, isolated from whatever the
+ // live revision runs with. Secrets live on the revision now, so a
+ // preview run against this draft gets exactly these secrets.
+ const draftSpec = AgentSpecSchema.parse({
+ model: 'faux/faux',
+ triggers: [
+ { type: 'chat', config: {}, auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] } },
+ ],
+ secrets: ['FOO_API_KEY'],
+ })
+ const draft = await c.revisions.createRevision({
+ application_id: application.id,
+ parent_revision_id: null,
+ created_by_id: null,
+ bundle_uri: `s3://${TEST_S3_BUCKET}/${c.bundlePrefix}/${application.id}/`,
+ spec: draftSpec,
+ encrypted_env: c.encryption.encrypt(JSON.stringify({ FOO_API_KEY: 'draft-val' })),
+ })
+ await c.bundle.write(draft.id, 'agent.md', 'You are a draft agent with its own secrets.')
+ const sha = await c.bundle.freeze(draft.id)
+ await c.revisions.setRevisionState(draft.id, 'ready', sha)
+
+ // Preview JWT bound to (application, draft revision) — no `sec_ovr`.
+ const token = await mintInternalJwt({
+ audience: INTERNAL_JWT_AUDIENCE.INGRESS_PREVIEW,
+ signingKey: DEV_INTERNAL_SIGNING_KEY,
+ claims: { app: application.id, rev: draft.id },
+ ttlSec: 900,
+ })
+
+ const slug = `preview-per-revision-secrets-${draft.id.replace(/-/g, '')}`
+ const res = await request(c.ingress)
+ .post(`/agents/${slug}/run`)
+ .set('x-agent-preview-token', token)
+ .send({ message: 'go' })
+ expect(res.status).toBe(200)
+
+ await c.drain()
+ const session = await c.queue.get(res.body.session_id)
+ expect(session).not.toBeNull()
+ // Routed to the draft, marked preview — the runner's secret resolver
+ // reads the draft revision's `encrypted_env`, so the draft-only
+ // `FOO_API_KEY` is what this session ran with.
+ expect(session!.is_preview).toBe(true)
+ expect(session!.revision_id).toBe(draft.id)
+ })
+
+ it('preview run on the same external_key as a live session does not resume the live session', async () => {
+ // Regression guard: a preview-authed request must never resume a live
+ // session — the runner reads `is_preview` off the session row, so a
+ // shared `(application_id, external_key)` would otherwise drag a
+ // preview request into a `is_preview = false` row and fire live
+ // secrets + un-suppressed external writes. The fix scopes the resume
+ // lookup to the preview/live boundary; this case asserts the
+ // user-facing outcome (two distinct sessions, each with the right
+ // `is_preview` flag).
+ c.setScript([fauxText('live reply'), fauxText('preview reply')])
+ const { application } = await c.deployAgent({ slug: 'preview-iso' })
+
+ // Live session: standard slug, no preview token, an external_key the
+ // preview run will collide with.
+ const liveRes = await request(c.ingress)
+ .post('/agents/preview-iso/run')
+ .send({ message: 'live opens thread', external_key: 'shared-thread-key' })
+ expect(liveRes.status).toBe(200)
+ const liveSessionId = liveRes.body.session_id as string
+ await c.drain()
+
+ // Draft revision routed via `<slug>-<rev-hex>`, preview JWT, same key.
+ const draftSpec = AgentSpecSchema.parse({
+ model: 'faux/faux',
+ triggers: [
+ { type: 'chat', config: {}, auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] } },
+ ],
+ })
+ const draft = await c.revisions.createRevision({
+ application_id: application.id,
+ parent_revision_id: null,
+ created_by_id: null,
+ bundle_uri: `s3://${TEST_S3_BUCKET}/${c.bundlePrefix}/${application.id}/`,
+ spec: draftSpec,
+ })
+ await c.bundle.write(draft.id, 'agent.md', 'Draft agent.')
+ const sha = await c.bundle.freeze(draft.id)
+ await c.revisions.setRevisionState(draft.id, 'ready', sha)
+ const token = await mintInternalJwt({
+ audience: INTERNAL_JWT_AUDIENCE.INGRESS_PREVIEW,
+ signingKey: DEV_INTERNAL_SIGNING_KEY,
+ claims: { app: application.id, rev: draft.id },
+ ttlSec: 900,
+ })
+ const previewSlug = `preview-iso-${draft.id.replace(/-/g, '')}`
+ const previewRes = await request(c.ingress)
+ .post(`/agents/${previewSlug}/run`)
+ .set('x-agent-preview-token', token)
+ .send({ message: 'preview author tests', external_key: 'shared-thread-key' })
+ expect(previewRes.status).toBe(200)
+ const previewSessionId = previewRes.body.session_id as string
+ await c.drain()
+
+ // Distinct sessions, each correctly flagged.
+ expect(previewSessionId).not.toBe(liveSessionId)
+ const liveSession = await c.queue.get(liveSessionId)
+ const previewSession = await c.queue.get(previewSessionId)
+ expect(liveSession!.is_preview).toBe(false)
+ expect(previewSession!.is_preview).toBe(true)
+ expect(previewSession!.revision_id).toBe(draft.id)
+ })
+
+ // Output-adapter and tool-level preview-mode noop branches (slack reply
+ // relay, slack-post-message synthetic `ts`, slack-failure-notifier skip,
+ // `isPreviewSideEffect` helper) live behind simple session.is_preview
+ // checks and are exercised by their own per-service unit tests. An e2e
+ // case that wired up a real Slack tool with encrypted bot tokens, mocked
+ // the slack.com endpoint, and asserted on the absence of a request would
+ // duplicate that coverage without catching any new integration drift —
+ // the seam that's hard to keep right under refactor is the flag flowing
+ // through the queue + analytics, which the cases above cover.
+})
diff --git a/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts b/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts
index cb80a4e95fc6..6abffda07ac2 100644
--- a/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts
@@ -22,6 +22,14 @@
import { createHmac } from 'crypto'
import request from 'supertest'
+import {
+ AgentSpecSchema,
+ DEV_INTERNAL_SIGNING_KEY,
+ INTERNAL_JWT_AUDIENCE,
+ mintInternalJwt,
+ TEST_S3_BUCKET,
+} from '@posthog/agent-shared'
+
import { buildCluster, closeSharedPool, Cluster, fauxCallTool, fauxText } from '../harness'
/** Every signed test below uses the same secret + the matching encrypted_env
@@ -1286,6 +1294,97 @@ describe('slack trigger: real e2e', () => {
await cc.teardown()
}
})
+
+ it('preview-mode: no reactions.add posted when the resolved revision is a draft (slug-rev URL)', async () => {
+ // A Slack event routed to a draft revision via the slug-rev URL
+ // must NOT write to slack.com — preview output adapters no-op so
+ // draft iteration can't touch a real workspace. Matches the
+ // analytics-sink / native-tool isolation contract elsewhere.
+ const { cc, slackCalls } = await ackCluster()
+ try {
+ const { application } = await cc.deployAgent({
+ slug: 'preview-ack',
+ spec: {
+ triggers: [
+ {
+ type: 'slack',
+ config: {
+ mention_only: false,
+ auto_resume_threads: false,
+ ack_reaction: 'eyes',
+ trusted_workspaces: '*',
+ },
+ },
+ ],
+ auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] },
+ },
+ encrypted_env: { ...SLACK_ENV, SLACK_BOT_TOKEN: 'xoxb-preview-ack' },
+ })
+ // Build a non-live draft revision under the same application so
+ // the slug-rev resolver path can pick it as preview.
+ const draftSpec = AgentSpecSchema.parse({
+ model: 'faux/faux',
+ triggers: [
+ {
+ type: 'slack',
+ config: {
+ mention_only: false,
+ auto_resume_threads: false,
+ ack_reaction: 'eyes',
+ trusted_workspaces: '*',
+ },
+ },
+ ],
+ auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] },
+ })
+ const draft = await cc.revisions.createRevision({
+ application_id: application.id,
+ parent_revision_id: null,
+ created_by_id: null,
+ bundle_uri: `s3://${TEST_S3_BUCKET}/${cc.bundlePrefix}/${application.id}/`,
+ spec: draftSpec,
+ encrypted_env: cc.encryption.encrypt(
+ JSON.stringify({ ...SLACK_ENV, SLACK_BOT_TOKEN: 'xoxb-draft' })
+ ),
+ })
+ await cc.bundle.write(draft.id, 'agent.md', 'You are a draft slack agent.')
+ const sha = await cc.bundle.freeze(draft.id)
+ await cc.revisions.setRevisionState(draft.id, 'ready', sha)
+
+ cc.setScript([fauxText('done')])
+ // Non-live revision invokes require a valid preview JWT — the
+ // ingress resolver's preview-gate rejects with 401 otherwise.
+ const previewToken = await mintInternalJwt({
+ audience: INTERNAL_JWT_AUDIENCE.INGRESS_PREVIEW,
+ signingKey: DEV_INTERNAL_SIGNING_KEY,
+ claims: { app: application.id, rev: draft.id },
+ ttlSec: 900,
+ })
+ const slug = `preview-ack-${draft.id.replace(/-/g, '')}`
+ const rawBody = JSON.stringify(
+ slackEvent({ eventType: 'app_mention', text: '<@U0BOT> hi', ts: '900.0' })
+ )
+ const ts = String(Math.floor(Date.now() / 1000))
+ const sig = `v0=${createHmac('sha256', SLACK_SECRET).update(`v0:${ts}:${rawBody}`).digest('hex')}`
+ const res = await request(cc.ingress)
+ .post(`/agents/${slug}/slack/events`)
+ .set('content-type', 'application/json')
+ .set('x-slack-request-timestamp', ts)
+ .set('x-slack-signature', sig)
+ .set('x-agent-preview-token', previewToken)
+ .send(rawBody)
+ expect(res.status).toBe(200)
+ expect(res.body.session_id).toBeTruthy()
+ // Fire-and-forget — drain the microtask queue before asserting absence.
+ await new Promise((r) => setTimeout(r, 50))
+ expect(slackCalls.filter((c) => c.url.endsWith('reactions.add'))).toHaveLength(0)
+ // Preview flag did flow through: confirm the row is_preview=true.
+ const session = await cc.queue.get(res.body.session_id)
+ expect(session!.is_preview).toBe(true)
+ } finally {
+ await cc.teardown()
+ }
+ })
})
describe('allow_workspace_participants', () => {
@@ -1380,6 +1479,90 @@ describe('slack trigger: real e2e', () => {
}
})
+ it('preview-mode: owner-only non-owner reply is rejected but NO chat.postMessage is sent (draft revision)', async () => {
+ // In live mode, an owner-only thread replies in-channel to tell the
+ // wrong user why their message did nothing. Preview-mode draft
+ // revisions must NOT write to slack.com — the elevation outcome is
+ // still returned in the HTTP response body for the author to inspect.
+ const { cc, slackCalls } = await recorderCluster()
+ try {
+ const { application } = await cc.deployAgent({
+ slug: 'preview-owner-only',
+ spec: ownerThreadSpec(false),
+ encrypted_env: { ...SLACK_ENV, SLACK_BOT_TOKEN: 'xoxb-preview-owner-only' },
+ })
+ const draftSpec = AgentSpecSchema.parse({
+ model: 'faux/faux',
+ ...ownerThreadSpec(false),
+ })
+ const draft = await cc.revisions.createRevision({
+ application_id: application.id,
+ parent_revision_id: null,
+ created_by_id: null,
+ bundle_uri: `s3://${TEST_S3_BUCKET}/${cc.bundlePrefix}/${application.id}/`,
+ spec: draftSpec,
+ encrypted_env: cc.encryption.encrypt(
+ JSON.stringify({ ...SLACK_ENV, SLACK_BOT_TOKEN: 'xoxb-draft-owner-only' })
+ ),
+ })
+ await cc.bundle.write(draft.id, 'agent.md', 'You are a draft owner-only agent.')
+ const sha = await cc.bundle.freeze(draft.id)
+ await cc.revisions.setRevisionState(draft.id, 'ready', sha)
+
+ cc.setScript([fauxText('alice first')])
+ // Non-live revision invokes require a valid preview JWT — see
+ // the preview-ack test above for the same pattern. Re-mintable
+ // per request; the harness's `slackPost` doesn't take headers,
+ // so we sign inline.
+ const previewToken = await mintInternalJwt({
+ audience: INTERNAL_JWT_AUDIENCE.INGRESS_PREVIEW,
+ signingKey: DEV_INTERNAL_SIGNING_KEY,
+ claims: { app: application.id, rev: draft.id },
+ ttlSec: 900,
+ })
+ const slug = `preview-owner-only-${draft.id.replace(/-/g, '')}`
+ const signedPreviewSlackPost = async (body: Record<string, unknown>): Promise<request.Response> => {
+ const raw = JSON.stringify(body)
+ const ts = String(Math.floor(Date.now() / 1000))
+ const sig = `v0=${createHmac('sha256', SLACK_SECRET).update(`v0:${ts}:${raw}`).digest('hex')}`
+ return request(cc.ingress)
+ .post(`/agents/${slug}/slack/events`)
+ .set('content-type', 'application/json')
+ .set('x-slack-request-timestamp', ts)
+ .set('x-slack-signature', sig)
+ .set('x-agent-preview-token', previewToken)
+ .send(raw)
+ }
+ const first = await signedPreviewSlackPost(
+ slackEvent({ eventType: 'app_mention', user: 'U-ALICE', text: '<@U0BOT> open', ts: '700.0' })
+ )
+ expect(first.body.session_id).toBeTruthy()
+ await cc.drain()
+
+ const second = await signedPreviewSlackPost(
+ slackEvent({
+ eventType: 'message',
+ user: 'U-BOB',
+ text: 'bob barges in',
+ ts: '701.0',
+ thread_ts: '700.0',
+ })
+ )
+ // Elevation is still signalled in the response body — the gate
+ // logic is unchanged in preview mode, only the side effect is
+ // suppressed.
+ expect(second.body.elevation_required).toBe(true)
+ expect(second.body.resumed).toBe(false)
+ const session = await cc.queue.get(first.body.session_id)
+ expect(session!.is_preview).toBe(true)
+ expect(session!.pending_inputs).toHaveLength(0)
+ // No external slack write in preview mode.
+ expect(slackCalls.filter((c) => c.url.endsWith('chat.postMessage'))).toHaveLength(0)
+ } finally {
+ await cc.teardown()
+ }
+ })
+
it('allow_workspace_participants=true: a non-owner advances the same thread (no elevation, no rejection reply)', async () => {
const { cc, slackCalls } = await recorderCluster()
try {
diff --git a/products/agent_platform/services/agent-tests/src/harness/cluster.ts b/products/agent_platform/services/agent-tests/src/harness/cluster.ts
index 3f4ced012f71..04b81d827c2f 100644
--- a/products/agent_platform/services/agent-tests/src/harness/cluster.ts
+++ b/products/agent_platform/services/agent-tests/src/harness/cluster.ts
@@ -54,6 +54,7 @@ import {
RedisSessionEventBus,
S3BundleStore,
S3JsonlTabularStore,
+ DEV_INTERNAL_SIGNING_KEY,
EncryptedEnvSecretResolver,
EncryptedFields,
HttpClient,
@@ -458,6 +459,11 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
// slack.com calls from the ingress (ack_reaction, identity bridge)
// can route them through a single recorder.
http: opts.http,
+ // Wire the JWT gate so preview-mode tests exercise the real claim
+ // verification (audience, signature, app/rev binding). Without this the
+ // resolver short-circuits and a non-live revision routes without a
+ // token. Same key `mintInternalJwt` uses in the preview-mode fixtures.
+ internalSigningKey: DEV_INTERNAL_SIGNING_KEY,
})
const janitor = buildJanitorApp({
diff --git a/products/agent_platform/services/agent-tools/src/test-helpers.ts b/products/agent_platform/services/agent-tools/src/test-helpers.ts
index 046898f965bb..ff139e1951a1 100644
--- a/products/agent_platform/services/agent-tools/src/test-helpers.ts
+++ b/products/agent_platform/services/agent-tools/src/test-helpers.ts
@@ -15,6 +15,7 @@ export function makeCtx(overrides?: Partial<ToolContext>): ToolContext {
},
http: new HttpClient(),
posthogApiBaseUrl: DEFAULT_POSTHOG_API_BASE_URL,
+ isPreview: false,
...overrides,
}
}
@@ -36,6 +37,7 @@ export function makeCapturingCtx(): {
},
http: new HttpClient(),
posthogApiBaseUrl: DEFAULT_POSTHOG_API_BASE_URL,
+ isPreview: false,
}
return { ctx, logs }
}
diff --git a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.test.ts
index 47600c88efdd..4aabc56859b3 100644
--- a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.test.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.test.ts
@@ -462,4 +462,44 @@ describe('@posthog/http-request', () => {
).rejects.toThrow(/http_request_timeout: 50ms/)
})
})
+
+ describe('preview-mode side-effect guard', () => {
+ it.each(['POST', 'PUT', 'PATCH', 'DELETE'] as const)(
+ 'short-circuits %s in preview and never reaches the wire',
+ async (method) => {
+ const { http, lastCall } = captureFetch(fakeResponse({ status: 200 }))
+ const out = await httpRequestV1.run(
+ { url: 'https://example.com/x', method },
+ makeCtx({ http, isPreview: true })
+ )
+ // `captureFetch` only writes `lastCall.url` when fetch is hit.
+ expect(lastCall.url).toBeUndefined()
+ expect(out).toEqual({
+ status: 204,
+ body: '',
+ content_type: '',
+ headers: {},
+ url: 'https://example.com/x',
+ truncated: false,
+ })
+ }
+ )
+
+ it('lets GET through in preview — reads have no external side effect', async () => {
+ const { http, lastCall } = captureFetch(fakeResponse({ status: 200, text: 'ok' }))
+ const out = await httpRequestV1.run(
+ { url: 'https://example.com/x', method: 'GET' },
+ makeCtx({ http, isPreview: true })
+ )
+ expect(lastCall.init?.method).toBe('GET')
+ expect(out.status).toBe(200)
+ expect(out.body).toBe('ok')
+ })
+
+ it('still dispatches mutating methods normally outside preview', async () => {
+ const { http, lastCall } = captureFetch(fakeResponse({ status: 201 }))
+ await httpRequestV1.run({ url: 'https://example.com/x', method: 'POST', body: { a: 1 } }, makeCtx({ http }))
+ expect(lastCall.init?.method).toBe('POST')
+ })
+ })
})
diff --git a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts
index 940328c972e3..e6dbe465e6d3 100644
--- a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts
@@ -26,7 +26,7 @@
* API."
*/
-import { defineNativeTool, secretHostMatches, type ToolContext, Type } from '@posthog/agent-shared'
+import { defineNativeTool, isPreviewSideEffect, secretHostMatches, type ToolContext, Type } from '@posthog/agent-shared'
import { parseFetchableUrl } from './http-url'
@@ -290,6 +290,18 @@ export const httpRequestV1 = defineNativeTool({
// IP filtering).
const { url, host } = substituteUrlAndExtractHost(args.url, ctx)
const method = args.method ?? 'GET'
+ // Preview-mode noop for mutating methods: a draft revision shouldn't
+ // be able to POST/PUT/PATCH/DELETE against external systems while the
+ // author iterates. GET is read-only and passes through so the author
+ // can still verify their read-path logic. (The schema only enumerates
+ // GET/POST/PUT/PATCH/DELETE — HEAD/OPTIONS never reach here, so a
+ // simple `!= 'GET'` correctly covers every mutating verb.) The
+ // synthetic 204 lets the model's next turn see a successful call and
+ // keep reasoning naturally, matching the slack write tools' shape.
+ const isMutating = method !== 'GET'
+ if (isMutating && isPreviewSideEffect(ctx, '@posthog/http-request', args)) {
+ return { status: 204, body: '', content_type: '', headers: {}, url, truncated: false }
+ }
const headersIn = substituteHeaders(args.headers, host, ctx)
const { body, headers: finalHeaders } = serializeBody(args.body, headersIn, host, ctx)
const maxBytes = args.max_response_bytes ?? DEFAULT_MAX_RESPONSE_BYTES
diff --git a/products/agent_platform/services/agent-tools/src/tools/memory.test.ts b/products/agent_platform/services/agent-tools/src/tools/memory.test.ts
index cd87c596444d..9ec8b945aa7d 100644
--- a/products/agent_platform/services/agent-tools/src/tools/memory.test.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/memory.test.ts
@@ -4,11 +4,12 @@
* SeaweedFS before running.
*/
import { S3Client } from '@aws-sdk/client-s3'
-import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import {
buildTestStore,
HttpClient,
+ MemoryStore,
newTestPrefix,
S3MemoryStore,
type ToolContext,
@@ -28,6 +29,7 @@ function makeCtx(store: S3MemoryStore | undefined): ToolContext {
memoryStore: store,
http: new HttpClient(),
posthogApiBaseUrl: 'http://localhost:8010',
+ isPreview: false,
}
}
@@ -240,3 +242,94 @@ describe('memory tools (real S3 / SeaweedFS)', () => {
})
})
})
+
+describe('memory tools — preview-mode side-effect isolation', () => {
+ /** Mutating tools must short-circuit before touching the store when the
+ * session is in preview mode: the store is keyed on (team_id,
+ * application_id) and not forked per revision, so a draft would otherwise
+ * mutate the same files the live revision reads. Each test pins a
+ * store-method spy and asserts it is never called. */
+ function previewCtxWithSpy(): { ctx: ToolContext; store: MemoryStore } {
+ const spied: MemoryStore = {
+ list: vi.fn(),
+ read: vi.fn(),
+ readHeader: vi.fn(),
+ put: vi.fn(),
+ delete: vi.fn(),
+ exists: vi.fn(),
+ }
+ const ctx: ToolContext = {
+ teamId: 42,
+ applicationId: 'app-test',
+ sessionId: 'sess-preview',
+ secret: () => undefined,
+ secretAllowedHosts: () => undefined,
+ log: () => undefined,
+ memoryStore: spied,
+ http: new HttpClient(),
+ posthogApiBaseUrl: 'http://localhost:8010',
+ isPreview: true,
+ }
+ return { ctx, store: spied }
+ }
+
+ it('memory-write returns a synthetic created_at and never calls store.put', async () => {
+ const { ctx, store: spied } = previewCtxWithSpy()
+ const r = (await memoryWriteV1.run(
+ { path: 'incidents/db.md', description: 'd', content: 'c' },
+ ctx
+ )) as Envelope
+ expect(r.ok).toBe(true)
+ const data = r.data as { path: string; created_at: string }
+ expect(data.path).toBe('incidents/db.md')
+ expect(data.created_at).toMatch(/^\d{4}-\d{2}-\d{2}T/)
+ expect(spied.put).not.toHaveBeenCalled()
+ })
+
+ it('memory-update returns a synthetic updated_at and never calls store.put / store.read', async () => {
+ const { ctx, store: spied } = previewCtxWithSpy()
+ const r = (await memoryUpdateV1.run({ path: 'notes/x.md', description: 'new' }, ctx)) as Envelope
+ expect(r.ok).toBe(true)
+ const data = r.data as { path: string; updated_at: string }
+ expect(data.path).toBe('notes/x.md')
+ expect(data.updated_at).toMatch(/^\d{4}-\d{2}-\d{2}T/)
+ expect(spied.read).not.toHaveBeenCalled()
+ expect(spied.put).not.toHaveBeenCalled()
+ })
+
+ it('memory-delete returns deleted=true and never calls store.delete', async () => {
+ const { ctx, store: spied } = previewCtxWithSpy()
+ const r = (await memoryDeleteV1.run({ path: 'incidents/db.md' }, ctx)) as Envelope
+ expect(r.ok).toBe(true)
+ expect(r.data).toEqual({ path: 'incidents/db.md', deleted: true })
+ expect(spied.delete).not.toHaveBeenCalled()
+ })
+
+ it('read tools (list / search / read) still touch the store in preview — reads have no live-state effect', async () => {
+ // Author must be able to verify the read paths during preview;
+ // only writes are gated. Pinning this guards against an accidental
+ // future overgeneralization that would block reads too.
+ const previewStore: MemoryStore = {
+ list: vi.fn().mockResolvedValue([]),
+ read: vi.fn().mockRejectedValue(new Error('not found')),
+ readHeader: vi.fn(),
+ put: vi.fn(),
+ delete: vi.fn(),
+ exists: vi.fn(),
+ }
+ const ctx: ToolContext = {
+ teamId: 42,
+ applicationId: 'app-test',
+ sessionId: 'sess-preview',
+ secret: () => undefined,
+ secretAllowedHosts: () => undefined,
+ log: () => undefined,
+ memoryStore: previewStore,
+ http: new HttpClient(),
+ posthogApiBaseUrl: 'http://localhost:8010',
+ isPreview: true,
+ }
+ await memoryListV1.run({}, ctx)
+ expect(previewStore.list).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/products/agent_platform/services/agent-tools/src/tools/memory.ts b/products/agent_platform/services/agent-tools/src/tools/memory.ts
index 6a721d41157b..15fa7cc431a0 100644
--- a/products/agent_platform/services/agent-tools/src/tools/memory.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/memory.ts
@@ -17,6 +17,7 @@
import {
defineNativeTool,
+ isPreviewSideEffect,
MAX_DESCRIPTION_LEN,
MemoryConflictError,
MemoryFile,
@@ -176,6 +177,16 @@ export const memoryReadV1 = defineNativeTool({
// =====================================================================
// MUTATING TOOLS — requires_approval=true by default
// (set via the spec.tools entry; the tool def itself doesn't carry the flag)
+//
+// Each mutating tool short-circuits in preview mode via `isPreviewSideEffect`
+// and returns a shape-valid synthetic envelope. The memory store is scoped on
+// `(team_id, application_id)` and not forked per revision, so without this
+// gate a draft revision's `memory-write`/`memory-update`/`memory-delete` would
+// mutate the same files the live revision reads. The approval gate (which
+// fires before `run`) doesn't help — a human approver in preview would still
+// reach this code path and hit live storage. The synthetic response shape
+// matches the live one so the model's next turn keeps reasoning naturally;
+// `tool_preview_skipped` lands in the log for the author to inspect.
// =====================================================================
export const memoryWriteV1 = defineNativeTool({
@@ -204,6 +215,9 @@ export const memoryWriteV1 = defineNativeTool({
if ('error' in s) {
return err(s.error)
}
+ if (isPreviewSideEffect(ctx, '@posthog/memory-write', args)) {
+ return ok({ path: args.path, created_at: new Date().toISOString() })
+ }
try {
validateMemoryPath(args.path)
validateForWrite({ description: args.description, tags: args.tags })
@@ -241,6 +255,9 @@ export const memoryUpdateV1 = defineNativeTool({
if ('error' in s) {
return err(s.error)
}
+ if (isPreviewSideEffect(ctx, '@posthog/memory-update', args)) {
+ return ok({ path: args.path, updated_at: new Date().toISOString() })
+ }
try {
validateMemoryPath(args.path)
const existing = await s.read(scope(ctx), args.path)
@@ -278,6 +295,9 @@ export const memoryDeleteV1 = defineNativeTool({
if ('error' in s) {
return err(s.error)
}
+ if (isPreviewSideEffect(ctx, '@posthog/memory-delete', args)) {
+ return ok({ path: args.path, deleted: true })
+ }
try {
validateMemoryPath(args.path)
await s.delete(scope(ctx), args.path)
diff --git a/products/agent_platform/services/agent-tools/src/tools/slack.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/slack.v1.test.ts
index 856f9839e2fc..a4bde4a3529b 100644
--- a/products/agent_platform/services/agent-tools/src/tools/slack.v1.test.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/slack.v1.test.ts
@@ -244,4 +244,60 @@ describe('slack.* tools', () => {
/missing_charset.*missing required field: ts/
)
})
+
+ describe('preview-mode side-effect isolation', () => {
+ /** A preview-mode ctx — every write-side slack tool must short-circuit
+ * without touching http.fetch when this is set, so an iterating
+ * author can never reach a real Slack workspace. */
+ function previewCtx(fetchSpy: ReturnType<typeof vi.fn>): ToolContext {
+ return makeCtx({
+ http: { fetch: fetchSpy as unknown as HttpFetcher['fetch'] },
+ secret: (name) => (name === 'SLACK_BOT_TOKEN' ? 'xoxb-real-but-must-not-be-used' : undefined),
+ isPreview: true,
+ })
+ }
+
+ it('slack-post-message returns a synthetic shape-valid envelope and never calls http.fetch', async () => {
+ const fetchSpy = vi.fn()
+ const out = await slackPostMessageV1.run({ channel: 'C01', text: 'hi' }, previewCtx(fetchSpy))
+ expect(out.channel).toBe('C01')
+ expect(out.ts).toMatch(/^preview-noop:\d+$/)
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+
+ it('slack-update-message returns ok and never calls http.fetch', async () => {
+ const fetchSpy = vi.fn()
+ const out = await slackUpdateMessageV1.run(
+ { channel: 'C01', ts: '123.456', text: 'edit' },
+ previewCtx(fetchSpy)
+ )
+ expect(out).toEqual({ ok: true })
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+
+ it('slack-react returns ok and never calls http.fetch', async () => {
+ const fetchSpy = vi.fn()
+ const out = await slackReactV1.run({ channel: 'C01', ts: '123.456', name: 'fire' }, previewCtx(fetchSpy))
+ expect(out).toEqual({ ok: true })
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+
+ it('read tools (read-channel / read-thread) still hit http.fetch in preview — reads have no external side effect', async () => {
+ // Authors must be able to verify their read paths during preview;
+ // only writes are gated. Pinning this guards against an accidental
+ // future overgeneralization that would block reads too.
+ const fetchSpy = vi.fn(
+ async () =>
+ ({
+ ok: true,
+ status: 200,
+ json: async () => ({ ok: true, messages: [], has_more: false }),
+ }) as unknown as Response
+ )
+ await slackReadChannelV1.run({ channel: 'C01' }, previewCtx(fetchSpy))
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
+ await slackReadThreadV1.run({ channel: 'C01', thread_ts: '111.222' }, previewCtx(fetchSpy))
+ expect(fetchSpy).toHaveBeenCalledTimes(2)
+ })
+ })
})
diff --git a/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts b/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts
index 63372fe563f7..21d109d3717d 100644
--- a/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts
@@ -1,4 +1,11 @@
-import { defineNativeTool, HttpFetcher, SLACK_BOT_TOKEN_KEY, ToolContext, Type } from '@posthog/agent-shared'
+import {
+ defineNativeTool,
+ HttpFetcher,
+ isPreviewSideEffect,
+ SLACK_BOT_TOKEN_KEY,
+ ToolContext,
+ Type,
+} from '@posthog/agent-shared'
/**
* Resolve the agent's Slack bot token from `encrypted_env` via `ctx.secret`.
@@ -123,6 +130,15 @@ export const slackPostMessageV1 = defineNativeTool({
requires: { provider: { id: 'slack', scopes: ['chat:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
+ // Preview-mode noop: don't post into the real channel attached to the
+ // live revision while the author is iterating. The synthetic `ts` is
+ // shape-valid so a follow-up `slack-update-message` / `slack-react`
+ // in the same preview turn doesn't blow up on a missing ts — though
+ // those write tools also short-circuit on preview, so the synthetic
+ // value never reaches slack.com regardless.
+ if (isPreviewSideEffect(ctx, '@posthog/slack-post-message', args)) {
+ return { ts: `preview-noop:${Date.now()}`, channel: args.channel }
+ }
const token = slackBotToken(ctx)
const res = (await slackCall(ctx.http, token, 'chat.postMessage', {
channel: args.channel,
@@ -145,6 +161,9 @@ export const slackUpdateMessageV1 = defineNativeTool({
requires: { provider: { id: 'slack', scopes: ['chat:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
+ if (isPreviewSideEffect(ctx, '@posthog/slack-update-message', args)) {
+ return { ok: true }
+ }
const token = slackBotToken(ctx)
await slackCall(ctx.http, token, 'chat.update', { channel: args.channel, ts: args.ts, text: args.text })
return { ok: true }
@@ -249,6 +268,9 @@ export const slackReactV1 = defineNativeTool({
requires: { provider: { id: 'slack', scopes: ['reactions:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
+ if (isPreviewSideEffect(ctx, '@posthog/slack-react', args)) {
+ return { ok: true }
+ }
const token = slackBotToken(ctx)
await slackCall(ctx.http, token, 'reactions.add', {
channel: args.channel,
diff --git a/products/agent_platform/services/agent-tools/src/tools/table.test.ts b/products/agent_platform/services/agent-tools/src/tools/table.test.ts
new file mode 100644
index 000000000000..51c374444619
--- /dev/null
+++ b/products/agent_platform/services/agent-tools/src/tools/table.test.ts
@@ -0,0 +1,83 @@
+/**
+ * Table-tool tests — focused on preview-mode side-effect isolation. End-to-end
+ * tabular behavior (membership, append, query, count, delete, truncate) is
+ * covered by `agent-shared/src/memory/tabular-store.test.ts` against a real
+ * S3 backend; this file exists to pin that mutating table tools short-circuit
+ * before touching the store when the session is in preview mode.
+ */
+import { describe, expect, it, vi } from 'vitest'
+
+import { HttpClient, type TabularStore, type ToolContext } from '@posthog/agent-shared'
+
+import { tableAppendV1, tableCountV1, tableDeleteV1, tableTruncateV1 } from './table'
+
+interface Envelope {
+ ok: boolean
+ error?: string
+ code?: string
+ data?: Record<string, unknown>
+}
+
+function previewCtxWithSpy(): { ctx: ToolContext; store: TabularStore } {
+ // The store is keyed on (team_id, application_id) and not forked per
+ // revision, so a draft preview would otherwise hit the same table the
+ // live revision reads — assert each spy stays untouched.
+ const spied: TabularStore = {
+ listTables: vi.fn().mockResolvedValue([]),
+ membership: vi.fn(),
+ append: vi.fn(),
+ query: vi.fn(),
+ queryPage: vi.fn(),
+ count: vi.fn().mockResolvedValue(0),
+ delete: vi.fn(),
+ truncate: vi.fn(),
+ }
+ const ctx: ToolContext = {
+ teamId: 42,
+ applicationId: 'app-test',
+ sessionId: 'sess-preview',
+ secret: () => undefined,
+ secretAllowedHosts: () => undefined,
+ log: () => undefined,
+ tabularStore: spied,
+ http: new HttpClient(),
+ posthogApiBaseUrl: 'http://localhost:8010',
+ isPreview: true,
+ }
+ return { ctx, store: spied }
+}
+
+describe('table tools — preview-mode side-effect isolation', () => {
+ it('table-append returns synthetic counts ({appended: rows.length, skipped: 0}) and never calls store.append', async () => {
+ const { ctx, store: spied } = previewCtxWithSpy()
+ const r = (await tableAppendV1.run({ table: 'seen', rows: [{ id: 1 }, { id: 2 }, { id: 3 }] }, ctx)) as Envelope
+ expect(r.ok).toBe(true)
+ expect(r.data).toEqual({ appended: 3, skipped: 0 })
+ expect(spied.append).not.toHaveBeenCalled()
+ })
+
+ it('table-delete returns deleted=0 and never calls store.delete', async () => {
+ const { ctx, store: spied } = previewCtxWithSpy()
+ const r = (await tableDeleteV1.run({ table: 'seen', where: { id: 1 } }, ctx)) as Envelope
+ expect(r.ok).toBe(true)
+ expect(r.data).toEqual({ deleted: 0 })
+ expect(spied.delete).not.toHaveBeenCalled()
+ })
+
+ it('table-truncate returns truncated=<table> and never calls store.truncate', async () => {
+ const { ctx, store: spied } = previewCtxWithSpy()
+ const r = (await tableTruncateV1.run({ table: 'seen' }, ctx)) as Envelope
+ expect(r.ok).toBe(true)
+ expect(r.data).toEqual({ truncated: 'seen' })
+ expect(spied.truncate).not.toHaveBeenCalled()
+ })
+
+ it('read tools (count / query / membership) still hit the store in preview — reads have no live-state effect', async () => {
+ // Author must be able to verify the read paths during preview;
+ // only writes are gated. Pinning this guards against an accidental
+ // future overgeneralization that would block reads too.
+ const { ctx, store: spied } = previewCtxWithSpy()
+ await tableCountV1.run({ table: 'seen' }, ctx)
+ expect(spied.count).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/products/agent_platform/services/agent-tools/src/tools/table.ts b/products/agent_platform/services/agent-tools/src/tools/table.ts
index 160389391e2a..d0f4899d5a0b 100644
--- a/products/agent_platform/services/agent-tools/src/tools/table.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/table.ts
@@ -17,6 +17,7 @@
import {
defineNativeTool,
+ isPreviewSideEffect,
TabularConflictError,
type TableQuery,
type TabularStore,
@@ -109,6 +110,9 @@ export const tableAppendV1 = defineNativeTool({
if ('error' in s) {
return err(s.error, 'unavailable')
}
+ if (isPreviewSideEffect(ctx, '@posthog/table-append', args)) {
+ return ok({ appended: args.rows.length, skipped: 0 })
+ }
try {
const res = await s.append(scope(ctx), args.table, args.rows, { dedupeOn: args.dedupe_on })
return ok(res)
@@ -182,6 +186,11 @@ export const tableDeleteV1 = defineNativeTool({
if ('error' in s) {
return err(s.error, 'unavailable')
}
+ if (isPreviewSideEffect(ctx, '@posthog/table-delete', args)) {
+ // We can't know how many rows the filter would have matched without
+ // touching the live store; a zero count is the safe synthetic.
+ return ok({ deleted: 0 })
+ }
try {
return ok(await s.delete(scope(ctx), args.table, args.where as Where))
} catch (e) {
@@ -201,6 +210,9 @@ export const tableTruncateV1 = defineNativeTool({
if ('error' in s) {
return err(s.error, 'unavailable')
}
+ if (isPreviewSideEffect(ctx, '@posthog/table-truncate', args)) {
+ return ok({ truncated: args.table })
+ }
try {
await s.truncate(scope(ctx), args.table)
return ok({ truncated: args.table })
diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yaml
index 12238061d9f3..e28970e68960 100644
--- a/services/mcp/definitions/agent_platform.yaml
+++ b/services/mcp/definitions/agent_platform.yaml
@@ -160,6 +160,9 @@ tools:
agent-applications-preview-token:
operation: agent_applications_preview_token
enabled: false
+ agent-applications-preview-token-mint:
+ operation: agent_applications_preview_token_mint
+ enabled: false
agent-applications-retrieve:
operation: agent_applications_retrieve
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 07f531f88726..5852d7e4e2d2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7554,6 +7554,8 @@ export namespace Schemas {
team_id: number;
/** Revision the gated call was proposed against. */
revision_id: string;
+ /** Mirrors the owning session's `is_preview`. True when the request originated from a draft revision running in preview mode — render a preview badge in the approvals queue so reviewers can tell author-iteration approvals apart from production traffic. */
+ is_preview: boolean;
/** Turn number within the session that emitted the call. */
turn: number;
/** pi-ai ToolCall.id from the original assistant message; matched into the synthetic tool_result. */
@@ -7731,6 +7733,8 @@ export namespace Schemas {
*/
preview: string | null;
retry_count: number;
+ /** True when the session ran against a draft revision in preview mode. Output adapters (Slack writes, failure notifier) no-op; `$ai_*` analytics events are tagged with `$agent_is_preview: true`. Surface a preview badge on the row so authors can distinguish iteration from live traffic. */
+ is_preview: boolean;
created_at: string;
updated_at: string;
}
@@ -7844,6 +7848,8 @@ export namespace Schemas {
pending_inputs: AgentConversationMessage[];
/** Times the janitor has re-queued this session after a stuck-running detection. */
retry_count: number;
+ /** True when the session ran against a draft revision in preview mode. Output adapters (Slack writes, failure notifier) no-op; `$ai_*` analytics events are tagged with `$agent_is_preview: true`. Surface a preview badge on session detail so authors can distinguish iteration from live traffic. */
+ is_preview: boolean;
created_at: string;
updated_at: string;
/** True when `?last_n=` was supplied AND the full conversation exceeded it. */
@@ -7917,6 +7923,8 @@ export namespace Schemas {
* @nullable
*/
preview: string | null;
+ /** True when the session ran against a draft revision in preview mode. Output adapters (Slack writes, failure notifier) no-op; `$ai_*` analytics events are tagged with `$agent_is_preview: true`. Render a preview badge on the row so author iteration is distinguishable from live traffic. */
+ is_preview: boolean;
created_at: string;
updated_at: string;
}
@@ -57185,6 +57193,13 @@ export namespace Schemas {
revision_id: string;
};
+ export type AgentApplicationsPreviewTokenMintParams = {
+ /**
+ * Target draft revision. Must belong to this application and not be live.
+ */
+ revision_id: string;
+ };
+
export type AgentApplicationsSessionsListParams = {
/**
* ISO datetime — return sessions with created_at >= this.