Files
PaperClipAI/server/src/__tests__/cloud-trial-inference.test.ts
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

712 lines
28 KiB
TypeScript

import { generateKeyPairSync, verify } from "node:crypto";
import { createServer, type Server } from "node:http";
import express from "express";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
CLOUD_TRIAL_DEFAULT_MODEL,
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
defaultMigrationTargetForProvider,
parseCloudTrialMigrationTargetsEnv,
resolveCloudTrialModel,
} from "@paperclipai/shared";
import {
CloudTrialExhaustedError,
CloudTrialWorkRequiresModelError,
createCloudTrialInferenceController,
} from "../services/cloud-trial-inference.js";
import { subscribeCompanyLiveEvents } from "../services/live-events.js";
import { cloudInferenceInternalProxyRoutes } from "../routes/cloud-inference.js";
import { resolveBrowserAnalyticsConfig } from "../services/cloud-posthog-browser.js";
import {
resetResolvedCloudTrialInferenceEnabledForTests,
setResolvedCloudTrialInferenceEnabled,
} from "../services/cloud-posthog-cohort.js";
import { createPostHogDirectTransport } from "../services/posthog-direct/transport.js";
function generateTestEd25519Pair() {
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
const privDer = privateKey.export({ format: "der", type: "pkcs8" });
const rawSeed = privDer.subarray(privDer.length - 32);
return {
publicKey,
privateKeyBase64Url: rawSeed.toString("base64url"),
};
}
async function listenExpress(app: express.Express): Promise<{ baseUrl: string; close: () => Promise<void> }> {
const server: Server = createServer(app);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const addr = server.address();
if (!addr || typeof addr !== "object") throw new Error("Failed to bind test server");
return {
baseUrl: `http://127.0.0.1:${addr.port}`,
close: () => new Promise<void>((resolve, reject) => server.close((err) => (err ? reject(err) : resolve()))),
};
}
function fakeDbWithFlag(enabled: boolean) {
const row = {
id: "00000000-0000-0000-0000-000000000001",
singletonKey: "default",
general: {},
experimental: { enableCloudTrialInference: enabled },
defaultEnvironmentId: null,
createdAt: new Date(),
updatedAt: new Date(),
};
return {
select: () => ({
from: () => ({
where: async () => [row],
limit: async () => [row],
}),
}),
} as never;
}
describe("cloud-trial-inference", () => {
const closers: Array<() => Promise<void>> = [];
afterEach(async () => {
while (closers.length > 0) {
await closers.pop()!();
}
resetResolvedCloudTrialInferenceEnabledForTests();
vi.restoreAllMocks();
});
it("signs Cloud requests with Ed25519 only, enforces strict starter model, renews active run tokens, and detects HTTP 402 exhaustion", async () => {
const keypair = generateTestEd25519Pair();
const seenAuthHeaders: string[] = [];
const seenAttributionHeaders: Array<string | undefined> = [];
let return402 = false;
let keyRemainingUsd = 0.75;
let fakeNow = 1_700_000_000_000;
// Mock upstream OpenRouter server
const mockOpenRouter = express();
mockOpenRouter.use(express.json());
mockOpenRouter.post("/api/v1/chat/completions", (req, res) => {
seenAuthHeaders.push(String(req.headers.authorization ?? ""));
seenAttributionHeaders.push(
typeof req.headers["x-openrouter-title"] === "string" ? req.headers["x-openrouter-title"] : undefined,
);
if (return402) {
res.status(402).json({ error: { code: 402, message: "Key limit exceeded" } });
return;
}
res.status(200).json({
id: "chatcmpl-test",
choices: [{ message: { role: "assistant", content: "Hello from Luna!" } }],
});
});
mockOpenRouter.get("/api/v1/key", (_req, res) => {
res.status(200).json({
data: { limit: 1.0, usage: 1.0 - keyRemainingUsd, limit_remaining: keyRemainingUsd },
});
});
const upstream = await listenExpress(mockOpenRouter);
closers.push(upstream.close);
// Mock Cloud Harness server verifying Ed25519 signature (no shared bearer token)
let exhaustedReportedToCloud = false;
const mockCloud = express();
mockCloud.use(express.json());
const verifySignature = (req: express.Request, pathname: string) => {
expect(req.headers.authorization).toBeUndefined();
const stackId = String(req.headers["x-paperclip-cloud-stack-id"] ?? "");
const ts = String(req.headers["x-paperclip-cloud-stack-timestamp"] ?? "");
const sig = String(req.headers["x-paperclip-cloud-stack-signature"] ?? "");
expect(stackId).toBe("stack-test-1");
const payload = Buffer.from(`POST\n${pathname}\n${stackId}\n${ts}`, "utf8");
expect(verify(null, payload, keypair.publicKey, Buffer.from(sig, "base64url"))).toBe(true);
};
mockCloud.post("/v1/tenant/inference-key", (req, res) => {
verifySignature(req, "/v1/tenant/inference-key");
res.status(200).json({
provider: "openrouter",
status: "active",
apiKey: "sk-or-v1-real-secret-key-never-sent-to-sandbox",
limitUsdCents: 100,
spentUsdCents: 0,
remainingUsdCents: 100,
defaultModel: "openrouter/openai/gpt-6-luna",
});
});
mockCloud.post("/v1/tenant/inference-key/exhausted", (req, res) => {
verifySignature(req, "/v1/tenant/inference-key/exhausted");
exhaustedReportedToCloud = true;
res.status(200).json({
provider: "openrouter",
status: "exhausted",
limitUsdCents: 100,
spentUsdCents: 100,
remainingUsdCents: 0,
});
});
const cloud = await listenExpress(mockCloud);
closers.push(cloud.close);
const controller = createCloudTrialInferenceController({
env: {
PAPERCLIP_CLOUD_STACK_ID: "stack-test-1",
PAPERCLIP_CLOUD_API_ORIGIN: cloud.baseUrl,
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "shared-token-must-not-be-sent",
PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY: keypair.privateKeyBase64Url,
PAPERCLIP_CLOUD_TRIAL_OPENROUTER_BASE_URL: `${upstream.baseUrl}/api/v1`,
PAPERCLIP_API_URL: "http://127.0.0.1:3100",
},
now: () => fakeNow,
});
// Mount internal proxy
const proxyApp = express();
proxyApp.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(controller));
const proxy = await listenExpress(proxyApp);
closers.push(proxy.close);
const db = fakeDbWithFlag(true);
// 0. Non-starter model is rejected at run preparation (cannot bypass starter model cap)
await expect(
controller.prepareCloudTrialRuntime(db, {
companyId: "comp-1",
agentId: "agent-1",
runId: "run-bad-model",
model: "openrouter/anthropic/claude-opus-4",
}),
).rejects.toMatchObject({
status: 422,
details: expect.objectContaining({ code: "cloud_trial_model_not_allowed" }),
});
const runtime = await controller.prepareCloudTrialRuntime(db, {
companyId: "comp-1",
agentId: "agent-1",
runId: "run-1",
model: "openrouter/openai/gpt-6-luna",
});
// Raw key MUST NOT be in sandbox env!
expect(runtime.env.OPENROUTER_API_KEY).toBe("");
expect(runtime.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN).toMatch(/^pctrial_/);
expect(runtime.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN).not.toContain("sk-or-v1-real-secret");
expect(runtime.env.PAPERCLIP_OPENROUTER_PROXY_URL).toBe("http://127.0.0.1:3100/api/internal/cloud-inference/v1");
const token = runtime.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN!;
// 1. Invalid token fails closed (401), unknown pctrial_ token reports distinct instance error
const badAuth = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: "Bearer bogus", "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }),
});
expect(badAuth.status).toBe(401);
expect(((await badAuth.json()) as { error: { code: string } }).error.code).toBe("unauthorized");
const unknownRunToken = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: "Bearer pctrial_unknown_from_other_instance", "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }),
});
expect(unknownRunToken.status).toBe(401);
expect(((await unknownRunToken.json()) as { error: { code: string } }).error.code).toBe(
"proxy_token_not_found_on_instance",
);
// 2. Disallowed model, missing model, fallback models array, and fallback route all fail closed (403)
const badModel = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify({ model: "anthropic/claude-opus-4", messages: [] }),
});
expect(badModel.status).toBe(403);
const missingModel = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify({ models: ["anthropic/claude-opus-4"], messages: [] }),
});
expect(missingModel.status).toBe(403);
const fallbackModels = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify({
model: "openai/gpt-6-luna",
models: ["openai/gpt-6-luna", "anthropic/claude-opus-4"],
messages: [],
}),
});
expect(fallbackModels.status).toBe(403);
const fallbackRoute = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify({
model: "openai/gpt-6-luna",
route: "fallback",
messages: [],
}),
});
expect(fallbackRoute.status).toBe(403);
// 3. Allowed model succeeds and active-run token survives multi-hour tool execution gaps until cleanup()
fakeNow += 2 * 60 * 60_000;
const okRes = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "Hi" }] }),
});
expect(okRes.status).toBe(200);
const okBody = (await okRes.json()) as { choices: Array<{ message: { content: string } }> };
expect(okBody.choices[0]!.message.content).toBe("Hello from Luna!");
expect(seenAuthHeaders[0]).toBe("Bearer sk-or-v1-real-secret-key-never-sent-to-sandbox");
expect(seenAttributionHeaders[0]).toBe("Paperclip");
// Advance another 3 hours — still valid while the run remains active!
fakeNow += 3 * 60 * 60_000;
const renewedRes = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "Still running" }] }),
});
expect(renewedRes.status).toBe(200);
// 4. Upstream HTTP 402 immediately triggers exhaustion + Cloud notification + 402 response
return402 = true;
const exhaustedRes = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "More" }] }),
});
expect(exhaustedRes.status).toBe(402);
const exhaustedBody = (await exhaustedRes.json()) as { error: { code: string } };
expect(exhaustedBody.error.code).toBe(CLOUD_TRIAL_EXHAUSTED_ERROR_CODE);
expect(exhaustedReportedToCloud).toBe(true);
// 5. Subsequent run preparation fails immediately with CloudTrialExhaustedError
await expect(
controller.prepareCloudTrialRuntime(db, {
companyId: "comp-1",
agentId: "agent-1",
runId: "run-2",
model: "openrouter/openai/gpt-6-luna",
}),
).rejects.toBeInstanceOf(CloudTrialExhaustedError);
await runtime.cleanup();
});
it("normalizes starter model slugs consistently and maps providers including acpx Google/GitHub and deployment overrides", () => {
expect(resolveCloudTrialModel(undefined)).toBe(CLOUD_TRIAL_DEFAULT_MODEL);
expect(resolveCloudTrialModel("openai/gpt-6-luna")).toBe("openrouter/openai/gpt-6-luna");
expect(resolveCloudTrialModel("openrouter/openai/gpt-6-luna")).toBe("openrouter/openai/gpt-6-luna");
expect(defaultMigrationTargetForProvider("openai", "subscription")).toEqual({
adapterType: "paperclip_runner",
runnerProvider: "codex",
model: "gpt-6-luna",
});
expect(defaultMigrationTargetForProvider("anthropic", "subscription")).toEqual({
adapterType: "paperclip_runner",
runnerProvider: "claude",
model: "claude-sonnet-4-6",
});
expect(defaultMigrationTargetForProvider("google", "subscription")).toEqual({
adapterType: "paperclip_runner",
runnerProvider: "acpx",
acpxAgent: "antigravity",
model: "gemini-2.5-pro",
});
expect(defaultMigrationTargetForProvider("github", "subscription")).toEqual({
adapterType: "paperclip_runner",
runnerProvider: "acpx",
acpxAgent: "copilot",
model: "gpt-5.6-luna",
});
expect(defaultMigrationTargetForProvider("xai", "subscription")).toEqual({
adapterType: "grok_local",
model: "grok-4",
});
const overrides = parseCloudTrialMigrationTargetsEnv(
JSON.stringify({
openai: { model: "gpt-6.5-pro" },
google: { acpxAgent: "antigravity", model: "gemini-3-pro" },
}),
);
expect(defaultMigrationTargetForProvider("openai", "subscription", undefined, overrides)).toEqual({
adapterType: "paperclip_runner",
runnerProvider: "codex",
model: "gpt-6.5-pro",
});
expect(defaultMigrationTargetForProvider("google", "subscription", undefined, overrides)).toEqual({
adapterType: "paperclip_runner",
runnerProvider: "acpx",
acpxAgent: "antigravity",
model: "gemini-3-pro",
});
expect(parseCloudTrialMigrationTargetsEnv("not-json")).toEqual({});
});
it("keeps PostHog server and browser experiment cohort synced with resolved staging overrides", async () => {
const captured: Array<{ event: string; properties?: Record<string, unknown> }> = [];
const transport = createPostHogDirectTransport(
{
token: "phc_test",
host: "https://us.i.posthog.com",
environment: "staging",
stackId: "stack-staging-1",
directEnabled: true,
browserEnabled: true,
replayEnabled: false,
replayWorkContentEnabled: false,
cloudTrialInferenceEnabled: false,
},
{
factory: async () => ({
capture: (msg) => captured.push({ event: msg.event, properties: msg.properties }),
groupIdentify: () => {},
flush: async () => {},
shutdown: async () => {},
}),
},
);
expect(transport.cloudTrialInferenceEnabled).toBe(false);
setResolvedCloudTrialInferenceEnabled(true);
expect(transport.cloudTrialInferenceEnabled).toBe(true);
await transport.captureCloudEvent({ event: "cloud_trial.started", properties: { source: "test" } });
expect(captured[0]?.properties?.cloud_trial_inference_enabled).toBe(true);
expect(captured[0]?.properties?.["$feature/cloud-trial-inference"]).toBe("treatment");
const browserCfg = resolveBrowserAnalyticsConfig(
{
PAPERCLIP_CLOUD_STACK_ID: "stack-staging-1",
PAPERCLIP_CLOUD_HOSTED: "1",
PAPERCLIP_POSTHOG_PROJECT_TOKEN: "phc_test",
PAPERCLIP_POSTHOG_BROWSER_ENABLED: "1",
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({ features: { enableCloudTrialInference: false } }),
},
{},
{ cloudTrialInferenceEnabled: true, onboardingVariant: "free_inference_1" },
);
expect(browserCfg?.cloudTrialInferenceEnabled).toBe(true);
expect(browserCfg?.onboardingVariant).toBe("free_inference_1");
});
it("resolves multi-variant onboarding config from Cloud control plane with Ed25519 signing and safe fallbacks", async () => {
const keypair = generateTestEd25519Pair();
let configCalls = 0;
const mockCloud = express();
mockCloud.get("/v1/tenant/onboarding-config", (req, res) => {
configCalls += 1;
const stackId = String(req.headers["x-paperclip-cloud-stack-id"] ?? "");
const ts = String(req.headers["x-paperclip-cloud-stack-timestamp"] ?? "");
const sig = String(req.headers["x-paperclip-cloud-stack-signature"] ?? "");
const payload = Buffer.from(`GET\n/v1/tenant/onboarding-config\n${stackId}\n${ts}`, "utf8");
expect(verify(null, payload, keypair.publicKey, Buffer.from(sig, "base64url"))).toBe(true);
res.status(200).json({
experimentKey: "onboarding-flow",
onboardingVariant: "free_inference_1",
trialInferenceEnabled: true,
});
});
const cloud = await listenExpress(mockCloud);
closers.push(cloud.close);
const controller = createCloudTrialInferenceController({
env: {
PAPERCLIP_CLOUD_STACK_ID: "stack-variant-1",
PAPERCLIP_CLOUD_API_ORIGIN: cloud.baseUrl,
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token-unused-for-ed25519",
PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY: keypair.privateKeyBase64Url,
},
});
const db = fakeDbWithFlag(false);
const resolved = await controller.resolveOnboardingConfig(db);
expect(resolved).toEqual({
onboardingVariant: "free_inference_1",
trialInferenceEnabled: true,
});
expect(configCalls).toBe(1);
// Self-hosted / unflagged defaults strictly to baseline with trial disabled.
const selfHostedController = createCloudTrialInferenceController({ env: {} });
expect(await selfHostedController.resolveOnboardingConfig(db)).toEqual({
onboardingVariant: "baseline",
trialInferenceEnabled: false,
});
// Env fallback works for local dev / staging testing without Cloud control plane.
const envFallbackController = createCloudTrialInferenceController({
env: { PAPERCLIP_ONBOARDING_VARIANT: "free_inference_1" },
});
expect(await envFallbackController.resolveOnboardingConfig(db)).toEqual({
onboardingVariant: "free_inference_1",
trialInferenceEnabled: true,
});
});
it("holds subtasks on trial-only inference, flips work_requires_model gate, broadcasts live event, and refuses LLM runs until connected", async () => {
const companyId = "00000000-0000-0000-0000-000000000010";
const agentId = "00000000-0000-0000-0000-000000000020";
const issueId = "00000000-0000-0000-0000-000000000030";
// Mock DB with one trial-bound agent and zero active AI connections.
let hasAiConnection = false;
const settingsRow = {
id: "00000000-0000-0000-0000-000000000001",
singletonKey: "default",
general: {},
experimental: { enableCloudTrialInference: true },
defaultEnvironmentId: null,
createdAt: new Date(),
updatedAt: new Date(),
};
const trialAgentRow = {
id: agentId,
companyId,
name: "Luna",
role: "ceo",
title: "Chief of Staff",
runtimeConfig: { cloudTrialInference: true },
createdByUserId: "user-1",
lifecycleState: "active",
pauseReason: null,
};
const heldActivityIds: string[] = [];
const fakeDb = {
insert: () => ({
values: async (val: { entityId?: string }) => {
if (val.entityId) heldActivityIds.push(val.entityId);
},
}),
select: (selection?: Record<string, unknown>) => ({
from: () => {
const buildWhere = () => {
const rows =
selection && "runtimeConfig" in selection
? [trialAgentRow]
: selection && "identifier" in selection && "assigneeAgentId" in selection
? heldActivityIds.map((id) => ({
id,
identifier: "PAP-1",
title: "Build landing page",
assigneeAgentId: agentId,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
}))
: selection && "errorCode" in selection
? []
: selection && "id" in selection && Object.keys(selection).length === 1
? (hasAiConnection ? [{ id: "conn-1" }] : [])
: [settingsRow];
const result = Promise.resolve(rows) as Promise<unknown[]> & {
limit: () => Promise<unknown[]>;
orderBy: () => Promise<unknown[]> & { limit: () => Promise<unknown[]> };
};
result.limit = async () => rows;
result.orderBy = () => {
const ordered = Promise.resolve(rows) as Promise<unknown[]> & {
limit: () => Promise<unknown[]>;
};
ordered.limit = async () => rows;
return ordered;
};
return result;
};
return {
innerJoin: () => ({ where: buildWhere }),
where: buildWhere,
limit: async () => [settingsRow],
};
},
}),
} as never;
const controller = createCloudTrialInferenceController({
env: {
PAPERCLIP_ONBOARDING_VARIANT: "free_inference_1",
PAPERCLIP_CLOUD_TRIAL_OPENROUTER_API_KEY: "sk-or-v1-local-test-key",
},
});
const liveEvents: Array<{ type: string; payload: Record<string, unknown> }> = [];
const unsubscribe = subscribeCompanyLiveEvents(companyId, (event) => {
liveEvents.push({ type: event.type, payload: event.payload });
});
closers.push(async () => {
unsubscribe();
});
// Initially active and unblocked.
const before = await controller.getCompanyStatus(fakeDb, companyId);
expect(before.onboardingVariant).toBe("free_inference_1");
expect(before.gateReason).toBeNull();
expect(before.llmBlocked).toBe(false);
expect(before.heldIssueIds).toEqual([]);
// Trigger B: creating a subtask/work item holds execution and flips gate.
const holdResult = await controller.holdIssueForWorkGate(fakeDb, companyId, {
id: issueId,
identifier: "PAP-1",
title: "Build landing page",
assigneeAgentId: agentId,
});
expect(holdResult.held).toBe(true);
expect(holdResult.heldIssueIds).toEqual([issueId]);
expect(liveEvents).toContainEqual(
expect.objectContaining({
type: "cloud_trial.status.updated",
payload: expect.objectContaining({
gateReason: "work_requires_model",
llmBlocked: true,
heldIssueCount: 1,
}),
}),
);
// Live event payload must remain content-free (no private issue titles/ids).
expect(liveEvents[0]?.payload).not.toHaveProperty("heldIssues");
expect(liveEvents[0]?.payload).not.toHaveProperty("issueId");
const gated = await controller.getCompanyStatus(fakeDb, companyId);
expect(gated.gateReason).toBe("work_requires_model");
expect(gated.llmBlocked).toBe(true);
expect(gated.heldIssueIds).toEqual([issueId]);
expect(gated.heldIssues).toHaveLength(1);
// Dismissible modal, LLM-blocked until connected:
// Both prepareCloudTrialRuntime and assertTrialLlmNotBlocked MUST refuse with HTTP 402.
await expect(
controller.prepareCloudTrialRuntime(fakeDb, {
companyId,
agentId,
runId: "run-blocked-1",
}),
).rejects.toBeInstanceOf(CloudTrialWorkRequiresModelError);
await expect(
controller.assertTrialLlmNotBlocked(fakeDb, companyId, agentId),
).rejects.toMatchObject({
status: 402,
details: expect.objectContaining({
code: "cloud_trial_work_requires_model",
gateReason: "work_requires_model",
heldIssueIds: [issueId],
}),
});
// Once a real AI connection exists, new issues are NOT held by the trial work gate.
hasAiConnection = true;
const afterConnectHold = await controller.holdIssueForWorkGate(fakeDb, companyId, {
id: "00000000-0000-0000-0000-000000000031",
identifier: "PAP-2",
title: "Follow-up task",
assigneeAgentId: agentId,
});
expect(afterConnectHold.held).toBe(false);
});
it("hydrates held subtasks from DB after a process restart/sleep-wake so work gate and LLM blocking survive", async () => {
const companyId = "00000000-0000-0000-0000-000000000011";
const agentId = "00000000-0000-0000-0000-000000000021";
const heldIssueId = "00000000-0000-0000-0000-000000000032";
const settingsRow = {
id: "00000000-0000-0000-0000-000000000001",
singletonKey: "default",
general: {},
experimental: { enableCloudTrialInference: true },
defaultEnvironmentId: null,
createdAt: new Date(),
updatedAt: new Date(),
};
const trialAgentRow = {
id: agentId,
companyId,
name: "Luna",
role: "ceo",
title: "Chief of Staff",
runtimeConfig: { cloudTrialInference: true },
createdByUserId: "user-1",
lifecycleState: "active",
pauseReason: null,
};
const dbHeldIssueRow = {
id: heldIssueId,
identifier: "PAP-9",
title: "Draft launch blog post",
assigneeAgentId: agentId,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
};
const fakeDb = {
select: (selection?: Record<string, unknown>) => ({
from: () => {
const buildWhere = () => {
const rows =
selection && "runtimeConfig" in selection
? [trialAgentRow]
: selection && "identifier" in selection && "assigneeAgentId" in selection
? [dbHeldIssueRow]
: selection && "errorCode" in selection
? []
: selection && "id" in selection && Object.keys(selection).length === 1
? []
: [settingsRow];
const result = Promise.resolve(rows) as Promise<unknown[]> & {
limit: () => Promise<unknown[]>;
orderBy: () => Promise<unknown[]> & { limit: () => Promise<unknown[]> };
};
result.limit = async () => rows;
result.orderBy = () => {
const ordered = Promise.resolve(rows) as Promise<unknown[]> & {
limit: () => Promise<unknown[]>;
};
ordered.limit = async () => rows;
return ordered;
};
return result;
};
return {
innerJoin: () => ({ where: buildWhere }),
where: buildWhere,
limit: async () => [settingsRow],
};
},
}),
} as never;
// Fresh controller simulating a cold process wake after Cloud stack sleep (empty in-memory map).
const freshController = createCloudTrialInferenceController({
env: {
PAPERCLIP_ONBOARDING_VARIANT: "free_inference_1",
PAPERCLIP_CLOUD_TRIAL_OPENROUTER_API_KEY: "sk-or-v1-local-test-key",
},
});
const status = await freshController.getCompanyStatus(fakeDb, companyId);
expect(status.gateReason).toBe("work_requires_model");
expect(status.llmBlocked).toBe(true);
expect(status.heldIssueIds).toEqual([heldIssueId]);
expect(status.heldIssues[0]?.title).toBe("Draft launch blog post");
// A brand-new controller (even before getCompanyStatus is called) also blocks prepareCloudTrialRuntime.
const coldController = createCloudTrialInferenceController({
env: {
PAPERCLIP_ONBOARDING_VARIANT: "free_inference_1",
PAPERCLIP_CLOUD_TRIAL_OPENROUTER_API_KEY: "sk-or-v1-local-test-key",
},
});
await expect(
coldController.prepareCloudTrialRuntime(fakeDb, {
companyId,
agentId,
runId: "run-after-wake",
}),
).rejects.toBeInstanceOf(CloudTrialWorkRequiresModelError);
});
});