feat(cloud): add Cloud starter inference proxy, migration modal, and PostHog A/B telemetry (#22966)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Cloud onboarding currently requires new users to connect a
model provider subscription or API key before their first agent can run
> - That upfront credential step creates drop-off before a new user sees
their first agent do real work
> - We need an opt-in, managed Cloud capability that runs the first
agent right away through a server-side proxy, keeps the raw provider key
out of sandboxes and browsers, prompts the user to connect their own
provider when starter inference runs out, and measures treatment vs.
control in PostHog
> - This pull request adds the default-off `enableCloudTrialInference`
managed feature, the server-side OpenRouter reverse proxy with ephemeral
per-run tokens, the blocking model-connection and agent-migration modal
with Storybook stories, and Cloud-only PostHog A/B cohort and funnel
telemetry
> - The benefit is zero-friction first-agent onboarding on Cloud stacks
enrolled in the experiment, with automatic migration to the user's own
model provider and clean A/B observability

## Linked Issues or Issue Description

**Subsystem affected**

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

**Problem or motivation**

New Cloud users must connect an AI subscription or API key before they
can run their first agent. We want to A/B test letting eligible Cloud
workspaces start their first agent right away with managed starter
inference (OpenCode / GPT-6 Luna in Paperclip Runner) without exposing
any raw upstream API key to the sandbox, database, or browser, and then
guide the user to connect their own model provider when starter
inference runs out.

**Proposed solution**

Add an experimental managed feature flag (`enableCloudTrialInference`,
off by default on both Cloud and self-hosted) that:

- Routes starter-inference runs through a server-side OpenRouter reverse
proxy (`/api/internal/cloud-inference/v1/*`) authenticated with
ephemeral per-run bearer tokens so the raw OpenRouter key never leaves
server memory.
- Enforces the configured starter model, detects upstream HTTP 402
exhaustion, invalidates active run tokens, reports exhaustion back to
the Cloud control plane, and broadcasts `cloud_trial.status.updated`
over live events.
- Displays a blocking modal (`CloudTrialExhaustedModal`) when starter
inference runs out while agents still depend on it, lets the user
connect their own model provider, automatically migrates trial agents to
that provider's default harness and model, clears incompatible provider
sessions, and resumes paused work.
- Stamps the `cloud-trial-inference` (`treatment` / `control`) cohort
onto Cloud-only server and browser PostHog telemetry and records
Cloud-only funnel events (`$feature_flag_called`, `cloud_trial.started`,
`cloud_trial.key_issued`, `cloud_trial.exhausted`,
`cloud_trial.modal_shown`, `cloud_trial.migrated`,
`cloud_trial.migration_failed`) without affecting self-hosted telemetry.

**Alternatives considered**

- Passing a capped OpenRouter API key directly into the agent sandbox
environment: rejected because a sandboxed agent or user could read and
reuse the raw key outside Paperclip.
- Showing starter dollar amounts or a usage progress bar in the UI:
rejected in favor of a simple prompt asking the user to connect a model
provider to continue.

**Roadmap alignment**

Supports hosted onboarding activation experiments while staying strictly
gated behind a default-off managed feature flag (`cloudDefault: false`,
`selfHostedDefault: false`) so self-hosted installs and unflagged Cloud
stacks see zero behavior change.

**Additional context**

Paired with the private Cloud control plane key-management service PR
that provisions per-stack capped OpenRouter child keys and enforces
single-trial caps across accounts.

## What Changed

- **Shared contracts & feature flag (`packages/shared`)**:
- Added `enableCloudTrialInference` (`tier: "managed"`, `cloudDefault:
false`, `selfHostedDefault: false`) to `feature-catalog.ts`,
`types/instance.ts`, and `validators/instance.ts`.
- Added `packages/shared/src/cloud-inference.ts` with trial status
types, migration schemas, provider-to-harness migration defaults, and
telemetry event validation.
- Added `cloud_trial.status.updated` to `LIVE_EVENT_TYPES`,
`cloudTrialInference` to `agentRuntimeConfigSchema`, and optional
`cloudTrialInferenceEnabled` to `browserAnalyticsConfigSchema`.
- **Paperclip Runner (`packages/paperclip-runner`)**:
- Updated OpenCode server driver (`opencode-server-driver.ts`) and
`configured-environment.ts` to accept `PAPERCLIP_OPENROUTER_PROXY_URL`
and `PAPERCLIP_OPENROUTER_PROXY_TOKEN`.
- Updated `provider-failure.ts` to classify HTTP 402 as quota exhaustion
and redact `sk-or-` key material.
- **Server proxy, migration, and onboarding (`server/`)**:
- Added `server/src/services/cloud-trial-inference.ts` and
`server/src/routes/cloud-inference.ts` for server-memory key custody,
ephemeral per-run proxy tokens, model guard, HTTP 402 exhaustion
handling, agent migration, blocked-run resume, and company-scoped
status/migrate/telemetry routes.
- Wired proxy mounting in `server/src/app.ts`, runtime env & cleanup in
`heartbeat.ts` / `execution-configuration.ts`, `cloud_trial_exhausted`
error code in `run-completion.ts`, and starter-agent seeding in
`onboarding-seed.ts`.
- **PostHog A/B telemetry (`server/`, `ui/`)**:
- Resolved `cloudTrialInferenceEnabled` from `PAPERCLIP_MANAGED_CONFIG`
in `cloud-posthog-config.ts` and `cloud-posthog-browser.ts`.
- Stamped `cloud_trial_inference_enabled` and
`$feature/cloud-trial-inference` on `workspace` groups,
`cloud.workspace_started`, direct server PostHog events, and browser
PostHog super-properties plus `$set_once.cloud_trial_inference_cohort`.
- Added Cloud-only direct PostHog helpers (`trackCloudPostHogEvent`,
`trackCloudTrialExposure`) in `server/src/telemetry.ts` and wired
exposure + lifecycle funnel events (no-op on self-hosted).
- **UI & Storybook (`ui/`)**:
- Added `ui/src/api/cloud-inference.ts`, `CloudTrialExhaustedModal.tsx`,
`CloudTrialGate.tsx`, and optional `hideCancel` / `hideProviderHeading`
props on `AiProviderSetup.tsx`.
- Wired `CloudTrialGate` into `Layout.tsx` / `Layout.production.tsx`,
live-event invalidation into `LiveUpdatesProvider.tsx`, starter
onboarding card into `OnboardingWizard.tsx`, and the experimental card
into `InstanceExperimentalSettings.tsx`.
- Added Storybook stories in
`ui/storybook/stories/onboarding/cloud-trial-exhausted-modal.stories.tsx`
covering single agent, multiple agents, migrating, migration succeeded,
and migration error states.

## Verification

- `pnpm --filter @paperclipai/shared build`: passed.
- `pnpm --filter @paperclipai/paperclip-runner build`: passed
(TypeScript, protocol manifest, Cargo release build, replay golden
parity).
- `pnpm --filter @paperclipai/ui typecheck` & `node
scripts/storybook-catalog.mjs --check`: passed (372 files, 3484
stories).
- `pnpm --filter @paperclipai/server exec tsc --noEmit`: passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/cloud-trial-inference.test.ts
src/__tests__/cloud-posthog-config.test.ts
src/__tests__/cloud-posthog-browser.test.ts
src/__tests__/posthog-direct-event-shape.test.ts
src/__tests__/posthog-direct-telemetry.test.ts
src/__tests__/auth-routes.test.ts`: 6 files, 144/144 passed.
- `pnpm --filter @paperclipai/ui exec vitest run
src/lib/analytics/product-analytics.test.ts
src/lib/analytics/product-analytics-events.test.ts`: 2 files, 14/14
passed.
- Verified Storybook stories interactively in the embedded browser
(`ExhaustedSingleAgent`, `ExhaustedMultipleAgents`,
`MigrationSucceeded`) with passing `play()` interactions and zero
console errors, plus live end-to-end onboarding → exhaustion → blocking
modal → provider connect → agent migration flow against a mock
OpenRouter server.

## Risks

- **Default-off isolation**: `enableCloudTrialInference` defaults to
`false` everywhere, and Cloud stacks hide `instance.experimental.*`
controls by default, so existing self-hosted and unflagged Cloud stacks
have zero behavior change.
- **Key custody boundary**: Raw OpenRouter keys stay strictly in server
process memory; sandboxes only receive short-lived per-run proxy tokens
invalidated on run exit or exhaustion.
- **PostHog direct contract**: Existing self-hosted collector envelopes
remain unchanged; `posthog-direct-event-shape.test.ts` and
`product-analytics-events.test.ts` verify event shape and ownership
invariants.
- **CI coverage**: Broad workspace suites and E2E lanes were not run
locally and will run on PR CI.

## Model Used

- Google Gemini (Antigravity agentic assistant) with code editing,
terminal execution, browser verification, and test tools.

## 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-25 14:44:42 -06:00
1 parent 9cfc80b340
commit 64bef50be0
63 files changed
+4295 -52

No files matched your search

@@ -0,0 +1,315 @@
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,
CloudTrialInferenceStatus,
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 { queryKeys } from "@/lib/queryKeys";
import { cn } from "@/lib/utils";
export interface CloudTrialExhaustedModalProps {
open: boolean;
companyId: string;
status: CloudTrialInferenceStatus;
/** 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 = true,
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,
})
.catch(() => {
// Best-effort analytics must never interrupt connecting a provider.
});
}, [open, phase, companyId, status.trialAgents.length]);
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: ["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;
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">
{phase === "done"
? "Model provider connected"
: "Connect a model provider to continue"}
</DialogTitle>
</DialogHeader>
<DialogDescription className="text-sm text-muted-foreground">
{phase === "done"
? "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."
: `You need to connect a model provider to continue. We’ll automatically update ${
agentCount === 1
? status.trialAgents[0]?.name || "your agent"
: agentCount > 1
? `all ${agentCount} agents`
: "your agents"
} and pick up where you left off.`}
</DialogDescription>
{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 && migrationResult.resumedRunIds.length > 0 && (
<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>Your paused work has been automatically resumed.</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>
);
}
+94
View File
@@ -0,0 +1,94 @@
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import type { CloudTrialInferenceStatus } from "@paperclipai/shared";
import { cloudInferenceApi } from "@/api/cloud-inference";
import { instanceSettingsApi } from "@/api/instanceSettings";
import { CloudTrialExhaustedModal } from "@/components/CloudTrialExhaustedModal";
import { useCompany } from "@/context/CompanyContext";
import { queryKeys } from "@/lib/queryKeys";
/**
* Global shell controller that watches the selected company's Cloud starter
* inference status and requires connecting a model provider when needed.
*/
export function CloudTrialGate() {
const { selectedCompanyId } = useCompany();
const [dismissedAfterMigration, setDismissedAfterMigration] = useState(false);
// Keep the modal mounted on its "Subscription connected" confirmation screen
// after migration flips `status` to "migrated" and empties `trialAgentIds`,
// until the user explicitly clicks "Continue to workspace".
const [holdingMigrationSuccess, setHoldingMigrationSuccess] = useState(false);
const [migrationComplete, setMigrationComplete] = useState(false);
const [lastExhaustedStatus, setLastExhaustedStatus] = useState<CloudTrialInferenceStatus | null>(null);
const experimental = useQuery({
queryKey: queryKeys.instance.experimentalSettings,
queryFn: instanceSettingsApi.getExperimental,
});
const enabled = experimental.data?.enableCloudTrialInference === true;
const statusQuery = useQuery({
queryKey: queryKeys.cloudInference.status(selectedCompanyId ?? "__none__"),
queryFn: () => cloudInferenceApi.getStatus(selectedCompanyId!),
enabled: Boolean(selectedCompanyId) && enabled,
staleTime: 15_000,
});
const status = statusQuery.data;
const isExhaustedWithTrialAgents =
Boolean(selectedCompanyId) &&
enabled &&
status?.status === "exhausted" &&
status.trialAgentIds.length > 0;
useEffect(() => {
if (isExhaustedWithTrialAgents && status) {
setLastExhaustedStatus(status);
}
}, [isExhaustedWithTrialAgents, status]);
useEffect(() => {
setDismissedAfterMigration(false);
setHoldingMigrationSuccess(false);
setMigrationComplete(false);
setLastExhaustedStatus(null);
}, [selectedCompanyId]);
const modalStatus = isExhaustedWithTrialAgents ? status : lastExhaustedStatus;
const shouldShowModal =
Boolean(selectedCompanyId) &&
Boolean(modalStatus) &&
!dismissedAfterMigration &&
(isExhaustedWithTrialAgents || holdingMigrationSuccess);
if (!selectedCompanyId || !modalStatus || !shouldShowModal) {
return null;
}
return (
<CloudTrialExhaustedModal
open={shouldShowModal}
companyId={selectedCompanyId}
status={modalStatus}
required={!migrationComplete && modalStatus.canMigrate !== false}
onOpenChange={(open) => {
if (!open) {
setHoldingMigrationSuccess(false);
setMigrationComplete(false);
setDismissedAfterMigration(true);
}
}}
onMigrationStart={() => {
// Lock the modal open BEFORE POST /migrate fires so the server's
// WebSocket `cloud_trial.status.updated` event cannot unmount the
// dialog before the confirmation screen renders.
setHoldingMigrationSuccess(true);
}}
onMigrated={() => {
setHoldingMigrationSuccess(true);
setMigrationComplete(true);
}}
/>
);
}
+2
View File
@@ -1,6 +1,7 @@
import { useDesignSandbox } from "@/context/DesignSandboxContext";
import { DesignSandboxSidebar } from "./DesignSandboxSidebar";
import { BoardDialogs } from "./BoardDialogs";
import { CloudTrialGate } from "./CloudTrialGate";
import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext";
import { PluginAppShellOverlays } from "./PluginAppShellOverlays";
import {
@@ -608,6 +609,7 @@ export function Layout() {
{isMobile && <MobileBottomNav visible={mobileNavVisible} />}
<CommandPalette />
<BoardDialogs />
<CloudTrialGate />
<KeyboardShortcutsCheatsheet
open={shortcutsOpen}
onOpenChange={setShortcutsOpen}
+2
View File
@@ -5,6 +5,7 @@ import { useBrowserTimeZoneSync } from "@/hooks/useBrowserTimeZoneSync";
import { useDesignSandbox } from "@/context/DesignSandboxContext";
import { DesignSandboxSidebar } from "./DesignSandboxSidebar";
import { BoardDialogs } from "./BoardDialogs";
import { CloudTrialGate } from "./CloudTrialGate";
import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
@@ -680,6 +681,7 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
{isMobile && <MobileBottomNav visible={mobileNavVisible} />}
<CommandPalette />
<BoardDialogs />
<CloudTrialGate />
<KeyboardShortcutsCheatsheet open={shortcutsOpen} onOpenChange={setShortcutsOpen} />
<ToastViewport />
{isMobile ? <AnnouncementWell health={health} placement="floating" /> : null}
+113 -1
View File
@@ -11,6 +11,7 @@ import { describeError } from "@/api/errors";
import { LocalProviderLoginInstructions } from "./AdapterLoginChrome";
import { useLocalAiLogin } from "./ai-connections/useLocalAiLogin";
import { aiConnectionsApi } from "@/api/ai-connections";
import { cloudInferenceApi } from "@/api/cloud-inference";
import { aiProviderForAdapter } from "./ai-connections/AiConnectionField";
import { useConnectionModelsState } from "./ai-connections/useConnectionModels";
import type { AiConnectionBinding } from "@paperclipai/shared";
@@ -31,7 +32,7 @@ import type {
Environment,
InstanceSettings,
} from "@paperclipai/shared";
import { AGENT_ROLES, AGENT_ROLE_LABELS, ADAPTER_AUTH_MISSING_CHECK_CODE } from "@paperclipai/shared";
import { AGENT_ROLES, AGENT_ROLE_LABELS, ADAPTER_AUTH_MISSING_CHECK_CODE, resolveCloudTrialModel } from "@paperclipai/shared";
import { AdapterLoginPanel, ModelDropdown } from "./AgentConfigForm";
import {
CONNECT_SOURCE_NAMES,
@@ -151,6 +152,7 @@ import {
Check,
Loader2,
ChevronDown,
Sparkles,
} from "lucide-react";
type Step = 0 | 1 | 2 | 3 | 4 | 5;
@@ -954,6 +956,78 @@ function OnboardingWizardInner({
queryFn: () => instanceSettingsApi.getExperimental(),
enabled: effectiveOnboardingOpen && step >= 3 && step <= 5,
});
const cloudTrialInferenceEnabled = experimentalSettingsForLogin?.enableCloudTrialInference === true;
const { data: cloudTrialStatus } = useQuery({
queryKey: queryKeys.cloudInference.status(createdCompanyId ?? "__none__"),
queryFn: () => cloudInferenceApi.getStatus(createdCompanyId!),
enabled: effectiveOnboardingOpen && step === 4 && Boolean(createdCompanyId) && cloudTrialInferenceEnabled,
});
const canUseCloudTrialStarter =
cloudTrialInferenceEnabled &&
Boolean(cloudTrialStatus) &&
(cloudTrialStatus?.status === "not_issued" || cloudTrialStatus?.status === "active");
const [startingCloudTrial, setStartingCloudTrial] = useState(false);
const trackedTrialExposureCompaniesRef = useRef<Set<string>>(new Set());
useEffect(() => {
if (!effectiveOnboardingOpen || step !== 4 || !createdCompanyId) return;
if (trackedTrialExposureCompaniesRef.current.has(createdCompanyId)) return;
trackedTrialExposureCompaniesRef.current.add(createdCompanyId);
void cloudInferenceApi
.trackTelemetry(createdCompanyId, {
event: "onboarding_exposure",
surface: "onboarding_wizard",
})
.catch(() => {
// Best-effort analytics must never interrupt onboarding.
});
}, [effectiveOnboardingOpen, step, createdCompanyId]);
async function handleStartWithCloudTrial() {
if (!createdCompanyId || startingCloudTrial || loading) return;
setStartingCloudTrial(true);
setError(null);
try {
const hireName = agentName.trim() || AGENT_ROLE_LABELS[agentRole];
const trialModel = resolveCloudTrialModel(cloudTrialStatus?.defaultModel);
await setupSave.current.catch(() => {});
const hire = await agentsApi.hire(createdCompanyId, {
...(setupAgentId ? { setupAgentId } : {}),
name: hireName,
appearance: agentAppearance,
role: agentRole,
...(restoredSetup?.companyId === createdCompanyId ? { reportsTo: restoredSetup.reportsTo } : {}),
adapterType: "paperclip_runner",
adapterConfig: {
provider: "opencode",
model: trialModel,
},
onboardingFirstAgent: true,
...(restoredSetup?.companyId === createdCompanyId && restoredSetup.defaultEnvironmentId
? { defaultEnvironmentId: resolvedLoginEnvironmentId }
: {}),
runtimeConfig: {
...buildNewAgentRuntimeConfig({ heartbeatEnabled: false }),
cloudTrialInference: true,
},
});
if (hire.approval) {
await approvalsApi.approve(
hire.approval.id,
"Approved during onboarding starter-credit setup.",
);
queryClient.invalidateQueries({ queryKey: queryKeys.approvals.list(createdCompanyId) });
}
queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(createdCompanyId) });
queryClient.invalidateQueries({ queryKey: queryKeys.cloudInference.status(createdCompanyId) });
setCreatedAgentId(hire.agent.id);
setStep(5);
} catch (err) {
setError(err instanceof Error ? err.message : "Could not start right away");
} finally {
setStartingCloudTrial(false);
}
}
const loginEnvironmentResolution = useMemo(() => {
try {
return { environmentId: resolveAdapterTestEnvironmentId({
@@ -3069,6 +3143,44 @@ function OnboardingWizardInner({
{/* Step 4: Connect a model — adapter + model + env check (capsule above) */}
{step === 4 && (
<motion.div key="step-4" {...stepContentMotion} exit={stepHandoff ? stepContentMotion.exit : undefined} className="space-y-8">
{canUseCloudTrialStarter && connectPhase === "idle" && (
<div className="rounded-xl border border-border bg-card p-4 shadow-xs space-y-3">
<div className="flex items-start justify-between gap-3">
<div className="space-y-1">
<div className="flex items-center gap-2">
<Sparkles className="size-4 text-primary" />
<span className="text-sm font-semibold text-foreground">
Start right away
</span>
<Badge variant="secondary" className="rounded-full text-xs">
{resolveCloudTrialModel(cloudTrialStatus?.defaultModel).split("/").pop() ?? "Starter"}
</Badge>
</div>
<p className="text-xs text-muted-foreground">
Try Paperclip right away without connecting an account. We’ll ask you to connect a model provider when it’s time to continue.
</p>
</div>
<Button
size="sm"
onClick={handleStartWithCloudTrial}
disabled={startingCloudTrial || loading}
className="shrink-0"
>
{startingCloudTrial ? (
<>
<Loader2 className="size-3.5 mr-1.5 animate-spin" />
Starting…
</>
) : (
<>
Start free
<ArrowRight className="size-3.5 ml-1.5" />
</>
)}
</Button>
</div>
</div>
)}
<div>
<ModelSourceTiles
label="Model source"
@@ -77,6 +77,8 @@ export function AiProviderSetup({
initialProtocol,
providerLabel,
advancedOnly = false,
hideCancel = false,
hideProviderHeading = false,
submitLabel,
reconnect,
onCancel,
@@ -89,6 +91,8 @@ export function AiProviderSetup({
initialProtocol?: AiProviderRouting["protocol"];
providerLabel?: string;
advancedOnly?: boolean;
hideCancel?: boolean;
hideProviderHeading?: boolean;
submitLabel?: string;
reconnect?: AiManagedConnectionSummary;
onCancel: () => void;
@@ -282,13 +286,15 @@ export function AiProviderSetup({
if (!reconnect && accountsView.kind === "error") return <QueryErrorState error={accounts.error} action="load connection permissions" onRetry={accountsView.retry} retrying={accountsView.isFetching} />;
return (
<div className="mx-auto w-full max-w-2xl space-y-6" onSubmit={(event) => event.stopPropagation()}>
<div className="space-y-2">
<h2 className="text-xl font-semibold">
{step === "provider"
? "Connect a model provider"
: `${reconnect ? "Reconnect" : "Connect"} ${label}`}
</h2>
</div>
{!(step === "provider" && hideProviderHeading) && (
<div className="space-y-2">
<h2 className="text-xl font-semibold">
{step === "provider"
? "Connect a model provider"
: `${reconnect ? "Reconnect" : "Connect"} ${label}`}
</h2>
</div>
)}
{agentsView.kind === "error" && <QueryErrorState size="inline" error={agents.error} action="load agents" onRetry={agentsView.retry} retrying={agentsView.isFetching} />}
{step === "provider" ? (
<>
@@ -301,9 +307,11 @@ export function AiProviderSetup({
<div className="pt-4">{choices(true)}</div>
</details>
</>}
<Button type="button" variant="ghost" onClick={onCancel}>
Cancel
</Button>
{!hideCancel && (
<Button type="button" variant="ghost" onClick={onCancel}>
Cancel
</Button>
)}
</>
) : !advanced ? (
<AiConnectionCredentialStep