Files
PaperClipAI/ui/src/components/CloudTrialExhaustedModal.tsx
T
DottaandPaperclip 689bfd04ac feat(onboarding): add free_inference_1 onboarding flow, dual-trigger model gate, and multi-variant PostHog attribution (#23401)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - First-time Cloud users currently must connect an external AI
provider during onboarding before they can talk to their first agent.
> - Requiring provider setup up front adds friction before users
experience their first agent chat.
> - Paperclip needs a multi-variant onboarding experiment
(`onboarding-flow`) that defaults to `baseline` while allowing an
alternate `free_inference_1` path that skips the model-connection screen
and starts with capped starter inference.
> - When a trial-only workspace either exhausts its starter credit or
creates its first executable task or subtask, Paperclip must hold the
new task, prompt the user to connect a model provider, keep LLM actions
blocked if the modal is dismissed, and automatically resume held work
once a model is connected.
> - This pull request adds multi-variant onboarding resolution, PostHog
multi-variant attribution, dual-trigger connect-model gating with
restart-safe DB hydration, the `free_inference_1` UI onboarding flow,
and full-flow Storybooks.
> - The benefit is a safe, measurable onboarding experiment that leaves
`baseline` and self-hosted installs unchanged while letting opted-in
Cloud workspaces reach their first chat immediately and upgrade
seamlessly when real work begins.

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/shared/`, `server/`, `ui/`)

**Problem or motivation**

New Cloud users currently hit a mandatory "Connect a model" step during
onboarding before they can open their first agent chat. Existing
trial-inference gating only supported a binary flag and only triggered
on starter-credit exhaustion, not on subtask or manual task creation,
and did not track multi-variant onboarding cohorts cleanly in PostHog.

**Proposed solution**

Introduce the extensible `onboarding-flow` experiment (`baseline`
default, `free_inference_1` variant) across shared contracts, server
services, and UI:
- Resolve `onboardingVariant` from the Cloud control plane (`GET
/v1/tenant/onboarding-config`) with safe fallbacks to
`PAPERCLIP_ONBOARDING_VARIANT`, managed config, and `"baseline"`.
- In `free_inference_1`, skip Step 4 ("Connect a model") in
`OnboardingWizard`, hire the first agent on starter inference, and drop
the user straight into the first chat.
- Support a dual-trigger connect-model gate (`exhausted` and
`work_requires_model`) that holds newly created tasks/subtasks on
trial-only workspaces (hydrated from DB across restarts), returns HTTP
402 for blocked LLM chat/runs, keeps the modal dismissible while
blocking chat composers with a "Connect a model" CTA banner, and
automatically resumes held work after provider migration.
- Stamp `$feature/onboarding-flow`, `onboarding_variant`, and immutable
`initial_onboarding_variant` across server PostHog events,
`$groupidentify` (with top-level `$group_set_once`), and browser PostHog
super-properties / `identify()`.

**Alternatives considered**

- Baking per-stack experiment variants into warm-pool container config
was ruled out because warm-pool stacks must remain homogeneous until
claim time.
- Failing agent subtask creation calls on trial-only workspaces was
ruled out because it breaks the agent's first-chat experience; creating
the task in a held state and auto-resuming it after model connection
preserves user intent.

## What Changed

- **`packages/shared`**: Added `onboarding-flow` variant
constants/helpers, `CloudTrialGateReason` (`"exhausted" |
"work_requires_model"`), `CloudTrialHeldIssueSummary`, `gateReason`,
`llmBlocked`, `heldIssueIds`, `heldIssues`, `onboardingVariant`, and
`resumedIssueIds` on cloud-inference and session/browser-analytics
contracts.
- **`server/`**:
- Added Ed25519-signed `GET /v1/tenant/onboarding-config` resolution
with warm-pool claim cache invalidation and safe `"baseline"` default.
- Added dual-trigger trial gating (`exhausted` + `work_requires_model`)
with DB-backed held-issue hydration across restarts, HTTP 402 refusal
for blocked trial runs and chat sends, and automatic wake/resume of held
subtasks upon migration.
- Updated PostHog server telemetry, `$groupidentify` (top-level
`$group_set` and `$group_set_once`), `$feature_flag_called`, and
`BrowserAnalyticsConfig` to stamp `onboarding-flow` multi-variant
properties while preserving backwards-compatible `cloud-trial-inference`
properties.
- Added and updated Vitest suites covering multi-variant resolution,
PostHog attribution, held subtask creation, cold-restart hydration, LLM
run refusal, and auto-resume.
- **`ui/`**:
- Updated `OnboardingWizard` so `free_inference_1` skips Step 4
("Connect a model"), auto-hires with `cloudTrialInference: true`, and
launches straight into the first chat while leaving `baseline`
unchanged.
- Updated `CloudTrialGate` and `CloudTrialExhaustedModal` for
dual-trigger copy (`work_requires_model` vs `exhausted`), waiting
subtask pills, and dismissible modal behavior (`required={false}`).
- Added `CloudTrialBlockedBanner` and wired LLM-blocked composer
disabling + "Connect a model" CTA into `IssueDetail` / `AgentChat` and
`DashboardChatComposer`, plus status refresh on manual task creation in
`NewIssueDialog`.
- Updated `product-analytics.ts` + tests to register
`$feature/onboarding-flow` and `onboarding_variant` super-properties and
`$set_once.initial_onboarding_variant`.
- Added full-flow Storybooks
(`free-inference-onboarding-flow.stories.tsx`) covering all 7 onboarding
and gate states.

## Verification

- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck` (0 errors)
- `pnpm --filter @paperclipai/ui typecheck` (0 errors)
- 9 targeted server Vitest suites (`cloud-trial-inference`,
`cloud-posthog-config`, `cloud-posthog-browser`,
`posthog-direct-telemetry`, `posthog-direct-transport`, `auth-routes`,
`cloud-runtime-identity`, `onboarding-seed-route`,
`issue-onboarding-first-task-routes`): 196/196 passed
- 4 targeted UI Vitest suites (`CloudTrialGate.test.tsx`,
`product-analytics.test.ts`, `onboarding-analytics.test.tsx`,
`Layout.mobile.test.tsx`): 37/37 passed
- `pnpm --filter @paperclipai/ui build` and `pnpm --filter
@paperclipai/ui build-storybook`: passed
- Visually inspected Storybook renders across all 7 `free_inference_1`
states in headless Chromium via Playwright with zero page errors.

## Risks

- Low risk to existing users: `onboardingVariant` defaults to
`"baseline"` everywhere, leaving self-hosted installs and unflagged
Cloud stacks unchanged.
- No database schema migrations are required; held trial subtasks are
hydrated from existing `issues` and `toolConnections` tables on restart.
- Requires the companion `paperclip-cloud` control-plane endpoint (`GET
/v1/tenant/onboarding-config`) to activate non-baseline variants in
Cloud; falls back safely to `"baseline"` if unavailable.

## Model Used

- Google Gemini (Antigravity agentic coding environment with multi-agent
swarm, tool use, code execution, and Playwright Storybook verification)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 20:54:03 +00:00

381 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useRef, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
ArrowRight,
Bot,
CheckCircle2,
Loader2,
RotateCcw,
Sparkles,
} from "lucide-react";
import type {
AiConnectionBinding,
MigrateCloudTrialAgentsResult,
} from "@paperclipai/shared";
import { cloudInferenceApi } from "@/api/cloud-inference";
import { describeError } from "@/api/errors";
import { AiProviderSetup } from "@/components/ai-connections/AiProviderSetup";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
getCloudTrialGateReason,
getCloudTrialHeldIssueIds,
getCloudTrialHeldIssues,
type CloudTrialInferenceStatusCompat,
} from "@/lib/cloud-trial-gate";
import { queryKeys } from "@/lib/queryKeys";
import { cn } from "@/lib/utils";
export interface CloudTrialExhaustedModalProps {
open: boolean;
companyId: string;
status: CloudTrialInferenceStatusCompat;
/** When true, blocks closing until the user connects a model provider and migrates agents. */
required?: boolean;
/** Initial visual phase override (primarily for Storybook & previewing states). */
initialPhase?: "connect" | "migrating" | "done" | "error";
initialResult?: MigrateCloudTrialAgentsResult | null;
initialError?: string | null;
onOpenChange?: (open: boolean) => void;
onMigrationStart?: () => void;
onMigrated?: (result: MigrateCloudTrialAgentsResult) => void;
}
export function CloudTrialExhaustedModal({
open,
companyId,
status,
required = false,
initialPhase = "connect",
initialResult = null,
initialError = null,
onOpenChange,
onMigrationStart,
onMigrated,
}: CloudTrialExhaustedModalProps) {
const queryClient = useQueryClient();
const [phase, setPhase] = useState<"connect" | "migrating" | "done" | "error">(initialPhase);
const [migrationResult, setMigrationResult] = useState<MigrateCloudTrialAgentsResult | null>(initialResult);
const [errorMessage, setErrorMessage] = useState<string | null>(initialError);
const [lastBinding, setLastBinding] = useState<Exclude<AiConnectionBinding, { mode: "responsible_user" }> | null>(
null,
);
const modalShownTrackedRef = useRef(false);
useEffect(() => {
if (!open) {
modalShownTrackedRef.current = false;
return;
}
if (phase !== "connect" || modalShownTrackedRef.current) return;
modalShownTrackedRef.current = true;
void cloudInferenceApi
.trackTelemetry(companyId, {
event: "modal_shown",
trialAgentCount: status.trialAgents.length,
gateReason: getCloudTrialGateReason(status) ?? "exhausted",
})
.catch(() => {
// Best-effort analytics must never interrupt connecting a provider.
});
}, [open, phase, companyId, status]);
const migrateMutation = useMutation({
mutationFn: (binding: Exclude<AiConnectionBinding, { mode: "responsible_user" }>) =>
cloudInferenceApi.migrate(companyId, {
connectionId: binding.connectionId,
grantId: binding.grantId,
provider: binding.provider,
method: binding.method,
ownership: binding.mode === "shared" ? "shared" : "personal",
resumeBlockedWork: true,
}),
onMutate: (binding) => {
onMigrationStart?.();
setLastBinding(binding);
setErrorMessage(null);
setPhase("migrating");
},
onSuccess: (result) => {
setMigrationResult(result);
setPhase("done");
onMigrated?.(result);
void queryClient.invalidateQueries({ queryKey: queryKeys.cloudInference.status(companyId) });
void queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });
void queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) });
void queryClient.invalidateQueries({ queryKey: ["ai-connections", companyId] });
},
onError: (err) => {
setErrorMessage(describeError(err).body);
setPhase("error");
},
});
const canMigrate = status.canMigrate !== false;
const canClose = !required || !canMigrate || phase === "done";
const agentCount = status.trialAgents.length;
const gateReason = getCloudTrialGateReason(status) ?? "exhausted";
const heldIssueIds = getCloudTrialHeldIssueIds(status);
const heldIssues = getCloudTrialHeldIssues(status);
const heldCount = Math.max(heldIssueIds.length, heldIssues.length);
const isWorkRequiresModel = gateReason === "work_requires_model";
const agentLabel =
agentCount === 1
? status.trialAgents[0]?.name || "your agent"
: agentCount > 1
? `all ${agentCount} agents`
: "your agents";
const resumedTaskCount = migrationResult?.resumedIssueIds.length ?? 0;
const resumedRunCount = migrationResult?.resumedRunIds.length ?? 0;
const hasResumedWork = resumedRunCount > 0 || resumedTaskCount > 0;
const headerTitle =
phase === "done"
? "Model provider connected"
: isWorkRequiresModel
? "Connect a model to run tasks"
: "Connect a model to keep going";
const headerDescription =
phase === "done"
? isWorkRequiresModel && hasResumedWork
? "Your agents have been updated and your waiting tasks are now running."
: "Your agents have been updated to use your connected model provider."
: !canMigrate
? "A company administrator needs to connect a model provider before these agents can continue running."
: isWorkRequiresModel
? heldCount === 1
? `Your subtask is ready and waiting to run. Connect a model provider and we’ll automatically update ${agentLabel} and start it.`
: heldCount > 1
? `Your ${heldCount} tasks are ready and waiting to run. Connect a model provider and we’ll automatically update ${agentLabel} and start them.`
: `Connect a model provider to run tasks. We’ll automatically update ${agentLabel} and start your work right away.`
: `Connect a model provider to keep going. We’ll automatically update ${agentLabel} and pick up where you left off.`;
return (
<Dialog
open={open}
onOpenChange={(nextOpen) => {
if (!nextOpen && !canClose) return;
onOpenChange?.(nextOpen);
}}
>
<DialogContent
showCloseButton={canClose}
onEscapeKeyDown={(event) => {
if (!canClose) event.preventDefault();
}}
onPointerDownOutside={(event) => {
if (!canClose) event.preventDefault();
}}
onInteractOutside={(event) => {
if (!canClose) event.preventDefault();
}}
className="max-h-(--sz-85vh) sm:max-w-2xl overflow-y-auto p-0 gap-0"
>
{/* Header */}
<div className="border-b border-border bg-card px-6 py-4">
<div className="flex items-start gap-3">
<div
className={cn(
"mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-lg border",
phase === "done"
? "border-(--status-task-icon-done)/30 bg-(--diff-add-bg) text-(--diff-add-fg)"
: "border-border bg-muted/50 text-foreground",
)}
>
{phase === "done" ? (
<CheckCircle2 className="size-4" />
) : (
<Sparkles className="size-4" />
)}
</div>
<div className="min-w-0 flex-1 space-y-1">
<DialogHeader className="text-left">
<DialogTitle className="text-base font-semibold">
{headerTitle}
</DialogTitle>
</DialogHeader>
<DialogDescription className="text-sm text-muted-foreground">
{headerDescription}
</DialogDescription>
{phase !== "done" && isWorkRequiresModel && heldIssues.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5 pt-2">
<span className="text-xs text-muted-foreground mr-1">
Waiting to run:
</span>
{heldIssues.map((issue) => (
<span
key={issue.id}
className="inline-flex items-center gap-1 rounded-full border border-border bg-background px-2 py-0.5 text-xs text-foreground"
>
{issue.identifier ? (
<span className="font-mono text-muted-foreground">{issue.identifier}</span>
) : null}
<span className="max-w-52 truncate font-medium">{issue.title}</span>
</span>
))}
</div>
)}
{phase !== "done" && status.trialAgents.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5 pt-2">
<span className="text-xs text-muted-foreground mr-1">
{canMigrate ? "Will update:" : "Waiting on provider:"}
</span>
{status.trialAgents.map((agent) => (
<span
key={agent.id}
className="inline-flex items-center gap-1 rounded-full border border-border bg-background px-2 py-0.5 text-xs text-foreground"
>
<Bot className="size-3 text-muted-foreground" />
<span className="font-medium">{agent.name}</span>
{agent.title ? (
<span className="text-muted-foreground">· {agent.title}</span>
) : null}
</span>
))}
</div>
)}
</div>
</div>
</div>
{/* Body */}
<div className="px-6 py-4">
{phase === "connect" && !canMigrate && (
<div className="space-y-4 py-2">
<p className="text-sm text-muted-foreground">
You have read-only access to agent model settings in this company. Ask an administrator to connect a model provider so paused agent work can resume.
</p>
<div className="flex justify-end">
<Button variant="outline" onClick={() => onOpenChange?.(false)}>
Dismiss
</Button>
</div>
</div>
)}
{phase === "connect" && canMigrate && (
<AiProviderSetup
companyId={companyId}
hideCancel={!canClose}
hideProviderHeading
submitLabel="Connect & update agents"
onCancel={() => {
if (canClose) onOpenChange?.(false);
}}
onComplete={(binding) => {
migrateMutation.mutate(binding);
}}
/>
)}
{phase === "migrating" && (
<div className="flex flex-col items-center justify-center gap-3 py-10 text-center">
<Loader2 className="size-6 animate-spin text-primary" />
<div className="space-y-1">
<p className="text-sm font-medium text-foreground">
Updating your agents to your model provider…
</p>
<p className="text-xs text-muted-foreground">
Switching harnesses and resuming paused work.
</p>
</div>
</div>
)}
{phase === "error" && (
<div className="space-y-4 py-4">
<div
role="alert"
className="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm text-destructive"
>
<p className="font-medium">Could not finish updating your agents</p>
<p className="mt-1 text-xs opacity-90">
{errorMessage ?? "An unexpected error occurred while updating your agents."}
</p>
</div>
<div className="flex items-center justify-between gap-2">
<Button
variant="ghost"
onClick={() => {
setErrorMessage(null);
setPhase("connect");
}}
>
Choose another provider
</Button>
{lastBinding && (
<Button onClick={() => migrateMutation.mutate(lastBinding)}>
<RotateCcw className="size-3.5 mr-1.5" />
Retry update
</Button>
)}
</div>
</div>
)}
{phase === "done" && (
<div className="space-y-5">
{migrationResult && migrationResult.agents.length > 0 && (
<div className="rounded-lg border border-border bg-muted/20 divide-y divide-border">
{migrationResult.agents.map((agent) => (
<div
key={agent.agentId}
className="flex items-center justify-between gap-3 px-3.5 py-2.5 text-sm"
>
<div className="flex items-center gap-2 min-w-0">
<Bot className="size-4 shrink-0 text-muted-foreground" />
<span className="truncate font-medium text-foreground">{agent.name}</span>
</div>
<span className="shrink-0 font-mono text-xs text-muted-foreground">
{agent.runnerProvider ? `${agent.runnerProvider} · ` : ""}
{agent.model}
</span>
</div>
))}
</div>
)}
{migrationResult && hasResumedWork && (
<div className="flex items-center gap-2 rounded-lg border border-(--status-task-icon-done)/30 bg-(--diff-add-bg) px-3.5 py-2.5 text-xs text-(--diff-add-fg)">
<Sparkles className="size-3.5 shrink-0" />
<span>
{isWorkRequiresModel
? resumedTaskCount > 1
? `Your ${resumedTaskCount} held tasks have been automatically started.`
: "Your held task has been automatically started."
: "Your paused work has been automatically resumed."}
</span>
</div>
)}
{migrationResult && !hasResumedWork && isWorkRequiresModel && heldCount > 0 && (
<div className="flex items-center gap-2 rounded-lg border border-border bg-muted/40 px-3.5 py-2.5 text-xs text-muted-foreground">
<Sparkles className="size-3.5 shrink-0" />
<span>
Your model provider is connected, but waiting tasks could not be started automatically. Open your tasks to start them.
</span>
</div>
)}
<div className="flex justify-end">
<Button onClick={() => onOpenChange?.(false)}>
Continue to workspace
<ArrowRight className="size-3.5 ml-1.5" />
</Button>
</div>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
}