mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
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>
This commit is contained in:
1 parent
b63445c8f1
commit
689bfd04ac
41 files changed
+3449
-284
No files matched your search
@@ -4,9 +4,27 @@ import { AI_PROVIDERS, type AiAuthMethod, type AiProvider } from "./ai-connectio
|
||||
const CLOUD_TRIAL_AUTH_METHODS = ["subscription", "api_key"] as const;
|
||||
|
||||
export const CLOUD_TRIAL_EXHAUSTED_ERROR_CODE = "cloud_trial_exhausted" as const;
|
||||
export const CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE = "cloud_trial_work_requires_model" as const;
|
||||
export const CLOUD_TRIAL_DEFAULT_MODEL = "openrouter/openai/gpt-6-luna" as const;
|
||||
export const CLOUD_TRIAL_DEFAULT_LIMIT_USD_CENTS = 100 as const;
|
||||
|
||||
export const ONBOARDING_FLOW_FLAG_KEY = "onboarding-flow" as const;
|
||||
export const DEFAULT_ONBOARDING_VARIANT = "baseline" as const;
|
||||
export const FREE_INFERENCE_ONBOARDING_VARIANT = "free_inference_1" as const;
|
||||
export type OnboardingVariant = string;
|
||||
|
||||
export function normalizeOnboardingVariant(raw?: string | null): OnboardingVariant {
|
||||
const trimmed = raw?.trim();
|
||||
return trimmed ? trimmed : DEFAULT_ONBOARDING_VARIANT;
|
||||
}
|
||||
|
||||
export function isFreeInferenceOnboardingVariant(variant?: string | null): boolean {
|
||||
return normalizeOnboardingVariant(variant) === FREE_INFERENCE_ONBOARDING_VARIANT;
|
||||
}
|
||||
|
||||
export const CLOUD_TRIAL_GATE_REASONS = ["exhausted", "work_requires_model"] as const;
|
||||
export type CloudTrialGateReason = (typeof CLOUD_TRIAL_GATE_REASONS)[number];
|
||||
|
||||
/**
|
||||
* Canonical starter-trial model normalizer used across onboarding seed, UI,
|
||||
* and server proxy/key-store so every layer agrees on the `openrouter/` prefix.
|
||||
@@ -35,11 +53,29 @@ export interface CloudTrialBlockedRunSummary {
|
||||
failedAt: string;
|
||||
}
|
||||
|
||||
export interface CloudTrialHeldIssueSummary {
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
title: string;
|
||||
assigneeAgentId: string | null;
|
||||
heldAt: string;
|
||||
}
|
||||
|
||||
export interface CloudTrialInferenceStatus {
|
||||
enabled: boolean;
|
||||
/** Assigned onboarding experiment variant ("baseline", "free_inference_1", or future variants). */
|
||||
onboardingVariant: OnboardingVariant;
|
||||
provider: "openrouter";
|
||||
status: CloudTrialInferenceState;
|
||||
reason?: string;
|
||||
/** Active connect-model gate reason, or null when unblocked. */
|
||||
gateReason: CloudTrialGateReason | null;
|
||||
/** True when trial-only LLM/chat runs are blocked until the user connects a model provider. */
|
||||
llmBlocked: boolean;
|
||||
/** Issue IDs created while on trial-only inference whose execution is held until model connection. */
|
||||
heldIssueIds: string[];
|
||||
/** Human-readable summaries of held tasks/subtasks for modal copy. */
|
||||
heldIssues: CloudTrialHeldIssueSummary[];
|
||||
limitUsdCents: number;
|
||||
spentUsdCents: number;
|
||||
remainingUsdCents: number;
|
||||
@@ -82,6 +118,7 @@ export const cloudTrialTelemetryEventSchema = z.discriminatedUnion("event", [
|
||||
z.object({
|
||||
event: z.literal("modal_shown"),
|
||||
trialAgentCount: z.number().int().nonnegative().max(1000),
|
||||
gateReason: z.enum(CLOUD_TRIAL_GATE_REASONS).optional(),
|
||||
}).strict(),
|
||||
]);
|
||||
|
||||
@@ -101,6 +138,7 @@ export interface MigrateCloudTrialAgentsResult {
|
||||
agents: MigratedCloudTrialAgentSummary[];
|
||||
resumedRunIds: string[];
|
||||
resumedIssueId: string | null;
|
||||
resumedIssueIds: string[];
|
||||
}
|
||||
|
||||
export interface CloudTrialMigrationTarget {
|
||||
|
||||
@@ -237,6 +237,7 @@ export const browserAnalyticsConfigSchema = z.object({
|
||||
replayWorkContentEnabled: z.boolean().optional(),
|
||||
consentRequired: z.boolean().nullable().optional(),
|
||||
cloudTrialInferenceEnabled: z.boolean().optional(),
|
||||
onboardingVariant: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
export type BrowserAnalyticsConfig = z.infer<typeof browserAnalyticsConfigSchema>;
|
||||
@@ -262,6 +263,8 @@ export const authSessionSchema = z.object({
|
||||
// Null or absent leaves browser product analytics off; the browser then never
|
||||
// downloads posthog-js. Optional for browser/server version skew.
|
||||
browserAnalytics: browserAnalyticsConfigSchema.nullable().optional(),
|
||||
// Assigned onboarding experiment variant ("baseline", "free_inference_1", etc.).
|
||||
onboardingVariant: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
export type AuthSession = z.infer<typeof authSessionSchema>;
|
||||
|
||||
@@ -97,6 +97,7 @@ describe("auth routes", () => {
|
||||
sentryEnvironment: null,
|
||||
browserTracing: null,
|
||||
browserAnalytics: null,
|
||||
onboardingVariant: "baseline",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -135,6 +136,7 @@ describe("auth routes", () => {
|
||||
replayWorkContentEnabled: false,
|
||||
consentRequired: false,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
onboardingVariant: "baseline",
|
||||
});
|
||||
|
||||
vi.stubEnv("PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED", "1");
|
||||
|
||||
@@ -52,6 +52,7 @@ describe("browser analytics config exposure", () => {
|
||||
replayWorkContentEnabled: false,
|
||||
consentRequired: false,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
onboardingVariant: "baseline",
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ describe("resolveCloudPostHogConfig", () => {
|
||||
replayEnabled: false,
|
||||
replayWorkContentEnabled: false,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
onboardingVariant: "baseline",
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -166,11 +166,13 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
|
||||
});
|
||||
|
||||
it("re-identifies the PostHog workspace group with the claimed slug and host", async () => {
|
||||
const groupIdentifies: Array<Parameters<PostHogNodeClient["groupIdentify"]>[0]> = [];
|
||||
const groupIdentifies: Array<Parameters<PostHogNodeClient["capture"]>[0]> = [];
|
||||
const flush = vi.fn(async () => {});
|
||||
const fakeClient: PostHogNodeClient = {
|
||||
capture: () => {},
|
||||
groupIdentify: (message) => void groupIdentifies.push(message),
|
||||
capture: (message) => {
|
||||
if (message.event === "$groupidentify") groupIdentifies.push(message);
|
||||
},
|
||||
groupIdentify: () => {},
|
||||
flush,
|
||||
shutdown: async () => {},
|
||||
};
|
||||
@@ -201,7 +203,7 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
|
||||
});
|
||||
|
||||
expect(groupIdentifies).toHaveLength(1);
|
||||
expect(groupIdentifies[0]?.properties).toMatchObject({
|
||||
expect(groupIdentifies[0]?.properties?.$group_set).toMatchObject({
|
||||
stack_slug: "pool-123",
|
||||
primary_host: "pool-123.staging.paperclip.app",
|
||||
});
|
||||
@@ -215,10 +217,10 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
|
||||
await vi.waitFor(() => {
|
||||
expect(groupIdentifies).toHaveLength(2);
|
||||
});
|
||||
expect(groupIdentifies[1]).toMatchObject({
|
||||
groupType: "workspace",
|
||||
groupKey: STACK_ID,
|
||||
properties: {
|
||||
expect(groupIdentifies[1]?.properties).toMatchObject({
|
||||
$group_type: "workspace",
|
||||
$group_key: STACK_ID,
|
||||
$group_set: {
|
||||
stack_slug: "gonzo",
|
||||
primary_host: "gonzo.staging.paperclip.app",
|
||||
environment: "staging",
|
||||
@@ -240,10 +242,12 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
|
||||
});
|
||||
|
||||
it("uses the claimed slug and host when the claim arrives while PostHog client loading is in flight", async () => {
|
||||
const groupIdentifies: Array<Parameters<PostHogNodeClient["groupIdentify"]>[0]> = [];
|
||||
const groupIdentifies: Array<Parameters<PostHogNodeClient["capture"]>[0]> = [];
|
||||
const fakeClient: PostHogNodeClient = {
|
||||
capture: () => {},
|
||||
groupIdentify: (message) => void groupIdentifies.push(message),
|
||||
capture: (message) => {
|
||||
if (message.event === "$groupidentify") groupIdentifies.push(message);
|
||||
},
|
||||
groupIdentify: () => {},
|
||||
flush: async () => {},
|
||||
shutdown: async () => {},
|
||||
};
|
||||
@@ -287,10 +291,10 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
|
||||
await announcePromise;
|
||||
|
||||
expect(groupIdentifies).toHaveLength(1);
|
||||
expect(groupIdentifies[0]).toMatchObject({
|
||||
groupType: "workspace",
|
||||
groupKey: STACK_ID,
|
||||
properties: {
|
||||
expect(groupIdentifies[0]?.properties).toMatchObject({
|
||||
$group_type: "workspace",
|
||||
$group_key: STACK_ID,
|
||||
$group_set: {
|
||||
stack_slug: "gonzo",
|
||||
primary_host: "gonzo.staging.paperclip.app",
|
||||
environment: "staging",
|
||||
|
||||
@@ -11,8 +11,10 @@ import {
|
||||
} 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 {
|
||||
@@ -388,8 +390,322 @@ describe("cloud-trial-inference", () => {
|
||||
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({ features: { enableCloudTrialInference: false } }),
|
||||
},
|
||||
{},
|
||||
{ cloudTrialInferenceEnabled: true },
|
||||
{ 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);
|
||||
});
|
||||
});
|
||||
@@ -238,6 +238,7 @@ describe("server telemetry sender selection", () => {
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(posthog.captured.map((message) => message.event).sort()).toEqual([
|
||||
"$groupidentify",
|
||||
"agent.task_run",
|
||||
"cloud.workspace_started",
|
||||
"company.imported",
|
||||
@@ -284,21 +285,32 @@ describe("server telemetry sender selection", () => {
|
||||
$process_person_profile: false,
|
||||
});
|
||||
for (const message of posthog.captured) {
|
||||
expect(message.properties?.environment, message.event).toBe("staging");
|
||||
if (message.event !== "$groupidentify") expect(message.properties?.attributed_via, message.event).toBe("none");
|
||||
if (message.event !== "$groupidentify") {
|
||||
expect(message.properties?.environment, message.event).toBe("staging");
|
||||
expect(message.properties?.attributed_via, message.event).toBe("none");
|
||||
}
|
||||
if (message.event !== "cloud.workspace_started") expect(message.properties).not.toHaveProperty("install_hash");
|
||||
}
|
||||
expect(posthog.groups).toEqual([
|
||||
const groupIdentifies = posthog.captured.filter((message) => message.event === "$groupidentify");
|
||||
expect(groupIdentifies).toEqual([
|
||||
{
|
||||
groupType: "workspace",
|
||||
groupKey: "stack-123",
|
||||
distinctId: "$groups_workspace_stack-123",
|
||||
event: "$groupidentify",
|
||||
disableGeoip: true,
|
||||
sendFeatureFlags: false,
|
||||
properties: {
|
||||
stack_slug: "acme",
|
||||
primary_host: "acme.paperclip.app",
|
||||
environment: "staging",
|
||||
cloud_trial_inference_enabled: false,
|
||||
cloud_trial_inference_cohort: "control",
|
||||
$group_type: "workspace",
|
||||
$group_key: "stack-123",
|
||||
$group_set: {
|
||||
stack_slug: "acme",
|
||||
primary_host: "acme.paperclip.app",
|
||||
environment: "staging",
|
||||
cloud_trial_inference_enabled: false,
|
||||
cloud_trial_inference_cohort: "control",
|
||||
onboarding_variant: "baseline",
|
||||
"$feature/onboarding-flow": "baseline",
|
||||
},
|
||||
$process_person_profile: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -632,28 +644,48 @@ describe("server telemetry sender selection", () => {
|
||||
);
|
||||
await shutdownTelemetry();
|
||||
|
||||
expect(posthog.groups[0]?.properties).toMatchObject({
|
||||
cloud_trial_inference_enabled: true,
|
||||
cloud_trial_inference_cohort: "treatment",
|
||||
const groupIdentifies = posthog.captured.filter((message) => message.event === "$groupidentify");
|
||||
// Once onboarding variant resolves (via Cloud config or exposure), $group_set_once is stamped.
|
||||
const resolvedGroupIdentify = groupIdentifies.find((message) => message.properties?.$group_set_once);
|
||||
expect(resolvedGroupIdentify?.properties).toMatchObject({
|
||||
$group_type: "workspace",
|
||||
$group_key: "stack-123",
|
||||
$group_set: {
|
||||
cloud_trial_inference_enabled: true,
|
||||
cloud_trial_inference_cohort: "treatment",
|
||||
onboarding_variant: "free_inference_1",
|
||||
"$feature/onboarding-flow": "free_inference_1",
|
||||
},
|
||||
$group_set_once: {
|
||||
initial_onboarding_variant: "free_inference_1",
|
||||
onboarding_variant: "free_inference_1",
|
||||
},
|
||||
});
|
||||
|
||||
const routine = posthog.captured.find((message) => message.event === "routine.created")!;
|
||||
expect(routine.properties).toMatchObject({
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
onboarding_variant: "free_inference_1",
|
||||
"$feature/onboarding-flow": "free_inference_1",
|
||||
});
|
||||
|
||||
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",
|
||||
$feature_flag: "onboarding-flow",
|
||||
$feature_flag_response: "free_inference_1",
|
||||
surface: "onboarding_wizard",
|
||||
company_id: "co-1",
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
$set_once: { cloud_trial_inference_cohort: "treatment" },
|
||||
onboarding_variant: "free_inference_1",
|
||||
"$feature/onboarding-flow": "free_inference_1",
|
||||
$set_once: {
|
||||
initial_onboarding_variant: "free_inference_1",
|
||||
cloud_trial_inference_cohort: "treatment",
|
||||
},
|
||||
});
|
||||
|
||||
const migrated = posthog.captured.find((message) => message.event === "cloud_trial.migrated")!;
|
||||
@@ -664,6 +696,12 @@ describe("server telemetry sender selection", () => {
|
||||
migrated_agent_count: 1,
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
onboarding_variant: "free_inference_1",
|
||||
"$feature/onboarding-flow": "free_inference_1",
|
||||
$set_once: {
|
||||
initial_onboarding_variant: "free_inference_1",
|
||||
cloud_trial_inference_cohort: "treatment",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -58,8 +58,7 @@ describe("PostHog direct transport", () => {
|
||||
});
|
||||
|
||||
expect(result).toEqual({ kind: "ok" });
|
||||
expect(fake.groups).toEqual(["stack-123"]);
|
||||
expect(fake.captured).toEqual(["cloud.workspace_started", "routine.created"]);
|
||||
expect(fake.captured).toEqual(["$groupidentify", "cloud.workspace_started", "routine.created"]);
|
||||
|
||||
// Sent once only.
|
||||
await transport.send({
|
||||
|
||||
@@ -393,6 +393,22 @@ export function setupLiveEventsWebSocketServer(
|
||||
if (event.type === "external_object.updated") return { ...event, payload: { externalObjectId: payload.externalObjectId } };
|
||||
// Only the id: reading the checklist itself goes through the board-only API.
|
||||
if (event.type === "agent_setup_progress.updated") return { ...event, payload: { progressId: payload.progressId } };
|
||||
// Safe, content-free gate status notification (no private issue titles/ids);
|
||||
// the browser refetches `/api/companies/:companyId/cloud-inference/status`.
|
||||
if (event.type === "cloud_trial.status.updated") {
|
||||
return {
|
||||
...event,
|
||||
payload: {
|
||||
...(typeof payload.status === "string" ? { status: payload.status } : {}),
|
||||
...(payload.gateReason === null || typeof payload.gateReason === "string"
|
||||
? { gateReason: payload.gateReason }
|
||||
: {}),
|
||||
...(typeof payload.llmBlocked === "boolean" ? { llmBlocked: payload.llmBlocked } : {}),
|
||||
...(typeof payload.heldIssueCount === "number" ? { heldIssueCount: payload.heldIssueCount } : {}),
|
||||
...(typeof payload.migratedCount === "number" ? { migratedCount: payload.migratedCount } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (event.type.startsWith("plugin.")) return event;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -14,8 +14,11 @@ import { resolveBrowserTracingConfig, warnOnce } from "../browser-tracing-config
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { loadBoardBootstrap } from "../services/board-bootstrap.js";
|
||||
import { resolveBrowserAnalyticsConfig } from "../services/cloud-posthog-browser.js";
|
||||
import { setResolvedCloudTrialInferenceEnabled } from "../services/cloud-posthog-cohort.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import {
|
||||
setResolvedCloudTrialInferenceEnabled,
|
||||
setResolvedOnboardingVariant,
|
||||
} from "../services/cloud-posthog-cohort.js";
|
||||
import { getDefaultCloudTrialInferenceController } from "../services/cloud-trial-inference.js";
|
||||
|
||||
async function loadCurrentUserProfile(db: Db, userId: string) {
|
||||
const user = await db
|
||||
@@ -58,18 +61,22 @@ export function authRoutes(db: Db) {
|
||||
return undefined;
|
||||
})
|
||||
: Promise.resolve(undefined);
|
||||
const [user, boardBootstrap, experimental] = await Promise.all([
|
||||
const [user, boardBootstrap, onboardingConfig] = await Promise.all([
|
||||
loadCurrentUserProfile(db, req.actor.userId),
|
||||
bootstrap,
|
||||
instanceSettingsService(db)
|
||||
.getExperimental()
|
||||
getDefaultCloudTrialInferenceController()
|
||||
.resolveOnboardingConfig(db)
|
||||
.catch(() => null),
|
||||
]);
|
||||
const cloudTrialInferenceEnabled =
|
||||
experimental !== null ? experimental.enableCloudTrialInference === true : undefined;
|
||||
onboardingConfig !== null ? onboardingConfig.trialInferenceEnabled : undefined;
|
||||
const onboardingVariant = onboardingConfig?.onboardingVariant;
|
||||
if (typeof cloudTrialInferenceEnabled === "boolean") {
|
||||
setResolvedCloudTrialInferenceEnabled(cloudTrialInferenceEnabled);
|
||||
}
|
||||
if (onboardingVariant) {
|
||||
setResolvedOnboardingVariant(onboardingVariant);
|
||||
}
|
||||
res.setHeader("Cache-Control", "private, no-store");
|
||||
const session = authSessionSchema.parse({
|
||||
session: {
|
||||
@@ -91,7 +98,9 @@ export function authRoutes(db: Db) {
|
||||
// null everywhere else. See `server/src/services/cloud-posthog-browser.ts`.
|
||||
browserAnalytics: resolveBrowserAnalyticsConfig(process.env, req.headers, {
|
||||
...(typeof cloudTrialInferenceEnabled === "boolean" ? { cloudTrialInferenceEnabled } : {}),
|
||||
...(onboardingVariant ? { onboardingVariant } : {}),
|
||||
}),
|
||||
...(onboardingVariant ? { onboardingVariant } : {}),
|
||||
});
|
||||
res.json({ ...session, ...(boardBootstrap ? { boardBootstrap } : {}) });
|
||||
});
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
getDefaultCloudTrialInferenceController,
|
||||
type CloudTrialInferenceController,
|
||||
} from "../services/cloud-trial-inference.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { trackCloudPostHogEvent, trackCloudTrialExposure } from "../telemetry.js";
|
||||
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
|
||||
@@ -107,19 +106,23 @@ export function cloudInferenceRoutes(
|
||||
const actor = getActorInfo(req);
|
||||
const body = req.body as
|
||||
| { event: "onboarding_exposure"; surface: "onboarding_wizard" | "onboarding_seed" }
|
||||
| { event: "modal_shown"; trialAgentCount: number };
|
||||
| { event: "modal_shown"; trialAgentCount: number; gateReason?: "exhausted" | "work_requires_model" };
|
||||
if (body.event === "onboarding_exposure") {
|
||||
const experimental = await instanceSettingsService(db).getExperimental();
|
||||
const effective = await controller.resolveOnboardingConfig(db);
|
||||
trackCloudTrialExposure({
|
||||
surface: body.surface,
|
||||
userId: actor.actorId,
|
||||
companyId,
|
||||
enabledOverride: experimental.enableCloudTrialInference === true,
|
||||
enabledOverride: effective.trialInferenceEnabled,
|
||||
onboardingVariantOverride: effective.onboardingVariant,
|
||||
});
|
||||
} else if (body.event === "modal_shown") {
|
||||
trackCloudPostHogEvent(
|
||||
"cloud_trial.modal_shown",
|
||||
{ trial_agent_count: body.trialAgentCount },
|
||||
{
|
||||
trial_agent_count: body.trialAgentCount,
|
||||
...(body.gateReason ? { gate_reason: body.gateReason } : {}),
|
||||
},
|
||||
{ userId: actor.actorId, companyId },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -326,6 +326,11 @@ import {
|
||||
} from "../attachment-types.js";
|
||||
import { retainBacklogHumanAssignment } from "../services/human-directed-work.js";
|
||||
import { queueIssueAssignmentWakeup } from "../services/issue-assignment-wakeup.js";
|
||||
import {
|
||||
getDefaultCloudTrialInferenceController,
|
||||
isCloudTrialWorkGateExecutableStatus,
|
||||
isCloudTrialWorkGateExemptOriginKind,
|
||||
} from "../services/cloud-trial-inference.js";
|
||||
import { shouldWakeAssigneeForIssueComment } from "../services/issue-comment-wakeup.js";
|
||||
import { createSecretProposalsService } from "../services/secret-proposals.js";
|
||||
import {
|
||||
@@ -13854,9 +13859,26 @@ export function issueRoutes(
|
||||
// (deterministic, no LLM) and the user's first comment wakes the assignee
|
||||
// through the normal comment path. A task created already done or
|
||||
// cancelled is a record, not work: like restoring an assignee on closed
|
||||
// work, it must not wake the assignee. Every other create keeps its wake.
|
||||
// work, it must not wake the assignee. Every other create keeps its wake,
|
||||
// unless the company is on Cloud trial-only inference (Trigger B): allow
|
||||
// the task/subtask to be created in a held state without dispatching a
|
||||
// trial run and flip the connect-model gate.
|
||||
const cloudTrialWorkHeld =
|
||||
!isOnboardingFirstTask &&
|
||||
!issue.conversationAgentId &&
|
||||
isCloudTrialWorkGateExecutableStatus(issue.status) &&
|
||||
!isCloudTrialWorkGateExemptOriginKind(issue.originKind)
|
||||
? (
|
||||
await getDefaultCloudTrialInferenceController().holdIssueForWorkGate(db, companyId, {
|
||||
id: issue.id,
|
||||
identifier: issue.identifier ?? null,
|
||||
title: issue.title,
|
||||
assigneeAgentId: issue.assigneeAgentId ?? null,
|
||||
})
|
||||
).held
|
||||
: false;
|
||||
|
||||
if (!isOnboardingFirstTask && !isClosedIssueStatus(issue.status)) {
|
||||
if (!isOnboardingFirstTask && !isClosedIssueStatus(issue.status) && !cloudTrialWorkHeld) {
|
||||
void queueIssueAssignmentWakeup({
|
||||
heartbeat,
|
||||
issue,
|
||||
@@ -18719,6 +18741,21 @@ export function issueRoutes(
|
||||
}
|
||||
|
||||
for (const createdIssue of createdIssues) {
|
||||
const heldByTrialGate = isCloudTrialWorkGateExecutableStatus(createdIssue.status)
|
||||
? (
|
||||
await getDefaultCloudTrialInferenceController().holdIssueForWorkGate(
|
||||
db,
|
||||
issue.companyId,
|
||||
{
|
||||
id: createdIssue.id,
|
||||
identifier: null,
|
||||
title: "Suggested task",
|
||||
assigneeAgentId: createdIssue.assigneeAgentId ?? null,
|
||||
},
|
||||
)
|
||||
).held
|
||||
: false;
|
||||
if (heldByTrialGate) continue;
|
||||
void queueIssueAssignmentWakeup({
|
||||
heartbeat,
|
||||
issue: createdIssue,
|
||||
@@ -19729,6 +19766,14 @@ export function issueRoutes(
|
||||
"Issue not found",
|
||||
);
|
||||
if (!issue) return;
|
||||
const targetTrialAgentId = issue.conversationAgentId ?? issue.assigneeAgentId;
|
||||
if (req.actor.type === "board" && targetTrialAgentId) {
|
||||
await getDefaultCloudTrialInferenceController().assertTrialLlmNotBlocked(
|
||||
db,
|
||||
issue.companyId,
|
||||
targetTrialAgentId,
|
||||
);
|
||||
}
|
||||
// Trusted /swarm: the composer sends it as a structured field; comment text is never read as a command.
|
||||
const swarmRequested = req.body.nativeCommand === ANTIGRAVITY_SWARM_COMMAND;
|
||||
if (swarmRequested) {
|
||||
|
||||
@@ -9,7 +9,13 @@
|
||||
// The browser sends to `POSTHOG_PROXY_PATH` on its own origin, not to PostHog,
|
||||
// so ad blockers do not drop the events. See `routes/posthog-proxy.ts`.
|
||||
|
||||
import type { BrowserAnalyticsConfig } from "@paperclipai/shared";
|
||||
import {
|
||||
DEFAULT_ONBOARDING_VARIANT,
|
||||
FREE_INFERENCE_ONBOARDING_VARIANT,
|
||||
normalizeOnboardingVariant,
|
||||
type BrowserAnalyticsConfig,
|
||||
type OnboardingVariant,
|
||||
} from "@paperclipai/shared";
|
||||
import { isCloudStagingInstance, type CloudInstanceEnv } from "./cloud-instance.js";
|
||||
import { resolveCloudPostHogConfig, type CloudPostHogConfig } from "./cloud-posthog-config.js";
|
||||
|
||||
@@ -47,7 +53,7 @@ export function posthogUiHost(ingestHost: string): string | null {
|
||||
export function resolveBrowserAnalyticsConfig(
|
||||
env: CloudInstanceEnv = process.env,
|
||||
_headers: RequestHeaders = {},
|
||||
options?: { cloudTrialInferenceEnabled?: boolean },
|
||||
options?: { cloudTrialInferenceEnabled?: boolean; onboardingVariant?: OnboardingVariant },
|
||||
): BrowserAnalyticsConfig | null {
|
||||
const config = resolveBrowserPostHogConfig(env);
|
||||
if (!config) return null;
|
||||
@@ -58,6 +64,17 @@ export function resolveBrowserAnalyticsConfig(
|
||||
// An invalid host cannot be proxied either; keep browser analytics off.
|
||||
return null;
|
||||
}
|
||||
const cloudTrialInferenceEnabled =
|
||||
typeof options?.cloudTrialInferenceEnabled === "boolean"
|
||||
? options.cloudTrialInferenceEnabled
|
||||
: config.cloudTrialInferenceEnabled;
|
||||
const onboardingVariant = options?.onboardingVariant
|
||||
? normalizeOnboardingVariant(options.onboardingVariant)
|
||||
: typeof options?.cloudTrialInferenceEnabled === "boolean"
|
||||
? (options.cloudTrialInferenceEnabled
|
||||
? FREE_INFERENCE_ONBOARDING_VARIANT
|
||||
: DEFAULT_ONBOARDING_VARIANT)
|
||||
: normalizeOnboardingVariant(config.onboardingVariant);
|
||||
return {
|
||||
token: config.token,
|
||||
apiHost: POSTHOG_PROXY_PATH,
|
||||
@@ -71,9 +88,7 @@ export function resolveBrowserAnalyticsConfig(
|
||||
// Consent banner is disabled during private beta; sending false also keeps
|
||||
// any cached older UI bundle from prompting during rollout.
|
||||
consentRequired: false,
|
||||
cloudTrialInferenceEnabled:
|
||||
typeof options?.cloudTrialInferenceEnabled === "boolean"
|
||||
? options.cloudTrialInferenceEnabled
|
||||
: config.cloudTrialInferenceEnabled,
|
||||
cloudTrialInferenceEnabled,
|
||||
onboardingVariant,
|
||||
};
|
||||
}
|
||||
@@ -1,17 +1,24 @@
|
||||
import { normalizeOnboardingVariant, type OnboardingVariant } from "@paperclipai/shared";
|
||||
|
||||
/**
|
||||
* Process-scoped resolved state for the Cloud starter-inference experiment flag.
|
||||
* Process-scoped resolved state for the Cloud onboarding / starter-inference
|
||||
* experiment flags.
|
||||
*
|
||||
* `instance-settings.ts` updates this whenever the effective experimental
|
||||
* settings are resolved (including staging database overrides), while PostHog
|
||||
* direct transport and browser analytics read it so runtime behavior,
|
||||
* `instance-settings.ts`, `cloud-trial-key-store.ts`, and `routes/auth.ts`
|
||||
* update this whenever the effective onboarding variant or experimental
|
||||
* settings are resolved (including control-plane `/v1/tenant/onboarding-config`
|
||||
* responses and staging database overrides), while PostHog direct transport
|
||||
* and browser analytics read it so runtime behavior, `$feature/onboarding-flow`,
|
||||
* `$feature/cloud-trial-inference`, browser super-properties, `$groupidentify`,
|
||||
* and server events always agree on the active cohort.
|
||||
* and server events always agree on the active variant/cohort.
|
||||
*
|
||||
* Kept in its own leaf module (separate from `telemetry.ts`) so existing tests
|
||||
* that mock `../telemetry.js` never break on an unmocked export.
|
||||
*/
|
||||
let resolvedCloudTrialInferenceEnabled: boolean | null = null;
|
||||
let resolvedOnboardingVariant: OnboardingVariant | null = null;
|
||||
const listeners = new Set<(enabled: boolean) => void>();
|
||||
const variantListeners = new Set<(variant: OnboardingVariant) => void>();
|
||||
|
||||
export function setResolvedCloudTrialInferenceEnabled(enabled: boolean): void {
|
||||
const changed = resolvedCloudTrialInferenceEnabled !== enabled;
|
||||
@@ -40,7 +47,37 @@ export function onCloudTrialInferenceCohortChange(
|
||||
};
|
||||
}
|
||||
|
||||
export function setResolvedOnboardingVariant(variant: OnboardingVariant): void {
|
||||
const normalized = normalizeOnboardingVariant(variant);
|
||||
const changed = resolvedOnboardingVariant !== normalized;
|
||||
resolvedOnboardingVariant = normalized;
|
||||
if (changed) {
|
||||
for (const listener of variantListeners) {
|
||||
try {
|
||||
listener(normalized);
|
||||
} catch {
|
||||
// Best-effort analytics listeners must never disrupt onboarding reads.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getResolvedOnboardingVariant(): OnboardingVariant | null {
|
||||
return resolvedOnboardingVariant;
|
||||
}
|
||||
|
||||
export function onOnboardingVariantChange(
|
||||
listener: (variant: OnboardingVariant) => void,
|
||||
): () => void {
|
||||
variantListeners.add(listener);
|
||||
return () => {
|
||||
variantListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function resetResolvedCloudTrialInferenceEnabledForTests(): void {
|
||||
resolvedCloudTrialInferenceEnabled = null;
|
||||
resolvedOnboardingVariant = null;
|
||||
listeners.clear();
|
||||
variantListeners.clear();
|
||||
}
|
||||
@@ -1,37 +1,126 @@
|
||||
import {
|
||||
DEFAULT_ONBOARDING_VARIANT,
|
||||
FREE_INFERENCE_ONBOARDING_VARIANT,
|
||||
ONBOARDING_FLOW_FLAG_KEY,
|
||||
isFreeInferenceOnboardingVariant,
|
||||
normalizeOnboardingVariant,
|
||||
type OnboardingVariant,
|
||||
} from "@paperclipai/shared";
|
||||
import { isCloudManagedInstance, type CloudInstanceEnv } from "./cloud-instance.js";
|
||||
import { getResolvedCloudTrialInferenceEnabled } from "./cloud-posthog-cohort.js";
|
||||
import {
|
||||
getResolvedCloudTrialInferenceEnabled,
|
||||
getResolvedOnboardingVariant,
|
||||
} from "./cloud-posthog-cohort.js";
|
||||
|
||||
/**
|
||||
* PostHog experiment / feature flag key for the Cloud starter-inference A/B test.
|
||||
* Stamped onto workspace groups, direct server events, browser super-properties,
|
||||
* and `$feature_flag_called` exposure events so every onboarding, activation,
|
||||
* conversion, and retention chart can split treatment vs. control cleanly.
|
||||
* PostHog experiment / feature flag key for the Cloud starter-inference A/B test
|
||||
* (legacy binary flag kept for backwards compatibility alongside `onboarding-flow`).
|
||||
*/
|
||||
export const CLOUD_TRIAL_INFERENCE_FLAG_KEY = "cloud-trial-inference";
|
||||
export type CloudTrialInferenceCohort = "treatment" | "control";
|
||||
|
||||
export { ONBOARDING_FLOW_FLAG_KEY, DEFAULT_ONBOARDING_VARIANT, FREE_INFERENCE_ONBOARDING_VARIANT };
|
||||
export type { OnboardingVariant };
|
||||
|
||||
export function cloudTrialInferenceCohort(enabled: boolean): CloudTrialInferenceCohort {
|
||||
return enabled ? "treatment" : "control";
|
||||
}
|
||||
|
||||
function parseManagedConfigObject(env: CloudInstanceEnv): Record<string, unknown> | null {
|
||||
const raw = env.PAPERCLIP_MANAGED_CONFIG?.trim();
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the synchronous onboarding experiment variant from process state,
|
||||
* `PAPERCLIP_ONBOARDING_VARIANT`, `PAPERCLIP_MANAGED_CONFIG`, or legacy
|
||||
* `enableCloudTrialInference`. Defaults safely to `"baseline"` so self-hosted
|
||||
* and unflagged Cloud stacks never enter an experimental onboarding flow.
|
||||
*/
|
||||
export function resolveOnboardingVariant(env: CloudInstanceEnv = process.env): OnboardingVariant {
|
||||
if (env === process.env) {
|
||||
const resolved = getResolvedOnboardingVariant();
|
||||
if (resolved !== null) return resolved;
|
||||
}
|
||||
const envVariant = env.PAPERCLIP_ONBOARDING_VARIANT?.trim();
|
||||
if (envVariant) return normalizeOnboardingVariant(envVariant);
|
||||
|
||||
const parsed = parseManagedConfigObject(env);
|
||||
const features =
|
||||
parsed?.features && typeof parsed.features === "object" && !Array.isArray(parsed.features)
|
||||
? (parsed.features as Record<string, unknown>)
|
||||
: null;
|
||||
if (typeof parsed?.onboardingVariant === "string" && parsed.onboardingVariant.trim()) {
|
||||
return normalizeOnboardingVariant(parsed.onboardingVariant);
|
||||
}
|
||||
if (typeof features?.onboardingVariant === "string" && features.onboardingVariant.trim()) {
|
||||
return normalizeOnboardingVariant(features.onboardingVariant);
|
||||
}
|
||||
if (features?.enableCloudTrialInference === true) {
|
||||
return FREE_INFERENCE_ONBOARDING_VARIANT;
|
||||
}
|
||||
if (env === process.env && getResolvedCloudTrialInferenceEnabled() === true) {
|
||||
return FREE_INFERENCE_ONBOARDING_VARIANT;
|
||||
}
|
||||
return DEFAULT_ONBOARDING_VARIANT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves whether `enableCloudTrialInference` is active in this stack's
|
||||
* `PAPERCLIP_MANAGED_CONFIG` document. Fails closed (`false`) if absent or
|
||||
* malformed so analytics never throw on startup.
|
||||
* resolved state, `PAPERCLIP_ONBOARDING_VARIANT`, or `PAPERCLIP_MANAGED_CONFIG`
|
||||
* document. Fails closed (`false`) if absent or malformed so analytics never
|
||||
* throw on startup.
|
||||
*/
|
||||
export function resolveCloudTrialInferenceEnabled(env: CloudInstanceEnv = process.env): boolean {
|
||||
if (env === process.env) {
|
||||
const resolved = getResolvedCloudTrialInferenceEnabled();
|
||||
if (resolved !== null) return resolved;
|
||||
const resolvedVariant = getResolvedOnboardingVariant();
|
||||
if (resolvedVariant !== null) return isFreeInferenceOnboardingVariant(resolvedVariant);
|
||||
}
|
||||
const raw = env.PAPERCLIP_MANAGED_CONFIG?.trim();
|
||||
if (!raw) return false;
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as { features?: Record<string, unknown> } | null;
|
||||
return parsed?.features?.enableCloudTrialInference === true;
|
||||
} catch {
|
||||
return false;
|
||||
const envVariant = env.PAPERCLIP_ONBOARDING_VARIANT?.trim();
|
||||
if (envVariant) return isFreeInferenceOnboardingVariant(envVariant);
|
||||
|
||||
const parsed = parseManagedConfigObject(env);
|
||||
const features =
|
||||
parsed?.features && typeof parsed.features === "object" && !Array.isArray(parsed.features)
|
||||
? (parsed.features as Record<string, unknown>)
|
||||
: null;
|
||||
if (features?.enableCloudTrialInference === true) return true;
|
||||
if (typeof parsed?.onboardingVariant === "string" && parsed.onboardingVariant.trim()) {
|
||||
return isFreeInferenceOnboardingVariant(parsed.onboardingVariant);
|
||||
}
|
||||
if (typeof features?.onboardingVariant === "string" && features.onboardingVariant.trim()) {
|
||||
return isFreeInferenceOnboardingVariant(features.onboardingVariant);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isOnboardingVariantExplicitlyResolved(env: CloudInstanceEnv = process.env): boolean {
|
||||
if (env === process.env && getResolvedOnboardingVariant() !== null) return true;
|
||||
if (env.PAPERCLIP_ONBOARDING_VARIANT?.trim()) return true;
|
||||
// On Cloud-managed stacks (including unclaimed warm-pool instances before
|
||||
// runtime identity/signing keys are attached), defer locking
|
||||
// `$group_set_once.initial_onboarding_variant` until the Cloud assignment
|
||||
// actually resolves via `/v1/tenant/onboarding-config` or exposure sync.
|
||||
if (isCloudManagedInstance(env)) return false;
|
||||
const parsed = parseManagedConfigObject(env);
|
||||
const features =
|
||||
parsed?.features && typeof parsed.features === "object" && !Array.isArray(parsed.features)
|
||||
? (parsed.features as Record<string, unknown>)
|
||||
: null;
|
||||
if (typeof parsed?.onboardingVariant === "string" && parsed.onboardingVariant.trim()) return true;
|
||||
if (typeof features?.onboardingVariant === "string" && features.onboardingVariant.trim()) return true;
|
||||
if (features?.enableCloudTrialInference === true) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -49,6 +138,9 @@ export type CloudPostHogConfig = {
|
||||
replayEnabled: boolean; // browserEnabled && PAPERCLIP_POSTHOG_REPLAY_ENABLED !== "0"
|
||||
replayWorkContentEnabled: boolean;
|
||||
cloudTrialInferenceEnabled: boolean; // PAPERCLIP_MANAGED_CONFIG.features.enableCloudTrialInference
|
||||
onboardingVariant?: OnboardingVariant; // "baseline", "free_inference_1", etc.
|
||||
/** True only when the variant came from an explicit source (Cloud config, env, or managed config), not an unresolved warm-pool boot default. */
|
||||
onboardingVariantResolved?: boolean;
|
||||
};
|
||||
|
||||
export const DEFAULT_CLOUD_POSTHOG_HOST = "https://us.i.posthog.com";
|
||||
@@ -68,6 +160,8 @@ export function resolveCloudPostHogConfig(
|
||||
|
||||
const browserEnabled = readEnv(env, "PAPERCLIP_POSTHOG_BROWSER_ENABLED") === "1";
|
||||
const replayEnabled = browserEnabled && readEnv(env, "PAPERCLIP_POSTHOG_REPLAY_ENABLED") !== "0";
|
||||
const onboardingVariant = resolveOnboardingVariant(env);
|
||||
const onboardingVariantResolved = isOnboardingVariantExplicitlyResolved(env);
|
||||
return {
|
||||
token,
|
||||
host: (readEnv(env, "PAPERCLIP_POSTHOG_HOST") ?? DEFAULT_CLOUD_POSTHOG_HOST).replace(/\/+$/, ""),
|
||||
@@ -78,6 +172,8 @@ export function resolveCloudPostHogConfig(
|
||||
replayEnabled,
|
||||
replayWorkContentEnabled: replayEnabled && readEnv(env, "PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED") === "1",
|
||||
cloudTrialInferenceEnabled: resolveCloudTrialInferenceEnabled(env),
|
||||
onboardingVariant,
|
||||
...(onboardingVariantResolved ? { onboardingVariantResolved: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,11 @@ import type { AuthorizationActor } from "./authorization.js";
|
||||
import type { CloudInstanceEnv } from "./cloud-instance.js";
|
||||
import {
|
||||
CloudTrialExhaustedError,
|
||||
CloudTrialWorkRequiresModelError,
|
||||
createCloudTrialKeyStore,
|
||||
isCloudTrialExhaustedError,
|
||||
isCloudTrialGateError,
|
||||
isCloudTrialWorkRequiresModelError,
|
||||
} from "./cloud-trial-key-store.js";
|
||||
import {
|
||||
migrateCloudTrialAgents,
|
||||
@@ -16,17 +19,31 @@ import {
|
||||
type PreparedCloudTrialRuntime,
|
||||
} from "./cloud-trial-proxy.js";
|
||||
import {
|
||||
assertCloudTrialInferenceEligible,
|
||||
assertCloudTrialInferenceEligible as assertCloudTrialInferenceEligibleWithKeyStore,
|
||||
assertCompanyTrialLlmNotBlocked,
|
||||
getCompanyCloudTrialStatus,
|
||||
holdIssueForCloudTrialWorkGate,
|
||||
isCloudTrialWorkGateExecutableStatus,
|
||||
isCloudTrialWorkGateExemptOriginKind,
|
||||
isCompanyOnTrialOnlyInference,
|
||||
resolveEffectiveOnboardingConfig,
|
||||
} from "./cloud-trial-status.js";
|
||||
|
||||
export {
|
||||
CloudTrialExhaustedError,
|
||||
CloudTrialWorkRequiresModelError,
|
||||
isCloudTrialExhaustedError,
|
||||
assertCloudTrialInferenceEligible,
|
||||
isCloudTrialWorkRequiresModelError,
|
||||
isCloudTrialGateError,
|
||||
isCloudTrialWorkGateExecutableStatus,
|
||||
isCloudTrialWorkGateExemptOriginKind,
|
||||
type PreparedCloudTrialRuntime,
|
||||
};
|
||||
|
||||
export function assertCloudTrialInferenceEligible(db: Db, companyId: string): Promise<void> {
|
||||
return getDefaultCloudTrialInferenceController().assertEligible(db, companyId);
|
||||
}
|
||||
|
||||
export interface CloudTrialInferenceOptions {
|
||||
env?: CloudInstanceEnv;
|
||||
fetchImpl?: typeof fetch;
|
||||
@@ -40,6 +57,24 @@ export function createCloudTrialInferenceController(opts: CloudTrialInferenceOpt
|
||||
return {
|
||||
prepareCloudTrialRuntime: proxy.prepareCloudTrialRuntime,
|
||||
proxyOpenRouterRequest: proxy.proxyOpenRouterRequest,
|
||||
resolveOnboardingConfig: (db: Db, options: { forceRefresh?: boolean } = {}) =>
|
||||
resolveEffectiveOnboardingConfig(db, keyStore, options),
|
||||
assertEligible: (db: Db, companyId: string) =>
|
||||
assertCloudTrialInferenceEligibleWithKeyStore(db, companyId, keyStore),
|
||||
isCompanyOnTrialOnlyInference: (db: Db, companyId: string) =>
|
||||
isCompanyOnTrialOnlyInference(db, companyId),
|
||||
holdIssueForWorkGate: (
|
||||
db: Db,
|
||||
companyId: string,
|
||||
issue: {
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
title: string;
|
||||
assigneeAgentId: string | null;
|
||||
},
|
||||
) => holdIssueForCloudTrialWorkGate(db, companyId, issue, keyStore),
|
||||
assertTrialLlmNotBlocked: (db: Db, companyId: string, agentId: string) =>
|
||||
assertCompanyTrialLlmNotBlocked(db, companyId, agentId, keyStore),
|
||||
getCompanyStatus: (
|
||||
db: Db,
|
||||
companyId: string,
|
||||
|
||||
@@ -2,19 +2,34 @@ import { createPrivateKey, sign } from "node:crypto";
|
||||
import {
|
||||
CLOUD_TRIAL_DEFAULT_LIMIT_USD_CENTS,
|
||||
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
|
||||
DEFAULT_ONBOARDING_VARIANT,
|
||||
FREE_INFERENCE_ONBOARDING_VARIANT,
|
||||
isFreeInferenceOnboardingVariant,
|
||||
normalizeOnboardingVariant,
|
||||
parseCloudTrialMigrationTargetsEnv,
|
||||
resolveCloudTrialModel,
|
||||
type CloudTrialGateReason,
|
||||
type CloudTrialHeldIssueSummary,
|
||||
type CloudTrialInferenceState,
|
||||
type CloudTrialMigrationTargetOverrides,
|
||||
type OnboardingVariant,
|
||||
} from "@paperclipai/shared";
|
||||
import { HttpError } from "../errors.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { getCloudStackContext, type CloudInstanceEnv } from "./cloud-instance.js";
|
||||
import { onCloudRuntimeIdentityChange } from "./cloud-runtime-identity.js";
|
||||
import {
|
||||
setResolvedCloudTrialInferenceEnabled,
|
||||
setResolvedOnboardingVariant,
|
||||
} from "./cloud-posthog-cohort.js";
|
||||
import { resolveOnboardingVariant } from "./cloud-posthog-config.js";
|
||||
import { publishLiveEvent } from "./live-events.js";
|
||||
import { trackCloudPostHogEvent } from "../telemetry.js";
|
||||
|
||||
const DEFAULT_OPENROUTER_UPSTREAM_BASE = "https://openrouter.ai/api/v1";
|
||||
const USAGE_PROBE_MIN_INTERVAL_MS = 15_000;
|
||||
const ONBOARDING_CONFIG_TTL_MS = 60_000;
|
||||
|
||||
export class CloudTrialExhaustedError extends HttpError {
|
||||
constructor(
|
||||
@@ -23,12 +38,27 @@ export class CloudTrialExhaustedError extends HttpError {
|
||||
) {
|
||||
super(402, message, {
|
||||
code: CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
gateReason: "exhausted",
|
||||
...details,
|
||||
});
|
||||
this.name = "CloudTrialExhaustedError";
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudTrialWorkRequiresModelError extends HttpError {
|
||||
constructor(
|
||||
message = "Connect a model provider to run tasks and continue chatting.",
|
||||
details: Record<string, unknown> = {},
|
||||
) {
|
||||
super(402, message, {
|
||||
code: CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
|
||||
gateReason: "work_requires_model",
|
||||
...details,
|
||||
});
|
||||
this.name = "CloudTrialWorkRequiresModelError";
|
||||
}
|
||||
}
|
||||
|
||||
export function isCloudTrialExhaustedError(error: unknown): error is CloudTrialExhaustedError {
|
||||
if (error instanceof CloudTrialExhaustedError) return true;
|
||||
if (error instanceof HttpError) {
|
||||
@@ -38,6 +68,30 @@ export function isCloudTrialExhaustedError(error: unknown): error is CloudTrialE
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isCloudTrialWorkRequiresModelError(
|
||||
error: unknown,
|
||||
): error is CloudTrialWorkRequiresModelError {
|
||||
if (error instanceof CloudTrialWorkRequiresModelError) return true;
|
||||
if (error instanceof HttpError) {
|
||||
const details = error.details as { code?: unknown } | undefined;
|
||||
return details?.code === CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isCloudTrialGateError(
|
||||
error: unknown,
|
||||
): error is CloudTrialExhaustedError | CloudTrialWorkRequiresModelError {
|
||||
return isCloudTrialExhaustedError(error) || isCloudTrialWorkRequiresModelError(error);
|
||||
}
|
||||
|
||||
export interface CachedOnboardingConfig {
|
||||
onboardingVariant: OnboardingVariant;
|
||||
trialInferenceEnabled: boolean;
|
||||
source: "cloud" | "env" | "managed_config" | "default";
|
||||
fetchedAtMs: number;
|
||||
}
|
||||
|
||||
export interface CachedCloudKeyState {
|
||||
status: CloudTrialInferenceState;
|
||||
reason?: string;
|
||||
@@ -113,6 +167,176 @@ export function createCloudTrialKeyStore(opts: CloudTrialKeyStoreOptions = {}) {
|
||||
|
||||
let cached: CachedCloudKeyState | null = null;
|
||||
let inflightFetch: Promise<CachedCloudKeyState> | null = null;
|
||||
let cachedOnboardingConfig: CachedOnboardingConfig | null = null;
|
||||
let inflightOnboardingConfigFetch: Promise<CachedOnboardingConfig> | null = null;
|
||||
const heldIssuesByCompany = new Map<string, Map<string, CloudTrialHeldIssueSummary>>();
|
||||
|
||||
// Warm-pool stacks may boot before signup/claim time. Invalidate cached
|
||||
// onboarding config when runtime identity changes so the next read fetches
|
||||
// the stack's claim-time assigned variant from Cloud control plane.
|
||||
if (env === process.env) {
|
||||
onCloudRuntimeIdentityChange(() => {
|
||||
cachedOnboardingConfig = null;
|
||||
});
|
||||
}
|
||||
|
||||
function syncResolvedCohort(onboardingVariant: OnboardingVariant, trialInferenceEnabled: boolean) {
|
||||
if (env !== process.env) return;
|
||||
setResolvedOnboardingVariant(onboardingVariant);
|
||||
setResolvedCloudTrialInferenceEnabled(trialInferenceEnabled);
|
||||
}
|
||||
|
||||
function fallbackOnboardingConfig(): CachedOnboardingConfig {
|
||||
const envVariant = env.PAPERCLIP_ONBOARDING_VARIANT?.trim();
|
||||
if (envVariant) {
|
||||
const normalized = normalizeOnboardingVariant(envVariant);
|
||||
const trialInferenceEnabled = isFreeInferenceOnboardingVariant(normalized);
|
||||
return {
|
||||
onboardingVariant: normalized,
|
||||
trialInferenceEnabled,
|
||||
source: "env",
|
||||
fetchedAtMs: now(),
|
||||
};
|
||||
}
|
||||
const managedRaw = env.PAPERCLIP_MANAGED_CONFIG?.trim();
|
||||
if (managedRaw) {
|
||||
const resolved = resolveOnboardingVariant(env);
|
||||
const trialInferenceEnabled = isFreeInferenceOnboardingVariant(resolved);
|
||||
if (resolved !== DEFAULT_ONBOARDING_VARIANT) {
|
||||
return {
|
||||
onboardingVariant: resolved,
|
||||
trialInferenceEnabled,
|
||||
source: "managed_config",
|
||||
fetchedAtMs: now(),
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
onboardingVariant: DEFAULT_ONBOARDING_VARIANT,
|
||||
trialInferenceEnabled: false,
|
||||
source: "default",
|
||||
fetchedAtMs: now(),
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchOnboardingConfig(forceRefresh = false): Promise<CachedOnboardingConfig> {
|
||||
if (
|
||||
!forceRefresh &&
|
||||
cachedOnboardingConfig &&
|
||||
now() - cachedOnboardingConfig.fetchedAtMs < ONBOARDING_CONFIG_TTL_MS
|
||||
) {
|
||||
return cachedOnboardingConfig;
|
||||
}
|
||||
|
||||
const context = getCloudStackContext(env);
|
||||
const hasSigningKey = Boolean(env.PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY?.trim());
|
||||
if (!context?.cloudOrigin || !context.stackId || !hasSigningKey) {
|
||||
const fallback = fallbackOnboardingConfig();
|
||||
cachedOnboardingConfig = fallback;
|
||||
syncResolvedCohort(fallback.onboardingVariant, fallback.trialInferenceEnabled);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
if (inflightOnboardingConfigFetch) return inflightOnboardingConfigFetch;
|
||||
inflightOnboardingConfigFetch = (async () => {
|
||||
try {
|
||||
const pathname = "/v1/tenant/onboarding-config";
|
||||
const url = new URL(pathname, context.cloudOrigin!);
|
||||
const response = await fetchImpl(url, {
|
||||
method: "GET",
|
||||
headers: buildCloudStackAuthHeaders(env, "GET", pathname, context.stackId!),
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
logger.warn(
|
||||
{ status: response.status, stackId: context.stackId },
|
||||
"Cloud onboarding config request returned non-OK status; falling back",
|
||||
);
|
||||
const fallback = fallbackOnboardingConfig();
|
||||
cachedOnboardingConfig = fallback;
|
||||
syncResolvedCohort(fallback.onboardingVariant, fallback.trialInferenceEnabled);
|
||||
return fallback;
|
||||
}
|
||||
const payload = readJsonRecord(await response.json());
|
||||
const onboardingVariant = normalizeOnboardingVariant(
|
||||
typeof payload.onboardingVariant === "string" ? payload.onboardingVariant : undefined,
|
||||
);
|
||||
const trialInferenceEnabled =
|
||||
payload.trialInferenceEnabled === true ||
|
||||
isFreeInferenceOnboardingVariant(onboardingVariant);
|
||||
cachedOnboardingConfig = {
|
||||
onboardingVariant,
|
||||
trialInferenceEnabled,
|
||||
source: "cloud",
|
||||
fetchedAtMs: now(),
|
||||
};
|
||||
syncResolvedCohort(onboardingVariant, trialInferenceEnabled);
|
||||
return cachedOnboardingConfig;
|
||||
} catch (err) {
|
||||
logger.debug({ err }, "Failed to fetch Cloud onboarding config; falling back");
|
||||
const fallback = fallbackOnboardingConfig();
|
||||
cachedOnboardingConfig = fallback;
|
||||
syncResolvedCohort(fallback.onboardingVariant, fallback.trialInferenceEnabled);
|
||||
return fallback;
|
||||
}
|
||||
})().finally(() => {
|
||||
inflightOnboardingConfigFetch = null;
|
||||
});
|
||||
return inflightOnboardingConfigFetch;
|
||||
}
|
||||
|
||||
function getHeldIssues(companyId: string): CloudTrialHeldIssueSummary[] {
|
||||
const map = heldIssuesByCompany.get(companyId);
|
||||
return map ? Array.from(map.values()) : [];
|
||||
}
|
||||
|
||||
function holdIssue(
|
||||
companyId: string,
|
||||
issue: {
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
title: string;
|
||||
assigneeAgentId: string | null;
|
||||
},
|
||||
): { heldIssues: CloudTrialHeldIssueSummary[]; newlyHeld: boolean } {
|
||||
let map = heldIssuesByCompany.get(companyId);
|
||||
if (!map) {
|
||||
map = new Map();
|
||||
heldIssuesByCompany.set(companyId, map);
|
||||
}
|
||||
const newlyHeld = !map.has(issue.id);
|
||||
if (newlyHeld) {
|
||||
map.set(issue.id, {
|
||||
id: issue.id,
|
||||
identifier: issue.identifier,
|
||||
title: issue.title,
|
||||
assigneeAgentId: issue.assigneeAgentId,
|
||||
heldAt: new Date(now()).toISOString(),
|
||||
});
|
||||
}
|
||||
return { heldIssues: Array.from(map.values()), newlyHeld };
|
||||
}
|
||||
|
||||
function clearHeldIssues(companyId: string): CloudTrialHeldIssueSummary[] {
|
||||
const existing = getHeldIssues(companyId);
|
||||
heldIssuesByCompany.delete(companyId);
|
||||
return existing;
|
||||
}
|
||||
|
||||
function removeHeldIssue(companyId: string, issueId: string): void {
|
||||
const map = heldIssuesByCompany.get(companyId);
|
||||
if (!map) return;
|
||||
map.delete(issueId);
|
||||
if (map.size === 0) {
|
||||
heldIssuesByCompany.delete(companyId);
|
||||
}
|
||||
}
|
||||
|
||||
function getGateReason(companyId: string): CloudTrialGateReason | null {
|
||||
if (cached?.status === "exhausted") return "exhausted";
|
||||
if (getHeldIssues(companyId).length > 0) return "work_requires_model";
|
||||
return null;
|
||||
}
|
||||
|
||||
// Best-effort PostHog funnel counters for this process (Cloud-only).
|
||||
let keyIssuedTracked = false;
|
||||
@@ -233,6 +457,18 @@ export function createCloudTrialKeyStore(opts: CloudTrialKeyStoreOptions = {}) {
|
||||
const apiKey = status === "active" && typeof payload.apiKey === "string" && payload.apiKey.trim()
|
||||
? payload.apiKey.trim()
|
||||
: null;
|
||||
if (typeof payload.onboardingVariant === "string" && payload.onboardingVariant.trim()) {
|
||||
const variant = normalizeOnboardingVariant(payload.onboardingVariant);
|
||||
const trialEnabled =
|
||||
isFreeInferenceOnboardingVariant(variant) || status === "active" || status === "exhausted";
|
||||
cachedOnboardingConfig = {
|
||||
onboardingVariant: variant,
|
||||
trialInferenceEnabled: trialEnabled,
|
||||
source: "cloud",
|
||||
fetchedAtMs: now(),
|
||||
};
|
||||
syncResolvedCohort(variant, trialEnabled);
|
||||
}
|
||||
cached = {
|
||||
status,
|
||||
reason: typeof payload.reason === "string" ? payload.reason : undefined,
|
||||
@@ -318,16 +554,18 @@ export function createCloudTrialKeyStore(opts: CloudTrialKeyStoreOptions = {}) {
|
||||
await reportExhaustedToCloud(spentUsdCents, input.reason ?? "budget_exhausted");
|
||||
|
||||
if (input.companyId) {
|
||||
const heldIssues = getHeldIssues(input.companyId);
|
||||
publishLiveEvent({
|
||||
companyId: input.companyId,
|
||||
type: "cloud_trial.status.updated",
|
||||
payload: {
|
||||
status: "exhausted",
|
||||
gateReason: "exhausted",
|
||||
llmBlocked: true,
|
||||
heldIssueCount: heldIssues.length,
|
||||
limitUsdCents,
|
||||
spentUsdCents,
|
||||
remainingUsdCents: 0,
|
||||
agentId: input.agentId ?? null,
|
||||
runId: input.runId ?? null,
|
||||
reason: input.reason ?? "budget_exhausted",
|
||||
},
|
||||
});
|
||||
@@ -397,11 +635,21 @@ export function createCloudTrialKeyStore(opts: CloudTrialKeyStoreOptions = {}) {
|
||||
configuredDefaultModel,
|
||||
configuredMigrationTargets,
|
||||
fetchKeyFromCloudOrLocal,
|
||||
fetchOnboardingConfig,
|
||||
getCachedOnboardingConfig: () => cachedOnboardingConfig,
|
||||
getHeldIssues,
|
||||
holdIssue,
|
||||
clearHeldIssues,
|
||||
removeHeldIssue,
|
||||
getGateReason,
|
||||
markExhausted,
|
||||
probeOpenRouterUsage,
|
||||
_resetForTests: () => {
|
||||
cached = null;
|
||||
inflightFetch = null;
|
||||
cachedOnboardingConfig = null;
|
||||
inflightOnboardingConfigFetch = null;
|
||||
heldIssuesByCompany.clear();
|
||||
keyIssuedTracked = false;
|
||||
keyIssuedAtMs = null;
|
||||
trialRunsCount = 0;
|
||||
|
||||
@@ -26,6 +26,8 @@ import { trackCloudPostHogEvent } from "../telemetry.js";
|
||||
import { readJsonRecord, type CloudTrialKeyStore } from "./cloud-trial-key-store.js";
|
||||
import {
|
||||
canActorConfigureTrialAgent,
|
||||
filterReadableHeldIssues,
|
||||
findHeldTrialIssuesFromDb,
|
||||
findLatestExhaustedTrialRun,
|
||||
} from "./cloud-trial-status.js";
|
||||
|
||||
@@ -256,37 +258,155 @@ export async function migrateCloudTrialAgents(
|
||||
});
|
||||
}
|
||||
|
||||
// Resume the most recent blocked turn/issue if requested (only when latest run was exhausted).
|
||||
// Clear held issues for migrated agents (combining in-memory state with DB
|
||||
// hydration so restarts before model connection still auto-resume held
|
||||
// subtasks), scoped strictly to migrated agents and issues readable by the
|
||||
// migrating actor.
|
||||
const migratedAgentIdSet = new Set(migratedAgentIds);
|
||||
const inMemoryHeldIssues = keyStore.getHeldIssues(companyId);
|
||||
const dbHeldIssues =
|
||||
migratedAgentIds.length > 0
|
||||
? await findHeldTrialIssuesFromDb(db, companyId).catch(() => [])
|
||||
: [];
|
||||
const heldIssueMap = new Map(dbHeldIssues.map((h) => [h.id, h]));
|
||||
for (const held of inMemoryHeldIssues) {
|
||||
if (!heldIssueMap.has(held.id)) heldIssueMap.set(held.id, held);
|
||||
}
|
||||
const allHeldIssues = Array.from(heldIssueMap.values());
|
||||
const migratedAgentHeldIssues = allHeldIssues.filter(
|
||||
(held) => held.assigneeAgentId !== null && migratedAgentIdSet.has(held.assigneeAgentId),
|
||||
);
|
||||
const remainingTrialAgents = companyAgents.filter(
|
||||
(agent) =>
|
||||
isAgentUsingCloudTrialInference(agent.runtimeConfig) && !migratedAgentIdSet.has(agent.id),
|
||||
);
|
||||
|
||||
const resumedRunIds: string[] = [];
|
||||
const resumedIssueIds: string[] = [];
|
||||
let resumedIssueId: string | null = null;
|
||||
let heldResumeAccessFailed = false;
|
||||
let heldWakeupFailedCount = 0;
|
||||
|
||||
if (input.resumeBlockedWork && migratedAgentIds.length > 0) {
|
||||
const blocked = await findLatestExhaustedTrialRun(db, companyId, migratedAgentIds);
|
||||
if (blocked) {
|
||||
resumedIssueId = blocked.issueId;
|
||||
// Evaluate per-actor readability BEFORE clearing holds so a transient
|
||||
// access lookup error never silently discards waiting tasks.
|
||||
let resumableHeldIssues: typeof migratedAgentHeldIssues = [];
|
||||
try {
|
||||
resumableHeldIssues = await filterReadableHeldIssues(
|
||||
db,
|
||||
companyId,
|
||||
migratedAgentHeldIssues,
|
||||
actorCtx.actor,
|
||||
{ throwOnError: true },
|
||||
);
|
||||
} catch (err) {
|
||||
heldResumeAccessFailed = true;
|
||||
logger.warn(
|
||||
{ err, companyId },
|
||||
"Migrated trial agents succeeded, but checking readability of held issues failed; keeping holds intact",
|
||||
);
|
||||
}
|
||||
|
||||
const resumableIds = new Set(resumableHeldIssues.map((item) => item.id));
|
||||
for (const held of resumableHeldIssues) {
|
||||
const targetAgentId = held.assigneeAgentId;
|
||||
if (!targetAgentId || !migratedAgentIdSet.has(targetAgentId)) continue;
|
||||
try {
|
||||
const woke = await heartbeatService(db).wakeup(blocked.agentId, {
|
||||
source: "on_demand",
|
||||
const woke = await heartbeatService(db).wakeup(targetAgentId, {
|
||||
source: "assignment",
|
||||
triggerDetail: "manual",
|
||||
reason: "cloud_trial_migrated_resume",
|
||||
requestedByActorType: "user",
|
||||
requestedByActorId: actorCtx.userId,
|
||||
payload: resumedIssueId ? { issueId: resumedIssueId } : undefined,
|
||||
payload: { issueId: held.id, mutation: "cloud_trial_migration" },
|
||||
contextSnapshot: {
|
||||
...(resumedIssueId ? { issueId: resumedIssueId, taskId: resumedIssueId } : {}),
|
||||
issueId: held.id,
|
||||
taskId: held.id,
|
||||
wakeReason: "cloud_trial_migrated_resume",
|
||||
source: "cloud_trial_migration",
|
||||
},
|
||||
});
|
||||
if (woke?.id) {
|
||||
resumedRunIds.push(woke.id);
|
||||
resumedIssueIds.push(held.id);
|
||||
resumedIssueId ??= held.id;
|
||||
keyStore.removeHeldIssue(companyId, held.id);
|
||||
}
|
||||
} catch (err) {
|
||||
heldWakeupFailedCount += 1;
|
||||
logger.warn(
|
||||
{ err, companyId, agentId: blocked.agentId, issueId: resumedIssueId },
|
||||
"Migrated trial agents succeeded, but auto-resuming the blocked run failed",
|
||||
{ err, companyId, agentId: targetAgentId, issueId: held.id },
|
||||
"Migrated trial agents succeeded, but auto-resuming held issue failed; keeping hold intact",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!heldResumeAccessFailed) {
|
||||
// Remove holds explicitly denied by access policy (not failed lookups).
|
||||
for (const held of migratedAgentHeldIssues) {
|
||||
if (!resumableIds.has(held.id)) {
|
||||
keyStore.removeHeldIssue(companyId, held.id);
|
||||
}
|
||||
}
|
||||
if (remainingTrialAgents.length === 0 && heldWakeupFailedCount === 0) {
|
||||
keyStore.clearHeldIssues(companyId);
|
||||
}
|
||||
}
|
||||
|
||||
const blocked = await findLatestExhaustedTrialRun(db, companyId, migratedAgentIds);
|
||||
if (blocked && (!blocked.issueId || !resumedIssueIds.includes(blocked.issueId))) {
|
||||
let readableBlockedIssueId = blocked.issueId;
|
||||
if (readableBlockedIssueId && actorCtx.actor) {
|
||||
const readable = await filterReadableHeldIssues(
|
||||
db,
|
||||
companyId,
|
||||
[
|
||||
{
|
||||
id: readableBlockedIssueId,
|
||||
identifier: null,
|
||||
title: "",
|
||||
assigneeAgentId: blocked.agentId,
|
||||
heldAt: blocked.failedAt,
|
||||
},
|
||||
],
|
||||
actorCtx.actor,
|
||||
);
|
||||
if (readable.length === 0) {
|
||||
readableBlockedIssueId = null;
|
||||
}
|
||||
}
|
||||
if (!blocked.issueId || readableBlockedIssueId) {
|
||||
try {
|
||||
const woke = await heartbeatService(db).wakeup(blocked.agentId, {
|
||||
source: "on_demand",
|
||||
triggerDetail: "manual",
|
||||
reason: "cloud_trial_migrated_resume",
|
||||
requestedByActorType: "user",
|
||||
requestedByActorId: actorCtx.userId,
|
||||
payload: readableBlockedIssueId ? { issueId: readableBlockedIssueId } : undefined,
|
||||
contextSnapshot: {
|
||||
...(readableBlockedIssueId
|
||||
? { issueId: readableBlockedIssueId, taskId: readableBlockedIssueId }
|
||||
: {}),
|
||||
wakeReason: "cloud_trial_migrated_resume",
|
||||
source: "cloud_trial_migration",
|
||||
},
|
||||
});
|
||||
if (woke?.id) {
|
||||
resumedRunIds.push(woke.id);
|
||||
if (readableBlockedIssueId) {
|
||||
resumedIssueIds.push(readableBlockedIssueId);
|
||||
resumedIssueId ??= readableBlockedIssueId;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, companyId, agentId: blocked.agentId, issueId: readableBlockedIssueId },
|
||||
"Migrated trial agents succeeded, but auto-resuming the blocked run failed",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
publishLiveEvent({
|
||||
@@ -294,10 +414,10 @@ export async function migrateCloudTrialAgents(
|
||||
type: "cloud_trial.status.updated",
|
||||
payload: {
|
||||
status: "migrated",
|
||||
gateReason: null,
|
||||
llmBlocked: false,
|
||||
heldIssueCount: 0,
|
||||
migratedCount: migrated.length,
|
||||
provider: input.provider,
|
||||
resumedRunIds,
|
||||
resumedIssueId,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -314,6 +434,7 @@ export async function migrateCloudTrialAgents(
|
||||
ownership: input.ownership,
|
||||
migrated_agent_count: migrated.length,
|
||||
resumed_run_count: resumedRunIds.length,
|
||||
resumed_issue_count: resumedIssueIds.length,
|
||||
target_adapter_type: targetSpec.adapterType,
|
||||
target_model: targetSpec.model,
|
||||
...(secondsSinceExhausted !== undefined
|
||||
@@ -328,5 +449,6 @@ export async function migrateCloudTrialAgents(
|
||||
agents: migrated,
|
||||
resumedRunIds,
|
||||
resumedIssueId,
|
||||
resumedIssueIds,
|
||||
};
|
||||
}
|
||||
@@ -4,16 +4,23 @@ import { Readable } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import type { ReadableStream as NodeReadableStream } from "node:stream/web";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { CLOUD_TRIAL_EXHAUSTED_ERROR_CODE } from "@paperclipai/shared";
|
||||
import {
|
||||
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
|
||||
} from "@paperclipai/shared";
|
||||
import { OPENROUTER_ATTRIBUTION_HEADERS } from "@paperclipai/shared/openrouter-attribution";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import {
|
||||
CloudTrialExhaustedError,
|
||||
CloudTrialWorkRequiresModelError,
|
||||
readJsonRecord,
|
||||
stripOpenRouterPrefix,
|
||||
type CloudTrialKeyStore,
|
||||
} from "./cloud-trial-key-store.js";
|
||||
import {
|
||||
resolveEffectiveOnboardingConfig,
|
||||
resolveHeldTrialIssues,
|
||||
} from "./cloud-trial-status.js";
|
||||
|
||||
const PROXY_REQUEST_TIMEOUT_MS = 180_000;
|
||||
const MAX_PROXY_REQUEST_BYTES = 16 * 1024 * 1024;
|
||||
@@ -84,13 +91,26 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
|
||||
model?: string;
|
||||
},
|
||||
): Promise<PreparedCloudTrialRuntime> {
|
||||
const experimental = await instanceSettingsService(db).getExperimental();
|
||||
if (!experimental.enableCloudTrialInference) {
|
||||
const effective = await resolveEffectiveOnboardingConfig(db, keyStore);
|
||||
if (!effective.trialInferenceEnabled) {
|
||||
throw unprocessable("Cloud starter inference is not enabled on this instance.", {
|
||||
code: "cloud_trial_disabled",
|
||||
});
|
||||
}
|
||||
|
||||
const heldIssues =
|
||||
keyStore.getGateReason(input.companyId) === "work_requires_model"
|
||||
? keyStore.getHeldIssues(input.companyId)
|
||||
: await resolveHeldTrialIssues(db, input.companyId, keyStore, true);
|
||||
if (heldIssues.length > 0) {
|
||||
throw new CloudTrialWorkRequiresModelError(undefined, {
|
||||
companyId: input.companyId,
|
||||
agentId: input.agentId,
|
||||
runId: input.runId,
|
||||
heldIssueIds: heldIssues.map((h) => h.id),
|
||||
});
|
||||
}
|
||||
|
||||
const state = await keyStore.fetchKeyFromCloudOrLocal(false);
|
||||
if (state.status === "exhausted" || (state.status === "active" && state.remainingUsdCents <= 0)) {
|
||||
await keyStore.markExhausted({
|
||||
@@ -187,6 +207,21 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (keyStore.getGateReason(tokenRecord.companyId) === "work_requires_model") {
|
||||
activeRunTokens.delete(tokenRecord.token);
|
||||
res.statusCode = 402;
|
||||
res.setHeader("content-type", "application/json");
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
code: CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
|
||||
message: "Connect a model provider to run tasks and continue chatting.",
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const state = keyStore.getCached() ?? (await keyStore.fetchKeyFromCloudOrLocal(false));
|
||||
if (state.status === "exhausted" || !state.apiKey || state.remainingUsdCents <= 0) {
|
||||
await keyStore.markExhausted({
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import { and, desc, eq, inArray, ne } from "drizzle-orm";
|
||||
import { and, asc, desc, eq, inArray, isNull, ne, notInArray, sql } from "drizzle-orm";
|
||||
import {
|
||||
activityLog,
|
||||
agents,
|
||||
heartbeatRuns,
|
||||
issues,
|
||||
toolConnections,
|
||||
type Db,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
DEFAULT_ONBOARDING_VARIANT,
|
||||
FREE_INFERENCE_ONBOARDING_VARIANT,
|
||||
isAgentUsingCloudTrialInference,
|
||||
isFreeInferenceOnboardingVariant,
|
||||
normalizeOnboardingVariant,
|
||||
type CloudTrialBlockedRunSummary,
|
||||
type CloudTrialGateReason,
|
||||
type CloudTrialHeldIssueSummary,
|
||||
type CloudTrialInferenceState,
|
||||
type CloudTrialInferenceStatus,
|
||||
type OnboardingVariant,
|
||||
} from "@paperclipai/shared";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
@@ -18,13 +27,61 @@ import { accessService } from "./access.js";
|
||||
import type { AuthorizationActor } from "./authorization.js";
|
||||
import { isAgentSetupDraft } from "../modules/agent-lifecycle/index.js";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import type { CloudTrialKeyStore } from "./cloud-trial-key-store.js";
|
||||
import {
|
||||
getResolvedCloudTrialInferenceEnabled,
|
||||
getResolvedOnboardingVariant,
|
||||
setResolvedCloudTrialInferenceEnabled,
|
||||
setResolvedOnboardingVariant,
|
||||
} from "./cloud-posthog-cohort.js";
|
||||
import { isCloudManagedInstance } from "./cloud-instance.js";
|
||||
import { resolveOnboardingVariant } from "./cloud-posthog-config.js";
|
||||
import { publishLiveEvent } from "./live-events.js";
|
||||
import { trackCloudPostHogEvent } from "../telemetry.js";
|
||||
import {
|
||||
CloudTrialExhaustedError,
|
||||
CloudTrialWorkRequiresModelError,
|
||||
type CloudTrialKeyStore,
|
||||
} from "./cloud-trial-key-store.js";
|
||||
|
||||
const EXHAUSTION_ERROR_CODES = new Set([
|
||||
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
"native_provider_usage_limit",
|
||||
]);
|
||||
|
||||
export const CLOUD_TRIAL_WORK_GATE_NON_EXECUTABLE_STATUSES = [
|
||||
"backlog",
|
||||
"in_review",
|
||||
"done",
|
||||
"cancelled",
|
||||
] as const;
|
||||
|
||||
const CLOUD_TRIAL_WORK_GATE_NON_EXECUTABLE_STATUS_SET = new Set<string>(
|
||||
CLOUD_TRIAL_WORK_GATE_NON_EXECUTABLE_STATUSES,
|
||||
);
|
||||
|
||||
export function isCloudTrialWorkGateExecutableStatus(status?: string | null): boolean {
|
||||
return Boolean(status && !CLOUD_TRIAL_WORK_GATE_NON_EXECUTABLE_STATUS_SET.has(status));
|
||||
}
|
||||
|
||||
export const CLOUD_TRIAL_ISSUE_HELD_ACTIVITY_ACTION = "cloud_trial.issue_held" as const;
|
||||
|
||||
export const CLOUD_TRIAL_WORK_GATE_EXEMPT_ORIGIN_KINDS = [
|
||||
"onboarding_first_task",
|
||||
"task_watchdog",
|
||||
"harness_liveness_escalation",
|
||||
"stale_active_run_evaluation",
|
||||
"issue_productivity_review",
|
||||
"stranded_issue_recovery",
|
||||
] as const;
|
||||
|
||||
const CLOUD_TRIAL_WORK_GATE_EXEMPT_ORIGIN_KIND_SET = new Set<string>(
|
||||
CLOUD_TRIAL_WORK_GATE_EXEMPT_ORIGIN_KINDS,
|
||||
);
|
||||
|
||||
export function isCloudTrialWorkGateExemptOriginKind(originKind?: string | null): boolean {
|
||||
return Boolean(originKind && CLOUD_TRIAL_WORK_GATE_EXEMPT_ORIGIN_KIND_SET.has(originKind));
|
||||
}
|
||||
|
||||
export interface TrialAgentCandidate {
|
||||
id: string;
|
||||
companyId: string;
|
||||
@@ -62,17 +119,72 @@ export async function canActorConfigureTrialAgent(
|
||||
return updateDecision.allowed;
|
||||
}
|
||||
|
||||
export interface EffectiveOnboardingConfig {
|
||||
onboardingVariant: OnboardingVariant;
|
||||
trialInferenceEnabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the effective onboarding variant and whether starter trial inference
|
||||
* is enabled, combining the Cloud control-plane `/v1/tenant/onboarding-config`
|
||||
* response with `PAPERCLIP_ONBOARDING_VARIANT`, `PAPERCLIP_MANAGED_CONFIG`, and
|
||||
* the instance's `enableCloudTrialInference` experimental flag.
|
||||
*/
|
||||
export async function resolveEffectiveOnboardingConfig(
|
||||
db: Db,
|
||||
keyStore?: CloudTrialKeyStore,
|
||||
options: { forceRefresh?: boolean } = {},
|
||||
): Promise<EffectiveOnboardingConfig> {
|
||||
const [experimental, remote] = await Promise.all([
|
||||
instanceSettingsService(db)
|
||||
.getExperimental()
|
||||
.catch(() => null),
|
||||
keyStore ? keyStore.fetchOnboardingConfig(Boolean(options.forceRefresh)) : Promise.resolve(null),
|
||||
]);
|
||||
|
||||
const legacyFlagEnabled = experimental?.enableCloudTrialInference === true;
|
||||
let onboardingVariant: OnboardingVariant;
|
||||
let trialInferenceEnabled: boolean;
|
||||
|
||||
if (remote && (remote.source === "cloud" || remote.source === "env")) {
|
||||
onboardingVariant = normalizeOnboardingVariant(remote.onboardingVariant);
|
||||
trialInferenceEnabled =
|
||||
remote.trialInferenceEnabled ||
|
||||
isFreeInferenceOnboardingVariant(onboardingVariant) ||
|
||||
legacyFlagEnabled;
|
||||
} else if (legacyFlagEnabled) {
|
||||
onboardingVariant = FREE_INFERENCE_ONBOARDING_VARIANT;
|
||||
trialInferenceEnabled = true;
|
||||
} else if (remote) {
|
||||
onboardingVariant = normalizeOnboardingVariant(remote.onboardingVariant);
|
||||
trialInferenceEnabled =
|
||||
remote.trialInferenceEnabled || isFreeInferenceOnboardingVariant(onboardingVariant);
|
||||
} else {
|
||||
onboardingVariant = resolveOnboardingVariant(process.env);
|
||||
trialInferenceEnabled = isFreeInferenceOnboardingVariant(onboardingVariant);
|
||||
}
|
||||
|
||||
if (!keyStore || keyStore.env === process.env) {
|
||||
setResolvedOnboardingVariant(onboardingVariant);
|
||||
setResolvedCloudTrialInferenceEnabled(trialInferenceEnabled);
|
||||
}
|
||||
|
||||
return { onboardingVariant, trialInferenceEnabled };
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforces server-side eligibility before any route permits setting
|
||||
* `runtimeConfig.cloudTrialInference: true`: the instance flag must be
|
||||
* enabled and the company must not already have an active AI connection.
|
||||
* `runtimeConfig.cloudTrialInference: true`: either the instance flag or the
|
||||
* assigned onboarding variant must enable trial inference, and the company
|
||||
* must not already have an active AI connection.
|
||||
*/
|
||||
export async function assertCloudTrialInferenceEligible(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
keyStore?: CloudTrialKeyStore,
|
||||
): Promise<void> {
|
||||
const experimental = await instanceSettingsService(db).getExperimental();
|
||||
if (!experimental.enableCloudTrialInference) {
|
||||
const effective = await resolveEffectiveOnboardingConfig(db, keyStore);
|
||||
if (!effective.trialInferenceEnabled) {
|
||||
throw unprocessable("Cloud starter inference is not enabled on this instance.", {
|
||||
code: "cloud_trial_disabled",
|
||||
});
|
||||
@@ -97,6 +209,456 @@ export async function assertCloudTrialInferenceEligible(
|
||||
}
|
||||
}
|
||||
|
||||
export async function isCompanyOnTrialOnlyInference(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
): Promise<{ trialOnly: boolean; trialAgentIds: string[] }> {
|
||||
const companyAgents = await db
|
||||
.select({
|
||||
id: agents.id,
|
||||
runtimeConfig: agents.runtimeConfig,
|
||||
})
|
||||
.from(agents)
|
||||
.where(
|
||||
and(
|
||||
eq(agents.companyId, companyId),
|
||||
ne(agents.status, "terminated"),
|
||||
ne(agents.status, "pending_approval"),
|
||||
),
|
||||
);
|
||||
const trialAgentIds = companyAgents
|
||||
.filter((a) => isAgentUsingCloudTrialInference(a.runtimeConfig))
|
||||
.map((a) => a.id);
|
||||
if (trialAgentIds.length === 0) {
|
||||
return { trialOnly: false, trialAgentIds: [] };
|
||||
}
|
||||
const [existingAiConnection] = await db
|
||||
.select({ id: toolConnections.id })
|
||||
.from(toolConnections)
|
||||
.where(
|
||||
and(
|
||||
eq(toolConnections.companyId, companyId),
|
||||
eq(toolConnections.connectionPurpose, "ai"),
|
||||
eq(toolConnections.enabled, true),
|
||||
eq(toolConnections.status, "active"),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return {
|
||||
trialOnly: !existingAiConnection,
|
||||
trialAgentIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger B: when a subtask or manual task is created while the company only
|
||||
* has trial-only inference (active trial agents, no connected AI provider),
|
||||
* hold execution before heartbeat dispatch, flip the company gate to
|
||||
* `work_requires_model`, and broadcast `cloud_trial.status.updated` so the UI
|
||||
* immediately prompts the user to connect a model.
|
||||
*/
|
||||
const persistedHeldMarkerIds = new Set<string>();
|
||||
|
||||
export async function holdIssueForCloudTrialWorkGate(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
issue: {
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
title: string;
|
||||
assigneeAgentId: string | null;
|
||||
},
|
||||
keyStore: CloudTrialKeyStore,
|
||||
): Promise<{
|
||||
held: boolean;
|
||||
heldIssueIds: string[];
|
||||
heldIssues: CloudTrialHeldIssueSummary[];
|
||||
}> {
|
||||
// Fast-path skip on non-Cloud / self-hosted stacks without trial config and
|
||||
// stubbed unit-test DBs. On any Cloud-managed stack, always check persisted
|
||||
// trial agents in DB even after a cold restart before caches are warm.
|
||||
const trialMayBeActive =
|
||||
isCloudManagedInstance(keyStore.env) ||
|
||||
keyStore.getGateReason(companyId) !== null ||
|
||||
keyStore.getCached() !== null ||
|
||||
(keyStore.env === process.env &&
|
||||
(getResolvedCloudTrialInferenceEnabled() === true ||
|
||||
isFreeInferenceOnboardingVariant(getResolvedOnboardingVariant()))) ||
|
||||
isFreeInferenceOnboardingVariant(resolveOnboardingVariant(keyStore.env));
|
||||
if (!trialMayBeActive || typeof (db as { select?: unknown }).select !== "function") {
|
||||
return { held: false, heldIssueIds: [], heldIssues: [] };
|
||||
}
|
||||
|
||||
const { trialOnly } = await isCompanyOnTrialOnlyInference(db, companyId);
|
||||
if (!trialOnly) {
|
||||
return { held: false, heldIssueIds: [], heldIssues: [] };
|
||||
}
|
||||
|
||||
const cached = keyStore.getCached();
|
||||
const gateReason: CloudTrialGateReason =
|
||||
cached?.status === "exhausted" ? "exhausted" : "work_requires_model";
|
||||
|
||||
// Record the in-memory hold FIRST so the gate and OpenRouter proxy fail
|
||||
// closed immediately even if durable marker persistence hits a transient DB error.
|
||||
const { heldIssues, newlyHeld } = keyStore.holdIssue(companyId, issue);
|
||||
const heldIssueIds = heldIssues.map((h) => h.id);
|
||||
|
||||
const markerKey = `${companyId}:${issue.id}`;
|
||||
if (
|
||||
!persistedHeldMarkerIds.has(markerKey) &&
|
||||
typeof (db as { insert?: unknown }).insert === "function"
|
||||
) {
|
||||
try {
|
||||
await db.insert(activityLog).values({
|
||||
companyId,
|
||||
actorType: "system",
|
||||
actorId: "cloud_trial_work_gate",
|
||||
action: CLOUD_TRIAL_ISSUE_HELD_ACTIVITY_ACTION,
|
||||
entityType: "issue",
|
||||
entityId: issue.id,
|
||||
details: {
|
||||
gateReason,
|
||||
assigneeAgentId: issue.assigneeAgentId,
|
||||
},
|
||||
});
|
||||
persistedHeldMarkerIds.add(markerKey);
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, companyId, issueId: issue.id },
|
||||
"Failed to persist cloud_trial.issue_held marker; keeping fail-closed in-memory hold for retry",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the broadcast payload content-free (no private issue titles/ids);
|
||||
// clients refetch `/api/companies/:companyId/cloud-inference/status` which
|
||||
// enforces per-actor issue readability.
|
||||
publishLiveEvent({
|
||||
companyId,
|
||||
type: "cloud_trial.status.updated",
|
||||
payload: {
|
||||
status: cached?.status ?? "active",
|
||||
gateReason,
|
||||
llmBlocked: true,
|
||||
heldIssueCount: heldIssueIds.length,
|
||||
},
|
||||
});
|
||||
|
||||
if (newlyHeld) {
|
||||
trackCloudPostHogEvent(
|
||||
"cloud_trial.work_gated",
|
||||
{
|
||||
gate_reason: gateReason,
|
||||
issue_id: issue.id,
|
||||
held_issue_count: heldIssueIds.length,
|
||||
},
|
||||
{ companyId },
|
||||
);
|
||||
}
|
||||
|
||||
return { held: true, heldIssueIds, heldIssues };
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries all open, executable issues that carry an explicit
|
||||
* `cloud_trial.issue_held` marker in `activityLog` via an inner join so
|
||||
* historical markers on closed/parked tasks are excluded in SQL and active
|
||||
* holds are never truncated by row caps.
|
||||
*/
|
||||
export async function findHeldTrialIssuesFromDb(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
): Promise<CloudTrialHeldIssueSummary[]> {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: issues.id,
|
||||
identifier: issues.identifier,
|
||||
title: issues.title,
|
||||
assigneeAgentId: issues.assigneeAgentId,
|
||||
createdAt: issues.createdAt,
|
||||
})
|
||||
.from(issues)
|
||||
.innerJoin(
|
||||
activityLog,
|
||||
and(
|
||||
eq(activityLog.companyId, issues.companyId),
|
||||
eq(activityLog.entityType, "issue"),
|
||||
eq(activityLog.entityId, sql`${issues.id}::text`),
|
||||
eq(activityLog.action, CLOUD_TRIAL_ISSUE_HELD_ACTIVITY_ACTION),
|
||||
),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(issues.companyId, companyId),
|
||||
isNull(issues.conversationAgentId),
|
||||
isNull(issues.hiddenAt),
|
||||
notInArray(issues.status, [...CLOUD_TRIAL_WORK_GATE_NON_EXECUTABLE_STATUSES]),
|
||||
notInArray(issues.originKind, [...CLOUD_TRIAL_WORK_GATE_EXEMPT_ORIGIN_KINDS]),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(issues.createdAt));
|
||||
|
||||
const deduped = new Map<string, CloudTrialHeldIssueSummary>();
|
||||
for (const row of rows) {
|
||||
if (deduped.has(row.id)) continue;
|
||||
deduped.set(row.id, {
|
||||
id: row.id,
|
||||
identifier: row.identifier ?? null,
|
||||
title: row.title,
|
||||
assigneeAgentId: row.assigneeAgentId ?? null,
|
||||
heldAt: row.createdAt instanceof Date ? row.createdAt.toISOString() : new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
return Array.from(deduped.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the active held issues for a company, hydrating from Postgres when
|
||||
* the company is on trial-only inference and pruning any stale in-memory holds
|
||||
* whose issues have moved to a non-executable/terminal status in DB.
|
||||
*/
|
||||
export async function resolveHeldTrialIssues(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
keyStore: CloudTrialKeyStore,
|
||||
hasTrialAgents: boolean,
|
||||
): Promise<CloudTrialHeldIssueSummary[]> {
|
||||
if (!hasTrialAgents) return [];
|
||||
|
||||
let existingAiConnection: { id: string } | undefined;
|
||||
try {
|
||||
[existingAiConnection] = await db
|
||||
.select({ id: toolConnections.id })
|
||||
.from(toolConnections)
|
||||
.where(
|
||||
and(
|
||||
eq(toolConnections.companyId, companyId),
|
||||
eq(toolConnections.connectionPurpose, "ai"),
|
||||
eq(toolConnections.enabled, true),
|
||||
eq(toolConnections.status, "active"),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
} catch {
|
||||
existingAiConnection = undefined;
|
||||
}
|
||||
if (existingAiConnection) {
|
||||
keyStore.clearHeldIssues(companyId);
|
||||
return [];
|
||||
}
|
||||
|
||||
const inMemory = keyStore.getHeldIssues(companyId);
|
||||
let fromDb: CloudTrialHeldIssueSummary[] | null = null;
|
||||
try {
|
||||
fromDb = await findHeldTrialIssuesFromDb(db, companyId);
|
||||
} catch {
|
||||
fromDb = null;
|
||||
}
|
||||
if (!fromDb) {
|
||||
return inMemory;
|
||||
}
|
||||
|
||||
// If DB returned authoritative held issues (or confirmed in-memory entries
|
||||
// were closed/parked), sync keyStore with DB. When `fromDb` is empty but
|
||||
// `inMemory` is non-empty, verify whether those in-memory IDs are still open
|
||||
// executable issues in DB (handles unit tests where activityLog insert is mocked).
|
||||
if (fromDb.length > 0) {
|
||||
const dbIds = new Set(fromDb.map((item) => item.id));
|
||||
for (const stale of inMemory) {
|
||||
if (!dbIds.has(stale.id)) {
|
||||
keyStore.removeHeldIssue(companyId, stale.id);
|
||||
}
|
||||
}
|
||||
for (const item of fromDb) {
|
||||
keyStore.holdIssue(companyId, item);
|
||||
}
|
||||
return fromDb;
|
||||
}
|
||||
|
||||
if (inMemory.length > 0) {
|
||||
try {
|
||||
const stillOpen = await db
|
||||
.select({ id: issues.id })
|
||||
.from(issues)
|
||||
.where(
|
||||
and(
|
||||
eq(issues.companyId, companyId),
|
||||
inArray(issues.id, inMemory.map((item) => item.id)),
|
||||
isNull(issues.hiddenAt),
|
||||
notInArray(issues.status, [...CLOUD_TRIAL_WORK_GATE_NON_EXECUTABLE_STATUSES]),
|
||||
),
|
||||
);
|
||||
const openIds = new Set(stillOpen.map((row) => row.id));
|
||||
for (const item of inMemory) {
|
||||
if (!openIds.has(item.id)) {
|
||||
keyStore.removeHeldIssue(companyId, item.id);
|
||||
continue;
|
||||
}
|
||||
// Self-heal durability if an earlier marker insert failed transiently.
|
||||
const markerKey = `${companyId}:${item.id}`;
|
||||
if (
|
||||
!persistedHeldMarkerIds.has(markerKey) &&
|
||||
typeof (db as { insert?: unknown }).insert === "function"
|
||||
) {
|
||||
try {
|
||||
await db.insert(activityLog).values({
|
||||
companyId,
|
||||
actorType: "system",
|
||||
actorId: "cloud_trial_work_gate",
|
||||
action: CLOUD_TRIAL_ISSUE_HELD_ACTIVITY_ACTION,
|
||||
entityType: "issue",
|
||||
entityId: item.id,
|
||||
details: {
|
||||
gateReason: "work_requires_model",
|
||||
assigneeAgentId: item.assigneeAgentId,
|
||||
},
|
||||
});
|
||||
persistedHeldMarkerIds.add(markerKey);
|
||||
} catch {
|
||||
// Keep in-memory hold and retry again on next status/gate check.
|
||||
}
|
||||
}
|
||||
}
|
||||
return keyStore.getHeldIssues(companyId);
|
||||
} catch {
|
||||
return inMemory;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters held issue summaries to only those readable by `actor` (fail-closed)
|
||||
* so private task titles and identifiers never leak to other company members,
|
||||
* while preserving the company-wide `gateReason` and `llmBlocked` state.
|
||||
*/
|
||||
export async function filterReadableHeldIssues(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
heldIssues: CloudTrialHeldIssueSummary[],
|
||||
actor?: AuthorizationActor,
|
||||
options?: { throwOnError?: boolean },
|
||||
): Promise<CloudTrialHeldIssueSummary[]> {
|
||||
if (heldIssues.length === 0 || !actor || actor.isInstanceAdmin) {
|
||||
return heldIssues;
|
||||
}
|
||||
try {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: issues.id,
|
||||
companyId: issues.companyId,
|
||||
projectId: issues.projectId,
|
||||
parentId: issues.parentId,
|
||||
assigneeAgentId: issues.assigneeAgentId,
|
||||
assigneeUserId: issues.assigneeUserId,
|
||||
status: issues.status,
|
||||
})
|
||||
.from(issues)
|
||||
.where(
|
||||
and(
|
||||
eq(issues.companyId, companyId),
|
||||
inArray(issues.id, heldIssues.map((h) => h.id)),
|
||||
),
|
||||
);
|
||||
if (rows.length === 0) return [];
|
||||
const decisions = await accessService(db).decideReads(
|
||||
actor,
|
||||
rows.map((row) => ({
|
||||
type: "issue" as const,
|
||||
companyId: row.companyId,
|
||||
issueId: row.id,
|
||||
projectId: row.projectId,
|
||||
parentIssueId: row.parentId,
|
||||
assigneeAgentId: row.assigneeAgentId,
|
||||
assigneeUserId: row.assigneeUserId,
|
||||
status: row.status,
|
||||
})),
|
||||
);
|
||||
const readableIds = new Set<string>();
|
||||
rows.forEach((row, index) => {
|
||||
if (decisions[index]?.allowed) readableIds.add(row.id);
|
||||
});
|
||||
return heldIssues.filter((item) => readableIds.has(item.id));
|
||||
} catch (err) {
|
||||
if (options?.throwOnError) throw err;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforces the "dismissible modal, LLM-blocked until connected" rule:
|
||||
* whenever `gateReason !== null` ("exhausted" OR "work_requires_model") and
|
||||
* the target agent is still a trial-only agent, refuse new chat/LLM turns
|
||||
* with a typed HTTP 402 error. Hydrates from DB on cold restart when trial
|
||||
* inference is active on this stack.
|
||||
*/
|
||||
export async function assertCompanyTrialLlmNotBlocked(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
agentId: string,
|
||||
keyStore: CloudTrialKeyStore,
|
||||
): Promise<void> {
|
||||
const inMemoryGateReason = keyStore.getGateReason(companyId);
|
||||
const trialMayBeActive =
|
||||
inMemoryGateReason !== null ||
|
||||
keyStore.getCached() !== null ||
|
||||
getResolvedCloudTrialInferenceEnabled() === true ||
|
||||
isFreeInferenceOnboardingVariant(getResolvedOnboardingVariant());
|
||||
if (!trialMayBeActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [agent] = await db
|
||||
.select({
|
||||
id: agents.id,
|
||||
runtimeConfig: agents.runtimeConfig,
|
||||
})
|
||||
.from(agents)
|
||||
.where(and(eq(agents.id, agentId), eq(agents.companyId, companyId)))
|
||||
.limit(1);
|
||||
if (!agent || !isAgentUsingCloudTrialInference(agent.runtimeConfig)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (inMemoryGateReason === "exhausted") {
|
||||
throw new CloudTrialExhaustedError(undefined, {
|
||||
companyId,
|
||||
agentId,
|
||||
gateReason: "exhausted",
|
||||
});
|
||||
}
|
||||
if (inMemoryGateReason === "work_requires_model") {
|
||||
const heldIssueIds = keyStore.getHeldIssues(companyId).map((h) => h.id);
|
||||
throw new CloudTrialWorkRequiresModelError(undefined, {
|
||||
companyId,
|
||||
agentId,
|
||||
gateReason: "work_requires_model",
|
||||
heldIssueIds,
|
||||
});
|
||||
}
|
||||
|
||||
// Cold-start / post-sleep-wake hydration from DB:
|
||||
const blockedRun = await findLatestExhaustedTrialRun(db, companyId, [agentId]).catch(() => null);
|
||||
if (blockedRun) {
|
||||
throw new CloudTrialExhaustedError(undefined, {
|
||||
companyId,
|
||||
agentId,
|
||||
gateReason: "exhausted",
|
||||
runId: blockedRun.runId,
|
||||
});
|
||||
}
|
||||
const heldIssues = await resolveHeldTrialIssues(db, companyId, keyStore, true);
|
||||
if (heldIssues.length > 0) {
|
||||
throw new CloudTrialWorkRequiresModelError(undefined, {
|
||||
companyId,
|
||||
agentId,
|
||||
gateReason: "work_requires_model",
|
||||
heldIssueIds: heldIssues.map((h) => h.id),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the most recent blocked trial run ONLY among agents whose *latest* run
|
||||
* ended with a trial exhaustion error. Once credits are restored or a newer
|
||||
@@ -151,8 +713,11 @@ export async function getCompanyCloudTrialStatus(
|
||||
keyStore: CloudTrialKeyStore,
|
||||
options: { refreshUsage?: boolean; actor?: AuthorizationActor } = {},
|
||||
): Promise<CloudTrialInferenceStatus> {
|
||||
const experimental = await instanceSettingsService(db).getExperimental();
|
||||
const enabled = experimental.enableCloudTrialInference === true;
|
||||
const effective = await resolveEffectiveOnboardingConfig(db, keyStore, {
|
||||
forceRefresh: Boolean(options.refreshUsage),
|
||||
});
|
||||
const enabled = effective.trialInferenceEnabled;
|
||||
const onboardingVariant = effective.onboardingVariant;
|
||||
|
||||
const companyAgents = await db
|
||||
.select({
|
||||
@@ -211,13 +776,21 @@ export async function getCompanyCloudTrialStatus(
|
||||
}
|
||||
|
||||
const blockedRun = await findLatestExhaustedTrialRun(db, companyId, trialAgentIds);
|
||||
const allHeldIssues = await resolveHeldTrialIssues(db, companyId, keyStore, trialAgentIds.length > 0);
|
||||
const heldIssues = await filterReadableHeldIssues(db, companyId, allHeldIssues, options.actor);
|
||||
const heldIssueIds = heldIssues.map((h) => h.id);
|
||||
|
||||
if (!enabled) {
|
||||
return {
|
||||
enabled: false,
|
||||
onboardingVariant,
|
||||
provider: "openrouter",
|
||||
status: "unavailable",
|
||||
reason: "feature_disabled",
|
||||
gateReason: null,
|
||||
llmBlocked: false,
|
||||
heldIssueIds: [],
|
||||
heldIssues: [],
|
||||
limitUsdCents: 0,
|
||||
spentUsdCents: 0,
|
||||
remainingUsdCents: 0,
|
||||
@@ -261,11 +834,25 @@ export async function getCompanyCloudTrialStatus(
|
||||
? "exhausted"
|
||||
: state.status;
|
||||
|
||||
const gateReason: CloudTrialGateReason | null =
|
||||
trialAgentIds.length === 0
|
||||
? null
|
||||
: effectiveStatus === "exhausted"
|
||||
? "exhausted"
|
||||
: allHeldIssues.length > 0
|
||||
? "work_requires_model"
|
||||
: null;
|
||||
|
||||
return {
|
||||
enabled: true,
|
||||
onboardingVariant,
|
||||
provider: "openrouter",
|
||||
status: effectiveStatus,
|
||||
...(state.reason ? { reason: state.reason } : {}),
|
||||
gateReason,
|
||||
llmBlocked: gateReason !== null,
|
||||
heldIssueIds,
|
||||
heldIssues,
|
||||
limitUsdCents: state.limitUsdCents,
|
||||
spentUsdCents: state.spentUsdCents,
|
||||
remainingUsdCents: effectiveStatus === "exhausted" ? 0 : state.remainingUsdCents,
|
||||
|
||||
@@ -8,8 +8,15 @@ import { PREDECESSOR_RETIREMENT_FALLBACK_KEY, readPredecessorRetirementFallback,
|
||||
import { releaseUnchangedFallbackWorkspace } from "./predecessor-retirement-fallback.js";
|
||||
import { hasNativeExecutionStartEvidence } from "../native-runtime/native-restart-recovery.js";
|
||||
import { isSandboxProviderDiskFullError, NATIVE_SANDBOX_DISK_FULL } from "../native-runtime/native-sandbox-disk-full.js";
|
||||
import { CLOUD_TRIAL_EXHAUSTED_ERROR_CODE, withoutSqlStatementText } from "@paperclipai/shared";
|
||||
import { isCloudTrialExhaustedError } from "../cloud-trial-inference.js";
|
||||
import {
|
||||
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
|
||||
withoutSqlStatementText,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
isCloudTrialExhaustedError,
|
||||
isCloudTrialWorkRequiresModelError,
|
||||
} from "../cloud-trial-inference.js";
|
||||
import { nativeTaskSessionPublicationHandled } from "../native-runtime/native-task-session-publication.js";
|
||||
import { boundOriginalMessage, describeRefusedExactResume, interruptedExactResumeCause } from "../native-runtime/native-exact-resume-failure.js";
|
||||
import { settledResponsePublicationSql } from "../native-runtime/native-response-publication-receipt.js";
|
||||
@@ -1746,6 +1753,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
configurationIncompleteSetupFailure?.resultJson.configurationIncomplete);
|
||||
const setupFailureErrorCode =
|
||||
(isCloudTrialExhaustedError(outerErr) ? CLOUD_TRIAL_EXHAUSTED_ERROR_CODE : null) ??
|
||||
(isCloudTrialWorkRequiresModelError(outerErr) ? CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE : null) ??
|
||||
(controllerLeaseLost && !ownedAiSelectionRejection ? CONTROLLER_LEASE_LOST_FAILURE_CODE : null) ??
|
||||
(storageUnavailable ? STORAGE_UNAVAILABLE_CODE : null) ??
|
||||
remoteWorkspacePreparationTimeout?.code ??
|
||||
|
||||
@@ -2,7 +2,7 @@ import { and, eq, ne, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { agents, companyOnboardingSeeds, goals, toolConnections } from "@paperclipai/db";
|
||||
import { resolveCloudTrialModel, type ApplyOnboardingSeed } from "@paperclipai/shared";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import { getDefaultCloudTrialInferenceController } from "./cloud-trial-inference.js";
|
||||
import { writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { findActiveServerAdapter } from "../adapters/registry.js";
|
||||
import { agentService } from "./agents.js";
|
||||
@@ -152,15 +152,16 @@ export function onboardingSeedService(db: Db) {
|
||||
if (agentId) {
|
||||
await agentSvc.update(agentId, { name: agentName, title: agentRole });
|
||||
} else {
|
||||
const experimental = await instanceSettingsService(dbx).getExperimental();
|
||||
const effectiveOnboarding = await getDefaultCloudTrialInferenceController().resolveOnboardingConfig(dbx);
|
||||
const actorUserId = audit?.actorType === "user" ? audit.actorId : null;
|
||||
trackCloudTrialExposure({
|
||||
surface: "onboarding_seed",
|
||||
userId: actorUserId,
|
||||
companyId,
|
||||
enabledOverride: experimental.enableCloudTrialInference === true,
|
||||
enabledOverride: effectiveOnboarding.trialInferenceEnabled,
|
||||
onboardingVariantOverride: effectiveOnboarding.onboardingVariant,
|
||||
});
|
||||
const existingAiConnections = experimental.enableCloudTrialInference
|
||||
const existingAiConnections = effectiveOnboarding.trialInferenceEnabled
|
||||
? await dbx
|
||||
.select({ id: toolConnections.id })
|
||||
.from(toolConnections)
|
||||
@@ -168,7 +169,7 @@ export function onboardingSeedService(db: Db) {
|
||||
.limit(1)
|
||||
: [];
|
||||
const useCloudTrial =
|
||||
experimental.enableCloudTrialInference && existingAiConnections.length === 0;
|
||||
effectiveOnboarding.trialInferenceEnabled && existingAiConnections.length === 0;
|
||||
const adapterType = useCloudTrial ? "paperclip_runner" : seededAgentAdapterType();
|
||||
const trialModel = resolveCloudTrialModel(process.env.PAPERCLIP_CLOUD_TRIAL_MODEL);
|
||||
const adapterConfig = useCloudTrial
|
||||
|
||||
@@ -5,6 +5,13 @@ import {
|
||||
type TelemetryDimensions,
|
||||
type TelemetryEvent,
|
||||
} from "@paperclipai/shared/telemetry";
|
||||
import {
|
||||
DEFAULT_ONBOARDING_VARIANT,
|
||||
FREE_INFERENCE_ONBOARDING_VARIANT,
|
||||
ONBOARDING_FLOW_FLAG_KEY,
|
||||
normalizeOnboardingVariant,
|
||||
type OnboardingVariant,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
CLOUD_TRIAL_INFERENCE_FLAG_KEY,
|
||||
cloudTrialInferenceCohort,
|
||||
@@ -55,15 +62,44 @@ export type PostHogDirectBatchMeta = {
|
||||
|
||||
type IdentityConfig = Pick<CloudPostHogConfig, "stackId" | "environment"> & {
|
||||
cloudTrialInferenceEnabled?: boolean;
|
||||
onboardingVariant?: OnboardingVariant;
|
||||
};
|
||||
|
||||
export function resolveEventOnboardingVariant(config: IdentityConfig): OnboardingVariant | undefined {
|
||||
if (typeof config.onboardingVariant === "string" && config.onboardingVariant.trim()) {
|
||||
return normalizeOnboardingVariant(config.onboardingVariant);
|
||||
}
|
||||
if (typeof config.cloudTrialInferenceEnabled === "boolean") {
|
||||
return config.cloudTrialInferenceEnabled
|
||||
? FREE_INFERENCE_ONBOARDING_VARIANT
|
||||
: DEFAULT_ONBOARDING_VARIANT;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function cloudExperimentProperties(
|
||||
cloudTrialInferenceEnabled: boolean | undefined,
|
||||
onboardingVariant?: OnboardingVariant,
|
||||
): Record<string, unknown> {
|
||||
if (typeof cloudTrialInferenceEnabled !== "boolean") return {};
|
||||
const variant =
|
||||
typeof onboardingVariant === "string" && onboardingVariant.trim()
|
||||
? normalizeOnboardingVariant(onboardingVariant)
|
||||
: typeof cloudTrialInferenceEnabled === "boolean"
|
||||
? (cloudTrialInferenceEnabled ? FREE_INFERENCE_ONBOARDING_VARIANT : DEFAULT_ONBOARDING_VARIANT)
|
||||
: undefined;
|
||||
return {
|
||||
cloud_trial_inference_enabled: cloudTrialInferenceEnabled,
|
||||
[`$feature/${CLOUD_TRIAL_INFERENCE_FLAG_KEY}`]: cloudTrialInferenceCohort(cloudTrialInferenceEnabled),
|
||||
...(typeof cloudTrialInferenceEnabled === "boolean"
|
||||
? {
|
||||
cloud_trial_inference_enabled: cloudTrialInferenceEnabled,
|
||||
[`$feature/${CLOUD_TRIAL_INFERENCE_FLAG_KEY}`]: cloudTrialInferenceCohort(cloudTrialInferenceEnabled),
|
||||
}
|
||||
: {}),
|
||||
...(variant
|
||||
? {
|
||||
onboarding_variant: variant,
|
||||
[`$feature/${ONBOARDING_FLOW_FLAG_KEY}`]: variant,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -173,6 +209,7 @@ export function buildPostHogDirectEvent(
|
||||
});
|
||||
const distinctId = resolveDistinctId(config, context);
|
||||
const hasPerson = Boolean(context?.userId);
|
||||
const resolvedVariant = resolveEventOnboardingVariant(config);
|
||||
return {
|
||||
event: event.name,
|
||||
distinct_id: distinctId,
|
||||
@@ -197,11 +234,14 @@ export function buildPostHogDirectEvent(
|
||||
...(context?.userId ? { user_id: context.userId } : {}),
|
||||
attributed_via: context?.userId ? (context.attributedVia ?? "request") : "none",
|
||||
...(config.environment ? { environment: config.environment } : {}),
|
||||
...cloudExperimentProperties(config.cloudTrialInferenceEnabled),
|
||||
...cloudExperimentProperties(config.cloudTrialInferenceEnabled, config.onboardingVariant),
|
||||
...(context?.sessionId ? { $session_id: context.sessionId } : {}),
|
||||
...(context?.windowId ? { $window_id: context.windowId } : {}),
|
||||
$groups: { [POSTHOG_WORKSPACE_GROUP_TYPE]: config.stackId },
|
||||
distinct_id: distinctId,
|
||||
...(hasPerson && resolvedVariant
|
||||
? { $set_once: { initial_onboarding_variant: resolvedVariant } }
|
||||
: {}),
|
||||
// A workspace id must never become a person profile.
|
||||
...(hasPerson ? {} : { $process_person_profile: false }),
|
||||
},
|
||||
@@ -244,7 +284,7 @@ export function buildWorkspaceStartedEvent(
|
||||
install_hash: input.installHash,
|
||||
attributed_via: "none",
|
||||
...(config.environment ? { environment: config.environment } : {}),
|
||||
...cloudExperimentProperties(config.cloudTrialInferenceEnabled),
|
||||
...cloudExperimentProperties(config.cloudTrialInferenceEnabled, config.onboardingVariant),
|
||||
$groups: { [POSTHOG_WORKSPACE_GROUP_TYPE]: config.stackId },
|
||||
distinct_id: distinctId,
|
||||
$process_person_profile: false,
|
||||
@@ -269,10 +309,12 @@ export function buildCloudDirectEvent(
|
||||
): PostHogDirectEvent {
|
||||
const distinctId = resolveDistinctId(config, context);
|
||||
const hasPerson = Boolean(context?.userId);
|
||||
const resolvedVariant = resolveEventOnboardingVariant(config);
|
||||
const setOnce: Record<string, unknown> = {
|
||||
...(typeof config.cloudTrialInferenceEnabled === "boolean"
|
||||
? { cloud_trial_inference_cohort: cloudTrialInferenceCohort(config.cloudTrialInferenceEnabled) }
|
||||
: {}),
|
||||
...(resolvedVariant ? { initial_onboarding_variant: resolvedVariant } : {}),
|
||||
...(input.setOncePersonProperties ?? {}),
|
||||
};
|
||||
return {
|
||||
@@ -288,7 +330,7 @@ export function buildCloudDirectEvent(
|
||||
...(context?.companyId ? { company_id: context.companyId } : {}),
|
||||
...(context?.userId ? { user_id: context.userId } : {}),
|
||||
...(config.environment ? { environment: config.environment } : {}),
|
||||
...cloudExperimentProperties(config.cloudTrialInferenceEnabled),
|
||||
...cloudExperimentProperties(config.cloudTrialInferenceEnabled, config.onboardingVariant),
|
||||
...(input.properties ?? {}),
|
||||
...(context?.sessionId ? { $session_id: context.sessionId } : {}),
|
||||
...(context?.windowId ? { $window_id: context.windowId } : {}),
|
||||
|
||||
@@ -3,13 +3,22 @@ import type {
|
||||
TelemetrySendResult,
|
||||
TelemetryTransport,
|
||||
} from "@paperclipai/shared/telemetry";
|
||||
import {
|
||||
DEFAULT_ONBOARDING_VARIANT,
|
||||
FREE_INFERENCE_ONBOARDING_VARIANT,
|
||||
ONBOARDING_FLOW_FLAG_KEY,
|
||||
normalizeOnboardingVariant,
|
||||
type OnboardingVariant,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
cloudTrialInferenceCohort,
|
||||
type CloudPostHogConfig,
|
||||
} from "../cloud-posthog-config.js";
|
||||
import {
|
||||
getResolvedCloudTrialInferenceEnabled,
|
||||
getResolvedOnboardingVariant,
|
||||
onCloudTrialInferenceCohortChange,
|
||||
onOnboardingVariantChange,
|
||||
} from "../cloud-posthog-cohort.js";
|
||||
import { onCloudRuntimeIdentityChange } from "../cloud-runtime-identity.js";
|
||||
import {
|
||||
@@ -81,8 +90,12 @@ export type WorkspaceStartup = {
|
||||
export type PostHogDirectTransport = TelemetryTransport & {
|
||||
/** Whether the stack has the Cloud starter-inference experiment enabled. */
|
||||
readonly cloudTrialInferenceEnabled: boolean;
|
||||
/** Active onboarding experiment variant ("baseline", "free_inference_1", etc.). */
|
||||
readonly onboardingVariant: OnboardingVariant;
|
||||
/** Syncs the resolved instance setting (including staging overrides) into all future events. */
|
||||
setCloudTrialInferenceEnabled(enabled: boolean): void;
|
||||
/** Syncs the resolved onboarding variant into all future events and workspace group. */
|
||||
setOnboardingVariant(variant: OnboardingVariant): void;
|
||||
/** Sends `$groupidentify` and `cloud.workspace_started` for this start. */
|
||||
announceWorkspace(startup: WorkspaceStartup): Promise<void>;
|
||||
/** Captures a Cloud-only direct PostHog event (not in the self-hosted collector contract). */
|
||||
@@ -104,30 +117,97 @@ export function createPostHogDirectTransport(
|
||||
let clientPromise: Promise<PostHogNodeClient> | null = null;
|
||||
let pendingAnnouncement: { startup: WorkspaceStartup; occurredAt: string } | null = null;
|
||||
let announcedCohort: boolean | null = null;
|
||||
let announcedVariant: OnboardingVariant | null = null;
|
||||
let announcedVariantResolved = false;
|
||||
let announcedIdentity: { stackSlug: string | null; primaryHost: string | null } | null = null;
|
||||
let latestIdentity: { stackSlug: string; primaryHost: string } | null = null;
|
||||
let explicitCloudTrialInferenceEnabled: boolean | null = null;
|
||||
let explicitOnboardingVariant: OnboardingVariant | null = null;
|
||||
|
||||
const effectiveCloudTrialInferenceEnabled = (): boolean =>
|
||||
explicitCloudTrialInferenceEnabled ??
|
||||
getResolvedCloudTrialInferenceEnabled() ??
|
||||
config.cloudTrialInferenceEnabled;
|
||||
|
||||
const syncWorkspaceGroupCohort = (enabled: boolean) => {
|
||||
if (announcedCohort === null || announcedCohort === enabled || !clientPromise) return;
|
||||
const isVariantResolved = (): boolean =>
|
||||
explicitOnboardingVariant !== null ||
|
||||
getResolvedOnboardingVariant() !== null ||
|
||||
config.onboardingVariantResolved === true;
|
||||
|
||||
const effectiveOnboardingVariant = (): OnboardingVariant => {
|
||||
if (explicitOnboardingVariant !== null) return explicitOnboardingVariant;
|
||||
const resolved = getResolvedOnboardingVariant();
|
||||
if (resolved !== null) return resolved;
|
||||
if (typeof config.onboardingVariant === "string" && config.onboardingVariant.trim()) {
|
||||
return normalizeOnboardingVariant(config.onboardingVariant);
|
||||
}
|
||||
return effectiveCloudTrialInferenceEnabled()
|
||||
? FREE_INFERENCE_ONBOARDING_VARIANT
|
||||
: DEFAULT_ONBOARDING_VARIANT;
|
||||
};
|
||||
|
||||
const captureWorkspaceGroupIdentify = (
|
||||
client: PostHogNodeClient,
|
||||
groupKey: string,
|
||||
groupSet: Record<string, unknown>,
|
||||
variant: OnboardingVariant,
|
||||
includeSetOnce: boolean,
|
||||
) => {
|
||||
// Emit `$groupidentify` via `capture` so `$group_set_once` sits at the
|
||||
// top level of the event properties (PostHog's `groupIdentify()` helper
|
||||
// wraps all `properties` inside `$group_set`). Only include
|
||||
// `$group_set_once.initial_onboarding_variant` once the stack's assigned
|
||||
// variant is actually resolved so warm-pool boot never locks `"baseline"`.
|
||||
client.capture({
|
||||
distinctId: `$groups_${POSTHOG_WORKSPACE_GROUP_TYPE}_${groupKey}`,
|
||||
event: "$groupidentify",
|
||||
disableGeoip: true,
|
||||
sendFeatureFlags: false,
|
||||
properties: {
|
||||
$group_type: POSTHOG_WORKSPACE_GROUP_TYPE,
|
||||
$group_key: groupKey,
|
||||
$group_set: groupSet,
|
||||
...(includeSetOnce
|
||||
? {
|
||||
$group_set_once: {
|
||||
initial_onboarding_variant: variant,
|
||||
onboarding_variant: variant,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
$process_person_profile: false,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const syncWorkspaceGroupCohort = (enabled: boolean, variant: OnboardingVariant, resolved: boolean) => {
|
||||
if (
|
||||
announcedCohort === null ||
|
||||
(announcedCohort === enabled &&
|
||||
announcedVariant === variant &&
|
||||
announcedVariantResolved === resolved) ||
|
||||
!clientPromise
|
||||
) {
|
||||
return;
|
||||
}
|
||||
announcedCohort = enabled;
|
||||
announcedVariant = variant;
|
||||
announcedVariantResolved = resolved;
|
||||
void clientPromise
|
||||
.then((client) => {
|
||||
client.groupIdentify({
|
||||
groupType: POSTHOG_WORKSPACE_GROUP_TYPE,
|
||||
groupKey: config.stackId,
|
||||
disableGeoip: true,
|
||||
properties: {
|
||||
captureWorkspaceGroupIdentify(
|
||||
client,
|
||||
config.stackId,
|
||||
{
|
||||
environment: config.environment,
|
||||
cloud_trial_inference_enabled: enabled,
|
||||
cloud_trial_inference_cohort: cloudTrialInferenceCohort(enabled),
|
||||
onboarding_variant: variant,
|
||||
[`$feature/${ONBOARDING_FLOW_FLAG_KEY}`]: variant,
|
||||
},
|
||||
});
|
||||
variant,
|
||||
resolved,
|
||||
);
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort analytics must never interrupt settings reads.
|
||||
@@ -136,7 +216,12 @@ export function createPostHogDirectTransport(
|
||||
|
||||
const unsubscribeCohortChange = onCloudTrialInferenceCohortChange((enabled) => {
|
||||
if (explicitCloudTrialInferenceEnabled !== null) return;
|
||||
syncWorkspaceGroupCohort(enabled);
|
||||
syncWorkspaceGroupCohort(enabled, effectiveOnboardingVariant(), isVariantResolved());
|
||||
});
|
||||
|
||||
const unsubscribeVariantChange = onOnboardingVariantChange((variant) => {
|
||||
if (explicitOnboardingVariant !== null) return;
|
||||
syncWorkspaceGroupCohort(effectiveCloudTrialInferenceEnabled(), variant, true);
|
||||
});
|
||||
|
||||
const identifyWorkspaceGroup = (
|
||||
@@ -144,18 +229,28 @@ export function createPostHogDirectTransport(
|
||||
activeConfig: CloudPostHogConfig,
|
||||
identity: { stackSlug: string | null; primaryHost: string | null },
|
||||
) => {
|
||||
client.groupIdentify({
|
||||
groupType: POSTHOG_WORKSPACE_GROUP_TYPE,
|
||||
groupKey: activeConfig.stackId,
|
||||
disableGeoip: true,
|
||||
properties: {
|
||||
const variant = normalizeOnboardingVariant(
|
||||
activeConfig.onboardingVariant ??
|
||||
(activeConfig.cloudTrialInferenceEnabled
|
||||
? FREE_INFERENCE_ONBOARDING_VARIANT
|
||||
: DEFAULT_ONBOARDING_VARIANT),
|
||||
);
|
||||
const resolved = activeConfig.onboardingVariantResolved === true;
|
||||
captureWorkspaceGroupIdentify(
|
||||
client,
|
||||
activeConfig.stackId,
|
||||
{
|
||||
stack_slug: identity.stackSlug,
|
||||
primary_host: identity.primaryHost,
|
||||
environment: activeConfig.environment,
|
||||
cloud_trial_inference_enabled: activeConfig.cloudTrialInferenceEnabled,
|
||||
cloud_trial_inference_cohort: cloudTrialInferenceCohort(activeConfig.cloudTrialInferenceEnabled),
|
||||
onboarding_variant: variant,
|
||||
[`$feature/${ONBOARDING_FLOW_FLAG_KEY}`]: variant,
|
||||
},
|
||||
});
|
||||
variant,
|
||||
resolved,
|
||||
);
|
||||
};
|
||||
|
||||
const syncWorkspaceGroupIdentity = (stackId: string, stackSlug: string, primaryHost: string) => {
|
||||
@@ -194,9 +289,13 @@ export function createPostHogDirectTransport(
|
||||
|
||||
const currentConfig = (): CloudPostHogConfig => {
|
||||
const enabled = effectiveCloudTrialInferenceEnabled();
|
||||
return enabled === config.cloudTrialInferenceEnabled
|
||||
const onboardingVariant = effectiveOnboardingVariant();
|
||||
const onboardingVariantResolved = isVariantResolved();
|
||||
return enabled === config.cloudTrialInferenceEnabled &&
|
||||
onboardingVariant === config.onboardingVariant &&
|
||||
onboardingVariantResolved === Boolean(config.onboardingVariantResolved)
|
||||
? config
|
||||
: { ...config, cloudTrialInferenceEnabled: enabled };
|
||||
: { ...config, cloudTrialInferenceEnabled: enabled, onboardingVariant, onboardingVariantResolved };
|
||||
};
|
||||
|
||||
const getClient = () => {
|
||||
@@ -236,6 +335,8 @@ export function createPostHogDirectTransport(
|
||||
primaryHost: startup.primaryHost,
|
||||
};
|
||||
announcedCohort = activeConfig.cloudTrialInferenceEnabled;
|
||||
announcedVariant = normalizeOnboardingVariant(activeConfig.onboardingVariant);
|
||||
announcedVariantResolved = activeConfig.onboardingVariantResolved === true;
|
||||
announcedIdentity = { ...identity };
|
||||
identifyWorkspaceGroup(client, activeConfig, identity);
|
||||
capture(
|
||||
@@ -259,9 +360,19 @@ export function createPostHogDirectTransport(
|
||||
return effectiveCloudTrialInferenceEnabled();
|
||||
},
|
||||
|
||||
get onboardingVariant() {
|
||||
return effectiveOnboardingVariant();
|
||||
},
|
||||
|
||||
setCloudTrialInferenceEnabled(enabled: boolean) {
|
||||
explicitCloudTrialInferenceEnabled = enabled;
|
||||
syncWorkspaceGroupCohort(enabled);
|
||||
syncWorkspaceGroupCohort(enabled, effectiveOnboardingVariant(), isVariantResolved());
|
||||
},
|
||||
|
||||
setOnboardingVariant(variant: OnboardingVariant) {
|
||||
const normalized = normalizeOnboardingVariant(variant);
|
||||
explicitOnboardingVariant = normalized;
|
||||
syncWorkspaceGroupCohort(effectiveCloudTrialInferenceEnabled(), normalized, true);
|
||||
},
|
||||
|
||||
hashesPrivateRefs: false,
|
||||
@@ -362,6 +473,7 @@ export function createPostHogDirectTransport(
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
unsubscribeCohortChange();
|
||||
unsubscribeVariantChange();
|
||||
unsubscribeIdentityChange();
|
||||
if (!clientPromise) return;
|
||||
const client = await clientPromise.catch(() => null);
|
||||
|
||||
+25
-8
@@ -11,12 +11,20 @@ import {
|
||||
import { resolvePaperclipInstanceRoot } from "./home-paths.js";
|
||||
import { serverVersion } from "./version.js";
|
||||
import { getCloudStackContext } from "./services/cloud-instance.js";
|
||||
import {
|
||||
DEFAULT_ONBOARDING_VARIANT,
|
||||
FREE_INFERENCE_ONBOARDING_VARIANT,
|
||||
ONBOARDING_FLOW_FLAG_KEY,
|
||||
isFreeInferenceOnboardingVariant,
|
||||
normalizeOnboardingVariant,
|
||||
type OnboardingVariant,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
resetResolvedCloudTrialInferenceEnabledForTests,
|
||||
setResolvedCloudTrialInferenceEnabled,
|
||||
setResolvedOnboardingVariant,
|
||||
} from "./services/cloud-posthog-cohort.js";
|
||||
import {
|
||||
CLOUD_TRIAL_INFERENCE_FLAG_KEY,
|
||||
cloudTrialInferenceCohort,
|
||||
isPostHogDirectDeliveryEnabled,
|
||||
resolveCloudPostHogConfig,
|
||||
@@ -161,27 +169,35 @@ export function trackCloudTrialExposure(input: {
|
||||
userId?: string | null;
|
||||
companyId?: string | null;
|
||||
enabledOverride?: boolean;
|
||||
onboardingVariantOverride?: OnboardingVariant;
|
||||
}): void {
|
||||
const transport = directTransport;
|
||||
if (!transport) return;
|
||||
const dedupeKey = `${input.userId ?? "workspace"}:${input.companyId ?? ""}`;
|
||||
if (exposedTrialActors.has(dedupeKey)) return;
|
||||
exposedTrialActors.add(dedupeKey);
|
||||
const onboardingVariant = input.onboardingVariantOverride
|
||||
? normalizeOnboardingVariant(input.onboardingVariantOverride)
|
||||
: typeof input.enabledOverride === "boolean"
|
||||
? (input.enabledOverride ? FREE_INFERENCE_ONBOARDING_VARIANT : DEFAULT_ONBOARDING_VARIANT)
|
||||
: transport.onboardingVariant;
|
||||
const enabled =
|
||||
typeof input.enabledOverride === "boolean"
|
||||
? input.enabledOverride
|
||||
: transport.cloudTrialInferenceEnabled;
|
||||
if (typeof input.enabledOverride === "boolean") {
|
||||
setResolvedCloudTrialInferenceEnabled(input.enabledOverride);
|
||||
transport.setCloudTrialInferenceEnabled(input.enabledOverride);
|
||||
}
|
||||
: input.onboardingVariantOverride
|
||||
? isFreeInferenceOnboardingVariant(onboardingVariant)
|
||||
: transport.cloudTrialInferenceEnabled;
|
||||
setResolvedCloudTrialInferenceEnabled(enabled);
|
||||
setResolvedOnboardingVariant(onboardingVariant);
|
||||
transport.setCloudTrialInferenceEnabled(enabled);
|
||||
transport.setOnboardingVariant(onboardingVariant);
|
||||
const cohort = cloudTrialInferenceCohort(enabled);
|
||||
void transport
|
||||
.captureCloudEvent({
|
||||
event: "$feature_flag_called",
|
||||
properties: {
|
||||
$feature_flag: CLOUD_TRIAL_INFERENCE_FLAG_KEY,
|
||||
$feature_flag_response: cohort,
|
||||
$feature_flag: ONBOARDING_FLOW_FLAG_KEY,
|
||||
$feature_flag_response: onboardingVariant,
|
||||
surface: input.surface,
|
||||
},
|
||||
contextOverride: {
|
||||
@@ -189,6 +205,7 @@ export function trackCloudTrialExposure(input: {
|
||||
...(input.companyId ? { companyId: input.companyId } : {}),
|
||||
},
|
||||
setOncePersonProperties: {
|
||||
initial_onboarding_variant: onboardingVariant,
|
||||
cloud_trial_inference_cohort: cohort,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -218,7 +218,7 @@
|
||||
"packages/shared/src/cliplab/svg-canvas.ts": "2b1bb631749524487d05a61df435da7effb5d607",
|
||||
"packages/shared/src/cliplab/svg-path.ts": "69ab5fc506a0ad9965837ddb41ecc245b2df1916",
|
||||
"packages/shared/src/cliplab/svg-snapshot.ts": "f1ef8e5d8e4d69db0d1cdcf80ba9b54a7ad3d0c7",
|
||||
"packages/shared/src/cloud-inference.ts": "29ccc0135b0d4557daf73ad674aa10faf6eccfd0",
|
||||
"packages/shared/src/cloud-inference.ts": "e91bb2e8d732a9935bbfc36a693de4b910184937",
|
||||
"packages/shared/src/company-import-transfer.test.ts": "213169db79a3f4b6788f4107d6a7b49cd0beb6b9",
|
||||
"packages/shared/src/company-import-transfer.ts": "376482a8c28feba53b1e4973db0ba2e158b65b41",
|
||||
"packages/shared/src/composio-app-setup.ts": "75f544f5647f227214b8a9d0f61d0196bcbbab55",
|
||||
@@ -496,7 +496,7 @@
|
||||
"packages/shared/src/upstream-failure-codes.test.ts": "b4a12899b8daa13b4a015945f21ead45a1f36a2a",
|
||||
"packages/shared/src/upstream-failure-codes.ts": "da13407180aa18d5bb20c8dfc1d3b48538bd71d0",
|
||||
"packages/shared/src/validators/access.test.ts": "121d9f1e0bd1715ba3c5d1ff1016d38898d06afa",
|
||||
"packages/shared/src/validators/access.ts": "85c63826b522027847cd22531ead9efc40008950",
|
||||
"packages/shared/src/validators/access.ts": "d74cd1c4950258d2e9d0fbe1cefb8c4e890932ad",
|
||||
"packages/shared/src/validators/adapter-auth-session.ts": "14cffbd7281265bf3f059bcf1b97739ebe0e1f81",
|
||||
"packages/shared/src/validators/adapter-registry.test.ts": "567c113e50dd0c0d259b095375f8f8f403ffa893",
|
||||
"packages/shared/src/validators/adapter-registry.ts": "6fb9f655d49f774ef7f082bf842f388f1187e545",
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { ArrowRight, Sparkles } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type {
|
||||
CloudTrialGateReason,
|
||||
CloudTrialHeldIssueSummaryCompat,
|
||||
} from "@/lib/cloud-trial-gate";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface CloudTrialBlockedBannerProps {
|
||||
gateReason: CloudTrialGateReason | null;
|
||||
heldIssues?: CloudTrialHeldIssueSummaryCompat[];
|
||||
canMigrate?: boolean;
|
||||
onConnect: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline composer banner shown when the user dismissed the connect-a-model
|
||||
* modal while starter inference is gated (`exhausted` or `work_requires_model`).
|
||||
* Keeps chat sending disabled and gives a direct CTA to re-open the modal.
|
||||
*/
|
||||
export function CloudTrialBlockedBanner({
|
||||
gateReason,
|
||||
heldIssues = [],
|
||||
canMigrate = true,
|
||||
onConnect,
|
||||
className,
|
||||
}: CloudTrialBlockedBannerProps) {
|
||||
const isWorkRequiresModel = gateReason === "work_requires_model";
|
||||
const heldCount = heldIssues.length;
|
||||
|
||||
const title = isWorkRequiresModel
|
||||
? "Connect a model to run tasks and keep chatting"
|
||||
: "Connect a model to keep chatting";
|
||||
|
||||
const description = !canMigrate
|
||||
? "Ask a company administrator to connect a model provider before agents can continue."
|
||||
: isWorkRequiresModel
|
||||
? heldCount === 1
|
||||
? `${heldIssues[0]?.identifier ? `${heldIssues[0].identifier} (${heldIssues[0].title})` : heldIssues[0]?.title || "Your subtask"} is waiting to run once you connect a model provider.`
|
||||
: heldCount > 1
|
||||
? `${heldCount} tasks are waiting to run once you connect a model provider.`
|
||||
: "Connect a model provider to run waiting tasks and resume chatting."
|
||||
: "Connect a model provider to continue chatting with your agents.";
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
data-testid="cloud-trial-blocked-banner"
|
||||
className={cn(
|
||||
"flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-card px-4 py-3 text-sm",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-start gap-2.5">
|
||||
<div className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-muted/50 text-foreground">
|
||||
<Sparkles className="size-3.5" aria-hidden="true" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 space-y-0.5">
|
||||
<p className="text-sm font-medium text-foreground">{title}</p>
|
||||
<p className="text-xs text-muted-foreground">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
{canMigrate && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={onConnect}
|
||||
className="shrink-0"
|
||||
>
|
||||
Connect a model
|
||||
<ArrowRight className="ml-1.5 size-3.5" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
} from "lucide-react";
|
||||
import type {
|
||||
AiConnectionBinding,
|
||||
CloudTrialInferenceStatus,
|
||||
MigrateCloudTrialAgentsResult,
|
||||
} from "@paperclipai/shared";
|
||||
import { cloudInferenceApi } from "@/api/cloud-inference";
|
||||
@@ -24,13 +23,19 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
getCloudTrialGateReason,
|
||||
getCloudTrialHeldIssueIds,
|
||||
getCloudTrialHeldIssues,
|
||||
type CloudTrialInferenceStatusCompat,
|
||||
} from "@/lib/cloud-trial-gate";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface CloudTrialExhaustedModalProps {
|
||||
open: boolean;
|
||||
companyId: string;
|
||||
status: CloudTrialInferenceStatus;
|
||||
status: CloudTrialInferenceStatusCompat;
|
||||
/** When true, blocks closing until the user connects a model provider and migrates agents. */
|
||||
required?: boolean;
|
||||
/** Initial visual phase override (primarily for Storybook & previewing states). */
|
||||
@@ -46,7 +51,7 @@ export function CloudTrialExhaustedModal({
|
||||
open,
|
||||
companyId,
|
||||
status,
|
||||
required = true,
|
||||
required = false,
|
||||
initialPhase = "connect",
|
||||
initialResult = null,
|
||||
initialError = null,
|
||||
@@ -74,11 +79,12 @@ export function CloudTrialExhaustedModal({
|
||||
.trackTelemetry(companyId, {
|
||||
event: "modal_shown",
|
||||
trialAgentCount: status.trialAgents.length,
|
||||
gateReason: getCloudTrialGateReason(status) ?? "exhausted",
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort analytics must never interrupt connecting a provider.
|
||||
});
|
||||
}, [open, phase, companyId, status.trialAgents.length]);
|
||||
}, [open, phase, companyId, status]);
|
||||
|
||||
const migrateMutation = useMutation({
|
||||
mutationFn: (binding: Exclude<AiConnectionBinding, { mode: "responsible_user" }>) =>
|
||||
@@ -102,6 +108,7 @@ export function CloudTrialExhaustedModal({
|
||||
onMigrated?.(result);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.cloudInference.status(companyId) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) });
|
||||
void queryClient.invalidateQueries({ queryKey: ["ai-connections", companyId] });
|
||||
},
|
||||
onError: (err) => {
|
||||
@@ -113,6 +120,43 @@ export function CloudTrialExhaustedModal({
|
||||
const canMigrate = status.canMigrate !== false;
|
||||
const canClose = !required || !canMigrate || phase === "done";
|
||||
const agentCount = status.trialAgents.length;
|
||||
const gateReason = getCloudTrialGateReason(status) ?? "exhausted";
|
||||
const heldIssueIds = getCloudTrialHeldIssueIds(status);
|
||||
const heldIssues = getCloudTrialHeldIssues(status);
|
||||
const heldCount = Math.max(heldIssueIds.length, heldIssues.length);
|
||||
const isWorkRequiresModel = gateReason === "work_requires_model";
|
||||
const agentLabel =
|
||||
agentCount === 1
|
||||
? status.trialAgents[0]?.name || "your agent"
|
||||
: agentCount > 1
|
||||
? `all ${agentCount} agents`
|
||||
: "your agents";
|
||||
|
||||
const resumedTaskCount = migrationResult?.resumedIssueIds.length ?? 0;
|
||||
const resumedRunCount = migrationResult?.resumedRunIds.length ?? 0;
|
||||
const hasResumedWork = resumedRunCount > 0 || resumedTaskCount > 0;
|
||||
|
||||
const headerTitle =
|
||||
phase === "done"
|
||||
? "Model provider connected"
|
||||
: isWorkRequiresModel
|
||||
? "Connect a model to run tasks"
|
||||
: "Connect a model to keep going";
|
||||
|
||||
const headerDescription =
|
||||
phase === "done"
|
||||
? isWorkRequiresModel && hasResumedWork
|
||||
? "Your agents have been updated and your waiting tasks are now running."
|
||||
: "Your agents have been updated to use your connected model provider."
|
||||
: !canMigrate
|
||||
? "A company administrator needs to connect a model provider before these agents can continue running."
|
||||
: isWorkRequiresModel
|
||||
? heldCount === 1
|
||||
? `Your subtask is ready and waiting to run. Connect a model provider and we’ll automatically update ${agentLabel} and start it.`
|
||||
: heldCount > 1
|
||||
? `Your ${heldCount} tasks are ready and waiting to run. Connect a model provider and we’ll automatically update ${agentLabel} and start them.`
|
||||
: `Connect a model provider to run tasks. We’ll automatically update ${agentLabel} and start your work right away.`
|
||||
: `Connect a model provider to keep going. We’ll automatically update ${agentLabel} and pick up where you left off.`;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
@@ -155,24 +199,30 @@ export function CloudTrialExhaustedModal({
|
||||
<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"}
|
||||
{headerTitle}
|
||||
</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.`}
|
||||
{headerDescription}
|
||||
</DialogDescription>
|
||||
{phase !== "done" && isWorkRequiresModel && heldIssues.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1.5 pt-2">
|
||||
<span className="text-xs text-muted-foreground mr-1">
|
||||
Waiting to run:
|
||||
</span>
|
||||
{heldIssues.map((issue) => (
|
||||
<span
|
||||
key={issue.id}
|
||||
className="inline-flex items-center gap-1 rounded-full border border-border bg-background px-2 py-0.5 text-xs text-foreground"
|
||||
>
|
||||
{issue.identifier ? (
|
||||
<span className="font-mono text-muted-foreground">{issue.identifier}</span>
|
||||
) : null}
|
||||
<span className="max-w-52 truncate font-medium">{issue.title}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{phase !== "done" && status.trialAgents.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1.5 pt-2">
|
||||
<span className="text-xs text-muted-foreground mr-1">
|
||||
@@ -293,10 +343,25 @@ export function CloudTrialExhaustedModal({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{migrationResult && migrationResult.resumedRunIds.length > 0 && (
|
||||
{migrationResult && hasResumedWork && (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-(--status-task-icon-done)/30 bg-(--diff-add-bg) px-3.5 py-2.5 text-xs text-(--diff-add-fg)">
|
||||
<Sparkles className="size-3.5 shrink-0" />
|
||||
<span>Your paused work has been automatically resumed.</span>
|
||||
<span>
|
||||
{isWorkRequiresModel
|
||||
? resumedTaskCount > 1
|
||||
? `Your ${resumedTaskCount} held tasks have been automatically started.`
|
||||
: "Your held task has been automatically started."
|
||||
: "Your paused work has been automatically resumed."}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{migrationResult && !hasResumedWork && isWorkRequiresModel && heldCount > 0 && (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-border bg-muted/40 px-3.5 py-2.5 text-xs text-muted-foreground">
|
||||
<Sparkles className="size-3.5 shrink-0" />
|
||||
<span>
|
||||
Your model provider is connected, but waiting tasks could not be started automatically. Open your tasks to start them.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type { ReactElement } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { CloudTrialBlockedBanner } from "./CloudTrialBlockedBanner";
|
||||
import { CloudTrialExhaustedModal } from "./CloudTrialExhaustedModal";
|
||||
import {
|
||||
getCloudTrialGateReason,
|
||||
isCloudTrialLlmBlocked,
|
||||
isFreeInferenceOnboardingVariant,
|
||||
requestCloudTrialConnectModal,
|
||||
subscribeCloudTrialConnectModal,
|
||||
type CloudTrialInferenceStatusCompat,
|
||||
} from "@/lib/cloud-trial-gate";
|
||||
|
||||
vi.mock("@/components/ai-connections/AiProviderSetup", () => ({
|
||||
AiProviderSetup: ({ onCancel }: { onCancel?: () => void }) => (
|
||||
<div data-testid="ai-provider-setup-mock">
|
||||
<button type="button" onClick={onCancel}>
|
||||
Cancel setup
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/api/cloud-inference", () => ({
|
||||
cloudInferenceApi: {
|
||||
trackTelemetry: vi.fn().mockResolvedValue(undefined),
|
||||
migrate: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const baseStatus: CloudTrialInferenceStatusCompat = {
|
||||
enabled: true,
|
||||
onboardingVariant: "free_inference_1",
|
||||
provider: "openrouter",
|
||||
status: "active",
|
||||
gateReason: "work_requires_model",
|
||||
llmBlocked: true,
|
||||
heldIssueIds: ["issue-1"],
|
||||
heldIssues: [
|
||||
{
|
||||
id: "issue-1",
|
||||
identifier: "ACME-2",
|
||||
title: "Draft Q3 launch memo",
|
||||
assigneeAgentId: "agent-1",
|
||||
heldAt: "2026-12-01T12:00:00Z",
|
||||
},
|
||||
],
|
||||
limitUsdCents: 100,
|
||||
spentUsdCents: 12,
|
||||
remainingUsdCents: 88,
|
||||
defaultModel: "openrouter/openai/gpt-6-luna",
|
||||
canMigrate: true,
|
||||
trialAgentIds: ["agent-1"],
|
||||
trialAgents: [
|
||||
{
|
||||
id: "agent-1",
|
||||
name: "Nova",
|
||||
role: "ceo",
|
||||
title: "Chief of Staff",
|
||||
},
|
||||
],
|
||||
blockedRun: null,
|
||||
};
|
||||
|
||||
let activeRoot: Root | null = null;
|
||||
let activeContainer: HTMLDivElement | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
if (activeRoot) {
|
||||
flushSync(() => {
|
||||
activeRoot?.unmount();
|
||||
});
|
||||
activeRoot = null;
|
||||
}
|
||||
activeContainer?.remove();
|
||||
activeContainer = null;
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
function mount(ui: ReactElement) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
activeContainer = document.createElement("div");
|
||||
document.body.appendChild(activeContainer);
|
||||
activeRoot = createRoot(activeContainer);
|
||||
flushSync(() => {
|
||||
activeRoot!.render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
|
||||
});
|
||||
return activeContainer;
|
||||
}
|
||||
|
||||
describe("cloud-trial-gate helpers", () => {
|
||||
it("recognizes free_inference_1 and defaults unknown/missing to baseline", () => {
|
||||
expect(isFreeInferenceOnboardingVariant(baseStatus)).toBe(true);
|
||||
expect(isFreeInferenceOnboardingVariant({ ...baseStatus, onboardingVariant: "baseline" })).toBe(false);
|
||||
expect(isFreeInferenceOnboardingVariant(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("derives gateReason and llmBlocked for both work_requires_model and exhausted", () => {
|
||||
expect(getCloudTrialGateReason(baseStatus)).toBe("work_requires_model");
|
||||
expect(isCloudTrialLlmBlocked(baseStatus)).toBe(true);
|
||||
|
||||
const legacyExhausted = {
|
||||
...baseStatus,
|
||||
status: "exhausted",
|
||||
gateReason: null,
|
||||
llmBlocked: false,
|
||||
} as CloudTrialInferenceStatusCompat;
|
||||
expect(getCloudTrialGateReason(legacyExhausted)).toBe("exhausted");
|
||||
expect(isCloudTrialLlmBlocked(legacyExhausted)).toBe(true);
|
||||
|
||||
const activeUngated: CloudTrialInferenceStatusCompat = {
|
||||
...baseStatus,
|
||||
gateReason: null,
|
||||
llmBlocked: false,
|
||||
heldIssueIds: [],
|
||||
heldIssues: [],
|
||||
};
|
||||
expect(getCloudTrialGateReason(activeUngated)).toBeNull();
|
||||
expect(isCloudTrialLlmBlocked(activeUngated)).toBe(false);
|
||||
});
|
||||
|
||||
it("notifies connect-modal subscribers on requestCloudTrialConnectModal", () => {
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = subscribeCloudTrialConnectModal(listener);
|
||||
requestCloudTrialConnectModal();
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
unsubscribe();
|
||||
requestCloudTrialConnectModal();
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CloudTrialBlockedBanner", () => {
|
||||
it("renders work_requires_model copy with held subtask and calls onConnect", () => {
|
||||
const onConnect = vi.fn();
|
||||
const container = mount(
|
||||
<CloudTrialBlockedBanner
|
||||
gateReason="work_requires_model"
|
||||
heldIssues={baseStatus.heldIssues}
|
||||
onConnect={onConnect}
|
||||
/>,
|
||||
);
|
||||
expect(container.textContent).toContain("Connect a model to run tasks and keep chatting");
|
||||
expect(container.textContent).toContain("ACME-2 (Draft Q3 launch memo)");
|
||||
const button = container.querySelector("button");
|
||||
expect(button?.textContent).toContain("Connect a model");
|
||||
button?.click();
|
||||
expect(onConnect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("renders exhausted copy and hides button for viewers", () => {
|
||||
const container = mount(
|
||||
<CloudTrialBlockedBanner
|
||||
gateReason="exhausted"
|
||||
canMigrate={false}
|
||||
onConnect={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(container.textContent).toContain("Connect a model to keep chatting");
|
||||
expect(container.textContent).toContain("Ask a company administrator");
|
||||
expect(container.querySelector("button")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("CloudTrialExhaustedModal", () => {
|
||||
it("shows work_requires_model copy, held subtask pill, and allows dismissal", () => {
|
||||
const onOpenChange = vi.fn();
|
||||
mount(
|
||||
<CloudTrialExhaustedModal
|
||||
open
|
||||
companyId="company-1"
|
||||
status={baseStatus}
|
||||
required={false}
|
||||
onOpenChange={onOpenChange}
|
||||
/>,
|
||||
);
|
||||
expect(document.body.textContent).toContain("Connect a model to run tasks");
|
||||
expect(document.body.textContent).toContain("ACME-2");
|
||||
expect(document.body.textContent).toContain("Draft Q3 launch memo");
|
||||
const cancelBtn = Array.from(document.body.querySelectorAll("button")).find(
|
||||
(btn) => btn.textContent?.trim() === "Cancel setup",
|
||||
);
|
||||
expect(cancelBtn).toBeTruthy();
|
||||
cancelBtn?.click();
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("shows exhausted copy for quota exhaustion", () => {
|
||||
mount(
|
||||
<CloudTrialExhaustedModal
|
||||
open
|
||||
companyId="company-1"
|
||||
status={{
|
||||
...baseStatus,
|
||||
status: "exhausted",
|
||||
gateReason: "exhausted",
|
||||
heldIssueIds: [],
|
||||
heldIssues: [],
|
||||
}}
|
||||
required={false}
|
||||
/>,
|
||||
);
|
||||
expect(document.body.textContent).toContain("Connect a model to keep going");
|
||||
});
|
||||
|
||||
it("does not claim held tasks started when migration resumed zero runs and zero issues", () => {
|
||||
mount(
|
||||
<CloudTrialExhaustedModal
|
||||
open
|
||||
companyId="company-1"
|
||||
status={baseStatus}
|
||||
required={false}
|
||||
initialPhase="done"
|
||||
initialResult={{
|
||||
migratedCount: 1,
|
||||
agents: [
|
||||
{
|
||||
agentId: "agent-1",
|
||||
name: "Nova",
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "claude",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
],
|
||||
resumedRunIds: [],
|
||||
resumedIssueId: null,
|
||||
resumedIssueIds: [],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(document.body.textContent).not.toContain("automatically started");
|
||||
expect(document.body.textContent).toContain("could not be started automatically");
|
||||
});
|
||||
});
|
||||
@@ -1,66 +1,71 @@
|
||||
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 { useEffect, useRef, useState } from "react";
|
||||
import { CloudTrialExhaustedModal } from "@/components/CloudTrialExhaustedModal";
|
||||
import { useCompany } from "@/context/CompanyContext";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { useCloudTrialStatus } from "@/hooks/useCloudTrialStatus";
|
||||
import {
|
||||
subscribeCloudTrialConnectModal,
|
||||
type CloudTrialInferenceStatusCompat,
|
||||
} from "@/lib/cloud-trial-gate";
|
||||
|
||||
/**
|
||||
* Global shell controller that watches the selected company's Cloud starter
|
||||
* inference status and requires connecting a model provider when needed.
|
||||
* inference status and surfaces the connect-a-model modal whenever a trial
|
||||
* gate activates (`exhausted` or `work_requires_model`) or the user clicks a
|
||||
* "Connect a model" CTA after dismissing it.
|
||||
*/
|
||||
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".
|
||||
// Dismissible modal: users may close it, leaving LLM actions blocked until
|
||||
// they connect a model provider. Clicking "Connect a model" or triggering a
|
||||
// new gate condition (e.g., creating another held task) re-opens it.
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
// Keep the modal mounted on its confirmation screen after migration flips
|
||||
// `status` to "migrated" and empties `trialAgentIds`, until the user clicks
|
||||
// "Continue to workspace".
|
||||
const [holdingMigrationSuccess, setHoldingMigrationSuccess] = useState(false);
|
||||
const [migrationComplete, setMigrationComplete] = useState(false);
|
||||
const [lastExhaustedStatus, setLastExhaustedStatus] = useState<CloudTrialInferenceStatus | null>(null);
|
||||
const [lastGatedStatus, setLastGatedStatus] = useState<CloudTrialInferenceStatusCompat | null>(null);
|
||||
const lastTriggerKeyRef = useRef<string | null>(null);
|
||||
|
||||
const experimental = useQuery({
|
||||
queryKey: queryKeys.instance.experimentalSettings,
|
||||
queryFn: instanceSettingsApi.getExperimental,
|
||||
});
|
||||
const { status, gateReason, heldIssueIds, llmBlocked } = useCloudTrialStatus(selectedCompanyId);
|
||||
|
||||
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;
|
||||
const isGated = Boolean(selectedCompanyId) && llmBlocked && Boolean(status);
|
||||
const triggerKey = isGated
|
||||
? `${gateReason ?? "exhausted"}:${heldIssueIds.join(",")}:${status?.blockedRun?.runId ?? ""}`
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (isExhaustedWithTrialAgents && status) {
|
||||
setLastExhaustedStatus(status);
|
||||
if (isGated && status) {
|
||||
setLastGatedStatus(status);
|
||||
if (triggerKey && triggerKey !== lastTriggerKeyRef.current) {
|
||||
lastTriggerKeyRef.current = triggerKey;
|
||||
setModalOpen(true);
|
||||
}
|
||||
} else if (!holdingMigrationSuccess) {
|
||||
lastTriggerKeyRef.current = null;
|
||||
setModalOpen(false);
|
||||
}
|
||||
}, [isExhaustedWithTrialAgents, status]);
|
||||
}, [isGated, status, triggerKey, holdingMigrationSuccess]);
|
||||
|
||||
useEffect(() => {
|
||||
setDismissedAfterMigration(false);
|
||||
return subscribeCloudTrialConnectModal(() => {
|
||||
if (status || lastGatedStatus) {
|
||||
setModalOpen(true);
|
||||
}
|
||||
});
|
||||
}, [status, lastGatedStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
setModalOpen(false);
|
||||
setHoldingMigrationSuccess(false);
|
||||
setMigrationComplete(false);
|
||||
setLastExhaustedStatus(null);
|
||||
setLastGatedStatus(null);
|
||||
lastTriggerKeyRef.current = null;
|
||||
}, [selectedCompanyId]);
|
||||
|
||||
const modalStatus = isExhaustedWithTrialAgents ? status : lastExhaustedStatus;
|
||||
const modalStatus = isGated ? status : lastGatedStatus ?? status;
|
||||
const shouldShowModal =
|
||||
Boolean(selectedCompanyId) &&
|
||||
Boolean(modalStatus) &&
|
||||
!dismissedAfterMigration &&
|
||||
(isExhaustedWithTrialAgents || holdingMigrationSuccess);
|
||||
(modalOpen || holdingMigrationSuccess);
|
||||
|
||||
if (!selectedCompanyId || !modalStatus || !shouldShowModal) {
|
||||
return null;
|
||||
@@ -71,12 +76,11 @@ export function CloudTrialGate() {
|
||||
open={shouldShowModal}
|
||||
companyId={selectedCompanyId}
|
||||
status={modalStatus}
|
||||
required={!migrationComplete && modalStatus.canMigrate !== false}
|
||||
required={false}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setHoldingMigrationSuccess(false);
|
||||
setMigrationComplete(false);
|
||||
setDismissedAfterMigration(true);
|
||||
setModalOpen(false);
|
||||
}
|
||||
}}
|
||||
onMigrationStart={() => {
|
||||
@@ -87,7 +91,6 @@ export function CloudTrialGate() {
|
||||
}}
|
||||
onMigrated={() => {
|
||||
setHoldingMigrationSuccess(true);
|
||||
setMigrationComplete(true);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -53,6 +53,7 @@ import { getTrustPreset } from "../lib/trust-policy-ui";
|
||||
import { useStagedIssueFiles } from "../hooks/useStagedIssueFiles";
|
||||
import { readStagedIssueFiles, writeStagedIssueFiles, type StagedIssueFile } from "../lib/staged-issue-files";
|
||||
import { isImageAttachment } from "./task-chat/task-chat-attachments";
|
||||
import { hasActiveCloudTrialAgents, requestCloudTrialConnectModal, type CloudTrialInferenceStatusCompat } from "@/lib/cloud-trial-gate";
|
||||
|
||||
const DRAFT_KEY = "paperclip:issue-draft";
|
||||
/** A create that is waiting to resend: its request body and idempotency key. */
|
||||
@@ -654,6 +655,13 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean })
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listTouchedByMe(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listUnreadTouchedByMe(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.cloudInference.status(companyId) });
|
||||
const cachedCloudTrial = queryClient.getQueryData<CloudTrialInferenceStatusCompat>(
|
||||
queryKeys.cloudInference.status(companyId),
|
||||
);
|
||||
if (hasActiveCloudTrialAgents(cachedCloudTrial)) {
|
||||
requestCloudTrialConnectModal();
|
||||
}
|
||||
const prefix = (companies.find((company) => company.id === companyId)?.issuePrefix ?? "").trim();
|
||||
const issueRef = issue.identifier ?? issue.id;
|
||||
const openIssueAction = prefix
|
||||
|
||||
@@ -20,7 +20,13 @@ import {
|
||||
} from "./AdapterLoginChrome";
|
||||
import { useLocalAiLogin } from "./ai-connections/useLocalAiLogin";
|
||||
import { aiConnectionsApi } from "@/api/ai-connections";
|
||||
import { authApi } from "@/api/auth";
|
||||
import { cloudInferenceApi } from "@/api/cloud-inference";
|
||||
import {
|
||||
FREE_INFERENCE_ONBOARDING_VARIANT,
|
||||
getCloudTrialOnboardingVariant,
|
||||
type CloudTrialInferenceStatusCompat,
|
||||
} from "@/lib/cloud-trial-gate";
|
||||
import { aiProviderForAdapter } from "./ai-connections/AiConnectionField";
|
||||
import { useConnectionModelsState } from "./ai-connections/useConnectionModels";
|
||||
import type { AiConnectionBinding } from "@paperclipai/shared";
|
||||
@@ -941,12 +947,37 @@ function OnboardingWizardInner({
|
||||
queryFn: () => instanceSettingsApi.getExperimental(),
|
||||
enabled: effectiveOnboardingOpen && step >= 3 && step <= 5,
|
||||
});
|
||||
const { data: onboardingSession } = useQuery({
|
||||
queryKey: queryKeys.auth.session,
|
||||
queryFn: () => authApi.getSession(),
|
||||
enabled: effectiveOnboardingOpen,
|
||||
});
|
||||
const sessionOnboardingVariant =
|
||||
(onboardingSession as { onboardingVariant?: string; browserAnalytics?: { onboardingVariant?: string } } | null | undefined)?.onboardingVariant ??
|
||||
(onboardingSession as { browserAnalytics?: { onboardingVariant?: string } } | null | undefined)?.browserAnalytics?.onboardingVariant ??
|
||||
null;
|
||||
const cloudTrialInferenceEnabled = experimentalSettingsForLogin?.enableCloudTrialInference === true;
|
||||
const { data: cloudTrialStatus } = useQuery({
|
||||
const { data: cloudTrialStatusRaw } = useQuery({
|
||||
queryKey: queryKeys.cloudInference.status(createdCompanyId ?? "__none__"),
|
||||
queryFn: () => cloudInferenceApi.getStatus(createdCompanyId!),
|
||||
enabled: effectiveOnboardingOpen && step === 4 && Boolean(createdCompanyId) && cloudTrialInferenceEnabled,
|
||||
enabled:
|
||||
effectiveOnboardingOpen &&
|
||||
step >= 3 &&
|
||||
Boolean(createdCompanyId) &&
|
||||
(cloudTrialInferenceEnabled ||
|
||||
Boolean(cloudInstance) ||
|
||||
sessionOnboardingVariant === FREE_INFERENCE_ONBOARDING_VARIANT),
|
||||
});
|
||||
const cloudTrialStatus = cloudTrialStatusRaw as CloudTrialInferenceStatusCompat | undefined;
|
||||
const resolvedOnboardingVariant =
|
||||
cloudTrialStatus?.onboardingVariant
|
||||
? getCloudTrialOnboardingVariant(cloudTrialStatus)
|
||||
: sessionOnboardingVariant ?? "baseline";
|
||||
const isFreeInferenceOnboarding =
|
||||
resolvedOnboardingVariant === FREE_INFERENCE_ONBOARDING_VARIANT &&
|
||||
(!cloudTrialStatus ||
|
||||
cloudTrialStatus.status === "not_issued" ||
|
||||
cloudTrialStatus.status === "active");
|
||||
const canUseCloudTrialStarter =
|
||||
cloudTrialInferenceEnabled &&
|
||||
Boolean(cloudTrialStatus) &&
|
||||
@@ -955,7 +986,8 @@ function OnboardingWizardInner({
|
||||
const trackedTrialExposureCompaniesRef = useRef<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
if (!effectiveOnboardingOpen || step !== 4 || !createdCompanyId) return;
|
||||
if (!effectiveOnboardingOpen || !createdCompanyId) return;
|
||||
if (step !== 4 && !(step === 3 && isFreeInferenceOnboarding)) return;
|
||||
if (trackedTrialExposureCompaniesRef.current.has(createdCompanyId)) return;
|
||||
trackedTrialExposureCompaniesRef.current.add(createdCompanyId);
|
||||
void cloudInferenceApi
|
||||
@@ -966,48 +998,70 @@ function OnboardingWizardInner({
|
||||
.catch(() => {
|
||||
// Best-effort analytics must never interrupt onboarding.
|
||||
});
|
||||
}, [effectiveOnboardingOpen, step, createdCompanyId]);
|
||||
}, [effectiveOnboardingOpen, step, createdCompanyId, isFreeInferenceOnboarding]);
|
||||
|
||||
async function handleStartWithCloudTrial() {
|
||||
async function handleStartWithCloudTrial(options?: { launchToChat?: boolean }) {
|
||||
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) });
|
||||
let agentId = createdAgentId;
|
||||
if (!agentId) {
|
||||
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) });
|
||||
agentId = hire.agent.id;
|
||||
setCreatedAgentId(agentId);
|
||||
}
|
||||
if (options?.launchToChat) {
|
||||
await prepareChat(createdCompanyId, agentId).issue;
|
||||
captureOnboardingStepCompleted("launch", "succeeded");
|
||||
if (!stillTheSameCompany(createdCompanyId)) return;
|
||||
onboardingAnalytics.finished();
|
||||
const prefix = createdCompanyPrefix;
|
||||
setSelectedCompanyId(createdCompanyId, { source: "route_sync" });
|
||||
reset();
|
||||
closeOnboarding();
|
||||
navigate(`${prefix ? `/${prefix}` : ""}/chats/${agentId}`, {
|
||||
state: { onboardingWelcome: true },
|
||||
});
|
||||
} else {
|
||||
setStep(5);
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(createdCompanyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.cloudInference.status(createdCompanyId) });
|
||||
setCreatedAgentId(hire.agent.id);
|
||||
setStep(5);
|
||||
} catch (err) {
|
||||
if (options?.launchToChat) {
|
||||
captureOnboardingStepCompleted("launch", "failed");
|
||||
captureOnboardingStepFailed({ step: "launch", reason: "launch_failed" });
|
||||
}
|
||||
setError(err instanceof Error ? err.message : "Could not start right away");
|
||||
} finally {
|
||||
setStartingCloudTrial(false);
|
||||
@@ -2949,7 +3003,13 @@ function OnboardingWizardInner({
|
||||
// yet — two organizations for one name, two agents for one hire.
|
||||
if (loading) return;
|
||||
if (step === 1 && companyName.trim()) void handleCreateCompany();
|
||||
else if (step === 3 && agentName.trim()) setStep(4);
|
||||
else if (step === 3 && agentName.trim()) {
|
||||
if (isFreeInferenceOnboarding) {
|
||||
void handleStartWithCloudTrial({ launchToChat: true });
|
||||
} else {
|
||||
setStep(4);
|
||||
}
|
||||
}
|
||||
// `connectStepReady`, the same predicate the step's button uses. Spelling
|
||||
// the condition out here again is what let this path hire against a
|
||||
// source the tile row had never shown, after the button was gated and
|
||||
@@ -3095,26 +3155,32 @@ function OnboardingWizardInner({
|
||||
count would visibly skip from 1 to 3. */}
|
||||
{!showsAgentArcStepper && (
|
||||
<Stepper
|
||||
step={onboardingStepPositionFor(step)}
|
||||
total={ONBOARDING_WIZARD_STEPS.length}
|
||||
labels={ONBOARDING_STEP_LABELS}
|
||||
canJumpToStep={(target) =>
|
||||
canJumpToOnboardingStep({
|
||||
targetStep: ONBOARDING_WIZARD_STEPS[target - 1]!,
|
||||
step={isFreeInferenceOnboarding ? (step === 1 ? 1 : 2) : onboardingStepPositionFor(step)}
|
||||
total={isFreeInferenceOnboarding ? 2 : ONBOARDING_WIZARD_STEPS.length}
|
||||
labels={
|
||||
isFreeInferenceOnboarding
|
||||
? (["Name your organization", "Create your first agent"] as const)
|
||||
: ONBOARDING_STEP_LABELS
|
||||
}
|
||||
canJumpToStep={(target) => {
|
||||
const targetSteps = isFreeInferenceOnboarding ? [1, 3] : ONBOARDING_WIZARD_STEPS;
|
||||
return canJumpToOnboardingStep({
|
||||
targetStep: targetSteps[target - 1]!,
|
||||
currentStep: step,
|
||||
entryStep,
|
||||
})
|
||||
}
|
||||
onJumpToStep={(target) =>
|
||||
setStep(ONBOARDING_WIZARD_STEPS[target - 1]! as Step)
|
||||
}
|
||||
});
|
||||
}}
|
||||
onJumpToStep={(target) => {
|
||||
const targetSteps = isFreeInferenceOnboarding ? [1, 3] : ONBOARDING_WIZARD_STEPS;
|
||||
setStep(targetSteps[target - 1]! as Step);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* The agent arc's progress strip. Numbered 1–3 over the wizard's
|
||||
steps 3–5, because company creation already happened in Cloud
|
||||
and the mission step is skipped when it did. */}
|
||||
{showsAgentArcStepper && (
|
||||
{showsAgentArcStepper && !isFreeInferenceOnboarding && (
|
||||
<Stepper
|
||||
step={agentArcStepFor(step)!}
|
||||
canJumpToStep={(target) =>
|
||||
@@ -3291,7 +3357,11 @@ function OnboardingWizardInner({
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.nativeEvent.isComposing && agentName.trim()) {
|
||||
e.preventDefault();
|
||||
setStep(4);
|
||||
if (isFreeInferenceOnboarding) {
|
||||
void handleStartWithCloudTrial({ launchToChat: true });
|
||||
} else {
|
||||
setStep(4);
|
||||
}
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
@@ -3322,7 +3392,7 @@ function OnboardingWizardInner({
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleStartWithCloudTrial}
|
||||
onClick={() => void handleStartWithCloudTrial()}
|
||||
disabled={startingCloudTrial || loading}
|
||||
className="shrink-0"
|
||||
>
|
||||
@@ -3869,15 +3939,19 @@ function OnboardingWizardInner({
|
||||
? "Get started"
|
||||
: step === 4
|
||||
? connectCta.label
|
||||
: "Next"
|
||||
: isFreeInferenceOnboarding
|
||||
? "Start chatting"
|
||||
: "Next"
|
||||
}
|
||||
primaryIcon={step === 4 ? connectCta.icon : undefined}
|
||||
loadingLabel={
|
||||
step === 1
|
||||
? "Creating..."
|
||||
: step === 4
|
||||
? "Connecting"
|
||||
: "Launching..."
|
||||
: step === 3 && isFreeInferenceOnboarding
|
||||
? "Starting..."
|
||||
: step === 4
|
||||
? "Connecting"
|
||||
: "Launching..."
|
||||
}
|
||||
// The browser-code login is finished on this screen, so the
|
||||
// button is genuinely busy for its duration and shows it. The
|
||||
@@ -3886,19 +3960,25 @@ function OnboardingWizardInner({
|
||||
// against work happening in another tab.
|
||||
// Step 4 says what it is doing through `connectCta` instead:
|
||||
// it has four faces and only two of them are the step working.
|
||||
loading={step === 3 || step === 4 ? false : loading}
|
||||
loading={step === 4 ? false : step === 3 ? (isFreeInferenceOnboarding && startingCloudTrial) : loading}
|
||||
primaryDisabled={
|
||||
step === 1
|
||||
? !companyName.trim() || loading
|
||||
: step === 3
|
||||
? !agentName.trim()
|
||||
? !agentName.trim() || (isFreeInferenceOnboarding && (startingCloudTrial || loading))
|
||||
: step === 4
|
||||
? connectCta.disabled || loading
|
||||
: loading || launchStateIncomplete
|
||||
}
|
||||
onPrimary={() => {
|
||||
if (step === 1) void handleCreateCompany();
|
||||
else if (step === 3) setStep(4);
|
||||
else if (step === 3) {
|
||||
if (isFreeInferenceOnboarding) {
|
||||
void handleStartWithCloudTrial({ launchToChat: true });
|
||||
} else {
|
||||
setStep(4);
|
||||
}
|
||||
}
|
||||
// One button, two jobs — start the sign-in, or hire — and
|
||||
// Cmd+Enter has to do the same thing. See
|
||||
// `handleConnectStepPrimary`.
|
||||
|
||||
@@ -6,6 +6,9 @@ import { authApi } from "@/api/auth";
|
||||
import { describeError } from "@/api/errors";
|
||||
import { TaskChatComposer } from "@/components/task-chat/TaskChatComposer";
|
||||
import type { ComposerRunSettings } from "@/components/task-chat/composer-run-settings";
|
||||
import { CloudTrialBlockedBanner } from "@/components/CloudTrialBlockedBanner";
|
||||
import { useCloudTrialStatus } from "@/hooks/useCloudTrialStatus";
|
||||
import { requestCloudTrialConnectModal } from "@/lib/cloud-trial-gate";
|
||||
import { useStartAgentChat } from "@/hooks/useAgentChatNavigation";
|
||||
import { agentIdFromChatValue, chatAgentOptions, defaultChatAgent } from "@/lib/dashboard-chat";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
@@ -50,6 +53,7 @@ export function DashboardChatComposer({
|
||||
loaded: boolean;
|
||||
}) {
|
||||
const session = useQuery({ queryKey: queryKeys.auth.session, queryFn: () => authApi.getSession() });
|
||||
const cloudTrial = useCloudTrialStatus(companyId);
|
||||
const userId = session.data?.user?.id ?? session.data?.session?.userId ?? null;
|
||||
const startChat = useStartAgentChat(companyId, userId);
|
||||
const mobile = useNarrowViewport();
|
||||
@@ -104,10 +108,21 @@ export function DashboardChatComposer({
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-(--tc-shell-max-w)" data-dashboard-chat="">
|
||||
{cloudTrial.llmBlocked ? (
|
||||
<CloudTrialBlockedBanner
|
||||
gateReason={cloudTrial.gateReason}
|
||||
heldIssues={cloudTrial.heldIssues}
|
||||
canMigrate={cloudTrial.status?.canMigrate !== false}
|
||||
onConnect={requestCloudTrialConnectModal}
|
||||
className="mb-2"
|
||||
/>
|
||||
) : null}
|
||||
<TaskChatComposer
|
||||
workMode="standard"
|
||||
mobile={mobile}
|
||||
companyId={companyId}
|
||||
disabled={cloudTrial.llmBlocked}
|
||||
disabledReason={cloudTrial.llmBlocked ? "Connect a model provider to start a chat." : undefined}
|
||||
enableReassign
|
||||
reassignOptions={options}
|
||||
modelAgents={modelAgents}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { cloudInferenceApi } from "@/api/cloud-inference";
|
||||
import { instanceSettingsApi } from "@/api/instanceSettings";
|
||||
import { useCloudInstance } from "@/hooks/useCloudInstance";
|
||||
import {
|
||||
getCloudTrialGateReason,
|
||||
getCloudTrialHeldIssueIds,
|
||||
getCloudTrialHeldIssues,
|
||||
getCloudTrialOnboardingVariant,
|
||||
hasActiveCloudTrialAgents,
|
||||
isCloudTrialLlmBlocked,
|
||||
type CloudTrialInferenceStatusCompat,
|
||||
} from "@/lib/cloud-trial-gate";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
|
||||
/**
|
||||
* Reads the company's Cloud starter-inference status when running on Paperclip
|
||||
* Cloud or when the experimental Cloud trial flag is enabled.
|
||||
*/
|
||||
export function useCloudTrialStatus(companyId: string | null | undefined) {
|
||||
const cloudInstance = useCloudInstance();
|
||||
const experimental = useQuery({
|
||||
queryKey: queryKeys.instance.experimentalSettings,
|
||||
queryFn: instanceSettingsApi.getExperimental,
|
||||
enabled: Boolean(companyId),
|
||||
});
|
||||
|
||||
const shouldQuery =
|
||||
Boolean(companyId) &&
|
||||
(experimental.data?.enableCloudTrialInference === true || Boolean(cloudInstance));
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: queryKeys.cloudInference.status(companyId ?? "__none__"),
|
||||
queryFn: () => cloudInferenceApi.getStatus(companyId!),
|
||||
enabled: shouldQuery,
|
||||
staleTime: 15_000,
|
||||
});
|
||||
|
||||
const status = statusQuery.data as CloudTrialInferenceStatusCompat | undefined;
|
||||
|
||||
return {
|
||||
...statusQuery,
|
||||
status,
|
||||
shouldQuery,
|
||||
onboardingVariant: getCloudTrialOnboardingVariant(status),
|
||||
gateReason: getCloudTrialGateReason(status),
|
||||
heldIssueIds: getCloudTrialHeldIssueIds(status),
|
||||
heldIssues: getCloudTrialHeldIssues(status),
|
||||
llmBlocked: isCloudTrialLlmBlocked(status),
|
||||
hasActiveTrialAgents: hasActiveCloudTrialAgents(status),
|
||||
};
|
||||
}
|
||||
@@ -218,4 +218,33 @@ describe("product analytics", () => {
|
||||
{ cloud_trial_inference_cohort: "treatment" },
|
||||
);
|
||||
});
|
||||
|
||||
it("registers multi-variant onboarding-flow super properties and initial_onboarding_variant on identify", async () => {
|
||||
const variantConfig = {
|
||||
...config,
|
||||
cloudTrialInferenceEnabled: true,
|
||||
onboardingVariant: "free_inference_1",
|
||||
} as BrowserAnalyticsConfig;
|
||||
setProductAnalyticsUser({ id: "user-10", email: "sam@example.com", name: "Sam" });
|
||||
startProductAnalytics(variantConfig, { load, schedule });
|
||||
scheduled!();
|
||||
await flush();
|
||||
|
||||
expect(client.register).toHaveBeenCalledWith({
|
||||
deployment_source: "cloud",
|
||||
environment: "staging",
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
onboarding_variant: "free_inference_1",
|
||||
"$feature/onboarding-flow": "free_inference_1",
|
||||
});
|
||||
expect(client.identify).toHaveBeenCalledWith(
|
||||
"user-10",
|
||||
{ email: "sam@example.com", name: "Sam" },
|
||||
{
|
||||
cloud_trial_inference_cohort: "treatment",
|
||||
initial_onboarding_variant: "free_inference_1",
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -205,7 +205,17 @@ export function buildPostHogInitOptions(
|
||||
};
|
||||
}
|
||||
|
||||
function superProperties(config: BrowserAnalyticsConfig) {
|
||||
type BrowserAnalyticsConfigCompat = BrowserAnalyticsConfig & {
|
||||
onboardingVariant?: string;
|
||||
};
|
||||
|
||||
function resolvedOnboardingVariant(config: BrowserAnalyticsConfigCompat): string | undefined {
|
||||
const raw = config.onboardingVariant?.trim();
|
||||
return raw || undefined;
|
||||
}
|
||||
|
||||
function superProperties(config: BrowserAnalyticsConfigCompat) {
|
||||
const onboardingVariant = resolvedOnboardingVariant(config);
|
||||
return {
|
||||
deployment_source: "cloud",
|
||||
environment: config.environment,
|
||||
@@ -215,6 +225,12 @@ function superProperties(config: BrowserAnalyticsConfig) {
|
||||
"$feature/cloud-trial-inference": config.cloudTrialInferenceEnabled ? "treatment" : "control",
|
||||
}
|
||||
: {}),
|
||||
...(onboardingVariant
|
||||
? {
|
||||
onboarding_variant: onboardingVariant,
|
||||
"$feature/onboarding-flow": onboardingVariant,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -248,17 +264,23 @@ function createAnalyticsState(config: BrowserAnalyticsConfig): State {
|
||||
};
|
||||
}
|
||||
|
||||
function applyIdentity(client: ProductAnalyticsClient, config: BrowserAnalyticsConfig) {
|
||||
function applyIdentity(client: ProductAnalyticsClient, config: BrowserAnalyticsConfigCompat) {
|
||||
const user = wantedUser;
|
||||
if (user) {
|
||||
if (identifiedUserId === user.id) return;
|
||||
const personProperties: Record<string, string> = {};
|
||||
if (user.email) personProperties.email = user.email;
|
||||
if (user.name) personProperties.name = user.name;
|
||||
const personPropertiesSetOnce: Record<string, string> = {};
|
||||
if (typeof config.cloudTrialInferenceEnabled === "boolean") {
|
||||
client.identify(user.id, personProperties, {
|
||||
cloud_trial_inference_cohort: config.cloudTrialInferenceEnabled ? "treatment" : "control",
|
||||
});
|
||||
personPropertiesSetOnce.cloud_trial_inference_cohort = config.cloudTrialInferenceEnabled ? "treatment" : "control";
|
||||
}
|
||||
const onboardingVariant = resolvedOnboardingVariant(config);
|
||||
if (onboardingVariant) {
|
||||
personPropertiesSetOnce.initial_onboarding_variant = onboardingVariant;
|
||||
}
|
||||
if (Object.keys(personPropertiesSetOnce).length > 0) {
|
||||
client.identify(user.id, personProperties, personPropertiesSetOnce);
|
||||
} else {
|
||||
client.identify(user.id, personProperties);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { CloudTrialInferenceStatus } from "@paperclipai/shared";
|
||||
|
||||
export type CloudTrialGateReason = "exhausted" | "work_requires_model";
|
||||
|
||||
export interface CloudTrialHeldIssueSummaryCompat {
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
title: string;
|
||||
assigneeAgentId: string | null;
|
||||
heldAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extended view of CloudTrialInferenceStatus that safely reads the multi-variant
|
||||
* and dual-trigger gate fields (`onboardingVariant`, `gateReason`, `heldIssueIds`,
|
||||
* `heldIssues`, `llmBlocked`) whether or not older fixtures populate them.
|
||||
*/
|
||||
export type CloudTrialInferenceStatusCompat = CloudTrialInferenceStatus & {
|
||||
onboardingVariant?: string;
|
||||
gateReason?: CloudTrialGateReason | null;
|
||||
heldIssueIds?: string[];
|
||||
heldIssues?: CloudTrialHeldIssueSummaryCompat[];
|
||||
llmBlocked?: boolean;
|
||||
};
|
||||
|
||||
export const FREE_INFERENCE_ONBOARDING_VARIANT = "free_inference_1" as const;
|
||||
|
||||
export function getCloudTrialOnboardingVariant(
|
||||
status?: CloudTrialInferenceStatusCompat | null,
|
||||
): string {
|
||||
const raw = status?.onboardingVariant?.trim();
|
||||
return raw || "baseline";
|
||||
}
|
||||
|
||||
export function isFreeInferenceOnboardingVariant(
|
||||
status?: CloudTrialInferenceStatusCompat | null,
|
||||
): boolean {
|
||||
return getCloudTrialOnboardingVariant(status) === FREE_INFERENCE_ONBOARDING_VARIANT;
|
||||
}
|
||||
|
||||
export function getCloudTrialGateReason(
|
||||
status?: CloudTrialInferenceStatusCompat | null,
|
||||
): CloudTrialGateReason | null {
|
||||
if (!status) return null;
|
||||
if (status.gateReason === "exhausted" || status.gateReason === "work_requires_model") {
|
||||
return status.gateReason;
|
||||
}
|
||||
if (status.status === "exhausted") {
|
||||
return "exhausted";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getCloudTrialHeldIssueIds(
|
||||
status?: CloudTrialInferenceStatusCompat | null,
|
||||
): string[] {
|
||||
return Array.isArray(status?.heldIssueIds) ? status.heldIssueIds : [];
|
||||
}
|
||||
|
||||
export function getCloudTrialHeldIssues(
|
||||
status?: CloudTrialInferenceStatusCompat | null,
|
||||
): CloudTrialHeldIssueSummaryCompat[] {
|
||||
return Array.isArray(status?.heldIssues) ? status.heldIssues : [];
|
||||
}
|
||||
|
||||
export function isCloudTrialLlmBlocked(
|
||||
status?: CloudTrialInferenceStatusCompat | null,
|
||||
): boolean {
|
||||
if (!status) return false;
|
||||
if (status.llmBlocked === true) return true;
|
||||
return getCloudTrialGateReason(status) !== null && status.trialAgentIds.length > 0;
|
||||
}
|
||||
|
||||
export function hasActiveCloudTrialAgents(
|
||||
status?: CloudTrialInferenceStatusCompat | null,
|
||||
): boolean {
|
||||
if (!status) return false;
|
||||
return (
|
||||
status.enabled &&
|
||||
status.trialAgentIds.length > 0 &&
|
||||
status.status !== "migrated" &&
|
||||
status.status !== "disabled" &&
|
||||
status.status !== "unavailable" &&
|
||||
status.status !== "ineligible"
|
||||
);
|
||||
}
|
||||
|
||||
type ConnectModalListener = () => void;
|
||||
const connectModalListeners = new Set<ConnectModalListener>();
|
||||
|
||||
/**
|
||||
* Requests that the global CloudTrialGate open (or re-open after dismissal)
|
||||
* the connect-a-model modal.
|
||||
*/
|
||||
export function requestCloudTrialConnectModal(): void {
|
||||
for (const listener of connectModalListeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribeCloudTrialConnectModal(listener: ConnectModalListener): () => void {
|
||||
connectModalListeners.add(listener);
|
||||
return () => {
|
||||
connectModalListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
@@ -42,6 +42,9 @@ import { EmailThreadProvider } from "../components/EmailMessageCard";
|
||||
import { TaskTranscriptAgents } from "../components/task-chat/TaskChatBubble";
|
||||
import { EmailTaskActivity } from "../components/EmailTaskActivity";
|
||||
import { TaskChatScrollNavigation, taskChatScrollEntry } from "@/components/task-chat/scroll-navigation";
|
||||
import { CloudTrialBlockedBanner } from "@/components/CloudTrialBlockedBanner";
|
||||
import { useCloudTrialStatus } from "@/hooks/useCloudTrialStatus";
|
||||
import { requestCloudTrialConnectModal } from "@/lib/cloud-trial-gate";
|
||||
import {
|
||||
lazy,
|
||||
memo,
|
||||
@@ -3934,6 +3937,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
queryFn: () => instanceSettingsApi.getExperimental(),
|
||||
enabled: !!issueId,
|
||||
});
|
||||
const cloudTrial = useCloudTrialStatus(issue?.companyId ?? selectedCompanyId);
|
||||
// Experimental Cases: linkify `PAP-C7` chips in this issue's comment bodies.
|
||||
const casesChipsEnabled = instanceExperimentalSettings?.enableCases === true;
|
||||
const feedbackDataSharingPreference =
|
||||
@@ -8898,16 +8902,27 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
onRefreshLatestComments={refetchLatestComments}
|
||||
composerRef={commentComposerRef}
|
||||
composerAccessory={
|
||||
hasVisibleMonitorSurface(issue) ? (
|
||||
<IssueMonitorComposerStrip
|
||||
issue={issue}
|
||||
hasActiveRun={hasLiveRuns}
|
||||
workProducts={workProducts}
|
||||
checkError={checkIssueMonitorNow.error ? describeError(checkIssueMonitorNow.error, { action: "check the monitor" }).body : null}
|
||||
onCheckNow={() => checkIssueMonitorNow.mutate()}
|
||||
checkingNow={checkIssueMonitorNow.isPending}
|
||||
/>
|
||||
) : null
|
||||
<>
|
||||
{cloudTrial.llmBlocked ? (
|
||||
<CloudTrialBlockedBanner
|
||||
gateReason={cloudTrial.gateReason}
|
||||
heldIssues={cloudTrial.heldIssues}
|
||||
canMigrate={cloudTrial.status?.canMigrate !== false}
|
||||
onConnect={requestCloudTrialConnectModal}
|
||||
className="mb-2"
|
||||
/>
|
||||
) : null}
|
||||
{hasVisibleMonitorSurface(issue) ? (
|
||||
<IssueMonitorComposerStrip
|
||||
issue={issue}
|
||||
hasActiveRun={hasLiveRuns}
|
||||
workProducts={workProducts}
|
||||
checkError={checkIssueMonitorNow.error ? describeError(checkIssueMonitorNow.error, { action: "check the monitor" }).body : null}
|
||||
onCheckNow={() => checkIssueMonitorNow.mutate()}
|
||||
checkingNow={checkIssueMonitorNow.isPending}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
footer={
|
||||
!taskChatShellEnabled && siblingNavigation ? (
|
||||
@@ -8941,7 +8956,15 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
} : undefined,
|
||||
resumeHref: !activePauseHold.isRoot ? createIssueDetailPath(activePauseHoldRoot?.identifier ?? activePauseHold.rootIssueId) : undefined,
|
||||
} : null}
|
||||
composerDisabledReason={issue.conversationAgentId && !instanceExperimentalSettings?.enableAgentChat ? "Agent Chat is disabled in Experimental settings." : treeControlStateError ? "Couldn’t check whether this task is paused. Refresh to try again." : null}
|
||||
composerDisabledReason={
|
||||
issue.conversationAgentId && !instanceExperimentalSettings?.enableAgentChat
|
||||
? "Agent Chat is disabled in Experimental settings."
|
||||
: cloudTrial.llmBlocked
|
||||
? "Connect a model provider to send messages."
|
||||
: treeControlStateError
|
||||
? "Couldn’t check whether this task is paused. Refresh to try again."
|
||||
: null
|
||||
}
|
||||
composerHint={composerHint}
|
||||
queuedCommentReason={queuedCommentReason}
|
||||
onVote={handleCommentVote}
|
||||
|
||||
@@ -8,9 +8,14 @@ const COMPANY_ID = "company-storybook";
|
||||
|
||||
const singleAgentExhaustedStatus: CloudTrialInferenceStatus = {
|
||||
enabled: true,
|
||||
onboardingVariant: "free_inference_1",
|
||||
provider: "openrouter",
|
||||
status: "exhausted",
|
||||
reason: "openrouter_http_402",
|
||||
gateReason: "exhausted",
|
||||
llmBlocked: true,
|
||||
heldIssueIds: [],
|
||||
heldIssues: [],
|
||||
limitUsdCents: 100,
|
||||
spentUsdCents: 100,
|
||||
remainingUsdCents: 0,
|
||||
@@ -198,7 +203,7 @@ export const ExhaustedSingleAgent: Story = {
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Connect a model provider to continue" }),
|
||||
screen.getByRole("heading", { name: "Connect a model to keep going" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText("Nova")).toBeInTheDocument();
|
||||
@@ -264,6 +269,7 @@ export const MigrationSucceeded: Story = {
|
||||
],
|
||||
resumedRunIds: ["99999999-9999-4999-8999-999999999999"],
|
||||
resumedIssueId: "33333333-3333-4333-8333-333333333333",
|
||||
resumedIssueIds: ["33333333-3333-4333-8333-333333333333"],
|
||||
},
|
||||
},
|
||||
play: async () => {
|
||||
|
||||
@@ -0,0 +1,610 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, screen, userEvent, waitFor } from "storybook/test";
|
||||
import { Bot, Clock, Plus } from "lucide-react";
|
||||
import type { TaskChatItem } from "@/components/task-chat/task-chat-model";
|
||||
import { OnboardingWizard } from "@/components/OnboardingWizard";
|
||||
import { CloudTrialBlockedBanner } from "@/components/CloudTrialBlockedBanner";
|
||||
import { CloudTrialExhaustedModal } from "@/components/CloudTrialExhaustedModal";
|
||||
import { TaskChatComposer } from "@/components/task-chat/TaskChatComposer";
|
||||
import { TaskChatComposerDock } from "@/components/task-chat/TaskChatComposerDock";
|
||||
import { TaskChatThreadView } from "@/components/task-chat/TaskChatThreadView";
|
||||
import { TaskChatPresentationProvider } from "@/components/task-chat/presentation-mode";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useCompanyListQuery } from "@/api/companies-query";
|
||||
import { useDialog } from "@/context/DialogContext";
|
||||
import type { CloudTrialInferenceStatusCompat } from "@/lib/cloud-trial-gate";
|
||||
import { prepareFixtureApi } from "../../support/capability-gaps/api";
|
||||
import {
|
||||
ONBOARDING_ARC_ENTRY_STEP,
|
||||
STORYBOOK_COMPANY_ID,
|
||||
clearOnboardingDraft,
|
||||
seedOnboardingDraft,
|
||||
} from "../../fixtures/onboardingDraft";
|
||||
|
||||
const COMPANY_ID = STORYBOOK_COMPANY_ID;
|
||||
const AGENT_ID = "11111111-1111-4111-8111-111111111111";
|
||||
|
||||
const activeFreeInferenceStatus: CloudTrialInferenceStatusCompat = {
|
||||
enabled: true,
|
||||
onboardingVariant: "free_inference_1",
|
||||
provider: "openrouter",
|
||||
status: "active",
|
||||
gateReason: null,
|
||||
llmBlocked: false,
|
||||
heldIssueIds: [],
|
||||
heldIssues: [],
|
||||
limitUsdCents: 100,
|
||||
spentUsdCents: 8,
|
||||
remainingUsdCents: 92,
|
||||
defaultModel: "openrouter/openai/gpt-6-luna",
|
||||
canMigrate: true,
|
||||
trialAgentIds: [AGENT_ID],
|
||||
trialAgents: [
|
||||
{
|
||||
id: AGENT_ID,
|
||||
name: "Nova",
|
||||
role: "ceo",
|
||||
title: "Chief of Staff",
|
||||
},
|
||||
],
|
||||
blockedRun: null,
|
||||
};
|
||||
|
||||
const agentHeldSubtaskStatus: CloudTrialInferenceStatusCompat = {
|
||||
...activeFreeInferenceStatus,
|
||||
gateReason: "work_requires_model",
|
||||
llmBlocked: true,
|
||||
heldIssueIds: ["issue-held-1"],
|
||||
heldIssues: [
|
||||
{
|
||||
id: "issue-held-1",
|
||||
identifier: "PAP-12",
|
||||
title: "Draft Q3 launch memo",
|
||||
assigneeAgentId: AGENT_ID,
|
||||
heldAt: "2026-12-01T12:00:00Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const manualTaskHeldStatus: CloudTrialInferenceStatusCompat = {
|
||||
...activeFreeInferenceStatus,
|
||||
gateReason: "work_requires_model",
|
||||
llmBlocked: true,
|
||||
heldIssueIds: ["issue-held-2"],
|
||||
heldIssues: [
|
||||
{
|
||||
id: "issue-held-2",
|
||||
identifier: "PAP-13",
|
||||
title: "Audit competitor pricing page",
|
||||
assigneeAgentId: AGENT_ID,
|
||||
heldAt: "2026-12-01T12:05:00Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const quotaExhaustedStatus: CloudTrialInferenceStatusCompat = {
|
||||
...activeFreeInferenceStatus,
|
||||
status: "exhausted",
|
||||
reason: "openrouter_http_402",
|
||||
gateReason: "exhausted",
|
||||
llmBlocked: true,
|
||||
spentUsdCents: 100,
|
||||
remainingUsdCents: 0,
|
||||
blockedRun: {
|
||||
runId: "22222222-2222-4222-8222-222222222222",
|
||||
agentId: AGENT_ID,
|
||||
issueId: "33333333-3333-4333-8333-333333333333",
|
||||
failedAt: "2026-12-01T12:15:00Z",
|
||||
},
|
||||
};
|
||||
|
||||
function installFreeInferenceFixtures(status: CloudTrialInferenceStatusCompat) {
|
||||
return prepareFixtureApi([
|
||||
{
|
||||
path: "/api/auth/get-session",
|
||||
read: () => ({
|
||||
session: { id: "sess-sb", userId: "user-storybook" },
|
||||
user: { id: "user-storybook", email: "founder@example.com", name: "Founder" },
|
||||
onboardingVariant: "free_inference_1",
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/cloud-inference/status`,
|
||||
read: () => status,
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/cloud-inference/telemetry`,
|
||||
method: "POST",
|
||||
read: () => new Response(null, { status: 204 }),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/cloud-inference/migrate`,
|
||||
method: "POST",
|
||||
read: () => ({
|
||||
migratedCount: 1,
|
||||
agents: [
|
||||
{
|
||||
agentId: AGENT_ID,
|
||||
name: "Nova",
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "claude",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
],
|
||||
resumedRunIds: ["99999999-9999-4999-8999-999999999999"],
|
||||
resumedIssueId: status.heldIssueIds?.[0] ?? "issue-held-1",
|
||||
resumedIssueIds: status.heldIssueIds ?? ["issue-held-1"],
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/ai-connections`,
|
||||
read: () => ({
|
||||
canManageConnections: true,
|
||||
accounts: [],
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/ai-connections`,
|
||||
method: "POST",
|
||||
read: () => ({
|
||||
connectionId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
grantId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/agents`,
|
||||
read: () => [
|
||||
{
|
||||
id: AGENT_ID,
|
||||
companyId: COMPANY_ID,
|
||||
name: "Nova",
|
||||
role: "ceo",
|
||||
title: "Chief of Staff",
|
||||
status: "idle",
|
||||
adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "opencode", model: "openrouter/openai/gpt-6-luna" },
|
||||
runtimeConfig: { cloudTrialInference: true },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/agent-hires`,
|
||||
method: "POST",
|
||||
read: () => ({
|
||||
agent: {
|
||||
id: AGENT_ID,
|
||||
companyId: COMPANY_ID,
|
||||
name: "Nova",
|
||||
role: "general",
|
||||
title: null,
|
||||
status: "idle",
|
||||
adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "opencode", model: "openrouter/openai/gpt-6-luna" },
|
||||
runtimeConfig: { cloudTrialInference: true },
|
||||
},
|
||||
approval: null,
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/agent-chats/${AGENT_ID}`,
|
||||
method: "POST",
|
||||
read: () => ({
|
||||
id: "chat-issue-1",
|
||||
companyId: COMPANY_ID,
|
||||
identifier: "PAP-1",
|
||||
title: "Chat with Nova",
|
||||
originKind: "onboarding_chat",
|
||||
conversationAgentId: AGENT_ID,
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/environments`,
|
||||
read: () => [
|
||||
{
|
||||
id: "env-managed-1",
|
||||
companyId: COMPANY_ID,
|
||||
name: "Paperclip Computer",
|
||||
driver: "local",
|
||||
status: "active",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/environments/capabilities`,
|
||||
read: () => ({ drivers: {} }),
|
||||
},
|
||||
{
|
||||
path: "/api/instance/settings",
|
||||
read: () => ({
|
||||
id: "inst-1",
|
||||
defaultEnvironmentId: "env-managed-1",
|
||||
general: { executionMode: "any" },
|
||||
experimental: { enableCloudTrialInference: true, enableManagedSandboxOnly: false },
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: "/api/instance/settings/experimental",
|
||||
read: () => ({
|
||||
enableCloudTrialInference: true,
|
||||
enableManagedSandboxOnly: false,
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: "/api/instance/settings/general",
|
||||
read: () => ({
|
||||
executionMode: "any",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function FreeInferenceWizardHarness() {
|
||||
const [seeded] = useState(() => {
|
||||
seedOnboardingDraft();
|
||||
return true;
|
||||
});
|
||||
|
||||
useEffect(() => clearOnboardingDraft, []);
|
||||
|
||||
const companies = useCompanyListQuery();
|
||||
const ready = companies.isSuccess && companies.data !== undefined;
|
||||
const { openOnboarding } = useDialog();
|
||||
|
||||
useEffect(() => {
|
||||
if (!seeded || !ready) return;
|
||||
openOnboarding({
|
||||
initialStep: ONBOARDING_ARC_ENTRY_STEP,
|
||||
companyId: COMPANY_ID,
|
||||
});
|
||||
}, [seeded, ready, openOnboarding]);
|
||||
|
||||
if (!ready) return null;
|
||||
return <OnboardingWizard />;
|
||||
}
|
||||
|
||||
const firstChatItems: TaskChatItem[] = [
|
||||
{
|
||||
id: "welcome-1",
|
||||
kind: "message",
|
||||
author: "agent",
|
||||
authorName: "Nova",
|
||||
timestamp: "Just now",
|
||||
text: "Hi! I’m Nova, your Chief of Staff. What would you like to tackle first? We can brainstorm strategy, outline a launch plan, or break work down into tasks.",
|
||||
},
|
||||
{
|
||||
id: "human-1",
|
||||
kind: "message",
|
||||
author: "human",
|
||||
authorName: "Founder",
|
||||
isCurrentUser: true,
|
||||
timestamp: "Just now",
|
||||
text: "Let’s plan our Q3 launch memo — can you spin up a task to draft it?",
|
||||
},
|
||||
{
|
||||
id: "agent-2",
|
||||
kind: "message",
|
||||
author: "agent",
|
||||
authorName: "Nova",
|
||||
timestamp: "Just now",
|
||||
text: "I’ve created **PAP-12 · Draft Q3 launch memo** and queued it up for execution.",
|
||||
},
|
||||
];
|
||||
|
||||
function FirstChatShell({
|
||||
status,
|
||||
initialModalOpen = false,
|
||||
initialModalPhase = "connect",
|
||||
showHeldSubtaskCard = false,
|
||||
showManualTaskTrigger = false,
|
||||
}: {
|
||||
status: CloudTrialInferenceStatusCompat;
|
||||
initialModalOpen?: boolean;
|
||||
initialModalPhase?: "connect" | "migrating" | "done" | "error";
|
||||
showHeldSubtaskCard?: boolean;
|
||||
showManualTaskTrigger?: boolean;
|
||||
}) {
|
||||
const [modalOpen, setModalOpen] = useState(initialModalOpen);
|
||||
const [activeStatus, setActiveStatus] = useState<CloudTrialInferenceStatusCompat>(status);
|
||||
const isBlocked = Boolean(activeStatus.llmBlocked);
|
||||
|
||||
return (
|
||||
<TaskChatPresentationProvider mode="streamlined">
|
||||
<div className="mx-auto flex min-h-(--sz-520px) w-full max-w-3xl flex-col justify-between rounded-2xl border border-border bg-background shadow-sm">
|
||||
<div className="flex items-center justify-between border-b border-border px-5 py-3.5">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="flex size-8 items-center justify-center rounded-full border border-border bg-muted/50">
|
||||
<Bot className="size-4 text-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-foreground">Nova</p>
|
||||
<p className="text-xs text-muted-foreground">Chief of Staff · Starter inference</p>
|
||||
</div>
|
||||
</div>
|
||||
{showManualTaskTrigger && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setActiveStatus(manualTaskHeldStatus);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-1.5 size-3.5" />
|
||||
New task
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 px-5 py-4 space-y-4">
|
||||
<TaskChatThreadView
|
||||
scroll={false}
|
||||
items={showHeldSubtaskCard ? firstChatItems : firstChatItems.slice(0, 1)}
|
||||
/>
|
||||
|
||||
{showHeldSubtaskCard && activeStatus.heldIssues && activeStatus.heldIssues.length > 0 && (
|
||||
<div className="rounded-xl border border-border bg-card px-4 py-3 flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<Clock className="size-4 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{activeStatus.heldIssues[0]?.identifier}
|
||||
</span>
|
||||
<span className="truncate text-sm font-medium text-foreground">
|
||||
{activeStatus.heldIssues[0]?.title}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Held until a model provider is connected
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant="secondary" className="shrink-0">
|
||||
Waiting for model
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border px-5 py-4">
|
||||
<TaskChatComposerDock mobile={false} streamlined>
|
||||
{isBlocked && (
|
||||
<CloudTrialBlockedBanner
|
||||
gateReason={activeStatus.gateReason ?? "exhausted"}
|
||||
heldIssues={activeStatus.heldIssues}
|
||||
canMigrate={activeStatus.canMigrate}
|
||||
onConnect={() => setModalOpen(true)}
|
||||
className="mb-2"
|
||||
/>
|
||||
)}
|
||||
<TaskChatComposer
|
||||
workMode="standard"
|
||||
onAdd={async () => {}}
|
||||
disabled={isBlocked}
|
||||
disabledReason={isBlocked ? "Connect a model provider to send messages." : undefined}
|
||||
conversationMode
|
||||
/>
|
||||
</TaskChatComposerDock>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CloudTrialExhaustedModal
|
||||
open={modalOpen}
|
||||
companyId={COMPANY_ID}
|
||||
status={activeStatus}
|
||||
required={false}
|
||||
initialPhase={initialModalPhase}
|
||||
initialResult={
|
||||
initialModalPhase === "done"
|
||||
? {
|
||||
migratedCount: 1,
|
||||
agents: [
|
||||
{
|
||||
agentId: AGENT_ID,
|
||||
name: "Nova",
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "claude",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
],
|
||||
resumedRunIds: ["99999999-9999-4999-8999-999999999999"],
|
||||
resumedIssueId: "issue-held-1",
|
||||
resumedIssueIds: ["issue-held-1"],
|
||||
}
|
||||
: null
|
||||
}
|
||||
onOpenChange={setModalOpen}
|
||||
onMigrated={() => {
|
||||
setActiveStatus({
|
||||
...activeStatus,
|
||||
status: "migrated",
|
||||
gateReason: null,
|
||||
llmBlocked: false,
|
||||
heldIssueIds: [],
|
||||
heldIssues: [],
|
||||
trialAgentIds: [],
|
||||
trialAgents: [],
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</TaskChatPresentationProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const meta = {
|
||||
id: "onboarding-free-inference-flow",
|
||||
title:
|
||||
"Getting started and access/Onboarding and first work/Onboarding/Free inference onboarding flow",
|
||||
parameters: {
|
||||
layout: "padded",
|
||||
paperclip: {
|
||||
capabilities: ["onboarding/adapter", "onboarding/first-task"],
|
||||
status: "current",
|
||||
implementation: "production",
|
||||
boundary: "fixtures",
|
||||
notes:
|
||||
"Full end-to-end free_inference_1 onboarding flow: skipping Step 4 straight into first chat, dual-trigger connect-model modal (agent held subtask, manual task creation, $1 quota exhaustion), dismissible modal with LLM-blocked composer CTA, and post-connect auto-resume confirmation.",
|
||||
},
|
||||
},
|
||||
} satisfies Meta;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
/** 1. `free_inference_1` onboarding skips Step 4 ("Connect a model") completely. */
|
||||
export const Step1OnboardingSkipsConnectModel: Story = {
|
||||
beforeEach: () =>
|
||||
installFreeInferenceFixtures({
|
||||
...activeFreeInferenceStatus,
|
||||
status: "not_issued",
|
||||
}).cleanup,
|
||||
render: () => <FreeInferenceWizardHarness />,
|
||||
play: async () => {
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(screen.getByRole("heading", { name: "Create your first agent" })).toBeInTheDocument();
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
expect(screen.getByRole("button", { name: /Start chatting/i })).toBeEnabled();
|
||||
expect(screen.queryByRole("heading", { name: "Connect a model" })).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
/** 2. Active first chat on free inference right after onboarding. */
|
||||
export const Step2ActiveFirstChatOnFreeInference: Story = {
|
||||
beforeEach: () => installFreeInferenceFixtures(activeFreeInferenceStatus).cleanup,
|
||||
render: () => <FirstChatShell status={activeFreeInferenceStatus} />,
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Hi! I’m Nova, your Chief of Staff/i)).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.queryByTestId("cloud-trial-blocked-banner")).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
/** 3. Agent creates a held subtask → connect-model modal pops with `work_requires_model` copy. */
|
||||
export const Step3AgentCreatesHeldSubtaskModal: Story = {
|
||||
beforeEach: () => installFreeInferenceFixtures(agentHeldSubtaskStatus).cleanup,
|
||||
render: () => (
|
||||
<FirstChatShell
|
||||
status={agentHeldSubtaskStatus}
|
||||
initialModalOpen
|
||||
showHeldSubtaskCard
|
||||
/>
|
||||
),
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Connect a model to run tasks" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getAllByText("PAP-12").length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText("Draft Q3 launch memo").length).toBeGreaterThan(0);
|
||||
},
|
||||
};
|
||||
|
||||
/** 4. User creates a manual task/subtask → held task + connect-model modal pops. */
|
||||
export const Step4ManualTaskCreationTriggersModal: Story = {
|
||||
beforeEach: () => installFreeInferenceFixtures(manualTaskHeldStatus).cleanup,
|
||||
render: () => (
|
||||
<FirstChatShell
|
||||
status={manualTaskHeldStatus}
|
||||
initialModalOpen
|
||||
showHeldSubtaskCard
|
||||
showManualTaskTrigger
|
||||
/>
|
||||
),
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Connect a model to run tasks" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getAllByText("PAP-13").length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText("Audit competitor pricing page").length).toBeGreaterThan(0);
|
||||
},
|
||||
};
|
||||
|
||||
/** 5. User dismisses modal → chat composer & LLM actions blocked with "Connect a model" CTA. */
|
||||
export const Step5DismissedModalComposerBlocked: Story = {
|
||||
beforeEach: () => installFreeInferenceFixtures(agentHeldSubtaskStatus).cleanup,
|
||||
render: () => (
|
||||
<FirstChatShell
|
||||
status={agentHeldSubtaskStatus}
|
||||
initialModalOpen={false}
|
||||
showHeldSubtaskCard
|
||||
/>
|
||||
),
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("cloud-trial-blocked-banner")).toBeInTheDocument();
|
||||
});
|
||||
expect(
|
||||
screen.getByText("Connect a model to run tasks and keep chatting"),
|
||||
).toBeInTheDocument();
|
||||
const cta = screen.getByRole("button", { name: /Connect a model/i });
|
||||
expect(cta).toBeEnabled();
|
||||
await userEvent.click(cta);
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Connect a model to run tasks" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
const closeBtn = screen.getByRole("button", { name: /Close/i });
|
||||
await userEvent.click(closeBtn);
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByRole("heading", { name: "Connect a model to run tasks" }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
/** 6. $1 quota exhausted → connect-model modal with `exhausted` copy. */
|
||||
export const Step6QuotaExhaustedModal: Story = {
|
||||
beforeEach: () => installFreeInferenceFixtures(quotaExhaustedStatus).cleanup,
|
||||
render: () => (
|
||||
<FirstChatShell
|
||||
status={quotaExhaustedStatus}
|
||||
initialModalOpen
|
||||
/>
|
||||
),
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Connect a model to keep going" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.queryByText(/\$1/)).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
/** 7. Model connected & migrated → confirmation screen & held subtask auto-resumed. */
|
||||
export const Step7ModelConnectedAndResumed: Story = {
|
||||
beforeEach: () => installFreeInferenceFixtures(agentHeldSubtaskStatus).cleanup,
|
||||
render: () => (
|
||||
<FirstChatShell
|
||||
status={agentHeldSubtaskStatus}
|
||||
initialModalOpen
|
||||
initialModalPhase="done"
|
||||
showHeldSubtaskCard
|
||||
/>
|
||||
),
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Model provider connected" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(
|
||||
screen.getByText(/Your held task has been automatically started/i),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: /Continue to workspace/i }),
|
||||
).toBeEnabled();
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user