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.

chore(agent_platform): remove is_preview session marker, keep draft preview (#65978)

Ben White40d065246702
diff --git a/products/agent_platform/backend/migrations/0010_remove_is_preview_state_only.py b/products/agent_platform/backend/migrations/0010_remove_is_preview_state_only.py
new file mode 100644
index 000000000000..93b469bb21d1
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0010_remove_is_preview_state_only.py
@@ -0,0 +1,34 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ """Phase 1 of dropping `is_preview` from agent_session + agent_tool_approval_request.
+
+ State-only: Django stops naming the column, the column stays in the DB. A
+ follow-up PR — landed only after this deploy has fully rolled out — adds
+ the matching `ALTER TABLE ... DROP COLUMN` migration. Splitting the phases
+ across deploys is what lets a rolling deploy run new code against the old
+ column without 5xx: old replicas still see a column they can safely INSERT
+ into while the new code never names it; the column drop then runs after
+ the last old replica is gone.
+
+ The preview-token flow itself is unchanged — an authed user can still
+ preview an unpublished draft revision. What this removes is only the
+ `is_preview` session marker and the side-effect suppression it drove; a
+ preview run now executes real tool calls and side effects, exactly like a
+ live run, differing only in which revision handles the request.
+ """
+
+ dependencies = [
+ ("agent_platform", "0009_agentsession_agenttoolapprovalrequest_is_preview"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(model_name="agentsession", name="is_preview"),
+ migrations.RemoveField(model_name="agenttoolapprovalrequest", name="is_preview"),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/max_migration.txt b/products/agent_platform/backend/migrations/max_migration.txt
index 4c9a8017a3d9..6f2720731c92 100644
--- a/products/agent_platform/backend/migrations/max_migration.txt
+++ b/products/agent_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0009_agentsession_agenttoolapprovalrequest_is_preview
+0010_remove_is_preview_state_only
diff --git a/products/agent_platform/backend/models.py b/products/agent_platform/backend/models.py
index a4b38f684a10..1de9d814f08f 100644
--- a/products/agent_platform/backend/models.py
+++ b/products/agent_platform/backend/models.py
@@ -177,13 +177,6 @@ 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(
@@ -281,13 +274,6 @@ 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 34f219ce1908..85acdbe870d2 100644
--- a/products/agent_platform/backend/presentation/views.py
+++ b/products/agent_platform/backend/presentation/views.py
@@ -1011,14 +1011,6 @@ 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(),
},
@@ -1229,14 +1221,6 @@ 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(
@@ -1349,13 +1333,6 @@ 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."
@@ -2967,14 +2944,6 @@ 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/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.ts
index ce4e634e4b37..a374360734ad 100644
--- a/products/agent_platform/frontend/generated/api.schemas.ts
+++ b/products/agent_platform/frontend/generated/api.schemas.ts
@@ -1275,8 +1275,6 @@ 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. */
@@ -1497,8 +1495,6 @@ 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
}
@@ -1614,8 +1610,6 @@ 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. */
@@ -1713,8 +1707,6 @@ 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
}
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 6c129268aeac..677ef9b54cb3 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,7 +54,6 @@ 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 945e41bb8cb6..f329595cdc60 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,13 +213,11 @@ 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.
+ it('isolates by revision: a request for a draft does not resume a session on another revision sharing the external_key', async () => {
+ // Resume is revision-scoped. `findByExternalKey` matches only sessions
+ // on the request's revision, so a draft-preview request can't resume a
+ // session created on the live (or a different draft) revision under the
+ // same external_key — it opens its own session instead.
const queue = new PgSessionQueue(pool)
const { app, rev } = makePair()
const draftRev: AgentRevision = { ...rev, id: randomUUID(), state: 'draft' }
@@ -232,7 +230,6 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: 'live opens thread', timestamp: Date.now() },
principal: ALICE,
trigger: 'slack',
- isPreview: false,
}
)
const preview = await enqueueOrResume(
@@ -244,21 +241,18 @@ describe('enqueueOrResume', () => {
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.
+ // The new session is its own row on 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.
+ // A second request on the same key + same (live) revision resumes the
+ // live row — the draft row doesn't poach it.
const liveAgain = await enqueueOrResume(
{ queue },
{
@@ -268,13 +262,12 @@ describe('enqueueOrResume', () => {
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.
+ // Two different draft revisions on 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 },
@@ -285,7 +278,6 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: 'other draft', timestamp: Date.now() },
principal: ALICE,
trigger: 'slack',
- isPreview: true,
}
)
expect(otherPreview.kind).toBe('created')
@@ -321,9 +313,7 @@ describe('enqueueOrResume', () => {
}
)
}
- const session = await queue.get(
- (await queue.findByExternalKey(app.id, 'slack:C01:thread5', { isPreview: false, revisionId: rev.id }))!.id
- )
+ const session = await queue.get((await queue.findByExternalKey(app.id, 'slack:C01:thread5', 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 9b48c3d9c196..020b108d212d 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
@@ -87,16 +87,6 @@ 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 =
@@ -139,17 +129,12 @@ async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Pro
}
}
if (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,
- })
+ // Scope the lookup to the resolved revision so a request routed to one
+ // revision can't resume a session created on another. A draft-preview
+ // request resumes only the draft it targeted (never the live session
+ // under a shared external_key), and two draft revisions previewed under
+ // the same external_key stay isolated.
+ const existing = await deps.queue.findByExternalKey(input.application.id, input.externalKey, 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)
@@ -196,7 +181,6 @@ 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 10d08f37ee58..489c3fa9a395 100644
--- a/products/agent_platform/services/agent-ingress/src/routing/resolver.ts
+++ b/products/agent_platform/services/agent-ingress/src/routing/resolver.ts
@@ -38,11 +38,11 @@ export interface ResolvedAgent {
* `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.
+ * by the time this is set on a non-live resolution, so the field also
+ * means "the request was authenticated for preview." Purely a routing /
+ * auth classification: a preview run against a draft executes exactly
+ * like a live one — real tool calls, real side effects, real session
+ * state — the only difference is which revision handles the request.
*/
isPreview: boolean
/**
diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts b/products/agent_platform/services/agent-ingress/src/routing/server.test.ts
index afcaef5b31dc..b77fe722d175 100644
--- a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts
+++ b/products/agent_platform/services/agent-ingress/src/routing/server.test.ts
@@ -797,7 +797,6 @@ describe('ingress HTTP server (path mode)', () => {
proposed_args: { x: 1 },
assistant_message: { role: 'assistant', content: [{ type: 'text', text: '' }], timestamp: Date.now() },
approver_scope: { type: opts.type, allow_edit: false },
- is_preview: false,
expires_at: new Date(Date.now() + 60_000).toISOString(),
})
return id
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 9a1eeb25fb9b..9cde9baf4610 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
@@ -48,7 +48,6 @@ 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') {
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 f42fa93a9593..1b401820cedb 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts
@@ -240,7 +240,6 @@ 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 f94c9eedd57d..3f938dc31ae7 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,7 +48,6 @@ 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 3a3bf0b96a4b..f5f6b1caad16 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
@@ -164,13 +164,10 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {
res.json({ ok: true, dropped: 'mention_only' })
return
}
- // 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,
- })
+ // Mention-only continuity is revision-scoped: a mention into a thread
+ // whose only owned session is on another revision must not
+ // short-circuit. Same scope as `enqueueOrResume`.
+ const existing = await deps.queue.findByExternalKey(resolved.application.id, externalKey, resolved.revision.id)
if (!existing) {
log.info(
{ slug: resolved.application.slug, channel: event.channel, thread_ts: event.thread_ts },
@@ -186,34 +183,23 @@ 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) {
- if (resolved.isPreview) {
- log.info(
- { slug: resolved.application.slug, channel: event.channel, ts: event.ts, reaction: ackReaction },
- 'ack_reaction_skipped_preview'
+ 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 {
- 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')
}
@@ -280,7 +266,6 @@ 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') {
@@ -288,27 +273,13 @@ 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.
- //
- // 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.',
- })
- }
+ 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 9d5266f06112..cb79c2213109 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts
@@ -39,7 +39,6 @@ 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 d5294b945dee..47b14e1eb9c2 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
@@ -352,10 +352,7 @@ 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', {
- isPreview: false,
- revisionId: rev.id,
- })
+ const byExternal = await queue.findByExternalKey(app.id, 'digest-2026-W23', 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 8b63ebf85eb0..a49cef390ecd 100644
--- a/products/agent_platform/services/agent-janitor/src/server.test.ts
+++ b/products/agent_platform/services/agent-janitor/src/server.test.ts
@@ -79,7 +79,6 @@ 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 fe36afbf17b0..e18311ebbf80 100644
--- a/products/agent_platform/services/agent-janitor/src/server.ts
+++ b/products/agent_platform/services/agent-janitor/src/server.ts
@@ -424,7 +424,6 @@ 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,
}))
@@ -482,7 +481,6 @@ 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,
}))
@@ -610,11 +608,6 @@ 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 f055936640cb..0d905a3e0547 100644
--- a/products/agent_platform/services/agent-janitor/src/sweep.test.ts
+++ b/products/agent_platform/services/agent-janitor/src/sweep.test.ts
@@ -70,7 +70,6 @@ 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 97576f5cae8e..f399e70f2830 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,7 +40,6 @@ 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 0e6a090e936c..27a0a806dbbe 100644
--- a/products/agent_platform/services/agent-runner/src/loop/approval.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/approval.ts
@@ -100,9 +100,6 @@ 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 7e10becabfa6..1d8a71458e8d 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,7 +130,6 @@ 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',
@@ -358,38 +357,6 @@ 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 81e30411bc85..8281d56a7566 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
@@ -37,7 +37,6 @@ import {
getSecretAllowedHosts,
HttpFetcher,
IdentityAuthRequiredError,
- isPreviewSideEffect,
MemoryStore,
TabularStore,
Sandbox,
@@ -299,7 +298,7 @@ export async function buildAgentTools(rev: AgentRevision, deps: AgentToolDeps):
continue
}
seen.add(exposedName)
- tools.push(makeMcpTool(exposedName, client, remote, deps))
+ tools.push(makeMcpTool(exposedName, client, remote))
}
}
}
@@ -409,16 +408,6 @@ 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
@@ -499,8 +488,7 @@ function makeClientTool(
function makeMcpTool(
exposedName: string,
client: OpenedMcp,
- remote: RemoteMcpTool,
- deps: AgentToolDeps
+ remote: RemoteMcpTool
): AgentTool<TSchema, ToolResultDetails> {
return {
name: exposedName,
@@ -509,18 +497,6 @@ function makeMcpTool(
parameters: remote.inputSchema as TSchema,
execute: async (_callId, args): Promise<AgentToolResult<ToolResultDetails>> => {
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
@@ -579,7 +555,6 @@ 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 c3fa19d83e9d..90f54cdf815f 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
@@ -94,7 +94,6 @@ 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 4fcbc78b9998..db9fa778e708 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts
@@ -253,14 +253,10 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
// much so it replies in natural language instead of forcing everything
// through the slack-post-message tool.
//
- // 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
+ // Slack-triggered sessions relay the model's reply back into the originating
+ // thread (the system prompt below tells the model to answer in natural
+ // language instead of calling a slack tool).
+ const slackReply = isSlackTriggerMetadata(session.trigger_metadata) ? session.trigger_metadata : null
const system = await buildSystemPrompt(rev, deps.bundle, {
unavailableMcps: (deps.mcpFailures ?? []).map((f) => ({
id: f.ref.id,
@@ -698,7 +694,6 @@ 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,
},
])
}
@@ -828,7 +823,6 @@ 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,
},
])
}
@@ -1098,7 +1092,6 @@ 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) {
@@ -1194,7 +1187,6 @@ 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 84a2177c28d3..7797f523cb8c 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,7 +34,6 @@ 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 43f674373fc4..d49452e6db5c 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,7 +134,6 @@ 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',
@@ -203,7 +202,6 @@ 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',
@@ -269,7 +267,6 @@ 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',
@@ -367,7 +364,6 @@ 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',
@@ -430,7 +426,6 @@ 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',
@@ -553,7 +548,6 @@ 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',
@@ -651,7 +645,6 @@ 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 bfd270fc07b8..bca8ea1f0ec1 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,7 +25,6 @@ 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 bd6b3a93e6c8..2db5f9b979c3 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,7 +66,6 @@ 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 ae82383a8dac..3f0e7f815ad2 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,15 +46,6 @@ 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
}
@@ -149,12 +140,6 @@ 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 0c2a1ff4c8a1..7bef8c158205 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, is_preview, created_at, expires_at`
+ dispatch_outcome, created_at, expires_at`
export class PgApprovalStore implements ApprovalStore {
constructor(private readonly pool: Pool) {}
@@ -38,10 +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, is_preview,
+ assistant_message, approver_scope, state,
created_at, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11::jsonb,
- $12::jsonb, 'queued', $13, NOW(), $14)
+ $12::jsonb, 'queued', NOW(), $13)
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`,
@@ -58,7 +58,6 @@ export class PgApprovalStore implements ApprovalStore {
argsHash,
JSON.stringify(input.assistant_message),
JSON.stringify(input.approver_scope),
- input.is_preview,
input.expires_at,
]
)
@@ -238,7 +237,6 @@ interface DbRow {
decision_reason: string | null
decided_args: unknown | null
dispatch_outcome: unknown | null
- is_preview: boolean
created_at: Date
expires_at: Date
}
@@ -263,7 +261,6 @@ 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 54a25b71a92e..d4aea44ca68a 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
@@ -215,7 +215,6 @@ 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(),
})
@@ -285,7 +284,6 @@ 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,
})
@@ -343,7 +341,6 @@ 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(),
})
@@ -357,7 +354,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
expect(after!.pending_inputs).toHaveLength(1)
})
- it('findByExternalKey resolves on (application_id, external_key, scope)', async () => {
+ it('findByExternalKey resolves on (application_id, external_key, revision_id)', async () => {
if (!reachable) {
return
}
@@ -387,22 +384,17 @@ 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 liveScope = { isPreview: false, revisionId: rev.id }
- const found = await queue.findByExternalKey(app.id, 'slack:C01:T1', liveScope)
+ const found = await queue.findByExternalKey(app.id, 'slack:C01:T1', rev.id)
expect(found!.id).toBe('22222222-2222-2222-2222-222222222222')
- const missing = await queue.findByExternalKey(app.id, 'nope', liveScope)
+ const missing = await queue.findByExternalKey(app.id, 'nope', rev.id)
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()
+ // A lookup scoped to a different revision does not see the row — resume
+ // never crosses a revision boundary.
+ const otherRevision = await queue.findByExternalKey(app.id, 'slack:C01:T1', randomUUID())
+ expect(otherRevision).toBeNull()
})
it('getForApplication scopes by (id, application_id) — null for another application', async () => {
@@ -437,7 +429,6 @@ 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(),
})
@@ -538,7 +529,6 @@ 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(),
})
@@ -637,7 +627,6 @@ 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(),
})
@@ -659,7 +648,6 @@ 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(),
}
@@ -725,7 +713,6 @@ 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(),
})
@@ -746,7 +733,6 @@ 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(),
}
@@ -819,7 +805,6 @@ 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 a6bef80e6df5..d8deaec759ae 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, is_preview,
+ usage_total, acl, pending_elevation_requests,
created_at, updated_at`
export class PgSessionQueue implements SessionQueue {
@@ -38,19 +38,14 @@ 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, is_preview,
+ usage_total, acl, pending_elevation_requests,
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, $18)
+ $11::jsonb, $12, $13::jsonb, $14::jsonb, $15::jsonb, $16, $17)
ON CONFLICT (id) DO UPDATE SET
state = EXCLUDED.state,
conversation = EXCLUDED.conversation,
@@ -75,7 +70,6 @@ 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,
]
@@ -387,24 +381,23 @@ export class PgSessionQueue implements SessionQueue {
async findByExternalKey(
applicationId: string,
externalKey: string,
- scope: { isPreview: boolean; revisionId: string }
+ 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.
+ // The revision scope 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 revision, and a JS-side reject would strand
+ // any older same-revision row. Filtering in the WHERE clause guarantees
+ // the lookup never reaches a session on a different revision. 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
- AND is_preview = $3
- AND ($3 = FALSE OR revision_id = $4)
+ AND revision_id = $3
ORDER BY updated_at DESC
LIMIT 1`,
- [applicationId, externalKey, scope.isPreview, scope.revisionId]
+ [applicationId, externalKey, revisionId]
)
if (r.rowCount === 0) {
return null
@@ -577,7 +570,6 @@ interface DbRow {
usage_total: unknown
acl: unknown
pending_elevation_requests: unknown
- is_preview: boolean
created_at: Date
updated_at: Date
}
@@ -644,7 +636,6 @@ 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 3995c2b00776..a19296c329c0 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/queue.ts
@@ -126,33 +126,19 @@ export interface SessionQueue extends SessionInputsStore {
*/
getForApplication(sessionId: string, applicationId: 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.
+ * Find an existing session matching `(application_id, external_key,
+ * revision_id)`. `revisionId` is part of the lookup, not a filter applied
+ * afterward, so resume never crosses a revision boundary: a request routed
+ * to one revision can only resume a session created on that same revision.
+ * This keeps draft-preview runs talking to the draft they targeted —
+ * rather than silently resuming the live session under a shared
+ * external_key — and keeps two draft revisions previewed against the same
+ * external_key isolated, so their conversation histories don't bleed
+ * together. The filter lives in SQL (not an after-the-fact JS guard) so the
+ * `ORDER BY updated_at DESC LIMIT 1` can never return a row from a
+ * different revision.
*/
- findByExternalKey(
- applicationId: string,
- externalKey: string,
- scope: { isPreview: boolean; revisionId: string }
- ): Promise<AgentSession | null>
+ findByExternalKey(applicationId: string, externalKey: string, 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 5f759216b66c..91fe1ddf3007 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,17 +60,6 @@ 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 {
@@ -201,13 +190,6 @@ 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/failure-notifier.test.ts b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
index 990278994dbf..c3c1b63c0af5 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,7 +49,6 @@ 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 f1d18a17363a..5e59d2f51e79 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,7 +46,6 @@ 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
@@ -190,35 +189,6 @@ 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 8de51e4bac8d..5aeb9fc474e0 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,22 +36,6 @@ 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 79fa66629097..dbdf15b6b8f0 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts
@@ -1174,18 +1174,6 @@ 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 51af3ddc0ce4..2bad3092df47 100644
--- a/products/agent_platform/services/agent-shared/src/spec/tool.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/tool.ts
@@ -155,17 +155,6 @@ export interface ToolContext {
* never sees a tool that just throws `web_search_not_configured`.
*/
webSearchProviders?: readonly WebSearchProvider[]
- /**
- * 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.
@@ -204,29 +193,5 @@ 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/identity-fetch-tool.test.ts b/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts
index 2652b4bb6453..aba78498b8f7 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,7 +110,6 @@ maybeDescribe('@posthog/identity-fetch × dogs (real PG + HTTP)', () => {
identity,
http: new HttpClient({}),
posthogApiBaseUrl: '',
- isPreview: false,
}
const tool = getNativeTool('@posthog/identity-fetch')
@@ -157,7 +156,6 @@ 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)
@@ -204,7 +202,6 @@ 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 d208995ac940..ea8294f29898 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,7 +162,6 @@ 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
index ca59b5480733..00fc7c2c8f56 100644
--- 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
@@ -1,9 +1,12 @@
/**
- * 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).
+ * Preview-routing e2e: an authed caller can drive a NON-LIVE (draft) revision
+ * by addressing the `<slug>-<rev-hex>` URL with a valid `aud=agent-ingress.preview`
+ * JWT. A preview run is otherwise indistinguishable from a live run — it
+ * executes real tool calls and real side effects, persists real session state,
+ * and emits the same analytics — the only difference is which revision handles
+ * the request. There is no `is_preview` session marker and no side-effect
+ * suppression; this suite guards the routing + revision-scoped resume isolation
+ * that make previewing a draft safe to keep.
*
* The harness's `deployAgent` always promotes the revision to live, so the
* test creates a SECOND revision directly via `c.revisions.createRevision`
@@ -24,7 +27,7 @@ import {
import { buildCluster, closeSharedPool, Cluster, fauxText } from '../harness'
-describe('preview-mode: real e2e', () => {
+describe('preview-routing: real e2e', () => {
let c: Cluster
beforeEach(async () => {
@@ -39,7 +42,7 @@ describe('preview-mode: real e2e', () => {
await closeSharedPool()
})
- it('preview run stamps is_preview on the session row and on every $ai_* event', async () => {
+ it('preview run resolves to and executes against the draft revision', 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
@@ -84,28 +87,10 @@ describe('preview-mode: real e2e', () => {
await c.drain()
const session = await c.queue.get(sessionId)
expect(session).not.toBeNull()
- expect(session!.is_preview).toBe(true)
+ // Routed to the draft and ran for real — same analytics a live run emits.
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 () => {
@@ -152,22 +137,20 @@ describe('preview-mode: real e2e', () => {
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)
+ // Routed to the draft — 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!.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).
+ // Regression guard for revision-scoped resume: a preview-authed request
+ // routed to a draft must never resume a live session that happens to
+ // share an `(application_id, external_key)`. `findByExternalKey` scopes
+ // the lookup to `revision_id`, so the draft request opens its own
+ // session instead of dragging the author into the live thread. This
+ // asserts the user-facing outcome — two distinct sessions, each on the
+ // revision the request targeted.
c.setScript([fauxText('live reply'), fauxText('preview reply')])
const { application } = await c.deployAgent({ slug: 'preview-iso' })
@@ -212,22 +195,11 @@ describe('preview-mode: real e2e', () => {
const previewSessionId = previewRes.body.session_id as string
await c.drain()
- // Distinct sessions, each correctly flagged.
+ // Distinct sessions, each on the revision its request targeted.
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(liveSession!.revision_id).toBe(application.live_revision_id)
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 6abffda07ac2..cb80a4e95fc6 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,14 +22,6 @@
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
@@ -1294,97 +1286,6 @@ 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', () => {
@@ -1479,90 +1380,6 @@ 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-tools/src/test-helpers.ts b/products/agent_platform/services/agent-tools/src/test-helpers.ts
index ff139e1951a1..046898f965bb 100644
--- a/products/agent_platform/services/agent-tools/src/test-helpers.ts
+++ b/products/agent_platform/services/agent-tools/src/test-helpers.ts
@@ -15,7 +15,6 @@ export function makeCtx(overrides?: Partial<ToolContext>): ToolContext {
},
http: new HttpClient(),
posthogApiBaseUrl: DEFAULT_POSTHOG_API_BASE_URL,
- isPreview: false,
...overrides,
}
}
@@ -37,7 +36,6 @@ 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 4aabc56859b3..47600c88efdd 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,44 +462,4 @@ 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 e6dbe465e6d3..940328c972e3 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, isPreviewSideEffect, secretHostMatches, type ToolContext, Type } from '@posthog/agent-shared'
+import { defineNativeTool, secretHostMatches, type ToolContext, Type } from '@posthog/agent-shared'
import { parseFetchableUrl } from './http-url'
@@ -290,18 +290,6 @@ 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 9ec8b945aa7d..cd87c596444d 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,12 +4,11 @@
* SeaweedFS before running.
*/
import { S3Client } from '@aws-sdk/client-s3'
-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
import {
buildTestStore,
HttpClient,
- MemoryStore,
newTestPrefix,
S3MemoryStore,
type ToolContext,
@@ -29,7 +28,6 @@ function makeCtx(store: S3MemoryStore | undefined): ToolContext {
memoryStore: store,
http: new HttpClient(),
posthogApiBaseUrl: 'http://localhost:8010',
- isPreview: false,
}
}
@@ -242,94 +240,3 @@ 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 15fa7cc431a0..6a721d41157b 100644
--- a/products/agent_platform/services/agent-tools/src/tools/memory.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/memory.ts
@@ -17,7 +17,6 @@
import {
defineNativeTool,
- isPreviewSideEffect,
MAX_DESCRIPTION_LEN,
MemoryConflictError,
MemoryFile,
@@ -177,16 +176,6 @@ 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({
@@ -215,9 +204,6 @@ 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 })
@@ -255,9 +241,6 @@ 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)
@@ -295,9 +278,6 @@ 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 a4bde4a3529b..856f9839e2fc 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,60 +244,4 @@ 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 21d109d3717d..63372fe563f7 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,11 +1,4 @@
-import {
- defineNativeTool,
- HttpFetcher,
- isPreviewSideEffect,
- SLACK_BOT_TOKEN_KEY,
- ToolContext,
- Type,
-} from '@posthog/agent-shared'
+import { defineNativeTool, HttpFetcher, SLACK_BOT_TOKEN_KEY, ToolContext, Type } from '@posthog/agent-shared'
/**
* Resolve the agent's Slack bot token from `encrypted_env` via `ctx.secret`.
@@ -130,15 +123,6 @@ 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,
@@ -161,9 +145,6 @@ 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 }
@@ -268,9 +249,6 @@ 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
deleted file mode 100644
index 51c374444619..000000000000
--- a/products/agent_platform/services/agent-tools/src/tools/table.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * 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 d0f4899d5a0b..160389391e2a 100644
--- a/products/agent_platform/services/agent-tools/src/tools/table.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/table.ts
@@ -17,7 +17,6 @@
import {
defineNativeTool,
- isPreviewSideEffect,
TabularConflictError,
type TableQuery,
type TabularStore,
@@ -110,9 +109,6 @@ 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)
@@ -186,11 +182,6 @@ 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) {
@@ -210,9 +201,6 @@ 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/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 34d39d2fd4dd..c442ea052329 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7591,8 +7591,6 @@ 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. */
@@ -7770,8 +7768,6 @@ 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;
}
@@ -7885,8 +7881,6 @@ 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. */
@@ -7960,8 +7954,6 @@ 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;
}