mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
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:
1 parent
9cfc80b340
commit
64bef50be0
63 files changed
+4295
-52
No files matched your search
@@ -132,6 +132,7 @@ describe("auth routes", () => {
|
||||
stackId: "stack-1",
|
||||
replayEnabled: true,
|
||||
consentRequired: null,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
});
|
||||
|
||||
vi.stubEnv("PAPERCLIP_POSTHOG_COUNTRY_HEADER", "cf-ipcountry");
|
||||
|
||||
@@ -50,6 +50,7 @@ describe("browser analytics config exposure", () => {
|
||||
stackId: "stack-1",
|
||||
replayEnabled,
|
||||
consentRequired: null,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -30,9 +30,31 @@ describe("resolveCloudPostHogConfig", () => {
|
||||
directEnabled: true,
|
||||
browserEnabled: false,
|
||||
replayEnabled: false,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves cloudTrialInferenceEnabled from PAPERCLIP_MANAGED_CONFIG and fails closed when invalid", () => {
|
||||
expect(
|
||||
resolveCloudPostHogConfig({
|
||||
...CLOUD,
|
||||
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({ features: { enableCloudTrialInference: true } }),
|
||||
})?.cloudTrialInferenceEnabled,
|
||||
).toBe(true);
|
||||
expect(
|
||||
resolveCloudPostHogConfig({
|
||||
...CLOUD,
|
||||
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({ features: { enableCloudTrialInference: false } }),
|
||||
})?.cloudTrialInferenceEnabled,
|
||||
).toBe(false);
|
||||
expect(
|
||||
resolveCloudPostHogConfig({
|
||||
...CLOUD,
|
||||
PAPERCLIP_MANAGED_CONFIG: "{not-json",
|
||||
})?.cloudTrialInferenceEnabled,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts the legacy managed-config Cloud signal", () => {
|
||||
const { PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: _omit, ...rest } = CLOUD;
|
||||
expect(resolveCloudPostHogConfig({ ...rest, PAPERCLIP_MANAGED_CONFIG: "{}" })?.stackId).toBe("stack-123");
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
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,
|
||||
createCloudTrialInferenceController,
|
||||
} from "../services/cloud-trial-inference.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,
|
||||
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 },
|
||||
);
|
||||
expect(browserCfg?.cloudTrialInferenceEnabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -147,6 +147,7 @@ describe("instance settings service", () => {
|
||||
enableExternalObjects: false,
|
||||
enableSmokeLab: false,
|
||||
enableCases: false,
|
||||
enableCloudTrialInference: false,
|
||||
enableIssuePlanDecompositions: true,
|
||||
enableExperimentalFileViewer: true,
|
||||
enableBuiltInAgents: true,
|
||||
|
||||
@@ -48,6 +48,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"slack-tools.ts": "/api",
|
||||
"email.ts": "/api",
|
||||
"cloud.ts": "/api/cloud",
|
||||
"cloud-inference.ts": "/api",
|
||||
"customer-success.ts": "/api/customer-success/v1",
|
||||
"companies.ts": "/api/companies",
|
||||
"company-skills.ts": "/api",
|
||||
|
||||
@@ -25,6 +25,8 @@ import {
|
||||
isPostHogDirectTelemetryActive,
|
||||
resetTelemetryForTests,
|
||||
shutdownTelemetry,
|
||||
trackCloudPostHogEvent,
|
||||
trackCloudTrialExposure,
|
||||
} from "../telemetry.js";
|
||||
import type { PostHogNodeClient } from "../services/posthog-direct/index.js";
|
||||
import {
|
||||
@@ -291,7 +293,13 @@ describe("server telemetry sender selection", () => {
|
||||
groupType: "workspace",
|
||||
groupKey: "stack-123",
|
||||
disableGeoip: true,
|
||||
properties: { stack_slug: "acme", primary_host: "acme.paperclip.app", environment: "staging" },
|
||||
properties: {
|
||||
stack_slug: "acme",
|
||||
primary_host: "acme.paperclip.app",
|
||||
environment: "staging",
|
||||
cloud_trial_inference_enabled: false,
|
||||
cloud_trial_inference_cohort: "control",
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(posthog.client.shutdownCalls).toBe(1);
|
||||
@@ -599,4 +607,71 @@ describe("server telemetry sender selection", () => {
|
||||
expect(byState.succeeded!.distinctId).toBe("paperclip-id:creator");
|
||||
expect(byState.succeeded!.properties).toMatchObject({ attributed_via: "task_creator", company_id: "company-1" });
|
||||
});
|
||||
|
||||
it("Cloud: stamps cloud-trial-inference experiment cohort on events and emits deduplicated exposure and funnel events", async () => {
|
||||
const posthog = fakePostHog();
|
||||
const treatmentEnv = {
|
||||
...CLOUD_ENV,
|
||||
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({
|
||||
v: 1,
|
||||
mode: "cloud",
|
||||
catalogVersion: "v1",
|
||||
features: { enableCloudTrialInference: true },
|
||||
plugins: { autoInstall: [] },
|
||||
}),
|
||||
};
|
||||
const client = initTelemetry({ enabled: true }, { env: treatmentEnv, postHogFactory: posthog.factory })!;
|
||||
trackRoutineCreated(client);
|
||||
trackCloudTrialExposure({ surface: "onboarding_wizard", userId: "user-42", companyId: "co-1" });
|
||||
// Second call for the same user/company deduplicates.
|
||||
trackCloudTrialExposure({ surface: "onboarding_wizard", userId: "user-42", companyId: "co-1" });
|
||||
trackCloudPostHogEvent(
|
||||
"cloud_trial.migrated",
|
||||
{ provider: "anthropic", auth_method: "subscription", migrated_agent_count: 1 },
|
||||
{ userId: "user-42", companyId: "co-1" },
|
||||
);
|
||||
await shutdownTelemetry();
|
||||
|
||||
expect(posthog.groups[0]?.properties).toMatchObject({
|
||||
cloud_trial_inference_enabled: true,
|
||||
cloud_trial_inference_cohort: "treatment",
|
||||
});
|
||||
|
||||
const routine = posthog.captured.find((message) => message.event === "routine.created")!;
|
||||
expect(routine.properties).toMatchObject({
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
});
|
||||
|
||||
const exposures = posthog.captured.filter((message) => message.event === "$feature_flag_called");
|
||||
expect(exposures).toHaveLength(1);
|
||||
expect(exposures[0]!.distinctId).toBe("user-42");
|
||||
expect(exposures[0]!.properties).toMatchObject({
|
||||
$feature_flag: "cloud-trial-inference",
|
||||
$feature_flag_response: "treatment",
|
||||
surface: "onboarding_wizard",
|
||||
company_id: "co-1",
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
$set_once: { cloud_trial_inference_cohort: "treatment" },
|
||||
});
|
||||
|
||||
const migrated = posthog.captured.find((message) => message.event === "cloud_trial.migrated")!;
|
||||
expect(migrated.distinctId).toBe("user-42");
|
||||
expect(migrated.properties).toMatchObject({
|
||||
provider: "anthropic",
|
||||
auth_method: "subscription",
|
||||
migrated_agent_count: 1,
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
});
|
||||
});
|
||||
|
||||
it("self-hosted: cloud trial PostHog helpers are no-ops and never load posthog-node", async () => {
|
||||
initTelemetry({ enabled: true }, { env: {} });
|
||||
trackCloudTrialExposure({ surface: "onboarding_wizard", userId: "user-1", companyId: "co-1" });
|
||||
trackCloudPostHogEvent("cloud_trial.started", { source: "onboarding_wizard" }, { userId: "user-1" });
|
||||
await shutdownTelemetry();
|
||||
expect(hoisted.posthogNodeLoads).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ const config: CloudPostHogConfig = {
|
||||
directEnabled: true,
|
||||
browserEnabled: false,
|
||||
replayEnabled: false,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
};
|
||||
|
||||
const startup = {
|
||||
|
||||
Reference in new issue
Block a user